diff --git "a/3706.jsonl" "b/3706.jsonl" new file mode 100644--- /dev/null +++ "b/3706.jsonl" @@ -0,0 +1,1832 @@ +{"seq_id":"24139851970","text":"import spacy\nfrom spacy.lang.en.stop_words import STOP_WORDS\nfrom string import punctuation\nfrom collections import Counter\nfrom heapq import nlargest\n\n# https://medium.com/analytics-vidhya/text-summarization-using-spacy-ca4867c6b744\n\nnlp = None\ninitialized = False\ndef init():\n global nlp\n nlp = spacy.load('en_core_web_sm')\n global initialized\n initialized = True\n\ndef summarize(text, n):\n if not initialized:\n init()\n # print current time\n global nlp\n doc = nlp(text)\n keyword = []\n stopwords = list(STOP_WORDS)\n pos_tag = ['PROPN', 'ADJ', 'NOUN', 'VERB']\n for token in doc:\n if(token.text in stopwords or token.text in punctuation):\n continue\n if(token.pos_ in pos_tag):\n keyword.append(token.text)\n freq_word = Counter(keyword)\n max_freq = Counter(keyword).most_common(5)\n\n max_freq = Counter(keyword).most_common(1)[0][1]\n for word in freq_word.keys():\n freq_word[word] = (freq_word[word]/max_freq)\n freq_word.most_common(5)\n\n sent_strength={}\n for sent in doc.sents:\n for word in sent:\n if word.text in freq_word.keys():\n if sent in sent_strength.keys():\n sent_strength[sent]+=freq_word[word.text]\n else:\n sent_strength[sent]=freq_word[word.text]\n summary = nlargest(n, sent_strength, key=sent_strength.get)\n return \" \".join([word.text for word in summary])\n","repo_name":"tabularization/bostonhacks2023","sub_path":"api/summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"31582586937","text":"import turtle\nfrom random import randint, choice\n\nturtle.shape('turtle')\nturtle.forward(-300)\nturtle.speed(10)\nturtle.tracer(False)\n\ndef randomise():\n s = [\"+\", \"−\"]\n return f\"F{choice(s)}[[X]{choice(s)}X]{choice(s)}F[{choice(s)}FX]{choice(s)}X\"\n\n# создаем грамматику\ncircuit = \"FX\"\nrules = {\"X\": \"F−[[X]+X]+F[+FX]−X\",\n \"F\": \"FF\",\n \"−\": \"−\",\n \"+\": \"+\",\n \"[\": \"[\",\n \"]\": \"]\"}\n\n\nclass Stack:\n def __init__(self):\n self.s = []\n\n def append(self, x):\n self.s.append(x)\n\n def give(self):\n a = self.s.pop(-1)\n return a\n\n\ndef next_generation(c):\n c = list(c)\n for i in range(len(c)):\n if c[i] != \"X\":\n c[i] = rules[c[i]]\n else:\n c[i] = randomise()\n return str(\"\".join(c))\n\n\nn = 6\nfor i in range(n):\n circuit = next_generation(circuit)\n print(i)\n\nq = Stack()\n\n\ndef forward():\n turtle.forward(3)\n\n\ndef right():\n turtle.right(randint(5, 30))\n\n\ndef left():\n turtle.left(randint(5, 30))\n\ndef save():\n x, y = turtle.pos()\n angle = turtle.heading()\n q.append((x, y, angle))\n\ndef restore():\n state = q.give()\n turtle.goto(state[0], state[1])\n turtle.setheading(state[2])\n\n\ndef nothing():\n pass\n\n\nmoves = {\"F\": forward,\n \"+\": right,\n \"−\": left,\n \"[\": save,\n \"]\": restore,\n \"X\": nothing}\n\nfor elem in circuit:\n moves[elem]()\n\n\n\nturtle.exitonclick()\n","repo_name":"ivansolomakhin007/infa_2020_solomakhin","sub_path":"lab9/kolos.py","file_name":"kolos.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72378587419","text":"from flask import current_app, Blueprint, render_template, flash, redirect, url_for, request\nfrom flask_login import login_required, current_user\nfrom werkzeug.utils import secure_filename\nfrom .forms import SignupForm, UploadForm\n\nimport uuid as uuid\nimport config\nimport os\n\n\nfrom .models import User, Post\nfrom . import db\n\n# this blueprint is for the remaining routes\nviews = Blueprint('routes', __name__)\n\n# route to delete user\n\n\n@views.route('/delete')\n@login_required\ndef delete():\n\n # we utilize the current_user from flask login\n delete_user = User.query.filter_by(id=current_user.id).first()\n\n try:\n\n db.session.delete(delete_user)\n db.session.commit()\n flash('account deleted')\n return redirect(url_for('auth.login'))\n\n except:\n flash('failed to delete account')\n\n\n@views.route('/home//post', methods=['GET', 'POST'])\n@login_required\ndef post(username):\n form = UploadForm() # from forms.py that enables file upload for pic post\n\n if request.method == 'POST' and form.validate_on_submit(): # checks with validators\n post = request.form.get('post')\n image_id = None\n image = request.files['image']\n if image: # checks to see if the image is there after request from files\n try:\n # creates image id to store in database\n image_id = str(uuid.uuid1()) + \"_\" + \\\n secure_filename(image.filename)\n image.save(os.path.join(\n current_app.config['UPLOAD_FOLDER'], image_id))\n new_post = Post(\n data=post, user_id=current_user.id, image=image_id)\n db.session.add(new_post)\n db.session.commit()\n flash('Post uploaded', category='success')\n # Once added to db, it will redirect to the user home page\n return redirect(url_for('routes.home', username=username))\n\n except OSError as err:\n print(\"OS error:\", err)\n flash('fail')\n\n if len(post) > 250:\n # ensures post length is no more than 250 characters\n flash('Text no more than 250 characters!', category='error')\n else:\n new_post = Post(data=post, user_id=current_user.id, image=image_id)\n db.session.add(new_post)\n db.session.commit()\n flash('Post uploaded', category='success')\n return redirect(url_for('routes.home', username=username))\n\n return render_template('post.html', user=current_user, username=username, form=form)\n\n\n@views.route('/home//delete-post/')\n@login_required\n# takes a an id so the deleted post can be identified and removed from the database\ndef deletePost(id, username):\n deleted_post = Post.query.get_or_404(id)\n db.session.delete(deleted_post)\n db.session.commit()\n\n return redirect(url_for('routes.home', username=username))\n\n\n# logged in users home route\n@views.route('/home//', methods=['GET', 'POST'])\n@login_required\ndef home(username):\n user = User.query.filter_by(username=current_user.username).first()\n bio = user.get_bio()\n posts = user.get_posts()\n profile_pic = user.get_pic()\n\n # we pass a lot of things because the home page would have a basic logic to display another users homepage found in visiting\n return render_template('home.html', username=current_user.username, userhome=current_user.username, bio=bio, posts=posts, profile_pic=profile_pic, user=user)\n\n# route for search\n\n\n@views.route(\"/home//search\", methods=['GET', 'POST'])\n@login_required\ndef search(username):\n if request.method == 'POST':\n # the user will search for the username and we will use to query\n searched_username = request.form.get('searched')\n searched = User.query.filter_by(username=searched_username).first()\n\n # if the user exists we can redirect to that user home page\n if searched:\n # redirect to that users home page\n return redirect(url_for('routes.visiting', username=current_user.username, other_user=searched_username))\n else:\n\n flash('user does not exist.', category='error')\n\n return render_template('search.html', username=current_user.username)\n\n# very similar to the home route but in this case we request and query based on the other users db\n\n\n@views.route('/visiting//', methods=['GET', 'POST'])\n@login_required\ndef visiting(username, other_user):\n\n other_user = User.query.filter_by(username=other_user).first()\n current = User.query.filter_by(username=current_user.username).first()\n\n # the post is for users to follow each other updating the db in models\n if request.method == 'POST':\n follow(current, other_user)\n return redirect(url_for('routes.visiting', username=current_user.username, other_user=other_user.get_username()))\n other_username = other_user.get_username()\n bio = other_user.get_bio()\n posts = other_user.get_posts()\n profile_pic = other_user.get_pic()\n following = current.is_following(other_user)\n return render_template(\n 'home.html', username=current_user.username, userhome=other_username, bio=bio, posts=posts, following=following, profile_pic=profile_pic, user=other_user)\n\n\ndef follow(current, other_user):\n\n # adding a button so people can follow each other\n if not current.is_following(other_user):\n # user toggle button and resulted in a following\n current_user.follow(other_user) # if not, follow them\n db.session.commit() # apply change to the db\n flash(f'followed ')\n\n else:\n current_user.unfollow(other_user) # if already following\n db.session.commit()\n flash(f'Unfollowed') # if apply change to db\n\n\n# user to update the user information\n@views.route('/update-info/', methods=['GET', 'POST'])\n@login_required\ndef update(username):\n form = SignupForm()\n update_user = User.query.filter_by(\n username=current_user.username).first()\n\n if request.method == 'POST':\n\n update_user.username = request.form.get('username')\n update_user.update_bio(request.form.get('bio'))\n if request.files['profile_pic']:\n # we have a special case for the profile pic since it would be a bit harder to keep safe than the username and bio\n # if the user submits a picture only then will we update it\n\n update_user.profile_pic = request.files['profile_pic']\n\n pic_filename = secure_filename(update_user.profile_pic.filename)\n # create a random name\n pic_name = str(uuid.uuid1()) + \"_\" + pic_filename\n # save pic at location in init\n\n # save profile_pic string\n update_user.profile_pic = pic_name\n\n save_file = request.files['profile_pic']\n try:\n\n db.session.commit()\n\n # os creates the string that we will save at the designated folder created in init (it is in static)\n save_file.save(os.path.join(\n current_app.config['UPLOAD_FOLDER'], pic_name))\n\n flash('update changed')\n\n return redirect(url_for('routes.home', username=username))\n except OSError as err:\n print(\"OS error:\", err)\n flash('fail')\n return render_template('update.html', username=username, form=form, update_user=update_user)\n db.session.commit()\n return redirect(url_for('routes.home', username=username))\n return render_template('update.html', username=username, form=form, update_user=update_user, bio=update_user.get_bio())\n","repo_name":"puibtx/131-Team10","sub_path":"teamProject/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":7746,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"43267126487","text":"# -*- coding: utf-8 -*-\n# Time : 2021/1/24 17:53\n# Author : LiaoKong\nimport sys\nimport ctypes\nfrom functools import partial\n\nfrom PySide2.QtWidgets import *\nfrom PySide2.QtGui import *\n\nfrom quicker import Quicker\nfrom utils import get_logger\nimport setting\n\nlog = get_logger(u'托盘')\n\n\ndef add_action(menu, name, connect_func, parent, icon=None):\n if icon:\n action = QAction(QIcon(icon), name, parent)\n else:\n action = QAction(name, parent)\n action.triggered.connect(connect_func)\n menu.addAction(action)\n return action\n\n\ndef tray_clicked(tray, quicker, reason):\n if reason is tray.Trigger:\n quicker.set_visible()\n\n\nif __name__ == '__main__':\n log.info(u'=========启动Quicker=============')\n app = QApplication(sys.argv)\n app.setQuitOnLastWindowClosed(False)\n app.setWindowIcon(QIcon('res/launch.png'))\n\n # 属性任务栏图标\n ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('quicker')\n\n tray = QSystemTrayIcon()\n quicker = Quicker()\n\n tray.setIcon(QIcon('res/launch.png'))\n menu = QMenu()\n tray.setContextMenu(menu)\n\n add_action(menu, u'主界面', quicker.set_visible, app)\n if setting.DEBUG:\n add_action(menu, u'重载插件', quicker.reload_plugin, app)\n add_action(menu, u'重载actions', quicker.reload_actions, app)\n add_action(menu, u'退出', app.exit, app)\n\n tray.activated.connect(partial(tray_clicked, tray, quicker))\n\n tray.show()\n\n sys.exit(app.exec_())\n","repo_name":"liaokongVFX/quicker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"22173128460","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.common.by import By\nimport time\nimport usuario\nimport random\n\nlogin = usuario.login_usuario\nnavegador = webdriver.Chrome()\nwait = WebDriverWait(navegador, 10, 1)\n\ndef executar_login():\n navegador.get(\"https://www.instagram.com\")\n time.sleep(3)\n campo_usuario = navegador.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[1]/div/label/input')\n campo_usuario.click()\n time.sleep(1)\n campo_usuario.send_keys(login['usuario'])\n time.sleep(1)\n campo_senha = navegador.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[2]/div/label/input')\n campo_senha.click()\n time.sleep(1)\n campo_senha.send_keys(login['senha'])\n time.sleep(3)\n campo_senha.send_keys(Keys.ENTER)\n time.sleep(10)\n\ndef inserir_comentario(repeticoes): #pausa\n for x in range(repeticoes):\n navegador.get('INSIRA AQUI O LINK DO SORTEIO')\n time.sleep(4)\n campo_comentario = wait.until( \n expected_conditions.element_to_be_clickable(\n (By.XPATH,'//div[@class=\"RxpZH\"]')\n )\n )\n campo_comentario.click()\n campo_comentario = wait.until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, '//textarea[@placeholder=\"Add a comment…\"]')\n )\n )\n for letra in x:\n campo_comentario.send_keys(letra)\n time.sleep(60 / random.randint(160,300))\n botao_publicar = wait.until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, '//button[@type=\"submit\"]')\n )\n )\n botao_publicar.click()\n #campo_comentario.send_keys(comentario) \n #campo_comentario.send_keys(Keys.ENTER)\n #time.sleep(10)\n\ndef inserir_comentario_lista(lista_contatos,pausa_padrao,numero_comentarios,pausa_entre_comentarios):\n comentarios_postados=0\n for contato in lista_contatos:\n navegador.get('LINK DO SORTEIO NOVAMENTE')\n time.sleep(4)\n campo_comentario = wait.until( \n expected_conditions.element_to_be_clickable(\n (By.XPATH,'//div[@class=\"RxpZH\"]')\n )\n )\n campo_comentario.click()\n campo_comentario = wait.until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, '//textarea[@placeholder=\"Add a comment…\"]')\n )\n )\n for letra in contato:\n campo_comentario.send_keys(letra)\n time.sleep(60 / random.randint(160,300))\n botao_publicar = wait.until(\n expected_conditions.element_to_be_clickable(\n (By.XPATH, '//button[@type=\"submit\"]')\n )\n )\n botao_publicar.click()\n comentarios_postados+=1\n if comentarios_postados==numero_comentarios:\n print(numero_comentarios, 'postados. Vamos aguardar',pausa_entre_comentarios,'segundos')\n time.sleep(pausa_entre_comentarios)\n comentarios_postados=0\n else: \n time.sleep(pausa_padrao)\n \n\n\n\ndef carregar_contatos(arquivo,n_marcacoes):\n contatos = open(arquivo,'r',encoding='UTF-8')\n lista_contatos = contatos.read()\n lista_contatos = lista_contatos.split('\\n')\n contatos_formatados=[]\n linha_atual=1\n proxima_linha=-1\n contador=0\n contato_formatado=''\n for contato in lista_contatos:\n if contato[0:4] == 'Foto':\n proxima_linha=linha_atual+1\n elif proxima_linha == linha_atual:\n contador+=1\n if len(contato_formatado)>0:\n contato_formatado+='@'+contato+' '\n else:\n contato_formatado='@'+contato+' ' \n if contador == n_marcacoes: \n contatos_formatados.append(contato_formatado)\n contador=0\n contato_formatado=''\n\n linha_atual+=1\n\n return contatos_formatados \nn_marcacoes=1\npausa_padrao=35\nnumero_comentarios=45\npausa_entre_comentarios=600\n\ncontatos=carregar_contatos('contatos.txt', n_marcacoes)\nprint(contatos) \n\n\nlogin = usuario.login_usuario\nnavegador = webdriver.Chrome()\nwait = WebDriverWait(navegador, 10, 1)\nexecutar_login()\n#inserir_comentario('quero ganhar',5)\n\n\ninserir_comentario_lista(contatos,pausa_padrao,numero_comentarios,pausa_entre_comentarios)","repo_name":"kaiangoncalves/Bot-Comentario-Instagram","sub_path":"bot_comentarios.py","file_name":"bot_comentarios.py","file_ext":"py","file_size_in_byte":4496,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"30392931869","text":"# Django settings for frontend project.\n\nimport os\ntry:\n import autotest.common as common # pylint: disable=W0611\nexcept ImportError:\n import common # pylint: disable=W0611\nfrom autotest.client.shared.settings import settings\n\n_section = 'AUTOTEST_WEB'\n\nDEBUG = settings.get_value(_section, \"sql_debug_mode\", type=bool, default=False)\nTEMPLATE_DEBUG = settings.get_value(_section, \"template_debug_mode\", type=bool,\n default=False)\n\nFULL_ADMIN = False\n\nADMINS = (\n # ('Your Name', 'your_email@domain.com'),\n)\n\nMANAGERS = ADMINS\n\n\ndef _get_config(config_key, default=None):\n return settings.get_value(_section, config_key, default=default)\n\n\nAUTOTEST_DEFAULT = {\n 'ENGINE': 'autotest.frontend.db.backends.afe',\n 'PORT': '',\n 'HOST': _get_config(\"host\"),\n 'NAME': _get_config(\"database\"),\n 'USER': _get_config(\"user\"),\n 'PASSWORD': _get_config(\"password\", default=''),\n 'READONLY_HOST': _get_config(\"readonly_host\", default=_get_config(\"host\")),\n 'READONLY_USER': _get_config(\"readonly_user\", default=_get_config(\"user\"))}\n\nif AUTOTEST_DEFAULT['READONLY_USER'] != AUTOTEST_DEFAULT['USER']:\n AUTOTEST_DEFAULT['READONLY_PASSWORD'] = _get_config(\"readonly_password\",\n default='')\nelse:\n AUTOTEST_DEFAULT['READONLY_PASSWORD'] = AUTOTEST_DEFAULT['PASSWORD']\n\nSOUTH_BACKENDS = {\n 'autotest.frontend.db.backends.afe': 'south.db.mysql',\n 'autotest.frontend.db.backends.afe_sqlite': 'south.db.sqlite3'\n}\n\nSOUTH_DATABASE_ADAPTERS = {\n 'default': SOUTH_BACKENDS[AUTOTEST_DEFAULT['ENGINE']]\n}\n\nDATABASES = {'default': AUTOTEST_DEFAULT}\n\n# Local time zone for this installation. Choices can be found here:\n# http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE\n# although not all variations may be possible on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'UTC'\n\n# Language code for this installation. All choices can be found here:\n# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes\n# http://blogs.law.harvard.edu/tech/stories/storyReader$15\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = False\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = ''\n\n# URL that handles the media served from MEDIA_ROOT.\n# Example: \"http://media.lawrence.com\"\nMEDIA_URL = ''\n\n# URL prefix for static files.\nSTATIC_URL = '/media/'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'pn-t15u(epetamdflb%dqaaxw+5u&2#0u-jah70w1l*_9*)=n7'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n # 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'autotest.frontend.apache_auth.ApacheAuthMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.middleware.doc.XViewMiddleware',\n 'autotest.frontend.shared.json_html_formatter.JsonToHtmlMiddleware',\n 'autotest.frontend.shared.retrieve_logs.RetrieveLogsHtmlMiddleware',\n)\n\nROOT_URLCONF = 'autotest.frontend.urls'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n\n os.path.abspath(os.path.dirname(__file__) + '/templates')\n)\n\nINSTALLED_APPS = (\n 'autotest.frontend.afe',\n 'autotest.frontend.tko',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'south'\n)\n\nAUTHENTICATION_BACKENDS = (\n 'autotest.frontend.apache_auth.SimpleAuthBackend',\n)\n\n# To prevent cache poisoning, please set this to the FQDN that your\n# server will be responsible for\nALLOWED_HOSTS = ['*']\n","repo_name":"autotest/autotest","sub_path":"frontend/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","stars":681,"dataset":"github-code","pt":"69"} +{"seq_id":"19905372331","text":"import itertools\n\nimport advent_tools\n\n\ndef run_part_1(data):\n for a, b in itertools.combinations(data, 2):\n if a + b == 2020:\n return a * b\n\n\ndef run_part_2(data):\n for a, b, c in itertools.combinations(data, 3):\n if a + b + c == 2020:\n return a * b * c\n\n\nif __name__ == '__main__':\n data = advent_tools.read_one_int_per_line()\n print(run_part_1(data))\n print(run_part_2(data))","repo_name":"moink/Advent2020","sub_path":"day1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1857882502","text":"#\n# Some more tests for exception handling.\n#\nimport objc\nfrom PyObjCTest.exceptions import PyObjCTestExceptions\nfrom PyObjCTools.TestSupport import TestCase\n\n\nclass TestExceptionsFromObjC(TestCase):\n def testSimple(self):\n o = PyObjCTestExceptions.alloc().init()\n\n try:\n o.raiseSimple()\n\n except objc.error as e:\n self.assertEqual(str(e), \"SimpleException - hello world\")\n self.assertEqual(e._pyobjc_info_[\"name\"], \"SimpleException\")\n self.assertEqual(e._pyobjc_info_[\"reason\"], \"hello world\")\n self.assertEqual(e._pyobjc_info_[\"userInfo\"], None)\n\n def testSimpleWithInfo(self):\n o = PyObjCTestExceptions.alloc().init()\n\n try:\n o.raiseSimpleWithInfo()\n\n except objc.error as e:\n self.assertEqual(str(e), \"InfoException - Reason string\")\n self.assertEqual(e._pyobjc_info_[\"name\"], \"InfoException\")\n self.assertEqual(e._pyobjc_info_[\"reason\"], \"Reason string\")\n self.assertEqual(\n e._pyobjc_info_[\"userInfo\"], {\"key1\": \"value1\", \"key2\": \"value2\"}\n )\n\n def testUnicodeName(self):\n o = PyObjCTestExceptions.alloc().init()\n\n try:\n o.raiseUnicodeName()\n\n except objc.error as e:\n self.assertEqual(str(e), \"SimpleException\\u1234\\u2049 - hello world\")\n self.assertEqual(e._pyobjc_info_[\"name\"], \"SimpleException\\u1234\\u2049\")\n self.assertEqual(e._pyobjc_info_[\"reason\"], \"hello world\")\n self.assertEqual(e._pyobjc_info_[\"userInfo\"], None)\n\n def testUnicodeReason(self):\n o = PyObjCTestExceptions.alloc().init()\n\n try:\n o.raiseUnicodeReason()\n\n except objc.error as e:\n self.assertEqual(str(e), \"SimpleException - hello world\\u1234\\u2049\")\n self.assertEqual(e._pyobjc_info_[\"name\"], \"SimpleException\")\n self.assertEqual(e._pyobjc_info_[\"reason\"], \"hello world\\u1234\\u2049\")\n self.assertEqual(e._pyobjc_info_[\"userInfo\"], None)\n\n def testUnicodeWithInfo(self):\n o = PyObjCTestExceptions.alloc().init()\n\n try:\n o.raiseUnicodeWithInfo()\n\n except objc.error as e:\n self.assertEqual(\n str(e), \"InfoException\\u1234\\u2049 - Reason string\\u1234\\u2049\"\n )\n self.assertEqual(e._pyobjc_info_[\"name\"], \"InfoException\\u1234\\u2049\")\n self.assertEqual(e._pyobjc_info_[\"reason\"], \"Reason string\\u1234\\u2049\")\n self.assertEqual(\n e._pyobjc_info_[\"userInfo\"],\n {\n \"key1\\u1234\\u2049\": \"value1\\u1234\\u2049\",\n \"key2\\u1234\\u2049\": \"value2\\u1234\\u2049\",\n },\n )\n\n def testRaisingStringsInObjectiveC(self):\n # Bug #1741095, @throw anNSString\n\n o = PyObjCTestExceptions.alloc().init()\n try:\n o.raiseAString()\n\n except objc.error as e:\n self.assertEqual(str(e), \"non-NSException object caught\")\n self.assertEqual(e._pyobjc_exc_, \"thrown string\")\n\n def test_conversion(self):\n o = PyObjCTestExceptions.alloc().init()\n\n for name, conversion in [\n (\"NSRangeException\", IndexError),\n (\"NSInvalidArgumentException\", ValueError),\n (\"NSMallocException\", MemoryError),\n (\"NSUnknownKeyException\", KeyError),\n ]:\n # Look up the variable name in Foundation\n objc_name = objc._loadConstant(name, \"@\", 0)\n\n with self.assertRaises(conversion):\n o.raiseWithString_(objc_name)\n\n with self.assertRaises(conversion):\n o.raiseWithString_(name)\n\n def test_null_exception(self):\n NSException = objc.lookUpClass(\"NSException\")\n exc = NSException.exceptionWithName_reason_userInfo_(None, None, None)\n self.assertRegex(str(exc), r\"\")\n\n try:\n exc.raise__()\n except objc.error as msg:\n self.assertEqual(str(msg), \"\")\n\n exc = NSException.exceptionWithName_reason_userInfo_(None, \"some reason\", None)\n\n try:\n exc.raise__()\n except objc.error as msg:\n self.assertEqual(str(msg), \" - some reason\")\n","repo_name":"ronaldoussoren/pyobjc","sub_path":"pyobjc-core/PyObjCTest/test_exceptions.py","file_name":"test_exceptions.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","stars":439,"dataset":"github-code","pt":"69"} +{"seq_id":"25684702764","text":"#!/usr/bin/env python3\n\nimport io\nimport textwrap\nimport trajectory\nimport unittest\n\n\nclass TestTrajectory(unittest.TestCase):\n def setUp(self) -> None:\n text_src = io.StringIO(textwrap.dedent(\"\"\"\\\n ..##.......\n #...#...#..\n .#....#..#.\n ..#.#...#.#\n .#...##..#.\n ..#.##.....\n .#.#.#....#\n .#........#\n #.##...#...\n #...##....#\n .#..#...#.#\"\"\"))\n self.text = trajectory.read_stdin(text_src)\n\n def test_example_three_one(self) -> None:\n self.assertEqual(7, trajectory.count_trees(self.text, 3, 1))\n\n def test_example_one_one(self) -> None:\n self.assertEqual(2, trajectory.count_trees(self.text, 1, 1))\n\n def test_example_one_two(self) -> None:\n self.assertEqual(2, trajectory.count_trees(self.text, 1, 2))\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","repo_name":"zfrank/advent-code-2020","sub_path":"03/python/test_trajectory.py","file_name":"test_trajectory.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"14761123932","text":"#!/usr/bin/env python\n\nimport unittest\n\n\ndef subconjunto_pa(conjunto):\n if len(conjunto) < 3:\n return []\n subconjuntos = []\n for r in range(1, len(conjunto)+1):\n for i in conjunto:\n parcial = []\n for n in range(1, len(conjunto) + 1):\n an = i + (n - 1) * r\n if an in conjunto:\n parcial.append(an)\n if len(parcial) >= 3:\n subconjuntos.append(parcial)\n\n return subconjuntos\n\n\nclass PATestCase(unittest.TestCase):\n # def test_pa_minimo(self):\n # conjunto = (1, 2)\n # self.assertEqual(subconjunto_pa(conjunto), [])\n\n # def test_pa_simples(self):\n # conjunto = (1, 2, 3)\n # self.assertEqual(subconjunto_pa(conjunto), [[1, 2, 3]])\n\n def test_pa_longo(self):\n conjunto = (1, 2, 3, 5)\n self.assertEqual(subconjunto_pa(conjunto), [[1, 2, 3], [1, 3, 5]])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"grupyrp/dojos","sub_path":"2018-11-01/programa.py","file_name":"programa.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"pt","doc_type":"code","stars":22,"dataset":"github-code","pt":"69"} +{"seq_id":"6349354052","text":"import http.server\nimport socketserver\nimport termcolor\nfrom pathlib import Path\nfrom Seq1 import Seq\n\nPORT = 8080\n# Preventing the error: \"Port already in use\"\nsocketserver.TCPServer.allow_reuse_address = True\n\nSEQ_LIST = [\"AGATCGCGCCACTTCACTGCAGCCTCCGCGAAAGAGCGAAACTCCGTCTCA\",\"TCCTTTCACTCCCAGCTCCCTGGAGTCTCTCACGTAGAATGTCCTCTCCACCCCCACCCA\",\"CAGGAGGCTGAGGCGGGAGGATCGCTTGAGCCCAGGAGGTTGAGGCTGCAGTGAGGTGTG\",\"CACTTGCAAATCATGCAGTTTATGTAGCATTTTCATTTAACACCTTCTCCCAACCATCTC\",\"CTATGCTAACCCTGTGAACCGTTGCTCGCTTCTCCTTGACATCTGACGGCCTGGCCTTCT\"]\nFOLDER = r\"C:\\\\Users\\maria\\PycharmProjects\\2019-2020-PNE-Practices\\session-04\\\\\"\nTXT = \".txt\"\n# Class with our Handler. It is a called derived from BaseHTTPRequestHandler\n# It means that our class inheritates all his methods and properties\n\n\nclass TestHandler(http.server.BaseHTTPRequestHandler):\n def do_GET(self):\n \"\"\"This method is called whenever the client invokes the GET method\n in the HTTP protocol request\"\"\"\n termcolor.cprint(self.requestline,\"green\")\n req_line = self.requestline.split(' ')\n path = req_line[1]\n arguments = path.split('?')\n option = arguments[0]\n content = Path('error.html').read_text()\n cod = 404\n if option == \"/\":\n content = Path('form-4.html').read_text()\n cod = 200\n elif option == \"/ping\":\n content = \"\"\" Ping \n

PING OK!

The SEQ2 server in running....

Main page\"\"\"\n cod = 200\n elif option == \"/get\":\n get_seq = arguments[1]\n seq = get_seq.split('?')\n name, seq_index = seq[0].split(\"=\")\n seq_index = int(seq_index)\n seq = LIST_SEQ[seq_index]\n content = f\"\"\" Get \n

Sequence number {seq_index}

{seq}

Main page\"\"\"\n cod = 200\n elif option == \"/gene\":\n get_gene = arguments[1]\n couple = get_gene.split('?')\n name, gene = couple[0].split(\"=\")\n seq = Seq()\n filename = FOLDER + gene + TXT\n seq = Seq(seq.read_fasta(filename))\n gene = str(seq)\n content = f\"\"\" Gene \n

Gene: {gene}



\n Main page\"\"\"\n cod = 200\n elif option == \"/operation\":\n operation = arguments[1]\n couple = operation.split('&')\n name_s, seq = couple[0].split(\"=\")\n name_o, op = couple[1].split(\"=\")\n seq = Seq(seq)\n if op == \"comp\":\n result = seq.complement()\n elif op == \"rev\":\n result = seq.reverse()\n else:\n l = seq.len()\n A_COUNTER = seq.count_base('A')\n C_COUNTER = seq.count_base('C')\n G_COUNTER= seq.count_base('G')\n T_COUNTER = seq.count_base('T')\n A_PER = 100 * A_COUNTER / l\n C_PER = 100 * C_COUNTER / l\n G_PER = 100 * G_COUNTER / l\n T_PER = 100 * T_COUNTER / l\n result = f\"\"\"

Total length: {l}

A: {A_COUNTER} ({A_PER}%)

G: {C_COUNTER} ({C_PER}%)\n

C: {G_COUNTER} ({G_PER}%)

T: {T_COUNTER} ({T_PER}%)

\"\"\"\n\n content = f\"\"\" Operation \n

Sequence

{seq}

Operation:

{op}

Result:

{result}\n



Main page\"\"\"\n cod = 200\n\n # Generating the response message\n self.send_response(cod) # -- Status line: OK!\n\n # Define the content-type header:\n self.send_header('Content-Type', 'text/html')\n self.send_header('Content-Length', len(str.encode(content)))\n\n # The header is finished\n self.end_headers()\n\n # Send the response message\n self.wfile.write(str.encode(content))\n\n return\n\n\n# ------------------------\n# - Server MAIN program\n# ------------------------\n# -- Set the new handler\nHandler = TestHandler\n\n# -- Open the socket server\nwith socketserver.TCPServer((\"\", PORT), Handler) as httpd:\n print(\"Serving at PORT\", PORT)\n\n # -- Main loop: Attend the client. Whenever there is a new\n # -- client, the handler is called\n try:\n httpd.serve_forever()\n except KeyboardInterrupt:\n print(\"\")\n print(\"Stoped by the user\")\n httpd.server_close()\n","repo_name":"mariaconde01/2019-2020-PNE-Practices","sub_path":"P6/Seq2-server.py","file_name":"Seq2-server.py","file_ext":"py","file_size_in_byte":4873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4348437897","text":"import xlrd, math\nfrom os import listdir\nfrom os.path import isfile, join\n\n\n# wb = xlrd.open_workbook('trekking3.xlsx')\n\ndef create_file_list(dir_path):\n return [f for f in listdir(dir_path) if isfile(join(dir_path, f))]\n\n\ndef download_file():\n import wget\n path = 'https://stepik.org/media/attachments/lesson/245299/'\n file_name = 'rogaikopyta.zip'\n url = f'{path}{file_name}'\n wget.download(url)\n import zipfile\n with zipfile.ZipFile(file_name, 'r') as zip_ref:\n zip_ref.extractall('.')\n\n\ndef get_payroll(dir_path, data_row, name_col, pay_col):\n payroll = list()\n for file_name in create_file_list(dir_path):\n wb = xlrd.open_workbook(join(dir_path, file_name))\n sheet = wb.sheet_by_index(0)\n payroll.append([sheet.cell_value(data_row, name_col), str(int(sheet.cell_value(data_row, pay_col)))])\n return payroll\n\n\ndef run(dir_path):\n result = get_payroll(dir_path, 1, 1, 3)\n result.sort(key=lambda x: x[0])\n result = list(map(lambda x: ' '.join(x), result))\n\n with open('payroll.txt', 'w', encoding='utf-8') as f_out:\n f_out.writelines('\\n'.join(result))\n\n\nrun('input')\n","repo_name":"genakoganovich/PythonPracticalProblems","sub_path":"2.Spreadsheets/2.4.more_tables/2.4.1.accountant.py","file_name":"2.4.1.accountant.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39052448","text":"import torch\r\nimport torch.nn\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nimport json\r\nimport os.path\r\nimport numba\r\nimport ipdb\r\nimport torch.optim as optim\r\nimport torch.nn as nn\r\nfrom functools import partial\r\n\r\nfrom train_utils.fastai_optim import OptimWrapper\r\nfrom train_utils import learning_schedules_fastai as lsf\r\n\r\nfrom params import para\r\nfrom model import PIXOR, PIXOR_RFB\r\nfrom model_sp import PIXOR_SPARSE\r\nfrom loss import CustomLoss, MultiTaskLoss, GHM_Loss\r\n\r\ndef dict2str(dt):\r\n res = ''\r\n for key, val in dt.items():\r\n if callable(val):\r\n v = val.__name__\r\n else:\r\n v = str(val)\r\n res += '%20s: %s\\n' % (str(key), str(v))\r\n return res\r\n\r\ndef trasform_label2metric(label, ratio=4, grid_size=0.1, base_height=400):\r\n '''\r\n :param label: numpy array of shape [..., 2] of coordinates in label map space\r\n :return: numpy array of shape [..., 2] of the same coordinates in metric space\r\n '''\r\n metric = np.copy(label)\r\n metric[..., 1] -= base_height\r\n metric = metric * grid_size * ratio\r\n return metric\r\n\r\ndef transform_metric2label(metric, ratio=4, grid_size=0.1, base_height=400):\r\n '''\r\n :param label: numpy array of shape [..., 2] of coordinates in metric space\r\n :return: numpy array of shape [..., 2] of the same coordinates in label_map space\r\n '''\r\n label = (metric / ratio) / grid_size\r\n label[..., 1] += base_height\r\n return label\r\n\r\ndef plot_bev(velo_array, predict_list=None, label_list=None, window_name='GT'):\r\n '''\r\n Plot a Birds Eye View Lidar and Bounding boxes (Using OpenCV!)\r\n The heading of the vehicle is marked as a red line\r\n (which connects front right and front left corner)\r\n\r\n :param velo_array: a 2d velodyne points\r\n :param label_list: a list of numpy arrays of shape [4, 2], which corresponds to the 4 corners' (x, y)\r\n The corners should be in the following sequence:\r\n rear left, rear right, front right and front left\r\n :param window_name: name of the open_cv2 window\r\n :return: None\r\n '''\r\n intensity = np.zeros((velo_array.shape[0], velo_array.shape[1], 3), dtype=np.uint8)\r\n val = velo_array[:, :, :].max(axis=2, keepdims=True)\r\n val = 1 - val / (np.ptp(val) + 1e-5)\r\n intensity[:, :, :] = (val * 255).astype(np.uint8)\r\n\r\n intensity1 = intensity.copy()\r\n intensity2 = intensity.copy()\r\n if label_list is not None:\r\n for corners in label_list:\r\n plot_corners = corners / para.grid_sizeLW\r\n plot_corners[:, 1] += int(para.input_shape[0]//2)\r\n plot_corners = plot_corners.astype(int).reshape((-1, 1, 2))\r\n cv2.polylines(intensity1, [plot_corners], True, (0, 0, 255), 2)\r\n cv2.line(intensity1, tuple(plot_corners[2, 0]), tuple(plot_corners[3, 0]), (0, 255, 0), 2)\r\n if predict_list is not None:\r\n for corners in predict_list:\r\n plot_corners = corners / para.grid_sizeLW\r\n plot_corners[:, 1] += int(para.input_shape[0]//2)\r\n plot_corners = plot_corners.astype(int).reshape((-1, 1, 2))\r\n cv2.polylines(intensity2, [plot_corners], True, (255, 255, 0), 2)\r\n cv2.line(intensity2, tuple(plot_corners[2, 0]), tuple(plot_corners[3, 0]), (255, 0, 0), 2)\r\n\r\n # ipdb.set_trace()\r\n intensity1 = intensity1.astype(np.uint8)\r\n intensity2 = intensity2.astype(np.uint8)\r\n if intensity.shape[0] > 1000:\r\n scale = intensity.shape[0] / 800.0\r\n height, width = intensity.shape[:2]\r\n dsize = (int(width / scale), int(height / scale))\r\n intensity1 = cv2.resize(intensity1, dsize, interpolation=cv2.INTER_AREA)\r\n intensity2 = cv2.resize(intensity2, dsize, interpolation=cv2.INTER_AREA)\r\n\r\n alpha = 0.5\r\n cv2.addWeighted(intensity1, alpha, intensity2, 1 - alpha, 0, intensity)\r\n cv2.imshow(window_name, intensity)\r\n cv2.imwrite(window_name+'.png', intensity)\r\n\r\ndef plot_label_map(label_map):\r\n plt.figure()\r\n plt.imshow(label_map)\r\n plt.show()\r\n\r\ndef get_points_in_a_rotated_box(corners, xmin = 0, ymin = 0, xmax = 176, ymax = 200):\r\n def minY(x0, y0, x1, y1, x):\r\n if x0 == x1:\r\n # vertical line, y0 is lowest\r\n return int(math.floor(y0))\r\n\r\n m = (y1 - y0) / (x1 - x0)\r\n\r\n if m >= 0.0:\r\n # lowest point is at left edge of pixel column\r\n return int(math.floor(y0 + m * (x - x0)))\r\n else:\r\n # lowest point is at right edge of pixel column\r\n return int(math.floor(y0 + m * ((x + 1.0) - x0)))\r\n\r\n\r\n def maxY(x0, y0, x1, y1, x):\r\n if x0 == x1:\r\n # vertical line, y1 is highest\r\n return int(math.ceil(y1))\r\n\r\n m = (y1 - y0) / (x1 - x0)\r\n\r\n if m >= 0.0:\r\n # highest point is at right edge of pixel column\r\n return int(math.ceil(y0 + m * ((x + 1.0) - x0)))\r\n else:\r\n # highest point is at left edge of pixel column\r\n return int(math.ceil(y0 + m * (x - x0)))\r\n\r\n\r\n # view_bl, view_tl, view_tr, view_br are the corners of the rectangle\r\n view = [(corners[i, 0], corners[i, 1]) for i in range(4)]\r\n\r\n pixels = []\r\n\r\n # find l,r,t,b,m1,m2\r\n l, m1, m2, r = sorted(view, key=lambda p: (p[0], p[1]))\r\n b, t = sorted([m1, m2], key=lambda p: (p[1], p[0]))\r\n\r\n lx, ly = l\r\n rx, ry = r\r\n bx, by = b\r\n tx, ty = t\r\n m1x, m1y = m1\r\n m2x, m2y = m2\r\n\r\n # inward-rounded integer bounds\r\n # note that we're clamping the area of interest to (xmin,ymin)-(xmax,ymax)\r\n lxi = max(int(math.ceil(lx)), xmin)\r\n rxi = min(int(math.floor(rx)), xmax)\r\n byi = max(int(math.ceil(by)), ymin)\r\n tyi = min(int(math.floor(ty)), ymax)\r\n\r\n x1 = lxi\r\n x2 = rxi\r\n\r\n for x in range(x1, x2):\r\n xf = float(x)\r\n\r\n if xf < m1x:\r\n # Phase I: left to top and bottom\r\n y1 = minY(lx, ly, bx, by, xf)\r\n y2 = maxY(lx, ly, tx, ty, xf)\r\n\r\n elif xf < m2x:\r\n if m1y < m2y:\r\n # Phase IIa: left/bottom --> top/right\r\n y1 = minY(bx, by, rx, ry, xf)\r\n y2 = maxY(lx, ly, tx, ty, xf)\r\n\r\n else:\r\n # Phase IIb: left/top --> bottom/right\r\n y1 = minY(lx, ly, bx, by, xf)\r\n y2 = maxY(tx, ty, rx, ry, xf)\r\n\r\n else:\r\n # Phase III: bottom/top --> right\r\n y1 = minY(bx, by, rx, ry, xf)\r\n y2 = maxY(tx, ty, rx, ry, xf)\r\n\r\n y1 = max(y1, byi)\r\n y2 = min(y2, tyi)\r\n\r\n for y in range(y1, y2):\r\n pixels.append((x, y))\r\n\r\n return pixels\r\n\r\ndef load_config(path):\r\n \"\"\" Loads the configuration file\r\n\r\n Args:\r\n path: A string indicating the path to the configuration file\r\n Returns:\r\n config: A Python dictionary of hyperparameter name-value pairs\r\n learning rate: The learning rate of the optimzer\r\n batch_size: Batch size used during training\r\n max_epochs: Number of epochs to train the network for\r\n \"\"\"\r\n with open(path) as file:\r\n config = json.load(file)\r\n\r\n learning_rate = config[\"learning_rate\"]\r\n batch_size = para.batch_size\r\n max_epochs = config[\"max_epochs\"]\r\n\r\n return config, learning_rate, batch_size, max_epochs\r\n\r\ndef get_model_name(name, config, para):\r\n \"\"\" Generate a name for the model consisting of all the hyperparameter values\r\n\r\n Args:\r\n name: Name of ckpt\r\n Returns:\r\n path: A string with the hyperparameter name and value concatenated\r\n \"\"\"\r\n code_len = para.box_code_len\r\n folder = \"experiments_{}_c{}\".format(para.channel_type, code_len)\r\n if para.use_se_mod:\r\n folder += \"_se\"\r\n if not os.path.exists(folder):\r\n os.makedirs(folder, exist_ok=True)\r\n if name is not None:\r\n path = os.path.join(folder, name)\r\n else:\r\n file_list = os.listdir(folder)\r\n prefix_len = len(para.net) + len(\"__epoch\")\r\n file_list.sort(key = lambda x: int(x[prefix_len:]))\r\n path = os.path.join(folder, file_list[-1])\r\n return path\r\n\r\n@numba.jit(nopython=False)\r\ndef corner_to_surfaces_3d(corners):\r\n \"\"\"convert 3d box corners from corner function above\r\n to surfaces that normal vectors all direct to internal.\r\n\r\n Args:\r\n corners (float array, [N, 8, 3]): 3d box corners.\r\n Returns:\r\n surfaces (float array, [N, 6, 4, 3]):\r\n \"\"\"\r\n # box_corners: [N, 8, 3], must from corner functions in this module\r\n surfaces = np.array([\r\n [corners[:, 0], corners[:, 1], corners[:, 2], corners[:, 3]],\r\n [corners[:, 7], corners[:, 6], corners[:, 5], corners[:, 4]],\r\n [corners[:, 0], corners[:, 3], corners[:, 7], corners[:, 4]],\r\n [corners[:, 1], corners[:, 5], corners[:, 6], corners[:, 2]],\r\n [corners[:, 0], corners[:, 4], corners[:, 5], corners[:, 1]],\r\n [corners[:, 3], corners[:, 2], corners[:, 6], corners[:, 7]],\r\n ]).transpose([2, 0, 1, 3])\r\n return surfaces\r\n\r\n@numba.jit(nopython=False)\r\ndef points_in_convex_polygon_3d_jit(points,\r\n polygon_surfaces,\r\n num_surfaces=None):\r\n \"\"\"check points is in 3d convex polygons.\r\n Args:\r\n points: [num_points, 3] array.\r\n polygon_surfaces: [num_polygon, max_num_surfaces,\r\n max_num_points_of_surface, 3]\r\n array. all surfaces' normal vector must direct to internal.\r\n max_num_points_of_surface must at least 3.\r\n num_surfaces: [num_polygon] array. indicate how many surfaces\r\n a polygon contain\r\n Returns:\r\n [num_points, num_polygon] bool array.\r\n \"\"\"\r\n max_num_surfaces, max_num_points_of_surface = polygon_surfaces.shape[1:3]\r\n num_points = points.shape[0]\r\n num_polygons = polygon_surfaces.shape[0]\r\n if num_surfaces is None:\r\n num_surfaces = np.full((num_polygons,), 9999999, dtype=np.int64)\r\n normal_vec, d = surface_equ_3d_jit(polygon_surfaces[:, :, :3, :])\r\n # normal_vec: [num_polygon, max_num_surfaces, 3]\r\n # d: [num_polygon, max_num_surfaces]\r\n ret = np.ones((num_points, num_polygons), dtype=np.bool_)\r\n sign = 0.0\r\n for i in range(num_points):\r\n for j in range(num_polygons):\r\n for k in range(max_num_surfaces):\r\n if k > num_surfaces[j]:\r\n break\r\n sign = points[i, 0] * normal_vec[j, k, 0] \\\r\n + points[i, 1] * normal_vec[j, k, 1] \\\r\n + points[i, 2] * normal_vec[j, k, 2] + d[j, k]\r\n if sign >= 0:\r\n ret[i, j] = False\r\n break\r\n return ret\r\n\r\n@numba.jit(nopython=False)\r\ndef surface_equ_3d_jit(polygon_surfaces):\r\n # return [a, b, c], d in ax+by+cz+d=0\r\n # polygon_surfaces: [num_polygon, num_surfaces, num_points_of_polygon, 3]\r\n surface_vec = polygon_surfaces[:, :, :2, :] - polygon_surfaces[:, :, 1:3, :]\r\n # normal_vec: [..., 3]\r\n normal_vec = np.cross(surface_vec[:, :, 0, :], surface_vec[:, :, 1, :])\r\n # print(normal_vec.shape, points[..., 0, :].shape)\r\n # d = -np.inner(normal_vec, points[..., 0, :])\r\n d = np.einsum('aij, aij->ai', normal_vec, polygon_surfaces[:, :, 0, :])\r\n return normal_vec, -d\r\n\r\ndef remove_points_in_boxes(points, rbbox_corners):\r\n '''\r\n points (N, 3/4)\r\n rbbox_corners (N, 8, 3)\r\n '''\r\n surfaces = corner_to_surfaces_3d(rbbox_corners)\r\n indices = points_in_convex_polygon_3d_jit(points[:, :3], surfaces)\r\n points = points[np.logical_not(indices.any(-1))]\r\n return points, np.logical_not(indices.any(-1))\r\n\r\ndef set_bn_momentum_default(bn_momentum):\r\n def fn(m):\r\n if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)):\r\n m.momentum = bn_momentum\r\n return fn\r\n\r\nclass BNMomentumScheduler(object):\r\n def __init__(\r\n self, model, bn_lambda, last_epoch=-1,\r\n setter=set_bn_momentum_default\r\n ):\r\n if not isinstance(model, nn.Module):\r\n raise RuntimeError(\"Class '{}' is not a PyTorch nn Module\".format(type(model).__name__))\r\n self.model = model\r\n self.setter = setter\r\n self.lmbd = bn_lambda\r\n\r\n self.step(last_epoch + 1)\r\n self.last_epoch = last_epoch\r\n\r\n def step(self, epoch=None):\r\n if epoch is None:\r\n epoch = self.last_epoch + 1\r\n\r\n self.last_epoch = epoch\r\n self.model.apply(self.setter(self.lmbd(epoch)))\r\n\r\ndef bnm_lmbd(cur_epoch):\r\n cur_decay = 1\r\n BN_DECAY_STEP_LIST = [650]\r\n BN_DECAY = 0.5\r\n BN_MOMENTUM = 0.1\r\n BNM_CLIP = 0.01\r\n for decay_step in BN_DECAY_STEP_LIST:\r\n if cur_epoch >= decay_step:\r\n cur_decay = cur_decay * BN_DECAY\r\n return max(BN_MOMENTUM * cur_decay, BNM_CLIP)\r\n\r\ndef build_model(config, device, train=True, train_loader=None):\r\n if para.net == 'PIXOR':\r\n net = PIXOR(use_bn=config['use_bn'], input_channels=para.input_channels).to(device)\r\n elif para.net == 'PIXOR_RFB':\r\n net = PIXOR_RFB(use_bn=config['use_bn'], input_channels=para.input_channels).to(device)\r\n elif para.net == 'PIXOR_SPARSE':\r\n net = PIXOR_SPARSE(para.full_shape, para.ratio, use_bn=config['use_bn']).to(device)\r\n else:\r\n raise NotImplementedError\r\n\r\n if config['loss_type'] == \"MultiTaskLoss\":\r\n criterion = MultiTaskLoss(device=device, num_classes=1)\r\n elif config['loss_type'] == \"CustomLoss\":\r\n criterion = CustomLoss(device=device, num_classes=1)\r\n elif config['loss_type'] == \"GHM_Loss\":\r\n criterion = GHM_Loss(device=device, num_classes=1)\r\n else:\r\n raise NotImplementedError\r\n\r\n if not train:\r\n return net, criterion\r\n\r\n if config['optimizer'] == 'ADAM':\r\n optimizer = torch.optim.Adam(params=[{'params': criterion.parameters()},\r\n {'params': net.parameters()}],\r\n lr=config['learning_rate'])\r\n elif config['optimizer'] == 'SGD':\r\n optimizer = torch.optim.SGD(net.parameters(), lr=config['learning_rate'], momentum=config['momentum'])\r\n elif config['optimizer'] == 'adam_onecycle':\r\n def children(m: nn.Module):\r\n return list(m.children())\r\n\r\n def num_children(m: nn.Module) -> int:\r\n return len(children(m))\r\n\r\n flatten_model = lambda m: sum(map(flatten_model, m.children()), []) if num_children(m) else [m]\r\n get_layer_groups = lambda m: [nn.Sequential(*flatten_model(m))]\r\n\r\n optimizer_func = partial(optim.Adam, betas=(0.9, 0.99))\r\n optimizer = OptimWrapper.create(\r\n optimizer_func, 3e-3, get_layer_groups(net), wd=0.001, true_wd=True, bn_wd=True\r\n )\r\n else:\r\n raise NotImplementedError\r\n\r\n if config['optimizer'] == 'adam_onecycle':\r\n total_steps = len(train_loader) * config['max_epochs']\r\n scheduler = lsf.OneCycle(\r\n optimizer, total_steps, config['learning_rate'], list([0.95, 0.85]), 10.0, 0.4)\r\n else:\r\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=config['lr_decay_every'], gamma=0.5)\r\n\r\n bnm_scheduler = BNMomentumScheduler(net, bnm_lmbd, last_epoch=-1)\r\n\r\n return net, criterion, optimizer, scheduler, bnm_scheduler\r\n","repo_name":"godspeed1989/kitti3d","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36311727989","text":"load(\n \"@io_bazel_rules_docker//container:providers.bzl\",\n \"PushInfo\",\n)\n\ndef _push_info_to_json(p):\n return struct(\n registry = p.registry,\n repository = p.repository,\n tag = p.tag,\n digestPath = p.digest.path,\n ).to_json()\n\ndef _cnab_impl(ctx):\n args = [\"-bundle-path\", ctx.outputs.bundle.path]\n deps = []\n\n invocation_images_arg = \"-invocation-images=\"\n for _, target in enumerate(ctx.attr.invocation_images):\n deps.append(target[PushInfo].digest)\n invocation_images_arg += _push_info_to_json(target[PushInfo]) + \"\\n\"\n args.append(invocation_images_arg)\n\n images_arg = \"-images=\"\n for target, name in ctx.attr.images.items():\n images_arg += \"{}={}\\n\".format(name, _push_info_to_json(target[PushInfo]))\n deps.append(target[PushInfo].digest)\n args.append(images_arg)\n\n ctx.actions.run(\n inputs = deps,\n outputs = [ctx.outputs.bundle],\n arguments = args,\n progress_message = \"Generating bundle.json file: \" + ctx.label.name,\n executable = ctx.executable._bundle_writer,\n )\n\ncnab = rule(\n implementation = _cnab_impl,\n attrs = {\n \"invocation_images\": attr.label_list(\n mandatory = True,\n providers = [PushInfo],\n doc = \"The array of invocation image definitions for this bundle.\",\n ),\n \"images\": attr.label_keyed_string_dict(\n allow_empty = True,\n providers = [PushInfo],\n doc = \"Images that are used by this bundle.\",\n ),\n \"_bundle_writer\": attr.label(\n executable = True,\n cfg = \"host\",\n allow_files = True,\n default = Label(\"//bundlegen:bundlegen\"),\n ),\n },\n outputs = {\"bundle\": \"%{name}.bundle.json\"},\n)\n","repo_name":"jlegrone/rules_cnab","sub_path":"cnab/cnab.bzl","file_name":"cnab.bzl","file_ext":"bzl","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"24266228098","text":"import torch\nfrom typing import List\nimport numpy as np\nfrom ffcv.pipeline.operation import Operation\nfrom ffcv.loader import Loader, OrderOption\nfrom ffcv.transforms import ToTensor, ToDevice, Squeeze, NormalizeImage, RandomHorizontalFlip, ToTorchImage\nfrom ffcv.fields.rgb_image import CenterCropRGBImageDecoder, RandomResizedCropRGBImageDecoder\nfrom ffcv.fields.basics import IntDecoder\n\nimport torch.utils.data\nimport torch.utils.data.distributed\nfrom torchvision import transforms, datasets\n\nfrom klib.kdataloader import KDataLoaderFFCV, KDataLoaderTorch, KDataLoader\n\nfrom klib import train_utils\n\nIMAGENET_MEAN = np.array([0.485, 0.456, 0.406])\nIMAGENET_STD = np.array([0.229, 0.224, 0.225])\n\nRESIZE_SIZE = 256\nOUTPUT_SIZE = 224\n\nDEFAULT_CROP_RATIO = OUTPUT_SIZE / RESIZE_SIZE\n\n__all__ = ['get_kdataloader']\n\n\ndef get_torch_dataloader(\n data_pth, *, batch_size, num_workers, drop_last, device, train, seed,\n shuffle, replacement, distributed\n) -> KDataLoaderTorch:\n\n normalize = transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)\n\n if train:\n dataset = datasets.ImageFolder(\n data_pth,\n transforms.Compose([\n transforms.RandomResizedCrop(OUTPUT_SIZE),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ])\n )\n return KDataLoaderTorch(\n train_utils.get_torch_dataloader_for_dataset(\n dataset, batch_size=batch_size, num_workers=num_workers,\n drop_last=drop_last, seed=seed, shuffle=shuffle, replacement=replacement, distributed=distributed\n ), device\n )\n else:\n dataset = datasets.ImageFolder(\n data_pth,\n transforms.Compose([\n transforms.Resize(RESIZE_SIZE),\n transforms.CenterCrop(OUTPUT_SIZE),\n transforms.ToTensor(),\n normalize,\n ])\n )\n return KDataLoaderTorch(\n train_utils.get_torch_dataloader_for_dataset(\n dataset, batch_size=batch_size, num_workers=num_workers,\n drop_last=False, seed=seed, shuffle=shuffle, replacement=replacement, distributed=distributed\n ), device\n )\n\n \ndef get_ffcv_dataloader(\n data_pth, *, batch_size, num_workers, drop_last, device, train, seed,\n shuffle, replacement, distributed\n) -> KDataLoaderFFCV:\n\n assert not replacement\n\n if train:\n assert shuffle\n\n decoder = RandomResizedCropRGBImageDecoder((OUTPUT_SIZE, OUTPUT_SIZE))\n image_pipeline: List[Operation] = [\n decoder,\n RandomHorizontalFlip(),\n ToTensor(),\n ToDevice(device, non_blocking=True),\n ToTorchImage(),\n NormalizeImage(IMAGENET_MEAN * 255, IMAGENET_STD * 255, np.float16)\n ]\n\n label_pipeline: List[Operation] = [\n IntDecoder(),\n ToTensor(),\n Squeeze(),\n ToDevice(device, non_blocking=True)\n ]\n\n loader = Loader(data_pth,\n batch_size=batch_size,\n num_workers=num_workers,\n order=OrderOption.RANDOM,\n os_cache=True,\n drop_last=drop_last,\n pipelines={\n 'image': image_pipeline,\n 'label': label_pipeline\n },\n distributed=distributed,\n seed=seed,\n batches_ahead=3)\n else:\n assert not shuffle\n \n cropper = CenterCropRGBImageDecoder((OUTPUT_SIZE, OUTPUT_SIZE), ratio=DEFAULT_CROP_RATIO)\n image_pipeline = [\n cropper,\n ToTensor(),\n ToDevice(device, non_blocking=True),\n ToTorchImage(),\n NormalizeImage(IMAGENET_MEAN * 255, IMAGENET_STD * 255, np.float16)\n ]\n\n label_pipeline = [\n IntDecoder(),\n ToTensor(),\n Squeeze(),\n ToDevice(device, non_blocking=True)\n ]\n\n loader = Loader(data_pth,\n batch_size=batch_size,\n num_workers=num_workers,\n order=OrderOption.SEQUENTIAL,\n drop_last=False,\n pipelines={\n 'image': image_pipeline,\n 'label': label_pipeline\n },\n distributed=distributed,\n seed=seed,\n batches_ahead=3)\n \n return KDataLoaderFFCV(loader)\n\n\ndef get_kdataloader(\n backend, data_pth, **kwargs\n) -> KDataLoader:\n \n if backend == 'ffcv':\n return get_ffcv_dataloader(data_pth, **kwargs)\n else:\n assert backend == 'torch'\n return get_torch_dataloader(data_pth, **kwargs)","repo_name":"Arora-group-codebase/klib","sub_path":"klib/imagenet/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"20120254837","text":"class SegmentTreeNode:\n\n def __init__(self, start, end, x):\n # intervals [start, end]\n self.start = start\n self.end = end\n self.interval_sum = x\n # left, right child\n self.left = None\n self.right = None\n\nclass SegmentTree:\n\n def __init__(self, nums: dict[int], start: int, end: int):\n self.root = self.construct(nums, start, end)\n\n def construct(self, nums: dict[int], start: int, end: int):\n if start > end:\n return None\n\n node = SegmentTreeNode(start, end, 0)\n if start < end:\n mid = start + (end - start) // 2\n node.left = self.construct(nums, start, mid) # [start, mid]\n node.right = self.construct(nums, mid + 1, end) # [mid+1, end]\n if node.left:\n node.interval_sum += node.left.interval_sum\n if node.right:\n node.interval_sum += node.right.interval_sum\n else:\n node.interval_sum = nums[start] # same as nums[end]\n return node\n\n # 单点修改\n def modify(self, root, index, value):\n if root.start == index and root.end == index:\n root.interval_sum = value\n return\n\n mid = root.start + (root.end - root.start) // 2\n if root.start <= index <= mid: # [start, mid]\n self.modify(root.left, index, value)\n if mid < index <= root.end: # [mid+1, end]\n self.modify(root.right, index, value)\n root.interval_sum = root.left.interval_sum + root.right.interval_sum\n\n # 区间查询\n # [start, end] 查询区间\n def query(self, root, start, end):\n if root.start == start and root.end == end:\n return root.interval_sum\n\n result = 0\n # mid 当前节点管辖区间\n mid = root.start + (root.end - root.start) // 2\n # 左右子树均存在查询区间的子区间\n if start <= mid < end:\n result += self.query(root.left, start, mid)\n result += self.query(root.right, mid + 1, end)\n elif start >= mid + 1: # mid [start, end], query right tree\n result += self.query(root.right, start, end)\n elif end <= mid: # [start, end] mid, query left tree\n result += self.query(root.left, start, end)\n return result\n\n\nclass IntervalSum:\n\n # 区间指的是下标区间\n def __init__(self, A):\n self.st = SegmentTree(A, 0, len(A) - 1) # [start, end]\n\n \"\"\" The sum from start to end \"\"\"\n def query(self, start, end):\n return self.st.query(self.st.root, start, end)\n\n def modify(self, index, value):\n self.st.modify(self.st.root, index, value)\n","repo_name":"entingwu/AlgorithmPython","sub_path":"SegmentTree/SegmentTreeNode.py","file_name":"SegmentTreeNode.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72975502301","text":"import pandas as pd\nimport os\nimport shutil\n\noptimizers = ['SGD', 'Adam', 'AdamW']\nlearning_rates = [0.0001, 0.0005, 0.001, 0.005, 0.01]\nmomentums = [0.1, 0.5, 0.9]\nresults_base_path = os.path.join(\"/home/liranc6/Using_YOLOv8/runs/detect/\")\ndest_base_path = \"/home/liranc6/Using_YOLOv8/results\"\n\n\"\"\"\nreads the results from path and returns a dict of dataframes when key=optimizer, val=df\n\"\"\"\ndef create_results_data_frames():\n df_dict = {}\n # loop through the optimizers\n for optimizer in optimizers:\n # create an empty data frame\n optimizer_df = pd.DataFrame(columns=momentums, index=learning_rates)\n\n optimizer_df = optimizer_df.fillna(0)\n\n for learning_rate in learning_rates:\n mAP_score = 0\n for momentum in momentums:\n # name path\n folder_name = f\"optimizer={str(optimizer)}_learning_rate={str(learning_rate)}_momentum={str(momentum)}\"\n\n full_folder_name = os.path.join(results_base_path, folder_name)\n \n #get mAP50-95 results\n result_csv_path = os.path.join(full_folder_name, 'results.csv')\n if os.path.exists(result_csv_path):\n df = pd.read_csv(result_csv_path)\n mAP_score = df[' metrics/mAP50-95(B)'].iloc[-1]\n optimizer_df.loc[learning_rate, momentum] = mAP_score\n\n # add the data frame to the dictionary with the optimizer name as the key\n df_dict[optimizer] = optimizer_df\n\n return df_dict\n\ndef print_df(df_dict):\n for optimizer, results in df_dict.items():\n print(optimizer + \":\")\n print(results)\n print(\"\\n\\n\")\n\ndef create_results_csv(df_dict):\n with open(\"results.csv\", \"w\") as f:\n for op in optimizers:\n f.write(str(op) + \":\\n\")\n df_dict[op].to_csv(f, mode='a')\n # write two new lines after each DataFrame\n f.write(\"\\n\\n\")\n\ndef find_best_params(df_dict):\n best_params = \"\"\n max = -1\n for op in optimizers:\n df = df_dict[op]\n # get the row and column labels of the maximum value\n max_row_label, max_col_label = df.stack().idxmax()\n # get the value of the maximum cell\n max_val = df.loc[max_row_label, max_col_label]\n if max_val>max:\n best_params = \"best params are: \" + str(op) + \" learning_rates=\" + str(max_row_label) + \" momentum=\" + str(max_col_label)\\\n + \"max_val_after_5_ephocs=\" + str(max_val)\n \n return best_params\n\ndef print_best_params(best_params):\n with open(\"results.txt\", \"a\") as f:\n f.write(best_params)\n print(best_params)\n\n\ndef copy_results_csv_to_new_folder(dest_base_path):\n # Create the directory\n os.makedirs(dest_base_path, exist_ok=True)\n # loop through the optimizers\n for optimizer in optimizers:\n for learning_rate in learning_rates:\n for momentum in momentums:\n #rename folder\n folder_name = f\"optimizer={str(optimizer)}_learning_rate={str(learning_rate)}_momentum={str(momentum)}\"\n new_name = os.path.join(results_base_path, folder_name)\n\n #get mAP50-95 results\n result_csv_path = os.path.join(new_name, 'results.csv')\n if os.path.exists(result_csv_path):\n # Set the source and destination paths\n src_path = result_csv_path\n\n dest_full_path = os.path.join(dest_base_path, folder_name+'.csv')\n\n # Copy the file to the destination folder\n shutil.copy(src_path, dest_full_path)\n else:\n print(\"no folder found\")\n\nif __name__ == \"__main__\":\n df_dict = create_results_data_frames()\n\n create_results_csv(df_dict)\n\n copy_results_csv_to_new_folder(dest_base_path)\n\n print_df(df_dict)\n\n create_results_csv(df_dict)\n\n best_params = find_best_params(df_dict)\n\n print_best_params(best_params)\n\n\n\n","repo_name":"liranc6/Deep-Learning-course-236781","sub_path":"final_project/after_submition/Evaluate_results.py","file_name":"Evaluate_results.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"10663272011","text":"#!/usr/bin/python3\n\nimport sys\nimport librosa\nimport numpy\nimport phash\nimport pickle\n\n\ndef get_hash(mel_basis, wavfn, start, end):\n y, sr = librosa.load(wavfn, sr=16000)\n y = y[int(start * sr):int(end * sr)]\n # Get the hop size so we get about 50 frames\n\n hop = int(y.shape[0] / 64) + 1\n\n S, n_fft = librosa.core.spectrum._spectrogram(y=y, n_fft=512, hop_length=hop, power=2.0)\n\n\n\n S = librosa.power_to_db(numpy.dot(mel_basis, S), ref=numpy.max)\n h = phash.hash(S)\n return h\n\nclass Segment():\n def __init__(self, utt, start, dur, name):\n self.utt = utt\n self.start = float(start)\n self.dur = float(dur)\n self.name = name\n\n def __repr__(self):\n return \"[%s %s %.3f %.3f]\" % (self.utt, self.name, self.start, self.dur)\n\ndef SegmentGenerator(wav_list, phone_list):\n wavs = {}\n for line in open(wav_list):\n items = line.split()\n wavs[items[0]] = items[1]\n\n segments={}\n for line in open(phone_list):\n utt, channel, start, dur, pn = line.split()\n if utt not in segments:\n segments[utt] = []\n segments[utt].append(Segment(utt, start, dur, pn))\n\n # Build a Mel filter\n mel_basis = librosa.filters.mel(16000, n_fft=512, n_mels=32)\n\n for utt in segments:\n utt_segments = segments[utt]\n for i, phone in enumerate(utt_segments):\n # End should be approximately + 0.5 seconds from start\n j = i\n start = phone.start\n end = phone.start\n while end < start + 0.5 and j < len(utt_segments):\n end = end + utt_segments[j].dur\n j = j + 1\n if j - i < 3 or end - start < 0.4: # Ignore this\n continue\n\n mhash = get_hash(mel_basis, wavs[utt], start, end)\n yield (mhash, start, end, utt_segments[i:j + 1])\n\n\ndef index_data():\n try:\n inf = open(sys.argv[3], \"rb\")\n database = pickle.load(inf)\n except:\n database = {}\n\n for mhash, start, end, segments in SegmentGenerator(sys.argv[1], sys.argv[2]):\n if mhash not in database:\n database[mhash] = []\n# print (mhash, start, end, segments)\n database[mhash].append((segments, start, end))\n pickle.dump(database, open(sys.argv[3], \"wb\"))\n\nif __name__ == '__main__':\n index_data()\n","repo_name":"alphacep/vosk","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":343,"dataset":"github-code","pt":"69"} +{"seq_id":"38152664582","text":"'''realiza todas las combinaciones para a^b y las guarda en una lista'''\nA = 100\nB = 100\nlista = []\nfor a in range(2, A + 1):\n\tfor b in range(2, B + 1):\n\t\tlista.append(a ** b)\n\n# se eliminan los elementos repetidos\nlista = set(lista)\n\nprint(len(lista))","repo_name":"luisalvaradoar/pj_euler","sub_path":"pj_29.py","file_name":"pj_29.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29370793740","text":"# Exercise!\n# Display the image below to the right hand side where the 0 is going to be ' ', and the 1 is going to be '*'. This will reveal an image!\npicture = [\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 1, 1, 1, 0],\n [1, 1, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0]\n]\n\nstar = '*'\nblank = ' '\n\nfor row in picture:\n for pixel in row:\n if pixel:\n print(star, end=' ')\n # change the default value of print end to make sure print in same line\n else:\n print(blank, end=' ')\n print('') # print new line after each row\n","repo_name":"brandon850213/pythonPractice","sub_path":"gui2.py","file_name":"gui2.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22275585129","text":"import random\n\nplay = True\n\nwhile play == True:\n a = False\n b = False\n c = False\n\n x = random.randint(0, 2)\n\n ace = \"\"\n\n if x == 0:\n ace = \"a\"\n\n elif x == 1:\n ace = \"b\"\n\n elif x == 2:\n ace = \"c\"\n\n else:\n play = False\n break\n\n print(ace)\n # print(x)\n # print(str(a) + \"\\n\" + str(b) + \"\\n\" + str(c))\n\n card = input(\"Pick the Ace: is it \\'a\\', \\'b\\', or \\'c\\'?\\n\")\n\n if card != \"a\" and card != \"b\" and card != \"c\":\n print(\"end\")\n play = False\n break\n\n randomCard = \"a\"\n count = 0\n if card == ace:\n while randomCard == ace or randomCard == card:\n if count % 3 == 0:\n randomCard = \"a\"\n if count % 3 == 1:\n randomCard = \"b\"\n if count % 3 == 2:\n randomCard = \"c\"\n count = count + 1\n else:\n randomCard = ace\n\n notAce = \"a\"\n while notAce == ace or notAce == card or notAce == randomCard:\n if count % 3 == 0:\n notAce = \"a\"\n if count % 3 == 1:\n notAce = \"b\"\n if count % 3 == 2:\n notAce = \"c\"\n count = count + 1\n\n print(\"You pick card \\'\" + card + \"\\'. Unexpectedly, you are shown that card \\'\" + notAce + \"\\' is not the Ace\")\n choice = input(\"You are given another choice: STAY with \\'\" + card + \"\\' or SWITCH to \\'\" + randomCard + \"\\'?\\n\")\n print(\"Your initial choice was card \\'\" + card + \"\\'.\")\n\n if choice == \"stay\":\n card = card\n elif choice == \"switch\":\n card = randomCard\n else:\n play = False\n print(\"end\")\n break\n\n print(\"Your final choice was card \\'\" + card + \"\\'.\")\n\n if card == ace:\n print(\"You Won!\")\n else:\n print(\"You Lost!\")\n\n print(\"The Ace was card \\'\" + ace + \"\\'.\")\n\n play = False\n break\n","repo_name":"aravpatel19/Data-Structures","sub_path":"FirstPython/FirstPython.py","file_name":"FirstPython.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74421776539","text":"from PIL import Image\n\n#constants\nPALLETSIZE = 1\ndiv = 255//PALLETSIZE\npallet = []\ncurVal = 0\n\n#creates the pallete\nwhile curVal <= 255:\n pallet.append(curVal)\n curVal += div\n\n\ndef findNearestPalletColor(rgb):\n rgb = list(rgb)\n newRgb = [255, 255, 255]\n for j in range(3):\n low = 255\n for i in range(len(pallet)):\n curLow = abs(rgb[j] - pallet[i])\n if curLow < low:\n low = curLow\n newRgb[j] = pallet[i]\n return tuple(newRgb)\n\ndef f(error, rgb, factor):\n newRgb = [0,0,0]\n\n for i in range(3):\n newRgb[i] = int(rgb[i] + (error[i] * factor))\n return tuple(newRgb)\n\nimg = Image.open(\"uni.jpg\")\n\nfor y in range(img.size[1]):\n print(y/img.size[1] * 100)\n for x in range (img.size[0]):\n oldPixel = list(img.getpixel((x,y)))\n newPixel = list(findNearestPalletColor(oldPixel))\n img.putpixel((x,y), tuple(newPixel))\n\n quantError = [ele1 - ele2 for(ele1, ele2) in zip(oldPixel, newPixel)]\n\n if x != img.size[0] -1:\n img.putpixel((x + 1, y), (f(quantError, img.getpixel((x + 1, y)), (7 / 16))))\n if x != 0 and y != img.size[1]-1:\n img.putpixel((x - 1, y + 1), (f(quantError, img.getpixel((x - 1, y + 1)), (3 / 16))))\n if y != img.size[1]-1:\n img.putpixel((x, y + 1), (f(quantError, img.getpixel((x, y + 1)), (5 / 16))))\n if x != img.size[0]-1 and y != img.size[1]-1:\n img.putpixel((x + 1, y + 1), (f(quantError, img.getpixel((x + 1, y + 1)), (1 / 16))))\n\n\nimg.show()\n","repo_name":"Smokeyjoe42/FL-Dithering","sub_path":"dither.py","file_name":"dither.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"24260576405","text":"# This file should probably be located within a 'cryostat' directory within the drivers directory\r\nfrom __future__ import print_function, unicode_literals, division # true_divide\r\nimport socket\r\nfrom codecs import encode, decode\r\nfrom instrumental import u, Q_\r\n# from . import Cryostat\r\n# from .. import _ParamDict\r\n# from ... import u, Q_, __path__\r\n#\r\n#\r\n# def _instrument(params):\r\n# # Should add a check of instrument type here. Not sure how to do this now,\r\n# # since querying '*IDN?' doesn't work.\r\n#\r\n# return MontanaCryostat()\r\n\r\nclass MontanaCryostat():\r\n def __init__(self):\r\n host = 'localhost'\r\n port = 7773\r\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.sock.connect((host, port))\r\n self.leftover = None\r\n # Parameter dicitonary for saving\r\n #self._param_dict = _ParamDict({})\r\n #self._param_dict['module'] = 'cryostats.montana'\r\n\r\n\r\n def close(self):\r\n self.sock.close()\r\n\r\n def __enter__(self):\r\n return self\r\n\r\n def __exit__(self, exc_type, exc_value, traceback):\r\n self.close()\r\n\r\n def _send(self, message):\r\n self.sock.sendall(bytes('{:02d}{}'.format(len(message), message), \"utf-8\"))\r\n # self.sock.sendall(bytes('{:02d}{}'.format(len(message), encode(message)), \"utf-8\"))\r\n #self.sock.sendall('{:02d}{}'.format(len(message), encode(message)))\r\n\r\n def _recv(self):\r\n if self.leftover:\r\n bytes_recd = len(self.leftover)\r\n chunks = [self.leftover]\r\n else:\r\n bytes_recd = 0\r\n chunks = []\r\n\r\n while bytes_recd < 2:\r\n try:\r\n chunk = self.sock.recv(2)\r\n except socket.timeout:\r\n raise Exception(\"Timed out while waiting for message data\")\r\n except Exception as e:\r\n raise Exception(\"Socket error while waiting for message data: {}\".format(str(e)))\r\n\r\n chunks.append(chunk)\r\n bytes_recd += len(chunk)\r\n if not chunk:\r\n if bytes_recd == 0:\r\n return None\r\n raise RuntimeError(\"Socket connection ended unexpectedly\")\r\n\r\n length = int(b''.join(chunks))\r\n while bytes_recd < length+2:\r\n try:\r\n chunk = self.sock.recv(4096)\r\n except socket.timeout:\r\n raise Exception(\"Timed out while waiting for message data\")\r\n except Exception as e:\r\n raise Exception(\"Socket error while waiting for message data: {}\".format(str(e)))\r\n\r\n chunks.append(chunk)\r\n bytes_recd += len(chunk)\r\n if not chunk:\r\n raise RuntimeError(\"Socket connection ended unexpectedly\")\r\n full_msg = b''.join(chunks)\r\n chunks = [full_msg[2+length:]] # Save excess chunks for later (shouldn't normally happen)\r\n return decode(full_msg[2:])\r\n\r\n def _query(self, message):\r\n self._send(message)\r\n return self._recv()\r\n\r\n # The following query/control methods are defined according to Montana\r\n # Instruments' \"Cryostation Communication Specification\" Ver. 1.12\r\n\r\n def get_platform_temperature(self):\r\n temp = float(self._query('GPT'))\r\n return None if temp < 0 else temp * u.degK\r\n\r\n def get_alarm_state(self):\r\n alarm_state = bool(self._query('GAS'))\r\n return alarm_state\r\n\r\n def get_chamber_pressure(self):\r\n pressure = float(self._query('GCP'))\r\n return None if pressure < 0 else pressure * u.mTorr\r\n\r\n def get_high_temp_set_point(self):\r\n response = self._query('GHTSP')\r\n try:\r\n temp = float(response)\r\n return temp * u.degK\r\n except:\r\n print(\"Message from Montana: \",response)\r\n return None\r\n\r\n def get_magnet_state(self):\r\n response = self._query('GHTSP')\r\n if response[0:5]==\"MAGNET\":\r\n return response\r\n else:\r\n print(\"Message from Montana: \",response)\r\n return None\r\n\r\n def get_magnet_target_field(self):\r\n field = float(self._query('GMTF'))\r\n return None if field==-9.999999 else field * u.Tesla\r\n\r\n def get_platform_heater_power(self):\r\n power = float(self._query('GPHP'))\r\n return None if power < 0 else power * u.watt\r\n\r\n def get_platform_stability(self):\r\n stability = float(self._query('GPS'))\r\n return None if stability < 0 else stability * u.degK\r\n\r\n def get_stage1_heater_power(self):\r\n power = float(self._query('GS1HP'))\r\n return None if power < 0 else power * u.watt\r\n\r\n def get_stage1_temperature(self):\r\n temp = float(self._query('GS1T'))\r\n return None if temp < 0 else temp * u.degK\r\n\r\n def get_stage2_temperature(self):\r\n temp = float(self._query('GS2T'))\r\n return None if temp < 0 else temp * u.degK\r\n\r\n def get_sample_stability(self):\r\n stability = float(self._query('GSS'))\r\n return None if stability < 0 else stability * u.degK\r\n\r\n def get_sample_temperature(self):\r\n temp = float(self._query('GST'))\r\n return None if temp < 0 else temp * u.degK\r\n\r\n def get_temperature_set_point(self):\r\n temp = float(self._query('GTSP'))\r\n return None if temp < 0 else temp * u.degK\r\n\r\n def get_user_stability(self):\r\n stability = float(self._query('GUS'))\r\n return None if stability < 0 else stability * u.degK\r\n\r\n def get_user_temperature(self):\r\n temp = float(self._query('GUT'))\r\n return None if temp < 0 else temp * u.degK\r\n\r\n def start_cool_down(self):\r\n response = self._query('SCD')\r\n print(\"Message from Montana: \",response)\r\n if response=='OK': return True\r\n else: return False\r\n\r\n def set_high_temperature_set_point(self,set_temp):\r\n set_temp_K = set_temp.to(u.degK).magnitude\r\n set_temp_str = \"{:0.2}\".format(float(set_temp_K))\r\n response = self._query('SHTSP'+set_temp_str)\r\n print(\"Message from Montana: \",response)\r\n if response[0:2]=='OK': return True\r\n else: return False\r\n\r\n def set_magnet_disabled(self):\r\n response = self._query('SMD')\r\n print(\"Message from Montana: \",response)\r\n if response[0:2]=='OK': return True\r\n else: return False\r\n\r\n def set_magnet_enabled(self):\r\n response = self._query('SME')\r\n print(\"Message from Montana: \",response)\r\n if response[0:2]=='OK': return True\r\n else: return False\r\n\r\n def set_magnet_target_field(self,set_field):\r\n set_field_T = set_field.to(u.Tesla).magnitude\r\n set_field_str = \"{:0.6}\".format(float(set_field_T))\r\n response = self._query('SMTF'+set_field_str)\r\n print(\"Message from Montana: \",response)\r\n if response[0:2]=='OK': return True\r\n else: return False\r\n\r\n def start_standby(self):\r\n response = self._query('SSB')\r\n print(\"Message from Montana: \",response)\r\n if response=='OK': return True\r\n else: return False\r\n\r\n def stop(self):\r\n response = self._query('STP')\r\n print(\"Message from Montana: \",response)\r\n if response=='OK': return True\r\n else: return False\r\n\r\n def set_temperature_set_point(self,set_temp):\r\n set_temp_K = set_temp.to(u.degK).magnitude\r\n set_temp_str = \"{:0.3}\".format(float(set_temp_K))\r\n response = self._query('STSP'+set_temp_str)\r\n print(\"Message from Montana: \",response)\r\n if response[0:2]=='OK': return True\r\n else: return False\r\n\r\n def start_warm_up(self):\r\n response = self._query('SWU')\r\n print(\"Message from Montana: \",response)\r\n if response=='OK': return True\r\n else: return False\r\n","repo_name":"doddgray/experiment_control","sub_path":"old_code/silicon_microrings/montana.py","file_name":"montana.py","file_ext":"py","file_size_in_byte":7814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36026657996","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\n\nchrome_driver_path=\"D:\\software\\chromedriver_win32\\chromedriver.exe\"\nservice=Service(chrome_driver_path)\ndriver=webdriver.Chrome(service=service)\n\nweb_url=\"https://www.python.org/\"\ndriver.get(web_url)\n\nevent_times=driver.find_elements(By.CSS_SELECTOR,\".event-widget time\")\nevent_names=driver.find_elements(By.CSS_SELECTOR,\".event-widget ul a\")\nevents={n:{'time':event_times[n].text,'name':event_names[n].text} for n in range(len(event_times))}\nprint(events)\n\ndriver.quit()","repo_name":"Bipul-Dubey/100DaysOfCode-Complete-Python-Course","sub_path":"Day048- Selenium/WebScraping.py","file_name":"WebScraping.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19162542210","text":"# -*- coding: utf-8 -*-\na = float(input())\ncedulas = [100, 50, 20, 10, 5, 2]\nmoedas = [1.00, 0.50, 0.25, 0.10, 0.05, 0.01]\nprint('NOTAS:', end='\\n')\nfor c in range(0, len(cedulas)):\n b = a // cedulas[c]\n print(f'{b:.0f} nota(s) de R$ {cedulas[c]}.00', end='\\n')\n a = a - b * cedulas[c]\nprint('MOEDAS:', end='\\n')\nfor c in range(0, len(moedas)-1):\n b = a // moedas[c]\n a -= b*moedas[c]\n print(f'{b:.0f} moeda(s) de R$ {moedas[c]:.2f}', end='\\n')\nprint(f'{(a*100):.0f} moeda(s) de R$ {moedas[-1]:.2f}', end='\\n')","repo_name":"Livia-ferrao/INE5402-POO1","sub_path":"1021.py","file_name":"1021.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36526758520","text":"'''\n Gaurav Laxmandas\n Nathani\n gauravla\n'''\n\nimport re\nimport time\nimport sys\nfrom pyspark import SparkContext\nfrom pyspark import SparkConf\n\ndef mapper1(edge):\n edge = edge.split()\n if edge[0] == edge[1]: yield (int(edge[0]), [int(edge[0]), int(edge[1])])\n else:\n yield (int(edge[0]), [int(edge[0]), int(edge[1])])\n yield (int(edge[1]), [int(edge[0]), int(edge[1])])\n\ndef mapper(edge):\n if edge[0] == edge[1]: yield (int(edge[0]), [int(edge[0]), int(edge[1])])\n else:\n yield (int(edge[0]), [int(edge[0]), int(edge[1])])\n yield (int(edge[1]), [int(edge[0]), int(edge[1])])\n\ndef reducer(edges):\n V = edges[0]\n E = edges[1]\n if len(E) == 1: return ()\n for e in E:\n if e[0] == V: \n par = e[1]\n break\n if V == par: yield (V, V)\n for e in E:\n if e[0] != V: yield (e[0], par)\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Wrong Input!\")\n print(\"Usage: a2.py \")\n sys.exit(1)\n\n APP_NAME = 'FindRoots'\n conf = SparkConf().setAppName(APP_NAME)\n start = time.time()\n sc = SparkContext(conf=conf)\n\n mapped_edges = sc.textFile(sys.argv[1]).flatMap(mapper1,preservesPartitioning=True).groupByKey().flatMap(reducer)\n c_me = mapped_edges.cache()\n prev_count = c_me.values().sum()\n while True:\n mapped_edges = c_me.flatMap(mapper,preservesPartitioning=True).groupByKey().flatMap(reducer)\n c_me.unpersist()\n c_me = mapped_edges.cache()\n curr_count = c_me.values().sum()\n if curr_count == prev_count:\n c_me.saveAsTextFile(sys.argv[2])\n break\n prev_count = curr_count\n\n sc.stop()\n end = time.time()\n\n print(round((end-start)/60,2),\"m\")\n","repo_name":"gnathani/Parallel-Processing","sub_path":"rooting_trees/a2.py","file_name":"a2.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1862708362","text":"import AppKit\nfrom PyObjCTools.TestSupport import TestCase, min_os_level\n\nNSStoryboardControllerCreator = b\"@@\"\n\n\nclass TestNSStoryboard(TestCase):\n @min_os_level(\"10.15\")\n def testMethods10_15(self):\n self.assertArgIsBlock(\n AppKit.NSStoryboard.instantiateInitialControllerWithCreator_,\n 0,\n NSStoryboardControllerCreator,\n )\n self.assertArgIsBlock(\n AppKit.NSStoryboard.instantiateControllerWithIdentifier_creator_,\n 1,\n NSStoryboardControllerCreator,\n )\n","repo_name":"ronaldoussoren/pyobjc","sub_path":"pyobjc-framework-Cocoa/PyObjCTest/test_nsstoryboard.py","file_name":"test_nsstoryboard.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":439,"dataset":"github-code","pt":"69"} +{"seq_id":"30038658747","text":"import logging\nfrom carla_utils import *\nfrom tornado import ioloop\nfrom mod.host import Host\nfrom mod.protocol import process_resp\n\nclass FakeSocket(object):\n def write(self, data):\n return\n\n def read_until(self, msg, callback):\n return\n\nclass CarlaHost(Host):\n def __init__(self, hmi, prefs, msg_callback):\n Host.__init__(self, hmi, prefs, msg_callback)\n\n self.carla = CarlaHostDLL(\"/usr/lib/carla/libcarla_standalone2.so\")\n self.carla.set_engine_callback(self.carla_callback)\n self.carla.set_engine_option(ENGINE_OPTION_PREFER_PLUGIN_BRIDGES, 0, \"\")\n self.carla.set_engine_option(ENGINE_OPTION_PREFER_UI_BRIDGES, 0, \"\")\n self.carla.set_engine_option(ENGINE_OPTION_PROCESS_MODE, ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS, \"\")\n self.carla.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, ENGINE_TRANSPORT_MODE_JACK, \"\")\n self.carla.set_engine_option(ENGINE_OPTION_PATH_BINARIES, 0, \"/usr/lib/carla/\")\n self.carla.set_engine_option(ENGINE_OPTION_PATH_RESOURCES, 0, \"/usr/share/carla/resources/\")\n self.carlatimer = ioloop.PeriodicCallback(self.carlatimer_callback, 300)\n\n self._client_id_system = -1\n self._plugins_info = []\n\n def __del__(self):\n if self.carla.is_engine_running():\n self.carlatimer.stop()\n self.carla.engine_close()\n\n #Host.__del__(self)\n\n def open_connection_if_needed(self, websocket):\n if self.readsock is not None and self.writesock is not None:\n self.report_current_state(websocket)\n return\n\n if not self.carla.engine_init(\"JACK\", \"MOD\"):\n return\n\n if self.readsock is None:\n self.readsock = FakeSocket()\n if self.writesock is None:\n self.writesock = FakeSocket()\n\n self.connected = True\n self.report_current_state(websocket)\n self.statstimer.start()\n self.carlatimer.start()\n\n if self.memtimer is not None:\n self.memtimer_callback()\n self.memtimer.start()\n\n if len(self._queue):\n self.process_write_queue()\n else:\n self._idle = True\n\n def process_write_queue(self):\n try:\n msg, callback, datatype = self._queue.pop(0)\n logging.info(\"[host] popped from queue: %s\" % msg)\n except IndexError:\n self._idle = True\n return\n\n if self.writesock is None:\n self.process_write_queue()\n return\n\n self._idle = False\n logging.info(\"[host] sending -> %s\" % msg)\n\n print(msg)\n ret = self.send_carla_msg(msg)\n\n if callback is not None:\n callback(process_resp(ret, datatype))\n\n self.process_write_queue()\n\n def send_carla_msg(self, msg):\n if msg == \"remove -1\":\n self.carla.remove_all_plugins()\n return True\n\n data = msg.split(\" \",1)\n cmd = data[0]\n\n if len(data) == 2:\n data = data[1]\n else:\n data = None\n\n if cmd == \"add\":\n uri, ret = data.split(\" \",1)\n if not self.carla.add_plugin(BINARY_NATIVE, PLUGIN_LV2, None, \"effect_\"+ret, uri, 0, None, 0x0):\n return -1\n return int(ret)\n\n def _getPluginId(self, instance):\n for i in range(len(self._plugins_info)):\n if self._plugins_info[i]['name'] == instance:\n return i\n return -1\n\n # host stuff\n def _get(self, subject):\n if subject == \"/graph\":\n self._client_id_system = -1\n self.carla.patchbay_refresh(True)\n return\n\n def _add_plugin(self, instance, uri, enabled, x, y, callback):\n if self.carla.add_plugin(BINARY_NATIVE, PLUGIN_LV2, \"\", instance, uri, 0, None, 0x0):\n if enabled:\n self.carla.set_active(self.carla.get_current_plugin_count()-1, True)\n callback(True)\n else:\n callback(False)\n\n def _remove_plugin(self, instance, callback):\n pluginId = self._getPluginId(instance)\n if pluginId >= 0:\n self.carla.remove_plugin(pluginId)\n callback(True)\n else:\n callback(False)\n\n def _enable(self, instance, enabled, callback):\n pluginId = self._getPluginId(instance)\n if pluginId >= 0:\n self.carla.set_active(pluginId, enabled)\n callback(True)\n else:\n callback(False)\n\n def _param_set(self, port, value, callback):\n instance, port = port.rsplit(\"/\", 1)\n pluginId = self._getPluginId(instance)\n if pluginId >= 0:\n #parameterId = self._plugins_info[pluginId]['symbols'][parameterId]\n #self.carla.set_parameter_value(pluginId, parameterId, value)\n callback(True)\n else:\n callback(False)\n\n def _connect(self, port_from, port_to, callback):\n # TODO\n #split_from = port_from.split(\"/\")\n #if len(split_from) != 3:\n #return\n #if split_from[1] == \"system\":\n #groupIdA = self._client_id_system\n #portIdA = int(split_from[2].rsplit(\"_\",1)[-1])\n #instance_from, port_from = port_from.rsplit(\"/\", 1)\n #else:\n #groupIdB = self._getPluginId(split_from[:1].join(\"/\"))\n #portIdB = int(split_from[2].rsplit(\"_\",1)[-1])\n #instance_from, port_from = port_from.rsplit(\"/\", 1)\n #self.carla.patchbay_connect()\n callback(True)\n\n def carla_callback(self, host, action, pluginId, value1, value2, value3, valueStr):\n valueStr = charPtrToString(valueStr)\n print(\"carla callback\", host, action, pluginId, value1, value2, value3, valueStr)\n return\n\n # Debug.\n # This opcode is undefined and used only for testing purposes.\n if action == ENGINE_CALLBACK_DEBUG:\n return\n\n # A plugin has been added.\n # @a pluginId Plugin Id\n # @a valueStr Plugin name\n if action == ENGINE_CALLBACK_PLUGIN_ADDED:\n if pluginId != len(self._plugins_info):\n return\n\n info = self.carla.get_plugin_info(pluginId)\n self._plugins_info.append(info)\n\n uri = info['label']\n x = 0.0\n y = 0.0\n msg = \"\"\"[]\n a ;\n <%s> ;\n [\n \"%.1f\"^^ ;\n \"%.1f\"^^ ;\n true ;\n <%s> ;\n a ;\n ] .\n \"\"\" % (valueStr, x, y, uri)\n\n self.plugin_added_callback(valueStr, uri, False, x, y)\n self.msg_callback(msg)\n return\n\n # A plugin has been removed.\n # @a pluginId Plugin Id\n if action == ENGINE_CALLBACK_PLUGIN_REMOVED:\n if pluginId >= len(self._plugins_info):\n return\n info = self._plugins_info.pop(pluginId)\n\n msg = \"\"\"[]\n a ;\n <%s> .\n \"\"\" % (info['name'])\n self.plugin_removed_callback(info['name'])\n self.msg_callback(msg)\n return\n\n # A plugin has been renamed.\n # @a pluginId Plugin Id\n # @a valueStr New plugin name\n if action == ENGINE_CALLBACK_PLUGIN_RENAMED:\n return\n\n # A plugin has become unavailable.\n # @a pluginId Plugin Id\n # @a valueStr Related error string\n if action == ENGINE_CALLBACK_PLUGIN_UNAVAILABLE:\n return\n\n # A parameter value has changed.\n # @a pluginId Plugin Id\n # @a value1 Parameter index\n # @a value3 New parameter value\n if action == ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:\n return\n\n # A parameter default has changed.\n # @a pluginId Plugin Id\n # @a value1 Parameter index\n # @a value3 New default value\n if action == ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED:\n return\n\n # A parameter's MIDI CC has changed.\n # @a pluginId Plugin Id\n # @a value1 Parameter index\n # @a value2 New MIDI CC\n if action == ENGINE_CALLBACK_PARAMETER_MIDI_CC_CHANGED:\n return\n\n # A parameter's MIDI channel has changed.\n # @a pluginId Plugin Id\n # @a value1 Parameter index\n # @a value2 New MIDI channel\n if action == ENGINE_CALLBACK_PARAMETER_MIDI_CHANNEL_CHANGED:\n return\n\n # A plugin option has changed.\n # @a pluginId Plugin Id\n # @a value1 Option\n # @a value2 New on/off state (1 for on, 0 for off)\n # @see PluginOptions\n if action == ENGINE_CALLBACK_OPTION_CHANGED:\n return\n\n # The current program of a plugin has changed.\n # @a pluginId Plugin Id\n # @a value1 New program index\n if action == ENGINE_CALLBACK_PROGRAM_CHANGED:\n return\n\n # The current MIDI program of a plugin has changed.\n # @a pluginId Plugin Id\n # @a value1 New MIDI program index\n if action == ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED:\n return\n\n # A plugin's custom UI state has changed.\n # @a pluginId Plugin Id\n # @a value1 New state, as follows:\n # 0: UI is now hidden\n # 1: UI is now visible\n # -1: UI has crashed and should not be shown again\n if action == ENGINE_CALLBACK_UI_STATE_CHANGED:\n return\n\n # A note has been pressed.\n # @a pluginId Plugin Id\n # @a value1 Channel\n # @a value2 Note\n # @a value3 Velocity\n if action == ENGINE_CALLBACK_NOTE_ON:\n return\n\n # A note has been released.\n # @a pluginId Plugin Id\n # @a value1 Channel\n # @a value2 Note\n if action == ENGINE_CALLBACK_NOTE_OFF:\n return\n\n # A plugin needs update.\n # @a pluginId Plugin Id\n if action == ENGINE_CALLBACK_UPDATE:\n return\n\n # A plugin's data/information has changed.\n # @a pluginId Plugin Id\n if action == ENGINE_CALLBACK_RELOAD_INFO:\n return\n\n # A plugin's parameters have changed.\n # @a pluginId Plugin Id\n if action == ENGINE_CALLBACK_RELOAD_PARAMETERS:\n return\n\n # A plugin's programs have changed.\n # @a pluginId Plugin Id\n if action == ENGINE_CALLBACK_RELOAD_PROGRAMS:\n return\n\n # A plugin state has changed.\n # @a pluginId Plugin Id\n if action == ENGINE_CALLBACK_RELOAD_ALL:\n return\n\n # A patchbay client has been added.\n # @a pluginId Client Id\n # @a value1 Client icon\n # @a value2 Plugin Id (-1 if not a plugin)\n # @a valueStr Client name\n # @see PatchbayIcon\n if action == ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED:\n if valueStr == \"system\":\n self._client_id_system = pluginId\n return\n\n # A patchbay client has been removed.\n # @a pluginId Client Id\n if action == ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED:\n if self._client_id_system == pluginId:\n self._client_id_system = -1\n return\n\n # A patchbay client has been renamed.\n # @a pluginId Client Id\n # @a valueStr New client name\n if action == ENGINE_CALLBACK_PATCHBAY_CLIENT_RENAMED:\n return\n\n # A patchbay client data has changed.\n # @a pluginId Client Id\n # @a value1 New icon\n # @a value2 New plugin Id (-1 if not a plugin)\n # @see PatchbayIcon\n if action == ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED:\n return\n\n # A patchbay port has been added.\n # @a pluginId Client Id\n # @a value1 Port Id\n # @a value2 Port hints\n # @a valueStr Port name\n # @see PatchbayPortHints\n if action == ENGINE_CALLBACK_PATCHBAY_PORT_ADDED:\n if self._client_id_system == pluginId:\n if value2 & PATCHBAY_PORT_TYPE_MIDI:\n types = \" ;\\n\"\n types += \"a ,\\n\"\n elif value2 & PATCHBAY_PORT_TYPE_AUDIO:\n types = \"a ,\\n\"\n elif value2 & PATCHBAY_PORT_TYPE_CV:\n types = \"a ,\\n\"\n else:\n return\n if value2 & PATCHBAY_PORT_IS_INPUT:\n types += \"\\n\"\n else:\n types += \"\\n\"\n msg = \"\"\"[]\n a ;\n ;\n [\n \"0\"^^ ;\n \"%s\" ;\n %s\n ] .\n \"\"\" % (valueStr, valueStr.title().replace(\"_\", \" \"), types)\n self.msg_callback(msg)\n return\n\n # A patchbay port has been removed.\n # @a pluginId Client Id\n # @a value1 Port Id\n if action == ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED:\n return\n\n # A patchbay port has been renamed.\n # @a pluginId Client Id\n # @a value1 Port Id\n # @a valueStr New port name\n if action == ENGINE_CALLBACK_PATCHBAY_PORT_RENAMED:\n return\n\n # A patchbay connection has been added.\n # @a pluginId Connection Id\n # @a valueStr Out group, port plus in group and port, in \"og:op:ig:ip\" syntax.\n if action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED:\n return\n\n # A patchbay connection has been removed.\n # @a pluginId Connection Id\n if action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED:\n return\n\n # Engine started.\n # @a value1 Process mode\n # @a value2 Transport mode\n # @a valuestr Engine driver\n # @see EngineProcessMode\n # @see EngineTransportMode\n if action == ENGINE_CALLBACK_ENGINE_STARTED:\n return\n\n # Engine stopped.\n if action == ENGINE_CALLBACK_ENGINE_STOPPED:\n return\n\n # Engine process mode has changed.\n # @a value1 New process mode\n # @see EngineProcessMode\n if action == ENGINE_CALLBACK_PROCESS_MODE_CHANGED:\n return\n\n # Engine transport mode has changed.\n # @a value1 New transport mode\n # @see EngineTransportMode\n if action == ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED:\n return\n\n # Engine buffer-size changed.\n # @a value1 New buffer size\n if action == ENGINE_CALLBACK_BUFFER_SIZE_CHANGED:\n return\n\n # Engine sample-rate changed.\n # @a value3 New sample rate\n if action == ENGINE_CALLBACK_SAMPLE_RATE_CHANGED:\n return\n\n # NSM callback.\n # (Work in progress, values are not defined yet)\n if action == ENGINE_CALLBACK_NSM:\n return\n\n # Idle frontend.\n # This is used by the engine during long operations that might block the frontend,\n # giving it the possibility to idle while the operation is still in place.\n if action == ENGINE_CALLBACK_IDLE:\n return\n\n # Show a message as information.\n # @a valueStr The message\n if action == ENGINE_CALLBACK_INFO:\n return\n\n # Show a message as an error.\n # @a valueStr The message\n if action == ENGINE_CALLBACK_ERROR:\n return\n\n # The engine has crashed or malfunctioned and will no longer work.\n if action == ENGINE_CALLBACK_QUIT:\n return\n\n def carlatimer_callback(self):\n self.carla.engine_idle()\n","repo_name":"moddevices/mod-ui","sub_path":"mod/old/host_carla.py","file_name":"host_carla.py","file_ext":"py","file_size_in_byte":16714,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"69"} +{"seq_id":"11361450750","text":"import os\nimport sys\nimport subprocess\nimport traceback\nimport importlib.util as il\nspec = il.spec_from_file_location(\"config\", snakemake.params.config)\nconfig = il.module_from_spec(spec)\nsys.modules[spec.name] = config\nspec.loader.exec_module(config)\nsys.path.append(snakemake.config['args']['mcc_path'])\nimport scripts.mccutils as mccutils\n\n\n\ndef main():\n sample_name = snakemake.params.sample_name\n threads = snakemake.threads\n out_dir = snakemake.params.out_dir\n median_insert_size_file = snakemake.input.median_insert_size\n log = snakemake.params.log\n status_log = snakemake.params.status_log\n script_dir = snakemake.params.script_dir\n\n try:\n # ensures intermediate files from previous runs are removed\n for f in os.listdir(out_dir):\n mccutils.remove(out_dir+\"/\"+f)\n\n is_paired = True\n if snakemake.params.raw_fq2 == \"None\":\n is_paired = False\n\n input_dir = snakemake.params.out_dir+\"/input/\"\n mccutils.remove(input_dir)\n mccutils.mkdir(input_dir)\n fq_dir = snakemake.params.out_dir+\"/input/fastq/\"\n mccutils.mkdir(fq_dir)\n\n reference = input_dir+\"reference.fasta\"\n te_seqs = input_dir+\"consensus.fasta\"\n rm_out = input_dir+\"repeatmasker.out\"\n\n os.symlink(snakemake.input.reference, reference)\n os.symlink(snakemake.input.te_seqs, te_seqs)\n os.symlink(snakemake.input.rm_out, rm_out)\n\n if is_paired:\n fq1 = fq_dir+sample_name+\"_1.fq\"\n fq2 = fq_dir+sample_name+\"_2.fq\"\n os.symlink(snakemake.input.fq1, fq1)\n os.symlink(snakemake.input.fq2, fq2)\n else:\n fq1 = fq_dir+sample_name+\".unPaired.fq\"\n os.symlink(snakemake.input.fq1, fq1)\n\n\n\n median_insert_size = get_median_insert_size(median_insert_size_file)\n # output = subprocess.Popen([\"which\", \"relocaTE2.py\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n # script = output.stdout.read()\n # script = script.decode()\n # script = script.replace(\"\\n\",\"\")\n script = script_dir+\"/relocaTE2.py\"\n\n\n\n\n mccutils.log(\"relocate2\",\"running RelocaTE2\", log=log)\n command = [\n \"python2\", script, \n \"-t\", te_seqs,\n \"-g\", reference,\n \"-r\", rm_out,\n \"-o\", out_dir,\n \"-s\", str(median_insert_size),\n \"--run\",\n \"-v\", \"4\",\n \"-c\", str(threads),\n \"-d\", fq_dir\n ]\n\n for param in config.PARAMS.keys():\n command.append(param)\n command.append(str(config.PARAMS[param]))\n\n if is_paired:\n command += [\"-1\", \"_1\", \"-2\", \"_2\"]\n \n else:\n command += [\"-u\", \".unPaired\"]\n\n mccutils.run_command(command, log=log)\n\n mccutils.check_file_exists(snakemake.output[0])\n mccutils.check_file_exists(snakemake.output[1])\n with open(status_log,\"w\") as l:\n l.write(\"COMPLETED\\n\")\n mccutils.log(\"relocate2\",\"RelocaTE2 run complete\")\n\n except Exception as e:\n track = traceback.format_exc()\n print(track, file=sys.stderr)\n with open(log,\"a\") as l:\n print(track, file=l)\n mccutils.log(\"relocate2\",\"RelocaTE2 run failed\")\n with open(status_log,\"w\") as l:\n l.write(\"FAILED\\n\")\n\n mccutils.run_command([\"touch\", snakemake.output[0]])\n mccutils.run_command([\"touch\", snakemake.output[1]])\n\ndef get_median_insert_size(infile):\n median_insert_size = 0\n with open(infile,\"r\") as inf:\n for line in inf:\n insert = line.split(\"=\")[1]\n insert = insert.replace(\"\\n\",\"\")\n median_insert_size = int(float(insert))\n \n return median_insert_size\n\nif __name__ == \"__main__\": \n main()","repo_name":"bergmanlab/mcclintock","sub_path":"scripts/relocaTE2/relocate2_run.py","file_name":"relocate2_run.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"69"} +{"seq_id":"73699716","text":"print(\"Welcome to library management system\")\n\nclass Book:\n def __init__(self, title, author):\n self.title = title\n self.author = author\n self.is_borrowed = False\n\nclass Author:\n def __init__(self, name):\n self.name = name\n self.books = []\n\n def add_book(self, book):\n self.books.append(book)\n\nclass Member:\n def __init__(self, name):\n self.name = name\n self.borrowed_books = []\n\n def borrow_book(self, book):\n if not book.is_borrowed:\n self.borrowed_books.append(book)\n book.is_borrowed = True\n print(f\"{self.name} has borrowed {book.title} by {book.author.name}.\")\n else:\n print(f\"{book.title} by {book.author.name} is already borrowed.\")\n\n def return_book(self, book):\n if book.is_borrowed and book in self.borrowed_books:\n self.borrowed_books.remove(book)\n book.is_borrowed = False\n print(f\"{self.name} has returned {book.title} by {book.author.name}.\")\n else:\n print(f\"{self.name} did not borrow {book.title} by {book.author.name}.\")\n\nclass Library:\n def __init__(self):\n self.books = []\n self.members = []\n self.authors = {}\n\n def add_item(self, book):\n author_name = book.author.name\n if author_name not in self.authors:\n self.authors[author_name] = Author(author_name)\n self.authors[author_name].add_book(book)\n self.books.append(book)\n print(f\"{book.title} by {book.author.name} has been added to the library.\")\n\n def add_member(self, member):\n self.members.append(member)\n print(f\"{member.name} was successfully added to the system.\")\n\n def remove_member(self, member_name):\n for member in self.members:\n if member.name == member_name:\n self.members.remove(member)\n print(f\"{member.name} was successfully removed from the system.\")\n break\n else:\n print(\"Member not found.\")\n\n def remove_book(self, book_title):\n for book in self.books:\n if book.title == book_title:\n author_name = book.author.name\n self.authors[author_name].books.remove(book)\n self.books.remove(book)\n print(f\"{book.title} by {book.author.name} has been removed from the library.\")\n break\n else:\n print(\"Book not found.\")\n\n def list_members(self):\n print(\"Members:\")\n for member in self.members:\n print(f\"- {member.name}\")\n\n def list_books(self):\n print(\"Books:\")\n for book in self.books:\n status = \"Available\" if not book.is_borrowed else \"Borrowed\"\n print(f\"- {book.title} by {book.author.name} ({status})\")\n\n def list_borrowed_books(self, member_name):\n for member in self.members:\n if member.name == member_name:\n if len(member.borrowed_books) == 0:\n print(f\"{member.name} has not borrowed any books.\")\n else:\n print(f\"{member.name} has borrowed the following books:\")\n for book in member.borrowed_books:\n print(f\"- {book.title} by {book.author.name}\")\n break\n else:\n print(\"Member not found.\")\ndef menu(library):\n while True:\n print(\"1. Add book\")\n print(\"2. Remove book\")\n print(\"3. List books\")\n print(\"4. Add member\")\n print(\"5. Remove member\")\n print(\"6. List members\")\n print(\"7. Borrow book\")\n print(\"8. Return book\")\n print(\"9. List borrowed books\")\n print(\"10. Quit\")\n \n choice = input(\"Enter your choice: \")\n \n if choice == \"1\":\n \n title = input(\"Enter a books title: \")\n author = input(\"Enter a book author: \")\n book = Book(title, Author(author))\n library.add_item(book)\n \n elif choice == \"2\":\n \n book_id = input(\"Enter a book title: \")\n library.remove_book(book_id)\n \n elif choice == \"3\":\n \n library.list_books()\n \n elif choice == \"4\":\n \n name = input(\"Enter a name to be a member: \")\n member = Member(name)\n library.add_member(member)\n \n elif choice == \"5\":\n \n member_id = input(\"Enter a member name: \")\n library.remove_member(member_id)\n \n elif choice == \"6\":\n \n library.list_members()\n \n elif choice == \"7\":\n \n book_id = input(\"Enter a book title: \")\n member_id = input(\"Enter a member name: \")\n \n book = None\n for b in library.books:\n if b.title == book_id:\n book = b\n break\n else:\n print(\"The book didn't exist.\")\n continue\n \n member = None\n for m in library.members:\n if m.name == member_id:\n member = m\n break\n else:\n print(\"The member didn't exist.\")\n continue\n \n if book.is_borrowed:\n print(\"The book is already borrowed.\")\n else:\n member.borrow_book(book)\n print(\"the book has been borrowed.\")\n \n elif choice == \"8\":\n \n book_id = input(\"Enter a book title: \")\n member_id = input(\"Enter a member name: \")\n \n book = None\n for b in library.books:\n if b.title == book_id:\n book = b\n break\n else:\n print(\"The book didn't exist.\")\n continue\n \n member = None\n for m in library.members:\n if m.name == member_id:\n member = m\n break\n else:\n print(\"The member didn't exist.\")\n continue\n \n if not book.is_borrowed or book not in member.borrowed_books:\n print(\"The book cann't be returned.\")\n else:\n member.return_book(book)\n print(\"The book has been returned.\")\n \n elif choice == \"9\":\n \n member_id = input(\"Enter a member name: \")\n library.list_borrowed_books(member_id)\n \n elif choice == \"10\":\n \n print(\"See you later!\")\n break\n else:\n print(\"Invalid choice. Please enter a number from 1-10.\")\n\nmy_library = Library()\nmenu(my_library)\n\n","repo_name":"Kotibtw/booklibrary","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":6932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4849442379","text":"\n#This program adds the uncorrected LR reads (not in Pileup file)\n#to the output file of HECIL\n\nimport fileinput, os, sys\n\n#USAGE: python Create_Corrected_AllLRReads.py Orig_LR.fa Corrected_LR.fa\n\nref_file=sys.argv[1]\n#num_LRread=int(sys.argv[2])\ncorrref_file=sys.argv[2]\n#num_corrLRread=int(sys.argv[4])\n\n# Open input files\nfref=open(ref_file,'r')\nfcorrref=open(corrref_file,'r')\n\n# Count the number of sequences in ref_file\nnum_LRread = 0.0\nfor line in fref:\n\tnum_LRread += 0.5\nnum_LRread = int(num_LRread)\nfref.seek(0)\n\n# Count the number of sequences in corref_file\nnum_corrLRread = 0.0\nfor line in fcorrref:\n\tnum_corrLRread += 0.5\nnum_corrLRread = int(num_corrLRread)\nfcorrref.seek(0)\n\nout='Corrected_'+ref_file\nfout=open(out,'w')\n\ndict_ref={}\n\n# Store all pre-corrected reads\nfor c in range(int(num_LRread)):\n\t# Check for header\n\tl1=fref.readline()\n\tl2=fref.readline()\n\tl1=l1.rstrip('\\n')\n\tl2=l2.rstrip('\\n')\n\n\tdict_ref[l1]=l2\n\n\ndict_corrref={}\n\n# Store all corrected reads (subset of original list)\nfor c1 in range(int(num_corrLRread)):\n\tlc1=fcorrref.readline()\n\tlc2=fcorrref.readline()\n\tlc1=lc1.rstrip('\\n')\n\tlc2=lc2.rstrip('\\n')\n\n\tdict_corrref[lc1]=lc2\n\nfor ref in dict_ref.keys():\n\tif (len(ref)>2):\n\t\tif ref in dict_corrref.keys():\n\t\t\theader=ref+'\\n'\n\t\t\tread=dict_corrref[ref]+'\\n'\n\t\telse:\n\t\t\theader=ref+'\\n'\n\t\t\tread=dict_ref[ref]+'\\n'\n\n\t\tfout.write(header)\n\t\tfout.write(read)\n\n\nfout.close()\n","repo_name":"cooperative-computing-lab/makeflow-examples","sub_path":"hecil/Create_Corrected_AllLRReads.py","file_name":"Create_Corrected_AllLRReads.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"69"} +{"seq_id":"17336903834","text":"import random\nimport json\nfrom nltk import probability\nimport torch\nfrom .mother import NeuralNet\nfrom .nltk_functions import bag_of_words, tokenize\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nwith open('api/model/data.json', 'r') as f:\n responses = json.load(f)\n\nfile = \"api/model/data.pth\"\ndata = torch.load(file)\n\n\n\ndef predict(sentence):\n input_size = data[\"input_size\"]\n hidden_size = data[\"hidden_size\"]\n output_size = data[\"output_size\"]\n all_words = data[\"all_words\"]\n tags = data[\"tags\"]\n model_state = data[\"model_state\"]\n\n\n model = NeuralNet(input_size, hidden_size, output_size).to(device)\n model.load_state_dict(model_state)\n model.eval()\n\n\n \n\n if sentence == 'quit':\n exit(1)\n \n sentence = tokenize(sentence)\n x = bag_of_words(sentence, all_words)\n x = x.reshape(1, x.shape[0])\n x = torch.from_numpy(x)\n\n output = model(x)\n _, predicted = torch.max(output, dim=1)\n tag = tags[predicted.item()]\n\n probability = torch.softmax(output, dim=1)\n probability = probability[0][predicted.item()]\n\n if probability.item() > 0.75:\n for intent in responses[\"intents\"]:\n if tag == intent[\"tag\"]:\n return f\"{random.choice(intent['responses'])}\"\n else:\n return f\"Unfortunately, that is beyond my understanding. Please try again.\"\n\n","repo_name":"4bdul4ziz/Artificial-Conversation-Entity","sub_path":"api/model/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"30524712156","text":"from __future__ import annotations\n\nimport os\nimport sys\n\nfrom adapter_smg2 import SuperMarioGalaxy2Adapter\nfrom guihelpers import resolve_asset, PROGRAM_TITLE\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QIcon\n\n__all__ = [\"GalaxyTextEditor\"]\n\n\nclass GalaxyTextEditor(QDialog):\n def __init__(self, parent: QMainWindow, adapter_maker: type[SuperMarioGalaxy2Adapter]):\n super().__init__(parent)\n\n # --------------------------------------------------------------------------------------------------------------\n # Variable declarations\n\n self._adapter_maker_: type[SuperMarioGalaxy2Adapter] = None\n\n self.textMessageText: QPlainTextEdit = None\n self.buttonTagPageBreak: QToolButton = None\n self.buttonTagTextSize: QToolButton = None\n self.buttonTagTextColor: QToolButton = None\n self.buttonTagResetColor: QToolButton = None\n self.buttonTagNumberFont: QToolButton = None\n self.buttonTagYCenter: QToolButton = None\n self.buttonTagXCenter: QToolButton = None\n self.buttonTagRuby: QToolButton = None\n self.buttonTagPicture: QToolButton = None\n self.buttonTagSound: QToolButton = None\n self.buttonTagPlayer: QToolButton = None\n self.buttonTagRaceTime: QToolButton = None\n self.buttonTagDelay: QToolButton = None\n self.buttonTagFormatNumber: QToolButton = None\n self.buttonTagFormatString: QToolButton = None\n self.buttonBox: QDialogButtonBox = None\n\n # --------------------------------------------------------------------------------------------------------------\n\n self._ui_ = uic.loadUi(resolve_asset(\"assets/dialog_text.ui\"), self)\n self.setWindowTitle(PROGRAM_TITLE)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)\n\n self._adapter_maker_ = adapter_maker\n\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(self.reject)\n self.buttonTagPageBreak.clicked.connect(self._insert_tag_page_break_)\n self.buttonTagTextSize.clicked.connect(self._insert_tag_text_size_)\n self.buttonTagTextColor.clicked.connect(self._insert_tag_text_color_)\n self.buttonTagResetColor.clicked.connect(self._insert_tag_reset_color_)\n self.buttonTagNumberFont.clicked.connect(self._insert_tag_number_font_)\n self.buttonTagYCenter.clicked.connect(self._insert_tag_y_center_)\n self.buttonTagXCenter.clicked.connect(self._insert_tag_x_center_)\n self.buttonTagRuby.clicked.connect(self._insert_tag_ruby_)\n self.buttonTagPicture.clicked.connect(self._insert_tag_picture_)\n self.buttonTagSound.clicked.connect(self._insert_tag_sound_)\n self.buttonTagPlayer.clicked.connect(self._insert_tag_player_)\n self.buttonTagRaceTime.clicked.connect(self._insert_tag_race_time_)\n self.buttonTagDelay.clicked.connect(self._insert_tag_delay_)\n self.buttonTagFormatNumber.clicked.connect(self._insert_tag_format_number_)\n self.buttonTagFormatString.clicked.connect(self._insert_tag_format_string_)\n\n def request(self, label: str, message: str) -> tuple[str, bool]:\n self.setWindowTitle(f\"Editing {label}\")\n self.textMessageText.setPlainText(message)\n self.exec()\n\n edited_text = self.textMessageText.toPlainText()\n valid = self.result() == QDialog.Accepted\n return edited_text, valid\n\n # ------------------------------------------------------------------------------------------------------------------\n # Event handlers\n # ------------------------------------------------------------------------------------------------------------------\n def _insert_tag_page_break_(self):\n self.textMessageText.insertPlainText(\"[pagebreak]\")\n\n def _insert_tag_text_size_(self):\n text_size, valid = QInputDialog.getItem(self, \"Insert size change\", \"Select text size:\",\n self._adapter_maker_.FONT_SIZES, editable=False,\n flags=self.windowFlags())\n\n if valid:\n full_tag = f\"[size:{text_size}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_text_color_(self):\n text_color, valid = QInputDialog.getItem(self, \"Insert color change\", \"Select text color:\",\n self._adapter_maker_.FONT_COLORS, editable=False,\n flags=self.windowFlags())\n\n if valid:\n full_tag = f\"[color:{text_color}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_number_font_(self):\n description = \"Enter the text to be displayed with NumberFont.brfnt. Keep in mind that\\n\" \\\n \"this font is specifically designed for displaying numbers, so the vast\\n\" \\\n \"majority of characters may not be visible ingame.\"\n number_text, valid = QInputDialog.getText(self, \"Insert number text\", description, flags=self.windowFlags())\n\n if valid:\n full_tag = f\"[numberfont:{number_text}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_reset_color_(self):\n self.textMessageText.insertPlainText(\"[defcolor]\")\n\n def _insert_tag_y_center_(self):\n self.textMessageText.insertPlainText(\"[ycenter]\")\n\n def _insert_tag_x_center_(self):\n self.textMessageText.insertPlainText(\"[xcenter]\")\n\n def _insert_tag_ruby_(self):\n description = \"Specify kanji and furigana texts for ruby. This tag will be rendered\\n\" \\\n \"only if the console's language is set to Japanese.\"\n kanji, furigana, valid = InsertRubyDialog.specify(self, \"Insert ruby\", description)\n\n if valid:\n full_tag = f\"[ruby:{kanji};{furigana}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_picture_(self):\n description = \"Select the icon to be inserted into the text.\"\n picture_icon, valid = PictureIconDialog.select(self, \"Insert icon\", description, self._adapter_maker_)\n\n if valid:\n full_tag = f\"[icon:{picture_icon}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_sound_(self):\n description = \"Enter the sound's name to be played. A complete list of sounds can be\\n\" \\\n \"found on the Luma's Workshop wiki. If the sound does not play, it may\\n\" \\\n \"have to be added to the Galaxy's UseResource file.\"\n sound_name, valid = QInputDialog.getText(self, \"Insert sound effect\", description, text=\"SE_SV_TICOFAT_META\",\n flags=self.windowFlags())\n\n if valid:\n full_tag = f\"[sound:{sound_name}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_player_(self):\n description = \"Specify the player name preset. SMG2 only supports preset 0 by default,\\n\" \\\n \"but more texts can be added by editing 'SystemMessage.arc/~/PlayerName.msbt'.\"\n preset_id, valid = QInputDialog.getInt(self, \"Insert player name\", description, 0, 0, 255,\n flags=self.windowFlags())\n\n if valid:\n full_tag = f\"[player:{preset_id}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_race_time_(self):\n description = \"Select the race whose time should be displayed.\"\n race_time, valid = QInputDialog.getItem(self, \"Insert race time\", description,\n self._adapter_maker_.RACE_TIMES, editable=False,\n flags=self.windowFlags())\n\n if valid:\n full_tag = f\"[race:{race_time}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_delay_(self):\n description = \"Specify by how many frames text printing should be delayed.\\n\" \\\n \"60 frames correspond to one 1 second.\"\n delay, valid = QInputDialog.getInt(self, \"Insert printing delay\", description, 60, 0, 65535,\n flags=self.windowFlags())\n\n if valid:\n full_tag = f\"[delay:{delay}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_format_number_(self):\n description = \"Inserts a variable that can be replaced with a proper number during gameplay.\\n\" \\\n \"\\n\" \\\n \"There are only a few situations where this can be used properly. If the game doesn't\\n\" \\\n \"replace this variable with a proper number, the default number will be used instead.\\n\" \\\n \"The default number will ignore the specified format option, though.\"\n format_id, argument_idx, default_value, valid = IntVarDialog.select(self, \"Insert number variable\", description)\n\n if valid:\n full_tag = f\"[intvar:{format_id};{argument_idx};{default_value}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n def _insert_tag_format_string_(self):\n description = \"Inserts a variable that can be replaced with a proper text string during gameplay.\\n\" \\\n \"\\n\" \\\n \"There are only a few situations where this can be used properly. If the game doesn't\\n\" \\\n \"replace this variable with a proper string, the text at the given default address will\\n\" \\\n \"be used. This feature is highly experimental and will most likely crash your game if\\n\" \\\n \"used wrongly. Therefore, just leave the default pointer at 0.\\n\" \\\n \"\\n\" \\\n \"Tag ID is unused by the game, but it can be specified.\"\n tag_id, argument_idx, default_pointer, valid = StringVarDialog.select(self, \"Insert text variable\", description)\n\n if valid:\n full_tag = f\"[stringvar:{tag_id};{argument_idx};0x{default_pointer:08X}]\"\n self.textMessageText.insertPlainText(full_tag)\n\n\nclass InsertRubyDialog(QDialog):\n def __init__(self, parent: QWidget):\n super().__init__(parent)\n\n # --------------------------------------------------------------------------------------------------------------\n # Variable declarations\n\n self.labelDescription: QLabel = None\n self.lineKanji: QLineEdit = None\n self.lineFurigana: QLineEdit = None\n self.buttonBox: QDialogButtonBox = None\n\n # --------------------------------------------------------------------------------------------------------------\n\n self._ui_ = uic.loadUi(resolve_asset(\"assets/dialog_ruby.ui\"), self)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(self.reject)\n\n @staticmethod\n def specify(parent: QWidget, title: str, description: str) -> tuple[str, str, bool]:\n dialog = InsertRubyDialog(parent)\n dialog.setWindowTitle(title)\n dialog.labelDescription.setText(description)\n dialog.exec()\n\n kanji = dialog.lineKanji.text()\n furigana = dialog.lineFurigana.text()\n valid = dialog.result() == QDialog.Accepted\n return kanji, furigana, valid\n\n\nclass PictureIconDialog(QDialog):\n def __init__(self, parent: QWidget, adapter_maker: type[SuperMarioGalaxy2Adapter]):\n super(PictureIconDialog, self).__init__(parent)\n\n # --------------------------------------------------------------------------------------------------------------\n # Variable declarations\n\n self.comboIcons: QComboBox = None\n self.labelDescription: QLabel = None\n self.buttonBox: QDialogButtonBox = None\n\n # --------------------------------------------------------------------------------------------------------------\n\n self._ui_ = uic.loadUi(resolve_asset(\"assets/dialog_picture.ui\"), self)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(self.reject)\n\n for key in sorted(adapter_maker.PICTURE_NAMES):\n icon_path = f\"icons/{key}.png\"\n icon = None\n\n if os.path.isfile(icon_path):\n try:\n icon = QIcon(icon_path)\n except Exception:\n print(f\"Couldn't load picture icon {icon_path}\", file=sys.stderr)\n\n if icon is None:\n self.comboIcons.addItem(key)\n else:\n self.comboIcons.addItem(icon, key)\n\n @staticmethod\n def select(parent: QWidget, title: str, description: str, adapter_maker: type[SuperMarioGalaxy2Adapter])\\\n -> tuple[str, bool]:\n dialog = PictureIconDialog(parent, adapter_maker)\n dialog.setWindowTitle(title)\n dialog.labelDescription.setText(description)\n dialog.exec()\n\n picture = dialog.comboIcons.currentText()\n valid = dialog.result() == QDialog.Accepted\n return picture, valid\n\n\nclass IntVarDialog(QDialog):\n def __init__(self, parent: QWidget):\n super(IntVarDialog, self).__init__(parent)\n\n # --------------------------------------------------------------------------------------------------------------\n # Variable declarations\n\n self.comboFormat: QComboBox = None\n self.spinArgumentIdx: QSpinBox = None\n self.spinDefaultValue: QSpinBox = None\n self.labelDescription: QLabel = None\n self.buttonBox: QDialogButtonBox = None\n\n # --------------------------------------------------------------------------------------------------------------\n\n self._ui_ = uic.loadUi(resolve_asset(\"assets/dialog_intvar.ui\"), self)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(self.reject)\n\n @staticmethod\n def select(parent: QWidget, title: str, description: str)\\\n -> tuple[int, int, int, bool]:\n dialog = IntVarDialog(parent)\n dialog.setWindowTitle(title)\n dialog.labelDescription.setText(description)\n dialog.exec()\n\n format_id = dialog.comboFormat.currentIndex()\n argument_idx = dialog.spinArgumentIdx.value()\n default_value = dialog.spinDefaultValue.value()\n valid = dialog.result() == QDialog.Accepted\n return format_id, argument_idx, default_value, valid\n\n\nclass StringVarDialog(QDialog):\n def __init__(self, parent: QWidget):\n super(StringVarDialog, self).__init__(parent)\n\n # --------------------------------------------------------------------------------------------------------------\n # Variable declarations\n\n self.spinTagID: QSpinBox = None\n self.spinArgumentIdx: QSpinBox = None\n self.lineDefaultPointer: QLineEdit = None\n self.labelDescription: QLabel = None\n self.buttonBox: QDialogButtonBox = None\n\n # --------------------------------------------------------------------------------------------------------------\n\n self._ui_ = uic.loadUi(resolve_asset(\"assets/dialog_stringvar.ui\"), self)\n self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(self.reject)\n\n @staticmethod\n def select(parent: QWidget, title: str, description: str)\\\n -> tuple[int, int, int, bool]:\n dialog = StringVarDialog(parent)\n dialog.setWindowTitle(title)\n dialog.labelDescription.setText(description)\n dialog.exec()\n\n tag_id = dialog.spinTagID.value()\n argument_idx = dialog.spinArgumentIdx.value()\n default_pointer_string = dialog.lineDefaultPointer.text()\n valid = dialog.result() == QDialog.Accepted\n\n try:\n default_pointer_string = default_pointer_string.strip()\n default_pointer = int(default_pointer_string, 0)\n\n if default_pointer < 0 or 0xFFFFFFFF < default_pointer:\n default_pointer = 0\n except Exception:\n default_pointer = 0\n\n return tag_id, argument_idx, default_pointer, valid\n","repo_name":"SunakazeKun/galaxymsbt","sub_path":"gui_text.py","file_name":"gui_text.py","file_ext":"py","file_size_in_byte":16563,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"4678126987","text":"import os\nimport shutil\nfrom core import *\n\n\ndef setup_module():\n os.mkdir(\"./test\")\n\ndef create_file_with_content(fname, content=\"\"):\n with open(fname, \"w+\") as f:\n f.write(content)\n\ndef teardown_module():\n shutil.rmtree(\"./test\")\n\n\nclass TestFileDirExist:\n\n @classmethod\n def setup_class(cls):\n os.mkdir(\"./test/exist\")\n create_file_with_content(\"./test/exist/exist1.txt\")\n create_file_with_content(\"./test/exist/exist2.txt\")\n\n @classmethod\n def teardown_class(cls):\n shutil.rmtree(\"./test/exist\")\n\n def test_is_file_not_exist(self):\n assert is_file(\"./notexist.txt\") == False\n\n def test_is_file_exists(self):\n assert is_file(\"./test/exist/exist1.txt\") == True\n assert is_file(\"./test/exist/exist2.txt\") == True\n\n def test_is_dir_not_exists(self):\n assert is_dir(\"./notexist\") == False\n\n def test_is_dir_exists(self):\n assert is_dir(\"./test/exist\") == True\n\n\nclass TestTimestamp:\n\n def test_filename_timestamp(self):\n fname = \"test.txt\"\n tstamp = \"20180629.111516\"\n assert fname_timestamp(fname, tstamp) == \"test.20180629.111516.txt\"\n\n\nclass TestFileManipulation:\n\n @classmethod\n def setup_class(cls):\n os.mkdir(\"./test/rename\")\n os.mkdir(\"./test/copy\")\n create_file_with_content(\"./test/rename/r1.txt\")\n create_file_with_content(\"./test/copy/c1.txt\")\n create_file_with_content(\"./test/copy/c1.txt\")\n\n @classmethod\n def teardown_class(cls):\n shutil.rmtree(\"./test/rename\")\n shutil.rmtree(\"./test/copy\")\n\n def test_rename(self):\n rename_file(\"./test/rename/r1.txt\", \"./test/rename/r2.txt\")\n assert is_file(\"./test/rename/r1.txt\") == False\n assert is_file(\"./test/rename/r2.txt\") == True\n\n def test_copy_file(self):\n copy_file(\"./test/copy/c1.txt\", \"./test/copy/c2.txt\")\n assert is_file(\"./test/copy/c1.txt\") == True\n assert is_file(\"./test/copy/c2.txt\") == True\n\n def test_path_filename(self):\n fpath = \"/home/john/test.txt\"\n assert path_filename(fpath) == \"test.txt\"\n\n\nclass TestBackup:\n\n @classmethod\n def setup_class(cls):\n os.mkdir(\"./test/backup\")\n os.mkdir(\"./test/backup/src\")\n os.mkdir(\"./test/backup/dest_empty\")\n os.mkdir(\"./test/backup/dest_populated\")\n os.mkdir(\"./test/backups\")\n os.mkdir(\"./test/backups/src\")\n os.mkdir(\"./test/backups/dest_empty\")\n os.mkdir(\"./test/backups/dest_populated\")\n create_file_with_content(\"./test/backup/src/test.txt\")\n create_file_with_content(\"./test/backup/dest_populated/test.txt\")\n create_file_with_content(\"./test/backups/src/test.txt\")\n create_file_with_content(\"./test/backups/src/test2.txt\")\n create_file_with_content(\"./test/backups/src/test3.txt\")\n create_file_with_content(\"./test/backups/dest_populated/test.txt\")\n create_file_with_content(\"./test/backups/dest_populated/test2.txt\")\n create_file_with_content(\"./test/backups/dest_populated/test3.txt\")\n\n @classmethod\n def teardown_class(cls):\n shutil.rmtree(\"./test/backup\")\n shutil.rmtree(\"./test/backups\")\n\n def test_backup_file_no_rename(self):\n src = os.path.abspath(\"./test/backup/src/test.txt\")\n dest = [os.path.abspath(\"./test/backup/dest_empty\")]\n backup_file(src, dest)\n assert is_file(src) == True\n assert is_file(os.path.join(dest[0], \"test.txt\")) == True\n\n def test_backup_file_rename(self):\n src = os.path.abspath(\"./test/backup/src/test.txt\")\n dest = [os.path.abspath(\"./test/backup/dest_populated\")]\n backup_file(src, dest)\n files = os.listdir(dest[0])\n assert len(files) == 2\n assert files[0].startswith(\"test\") == True\n assert files[0].endswith(\".txt\") == True\n assert files[1].startswith(\"test\") == True\n assert files[0].endswith(\".txt\") == True\n assert files[0] != files[1]\n\n def test_backup_files_no_rename(self):\n srcs = [\n os.path.abspath(\"./test/backups/src/test.txt\"),\n os.path.abspath(\"./test/backups/src/test2.txt\"),\n os.path.abspath(\"./test/backups/src/test3.txt\")\n ]\n dest = [os.path.abspath(\"./test/backups/dest_empty\")]\n backup_files(srcs, dest)\n files = os.listdir(dest[0])\n assert len(files) == 3\n assert \"test.txt\" in files\n assert \"test2.txt\" in files\n assert \"test3.txt\" in files\n\n def test_backup_files_rename(self):\n srcs = [\n os.path.abspath(\"./test/backups/src/test.txt\"),\n os.path.abspath(\"./test/backups/src/test2.txt\"),\n os.path.abspath(\"./test/backups/src/test3.txt\")\n ]\n dest = [os.path.abspath(\"./test/backups/dest_populated\")]\n backup_files(srcs, dest)\n files = os.listdir(dest[0])\n assert len(files) == 6\n counts = [0, 0, 0]\n for file in files:\n if file.startswith(\"test2\"):\n counts[1] += 1\n elif file.startswith(\"test3\"):\n counts[2] += 1\n elif file.startswith(\"test\"):\n counts[0] += 1\n assert counts == [2, 2, 2]\n\n\nclass TestConfig:\n\n @classmethod\n def setup_class(cls):\n os.mkdir(\"./test/template\")\n\n @classmethod\n def teardown_class(cls):\n shutil.rmtree(\"./test/template\")\n\n def test_template_config(self):\n loc = os.path.abspath(\"./test/template/\")\n loc = os.path.join(loc, fname_timestamp(\"config.json\", timestamp_str()))\n template_config(loc)\n files = os.listdir(\"./test/template\")\n assert len(files) == 1\n assert files[0].startswith(\"config\") == True\n assert files[0].endswith(\".json\") == True\n\n def test_config_read(self):\n loc = os.path.abspath(\"./test/template/\")\n loc = os.path.join(loc, fname_timestamp(\"config.json\", timestamp_str()))\n template_config(loc)\n valid, cfg = read_config(loc)\n assert valid == True\n assert \"/home/anon/test1.txt\" in cfg[\"sources\"]\n assert \"/home/anon/test2.txt\" in cfg[\"sources\"]\n assert \"/home/anon/backup/\" in cfg[\"destinations\"]\n assert \"/home/anon/backup2/\" in cfg[\"destinations\"]\n\n\nclass TestUserInputValidation:\n\n @classmethod\n def setup_class(cls):\n os.mkdir(\"./test/validate\")\n os.mkdir(\"./test/validate/dest\")\n create_file_with_content(\"./test/validate/test.txt\")\n\n @classmethod\n def teardown_class(cls):\n shutil.rmtree(\"./test/validate\")\n\n def test_user_input_validation_errs(self):\n root = os.path.abspath(\"./test/validate\")\n bad_file = os.path.join(root, \"nosrc1.txt\")\n bad_dir = os.path.join(root, \"nosrc2/\")\n valid, errors = validate_user_input([bad_file], [bad_dir])\n assert valid == False\n assert len(errors) == 2\n assert \"The source file `{}` does not exist\".format(bad_file) in errors\n assert \"The destination directory `{}` does not exist\".format(bad_dir) in errors\n\n def test_user_input_validation_no_errs(self):\n root = os.path.abspath(\"./test/validate\")\n good_file = os.path.join(root, \"test.txt\")\n good_dir = os.path.join(root, \"dest/\")\n valid, errors = validate_user_input([good_file], [good_dir])\n assert valid == True\n assert len(errors) == 0\n\n","repo_name":"sirrah23/MultiBack","sub_path":"test_multiback.py","file_name":"test_multiback.py","file_ext":"py","file_size_in_byte":7439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"32895487241","text":"import json\nimport datetime\nimport re\nfrom telethon.tl.tlobject import TLObject\n\ndef date_format(field):\n if type(field) is datetime.datetime:\n return field.strftime(\"%Y-%m-%d %H:%M:%S\")\n elif str(type(field)).find('telethon') != -1:\n return ttjson(field)\n\ndef tt_to_json_string(ttobject):\n #return json.dumps(ttobject.to_dict(), default=date_format)\n return json.dumps(tt_to_dict(ttobject))\n\ndef is_convertable_type(var):\n supported_types = (int, float, str, bool, tuple)\n return var is None or type(var) in supported_types\n\ndef tt_to_dict(ttoject):\n ttdict = {}\n fields = []\n if type(ttoject) is dict:\n fields = ttoject.items()\n elif hasattr(ttoject, '__dict__'):\n fields = vars(ttoject).items()\n else:\n return str(ttoject)\n\n for key, value in fields:\n if key.find('_') == 0:\n pass\n\n try:\n iter(value)\n except TypeError:\n is_list = False\n else:\n is_list = True\n\n if is_convertable_type(value):\n ttdict[key] = value\n elif type(value) is datetime.datetime:\n ttdict[key] = value.strftime(\"%Y-%m-%d %H:%M:%S\")\n elif type(value) is bytes:\n ttdict[key] = \"\".join(map(chr, value))\n elif type(value) is list:\n ttdict[key] = [tt_to_dict(child) for child in iter(value)]\n elif type(value).__base__ is object:\n ttdict[key] = tt_to_dict(value)\n elif type(value).__base__ is TLObject or hasattr(value, 'to_dict'):\n ttdict[key] = tt_to_dict(value.to_dict())\n elif str(value).find('object at') != -1:\n ttdict[key] = None\n elif is_list:\n ttdict[key] = [tt_to_dict(child) for child in iter(value)]\n else:\n ttdict[key] = str(value)\n\n return ttdict\n\ndef ttjson(ttobject):\n try:\n iterator = iter(ttobject)\n except TypeError:\n tt_str = tt_to_json_string(ttobject)\n else:\n tt_str = json.dumps([json.loads(tt_to_json_string(child)) for child in iterator])\n\n return json.loads(tt_str)","repo_name":"lup-/tg_digger","sub_path":"telegram/ttjson.py","file_name":"ttjson.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29083972373","text":"#TODO dataclass TAG (for beta function)\n#TODO quads geometric strength\n#TODO manual geometric strength variation \n#TODO documentation for functions\n\n# this script creates lte files and saves in ../lteFiles\n\n#read lte parameters\nimport toml\nfrom dataclasses import dataclass\nimport sys\n\n@dataclass\nclass Quaddrupole:\n identifier: str\n elegantKey: str\n l: float\n hA: float\n k: float\n position: int\n\n\n@dataclass\nclass BendingMagnet:\n identifier: str\n elegantKey: str\n l: float\n angle: float\n e1: float\n e2: float\n h1: float\n h2: float\n position: int\n\n@dataclass\nclass Drift:\n identifier: str\n elegantKey: str\n l: float\n position: int\n\n#-------------------------------------------------------------------------------\n\n# read lattice parameters into list of quads and bends\ndef readFileMagtoList(quadFile: str):\n \"\"\"\n reads the quadPath file to a list of Quadrupole\n\n quadFile: string of Path to file\n \"\"\"\n quadsFile = open(quadFile) #\"../latticeParameter/latticeElements/c_weg_quads.toml\" \n quadDict = toml.load(quadsFile, _dict=dict)\n\n quads = []\n bends = []\n\n for k, element in enumerate(quadDict):\n if quadDict[element][\"elegantKey\"] == \"quad\":\n quads.append(Quaddrupole( element, \"quad\", \n quadDict[element][\"l\"], \n quadDict[element][\"hA\"], \n quadDict[element][\"k1\"] , # geometric strength maybe here maybe later\n k)) \n elif quadDict[element][\"elegantKey\"] == \"sbend\":\n bends.append(BendingMagnet( element, \"sbend\", \n quadDict[element][\"l\"], \n quadDict[element][\"angle\"], \n quadDict[element][\"e1\"],\n quadDict[element][\"e2\"],\n quadDict[element][\"h1\"],\n quadDict[element][\"h2\"],\n k))\n\n return quads, bends\n\ndef readFileDrifttoList(driftFile):\n \"\"\"\n reads the driftPath file to a list of Drift\n\n driftFile: string of Path to file\n \"\"\"\n quadsFile = open(driftFile) \n driftDict = toml.load(quadsFile, _dict=dict)\n\n drifts = []\n for k, element in enumerate(driftDict):\n drifts.append(Drift(element, \"drift\", driftDict[element][\"l\"], k))\n\n return drifts\n\n#-------------------------------------------------------------------------------\n\n#following functions assemble strings for lte file from objects\ndef quadtoString(quad: Quaddrupole):\n string = f\"{quad.identifier}: {quad.elegantKey}, l={quad.l}, k1={quad.k}\"\n return string\n\ndef bendtoString(bend: BendingMagnet):\n string= f\"{bend.identifier}: {bend.elegantKey}, l={bend.l}, angle={bend.angle}, e1={bend.e1}, e2={bend.e2}, h1={bend.h1}, h2={bend.h2}\"\n return string\n\ndef drifttoString(drift: Drift):\n string=f\"{drift.identifier}: {drift.elegantKey}, l={drift.l}\"\n return string\n\ndef clearstr(prevel, xlim, ylim):\n return f\"{prevel}CLEAN: clean,mode=\\\"absval\\\", xlimit={xlim}, ylimit={ylim}\"\n\ndef lineString(upperstring: str):\n lines = upperstring.split(\"\\n\")\n elements = []\n for line in lines:\n if line.split(\":\", 1)[0].strip() != \"\":\n elements.append(line.split(\":\", 1)[0].strip())\n string = \"path: LINE=(\"\n for e in elements:\n string = string + e + \", \"\n string = string[:-2] + \")\\n\"\n return string\n\n#-------------------------------------------------------------------------------\n\n\n\ndef assembleLine(quads, bends, drifts, tags, xlim= 0.035, ylim= 0.035):\n \"\"\"\n assembles the lte string\n \"\"\"\n string = \"\"\n\n string = string + f\"apperture: maxamp, x_max={xlim}, y_max={ylim}, elliptical=1, exponent=2\\n\"\n\n for pos in range(len(drifts)):\n string = string + drifttoString(drifts[pos]) + \"\\n\"\n for quad in quads:\n if quad.position == pos:\n string = string + quadtoString(quad) + \"\\n\"\n break\n for bend in bends:\n if bend.position == pos:\n string = string + bendtoString(bend) + \"\\n\"\n break\n string = string + lineString(string)\n return string\n\ndef writelteFile(filename, magfile, driftfile):\n \"\"\"\n writes the lte string to lte file\n \"\"\"\n quads, bends = readFileMagtoList(magfile)\n drifts = readFileDrifttoList(driftfile)\n string = assembleLine(quads, bends, drifts, 0)\n with open(filename, \"w\") as text_file:\n text_file.write(string)\n\n#-------------------------------------------------------------------------------\n\nltePath, quadPath, driftPath = sys.argv[1:4]\n\nif __name__ == \"__main__\":\n writelteFile(ltePath, quadPath, driftPath)\n","repo_name":"cyclotron-bonn/beamline_simulation","sub_path":"buildLte/buildlte.py","file_name":"buildlte.py","file_ext":"py","file_size_in_byte":4891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29242652783","text":"from rest_framework import views\nfrom rest_framework.response import Response\nfrom .external_data import STATIONS_DATA, get_selected_trains\nfrom .choices import STATIONS_LIST, TRAINS_LIST\n\n\nclass StationNameView(views.APIView):\n def get_object(self, index):\n try:\n return STATIONS_LIST[index]\n except IndexError:\n return \"���無此車站\"\n\n def get(self, request, index, format=None):\n station_name = self.get_object(index)\n if station_name != \"查無此車站\":\n return Response({\"station_name\": station_name})\n else:\n return Response({\"detail\": \"查無此車站\"})\n\n\nclass StationNameToPosView(views.APIView):\n def get_object(self, name):\n try:\n return STATIONS_DATA[name]\n except KeyError:\n return \"查無此車站\"\n\n def get(self, request, name, format=None):\n station_pos = self.get_object(name)\n if station_pos != \"查無此車站\":\n return Response({\"x\": station_pos[0], \"y\": station_pos[1]})\n else:\n return Response({\"detail\": \"查無此車站\"})\n\n\nclass TrainNameView(views.APIView):\n def get_object(self, index):\n try:\n return TRAINS_LIST[index]\n except IndexError:\n return \"查無此列車\"\n\n def get(self, request, index, format=None):\n train_name = self.get_object(index)\n if train_name != \"查無此列車\":\n return Response({\"train_name\": train_name})\n else:\n return Response({\"detail\": \"查無此車站\"})\n\n\nclass SelectTrainView(views.APIView):\n def get(self, request, format=None):\n try:\n start_station = request.data[\"start_station\"]\n end_station = request.data[\"end_station\"]\n start_time = request.data[\"start_time\"]\n end_time = request.data[\"end_time\"]\n except KeyError:\n return Response({\"detail\": \"json資料錯誤\"})\n\n if not start_station in STATIONS_LIST and not end_station in STATIONS_LIST:\n return Response({\"detail\": \"車站資料錯誤\"})\n\n selected_trains = get_selected_trains(\n start_station=start_station,\n end_station=end_station,\n start_time=start_time,\n end_time=end_time,\n )\n\n return Response(selected_trains)\n","repo_name":"Penguin-jpg/TRA_Helper_Backend","sub_path":"utils/util_views.py","file_name":"util_views.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34437562069","text":"# Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.\n#\n# Assume a BST is defined as follows:\n#\n# The left subtree of a node contains only nodes with keys less than or equal to the node's key.\n# The right subtree of a node contains only nodes with keys greater than or equal to the node's key.\n# Both the left and right subtrees must also be binary search trees.\n#\n#\n# For example:\n# Given BST [1,null,2,2],\n#\n# 1\n# \\\n# 2\n# /\n# 2\n#\n#\n# return [2].\n\n# 解决方法:考虑到对于一颗BST,其中序遍历得到的即为升序的结果,因此,只要在中序遍历的过程中,判断当前节点与前一个节点是否相同。如果相同,可以计数+1,如果不相同,则判断当前节点的计数与最大计数\n# 的大小,如果计数一致,则将该节点的值加入到result中,如果计数大于max_count,则将result更新为当前节点的值,然后交给递归遍历。\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n prev = None\n max_count = 0\n current_count = 0\n result = []\n\n def findMode(self, root: TreeNode) -> List[int]:\n self.dfs(root)\n return self.result\n\n def dfs(self, node):\n if not node: return None\n\n self.dfs(node.left)\n self.current_count = 1 if node.val != self.prev else self.current_count + 1\n if self.current_count == self.max_count:\n self.result.append(node.val)\n elif self.current_count > self.max_count:\n self.result = [node.val]\n self.max_count = self.current_count\n self.prev = node.val\n self.dfs(node.right)\n","repo_name":"YLyeliang/now_leet_code_practice","sub_path":"tree/find_mode_in_BST.py","file_name":"find_mode_in_BST.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"7004272141","text":"import argparse\nimport datetime\nimport logging\nfrom pathlib import Path\nimport shutil\nimport sys\n\nfrom google.cloud.bigquery import Client\nfrom google.cloud.exceptions import Conflict\n\nfrom common.py_libs.dag_generator import generate_file_from_template\nfrom common.py_libs.jinja import apply_jinja_params_dict_to_file\nfrom src.constants import DAG_TEMPLATE_FILE\nfrom src.constants import DATASET\nfrom src.constants import DDL_SQL_FILES\nfrom src.constants import DEPENDENCIES_INPUT_DIR\nfrom src.constants import DEPENDENCIES_OUTPUT_DIR\nfrom src.constants import OUTPUT_DIR\nfrom src.constants import PROJECT\n\n\ndef _generate_dag_from_template(template_file: Path,\n generation_target_directory: Path,\n subs: dict) -> None:\n \"\"\"Generates DAG code from template file.\n Each DAG is responsible for loading one table.\n\n Args:\n template_file (Path): Path of the template file.\n generation_target_directory (Path): Directory where files are generated.\n \"\"\"\n output_dag_py_file = Path(generation_target_directory,\n \"marketing_liveramp_extract_to_bq.py\")\n\n generate_file_from_template(template_file, output_dag_py_file, **subs)\n\n\ndef _create_output_dir_structure() -> None:\n OUTPUT_DIR.mkdir(exist_ok=True, parents=True)\n DEPENDENCIES_OUTPUT_DIR.mkdir(exist_ok=True, parents=True)\n\n\ndef _parse_args(args) -> str:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--debug\",\n action=\"store_true\",\n help=\"Flag to set log level to DEBUG. Default is INFO.\")\n args = parser.parse_args(args)\n return args.debug\n\n\ndef main(parsed_args):\n debug = parsed_args\n\n logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)\n\n logging.info(\n \"\\n---------------------------------------\\n\"\n \"Using the following parameters from config:\\n\"\n \" PROJECT = %s \\n\"\n \" DATASET = %s \\n\"\n \"---------------------------------------\\n\", PROJECT, DATASET)\n logging.info(\"Processing tables...\")\n\n _create_output_dir_structure()\n\n now = datetime.datetime.utcnow()\n now_date = datetime.datetime(now.year, now.month, now.day)\n\n bq_client = Client()\n\n # Get table name and SQL file for current table.\n for sql_file in DDL_SQL_FILES:\n\n sql_subs = {\n \"project_id_src\": PROJECT,\n \"marketing_liveramp_datasets_cdc\": DATASET,\n }\n\n try:\n logging.info(\"Processing table %s\", sql_file)\n\n sql_code = apply_jinja_params_dict_to_file(input_file=sql_file,\n jinja_data_dict=sql_subs)\n\n logging.debug(\"Creating table %s ...\", sql_file)\n\n query_job = bq_client.query(sql_code)\n\n # Let's wait for the query to complete.\n _ = query_job.result()\n\n logging.debug(\"Table %s.%s.%s has been created.\", PROJECT, DATASET,\n sql_file)\n\n logging.info(\"Table processed successfully.\")\n\n except Conflict:\n logging.warning(\"❗ Table already exists. Skipping it.\")\n\n py_subs = {\n \"project_id\": PROJECT,\n \"dataset\": DATASET,\n \"start_date\": now_date\n }\n\n logging.info(\"Generating DAG...\")\n _generate_dag_from_template(template_file=DAG_TEMPLATE_FILE,\n generation_target_directory=OUTPUT_DIR,\n subs=py_subs)\n\n logging.info(\"Done generating DAG.\")\n\n logging.info(\"-----------------------------\")\n\n logging.info(\"Copying dependencies...\")\n\n shutil.copytree(src=DEPENDENCIES_INPUT_DIR,\n dst=DEPENDENCIES_OUTPUT_DIR,\n dirs_exist_ok=True)\n\n logging.info(\"Done preparing the directory for Airflow.\")\n\n logging.info(\"✅ LiveRamp module deployed successfully!\")\n\n\nif __name__ == \"__main__\":\n deploy_arguments = _parse_args(sys.argv[1:])\n main(deploy_arguments)\n","repo_name":"GoogleCloudPlatform/cortex-marketing","sub_path":"src/LiveRamp/src/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"21850664656","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Point:\n def __init__(self, x_position, y_position, x_speed, y_speed, mass, frequency=1):\n self.x_position = x_position\n self.y_position = y_position\n self.x_speed = x_speed\n self.y_speed = y_speed\n self.frequency = frequency\n self.mass = mass\n\n def move(self):\n self.x_position += self.x_speed / self.frequency\n self.y_position += self.y_speed / self.frequency\n\n def set_x_position(self, x_position):\n self.x_position = x_position\n\n def set_y_position(self, y_position):\n self.y_position = y_position\n\n def set_x_speed(self, x_speed):\n self.x_speed = x_speed\n\n def set_y_speed(self, y_speed):\n self.y_speed = y_speed\n\n\ndef compute_next_step(point, x_forces=0, y_forces=0):\n point.set_x_position(point.x_position + point.x_speed / point.frequency)\n point.set_x_speed(point.x_speed + x_forces / point.frequency / point.mass)\n point.set_y_position(point.y_position + point.y_speed / point.frequency)\n point.set_y_speed(point.y_speed + y_forces / point.frequency / point.mass)\n return point\n\n\ndef generate_equilibrium():\n p = Point(0, 0, 1, 1, mass=1)\n history = []\n for i in range(100):\n p = compute_next_step(point=p)\n history.append((p.x_position, p.y_position))\n\n history = np.array(history)\n plt.scatter(history[:, 1], history[:, 0], color='b')\n plt.show()\n return history\n\n\ndef generate_free_fall(initial_x_speed=0, initial_y_speed=0, nb_steps=10):\n p = Point(0, 0, x_speed=initial_x_speed, y_speed=initial_y_speed, mass=1)\n history = []\n for i in range(nb_steps):\n p = compute_next_step(point=p, x_forces=-9.81)\n history.append((p.x_position, p.y_position))\n\n history = np.array(history)\n plt.scatter(history[:, 1], history[:, 0], color='b')\n plt.show()\n return history\n\n\nif __name__ == '__main__':\n # generate_equilibrium()\n generate_free_fall(initial_x_speed=10, initial_y_speed=10, nb_steps=20)\n","repo_name":"pauldechorgnat/physics-simulations","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21826217866","text":"from itertools import chain\r\nfrom time import time\r\n\r\nfrom numpy import sum\r\nfrom pandas import DataFrame\r\nfrom glider import Frame\r\nimport psutil\r\n\r\n\r\ncurrent_process = psutil.Process()\r\n\r\ndef get_data(factor):\r\n n = lambda i: 'ham{0} ham{0} foo{0}'.format(i).split()\r\n # n = lambda i: 'ham ham foo'.format(i).split()\r\n names = lambda s: list(chain.from_iterable(n(i) for i in range(s)))\r\n values = [1, 2, 3]\r\n # Create two sets of arrays\r\n d1 = {'name': names(100 * factor)}\r\n d2 = {'name': names(10 * factor)}\r\n # Add some columns\r\n new_cols = [\r\n (100 * factor, d1, 'abc'),\r\n (10 * factor, d2, 'fgh')]\r\n for size, d, names in new_cols:\r\n for n in names:\r\n d[n] = values * size\r\n return d1, d2\r\n\r\n\r\ndef join_bench(factor):\r\n d1, d2 = get_data(factor)\r\n print('-- join (%s x %s)--' % (len(d1['a']), len(d2['f'])))\r\n\r\n start = time()\r\n f1 = Frame(d1)\r\n f2 = Frame(d2)\r\n f3 = f1.join(f2, 'name', how='inner')\r\n glider_time = time() - start\r\n\r\n\r\n start = time()\r\n df1 = DataFrame(d1)\r\n df2 = DataFrame(d2)\r\n df3 = df1.merge(df2, on='name')\r\n pandas_time = time() - start\r\n\r\n print('glider: %.2f / pandas: %.2f' % (glider_time, pandas_time))\r\n\r\n print(len(f3), len(df3))\r\n\r\ndef groupby_bench(factor):\r\n print('-- groupby --')\r\n n = lambda i: 'ham{} ham foo'.format(i % (factor / 1000)).split()\r\n names = list(chain.from_iterable(n(i) for i in range(factor)))\r\n data = {\r\n 'name': names,\r\n 'a': [1, 2, 3] * factor,\r\n 'b': [1, 2, 3] * factor,\r\n 'c': [1, 2, 3] * factor,\r\n 'd': [1, 2, 3] * factor,\r\n 'e': [1, 2, 3] * factor,\r\n }\r\n\r\n start = time()\r\n f1 = Frame(data)\r\n f2 = f1.select('name', (sum, 'b'))\r\n print('glider:', time() - start)\r\n\r\n start = time()\r\n df1 = DataFrame(data)\r\n df2 = df1.groupby('name')['b'].sum()\r\n print('pandas:', time() - start)\r\n # Output\r\n # glider: 0.088\r\n # pandas: 0.264\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n for exp in range(1, 5):\r\n join_bench(10**exp)\r\n groupby_bench(50000)\r\n","repo_name":"bertrandchenal/glider","sub_path":"bench.py","file_name":"bench.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"42131634446","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Задание 3. Вариант 3. Дано предложение. Удалить из него все символы с n1-го по n2-й (n1 <= n2).\n\nif __name__ == '__main__':\n predlog = str(input(\"Введите предложение: \"))\n\n print(\"Введите диапазон для удаления: \")\n n1 = int(input())\n n2 = int(input())\n\n print(predlog[:n1], predlog[n2+1:])\n","repo_name":"ItsMyLife1337/ForPrograms2.3","sub_path":"individual/Individual3.py","file_name":"Individual3.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74433007579","text":"#!/usr/bin/python3\n\nimport argparse\nfrom desidulate.sidinfo import sidinfo\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('sidfile', nargs='+')\n args = parser.parse_args()\n\n for f in args.sidfile:\n print(sidinfo(f))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"anarkiwi/desidulate","sub_path":"desidulate/getsidinfo.py","file_name":"getsidinfo.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"69"} +{"seq_id":"42434854065","text":"import pandas as pd\n\nfrom helpers.utils import save_output_to_csv\nfrom .runner_base import RunnerBase\nfrom scrapers.transfermarkt_general_team import *\n\n\nclass TransfermarktClubs(RunnerBase):\n URL_BASE = 'https://www.transfermarkt.com'\n\n def collect_data_season_league(self, page_content, season, country):\n teams, links = teams_list(page_content)\n age = teams_age(page_content)\n a_players = abroad_players(page_content)\n value, difference = team_market_value(page_content)\n return pd.DataFrame.from_dict(dict(Country=country, Year=season, Team=teams, Link=links, Value=value,\n Difference=difference, Age=age, AbroadPlayers=a_players))\n\n def keep_top_tier_teams(self, teams_per_season_league, minimum_number_of_seasons):\n top_tier_teams = list(teams_per_season_league.groupby(['Team']).count()[\n teams_per_season_league.groupby(\n ['Team']).count() == minimum_number_of_seasons].dropna().index)\n return teams_per_season_league[teams_per_season_league['Team'].isin(top_tier_teams)].reset_index(drop=True)\n\n def collect_teams(self):\n similar_leagues_top_tier_links = self.similar_leagues_top_tier_links()\n\n teams_per_season_league = []\n for row in similar_leagues_top_tier_links.itertuples():\n for season in range(self.SEASON_START, self.SEASON_END):\n page_content = self.scrape_page(self.URL_BASE + row.Link + '/plus/?saison_id=', str(season))\n teams_per_season_league.append(self.collect_data_season_league(page_content, season, row.Country))\n\n return pd.concat(teams_per_season_league).reset_index(drop=True)\n\n def get_id_from_link(self, teams):\n teams[\"TransfermarktId\"] = teams[\"Link\"].str.split(expand=True, pat='/')[4]\n\n def run(self):\n teams = self.keep_top_tier_teams(teams_per_season_league=self.collect_teams(),\n minimum_number_of_seasons=self.MINIMUM_SEASON)\n self.get_id_from_link(teams)\n save_output_to_csv(output=teams, filename=\"teams_general\")\n","repo_name":"marcinpawelkot/mgr","sub_path":"scraping_runners/transfermarkt_clubs_runner.py","file_name":"transfermarkt_clubs_runner.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12039809690","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 21 20:20:31 2018\n\n@author: Mohammad Wasil Saleem\n\"\"\"\n\nimport numpy as np\nfrom scipy.io import loadmat\n\nimport displayData as dd\n\ndef Sigmoid(x):\n # for large positive value, sigmoid will be close to 1.\n # for large negative value, sigmoid will be close to 0. \n g = ( 1 / (1 + np.exp(-x))) \n return g\n\ndef Predict(theta1, theta2, X):\n [m,n] = X.shape\n a1 = np.hstack((np.ones((m,1)), X))\n z2 = Sigmoid(a1.dot(theta1.T))\n a2 = np.hstack((np.ones((m,1)), z2))\n z3 = Sigmoid(a2.dot(theta2.T))\n prediction = 1 + np.argmax(z3, axis=1)\n return prediction\n\n\n# Since the images are of size 20X20, this gives us 400 input layer\n# units (excluding the extra bias unit which always outputs +1).\n# You have been provided with a set of network parameters (theta(1);theta(2)) already trained.\n# The parameters have dimensions that are sized for a neural network with 25 units \n# in the second layer and 10 output units (corresponding to the 10 digit classes).\n\n# load the data mat.\nprint('Loading and Visualizing Data ...')\ndata = loadmat('D:\\ML\\ML\\CSR ML\\WEEK#4\\Machine Learning Assignment#3\\Python\\ex3data1.mat')\nX = data['X'] # size 5000X400\ny = data['y'].flatten() # size 5000\nm = len(y)\n\n#Randomly select 100 data points to display\nrand_indices = np.random.permutation(m)\nsel = X[rand_indices[0:100], :] # Size of sel = (100, 400)\n\ndd.displayData(sel)\n\nweight = loadmat('D:\\ML\\ML\\CSR ML\\WEEK#4\\Machine Learning Assignment#3\\Python\\ex3weights.mat')\ntheta1 = np.zeros((25,401))\ntheta2 = np.zeros((10,26))\ntheta1 = weight['Theta1'] # 25X401 size, where 25=hidden layers, and 400+1 = input layers + bias\ntheta2 = weight['Theta2'] # 10X26 size, where 10= output layers, and 25+1 = hidden layers + bias\n\nnum_labels = len(theta2)\n\n# You need to return the following variables correctly \np = np.zeros((len(X), 1));\npredict = Predict(theta1, theta2, X)\naccuracy = np.mean(predict == y) * 100\nprint('Training set accuracy', accuracy)\n\nrp = np.random.permutation(m)\n\nfor i in range(m):\n inputs = input('Paused - press enter to continue, q to exit: ')\n if inputs == 'q':\n break\n else :#if inputs == 'w':\n test = X[rp[i], :].reshape(1,-1)\n print(test.shape)\n dd.displayData(test)\n pred = Predict(theta1, theta2, test)\n print('Neural Network Prediction: ', pred[0] )\n print('Digit: ', (pred[0] % 10) )\n \n","repo_name":"MohammadWasil/Coursera-Machine-Learning-Python","sub_path":"CSR ML/WEEK#4/Machine Learning Assignment#3/Python/ex3_nn.py","file_name":"ex3_nn.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17562581445","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \n if head == None:\n return head\n \n first = head\n second = None\n if head.next:\n second = head.next \n \n if second == None:\n return head\n \n while first.next.next and second.next.next:\n first.val, second.val = second.val, first.val \n first = first.next.next \n second = second.next.next\n \n first.val, second.val = second.val, first.val\n \n return head\n ","repo_name":"python-algorithm-study-and-learning/Sangjun","sub_path":"ch08/08-17.py","file_name":"08-17.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"24791803115","text":"from Camera import read_camera_data\nfrom flask import Flask\nfrom flask_cors import CORS\nimport json\n\napp = Flask(__name__)\nCORS(app)\n\nif __name__ == '__main__':\n app.run()\n\n@app.route('/api/', methods=['GET'])\ndef index():\n return 'Cameras API'\n\n@app.route('/api/cameras', methods=['GET'])\ndef cameras():\n camera_dicts = [camera.__dict__ for camera in read_camera_data()]\n return json.dumps(camera_dicts)","repo_name":"suzaninfi/everybody-codes","sub_path":"backend/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"28461500892","text":"import os\nimport discord\nimport csv\n\nfrom dotenv import load_dotenv\n\nassociation_file_name = \"associations.csv\"\n\nload_dotenv()\nTOKEN = os.getenv(\"DISCORD_TOKEN\")\nGUILD = os.getenv(\"DISCORD_GUILD\")\n\nintents = discord.Intents.default()\nintents.messages = True\nintents.message_content = True\nclient = discord.Client(intents=intents)\n\nf = open(association_file_name, \"a+\")\nf.close()\n\n'''\nTODO:\nReduce the number of reads to the association_file_name\nIncrease the specificity of bot messages to the channel\nResolve errors caused when invalid emojis are input (input validation)\n'''\n\ndef get_associations():\n associations = {}\n with open(association_file_name, \"r\", encoding=\"utf-8\") as f:\n reader = csv.reader(f)\n for row in reader:\n if len(row) > 1:\n associations[row[0]] = row[1:]\n return associations\n\ndef add_association(word, emoji):\n associations = get_associations()\n if word in associations.keys():\n associations[word].append(emoji)\n else:\n associations[word] = [emoji]\n write_associations_to_file(associations)\n\ndef write_associations_to_file(associations):\n with open(association_file_name, \"w\", encoding=\"utf-8\") as f:\n writer = csv.writer(f)\n for word,emojis in associations.items():\n writer.writerow([word,*emojis])\n\ndef remove_association(word, emoji=None):\n if emoji == None:\n associations = get_associations()\n associations.pop(word, None)\n write_associations_to_file(associations)\n else:\n associations = get_associations()\n if word in associations.keys() and emoji in associations[word]:\n associations[word] = [curr_emoji for curr_emoji in associations[word] if curr_emoji != emoji]\n if len(associations[word]) == 0:\n associations.pop(word)\n write_associations_to_file(associations)\n\nassociations = get_associations()\n\n@client.event\nasync def on_ready():\n print(\"Initializing HeckBot..\")\n for guild in client.guilds:\n print(f\"{client.user} has connected to the following guild: {guild.name}(id: {guild.id})\")\n channel = guild.get_channel(744611387371683962)\n await channel.send('hello, i am online')\n\n@client.event\nasync def on_message(message):\n global associations\n text = message.content.lower()\n\n if text[:10] == \"!associate\":\n args = text.split(\" \")\n if len(args) != 3:\n await message.channel.send(\"Incorrect syntax, try \\\"`!associate `\\\"\")\n else:\n word = args[1].lower()\n emoji = args[2]\n add_association(word, emoji)\n associations = get_associations()\n await message.channel.send(f\"Successfully associated the keyword \\\"{word}\\\" with the reaction \\\"{emoji}\\\"!\")\n\n if text[:11] == \"!dissociate\":\n args = text.split(\" \")\n if len(args) == 2:\n word = args[1].lower()\n remove_association(word)\n associations = get_associations()\n await message.channel.send(f\"Successfully dissociated the keyword \\\"{word}\\\" from all reactions!\")\n elif len(args) == 3:\n word = args[1].lower()\n emoji = args[2]\n remove_association(word, emoji)\n associations = get_associations()\n await message.channel.send(f\"Successfully dissociated the keyword \\\"{word}\\\" with the reaction \\\"{emoji}\\\"!\")\n else:\n await message.channel.send(\"Incorrect syntax, try \\\"`!dissociate `\\\"\")\n\n if text[:13] == \"!disassociate\":\n await message.channel.send(\"The command is \\\"`!dissociate`\\\", y'know 😉\")\n\n for word,emojis in associations.items():\n if word in text:\n for emoji in emojis:\n await message.add_reaction(emoji)\n\n\n\nclient.run(TOKEN)","repo_name":"ChristiandWilliams/heckbot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"2114468121","text":"from django.urls import path\n\nfrom blog.views import CreateCommentView, CreatePostView, DeletePostView, IndexView, ShowPostView, UpdatePostView\n\n\nurlpatterns = [\n path(\"\", IndexView.as_view()),\n path(\"create_post\", CreatePostView.as_view()),\n path(\"post/\", ShowPostView.as_view()),\n path(\"update_post/\", UpdatePostView.as_view()),\n path(\"delete_post/\", DeletePostView.as_view()),\n path(\"create_comment/\", CreateCommentView.as_view()),\n]\n","repo_name":"mimmasoumi/django_blog_rest_api","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"27140030460","text":"# make sure all the triggers to this function are active\n\nimport json\nimport boto3\nimport datetime\nimport os\nimport urllib3\n\nslackWebhookUrl = os.environ['webHookUrlSlack']\n\ndef lambda_handler(event, context):\n currentBH = event['instanceIdLambda2']\n client = boto3.client(\"ec2\")\n status = client.describe_instances(InstanceIds=[currentBH])\n for i in status[\"Reservations\"]:\n instanceDetails = i['Instances'][0]\n stateCurrent = instanceDetails[\"State\"][\"Name\"].lower()\n launchTime = instanceDetails[\"LaunchTime\"]\n currentTime = datetime.datetime.now(launchTime.tzinfo)\n currentDate = currentTime.date()\n if instanceDetails[\"State\"][\"Name\"].lower() == \"running\":\n differenceTime = currentTime - launchTime\n differenceTimeSeconds = differenceTime.total_seconds()\n differenceTimeMinutes = differenceTimeSeconds/60\n differenceTimeHours = differenceTimeMinutes/60\n differenceTimeDays = differenceTimeHours/24\n bhLink = \"https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#InstanceDetails:instanceId=\"+instanceDetails[\"InstanceId\"] # change the region if required\n \n # to trigger the alert when the total running time > 2 days\n if differenceTimeDays > 1.9:\n print(\"The bastion instance has been left running for more than 2 days\")\n slackPayload = payload = {\n \"username\" : \"Bastion Host Monitoring\",\n \"text\": \"*:alert-light: The bastion host has been left running for more than 2 days*\",\n \"attachments\": [\n {\"fields\": [{\"title\": \"Account Name\",\"value\": \"\", \"short\": True},\n {\"title\": \"Total Running Time (Hours)\",\"value\": round(differenceTimeHours,2), \"short\": True},\n {\"title\": \"Bastion Instance ID\",\"value\": instanceDetails[\"InstanceId\"], \"short\": True},\n {\"title\": \"Date (UTC)\",\"value\": str(currentDate), \"short\": True},\n {\"title\": \"Bastion Instance Link\", \"value\": bhLink,\"short\": False}],\n \"color\": \"#FF0000\"}]}\n sendSlackAlert(json.dumps(slackPayload))\n else:\n print(\"Bastion host is not running\")\n\ndef sendSlackAlert(slackPayload):\n headers = {'Content-type': \"application/json\"}\n http = urllib3.PoolManager()\n response = http.request('POST', slackWebhookUrl, headers={'Content-Type': 'application/json'}, body=slackPayload)\n print(\"Slack alert sent successfully\")\n","repo_name":"5h4d0wr007/Monitor-Bastion-Hosts","sub_path":"lambda2.py","file_name":"lambda2.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13976617538","text":"from torch.multiprocessing import set_start_method\nfrom fiber_guard.pipeline import AnalyzingPipeline\nimport sys\nfrom fiber_guard.data_gen import ReadFile\n\n\ndef main() -> int:\n set_start_method(\"spawn\")\n data_gen = ReadFile(overlap=0.5, window=1024, engine=\"torch\")\n\n pipeline = AnalyzingPipeline(data_gen=data_gen)\n try:\n\n pipeline.init_eval_pipeline()\n pipeline.execute_pipeline()\n except Exception as e:\n raise e\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"tearexJS/minimal_fiberguard","sub_path":"fiber_guard/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"33057976657","text":"from __future__ import division\nimport numpy as np\nimport random\nimport cv2\n\n_data_rng = np.random.RandomState(None)\ndef np_random_color_distort(image, data_rng=None, eig_val=None,\n eig_vec=None, var=0.4, alphastd=0.1):\n \"\"\"Numpy version of random color jitter.\n Parameters\n ----------\n image : numpy.ndarray\n original image.\n data_rng : numpy.random.rng\n Numpy random number generator.\n eig_val : numpy.ndarray\n Eigen values.\n eig_vec : numpy.ndarray\n Eigen vectors.\n var : float\n Variance for the color jitters.\n alphastd : type\n Jitter for the brightness.\n Returns\n -------\n numpy.ndarray\n The jittered image\n \"\"\"\n # from ....utils.filesystem import try_import_cv2\n # cv2 = try_import_cv2()\n\n if data_rng is None:\n data_rng = _data_rng\n if eig_val is None:\n eig_val = np.array([0.2141788, 0.01817699, 0.00341571],\n dtype=np.float32)\n if eig_vec is None:\n eig_vec = np.array([[-0.58752847, -0.69563484, 0.41340352],\n [-0.5832747, 0.00994535, -0.81221408],\n [-0.56089297, 0.71832671, 0.41158938]], dtype=np.float32)\n def grayscale(image):\n return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n def lighting_(data_rng, image, alphastd, eigval, eigvec):\n alpha = data_rng.normal(scale=alphastd, size=(3, ))\n image = image.astype(np.float32) + np.dot(eigvec, eigval * alpha)\n\n image = image.astype(np.uint8)\n return image\n def blend_(alpha, image1, image2):\n\n image1 = image1.astype(np.float32)*alpha\n image2 = image2.astype(np.float32)*(1 - alpha)\n image1 += image2\n image1 = image1.astype(np.uint8)\n return image1\n def saturation_(data_rng, image, gs, gs_mean, var):\n # pylint: disable=unused-argument\n alpha = 1. + data_rng.uniform(low=-var, high=var)\n return blend_(alpha, image, gs[:, :, None])\n\n def brightness_(data_rng, image, gs, gs_mean, var):\n # pylint: disable=unused-argument\n alpha = 1. + data_rng.uniform(low=-var, high=var)\n # print(alpha)\n # image *= alpha\n image = image.astype(np.float32)*alpha\n image = image.astype(np.uint8)\n return image\n def contrast_(data_rng, image, gs, gs_mean, var):\n # pylint: disable=unused-argument\n alpha = 1. + data_rng.uniform(low=-var, high=var)\n return blend_(alpha, image, gs_mean)\n\n functions = [brightness_, contrast_, saturation_]\n random.shuffle(functions)\n\n gs = grayscale(image)\n gs_mean = gs.mean()\n for f in functions:\n image = f(data_rng, image, gs, gs_mean, var)\n image = lighting_(data_rng, image, alphastd, eig_val, eig_vec)\n # print(data_rng)\n return image","repo_name":"wangermeng2021/Scaled-YOLOv4-tensorflow2","sub_path":"utils/image_gluoncv.py","file_name":"image_gluoncv.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"67"} +{"seq_id":"43967720818","text":"\"\"\"\nSistema de perguntas e respostas com dicionário em Python\n\n\"\"\"\n\nperguntas = {\n 'Pergunta_1' : {\n 'Pergunta' : 'Quanto é 4 * 2?',\n 'Alternativas' : {\n 'a' : 4,\n 'b' : 8,\n 'c' : 5,\n 'd' : 2,\n 'e' : 9,\n },\n 'Resposta' : 'b',\n },\n 'Pergunta_2' : {\n 'Pergunta' : 'Quanto é 4 + 2?',\n 'Alternativas' : {\n 'a' : 7,\n 'b' : 35,\n 'c' : 42,\n 'd' : 6,\n 'e' : 11,\n },\n 'Resposta' : 'd',\n },\n 'Pergunta_3' : {\n 'Pergunta' : 'Quanto é 8 * 2:',\n 'Alternativas' : {\n 'a' : 46,\n 'b' : 10,\n 'c' : 20,\n 'd' : 18,\n 'e' : 16,\n },\n 'Resposta' : 'e',\n },\n 'Pergunta_4' : {\n 'Pergunta': \"Quanto é 10 / 2 : \",\n 'Alternativas' : {\n 'a' : 10,\n 'b' : 5,\n 'c' : 7,\n 'd' : 4,\n 'e' : 17,\n },\n 'Resposta' : 'b',\n },\n 'Pergunta_5' : {\n 'Pergunta' : 'Quanto é 100 - 50?',\n 'Alternativas' : {\n 'a' : 50,\n 'b' : 45,\n 'c' : 60,\n 'd' : 56,\n 'e' : 100,\n },\n 'Resposta' : 'a',\n }\n\n}\nrespostas_corretas = 0\n\nfor chave_perg, chave_itens in perguntas.items():\n print(f\"\\n{chave_perg} : {chave_itens['Pergunta']}\")\n print('Escolha uma das opções abaixo:')\n for alternativas, opcoes in chave_itens['Alternativas'].items():\n print(f\"{alternativas} : {opcoes}\")\n escolhida = input('Qual é a sua resposta ? R:').lower()\n if len(escolhida) > 1 or len(escolhida) == 0:\n print('Escreva uma opção válida')\n continue\n if escolhida == chave_itens['Resposta']:\n print('Você acertou a questão!!! Parabéns!')\n respostas_corretas += 1\n else:\n print('Você errou a questão!')\n\nprint(f'\\nVocê acertou {respostas_corretas} questões!!')\n","repo_name":"Bindeli/cursopython","sub_path":"revisandointermediario/exerciciodicionario.py","file_name":"exerciciodicionario.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"15225597985","text":"from ewb_mappy.validation import validate\n\nimport re\nimport pandas as pd\nimport os\n\nCSV_EXTENSION = 'csv'\nEXCEL_EXTENSION = 'xls'\n\n\n\nclass Map():\n \"\"\"\n Object to reprent map\n Attributes: \n - df: Dataframe with data\n \"\"\"\n\n def __init__(self):\n df = None\n\n\n\ndef determine_extension(filename: str) -> str:\n \"\"\"\n Returns type of extension constant associated with a Filename.\n If Extension is not supperted IOError is raised.\n \"\"\"\n name_pattern = r'.*'\n excel_reg = re.compile(name_pattern + r'.(xls|xlsx|xlsm|xlsb|xls)$')\n csv_reg = re.compile(name_pattern + r'.csv$')\n extension = None\n \n if excel_reg.match(filename):\n extension = EXCEL_EXTENSION\n elif csv_reg.match(filename):\n extension = CSV_EXTENSION\n else:\n error_msg = \"File extension or name of \" + filename\n error_msg += \" not supported. Use csv or excel documents\"\n raise IOError(error_msg)\n \n return extension\n\n \ndef get_dataframe(filename: str) -> pd.DataFrame:\n \"\"\"\n Returns a dataframe from an excel or csv file\n \"\"\"\n \n extension = determine_extension(filename)\n df = None\n if extension == EXCEL_EXTENSION:\n df = pd.read_excel(filename)\n elif extension == CSV_EXTENSION:\n df = pd.read_csv(filename)\n\n return df\n\n\ndef get_map(files: list) -> EWBMap:\n \"\"\"\"\n Returns a map object with layers as specified in files\n \"\"\"\n \n map_object = EWBMap()\n for f in files:\n layer = getlayer(f)\n map_object.layers.append(layer)\n map_object.layerNames.append(layer.name)\n map_object.makeMapfromLayers()\n map_object.recenter()\n return map_object\n \n\ndef get_layers(filename: str) -> EWBLayer:\n \"\"\"\n Function that returns an EWBLayer from filename. \n Extensions can be csv or can be excel. \n Color of the layer must be specified in the file\n \"\"\"\n\n #TODO find a better way to deal with colors\n layer_df = get_dataframe(filename)\n color = 'lightgray'\n layername = os.path.splitext(filename)[0]\n layer_object = EWB(layername, color, layerdf)\n for row in layer_df.itertuples():\n tmpRow = list(row)\n #TODO remember to change this \n layer_object.make_popups(lat=tmpRow[1],\n lon=tmpRow[2],\n title=tmpRow[3],\n date=tmpRow[4],\n description=tmpRow[5],\n icon=tmpRow[6])\n \n\n\n\n \n \n","repo_name":"EWB-Ghana/EWB-visualization","sub_path":"ewb_mappy/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42475491746","text":"# coding=utf-8\nfrom collective.documentgenerator.search_replace.pod_template import SearchAndReplacePODTemplates\nfrom collective.documentgenerator.testing import PODTemplateIntegrationTest\nfrom collective.documentgenerator.utils import compute_md5\nfrom plone.testing._z2_testbrowser import Browser\nfrom zExceptions import Unauthorized\nfrom zope.interface import Invalid\n\nimport io\nimport os\nimport zipfile\n\n\nclass TestSearchReplaceTemplate(PODTemplateIntegrationTest):\n \"\"\"\n Test search and replace feature\n \"\"\"\n\n def setUp(self):\n super(TestSearchReplaceTemplate, self).setUp()\n self.template1 = self.portal.podtemplates.test_template\n self.template2 = self.portal.podtemplates.test_template_bis\n self.ods_template = self.portal.podtemplates.test_ods_template\n\n def test_podtemplate_is_searchable(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n results = search_replace.search(\"view\")\n\n self.assertGreater(len(results.keys()), 0)\n\n def test_search_dont_alter_podtemplate(self):\n template1_md5 = compute_md5(self.template1.odt_file.data)\n template2_md5 = compute_md5(self.template2.odt_file.data)\n\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n search_replace.search(\"view\")\n\n self.assertEqual(compute_md5(self.template1.odt_file.data), template1_md5)\n self.assertEqual(compute_md5(self.template2.odt_file.data), template2_md5)\n\n def test_can_search_regex(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n # We want only the `view` before the `get_localized_field_name` method\n results = search_replace.search(\"view(?=.get_localized_field_name)\", is_regex=True)\n\n template1_results = results[self.template1.UID()]\n self.assertEqual(len(template1_results), 1)\n self.assertIn(\"view.get_localized_field_name\", template1_results[0].content)\n\n self.assertNotIn(self.template2.UID(), results.keys()) # Nothing in template2\n\n def test_can_search_string(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n results = search_replace.search(\"Author\")\n\n self.assertNotIn(self.template1.UID(), results.keys())\n template2_results = results[self.template2.UID()]\n self.assertEqual(len(template2_results), 1)\n\n self.assertIn(\"Author\", template2_results[0].content)\n\n def test_can_search_in_ods(self):\n with SearchAndReplacePODTemplates((self.ods_template,)) as search_replace:\n not_found_results = search_replace.search(\"Nowhere to be found\")\n brain_results = search_replace.search(\"brain\")\n regex_results = search_replace.search(\"view\\\\..*\\\\.results\\\\(\\\\)\", is_regex=True)\n # At the regex start, '^' was failing before\n regex_start_results = search_replace.search(\"^do row\", is_regex=True)\n\n self.assertNotIn(self.ods_template.UID(), not_found_results.keys())\n self.assertIn(self.ods_template.UID(), regex_start_results.keys())\n ods_brain_results = brain_results[self.ods_template.UID()]\n ods_regex_results = regex_results[self.ods_template.UID()]\n\n self.assertEqual(len(ods_brain_results), 4)\n self.assertEqual(len(ods_regex_results), 1)\n for result in ods_brain_results:\n self.assertIn(\"brain\", result.content)\n\n self.assertIn(\"view.real_context.results()\", ods_regex_results[0].content)\n\n def test_can_search_in_headers_and_footers(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n header_results = search_replace.search(\"context.title.upper()\")\n footer_results = search_replace.search(\"^view.display_date\", is_regex=True)\n\n self.assertNotIn(self.template1.UID(), header_results.keys())\n self.assertNotIn(self.template1.UID(), footer_results.keys())\n\n self.assertEqual(len(header_results[self.template2.UID()]), 1)\n self.assertIn(\"context.title.upper()\", header_results[self.template2.UID()][0].content)\n\n self.assertEqual(len(footer_results[self.template2.UID()]), 1)\n self.assertIn(\"view.display_date\", footer_results[self.template2.UID()][0].content)\n\n def test_can_search_multiple_times(self):\n with SearchAndReplacePODTemplates((self.template1,)) as search_replace:\n not_found_results = search_replace.search(\"Nowhere to be found\")\n view_results = search_replace.search(\"view\")\n regex_results = search_replace.search(\n \"view(?=.get_localized_field_name)\", is_regex=True\n )\n\n template1_uid = self.template1.UID()\n\n self.assertNotEqual(not_found_results, view_results)\n self.assertNotEqual(view_results, regex_results)\n\n self.assertNotIn(template1_uid, not_found_results)\n\n for result in view_results[template1_uid]:\n self.assertIn(\"view\", result.content)\n\n self.assertEqual(len(regex_results[template1_uid]), 1)\n self.assertIn(\"view.get_localized_field_name\", regex_results[template1_uid][0].content)\n\n def test_search_clean_after_itself(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n tmp_dir = search_replace.tmp_dir\n search_replace.search(\"view\")\n\n self.assertFalse(os.path.exists(tmp_dir))\n\n # Test if it clean after itself after an exception is raised\n try:\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n tmp_dir = search_replace.tmp_dir\n search_replace.search(\"view\")\n raise OSError\n except OSError:\n pass\n\n self.assertFalse(os.path.exists(tmp_dir))\n\n def test_can_replace_in_podtemplate(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n results = search_replace.replace(\"view\", \"View\")\n\n self.assertGreater(len(results), 0)\n\n def test_replace_change_podtemplate_file(self):\n template1_md5 = compute_md5(self.template1.odt_file.data)\n template2_md5 = compute_md5(self.template2.odt_file.data)\n\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n search_replace.replace(\"view\", \"View\")\n\n self.assertNotEquals(compute_md5(self.template1.odt_file.data), template1_md5)\n self.assertNotEquals(compute_md5(self.template2.odt_file.data), template2_md5)\n\n def test_replace_dont_alter_pod_template_odt_file_structure(self):\n with SearchAndReplacePODTemplates((self.template1,)) as search_replace:\n search_replace.replace(\"view\", \"View\")\n\n zip_bytes = io.BytesIO(self.template1.odt_file.data)\n zip_file = zipfile.ZipFile(zip_bytes)\n odt_subfiles = zip_file.namelist()\n\n expected_files = [\n u\"mimetype\",\n u\"content.xml\",\n u\"styles.xml\",\n u\"meta.xml\",\n u\"settings.xml\",\n u\"manifest.rdf\",\n u\"META-INF/manifest.xml\",\n ]\n\n for expected_file in expected_files:\n self.assertIn(expected_file, odt_subfiles)\n\n def test_replace_dont_change_podtemplate_file_size_too_much(self):\n before_template1_filesize = self.template1.odt_file.getSize()\n before_template2_filesize = self.template2.odt_file.getSize()\n\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n search_replace.replace(\"view\", \"View\")\n\n self.assertAlmostEqual(before_template1_filesize, self.template1.odt_file.getSize(), delta=1000)\n self.assertAlmostEqual(before_template2_filesize, self.template2.odt_file.getSize(), delta=1000)\n\n def test_can_replace_string(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n results = search_replace.replace(\"Author\", \"Writer\")\n\n self.assertNotIn(self.template1.UID(), results.keys())\n template2_results = results[self.template2.UID()]\n self.assertEqual(len(template2_results), 1)\n\n self.assertEqual(\"Author\", template2_results[0].keyword)\n self.assertIn(\"Author\", template2_results[0].content)\n self.assertNotIn(\"Author\", template2_results[0].patched)\n self.assertIn(\"Writer\", template2_results[0].patched)\n\n # Verification with search\n with SearchAndReplacePODTemplates((self.template2,)) as search_replace:\n writer_search = search_replace.search(\"Writer\")\n author_search = search_replace.search(\"Author\")\n\n template2_writer_search = writer_search[self.template2.UID()]\n self.assertGreater(len(template2_writer_search), 0)\n\n self.assertNotIn(self.template2.UID(), author_search.keys())\n\n def test_can_replace_regex(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n # We want only the `view` before the `get_localized_field_name` method\n results = search_replace.replace(\n \"view(?=.get_localized_field_name)\", \"NewView\", is_regex=True\n )\n\n template1_results = results[self.template1.UID()]\n self.assertEqual(len(template1_results), 1)\n self.assertNotIn(self.template2.UID(), results.keys()) # Nothing in template2\n\n self.assertIn(\"view.get_localized_field_name\", template1_results[0].content)\n self.assertIn(\"NewView.get_localized_field_name\", template1_results[0].patched)\n\n # Verification with search\n with SearchAndReplacePODTemplates((self.template1,)) as search_replace:\n results = search_replace.search(\"NewView\")\n\n result = results[self.template1.UID()]\n self.assertEqual(\"NewView\", result[0].keyword)\n\n def test_can_replace_multiple_times(self):\n with SearchAndReplacePODTemplates((self.template2,)) as search_replace:\n search_replace.replace(\"Author\", \"Writer\")\n search_replace.replace(\"Writer\", \"Écrivain\")\n results = search_replace.replace(\"Écrivain\", \"Schrijver\")\n\n template2_results = results[self.template2.UID()]\n self.assertEqual(len(template2_results), 1)\n self.assertIn(\"Schrijver\", template2_results[0].patched)\n self.assertNotIn(\"Author\", template2_results[0].patched)\n\n # Verification with search\n with SearchAndReplacePODTemplates((self.template2,)) as search_replace:\n results = search_replace.search(\"Schrijver\")\n\n template2_results = results[self.template2.UID()]\n self.assertEqual(len(template2_results), 1)\n self.assertEqual(\"Schrijver\", template2_results[0].keyword)\n self.assertIn(\"Schrijver\", template2_results[0].content)\n\n def test_replace_clean_after_itself(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n tmp_dir = search_replace.tmp_dir\n search_replace.replace(\"View\", \"view\")\n\n self.assertFalse(os.path.exists(tmp_dir))\n # Test if it clean after itself after an exception is raised\n try:\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n tmp_dir = search_replace.tmp_dir\n search_replace.replace(\"View\", \"view\")\n raise OSError\n except OSError:\n pass\n\n self.assertFalse(os.path.exists(tmp_dir))\n\n def test_can_replace_in_ods(self):\n with SearchAndReplacePODTemplates((self.ods_template,)) as search_replace:\n brain_results = search_replace.replace(\"brain\", \"cell\")\n not_found_results = search_replace.replace(\"Nowhere to be found\", \"xxx\")\n regex_results = search_replace.replace(\n \"view\\\\..*\\\\.results\\\\(\\\\)\", \"regex are evil\", is_regex=True\n )\n # At the regex start, '^' was failing before\n regex_start_results = search_replace.replace(\"^do row\", \"do this\", is_regex=True)\n\n self.assertNotIn(self.ods_template.UID(), not_found_results.keys())\n self.assertIn(self.ods_template.UID(), regex_start_results.keys())\n ods_brain_results = brain_results[self.ods_template.UID()]\n ods_regex_results = regex_results[self.ods_template.UID()]\n\n self.assertIn(\"brain\", ods_brain_results[0].content)\n self.assertNotIn(\"brain\", ods_brain_results[0].patched)\n self.assertIn(\"cell\", ods_brain_results[0].patched)\n\n self.assertIn(\"view.real_context.results()\", ods_regex_results[0].content)\n self.assertIn(\"regex are evil\", ods_regex_results[0].patched)\n\n # Verification with search\n with SearchAndReplacePODTemplates((self.ods_template,)) as search_replace:\n cell_search = search_replace.search(\"cell\")\n regex_search = search_replace.search(\"regex are evil\")\n\n self.assertIn(self.ods_template.UID(), cell_search.keys())\n self.assertIn(self.ods_template.UID(), regex_search.keys())\n\n self.assertIn(\"cell\", cell_search[self.ods_template.UID()][0].content)\n self.assertIn(\"regex are evil\", regex_search[self.ods_template.UID()][0].content)\n\n def test_replace_can_replace_in_headers_and_footers(self):\n with SearchAndReplacePODTemplates((self.template1, self.template2)) as search_replace:\n header_results = search_replace.replace(\n \"context.title.upper()\", \"context.title.lower()\"\n )\n footer_results = search_replace.replace(\n \"^view.display_date\", \"view.new_method\", is_regex=True\n )\n\n self.assertNotIn(self.template1.UID(), header_results.keys())\n self.assertNotIn(self.template1.UID(), footer_results.keys())\n\n self.assertIn(\"context.title.lower()\", header_results[self.template2.UID()][0].patched)\n self.assertIn(\"view.new_method(\", footer_results[self.template2.UID()][0].patched)\n\n # Verification with search\n with SearchAndReplacePODTemplates((self.template2,)) as search_replace:\n header_results = search_replace.search(\"context.title.lower()\")\n footer_results = search_replace.search(\"view.new_method(\")\n\n self.assertGreater(len(header_results), 0)\n self.assertEqual(\"context.title.lower()\", header_results[self.template2.UID()][0].keyword)\n\n self.assertGreater(len(footer_results), 0)\n self.assertEqual(\"view.new_method(\", footer_results[self.template2.UID()][0].keyword)\n\n def test_podtemplate_is_still_functional_after_search_replace(self):\n with SearchAndReplacePODTemplates((self.template2,)) as search_replace:\n search_replace.replace(\"context.description\", \"context.title\")\n search_replace.search(\"context.description\")\n\n template_uid = self.template2.UID()\n view = self.portal.podtemplates.restrictedTraverse(\"@@document-generation\")\n self.assertIn(\"pdf\", self.template2.get_available_formats())\n generated_doc = view(template_uid, \"pdf\")\n self.assertEqual(\"%PDF\", generated_doc[:4])\n\n def test_search_replace_control_panel_anonymous_unauthorized(self):\n app = self.layer[\"app\"]\n browser = Browser(app)\n browser.handleErrors = False\n with self.assertRaises(Unauthorized): # Anonymous cannot access this page\n browser.open(\n \"{}/@@collective.documentgenerator-searchreplacepanel\".format(\n self.portal.absolute_url()\n )\n )\n\n def test_search_replace_control_panel_doesnt_fail(self):\n # self.browser is logged in as admin\n self.browser.handleErrors = False\n self.browser.open(\n \"{}/@@collective.documentgenerator-searchreplacepanel\".format(\n self.portal.absolute_url()\n )\n )\n\n def test_search_replace_control_panel_can_preview(self):\n view = self.portal.restrictedTraverse(\"@@collective.documentgenerator-searchreplacepanel\")\n selected_templates_mock = [self.template1.UID(), self.template2.UID()]\n replacements_mock = [\n {\n \"search_expr\": \"^view.display_date\",\n \"replace_expr\": \"view.display_new_date\",\n \"is_regex\": True,\n },\n {\"search_expr\": \"Author\", \"replace_expr\": \"Writer\", \"is_regex\": False},\n ]\n form_data = {\n \"selected_templates\": selected_templates_mock,\n \"replacements\": replacements_mock,\n }\n\n view.form_instance.perform_preview(form_data)\n view()\n\n def test_search_replace_control_panel_can_replace(self):\n view = self.portal.restrictedTraverse(\"@@collective.documentgenerator-searchreplacepanel\")\n selected_templates_mock = [self.template1.UID(), self.template2.UID()]\n replacements_mock = [\n {\n \"search_expr\": \"^view.display_date\",\n \"replace_expr\": \"view.display_new_date\",\n \"is_regex\": True,\n },\n {\"search_expr\": \"Author\", \"replace_expr\": \"Writer\", \"is_regex\": False},\n ]\n form_data = {\n \"selected_templates\": selected_templates_mock,\n \"replacements\": replacements_mock,\n }\n\n view.form_instance.perform_replacements(form_data)\n view()\n\n def test_search_replace_control_panel_regex_validator(self):\n view = self.portal.restrictedTraverse(\"@@collective.documentgenerator-searchreplacepanel\")\n form = view.form_instance\n form.update()\n selected_templates = [self.template1.UID(), self.template2.UID()]\n replacements = [\n {\"search_expr\": \"get_elements(\", \"replace_expr\": \"\", \"is_regex\": False},\n {\"search_expr\": \"get_elements(\", \"replace_expr\": \"\", \"is_regex\": True},\n ]\n data = {\"replacements\": replacements, \"selected_templates\": selected_templates}\n errors = form.widgets.validate(data)\n self.assertEqual(len(errors), 1)\n self.assertTrue(isinstance(errors[0], Invalid))\n self.assertEqual(errors[0].message, u'Incorrect regex at row #2 : \"get_elements(\"')\n replacements = [\n {\"search_expr\": \"get_elements(\", \"replace_expr\": \"\", \"is_regex\": False},\n {\"search_expr\": \"valid_regex?\", \"replace_expr\": \"\", \"is_regex\": True},\n ]\n data = {\"replacements\": replacements}\n errors = form.widgets.validate(data)\n self.assertFalse(errors)\n","repo_name":"collective/collective.documentgenerator","sub_path":"src/collective/documentgenerator/tests/test_search_replace.py","file_name":"test_search_replace.py","file_ext":"py","file_size_in_byte":18763,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"67"} +{"seq_id":"74135858133","text":"from django.shortcuts import render\nfrom django.views.generic import View, CreateView, UpdateView, FormView\nfrom django.db.models import Sum\nimport datetime\n\nfrom .models import Transaction\nfrom accounts.models import Account\nfrom .forms import AddTransactionForm, FilterForm\nfrom budget.models import MonthlyBudget\n\n\nclass AccountTransactions(View): #View transactions from a single account\n\n def get_context_data(self, *args, **kwargs):\n transaction_form = AddTransactionForm(prefix='transaction_form')\n filter_form = FilterForm(prefix='filter_form')\n accountobj = Account.objects.get(slug=kwargs['account'])\n today = datetime.datetime.today().strftime('%Y-%m-%d')\n\n thirty_days_ago = datetime.datetime.today() + datetime.timedelta(-30)\n thirty_days_ago = thirty_days_ago.strftime('%Y-%m-%d')\n\n start_date = kwargs['start_date']\n end_date = kwargs['end_date']\n\n if start_date == 0 and end_date == 0:\n transactions = Transaction.objects.filter(account=accountobj, date__range=[thirty_days_ago, today]).order_by('date', 'id')\n total_transactions = Transaction.objects.filter(account=accountobj, date__gte=thirty_days_ago).order_by('date', 'id').reverse()\n else:\n transactions = Transaction.objects.filter(account=accountobj, date__range=[start_date, end_date]).order_by('date', 'id')\n total_transactions = Transaction.objects.filter(account=accountobj, date__gte=start_date).order_by('date', 'id').reverse()\n\n balances = {}\n balance = accountobj.balance\n\n for item in total_transactions:\n balances[item.id] = balance\n if item.debit == True:\n balance = item.amount + balance\n elif item.debit == False:\n balance = balance - item .amount\n\n context = {'transactions': transactions, 'account': accountobj, 'transaction_form': transaction_form, 'filter_form': filter_form, 'balances': balances}\n return context\n\n\n def get(self, request, account):\n start_date = 0\n end_date = 0\n\n return render(request, 'transactions/overview.html', self.get_context_data(request, account=account, start_date=start_date, end_date=end_date))\n\n\n def post(self, request, account):\n action = self.request.POST['action']\n accountobj = Account.objects.get(slug = account)\n start_date =0\n end_date = 0\n\n if (action == 'add_transaction'):\n transaction_form = AddTransactionForm(request.POST, prefix='transaction_form')\n if transaction_form.is_valid():\n transaction_data = {'account': accountobj}\n for key, value in transaction_form.cleaned_data.items():\n ###Handle special fields###\n if key == \"budget\":# If the transaction is applied towards a budget:\n #The transaction will hit the monthly budget for the month the transaction is posted in\n #If you are paying something for next months budget (i.e. paying the mortgage due the 1st)\n #then you need to post-date the transaction to the next month\n if value != None: #If the budget value is not NONE\n date = transaction_form.cleaned_data['date']\n year = date.year\n month = date.month\n #Get the budget for the month and year of the transaction\n budget = MonthlyBudget.objects.filter(budget__slug=value, month__year=year, month__month=month).first()\n if budget:\n transaction_data[key] = budget #pass the instance of the monthly budget\n #Apply the transaction to the monthly budget\n new_budget_actual = budget.actual + transaction_form.cleaned_data['amount']\n budget.actual = new_budget_actual\n budget.save()\n else: #Otherwise show an error notifying the user that no instance of the budget for the given month and year\n month = date.strftime('%B')\n error = \"Error: There is no {} budget for {}. {}. Please add the budget then resubmit the transaction.\".format(value, month, year) #if there is no matching budget set the value to Error\n context = {'transaction_form': transaction_form, 'error': error, 'account': accountobj, 'filter_form': filter_form}\n return render(request, 'transactions\\overview.html', context)\n elif key == \"direction\": #Convert the direction to either True or False for the debit field\n if value == \"O\": #If money is going OUT it is a debit\n transaction_data[\"debit\"] = True\n else: #If money is coming in it is not a debit\n transaction_data[\"debit\"] = False\n ###If there is nothing special with the field just add the key and value to the dictionary###\n else:\n transaction_data[key] = value\n if transaction_form.cleaned_data['direction'] == 'O': #Check the direction of money flow and update the balance of the account\n new_balance = accountobj.balance - transaction_data['amount'] #Money is going out\n else:\n new_balance = accountobj.balance + transaction_data['amount'] #Money coming in\n transaction_data['balance'] = new_balance\n Transaction.objects.create(**transaction_data) # Create the transaction from the dictionary\n accountobj.balance = new_balance\n accountobj.save()\n else:\n error = \"There was an error with the form\"\n context = {'transaction_form': transaction_form, 'error': error, 'account': accountobj,\n 'filter_form': filter_form}\n return render(request, 'transactions\\overview.html', context)\n\n elif (action == 'date_filter'):\n filter_form = FilterForm(request.POST, prefix='filter_form')\n if filter_form.is_valid():\n start_date = filter_form.cleaned_data['start_date']\n end_date = filter_form.cleaned_data['end_date']\n transactions = Transaction.objects.filter(account = accountobj, date__range=[start_date, end_date]).order_by('date')\n else:\n transactions = Transaction.objects.filter(account = accountobj, date__range=[thirty_days_ago, today]).order_by('date')\n\n return render(request, 'transactions/overview.html', self.get_context_data(request, account=account, start_date=start_date, end_date=end_date))","repo_name":"drewblay/Personal-Finance-Django-App","sub_path":"banking/transactions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6981,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"39317248888","text":"#!/usr/bin/python\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nDOCUMENTATION = '''\n---\nmodule: lb_certificate\nshort_description: Manage ELB certificates\nextends_documentation_fragment: opentelekomcloud.cloud.otc\nversion_added: \"0.2.0\"\nauthor: \"Anton Sidelnikov (@anton-sidelnikov)\"\ndescription:\n - Manage ELB certificates.\noptions:\n name:\n description: Certificate name or ID.\n type: str\n required: true\n admin_state_up:\n description: Specifies the administrative status of the certificate.\n type: bool\n description:\n description: Provides supplementary information about the certificate.\n type: str\n type:\n description: Specifies the certificate type.\n choices: [server, client]\n default: server\n type: str\n domain:\n description: Specifies the domain name associated with the server certificate.\n type: str\n content:\n description: Certificate content or path to file with content. Required for creation.\n type: str\n private_key:\n description: Private key for the certificate or path to file with key. Required for creation.\n type: str\n state:\n choices: [present, absent]\n default: present\n description: Certificate state\n type: str\nrequirements: [\"openstacksdk\", \"otcextensions\"]\n'''\n\nRETURN = '''\nelb_certificate:\n description: Certificate data.\n type: complex\n returned: On Success.\n contains:\n id:\n description: Unique UUID.\n type: str\n sample: \"39007a7e-ee4f-4d13-8283-b4da2e037c69\"\n name:\n description: Name of the certificate.\n type: str\n sample: \"test\"\n admin_state_up:\n description: Administrative status of the certificate.\n type: bool\n description:\n description: Supplementary information about the certificate.\n type: str\n type:\n description: Certificate type.\n type: str\n domain:\n description: Domain name associated with the server certificate.\n type: str\n private_key:\n description: Private key of the server certificate in PEM format.\n type: str\n certificate:\n description: Public key of the server certificate or CA certificate used to authenticate the client.\n type: str\n expire_time:\n description: Expiration timestamp\n type: int\n sample: 1630488473000\n create_time:\n description: Certificate creation time\n type: int\n sample: 1630488473000\n update_time:\n description: Certificate update time\n type: int\n sample: 1630488473000\n'''\n\nEXAMPLES = '''\n# Create lb certificate.\n- opentelekomcloud.cloud.lb_certificate:\n state: present\n name: certificate-test\n content: \"{{ dummy-cert }}\"\n type: client\n register: lb_cert\n'''\n\nimport os\n\nfrom ansible_collections.opentelekomcloud.cloud.plugins.module_utils.otc import OTCModule\n\n\nclass LoadBalancerCertificateModule(OTCModule):\n argument_spec = dict(\n name=dict(required=True, type='str'),\n content=dict(type='str', no_log=True),\n private_key=dict(type='str', no_log=True),\n admin_state_up=dict(type='bool'),\n description=dict(type='str'),\n type=dict(type='str', choices=['server', 'client'], default='server'),\n domain=dict(type='str', default=None),\n state=dict(type='str', choices=['present', 'absent'],\n default='present')\n )\n module_kwargs = dict(\n supports_check_mode=True\n )\n\n otce_min_version = '0.10.1'\n\n @staticmethod\n def _is_path(path):\n if os.path.isfile(path):\n return True\n return False\n\n @staticmethod\n def _read_content(path):\n with open(path, 'r') as file:\n content = file.read()\n return content.strip()\n\n def _system_state_change(self, obj):\n state = self.params['state']\n if state == 'present':\n if not obj:\n return True\n elif state == 'absent' and obj:\n return True\n return False\n\n def run(self):\n name = self.params['name']\n\n changed = False\n attrs = {}\n cert = self.conn.elb.find_certificate(\n name_or_id=name, ignore_missing=True)\n\n if self.ansible.check_mode:\n self.exit(changed=self._system_state_change(cert))\n\n if self.params['state'] == 'absent':\n changed = False\n\n if cert:\n self.conn.elb.delete_certificate(cert)\n changed = True\n\n self.exit(changed=changed)\n\n elif self.params['state'] == 'present':\n name_filter = self.params['name']\n admin_state_filter = self.params['admin_state_up']\n description_filter = self.params['description']\n type_filter = self.params['type']\n domain_filter = self.params['domain']\n private_key_filter = self.params['private_key']\n content_filter = self.params['content']\n\n if name_filter:\n attrs['name'] = name_filter\n if type_filter:\n attrs['type'] = type_filter\n if admin_state_filter:\n attrs['admin_state_up'] = admin_state_filter\n if description_filter:\n attrs['description'] = description_filter\n if domain_filter:\n attrs['domain'] = domain_filter\n if private_key_filter:\n if self._is_path(private_key_filter):\n attrs['private_key'] = self._read_content(private_key_filter)\n else:\n attrs['private_key'] = private_key_filter.strip()\n if content_filter:\n if self._is_path(content_filter):\n attrs['content'] = self._read_content(content_filter)\n else:\n attrs['content'] = content_filter.strip()\n\n if type_filter == 'server' and not cert:\n if not private_key_filter:\n self.fail_json(msg='private_key mandatory when type is set to server.')\n if not content_filter and not cert:\n self.fail_json(msg='certificate is mandatory field.')\n\n if cert:\n changed = False\n\n mattrs = {}\n\n if admin_state_filter and cert.admin_state_up != admin_state_filter:\n mattrs['admin_state_up'] = admin_state_filter\n if description_filter and cert.description != description_filter:\n mattrs['description'] = description_filter\n if domain_filter and cert.domain != domain_filter:\n mattrs['domain'] = domain_filter\n if private_key_filter and cert.private_key != private_key_filter.strip():\n mattrs['private_key'] = private_key_filter.strip()\n if content_filter and cert.content != content_filter.strip():\n mattrs['content'] = content_filter.strip()\n if mattrs:\n changed = True\n if self.ansible.check_mode:\n self.exit_json(changed=True)\n certificate = self.conn.elb.update_certificate(cert, **mattrs)\n self.exit_json(\n changed=changed,\n elb_certificate=certificate.to_dict(),\n id=certificate.id)\n\n cert = self.conn.elb.create_certificate(**attrs)\n data = cert.to_dict()\n data.pop('location')\n self.exit(changed=True, elb_certificate=data)\n\n\ndef main():\n module = LoadBalancerCertificateModule()\n module()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"opentelekomcloud/ansible-collection-cloud","sub_path":"plugins/modules/lb_certificate.py","file_name":"lb_certificate.py","file_ext":"py","file_size_in_byte":8113,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"67"} +{"seq_id":"71937348054","text":"import time\nimport unittest\n\nfrom citizens.schema import CitizenSchema\n\nmarshmallow_is_not_installed = False\ntry:\n from marshmallow import Schema, fields, validate, validates, ValidationError\n\n\n def letter_or_digit_required(value):\n valid = any(filter(lambda s: s.isalpha() or s.isdigit(), value))\n if not valid:\n raise ValidationError('At least one letter or digit required')\n\n\n def validate_int(value):\n if value <= 0:\n raise ValidationError('Value must be positive')\n\n\n class MarshmallowCitizenSchema(Schema):\n citizen_id = fields.Int(strict=True, validate=validate_int)\n town = fields.Str(validate=letter_or_digit_required)\n street = fields.Str(validate=letter_or_digit_required)\n building = fields.Str(validate=letter_or_digit_required)\n apartment = fields.Int(strict=True, validate=validate_int)\n name = fields.Str(validate=validate.Length(min=1))\n birth_date = fields.Date('%d.%m.%Y')\n gender = fields.Str(validate=validate.OneOf(('male', 'female')))\n relatives = fields.List(fields.Int(strict=True, validate=validate_int))\n\n @validates('relatives')\n def validate_relatives(self, value):\n return len(value) == len(set(value))\n\nexcept ImportError:\n marshmallow_is_not_installed = True\n\n\n@unittest.skipIf(marshmallow_is_not_installed, 'Marshmallow is not installed.')\nclass TestMarshmallow(unittest.TestCase):\n def setUp(self):\n self.citizens = [self._make_citizen_data(i + 1) for i in range(10000)]\n invalid_data = self._make_citizen_data(-1)\n self.citizens.append(invalid_data)\n\n def _make_citizen_data(self, citizen_id):\n return {\n \"citizen_id\": citizen_id,\n \"town\": \"Амстердам\",\n \"street\": \"Ленина\",\n \"building\": \"16к7стр5\",\n \"apartment\": 365,\n \"name\": \"Иванов Сергей Иванович\",\n \"birth_date\": \"01.02.1997\",\n \"gender\": \"male\",\n \"relatives\": [1, 2, 3]\n }\n\n def test_speed(self):\n for _ in range(1):\n t1 = time.time()\n schema = MarshmallowCitizenSchema()\n for data in self.citizens:\n errors = schema.validate(data)\n if errors:\n break\n marshmallow = time.time() - t1\n schema = CitizenSchema()\n t1 = time.time()\n try:\n for data in self.citizens:\n schema.validate(data)\n except Exception:\n pass\n my_one = time.time() - t1\n print('Marshmallow: {0} sec\\nCustom: {1} sec\\nRatio: x{2}'.format(\n round(marshmallow, 3),\n round(my_one, 3),\n round(marshmallow / my_one, 1)\n ))\n","repo_name":"djudman/citizens","sub_path":"tests/test_marshmallow.py","file_name":"test_marshmallow.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25975112367","text":"from sklearn.model_selection import train_test_split\nimport csv\nimport numpy as np\nimport sys\nimport getopt\n\nimport time\n\nfrom Normalizer import Normalizer\nfrom SVMClassifier import SVMClassifier\nfrom DecisionTree import DecisionTree\nfrom KDTree import Kd_Tree\n# from LogisticRegression import LogisticRegression\n# from neuralNetwork import neural_network_classifier\nfrom tec.ic.ia.pc1.g06 import (\n generar_muestra_pais,\n generar_muestra_provincia\n)\n\n\nsavedSamples = []\n\n\ndef clear_csv():\n with open(\"./data.csv\", \"w\", newline='') as file:\n\n writer = csv.writer(file, delimiter=\",\")\n\n writer.writerow(\"\")\n\n\ndef make_csv(k, data, lenData, pctTest, predictions):\n\n featureNames = [\n \"Provincia\", \"Canton\", \"Total de la población\", \"Superficie\",\n \"Densidad de la población\", \"Urbano/Rural\", \"Género\", \"Edad\",\n \"Dependencia\", \"Alfabeta\", \"Escolaridad promedio\",\n \"Escolaridad regular\", \"Trabaja\", \"Asegurado\",\n \"Cant. casas individuales\", \"Ocupantes promedio\", \"Condicion\",\n \"Hacinada\", \"Nacido en...\", \"Discapacitado\", \"Jefatura femenina\",\n \"Jefatura compartida\", \"Voto ronda 1\", \"Voto ronda 2\",\n \"es_entrenamiento\", \"prediccion_r1\", \"prediccion_r2\",\n \"prediccion_r2_con_r1\"\n ]\n quantity_for_testing = int(lenData*0.3)\n quantityTraining = len(data[\"trainingFeatures\"])\n\n with open(\"./data.csv\", \"a\", newline='') as file:\n\n writer = csv.writer(file, delimiter=\",\")\n\n writer.writerow(\n featureNames\n )\n\n group = 0\n groupLen = int((lenData-(lenData*pctTest)-(lenData*0.3)) // k)\n\n for i in range(0, k):\n index = 0\n for j in range(group, group+groupLen):\n writer.writerow(\n data[\"trainingFeatures\"].tolist()[j] +\n [data[\"trainingClassesFirst\"].tolist()[j]] +\n [data[\"trainingClassesSecond\"].tolist()[j]] +\n [\"Verdadero\"] + [predictions[0][2][i][1][index]] +\n [predictions[1][2][i][1][index]] +\n [predictions[2][2][i][1][index]]\n )\n index += 1\n\n for i in range(0, quantity_for_testing):\n writer.writerow(\n data[\"trainingFeatures\"].tolist()[i] +\n [data[\"trainingClassesFirst\"].tolist()[i]] +\n [data[\"trainingClassesSecond\"].tolist()[i]] + [\"Verdadero\"] +\n [predictions[0][1][i]] + [predictions[1][1][i]] +\n [predictions[2][1][i]]\n )\n\n for i in range(0, len(data[\"testingFeatures\"])):\n writer.writerow(\n data[\"testingFeatures\"].tolist()[i] +\n [data[\"testingClassesFirst\"].tolist()[i]] +\n [data[\"testingClassesSecond\"].tolist()[i]] +\n [\"Falso\"] + [predictions[0][4][i]] + [predictions[1][4][i]] +\n [predictions[2][4][i]]\n )\n\n file.close()\n\n\ndef get_accuracy2(classifier, toTrain, toTest):\n\n predictions = []\n classifier.train(toTrain)\n\n i = 0\n for sample in toTest[\"testingFeatures\"]:\n\n data = {\n \"testingFeatures\": [sample],\n \"testingClasses\": [toTest[\"testingClasses\"][i]]\n }\n\n prediction = classifier.classify(data)\n predictions.append(prediction[0])\n i += 1\n\n testingClasses = toTest[\"testingClasses\"]\n right = 0\n\n # print(\"PREEE\", predictions)\n for i in range(0, len(predictions)):\n print(predictions[i], \" - \", testingClasses[i])\n if (predictions[i] == testingClasses[i]):\n right += 1\n\n accuracy = right / len(predictions)\n\n return (accuracy, predictions)\n\n\ndef get_accuracy(classifier, toTrain, toTest):\n\n predictions = []\n classifier.train(toTrain)\n\n for sample in toTest[\"testingFeatures\"]:\n prediction = classifier.classify([sample])\n predictions.append(prediction[0])\n\n testingClasses = toTest[\"testingClasses\"]\n right = 0\n\n for i in range(0, len(predictions)):\n if (predictions[i] == testingClasses[i]):\n right += 1\n\n accuracy = right / len(predictions)\n\n return (accuracy, predictions)\n\n\naccList = []\n\n\ndef k_fold_cross_validation(k, classifier, data, lenData):\n groupLen = len(data[\"trainingFeatures\"]) // k\n group = 0\n toTrain = {}\n toTest = {}\n results = []\n\n while group < len(data[\"trainingFeatures\"]):\n\n testingFeatures = data[\"trainingFeatures\"][group:group+groupLen]\n testingClasses = data[\"trainingClasses\"][group:group+groupLen]\n\n toTest[\"testingFeatures\"] = testingFeatures\n toTest[\"testingClasses\"] = testingClasses\n\n trainingFeatures = np.append(\n data[\"trainingFeatures\"][:group],\n data[\"trainingFeatures\"][group+groupLen:],\n axis=0\n )\n\n trainingClasses = np.append(\n data[\"trainingClasses\"][:group],\n data[\"trainingClasses\"][group+groupLen:],\n axis=0\n )\n\n toTrain[\"trainingFeatures\"] = trainingFeatures\n toTrain[\"trainingClasses\"] = trainingClasses\n toTrain[\"testingFeatures\"] = testingFeatures\n\n results.append(get_accuracy(classifier, toTrain, toTest))\n\n group += groupLen\n\n return results\n\n\ndef cross_validation(\n k,\n classifier,\n data,\n lenData,\n training_name,\n testing_name,\n round):\n\n quantity_for_testing = int(lenData*0.3)\n results = []\n\n toTrain = {\n \"trainingFeatures\": data[training_name],\n \"trainingClasses\": data[\"trainingClasses\" + round]\n }\n\n X_train = toTrain[\"trainingFeatures\"][quantity_for_testing:]\n y_train = toTrain[\"trainingClasses\"][quantity_for_testing:]\n\n X_test = toTrain[\"trainingFeatures\"][:quantity_for_testing]\n y_test = toTrain[\"trainingClasses\"][:quantity_for_testing]\n\n toTrain = {\n \"trainingFeatures\": X_train,\n \"trainingClasses\": y_train,\n \"testingFeatures\": X_test\n }\n\n results = k_fold_cross_validation(k, classifier, toTrain, lenData)\n\n toTest = {\n \"testingFeatures\": X_test,\n \"testingClasses\": y_test\n }\n\n accuracyCV, predictionsCV = get_accuracy(classifier, toTrain, toTest)\n\n toTrain = {\n \"trainingFeatures\": data[training_name],\n \"trainingClasses\": data[\"trainingClasses\" + round],\n \"testingFeatures\": data[testing_name]\n }\n\n toFinalTest = {\n \"testingFeatures\": data[testing_name],\n \"testingClasses\": data[\"testingClasses\" + round]\n }\n\n accuracyReal, predictions = get_accuracy(classifier, toTrain, toFinalTest)\n accList.append((accuracyCV, accuracyReal))\n\n return (accuracyCV, predictionsCV, results, accuracyReal, predictions)\n\n\ndef show_accuracy(model, predictions):\n print(\"----------------------------------------------\")\n print(\"Tasa de error para: \" + model)\n print()\n print(\"Cross validation>\")\n print(\"Primera ronda: \" + str(1-predictions[0][0]))\n print(\"Segunda ronda: \" + str(1-predictions[1][0]))\n print(\"Segunda ronda (con primera incluida): \" + str(1-predictions[2][0]))\n print()\n print(\"Pruebas>\")\n print(\"Primera ronda: \" + str(1-predictions[0][3]))\n print(\"Segunda ronda: \" + str(1-predictions[1][3]))\n print(\"Segunda ronda (con primera incluida): \" + str(1-predictions[2][3]))\n print(\"----------------------------------------------\")\n\n\ndef svm_classification(\n k, lenData, pctTest, params, C=1, gamma=1, kernel=\"rbf\"):\n\n clear_csv()\n\n samples = []\n\n print(params)\n if (params[0] == \"PAIS\"):\n samples = generar_muestra_pais(lenData)\n else:\n samples = generar_muestra_provincia(lenData, params[1])\n\n quantity_for_testing = int(lenData * pctTest)\n\n normalizer = Normalizer()\n data = normalizer.prepare_data(samples, quantity_for_testing)\n\n svmClassifier = SVMClassifier(kernel, C, gamma)\n\n firstRound = cross_validation(\n k,\n svmClassifier,\n data,\n lenData,\n \"trainingFeatures\",\n \"testingFeatures\",\n \"First\"\n )\n\n secondRound = cross_validation(\n k,\n svmClassifier,\n data,\n lenData,\n \"trainingFeatures\",\n \"testingFeatures\",\n \"Second\"\n )\n\n secondWithFirst = cross_validation(\n k,\n svmClassifier,\n data,\n lenData,\n \"trainingFeaturesFirstInclude\",\n \"testingFeaturesFirstInclude\",\n \"Second\"\n )\n\n normalData = normalizer.get_normal_data()\n predictions = [firstRound, secondRound, secondWithFirst]\n\n show_accuracy(\"SVM\", predictions)\n make_csv(k, normalData, lenData, pctTest, predictions)\n\n\ndef kd_tree_classification(k, lenData, pctTest, params, neightboards):\n\n clear_csv()\n\n samples = []\n\n if (params[0] == \"PAIS\"):\n samples = generar_muestra_pais(lenData)\n else:\n samples = generar_muestra_provincia(lenData, params[1])\n quantity_for_testing = int(lenData * pctTest)\n\n normalizer = Normalizer()\n data = normalizer.prepare_data(samples, quantity_for_testing)\n\n kdTree = Kd_Tree(neightboards)\n firstRound = cross_validation(\n k,\n kdTree,\n data,\n lenData,\n \"trainingFeatures\",\n \"testingFeatures\",\n \"First\"\n )\n\n secondRound = cross_validation(\n k,\n kdTree,\n data,\n lenData,\n \"trainingFeatures\",\n \"testingFeatures\",\n \"Second\"\n )\n\n secondWithFirst = cross_validation(\n k,\n kdTree,\n data,\n lenData,\n \"trainingFeaturesFirstInclude\",\n \"testingFeaturesFirstInclude\",\n \"Second\"\n )\n\n normalData = normalizer.get_normal_data()\n predictions = [firstRound, secondRound, secondWithFirst]\n\n show_accuracy(\"KD-TREE\", predictions)\n make_csv(k, normalData, lenData, pctTest, predictions)\n\n\ndef desicion_tree(k, lenData, pctTest, params, threshold):\n\n clear_csv()\n\n samples = []\n\n if (params[0] == \"PAIS\"):\n samples = generar_muestra_pais(lenData)\n else:\n samples = generar_muestra_provincia(lenData, params[1])\n\n normalizer = Normalizer()\n data = normalizer.separate_data_2(samples, quantity_for_testing)\n\n decisionTree = DecisionTree(threshold)\n firstRound = cross_validation(\n k,\n decisionTree,\n data,\n lenData,\n \"trainingFeaturesFirst\",\n \"testingFeaturesFirst\",\n \"First\"\n )\n\n secondRound = cross_validation(\n k,\n decisionTree,\n data,\n lenData,\n \"trainingFeaturesSecond\",\n \"testingFeaturesSecond\",\n \"Second\"\n )\n\n secondWithFirst = cross_validation(\n k,\n decisionTree,\n data,\n lenData,\n \"trainingFeaturesFirstInclude\",\n \"testingFeaturesFirstInclude\",\n \"Second\"\n )\n\n normalData = normalizer.get_normal_data()\n predictions = [firstRound, secondRound, secondWithFirst]\n\n show_accuracy(\"DT\", predictions)\n make_csv(k, normalData, lenData, pctTest, predictions)\n\n\ndef lr_classification(k, lenData, pctTest, l_regulizer=1):\n\n clear_csv()\n\n samples = generar_muestra_pais(lenData)\n quantity_for_testing = int(lenData * pctTest)\n\n normalizer = Normalizer()\n data = normalizer.prepare_data_tensor(samples, quantity_for_testing)\n\n lrClassifier = LogisticRegression(1, l_regulizer)\n\n firstRound = cross_validation(\n k,\n lrClassifier,\n data,\n lenData,\n \"trainingFeatures\",\n \"testingFeatures\",\n \"First\"\n )\n\n lrClassifier = LogisticRegression(2, l_regulizer)\n print(\"Paso primero\")\n\n secondRound = cross_validation(\n k,\n lrClassifier,\n data,\n lenData,\n \"trainingFeatures\",\n \"testingFeatures\",\n \"Second\"\n )\n print(\"Paso segundo\")\n\n secondWithFirst = cross_validation(\n k,\n lrClassifier,\n data,\n lenData,\n \"trainingFeaturesFirstInclude\",\n \"testingFeaturesFirstInclude\",\n \"Second\"\n )\n print(\"Paso tercero\")\n\n normalData = normalizer.get_normal_data()\n # predictions = [firstRound, secondRound, secondWithFirst]\n predictions = [secondRound]\n show_accuracy(\"LR\", predictions)\n make_csv(k, normalData, lenData, pctTest, predictions)\n\n\ndef main2():\n lr_classification(2, 100, 0.2, l_regulizer=1)\n\n\ndef pruebas():\n # svm_classification(1000, 0.2, C=10, gamma=0.00833333333, kernel=\"rbf\")\n lenData = 2500\n print(lenData)\n print(\"kernel: \", \"sigmoid\", \" C: \", 1, \" G: \", 0.000000001)\n pctTest = 0.2\n\n # samples = generar_muestra_provincia(lenData, \"SAN JOSE\")\n # quantity_for_testing = int(lenData*pctTest)\n\n # normalizer = Normalizer()\n # data = normalizer.prepare_data(samples, quantity_for_testing)\n\n # svm_classification(10, lenData, pctTest, C=1, gamma=1, kernel=\"rbf\")\n\n time1 = time.time()\n\n for i in range(0, 30):\n samples = generar_muestra_pais(lenData)\n quantity_for_testing = int(lenData*pctTest)\n\n normalizer = Normalizer()\n data = normalizer.prepare_data(samples, quantity_for_testing)\n svm_classification(\n 10, lenData, pctTest, C=1, gamma=0.000000001, kernel=\"sigmoid\")\n\n time2 = time.time()\n\n print(\"ms: \", ((time2-time1)*1000.0))\n\n totalacc = 0.0\n for i in range(0, len(accList), 3):\n totalacc += accList[i][1]\n print(\"ER: \", 1-(totalacc/30.0))\n\n totalacc = 0.0\n for i in range(1, len(accList), 3):\n totalacc += accList[i][1]\n print(\"ER: \", 1-(totalacc/30.0))\n\n totalacc = 0.0\n for i in range(2, len(accList), 3):\n totalacc += accList[i][1]\n print(\"ER: \", 1-(totalacc/30.0))\n\n # svmClassifier = SVMClassifier(\"rbf\", 1, 1)\n # svmClassifier.test_parameters(\n # data[\"trainingFeatures\"],\n # data[\"trainingClassesSecond\"]\n # )\n\n\ndef main(argv):\n print(argv)\n if(len(argv) < 6):\n print(\"\\n ***INSTRUCCIONES***\\n\")\n print(\n \" main.py --poblacion --porcentaje-pruebas\",\n \" bandera\\n\")\n print(\" BANDERAS:\\n\")\n print(\"** --provincia | --pais\")\n print(\"* --regresion-logistica [--l1 o --l2] \")\n print(\n \"* --red-neuronal --numero-capas \",\n \"--unidades-por-capa --funcion-activacion ? \")\n print(\"* --knn --k \")\n print(\"* --arbol --umbral-poda \")\n print(\n \"* --svm --kernel \",\n \" --C --Gamma \\n\")\n else:\n params = []\n method = argv[4]\n lenData = int(argv[1])\n pctTest = float(argv[3])/100.0\n if (method == \"--pais\"):\n params.append(\"PAIS\")\n\n if(argv[5] == \"--regresion-logistica\"):\n print(\"REGRESION LOGISTICA\")\n if(len(argv) == 7):\n print(argv[6])\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\"Debe ingresar --l1 o --l2\")\n\n elif(argv[5] == \"--red-neuronal\"):\n print(\"RED NEURONAL\")\n if(len(argv) == 12):\n print(argv[6])\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\n \"Debe ingresar --numero-capas \",\n \"--unidades-por-capa --funcion-activacion ?\")\n elif(argv[5] == \"--knn\"):\n print(\"KD-TREE\")\n if(len(argv) == 8):\n print(argv[7])\n neightboards = int(argv[7])\n kd_tree_classification(\n 2, lenData, pctTest, params, neightboards)\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\"Debe ingresar --k \")\n elif(argv[5] == \"--arbol\"):\n print(\"ARBOL DE DECISION\")\n if(len(argv) == 8):\n print(argv[7])\n threshold = float(argv[7])\n desicion_tree(2, lenData, pctTest, params, threshold)\n\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\"Debe ingresar --umbral-poda \")\n\n elif(argv[5] == \"--svm\"):\n print(\"SVM\")\n print(len(argv))\n if(len(argv) == 12):\n # print(argv[5:])\n k = argv[7]\n c = float(argv[9])\n try:\n g = float(argv[11])\n except ValueError:\n g = argv[11]\n svm_classification(\n 10, lenData, pctTest, params, C=c, gamma=g, kernel=k)\n\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\n \"Debe ingresar --kernel --C --Gamma \")\n else:\n print(\"ERROR: Bandera inexistente\")\n else:\n params.append(\"PROVINCIA\")\n params.append(argv[5])\n\n if(argv[6] == \"--regresion-logistica\"):\n print(\"REGRESION LOGISTICA\")\n if(len(argv) == 8):\n print(argv[7])\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\"Debe ingresar --l1 o --l2\")\n\n elif(argv[6] == \"--red-neuronal\"):\n print(\"RED NEURONAL\")\n if(len(argv) == 13):\n print(argv[7])\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\n \"Debe ingresar --numero-capas \",\n \" --unidades-por-capa --funcion-activacion ?\")\n elif(argv[6] == \"--knn\"):\n print(\"KD-TREE\")\n if(len(argv) == 9):\n print(argv[8])\n neightboards = int(argv[8])\n kd_tree_classification(\n 2, lenData, pctTest, params, neightboards)\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\"Debe ingresar --k \")\n elif(argv[6] == \"--arbol\"):\n print(\"ARBOL DE DECISION\")\n if(len(argv) == 9):\n print(argv[8])\n threshold = float(argv[8])\n desicion_tree(2, lenData, pctTest, params, threshold)\n\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\"Debe ingresar --umbral-poda \")\n\n elif(argv[6] == \"--svm\"):\n print(\"SVM\")\n print(len(argv))\n if(len(argv) == 13):\n # print(argv[5:])\n k = argv[8]\n c = float(argv[10])\n try:\n g = float(argv[12])\n except ValueError:\n g = argv[12]\n svm_classification(\n 10, lenData, pctTest, params, C=c, gamma=g, kernel=k)\n\n else:\n print(\"ERROR: Parametros Incompletos\")\n print(\n \"Debe ingresar --kernel --C --Gamma \"\n )\n else:\n print(\"ERROR: Bandera inexistente\")\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n # main2()\n # pruebas()\n","repo_name":"Feymus/PredictorDeVotaciones","sub_path":"tec/ic/ia/p1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"72819721174","text":"import cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom tensorflow import keras \r\nfrom PIL import Image\r\nimport string\r\nimport os\r\ncategories=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',\r\n 'L', 'M', 'N','O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',\r\n 'W', 'X', 'Y', 'Z','middle finger','nothing']\r\n\r\nmodel = keras.models.load_model(\"version98.h5\")\r\ncam=cv2.VideoCapture(cv2.CAP_DSHOW)\r\n\r\nwhile True:\r\n ret,frame =cam.read()\r\n img=cv2.rectangle(frame,(0,0),(250,250),(255,0,0),3)\r\n roi=img[0:250,0:250]\r\n resizeimg=cv2.resize(roi,(64,64))\r\n resizeimg=cv2.cvtColor(resizeimg,cv2.COLOR_BGR2GRAY)\r\n imgarray=np.array(resizeimg)\r\n\r\n imgarray=imgarray/255\r\n imgarray=np.expand_dims(imgarray, axis=0)\r\n imgarray=np.expand_dims(imgarray, axis=-1)\r\n \r\n\r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n bottomLeftCornerOfText = (20,300)\r\n fontScale = 1\r\n fontColor = (0,0,255)\r\n lineType = 2\r\n cv2.putText(frame,categories[(np.argmax(model.predict(imgarray)))], \r\n bottomLeftCornerOfText, \r\n font, \r\n fontScale,\r\n fontColor,\r\n lineType)\r\n\r\n cv2.imwrite(\"img.jpg\",resizeimg)\r\n cv2.imshow(\"freame\",img)\r\n cv2.imshow(\"roi\",resizeimg)\r\n \r\n \r\n\r\n \r\n\r\n \r\n if cv2.waitKey(1) == ord('q'):\r\n break\r\n \r\ncam.release()\r\ncv2.destroyAllWindows()\r\n\r\n","repo_name":"themnvrao76/Sign-Language-Classification-with-CNN","sub_path":"recognition.py","file_name":"recognition.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"12546280120","text":"# MD5\r\n\r\n__all__ = ['MD5']\r\n\r\nfrom msmath.bitstring import bitstrings\r\nbitstring = bitstrings(32)\r\n\r\nfrom msmath.rational import sin\r\n\r\nfrom msmath.conversions import xrange\r\n\r\nT = tuple(bitstring(int(abs(sin(i+1))<<32),32) for i in xrange(64));\r\n\r\nF = (lambda x,y,z : x&y|~x&z,\r\n lambda x,y,z : x&z|y&~z,\r\n lambda x,y,z : x^y^z,\r\n lambda x,y,z : y^(x|~z)\r\n );\r\n\r\nS = ((7,12,17,22),\r\n (5,9,14,20),\r\n (4,11,16,23),\r\n (6,10,15,21)\r\n );\r\n\r\nX = (lambda k : k,\r\n lambda k : (5*k+1)&15,\r\n lambda k : (3*k+5)&15,\r\n lambda k : (7*k)&15\r\n );\r\n\r\nblocksize = 512;\r\nwordsize = 32;\r\nlensize = 64;\r\nwpb = blocksize//wordsize;\r\n\r\nH0 = bitstring(0x67452301efcdab8998badcfe10325476,128);\r\n\r\ndef MD5(M) :\r\n \"\"\"Return, as a bitstring, MD5 hash of a string or bitstring, as per RFC1321\"\"\"\r\n M = bitstring(M); # make a copy, or convert a string\r\n l = len(M); # if this isn't a multiple of 8, endianness may be an issue!\r\n M = M.iconcat(1); # pad to multiple of blocksize ...\r\n M.itrunc((l+blocksize+lensize)//blocksize*blocksize-lensize);\r\n L = bitstring(l,64).split(8); # big-endian length field\r\n M.iconcat(*L[::-1]); # -> little-endian\r\n M = M.split(blocksize);\r\n N = len(M)//wpb;\r\n H = H0.split(wordsize);\r\n for i,B in enumerate(M) : # for each message block\r\n B = B.split(wordsize);\r\n for i,b in enumerate(B) : # rearrange octets in words\r\n o = b.split(8);\r\n B[i] = bitstring.concat(*o[::-1]);\r\n I = tuple(map(bitstring,H)); # save a copy of digest so far\r\n for j in xrange(4) : # for each pass\r\n for k in xrange(wpb) : # for each word in message block\r\n H[-k&3] = H[(1-k)&3]+((H[-k&3]+F[j](H[(1-k)&3],H[(2-k)&3],H[(3-k)&3])+\r\n B[X[j](k)]+T[16*j+k])< 20)\n\n\nxx.unpersist() #xx is no longer needed, so garbage collect it.\n\ny = sc.parallelize([2,3])\n\n\n\n\"\"\"\n\n\n#======== 8 ========\n#This is to practice accumulators\naccum = sc.accumulator(0) #only int\n\nx = sc.parallelize([2,3,4,5])\n\ndef f(a):\n\tglobal accum\n\taccum += a\n\nx.foreach(f)\nprint('\\n', accum.value, '\\n')\n\ndef g(a):\n\taccum.add(-a)\n\t\nx.foreach(g)\nprint ('\\n', accum, '\\n')\n\n\n\n#======= 7 ========\n#This is to practice broadcast\nbdct_1 = sc.broadcast(2)\nbdct_2 = sc.broadcast({'a': 8})\nbdct_3 = sc.broadcast([2,7])\n\nx = sc.parallelize(range(10))\n\nprint ('\\n', 'Larger than bdct_1', x.filter(lambda a: a>bdct_1.value).collect(), '\\n')\nprint ('\\n', 'Smaller than bdct_2', x.filter(lambda a: a< bdct_2.value['a']).collect(), '\\n')\nprint ('\\n', 'Between bdct_3', x.filter(lambda a: a>bdct_3.value[0] and a< bdct_3.value[1]).collect(), '\\n')\nx.foreach(lambda x: print ('\\n', x+bdct_2.value['a'], '\\n'))\n\n\n\n#======== 6 =========\n#This is to practice two pair-RDD operations\nx = sc.parallelize([(2,3), (2,4), (3,7), (4,7), (4,700)])\ny = sc.parallelize([(2,'3'), (2,'4'), (4,70), (5,5)])\n\nprint ('\\n', x.subtractByKey(y).collect(), '\\n') #remove the sharing keys in y\nx_y_cogroup = x.cogroup(y).collect() #a list of tuple(key, (values))\nfor key, value in x_y_cogroup:\n\tfor v in value:\n\t\tprint ('\\n', key, list(v), '\\n')\n\nprint ('\\n', x.join(y).collect(), '\\n')\t#join() only for the sharing keys with all possible combinaiton of values\n\t\nprint ('\\n', x.leftOuterJoin(y).collect(), '\\n') #with keys in x as the base, if not exist in y, then y value as None\n\nprint ('\\n', x.rightOuterJoin(y).collect(), '\\n') #with keys in y as the base, if not exist in x, then x value as None\n\n\n#======== 5 ========\n#This is to practice pair RDD\nx = sc.parallelize([(2,3,4), (2,3,5), (2,4,9)]) #when using pair RDD, only the first two columns are considered\n\t\t\t\t\t\t\t\t\t\t\t #the first as the key and the second as the value\n\t\t\t\t\t\t\t\t\t\t\t \nprint ('\\n', x.keys().collect(),'\\n')\t\t\t\t\t\t\t\t\t\t\t \nprint ('\\n', x.values().collect(), '\\n')\nprint ('\\n', x.countByKey().items(), '\\n')\n#print ('\\n', x.groupByKey().collect(), '\\n') #does not work for more than one value for each key, nor does sortByKey() works.\nprint ('\\n', list(x.map(lambda x: (x[0], tuple(x[1:]))).groupByKey().collect()[0][1]), '\\n') #collect all values for each key, not do anything yet. Use reduceByKey() to assign only one value for each key.\n\ny = sc.parallelize([(2,3), (0,3), (-1, 7), (2,9)])\nprint ('\\n', y.reduceByKey(lambda x, y: x+y).collect(), '\\n')\nprint ('\\n', y.sortByKey().collect(), '\\n')\n\nprint ('\\n', y.mapValues(lambda x: (x,1)).reduceByKey(lambda x, y: (x[0]+y[0], y[1]+x[1])).mapValues(lambda x: x[0]/x[1]).collect(), '\\n') #mapValues() only changes the value not the key.\nprint ('\\n', y.lookup(2), '\\n') #return the values for the key.\n\n\n\n#======== 4 =========\n#practice non-pair RDD\nx = sc.parallelize([2, 2, 3, 3, 0, 3, 0, -2, 9, 9, -23]) #create a RDD with a list or a list of tuples (pair RDD)\n\nprint ('\\n', x.first(), x.take(3), x.top(3), '\\n') #the first element, 3 elements, and largest 3 elements\nprint ('\\n', x.distinct().collect(), '\\n') #only return the distinct values\nprint ('\\n', x.map(lambda x: x*x).collect()) #map() returns RDD with the same size as the original RDD\nprint ('\\n', x.filter(lambda x: x>0).collect()) # filter() returns fewer # of elements\n\ny = sc.parallelize(['abcd', 'efghi'])\nprint ('\\n', y.flatMap(lambda x: [i for i in x]).collect(), '\\n') #flatMap() returns more elements\nprint ('\\n', x.cartesian(y).collect(), '\\n') #returns cartesian product\n\nz = sc.parallelize([2,3,0,3,3,2])\nprint ('\\n', x.union(z).collect(), '\\n', x.intersection(z).collect(), '\\n', x.subtract(z).collect(), '\\n') #simply concatenate, only contain the sharing elements, remove the sharing elements \n\nprint ('\\n', sc.parallelize([2,3,4]).reduce(lambda x,y: x*y), '\\n')\nprint ('\\n', x.countByValue().items(), '\\n')\nprint ('\\n', sc.parallelize(x.countByValue().items()).collect(), '\\n')\n\nx.foreach(lambda x: print ('\\n', 'this: ', x**2, '\\n'))\n\nprint ('\\n', sc.parallelize(x.countByValue().items()).map(lambda x: (x[1], x[0])).sortByKey().collect(), '\\n')\n\n\n\n\n#======== 3 =======\n#This is to find the average number of friends for each age\nfrom pyspark import SparkConf, SparkContext\nimport statistics\n\nconf = SparkConf().setMaster('local[*]').setAppName('test_mapValues')\nsc = SparkContext(conf = conf)\n\nlines = sc.textFile('fakefriends.csv')\n\ndef parseline(line):\n\tline_split = line.split(',')\n\treturn (line_split[2], int(line_split[3]))\n\nage_friends = lines.map(parseline)\naverage_age_friends = age_friends.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1])).mapValues(lambda x: x[0]/x[1]).collect()\n\naverage_age_friends = sorted(average_age_friends, key = lambda x: x[1])\nprint ('\\n\\n\\n====')\nfor result in average_age_friends:\n\tprint (result)\n\nprint ('====\\n\\n\\n')\n\nage_friends_gbk = age_friends.groupByKey().collect()\nfor i in range(len(age_friends_gbk)):\n\tage_friends_gbk[i] = list(age_friends_gbk[i]) #tuple is immutable, so convert to list\n\tage_friends_gbk[i][1] = statistics.mean(age_friends_gbk[i][1])\n\naverage_age_friends_gbk = sorted(age_friends_gbk, key = lambda x: x[1])\nfor result in average_age_friends_gbk:\n\tprint (result)\n\n\n\n#======= 2 =======\n#This is to practice mapValues() and reduceByKey()\nfrom pyspark import SparkConf, SparkContext\nconf = SparkConf().setMaster('local').setAppName('test_mapValus')\nsc = SparkContext(conf = conf)\n\nlines = sc.textFile('1_movie_rating/ml-100k/u1.base')\ndef parseline(line):\n\tline_split = line.split()\n\treturn (line_split[0], int(line_split[2]))\n\nuser_ratings = lines.map(parseline)\n\nuser_ratings = user_ratings.groupByKey().collect() #return a list\nprint ('\\n\\n\\n======')\nprint (len(user_ratings))\n\nuser_ratings_sorted = sorted(user_ratings, key=lambda x: int(x[0]))\nfor item in user_ratings_sorted:\n\tprint (item[0], len(item[1]))#one way to find out the number of values for each key\n\n#use mapValues()\nuser_ratings = lines.map(parseline)\nave_ratings = user_ratings.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y: (x[0]+y[0], x[1]+y[1])).mapValues(lambda x: x[0]/x[1]).collect()\n\nave_ratings = sorted(ave_ratings, key = lambda x: x[1]) #sort the list in rating ascending order\nfor item in ave_ratings:\n\tprint (item)\n\nprint ('======\\n\\n\\n')\n\n\n#======= 1 =======\n#in standalone system\nfrom pyspark import SparkConf, SparkContext\nconf = SparkConf().setMaster('local').setAppName('my_test')\nsc = SparkContext(conf=conf)\n\nlines = sc.textFile('1_movie_rating/ml-100k/u1.base')\nratings = lines.map(lambda line: line.split()[1])\nresult = ratings.countByValue() #result is a dictionary\n\nresult_sorted = sorted(result.items(), key=lambda x: x[1]) #sort by value\nprint (type(result_sorted))\nfor i in result_sorted:\n\tprint (i)\n\n\n\"\"\"\n","repo_name":"zhao1157/Big_Data","sub_path":"Learning_PySpark.py","file_name":"Learning_PySpark.py","file_ext":"py","file_size_in_byte":7260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18581582947","text":"import os\nimport platform\n\nfrom twisted.internet import defer\n\nfrom . import data\nfrom p2pool.util import math, pack\n\nnets = dict(\n ###Neisklar: IMPORTANT!!!!!!!!!!!!!1111!!11einself\n ### The SUBSIDY_FUNC is NOT correctly in terms of keeping the minimum 1 QRK\n ### Reward for the end of the regular mining period. Means: it will work now\n ### and some time in the future. I think a simple max(..., 1) around it will fix it\n ### Maybe the dust threshold should also be rised somewhat, since we only have 5 decimals...\n quarkcoin=math.Object(\n P2P_PREFIX='fea503dd'.decode('hex'),\n P2P_PORT=19994,\n ADDRESS_VERSION=58,\n RPC_PORT=9994,\n RPC_CHECK=defer.inlineCallbacks(lambda bitcoind: defer.returnValue(\n 'quarkaddress' in (yield bitcoind.rpc_help()) and\n not (yield bitcoind.rpc_getinfo())['testnet']\n )),\n SUBSIDY_FUNC=lambda height: 2048*100000000 >> (height + 1)//60480,\n BLOCKHASH_FUNC=lambda data: pack.IntType(256).unpack(__import__('quark_hash').getPoWHash(data)),\n POW_FUNC=lambda data: pack.IntType(256).unpack(__import__('quark_hash').getPoWHash(data)),\n BLOCK_PERIOD=30, # s\n SYMBOL='QRK',\n CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'Quarkcoin') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/Quarkcoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.quarkcoin'), 'quarkcoin.conf'),\n BLOCK_EXPLORER_URL_PREFIX='http://qrk.blockr.io/block/info/',\n ADDRESS_EXPLORER_URL_PREFIX='http://qrk.blockr.io/address/info/',\n TX_EXPLORER_URL_PREFIX='http://qrk.blockr.io/tx/info/',\n SANE_TARGET_RANGE=(2**256//2**32//1000 - 1, 2**256//2**20 - 1),\n DUMB_SCRYPT_DIFF=1,\n DUST_THRESHOLD=0.001e8,\n ),\n monetaryunit=math.Object(\n P2P_PREFIX='04050504'.decode('hex'),\n P2P_PORT=19963,\n ADDRESS_VERSION=15,\n RPC_PORT=9963,\n RPC_CHECK=defer.inlineCallbacks(lambda bitcoind: defer.returnValue(\n 'monetaryunitaddress' in (yield bitcoind.rpc_help()) and\n not (yield bitcoind.rpc_getinfo())['testnet']\n )),\n\tSUBSIDY_FUNC=lambda height: 40*100000000 >> (height + 1)//320001,\n BLOCKHASH_FUNC=lambda data: pack.IntType(256).unpack(__import__('quark_hash').getPoWHash(data)),\n POW_FUNC=lambda data: pack.IntType(256).unpack(__import__('quark_hash').getPoWHash(data)),\n BLOCK_PERIOD=40, # s\n SYMBOL='MUE',\n CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'monetaryunit') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/monetaryunit/') if platform.system() == 'Darwin' else os.path.expanduser('~/.monetaryunit'), 'monetaryunit.conf'),\n BLOCK_EXPLORER_URL_PREFIX='https://chainz.cryptoid.info/mue/block.dws?',\n ADDRESS_EXPLORER_URL_PREFIX='https://chainz.cryptoid.info/mue/address.dws?',\n TX_EXPLORER_URL_PREFIX='https://chainz.cryptoid.info/mue/tx.dws?',\n SANE_TARGET_RANGE=(2**256//2**32//1000 - 1, 2**256//2**20 - 1),\n DUMB_SCRYPT_DIFF=1,\n DUST_THRESHOLD=0.001e8,\n ),\n\n)\nfor net_name, net in nets.iteritems():\n net.NAME = net_name\n","repo_name":"amarian12/p2pool.monetary","sub_path":"p2pool/bitcoin/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17403419444","text":"import json\nimport os\n\n\n# JSON file management class\nclass IO:\n def __init__(self, name):\n self.name = name\n self.create()\n\n def store(self, obj, inputData):\n data = self.read()\n if obj.name.lower() not in data.keys():\n data[obj.name.lower()] = inputData\n print(f\"Stored: {obj.name}\")\n else:\n print(f\"Exists: {obj.name}\")\n with open(self.name, \"w\") as f:\n json.dump(data, f, indent=4)\n\n def read(self):\n self.create()\n with open(self.name, \"r\") as f:\n data = json.load(f)\n return data\n\n def create(self):\n dir = self.name.split(\"/\")[0]\n if not os.path.exists(dir):\n os.mkdir(dir)\n with open(self.name, \"a+\") as f:\n f.seek(0)\n content = f.read()\n if content == \"\":\n json.dump({}, f, indent=4)\n","repo_name":"isaac238/StarWarsAPI","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72188818134","text":"import sys\nsys.stdin = open(\"./input.txt\", \"rt\")\ninput = sys.stdin.readline\n\nINF = int(10e8)\ndef compare(K):\n cnt, bal = 1, 0\n for i in range(n):\n if bal + arr[i] <= K:\n bal += arr[i]\n else:\n bal = arr[i]\n cnt += 1\n return cnt\n\nif __name__ == '__main__':\n n, m = map(int, input().split())\n arr = [int(input()) for _ in range(n)]\n res = None\n\n lt, rt = max(arr), INF\n while lt <= rt:\n mid = (lt + rt) // 2\n\n t = compare(mid)\n if t > m:\n lt = mid + 1\n else:\n res = mid\n rt = mid - 1\n print(res)","repo_name":"Heongilee/CodingTestStudy","sub_path":"Heongilee/2106__/210609/6236.py","file_name":"6236.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16020466085","text":"\"\"\"Internal representation of dataset in numpy, pandas and csr formats.\"\"\"\n\nimport warnings\n\nfrom copy import copy\nfrom copy import deepcopy\nfrom typing import Any\nfrom typing import Callable\nfrom typing import List\nfrom typing import Optional\nfrom typing import Sequence\nfrom typing import Tuple\nfrom typing import TypeVar\nfrom typing import Union\n\nimport numpy as np\nimport pandas as pd\n\nfrom pandas import DataFrame\nfrom pandas import Series\nfrom scipy import sparse\n\nfrom ..tasks.base import Task\nfrom .base import IntIdx\nfrom .base import LAMLColumn\nfrom .base import LAMLDataset\nfrom .base import RolesDict\nfrom .base import valid_array_attributes\nfrom .np_pd_dataset import CSRSparseDataset\nfrom .np_pd_dataset import NumpyDataset\nfrom .np_pd_dataset import PandasDataset\nfrom .roles import ColumnRole\n\n\nNpFeatures = Union[Sequence[str], str, None]\nNpRoles = Union[Sequence[ColumnRole], ColumnRole, RolesDict, None]\nDenseSparseArray = Union[np.ndarray, sparse.csr_matrix]\nFrameOrSeries = Union[DataFrame, Series]\nDataset = TypeVar(\"Dataset\", bound=LAMLDataset)\nRowSlice = Optional[Union[Sequence[int], Sequence[bool]]]\nColSlice = Optional[Union[Sequence[str], str]]\n\n\nclass SeqNumpyPandasDataset(PandasDataset):\n \"\"\"Sequential Dataset, that contains info in pd.DataFrame format.\"\"\"\n\n _dataset_type = \"SeqNumpyPandasDataset\"\n\n def _check_dtype(self):\n \"\"\"Check if dtype in .set_data is ok and cast if not.\"\"\"\n date_columns = []\n\n self.dtypes = {}\n for f in self.roles:\n if self.roles[f].name == \"Datetime\":\n date_columns.append(f)\n else:\n self.dtypes[f] = self.roles[f].dtype\n\n self.data = self.data.astype(self.dtypes)\n self.data.reset_index(drop=True, inplace=True)\n # do we need to reset_index ?? If yes - drop for Series attrs too\n # case to check - concat pandas dataset and from numpy to pandas dataset\n # TODO: Think about reset_index here\n # self.data.reset_index(inplace=True, drop=True)\n\n # handle dates types\n for i in date_columns:\n dt_role = self.roles[i]\n if not (self.data.dtypes[i] is np.datetime64):\n self.data[i] = pd.to_datetime(\n self.data[i], format=dt_role.format, unit=dt_role.unit, origin=dt_role.origin, cache=True\n )\n\n self.dtypes[i] = np.datetime64\n\n @property\n def idx(self) -> Any:\n \"\"\"Get idx attribute.\n\n Returns:\n Any, array like or ``None``.\n\n \"\"\"\n return self._idx\n\n @idx.setter\n def idx(self, val: Any):\n \"\"\"Set idx array or ``None``.\n\n Args:\n val: Some idx or ``None``.\n\n \"\"\"\n self._idx = val\n\n def _initialize(self, task: Optional[Task], **kwargs: Any):\n \"\"\"Initialize empty dataset with task and array like attributes.\n\n Args:\n task: Task name for dataset.\n **kwargs: 1d arrays like attrs like target, group etc.\n\n \"\"\"\n assert all([x in valid_array_attributes for x in kwargs]), \"Unknown array attribute. Valid are {0}\".format(\n valid_array_attributes\n )\n\n self.task = task\n # here we set target and group and so ...\n self._array_like_attrs = []\n for k in kwargs:\n self._array_like_attrs.append(k)\n self.__dict__[k] = kwargs[k]\n\n # checks for valid values in target, groups ...\n for check in self._init_checks:\n check(self)\n\n # set empty attributes\n self._idx = None\n self._data = None\n self._features = []\n self._roles = {}\n\n def __init__(\n self,\n data: Optional[DenseSparseArray],\n features: NpFeatures = (),\n roles: NpRoles = None,\n idx: List = (),\n task: Optional[Task] = None,\n name: Optional[str] = \"seq\",\n scheme: Optional[dict] = None,\n **kwargs: np.ndarray\n ):\n \"\"\"Create dataset from `pd.DataFrame` and `pd.Series`.\n\n Args:\n data: Table with features.\n features: features names.\n roles: Roles specifier.\n idx: sequential indexes. Each element consists of corresponding sequence in data table.\n task: Task specifier.\n name: name of currnet dataset.\n scheme: dict of relations of current dataset with others.\n **kwargs: Series, array like attrs target, group etc...\n\n \"\"\"\n self.name = name\n if scheme is not None:\n self.scheme = scheme\n else:\n self.scheme = {}\n\n self._initialize(task, **kwargs)\n if data is not None:\n self.set_data(data, roles, idx)\n\n def set_data(self, data: DenseSparseArray, roles: NpRoles = None, idx: Optional[List] = None):\n \"\"\"Inplace set data, features, roles for empty dataset.\n\n Args:\n data: 2d array like or ``None``.\n roles: roles dict.\n idx: list.\n\n \"\"\"\n # assert data is None or type(data) is np.ndarray, 'Numpy dataset support only np.ndarray features'\n super().set_data(data, None, roles)\n if idx is None:\n idx = np.arange(len(data)).reshape(-1, 1)\n self.idx = idx\n self._check_dtype()\n\n def __len__(self):\n return len(self.idx)\n\n def _get_cols_idx(self, columns: Union[Sequence[str], str]) -> Union[Sequence[int], int]:\n \"\"\"Get numeric index of columns by column names.\n\n Args:\n columns: sequence of columns of single column.\n\n Returns:\n sequence of int indexes or single int.\n\n \"\"\"\n if type(columns) is str:\n idx = self.data.columns.get_loc(columns)\n\n else:\n idx = self.data.columns.get_indexer(columns)\n\n return idx\n\n def __getitem__(self, k: Tuple[RowSlice, ColSlice]) -> Union[\"LAMLDataset\", LAMLColumn]:\n \"\"\"Select a subset of dataset.\n\n Define how to slice a dataset\n in way ``dataset[[1, 2, 3...], ['feat_0', 'feat_1'...]]``.\n Default behavior based on ``._get_cols``, ``._get_rows``, ``._get_2d``.\n\n Args:\n k: First element optional integer columns indexes,\n second - optional feature name or list of features names.\n\n Returns:\n Subset.\n\n \"\"\"\n # TODO: Maybe refactor this part?\n if type(k) is tuple:\n rows, cols = k\n if isinstance(cols, str):\n cols = [cols]\n else:\n rows = k\n cols = None\n\n is_slice = False\n if isinstance(rows, slice):\n is_slice = True\n\n rows = [rows] if isinstance(rows, int) else np.arange(self.__len__()) if isinstance(rows, slice) else rows\n temp_idx = self.idx[rows]\n rows = []\n idx_new = []\n _c = 0\n for i in temp_idx:\n rows.extend(list(i))\n idx_new.append(list(np.arange(len(i)) + _c))\n _c += len(i)\n idx_new = np.array(idx_new, dtype=object)\n\n rows = np.array(sorted(list(set(rows))))\n\n if is_slice:\n idx_new = self.idx\n rows = np.arange(len(self.data))\n else:\n warnings.warn(\n \"Resulted sequential dataset may have different structure. It's not recommended to slice new dataset\"\n )\n\n # case when columns are defined\n if cols is not None:\n idx = self._get_cols_idx(cols)\n data = self._get_2d(self.data, (rows, idx))\n\n # case of multiple columns - return LAMLDataset\n roles = dict(((x, self.roles[x]) for x in self.roles if x in cols))\n else:\n roles = self.roles\n data = self._get_rows(self.data, rows)\n\n # case when rows are defined\n if rows is None:\n dataset = self.empty()\n else:\n dataset = copy(self)\n params = dict(((x, self._get_rows(self.__dict__[x], rows)) for x in self._array_like_attrs))\n dataset._initialize(self.task, **params)\n\n dataset.set_data(data, roles, idx=idx_new)\n\n return dataset\n\n def to_sequence(self, k: Tuple[RowSlice, ColSlice] = None) -> Union[\"LAMLDataset\", LAMLColumn]:\n \"\"\"Select a subset of dataset and transform it to sequence.\n\n Define how to slice a dataset in way ``dataset[[1, 2, 3...], ['feat_0', 'feat_1'...]]``.\n Default behavior based on ``._get_cols``, ``._get_rows``, ``._get_2d``.\n\n Args:\n k: First element optional integer columns indexes,\n second - optional feature name or list of features names.\n\n Returns:\n Numpy Dataset with new sequential dimension.\n\n \"\"\"\n self._check_dtype()\n if k is None:\n k = slice(None, None, None)\n\n # TODO: Maybe refactor this part?\n if type(k) is tuple:\n rows, cols = k\n if isinstance(cols, str):\n cols = [cols]\n else:\n rows = k\n cols = None\n\n rows = [rows] if isinstance(rows, int) else np.arange(self.__len__()) if isinstance(rows, slice) else rows\n\n # case when columns are defined\n if cols is not None:\n idx = self._get_cols_idx(cols)\n\n # case when seqs have different shape, return array with arrays\n if len(self.idx.shape) == 1:\n data = []\n _d = self.data.iloc[:, idx].values\n for row in rows:\n data.append(_d[self.idx[row]])\n data = np.array(data, dtype=object)\n else:\n data = self._get_3d(self.data, (self.idx[rows], idx))\n\n # case of multiple columns - return LAMLDataset\n roles = dict(((x, self.roles[x]) for x in self.roles if x in cols))\n features = [x for x in cols if x in set(self.features)]\n else:\n roles, features = self.roles, self.features\n\n if len(self.idx.shape) == 1:\n data = []\n _d = self.data.values\n for row in rows:\n data.append(_d[self.idx[row]])\n data = np.array(data, dtype=object)\n else:\n data = self._get_3d(self.data, (self.idx[rows], self._get_cols_idx(self.data.columns)))\n\n # case when rows are defined\n if rows is None:\n dataset = NumpyDataset(None, features, deepcopy(roles), task=self.task)\n else:\n dataset = NumpyDataset(data, features, deepcopy(roles), task=self.task)\n\n return dataset\n\n def apply_func(self, k: Tuple[RowSlice, ColSlice] = None, func: Callable = None) -> np.ndarray:\n \"\"\"Apply function to each sequence.\n\n Args:\n k: First element optional integer columns indexes,\n second - optional feature name or list of features names.\n func: any callable function\n\n Returns:\n output np.ndarray\n\n \"\"\"\n self._check_dtype()\n if k is None:\n k = slice(None, None, None)\n\n # TODO: Maybe refactor this part?\n if type(k) is tuple:\n rows, cols = k\n if isinstance(cols, str):\n cols = [cols]\n else:\n rows = k\n cols = None\n\n rows = [rows] if isinstance(rows, int) else np.arange(self.__len__()) if isinstance(rows, slice) else rows\n\n # case when columns are defined\n if cols is not None:\n idx = self._get_cols_idx(cols)\n\n # case when seqs have different shape, return array with arrays\n data = []\n _d = self.data.iloc[:, idx].values\n for row in rows:\n data.append(func(_d[self.idx[row]]))\n data = np.array(data)\n else:\n data = []\n _d = self.data.values\n for row in rows:\n data.append(func(_d[self.idx[row]]))\n data = np.array(data)\n\n return data\n\n @classmethod\n def _get_2dT(cls, data: np.ndarray, k: Tuple[IntIdx, IntIdx]) -> np.ndarray:\n \"\"\"Get 2d slice.\n\n Args:\n data: Data.\n k: Tuple of integer sequences.\n\n Returns:\n 2d slice.\n\n \"\"\"\n rows, cols = k\n\n return data[rows][:, cols]\n\n @classmethod\n def _get_3d(cls, data: np.ndarray, k: Tuple[IntIdx, IntIdx]) -> np.ndarray:\n \"\"\"Get 3d slice.\n\n Args:\n data: Data.\n k: Tuple of integer sequences.\n\n Returns:\n 3d slice.\n\n \"\"\"\n rows, cols = k\n\n return data.iloc[:, cols].values[rows]\n\n def to_csr(self) -> \"CSRSparseDataset\":\n \"\"\"Convert to csr.\n\n # noqa: DAR202\n Returns:\n Same dataset in CSRSparseDatatset format.\n\n \"\"\"\n raise NotImplementedError\n\n def to_numpy(self) -> \"NumpyDataset\":\n \"\"\"Convert to class:`NumpyDataset`.\n\n Returns:\n Same dataset in class:`NumpyDataset` format without sequential features.\n\n \"\"\"\n # check for empty\n data = None if self.data is None else self.data.values\n roles = self.roles\n features = self.features\n # target and etc ..\n params = dict(((x, self.__dict__[x].values) for x in self._array_like_attrs))\n task = self.task\n\n return NumpyDataset(data, features, roles, task, **params)\n\n def to_pandas(self) -> \"PandasDataset\":\n \"\"\"Convert to plain PandasDataset.\n\n Returns:\n Same dataset in PandasDataset format without sequential features.\n\n \"\"\"\n # check for empty case\n data = None if self.data is None else DataFrame(self.data, columns=self.features)\n roles = self.roles\n # target and etc ..\n params = dict(((x, Series(self.__dict__[x])) for x in self._array_like_attrs))\n task = self.task\n\n return PandasDataset(data, roles, task, **params)\n\n @classmethod\n def concat(cls, datasets: Sequence[\"LAMLDataset\"]) -> \"LAMLDataset\":\n \"\"\"Concat multiple dataset.\n\n Default behavior - takes empty dataset from datasets[0]\n and concat all features from others.\n\n Args:\n datasets: Sequence of datasets.\n\n Returns:\n Concated dataset.\n\n \"\"\"\n for check in cls._concat_checks:\n check(datasets)\n\n idx = datasets[0].idx\n dataset = datasets[0].empty()\n data = []\n features = []\n roles = {}\n\n atrs = set(dataset._array_like_attrs)\n for ds in datasets:\n data.append(ds.data)\n features.extend(ds.features)\n roles = {**roles, **ds.roles}\n for atr in ds._array_like_attrs:\n if atr not in atrs:\n dataset._array_like_attrs.append(atr)\n dataset.__dict__[atr] = ds.__dict__[atr]\n atrs.update({atr})\n\n data = cls._hstack(data)\n dataset.set_data(data, roles, idx=idx)\n\n return dataset\n","repo_name":"sb-ai-lab/LightAutoML","sub_path":"lightautoml/dataset/seq_np_pd_dataset.py","file_name":"seq_np_pd_dataset.py","file_ext":"py","file_size_in_byte":15125,"program_lang":"python","lang":"en","doc_type":"code","stars":640,"dataset":"github-code","pt":"67"} +{"seq_id":"19179524217","text":"from flask import Flask, render_template, request, flash, redirect, url_for\nimport json, os,datetime,sys\n\napp = Flask(__name__,template_folder='templates')\napp.secret_key = '\\xe0\\xb8]\\xff\\xe8oA\\x1a\\x01x\\x17vQ\\x85\\xf2\\xf3?BC\\xba'\n\nprofiles_path = './contributors/'\nprofiles = os.listdir(profiles_path)\n# print(profiles)\n\nclass profile:\n def __init__(self,name,avatar,cover,lang,github,linkedin,twitter):\n self.name = name\n self.avatar = avatar\n self.cover = cover\n self.lang = lang\n self.github = github\n self.linkedin = linkedin\n self.twitter = twitter\n \ncontributors = []\n\nfor p in profiles:\n with open(profiles_path + p, 'r') as c:\n params = json.load(c)\n contributors.append( profile(params['name'],params['avatar'],params['cover'],params['lang'],params['github'],params['linkedin'],params['twitter']) )\n\nnow = datetime.datetime.now()\ncurr_yr = now.year\n\n@app.route('/')\ndef home():\n return render_template('index.html',contributors=contributors,curr_yr=curr_yr)\n\nif __name__==\"__main__\":\n app.run(debug=False)\n\n","repo_name":"pinakipb2/contrib-here","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"7147269820","text":"from django.contrib.auth import get_user_model\nfrom django.urls import include, path\nfrom rest_framework import status\nfrom rest_framework.reverse import reverse\nfrom rest_framework.test import APIClient, APITestCase, URLPatternsTestCase\n\nfrom recipes.models import (Favorite, Ingredient, IngredientRecipeRelation,\n Recipe, Tag)\n\nUser = get_user_model()\n\n\nclass APITests(APITestCase, URLPatternsTestCase):\n urlpatterns = [\n path('api/', include('api.urls')),\n ]\n fixtures = ('users.json', 'recipes.json',)\n\n user: User\n recipe: Recipe\n\n user_client: APIClient\n anon_client: APIClient\n\n keys_post_detail: list\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n\n cls.recipe = cls.recipe = Recipe.objects.all().first()\n cls.user = cls.recipe.author\n\n cls.keys_post_detail = sorted(\n ['id', 'name', 'image', 'cooking_time'])\n\n @classmethod\n def tearDownClass(cls):\n IngredientRecipeRelation.objects.all().delete()\n Tag.objects.all().delete()\n Ingredient.objects.all().delete()\n Recipe.objects.all().delete()\n User.objects.all().delete()\n\n def setUp(self):\n self.anon_client = APIClient()\n\n self.user_client = APIClient()\n self.user_client.force_authenticate(user=self.user)\n\n def tearDown(self):\n Favorite.objects.all().delete()\n\n def test_user_favorites_add_item(self):\n \"\"\"Авторизованные пользователи. Добавить рецепт в избранное.\"\"\"\n\n endpoint = reverse('api:favorites', args=(self.recipe.pk,))\n recipes_in_cart_count = Favorite.objects.all().count()\n\n response = self.user_client.post(endpoint)\n recipes_in_cart_count_1 = Favorite.objects.all().count()\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(sorted(response.data.keys()), self.keys_post_detail)\n self.assertEqual(recipes_in_cart_count_1, recipes_in_cart_count + 1)\n self.assertEqual(self.user.favorites.get().recipe, self.recipe)\n\n response = self.user_client.post(endpoint)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(\n Favorite.objects.all().count(), recipes_in_cart_count_1)\n\n def test_user_favorites_delete_item(self):\n \"\"\"Авторизованные пользователи. Удалить рецепт из избранного.\"\"\"\n\n endpoint = reverse('api:favorites', args=(self.recipe.pk,))\n Favorite.objects.create(user=self.user, recipe=self.recipe)\n recipes_in_cart_count = Favorite.objects.all().count()\n self.assertEqual(recipes_in_cart_count, 1)\n\n response = self.user_client.delete(endpoint)\n recipes_in_cart_count_1 = Favorite.objects.all().count()\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n self.assertEqual(recipes_in_cart_count_1, recipes_in_cart_count - 1)\n\n response = self.user_client.delete(endpoint)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(\n Favorite.objects.all().count(), recipes_in_cart_count_1)\n","repo_name":"cianoid/foodgram-project-react","sub_path":"backend/foodgram/api/tests/test_favorites.py","file_name":"test_favorites.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"9276711551","text":"def bubble_sort(elements):\r\n size=len(elements)\r\n for i in range(size-1):\r\n swap=False\r\n for j in range(size-1-i):\r\n if elements[j]>elements[j+1]:\r\n elements[j], elements[j+1]= elements[j+1], elements[j]\r\n swap=True\r\n if not swap:\r\n break\r\n \r\n\r\nelements=[]\r\nsize = int(input(\"Enter the size of array: \"))\r\nfor i in range(size):\r\n value=int(input(\"Enter the elements in array: \"))\r\n elements.append(value)\r\n\r\nbubble_sort(elements)\r\nprint(\"Sorted Array: \")\r\nfor i in range(size): \r\n print(elements[i], end=' ') ","repo_name":"iamhozu/Bubble-sort-algorithm-using-python","sub_path":"bubblrSort.py","file_name":"bubblrSort.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"32147586368","text":"####################################################################\n#\n# https://stackoverflow.com/questions/25777037/how-can-i-left-justify-text-in-a-pandas-dataframe-column-in-an-ipython-notebook\n#\n####################################################################\n\nimport mplfinance as mpf\nimport pandas as pd\nimport textwrap\n\nvk = mpf.plotting._valid_plot_kwargs()\n\ndf = (pd.DataFrame(vk).T.head(18)).drop('Validator',axis=1)\n\ndf['Kwarg'] = df.index.values\ndf['Default'] = [\"'\"+d+\"'\" if isinstance(d,str) else str(d) for d in df['Default']]\n\ndf = df[['Kwarg','Default','Description']]\ndf = df.head(5).append(df.tail(7))\n\n# df.sort_index(inplace=True)\n\ndf \n\nprint('===========================')\n\nprint(df)\n\nprint('===========================')\n\ndef make_left_formatter(maxwidth):\n wm3 = maxwidth-3\n w = maxwidth\n def left_formatter(value):\n if not isinstance(value,str):\n return f'{value:<}'\n elif value[0:maxwidth] == '-'*maxwidth:\n return f'{value:<{w}.{w}s}'\n #elif len(value) > maxwidth and value[0:maxwidth] != '-'*maxwidth:\n elif len(value) > maxwidth:\n return f'{value:<{wm3}.{wm3}s}...'\n else:\n return f'{value:<{w}.{w}s}'\n return left_formatter\n\ndef df_wrapcols(df,wrap_columns=None):\n\n if wrap_columns is None: return df\n if not isinstance(wrap_columns,dict):\n raise TypeError('wrap_columns must be a dict of column_names and wrap_lengths')\n\n for col in wrap_columns:\n if col not in df.columns:\n raise ValueError('column \"'+str(col)+'\" not found in df.columns')\n\n index = []\n column_data = {}\n for col in df.columns:\n column_data[col] = []\n \n for ix in df.index:\n row = df.loc[ix,]\n \n row_data = {}\n for col in row.index:\n cstr = str(row[col])\n if col in wrap_columns:\n wlen = wrap_columns[col]\n tw = textwrap.wrap(cstr,wlen) if not cstr.isspace() else [' ']\n else:\n tw = [cstr]\n row_data[col] = tw\n\n cmax = max(row_data,key=lambda k: len(row_data[k]))\n rlen = len(row_data[cmax])\n for r in range(rlen):\n for col in row.index:\n extension = [' ']*(rlen - len(row_data[col]))\n row_data[col].extend(extension)\n column_data[col].append(row_data[col][r])\n ixstr = str(ix)+'.'+str(r) if r > 0 else str(ix)\n index.append(ixstr)\n\n return pd.DataFrame(column_data,index=index)\n\nWRAPLEN = 55\n\ndf = df_wrapcols(df,wrap_columns={'Description':WRAPLEN})\nprint('===========================')\nprint('dfnew1=',df)\n\n\n# print('===========================')\n# df.columns = [ ' '+col for col in df.columns ]\n\ndividers = []\nfor col in df.columns:\n dividers.append('-'*int(df[col].str.len().max()))\ndfd = pd.DataFrame(dividers).T\ndfd.columns = df.columns\ndfd.index = pd.Index(['---'])\n\nprint('===========================')\n\ndf = dfd.append(df)\n\nfmts = {'Kwarg': make_left_formatter(df['Kwarg'].str.len().max()+1),\n 'Description': make_left_formatter(WRAPLEN),\n 'Default': make_left_formatter(8),\n }\ns = df.to_string(formatters=fmts,index=False,justify='left')\n\nprint('\\n ',s.replace('\\n','\\n '))\n\nprint('===========================')\n\n","repo_name":"matplotlib/mplfinance","sub_path":"examples/scratch_pad/fmtr.py","file_name":"fmtr.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","stars":3080,"dataset":"github-code","pt":"67"} +{"seq_id":"7891859060","text":"\"\"\"\nProduces a (Newick-formatted) hierarchical clustering tree\nAnd annotation metadata in ITOL-readable format\nFor visualisation on: https://itol.embl.de/\n\nA note on laverania:\n - All of the other `seq_stats` analyses use MSAs computed on P. falciparum only, not other laverania species. This is normal: sharing, sequence logos, conversion clusters are all defined with respect to the falciparum gene pool\n - We also want to add laverania sequences to the analysis, here, and thus expect an MSA with laverania sequences.\n - For plotting the metadata though (especially the fraction of shared kmers in each sequence), we load the original falciparum-only MSA and compute the stats on that.\n\"\"\"\nimport sqlite3\nfrom itertools import tee\nfrom typing import List, Tuple, Dict\nfrom pathlib import Path\n\nfrom Bio.Align import MultipleSeqAlignment as MSA\nfrom Bio import AlignIO\nfrom scipy.cluster.hierarchy import linkage, to_tree\nfrom scipy.spatial.distance import pdist\nimport click\n\nfrom plasmo_paralogs.common_utils import VALID_SEQTYPES, ID_DELIM\nfrom plasmo_paralogs.common_utils import (\n REGION_CLICK_HELP,\n REGION_DELIM,\n VALID_SQLITE_DATA,\n)\nfrom plasmo_paralogs.common_utils.msa import (\n split_alignment_by_gene,\n get_gene_name,\n get_sample_id,\n)\nfrom plasmo_paralogs.common_utils.sqlite import (\n get_sqlite_table_name,\n load_percent_identities,\n)\nfrom plasmo_paralogs.common_utils.metrics import MetricsRecorder\nfrom plasmo_paralogs.common_utils.mosaic import Donors, parse_mosaic_alignment_file\nfrom plasmo_paralogs.seq_stats.sharing import load_kmer_sharing_mapping\nfrom plasmo_paralogs.common_utils.sequences import get_pos_tuple, extract_kmer\n\n\nLAV_SPECIES = [\"P. praefalciparum\", \"P. reichenowi\", \"P. billcollinsi\", \"P. falciparum\"]\n\n\ndef get_species_name(record):\n species_map = {\n \"PPRFG01\": LAV_SPECIES[0],\n \"PPRFG02\": LAV_SPECIES[0],\n \"PPRFG03\": LAV_SPECIES[0],\n \"PPRFG04\": LAV_SPECIES[0],\n \"PRG01\": LAV_SPECIES[1],\n \"PREICH001\": LAV_SPECIES[1],\n \"PBILCG01\": LAV_SPECIES[2],\n }\n sample_name = record.id.split(ID_DELIM)[-1].strip()\n return species_map.get(sample_name, LAV_SPECIES[3])\n\n\ndef load_MSA(msa_fname: str, start: int, end: int):\n with open(msa_fname) as fhandle_in:\n alignment = AlignIO.read(fhandle_in, \"fasta\")\n alignment = alignment[:, start - 1 : end]\n for record in alignment:\n record.id = record.id.split(\"::\")[0]\n return alignment\n\n\ndef get_split_alignments(alignment, seq_names_to_include, SHARED_ID, dedup=True):\n if dedup:\n alignment = deduplicate(alignment, seq_names_to_include=seq_names_to_include)\n split_alignments = split_alignment_by_gene(alignment)\n split_alignments[SHARED_ID] = alignment\n return split_alignments\n\n\ndef pairwise(iterable):\n # pairwise('ABCDEFG') --> AB BC CD DE EF FG\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\nSeqNames = List[str]\nNewick = str\nPROTEIN_CHARS = {\n \"A\",\n \"C\",\n \"D\",\n \"E\",\n \"F\",\n \"G\",\n \"H\",\n \"I\",\n \"K\",\n \"L\",\n \"M\",\n \"N\",\n \"P\",\n \"Q\",\n \"R\",\n \"S\",\n \"T\",\n \"V\",\n \"W\",\n \"Y\",\n \"-\",\n}\nPROT_TO_INT = {char: i for i, char in enumerate(PROTEIN_CHARS)}\n\nconvert_prot_to_int = lambda prot_seq: [PROT_TO_INT[char] for char in prot_seq]\n\n\nclass FracShared(MetricsRecorder):\n _headers = [\"sample_ID\", \"frac_shared\"]\n _required_headers = _headers\n\n\nclass NodeLinks(MetricsRecorder):\n _headers = [\"sample_ID_1\", \"sample_ID_2\", \"width\", \"color\", \"style\", \"label\"]\n _required_headers = _headers\n\n\ndef deduplicate(msa: MSA, seq_names_to_include: SeqNames = []) -> MSA:\n unique_seqs = set()\n seq_names_to_include = set(seq_names_to_include)\n result = MSA([])\n for record in msa:\n seq = str(record.seq)\n if record.id in seq_names_to_include and seq not in unique_seqs:\n unique_seqs.add(seq)\n result.append(record)\n for record in msa:\n seq = str(record.seq)\n if seq not in unique_seqs:\n unique_seqs.add(seq)\n result.append(record)\n return result\n\n\ndef tree2newick(node, newick, parentdist, leaf_names):\n \"\"\"\n Taken from: https://gist.github.com/fbkarsdorp/a5d95f7ccc8c308a70c93aff38ac4860\n [Note] For the corresponding feature request in scipy, see https://github.com/scipy/scipy/issues/8274\n \"\"\"\n if node.is_leaf():\n return f\"{leaf_names[node.id]}:{parentdist - node.dist:.2f}{newick}\"\n else:\n if len(newick) > 0:\n newick = f\"):{parentdist - node.dist:.2f}{newick}\"\n else:\n newick = \");\"\n newick = tree2newick(node.get_left(), newick, node.dist, leaf_names)\n newick = tree2newick(node.get_right(), f\",{newick}\", node.dist, leaf_names)\n newick = f\"({newick}\"\n return newick\n\n\ndef newick_from_msa(msa: MSA) -> Newick:\n leaf_names = []\n int_seqs = []\n for record in msa:\n int_seq = convert_prot_to_int(str(record.seq))\n int_seqs.append(int_seq)\n leaf_names.append(record.id)\n distances = pdist(int_seqs, metric=\"hamming\")\n linkages = linkage(distances, method=\"average\")\n tree = to_tree(linkages)\n result = tree2newick(tree, \"\", tree.dist, leaf_names)\n return result\n\n\ndef compute_and_write_frac_shared(\n msa: MSA, kmer_sharing_mapping, kmer_size, region_start, gene_dir\n) -> None:\n result = list()\n for record in msa:\n sharing_array = []\n seq = str(record.seq)\n for start, center_pos, stop in get_pos_tuple(kmer_size, [seq], region=None):\n kmer_seq = extract_kmer(seq, start, stop)\n kmer_mapping_key = f\"{center_pos+region_start-1}{ID_DELIM}{kmer_seq}\"\n sharing_array.append(int(kmer_sharing_mapping[kmer_mapping_key]))\n result.append(\n FracShared(\n sample_ID=record.id, frac_shared=sum(sharing_array) / len(sharing_array)\n )\n )\n with (gene_dir / f\"frac_shared.txt\").open(\"w\") as fout:\n fout.write(\"DATASET_GRADIENT\\n\")\n fout.write(\"SEPARATOR TAB\\n\")\n fout.write(f\"DATASET_LABEL\\tFraction of shared {kmer_size}-mer peptides\\t1\\n\")\n fout.write(\"COLOR\\t#ff0000\\n\")\n fout.write(\"MARGIN\\t10\\n\")\n fout.write(\"BORDER_WIDTH\\t4\\n\")\n fout.write(\"BORDER_COLOR\\t#000000\\n\")\n fout.write(\"COLOR_MIN\\t#e02582\\n\")\n # fout.write(\"COLOR_MIN\\t#cb0b0b\\n\")\n fout.write(\"COLOR_MAX\\t#14ee14\\n\")\n fout.write(\"DATA\\n\")\n for entry in result:\n fout.write(str(entry))\n\n\ndef compute_and_write_recomb_links(donors: Donors, outdir, gene_name=None):\n result = list()\n for target_ID, donor_list in donors.items():\n for e1, e2 in pairwise(donor_list):\n result.append(\n NodeLinks(\n sample_ID_1=e1.seq_ID,\n sample_ID_2=e2.seq_ID,\n width=4,\n color=\"#8C99A6\",\n style=\"dashed\",\n label=target_ID,\n )\n )\n with (outdir / f\"recomb_links.txt\").open(\"w\") as fout:\n fout.write(\"DATASET_CONNECTION\\n\")\n fout.write(\"SEPARATOR TAB\\n\")\n fout.write(f\"DATASET_LABEL\\tSample pairs that recombined\\n\")\n fout.write(\"COLOR\\t#ff0000\\n\")\n fout.write(\"CENTER_CURVES\\t1\\n\")\n fout.write(\"ALIGN_TO_LABELS\\t1\\n\")\n fout.write(\"DRAW_ARROWS\\t0\\n\")\n fout.write(\"MAXIMUM_LINE_WIDTH\\t4\\n\")\n fout.write(\"DATA\\n\")\n for entry in result:\n fout.write(str(entry))\n\n\ndef write_gene_colours(msa: MSA, gene_dir):\n colour_map = {\"DBLMSP\": \"#efbd24\", \"DBLMSP2\": \"#3d85c6\"}\n all_colours = \"\\t\".join(colour_map.values())\n all_labels = \"\\t\".join(colour_map.keys())\n with (gene_dir / f\"gene_colours.txt\").open(\"w\") as fout:\n fout.write(\"DATASET_COLORSTRIP\\n\")\n fout.write(\"SEPARATOR TAB\\n\")\n fout.write(f\"DATASET_LABEL\\tGene\\n\")\n fout.write(\"COLOR\\t#ff0000\\n\")\n fout.write(\"BORDER_WIDTH\\t4\\n\")\n fout.write(\"BORDER_COLOR\\t#000000\\n\")\n fout.write(f\"LEGEND_TITLE\\tGene\\n\")\n fout.write(f\"LEGEND_COLORS\\t{all_colours}\\n\")\n fout.write(f\"LEGEND_LABELS\\t{all_labels}\\n\")\n fout.write(f\"LEGEND_SHAPES\\t1\\t1\\n\")\n fout.write(\"DATA\\n\")\n for record in msa:\n gene_name = get_gene_name(record)\n colour = colour_map[gene_name]\n fout.write(f\"{record.id}\\t{colour}\\t{gene_name}\\n\")\n\n\ndef write_species_colours(msa: MSA, gene_dir):\n colour_map = {\n LAV_SPECIES[0]: \"#0008e8\",\n LAV_SPECIES[1]: \"#0096ff\",\n LAV_SPECIES[2]: \"#00e8c4\",\n LAV_SPECIES[3]: \"#8a03ff\",\n # LAV_SPECIES[3]: \"#cc0000\",\n }\n all_colours = \"\\t\".join(colour_map.values())\n all_labels = \"\\t\".join(colour_map.keys())\n with (gene_dir / f\"species_colours.txt\").open(\"w\") as fout:\n fout.write(\"DATASET_COLORSTRIP\\n\")\n fout.write(\"SEPARATOR TAB\\n\")\n fout.write(f\"DATASET_LABEL\\tSpecies\\n\")\n fout.write(\"COLOR\\t#ff0000\\n\")\n fout.write(\"MARGIN\\t10\\n\")\n fout.write(\"BORDER_WIDTH\\t4\\n\")\n fout.write(\"BORDER_COLOR\\t#000000\\n\")\n fout.write(f\"LEGEND_TITLE\\tSpecies\\n\")\n fout.write(f\"LEGEND_COLORS\\t{all_colours}\\n\")\n fout.write(f\"LEGEND_LABELS\\t{all_labels}\\n\")\n fout.write(f\"LEGEND_SHAPES\\t1\\t1\\t1\\t1\\n\")\n fout.write(\"DATA\\n\")\n for record in msa:\n species_name = get_species_name(record)\n colour = colour_map[species_name]\n fout.write(f\"{record.id}\\t{colour}\\t{species_name}\\n\")\n\n\ndef write_premature_stops(msa: MSA, gene_dir):\n colour_map = {True: \"#2B0000\", False: \"#FFCCAA\"}\n all_colours = \"\\t\".join(colour_map.values())\n all_labels = \"\\t\".join(map(str,colour_map.keys()))\n with (gene_dir / f\"premature_stops.txt\").open(\"w\") as fout:\n fout.write(\"DATASET_COLORSTRIP\\n\")\n fout.write(\"SEPARATOR TAB\\n\")\n fout.write(f\"DATASET_LABEL\\tPremature_stops\\n\")\n fout.write(\"COLOR\\t#ff0000\\n\")\n fout.write(\"MARGIN\\t10\\n\")\n fout.write(\"BORDER_WIDTH\\t4\\n\")\n fout.write(\"BORDER_COLOR\\t#000000\\n\")\n fout.write(f\"LEGEND_TITLE\\tProtein has premature stop codon(s)\\n\")\n fout.write(f\"LEGEND_COLORS\\t{all_colours}\\n\")\n fout.write(f\"LEGEND_LABELS\\t{all_labels}\\n\")\n fout.write(f\"LEGEND_SHAPES\\t1\\t1\\n\")\n fout.write(\"DATA\\n\")\n for record in msa:\n premature_stop = \"STOP\" in record.id\n colour = colour_map[premature_stop]\n fout.write(f\"{record.id}\\t{colour}\\t{premature_stop}\\n\")\n\n\ndef write_percent_identities(msa: MSA, percent_identities, gene_dir) -> None:\n with (gene_dir / f\"percent_identities.txt\").open(\"w\") as fout:\n fout.write(\"DATASET_GRADIENT\\n\")\n fout.write(\"SEPARATOR TAB\\n\")\n fout.write(\n f\"DATASET_LABEL\\tFraction of identical codons between paralogs in sample\\t1\\n\"\n )\n fout.write(\"COLOR\\t#ff0000\\n\")\n fout.write(\"MARGIN\\t10\\n\")\n fout.write(\"COLOR_MIN\\t#0000ff\\n\")\n fout.write(\"COLOR_MAX\\t#ff0000\\n\")\n fout.write(\"DATA\\n\")\n for record in msa:\n sample_ID = get_sample_id(record)\n if sample_ID in percent_identities:\n fout.write(f\"{record.id}\\t{percent_identities[sample_ID]}\\n\")\n\n\n@click.command()\n@click.argument(\"msa_fname\")\n@click.argument(\"dir_ofname\")\n@click.option(\"-s\", \"--sqlite_db_fpath\", required=True)\n@click.option(\"--seqtype\", required=True, type=click.Choice(VALID_SEQTYPES))\n@click.option(\"--seq_region\", type=str, required=True, help=REGION_CLICK_HELP)\n@click.option(\n \"--kmer_sizes\",\n type=str,\n help=\"kmer sizes to compute; comma-delimited\",\n default=\"10\",\n show_default=True,\n)\n@click.option(\"-m\", \"--mosaic_alignment_fname\")\ndef main(\n msa_fname,\n dir_ofname,\n sqlite_db_fpath,\n seqtype,\n seq_region,\n kmer_sizes,\n mosaic_alignment_fname,\n):\n SHARED_ID = \"DBs\"\n start, end = map(int, seq_region.split(REGION_DELIM))\n outdir = Path(dir_ofname)\n outdir.mkdir(exist_ok=True, parents=True)\n\n # Load MSA, with laverania\n alignment = load_MSA(msa_fname, start, end)\n\n # Load MSA, without laverania\n msa_fname_no_laverania = msa_fname.replace(\"_and_laverania\", \"\").replace(\"_and_premature_stops\",\"\")\n alignment_no_laverania = load_MSA(msa_fname_no_laverania, start, end)\n\n # Load and compute mosaic-recomb links\n if mosaic_alignment_fname is not None:\n recomb_donors = parse_mosaic_alignment_file({}, mosaic_alignment_fname, True)\n compute_and_write_recomb_links(recomb_donors, outdir)\n\n # Load percent identities\n dna_msa_fname = msa_fname_no_laverania.replace(VALID_SEQTYPES[0], VALID_SEQTYPES[1])\n table_name = get_sqlite_table_name(\n dna_msa_fname,\n SHARED_ID,\n VALID_SEQTYPES[1],\n metric_info=VALID_SQLITE_DATA[5],\n seq_region=seq_region,\n )\n percent_identities = load_percent_identities(sqlite_db_fpath, table_name, SHARED_ID)\n percent_identities = {\n key: val for key, val in percent_identities.items() if val > 0.5\n }\n high_shared_samples = []\n for sample_ID in percent_identities:\n for gene_name in [\"DBLMSP\", \"DBLMSP2\"]:\n high_shared_samples.append(f\"{gene_name}{ID_DELIM}{sample_ID}\")\n\n seq_names_to_include = list(recomb_donors.keys()) + high_shared_samples\n split_alignments = get_split_alignments(alignment, seq_names_to_include, SHARED_ID)\n # Write trees\n region_for_output = f\"{start}{ID_DELIM}{end}\"\n for gene_name, gene_alignment in split_alignments.items():\n gene_dir = Path(outdir) / f\"{gene_name}{ID_DELIM}{region_for_output}\"\n gene_dir.mkdir(exist_ok=True)\n tree = newick_from_msa(gene_alignment)\n with (gene_dir / \"clustering_tree.nwk\").open(\"w\") as fout:\n fout.write(tree)\n\n assert len(kmer_sizes.split(\",\")) == 1\n ## Load kmer sharing stats\n con = sqlite3.connect(sqlite_db_fpath)\n input_table_name = get_sqlite_table_name(\n msa_fname_no_laverania, SHARED_ID, seqtype, metric_info=VALID_SQLITE_DATA[2]\n )\n kmer_sharing_mapping = load_kmer_sharing_mapping(input_table_name, con)\n con.close()\n\n ## Write additional data for trees\n for gene_name, gene_alignment in split_alignments.items():\n gene_dir = Path(outdir) / f\"{gene_name}{ID_DELIM}{region_for_output}\"\n write_percent_identities(gene_alignment, percent_identities, gene_dir)\n if gene_name == SHARED_ID:\n write_gene_colours(gene_alignment, gene_dir)\n write_species_colours(gene_alignment, gene_dir)\n write_premature_stops(gene_alignment, gene_dir)\n\n split_alignments_no_laverania = get_split_alignments(\n alignment_no_laverania, seq_names_to_include, SHARED_ID, dedup=False\n )\n for gene_name, gene_alignment in split_alignments_no_laverania.items():\n compute_and_write_frac_shared(\n gene_alignment, kmer_sharing_mapping, int(kmer_sizes), start, gene_dir\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"iqbal-lab-org/paper_pfalciparum_DBs","sub_path":"plasmo_paralogs/analysis/scripts/plasmo_paralogs/plotting/plot_clustering_trees.py","file_name":"plot_clustering_trees.py","file_ext":"py","file_size_in_byte":15150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"8305320271","text":"#this is a function to solve the dictionaries problem on Rosalind-Python set\n\ndef wordcnt():\n\t#get string chop into words\n\ts = input(\"Please input string of interest: \")\n\tlst = s.split(\" \")\n\tsetlst = set(lst)\n\tprint(lst, \"\\n\", setlst, \"\\n\")\n\t\n\t#open dictionary\n\tdiction = {}\n\tc = 0\n\tfor i in setlst:\n\t\tfor j in lst:\n\t\t\tif i == j:\n\t\t\t\tc += 1\n\t\t\t\tdiction[i] = c\n\t\tc = 0\t\n\tprint(diction, \"\\n\")\n\tfor i in diction:\n\t\tprint(i+\" \"+str(diction[i]))\nwordcnt()\n\t\n","repo_name":"crysclitheroe/Rosalind","sub_path":"Python_Village/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36995770678","text":"import random\nfrom scipy import spatial\nimport numpy as np\n\nclass Points:\n def __init__(self,chain):\n\n self.chain = chain\n self.zero_point = [0,0,0]\n self.points = np.array([[0.,0.,0.]]*len(self.chain))\n self.points_vel = np.array([[0.,0.,0.]]*len(self.chain))\n\n self.bounds = 0\n for i in range(len(self.chain)):\n for j in range(self.chain[i]._segment_count):\n self.bounds += self.chain[i]._segments[j]._segment_length\n\n self.step = self.bounds/(len(self.points)+1.)\n\n self.prox_size = self.step/2\n\n for i in range(len(self.points)):\n self.points[i] = [self.step*(i+1),0.,0.]\n\n\n def line_separation(self):\n total_pos_arr = []\n\n total_pos = np.subtract(self.zero_point[0],self.points[0])\n total_pos += np.subtract(self.points[1],self.points[0])\n\n length = np.linalg.norm(total_pos)\n if(length==0):\n total_pos_arr.append(np.array([0,0,0]))\n else:\n total_pos_arr.append(total_pos/length)\n\n for i in range(1,(len(self.points)-1)):\n total_pos = np.subtract(self.points[i-1],self.points[i])\n total_pos += np.subtract(self.points[i+1],self.points[i])\n length = np.linalg.norm(total_pos)\n if(length==0):\n total_pos_arr.append(np.array([0,0,0]))\n else:\n total_pos_arr.append(total_pos/length)\n\n total_pos = np.subtract(self.points[len(self.points)-2],self.points[len(self.points)-1])\n total_pos += np.subtract(self.points[len(self.points)-3],self.points[len(self.points)-1])\n\n length = np.linalg.norm(total_pos)\n if(length==0):\n total_pos_arr.append(np.array([0,0,0]))\n else:\n total_pos_arr.append(total_pos/length)\n\n\n self.separate = np.array([-1,-1,-1]*np.array(total_pos_arr))\n\n return self.separate\n\n def line_cohesion(self):\n avg_pos_arr = []\n avg_pos = (self.points[1]/2)-self.points[0]\n avg_pos_arr.append(avg_pos)\n length = np.linalg.norm(avg_pos_arr[0])\n if length == 0:\n avg_pos_arr[0] = np.array([0,0,0])\n else:\n avg_pos_arr[0] = avg_pos_arr[0]\n\n for i in range(1,(len(self.points)-1)):\n avg_pos = ((self.points[i-1]+self.points[i+1])/2)-self.points[i]\n avg_pos_arr.append(avg_pos)\n length = np.linalg.norm(avg_pos_arr[i])\n if length ==0:\n avg_pos_arr[i] = np.array([0,0,0])\n else:\n avg_pos_arr[i] = avg_pos_arr[i]\n\n #avg_pos = ((self.points[len(self.points)-2]+self.points[len(self.points)-3])/2)-self.points[len(self.points)-1]\n #avg_pos_arr.append(avg_pos)\n\n avg_pos_arr.append(np.array([0,0,0]))\n self.cohesion = avg_pos_arr\n return self.cohesion\n\n\n def separation(self):\n tree = spatial.cKDTree(self.points)\n is_close = tree.query_ball_tree(tree,self.prox_size)\n\n can_see_pos = [self.points[i] for i in is_close]\n total_pos_arr = []\n\n for i in range(len(self.points)):\n total_pos = np.sum(np.subtract(can_see_pos[i],self.points[i]),axis=0)\n length = np.linalg.norm(total_pos)\n if(length==0):\n total_pos_arr.append(np.array([0,0,0]))\n else:\n total_pos_arr.append(total_pos/length)\n\n self.separate = np.array([-1,-1,-1]*np.array(total_pos_arr))\n\n return self.separate\n\n def cohese(self):\n self.cohesion = []\n for i in range(len(self.points)):\n distance_from = np.subtract(np.array([self.step*(i+1),0,0]),self.points[i])\n length = np.linalg.norm(distance_from)\n if(length == 0):\n self.cohesion.append(np.array([0,0,0]))\n else:\n self.cohesion.append(distance_from/length)\n\n return self.cohesion\n\n #Weights is [random,separation,cohesion]\n def update(self,weights):\n\n self.separation()\n self.cohese()\n\n for i in range(len(self.points)):\n for j in range(3):\n if self.points_vel[i][j] > 2:\n self.points_vel[i][j] = 2\n elif self.points_vel[i][j] < -2:\n self.points_vel[i][j] = -2\n\n self.points_vel[i] = self.points_vel[i] + self.separate[i]*weights[1] + self.cohesion[i]*weights[2]\n\n self.points_vel[i] = [self.points_vel[i][0]+random.uniform(-self.bounds*weights[0],self.bounds*weights[0]),self.points_vel[i][1]+random.uniform(-self.bounds*weights[0],self.bounds*weights[0]),self.points_vel[i][2]+random.uniform(-self.bounds*weights[0],self.bounds*weights[0])]\n\n self.points[i] = self.points[i]+self.points_vel[i]\n return self.points\n\nif __name__ == \"__main__\":\n from segment2 import ConstLineSegment,CircleSegment\n from chain2 import CompositeSegment, FittingChain\n from scipy.optimize import Bounds\n from matplotlib import pyplot as plt\n import mpl_toolkits.mplot3d.axes3d as p3\n import matplotlib.animation as animation\n from matplotlib import animation\n\n segment_list = []\n\n segment_list.append(ConstLineSegment(10))\n segment_list.append(CircleSegment(100,0.2,np.pi/2,))\n\n chain_segments = [CompositeSegment(segment_list=segment_list) for _ in range(5)]\n\n bounds = Bounds(np.array([-2*np.pi+0.01,-np.inf]*5),\n np.array([2*np.pi-0.01,np.inf]*5),\n keep_feasible=True)\n\n chain = FittingChain(segment_list=chain_segments,\n bounds=bounds)\n\n points = Points(chain_segments)\n\n\n fig = plt.figure()\n ax = p3.Axes3D(fig)\n scatter, = ax.plot([],[],[],'bo',ms=6)\n\n def init():\n scatter.set_data([],[])\n scatter.set_3d_properties([])\n return scatter,\n\n def animate(i):\n\n goal_points = points.update([.001,.05,.2])\n scatter.set_data(goal_points[:,0],goal_points[:,1])\n scatter.set_3d_properties(goal_points[:,2])\n return scatter,\n\n ax.set_xlabel(\"X(mm)\")\n ax.set_ylabel(\"Y(mm)\")\n ax.set_zlabel(\"Z(mm)\")\n ax.set_xlim3d([0,500])\n ax.set_ylim3d([-250,250])\n ax.set_zlim3d([-250,250])\n\n anim = animation.FuncAnimation(fig,animate,init_func=init, interval=20,frames=500)\n #anim.save('videos/fly.mp4',fps=20)\n plt.show()\n","repo_name":"MasonDMitchell/pose-chain","sub_path":"points.py","file_name":"points.py","file_ext":"py","file_size_in_byte":6368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28347630571","text":"import astroid\nfrom pylint.checkers import BaseChecker\nfrom pylint.interfaces import IAstroidChecker\n\n\ndef register(linter):\n linter.register_checker(JflyChecker(linter))\n\nclass JflyChecker(BaseChecker):\n \"\"\" This checker makes sure you have no variables named jfly \"\"\"\n\n __implements__ = IAstroidChecker\n\n name = 'j3-no-jfly'\n priority = -1\n msgs = {\n # The current largest \"real\" warning code is W1662\n 'W5000': (\n \"Has a variable named 'jfly'\", # (displayed-message, what shows up on any violations)\n 'j3-no-jfly', # (message-symbol, can be used with `pylintdisable=` to silence it)\n \"Please do not call any of your variables 'jfly'\", # (message-help, will show in `pylint --list-msgs`)\n ),\n }\n options = (\n (\n 'j3-no-jfly',\n {\n 'default': True,\n 'type': 'yn',\n 'metavar': '',\n 'help': \"Forbid variables named 'jfly'\",\n },\n ),\n )\n\n def visit_assignname(self, node: astroid.node_classes.AssignName):\n \"\"\" Make sure that any callable nodes are not named print.\n\n Because we only have access to the AST, we technically cannot\n know if the callable named `print` is *actually* going to be\n __builtins__.print at runtime. That's fine, though, since\n `redefined-builtin` should catch any obvious reassignments\n of the print.\n\n For example, this checker *cannot* detect:\n\n say = print\n say(\"Hello\")\n\n It can detect:\n\n print(\"Hello\")\n\n If we want to forbid referencing the `print` built-in whatsoever, this\n is very possible! See the way that pylint enforces other \"bad\" builtins.\n \"\"\"\n if not self.config.j3_no_jfly:\n return\n\n if node.name == \"jfly\":\n self.add_message('j3-no-jfly', node=node)\n","repo_name":"jfly/pylint-demo","sub_path":"custom_checker/no_jfly.py","file_name":"no_jfly.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20059942245","text":"import sys\r\nn = int(input())\r\na = [set()]\r\nfor _ in range(n):\r\n a[0].add(input())\r\n\r\ndef rep(a):\r\n for s in a:\r\n if s == a[len(a)-1]:\r\n return True\r\n return False\r\n\r\ndef rp(s1, s2, pd, d):\r\n s = set()\r\n for c1 in s1:\r\n for c2 in s2:\r\n if len(c2) > len(c1) and c1 == c2[:len(c1)]:\r\n s.add(c2[len(c1):])\r\n d[c2[len(c1):]] = min(d.get(c2[len(c1):], 100000000000000), pd.get(c2, 0) + len(c1))\r\n elif len(c1) > len(c2) and c2 == c1[:len(c2)]:\r\n s.add(c1[len(c2):])\r\n d[c1[len(c2):]] = min(d.get(c1[len(c2):], 100000000000000), pd.get(c2, 0) + len(c2))\r\n return s\r\n\r\ni = 1\r\npd, d = dict(), dict()\r\nwhile True:\r\n if i == 1:\r\n s = rp(a[0], a[i-1], pd, d) - {0}\r\n else:\r\n s = rp(a[0], a[i-1], pd, d)\r\n # print(s, d)\r\n if len(s & a[0]) > 0:\r\n mc = 100000000000000\r\n for c in s & a[0]:\r\n mc = min(mc, d[c]+len(c))\r\n print(mc)\r\n sys.exit()\r\n for j in range(1, i):\r\n if s == a[j]:\r\n print(0)\r\n sys.exit()\r\n a.append(s)\r\n i += 1\r\n pd = d.copy()","repo_name":"hmku/icpc","sub_path":"wi21_quals/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16766174581","text":"#!/usr/bin/env python\n# Minhyuk Sung (mhsung@cs.stanford.edu)\n# April 2018\n\nimport os, sys\nBASE_DIR = os.path.normpath(\n os.path.join(os.path.dirname(os.path.abspath(__file__))))\nsys.path.append(os.path.join(BASE_DIR, '..'))\n\nfrom global_variables import *\nfrom datasets import *\nfrom datetime import datetime\nfrom generate_outputs import *\nfrom network import Network\nfrom network_sem_seg import NetworkSemSeg\nfrom train_util import validate, train\nimport argparse\nimport numpy as np\nimport evaluate\nimport evaluate_keypoints\nimport evaluate_obj_det\nimport evaluate_sem_seg\nimport random\nimport tensorflow as tf\n\n\n'''\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--exp_type', type=str, default='ours',\\\n choices=['ours', 'sem_seg'])\nparser.add_argument('--eval_type', action='append', default=['eval'],\n help='[eval, eval_keypoints, eval_obj_det, save_dict]')\n\nparser.add_argument('--net_options', action='append', default=['softmax', 'use_stn'],\n help='[softmax, column_softmax, sigmoid, clip_A, use_stn, pointnet2]')\n\nparser.add_argument('--in_model_dirs', type=str, default='', help='')\nparser.add_argument('--in_model_scopes', type=str, default='', help='')\nparser.add_argument('--out_model_dir', type=str, default='model', help='')\nparser.add_argument('--out_dir', type=str, default='outputs', help='')\nparser.add_argument('--log_dir', type=str, default='log', help='')\n\nparser.add_argument('--train', action=\"store_true\", help='')\nparser.add_argument('--init_learning_rate', type=float, default=0.001,\\\n help='Initial learning rate [default: 0.001]')\nparser.add_argument('--decay_step', type=int, default=200000,\\\n help='Decay step for lr decay [default: 200000]')\nparser.add_argument('--decay_rate', type=float, default=0.7,\\\n help='Decay rate for lr decay [default: 0.7]')\nparser.add_argument('--bn_decay_step', type=int, default=200000,\\\n help='Decay step for bn decay [default: 200000]')\n\nparser.add_argument('--n_epochs', type=int, default=1000,\\\n help='Number of epochs')\nparser.add_argument('--batch_size', type=int, default=32,\\\n help='Batch size')\nparser.add_argument('--snapshot_epoch', type=int, default=100,\\\n help='Interval of snapshot')\nparser.add_argument('--validation_epoch', type=int, default=10,\\\n help='Interval of validation')\n\nparser.add_argument('--K', type=int, default=10,\\\n help='Number of predicted basis functions [default: 10]')\nparser.add_argument('--l21_norm_weight', type=float, default=0.0,\n help='L2,1 norm regularizer weight [default: 0.0]')\n\nparser.add_argument('--part_removal_fraction', type=float, default=0.0,\n help='Fraction of parts to be removed [default: 0.0]')\nparser.add_argument('--indicator_noise_probability', type=float, default=0.0,\n help='Probability of adding noise in indicator functions [default: 0.0]')\n\nargs = parser.parse_args()\n'''\n\n\ndef load_model(sess, in_model_dir, include=''):\n # Read variables names in checkpoint.\n var_names = [x for x,_ in tf.contrib.framework.list_variables(in_model_dir)]\n\n # Find variables with given names.\n # HACK:\n # Convert unicode to string and remove postfix ':0'.\n var_list = [x for x in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\\\n if str(x.name)[:-2] in var_names]\n\n if include != '':\n var_list = [x for x in var_list if include in x.name]\n #print([x.name for x in var_list])\n\n saver = tf.train.Saver(var_list)\n\n ckpt = tf.train.get_checkpoint_state(in_model_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n print (\"Loaded '{}'.\".format(ckpt.model_checkpoint_path))\n else:\n print (\"Failed to loaded '{}'.\".format(in_model_dir))\n return False\n return True\n\n\ndef run(args, train_data, val_data, test_data):\n tf.set_random_seed(1234)\n np.random.seed(1234)\n random.seed(1234)\n\n print('\\n==== PARAMS ====')\n for arg in vars(args):\n print('{}={}'.format(arg, getattr(args, arg)))\n print('========\\n')\n\n\n if args.exp_type == 'ours':\n net = Network(train_data.n_points, train_data.n_dim,\n test_data.n_seg_ids, args.K, args.batch_size,\n args.init_learning_rate, args.decay_step, args.decay_rate,\n args.bn_decay_step, args.l21_norm_weight, args.net_options)\n elif args.exp_type == 'sem_seg':\n print(\"## Sementic Segmentation ##\")\n net = NetworkSemSeg(train_data.n_points, train_data.n_dim,\n train_data.n_labels, args.batch_size, args.init_learning_rate,\n args.decay_step, args.decay_rate, args.bn_decay_step,\n args.net_options)\n else:\n assert(False)\n\n\n config = tf.ConfigProto()\n config.allow_soft_placement = True\n config.gpu_options.allow_growth = True\n\n with tf.Session(config=config, graph=net.graph) as sess:\n sess.run(tf.global_variables_initializer(), {net.is_training: True})\n\n if args.in_model_dirs:\n include = ''\n for in_model_dir in args.in_model_dirs.split(','):\n assert(load_model(sess, in_model_dir, include))\n\n if args.train:\n train(sess, net, args.exp_type, train_data, val_data,\n n_epochs=args.n_epochs, snapshot_epoch=args.snapshot_epoch,\n validation_epoch=args.validation_epoch,\n model_dir=args.out_model_dir, log_dir=args.log_dir,\n data_name=train_data.name, output_generator=None)\n\n train_loss, _ = validate(sess, net, args.exp_type, train_data)\n test_loss, _ = validate(sess, net, args.exp_type, test_data)\n\n msg = \"|| Train Loss: {:6f}\".format(train_loss)\n msg += \" | Test Loss: {:6f}\".format(test_loss)\n msg += \" ||\"\n print(msg)\n\n if args.train:\n # Save training result.\n if not os.path.exists(args.out_dir): os.makedirs(args.out_dir)\n out_file = os.path.join(args.out_dir, '{}.txt'.format(\n datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")))\n with open(out_file, 'w') as f:\n f.write(msg + '\\n')\n print(\"Saved '{}'.\".format(out_file))\n\n if args.exp_type == 'ours':\n if 'eval' in args.eval_type:\n evaluate.evaluate(sess, net, test_data, args.out_dir)\n if 'eval_keypoints' in args.eval_type:\n evaluate_keypoints.evaluate(sess, net, test_data, args.out_dir)\n if 'eval_obj_det' in args.eval_type:\n evaluate_obj_det.evaluate(sess, net, test_data, args.out_dir)\n if 'save_dict' in args.eval_type:\n P = test_data.point_clouds\n A = predict_A(P, sess, net)\n out_file = os.path.join(args.out_dir, 'dictionary.npy')\n np.save(out_file, A)\n print(\"Saved '{}'\".format(out_file))\n elif args.exp_type == 'sem_seg':\n evaluate_sem_seg.evaluate(sess, net, test_data, args.out_dir)\n\n","repo_name":"mhsung/deep-functional-dictionaries","sub_path":"network/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7070,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"67"} +{"seq_id":"22640327508","text":"# -*- coding: utf-8 -*-\n\n'''\nclodss: keys-related functions\n'''\n\nimport re\nimport time\n\nfrom .common import SEP, _clearexpired\n\n\ndef _keyexists(db, key):\n for k, _ in db[key.encode('utf-8'):]:\n if k == key.encode('utf-8') or k.startswith(\n f'{key}{SEP}'.encode('utf-8')):\n return True\n break\n return False\n\n\ndef get(instance, key):\n 'https://redis.io/commands/get'\n db = instance.router.connection(key).db()\n try:\n return instance.makevalue(db[key])\n except KeyError:\n return None\n\n\ndef sēt(instance, key, value):\n 'https://redis.io/commands/set'\n db = instance.router.connection(key).db()\n db[key] = value\n\n\ndef delete(instance, key):\n 'https://redis.io/commands/del'\n db = instance.router.connection(key).db()\n for k, _ in db[key:]:\n if k == key.encode('utf-8') or k.startswith(\n f'{key}{SEP}'.encode('utf-8')):\n del db[k]\n else:\n break\n\n\ndef expire(instance, key, duration: float) -> int:\n 'https://redis.io/commands/expire'\n db = instance.router.connection(key).db()\n if not _keyexists(db, key):\n print('key doesnt exist', key)\n return 0\n expiretime = duration + time.time()\n db[f'{SEP}expire{SEP}{key}'] = expiretime\n instance.keystoexpire[key] = expiretime\n return 1\n\n\ndef persist(instance, key) -> int:\n 'https://redis.io/commands/persist'\n db = instance.router.connection(key).db()\n if not _keyexists(db, key):\n return 0\n if instance.checkexpired(key) != 'scheduled':\n return 0\n _clearexpired(instance, db, key)\n return 1\n\n\ndef incr(instance, key, amount=1):\n 'https://redis.io/commands/incr'\n db = instance.router.connection(key).db()\n try:\n val = db[key]\n except KeyError:\n val = 0\n try:\n val = int(val)\n except ValueError as e:\n raise TypeError('invalid numeric %s' %val) from e\n newval = val + amount\n db[key] = newval\n return newval\n\n\ndef incrby(instance, key, amount):\n 'https://redis.io/commands/incrby'\n return incr(instance, key, amount)\n\n\ndef decr(instance, key, amount=1):\n 'https://redis.io/commands/decr'\n db = instance.router.connection(key).db()\n try:\n val = db[key]\n except KeyError:\n val = 0\n try:\n val = int(val)\n except ValueError as e:\n raise TypeError('invalid numeric %s' %val) from e\n newval = int(val) - amount\n db[key] = newval\n return newval\n\n\ndef decrby(instance, key, amount):\n 'https://redis.io/commands/decrby'\n return decr(instance, key, amount)\n\n\ndef flushdb(instance):\n 'https://redis.io/commands/flushdb'\n instance.reset()\n\n\ndef keys(instance, pattern='*', checkexpired=True):\n '''\n https://redis.io/commands/keys\n generator function, non standard parameter `checkexpired` allows disabling\n expiry check, which improves performance but will return keys which should\n be expired\n '''\n pattern = pattern.replace('*', '.*')\n regex = re.compile(pattern)\n sep = SEP.encode('utf-8')\n yielded_compounds = set()\n for db in instance.router.allconnections():\n for k, _ in db.db():\n if checkexpired and instance.checkexpired(\n k.decode('utf-8'), enforce=True) is True:\n continue\n compound = sep in k\n k = k.split(sep)[0]\n if not k:\n continue\n if compound:\n if k in yielded_compounds:\n continue\n yielded_compounds.add(k)\n if regex.match(k.decode('utf-8')):\n yield instance.makevalue(k)\n\n\ndef scan(instance, cursor=None, match='*'):\n '''\n https://redis.io/commands/scan\n currently is the same as `keys`\n '''\n\n if cursor not in (None, True):\n raise ValueError('invalid cursor %r' %cursor)\n\n if cursor is True:\n return []\n\n return True, keys(instance, match)\n","repo_name":"codomatech/clodss","sub_path":"clodss/keys.py","file_name":"keys.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"39003471010","text":"import os\nimport shutil\nfrom PIL import Image\nimport argparse\nimport random\n\ndef copy_images(base_folder, out_folder, min_width, min_height):\n # Check if output directories exist; if not, create them\n landscape_dir = os.path.join(out_folder, 'landscape')\n portrait_dir = os.path.join(out_folder, 'portrait')\n\n if not os.path.exists(landscape_dir):\n os.makedirs(landscape_dir)\n if not os.path.exists(portrait_dir):\n os.makedirs(portrait_dir)\n\n current_seed = None\n\n # Walk through the base directory\n for dirpath, dirnames, filenames in os.walk(base_folder):\n for filename in filenames:\n if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff')):\n full_path = os.path.join(dirpath, filename)\n\n # Check image dimensions using PIL\n with Image.open(full_path) as img:\n width, height = img.size\n\n # Check if the image dimensions are above the minimum dimensions\n if width > min_width and height > min_height:\n destination_dir = landscape_dir if width > height else portrait_dir\n destination_path = os.path.join(destination_dir, filename)\n\n # Roll a new seed if needed\n if os.path.exists(destination_path):\n current_seed = random.randint(1000, 1001000)\n \n new_filename = f\"{current_seed}_{filename}\" if current_seed and os.path.exists(destination_path) else filename\n destination_path = os.path.join(destination_dir, new_filename)\n\n shutil.copy2(full_path, destination_path)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Sort images into portrait and landscape folders.')\n parser.add_argument('--folder', required=True, help='Base folder containing images.')\n parser.add_argument('--out', required=True, help='Output directory where images should be copied.')\n parser.add_argument('--minWidth', type=int, default=0, help='Minimum width of images to be copied.')\n parser.add_argument('--minHeight', type=int, default=0, help='Minimum height of images to be copied.')\n\n args = parser.parse_args()\n\n copy_images(args.folder, args.out, args.minWidth, args.minHeight)\n","repo_name":"Ryan-Haines/ai-utils","sub_path":"data_collection/copy_sort_images.py","file_name":"copy_sort_images.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"33947925362","text":"import logging\n\nfrom rx import disposable\nfrom rx.core import typing\nfrom rx.disposable import SingleAssignmentDisposable, CompositeDisposable\nfrom rx.concurrency.schedulerbase import SchedulerBase\n\nlog = logging.getLogger(\"Rx\")\n\n\nclass QtScheduler(SchedulerBase):\n \"\"\"A scheduler for a PyQt4/PyQt5/PySide event loop.\"\"\"\n\n def __init__(self, qtcore):\n self.qtcore = qtcore\n self._timers = set()\n\n def _qtimer_schedule(self, time, action, state, periodic=False):\n scheduler = self\n msecs = int(self.to_seconds(time)*1000.0)\n\n sad = SingleAssignmentDisposable()\n\n periodic_state = [state]\n\n def interval():\n if periodic:\n periodic_state[0] = action(periodic_state[0])\n else:\n sad.disposable = action(scheduler, state)\n\n log.debug(\"timeout: %s\", msecs)\n\n timer = self.qtcore.QTimer()\n timer.setSingleShot(not periodic)\n timer.timeout.connect(interval)\n timer.setInterval(msecs)\n timer.start()\n self._timers.add(timer)\n\n def dispose():\n timer.stop()\n self._timers.remove(timer)\n\n return CompositeDisposable(sad, disposable.create(dispose))\n\n def schedule(self, action: typing.ScheduledAction, state: typing.TState = None) -> typing.Disposable:\n \"\"\"Schedules an action to be executed.\"\"\"\n return self._qtimer_schedule(0, action, state)\n\n def schedule_relative(self, duetime: typing.RelativeTime, action: typing.ScheduledAction,\n state: typing.TState = None) -> typing.Disposable:\n \"\"\"Schedules an action to be executed after duetime.\n\n Args:\n duetime: Relative time after which to execute the action.\n action: Action to be executed.\n\n Returns:\n The disposable object used to cancel the scheduled action\n (best effort).\n \"\"\"\n return self._qtimer_schedule(duetime, action, state)\n\n def schedule_absolute(self, duetime: typing.AbsoluteTime, action: typing.ScheduledAction,\n state: typing.TState = None) -> typing.Disposable:\n \"\"\"Schedules an action to be executed at duetime.\n\n Args:\n duetime: Absolute time after which to execute the action.\n action: Action to be executed.\n\n Returns:\n The disposable object used to cancel the scheduled action\n (best effort).\n \"\"\"\n\n duetime = self.to_datetime(duetime)\n return self._qtimer_schedule(duetime, action, state)\n\n def schedule_periodic(self, period: typing.RelativeTime, action: typing.ScheduledPeriodicAction,\n state: typing.TState = None):\n \"\"\"Schedules a periodic piece of work to be executed in the Qt\n mainloop.\n\n Args:\n period: Period in milliseconds for running the work\n periodically.\n action: Action to be executed.\n state: [Optional] Initial state passed to the action upon\n the first iteration.\n\n Returns:\n The disposable object used to cancel the scheduled\n recurring action (best effort).\n \"\"\"\n\n return self._qtimer_schedule(period, action, state, periodic=True)\n","repo_name":"Sammyalhashe/Capstone2","sub_path":"Charter/python-gui/venv/lib/python3.6/site-packages/rx/concurrency/mainloopscheduler/qtscheduler.py","file_name":"qtscheduler.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21495633052","text":"from metaswitch.sasclient.messages import Init\nfrom test_sasclient import SASClientTestCase\n\nTIMESTAMP = 1450180692598\nINIT_STRING_EMPTY = (\n '\\x00\\x19\\x03\\x01\\x00\\x00\\x01Q\\xa5\\x81Jv\\x00\\x01\\x00\\x00\\x00\\x04v0.1\\x00\\x00\\x00'\n)\nINIT_STRING_NONEMPTY = (\n '\\x00U\\x03\\x01\\x00\\x00\\x01Q\\xa5\\x81Jv\\x16ellis@ellis.cw-ngv.com\\x01\\x00\\x00\\x00\\x04v0.1'\n '\\x05ellis\\x1eorg.projectclearwater.20151201\\x031.1'\n)\n\n\nclass SASClientInitMessageTest(SASClientTestCase):\n \"\"\"\n Test the serialisation of Init messages. We test against recorded byte strings that we know to\n be correct.\n \"\"\"\n def test_empty_strings(self):\n init = Init('', '', '').set_timestamp(TIMESTAMP)\n self.assertEqual(init.serialize(), INIT_STRING_EMPTY)\n\n def test_nonempty_strings(self):\n init = Init(\"ellis@ellis.cw-ngv.com\", \"ellis\", \"org.projectclearwater.20151201\", '1.1')\n init.set_timestamp(TIMESTAMP)\n self.assertEqual(init.serialize(), INIT_STRING_NONEMPTY)\n # Now just check that __str__ doesn't throw\n self.assertGreater(len(str(init)), 0)\n","repo_name":"Metaswitch/sasclient.py","sub_path":"test/tests/test_sasclient_init_message.py","file_name":"test_sasclient_init_message.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"42730431042","text":"import argparse\n\nimport skorch\nimport torch\nfrom sklearn.model_selection import GridSearchCV\n\nimport data\nfrom model import RNNModel\nfrom net import Net\n\nparser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model')\nparser.add_argument('--data', type=str, default='./data/penn',\n help='location of the data corpus')\nparser.add_argument('--bptt', type=int, default=35,\n help='sequence length')\nparser.add_argument('--batch_size', type=int, default=20, metavar='N',\n help='batch size')\nparser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs')\nparser.add_argument('--data-limit', type=int, default=-1,\n help='Limit the input data to length N.')\nparser.add_argument('--seed', type=int, default=1111,\n help='random seed')\nparser.add_argument('--no-cuda', dest='cuda', action='store_false',\n help='use CUDA')\nparser.add_argument('--save', type=str, default='model.pt',\n help='path to save the final model')\nargs = parser.parse_args()\n\ntorch.manual_seed(args.seed)\n\ncorpus = data.Corpus(args.data)\nntokens = len(corpus.dictionary)\ndevice = 'cuda' if args.cuda else 'cpu'\n\nclass LRAnnealing(skorch.callbacks.Callback):\n def on_epoch_end(self, net, **kwargs):\n if not net.history[-1]['valid_loss_best']:\n net.lr /= 4.0\n\nclass ExamplePrinter(skorch.callbacks.Callback):\n def on_epoch_end(self, net, **kwargs):\n seed_sentence = \"the meaning of\"\n indices = [corpus.dictionary.word2idx[n] for n in seed_sentence.split()]\n indices = skorch.utils.to_tensor(\n torch.LongTensor([indices]).t(), device=device)\n sentence, _ = net.sample_n(num_words=10, input=indices)\n print(seed_sentence,\n \" \".join([corpus.dictionary.idx2word[n] for n in sentence]))\n\n\ndef my_train_split(ds, y):\n # Return (corpus.train, corpus.valid) in case the network\n # is fitted using net.fit(corpus.train).\n return ds, skorch.dataset.Dataset(corpus.valid[:200], y=None)\n\nnet = Net(\n module=RNNModel,\n max_epochs=args.epochs,\n batch_size=args.batch_size,\n device=device,\n callbacks=[\n skorch.callbacks.Checkpoint(),\n skorch.callbacks.ProgressBar(),\n LRAnnealing(),\n ExamplePrinter()\n ],\n module__rnn_type='LSTM',\n module__ntoken=ntokens,\n module__ninp=200,\n module__nhid=200,\n module__nlayers=2,\n\n # Use (corpus.train, corpus.valid) as validation split.\n # Even though we are doing a grid search, we use an internal\n # validation set to determine when to save (Checkpoint callback)\n # and when to decrease the learning rate (LRAnnealing callback).\n train_split=my_train_split,\n\n # To demonstrate that skorch is able to use already available\n # data loaders as well, we use the data loader from the word\n # language model.\n iterator_train=data.Loader,\n iterator_train__device=device,\n iterator_train__bptt=args.bptt,\n iterator_valid=data.Loader,\n iterator_valid__device=device,\n iterator_valid__bptt=args.bptt)\n\n\n# Demonstrate the use of grid search by testing different learning\n# rates while saving the best model at the end.\n\nparams = [\n {\n 'lr': [10,20,30],\n },\n]\n\npl = GridSearchCV(net, params)\n\npl.fit(corpus.train[:args.data_limit].numpy())\n\nprint(\"Results of grid search:\")\nprint(\"Best parameter configuration:\", pl.best_params_)\nprint(\"Achieved F1 score:\", pl.best_score_)\n\nprint(\"Saving best model to '{}'.\".format(args.save))\npl.best_estimator_.save_params(f_params=args.save)\n\n","repo_name":"skorch-dev/skorch","sub_path":"examples/word_language_model/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":5403,"dataset":"github-code","pt":"67"} +{"seq_id":"32753124339","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import Softmax\n\n\ndef INF(B,H,W):\n return -torch.diag(torch.tensor(float(\"inf\")).cuda().repeat(H),0).unsqueeze(0).repeat(B*W,1,1)\n\n\nclass CrissCrossAttention(nn.Module):\n \"\"\" Criss-Cross Attention Module\"\"\"\n def __init__(self, in_dim):\n super(CrissCrossAttention,self).__init__()\n self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1)\n self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1)\n self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1)\n self.softmax = Softmax(dim=3)\n self.INF = INF\n self.gamma = nn.Parameter(torch.zeros(1))\n\n\n def forward(self, x):\n m_batchsize, _, height, width = x.size()\n proj_query = self.query_conv(x)\n proj_query_H = proj_query.permute(0,3,1,2).contiguous().view(m_batchsize*width,-1,height).permute(0, 2, 1)\n proj_query_W = proj_query.permute(0,2,1,3).contiguous().view(m_batchsize*height,-1,width).permute(0, 2, 1)\n proj_key = self.key_conv(x)\n proj_key_H = proj_key.permute(0,3,1,2).contiguous().view(m_batchsize*width,-1,height)\n proj_key_W = proj_key.permute(0,2,1,3).contiguous().view(m_batchsize*height,-1,width)\n proj_value = self.value_conv(x)\n proj_value_H = proj_value.permute(0,3,1,2).contiguous().view(m_batchsize*width,-1,height)\n proj_value_W = proj_value.permute(0,2,1,3).contiguous().view(m_batchsize*height,-1,width)\n energy_H = (torch.bmm(proj_query_H, proj_key_H)+self.INF(m_batchsize, height, width)).view(m_batchsize,width,height,height).permute(0,2,1,3)\n energy_W = torch.bmm(proj_query_W, proj_key_W).view(m_batchsize,height,width,width)\n concate = self.softmax(torch.cat([energy_H, energy_W], 3))\n\n att_H = concate[:,:,:,0:height].permute(0,2,1,3).contiguous().view(m_batchsize*width,height,height)\n att_W = concate[:,:,:,height:height+width].contiguous().view(m_batchsize*height,width,width)\n out_H = torch.bmm(proj_value_H, att_H.permute(0, 2, 1)).view(m_batchsize,width,-1,height).permute(0,2,3,1)\n out_W = torch.bmm(proj_value_W, att_W.permute(0, 2, 1)).view(m_batchsize,height,-1,width).permute(0,2,1,3)\n return self.gamma*(out_H + out_W) + x\n\n\n\nclass Encoder(torch.nn.Module):\n def __init__(self, t_length = 5, n_channel =3):\n super(Encoder, self).__init__()\n \n def Basic(intInput, intOutput):\n return torch.nn.Sequential(\n torch.nn.Conv2d(in_channels=intInput, out_channels=intOutput, kernel_size=3, stride=1, padding=1),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(in_channels=intOutput, out_channels=intOutput, kernel_size=3, stride=1, padding=1),\n torch.nn.ReLU(inplace=False)\n )\n \n def Basic_(intInput, intOutput):\n return torch.nn.Sequential(\n torch.nn.Conv2d(in_channels=intInput, out_channels=intOutput, kernel_size=3, stride=1, padding=1),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(in_channels=intOutput, out_channels=intOutput, kernel_size=3, stride=1, padding=1),\n )\n \n self.moduleConv1 = Basic(n_channel*(t_length-1), 64)\n self.modulePool1 = torch.nn.MaxPool2d(kernel_size=2, stride=2)\n\n self.moduleConv2 = Basic(64, 128)\n self.modulePool2 = torch.nn.MaxPool2d(kernel_size=2, stride=2)\n \n self.moduleConv3 = Basic(128, 256)\n\n self.encoder_attention1 = CrissCrossAttention(64)\n self.encoder_attention2 = CrissCrossAttention(128)\n self.encoder_attention3 = CrissCrossAttention(256)\n \n def forward(self, x):\n\n tensorConv1 = self.moduleConv1(x)\n\n f1 = self.encoder_attention1(tensorConv1)\n f1 = self.encoder_attention1(f1)\n tensorConv1 = tensorConv1 + f1\n\n tensorPool1 = self.modulePool1(tensorConv1)\n\n tensorConv2 = self.moduleConv2(tensorPool1)\n\n f2 = self.encoder_attention2(tensorConv2)\n f2 = self.encoder_attention2(f2)\n tensorConv2 = tensorConv2 + f2\n\n tensorPool2 = self.modulePool2(tensorConv2)\n\n tensorConv3 = self.moduleConv3(tensorPool2)\n\n f3 = self.encoder_attention3(tensorConv3)\n f3 = self.encoder_attention3(f3)\n tensorConv3 = tensorConv3 + f3\n\n return tensorConv1, tensorConv2, tensorConv3\n \nclass Decoder(torch.nn.Module):\n def __init__(self, t_length = 5, n_channel =3):\n super(Decoder, self).__init__()\n \n def Basic(intInput, intOutput):\n return torch.nn.Sequential(\n torch.nn.Conv2d(in_channels=intInput, out_channels=intOutput, kernel_size=3, stride=1, padding=1),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(in_channels=intOutput, out_channels=intOutput, kernel_size=3, stride=1, padding=1),\n torch.nn.ReLU(inplace=False)\n )\n \n \n def Upsample(nc, intOutput):\n return torch.nn.Sequential(\n torch.nn.ConvTranspose2d(in_channels = nc, out_channels=intOutput, kernel_size = 3, stride = 2, padding = 1, output_padding = 1),\n torch.nn.ReLU(inplace=False)\n )\n \n self.moduleConv3 = Basic(256, 256)\n self.moduleUpsample3 = Upsample(256, 128)\n\n self.moduleDeconv2 = Basic(256, 128)\n self.moduleUpsample2 = Upsample(128, 64)\n \n def forward(self, x, skip1, skip2):\n \n tensorConv3 = self.moduleConv3(x)\n tensorUpsample2 = self.moduleUpsample3(tensorConv3)\n cat2 = torch.cat((skip2, tensorUpsample2), dim = 1)\n \n tensorDeconv2 = self.moduleDeconv2(cat2)\n tensorUpsample = self.moduleUpsample2(tensorDeconv2)\n cat = torch.cat((skip1, tensorUpsample), dim = 1)\n \n return cat\n\nclass ExactNet(torch.nn.Module):\n def __init__(self, t_length = 5, n_channel =3):\n super(ExactNet, self).__init__()\n self.encoder = Encoder(t_length, n_channel)\n self.decoder = Decoder(t_length, n_channel)\n\n def forward(self, x):\n fea1, fea2, fea3 = self.encoder(x)\n fea = self.decoder(fea3, fea1, fea2)\n return fea\n\nif __name__ == '__main__':\n #model = CrissCrossAttention(512)\n model = ExactNet(t_length = 5, n_channel =3)\n model.cuda()\n x = torch.randn(4, 12, 256, 256)\n model(x.cuda())\n #print('x shape: ', x.shape , 'attention shape: ', out.shape)\n","repo_name":"huchao-AI/APN","sub_path":"model/ccattention.py","file_name":"ccattention.py","file_ext":"py","file_size_in_byte":6625,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"67"} +{"seq_id":"4862878853","text":"#from pprint import pprint\nimport json\nimport cv2\nimport face_recognition\nimport sys,os\nimport time\nimport numpy as np\n#from PIL import Image\n#from io import BytesIO\nfrom simple_salesforce import Salesforce, SalesforceLogin, SFType\nimport pickle\n\ndef resource_path(relative_path):\n if hasattr(sys, '_MEIPASS'):\n return os.path.join(sys._MEIPASS, relative_path)\n return os.path.join(os.path.abspath(\".\"), relative_path)\n\nloginInfo = json.load(open(resource_path('login.json')))\nusername = loginInfo['username']\npassword = loginInfo['password']\nsecurity_token = loginInfo['security_token']\ncamera_index = loginInfo['camera']\ndomain = 'login'\n\nsession_id, instance = SalesforceLogin(username=username, password=password, security_token=security_token, domain=domain)\nsf = Salesforce(instance=instance, session_id=session_id)\n\nknown_face_encodings = []\nknown_face_names = []\nnameVSid = {}\naidVStid = {}\n\nfile = open(resource_path(\"knownFacesEncodings.npy\"),\"rb\")\nknown_face_encodings = np.load(file)\n\nwith open (resource_path('knownFacesNames.txt'), 'rb') as fp:\n known_face_names = pickle.load(fp)\n\nwith open (resource_path('nameVSid.txt'), 'rb') as fp:\n nameVSid = pickle.load(fp)\n\nwith open (resource_path('aidVStid.txt'), 'rb') as fp:\n aidVStid = pickle.load(fp)\n\nprint('known_face_encodings::',known_face_encodings)\nprint('known_face_names::',known_face_names)\nprint('nameVSid::',nameVSid)\nprint('aidVStid::',aidVStid)\n\n#video_capture = cv2.VideoCapture(int(camera_index))\nvideo_capture = cv2.VideoCapture(0)\nface_locations = []\nface_encodings = []\nface_names = []\nprocess_this_frame = True\nnamelist = []\nupdate_data = {}\nwhile True:\n # Grab a single frame of video\n ret, frame = video_capture.read()\n\n # Resize frame of video to 1/4 size for faster face recognition processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n rgb_small_frame = small_frame[:, :, ::-1]\n\n # Only process every other frame of video to save time\n if process_this_frame:\n # Find all the faces and face encodings in the current frame of video\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n\n face_names = []\n for face_encoding in face_encodings:\n # See if the face is a match for the known face(s)\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding)\n name = \"Unknown\"\n\n # # If a match was found in known_face_encodings, just use the first one.\n if True in matches:\n first_match_index = matches.index(True)\n name = known_face_names[first_match_index]\n print('result is :::',name)\n if(name in nameVSid.keys()):\n update_data.clear()\n update_data['Omo__FaceRecognized__c'] = True\n accId = nameVSid[name]\n print('accountId::',accId)\n print('transId::',aidVStid[accId])\n getattr(sf, \"Omo__Transaction__c\").update(aidVStid[accId],update_data)\n #time.sleep(2)\n #selfcheckin.update(aidVStid[accId], update_data)\n #os._exit(0)\n\n # Or instead, use the known face with the smallest distance to the new face\n face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)\n best_match_index = np.argmin(face_distances)\n if matches[best_match_index]:\n name = known_face_names[best_match_index]\n\n face_names.append(name)\n\n process_this_frame = not process_this_frame\n\n\n # Display the results\n for (top, right, bottom, left), name in zip(face_locations, face_names):\n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n\n # Draw a box around the face\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n\n # Draw a label with a name below the face\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n\n # Display the resulting image\n cv2.imshow('Video', frame)\n\n # Hit 'q' on the keyboard to quit!\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Release handle to the webcam\nvideo_capture.release()\ncv2.destroyAllWindows()","repo_name":"mrsalesforce/sf_py_face-recognition","sub_path":"face recognition.py","file_name":"face recognition.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72976634454","text":"from django.template import loader, RequestContext\nfrom django.shortcuts import get_object_or_404\nfrom django.http import Http404, HttpResponse, HttpResponsePermanentRedirect\nfrom django.conf import settings\nfrom django.core.xheaders import populate_xheaders\nfrom django.utils.safestring import mark_safe\nfrom django.views.decorators.csrf import csrf_protect\nfrom .models import Page\n\nDEFAULT_TEMPLATE = 'page_default.haml'\n\ndef page(request, url):\n \"\"\"\n Public interface to the page view.\n This view is called from PageFallbackMiddleware.process_response\n when a 404 is raised, which often means CsrfViewMiddleware.process_view\n has not been called even if CsrfViewMiddleware is installed. So we need\n to use @csrf_protect, in case the template needs {% csrf_token %}.\n However, we can't just wrap this view; if no matching flatpage exists,\n or a redirect is required for authentication, the 404 needs to be returned\n without any CSRF checks. Therefore, we only CSRF protect the internal implementation.\n \"\"\"\n if not url.startswith('/'):\n url = '/' + url\n try:\n page = get_object_or_404(Page, url__exact=url, is_enabled=True)\n except Http404:\n if not url.endswith('/') and settings.APPEND_SLASH:\n url += '/'\n get_object_or_404(Page, url__exact=url, is_enabled=True)\n return HttpResponsePermanentRedirect('%s/' % request.path)\n else:\n raise\n if page.is_inside_disabled_parent:\n raise Http404\n return render_page(request, page)\n\n@csrf_protect\ndef render_page(request, page):\n \"\"\"\n Internal interface to the page view. CSRF protected explicitly.\n \"\"\"\n t = loader.get_template(DEFAULT_TEMPLATE)\n\n # To avoid having to always use the \"|safe\" filter in flatpage templates,\n # mark the title and content as already safe (since they are raw HTML\n # content in the first place).\n page.title = mark_safe(page.title)\n page.content = mark_safe(page.content)\n\n c = RequestContext(request, {\n 'page': page,\n })\n response = HttpResponse(t.render(c))\n populate_xheaders(request, response, Page, page.id) # dunno wat\n return response","repo_name":"gbezyuk/django-pagetree","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11625038369","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.cluster import KMeans\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split \n\n\ndef getLogisticRegression(X_list, X_values):\n \"\"\"\n Function to train a logistic regression model. \n Used to predict if passed in values would result in 5-star rating. \n\n Returns formatted string with yes/no result & model accuracy. \n \"\"\"\n # Read in data\n df = pd.read_csv('./CarRentalDataCleaned.csv')\n\n # Train the logistic regression model\n X_train, X_test, y_train, y_test = train_test_split(df[X_list], df['recommended'])\n LogReg = LogisticRegression()\n LogReg.fit(X_train, y_train)\n \n # Run prediction and gets accuracy score\n result = LogReg.predict(np.array([X_values]))[0]\n accuracy = LogReg.score(X_test, y_test)\n \n # Returns the result as formatted string\n if result == 1:\n return f\"Vehicle is predicted to be recommended! The model is {(accuracy*100):.2f}% confident in it's accuracy.\"\n else: \n return f\"Vehicle is predicted to be not recommended. The model is {(accuracy*100):.2f}% confident in it's accuracy.\"\n\n\n\ndef getKMeansGraph(x_axis, y_axis, cluster_count):\n \"\"\"\n Function to determin clusters using K-means\n Saves created graph as an image to be used by `KMeansTab.py`\n \"\"\"\n\n # Read in data\n df = pd.read_csv('./CarRentalDataCleaned.csv')\n\n # Run K-Mean Clustering Model\n kmeans = KMeans(n_clusters=cluster_count)\n kmeans = kmeans.fit(df[[x_axis, y_axis]])\n clusters = []\n clusters = kmeans.labels_\n\n # create graph\n plot = sns.scatterplot(x=x_axis, y=y_axis, hue=clusters, data=df)\n plt.savefig('output.png')\n\n # Delete dataframe from memory.\n del df\n del clusters\n del kmeans\n del plot\n\n","repo_name":"AlexBIrvine/Machine-Learning-Capstone","sub_path":"Models.py","file_name":"Models.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10850996323","text":"\n#as we can see the counter adds 1 by default and value is the elem in list being iterated\nmy_list = ['apple', 'banana', 'grapes', 'pear']\nfor counter, value in enumerate(my_list, 1):\n print(counter, value)\n\n\n# Output:\n# 1 apple\n# 2 banana\n# 3 grapes\n# 4 pear\n\nmy_list = ['china', 'us', 'russia', 'europe', 'japan']\ncounter_list = list(enumerate(my_list, 1))\nprint(counter_list)\n# Output: [(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]","repo_name":"prosales95/PythonInterm","sub_path":"enumerate.py","file_name":"enumerate.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"12189085709","text":"# -*- coding: mbcs -*-\ntypelib_path = u'C:\\\\Program Files (x86)\\\\ArcGIS\\\\Desktop10.2\\\\com\\\\esriSearch.olb'\n_lcid = 0 # change this if required\nfrom ctypes import *\nimport comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2\nfrom comtypes import GUID\nfrom comtypes import CoClass\nimport comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0\nimport comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2\nimport comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2\nfrom comtypes import BSTR\nfrom ctypes.wintypes import VARIANT_BOOL\nfrom ctypes import HRESULT\nfrom comtypes import helpstring\nfrom comtypes import COMMETHOD\nfrom comtypes import dispid\nimport comtypes.gen._18F2FC71_6B30_45B9_B101_037A8B868B66_0_10_2\nimport comtypes.gen._C4B094C2_FF32_4FA1_ABCB_7820F8D6FB68_0_10_2\nimport comtypes.gen._1CE6AC65_43F5_4529_8FC0_D7ED298E4F1A_0_10_2\n\n\nclass SearchServerIP(CoClass):\n u'Search Server Message Proxy.'\n _reg_clsid_ = GUID('{27649117-93FF-4E04-B3EB-1C94D11C160B}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nclass ISearchServer(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to search server object.'\n _iid_ = GUID('{1B8A0E7C-63DA-4D43-8463-DD64FF779849}')\n _idlflags_ = ['oleautomation']\nSearchServerIP._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IAGSServerObject2, comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IAGSServerObject, ISearchServer, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.ISupportErrorInfo]\n\nclass SearchServerObjectDescription(CoClass):\n u'SearchServer Object Description Class.'\n _reg_clsid_ = GUID('{1B34B850-528C-4F12-A2F4-0F139EB2619C}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nSearchServerObjectDescription._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IServerObjectDescription]\n\nclass IGPItemIndexer(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to GP Indexer.'\n _iid_ = GUID('{289EA2B6-D185-40F7-B1E7-B2234AE1C9F6}')\n _idlflags_ = ['oleautomation']\nIGPItemIndexer._methods_ = [\n COMMETHOD([helpstring(u'The Build ItemInfos..')], HRESULT, 'IndexItems',\n ( ['in'], BSTR, 'Path' ),\n ( ['in'], VARIANT_BOOL, 'ReplaceIndex' ),\n ( ['in'], VARIANT_BOOL, 'Recursive' ),\n ( ['in'], VARIANT_BOOL, 'UseStaging' ),\n ( ['in'], BSTR, 'indexPath' ),\n ( ['in'], VARIANT_BOOL, 'UseQueue' )),\n COMMETHOD([helpstring(u'Add ItemInfo to Index File.')], HRESULT, 'AddItemInfo',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' ),\n ( ['in'], VARIANT_BOOL, 'ReplaceItems' ),\n ( ['in'], BSTR, 'indexPath' ),\n ( ['in'], BSTR, 'SDEConnection' ),\n ( ['in'], POINTER(BSTR), 'pGuid' )),\n COMMETHOD([helpstring(u'Delete ItemInfo from Index File.')], HRESULT, 'DeleteItemInfo',\n ( ['in'], BSTR, 'indexPath' ),\n ( ['in'], BSTR, 'pGuid' )),\n COMMETHOD([helpstring(u'Update the index.')], HRESULT, 'UpdateItemInfo',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD([helpstring(u'Index Item without children with passed in catalogpath.')], HRESULT, 'IndexItem',\n ( ['in'], BSTR, 'Path' )),\n COMMETHOD([helpstring(u'Update Thumbnail of a ItemInfo by passing in a catalogpath.')], HRESULT, 'UpdateThumbnailInIndex',\n ( ['in'], BSTR, 'Path' )),\n COMMETHOD(['propget', helpstring(u'Total indexed items count.')], HRESULT, 'Count',\n ( ['retval', 'out'], POINTER(c_int), 'pCount' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether the ancestor of this ItemInfo has been registered to be indexed.')], HRESULT, 'IsAncestorRegistered',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' ),\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pRegistered' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether the current item has been indexed.')], HRESULT, 'HasBeenIndexed',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' ),\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pIndexed' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether staging is used during index.')], HRESULT, 'UseStaging',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pUseStaging' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether staging is used during index.')], HRESULT, 'UseStaging',\n ( ['in'], VARIANT_BOOL, 'pUseStaging' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether queue is used during index.')], HRESULT, 'UseQueue',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'UseQueue' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether queue is used during index.')], HRESULT, 'UseQueue',\n ( ['in'], VARIANT_BOOL, 'UseQueue' )),\n COMMETHOD(['propget', helpstring(u'Name of the index folder.')], HRESULT, 'IndexFolder',\n ( ['retval', 'out'], POINTER(BSTR), 'pFolderName' )),\n COMMETHOD(['propput', helpstring(u'Name of the index folder.')], HRESULT, 'IndexFolder',\n ( ['in'], BSTR, 'pFolderName' )),\n COMMETHOD(['propget', helpstring(u'Name of the index.')], HRESULT, 'IndexName',\n ( ['retval', 'out'], POINTER(BSTR), 'pName' )),\n COMMETHOD(['propput', helpstring(u'Name of the index.')], HRESULT, 'IndexName',\n ( ['in'], BSTR, 'pName' )),\n COMMETHOD(['propget', helpstring(u'SDE Connection file.')], HRESULT, 'SDEConnection',\n ( ['retval', 'out'], POINTER(BSTR), 'pName' )),\n COMMETHOD(['propput', helpstring(u'SDE Connection file.')], HRESULT, 'SDEConnection',\n ( ['in'], BSTR, 'pName' )),\n]\n################################################################\n## code template for IGPItemIndexer implementation\n##class IGPItemIndexer_Impl(object):\n## @property\n## def Count(self):\n## u'Total indexed items count.'\n## #return pCount\n##\n## def _get(self):\n## u'SDE Connection file.'\n## #return pName\n## def _set(self, pName):\n## u'SDE Connection file.'\n## SDEConnection = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Name of the index.'\n## #return pName\n## def _set(self, pName):\n## u'Name of the index.'\n## IndexName = property(_get, _set, doc = _set.__doc__)\n##\n## @property\n## def HasBeenIndexed(self, pItemInfo):\n## u'Indicates whether the current item has been indexed.'\n## #return pIndexed\n##\n## def _get(self):\n## u'Name of the index folder.'\n## #return pFolderName\n## def _set(self, pFolderName):\n## u'Name of the index folder.'\n## IndexFolder = property(_get, _set, doc = _set.__doc__)\n##\n## def IndexItems(self, Path, ReplaceIndex, Recursive, UseStaging, indexPath, UseQueue):\n## u'The Build ItemInfos..'\n## #return \n##\n## def _get(self):\n## u'Indicates whether staging is used during index.'\n## #return pUseStaging\n## def _set(self, pUseStaging):\n## u'Indicates whether staging is used during index.'\n## UseStaging = property(_get, _set, doc = _set.__doc__)\n##\n## def IndexItem(self, Path):\n## u'Index Item without children with passed in catalogpath.'\n## #return \n##\n## def UpdateThumbnailInIndex(self, Path):\n## u'Update Thumbnail of a ItemInfo by passing in a catalogpath.'\n## #return \n##\n## def AddItemInfo(self, pItemInfo, ReplaceItems, indexPath, SDEConnection, pGuid):\n## u'Add ItemInfo to Index File.'\n## #return \n##\n## def _get(self):\n## u'Indicates whether queue is used during index.'\n## #return UseQueue\n## def _set(self, UseQueue):\n## u'Indicates whether queue is used during index.'\n## UseQueue = property(_get, _set, doc = _set.__doc__)\n##\n## def UpdateItemInfo(self, pItemInfo):\n## u'Update the index.'\n## #return \n##\n## @property\n## def IsAncestorRegistered(self, pItemInfo):\n## u'Indicates whether the ancestor of this ItemInfo has been registered to be indexed.'\n## #return pRegistered\n##\n## def DeleteItemInfo(self, indexPath, pGuid):\n## u'Delete ItemInfo from Index File.'\n## #return \n##\n\nclass IItemIndexAdmin(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to members to administrate indexing process.'\n _iid_ = GUID('{CB225681-C42D-4A5F-B26E-F4A790CEF7A7}')\n _idlflags_ = ['oleautomation']\nIItemIndexAdmin._methods_ = [\n COMMETHOD(['propget', helpstring(u'Name of the index folder.')], HRESULT, 'IndexFolder',\n ( ['retval', 'out'], POINTER(BSTR), 'pFolderName' )),\n COMMETHOD(['propput', helpstring(u'Name of the index folder.')], HRESULT, 'IndexFolder',\n ( ['in'], BSTR, 'pFolderName' )),\n COMMETHOD(['propget', helpstring(u'Name of the index.')], HRESULT, 'IndexName',\n ( ['retval', 'out'], POINTER(BSTR), 'pName' )),\n COMMETHOD(['propput', helpstring(u'Name of the index.')], HRESULT, 'IndexName',\n ( ['in'], BSTR, 'pName' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to use staging during index.')], HRESULT, 'UseStaging',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pUseStaging' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to use staging during index.')], HRESULT, 'UseStaging',\n ( ['in'], VARIANT_BOOL, 'pUseStaging' )),\n COMMETHOD([helpstring(u'Prepare and start indexing.')], HRESULT, 'StartIndexing',\n ( ['in'], VARIANT_BOOL, 'ReplaceIndex' ),\n ( ['in'], VARIANT_BOOL, 'ReplaceItems' )),\n COMMETHOD([helpstring(u'Close and end indexing.')], HRESULT, 'EndIndexing'),\n]\n################################################################\n## code template for IItemIndexAdmin implementation\n##class IItemIndexAdmin_Impl(object):\n## def EndIndexing(self):\n## u'Close and end indexing.'\n## #return \n##\n## def _get(self):\n## u'Indicates whether to use staging during index.'\n## #return pUseStaging\n## def _set(self, pUseStaging):\n## u'Indicates whether to use staging during index.'\n## UseStaging = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Name of the index folder.'\n## #return pFolderName\n## def _set(self, pFolderName):\n## u'Name of the index folder.'\n## IndexFolder = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Name of the index.'\n## #return pName\n## def _set(self, pName):\n## u'Name of the index.'\n## IndexName = property(_get, _set, doc = _set.__doc__)\n##\n## def StartIndexing(self, ReplaceIndex, ReplaceItems):\n## u'Prepare and start indexing.'\n## #return \n##\n\nclass SearchServerConfigurationFactory(CoClass):\n u'SearchServer Configuration Factory Class.'\n _reg_clsid_ = GUID('{34DAF65A-3A86-4A76-B7CD-7614906626C5}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nSearchServerConfigurationFactory._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, comtypes.gen._18F2FC71_6B30_45B9_B101_037A8B868B66_0_10_2.IConfigurationFactory, comtypes.gen._18F2FC71_6B30_45B9_B101_037A8B868B66_0_10_2.IConfigurationFactory2, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.ISupportErrorInfo]\n\nclass IIndexingConfiguration(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to the IndexingConfiguration Interface.'\n _iid_ = GUID('{804C00D1-DCD8-4C7A-8F95-0AF743E22EE0}')\n _idlflags_ = ['oleautomation']\nIIndexingConfiguration._methods_ = [\n COMMETHOD(['propget', helpstring(u'The target paths to be indexed.')], HRESULT, 'Paths',\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IStringArray)), 'ppPaths' )),\n COMMETHOD(['propput', helpstring(u'The target paths to be indexed.')], HRESULT, 'Paths',\n ( ['in'], POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IStringArray), 'ppPaths' )),\n COMMETHOD(['propget', helpstring(u'File extensions to be filtered out.')], HRESULT, 'Filter',\n ( ['retval', 'out'], POINTER(BSTR), 'pFilter' )),\n COMMETHOD(['propput', helpstring(u'File extensions to be filtered out.')], HRESULT, 'Filter',\n ( ['in'], BSTR, 'pFilter' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to recursively get the children of target path.')], HRESULT, 'Recursive',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pRecursive' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to recursively get the children of target path.')], HRESULT, 'Recursive',\n ( ['in'], VARIANT_BOOL, 'pRecursive' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to replace existing index.')], HRESULT, 'ReplaceIndex',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pReplaceIndex' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to replace existing index.')], HRESULT, 'ReplaceIndex',\n ( ['in'], VARIANT_BOOL, 'pReplaceIndex' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to replace existing items.')], HRESULT, 'ReplaceItems',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pReplaceItems' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to replace existing items.')], HRESULT, 'ReplaceItems',\n ( ['in'], VARIANT_BOOL, 'pReplaceItems' )),\n COMMETHOD(['propget', helpstring(u'Incremental index interval.')], HRESULT, 'IncrementalIndexInterval',\n ( ['retval', 'out'], POINTER(c_int), 'pInterval' )),\n COMMETHOD(['propput', helpstring(u'Incremental index interval.')], HRESULT, 'IncrementalIndexInterval',\n ( ['in'], c_int, 'pInterval' )),\n COMMETHOD(['propget', helpstring(u'Full index interval.')], HRESULT, 'FullIndexInterval',\n ( ['retval', 'out'], POINTER(c_int), 'pInterval' )),\n COMMETHOD(['propput', helpstring(u'Full index interval.')], HRESULT, 'FullIndexInterval',\n ( ['in'], c_int, 'pInterval' )),\n COMMETHOD(['propget', helpstring(u'Index start time.')], HRESULT, 'StartTime',\n ( ['retval', 'out'], POINTER(BSTR), 'StartTime' )),\n COMMETHOD(['propput', helpstring(u'Index start time.')], HRESULT, 'StartTime',\n ( ['in'], BSTR, 'StartTime' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.')], HRESULT, 'SkipConnections',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pSkip' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.')], HRESULT, 'SkipConnections',\n ( ['in'], VARIANT_BOOL, 'pSkip' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to pause indexing until instructed to resume.')], HRESULT, 'IsPaused',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pPaused' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to pause indexing until instructed to resume.')], HRESULT, 'IsPaused',\n ( ['in'], VARIANT_BOOL, 'pPaused' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether the indexer was running when it was paused.')], HRESULT, 'WasRunning',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pRunning' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether the indexer was running when it was paused.')], HRESULT, 'WasRunning',\n ( ['in'], VARIANT_BOOL, 'pRunning' )),\n]\n################################################################\n## code template for IIndexingConfiguration implementation\n##class IIndexingConfiguration_Impl(object):\n## def _get(self):\n## u'Indicates whether to replace existing index.'\n## #return pReplaceIndex\n## def _set(self, pReplaceIndex):\n## u'Indicates whether to replace existing index.'\n## ReplaceIndex = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'The target paths to be indexed.'\n## #return ppPaths\n## def _set(self, ppPaths):\n## u'The target paths to be indexed.'\n## Paths = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether to recursively get the children of target path.'\n## #return pRecursive\n## def _set(self, pRecursive):\n## u'Indicates whether to recursively get the children of target path.'\n## Recursive = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether the indexer was running when it was paused.'\n## #return pRunning\n## def _set(self, pRunning):\n## u'Indicates whether the indexer was running when it was paused.'\n## WasRunning = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Full index interval.'\n## #return pInterval\n## def _set(self, pInterval):\n## u'Full index interval.'\n## FullIndexInterval = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether to replace existing items.'\n## #return pReplaceItems\n## def _set(self, pReplaceItems):\n## u'Indicates whether to replace existing items.'\n## ReplaceItems = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Incremental index interval.'\n## #return pInterval\n## def _set(self, pInterval):\n## u'Incremental index interval.'\n## IncrementalIndexInterval = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'File extensions to be filtered out.'\n## #return pFilter\n## def _set(self, pFilter):\n## u'File extensions to be filtered out.'\n## Filter = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.'\n## #return pSkip\n## def _set(self, pSkip):\n## u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.'\n## SkipConnections = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Index start time.'\n## #return StartTime\n## def _set(self, StartTime):\n## u'Index start time.'\n## StartTime = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether to pause indexing until instructed to resume.'\n## #return pPaused\n## def _set(self, pPaused):\n## u'Indicates whether to pause indexing until instructed to resume.'\n## IsPaused = property(_get, _set, doc = _set.__doc__)\n##\n\nclass Library(object):\n u'Esri Search Object Library 10.2'\n name = u'esriSearch'\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\n\nclass IIndexingConfiguration2(IIndexingConfiguration):\n _case_insensitive_ = True\n u'Provides access to the IndexingConfiguration Interface.'\n _iid_ = GUID('{800FEC88-4FED-40A5-9798-9BE7BF73E051}')\n _idlflags_ = ['oleautomation']\nclass IIndexingConfiguration3(IIndexingConfiguration2):\n _case_insensitive_ = True\n u'Provides access to the IndexingConfiguration Interface.'\n _iid_ = GUID('{56E962F0-2A97-4189-B69F-CBBBB7694D2C}')\n _idlflags_ = ['oleautomation']\nIIndexingConfiguration2._methods_ = [\n COMMETHOD(['propget', helpstring(u'Indicates whether to generate thumbnails after indexing.')], HRESULT, 'GenerateThumbnails',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'GenerateThumbnails' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to generate thumbnails after indexing.')], HRESULT, 'GenerateThumbnails',\n ( ['in'], VARIANT_BOOL, 'GenerateThumbnails' )),\n COMMETHOD([helpstring(u'Loads current index configuration settings.')], HRESULT, 'LoadConfigFile'),\n COMMETHOD([helpstring(u'Deletes existing index configuration file and creates a new one with default settings.')], HRESULT, 'ResetConfigFile'),\n]\n################################################################\n## code template for IIndexingConfiguration2 implementation\n##class IIndexingConfiguration2_Impl(object):\n## def LoadConfigFile(self):\n## u'Loads current index configuration settings.'\n## #return \n##\n## def _get(self):\n## u'Indicates whether to generate thumbnails after indexing.'\n## #return GenerateThumbnails\n## def _set(self, GenerateThumbnails):\n## u'Indicates whether to generate thumbnails after indexing.'\n## GenerateThumbnails = property(_get, _set, doc = _set.__doc__)\n##\n## def ResetConfigFile(self):\n## u'Deletes existing index configuration file and creates a new one with default settings.'\n## #return \n##\n\nIIndexingConfiguration3._methods_ = [\n COMMETHOD(['propget', helpstring(u'Indicates whether to skip mosaic dataset items when indexing.')], HRESULT, 'SkipMosaicItems',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pSkipMosaicItems' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to skip mosaic dataset items when indexing.')], HRESULT, 'SkipMosaicItems',\n ( ['in'], VARIANT_BOOL, 'pSkipMosaicItems' )),\n COMMETHOD(['propget', helpstring(u'The number of indexing threads.')], HRESULT, 'ThreadCount',\n ( ['retval', 'out'], POINTER(c_int), 'pCount' )),\n COMMETHOD(['propput', helpstring(u'The number of indexing threads.')], HRESULT, 'ThreadCount',\n ( ['in'], c_int, 'pCount' )),\n]\n################################################################\n## code template for IIndexingConfiguration3 implementation\n##class IIndexingConfiguration3_Impl(object):\n## def _get(self):\n## u'Indicates whether to skip mosaic dataset items when indexing.'\n## #return pSkipMosaicItems\n## def _set(self, pSkipMosaicItems):\n## u'Indicates whether to skip mosaic dataset items when indexing.'\n## SkipMosaicItems = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'The number of indexing threads.'\n## #return pCount\n## def _set(self, pCount):\n## u'The number of indexing threads.'\n## ThreadCount = property(_get, _set, doc = _set.__doc__)\n##\n\nclass IProtectNameSearch(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to dummy methods protecting name correctness.'\n _iid_ = GUID('{4F37BE4D-3CC6-421D-BDE9-F73D48FF5CB9}')\n _idlflags_ = []\nIProtectNameSearch._methods_ = [\n COMMETHOD([], HRESULT, 'ProtectOLE_HANDLE',\n ( [], comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.OLE_HANDLE, 'aHandle' )),\n COMMETHOD([], HRESULT, 'ProtectOLE_COLOR',\n ( [], comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.OLE_COLOR, 'aColor' )),\n]\n################################################################\n## code template for IProtectNameSearch implementation\n##class IProtectNameSearch_Impl(object):\n## def ProtectOLE_COLOR(self, aColor):\n## '-no docstring-'\n## #return \n##\n## def ProtectOLE_HANDLE(self, aHandle):\n## '-no docstring-'\n## #return \n##\n\nclass IGPItemIndexer2(IGPItemIndexer):\n _case_insensitive_ = True\n u'Provides access to GP Indexer.'\n _iid_ = GUID('{E76ACE8C-074C-4B5C-84B1-04ED7C5B2A7C}')\n _idlflags_ = ['oleautomation']\nclass IItemIndex(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to helper functions for indexing.'\n _iid_ = GUID('{ACF9354C-05DB-4A70-B5F3-48D2822CB400}')\n _idlflags_ = ['oleautomation']\nIGPItemIndexer2._methods_ = [\n COMMETHOD(['propget', helpstring(u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.')], HRESULT, 'SkipConnections',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pSkipConnections' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.')], HRESULT, 'SkipConnections',\n ( ['in'], VARIANT_BOOL, 'pSkipConnections' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to skip mosaic dataset items when indexing.')], HRESULT, 'SkipMosaicItems',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pSkipMosaicItems' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to skip mosaic dataset items when indexing.')], HRESULT, 'SkipMosaicItems',\n ( ['in'], VARIANT_BOOL, 'pSkipMosaicItems' )),\n COMMETHOD(['propget', helpstring(u'The native item index.')], HRESULT, 'ItemIndex',\n ( ['retval', 'out'], POINTER(POINTER(IItemIndex)), 'ppItemIndex' )),\n]\n################################################################\n## code template for IGPItemIndexer2 implementation\n##class IGPItemIndexer2_Impl(object):\n## def _get(self):\n## u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.'\n## #return pSkipConnections\n## def _set(self, pSkipConnections):\n## u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.'\n## SkipConnections = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether to skip mosaic dataset items when indexing.'\n## #return pSkipMosaicItems\n## def _set(self, pSkipMosaicItems):\n## u'Indicates whether to skip mosaic dataset items when indexing.'\n## SkipMosaicItems = property(_get, _set, doc = _set.__doc__)\n##\n## @property\n## def ItemIndex(self):\n## u'The native item index.'\n## #return ppItemIndex\n##\n\nclass DataSourceConfiguration(CoClass):\n u'DataSource Configuration object.'\n _reg_clsid_ = GUID('{5D6268D0-9E95-4A1D-9F1E-E943B47E2588}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nclass IDataSourceConfiguration(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to data source configuration.'\n _iid_ = GUID('{CC8F1331-2BF5-4CAD-B30C-FFCB95EB96B0}')\n _idlflags_ = ['oleautomation']\nDataSourceConfiguration._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, IDataSourceConfiguration, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IXMLSerialize, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersistStream, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersist]\n\nIItemIndex._methods_ = [\n COMMETHOD([helpstring(u'Add item info to index.')], HRESULT, 'AddItemInfo',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD([helpstring(u'Delete item info from index.')], HRESULT, 'DeleteItemInfo',\n ( ['in'], BSTR, 'catalogPath' )),\n COMMETHOD([helpstring(u'Delete item infos from index.')], HRESULT, 'DeleteItemInfos',\n ( ['in'], BSTR, 'catalogPath' )),\n COMMETHOD([helpstring(u'Update the specified item info in index.')], HRESULT, 'UpdateItemInfo',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to check a particular iteminfo exists or not.')], HRESULT, 'ItemInfoExists',\n ( ['in'], BSTR, 'catalogPath' ),\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pbExsits' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to check index exists or not.')], HRESULT, 'ItemInfoCount',\n ( ['retval', 'out'], POINTER(c_int), 'pCount' )),\n]\n################################################################\n## code template for IItemIndex implementation\n##class IItemIndex_Impl(object):\n## def AddItemInfo(self, pItemInfo):\n## u'Add item info to index.'\n## #return \n##\n## def DeleteItemInfos(self, catalogPath):\n## u'Delete item infos from index.'\n## #return \n##\n## @property\n## def ItemInfoCount(self):\n## u'Indicates whether to check index exists or not.'\n## #return pCount\n##\n## @property\n## def ItemInfoExists(self, catalogPath):\n## u'Indicates whether to check a particular iteminfo exists or not.'\n## #return pbExsits\n##\n## def UpdateItemInfo(self, pItemInfo):\n## u'Update the specified item info in index.'\n## #return \n##\n## def DeleteItemInfo(self, catalogPath):\n## u'Delete item info from index.'\n## #return \n##\n\nclass IDSCStatusArray(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to Array of DSCStatus.'\n _iid_ = GUID('{855C8D89-4AD8-403D-A78D-FB62A19A2BE9}')\n _idlflags_ = ['oleautomation']\nclass IDSCStatus(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to SDCStatus object.'\n _iid_ = GUID('{1B933540-819B-492B-9A0B-498ED4307E8C}')\n _idlflags_ = ['oleautomation']\nIDSCStatusArray._methods_ = [\n COMMETHOD(['propget', helpstring(u'DSCStatus Object count.')], HRESULT, 'Count',\n ( ['retval', 'out'], POINTER(c_int), 'Count' )),\n COMMETHOD(['propget', helpstring(u'The DSCStatus Object at the specified position.')], HRESULT, 'Element',\n ( ['in'], c_int, 'index' ),\n ( ['retval', 'out'], POINTER(POINTER(IDSCStatus)), 'dataObject' )),\n COMMETHOD([helpstring(u'Removes the DSCStatus Object at the specified position.')], HRESULT, 'Remove',\n ( ['in'], c_int, 'index' )),\n COMMETHOD([helpstring(u'Removes all DSCStatus Objects.')], HRESULT, 'RemoveAll'),\n COMMETHOD([helpstring(u'Adds a DSCStatus.')], HRESULT, 'Add',\n ( ['in'], POINTER(IDSCStatus), 'pDSCStatus' )),\n COMMETHOD([helpstring(u'Adds a DSCStatus Object at the specified position.')], HRESULT, 'Insert',\n ( ['in'], c_int, 'index' ),\n ( ['in'], POINTER(IDSCStatus), 'DSCStatus' )),\n]\n################################################################\n## code template for IDSCStatusArray implementation\n##class IDSCStatusArray_Impl(object):\n## @property\n## def Count(self):\n## u'DSCStatus Object count.'\n## #return Count\n##\n## def Insert(self, index, DSCStatus):\n## u'Adds a DSCStatus Object at the specified position.'\n## #return \n##\n## def Remove(self, index):\n## u'Removes the DSCStatus Object at the specified position.'\n## #return \n##\n## @property\n## def Element(self, index):\n## u'The DSCStatus Object at the specified position.'\n## #return dataObject\n##\n## def RemoveAll(self):\n## u'Removes all DSCStatus Objects.'\n## #return \n##\n## def Add(self, pDSCStatus):\n## u'Adds a DSCStatus.'\n## #return \n##\n\nclass IndexingStatus(CoClass):\n u'Indexing Status object.'\n _reg_clsid_ = GUID('{9FEC3A52-230C-4337-AAF4-24AC06FC6E30}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nclass IIndexingStatus(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to indexing status.'\n _iid_ = GUID('{3AED1CD7-B3E8-446B-81B3-F35C466994DB}')\n _idlflags_ = ['oleautomation']\nIndexingStatus._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, IIndexingStatus, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IXMLSerialize, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersistStream, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersist]\n\nclass SearchConfiguration(CoClass):\n u'Provides access to members of SearchConfiguration.'\n _reg_clsid_ = GUID('{0B7BF27E-0AFF-4C1B-B695-FB3EE0EA51CD}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nclass ISearchConfiguration(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to the search configuration object.'\n _iid_ = GUID('{EE2DF519-39A5-48F6-AB24-BE147EBDD4BD}')\n _idlflags_ = ['oleautomation']\nSearchConfiguration._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, ISearchConfiguration]\n\nclass IGPItemInfoHelper(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to helper functions for item info.'\n _iid_ = GUID('{AF93FAAE-E112-4CD3-BB3F-1B0690FC7D57}')\n _idlflags_ = ['oleautomation']\nIGPItemInfoHelper._methods_ = [\n COMMETHOD(['propget', helpstring(u'Provides access to ItemInfo Helper object. User can get item info from it.')], HRESULT, 'ItemInfoByDataElement',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IDataElement), 'pDE' ),\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo)), 'ppItemInfo' )),\n COMMETHOD(['propget', helpstring(u'Create item info from Data Element and Geometry Types.')], HRESULT, 'ItemInfoByDataElement2',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IDataElement), 'pDE' ),\n ( ['in'], comtypes.gen._C4B094C2_FF32_4FA1_ABCB_7820F8D6FB68_0_10_2.esriGeometryType, 'geoType' ),\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo)), 'ppItemInfo' )),\n COMMETHOD(['propget', helpstring(u'Create item info from Dataset.')], HRESULT, 'ItemInfoByDataset',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IDataset), 'pDataset' ),\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo)), 'ppItemInfo' )),\n COMMETHOD(['propget', helpstring(u'Create item info from DatesetName.')], HRESULT, 'ItemInfoByDatasetName',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IDatasetName), 'pDatasetName' ),\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo)), 'ppItemInfo' )),\n COMMETHOD(['propget', helpstring(u'Create item info from Catalog path.')], HRESULT, 'ItemInfoByCatalogPathAndType',\n ( ['in'], BSTR, 'catalogPath' ),\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IGPDataType), 'pDataType' ),\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo)), 'ppItemInfo' )),\n COMMETHOD(['propget', helpstring(u'Create item infos from a catalog path.')], HRESULT, 'ItemInfoByCatalogPath',\n ( ['in'], BSTR, 'catalogPath' ),\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfos)), 'ppItemInfos' )),\n COMMETHOD(['propget', helpstring(u'Create item infos from layer.')], HRESULT, 'ItemInfoByGPLayer',\n ( ['in'], POINTER(comtypes.gen._1CE6AC65_43F5_4529_8FC0_D7ED298E4F1A_0_10_2.IGPLayer), 'pGPLayer' ),\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo)), 'ppItemInfo' )),\n COMMETHOD([helpstring(u'Update the item info of the specified object.')], HRESULT, 'UpdateItemInfoByMetadata',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IMetadata), 'pMetadata' ),\n ( ['in', 'out'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD([helpstring(u'Update the item info of the specified object.')], HRESULT, 'UpdateItemInfoByDataElement',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IDataElement), 'pDE' ),\n ( ['in', 'out'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD([helpstring(u'Update the item info of the specified object.')], HRESULT, 'UpdateItemInfoByDataset',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IDataset), 'pDataset' ),\n ( ['in', 'out'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD([helpstring(u'Update the item info of the specified object.')], HRESULT, 'UpdateItemInfoByDatasetName',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IDatasetName), 'pDatasetName' ),\n ( ['in', 'out'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD([helpstring(u'Update the item info of the specified object.')], HRESULT, 'UpdateItemInfoByCatalogPathAndType',\n ( ['in'], BSTR, 'catalogPath' ),\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IGPDataType), 'pDataType' ),\n ( ['in', 'out'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD([helpstring(u'Update the item info of the specified object.')], HRESULT, 'UpdateItemInfoByGPLayer',\n ( ['in'], POINTER(comtypes.gen._1CE6AC65_43F5_4529_8FC0_D7ED298E4F1A_0_10_2.IGPLayer), 'pGPLayer' ),\n ( ['in', 'out'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD([helpstring(u'Extract user defined Item Info from metadata.')], HRESULT, 'ExtractItemInfoFromMetadata',\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IMetadata), 'pMetadata' ),\n ( ['in', 'out'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n COMMETHOD([helpstring(u'Converts the coordinates of the item info extent to WGS84.')], HRESULT, 'ConvertExtentToWGS84',\n ( ['in', 'out'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IItemInfo), 'pItemInfo' )),\n]\n################################################################\n## code template for IGPItemInfoHelper implementation\n##class IGPItemInfoHelper_Impl(object):\n## def UpdateItemInfoByDataset(self, pDataset):\n## u'Update the item info of the specified object.'\n## #return pItemInfo\n##\n## def ExtractItemInfoFromMetadata(self, pMetadata):\n## u'Extract user defined Item Info from metadata.'\n## #return pItemInfo\n##\n## @property\n## def ItemInfoByCatalogPathAndType(self, catalogPath, pDataType):\n## u'Create item info from Catalog path.'\n## #return ppItemInfo\n##\n## @property\n## def ItemInfoByDatasetName(self, pDatasetName):\n## u'Create item info from DatesetName.'\n## #return ppItemInfo\n##\n## def UpdateItemInfoByDataElement(self, pDE):\n## u'Update the item info of the specified object.'\n## #return pItemInfo\n##\n## @property\n## def ItemInfoByCatalogPath(self, catalogPath):\n## u'Create item infos from a catalog path.'\n## #return ppItemInfos\n##\n## def ConvertExtentToWGS84(self):\n## u'Converts the coordinates of the item info extent to WGS84.'\n## #return pItemInfo\n##\n## def UpdateItemInfoByGPLayer(self, pGPLayer):\n## u'Update the item info of the specified object.'\n## #return pItemInfo\n##\n## def UpdateItemInfoByDatasetName(self, pDatasetName):\n## u'Update the item info of the specified object.'\n## #return pItemInfo\n##\n## @property\n## def ItemInfoByGPLayer(self, pGPLayer):\n## u'Create item infos from layer.'\n## #return ppItemInfo\n##\n## def UpdateItemInfoByCatalogPathAndType(self, catalogPath, pDataType):\n## u'Update the item info of the specified object.'\n## #return pItemInfo\n##\n## @property\n## def ItemInfoByDataElement2(self, pDE, geoType):\n## u'Create item info from Data Element and Geometry Types.'\n## #return ppItemInfo\n##\n## @property\n## def ItemInfoByDataset(self, pDataset):\n## u'Create item info from Dataset.'\n## #return ppItemInfo\n##\n## def UpdateItemInfoByMetadata(self, pMetadata):\n## u'Update the item info of the specified object.'\n## #return pItemInfo\n##\n## @property\n## def ItemInfoByDataElement(self, pDE):\n## u'Provides access to ItemInfo Helper object. User can get item info from it.'\n## #return ppItemInfo\n##\n\nclass SearchServerLP(CoClass):\n u'Map Server LAN Proxy.'\n _reg_clsid_ = GUID('{E6BCDBC4-EFBF-46E3-9F13-E5B9BBFCD99D}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nSearchServerLP._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IAGSServerObject2, comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IAGSServerObject, ISearchServer, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.ISupportErrorInfo]\n\nclass DSCStatusArray(CoClass):\n u'Data source status Array.'\n _reg_clsid_ = GUID('{980AA1E3-11BF-45AF-BE11-5A69FA2ABE5F}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nDSCStatusArray._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, IDSCStatusArray, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IXMLSerialize, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IXMLVersionSupport, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersistStream, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersist]\n\nclass ItemIndex(CoClass):\n u'Provides access to the ItemIndex object.'\n _reg_clsid_ = GUID('{9866E6C3-41EA-4AFE-9921-AF94435817CB}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nclass IItemIndex2(IItemIndex):\n _case_insensitive_ = True\n u'Provides access to update thumbnail in index.'\n _iid_ = GUID('{FCAF5F49-FDA4-4DD6-87E9-743E139DBBCB}')\n _idlflags_ = ['oleautomation']\nclass IItemIndex3(IItemIndex2):\n _case_insensitive_ = True\n u'Provides access to members for merging index.'\n _iid_ = GUID('{2A2148D1-4653-4658-B4D6-A50BF3B7EA78}')\n _idlflags_ = ['oleautomation']\nItemIndex._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, IItemIndex, IItemIndex2, IItemIndex3, IItemIndexAdmin]\n\nclass IIndexingOptions(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to indexing options object.'\n _iid_ = GUID('{1F12DC45-A7A1-4504-AC1B-6E52DD5B12F9}')\n _idlflags_ = ['oleautomation']\nISearchServer._methods_ = [\n COMMETHOD([helpstring(u'Register data source to index.')], HRESULT, 'RegisterDataSource',\n ( ['in'], POINTER(IDataSourceConfiguration), 'DataSourceConfiguration' )),\n COMMETHOD([helpstring(u'Unregister Data Source.')], HRESULT, 'UnregisterDataSource',\n ( ['in'], BSTR, 'Path' )),\n COMMETHOD([helpstring(u'The list of dataSource path.')], HRESULT, 'GetDataSourceList',\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IStringArray)), 'ppDataSourceList' )),\n COMMETHOD([helpstring(u'The indexing options.')], HRESULT, 'GetIndexingOptions',\n ( ['retval', 'out'], POINTER(POINTER(IIndexingOptions)), 'ppIndexingOptions' )),\n COMMETHOD([helpstring(u'The indexing options.')], HRESULT, 'SetIndexingOptions',\n ( ['in'], POINTER(IIndexingOptions), 'pIndexingOptions' )),\n COMMETHOD([helpstring(u'The indexing status.')], HRESULT, 'GetIndexingStatus',\n ( ['retval', 'out'], POINTER(POINTER(IIndexingStatus)), 'ppIndexingStatus' )),\n]\n################################################################\n## code template for ISearchServer implementation\n##class ISearchServer_Impl(object):\n## def SetIndexingOptions(self, pIndexingOptions):\n## u'The indexing options.'\n## #return \n##\n## def GetIndexingStatus(self):\n## u'The indexing status.'\n## #return ppIndexingStatus\n##\n## def UnregisterDataSource(self, Path):\n## u'Unregister Data Source.'\n## #return \n##\n## def RegisterDataSource(self, DataSourceConfiguration):\n## u'Register data source to index.'\n## #return \n##\n## def GetIndexingOptions(self):\n## u'The indexing options.'\n## #return ppIndexingOptions\n##\n## def GetDataSourceList(self):\n## u'The list of dataSource path.'\n## #return ppDataSourceList\n##\n\nISearchConfiguration._methods_ = [\n COMMETHOD([helpstring(u'Load configuration settings from the specificed location.')], HRESULT, 'LoadFromFile',\n ( ['in'], BSTR, 'Path' )),\n COMMETHOD([helpstring(u'Save configuration settings to the specificed location.')], HRESULT, 'SaveToFile',\n ( ['in'], BSTR, 'Path' )),\n COMMETHOD(['propget', helpstring(u'The count of search services.')], HRESULT, 'ServicesCount',\n ( ['retval', 'out'], POINTER(c_int), 'pCount' )),\n COMMETHOD(['propget', helpstring(u'The search service object name at the specified index.')], HRESULT, 'ServiceName',\n ( ['in'], c_int, 'index' ),\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IAGSServerObjectName)), 'ppSON' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether a service is selected.')], HRESULT, 'IsServiceSelected',\n ( ['in'], POINTER(comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IAGSServerObjectName), 'pSON' ),\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'bSelected' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether a service is selected.')], HRESULT, 'IsServiceSelected',\n ( ['in'], POINTER(comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IAGSServerObjectName), 'pSON' ),\n ( ['in'], VARIANT_BOOL, 'bSelected' )),\n COMMETHOD([helpstring(u'Add search service name.')], HRESULT, 'AddServiceName',\n ( ['in'], POINTER(comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IAGSServerObjectName), 'pSON' )),\n COMMETHOD([helpstring(u'Delete search service name.')], HRESULT, 'DeleteServiceName',\n ( ['in'], POINTER(comtypes.gen._746F6817_89BB_4490_9829_83CA25FD505A_0_10_2.IAGSServerObjectName), 'pSON' )),\n COMMETHOD([helpstring(u'Reset to default value and clean service names array.')], HRESULT, 'Empty'),\n COMMETHOD(['propget', helpstring(u'The maximum number of search result per page.')], HRESULT, 'MaxResultsPerPage',\n ( ['retval', 'out'], POINTER(c_int), 'pCount' )),\n COMMETHOD(['propput', helpstring(u'The maximum number of search result per page.')], HRESULT, 'MaxResultsPerPage',\n ( ['in'], c_int, 'pCount' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to show pop-up in search result page.')], HRESULT, 'ShowPopup',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pShow' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to show pop-up in search result page.')], HRESULT, 'ShowPopup',\n ( ['in'], VARIANT_BOOL, 'pShow' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to zoom to the select text based spatial search location.')], HRESULT, 'ZoomToSelectedLocation',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pZoomToSelectedLocation' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to zoom to the select text based spatial search location.')], HRESULT, 'ZoomToSelectedLocation',\n ( ['in'], VARIANT_BOOL, 'pZoomToSelectedLocation' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to use the built in WordNet synonyms.')], HRESULT, 'CheckSynonymsWordNet',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pCheckSynonymsWordNet' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to use the built in WordNet synonyms.')], HRESULT, 'CheckSynonymsWordNet',\n ( ['in'], VARIANT_BOOL, 'pCheckSynonymsWordNet' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to use custom synonyms.')], HRESULT, 'CheckSynonymsUserDefined',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pCheckSynonymsUserDefined' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to use custom synonyms.')], HRESULT, 'CheckSynonymsUserDefined',\n ( ['in'], VARIANT_BOOL, 'pCheckSynonymsUserDefined' )),\n COMMETHOD([helpstring(u'Resets the default values of the search options page.')], HRESULT, 'EmptySearchOptions'),\n COMMETHOD([helpstring(u'Resets the default values of the advanced options page and cleans the array of service names.')], HRESULT, 'EmptyAdvancedOptions'),\n]\n################################################################\n## code template for ISearchConfiguration implementation\n##class ISearchConfiguration_Impl(object):\n## def _get(self):\n## u'Indicates whether to use custom synonyms.'\n## #return pCheckSynonymsUserDefined\n## def _set(self, pCheckSynonymsUserDefined):\n## u'Indicates whether to use custom synonyms.'\n## CheckSynonymsUserDefined = property(_get, _set, doc = _set.__doc__)\n##\n## def SaveToFile(self, Path):\n## u'Save configuration settings to the specificed location.'\n## #return \n##\n## def _get(self):\n## u'Indicates whether to use the built in WordNet synonyms.'\n## #return pCheckSynonymsWordNet\n## def _set(self, pCheckSynonymsWordNet):\n## u'Indicates whether to use the built in WordNet synonyms.'\n## CheckSynonymsWordNet = property(_get, _set, doc = _set.__doc__)\n##\n## def AddServiceName(self, pSON):\n## u'Add search service name.'\n## #return \n##\n## def LoadFromFile(self, Path):\n## u'Load configuration settings from the specificed location.'\n## #return \n##\n## def EmptyAdvancedOptions(self):\n## u'Resets the default values of the advanced options page and cleans the array of service names.'\n## #return \n##\n## def _get(self):\n## u'Indicates whether to zoom to the select text based spatial search location.'\n## #return pZoomToSelectedLocation\n## def _set(self, pZoomToSelectedLocation):\n## u'Indicates whether to zoom to the select text based spatial search location.'\n## ZoomToSelectedLocation = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self, pSON):\n## u'Indicates whether a service is selected.'\n## #return bSelected\n## def _set(self, pSON, bSelected):\n## u'Indicates whether a service is selected.'\n## IsServiceSelected = property(_get, _set, doc = _set.__doc__)\n##\n## @property\n## def ServiceName(self, index):\n## u'The search service object name at the specified index.'\n## #return ppSON\n##\n## def Empty(self):\n## u'Reset to default value and clean service names array.'\n## #return \n##\n## @property\n## def ServicesCount(self):\n## u'The count of search services.'\n## #return pCount\n##\n## def _get(self):\n## u'The maximum number of search result per page.'\n## #return pCount\n## def _set(self, pCount):\n## u'The maximum number of search result per page.'\n## MaxResultsPerPage = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether to show pop-up in search result page.'\n## #return pShow\n## def _set(self, pShow):\n## u'Indicates whether to show pop-up in search result page.'\n## ShowPopup = property(_get, _set, doc = _set.__doc__)\n##\n## def EmptySearchOptions(self):\n## u'Resets the default values of the search options page.'\n## #return \n##\n## def DeleteServiceName(self, pSON):\n## u'Delete search service name.'\n## #return \n##\n\nclass IItemIndexer(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to members of indexer.'\n _iid_ = GUID('{B1213E5F-D10A-45DC-9413-6C39CFE1254E}')\n _idlflags_ = ['oleautomation']\nIItemIndexer._methods_ = [\n COMMETHOD(['propget', helpstring(u'Name of the indexer.')], HRESULT, 'IndexerName',\n ( ['retval', 'out'], POINTER(BSTR), 'pName' )),\n COMMETHOD(['propput', helpstring(u'Name of the indexer.')], HRESULT, 'IndexerName',\n ( ['in'], BSTR, 'pName' )),\n COMMETHOD([helpstring(u'Build index with indexing helper.')], HRESULT, 'BuildIndex',\n ( ['in'], POINTER(IIndexingConfiguration), 'pConfig' ),\n ( ['in'], POINTER(IItemIndex), 'pIItemIndex' )),\n]\n################################################################\n## code template for IItemIndexer implementation\n##class IItemIndexer_Impl(object):\n## def _get(self):\n## u'Name of the indexer.'\n## #return pName\n## def _set(self, pName):\n## u'Name of the indexer.'\n## IndexerName = property(_get, _set, doc = _set.__doc__)\n##\n## def BuildIndex(self, pConfig, pIItemIndex):\n## u'Build index with indexing helper.'\n## #return \n##\n\nclass ISearchServerAdmin(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to search server admin information.'\n _iid_ = GUID('{92CA4211-1C08-4A8E-A592-27A00C37D308}')\n _idlflags_ = ['oleautomation']\nISearchServerAdmin._methods_ = [\n COMMETHOD(['propget', helpstring(u'Search index location.')], HRESULT, 'SearchIndexLocation',\n ( ['retval', 'out'], POINTER(BSTR), 'SearchIndexLocation' )),\n]\n################################################################\n## code template for ISearchServerAdmin implementation\n##class ISearchServerAdmin_Impl(object):\n## @property\n## def SearchIndexLocation(self):\n## u'Search index location.'\n## #return SearchIndexLocation\n##\n\n\n# values for enumeration 'esriIndexingType'\nesriIndexingTypeFirstTimeFull = 0\nesriIndexingTypeFull = 1\nesriIndexingTypeIncremental = 2\nesriIndexingType = c_int # enum\nIIndexingStatus._methods_ = [\n COMMETHOD(['propget', helpstring(u'Indicates the indexing type.')], HRESULT, 'IndexingType',\n ( ['retval', 'out'], POINTER(esriIndexingType), 'IndexingType' )),\n COMMETHOD(['propput', helpstring(u'Indicates the indexing type.')], HRESULT, 'IndexingType',\n ( ['in'], esriIndexingType, 'IndexingType' )),\n COMMETHOD(['propget', helpstring(u'Indicates if the index tasks is running.')], HRESULT, 'IsRunning',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pValid' )),\n COMMETHOD(['propput', helpstring(u'Indicates if the index tasks is running.')], HRESULT, 'IsRunning',\n ( ['in'], VARIANT_BOOL, 'pValid' )),\n COMMETHOD(['propget', helpstring(u'Index start time.')], HRESULT, 'StartTime',\n ( ['retval', 'out'], POINTER(BSTR), 'StartTime' )),\n COMMETHOD(['propput', helpstring(u'Index start time.')], HRESULT, 'StartTime',\n ( ['in'], BSTR, 'StartTime' )),\n COMMETHOD(['propget', helpstring(u'Time used for indexing.')], HRESULT, 'TimeUsed',\n ( ['retval', 'out'], POINTER(c_int), 'TimeUsed' )),\n COMMETHOD(['propput', helpstring(u'Time used for indexing.')], HRESULT, 'TimeUsed',\n ( ['in'], c_int, 'TimeUsed' )),\n COMMETHOD(['propput', helpstring(u'Indicators whether items are indexed.')], HRESULT, 'ItemsIndexed',\n ( ['in'], c_int, 'ItemsIndexed' )),\n COMMETHOD(['propget', helpstring(u'Indicators whether items are indexed.')], HRESULT, 'ItemsIndexed',\n ( ['retval', 'out'], POINTER(c_int), 'ItemsIndexed' )),\n COMMETHOD(['propget', helpstring(u'Next Full indexing start time.')], HRESULT, 'NextFullIndexingStartTime',\n ( ['retval', 'out'], POINTER(BSTR), 'NextFullIndexingStartTime' )),\n COMMETHOD(['propput', helpstring(u'Next Full indexing start time.')], HRESULT, 'NextFullIndexingStartTime',\n ( ['in'], BSTR, 'NextFullIndexingStartTime' )),\n COMMETHOD(['propget', helpstring(u'Next Incremetal indexing start time.')], HRESULT, 'NextIncrementalIndexingStartTime',\n ( ['retval', 'out'], POINTER(BSTR), 'nextIncremetalIndexingStartTime' )),\n COMMETHOD(['propput', helpstring(u'Next Incremetal indexing start time.')], HRESULT, 'NextIncrementalIndexingStartTime',\n ( ['in'], BSTR, 'nextIncremetalIndexingStartTime' )),\n COMMETHOD(['propget', helpstring(u'Indicates next indexing type.')], HRESULT, 'NextIndexingType',\n ( ['retval', 'out'], POINTER(esriIndexingType), 'IndexingType' )),\n COMMETHOD(['propput', helpstring(u'Indicates next indexing type.')], HRESULT, 'NextIndexingType',\n ( ['in'], esriIndexingType, 'IndexingType' )),\n]\n################################################################\n## code template for IIndexingStatus implementation\n##class IIndexingStatus_Impl(object):\n## def _get(self):\n## u'Indicates the indexing type.'\n## #return IndexingType\n## def _set(self, IndexingType):\n## u'Indicates the indexing type.'\n## IndexingType = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Next Incremetal indexing start time.'\n## #return nextIncremetalIndexingStartTime\n## def _set(self, nextIncremetalIndexingStartTime):\n## u'Next Incremetal indexing start time.'\n## NextIncrementalIndexingStartTime = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Next Full indexing start time.'\n## #return NextFullIndexingStartTime\n## def _set(self, NextFullIndexingStartTime):\n## u'Next Full indexing start time.'\n## NextFullIndexingStartTime = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates next indexing type.'\n## #return IndexingType\n## def _set(self, IndexingType):\n## u'Indicates next indexing type.'\n## NextIndexingType = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates if the index tasks is running.'\n## #return pValid\n## def _set(self, pValid):\n## u'Indicates if the index tasks is running.'\n## IsRunning = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Time used for indexing.'\n## #return TimeUsed\n## def _set(self, TimeUsed):\n## u'Time used for indexing.'\n## TimeUsed = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Index start time.'\n## #return StartTime\n## def _set(self, StartTime):\n## u'Index start time.'\n## StartTime = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicators whether items are indexed.'\n## #return ItemsIndexed\n## def _set(self, ItemsIndexed):\n## u'Indicators whether items are indexed.'\n## ItemsIndexed = property(_get, _set, doc = _set.__doc__)\n##\n\nclass IndexingConfiguration(CoClass):\n u'Provide access to the IndexingConfiguration object.'\n _reg_clsid_ = GUID('{95572BB7-BC6D-4185-9CB2-CDF7E459DD9A}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nIndexingConfiguration._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, IIndexingConfiguration]\n\nclass DSCStatus(CoClass):\n u'Data source status object.'\n _reg_clsid_ = GUID('{CAD5A673-3499-4D43-842F-37CE02A9ECEA}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nDSCStatus._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, IDSCStatus, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IXMLSerialize, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersistStream, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersist, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IXMLVersionSupport]\n\nclass GPItemInfoHelper(CoClass):\n u'Item Info Helper.'\n _reg_clsid_ = GUID('{2EF6232E-2202-4FCF-A36E-31B3FA4AAA80}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nGPItemInfoHelper._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, IGPItemInfoHelper]\n\nIItemIndex2._methods_ = [\n COMMETHOD([helpstring(u'Update thumbnail info in index.')], HRESULT, 'UpdateThumbnail',\n ( ['in'], BSTR, 'catalogPath' ),\n ( ['in'], POINTER(comtypes.gen._0475BDB1_E5B2_4CA2_9127_B4B1683E70C2_0_10_2.IThumbnailInfo), 'pThumbInfo' )),\n COMMETHOD(['propget', helpstring(u'The CatalogPaths without thumbnail info.')], HRESULT, 'ItemsMissingThumbnails',\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IStringArray)), 'ppCatalogPaths' )),\n]\n################################################################\n## code template for IItemIndex2 implementation\n##class IItemIndex2_Impl(object):\n## @property\n## def ItemsMissingThumbnails(self):\n## u'The CatalogPaths without thumbnail info.'\n## #return ppCatalogPaths\n##\n## def UpdateThumbnail(self, catalogPath, pThumbInfo):\n## u'Update thumbnail info in index.'\n## #return \n##\n\n\n# values for enumeration 'esriDataSourceType'\nesriDataSourceTypeDatabase = 0\nesriDataSourceTypeFolder = 1\nesriDataSourceTypeServer = 2\nesriDataSourceType = c_int # enum\nIItemIndex3._methods_ = [\n COMMETHOD([helpstring(u'Adds another index.')], HRESULT, 'AddIndex',\n ( ['in'], BSTR, 'indexDirectory' ),\n ( ['in'], VARIANT_BOOL, 'dedup' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether if a give prefix matches any catalog path.')], HRESULT, 'PrefixExists',\n ( ['in'], BSTR, 'prefix' ),\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pbExsits' )),\n COMMETHOD([helpstring(u'Compares with another index.')], HRESULT, 'Compare',\n ( ['in'], BSTR, 'indexDirectory' ),\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IStringArray)), 'ppDiffs' )),\n]\n################################################################\n## code template for IItemIndex3 implementation\n##class IItemIndex3_Impl(object):\n## @property\n## def PrefixExists(self, prefix):\n## u'Indicates whether if a give prefix matches any catalog path.'\n## #return pbExsits\n##\n## def Compare(self, indexDirectory):\n## u'Compares with another index.'\n## #return ppDiffs\n##\n## def AddIndex(self, indexDirectory, dedup):\n## u'Adds another index.'\n## #return \n##\n\nclass GPItemIndexer(CoClass):\n u'GPItemIndexer object.'\n _reg_clsid_ = GUID('{3FCA2200-95F0-4B78-A575-4F0AAA04FCCE}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nclass IGPMultithreadedItemIndexer(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides access to multithreaded GP Indexer.'\n _iid_ = GUID('{DB185959-C37D-4B82-A6D4-CDDE04C8373B}')\n _idlflags_ = ['oleautomation']\nGPItemIndexer._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, IItemIndexer, IGPItemIndexer, IGPItemIndexer2, IGPMultithreadedItemIndexer]\n\nIGPMultithreadedItemIndexer._methods_ = [\n COMMETHOD(['propget', helpstring(u'The number of instances for index creation.')], HRESULT, 'ThreadCount',\n ( ['retval', 'out'], POINTER(c_int), 'pThreadCount' )),\n COMMETHOD(['propput', helpstring(u'The number of instances for index creation.')], HRESULT, 'ThreadCount',\n ( ['in'], c_int, 'pThreadCount' )),\n COMMETHOD(['propget', helpstring(u'The ArcGIS server object to perform index creation.')], HRESULT, 'ServerObjectName',\n ( ['retval', 'out'], POINTER(POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IName)), 'ppName' )),\n COMMETHOD(['propputref', helpstring(u'The ArcGIS server object to perform index creation.')], HRESULT, 'ServerObjectName',\n ( ['in'], POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IName), 'ppName' )),\n COMMETHOD([helpstring(u'Indexes items from an array of data sources.')], HRESULT, 'IndexItems',\n ( ['in'], POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IStringArray), 'pPaths' ),\n ( ['in'], VARIANT_BOOL, 'ReplaceIndex' ),\n ( ['in'], VARIANT_BOOL, 'Recursive' ),\n ( ['in'], BSTR, 'indexPath' ),\n ( ['in'], POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.ITrackCancel), 'pTrackCancel' )),\n]\n################################################################\n## code template for IGPMultithreadedItemIndexer implementation\n##class IGPMultithreadedItemIndexer_Impl(object):\n## def ServerObjectName(self, ppName):\n## u'The ArcGIS server object to perform index creation.'\n## #return \n##\n## def IndexItems(self, pPaths, ReplaceIndex, Recursive, indexPath, pTrackCancel):\n## u'Indexes items from an array of data sources.'\n## #return \n##\n## def _get(self):\n## u'The number of instances for index creation.'\n## #return pThreadCount\n## def _set(self, pThreadCount):\n## u'The number of instances for index creation.'\n## ThreadCount = property(_get, _set, doc = _set.__doc__)\n##\n\nclass IndexingOptions(CoClass):\n u'Indexing Options object.'\n _reg_clsid_ = GUID('{63B1F04D-A050-4DA8-957D-397FF55CBCD9}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{E418C392-C3A6-4EB2-8870-001ABAE6B5B4}', 10, 2)\nIndexingOptions._com_interfaces_ = [comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown, IIndexingOptions, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IXMLSerialize, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersistStream, comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.IPersist]\n\nclass IGPItemThumbnailIndexer(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IUnknown):\n _case_insensitive_ = True\n u'Provides to members for adding thumbnails to index.'\n _iid_ = GUID('{C1E4C2D8-1C52-4E53-B9AA-3C6B71F70E68}')\n _idlflags_ = ['oleautomation']\nIGPItemThumbnailIndexer._methods_ = [\n COMMETHOD([helpstring(u'Generate thumbnails in Index')], HRESULT, 'GenerateThumbnails'),\n COMMETHOD(['propget', helpstring(u'Percent of updated thumbnails.')], HRESULT, 'Percent',\n ( ['retval', 'out'], POINTER(c_int), 'pPercent' )),\n]\n################################################################\n## code template for IGPItemThumbnailIndexer implementation\n##class IGPItemThumbnailIndexer_Impl(object):\n## @property\n## def Percent(self):\n## u'Percent of updated thumbnails.'\n## #return pPercent\n##\n## def GenerateThumbnails(self):\n## u'Generate thumbnails in Index'\n## #return \n##\n\nIDataSourceConfiguration._methods_ = [\n COMMETHOD(['propget', helpstring(u'Data source type.')], HRESULT, 'Type',\n ( ['retval', 'out'], POINTER(esriDataSourceType), 'Type' )),\n COMMETHOD(['propput', helpstring(u'Data source type.')], HRESULT, 'Type',\n ( ['in'], esriDataSourceType, 'Type' )),\n COMMETHOD(['propget', helpstring(u'Catalogpath of Data source.')], HRESULT, 'Path',\n ( ['retval', 'out'], POINTER(BSTR), 'Path' )),\n COMMETHOD(['propput', helpstring(u'Catalogpath of Data source.')], HRESULT, 'Path',\n ( ['in'], BSTR, 'Path' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether it is revursive index.')], HRESULT, 'Recursive',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'Recursive' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether it is revursive index.')], HRESULT, 'Recursive',\n ( ['in'], VARIANT_BOOL, 'Recursive' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether it replaces existing index.')], HRESULT, 'ReplaceItems',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'ReplaceItems' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether it replaces existing index.')], HRESULT, 'ReplaceItems',\n ( ['in'], VARIANT_BOOL, 'ReplaceItems' )),\n COMMETHOD(['propget', helpstring(u'Indexing start time.')], HRESULT, 'StartTime',\n ( ['retval', 'out'], POINTER(BSTR), 'StartTime' )),\n COMMETHOD(['propput', helpstring(u'Indexing start time.')], HRESULT, 'StartTime',\n ( ['in'], BSTR, 'StartTime' )),\n COMMETHOD(['propget', helpstring(u'Repeat interval of indexing.')], HRESULT, 'RepeatInterval',\n ( ['retval', 'out'], POINTER(c_int), 'RepeatInterval' )),\n COMMETHOD(['propput', helpstring(u'Repeat interval of indexing.')], HRESULT, 'RepeatInterval',\n ( ['in'], c_int, 'RepeatInterval' )),\n]\n################################################################\n## code template for IDataSourceConfiguration implementation\n##class IDataSourceConfiguration_Impl(object):\n## def _get(self):\n## u'Repeat interval of indexing.'\n## #return RepeatInterval\n## def _set(self, RepeatInterval):\n## u'Repeat interval of indexing.'\n## RepeatInterval = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether it is revursive index.'\n## #return Recursive\n## def _set(self, Recursive):\n## u'Indicates whether it is revursive index.'\n## Recursive = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether it replaces existing index.'\n## #return ReplaceItems\n## def _set(self, ReplaceItems):\n## u'Indicates whether it replaces existing index.'\n## ReplaceItems = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indexing start time.'\n## #return StartTime\n## def _set(self, StartTime):\n## u'Indexing start time.'\n## StartTime = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Catalogpath of Data source.'\n## #return Path\n## def _set(self, Path):\n## u'Catalogpath of Data source.'\n## Path = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Data source type.'\n## #return Type\n## def _set(self, Type):\n## u'Data source type.'\n## Type = property(_get, _set, doc = _set.__doc__)\n##\n\nIIndexingOptions._methods_ = [\n COMMETHOD(['propget', helpstring(u'Incremental index interval.')], HRESULT, 'IncrementalIndexInterval',\n ( ['retval', 'out'], POINTER(c_int), 'pInterval' )),\n COMMETHOD(['propput', helpstring(u'Incremental index interval.')], HRESULT, 'IncrementalIndexInterval',\n ( ['in'], c_int, 'pInterval' )),\n COMMETHOD(['propget', helpstring(u'Full index interval.')], HRESULT, 'FullIndexInterval',\n ( ['retval', 'out'], POINTER(c_int), 'pInterval' )),\n COMMETHOD(['propput', helpstring(u'Full index interval.')], HRESULT, 'FullIndexInterval',\n ( ['in'], c_int, 'pInterval' )),\n COMMETHOD(['propget', helpstring(u'Index start time.')], HRESULT, 'StartTime',\n ( ['retval', 'out'], POINTER(BSTR), 'StartTime' )),\n COMMETHOD(['propput', helpstring(u'Index start time.')], HRESULT, 'StartTime',\n ( ['in'], BSTR, 'StartTime' )),\n]\n################################################################\n## code template for IIndexingOptions implementation\n##class IIndexingOptions_Impl(object):\n## def _get(self):\n## u'Full index interval.'\n## #return pInterval\n## def _set(self, pInterval):\n## u'Full index interval.'\n## FullIndexInterval = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Index start time.'\n## #return StartTime\n## def _set(self, StartTime):\n## u'Index start time.'\n## StartTime = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Incremental index interval.'\n## #return pInterval\n## def _set(self, pInterval):\n## u'Incremental index interval.'\n## IncrementalIndexInterval = property(_get, _set, doc = _set.__doc__)\n##\n\nIDSCStatus._methods_ = [\n COMMETHOD(['propget', helpstring(u'Catalog Path of Data Source.')], HRESULT, 'Path',\n ( ['retval', 'out'], POINTER(BSTR), 'Path' )),\n COMMETHOD(['propput', helpstring(u'Catalog Path of Data Source.')], HRESULT, 'Path',\n ( ['in'], BSTR, 'Path' )),\n COMMETHOD(['propget', helpstring(u'Job ID of the Data Source.')], HRESULT, 'JobID',\n ( ['retval', 'out'], POINTER(BSTR), 'JobID' )),\n COMMETHOD(['propput', helpstring(u'Job ID of the Data Source.')], HRESULT, 'JobID',\n ( ['in'], BSTR, 'JobID' )),\n COMMETHOD(['propget', helpstring(u'JobStatus of the Data Source.')], HRESULT, 'JobStatus',\n ( ['retval', 'out'], POINTER(comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.esriJobStatus), 'JobID' )),\n COMMETHOD(['propput', helpstring(u'JobStatus of the Data Source.')], HRESULT, 'JobStatus',\n ( ['in'], comtypes.gen._5E1F7BC3_67C5_4AEE_8EC6_C4B73AAC42ED_0_10_2.esriJobStatus, 'JobID' )),\n]\n################################################################\n## code template for IDSCStatus implementation\n##class IDSCStatus_Impl(object):\n## def _get(self):\n## u'Catalog Path of Data Source.'\n## #return Path\n## def _set(self, Path):\n## u'Catalog Path of Data Source.'\n## Path = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'JobStatus of the Data Source.'\n## #return JobID\n## def _set(self, JobID):\n## u'JobStatus of the Data Source.'\n## JobStatus = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Job ID of the Data Source.'\n## #return JobID\n## def _set(self, JobID):\n## u'Job ID of the Data Source.'\n## JobID = property(_get, _set, doc = _set.__doc__)\n##\n\nclass IDataSourceConfiguration2(IDataSourceConfiguration):\n _case_insensitive_ = True\n u'Provides access to data source configuration.'\n _iid_ = GUID('{A1CA9D07-71B5-4D6B-B6FA-663345FBC4FE}')\n _idlflags_ = ['oleautomation']\nIDataSourceConfiguration2._methods_ = [\n COMMETHOD(['propget', helpstring(u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.')], HRESULT, 'SkipConnections',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pSkipConnections' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.')], HRESULT, 'SkipConnections',\n ( ['in'], VARIANT_BOOL, 'pSkipConnections' )),\n COMMETHOD(['propget', helpstring(u'Indicates whether to skip mosaic dataset items when indexing.')], HRESULT, 'SkipMosaicItems',\n ( ['retval', 'out'], POINTER(VARIANT_BOOL), 'pSkipMosaicItems' )),\n COMMETHOD(['propput', helpstring(u'Indicates whether to skip mosaic dataset items when indexing.')], HRESULT, 'SkipMosaicItems',\n ( ['in'], VARIANT_BOOL, 'pSkipMosaicItems' )),\n]\n################################################################\n## code template for IDataSourceConfiguration2 implementation\n##class IDataSourceConfiguration2_Impl(object):\n## def _get(self):\n## u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.'\n## #return pSkipConnections\n## def _set(self, pSkipConnections):\n## u'Indicates whether to skip connection files (sde, ags, wcs, wms, etc) copied to non-default locations.'\n## SkipConnections = property(_get, _set, doc = _set.__doc__)\n##\n## def _get(self):\n## u'Indicates whether to skip mosaic dataset items when indexing.'\n## #return pSkipMosaicItems\n## def _set(self, pSkipMosaicItems):\n## u'Indicates whether to skip mosaic dataset items when indexing.'\n## SkipMosaicItems = property(_get, _set, doc = _set.__doc__)\n##\n\n__all__ = ['IItemIndex3', 'IItemIndex2', 'IDataSourceConfiguration2',\n 'esriDataSourceTypeFolder', 'GPItemIndexer', 'IDSCStatus',\n 'ISearchConfiguration', 'IGPItemInfoHelper', 'DSCStatus',\n 'IIndexingOptions', 'IIndexingConfiguration2',\n 'IIndexingConfiguration3', 'SearchServerObjectDescription',\n 'IIndexingStatus', 'GPItemInfoHelper', 'IItemIndexer',\n 'ISearchServer', 'IDSCStatusArray',\n 'esriIndexingTypeFirstTimeFull',\n 'esriDataSourceTypeDatabase', 'SearchServerIP',\n 'IGPItemIndexer2', 'SearchConfiguration',\n 'IIndexingConfiguration', 'IProtectNameSearch',\n 'esriIndexingTypeIncremental', 'SearchServerLP',\n 'IndexingStatus', 'esriIndexingType',\n 'esriIndexingTypeFull', 'IndexingOptions',\n 'IGPItemIndexer', 'IItemIndexAdmin',\n 'IGPItemThumbnailIndexer', 'DataSourceConfiguration',\n 'DSCStatusArray', 'ItemIndex', 'esriDataSourceTypeServer',\n 'IItemIndex', 'IndexingConfiguration',\n 'esriDataSourceType', 'IGPMultithreadedItemIndexer',\n 'SearchServerConfigurationFactory', 'ISearchServerAdmin',\n 'IDataSourceConfiguration']\nfrom comtypes import _check_version; _check_version('501')\n","repo_name":"nohe427/MyAddins","sub_path":"Shana/RemoveData/Install/comtypes/gen/_E418C392_C3A6_4EB2_8870_001ABAE6B5B4_0_10_2.py","file_name":"_E418C392_C3A6_4EB2_8870_001ABAE6B5B4_0_10_2.py","file_ext":"py","file_size_in_byte":78984,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"1442632617","text":"#!/usr/bin/python3\n\"\"\"\nFly-by-Pi Controller\n\t\nClass file for the motor driver (Pololu 24v13). Simplifies the\ncontrol motor driver by exposing function to enable/disengage\nthe motor, set the speed (duty cycle) and direction of movement.\nStandard Raspberry Pi pinouts are used.\n\nModified by Andre Broekman 2020/05/13\nOpen Source License: Creative Commons Attribution-ShareAlike\n\"\"\"\n\nimport RPi.GPIO as GPIO\nfrom time import sleep\n\nclass cMotorDriver:\n def __init__(self): \n self.pinAssign = [18, 27, 22] # PWM, DIR, SLP\n self.enabled = 0 # LOW state disables the driver, HIGH state enables the driver\n self.direction = 0 # 0 = Current flows from OUTB to OUTA // 1 = Current flows from OUTA to OUTB\n self.speed = 0 # PWM value\n try:\n GPIO.setmode(GPIO.BCM) # Use Broadcom chip-specific numbering scheme\n for pin in self.pinAssign: # Set all pins as output\n GPIO.setup(pin, GPIO.OUT)\n self.p = GPIO.PWM(self.pinAssign[0], 300) # 300 Hz PWM frequency\n self.p.start(0) # Start the PWM generator (0% duty cycle)\n except:\n print(\"MotorDriver class _init_ exception\")\n\n\n def setEnable(self, enabled=0): # enable the motor\n try:\n if enabled == 1:\n GPIO.output(self.pinAssign[2], 1)\n self.enabled = 1\n else:\n GPIO.output(self.pinAssign[2], 0)\n self.enabled = 0\n except:\n print(\"motor enable: try exception\")\n\n\n def toggleSleep(self): # toggle the motor sleep state\n try:\n if self.enabled == 0:\n GPIO.output(self.pinAssign[2], 1)\n self.enabled = 1\n else:\n GPIO.output(self.pinAssign[2], 0)\n self.enabled = 0\n except:\n print(\"motor sleep toggle: try exception\")\n\n\n def setForward(self): # set the actuator to extend (go forward)\n try:\n GPIO.output(self.pinAssign[1], 1)\n self.direction = 1\n except:\n print(\"motor forward: try exception\")\n\n\n def setBackward(self): # set the actuator to retract (go backward)\n try:\n GPIO.output(self.pinAssign[1], 0)\n self.direction = 0\n except:\n print(\"motor backward: try exception\")\n\n\n def toggleDirection(self): # toggle the direction of the motor\n try:\n if self.direction == 0:\n GPIO.output(self.pinAssign[1], 1)\n self.direction = 1\n else:\n GPIO.output(self.pinAssign[1], 0)\n self.direction = 0\n except:\n print(\"motor sleep toggle: try exception\")\n\n\n def setSpeed(self, speed=0): # set the duty cycle of PWM pin (0-100%)\n if speed in range(101):\n try:\n self.p.ChangeDutyCycle(speed)\n except:\n print(\"motor speed: try exception\")\n else:\n try:\n self.p.ChangeDutyCycle(0)\n except:\n print(\"motor speed: catastrophic exception\")\n ","repo_name":"andrebroekman/FlyByPi","sub_path":"mMotorDriver.py","file_name":"mMotorDriver.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"70158231895","text":"import cv2 as cv\r\nimport numpy as np\r\nfrom read_a_image_series import read_an_image_series\r\n\r\nif __name__ == '__main__':\r\n\r\n # determine how much fast results are shown\r\n delay = 50\r\n\r\n # apply mixture of gaussian on different sequence of images\r\n for folder_name in ['birds', 'boats', 'bottle', 'cyclists', 'surf']:\r\n\r\n # read a sequence of image\r\n cap = cv.VideoCapture('C:\\\\Users\\\\Home\\\\Dropbox\\\\codes\\\\CV\\\\96131125_HW06\\\\JPEGS_min_v2\\\\JPEGS\\\\{}\\\\frame_%02d.jpg'.format(folder_name))\r\n\r\n # Define the codec and create VideoWriter object\r\n fourcc = cv.VideoWriter_fourcc(*'DIVX')\r\n out = cv.VideoWriter('.\\\\mog_output\\\\output-{}.avi'.format(folder_name), fourcc, 10.0, (int(cap.get(3)),int(cap.get(4))))\r\n\r\n # create MOG\r\n mog = cv.bgsegm.createBackgroundSubtractorMOG()\r\n while True:\r\n ret, frame = cap.read()\r\n # apply MOG\r\n fgmask = mog.apply(frame)\r\n if fgmask is None:\r\n break\r\n cv.imshow('frame', fgmask)\r\n fgmask_rbg = cv.cvtColor(fgmask,cv.COLOR_GRAY2BGR)\r\n out.write(fgmask_rbg)\r\n k = cv.waitKey(delay) & 0xff\r\n if k == 27:\r\n break\r\n cap.release()\r\n out.release()\r\n cv.destroyAllWindows()\r\n","repo_name":"farhad-dalirani/AUT_Computer_Vision","sub_path":"96131125_HW06/mixture_of_gaussians.py","file_name":"mixture_of_gaussians.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71895175892","text":"from cgitb import text\nfrom tempfile import TemporaryFile\nfrom typing import List\nfrom pygame import mixer\nfrom tkinter import *\nimport tkinter.font as font\nfrom tkinter import filedialog, messagebox\n\nsongs = {}\n\ndef play():\n try:\n current_list = songs[Listofsongs.get(ACTIVE)]\n current = current_list[0]\n Listofsongs.selection_set(current_list[1])\n mixer.music.load(f'{current}')\n mixer.music.play()\n except:\n pass\n\ndef pause():\n mixer.music.pause()\n\ndef next():\n try:\n try:\n next_song = Listofsongs.curselection()[0]\n except:\n next_song = songs[Listofsongs.get(ACTIVE)][1]\n\n if next_song == len(songs)-1:\n stop()\n return 0\n else:\n next_song = next_song + 1\n\n try:\n ns = songs[Listofsongs.get(next_song)][0]\n except:\n try:\n ns = songs[Listofsongs.get(0)][0]\n except:\n messagebox.showinfo(\"\",\"0 songs available in the queue\")\n return 0\n mixer.music.load(f'{ns}')\n mixer.music.play()\n Listofsongs.selection_clear(0, END)\n Listofsongs.activate(next_song)\n Listofsongs.selection_set(next_song)\n except:\n pass\n \n\ndef previous():\n try:\n try:\n previous_song = Listofsongs.curselection()[0]\n except:\n previous_song = songs[Listofsongs.get(ACTIVE)][1]\n if (previous_song == 0):\n previous_song = 1\n previous_song = previous_song-1\n Listofsongs.selection_set(previous_song)\n\n try:\n ps = songs[Listofsongs.get(previous_song)][0]\n except:\n try:\n ps = songs[Listofsongs.get(END)][0]\n except:\n messagebox.showinfo(\"\",\"0 songs available in the queue\")\n return 0\n mixer.music.load(f'{ps}')\n mixer.music.play()\n\n Listofsongs.selection_clear(0, END)\n Listofsongs.activate(previous_song)\n Listofsongs.selection_set(previous_song)\n except:\n pass\n\ndef resume():\n try:\n song_pla = songs[Listofsongs.get(ACTIVE)]\n mixer.music.load(song_pla[0])\n mixer.music.play()\n Listofsongs.selection_set(song_pla[1])\n except:\n pass\n\ndef stop():\n mixer.music.stop()\n Listofsongs.selection_clear(ACTIVE)\n\ndef addsongs():\n song=filedialog.askopenfilenames(initialdir=\"Music/\",title=\"Choose a song\", filetypes=((\"mp3 Files\",\"*.mp3\"),))\n\n for i in song:\n e = i.split(\"/\")[-1]\n songs[e] = [i, len(songs)]\n Listofsongs.insert(END, e)\n\ndef deletesong():\n try:\n current=Listofsongs.curselection()\n songs.pop(Listofsongs.get(current[0]))\n Listofsongs.delete(current[0])\n except:\n messagebox.showerror(\"Error\", \"No song is selected\")\n\nroot = Tk()\nroot.title(\"Media Player\")\nmixer.init()\nListofsongs = Listbox(root, selectmode= SINGLE, bg=\"black\", fg=\"green\", font=('arial',15),height=12,width=47,selectbackground=\"gray\",selectforeground=\"black\")\nListofsongs.grid(columnspan=9)\n\n\ndefined_font = font.Font(family='Helvetica')\n\nplay_but = Button(root, text=\"Play\", width=7, command=play)\nplay_but['font'] = defined_font\nplay_but.grid(row=1, column=0)\n\npause_but = Button(root, text=\"Pause\", width=7, command=pause)\npause_but['font'] = defined_font\npause_but.grid(row=1, column=1)\n\nnext_but = Button(root, text=\"Next\", width=7, command=next)\nnext_but['font'] = defined_font\nnext_but.grid(row=1, column=2)\n\nprevious_but = Button(root, text=\"Previous\", width=7, command=previous)\nprevious_but['font'] = defined_font\nprevious_but.grid(row=1, column=3)\n\nResume_but = Button(root, text=\"Resume\", width=7, command=resume)\nResume_but['font'] = defined_font\nResume_but.grid(row=1, column=4)\n\nstop_but = Button(root, text=\"Stop\", width=7, command=stop)\nstop_but['font'] = defined_font\nstop_but.grid(row=1, column=5)\n\n\nnav = Menu(root)\nroot.config(menu = nav)\nadd_song_menu=Menu(nav)\nnav.add_cascade(label=\"Menu\",menu=add_song_menu)\nadd_song_menu.add_command(label=\"Add songs\",command=addsongs)\nadd_song_menu.add_command(label=\"Delete song\",command=deletesong)\n\n\nmainloop()","repo_name":"DeeshantGupta/unicompiler_tasks","sub_path":"task3_final.py","file_name":"task3_final.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17035529520","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# 데이터 불러오기 : 타이타닉 예제\r\ndata = pd.read_csv('https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv')\r\n# print(data.head(5)) # Raw 데이터\r\n# print(data.isna().sum()) # 데이터 확인 : Null 값 여부\r\n\r\n# 데이터 전처리\r\ndata['Sex'] = data['Sex'].map({'male':0, 'female':1}) # 성별 데이터를 숫자로 변환\r\ntarget = data['Survived'] # 타겟 데이터 세트\r\ndata.drop(labels=['Name', 'Survived'], axis=1, inplace=True) # 필요없는 데이터 제거 : 이름, 생존여부\r\n# print(data)\r\n\r\n# dataframe 열 이름 변경\r\ndata.rename(columns={'Siblings/Spouses Aboard':'Spouses',\r\n 'Parents/Children Aboard':'Children'}, inplace=True)\r\n\r\n# 훈련 데이터 중에서 랜덤으로 테스트 세트 추출\r\ntrain_input, test_input, train_target, test_target = train_test_split(data, target,\r\n stratify=target,\r\n test_size=0.2,\r\n random_state=5)\r\n\r\n# 로지스틱 회귀 알고리즘 훈련 : 훈련 반복 횟수 1000회\r\nlr = LogisticRegression(max_iter=1000, solver='lbfgs', multi_class='auto')\r\nlr.fit(train_input, train_target)\r\n\r\n# 회귀 함수\r\nnp.set_printoptions(precision=3,suppress=True) # numpy print 자릿수\r\nprint('>>변수 =', data.columns.values)\r\nprint('>>결정계수 =', lr.coef_[0])\r\n\r\n# 예측 결과 출력\r\nprint('\\n>>테스트 세트 데이터\\n', test_input.iloc[0:5])\r\nprint('\\n>>테스트 세트 z값\\n', lr.decision_function(test_input[0:5]))\r\nprint('\\n>>테스트 세트 예측 확률\\n', lr.predict_proba(test_input[0:5]))\r\nprint('\\n>>테스트 세트 예측 결과\\n', lr.predict(test_input[0:5]))\r\n\r\n# 생존 테스트 : 2등석, 남자, 25세, 혼자, 혼자, 50달러\r\nnew_data = [2, 0, 25, 0, 0, 50]\r\nnew_pred = lr.predict([new_data])\r\nprint('\\n>>생존 테스트 =',new_data)\r\nprint('>>[사망 확률, 생존 확률] =', format(lr.predict_proba([new_data])))\r\nif(new_pred[0]==0): print('>>사망 ㅜㅜ\\n')\r\nelse: print('>>생존 ^^\\n')\r\n","repo_name":"kkangjm/class_room","sub_path":"Python_ML/ch_05/ch05_Binomial_Logistic.py","file_name":"ch05_Binomial_Logistic.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36663631142","text":"def same_structure_as(original,other):\n print(original, other)\n brackets = (\"[\", \"]\")\n or_stack = \"\"\n ot_stack = \"\"\n open = False\n for c in str(original):\n if c == '\\'':\n open = not open\n elif c in brackets and not open:\n or_stack += c\n else:\n or_stack += \"_\"\n for c in str(other):\n if c == '\\'':\n open = not open\n elif c in brackets and not open:\n ot_stack += c\n else:\n ot_stack += \"_\"\n return or_stack == ot_stack\n","repo_name":"dsipakou/codewars","sub_path":"nes_str.py","file_name":"nes_str.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20670661019","text":"#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting\nimport os\ntry:\n\tos.chdir(os.path.join(os.getcwd(), '../Presencial 8'))\n\tprint(os.getcwd())\nexcept:\n\tpass\n\n#%%\nimport pandas as pd\n\ndf = pd.read_csv('athlete_events.csv')\ndf.head()\n\n\n#%%\nejercicio_1 = df.shape\nejercicio_1\n\n\n#%%\nejercicio_2 = df[\"Games\"].unique().size\nejercicio_2\n\n\n#%%\nejercicio_3 = df[\"Season\"].value_counts(normalize = True)\nejercicio_3\n\n\n#%%\npre_4 = df[df[\"Season\"] == \"Summer\"]\npost_4 = pre_4[pre_4[\"Year\"] == pre_4[\"Year\"].min()]\nejercicio_4 = post_4[\"City\"].tolist()[0]\nejercicio_4\n\n\n#%%\npre_5 = df[df[\"Season\"] == \"Winter\"]\npost_5 = pre_5[pre_5[\"Year\"] == pre_5[\"Year\"].min()]\nejercicio_5 = post_5[\"City\"].tolist()[0]\nejercicio_5\n\n\n#%%\npre_6 = df[\"Team\"].value_counts()\nejercicio_6 = pre_6.head(10)\nejercicio_6\n\n\n#%%\nejercicio_7 = df[\"Medal\"].value_counts(normalize = True, dropna=True)\nejercicio_7\n\n\n#%%\npre_8 = df[df[\"Season\"] == \"Summer\"]\npost_8 = pre_8[pre_8[\"Year\"] == pre_8[\"Year\"].min()]\nejercicio_8 = post_8[\"Team\"].unique()\nejercicio_8\n\n\n#%%\n\n\n\n","repo_name":"Eddonofuture/DSDesafLatam","sub_path":"Introduccion a Programacion/Presencial 8/juegos.py","file_name":"juegos.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11833150217","text":"# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n\nfrom RobotLibrary import i2c as i2c\n\nI2C_STATUS\t\t= 0\nI2C_CMD\t\t\t= 1\nI2C_CMD_ARG1\t = 2\nI2C_CMD_ARG2\t = 3\nI2C_CMD_ARG3\t = 4\nI2C_CMD_ARG4\t = 5\nI2C_CELL1VOLTl = 6\nI2C_CELL1VOLTh = 7\nI2C_CELL2VOLTl = 8\nI2C_CELL2VOLTh = 9\nI2C_CELL3VOLTl = 10\nI2C_CELL3VOLTh = 11\nI2C_CELL4VOLTl = 12\nI2C_CELL4VOLTh = 13\nI2C_CELL1PERC = 14\nI2C_CELL2PERC = 15\nI2C_CELL3PERC = 16\nI2C_CELL4PERC = 17\n\nNOCMD\t\t\t= 0\nCMD_STOP\t\t= 1\nCMD_WRITEREG\t= 2\nCMD_USERANGLE\t= 3\nCMD_USERSPEED\t= 4\nCMD_MOTORL\t\t= 5\nCMD_MOTORR\t\t= 6\nCMD_MOVEMODE\t= 7\n\nMoveMode_Torque = 1\nMoveMode_Speed\t= 2\n\nSLAVE_ADDRESS = 0x30\n\ndef GET_BAT():\n i2c.SETSLAVE(SLAVE_ADDRESS)\n bat = {}\n bat[\"CELL1\"] = {}\n bat[\"CELL1\"][\"VOLT\"] = (i2c.READ(I2C_CELL1VOLTh)*128+i2c.READ(I2C_CELL1VOLTl))/1000\n bat[\"CELL1\"][\"PERCENTAGE\"] = i2c.READ(I2C_CELL1PERC)\n bat[\"CELL2\"] = {}\n bat[\"CELL2\"][\"VOLT\"] = (i2c.READ(I2C_CELL2VOLTh)*128+i2c.READ(I2C_CELL2VOLTl))/1000\n bat[\"CELL2\"][\"PERCENTAGE\"] = i2c.READ(I2C_CELL2PERC)\n bat[\"CELL3\"] = {}\n bat[\"CELL3\"][\"VOLT\"] = (i2c.READ(I2C_CELL3VOLTh)*128+i2c.READ(I2C_CELL3VOLTl))/1000\n bat[\"CELL3\"][\"PERCENTAGE\"] = i2c.READ(I2C_CELL3PERC)\n bat[\"CELL4\"] = {}\n bat[\"CELL4\"][\"VOLT\"] = (i2c.READ(I2C_CELL4VOLTh)*128+i2c.READ(I2C_CELL4VOLTl))/1000\n bat[\"CELL4\"][\"PERCENTAGE\"] = i2c.READ(I2C_CELL4PERC)\n \n return bat\n\t\ndef GET_STATUS():\n\ti2c.SETSLAVE(SLAVE_ADDRESS)\n\tstatus = {}\n\t#status[\"angle\"] = int(i2c.READ(I2C_ANGLE))-100\n\t#status[\"FLpower\"] = int(i2c.READ(I2C_FLpower))-100\n\t#status[\"FLspeed\"] = int(i2c.READ(I2C_FLspeed))-100\n\t#status[\"FLspdmeas\"] = int(i2c.READ(I2C_FLspdmeas))-100\n\t#status[\"FRpower\"] = int(i2c.READ(I2C_FRpower))-100\n\t#status[\"FRspeed\"] = int(i2c.READ(I2C_FRspeed))-100\n\t#status[\"FRspdmeas\"] = int(i2c.READ(I2C_FRspdmeas))-100\n\t#status[\"BLpower\"] = int(i2c.READ(I2C_BLpower))-100\n\t#status[\"BLspeed\"] = int(i2c.READ(I2C_BLspeed))-100\n\t#status[\"BLspdmeas\"] = int(i2c.READ(I2C_BLspdmeas))-100\n\t#status[\"BRpower\"] = int(i2c.READ(I2C_BRpower))-100\n\t#status[\"BRspeed\"] = int(i2c.READ(I2C_BRspeed))-100\n\t#status[\"BRspdmeas\"] = int(i2c.READ(I2C_BRspdmeas))-100\n\t#MoveMode = int(i2c.READ(I2C_MoveMode))\n\t#if MoveMode == MoveMode_Speed:\n\t#\tstatus[\"MoveMode\"] = \"Speed\"\n\t#elif MoveMode == MoveMode_Torque:\n\t#\tstatus[\"MoveMode\"] = \"Torque\"\n\treturn status\n\t\n\t\n","repo_name":"schuhumi/autocut","sub_path":"Software/Main Module/Commandserver/RobotLibrary/robot_powersupply.py","file_name":"robot_powersupply.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"67"} +{"seq_id":"5599508309","text":"from setuptools import setup\n\ndependencies = [\n \"blspy==1.0.5\", # Signature library\n \"chiavdf==1.0.2\", # timelord and vdf verification\n \"chiabip158==1.0\", # bip158-style wallet filters\n \"chiapos==1.0.4\", # proof of space\n \"clvm==0.9.7\",\n \"clvm_rs==0.1.8\",\n \"clvm_tools==0.4.3\",\n \"aiohttp==3.7.4\", # HTTP server for full node rpc\n \"aiosqlite==0.17.0\", # asyncio wrapper for sqlite, to store blocks\n \"bitstring==3.1.7\", # Binary data management library\n \"colorlog==5.0.1\", # Adds color to logs\n \"concurrent-log-handler==0.9.19\", # Concurrently log and rotate logs\n \"cryptography==3.4.7\", # Python cryptography library for TLS - keyring conflict\n \"keyring==23.0.1\", # Store keys in MacOS Keychain, Windows Credential Locker\n \"keyrings.cryptfile==1.3.4\", # Secure storage for keys on Linux (Will be replaced)\n # \"keyrings.cryptfile==1.3.8\", # Secure storage for keys on Linux (Will be replaced)\n # See https://github.com/frispete/keyrings.cryptfile/issues/15\n \"PyYAML==5.4.1\", # Used for config file format\n \"setproctitle==1.2.2\", # Gives the chia processes readable names\n \"sortedcontainers==2.3.0\", # For maintaining sorted mempools\n \"websockets==8.1.0\", # For use in wallet RPC and electron UI\n \"click==7.1.2\", # For the CLI\n \"dnspython==2.1.0\", # Query DNS seeds\n]\n\nupnp_dependencies = [\n \"miniupnpc==2.2.2\", # Allows users to open ports on their router\n]\n\ndev_dependencies = [\n \"pytest\",\n \"pytest-asyncio\",\n \"flake8\",\n \"mypy\",\n \"black\",\n \"aiohttp_cors\", # For blackd\n \"ipython\", # For asyncio debugging\n]\n\nkwargs = dict(\n name=\"kiwi-blockchain\",\n author=\"Mariano Sorgente\",\n author_email=\"mariano@chia.net\",\n description=\"Kiwi blockchain full node, farmer, timelord, and wallet.\",\n url=\"https://kiwinetwork.org/\",\n license=\"Apache License\",\n python_requires=\">=3.7, <4\",\n keywords=\"kiwi blockchain node\",\n install_requires=dependencies,\n setup_requires=[\"setuptools_scm\"],\n extras_require=dict(\n uvloop=[\"uvloop\"],\n dev=dev_dependencies,\n upnp=upnp_dependencies,\n ),\n packages=[\n \"build_scripts\",\n \"kiwi\",\n \"kiwi.cmds\",\n \"kiwi.clvm\",\n \"kiwi.consensus\",\n \"kiwi.daemon\",\n \"kiwi.full_node\",\n \"kiwi.timelord\",\n \"kiwi.farmer\",\n \"kiwi.harvester\",\n \"kiwi.introducer\",\n \"kiwi.plotting\",\n \"kiwi.pools\",\n \"kiwi.protocols\",\n \"kiwi.rpc\",\n \"kiwi.server\",\n \"kiwi.simulator\",\n \"kiwi.types.blockchain_format\",\n \"kiwi.types\",\n \"kiwi.util\",\n \"kiwi.wallet\",\n \"kiwi.wallet.puzzles\",\n \"kiwi.wallet.rl_wallet\",\n \"kiwi.wallet.cc_wallet\",\n \"kiwi.wallet.did_wallet\",\n \"kiwi.wallet.settings\",\n \"kiwi.wallet.trading\",\n \"kiwi.wallet.util\",\n \"kiwi.ssl\",\n \"mozilla-ca\",\n ],\n entry_points={\n \"console_scripts\": [\n \"kiwi = kiwi.cmds.kiwi:main\",\n \"kiwi_wallet = kiwi.server.start_wallet:main\",\n \"kiwi_full_node = kiwi.server.start_full_node:main\",\n \"kiwi_harvester = kiwi.server.start_harvester:main\",\n \"kiwi_farmer = kiwi.server.start_farmer:main\",\n \"kiwi_introducer = kiwi.server.start_introducer:main\",\n \"kiwi_timelord = kiwi.server.start_timelord:main\",\n \"kiwi_timelord_launcher = kiwi.timelord.timelord_launcher:main\",\n \"kiwi_full_node_simulator = kiwi.simulator.start_simulator:main\",\n ]\n },\n package_data={\n \"kiwi\": [\"pyinstaller.spec\"],\n \"\": [\"*.clvm\", \"*.clvm.hex\", \"*.clib\", \"*.clinc\", \"*.clsp\"],\n \"kiwi.util\": [\"initial-*.yaml\", \"english.txt\"],\n \"kiwi.ssl\": [\"kiwi_ca.crt\", \"kiwi_ca.key\", \"dst_root_ca.pem\"],\n \"mozilla-ca\": [\"cacert.pem\"],\n },\n use_scm_version={\"fallback_version\": \"unknown-no-.git-directory\"},\n long_description=open(\"README.md\").read(),\n long_description_content_type=\"text/markdown\",\n zip_safe=False,\n)\n\n\nif __name__ == \"__main__\":\n setup(**kwargs)\n","repo_name":"WarutaShinken/kiwi-blockchain","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"26095557119","text":"import json\nfrom pars_rule_config import RuleConfig\nfrom sigma_method import SigmaMethodClass\nfrom extrapolation_method import ExtrapolationMethodClass\nfrom req import Req\nfrom sortedcontainers import SortedDict\nimport datetime\nfrom collections import defaultdict\n\nclass RuleFactory(object):\n def __init__(self):\n self.rule_config = RuleConfig(\"rule_config.yaml\")\n json_data = open(\"group_config.json\").read()\n self.group_config = json.loads(json_data)\n self.rule_buffer = []\n self.buffer = SortedDict()\n self.channel_condition = defaultdict(defaultdict)\n self.channel = []\n\n def create_buff(self):\n\n req = Req(\"172.16.1.117\", 80, \"/api/v1\")\n\n array1 = []\n #print(self.group_config)\n for met in self.rule_config.list_method:\n channel = []\n for group in self.rule_config.__getattribute__(met)[\"group_list\"]:\n #print(group)\n #for k, i in self.group_config[group[:group.find(\"/\")]][group[:group.rfind(\"/\")]].items():\n str = group[:group.rfind(\"/\")]\n try:\n channel += self.group_config[group[:group.find(\"/\")]][str][group]\n #print(self.group_config[group[:group.find(\"/\")]][str][group])\n except(KeyError):\n str = str[:str.rfind(\"/\")]\n channel += self.group_config[group[:group.find(\"/\")]][str][group]\n # print(self.group_config[group[:group.find(\"/\")]][str][group])\n\n #print(self.channel)\n array = []\n buffer = SortedDict()\n #print(channel)\n print((datetime.datetime.now() - datetime.timedelta(hours=self.rule_config.__getattribute__(met)[\"insert_inteval\"])),(datetime.datetime.now() + datetime.timedelta(hours=self.rule_config.__getattribute__(met)[\"insert_inteval\"])), met)\n t1 = datetime.datetime.strftime((datetime.datetime.now() - datetime.timedelta(hours=self.rule_config.__getattribute__(met)[\"insert_inteval\"])),'%Y-%m-%d %H:%M:%S.%f')\n t2 = datetime.datetime.strftime((datetime.datetime.now() + datetime.timedelta(hours=self.rule_config.__getattribute__(met)[\"insert_inteval\"])),'%Y-%m-%d %H:%M:%S.%f')\n for i in req.CursorCompress(t1, t2, channel, \"raw\"):\n try:\n array.append(i)\n except(KeyError):\n pass\n for i in array:\n try:\n del i[\"next\"]\n except(KeyError):\n pass\n #print(array)\n\n for group in self.rule_config.__getattribute__(met)[\"group_list\"]:\n buff_data = SortedDict()\n #print(self.group_config[group[:group.find(\"/\")]][group[:group.rfind(\"/\")]])\n str = group[:group.rfind(\"/\")]\n try:\n arr = self.group_config[group[:group.find(\"/\")]][str][group]\n except(KeyError):\n str = str[:str.rfind(\"/\")]\n arr = self.group_config[group[:group.find(\"/\")]][str][group]\n\n for ch in arr:\n result = SortedDict()\n #print(array[0][ch])\n try:\n for i in array[0][ch]:\n result[datetime.datetime.strptime(i[\"time\"],'%Y-%m-%d %H:%M:%S.%f')] = float(i[\"value\"])\n except(KeyError):\n pass\n buff_data[ch]=result\n #print(buff_data.keys())\n if len(buff_data)!=0:\n self.buffer[group] = buff_data\n for k in buffer.keys():\n self.channel_condition[k] = {\"active\": True}\n #channel.basic_publish(exchange='', routing_key='alarm_queue', body=str(json.dumps(self.channel_condition)),\n # properties=pika.BasicProperties(delivery_mode=2, ))\n\n self.channel += channel\n #print(self.channel)\n return self.buffer\n\n def create_rule(self):\n for i in self.rule_config.list_method:\n for group in self.rule_config.__getattribute__(i)[\"group_list\"]:\n self.rule_buffer.append(eval(self.rule_config.__getattribute__(i)[\"name_class\"])(self.rule_config.__getattribute__(i)[\"error_value\"],\n group, self.rule_config.__getattribute__(i)[\"active_interval\"],\n self.buffer[group]))\n return self.rule_buffer\n\n\nif __name__ =='__main__':\n factory = RuleFactory()\n factory.create_rule()\n","repo_name":"OlgaShubina/CheckSystem","sub_path":"rule_factory.py","file_name":"rule_factory.py","file_ext":"py","file_size_in_byte":4787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70479723093","text":"#!/usr/bin/env python\nimport pytest\nimport unittest.mock\nimport logging\n\nimport univisal\nfrom univisal.keys import Keys\nfrom univisal.motion import Motion\nfrom tests.mock_setup import init_univisal\n\n@pytest.fixture(autouse=True)\ndef init_store():\n global inI, outI, outpts, inpts\n inI=-1\n outI=-1\n outpts=[]\n inpts=[]\n\noutpts=[]\noutI=-1\ndef addOutput(key):\n global outpts\n outpts.append(key)\ninpts=[]\ninI=-1\ndef setInputs(keys):\n global inpts\n inpts=keys\n\ndef mock_write(key):\n addOutput(key)\ndef mock_read():\n global inI\n inI += 1\n return inpts[inI]\n\n\ndef init_loop():\n # caplog.set_level(logging.DEBUG)\n with unittest.mock.patch(\"univisal.message_interface.write_message\",\n side_effect=mock_write), \\\n unittest.mock.patch(\"univisal.message_interface.read_message\",\n side_effect=mock_read):\n init_univisal(with_interface=True)\n\ndef loop(keys):\n # Copy to stop HUP ending up in failure output.\n send = keys.copy()\n # Stop the loop at the end of the input keys.\n send.append(\"HUP\")\n setInputs(send)\n init_loop()\n\n\n@pytest.mark.parametrize(\"keys, expected\", [\n ([\"l\"], Motion.right.value),\n ([\"l\", 'l'], Motion.right.value * 2),\n ])\ndef test_loop(keys, expected):\n if not isinstance(keys, list):\n keys = [keys]\n loop(keys)\n assert ''.join(outpts)==expected, \"Main loop failed with keys {}\".format(keys)\n","repo_name":"BlueDrink9/Univisal","sub_path":"tests/test_readloop.py","file_name":"test_readloop.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"39409303238","text":"import os\nimport random\nimport string\n\nfrom construct_format_defs import data_simple_fmt, data_varying_fmt, data_complex_fmt\n\n# generation switches\ngen_simple = False\ngen_varying = True\ngen_complex = False\n\n# output directory\noutput_dir = \"./test_binary_files\"\n\n# create output directory if it doesn't exist\nif not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n# file names\ndata_simple_fn = \"data_simple\"\ndata_varying_fn = \"data_varying\"\ndata_complex_fn = \"data_complex\"\n\n# desired file sizes\nfile_size_small = 100*1024 # 100 kib\nfile_size_medium = 100*1024**2 # 100 mib\nfile_size_big = 1024**3 # 1 gib\n\nfor fname in [data_simple_fn, data_varying_fn, data_complex_fn]:\n\n if (fname in data_simple_fn and gen_simple) or (fname in data_varying_fn and gen_varying) or \\\n (fname in data_complex_fn and gen_complex):\n\n # build each file type\n with open(os.path.join(output_dir, fname + \"_small.bin\"), \"wb\") as f_small, \\\n open(os.path.join(output_dir, fname + \"_medium.bin\"), \"wb\") as f_medium, \\\n open(os.path.join(output_dir, fname + \"_large.bin\"), \"wb\") as f_large:\n\n # initialize file size in bytes\n file_size = 0\n while file_size < file_size_big:\n\n # Create randomized dictionary\n if fname in data_simple_fn:\n d_write = {\n \"field1\": random.randint(0, 2**16-1),\n \"field2\": random.randint(0, 2**8-1),\n \"field3\": random.randint(0, 25 * 10000) / 10000,\n \"field4\": random.randint(-(2**31), 2**31-1)\n }\n # write byte stream to files\n bytes_data = data_simple_fmt.build(d_write)\n\n elif fname in data_varying_fn:\n d_write = {\n \"field1\": random.randint(0, 2**16-1),\n \"field2\": random.randint(0, 2**8-1),\n \"field3\": random.randint(0, 2**16-1),\n \"field4\": ''.join(str(chr(random.choice(range(0, 128)))) for x in range(random.randint(1, 20))),\n \"field5\": ''.join(random.choice(string.ascii_letters) for x in range(random.randint(1, 20))),\n \"field6\": random.randint(-(2**31), 2**31-1)\n }\n # calculate what record length is with varying fields\n d_write[\"record_len\"] = 9 + len(d_write[\"field4\"]) + len(d_write[\"field5\"]) + 2\n # write byte stream to files\n bytes_data = data_varying_fmt.build(d_write)\n\n else:\n d_write = {\n \"record_typ\": random.randint(1, 3)\n }\n d_sub_write = {}\n if d_write[\"record_typ\"] == 1:\n d_sub_write[\"table1_field1\"] = random.randint(0, 2**16-1)\n d_sub_write[\"table1_field2\"] = random.randint(0, 2**8-1)\n d_sub_write[\"table1_field3\"] = ''.join(\n str(chr(random.choice(range(0, 128)))) for x in range(random.randint(1, 20)))\n d_sub_write[\"table1_field4\"] = random.randint(-(2**31), 2**31-1)\n d_write[\"record_len\"] = len(d_sub_write[\"table1_field3\"]) + 7 + 1\n\n elif d_write[\"record_typ\"] == 2:\n d_sub_write[\"table2_field1\"] = ''.join(\n random.choice(string.ascii_letters) for x in range(random.randint(1, 20)))\n d_sub_write[\"table2_field2\"] = ''.join(\n str(chr(random.choice(range(0, 128)))) for x in range(random.randint(1, 20)))\n d_sub_write[\"table2_field3\"] = ''.join(\n str(chr(random.choice(range(0, 128)))) for x in range(random.randint(1, 20)))\n d_write[\"record_len\"] = len(d_sub_write[\"table2_field1\"]) + len(d_sub_write[\"table2_field2\"]) + len(\n d_sub_write[\"table2_field3\"]) + 3\n\n else:\n d_sub_write[\"table3_field1\"] = random.randint(0, 2**16-1)\n d_sub_write[\"table3_field2\"] = random.randint(0, 2**32-1)\n d_sub_write[\"table3_field3\"] = random.randint(0, 2**32-1)\n d_sub_write[\"table3_field4\"] = random.randint(0, 2**32-1)\n d_sub_write[\"table3_field5\"] = random.randint(0, 2**32-1)\n d_sub_write[\"table3_field6\"] = random.randint(0, 2**32-1)\n d_sub_write[\"table3_field7\"] = random.randint(0, 2**32-1)\n d_sub_write[\"table3_field8\"] = random.randint(0, 2**32-1)\n d_sub_write[\"table3_field9\"] = ''.join(\n random.choice(string.ascii_letters) for x in range(random.randint(1, 20)))\n d_sub_write[\"table3_field10\"] = random.randint(-(2**31), 2**31-1)\n d_sub_write[\"table3_field11\"] = random.randint(-(2**31), 2**31-1)\n d_write[\"record_len\"] = 38 + len(d_sub_write[\"table3_field9\"]) + 1\n\n d_write[\"sub_table\"] = d_sub_write\n # write byte stream to files\n bytes_data = data_complex_fmt.build(d_write)\n\n # gate writing if we have surpassed desired file size\n if file_size < file_size_small:\n f_small.write(bytes_data)\n if file_size < file_size_medium:\n f_medium.write(bytes_data)\n f_large.write(bytes_data)\n\n # add bytes data to determine file size\n file_size += len(bytes_data)\n","repo_name":"haydenridd/binary_parser_comparison","sub_path":"test_data_generator.py","file_name":"test_data_generator.py","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"17441827262","text":"import serial \n#import MySQLdb\nimport time\nfrom datetime import datetime\nfrom pymongo import MongoClient\n#establish connection to MySQL. You'll have to change this for your database.\n#dbConn = MySQLdb.connect(\"localhost\",\"root\",\"\",\"rfid_scanner\") or die (\"could not connect to database\")\n#open a cursor to the database\n#cursor = dbConn.cursor()\nclient = MongoClient(\"mongodb+srv://root:root@cluster0-1enyv.mongodb.net/test?retryWrites=true&w=majority\")\n#pprint(client.mflix)\ndb = client.get_database('Eventify')\nrfid_collection= db.rfid_tags\n\ndevice = 'COM3' #this will have to be changed to the serial port you are using\ntry:\n print (\"Trying...\",device) \n arduino = serial.Serial(device, 9600) \nexcept: \n print (\"Failed to connect on\",device)\nwhile True:\n time.sleep(2)\n try:\n data=arduino.readline()\n print (data)\n pieces=data.split( )\n print (pieces)\n try:\n print(\"hhhh\")\n tagId = pieces[0].decode('ascii')\n print(\"tagId\",tagId)\n if tagId.isnumeric():\n now = datetime.now()\n current_time = now.strftime(\"%H:%M:%S\")\n print(\"Current Time =\", current_time)\n document_id = rfid_collection.find_one({'id':tagId, 'isComplete':'false','reader':1},{'_id':1,'current_time_in':1})\n print(document_id)\n # print(document_id[\"_id\"])\n if not document_id is None:\n entryTime = document_id[\"current_time_in\"]\n timeDiff1 = now - entryTime\n timeDiff = timeDiff1.total_seconds() / 60\n print(\"diff\",timeDiff )\n updateQuery = { '_id': document_id[\"_id\"] }\n\n newvalues = { \"$set\": { 'isComplete' : 'true', 'current_time_out': now , 'timeDifference':timeDiff }}\n rfid_collection.update_one(updateQuery, newvalues)\n print(\"data updated\")\n else:\n print(\"inside else\")\n new_rfid={'id' : tagId ,'current_time_in': now, 'reader': 1, 'isComplete':'false' }\n rfid_collection.insert_one(new_rfid)\n print(\"data inserted\")\n \n\n # new_rfid= {\n # 'id':pieces[0].decode('ascii'),\n # 'time':'to be fixed',\n # 'reader':'1',\n # 'flag': pieces[1].decode('ascii')\n # }\n # rfid_collection.insert_one(new_rfid)\n # print(\"Inserted, new Count\", rfid_collection.count_documents({}))\n # client.close()\n except :\n print (\"failed to insert data\")\n finally:\n print(\"done\")\n #client.close()\n except:\n print (\"Processing\")\n \n \n","repo_name":"ahuja101992/Eventify","sub_path":"Arduino/python_code.py","file_name":"python_code.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12352750693","text":"# G7-T22\n# BENJAMIN CHEW PIN HSIEN, NICHOLAS CHEN HAN WEI\n\n# Q2\n\n# Replace the content of this function with your own algorithm\n# inputs: \n# n: the number of members in your team\n# W: weight limit of each vehicle used for deliveries.\n# packages: 2D list [[packageID, reward, weight], [packageID, reward, weight], ...]\n# returns:\n# 2D list of package IDs to represent n sets of packages. \n# e.g. if n = 2, this is a possible solution: [[\"P001\", \"P003\"], [\"P010\"]]\nimport copy\nimport numpy\nimport sys\n\n\ndef select_packageSets(n, W, packages):\n readonly_package_dict = {pkg[0]: pkg[1:] for pkg in packages}\n avail_packages = copy.deepcopy(packages)\n # Split into chunks, sort them via profitability.\n # Profitability = reward/weight\n # Best to worst\n packages.sort(key=lambda x: (x[1] / x[2]), reverse=True)\n\n # Take the best packages till we hit the total weight limit\n weight_total = 0\n max_index = 0\n for i in range(len(packages)):\n max_index = i\n if weight_total > (W * n):\n break\n weight_total += packages[i][2]\n\n # Setup the bins\n set_thresholds = [0] * n\n set_rewards = [0] * n\n p_sets = []\n while len(p_sets) < n:\n p_sets.append([])\n\n if max_index == len(packages) - 1:\n packages.sort(key=lambda x: (x[2]), reverse=True)\n elif max_index < len(packages) - 1:\n overflowing_packages = packages[max_index + 1:]\n overflowing_packages.sort(key=lambda x: x[1], reverse=True)\n packages = packages[:max_index + 1] + overflowing_packages\n\n while can_still_fit(set_thresholds, avail_packages, W):\n for package in packages:\n # Try to fit item into a bin\n i = get_next_fit_index(p_sets, set_thresholds, set_rewards, package[2], W)\n\n if i > -1:\n # print 'Adding', item, 'to', bin\n p_sets[i].append(package[0])\n set_thresholds[i] += package[2]\n set_rewards[i] += package[1]\n del avail_packages[avail_packages.index(package)]\n\n fresh_deviation = numpy.std(set_rewards)\n fresh_set = copy.deepcopy(p_sets)\n fresh_thresholds = copy.deepcopy(set_thresholds)\n fresh_rewards = copy.deepcopy(set_rewards)\n\n while can_still_fit_differential((n * W) - sum(set_thresholds), avail_packages):\n shifted_deviation = numpy.std(set_rewards)\n if shifted_deviation > fresh_deviation:\n reduce_deviation(readonly_package_dict, p_sets, set_thresholds, set_rewards, W)\n\n least_filled_set_index = get_least_filled_set_index(set_thresholds)\n if least_filled_set_index < 0 and not can_still_fit_differential((n * W) - sum(set_thresholds), avail_packages):\n break\n one_last_time = get_best_fit_in_set(set_thresholds[least_filled_set_index], avail_packages, W)\n if one_last_time is None and not can_still_fit_differential((n * W) - sum(set_thresholds), avail_packages):\n break\n if one_last_time is not None:\n p_sets[least_filled_set_index].append(one_last_time[0])\n set_rewards[least_filled_set_index] += one_last_time[1]\n set_thresholds[least_filled_set_index] += one_last_time[2]\n avail_packages.remove(one_last_time)\n\n if not fill_smallest(readonly_package_dict, avail_packages, p_sets, set_thresholds, set_rewards,\n W) and not can_still_fit_differential((n * W) - sum(set_thresholds), avail_packages):\n break\n else:\n skewer(readonly_package_dict, p_sets, set_thresholds, set_rewards, W, avail_packages)\n\n if shifted_deviation == numpy.std(set_rewards):\n break\n\n # reduce_deviation(readonly_package_dict, p_sets, set_thresholds, set_rewards, W)\n post_differential_deviation = numpy.std(set_rewards)\n if post_differential_deviation > fresh_deviation:\n p_sets = fresh_set\n set_thresholds = fresh_thresholds\n set_rewards = fresh_rewards\n\n if max_index < len(packages) - 1 or post_differential_deviation > fresh_deviation:\n new_deviation = numpy.std(set_rewards)\n while True:\n prev_deviation = numpy.std(set_rewards)\n reduce_deviation(readonly_package_dict, p_sets, set_thresholds, set_rewards, W)\n new_deviation = numpy.std(set_rewards)\n\n if prev_deviation == new_deviation:\n break\n\n return p_sets\n\n\ndef get_next_fit_index(p_sets, thresholds, rewards, cur_item_w, limit):\n # Get all indexes that have exceeded the thresholds in accordance to cur_item_w\n banned_set_indexes = get_exceeded_indexes(thresholds, cur_item_w, limit)\n # Always prioritise rewards first\n l_rw_i = get_lowest_reward(rewards, banned_set_indexes) # Lowest reward index\n\n return l_rw_i[0]\n\n\ndef get_lowest_reward(rewards, blacklisted=[]):\n lowest = (-1, sys.maxsize)\n for i in range(len(rewards)):\n if rewards[i] < lowest[1] and i not in blacklisted:\n lowest = (i, rewards[i])\n return lowest\n\n\ndef get_exceeded_indexes(thresholds, cur_item_w, lim):\n res = []\n\n for i in range(len(thresholds)):\n if thresholds[i] + cur_item_w > lim:\n res.append(i)\n\n return res\n\n\ndef get_non_full_set_indexes(thresholds, limit):\n non_full_set_indexes = []\n for i in range(len(thresholds)):\n if thresholds[i] < limit:\n non_full_set_indexes.append(i)\n\n return non_full_set_indexes\n\n\ndef get_best_fit_in_set(threshold, available_packages, limit):\n available_packages.sort(key=lambda x: (x[1] / x[2]), reverse=True)\n for package in available_packages:\n if threshold + package[2] <= limit:\n return package\n\n return None\n\n\ndef can_still_fit(thresholds, available_packages, limit):\n for package in available_packages:\n for threshold in thresholds:\n if threshold + package[2] <= limit:\n return True\n\n return False\n\n\ndef can_still_fit_differential(differential, available_packages):\n for package in available_packages:\n if differential - package[2] >= 0:\n return True\n\n return False\n\n\ndef get_least_filled_set_index(thresholds):\n smallest_threshold = (-1, sys.maxsize)\n for i in range(len(thresholds)):\n if thresholds[i] < smallest_threshold[1]:\n smallest_threshold = (i, thresholds[i])\n\n return smallest_threshold[0]\n\n\ndef get_most_filled_set_index(thresholds):\n biggest_threshold = (-1, -sys.maxsize)\n for i in range(len(thresholds)):\n if thresholds[i] > biggest_threshold[1]:\n biggest_threshold = (i, thresholds[i])\n\n return biggest_threshold[0]\n\n\ndef compute_threshold(package_dict, p_set):\n threshold = 0\n for p in p_set:\n if p in package_dict.keys():\n threshold += package_dict[p][1]\n\n return threshold\n\n\ndef compute_reward(package_dict, p_set):\n reward = 0\n for p in p_set:\n if p in package_dict.keys():\n reward += package_dict[p][0]\n\n return reward\n\n\ndef reduce_deviation(package_dict, p_sets, set_thresholds, set_rewards, W):\n # reward_sd = numpy.std(set_rewards)\n set_reward_ranking = numpy.argsort(set_rewards)\n set_combinations_left = choose(len(p_sets), 2)\n lower = 0\n upper = lower + 1\n while set_combinations_left > 0:\n least_reward_index = set_reward_ranking[lower]\n lower_set_threshold = set_thresholds[least_reward_index]\n least_reward_set_reward = set_rewards[least_reward_index] + 0\n most_reward_index = set_reward_ranking[upper]\n upper_set_threshold = set_thresholds[most_reward_index]\n most_reward_set_reward = set_rewards[most_reward_index] + 0\n orig_reward_sd = numpy.std([least_reward_set_reward, most_reward_set_reward])\n\n if orig_reward_sd > 5:\n new_reward_sd = orig_reward_sd + 0\n\n least_reward_set = regenerate_set(package_dict, p_sets[least_reward_index])\n least_reward_set.sort(key=lambda x: (x[2]))\n most_reward_set = regenerate_set(package_dict, p_sets[most_reward_index])\n most_reward_set.sort(key=lambda x: (x[2]))\n\n iter_allowed = len(p_sets[least_reward_index]) * len(p_sets[most_reward_index])\n set_lower = 0\n set_upper = 0\n while new_reward_sd >= orig_reward_sd and iter_allowed > 0 and len(least_reward_set) > 0 \\\n and len(most_reward_set) > 0:\n lrs_least_profitable = least_reward_set.pop(set_lower)\n if set_upper >= len(most_reward_set):\n print()\n mrs_least_profitable = most_reward_set.pop(set_upper)\n\n if (lrs_least_profitable[1] / lrs_least_profitable[2]) < (\n mrs_least_profitable[1] / mrs_least_profitable[2]) \\\n and (numpy.std([least_reward_set_reward - (lrs_least_profitable[1] + mrs_least_profitable[1]),\n most_reward_set_reward - (mrs_least_profitable[1] + lrs_least_profitable[1])])) \\\n and (lower_set_threshold - lrs_least_profitable[2] + mrs_least_profitable[2] <= W) \\\n and (upper_set_threshold - mrs_least_profitable[2] + lrs_least_profitable[2] <= W):\n # Reduce\n least_reward_set_reward -= lrs_least_profitable[1]\n lower_set_threshold -= lrs_least_profitable[2]\n most_reward_set_reward -= mrs_least_profitable[1]\n upper_set_threshold -= mrs_least_profitable[2]\n\n # Increase\n least_reward_set_reward += mrs_least_profitable[1]\n lower_set_threshold += mrs_least_profitable[2]\n most_reward_set_reward += lrs_least_profitable[1]\n upper_set_threshold += lrs_least_profitable[2]\n\n # Replace\n least_reward_set.append(mrs_least_profitable)\n most_reward_set.append(lrs_least_profitable)\n\n new_reward_sd = numpy.std([least_reward_set_reward, most_reward_set_reward])\n else:\n least_reward_set.append(lrs_least_profitable)\n most_reward_set.append(mrs_least_profitable)\n\n iter_allowed -= 1\n\n if set_upper == len(most_reward_set) - 1 and set_lower + 1 < len(least_reward_set):\n set_lower += 1\n set_upper = 0\n elif set_upper + 1 < len(most_reward_set):\n set_upper += 1\n else:\n break\n\n if new_reward_sd < orig_reward_sd:\n p_sets[least_reward_index] = [tuple[0] for tuple in least_reward_set]\n p_sets[most_reward_index] = [tuple[0] for tuple in most_reward_set]\n\n set_thresholds[least_reward_index] = lower_set_threshold\n set_thresholds[most_reward_index] = upper_set_threshold\n\n set_rewards[least_reward_index] = least_reward_set_reward\n set_rewards[most_reward_index] = most_reward_set_reward\n\n reward_sd = numpy.std(set_rewards)\n set_combinations_left -= 1\n if upper == len(set_rewards) - 1:\n lower += 1\n upper = 0\n else:\n upper += 1\n\n\ndef fill_smallest(package_dict, avail_packages, p_sets, set_thresholds, set_rewards, W):\n set_threshold_ranking = numpy.argsort(set_thresholds)\n\n if len(set_threshold_ranking) >= 2:\n lightest_index = set_threshold_ranking[0]\n heavier_index = set_threshold_ranking[1]\n\n # Drain and fit\n smaller_package_set = regenerate_set(package_dict, p_sets[lightest_index] + p_sets[heavier_index])\n heavier_package_set = select_packageSet(W, smaller_package_set)\n smaller_set_threshold = sum([package[2] for package in smaller_package_set])\n smaller_package_set = [package[0] for package in smaller_package_set]\n\n # Get the heavier out of the way first\n set_thresholds[heavier_index] = compute_threshold(package_dict, heavier_package_set)\n set_rewards[heavier_index] = compute_reward(package_dict, heavier_package_set)\n p_sets[heavier_index] = heavier_package_set\n\n # Additional fit\n for package in avail_packages:\n if package[2] + smaller_set_threshold <= W:\n smaller_set_threshold += package[2]\n smaller_package_set.append(package[0])\n\n set_thresholds[lightest_index] = smaller_set_threshold\n set_rewards[lightest_index] = compute_reward(package_dict, smaller_package_set)\n p_sets[lightest_index] = smaller_package_set\n\n if can_still_fit([set_thresholds[lightest_index], set_thresholds[heavier_index]], avail_packages, W):\n return True\n else:\n return False\n return False\n\n\ndef regenerate_set(package_dict, p_set):\n res = []\n\n for i in p_set:\n if i in package_dict.keys():\n res.append((i, package_dict[i][0], package_dict[i][1]))\n else:\n print(\"Critical! Key \" + str(i) + \" missing!\")\n\n return res\n\n\ndef choose(n, k):\n if k == 0:\n return 1\n elif n < k:\n return 0\n else:\n return choose(n - 1, k - 1) + choose(n - 1, k)\n\n\ndef skewer(package_dict, p_sets, set_thresholds, set_rewards, W, avail_packages):\n # threshold_ordering = numpy.argsort(set_thresholds)\n is_rising = numpy.all(numpy.diff(numpy.argsort(set_thresholds)) >= 0)\n cur_ordering = copy.deepcopy(set_thresholds)\n while not is_rising:\n if not can_still_fit(set_thresholds, avail_packages, W):\n break\n\n for i in range(len(p_sets) - 1, -1, -1):\n if set_thresholds[i] < W:\n # Check all sets to the left and find packages to shift to.\n for j in range(i - 1, -1, -1):\n k = len(p_sets[j]) - 1\n while k > -1:\n if (package_dict[p_sets[j][k]][1] + set_thresholds[i]) <= W:\n set_thresholds[i] += package_dict[p_sets[j][k]][1]\n set_rewards[i] += package_dict[p_sets[j][k]][0]\n set_thresholds[j] -= package_dict[p_sets[j][k]][1]\n set_rewards[j] -= package_dict[p_sets[j][k]][0]\n p_sets[i].append(p_sets[j][k])\n p_sets[j].remove(p_sets[j][k])\n\n if set_thresholds[i] == W:\n break\n\n k -= 1\n\n if set_thresholds[i] == W:\n break\n is_rising = numpy.all(numpy.diff(set_thresholds) >= 0)\n new_ordering = copy.deepcopy(set_thresholds)\n\n if cur_ordering == new_ordering:\n break\n else:\n cur_ordering = new_ordering\n\n if not is_rising:\n is_falling = numpy.all(numpy.diff(numpy.argsort(set_thresholds[::-1])) >= 0)\n while not is_falling:\n if not can_still_fit(set_thresholds, avail_packages, W):\n break\n for i in range(len(p_sets) - 1):\n if set_thresholds[i] < W:\n # Check all sets to the left and find packages to shift to.\n for j in range(i + 1, len(set_thresholds)):\n k = len(p_sets[j]) - 1\n while k > -1:\n if (package_dict[p_sets[j][k]][1] + set_thresholds[i]) <= W:\n set_thresholds[i] += package_dict[p_sets[j][k]][1]\n set_rewards[i] += package_dict[p_sets[j][k]][0]\n set_thresholds[j] -= package_dict[p_sets[j][k]][1]\n set_rewards[j] -= package_dict[p_sets[j][k]][0]\n p_sets[i].append(p_sets[j][k])\n p_sets[j].remove(p_sets[j][k])\n\n if set_thresholds[i] == W:\n break\n\n k -= 1\n\n if set_thresholds[i] == W:\n break\n is_falling = numpy.all(numpy.diff(numpy.argsort(set_thresholds[::-1])) >= 0)\n new_ordering = copy.deepcopy(set_thresholds)\n\n if cur_ordering == new_ordering:\n break\n else:\n cur_ordering = new_ordering\n\n\n# Adapted from Q1.\ndef select_packageSet(W, packages):\n val = [package[1] for package in packages]\n wt = [package[2] for package in packages]\n package = [package[0] for package in packages]\n package_select = []\n\n selected_wt_index = knapSack(W, wt, val, len(val))\n\n for wt_index in selected_wt_index:\n package_select.append(package[wt_index])\n del packages[wt_index]\n\n return package_select\n\n\ndef knapSack(W, wt, val, n):\n selected_weight = []\n\n K = [[0 for x in range(W + 1)] for x in range(n + 1)]\n\n # Build table K[][] in bottom up manner\n for i in range(n + 1):\n for w in range(W + 1):\n if i == 0 or w == 0:\n K[i][w] = 0\n elif wt[i - 1] <= w:\n K[i][w] = max(val[i - 1]\n + K[i - 1][w - wt[i - 1]],\n K[i - 1][w])\n else:\n K[i][w] = K[i - 1][w]\n # print(K)\n\n # return K[n][W]\n while K[n][W] != 0:\n if K[n][W] != K[n - 1][W]:\n selected_weight.append(n - 1)\n W -= wt[n - 1]\n n -= 1\n\n return selected_weight\n","repo_name":"nixxholas/cor1702-rekt","sub_path":"Project/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":17690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"35382142039","text":"import datetime\nimport json\nimport logging\nimport re\nfrom typing import Any, Optional, Dict, List\n\nfrom requests import Response\n\nfrom urbanairship import Airship\n\nVALID_UUID = re.compile(r\"[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15}\\Z\")\n\nlogger = logging.getLogger(\"urbanairship\")\n\n\nclass OpenChannel(object):\n \"\"\"\n Represents an open channel.\n\n :param channel_id: The Airship generated channel_id value for the open channel\n :param address: The open channel's address\n :param open_platform: The open platform associated with the channel\n \"\"\"\n\n channel_id: Optional[str] = None\n address: Optional[str] = None\n open_platform: Optional[str] = None\n identifiers: Optional[str] = None\n opt_in: Optional[bool] = None\n installed: Optional[bool] = None\n created: Optional[str] = None\n last_registration: Optional[str] = None\n tags: Optional[List] = None\n template_fields: Optional[Dict] = None\n\n def __init__(self, airship: Airship) -> None:\n self.airship = airship\n\n @property\n def create_and_send_audience(self) -> Dict:\n if not self.address:\n raise ValueError(\"open channel address must be set\")\n\n audience = {\"ua_address\": self.address}\n\n if self.template_fields:\n audience.update(self.template_fields)\n\n return audience\n\n def create(self) -> Response:\n \"\"\"Create this OpenChannel object with the API.\"\"\"\n\n if not self.address:\n raise ValueError(\"Must set address before creation.\")\n\n if not self.open_platform:\n raise ValueError(\"Must set open_platform before creation.\")\n\n if not isinstance(self.opt_in, bool):\n raise ValueError(\"Must set opt_in before creation.\")\n\n if self.tags and not isinstance(self.tags, list):\n raise TypeError('\"tags\" must be a list')\n\n url = self.airship.urls.get(\"open_channel_url\")\n\n channel_data: Dict[str, Any] = {\n \"type\": \"open\",\n \"address\": self.address,\n \"opt_in\": self.opt_in,\n \"open\": {\"open_platform_name\": self.open_platform},\n }\n\n if self.tags:\n channel_data[\"tags\"] = self.tags\n if self.identifiers:\n channel_data[\"open\"][\"identifiers\"] = self.identifiers\n\n body = json.dumps({\"channel\": channel_data})\n response = self.airship.request(method=\"POST\", body=body, url=url, version=3)\n\n self.channel_id = response.json().get(\"channel_id\")\n\n logger.info(\n \"Successful open channel creation: %s (%s)\", self.channel_id, self.address\n )\n\n return response\n\n def update(self) -> Response:\n \"\"\"Update this OpenChannel object.\"\"\"\n\n if not self.address and not self.channel_id:\n raise ValueError(\"Must set address or channel ID to update.\")\n\n if not self.open_platform:\n raise ValueError(\"Must set open_platform.\")\n\n if not isinstance(self.opt_in, bool):\n raise ValueError(\"Must set opt_in.\")\n\n if not self.address and self.opt_in is True:\n raise ValueError(\"Address must be set for opted in channels.\")\n\n url = self.airship.urls.get(\"open_channel_url\")\n\n channel_data: Dict[str, Any] = {\n \"type\": \"open\",\n \"open\": {\"open_platform_name\": self.open_platform},\n \"opt_in\": self.opt_in,\n }\n if self.channel_id:\n channel_data[\"channel_id\"] = self.channel_id\n if self.address:\n channel_data[\"address\"] = self.address\n if self.tags:\n channel_data[\"tags\"] = self.tags\n if self.identifiers:\n channel_data[\"open\"][\"identifiers\"] = self.identifiers\n\n body = json.dumps({\"channel\": channel_data})\n response = self.airship.request(method=\"POST\", body=body, url=url, version=3)\n\n self.channel_id = response.json().get(\"channel_id\")\n\n logger.info(\n \"Successful open channel update: %s (%s)\", self.channel_id, self.address\n )\n\n return response\n\n @classmethod\n def from_payload(cls, payload: Dict, airship: Airship):\n \"\"\"Instantiate an OpenChannel from a payload.\"\"\"\n obj = cls(airship)\n for key in payload:\n # Extract the open channel data\n if key == \"open\":\n obj.open_platform = payload[\"open\"].get(\"open_platform_name\")\n obj.identifiers = payload[\"open\"].get(\"identifiers\", [])\n continue\n\n if key in (\"created\", \"last_registration\"):\n try:\n payload[key] = datetime.datetime.strptime(\n payload[key], \"%Y-%m-%dT%H:%M:%S\"\n )\n except (KeyError, ValueError):\n payload[key] = \"UNKNOWN\"\n setattr(obj, key, payload[key])\n\n return obj\n\n def lookup(self, channel_id: str):\n \"\"\"Retrieves an open channel from the provided channel ID.\"\"\"\n url = self.airship.urls.get(\"channel_url\") + channel_id\n response = self.airship._request(method=\"GET\", body=None, url=url, version=3)\n payload = response.json().get(\"channel\")\n\n return self.from_payload(payload, self.airship)\n\n def uninstall(self) -> Response:\n \"\"\"Mark this OpenChannel object uninstalled\"\"\"\n url = self.airship.urls.get(\"open_channel_url\") + \"uninstall/\"\n if self.address is None or self.open_platform is None:\n raise ValueError('\"address\" and \"open_platform\" are required attributes')\n\n channel_data = {\n \"address\": self.address,\n \"open_platform_name\": self.open_platform,\n }\n\n body = json.dumps(channel_data)\n response = self.airship.request(method=\"POST\", body=body, url=url, version=3)\n\n logger.info(\n \"Successfully uninstalled open channel %s\"\n % channel_data[\"open_platform_name\"]\n )\n\n return response\n","repo_name":"urbanairship/python-library","sub_path":"urbanairship/devices/open_channel.py","file_name":"open_channel.py","file_ext":"py","file_size_in_byte":5976,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"67"} +{"seq_id":"3925109815","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def isUnivalTree(self, root) -> bool:\n vals = []\n def dfs(node):\n if node:\n vals.append(node.val)\n dfs(node.left)\n dfs(node.right)\n dfs(root)\n return len(set(vals)) == 1","repo_name":"YunYouJun/LeetCode","sub_path":"problems/univalued-binary-tree/solution-1.py","file_name":"solution-1.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"12922468551","text":"# -*- coding: utf-8 -*-\nimport sublime\nimport sublime_plugin\nimport time\nimport subprocess\nimport os\nimport os.path\nimport sys\nimport time\nimport shutil\n# import pymysql\n# import mysql.connector\n\n# 新增颜色,包含到其中\nclass AddColorCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit, fir='[/0xFF0000]', send='[/0xffffff]'):\n\t\tview = self.view\n\t\tsels = view.sel() #当前选中\n\t\tif len(sels):\n\t\t\tsels = sels[0]\n\t\t\tregionStr = view.substr(sels) #获取选中区域内容\n\t\t\tselContent = fir + regionStr + send\n\t\t\tview.run_command('cut')\n\t\t\tview.insert(edit,sels.begin(),selContent)\n\t\t\tsublime.set_clipboard('')\n\n# 生成sql表头\nclass SqlTitleCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit, name=''):\n\t\tview = self.view\n\t\tselContent = '''##############################################################\\n#name:''' + time.strftime(\"%Y%m%d\", time.localtime()) + '''[手机魔域][XX脚本]XXX\\n#by:''' + name + '''\\n#date:''' + time.strftime(\"%Y-%m-%d\", time.localtime()) + '''\\n##############################################################\\n#注释部分\\n\\n\\n##############################################################\\n\\n'''\n\t\tview.insert(edit,0,selContent)\n\n# 生成lua表头\nclass LuaTitleCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit, name=''):\n\t\tview = self.view\n\t\tselContent = '''-- luaId:XXXXX\\n--Name:\\t\\t\\t''' + time.strftime(\"%Y%m%d\", time.localtime()) + '''[手机魔域][XX脚本]XXX\\n--Creator:\\t\\t''' + name + '''\\n--Created:\\t\\t''' + time.strftime(\"%Y-%m-%d\", time.localtime()) + '''\\n-------------------------------------------------------------------\\n\\tmodule(\"Lua_XXXXX\",package.seeall)\\n-------------------------------------------------------------------\\n\\n'''\n\t\tview.insert(edit,0,selContent)\n\n# 顺延id\nclass ChangIdCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit, isSequen = 'false'):\n\t\tview = self.view\n\t\tsels = view.sel() #当前选中\n\t\tfirstNum = int(view.substr(sels[0]))\t#获取第一个���字\n\t\ti = 0\n\t\tview.run_command('cut')\n\t\tif isSequen == 'false':\n\t\t\tfor region in self.view.sel():\n\t\t\t\tview.insert(edit,region.begin(),str(firstNum + i))\n\t\t\t\ti = i + 1\n\t\telse:\n\t\t\tfor region in self.view.sel():\n\t\t\t\tview.insert(edit,region.begin(),str(firstNum - i))\n\t\t\t\ti = i + 1\n\n# 判断选中字符长度\nclass GetSelectLenCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit):\n\t\tview = self.view\n\t\tsels = view.sel() #当前选中\n\t\tif len(sels):\n\t\t\tsels = sels[0]\n\t\t\tregionStr = view.substr(sels)\n\t\t\tleng = len(regionStr)\n\t\t\tutf8_length = len(regionStr.encode('utf-8'))\n\t\t\tprint('\\n\\n当前选中字符串:' + regionStr + '\\n\\n选中长度:' + str(int((utf8_length-leng)/2 + leng)))\n\t\t\t# sublime.message_dialog('选中长度:' + str(int((utf8_length-leng)/2 + leng)))\n\n# 转换字符串大小写\nclass SetSelectCharUpperCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit, isupper = True):\n\t\tview = self.view\n\t\tsels = view.sel() #当前选中\n\t\tif len(sels):\n\t\t\tsels = sels[0]\n\t\t\tregionStr = view.substr(sels)\n\t\t\tif isupper:\n\t\t\t\tregionStr = regionStr.upper()\n\t\t\telse:\n\t\t\t\tregionStr = regionStr.lower()\n\t\t\tview.run_command('cut')\n\t\t\tview.insert(edit,sels.begin(),regionStr)\n\t\t\t# sublime.message_dialog('选中长度:' + str(int((utf8_length-leng)/2 + leng)))\n\n# 转换驼峰写法\nclass SetSelectCharHumpCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit, splitStr = \"_\"):\n\t\tview = self.view\n\t\tsels = view.sel() #当前选中\n\t\tif len(sels):\n\t\t\tsels = sels[0]\n\t\t\tregionStr = view.substr(sels)\n\t\t\tregionStrArr = regionStr.upper().split(splitStr)\n\t\t\tregionStr = \"\"\n\t\t\tfor x in regionStrArr:\n\t\t\t\tregionStr += x.capitalize()\n\t\t\tregionStr = regionStr[0].lower() + regionStr[1:]\n\t\t\tview.run_command('cut')\n\t\t\tview.insert(edit,sels.begin(),regionStr)\n\t\t\t# sublime.message_dialog('选中长度:' + str(int((utf8_length-leng)/2 + leng)))\n\n# 执行sql\nclass CommitSqlCommand(sublime_plugin.WindowCommand):\n\tdef run(self, dataName='sjmy31'):\n\t\tself.window.run_command('show_panel', {\"panel\": \"console\",})\n\t\tprint('\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n')\n\t\tdir = self.get_path(None)\n\t\tdirArr = os.path.splitext(dir)\n\t\tend = dirArr[len(dirArr)-1]\n\t\tif end != '.sql' and end != '.lua':\n\t\t\tprint(\"刷入文件并非sql或lua\")\n\t\t\treturn\n\n\t\tprint(time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time())))\n\t\tprint('刷入数据库:' + dataName)\n\t\tprint('刷入文件:' + dir)\n\t\tproce = subprocess.Popen( '\"python\"' + ' \"C:\\\\Users\\\\Administrator\\\\AppData\\\\Roaming\\\\Sublime Text 3\\\\Packages\\\\demo\\\\sql.py\" \"' + dataName + '\" \"' + dir +'\"', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )\n\t\treturncode = proce.poll()\n\t\twhile returncode is None:\n\t\t\tline = proce.stdout.readline()\n\t\t\treturncode = proce.poll()\n\t\t\tline = line.strip()\n\t\t\tif line != b'':\n\t\t\t\tprint(line)\n\t\t# print(returncode)\n\t\t# proce.communicate()\n\t\t# print(subprocess.PIPE)\n\n\t\t# conn = pymysql.connect( \n\t\t# \thost=\"192.168.19.38\", \n\t\t# \t# port=3306, \n\t\t# \tuser=\"root\", \n\t\t# \tpassword=\"aaa\", \n\t\t# \tdatabase=\"sjmy31\", \n\t\t# \tautocommit=True, \n\t\t# \t# use_unicode=True, \n\t\t# \t# no_delay=True, \n\t\t# )\n\n\t\t# # conn.select_db('sjmy31')\n\t\t# # print(conn)\n\t\t# # print(conn.thread_id())\n\t\t# # cursor = conn.cursor()\n\t\t# # print(cursor.connection.get_host_info())\n\t\t# conn.query(\"use sjmy31\")\n\t\t# # conn.commit()\n\t\t# cursor.close()\n\t\t# conn.close()\n\n\t# 获取文件位置\n\tdef get_path(self, paths):\n\t\tpath = None\n\t\tif paths:\n\t\t\tpath = '*'.join(paths)\n\t\telse:\n\t\t\tview = sublime.active_window().active_view()\n\t\t\tpath = view.file_name() if view else None\n\t\treturn path\n\n# 生成MyBatis表头\nclass MyBatisTitleCommand(sublime_plugin.TextCommand):\n\tdef run(self, edit):\n\t\tview = self.view\n\n\t\tfirstLine = view.substr(view.line(1))\n\t\tif firstLine == '##############':\n\t\t\tprint(\"已有注释,不再生成\")\n\t\t\treturn\n\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\t\tMyBatisTitleArr = settings.get(\"MyBatisTitle\")\n\n\t\tselContent = '''##############\\n# 多表在不同项目时,需挨个在表前加入表头,配置路径包名,否则取第一张表的设置\\n# 包名中的entity等关键字用*号代替\\n# 服务端路由默认为after/bean名称\\n\\n'''\n\t\treplaceString = \"\"\n\t\tfor x in MyBatisTitleArr.keys():\n\t\t\treplaceString += \"#\" + MyBatisTitleArr[x] + \"\\n\" + x + \":\\n\\n\"\n\t\tselContent += replaceString + '##############\\n\\n'\n\n\t\tview.insert(edit,0,selContent)\n\n# MyBatis工具\nclass MyBatisCommand(sublime_plugin.WindowCommand):\n\tdef run(self, createFileName = \"all\"):\n\t\tself.window.run_command('show_panel', {\"panel\": \"console\",})\n\t\tprint('\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n')\n\t\tdir = self.get_path(None)\n\t\tif dir:\n\t\t\tdirArr = os.path.splitext(dir)\n\t\t\tend = dirArr[len(dirArr)-1]\n\t\t\tif end != '.sql':\n\t\t\t\tprint(\"解析文件需为sql\")\n\t\t\t\treturn\n\n\t\t\tprint(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))\n\t\t\tprint('解析文件:' + dir)\n\t\t\tself.window.run_command('save')\n\t\t\tself.main_mybatis(dir,createFileName)\n\t\telse:\n\t\t\tprint(\"解析的文件并未保存,无法生成数据!\")\n\t\t\n\tdef main_mybatis(self,dir,createFileName):\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\t\t# sql关键字 -- 忽略\n\t\tsqlKey = settings.get(\"sqlKey\")\n\t\tauthor = settings.get(\"author\")\n\n\t\tAllTable = []\n\n\t\t# 单表\n\t\ttable = {'javaBeanName': { 'beanName':'', 'tableName':'' },'javaBeanVar': []}\n\t\t\n\t\t# 默认信息\n\t\tdefaultInfor = {}\n\n\t\tfile = open(dir, mode='r', encoding='UTF-8')\n\t\tfor line in file:\n\t\t\tline = line.expandtabs().lstrip()\t# 去掉开头空格\n\t\t\tfor key in sqlKey.keys():\n\t\t\t\tif line.upper().startswith(key) or str(line).upper().startswith(key):\n\t\t\t\t\tif not sqlKey[key]:\n\t\t\t\t\t\t# 获取实体名\n\t\t\t\t\t\tif key == 'CREATE TABLE':\n\t\t\t\t\t\t\ttable['javaBeanName'] = self.getJavaBeanName(line)\n\t\t\t\t\t\t# 获取字段\n\t\t\t\t\t\tif key == '`':\n\t\t\t\t\t\t\ttable['javaBeanVar'].append(self.getJavaBeanVar(line))\n\n\t\t\t\t\t\t# 获取其他信息\n\t\t\t\t\t\tif key == 'PACKAGE':\n\t\t\t\t\t\t\ttemp = self.getOtherInfor(line)\n\t\t\t\t\t\t\tif temp:\n\t\t\t\t\t\t\t\ttable['package'] = temp\n\t\t\t\t\t\t\t\t# 不存在的话设置数据\n\t\t\t\t\t\t\t\tif not 'package' in defaultInfor:\n\t\t\t\t\t\t\t\t\tdefaultInfor['package'] = table['package']\n\n\t\t\t\t\t\tif key == 'PROJECTPATH':\n\t\t\t\t\t\t\ttemp = self.getOtherInfor(line)\n\t\t\t\t\t\t\tif temp:\n\t\t\t\t\t\t\t\ttable['projectPath'] = temp\n\t\t\t\t\t\t\t\tif not 'projectPath' in defaultInfor:\n\t\t\t\t\t\t\t\t\tdefaultInfor['projectPath'] = table['projectPath']\n\n\t\t\t\t\t\tif key == 'APIPROJECTPATH':\n\t\t\t\t\t\t\ttemp = self.getOtherInfor(line)\n\t\t\t\t\t\t\tif temp:\n\t\t\t\t\t\t\t\ttable['apiProjectPath'] = temp\n\t\t\t\t\t\t\t\tif not 'apiProjectPath' in defaultInfor:\n\t\t\t\t\t\t\t\t\tdefaultInfor['apiProjectPath'] = table['apiProjectPath']\n\n\t\t\t\t\t\tif key == 'APIPACKAGE':\n\t\t\t\t\t\t\ttemp = self.getOtherInfor(line)\n\t\t\t\t\t\t\tif temp:\n\t\t\t\t\t\t\t\ttable['apiPackage'] = temp\n\t\t\t\t\t\t\t\tif not 'apiPackage' in defaultInfor:\n\t\t\t\t\t\t\t\t\tdefaultInfor['apiPackage'] = table['apiPackage']\n\n\t\t\t\t\t\tif key == 'SERVICEPROJECTPATH':\n\t\t\t\t\t\t\ttemp = self.getOtherInfor(line)\n\t\t\t\t\t\t\tif temp:\n\t\t\t\t\t\t\t\ttable['serviceProjectPath'] = temp\n\t\t\t\t\t\t\t\tif not 'serviceProjectPath' in defaultInfor:\n\t\t\t\t\t\t\t\t\tdefaultInfor['serviceProjectPath'] = table['serviceProjectPath']\n\n\t\t\t\t\t\tif key == 'SERVICEPACKAGE':\n\t\t\t\t\t\t\ttemp = self.getOtherInfor(line)\n\t\t\t\t\t\t\tif temp:\n\t\t\t\t\t\t\t\ttable['servicePackage'] = temp\n\t\t\t\t\t\t\t\tif not 'servicePackage' in defaultInfor:\n\t\t\t\t\t\t\t\t\tdefaultInfor['servicePackage'] = table['servicePackage']\n\n\t\t\t\t\t\tif key == 'MYBATIS':\n\t\t\t\t\t\t\tif len(line.split(':')) > 1:\n\t\t\t\t\t\t\t\ttable['myBatis'] = line.split(':')[1].replace('.', '\\\\').replace('\\n', '')\n\t\t\t\t\t\t\t\tif not 'myBatis' in defaultInfor:\n\t\t\t\t\t\t\t\t\tdefaultInfor['myBatis'] = table['myBatis']\n\n\t\t\t\t\t\t# 获取表注释\n\t\t\t\t\t\tif key == ') ENGINE=INNODB':\n\t\t\t\t\t\t\tinforArr = line.split('COMMENT=')\n\t\t\t\t\t\t\tif len(inforArr) > 1:\n\t\t\t\t\t\t\t\ttable['comm'] = inforArr[1].replace('\\n', '').replace('\\'', '').replace(';', '')\n\t\t\t\t\t\t\t# 下一张表,对tab进行初始化\n\t\t\t\t\t\t\tif table['javaBeanName']['beanName'] != '':\n\t\t\t\t\t\t\t\tAllTable.append(table)\n\t\t\t\t\t\t\t\ttable = { 'javaBeanName': { 'beanName':'', 'tableName':'' }, 'javaBeanVar': [] }\n\n\t\tdefaultInfor['author'] = author\n\n\t\tlocalPath = dir.split('\\\\')\n\t\tlocalPath[len(localPath) - 1] = 'Java'\n\t\tlocalPath = \"\\\\\".join(localPath)\n\n\t\tself.createAllFile(localPath,AllTable,defaultInfor,createFileName)\n\n\t\tfile.close()\n\n\t# 获取表名\n\tdef getJavaBeanName(self, line):\n\t\t# 忽略的表名关键字\n\t\tignoSqlTableNameKey = sublime.load_settings('Tools.sublime-settings').get('ignoSqlTableNameKey')\n\n\t\tlineArr = line.split('`')\n\t\ttableName = lineArr[1]\n\t\tnameArr = tableName.split('_')\n\n\t\tname = \"\"\n\t\tfor x in nameArr:\n\t\t\tif ignoSqlTableNameKey.count(x) == 0:\n\t\t\t\tname += x.capitalize()\n\t\treturn {'beanName': name, 'tableName': tableName}\n\n\t# 获取参数\n\tdef getJavaBeanVar(self, line):\n\t\t# sql 转java类型 定义\n\t\tsqlType = sublime.load_settings('Tools.sublime-settings').get('sqlToJavaType')\n\n\t\tlineArr = line.split('`')\n\t\tsqlVar = lineArr[1]\n\n\t\tjavaVar = { 'name': '', 'type': '', 'comm': '', 'sqlType': '', 'sqlName': '' }\n\n\t\tsqlvarTemp = sqlVar.split('_')\n\t\tif len(sqlvarTemp) > 0:\n\t\t\tjavaVar['name'] += sqlvarTemp[0]\n\t\tfor x in range(1, len(sqlvarTemp)):\n\t\t\tjavaVar['name'] += sqlvarTemp[x].capitalize()\n\n\t\tjavaBeanTemp = lineArr[2]\n\n\t\t# 获取注释\n\t\tCOMMENT = javaBeanTemp.split('COMMENT')\n\t\tif len(COMMENT) >= 2:\n\t\t\tCOMMENT = COMMENT[1].split('\\'')\n\t\t\tif len(COMMENT) >= 2:\n\t\t\t\tjavaVar['comm'] = COMMENT[1]\n\n\t\t# 获取sql类型\n\t\tfor key in sqlType.keys():\n\t\t\tif str(javaBeanTemp).expandtabs().lstrip().lower().startswith(key):\n\t\t\t\tjavaVar['type'] = sqlType[key]\n\t\t\t\tjavaVar['sqlType'] = key\n\t\t\t\tbreak\n\t\tjavaVar['sqlName'] = sqlVar\n\n\t\treturn javaVar\n\n\t# 获取其余信息\n\tdef getOtherInfor(self, line):\n\t\tif len(line.split(':')) > 1:\n\t\t\treturn line.split(':')[1].replace(';', '').replace('\\n', '')\n\t\treturn False\n\n\t# 生成文件\n\tdef createAllFile(self, path, infor, defaultInfor, createFileName):\n\t\tif createFileName == 'all':\n\t\t\tself.clearPath(path)\n\t\t\tos.makedirs(path + '\\\\bean')\n\t\t\tos.makedirs(path + '\\\\map')\n\t\t\tos.makedirs(path + '\\\\dao')\n\t\t\tos.makedirs(path + '\\\\service')\n\t\t\tos.makedirs(path + '\\\\service.impl')\n\t\t\tos.makedirs(path + '\\\\controller')\n\t\t\tos.makedirs(path + '\\\\html')\n\t\t\tos.makedirs(path + '\\\\other')\n\n\t\t\tfor x in infor:\n\t\t\t\tself.createBean(path + '\\\\bean', x, defaultInfor)\n\t\t\t\tself.createDao(path + '\\\\dao',x, defaultInfor)\n\t\t\t\tself.createMap(path + '\\\\map',x, defaultInfor)\n\t\t\t\tself.createService(path + '\\\\service',x, defaultInfor)\n\t\t\t\tself.createServiceImpl(path + '\\\\service.impl',x, defaultInfor)\n\t\t\t\tself.createController(path + '\\\\controller',x, defaultInfor)\n\t\t\t\tself.createOtherInfor(path + '\\\\other',x, defaultInfor)\n\t\t\t\tself.createHTML(path + '\\\\html',x, defaultInfor)\n\t\telse:\n\t\t\tif not os.path.exists(path + '\\\\' + createFileName):\n\t\t\t\tos.makedirs(path + '\\\\' + createFileName)\n\n\t\t\tif createFileName == 'bean':\n\t\t\t\tfor x in infor:\n\t\t\t\t\tself.createBean(path + '\\\\bean', x, defaultInfor)\n\t\t\tif createFileName == 'dao':\n\t\t\t\tfor x in infor:\n\t\t\t\t\tself.createDao(path + '\\\\dao',x, defaultInfor)\n\t\t\tif createFileName == 'map':\n\t\t\t\tfor x in infor:\n\t\t\t\t\tself.createMap(path + '\\\\map',x, defaultInfor)\n\t\t\tif createFileName == 'service':\n\t\t\t\tif not os.path.exists(path + '\\\\service.impl'):\n\t\t\t\t\tos.makedirs(path + '\\\\service.impl')\n\t\t\t\tfor x in infor:\n\t\t\t\t\tself.createService(path + '\\\\service',x, defaultInfor)\n\t\t\t\t\tself.createServiceImpl(path + '\\\\service.impl',x, defaultInfor)\n\t\t\tif createFileName == 'controller':\n\t\t\t\tfor x in infor:\n\t\t\t\t\tself.createController(path + '\\\\controller',x, defaultInfor)\n\t\t\tif createFileName == 'other':\n\t\t\t\tfor x in infor:\n\t\t\t\t\tself.createOtherInfor(path + '\\\\other',x, defaultInfor)\n\t\t\tif createFileName == 'html':\n\t\t\t\tfor x in infor:\n\t\t\t\t\tself.createHTML(path + '\\\\html',x, defaultInfor)\n\n\t# 清除文件\n\tdef clearPath(self, path):\n\t\tif os.path.exists(path):\n\t\t\tcurrent_filelist = os.listdir(path)\n\t\t\tfor x in current_filelist:\n\t\t\t\treal_folder_path = os.path.join(path,x)\n\t\t\t\tif os.path.isdir(real_folder_path):\n\t\t\t\t\tfor root, dirs, files in os.walk(real_folder_path):\n\t\t\t\t\t\tfor file in files:\n\t\t\t\t\t\t\tos.remove(os.path.join(real_folder_path,file))\n\t\t\t\t\t\tfor dir in dirs:\n\t\t\t\t\t\t\tpathTemp = os.path.join(real_folder_path,dir)\n\t\t\t\t\t\t\tfor root, dirs, files in os.walk(pathTemp):\n\t\t\t\t\t\t\t\tfor file in files:\n\t\t\t\t\t\t\t\t\tos.remove(os.path.join(root,file))\n\t\t\t\t\t\t\tshutil.rmtree(pathTemp)\n\t\t\t\t\tshutil.rmtree(real_folder_path)\n\t\t\tprint(\"非工程路径旧文件清除成功\")\n\n\t# 获取所需的真实字段\n\tdef getBaseData(self, keyFirst, keySeconnd, object, defaultInfor):\n\t\tif keyFirst in object:\n\t\t\treturn object[keyFirst]\n\t\telif keySeconnd in object:\n\t\t\treturn object[keySeconnd]\n\t\telif keyFirst in defaultInfor:\n\t\t\treturn defaultInfor[keyFirst]\n\t\telif keySeconnd in defaultInfor:\n\t\t\treturn defaultInfor[keySeconnd]\n\t\telse:\n\t\t\treturn \"\"\n\n\t# 创建bean\n\tdef createBean(self, path, object, defaultInfor):\n\t\tclassName = object['javaBeanName']['beanName']\t# 类名\n\t\tbeanName = className[0].lower() + className[1:]\t# 实体名\n\t\ttableName = object['javaBeanName']['tableName']\t# 表名\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\t\tcomm = \"\"\n\t\tif 'comm' in object:\n\t\t\tcomm = \" \\n\\t* 表注释:\" + object['comm']\n\n\t\tpackage = self.getBaseData('apiPackage', 'package', object, defaultInfor)\t# 包名\n\t\tif package == \"\":\n\t\t\tpackage = settings.get('defaultPackageName')\n\t\tpackage = package.replace('*', 'entity', 1)\n\n\t\tpathTemp = self.getBaseData('apiProjectPath', 'projectPath', object, defaultInfor)\t# 文件路径\n\t\tif pathTemp != \"\":\n\t\t\tpath = pathTemp + '\\\\src\\\\main\\\\java\\\\' + package.replace('.', '\\\\')\n\n\t\tauthor = \"\"\t# 作者\n\t\tif 'author' in defaultInfor:\n\t\t\tauthor = defaultInfor['author']\n\n\t\t# 忽略的字段\n\t\tignoredField = settings.get('ignoredField')\n\n\t\tfp = open(path + '\\\\' + className + '.java', mode='w', encoding='UTF-8')\n\t\tfp.write(\n\t\t\t\"package \" + package + \";\\n\\n\" + \n\t\t\t\"import java.util.Date;\\n\" + \n\t\t\t\"import org.apache.ibatis.type.Alias;\\n\" + \n\t\t\t\"import org.zte.framework.orm.mybatis.entity.DataEntity;\\n\\n\\n\" + \n\t\t\t\"\\n/**\\n\\t* 映射表名:\" + tableName + comm + \" \\n\\t* 作者:\" + author + \"\\n\\t* 时间:\" + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + \"\\n*/\\n\\n\" + \n\t\t\t\"@Alias(\\\"\" + beanName + \"\\\")\\n\" + \n\t\t\t\"public class \" + className + \" extends DataEntity {\\n\" + \n\t\t\t\"\\n\\tprivate static final long serialVersionUID = 1L;\\n\"\n\t\t)\n\n\t\tfunc = ''\n\t\tfor x in object['javaBeanVar']:\n\t\t\tif x['name'] in ignoredField:\n\t\t\t\tcontinue\n\t\t\tString = \"\\tprivate \" + x['type'] + \" \" + x['name'] + ';'\n\t\t\tif x['comm'] != '':\n\t\t\t\tString += '\\t\\t// ' + x['comm']\n\t\t\tfp.write(String + '\\n')\n\n\t\t\tfunc += '\\n\\n\\tpublic ' + x['type'] + ' get' + x['name'][0].capitalize() + x['name'][1:] + \"(){\\n\\t\\treturn \" + x['name'] + \";\\n\\t}\"\n\t\t\tfunc += '\\n\\n\\tpublic void set' + x['name'][0].capitalize() + x['name'][1:] + \"(\" + x['type'] + ' ' + x['name'] + \"){\\n\\t\\tthis.\" + x['name'] + ' = ' + x['name'] + \";\\n\\t}\"\n\n\t\tfp.write(func + \"\\n\\n}\\n\")\n\t\tfp.close()\n\t\tprint(\"生成实体类:\" + className)\n\n\t# 创建dao\n\tdef createDao(self, path, object, defaultInfor):\n\t\tclassName = object['javaBeanName']['beanName'] + \"Dao\"\n\t\tbaseClassName = object['javaBeanName']['beanName']\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\n\t\tcomm = \"\"\n\t\tif 'comm' in object:\n\t\t\tcomm = \" \\n\\t* 表注释:\" + object['comm']\n\n\t\tauthor = \"\"\t# 作者\n\t\tif 'author' in defaultInfor:\n\t\t\tauthor = defaultInfor['author']\n\n\t\tapiPackage = self.getBaseData('apiPackage', 'package', object, defaultInfor)\t# api包名\n\t\tif apiPackage == \"\":\n\t\t\tapiPackage = settings.get('defaultPackageName')\n\n\t\tpackage = self.getBaseData('servicePackage', 'package', object, defaultInfor)\t# service包名\n\t\tif package == \"\":\n\t\t\tpackage = settings.get('defaultPackageName')\n\n\t\tpathTemp = self.getBaseData('serviceProjectPath', 'projectPath', object, defaultInfor)\t# 文件路径\n\t\tif pathTemp != \"\":\n\t\t\tpath = pathTemp + '\\\\src\\\\main\\\\java\\\\' + package.replace('.', '\\\\').replace('*', 'dao', 1)\n\n\t\tfp = open(path + '\\\\' + className + '.java', mode='w', encoding='UTF-8')\n\t\tfp.write(\n\t\t\t\"package \" + package.replace('*', 'dao', 1).replace('\\n', '', 1) + \";\\n\\n\" + \n\t\t\t\"import java.util.Map;\\n\" + \n\t\t\t\"import java.util.List;\\n\" + \n\t\t\t\"import org.zte.framework.mybatis.paginator.domain.PageBounds;\\n\" + \n\t\t\t\"import org.zte.framework.mybatis.paginator.domain.PageList;\\n\" + \n\t\t\t\"import org.zte.framework.orm.mybatis.dao.BaseDao;\\n\" + \n\t\t\t\"import \" + apiPackage.replace('*', 'entity', 1).replace('\\n', '', 1) + '.' + baseClassName + \";\\n\" + \n\t\t\t\"import org.zte.framework.orm.mybatis.MyBatisRepository;\\n\\n\\n\" + \n\t\t\t\"\\n/**\\n\\t* 映射表名:\" + object['javaBeanName']['tableName'] + comm + \" \\n\\t* 实体:\" + baseClassName + \" \\n\\t* 作者:\" + author + \"\\n\\t* 时间:\" + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + \"\\n*/\\n\\n\" + \n\t\t\t\"@MyBatisRepository\\n\" + \n\t\t\t\"public interface \" + className + \" extends BaseDao<\" + baseClassName + \",Integer> {\" + \n\n\t\t\t\"\\n\\t/**\\n\\t * 分页查找数据\\n\\t * @param map\\n\\t * @param pageBounds\\n\\t * @return\\n\\t*/\\n\" +\n\t\t\t\"\\tPageList> findByCondition(Map map, PageBounds pageBounds);\\n\\n\" +\n\n\t\t\t\"\\n\\t/**\\n\\t * 不分页查找数据\\n\\t * @param map\\n\\t * @param pageBounds\\n\\t * @return\\n\\t*/\\n\" +\n\t\t\t\"\\tList> findByCondition(Map map);\\n\\n\" +\n\n\t\t\t\"\\n\\t/**\\n\\t * 按条件查找记录数量\\n\\t * @param map\\n\\t * @return\\n\\t*/\\n\" + \n\t\t\t\"\\tInteger getCountByCondition(Map map);\\n\\n\" + \n\n\t\t\t\"}\\n\"\n\t\t)\n\t\tfp.close()\n\t\tprint(\"生成Dao类:\" + className)\n\n\t# 创建map\n\tdef createMap(self, path, object, defaultInfor):\n\t\tmapName = object['javaBeanName']['beanName'] + \"Mapper\"\n\t\tbeanClassName = object['javaBeanName']['beanName']\n\t\ttableName = object['javaBeanName']['tableName']\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\n\t\tcomm = \"\"\n\t\tif 'comm' in object:\n\t\t\tcomm = \"\\n\\t表注释:\" + object['comm']\n\n\t\tauthor = \"\"\t# 作者\n\t\tif 'author' in defaultInfor:\n\t\t\tauthor = defaultInfor['author']\n\n\t\tapiPackage = self.getBaseData('apiPackage', 'package', object, defaultInfor)\t# api���名\n\t\tif apiPackage == \"\":\n\t\t\tapiPackage = settings.get('defaultPackageName')\n\n\t\tpackage = self.getBaseData('servicePackage', 'package', object, defaultInfor)\t# service包名\n\t\tif package == \"\":\n\t\t\tpackage = settings.get('defaultPackageName')\n\n\t\tpathTemp = self.getBaseData('serviceProjectPath', 'projectPath', object, defaultInfor)\t# 文件路径\n\t\tif pathTemp != \"\":\n\t\t\tif 'myBatis' in object:\n\t\t\t\tpath = pathTemp + '\\\\src\\\\main\\\\resources\\\\mybatis\\\\' +object['myBatis']\n\t\t\telif 'myBatis' in defaultInfor:\n\t\t\t\tpath = pathTemp + '\\\\src\\\\main\\\\resources\\\\mybatis\\\\' +defaultInfor['myBatis']\n\t\t\telse:\n\t\t\t\tpath = pathTemp + '\\\\src\\\\main\\\\resources\\\\mybatis'\n\n\t\tfp = open(path + '\\\\' + mapName + '.xml', mode='w', encoding='UTF-8')\n\t\tfp.write(\n\t\t\t'\\n' + \n\t\t\t'\\n' + \n\t\t\t'\\n\\n' + \n\t\t\t'\\n' + \n\t\t\t'\\t\\n\\n' + \n\t\t\t'\\t\\n' + \n\t\t\t'\\t\\n' + \n\t\t\t'\\t\\tinsert into ' + tableName + '(\\n' + \n\t\t\t'\\t\\t\\n' + \n\t\t\t'\\t\\t\\tid,\\n' + \n\t\t\t'\\t\\t'\n\t\t)\n\t\tsqlString = '\\n\\t\\t'\n\t\tjavaString = '\\n\\t\\t'\n\n\t\t# insert\n\t\tjavaBeanVar = object['javaBeanVar']\n\t\tfor x in javaBeanVar:\n\t\t\tif x['sqlName'] == 'id':\n\t\t\t\tcontinue\n\t\t\tif x['sqlName'] == javaBeanVar[len(javaBeanVar) - 1]['sqlName']:\n\t\t\t\tsqlString += x['sqlName']\n\t\t\t\tjavaString += '#{'+ x['name'] +'}'\n\t\t\t\tbreak\n\t\t\tsqlString += x['sqlName'] + ',\\n\\t\\t'\n\t\t\tjavaString += '#{'+ x['name'] +'},\\n\\t\\t'\n\t\tfp.write(\n\t\t\tsqlString + '\\n\\t\\t) values (\\n\\t\\t\\n\\t\\t\\t#{id},\\n\\t\\t' + javaString + \n\t\t\t'\\n\\t\\t)\\n\\t\\t select LAST_INSERT_ID() \\n\\t\\n\\n\\n'\n\t\t)\n\n\t\t# delete\n\t\tfp.write('\\t\\n\\t\\n\\t\\tdelete from ' + tableName + ' where id = #{id}\\n\\t\\n\\n\\n')\n\n\t\t# deletes\n\t\tfp.write('\\t\\n\\t\\n\\t\\tdelete from ' + tableName + ' where id in\\n\\t\\t\\n\\t\\t\\t#{item}\\n\\t\\t\\n\\t\\n\\n\\n')\n\n\t\t# update\n\t\tupdateString = ''\n\t\tfor x in javaBeanVar:\n\t\t\tif x['sqlName'] == 'id':\n\t\t\t\tcontinue\n\t\t\tif x['sqlName'] == javaBeanVar[len(javaBeanVar) - 1]['sqlName']:\n\t\t\t\tupdateString += 't.' + x['sqlName'] + ' = ' + '#{' + x['name'] + '}'\n\t\t\t\tbreak\n\t\t\tupdateString += 't.' + x['sqlName'] + ' = ' + '#{' + x['name'] + '},\\n\\t\\t\\t'\n\t\tfp.write('\\t\\n\\t\\n\\t\\tupdate ' + tableName + ' t\\n\\t\\tset ' +\n\t\t\tupdateString + \n\t\t\t'\\n\\t\\twhere t.id = #{id}\\n\\t\\n\\n\\n'\n\t\t)\n\n\t\t# get\n\t\tfp.write('\\t\\n\\t\\n\\n\\n'\n\t\t)\n\n\t\t# findByCondition\n\t\tgetString = ''\n\t\torderBy = ''\n\t\tfor x in javaBeanVar:\n\t\t\tif x['sqlName'] == 'id':\n\t\t\t\tcontinue\n\t\t\tif x['sqlName'] == javaBeanVar[len(javaBeanVar) - 1]['sqlName']:\n\t\t\t\tgetString += 't.' + x['sqlName'] + ' as `' + x['name'] + '`'\n\t\t\t\t\n\t\t\t\tbreak\n\t\t\tgetString += 't.' + x['sqlName'] + ' as `' + x['name'] + '`,\\n\\t\\t\\t'\n\t\tif getString.count('order_num') > 0:\n\t\t\torderBy = '\\n\\t\\torder by IFNULL(t.order_num,99999)'\n\t\tfp.write('\\t\\n\\t\\n\\n\\n'\n\t\t)\n\n\t\t# getCountByCondition\n\t\tfp.write('\\t\\n\\t')\n\n\t\tfp.write('\\n')\n\n\t\tfp.close()\n\n\t\tprint(\"生成Map:\" + mapName)\n\n\t# 创建service\n\tdef createService(self, path, object, defaultInfor):\n\t\tclassName = object['javaBeanName']['beanName'] + \"Service\"\t# 类名\n\t\tbaseClassName = object['javaBeanName']['beanName']\t# bean类名\n\t\tpackage = self.getBaseData('apiPackage', 'package', object, defaultInfor)\t# 包名\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\t\tif package == \"\":\n\t\t\tpackage = settings.get('defaultPackageName')\n\n\t\tpathTemp = self.getBaseData('apiProjectPath', 'projectPath', object, defaultInfor)\t# 文件路径\n\t\tif pathTemp != \"\":\n\t\t\tpath = pathTemp + '\\\\src\\\\main\\\\java\\\\' + package.replace('.', '\\\\').replace('*', 'service', 1)\n\n\t\tauthor = \"\"\t# 作者\n\t\tif 'author' in defaultInfor:\n\t\t\tauthor = defaultInfor['author']\n\n\t\tcomm = \"\"\n\t\tif 'comm' in object:\n\t\t\tcomm = \" \\n\\t* 表注释:\" + object['comm']\n\n\t\tfp = open(path + '\\\\' + className + '.java', mode='w', encoding='UTF-8')\n\t\tfp.write(\n\t\t\t\"package \" + package.replace('*', 'service', 1).replace('\\n', '', 1) + \";\\n\\n\" + \n\t\t\t\"import java.util.List;\\n\" + \n\t\t\t\"import java.util.Map;\\n\" + \n\t\t\t\"import org.zte.framework.mybatis.paginator.domain.PageBounds;\\n\" + \n\t\t\t\"import org.zte.framework.page.PageResult;\\n\" + \n\t\t\t\"import \" + package.replace('*', 'entity', 1).replace('\\n', '', 1) + '.' + baseClassName + \";\\n\" + \n\t\t\t\"import org.zte.framework.orm.mybatis.service.BaseService;\\n\\n\\n\" + \n\t\t\t\"\\n/**\\n\\t* 映射表名:\" + object['javaBeanName']['tableName'] + comm + \" \\n\\t* 实体:\" + baseClassName + \" \\n\\t* 作者:\" + author + \"\\n\\t* 时间:\" + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + \"\\n*/\\n\\n\" + \n\t\t\t\"public interface \" + className + \" extends BaseService<\" + baseClassName + \",Integer> {\" + \n\n\t\t\t\"\\n\\t/**\\n\\t * 分页查找数据\\n\\t * @param map\\n\\t * @param pageBounds\\n\\t * @return\\n\\t*/\\n\" +\n\t\t\t\"\\tpublic PageResult>> findByCondition(Map map, PageBounds pageBounds);\\n\\n\" +\n\n\t\t\t\"\\n\\t/**\\n\\t * 不分页查找数据\\n\\t * @param map\\n\\t * @param pageBounds\\n\\t * @return\\n\\t*/\\n\" +\n\t\t\t\"\\tpublic List> findByCondition(Map map);\\n\\n\" +\n\n\t\t\t\"\\n\\t/**\\n\\t * 按条件查找记录数量\\n\\t * @param map\\n\\t * @return\\n\\t*/\\n\" + \n\t\t\t\"\\tpublic Integer getCountByCondition(Map map);\\n\\n\" + \n\n\t\t\t\"}\\n\"\n\t\t)\n\t\tfp.close()\n\t\tprint(\"生成service类:\" + className)\n\n\t# 创建createServiceImpl\n\tdef createServiceImpl(self, path, object, defaultInfor):\n\t\tclassName = object['javaBeanName']['beanName'] + \"ServiceImpl\"\n\t\tbaseClassName = object['javaBeanName']['beanName']\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\n\t\tauthor = \"\"\t# 作者\n\t\tif 'author' in defaultInfor:\n\t\t\tauthor = defaultInfor['author']\n\n\t\tcomm = \"\"\n\t\tif 'comm' in object:\n\t\t\tcomm = \" \\n\\t* 表注释:\" + object['comm']\n\n\t\tpackage = self.getBaseData('servicePackage', 'package', object, defaultInfor)\t# service包名\n\t\tif package == \"\":\n\t\t\tpackage = settings.get('defaultPackageName')\n\n\t\tpathTemp = self.getBaseData('serviceProjectPath', 'projectPath', object, defaultInfor)\t# 文件路径\n\t\tif pathTemp != \"\":\n\t\t\tpath = pathTemp + '\\\\src\\\\main\\\\java\\\\' + package.replace('*', 'service.impl', 1).replace('.', '\\\\')\n\n\t\tapiPackage = self.getBaseData('apiPackage', 'package', object, defaultInfor)\t# api包名\n\t\tif apiPackage == \"\":\n\t\t\tapiPackage = settings.get('defaultPackageName')\n\n\t\tfp = open(path + '\\\\' + className + '.java', mode='w', encoding='UTF-8')\n\t\tfp.write(\n\t\t\t\"package \" + package.replace('*', 'service.impl', 1).replace('\\n', '', 1) + \";\\n\\n\" + \n\t\t\t\"import java.util.List;\\n\" + \n\t\t\t\"import java.util.Map;\\n\" + \n\t\t\t\"import org.springframework.stereotype.Service;\\n\" + \n\t\t\t\"import org.zte.framework.mybatis.paginator.domain.PageBounds;\\n\" + \n\t\t\t\"import org.zte.framework.orm.mybatis.service.impl.BaseServiceImpl;\\n\" + \n\t\t\t\"import org.zte.framework.page.PageResult;\\n\" + \n\t\t\t\"import org.zte.framework.page.PageUtils;\\n\" + \n\t\t\t\"import \" + package.replace('*', 'dao', 1).replace('\\n', '', 1) + '.' + baseClassName + \"Dao;\\n\" + \n\t\t\t\"import \" + apiPackage.replace('*', 'service', 1).replace('\\n', '', 1) + '.' + baseClassName + \"Service;\\n\" + \n\t\t\t\"import \" + apiPackage.replace('*', 'entity', 1).replace('\\n', '', 1) + '.' + baseClassName + \";\\n\\n\\n\" + \n\t\t\t\"\\n/**\\n\\t* 映射表名:\" + object['javaBeanName']['tableName'] + comm + \" \\n\\t* 实体:\" + baseClassName + \" \\n\\t* 作者:\" + author + \"\\n\\t* 时间:\" + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + \"\\n*/\\n\\n\" + \n\t\t\t'@Service(\"' + baseClassName[0].lower() + baseClassName[1:] + 'Service\")\\n' + \n\t\t\t\"public class \" + className + \" extends BaseServiceImpl<\" + baseClassName + \"Dao,\" + baseClassName + \",Integer> implements \" + baseClassName + \"Service {\\n\\n\" + \n\t\t\t\"\\t@Override\\n\\tpublic Integer getCountByCondition(Map map) {\\n\\t\\treturn dao.getCountByCondition(map);\\n\\t}\\n\\n\" + \n\t\t\t\"\\t@Override\\n\\tpublic PageResult>> findByCondition(Map map, PageBounds pageBounds) {\\n\\t\\treturn PageUtils.returnPage(dao.findByCondition(map,pageBounds));\\n\\t}\\n\\n\" + \n\t\t\t\"\\t@Override\\n\\tpublic List> findByCondition(Map map) {\\n\\t\\treturn dao.findByCondition(map);\\n\\t}\\n\\n}\"\n\t\t)\n\t\tfp.close()\n\t\tprint(\"生成serviceImpl类:\" + className)\n\n\t# 创建controller\n\tdef createController(self, path, object, defaultInfor):\n\t\tclassName = object['javaBeanName']['beanName'] + \"Controller\"\n\t\tbaseClassName = object['javaBeanName']['beanName']\n\t\tserviceBean = baseClassName[0].lower() + baseClassName[1:] + 'Service'\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\n\t\tcomm = \"\"\n\t\tif 'comm' in object:\n\t\t\tcomm = \"\\n\\t* 表注释:\" + object['comm']\n\n\t\tauthor = \"\"\t# 作者\n\t\tif 'author' in defaultInfor:\n\t\t\tauthor = defaultInfor['author']\n\n\t\tapiPackage = self.getBaseData('apiPackage', 'package', object, defaultInfor)\t# api包名\n\t\tif apiPackage == \"\":\n\t\t\tapiPackage = settings.get('defaultPackageName')\n\n\t\tservicePackage = self.getBaseData('servicePackage', 'package', object, defaultInfor)\t# service包名\n\t\tif servicePackage == \"\":\n\t\t\tservicePackage = settings.get('defaultPackageName')\n\n\t\tpackage = self.getBaseData('package', 'package', object, defaultInfor)\t# 包名\n\t\tif package == \"\":\n\t\t\tpackage = settings.get('defaultPackageName')\n\n\t\tpathTemp = self.getBaseData('projectPath', 'projectPath', object, defaultInfor)\t# 文件路径\n\t\tif pathTemp != \"\":\n\t\t\tpath = pathTemp + '\\\\src\\\\main\\\\java\\\\' + package.replace('*', 'controller.after').replace('.', '\\\\')\n\n\t\t# baseController的位置\n\t\tBaseController = \"import \" + package.split('*')[0] + \"BaseController;\\n\"\n\t\tif BaseController.count(\"main_web\") >= 1:\n\t\t\tBaseController = \"import com.zte.platform.main_web.web.BaseController;\\n\"\n\n\t\tfp = open(path + '\\\\' + className + '.java', mode='w', encoding='UTF-8')\n\t\tfp.write(\n\t\t\t\"package \" + package.replace('*', 'controller.after', 1).replace('\\n', '', 1) + \";\\n\\n\" + \n\t\t\t\"import java.util.List;\\n\" + \n\t\t\t\"import java.util.Map;\\n\" + \n\t\t\t\"import org.zte.framework.mybatis.paginator.domain.PageBounds;\\n\" + \n\t\t\t\"import org.zte.framework.result.ResultUtils;\\n\" + \n\t\t\t\"import org.zte.framework.result.Result;\\n\" + \n\t\t\t\"import org.zte.framework.bean.MyBeanUtils;\\n\" + \n\t\t\t\"import javax.servlet.http.HttpServletRequest;\\n\" + \n\t\t\t\"import javax.servlet.http.HttpServletResponse;\\n\" + \n\t\t\t\"import org.springframework.stereotype.Controller;\\n\" + \n\t\t\t\"import org.springframework.beans.factory.annotation.Autowired;\\n\" + \n\t\t\t\"import org.springframework.web.bind.annotation.ResponseBody;\\n\" + \n\t\t\t\"import org.springframework.web.bind.annotation.RequestMethod;\\n\" + \n\t\t\t\"import org.springframework.web.bind.annotation.RequestMapping;\\n\" + \n\t\t\t\"import org.zte.framework.page.PageResult;\\n\" + \n\t\t\t\"import com.google.common.collect.Maps;\\n\" + \n\t\t\t\"import org.springframework.web.bind.annotation.RequestParam;\\n\\n\" + BaseController +\n\t\t\t\"import \" + servicePackage.replace('*','service') + '.' + baseClassName + \"Service;\\n\" + \n\t\t\t\"import \" + apiPackage.replace('*','entity') + '.' + baseClassName + \";\\n\" + \n\t\t\t\"import \" + package.split('*')[0] + \"annotation.OperationType;\\n\" + \n\t\t\t\"import \" + package.split('*')[0] + \"annotation.SysOperationLog;\\n\" + \n\t\t\t\"\\n/**\\n\\t* 映射表名:\" + object['javaBeanName']['tableName'] + comm + \" \\n\\t* 实体:\" + baseClassName + \" \\n\\t* 作者:\" + author + \"\\n\\t* 时间:\" + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + \"\\n*/\\n\\n\" + \n\t\t\t\"@Controller\\n\" + \n\t\t\t'@RequestMapping(\"after/' + baseClassName[0].lower() + baseClassName[1:] + '\")\\n' + \n\t\t\t'public class ' + className + ' extends BaseController {\\n' + \n\t\t\t'\\t@Autowired\\n\\tprivate ' + baseClassName + 'Service ' + serviceBean + ';\\n\\n' + \n\t\t\t# data\n\t\t\t'\\t/**\\n\\t* 获取数据列表\\n\\t* @param request 请求对象\\n\\t* @param response 响应对象\\n\\t* @param pageSize 每页条数\\n\\t* @param currPage 当前页码\\n\\t* @return\\n\\t*/\\n' + \n\t\t\t'\\t@RequestMapping(value=\"/data\",method=RequestMethod.GET)\\n' + \n\t\t\t'\\t@ResponseBody\\n' + \n\t\t\t'\\tpublic PageResult>> data(\\n' + \n\t\t\t'\\t\\t\\tHttpServletRequest request, HttpServletResponse response,\\n' + \n\t\t\t'\\t\\t\\t@RequestParam(value = \"pageSize\", defaultValue = \"10\", required = false) Integer pageSize,\\n' + \n\t\t\t'\\t\\t\\t@RequestParam(value = \"currPage\", defaultValue = \"1\", required = false) Integer currPage\\n' + \n\t\t\t'\\t){\\n' + \n\t\t\t'\\t\\t// 参数\\n' + \n\t\t\t'\\t\\tMap map = Maps.newHashMap();\\n\\n\\n' + \n\t\t\t'\\t\\tPageBounds pb = new PageBounds(currPage, pageSize);\\n' + \n\t\t\t'\\t\\treturn ' + serviceBean + '.findByCondition(map, pb);\\n\\t}\\n\\n\\n'+\n\n\t\t\t# get\n\t\t\t'\\t/**\\n\\t* 根据id获取记录数\\n\\t* @param request 请求对象\\n\\t* @param response 响应对象\\n\\t* @param id 根据id获取记录数\\n\\t* @return\\n\\t*/\\n' + \n\t\t\t'\\t@RequestMapping(value = \"/get\", method = RequestMethod.GET)\\n' + \n\t\t\t'\\t@ResponseBody\\n' + \n\t\t\t'\\tpublic Result getData(\\n' + \n\t\t\t'\\t\\t\\tHttpServletRequest request, HttpServletResponse response,\\n' + \n\t\t\t'\\t\\t\\t@RequestParam(value = \"id\", required = true) Integer id\\n' + \n\t\t\t'\\t){\\n' + \n\t\t\t'\\t\\treturn ResultUtils.returnSuccess(\"成功\", ' + serviceBean + '.get(id));\\n\\t}\\n\\n\\n' + \n\n\t\t\t# deletes\n\t\t\t'\\t/**\\n\\t* 根据ids删除记录数\\n\\t* @param request 请求对象\\n\\t* @param response 响应对象\\n\\t* @param ids 根据ids删除记录数\\n\\t* @return\\n\\t*/\\n' + \n\t\t\t'\\t@SysOperationLog(description=\"删除' + baseClassName + '\",idField=\"ids\",type=OperationType.delete)\\n' + \n\t\t\t'\\t@RequestMapping(value = \"/deletes\",method = RequestMethod.POST)\\n' + \n\t\t\t'\\t@ResponseBody\\n' + \n\t\t\t'\\tpublic Result delete(\\n' + \n\t\t\t'\\t\\t\\tHttpServletRequest request, HttpServletResponse response,\\n' + \n\t\t\t'\\t\\t\\t@RequestParam(value=\"ids\",required=true) String ids\\n' + \n\t\t\t'\\t){\\n' + \n\t\t\t'\\t\\treturn ' + serviceBean + '.deletes(ids);\\n\\t}\\n\\n\\n' + \n\n\t\t\t# save\n\t\t\t'\\t/**\\n\\t* 保存记录信息\\n\\t* @param request 请求对象\\n\\t* @param response 响应对象\\n\\t* @param porp 要保存的对象\\n\\t* @return\\n\\t*/\\n' + \n\t\t\t'\\t@SysOperationLog(description=\"新增或修改' + baseClassName + '\",idField=\"ids\",type=OperationType.saveorupdate)\\n' + \n\t\t\t'\\t@RequestMapping(value = \"/save\",method = RequestMethod.POST)\\n' + \n\t\t\t'\\t@ResponseBody\\n' + \n\t\t\t'\\tpublic Result save(\\n' + \n\t\t\t'\\t\\t\\tHttpServletRequest request, HttpServletResponse response,\\n' + \n\t\t\t'\\t\\t\\t' + baseClassName + ' porp\\n' + \n\t\t\t'\\t){\\n' + \n\n\t\t\t'\\t\\tResult result = super.beanValidatorList(porp);\\n' + \n\t\t\t'\\t\\tif (!result.isSuccess()) return result;\\n\\n' + \n\t\t\t'\\t\\t' + baseClassName + ' saveModel = null;\\n' + \n\t\t\t'\\t\\tif (porp.getId() == null) {\\n' + \n\t\t\t'\\t\\t\\tsaveModel = new ' + baseClassName + '();\\n' + \n\t\t\t'\\t\\t} else {\\n' + \n\t\t\t'\\t\\t\\tsaveModel = ' + serviceBean + '.get(porp.getId());\\n' + \n\t\t\t'\\t\\t}\\n\\n' + \n\t\t\t'\\t\\tMyBeanUtils.propertyUtils(saveModel, porp);\\n' + \n\t\t\t'\\t\\treturn ' + serviceBean + '.save(saveModel);\\n\\t}\\n\\n\\n' + \n\t\t\t\n\t\t\t'}'\n\t\t)\n\t\tfp.close()\n\t\tprint(\"生成controller类:\" + className)\n\n\t# 创建其余信息\n\tdef createOtherInfor(self, path, object, defaultInfor):\n\t\tbaseClassName = object['javaBeanName']['beanName']\n\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\t\totherTemp = settings.get('otherTemp')\n\n\t\tservicePackage = self.getBaseData('servicePackage', 'package', object, defaultInfor)\t# service包名\n\t\tif servicePackage == \"\":\n\t\t\tservicePackage = settings.get('defaultPackageName')\n\n\t\ttemp = servicePackage.split('.')\n\t\tduboName = temp[len(temp) - 2]\n\n\t\t# dubbo\n\t\tserverClass = servicePackage.replace('*','service') + '.' + baseClassName\n\t\tserverBean = baseClassName[0].lower() + baseClassName[1:]\n\t\t\n\t\tfp = open(path + '\\\\otherInfor.txt', mode='w', encoding='UTF-8')\n\t\tfp.write('#生成信息不一定正确\\n\\n')\n\t\tfp.write(otherTemp[\"dubboService\"].replace(\"server-class\", serverClass).replace(\"server-bean\", serverBean))\n\t\tfp.write(otherTemp[\"dubboClient\"].replace(\"server-class\", serverClass).replace(\"server-bean\", serverBean))\n\t\tfp.close()\n\t\tprint(\"生成附加信息\")\n\n\t# 创建HTML\n\tdef createHTML(self, path, object, defaultInfor):\n\t\tbaseClassName = object['javaBeanName']['beanName']\n\t\tpathName = baseClassName\n\t\thtmlListName = baseClassName[0].lower() + baseClassName[1:] + 'List'\n\t\thtmlEditName = baseClassName[0].lower() + baseClassName[1:] + 'Edit'\n\t\turlName = baseClassName[0].lower() + baseClassName[1:]\n\t\tsettings = sublime.load_settings('Tools.sublime-settings')\n\t\thtmlTemp = settings.get('htmlTemp')\n\t\tjsTemp = settings.get('jsTemp')\n\t\tignoredField = settings.get('ignoredField')\n\n\t\tos.makedirs(path + '\\\\' + pathName)\n\n\t\t# html - list\n\t\tfp = open(path + '\\\\' + pathName + '\\\\' + htmlListName + '.html', mode='w', encoding='UTF-8')\n\t\tnameTh = ''\n\t\tvalTd = ''\n\t\tfor x in object['javaBeanVar']:\n\t\t\tif x['name'] in ignoredField:\n\t\t\t\tcontinue\n\t\t\tnameTh += '\\t\\t\\t\\t\\t\\t' + x['comm'] + '\\n'\n\t\t\tvalTd += '\\t\\t\\t\\t\\t\\t{{index.' + x['name'] + '}}\\n'\n\n\t\tfp.write(htmlTemp['list'].replace('path-name',pathName).replace('html-edit-name',htmlEditName).replace('name-th',nameTh).replace('val-td',valTd))\n\t\tfp.close()\n\n\t\t# html - edit\n\t\tfp = open(path + '\\\\' + pathName + '\\\\' + htmlEditName + '.html', mode='w', encoding='UTF-8')\n\t\teditString = ''\n\t\tfor x in object['javaBeanVar']:\n\t\t\tif x['name'] in ignoredField:\n\t\t\t\tcontinue\n\t\t\tif x['name'] in htmlTemp:\n\t\t\t\teditString += htmlTemp[x['name']].replace('replace-value',x['name']).replace('replace-name',x['comm'])\n\t\t\telif x['type'] in htmlTemp:\n\t\t\t\teditString += htmlTemp[x['type']].replace('replace-value',x['name']).replace('replace-name',x['comm'])\n\t\t\telif x['sqlType'] in htmlTemp:\n\t\t\t\teditString += htmlTemp[x['sqlType']].replace('replace-value',x['name']).replace('replace-name',x['comm'])\n\t\t\telse:\n\t\t\t\teditString += htmlTemp['other'].replace('replace-value',x['name']).replace('replace-name',x['comm'])\n\n\t\tfp.write(htmlTemp['edit'].replace('path-name',pathName).replace('edit-string',editString))\n\t\tfp.close()\n\n\t\t# js - list\n\t\tfp = open(path + '\\\\' + pathName + '\\\\' + htmlListName + '.js', mode='w', encoding='UTF-8')\n\t\t\n\t\tfp.write(jsTemp[\"list\"].replace(\"path-name\",pathName).replace(\"url-name\",urlName).replace(\"html-edit-name\",htmlEditName))\n\n\t\tfp.close()\n\n\t\t# js - edit\n\t\tfp = open(path + '\\\\' + pathName + '\\\\' + htmlEditName + '.js', mode='w', encoding='UTF-8')\n\t\tfp.write(jsTemp[\"edit\"].replace(\"path-name\",pathName).replace(\"url-name\",urlName))\n\t\tfp.close()\n\n\t\tprint(\"生成HTML\")\n\n\n\t# 获取文件位置\n\tdef get_path(self, paths):\n\t\tpath = None\n\t\tif paths:\n\t\t\tpath = '*'.join(paths)\n\t\telse:\n\t\t\tview = sublime.active_window().active_view()\n\t\t\tpath = view.file_name() if view else None\n\t\treturn path\n\n\t# 显示菜单\n\t# def is_visible(self):\n\t# \tview = self.view\n\t# \tfName = view.file_name()\n\t# \tvSettings = view.settings()\n\t# \tsyntaxPath = vSettings.get('syntax')\n\t# \tsyntax = \"\"\n\t# \text = \"\"\n\n\t# \tif (fName != None): # file exists, pull syntax type from extension\n\t# \t\text = os.path.splitext(fName)[1][1:]\n\t# \tif(syntaxPath != None):\n\t# \t\tsyntax = os.path.splitext(syntaxPath)[0].split('/')[-1].lower()\n\n\t# \treturn ext in ['sql']\n\n\nclass TestCommand(sublime_plugin.WindowCommand):\n\tdef run(self):\n\t\tsublime.status_message('Prefixr successfully run on %s selection%s' % (1, '' if 1 == 1 else 's'))","repo_name":"CCSQ/Tools","sub_path":"Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":41049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30012686841","text":"import pandas as pd\n\n# rutaFileCsv -> ruta del archivo\nrutaFileCsv = 'https://raw.githubusercontent.com/luisguillermomolero/MisionTIC2022_2/master/Modulo1_Python_MisionTIC2022_Main/Semana_5/Reto/movies.csv'\n\ndef listaPeliculas(rutaFileCsv: str)->str:\n\n # print(rutaFileCsv.split('.')[-1])\n if rutaFileCsv.split('.')[-1] == 'csv':\n \n try:\n # Leer el archivo csv\n arc_csv = pd.read_csv(rutaFileCsv)\n # print(type(arc_csv))\n\n # Se crea un subconjunto con las columnas 'Country', 'Language' e 'Gross Earnings'\n subGrupoPeliculas = arc_csv[['Country','Language','Gross Earnings']]\n #print(subGrupoPeliculas)\n\n ganaciaPaisLenguaje = subGrupoPeliculas.pivot_table(index=['Country','Language'])\n return ganaciaPaisLenguaje.head(10)\n\n except:\n print('Error al leer el archivo de datos.')\n else:\n print('Extensión inválida.')\n\nprint(listaPeliculas(rutaFileCsv))","repo_name":"IsraelArbona/mision_tic_gp_37","sub_path":"ciclo_1/semana5/solucion_reto5.py","file_name":"solucion_reto5.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"40333711047","text":"from link_list import *\nl1=LinkList()\nl2=LinkList()\nl1.init_list([1,5,7,8,9,4,3,])\nl2.init_list([2,3,4,5,2,9,4,3,])\nl1.show()\nl2.show()\n\ndef merge(l1,l2):\n \"\"\"\n #合并l2到l1中\n \"\"\"\n p=l1.head\n q=l2.head.next\n while p.next is not None:\n if p.next.val Optional[ListNode]:\n \n node = head\n while (node and node.next):\n node.val, node.next.val = node.next.val, node.val\n node = node.next.next\n \n return head\n \n \n","repo_name":"dryeab/competitive-programming","sub_path":"Leetcode/24. Swap Nodes in Pairs.py","file_name":"24. Swap Nodes in Pairs.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"17971668490","text":"from pipeline.pipeline import Payload, PipelineStep\nfrom intercom.api import get_conversation_details\nfrom database.database_operations import load_dataframe_to_table, merge_dataframe_into_table\nimport pandas as pd\n\n\nclass RetrieveApiData(PipelineStep):\n def execute(self, payload: Payload):\n payload.api_data = get_conversation_details(payload.conversation_id)\n\n\nclass ParseApiData(PipelineStep):\n def execute(self, payload: Payload):\n # We will be constructing dataframes that correspond to the data we want to load in each table\n # The majority of these dataframes will have a single record\n conversations = [{'type': payload.api_data['type'],\n 'id': payload.api_data['id'],\n 'title': payload.api_data['title'],\n 'created_at': payload.api_data['created_at'],\n # For updated_at, we have to limit it to no greater than end_timestamp to ensure that future pipeline runs are successful\n 'updated_at': min(payload.api_data['updated_at'], payload.end_timestamp),\n 'waiting_since': payload.api_data['waiting_since'],\n 'snoozed_until': payload.api_data['snoozed_until'],\n 'open': payload.api_data['open'],\n 'state': payload.api_data['state'],\n 'read': payload.api_data['read'],\n 'priority': payload.api_data['priority'],\n 'admin_assignee_id': payload.api_data['admin_assignee_id'],\n 'team_assignee_id': payload.api_data['team_assignee_id']\n }]\n payload.conversations = pd.DataFrame(conversations)\n # The api data contains several complex objects that may contain complex data\n # These will be loaded to their own tables\n # In this current version of the pipeline, we will flatten these to a single text field containing the object as a json\n # Future developments are anticipated where we will also process these other objects, unflattening these will be part of those future developments\n # Not all of these are guaranteed to exist, so we will have to check for existence first\n if payload.api_data['tags'] is not None:\n conversation_tags = [{'conversation_id': payload.conversation_id,\n 'type': payload.api_data['tags']['type'],\n 'tags': str(payload.api_data['tags']['tags'])\n }]\n else:\n conversation_tags = []\n payload.conversation_tags = pd.DataFrame(conversation_tags)\n if payload.api_data['conversation_rating'] is not None:\n conversation_ratings = [{'conversation_id': payload.conversation_id,\n 'rating': payload.api_data['conversation_rating']['rating'],\n 'remark': payload.api_data['conversation_rating']['remark'],\n 'created_at': payload.api_data['conversation_rating']['created_at'],\n 'contact': str(payload.api_data['conversation_rating']['contact']),\n 'teammate': str(payload.api_data['conversation_rating']['teammate'])\n }]\n else:\n conversation_ratings = []\n payload.conversation_ratings = pd.DataFrame(conversation_ratings)\n if payload.api_data['source'] is not None:\n conversation_sources = [{'conversation_id': payload.conversation_id,\n 'type': payload.api_data['source']['type'],\n 'id': payload.api_data['source']['id'],\n 'delivered_as': payload.api_data['source']['delivered_as'],\n 'subject': payload.api_data['source']['subject'],\n 'body': payload.api_data['source']['body'],\n 'author': str(payload.api_data['source']['author']),\n 'attachments': str(payload.api_data['source']['attachments']),\n 'url': payload.api_data['source']['url'],\n 'redacted': payload.api_data['source']['redacted'],\n }]\n else:\n conversation_sources = []\n payload.conversation_sources = pd.DataFrame(conversation_sources)\n if payload.api_data['contacts'] is not None:\n conversation_contacts = [{'conversation_id': payload.conversation_id,\n 'type': payload.api_data['contacts']['type'],\n 'contacts': str(payload.api_data['contacts']['contacts'])\n }]\n else:\n conversation_contacts = []\n payload.conversation_contacts = pd.DataFrame(conversation_contacts)\n if payload.api_data['teammates'] is not None:\n conversation_teammates = [{'conversation_id': payload.conversation_id,\n 'teammates': str(payload.api_data['teammates'])\n }]\n else:\n conversation_teammates = []\n payload.conversation_teammates = pd.DataFrame(conversation_teammates)\n if payload.api_data['first_contact_reply'] is not None:\n conversation_first_contact_replies = [{'conversation_id': payload.conversation_id,\n 'created_at': payload.api_data['first_contact_reply']['created_at'],\n 'type': payload.api_data['first_contact_reply']['type'],\n 'url': payload.api_data['first_contact_reply']['url']\n }]\n else:\n conversation_first_contact_replies = []\n payload.conversation_first_contact_replies = pd.DataFrame(conversation_first_contact_replies)\n if payload.api_data['sla_applied'] is not None:\n conversation_sla_applied = [{'conversation_id': payload.conversation_id,\n 'sla_name': payload.api_data['sla_applied']['sla_name'],\n 'sla_status': payload.api_data['sla_applied']['sla_status']\n }]\n else:\n conversation_sla_applied = []\n payload.conversation_sla_applied = pd.DataFrame(conversation_sla_applied)\n if payload.api_data['statistics'] is not None:\n conversation_statistics = [{'conversation_id': payload.conversation_id,\n 'time_to_assignment': payload.api_data['statistics']['time_to_assignment'],\n 'time_to_admin_reply': payload.api_data['statistics']['time_to_admin_reply'],\n 'time_to_first_close': payload.api_data['statistics']['time_to_first_close'],\n 'time_to_last_close': payload.api_data['statistics']['time_to_last_close'],\n 'median_time_to_reply': payload.api_data['statistics']['median_time_to_reply'],\n 'first_contact_reply_at': payload.api_data['statistics']['first_contact_reply_at'],\n 'first_assignment_at': payload.api_data['statistics']['first_assignment_at'],\n 'first_admin_reply_at': payload.api_data['statistics']['first_admin_reply_at'],\n 'first_close_at': payload.api_data['statistics']['first_close_at'],\n 'last_assignment_at': payload.api_data['statistics']['last_assignment_at'],\n 'last_assignment_admin_reply_at': payload.api_data['statistics']['last_assignment_admin_reply_at'],\n 'last_contact_reply_at': payload.api_data['statistics']['last_contact_reply_at'],\n 'last_admin_reply_at': payload.api_data['statistics']['last_admin_reply_at'],\n 'last_close_at': payload.api_data['statistics']['last_close_at'],\n 'last_closed_by_id': payload.api_data['statistics']['last_closed_by_id'],\n 'count_reopens': payload.api_data['statistics']['count_reopens'],\n 'count_assignments': payload.api_data['statistics']['count_assignments'],\n 'count_conversation_parts': payload.api_data['statistics']['count_conversation_parts']\n }]\n else:\n conversation_statistics = []\n payload.conversation_statistics = pd.DataFrame(conversation_statistics)\n # conversation_parts is unlike the others as the dataframe may contain more than one record\n if payload.api_data['conversation_parts'] is not None:\n conversation_parts = [{\n 'conversation_id': payload.conversation_id,\n 'type': part['type'],\n 'id': part['id'],\n 'part_type': part['part_type'],\n 'body': part['body'],\n 'created_at': part['created_at'],\n 'updated_at': part['updated_at'],\n 'notified_at': part['notified_at'],\n 'assigned_to': part['assigned_to'],\n 'author': str(part['author']),\n 'attachments': part['attachments'],\n 'external_id': part['external_id'],\n 'redacted': part['redacted']\n } for part in payload.api_data['conversation_parts']['conversation_parts']]\n else:\n conversation_parts = []\n payload.conversation_parts = pd.DataFrame(conversation_parts)\n\n\nclass LoadToDatabase(PipelineStep):\n def execute(self, payload: Payload):\n # For the majority of the data, we expect the API data to completely contain all the data\n # Deleting based on conversation_id and reinserting will guarantee that we have the most recent data and not any old data remaining\n payload.cur.execute(f\"delete from {payload.db_schema}.conversations where id = %s\", (payload.conversation_id,))\n load_dataframe_to_table(schema_name=payload.db_schema, table_name=\"conversations\", df=payload.conversations, cur=payload.cur)\n payload.cur.execute(f\"delete from {payload.db_schema}.conversation_contacts where conversation_id = %s\", (payload.conversation_id,))\n load_dataframe_to_table(schema_name=payload.db_schema, table_name=\"conversation_contacts\", df=payload.conversation_contacts, cur=payload.cur)\n payload.cur.execute(f\"delete from {payload.db_schema}.conversation_first_contact_replies where conversation_id = %s\", (payload.conversation_id,))\n load_dataframe_to_table(schema_name=payload.db_schema, table_name=\"conversation_first_contact_replies\", df=payload.conversation_first_contact_replies, cur=payload.cur)\n payload.cur.execute(f\"delete from {payload.db_schema}.conversation_ratings where conversation_id = %s\", (payload.conversation_id,))\n load_dataframe_to_table(schema_name=payload.db_schema, table_name=\"conversation_ratings\", df=payload.conversation_ratings, cur=payload.cur)\n payload.cur.execute(f\"delete from {payload.db_schema}.conversation_sla_applied where conversation_id = %s\", (payload.conversation_id,))\n load_dataframe_to_table(schema_name=payload.db_schema, table_name=\"conversation_sla_applied\", df=payload.conversation_sla_applied, cur=payload.cur)\n payload.cur.execute(f\"delete from {payload.db_schema}.conversation_sources where conversation_id = %s\", (payload.conversation_id,))\n load_dataframe_to_table(schema_name=payload.db_schema, table_name=\"conversation_sources\", df=payload.conversation_sources, cur=payload.cur)\n payload.cur.execute(f\"delete from {payload.db_schema}.conversation_statistics where conversation_id = %s\", (payload.conversation_id,))\n load_dataframe_to_table(schema_name=payload.db_schema, table_name=\"conversation_statistics\", df=payload.conversation_statistics, cur=payload.cur)\n payload.cur.execute(f\"delete from {payload.db_schema}.conversation_tags where conversation_id = %s\", (payload.conversation_id,))\n load_dataframe_to_table(schema_name=payload.db_schema, table_name=\"conversation_tags\", df=payload.conversation_tags, cur=payload.cur)\n payload.cur.execute(f\"delete from {payload.db_schema}.conversation_teammates where conversation_id = %s\", (payload.conversation_id,))\n load_dataframe_to_table(schema_name=payload.db_schema, table_name=\"conversation_teammates\", df=payload.conversation_teammates, cur=payload.cur)\n # conversation_parts is more complicated, as we do not expect the api to return the entire conversation history, only a segment of the most recent parts\n # For this reason, we cannot delete all the previous rows before reinserting, as this will lose data\n # Instead, we will insert, and use the primary key of the table to update if the inserted row matches one in the table on the primary ket columns\n merge_dataframe_into_table(schema_name=payload.db_schema, table_name='conversation_parts', df=payload.conversation_parts, cur=payload.cur)\n","repo_name":"Edg209/etl_pipeline","sub_path":"intercom/conversation/pipeline_steps.py","file_name":"pipeline_steps.py","file_ext":"py","file_size_in_byte":13731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39271411288","text":"# File: DebugUtility.py\n# Notes: This template includes basic debugging functions that help in the development of the FlexLink Phy\n\n__title__ = \"DebugUtility\"\n__author__ = \"Andreas Schwarzinger\"\n__status__ = \"preliminary\"\n__date__ = \"Sept, 10rd, 2022\"\n__copyright__ = 'Andreas Schwarzinger'\n\n\nimport numpy as np\nimport os\n\n\n# -------------------------------------------------------------------\n# > ShowMatrix() \n# -------------------------------------------------------------------\ndef ShowMatrix(InputMatrix: np.ndarray\n , strFileName: str = 'Matrix.txt'\n , bShow: bool = True) -> str:\n \"\"\"\n notes: The show matrix function will write a 2 dimensional numpy array to a file for easy visualization.\n param: InputMatrix I This must be a numpy array\n param: strFileName I The matrix will be formatted and writted to a file with name FileName\n param: bShow I This function can show the file content in notepad\n \"\"\"\n\n # -------------------------------------------\n # Check errors\n assert isinstance(InputMatrix, np.ndarray), 'The InputMatrix argument must be of type numpy.ndarray'\n assert InputMatrix.ndim == 2, 'The InputMatrix must feature two dimensions.'\n assert isinstance(strFileName, str), 'The strFileName argument must be of type str'\n assert isinstance(bShow, bool), 'The bShow argument must be of type bool'\n\n bIsInteger = np.issubdtype(InputMatrix.dtype, np.integer)\n bIsFloat = np.issubdtype(InputMatrix.dtype, np.floating)\n bIsComplex = np.issubdtype(InputMatrix.dtype, np.complex64) or np.issubdtype(InputMatrix.dtype, np.complex128)\n\n assert bIsInteger or bIsFloat or bIsComplex, 'The dtype of the input matrix is unsupported'\n\n # ---------------------------------------------\n # Write the matrix to a string so we may print it out\n rows, columns = InputMatrix.shape\n strMatrix = ''\n\n for row in range(0, rows + 1):\n for column in range(0, columns + 1):\n if row == 0 and column == 0:\n strMatrix += ' | '\n continue\n\n if column == 0:\n strMatrix += \"{:6d}\".format(row -1) + ' | '\n\n if row == 0:\n if bIsInteger:\n strMatrix += '{:^5}'.format(column - 1) + ' | '\n if bIsFloat:\n strMatrix += '{:^15}'.format(column - 1) + ' | '\n if bIsComplex:\n strMatrix += '{:^22}'.format(column - 1) + ' | '\n\n if row > 0 and column > 0 :\n if bIsInteger:\n strMatrix += '{:^5}'.format(InputMatrix[row-1, column-1]) + ' | '\n if bIsFloat:\n strMatrix += '{:^15.7e}'.format(InputMatrix[row-1, column-1]) + ' | '\n if bIsComplex:\n strMatrix += '{:^20.4e}'.format(InputMatrix[row-1, column-1]) + ' | ' \n\n if column == columns:\n strMatrix += ' \\n'\n \n\n # Show the matrix in notepad if desired\n if bShow == True: \n # -------------------\n f = open(file = strFileName, mode = 'w', encoding = 'utf-8')\n f.write(strMatrix)\n f.close()\n os.system(\"notepad++ \" + strFileName)\n else:\n return strMatrix\n\n\n\n\n# -------------------------------------------------------\n# Testbench\nif __name__ == '__main__':\n A = np.zeros([2, 4], dtype = np.int8)\n A[1,1] = 1 \n A[0,0] = 2\n ShowMatrix(A)\n\n Done = 1\n\n","repo_name":"OpenResearchInstitute/Neptune","sub_path":"FlexLink/python/flexlinkPhy/DebugUtility.py","file_name":"DebugUtility.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"2472243570","text":"#!/usr/bin/python\n\nimport gvgen\n\n# Creates the new graph instance\ngraph = gvgen.GvGen()\n\n# Creates two items labeled \"Foo\" and \"Bar\"\na = graph.newItem(\"foo\")\nb = graph.newItem(\"bar\")\n\n# Links from \"foo\" to \"bar\"\ngraph.newLink(a,b)\n\n# Outputs the graphviz code\ngraph.dot()\n\n","repo_name":"stricaud/gvgen","sub_path":"examples/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"67"} +{"seq_id":"25778672506","text":"def fib1(n):\n if n in (0,1):\n return n\n else:\n return fib1(n-1)+fib1(n-2)\n\ndef fib2(n):\n cache = {0:0,1:1}\n if n in cache:\n return cache[n]\n else:\n cache[n] = fib1(n-1)+fib1(n-2)\n return cache[n]\n\ndef get_fib_series(n):\n a,b,i = 0,1,0\n yield a\n while True:\n a, b , i = b, a+b , i+1\n yield a\n if(n==i):\n break\n\n\ndef get_nth_fib_no(n):\n if n<2:\n return n\n return get_nth_fib_no(n-1) + get_nth_fib_no(n-2)\n\n\nclass Fib():\n def __init__(self, howMany):\n self.counter = howMany\n self.curFib = 0\n self.nextFib = 1\n\n def __iter__(self):\n # Creates iterator object\n # Called when iteration is initialized\n # Called during initialization\n # Return an object that exposes an __next__ method.\n # self (whose type is Fibonacci) is such an object:\n #\n return self\n\n def __next__(self):\n\n if self.counter == 0:\n #\n # We have returned the count of fibonacci numbers\n # asked for… stop the iteration:\n #\n raise StopIteration\n\n self.counter -= 1\n result = self.curFib\n nextFib = self.curFib + self.nextFib\n self.curFib = self.nextFib\n self.nextFib = nextFib\n\n return result\n\n\nif __name__ == '__main__':\n import timeit\n\n for i in get_fib_series(9):\n print(i, end=\" \")\n\n print(\"*\"*50)\n\n fib_10 = Fib(10)\n for i in fib_10:\n print(i, end=\" \")\n\n assert fib1(0) == 0\n assert fib1(1) == 1\n assert fib1(2) == 1\n assert fib1(3) == 2\n\n assert fib2(0) == 0\n assert fib2(1) == 1\n assert fib2(2) == 1\n assert fib2(3) == 2\n assert fib2(4) == 3\n","repo_name":"sidaker/dq","sub_path":"python_interview/code_interviews/fibinocci_all.py","file_name":"fibinocci_all.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"29496298160","text":"import pandas as pd\nfrom scipy.io import arff\nfrom sklearn.impute import SimpleImputer\nimport numpy as np\nimport scipy.io\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.preprocessing import PowerTransformer\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.base import BaseEstimator, TransformerMixin\nimport os\n\nclass imputation(BaseEstimator, TransformerMixin):\n def fit(self, X, y=None):\n self.X = X\n imp_mean = SimpleImputer(missing_values=np.nan, strategy='mean')\n X = imp_mean.fit_transform(X)\n return X\n\n def transform(self, X):\n return self.X\n\n def fit_transform(self, X, y=None):\n X = self.fit(X)\n return X\n\n def get_feature_names_out(self, features=None):\n return self.X.columns\n\nclass variance(BaseEstimator, TransformerMixin):\n def fit(self, X, y=None):\n scaler = StandardScaler()\n X = scaler.fit_transform(X)\n\n pt = PowerTransformer()\n X = pt.fit_transform(X)\n return X\n\n def transform(self, X):\n return self.X\n\n def fit_transform(self, X, y=None):\n X = self.fit(X)\n return X\n\ndef fillna(X, y):\n y = y.astype(str).astype(float)\n y = y.fillna(y.max() + 1)\n y = y.astype(int).values\n return X, y\n\ndef read_bioconductor(db):\n df = pd.read_csv(db, header=0)\n df = df.T\n cols = df.iloc[0, :]\n cols = cols[1:]\n df = df[1:]\n X = df.iloc[:, 1:]\n y = df.iloc[:, 0]\n X, y = fillna(X, y)\n X.columns = cols\n return X, y\n\ndef read_scikit_mat(db):\n mat = scipy.io.loadmat(db)\n X = mat['X']\n X = pd.DataFrame(X)\n y = mat['Y'][:, 0]\n return X, y\n\ndef read_ARFF(db):\n df = arff.loadarff(db)\n df = pd.DataFrame(df[0])\n X = df.iloc[:, :-1]\n y = df.iloc[:, -1]\n return X, y\n\ndef read_datamicroarray(db):\n df = pd.read_csv(db, header=None)\n X = df.iloc[:, :-1]\n y = df.iloc[:, -1]\n X, y = fillna(X, y)\n return X, y\n\ndef read_and_fix(db):\n function_name = {'bioconductor': read_bioconductor, 'scikit': read_scikit_mat, 'ARFF': read_ARFF, 'datamicroarray': read_datamicroarray}\n file_type = db.split(\"/\")[1].split(\"_\")[0]\n X, y = function_name[file_type](db)\n return X, y\n\ndef to_csv(X, y, name, cols):\n suffix_name = name.split(\"/\")[1].split(\".\")[0]\n df_array = np.column_stack((X,y))\n df = pd.DataFrame(df_array)\n cols = np.append(cols, \"label\")\n df.to_csv('after_preprocess/' + suffix_name + \".csv\", index=False, header=cols)\n \npath = 'Data/'\nall_files = []\nfor file in os.listdir(path):\n if os.path.isfile(os.path.join(path,file)):\n all_files.append(os.path.join(path,file))\n\nfor name in all_files:\n X, y = read_and_fix(name)\n cols = X.columns\n label_encoder = LabelEncoder().fit(y)\n y = label_encoder.transform(y)\n pipe = Pipeline(steps=[('imputation', imputation()), ('variance_thresh', VarianceThreshold()), ('normalization', StandardScaler()),\n ('power_transformer', PowerTransformer())])\n X = pipe.fit_transform(X, y)\n cols = pipe.get_feature_names_out(cols)\n to_csv(X, y, name, cols)\n\n","repo_name":"daniel-izmaylov/feature-selection-comparison-study","sub_path":"data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3378501881","text":"import pygame\r\nfrom pygame.locals import *\r\nimport random\r\n\r\n# Define the Fruit class to represent the apple object\r\n\r\n\r\nclass Fruit:\r\n def __init__(self, screen):\r\n self.screen = screen\r\n self.fruit_x = 200\r\n self.fruit_y = 200\r\n\r\n def draw_fruit(self):\r\n # Create a rectangle representing the fruit\r\n fruit_box = pygame.Rect((self.fruit_x, self.fruit_y, 25, 25))\r\n # Draw the fruit on display with a green color\r\n pygame.draw.rect(self.screen, (0, 255, 0), fruit_box)\r\n\r\n# Define the Snake class to represent the snake object\r\n\r\n\r\nclass Snake:\r\n def __init__(self):\r\n pygame.init() # Initialize Pygame\r\n self.box_x = 100 # Initial x-coordinate of the snake's head\r\n self.box_y = 100 # Initial y-coordinate of the snake's head\r\n self.screen = pygame.display.set_mode(\r\n (700, 700)) # Create the game window\r\n pygame.display.set_caption(\"Snake Game\") # Set the window title\r\n\r\n self.direction_x = 0 # Initial x-direction of the snake's movement\r\n self.direction_y = 0 # Initial y-direction of the snake's movement\r\n self.move_timer = 0 # Initialize a timer for controlling movement\r\n # Set the interval for snake movement (milliseconds)\r\n self.move_interval = 150\r\n self.clock = pygame.time.Clock() # Create a Pygame clock object\r\n\r\n # Initialize with a starting segment\r\n self.body = [pygame.Rect(self.box_x, self.box_y, 25, 25)]\r\n self.body_length = 1 # Initial length of the snake\r\n\r\n self.apple = Fruit(self.screen)\r\n self.spawn_apple()\r\n\r\n def spawn_apple(self):\r\n # Generate random coordinates for the apple\r\n self.apple.fruit_x = random.randrange(0, 700, 25)\r\n self.apple.fruit_y = random.randrange(0, 700, 25)\r\n\r\n def draw_snake(self):\r\n # Draw each segment of the snake\r\n for segment in self.body:\r\n pygame.draw.rect(self.screen, (255, 0, 0), segment)\r\n\r\n def move_snake(self):\r\n # Move the snake by adding a new head segment and removing the tail segment to maintain length\r\n new_head = pygame.Rect(self.body[0].left + self.direction_x,\r\n self.body[0].top + self.direction_y, 25, 25)\r\n # insert new head as the first element of the list\r\n self.body.insert(0, new_head)\r\n # keeps the length correct by popping any overhanging elements off the list\r\n if len(self.body) > self.body_length:\r\n self.body.pop()\r\n\r\n def check_collision(self):\r\n # Check if the snake's head collides with the apple\r\n if self.body[0].colliderect(self.apple.fruit_x, self.apple.fruit_y, 25, 25):\r\n self.body_length += 1 # Increase the snake's length\r\n # increase speed by decreasing the interval between each movement\r\n self.move_interval -= 5\r\n self.spawn_apple() # Spawn a new apple\r\n\r\n def check_self_collision(self):\r\n for i in self.body[1:]: # create slice of the list that excludes the snake head\r\n if self.body[0].colliderect(i):\r\n pygame.quit()\r\n\r\n # Inside the Snake class, add a method to check for border collision\r\n def check_border_collision(self):\r\n if (self.body[0].left < 0 or self.body[0].right > 700 or\r\n self.body[0].top < 0 or self.body[0].bottom > 700):\r\n pygame.quit()\r\n\r\n def auto_move(self):\r\n self.move_timer += self.clock.tick(30) # Limit frame rate to 30 FPS\r\n if self.move_timer >= self.move_interval: # Check if move timer has exceeded the frame time limit\r\n self.move_snake() # Move the snake\r\n self.check_collision()\r\n self.check_self_collision() # Check for collision with the apple\r\n self.check_border_collision()\r\n self.move_timer = 0 # Reset the move timer\r\n\r\n # Move functions for arrow key controls\r\n def move_up(self):\r\n self.direction_x = 0\r\n self.direction_y = -25\r\n\r\n def move_down(self):\r\n self.direction_x = 0\r\n self.direction_y = 25\r\n\r\n def move_left(self):\r\n self.direction_x = -25\r\n self.direction_y = 0\r\n\r\n def move_right(self):\r\n self.direction_x = 25\r\n self.direction_y = 0\r\n\r\n def run_program(self):\r\n run = True\r\n while run:\r\n for event in pygame.event.get():\r\n if event.type == KEYDOWN:\r\n if event.key == K_ESCAPE:\r\n run = False # Exit the game when the ESC key is pressed\r\n if event.key == K_UP:\r\n self.move_up() # Call the move_up method\r\n if event.key == K_DOWN:\r\n self.move_down() # Call the move_down method\r\n if event.key == K_LEFT:\r\n self.move_left() # Call the move_left method\r\n if event.key == K_RIGHT:\r\n self.move_right() # Call the move_right method\r\n elif event.type == QUIT:\r\n run = False # Exit the game when the window is closed\r\n\r\n self.auto_move() # Automatically move the snake\r\n\r\n # Clear the screen with a background color\r\n self.screen.fill((110, 110, 5))\r\n\r\n self.draw_snake() # Draw the snake on the screen\r\n self.apple.draw_fruit() # Draw the apple on the screen\r\n\r\n pygame.display.update() # Update the display to show the snake and apple\r\n\r\n pygame.quit()\r\n\r\n\r\n# Run the game when this script is executed\r\nif __name__ == \"__main__\":\r\n game = Snake()\r\n game.run_program()\r\n","repo_name":"RakhinAmin/snakeGame","sub_path":"snakeGame/snakeGame.py","file_name":"snakeGame.py","file_ext":"py","file_size_in_byte":5726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23908162095","text":"\n# coding: utf-8\n\n# # Intro to satellite data IV -- using numba for speed\n# \n# In the satellite_III notebook we histogrammed into lat/lon bins and averaged the chan31 radiances in each bin to get a regular grid that could be mapped. Unfortunately, the plain python routine python routine for binning was too slow to do the whole scene in less than 5 minutes or so. In this notebook we:\n# \n# 1. move the satellite_III routines [slow_hist](https://clouds.eos.ubc.ca/~phil/courses/eosc582/_modules/e582lib/geolocate.html#slow_hist) and [slow_avg](https://clouds.eos.ubc.ca/~phil/courses/eosc582/_modules/e582lib/geolocate.html#slow_avg)\n# to the e582lib.geolocate library and replace them with [fast_hist](https://clouds.eos.ubc.ca/~phil/courses/eosc582/_modules/e582lib/geolocate.html#fast_hist) which uses numpy vector operations np.searchsorted and np.bincount, and [fast_avg](https://clouds.eos.ubc.ca/~phil/courses/eosc582/_modules/e582lib/geolocate.html#fast_hist) which uses [numba](http://numba.pydata.org/)\n# \n# 2. with those functions we can regrid the entire image and plot it using the python [basemap](http://matplotlib.org/basemap/#) module\n# \n# \n# Some topics we briefly introduce here and will return to in more detail in the future\n# \n# a. numba\n# b. keyword argument unpacking\n# c. palettes and normalized colormaps\n# d. masked arrays\n# e. map projections\n# f. operations along axes\n# g. IPython magic operations like %timeit\n# \n\n# # Repeat the raw image plot from satellite_III\n\n# In[1]:\n\nfrom e582utils.data_read import download\nimport numpy as np\nimport h5py\nimport sys\nfrom e582lib.geolocate import fast_hist, slow_hist, fast_avg, slow_avg,make_plot \n\nfilename = 'MYD021KM.A2016136.2015.006.2016138123353.h5'\ndownload(filename)\n\n\n# Here is the corresponding red,green,blue color composite for the granule.\n\n# In[2]:\n\nfrom IPython.display import Image\nImage(url='http://clouds.eos.ubc.ca/~phil/courses/atsc301/downloads/aqua_136_2015.jpg',width=600)\n\n\n# In[3]:\n\nh5_file=h5py.File(filename)\n\n\n# ### **Read the radiance data from MODIS_SWATH_Type_L1B/Data Fields/EV_1KM_Emissive**\n# \n# According to the [Modis channel listing](https://modis.gsfc.nasa.gov/about/specifications.php)\n# channel 31 is centered at 11 microns. The Band_1KM_Emissive band listing says that this is index 10 of the the Emissive data array. Note that Channel 26 is missing:\n\n# In[4]:\n\nindex31=10\n\nmy_name = 'EV_1KM_Emissive'\nchan31=h5_file['MODIS_SWATH_Type_L1B']['Data Fields'][my_name][index31,:,:]\nscale=h5_file['MODIS_SWATH_Type_L1B']['Data Fields']['EV_1KM_Emissive'].attrs['radiance_scales'][...]\noffset=h5_file['MODIS_SWATH_Type_L1B']['Data Fields']['EV_1KM_Emissive'].attrs['radiance_offsets'][...]\nchan31_calibrated =(chan31 - offset[index31])*scale[index31]\n\n\n# In[5]:\n\nget_ipython().magic('matplotlib inline')\nfrom matplotlib import pyplot as plt\n\n\n# In[6]:\n\nfig,ax = plt.subplots(1,1,figsize = (10,14))\nCS=ax.imshow(chan31_calibrated)\ncax=fig.colorbar(CS)\nax.set_title('calibrated radiance, Ft. McMurray')\nout=cax.ax.set_ylabel('Chan 31 radiance $(W\\,m^{-2}\\,\\mu m^{-1}\\,sr^{-1}$)')\nout.set_rotation(270)\nout.set_verticalalignment('bottom')\n\n\n# In[7]:\n\nfilename='MYD03.A2016136.2015.006.2016138121537.h5'\ndownload(filename)\ngeo_file = h5py.File(filename)\nlon_data=geo_file['MODIS_Swath_Type_GEO']['Geolocation Fields']['Longitude'][...]\nlat_data=geo_file['MODIS_Swath_Type_GEO']['Geolocation Fields']['Latitude'][...]\n\n\n# # Now time the slow and fast code to see how much of a speedup we can get on a small problem (gridding a corner of the scene)\n\n# In[8]:\n\nslow_calc=False\ntest_rows=100\ntest_cols=200\nrow_slice = slice(0,test_rows) # 0:test_rows\ncol_slice = slice(0,test_cols) # 0:test_cols\nlon_flat = lon_data[row_slice,col_slice].ravel()[:]\nlat_flat = lat_data[row_slice,col_slice].ravel()[:]\n\nlon_min= -115\nlon_max = -93\nnum_lon_bins=10\n\nlat_min = 50\nlat_max = 65\nnum_lat_bins=20\n#\n# now run the function\n#\nif slow_calc:\n lon_hist=slow_hist(lon_flat,lon_min,lon_max,numbins=num_lon_bins)\n lat_hist=slow_hist(lat_flat,lat_min,lat_max,numbins=num_lon_bins)\nelse:\n lon_hist = fast_hist(lon_flat,lon_min,lon_max,numbins=num_lon_bins)\n lat_hist = fast_hist(lat_flat,lat_min,lat_max,numbins=num_lat_bins)\nchan31_slice=chan31_calibrated[row_slice,col_slice].ravel()\nout1 = get_ipython().magic('timeit -o slow_hist(lon_flat,lon_min,lon_max,numbins=num_lon_bins)')\nout2 = get_ipython().magic('timeit -o fast_hist(lon_flat,lon_min,lon_max,numbins=num_lon_bins)')\nprint('faster by a factor of: ',(out1.best/out2.best))\n\n\n# In[9]:\n\nslow_calc=False\nif slow_calc:\n gridded_image = slow_avg(lat_hist,lon_hist,chan31_slice)\nelse:\n gridded_image = fast_avg(lat_hist,lon_hist,chan31_slice)\nout1 = get_ipython().magic('timeit -o slow_avg(lat_hist,lon_hist,chan31_slice)')\nout2 = get_ipython().magic('timeit -o fast_avg(lat_hist,lon_hist,chan31_slice)')\nprint('faster by a factor of: ',(out1.best/out2.best))\n\n\n# ### So numba loops are giving us a speedup of almost 20,000 x straight python\n# \n# Now we can geolocate the whole scene. First find the scene corners using [find_corners](http://clouds.eos.ubc.ca/~phil/courses/atsc301/_modules/a301lib/geolocate.html#find_corners). This also uses np.diff with the axis argument to try and determine how far apart the pixels are, so we can set the size of our histogram bins approporiately.\n\n# In[10]:\n\nfrom importlib import reload\nimport e582lib.geolocate\nfrom e582lib.geolocate import find_corners\ncorners=find_corners(lat_data,lon_data)\ncorners\n\n\n# ### The corners dictionary will be used by basemap below. For now we can use the corner positions and the pixel spacing to get histogram limits:\n# \n# Note that [fast_hist](http://clouds.eos.ubc.ca/~phil/courses/atsc301/_modules/a301lib/geolocate.html#fast_hist) not takes either a numbins or a binsize keyword argument to make the histogram bins.\n\n# In[11]:\n\nlon_min= -144\nlon_max = -92\n\nlat_min = 47\nlat_max = 70\nbinsize = 0.1\n\nlon_hist = fast_hist(lon_data.ravel(),lon_min,lon_max,binsize=binsize)\nlat_hist = fast_hist(lat_data.ravel(),lat_min,lat_max,binsize=binsize)\ngridded_image = fast_avg(lat_hist,lon_hist,chan31_calibrated.ravel())\n\n\n# In[12]:\n\nlat_centers=(lat_hist['edges_vec'][1:] + lat_hist['edges_vec'][:-1])/2.\nlon_centers=(lon_hist['edges_vec'][1:] + lon_hist['edges_vec'][:-1])/2.\nlon_array,lat_array=np.meshgrid(lon_centers,lat_centers)\n\n\n# In[13]:\n\nimport numpy as np\nlon,lat=np.meshgrid([1,2,3,4,5],[100,101,102,104])\nlon\nlat\n\n\n# In[14]:\n\nfig,ax = plt.subplots(1,1,figsize = (10,14))\nCS=ax.imshow(gridded_image)\ncax=fig.colorbar(CS)\nax.set_title('calibrated radiance, Ft. McMurray')\nout=cax.ax.set_ylabel('Chan 31 radiance $(W\\,m^{-2}\\,\\mu m^{-1}\\,sr^{-1}$)')\nout.set_rotation(270)\nout.set_verticalalignment('bottom')\n\n\n# In[15]:\n\nfig,ax = plt.subplots(1,1,figsize = (10,14))\nmasked_31 = np.ma.masked_invalid(gridded_image)\nmasked_31\nlon_centers\nlat_centers\nCS=ax.pcolormesh(lon_centers,lat_centers,masked_31)\ncax=fig.colorbar(CS)\nax.set_title('calibrated radiance, Ft. McMurray')\nout=cax.ax.set_ylabel('Chan 31 radiance $(W\\,m^{-2}\\,\\mu m^{-1}\\,sr^{-1}$)')\nout.set_rotation(270)\nout.set_verticalalignment('bottom')\n\n\n# ### Mapping the image\n# \n# The cell below does a couple of things:\n# \n# 1) uses the autumn colormap with over, under and bad colors set separately\n# \n# 2) Uses the Normalize object to compress the palette so that all of the color range\n# is used for data between 7 and 10 $W\\,m^{-2}\\,\\mu m^{-1}\\,sr^{-1}$\n# Data larger than that is colored white, smaller pale blue (low saturation $\\alpha$).\n# Histogram cells that had 0 pixels were set to np.nan -- color those grey with set_bad\n# \n# 3) adds three new items to the corners dictionary -- the axis to plot into (ax), the resolution for basemap\n# (choices are c (crude), l (low), i (intermediate), h (high), f (full)), and the map projection from\n# [this list](http://matplotlib.org/basemap/users/mapsetup.html). Note how I use [make_plot](http://clouds.eos.ubc.ca/~phil/courses/atsc301/codedoc.html#a301lib.geolocate.make_plot) to initialze the plot,\n# and [meshgrid](http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html) to set up 2-dimensional latitude and longitude arrays from the histogram bins. The basemap projection object proj maps lat,lon coords to\n# x,y plotting coords.\n\n# In[16]:\n\nfrom matplotlib import cm\nfrom matplotlib.colors import Normalize\n\ncmap=cm.autumn #see http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps\ncmap.set_over('w')\ncmap.set_under('b',alpha=0.1)\ncmap.set_bad('0.75') #75% grey\n#\n# use all my colors on data between 7 and 10 \n#\nvmin= 7\nvmax= 10\nthe_norm=Normalize(vmin=vmin,vmax=vmax,clip=False)\nfig,ax = plt.subplots(1,1,figsize=(14,18))\ncorners['ax'] = ax\ncorners['resolution']='l'\ncorners['projection']='lcc'\ncorners['urcrnrlon'] = -70.\ncorners['urcrnrlat'] = 65.\ncorners['llcrnrlat'] = 46.\ncorners['llcrnrlon'] = -140.\nproj = make_plot(corners)\nlat_centers=(lat_hist['edges_vec'][1:] + lat_hist['edges_vec'][:-1])/2.\nlon_centers=(lon_hist['edges_vec'][1:] + lon_hist['edges_vec'][:-1])/2.\nlon_array,lat_array=np.meshgrid(lon_centers,lat_centers)\n#\n# translate every lat,lon pair in the scene to x,y plotting coordinates \n# for th Lambert projection\n#\nx,y=proj(lon_array,lat_array)\nCS=proj.pcolormesh(x, y,masked_31, cmap=cmap, norm=the_norm)\nCBar=proj.colorbar(CS, 'right', size='5%', pad='5%',extend='both')\nCBar.set_label('11 $\\mu m$ radiance ($W\\,m^{-2}\\,\\mu m^{-1}\\,sr^{-1}$)',\n rotation=270,verticalalignment='bottom',size=18)\n_=ax.set_title('Modis Channel 11, May 15, 2016 -- Fort McMurray',size=22)\nmy_ax=proj.ax\nax.set(title='the new title')\nax.figure.canvas.draw()\n\n\n# In[ ]:\n\n\n\n","repo_name":"pgonzaleze/e582","sub_path":"notebooks/python/satellite_IV.py","file_name":"satellite_IV.py","file_ext":"py","file_size_in_byte":9732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"67"} +{"seq_id":"86595502945","text":"# -*- coding:utf-8 -*-\r\n'''\r\n在tensorflow中使用一个简单的线性模型的工作流程\r\n使用MINIST的手写数字图片数据集\r\n使用tensorflow定义并优化了一个数学模型\r\n并画出最终的结果\r\n'''\r\n\r\nimport matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\nimport numpy as np\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\nprint(tf.__version__)\r\n\r\n'''\r\n载入数据\r\n'''\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\ndata=input_data.read_data_sets('data/MNIST/',one_hot=True)\r\nprint('size of:')\r\nprint('-Training-set:\\t\\t{}'.format(len(data.train.labels)))\r\nprint('-Test-set:\\t\\t{}'.format(len(data.test.labels)))\r\nprint('-Validation-set:\\t\\t{}'.format(len(data.validation.labels)))\r\nprint(data.test.labels[0:5,:])\r\n#通过获取最大元素的索引将one-hot编码的向量转换成一个单独的数字\r\ndata.test.cls=np.array([label.argmax() for label in data.test.labels])\r\nprint(data.test.cls[0:5])\r\n\r\n'''\r\n数据维度\r\n'''\r\nimg_size=28\r\nimg_size_flat=img_size*img_size\r\nimg_shape=(img_size,img_size)\r\nnum_classes=10\r\n\r\n'''\r\n用来绘制图像的帮助函数\r\n'''\r\ndef plot_images(images,cls_true,cls_pred=None):\r\n #确保传入的是9张图片\r\n assert len(images)==len(cls_true)==9\r\n #创建图片 with 3*3个子图\r\n fig,axes=plt.subplots(3,3)\r\n fig.subplots_adjust(hspace=0.3,wspace=0.3)\r\n\r\n for i,ax in enumerate(axes.flat):\r\n #plot image\r\n ax.imshow(images[i].reshape(img_shape),cmap='binary')\r\n\r\n #show true and predicted classes\r\n if cls_pred is None:\r\n xlabel='True:{0}'.format(cls_true[i])\r\n else:\r\n xlabel='True:{0},Pred:{1}'.format(cls_true[i],cls_pred[i])\r\n\r\n ax.set_xlabel(xlabel)\r\n #移除图片中的刻度\r\n ax.set_xticks([])\r\n ax.set_yticks([])\r\n #显示图像\r\n plt.show()\r\n\r\n'''\r\n绘制几张图片验证以上函数\r\n'''\r\nimages=data.test.images[0:9]\r\ncls_true=data.test.cls[0:9]\r\nplot_images(images,cls_true=cls_true)\r\n\r\n'''\r\ntensorflow占位符\r\n'''\r\nx=tf.placeholder(tf.float32,[None,img_size_flat])\r\n#真实的类别 one-hot编码\r\ny_true=tf.placeholder(tf.float32,[None,num_classes])\r\n#真实的类别 class number 注意这个的data type为int64 否则会报错\r\ny_true_cls=tf.placeholder(tf.int64,[None])\r\nweights=tf.Variable(tf.zeros([img_size_flat,num_classes]))\r\n#行向量 1*num_classes\r\nbiases=tf.Variable(tf.zeros([num_classes]))\r\nlogist=tf.matmul(x,weights)+biases\r\n#使用softmax函数将数值限制在0-1之间\r\ny_pred=tf.nn.softmax(logist)\r\n#从y_pred矩阵中选取每行最大元素的索引值就是预测的类别\r\ny_pred_cls=tf.argmax(y_pred,dimension=1)\r\n\r\n'''\r\n优化损失函数\r\n'''\r\n#计算交叉熵,注意它使用的是logits的值,因为在它内部也计算了softmax\r\ncross_entropy=tf.nn.softmax_cross_entropy_with_logits(logits=logist,labels=y_true)\r\n#利用所有图像分类交叉熵的均值 作为损失值\r\ncost=tf.reduce_mean(cross_entropy)\r\noptimizer=tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(cost)\r\n\r\n'''\r\n性能度量\r\n'''\r\n\r\n#这是一个布尔值,代表预测类型是否等于每张图片的真实类型\r\ncorrect_prediction=tf.equal(y_pred_cls,y_true_cls)\r\n#先将布尔值转换成浮点型向量 flase->0,true->1,计算这些值的平均值以此计算准确度\r\naccuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\r\n\r\n''''\r\n运行tensorflow\r\n'''\r\nsession=tf.Session()\r\n#初始化变量\r\nsession.run(tf.global_variables_initializer())\r\n\r\nbatch_size=100\r\n#优化迭代来逐步提升模型的权重和偏见\r\ndef optimize(num_iterations):\r\n for i in range(num_iterations):\r\n x_batch,y_true_batch=data.train.next_batch(batch_size)\r\n feed_dict_train={x:x_batch,y_true:y_true_batch}\r\n session.run(optimizer,feed_dict=feed_dict_train)\r\n\r\n'''\r\n展示性能的帮助函数\r\n'''\r\nfeed_dict_test={x:data.test.images,y_true:data.test.labels,y_true_cls:data.test.cls}\r\n#用来打印测试集分类准确度的函数\r\ndef print_accuracy():\r\n acc=session.run(accuracy,feed_dict=feed_dict_test)\r\n print('The accuracy on test-data:{0:.1%}'.format(acc))\r\n\r\n#用sklearn打印混淆矩阵\r\ndef print_confusion_matrix():\r\n cls_true=data.test.cls\r\n cls_pred=session.run(y_pred_cls,feed_dict=feed_dict_test)\r\n #得到混淆矩阵\r\n cm=confusion_matrix(y_true=cls_true,y_pred=cls_pred)\r\n print(cm)\r\n #将混淆矩阵绘制成图像\r\n plt.imshow(cm,interpolation='nearest',cmap=plt.cm.Blues)\r\n\r\n #调整图像\r\n plt.tight_layout()\r\n plt.colorbar()\r\n tick_marks=np.array(num_classes)\r\n plt.xticks(tick_marks,range(num_classes))\r\n plt.yticks(tick_marks,range(num_classes))\r\n plt.xlabel('Predicted')\r\n plt.ylabel('True')\r\n\r\n'''\r\n绘制测试集中误分类图像的函数\r\n'''\r\ndef plot_example_error():\r\n correct,cls_pred=session.run([correct_prediction,y_pred_cls],feed_dict=feed_dict_test)\r\n incorrect=(correct==False)\r\n #从测试集中获取这些误分类的图像\r\n images=data.test.images[incorrect]\r\n #获取这些图片被误分成的类别\r\n cls_pred=cls_pred[incorrect]\r\n #真实的类别\r\n cls_true=data.test.cls[incorrect]\r\n #绘制前9张图片\r\n plot_images(images=images[:9],cls_true=cls_true[:9],cls_pred=cls_pred[:9])\r\n\r\n'''\r\n绘制模型权重的帮助函数\r\n'''\r\ndef plot_weights():\r\n w=session.run(weights)\r\n w_min=w.min()\r\n w_max=w.max()\r\n\r\n fig,axes=plt.subplots(3,4)\r\n fig.subplots_adjust(hspace=0.3,wspace=0.3)\r\n\r\n for i,ax in enumerate(axes.flat):\r\n #仅仅使用前10张图的权重\r\n if i <10:\r\n #w.shape==(img_size,10)\r\n image=w[:,i].reshape(img_shape)\r\n ax.set_label('weights:{0}'.format(i))\r\n ax.imshow(image,vmin=w_min,vmax=w_max,cmap='seismic')\r\n\r\n ax.set_xticks([])\r\n ax.set_yticks([])\r\n\r\n plt.show()\r\n\r\n'''\r\n优化之前的性能\r\n'''\r\nprint_accuracy()\r\nplot_example_error()\r\n\r\n'''\r\n1次迭代优化后的性能\r\n'''\r\noptimize(num_iterations=1)\r\nprint_accuracy()\r\nplot_weights()\r\n\r\n'''\r\n10次迭代优化后的性能\r\n'''\r\noptimize(num_iterations=10)\r\nprint_accuracy()\r\nplot_weights()\r\n\r\n''''\r\n1000次迭代优化后的性能\r\n'''\r\noptimize(num_iterations=1000)\r\nprint_accuracy()\r\nplot_weights()\r\n\r\n\r\n\r\n\r\n","repo_name":"WOW5678/tensorflow_study","sub_path":"linear_regression/09_SimpleLinearModelWithPlot.py","file_name":"09_SimpleLinearModelWithPlot.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31105784334","text":"from flask import Flask, request\nimport random\nimport requests\nfrom utils import send_message\n\napp = Flask('hi')\n\n@app.route('/', methods=['POST']) # route 란 길을 뚫어주는 역할을 하는것\ndef home():\n # 서버로서 우리가 받은 요청 --> server\n data = request.json # 요청을 받는것\n input_message = data['message']['text']\n sender_id = data['message']['from']['id']\n\n if input_message == '안녕':\n send_message('안녕하세요', sender_id)\n elif input_message == '로또':\n lotto = random.sample(range(1,46), 6)\n send_message(lotto, sender_id)\n\n return 'Hello Server'\nif __name__ == '__main__':\n app.run(port=80, debug=True)\n\n\n","repo_name":"yjh5019/BOOT-CAMP-PYTHON-DATA-","sub_path":"TELEGRAM/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14447650060","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.distributions import Categorical\nimport gym\nimport numpy as np\n\nlearning_rate = 0.0005\ngamma = 0.98\neps_clip = 0.1\nK_epoch = 3\nT_horizon = 128\n\n\nclass Agent(nn.Module):\n def __init__(self, state_dim,action_dim,learning_rate):\n self.state_dim = state_dim\n self.action_dim = action_dim\n \n super(Agent,self).__init__()\n self.memory = []\n\n self.fc1 = nn.Linear(self.state_dim,256)\n self.policy = nn.Linear(256, self.action_dim)\n self.value = nn.Linear(256, self.action_dim)\n self.optimizer = optim.Adam(self.parameters(),lr = learning_rate)\n \n def get_action(self,x, softmax_dim = 0):\n x = F.relu(self.fc1(x))\n x = self.policy(x)\n prob = F.softmax(x, dim = softmax_dim)\n return prob\n \n def get_q_value(self,x):\n x = F.relu(self.fc1(x))\n x = self.value(x)\n return x\n \n def put_data(self,data):\n self.memory.append(data)\n \n def make_batch(self):\n state_list, action_list, reward_list, next_state_list, prob_list, done_list = [],[],[],[],[],[]\n for data in self.memory:\n state,action,reward,next_state,prob,done = data\n state_list.append(state)\n action_list.append([action])\n reward_list.append([reward])\n prob_list.append([prob])\n next_state_list.append(next_state)\n done_mask = 0 if done else 1\n done_list.append([done_mask])\n self.memory = []\n \n s,a,r,next_s,done_mask,prob = torch.tensor(state_list,dtype=torch.float),\\\n torch.tensor(action_list),torch.tensor(reward_list),\\\n torch.tensor(next_state_list,dtype=torch.float),\\\n torch.tensor(done_list,dtype = torch.float),\\\n torch.tensor(prob_list)\n return s,a,r,next_s,done_mask,prob\n \n def train(self):\n state,action,reward, next_state,done_mask,action_prob = self.make_batch()\n \n for i in range(K_epoch):\n now_action = self.get_action(state,softmax_dim = 1)\n now_action = now_action.gather(1,action)\n \n now_q_value = self.get_q_value(state)\n now_q_value = now_q_value.gather(1,action)\n \n now_value = now_q_value.mean()\n \n next_q_value = self.get_q_value(next_state)\n next_q_value = next_q_value.gather(1,action)\n #next_value = next_q_value.mean()\n td_error = (reward + gamma * next_q_value * done_mask).detach() - now_q_value \n advantage = (now_q_value - now_value).detach()\n #td_error = reward + gamma * self.get_value(next_state) * done_mask\n #advantage = reward + gamma * self.get_value(next_state) * done_mask - self.get_value(state)\n #advantage = advantage.detach()\n \n\n \n ratio = torch.exp(torch.log(now_action) - torch.log(action_prob))\n \n surr1 = ratio * advantage\n surr2 = torch.clamp(ratio , 1-eps_clip, 1 + eps_clip) * advantage\n loss = - torch.min(surr1,surr2) + td_error.mean()\n \n self.optimizer.zero_grad()\n loss.mean().backward()\n self.optimizer.step()\n \nepochs = 10000\nmax_steps = 100\nprint_interval = 100\n\nenv = gym.make('CartPole-v1')\nmodel = Agent(4,2,learning_rate)\nave_reward = 0\n\nfor epoch in range(epochs):\n state = env.reset()\n done = False\n while not done:\n for t in range(T_horizon):\n global_step += 1\n action_prob = model.get_action(torch.from_numpy(np.array(state)).float())\n m = Categorical(action_prob)\n action = m.sample().item()\n next_state,reward,done,info = env.step(action)\n model.put_data((state, action, reward/100.0, next_state, action_prob[action].item(), done))\n state = next_state\n ave_reward += reward\n \n model.train()\n if epoch%print_interval==0 and epoch!=0:\n print(\"# of episode :{}, avg score : {:.1f}\".format(epoch, ave_reward/print_interval))\n ave_reward = 0\n","repo_name":"spebern/Vanilla-ppo-pytorch-in-cartpole","sub_path":"using-q-function-ppo.py","file_name":"using-q-function-ppo.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31376541053","text":"from PIL import Image, ImageDraw, ImageFont\nfrom datetime import datetime\nimport pandas as pd\n\narial_font_path = '/System/Library/Fonts/Supplemental/Arial.ttf'\n\ndef watermark_text(input_image_path, output_image_path, text, pos):\n # Load image\n base_image = Image.open(input_image_path).convert(\"RGBA\")\n\n # Make image editable\n txt = Image.new('RGBA', base_image.size, (255,255,255,0))\n\n # Load font (change the path if needed)\n font = ImageFont.truetype(arial_font_path, 15)\n \n # Prepare draw and text\n d = ImageDraw.Draw(txt)\n d.text(pos, text, font=font, fill=(0,0,0,76)) # 30% opacity (0,0,0,76)\n\n watermarked = Image.alpha_composite(base_image, txt)\n watermarked.save(output_image_path, 'PNG')\n\ndef append_to_csv(text, csv_path):\n df = pd.DataFrame([[text, datetime.now()]], columns=[\"Watermark\", \"Timestamp\"])\n df.to_csv(csv_path, mode='a', header=False, index=False)\n\nif __name__ == '__main__':\n # Input parameters\n input_image_path1 = 'original/CNI-recto-original.png'\n output_image_path1 = 'CNI-recto.png'\n\n input_image_path2 = 'original/CNI-verso-original.png'\n output_image_path2 = 'CNI-verso.png'\n\n csv_path = 'watermark_log.csv'\n pos = (1113, 71)\n\n text = input(\"Enter watermark text: \")\n \n watermark_text(input_image_path1, output_image_path1, text, pos)\n append_to_csv(text, csv_path)\n\n watermark_text(input_image_path2, output_image_path2, text, pos)\n append_to_csv(text, csv_path)\n\n print(f\"Watermark '{text}' added to images and logged in CSV.\")\n","repo_name":"pgchenu/CNI-watermark-generator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"14125646231","text":"# Lambda\n\n# def calc(op, a, b):\n# print(op(a,b))\n\n# calc(lambda x,y: x+y, 4, 5)\n \n# List Comprehension\n\n# list = [i for i in range(0,101)]\n# print(list)\n\n# list = [i for i in range(0,101) if i%2 ==0]\n# print(list)\n\n\n# def select(f,col):\n# return [f(x) for x in col] # формируем новый список и его возвращает\n\n# def where(f,col):\n# return [x for x in col if f(x)] # возвращает список если выполняется условие\n\n\n\ndata = '1 2 3 5 8 15 23 38'.split()\n\n# res = select(int, data) # из data формирует список int\nres = map(int, data)\nprint(res)\n# res = where(lambda x: not x%2, res) #формирует список только четных чисел\nres = list(filter(lambda x: not x%2, res))\nprint(res)\n# res = select(lambda x:(x, x**2), res) #формирует кортеж из числа и квадрата\n# res = list(map(lambda x: (x, x**2), res))\n# print(res)\n\n# Перевод строки в числа\n# data = list(map(int,input().split))\n# print(data)\n\n\n","repo_name":"staspereverzev/PythonHomework","sub_path":"Lekciya003/Lekciya003.py","file_name":"Lekciya003.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"12722862343","text":"from syne_tune.blackbox_repository.conversion_scripts.scripts.icml2020_import import (\n DeepARRecipe,\n XGBoostRecipe,\n)\nfrom syne_tune.blackbox_repository.conversion_scripts.scripts.lcbench.lcbench import (\n LCBenchRecipe,\n)\nfrom syne_tune.blackbox_repository.conversion_scripts.scripts.nasbench201_import import (\n NASBench201Recipe,\n)\nfrom syne_tune.blackbox_repository.conversion_scripts.scripts.fcnet_import import (\n FCNETRecipe,\n)\nfrom syne_tune.blackbox_repository.conversion_scripts.scripts.pd1_import import (\n PD1Recipe,\n)\n\n\n# add a blackbox recipe here to expose it in Syne Tune\nrecipes = [\n DeepARRecipe(),\n XGBoostRecipe(),\n NASBench201Recipe(),\n FCNETRecipe(),\n LCBenchRecipe(),\n PD1Recipe(),\n]\n\n\nfrom syne_tune.try_import import try_import_yahpo_message\n\ntry:\n from syne_tune.blackbox_repository.conversion_scripts.scripts.yahpo_import import (\n YAHPORecipe,\n yahpo_scenarios,\n )\n\n for scenario in yahpo_scenarios:\n recipes.append(YAHPORecipe(\"yahpo-\" + scenario))\nexcept ImportError:\n print(try_import_yahpo_message())\n\n\ngenerate_blackbox_recipes = {recipe.name: recipe for recipe in recipes}\n","repo_name":"awslabs/syne-tune","sub_path":"syne_tune/blackbox_repository/conversion_scripts/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":332,"dataset":"github-code","pt":"67"} +{"seq_id":"6157597226","text":"import asyncio\nimport random\n\nimport command_line_interface\nfrom unit_tests import ChatMessage\n\n\ndef main():\n # asyncio.run(straw_poll_test())\n asyncio.run(normal_chat_test(1000))\n\n\nasync def straw_poll_test():\n cmd = command_line_interface.CMDInterface()\n answers = {1: \"Putin\", 2: 'Trump'}\n cmd.CA.set_straw_poll_options(answers)\n cmd.CA.set_straw_poll_mode(True)\n for _ in range(20):\n await cmd.CA.add_comment(ChatMessage(f'!cd {random.randint(0, 1) + 1}'), translate=False)\n cmd.print_top_words(2, 0)\n\n\nasync def normal_chat_test(n: int):\n cmd = command_line_interface.CMDInterface()\n answers = ['Ich mag bier', 'bier', 'tee', 'Koffein', 'Schlafmangel', 'partys']\n for _ in range(n):\n await cmd.CA.add_comment(ChatMessage(f'!cd {answers[random.randint(0, len(answers) - 1)]}'))\n cmd.print_top_words(3, 2)\n cmd.print_result(\"tee\")\n cmd.print_result(\"ich mag bier\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ODeinsN/ChatDuelBot","sub_path":"tests/manual_tests.py","file_name":"manual_tests.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1156591331","text":"import math\nimport venv\nimport numpy\n# funtion drot\ndef drot(n,dx,incx,dy,incy,c,s):\n if(abs(c) > abs(s)):\n c1 = c\n s1 = s\n s2 = -s1/c1\n c2 = c1 - s2*s1\n else:\n c1 = s\n s1 = c\n dswap(n,dx,incx,dy,incy)\n s2 = s1/c1\n c2 = -s2*s1 - c1\n dscal(n,c1,dx,incx)\n daxpy(n,s1,dy,incy,dx,incx)\n dscal(n,c2,dy,incy)\n daxpy(n,s2,dx,incx,dy,incy)\n#end funtion drot\n\n#funtion dcopy\ndef dcopy(n, dx, incx, dy, incy):\n if incx == 1 and incy == 1:\n i = 1\n while i <= n:\n dy[i] = dx[i]\n i += 1\n else:\n ix = 1\n iy = 1\n i = 1\n while i <= n:\n dy[iy] = dx[ix]\n iy = iy + incy\n ix = ix + incx \n i += 1\n#end funtion dcopy \n\n#function idamax\ndef idamax(n,dx,incx):\n ii = 1\n xmax = abs(dx[1])\n if (incx == 1):\n i = 1\n while(i <= n):\n if (abs(dx[i]) > xmax):\n xmax = abs(dx[i])\n ii = i\n i += 1\n else:\n ix = 1\n i = 1\n while (i <= n):\n ix = ix + incx\n if(abs(dx[ix]) > xmax):\n xmax = abs(dx[ix])\n ii = i\n i += 1 \n idamax = ii\n return idamax\n# end function idamax\n\n# function dscal \ndef dscal(n,da,dx,incx):\n if (incx == 1):\n i = 1\n while (i <= n):\n dx[i] = da*dx[i]\n i += 1\n else:\n ix = 1\n while (i <= n):\n dx[ix] = da*dx[ix]\n ix = ix + incx\n i += 1\n#end function dscal\n\n#function daxpy\ndef daxpy(n,da,dx,incx,dy,incy):\n if (incx == 1 and incy == 1):\n i = 1\n while (i <= n):\n dy[i] = dy[i] + da*dx[i]\n i += 1\n else:\n ix = 1\n iy = 1\n i = 1\n while (i <= n):\n dy[iy] = dy[iy] + da*dx[ix]\n iy = iy + incy\n ix = ix + incx\n i += 1\n#end function daxpy\n\n#function ddot\ndef ddot(n,dx,incx,dy,incy):\n s = 0\n if (incx == 1 and incy == 1):\n i = 1\n while (i <= n):\n s = s + dx[i]*dy[i]\n i += 1\n else:\n ix = 1\n iy = 1\n i = 1\n while (i <= n):\n s = s + dx[ix]*dy[iy]\n ix = ix + incx\n iy = iy + incy\n i += 1\n ddot = s \n return ddot\n#end function ddot\n\n#funtion dswap\ndef dswap(n,dx,incx,dy,incy):\n if(incx == 1 and incy == 1):\n i = 1\n while(i <= n):\n s = dx[i]\n dx[i] = dy[i]\n dy[i] = s\n i += 1\n else:\n ix = 1\n iy = 1\n i = 1\n while (i <= n):\n s = dx[ix]\n dx[ix] = dy[iy]\n dy[iy] = s\n ix = ix + incx\n iy = iy + incy\n i += 1\n#end funtion dswap\n\n# function backsub\ndef BACKSUB(A,M,N,B,KB,LB,X):\n A[M,N],B[KB,LB],X[KB,LB]\n dcopy(KB*LB,B,1,X,1)\n L = 1\n while (L <= LB):\n J == N\n while (J >= 2):\n X[J,L] = X[J,L]/A[J,J]\n daxpy(J-1,-X[J,L],A[1,J],1,X[1,L],1)\n J -= 1\n X[1,L] = X[1,L]/A[1,1]\n# end function backsub \n\n# function housetrans\ndef HOUSETRANS(A,M,N,B,KB,LB,W,ISING):\n A[M,N],B[KB,LB],W(M)\n ISING = 0\n K = 1 \n while (K <= N):\n MX = idamax(M-K+1,A[K,K],1) + K - 1\n if (A[MX,K] == 0): ISING = K\n RMS = 0.0\n I = K\n while (I <= M):\n W[I] = A[I,K]/abs(A[MX,K])\n RMS = RMS + W[I]*W[I]\n I += 1\n RMS = math.sqrt(RMS)\n BK = 1/(RMS*(RMS + abs(W[K])))\n ZZ = W[K]\n W[K] = W[K] + numpy.sign(RMS,ZZ)\n J = 1\n while (J <= N):\n S = ddot(M-K+1,W[K],1,A[K,J],1)\n S = BK*S\n daxpy(M-K+1,-S,W[K],1,A[K,J],1)\n J += 1\n J = 1\n while (J <= LB):\n S = ddot(M-K+1,W[K],1,B[K,J],1)\n S = BK*S\n daxpy(M-K+1,-S,W[K],1,B[K,J],1)\n J += 1\n K += 1\n#end funtion housetrans\n\n#housefit\ndef HOUSEFIT(A,M,N,B,K,L,X,W,ISING):\n A[M,N],B[K,L],X[K,L],W[M]\n HOUSETRANS(A,M,N,B,K,L,W,ISING)\n BACKSUB(A,M,N,B,K,L,X)\n#end housefit\n\n#gibbbs\ndef GIBBS (NT,TEMP,NN,SPECIES,WT,G0,G1,EE,BE,AE,WE,WEX,SN,SF,A,B,C,F,NF,W,NV,DGT,E,RES,ZPE,EZ,V):\n W[100],V[100],TEMP[100], DGT[100,100], EZ[100]\n C1=1.438767553\n C2=40.27512295\n R=1.9872\n PI=numpy.arccos(-1.0)\n if (RES == \"atm\"): TC = -3.664854875\n if (RES == \"bar\") : TC = -3.651691889\n #Loop over Temperatures\n II = 1\n while (II <= NT):\n T = TEMP(II)\n if (EE == 0): CELECT = numpy.log(G0)\n if (EE != 0): CELECT = numpy.log(G0 + G1*numpy.exp(C1*EE/T))\n \n CTRANS = 1.5*numpy.log(WT) + 2.5*numpy.log(T) + TC\n \n if(SPECIES == \"monatomic\"): G = (CELECT + CTRANS)*R*T\n if(SPECIES == \"monatomic\"): E0 = 0\n #Diatomic Species \n if(SPECIES == \"diatomic\"):\n Y=C1*(BE-AE/2)/T\n U=C1*(WE-2*WEX)/T\n XE=WEX/WE\n D=AE/BE\n GG=BE/WE\n if(U > 80):\n EU = numpy.exp(80)\n U1 = 0\n else: \n EU = numpy.exp(U) - 1\n U1 = U/EU/EU\n if(ZPE != \"yes\"): E0 = 0\n if(ZPE == \"yes\"): E0 = -U/2\n G= CTRANS - numpy.log(SN*Y) + Y/3 + Y**2/90 - numpy.log(1-numpy.exp(-U)) + CELECT + E0 + (2*XE*U1) + D/EU + 8*GG/U\n G = G*R*T\n E0= E0*R*T\n \n #Polyatomic Species \n E0 = 0\n CVIB = 0\n for I in range (1,NV+1):\n V[I] = C1*W[I]/T\n if (ZPE == \"yes\"):\n E0 = E0 -V[I]/2\n CVIB = CVIB - numpy.log(1-numpy.exp(-V[I]))\n CVIB = CVIB + E0\n if(SPECIES == \"linear \"):\n Y= C2/A/T\n if(F<=0):\n FR = 0\n else: \n YY=C2/F/T\n if(NF-2<0):\n FR=0.5*math.log(math.pow(SF,2)*YY/PI)\n elif(NF-2 ==0):\n FR=math.log(SF*YY)\n else:\n FR= 0.5*math.log(math.pow(SF,2)*math.pow(YY,3)/PI)\n G = CTRANS - FR - math.log(SN*Y) + Y/3 + math.pow(Y,2)/90 + CVIB + CELECT\n G = G*R*T\n E0 = E0*R*T\n if(SPECIES == \"nonlinear \"):\n Y=(C2/A/T)*(C2/B/T)*(C2/C/T)\n if(F<=0):\n FR=0\n else:\n YY=C2/F/T\n if(NF-2<0):\n FR=0.5*math.log(math.pow(SF,2)*YY/PI)\n elif(NF-2==0):\n FR= math.log(SF*YY)\n else: \n FR=0.5*math.log(math.pow(SF,2)*math.pow(YY,3)/PI)\n G = CTRANS -FR - 0.5*math.log(math.pow(SN,2)*Y/PI) + CVIB + CELECT\n G = G*R*T\n E0 = E0*R*T\n \n DGT[NN,II]= E - G/1000\n EZ[NN] = E - E0/1000\n II += 1\n#end gibbs\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n # inputArr = []\n # file1 = open('bimo.inp', 'r')\n # Lines = file1.readlines()\n # for line in Lines:\n # inputArr.append(line.strip())\n \n # #Gán giá trị các biến \n # Title = inputArr[0]\n # NP = int(inputArr[1][29:32])\n # NR = int(inputArr[2][22:25])\n # Title = inputArr[3]\n # NN = 0\n # for i in range (1,9):\n # M[i]= list(map(int, inputArr[4].split(' ')))\n # NN += M[i]\n # NT = int(inputArr[5][25:28])\n # ZPE = bool(inputArr[6][27:30])\n # TUN = bool(inputArr[7][31:33])\n # Title = inputArr[8]\n # RES = \"bar\"\n # ASK = bool(inputArr[9][24:27])\n # if(ASK == \"yes\"):\n # RES = \"atm\"\n # ASK = bool(inputArr[10][17:19])\n # if(ASK == \"yes\"):\n # RES = \"bar\"\n \n # #CONSTANTS\n # FAC = 0.46499834\n # R = 1.9872\n # RCC1 = 2.08367541593\n # if(RES == \"atm\"):\n # RCC2= 1.3626055\n # if(RES==\"bar\"):\n # RCC2=1.38066\n # RCC = RCC1 * numpy.pow(RCC2,(NN-1))\n # C1 = 1.438767553\n \n # #Read Temperatures\n \n # for i in range(1,NT+1):\n # TEMP[i]= list(map(int, inputArr[i+11].split('.')))\n \n # #Loop over structures\n # for L in range(1,NP+1):\n # GEO[L],E[L],SPECIES = list(map(float, inputArr[36].split(' ')))\n # E[L] = E[L]*627.50595E0\n # file1.writelines(GEO(L), E(L)/627.50595, SPECIES, '\\n')\n # BE = 0.0\n # AE = 0.0\n # WE = 0.0\n # WEX = 0.0\n # if (SPECIES == \"diatomic\"):\n # # READ(10,*) WT,G0,G1,EE\n # # READ(10,*) BE,AE,WE,WEX\n # WT,G0,G1,EE,BE,AE,WE,WEX = list(map(float, inputArr[38].split(' ')))\n # else:\n # # READ(10,*) WT,G0,G1,EE\n # # READ(10,*) A,B,C,SN,SF,F,NF,NV\n # WT,G0,G1,EE = list(map(float, inputArr[37].split(' '))) \n # A,B,C,SN,SF,F,NF,NV = list(map(float, inputArr[38].split('')))\n # A = A * FAC\n # B = B * FAC\n # C = C * FAC\n # F = F * FAC\n # #IF(NV.NE.0) READ(10,*)(W(j),j=1,NV)\n # #IF(TUN.EQ.\"yes\") READ(10,*) RCV(L)\n # if(NV!=0):\n # for j in range (1,NV+1):\n # W[j]=list(map(float, inputArr[39].split(' ')))\n # GIBBS (NT,TEMP,L,SPECIES,WT,G0,G1,EE,BE,AE,WE,WEX,SN,SF,A,B,C,F,NF,W,NV,DGT,E[L],RES,ZPE,EZ)\n # # Ghi ra file \n # file1 = open('bimo.out', 'w')\n # file1.writelines(L) \n \n # #List \"Delta G\"\n # if(NR > 1):\n # for J in range(1,NT+1):\n # DGT[NR,J]= M[NR]*DGT[NR,J]\n # EZ[NR]=M[NR]*EZ[NR]\n # for I in range(1,NR):\n # EZ[NR]=EZ[NR]+M[I]*EZ[I]\n # for J in range(1,NT+1):\n # DGT[NR,J]=DGT[NR,J]+M[I]*DGT[I,J]\n # file1.writelines()\n # for I in range(NR,NP+1):\n # file1.writelines(GEO[I])\n # #Save Geometric \n # for I in range(1,NT+1):\n # #WRITE(11,102) TEMP(I) \n # GDAT[I] = -10.0\n # for J in range(NR,NP+1):\n # DD=DGT[J,I]-DGT[NR,I]\n # GG[J]=DD\n # if(DD>GDAT[I]):\n # GDAT[I]=DD\n # if(TUN==\"yes\"):\n # TV[I]=RCV(J)\n # else: TV[I]=0\n # EZT[I]=EZ[J]-EZ[NR]\n # GEOM[I]=GEO[J]\n # #Do dG/dR (Central Difference)\n # for J in range(NR,NP+1):\n # if(J==NR or J==NP):\n # file1.writelines(GEO[J],GG[J])\n # else:\n # dGdRA = (GG[J+1]-GG[J])/(GEO[J+1]-GEO[J])\n # dGdRB = (GG[J]-GG[J-1])/(GEO[J]-GEO[J-1])\n # dGdR[J]=(dGdRA+dGdRB)/2\n # file1.writelines(GEO[J],GG[J],dGdR[J])\n # # WRITE(11,\"(F15.4, F15.6, F15.6)\") GEO(J), GG(J), dGdR(J)\n # #WRITE(11,\"(1X)\") \n # #WRITE(11,105) \n # #WRITE(11,106) \n # #WRITE(11,107)'\n # for I in range(1,NT+1):\n # file1.writelines(TEMP[I], GEOM[I],GDAT[I])\n # # DO quadratic least\n # for I in range(1,NT+1):\n # AA[I]= TEMP[I]*TEMP[I]\n # AA[I+NT]=TEMP[I]\n # AA[I+(2*NT)]=1.0\n # BB[I] = GDAT[I]\n # HOUSEFIT(AA,NT,3,BB,NT,1,X,WW,ISING)\n # #WRITE(11,\"(1X)\") \n\t# #WRITE(11,108) \n # #WRITE(11,109)\n # for I in range(1,NT+1):\n # PRED = X[1]*TEMP[I]*TEMP[I]+X[2]*TEMP[I]+X[3]\n # file1.writelines(TEMP[I],PRED)\n # X[1]=X[1]*1000.0\n # X[2]=X[2]*1000.0\n # X[3]=X[3]*1000.0 \n # #WRITE(11,\"(1X)\") \n # #WRITE(11,110) X(1), X(2), X(3)\n # #WRITE(11,\"(1X)\") \n # for I in range(1,NT):\n # #WRITE(12,\"(F10.3)\") TEMP(I)\n # #WRITE(12,\"(1X)\") \n # #WRITE(11,\"(1X)\") \n # #WRITE(11,111) \n # #WRITE(11,\"(1X)\") \n # #WRITE(11,112) RCC, NN, NN-1\n # #WRITE(11,\"(1X)\") \n # #WRITE(11,113)\n # #WRITE(11,\"(1X)\") \n \n # for I in range(1,NT+1):\n # PRED = X[1]*TEMP[I]*TEMP[I]+X[2]*TEMP[I]+X[3]\n # FRC = RCC * numpy.pow(TEMP[I],NN) * numpy.exp(-PRED/(R*TEMP[I]))\n # RRC = RCC * numpy.pow(TEMP[I],NN) * numpy.exp(-GDAT[I]*1000.0/(R*TEMP[I]))\n # #WRITE(11,114) TEMP(I), RRC, FRC\n # #WRITE(12,\"(E12.6)\") RRC\n # if(TUN != \"yes\"):\n # #CLOSE (UNIT=10)\n # #CLOSE (UNIT=11)\n # else:\n # #WRITE(11,\"(1X)\") \n # #WRITE(12,\"(1X)\") \n # #WRITE(11,\"(49x)\") 'where w(cm^-1) = negative frequency (along path))'\n # #WRITE(11,\"(48x)\") 'Note: This factor only valid for small barriers)'\n # #WRITE(11,\"(47x)\") 'with a width of less than about 1.8 Angstroms.)'\n # #WRITE(11,\"(1X)\") \n # #WRITE(11,\"(33x)\") 'Rates with Tunneling Correction:)'\n # #WRITE(11,\"(1X)\") \n # for I in range(1,NT+1):\n # PRED = X[1]*TEMP[I]*TEMP[I]+X[2]*TEMP[I]+X[3]\n # FRC = RCC * numpy.pow(TEMP[I],NN) * numpy.exp(-PRED/(R*TEMP[I]))\n # RRC = RCC * numpy.pow(TEMP[I],NN) * numpy.exp(-GDAT[I]*1000.0/(R*TEMP[I]))\n # TF = math.pow((C1*TV[I]/TEMP[I]),2)\n # TF = TF * (1.0 + R*TEMP[I]/(EZT[I]*1000.0))/24.0\n # TF = TF + 1.0\n # RRC = TF * RRC\n # FRC = TF * FRC\n # #WRITE(11,114) TEMP(I), RRC, FRC\n # #WRITE(12,\"(E12.6)\") RRC\n \n \n \n ","repo_name":"ngocnamk3er/chem_it","sub_path":"CVTST-m_py/CVTST-m.py","file_name":"CVTST-m.py","file_ext":"py","file_size_in_byte":13122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"22996341010","text":"class Solution:\n def wordBreak(self, s, wordDict):\n wordSet = set(wordDict)\n memo = {}\n\n def helper(sub):\n if sub in memo:\n return memo[sub]\n result = []\n for i in range(len(sub)):\n prefix = sub[:i + 1]\n if prefix in wordSet:\n if prefix == sub:\n result.append(prefix)\n else:\n restOfWords = helper(sub[i + 1:])\n for item in restOfWords:\n result.append(prefix + ' ' + item)\n\n memo[sub] = result\n return result\n\n return helper(s)\n\nX = Solution()\nprint(X.wordBreak(\"catsanddog\",[\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]))","repo_name":"anugrah18/Leetcode_solutions","sub_path":"Backtracking/140-wordBreakII.py","file_name":"140-wordBreakII.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71619086292","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport math\nimport random\nfrom collections import namedtuple\n\nPoint = namedtuple(\"Point\", ['x', 'y'])\n\ndef length(point1, point2):\n return math.sqrt((point1.x - point2.x)**2 + (point1.y - point2.y)**2)\n\ndef solve_it(input_data):\n # Modify this code to run your optimization algorithm\n # parse the input\n lines = input_data.split('\\n')\n nodeCount = int(lines[0])\n \n points = []\n solution=[]\n for i in range(1, nodeCount+1):\n line = lines[i]\n parts = line.split()\n points.append(Point(float(parts[0]), float(parts[1])))\n ptsX={}\n for ind,pt in enumerate(points):\n if pt[0] in ptsX:\n ptsX[pt[0]].append(ind)\n else:\n ptsX[pt[0]]=[ind]\n # print(\"group in X cord: \",ptsX)\n revVar=False\n while ptsX:\n minX=min(ptsX)\n ptsIds=ptsX.pop(minX)\n pY={}\n for ind in ptsIds:\n pY[ind]=points[ind][1]\n # print(\"group in Y cord: \",pY)\n pYs=dict(sorted(pY.items(), key=lambda x: x[1],reverse=revVar))\n # print(pYs)\n solution+=list(pYs.keys())\n revVar= not revVar\n # print(\"solution: \",solution)\n\n #calc\n sum_dist=length(points[solution[-1]], points[solution[0]])\n for i in range(0,nodeCount-1):\n sum_dist+=length(points[solution[i]], points[solution[i+1]])\n\n # prepare the solution in the specified output format\n output_data = '%.2f' % sum_dist + ' ' + str(0) + '\\n'\n output_data += ' '.join(map(str, solution))\n\n return output_data\n\n\nimport sys\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) > 1:\n file_location = sys.argv[1].strip()\n with open(file_location, 'r') as input_data_file:\n input_data = input_data_file.read()\n print(solve_it(input_data))\n else:\n print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/tsp_51_1)')\n\n","repo_name":"BiancaZYCao/discreteOptimization2021Fall","sub_path":"assignment03-tsp/solver-33810.py","file_name":"solver-33810.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"39349824722","text":"import mysql.connector\r\n\r\n#pip install mysql.connector\r\nmydb = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"\", database = \"svkm_43\")\r\n\r\nmycursor = mydb.cursor()\r\n# sql = \"show databases\"\r\n# sql = \"create database svkm_43\"\r\n# sql = \"drop database svkm_43\"\r\n\r\nsql = \"create table TYCOMP(ID int auto_increment primary key, Name varchar(50) not null, Email varchar(50), C_no int) values(%d, %s, %s, %d)\"\r\nmycursor.execute(sql)\r\n\r\nsql = \"show tables\"\r\nmycursor.execute(sql)\r\n\r\nsql = \"Insert into TYCOMP( ID, Name, Email, C_no)\"\r\nvalues = [\r\n (101, 'Rahul Patil', 'rahul123@gmail.com',9997457289)\r\n (102, 'Anu Kumari', 'anu1@gmail.com',9991247289)\r\n (103, 'Samar Patil', 'sam13@gmail.com',8887457289)\r\n (104, 'Reena Sehgal', 'reena90@gmail.com',8877457289)\r\n (105, 'Peter Parker', 'peterp3@gmail.com',3337457289)\r\n]\r\nmycursor.executemany(sql, values)\r\nmydb.commit()\r\nsql = \"select * from TYCOMP\"\r\n\r\nfor database in mycursor:\r\n print(database)\r\n\r\n","repo_name":"NICK1309/NICK1309","sub_path":"new3.py","file_name":"new3.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31667556010","text":"#!/usr/bin/env python3\nimport sys\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport librosa\nimport librosa.display\nimport time\n\nfrom absl import flags\nfrom joblib import Memory\n\nfrom tensorflow.keras.layers import Conv2D, Dropout, MaxPool2D, Flatten, Add, Dense, Activation, BatchNormalization, Lambda, ReLU, PReLU\nfrom tensorflow.keras.layers import Conv2D, AveragePooling2D, MaxPooling2D, Flatten, Input, concatenate, ZeroPadding2D, LeakyReLU, GlobalAveragePooling2D\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.optimizers import Adam, SGD, RMSprop\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, LearningRateScheduler\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.metrics import TopKCategoricalAccuracy\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder\n\nmemory = Memory(\".cache\")\n\nFLAGS = flags.FLAGS\nflags.DEFINE_integer(\"batch_size\", 32, \"Number of samples in a batch\")\nflags.DEFINE_integer(\"epochs\", 20, \"Number of epochs\")\nflags.DEFINE_float(\"lr\", .1, \"Learning rate for ADAM\")\nflags.DEFINE_integer(\"num_iters\", 50000, \"number of iterations for ADAM\")\nflags.DEFINE_string(\"ds_path\", \"./recordings\", \"path to dataset\")\nflags.DEFINE_integer(\"seed\", 31415, \"random seed for reproducible results\")\n\ndef to_decibles(signal, method = 'librosa'):\n # Perform short time Fourier Transformation of signal and take absolute value of results\n if method == 'librosa':\n stft = np.abs(librosa.stft(signal))\n else:\n frame_length = 4096\n frame_step = 1024\n\n stft = tf.signal.stft(\n signal,\n frame_length,\n frame_step,\n pad_end=False\n )\n # Convert to dB\n D = librosa.amplitude_to_db(stft, ref = np.max) # Set reference value to the maximum value of stft.\n\n return D # Return converted audio signal\n\n# Function to plot the converted audio signal for checking\ndef plot_spec(D, sr, raag = \"raag\"):\n fig, ax = plt.subplots(figsize = (30,10))\n spec = librosa.display.specshow(D, sr=sr, x_axis='time', y_axis='linear', ax=ax)\n ax.set(title = 'Spectrogram of ' + raag)\n fig.colorbar(spec)\n plt.show()\n plt.savefig(\"D\")\n\n return spec\n\n '''\n Iterate through directory and collect the relative path of each recording.\n Parameters: x\n - dataset_path: the absolute path to the directory containing all of the data. Each subdirectory inside of this should\n contain all of the recordings for a specific raga, and the name of the subdirectory should be the common name of the raga\n in question.\n Returns:\n - df: dataframe containing the paths to each audio file, the name of the raga they correspond to, and the one-hot encoded version\n of the raga names\n - enc: the OneHotEncoder using to encode the ragas (so we can invert the process later)\n '''\ndef generate_dataset(dataset_path):\n raga_dict = dict()\n raga_directories = next(os.walk(dataset_path))[1]\n\n for raga_directory in raga_directories:\n recordings_path = os.path.join(dataset_path, raga_directory)\n filenames = [os.path.join(recordings_path, x) for x in next(os.walk(recordings_path), (None, None, []))[2]]\n raga_dict[raga_directory] = filenames\n\n # Generate master list where each entry is [path to audio file, name of Raag]\n master_list = []\n\n for raga in raga_dict.keys():\n expanded_list = [[x, raga] for x in raga_dict[raga]]\n master_list += expanded_list\n\n df = pd.DataFrame (master_list, columns = ['File path', 'Raga'])\n ragas = df.Raga.values\n\n enc = OneHotEncoder(handle_unknown='ignore')\n ragas_onehot = enc.fit_transform(ragas.reshape(-1,1)).toarray()\n\n # https://stackoverflow.com/questions/35565376/insert-list-of-lists-into-single-column-of-pandas-df\n df['Raga One-Hot'] = pd.Series(list(ragas_onehot))\n\n # print(ragas)\n # print(enc.inverse_transform(ragas))\n\n #display(df.to_string())\n\n return df, enc\n\n@memory.cache()\ndef create_batch(dataset):\n '''\n To conserve memory, the dataset will only consist of a list of filenames and the raga they correspond too.\n At runtime, this function will be called periodically to retrieve the next batch of audio data.\n Process:\n - Slice the audio file into 30s chunks\n - Take the STFT of each chunk and pair it with the corresponding class\n - Return list spectrogram, one hot encoded pairs\n '''\n batch_x = []\n batch_y = []\n\n dataset = dataset.reset_index()\n\n for index, audiofile in dataset.iterrows():\n t = time.time()\n offset = 0.0\n duration = 30.0\n target_sr = 8000\n file_length = librosa.get_duration(filename = audiofile['File path'])\n\n while offset + duration < file_length:\n # Load the audio in to a np array\n y, sr = librosa.load(audiofile['File path'], sr=None, offset = offset, duration = 30.0)\n\n # Resample the audio to a consistent sampling rate, pad/truncate as needed\n y = librosa.resample(y, orig_sr=sr, target_sr=target_sr)\n\n # Padding when\n if len(y) != duration * target_sr:\n y = librosa.util.fix_length(y, size = duration * target_sr)\n print(\"padded\")\n\n # Any sort of data augmentation (optional - can add in later)\n\n # Take STFT\n spec = to_decibles(y)\n\n # Add data to batch\n batch_x.append(spec)\n batch_y.append(audiofile['Raga One-Hot'])\n\n # Increment Offset\n offset += duration\n\n print(f'Elapsed: {time.time() - t}')\n\n #img = plot_spec(batch_x[10], target_sr)\n\n return batch_x, batch_y, #img\n\ndef conv_module(input, num_filters, activation, kern_reg, dropout, padding=\"same\"):\n input = Conv2D(filters = num_filters, kernel_size = (3, 3), activation = activation, padding = padding, kernel_regularizer = kern_reg)(input)\n input = BatchNormalization(axis=-1)(input)\n\n return input\n\n\n@memory.cache()\ndef simple_model(image_len, image_width, num_classes, lambda_val):\n inputShape = (image_len, image_width, 1)\n inputs = Input(shape=inputShape)\n\n output = Conv2D(filters = 32, kernel_size = (3, 3), activation = 'relu', kernel_regularizer = l2(lambda_val))(inputs)\n output = BatchNormalization(name='batchnorm_1')(output)\n output = Activation('relu')(output)\n\n output = MaxPool2D(pool_size=(2,2))(output)\n output = Conv2D(filters = 64, kernel_size = (3, 3), activation = 'relu', kernel_regularizer = l2(lambda_val))(output)\n\n output = MaxPool2D(pool_size=(2,2))(output)\n output = Dropout(0.25)(output)\n output = Flatten()(output)\n output = Dense(128,activation='relu',kernel_regularizer=l2(lambda_val))(output)\n output = Dropout(0.5)(output)\n\n output = Dense(num_classes,activation='softmax')(output)\n\n model = Model(inputs, output, name=\"simple_model\")\n print(model.summary())\n\n return model\n\n\ndef main():\n\n #parse flags before use\n FLAGS(sys.argv)\n epochs = FLAGS.epochs\n batch_size = FLAGS.batch_size\n lr = FLAGS.lr\n iters = FLAGS.num_iters\n ds_path = FLAGS.ds_path\n seed = FLAGS.seed\n\n #dataset with file paths and one hot encoded labels\n data, encoder = generate_dataset(ds_path)\n\n #train 80%, validate 10%, test 10% dfs\n train_df, rest_df = train_test_split(data, test_size= 0.2, random_state = seed)\n val_df, test_df = train_test_split(rest_df, test_size = 0.5, random_state = seed)\n\n #print(train_df.shape, val_df.shape, test_df.shape, val_df, test_df)\n\n #x, y, img = create_batch(val_df)\n t_test_x, t_test_y = create_batch(test_df)\n t_val_x,t_val_y = create_batch(val_df)\n t_train_x, t_train_y = create_batch(train_df)\n\n #print(img.shape)\n input_len = t_train_x[0].shape[0]\n input_wid = t_train_x[0].shape[1]\n print(t_train_y[0].shape)\n num_cats = t_train_y[0].shape[0]\n print(len(t_train_x))\n\n #conv list of np arrays to np array\n train_x = np.vstack([np.expand_dims(x,0) for x in t_train_x])\n print(train_x.shape)\n train_y = np.vstack([np.expand_dims(x,0) for x in t_train_y])\n test_x = np.vstack([np.expand_dims(x,0) for x in t_test_x])\n test_y = np.vstack([np.expand_dims(x,0) for x in t_test_y])\n val_x = np.vstack([np.expand_dims(x,0) for x in t_val_x])\n val_y = np.vstack([np.expand_dims(x,0) for x in t_val_y])\n\n\n #doesn't look like this is used yet\n variable_learning_rate=ReduceLROnPlateau(monitor='val_loss',factor=0.2,patience=2)\n\n\n #initialize model\n model = simple_model(input_len, input_wid, num_cats, lambda_val = 1e-5)\n model.compile(optimizer='adam',loss=tf.keras.losses.categorical_crossentropy,metrics=['accuracy'])\n print(train_x.shape, train_y.shape)\n history = model.fit(train_x, train_y,\n steps_per_epoch = (len(train_x)//batch_size),\n batch_size=batch_size,\n epochs = epochs,\n validation_data=(val_x, val_y),\n verbose = 1)\n\n\n test_loss, test_acc = model.evaluate(test_x, test_y, verbose = 2)\n print(\"test_loss\", test_loss, \"test_acc\", test_acc)\n\n #PLOTTING\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 100])\n plt.legend(loc='lower right')\n plt.tight_layout()\n plt.savefig('./epochaccuracy.pdf')\n\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"poltergeistjoya/Raag_Classification","sub_path":"joya.py","file_name":"joya.py","file_ext":"py","file_size_in_byte":9643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72972079574","text":"\"\"\"\nVariables set by the command line arguments dictating which parts of the program to execute, and constants.\n\"\"\"\n\n\n# Constants\nSTART_TAG_TUPLE = (\"\", \"\")\nEND_TAG_TUPLE = (\"\", \"\")\nSTART_TAG_STRING = \"\"\nEND_TAG_STRING = \"\"\nDEFAULT_TRAIN_SIZE = 10000\nDEFAULT_TEST_SIZE = 500\nMAX_SENTENCE_LENGTH = 150\n\nNOUN_SUFFIX = [\"action\", \"age\", \"ance\", \"cy\", \"ee\", \"ence\", \"er\", \"hood\", \"ion\", \"ism\", \"ist\", \"ity\", \"ling\",\n \"ment\", \"ness\", \"or\", \"ry\", \"scape\", \"ship\", \"dom\", \"ty\"]\nVERB_SUFFIX = [\"ed\", \"ify\", \"ise\", \"ize\", \"ate\", \"ing\"]\nADJ_SUFFIX = [\"ous\", \"ese\", \"ful\", \"i\", \"ian\", \"ible\", \"ic\", \"ish\", \"ive\", \"less\", \"ly\", \"able\"]\nADV_SUFFIX = [\"wise\", \"wards\", \"ward\"]\n\n\n# Global variables (set by command-line arguments).\ncorpus = \"brown\" # Default corpus to use.\nrecalculate = False # Recalculate the HMM's tag transition and word emission probability matrices.\ndebug = False # Boolean used to print additional logs for debugging purposes.\n","repo_name":"Adamouization/POS-Tagging-and-Unknown-Words","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19129831780","text":"import torch\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import Dataset\n\n\n### Dataset ###\nclass ParallelDatasetForMBart(Dataset):\n def __init__(self, config, tokenizer, eval=False):\n self.config = config\n if eval:\n dataset = pd.read_csv(config[\"eval_data_path\"])\n else:\n dataset = pd.read_csv(config[\"train_data_path\"])\n self.tokenizer = tokenizer\n\n if config[\"oneshot\"] == 1:\n dataset = oneshotrand(config, dataset, tokenizer)\n elif config[\"oneshot\"] == 2:\n dataset = oneshotsim(config, dataset, tokenizer)\n\n self.source = tokenizer(\n list(dataset[\"source\"]),\n max_length=config[\"max_length\"],\n padding=\"max_length\",\n return_attention_mask=True,\n return_token_type_ids=True,\n return_tensors=\"pt\",\n )\n self.labels = tokenizer(\n list(dataset[\"target\"]),\n max_length=config[\"max_length\"],\n padding=\"max_length\",\n return_attention_mask=True,\n return_token_type_ids=True,\n )\n\n def __len__(self):\n return len(self.source[\"input_ids\"])\n\n def __getitem__(self, idx):\n return {\n \"input_ids\": self.source[\"input_ids\"][idx],\n \"attention_mask\": self.source[\"attention_mask\"][idx],\n \"labels\": torch.tensor([self.tokenizer.bos_token_id] + self.labels[\"input_ids\"][idx]),\n }\n\n\nclass ParallelDatasetForT5(Dataset):\n def __init__(self, config, tokenizer, eval=False):\n self.config = config\n if eval:\n dataset = pd.read_csv(config[\"eval_data_path\"])\n else:\n dataset = pd.read_csv(config[\"train_data_path\"])\n self.tokenizer = tokenizer\n\n if config[\"oneshot\"] == 1:\n dataset = oneshotrand(config, dataset, tokenizer)\n elif config[\"oneshot\"] == 2:\n dataset = oneshotsim(config, dataset, tokenizer)\n\n src_seq, tgt_seq, attention = [], [], []\n\n for s, t in zip(dataset[\"source\"], dataset[\"target\"]):\n s = tokenizer.encode(s, add_special_tokens=False)\n t = tokenizer.encode(t, add_special_tokens=False)\n\n if len(s) > config[\"max_length\"] - 1:\n s = s[: config[\"max_length\"] - 1] + [tokenizer.eos_token_id]\n att = [1 for _ in range(config[\"max_length\"])]\n else:\n att = [1 for _ in range(len(s) + 1)] + [0 for _ in range(config[\"max_length\"] - 1 - len(s))]\n s = (\n s\n + [tokenizer.eos_token_id]\n + [tokenizer.pad_token_id for _ in range(config[\"max_length\"] - 1 - len(s))]\n )\n\n if len(t) > config[\"max_length\"] - 2:\n t = [tokenizer.bos_token_id] + t[: config[\"max_length\"] - 2] + [tokenizer.eos_token_id]\n else:\n t = (\n [tokenizer.bos_token_id]\n + t\n + [tokenizer.eos_token_id]\n + [tokenizer.pad_token_id for _ in range(config[\"max_length\"] - 2 - len(t))]\n )\n\n src_seq.append(s)\n tgt_seq.append(t)\n attention.append(att)\n self.source = src_seq\n self.labels = tgt_seq\n self.attention_mask = attention\n\n def __len__(self):\n return len(self.source)\n\n def __getitem__(self, idx):\n return {\n \"input_ids\": torch.tensor(self.source[idx]),\n \"attention_mask\": torch.tensor(self.attention_mask[idx]),\n \"labels\": torch.tensor([self.tokenizer.bos_token_id] + self.labels[idx]),\n }\n\n\ndef collate_fn(batch):\n input = []\n attention = []\n labels = []\n for b in batch:\n input.append(b[\"input_ids\"].unsqueeze(0))\n attention.append(b[\"attention_mask\"].unsqueeze(0))\n labels.append(b[\"labels\"].unsqueeze(0))\n return {\n \"input_ids\": torch.cat(input, 0),\n \"attention_mask\": torch.cat(attention, 0),\n \"labels\": torch.cat(labels, 0),\n } # Shape: (batch_size, max length)\n\n\ndef oneshotrand(config, dataset, tokenizer):\n example_dataset = pd.read_csv(config[\"train_data_path\"])\n newsource = []\n prefixsc = \"순화된 표현으로 변환: \"\n for i in range(len(dataset)):\n k = i\n while k == i:\n k = np.random.randint(len(example_dataset))\n if eval:\n break\n newsource.append(\n prefixsc\n + example_dataset.iloc[k][\"source\"]\n + \" > \"\n + example_dataset.iloc[k][\"target\"]\n + tokenizer.sep_token\n + dataset.iloc[i][\"source\"]\n + \" > \"\n )\n dataset[\"source\"] = newsource\n\n return dataset\n\n\ndef oneshotsim(config, dataset, tokenizer):\n newsource = []\n prefixsc = \"순화된 표현으로 변환: \"\n for i in range(len(dataset)):\n newsource.append(\n prefixsc\n + dataset.iloc[i][\"example_source\"]\n + \" > \"\n + dataset.iloc[i][\"example_target\"]\n + tokenizer.sep_token\n + dataset.iloc[i][\"source\"]\n + \" > \"\n )\n dataset[\"source\"] = newsource\n\n return dataset\n","repo_name":"gustn9609/kpmg_boosting","sub_path":"generation/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"67"} +{"seq_id":"9593246403","text":"#coding:utf-8\nimport numpy as np\nimport itertools\nfrom scipy.stats import mode\nimport sys\nsys.setrecursionlimit(1000000)\nimport copy\nimport struct\nimport time\n\n# 参考大佬:https://github.com/qingshangithub/KNNbyMatlab\n\ntrain_images_path = 'train-images.idx3-ubyte'\ntrain_labels_path = 'train-labels.idx1-ubyte'\ntest_images_path = 't10k-images.idx3-ubyte'\ntest_labels_path = 't10k-labels.idx1-ubyte'\n\n# mnist 格式参考: http://www.fon.hum.uva.nl/praat/manual/IDX_file_format.html\ndef decode_idx3_ubyte(idx3_ubyte_file):\n bin_data = open(idx3_ubyte_file,'rb').read()\n\n #解析文件头信息 \n offset = 0\n fmt_header = '>iiii'\n magic_number, num_images, num_rows, num_cols = struct.unpack_from(fmt_header, bin_data, offset)\n print('图片数量:%d,图片大小:%d*%d' %(num_images, num_rows, num_cols))\n #解析数据集\n image_size = num_cols * num_rows\n offset += struct.calcsize(fmt_header)\n fmt_image = '>' + str(image_size) + 'B'\n images = np.empty((num_images, num_rows, num_cols))\n for i in range(num_images):\n #if (i+1)%10000 == 0:\n #print(\"已解析 %d\" %(i + 1) + \"张\")\n images[i] = np.array(struct.unpack_from(fmt_image, bin_data, offset)).reshape((num_rows, num_cols))\n offset += struct.calcsize(fmt_image)\n return images\n\ndef decode_idx1_ubyte(idx1_ubyte_file):\n\n # 读取二进制数据\n bin_data = open(idx1_ubyte_file, 'rb').read()\n\n # 解析文件头信息\n offset = 0\n fmt_header = '>ii'\n magic_number, num_images = struct.unpack_from(fmt_header, bin_data, offset)\n print('图片数量: %d张' % (num_images))\n # 解析数据集\n offset += struct.calcsize(fmt_header)\n fmt_image = '>B'\n labels = np.empty(num_images)\n for i in range(num_images):\n #if (i + 1) % 10000 == 0:\n #print('已解析 %d' % (i + 1) + '张')\n labels[i] = struct.unpack_from(fmt_image, bin_data, offset)[0]\n offset += struct.calcsize(fmt_image)\n return labels\n\ndef load_train_images(idx_ubyte_file = train_images_path):\n return decode_idx3_ubyte(idx_ubyte_file)\n\ndef load_train_labels(idx_ubyte_file = train_labels_path):\n return decode_idx1_ubyte(idx_ubyte_file)\n\ndef load_test_images(idx_ubyte_file = test_images_path):\n return decode_idx3_ubyte(idx_ubyte_file)\n\ndef load_test_labels(idx_ubyte_file = test_labels_path):\n return decode_idx1_ubyte(idx_ubyte_file)\n\n\n\nclass KDNode: #KD树的节点\n\n def __init__(self, point, dim):\n self.point = point # kd树储存的点\n self.split_dim = dim # 分割维度\n self.left = None\n self.right = None\n\n\ndef findMedian(data_lst, split_dim):\n '''\n 找出 data_lst 的中位数\n data_lst 是一个 **排序后** 的 list\n data_lst的长度为: 4000\n data_lst[i] 长度为 784\n '''\n\n d = len(data_lst) / 2\n h, l = int(d), 0\n while l < h: \n m = int((l + h) / 2)\n if data_lst[m][split_dim] < data_lst[h][split_dim]:\n l = m + 1\n else:\n h = m\n return data_lst[h], h\n\n\ndef getSplitDim(data_lst):\n \"\"\"\n @:parameter\n data_lst: 不懂\n data_lst的长度为: 4000\n data_lst[i] 长度为 784\n\n 计算points在每个维度上的和, 选择在和最大的维度上进行切割\n \n \"\"\"\n \n # data_lst 相当于 4000*784 的 np.array, 在按行方向累加\n sum_lst = np.sum(data_lst, axis=0) # 维度为 (784,)\n # 注意: A numpy array with shape (5,) is a 1 dimensional array while one with shape (5,1) is a 2 dimensional array. \n split_dim = 0\n for v in range(1, len(sum_lst)):\n if sum_lst[v] > sum_lst[split_dim]:\n split_dim = v\n return split_dim\n\n\ndef buildKDTree(data_lst):\n #构建kd树\n # 确定在那个维度上进行分割\n split_dim = getSplitDim(data_lst) \n data_lst = sorted(data_lst, key=lambda x: x[split_dim])\n # 选中值??\n point, m = findMedian(data_lst, split_dim)\n tree_node = KDNode(point, split_dim)\n\n if m > 0:\n tree_node.left = buildKDTree(data_lst[:m])\n if len(data_lst) > m + 1:\n tree_node.right = buildKDTree(data_lst[m + 1:])\n\n return tree_node\n\n\nclass NeiNode:\n '''neighbor node'''\n def __init__(self, p, d):\n self.__point = p\n self.__dist = d\n\n def get_point(self):\n return self.__point\n\n def get_dist(self):\n return self.__dist\n\n\nclass priorityQueue:\n '''优先队列'''\n def __init__(self, k):\n self.__K = k # k近邻\n self.__pos = 0\n self.__priorityQueue = [0] * (k + 2)\n\n def add_neighbor(self, neighbor):\n self.__pos += 1\n self.__priorityQueue[self.__pos] = neighbor\n self.__swim_up(self.__pos)\n if self.__pos > self.__K:\n self.__exchange(1, self.__pos)\n self.__pos -= 1\n self.__sink_down(1)\n\n def get_knn_points(self):\n return [neighbor.get_point() for neighbor in self.__priorityQueue[1:self.__pos + 1]]\n\n def get_max_distance(self):\n if self.__pos > 0:\n return self.__priorityQueue[1].get_dist()\n return 0\n\n def get_knearest(self,k):\n if self.__pos > 0:\n tmp=[]\n while k > 0:\n tmp.append([self.__priorityQueue[k].get_dist(),self.__priorityQueue[k].get_point()])\n k = k-1\n return tmp\n return 0\n\n def is_full(self):\n return self.__pos >= self.__K\n\n def __swim_up(self, n):\n while n > 1 and self.__less(int(n / 2), n):\n self.__exchange(int(n / 2), n)\n n = n / 2\n\n def __sink_down(self, n):\n while 2 * n <= self.__pos:\n j = 2 * n\n if j < self.__pos and self.__less(j, j + 1):\n j += 1\n if not self.__less(n, j):\n break\n self.__exchange(n, j)\n n = j\n\n def __less(self, m, n):\n if m != 0:\n return self.__priorityQueue[m].get_dist() < self.__priorityQueue[n].get_dist()\n\n def __exchange(self, m, n):\n tmp = self.__priorityQueue[m]\n self.__priorityQueue[m] = self.__priorityQueue[n]\n self.__priorityQueue[n] = tmp\n\ndef knn_search_kd_tree_non_recursively(knn_priorityQueue, tree, target, search_track):\n track_node = []\n node_ptr = tree\n while node_ptr:\n while node_ptr:\n track_node.append(node_ptr)\n search_track.append([node_ptr.point, knn_priorityQueue.get_knn_points(), knn_priorityQueue.get_max_distance()])\n # 计算欧氏距离\n dist = np.linalg.norm(np.array(node_ptr.point) - np.array(target))\n\n knn_priorityQueue.add_neighbor(NeiNode(node_ptr.point, dist))\n\n search_track.append([None, knn_priorityQueue.get_knn_points(), knn_priorityQueue.get_max_distance()])\n\n split_dim = node_ptr.split_dim\n if target[split_dim] < node_ptr.point[split_dim]:\n node_ptr = node_ptr.left\n else:\n node_ptr = node_ptr.right\n\n while track_node:\n iter_node = track_node[-1]\n del track_node[-1]\n\n split_dim = iter_node.split_dim\n if not knn_priorityQueue.is_full() or \\\n abs(iter_node.point[split_dim] - target[split_dim]) < knn_priorityQueue.get_max_distance():\n if target[split_dim] < iter_node.point[split_dim]:\n node_ptr = iter_node.right\n else:\n node_ptr = iter_node.left\n\n if node_ptr:\n break\n a = knn_priorityQueue.get_knearest(k)\n return a\n\n\nif __name__ == '__main__':\n train_images = load_train_images()\n train_labels = load_train_labels()\n test_images = load_test_images()\n test_labels = load_test_labels()\n\n\n time_1 = time.time()\n\n T = train_images\n nn = 3999\n mm = 399\n TT = [[0]*784]*(nn+1)\n TST = [[0]*784]*(mm+1)\n n = nn\n m = mm\n while n >= 0:\n TT[n] = list(itertools.chain.from_iterable(T[n]))\n n = n-1\n while m >= 0:\n TST[m] = list(itertools.chain.from_iterable(test_images[m]))\n m = m-1\n print('开始建树')\n kd_tree = buildKDTree(TT)\n print('建树结束\\n')\n\n k = 2\n m = mm\n labelK = [0]*k\n labelResult = [0]*(m+1)\n j = 0\n print('begin to search target point in kd-tree')\n while j <= m:\n knn_priorityQueue = priorityQueue(k)\n search_track = []\n a = knn_search_kd_tree_non_recursively(knn_priorityQueue, kd_tree, TST[j], search_track)\n tmp1 = 0\n while tmp1 < k:\n labelK[tmp1] = TT.index(a[tmp1][1])\n tmp1 = tmp1+1\n #print(train_labels[labelK[:]])\n labelResult[j] = int(mode(train_labels[labelK[:]])[0][0])\n j = j+1\n lx = 0\n error = 0\n while lx <= m:\n if test_labels[lx] != labelResult[lx]:\n error = error+1\n lx = lx+1\n accuracy = 1-error/(m+1)\n print(\"accuracy: \", accuracy)\n\n time_2 = time.time()\n print('training cost ', time_2 - time_1,' second', '\\n')\n","repo_name":"cw-plus/Lihang_Statistical_Machine_Learning","sub_path":"my_implement_try../02-kNN/KD-tree.py","file_name":"KD-tree.py","file_ext":"py","file_size_in_byte":9071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24647670144","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n # reverse linked list\n reversed_l1 = self.reverse_linked_list(l1)\n reversed_l2 = self.reverse_linked_list(l2)\n\n # convert linked list into list\n list_l1 = self.to_list(reversed_l1)\n list_l2 = self.to_list(reversed_l2)\n\n # concat list elements and convert into integer\n final_l1 = int(\"\".join(map(str, list_l1)))\n final_l2 = int(\"\".join(map(str, list_l2)))\n\n # return reversed linked list\n return self.to_reversed_linked_list(str(final_l1 + final_l2))\n\n def reverse_linked_list(self, head: ListNode) -> ListNode:\n node, prev = head, None\n while node:\n next, node.next = node.next, prev\n prev, node = node, next\n return prev\n\n def to_list(self, node: ListNode) -> list:\n result = []\n while node:\n result.append(node.val)\n node = node.next\n return result\n\n def to_reversed_linked_list(self, elements: str) -> ListNode:\n prev = None\n for elem in elements:\n node = ListNode(elem)\n node.next = prev\n prev = node\n return node\n\n\nclass Solution2:\n \"\"\"\n 전가산기(Full Adder)의 원리를 활용한 풀이\n \"\"\"\n\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n root = ListNode(0)\n head = ListNode(0)\n\n carry = 0\n while l1 or l2 or carry:\n total = 0\n # 두 입력값의 합 계산\n if l1:\n total += l1.val\n l1 = l1.next\n if l2:\n total += l2.val\n l2 = l2.next\n\n # 몫(자리올림수)와 나머지(값) 계산\n carry, val = divmod(total + carry, 10)\n head.next = ListNode(val)\n head = head.next\n\n return root.next\n","repo_name":"youngerous/algorithm","sub_path":"leetcode/2. Add Two Numbers.py","file_name":"2. Add Two Numbers.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73363254934","text":"#!/usr/bin/env python\n\nimport argparse, os, sys\n\n\ndef new_tmux_cmd(name, cmd):\n if isinstance(cmd, (list, tuple)):\n cmd = ' '.join(str(v) for v in cmd)\n return name, \"tmux send-keys -t {} '{}' Enter\".format(name, cmd)\n\ndef create_tmux_commands(session, num_workers, logdir, use_gpu, port, extra_args):\n # for launching the TF workers and for launching tensorboard\n # cluster start from the next port\n base_cmd = [sys.executable, 'async_node.py', '--log-dir', logdir, '--n-workers', num_workers, '--cluster-port', port + 1]\n\n if not use_gpu:\n # hide GPU from tensorflow\n base_cmd = ['CUDA_VISIBLE_DEVICES='] + base_cmd\n\n # parameter server\n cmds_map = [new_tmux_cmd('ps', base_cmd + ['--job', 'ps'])]\n # workers\n for i in range(num_workers):\n cmds_map += [new_tmux_cmd( 'w-%d' % i, base_cmd + ['--job', 'worker', '--task-index', str(i)] + extra)]\n\n # tensorboard\n cmds_map += [new_tmux_cmd('tb', ['tensorboard --logdir {} --port {}'.format(logdir, port)])]\n\n windows = [v[0] for v in cmds_map]\n\n cmds = [\n 'mkdir -p {}'.format(logdir),\n 'tmux new-session -s {} -n {} -d'.format(session, windows[0]),\n ]\n for w in windows[1:]:\n cmds += ['tmux new-window -t {} -n {}'.format(session, w)]\n cmds += ['sleep 1']\n for window, cmd in cmds_map:\n cmds += [cmd]\n\n return cmds\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-w', '--n-workers', default=1, type=int, help='number of workers')\n parser.add_argument('-l', '--log-dir', type=str, default='/tmp/pong', help='checkpoint directory path')\n parser.add_argument('-g', '--use-gpu', action='store_true', help='use GPU for training')\n parser.add_argument('-p', '--port', type=int, help='port for tensorboard', default=12345)\n\n args, extra = parser.parse_known_args()\n\n cmds = create_tmux_commands(os.path.basename(args.log_dir), args.n_workers, args.log_dir, args.use_gpu, args.port, extra)\n print('\\n'.join(cmds))\n os.system('\\n'.join(cmds))\n","repo_name":"falcondai/ttic-programming-requirement","sub_path":"launch_tmux_async.py","file_name":"launch_tmux_async.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"14272641348","text":"with open('input.txt', 'r') as f:\n contents = f.read()\n\nlines = contents.split() \ntrees = [] \n\ndef print_trees() : \n for t in trees: \n print(t) \n\nfor line in lines: \n trees.append([])\n for char in line: \n trees[-1].append((int(char), 0))\n\nprint_trees() \n\ndef viewing_distance(x,y): \n curr_tree = trees[x][y][0]\n print(\"Current tree:\", curr_tree)\n\n # Up\n updist = 0 \n for i in range(x-1, -1, -1): \n updist += 1 \n if trees[i][y][0] >= curr_tree: \n break \n print(\"Up distance:\", updist)\n\n # Left\n leftdist = 0 \n for j in range(y-1, -1, -1): \n leftdist += 1 \n if trees[x][j][0] >= curr_tree: \n break \n print(\"Left distance:\", leftdist)\n\n # Right\n rightdist = 0 \n for j in range(y+1,len(trees[0])): \n rightdist += 1 \n if trees[x][j][0] >= curr_tree: \n break \n print(\"Right distance:\", rightdist)\n\n # Down\n downdist = 0 \n for i in range(x+1,len(trees)): \n downdist += 1 \n if trees[i][y][0] >= curr_tree: \n break \n print(\"Down distance:\", downdist)\n\n score = updist * downdist * leftdist * rightdist\n print(\"Score:\", score)\n return score\n\nviewing_distance(1,2)\n \nanswer2 = 0 \n\nfor i in range(len(trees)):\n for j in range(len(trees[0])): \n answer2 = max(viewing_distance(i,j), answer2) \n\nprint(answer2)\n","repo_name":"septract/aoc-2022","sub_path":"day08/day08-part2.py","file_name":"day08-part2.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"23613039509","text":"from django.shortcuts import render, redirect\nfrom django.http import request, HttpResponse, HttpResponseRedirect\nfrom django.urls import reverse\nfrom lxml import etree\nimport xml.etree.ElementTree as xml\nimport os\n\nfrom .forms import BlogForm\nfrom .functions import handle_uploaded_file\nfrom .models import Blogs\n\n# Create your views here.\n\ndef index(request):\n return HttpResponse(\"this is index page. go to log/blog for blog or go to log/cat to see cats\")\n\ndef cat(request):\n if request.method == 'POST':\n title = request.POST['title']\n # print(title)\n delete_saved_blog(request, given_title=title)\n return redirect('https://www.google.com/search?q=cats')\n return render(request, 'log/cat.html')\n\ndef blog(request):\n if request.method == 'POST':\n blog = BlogForm(request.POST, request.FILES)\n if blog.is_valid():\n if request.FILES:\n f = request.FILES['file']\n title = handle_uploaded_file(f)\n else:\n title = blog.cleaned_data['title']\n body = blog.cleaned_data['body']\n author = blog.cleaned_data['author']\n filename = \"log/upload/{}.xml\".format(title)\n root = xml.Element(\"Blogs\")\n blogelement = xml.Element(\"blog\")\n root.append(blogelement)\n\n title_element = xml.SubElement(blogelement, \"title\")\n title_element.text = str(title)\n\n body_element = xml.SubElement(blogelement, \"body\")\n body_element.text = str(body)\n\n author_element = xml.SubElement(blogelement, \"author\")\n author_element.text = str(author)\n\n tree = xml.ElementTree(root)\n # print(root[0][0].text)\n tree.write(filename)\n \n b = Blogs()\n b.blog_titles = title\n b.save()\n\n return HttpResponse(\"blog posted\")\n # parser = etree.XMLParser(load_dtd=True, resolve_entities=True)\n # tree = etree.parse('log/upload/{}.xml'.format(title), parser=parser)\n # # extraction of information\n # root = tree.getroot()\n \n # return HttpResponse(\"{}
{}
{}\".format(root[0][0].text, root[0][1].text, root[0][2].text))\n else:\n blog = BlogForm()\n return render(request, 'log/login.html', {'form':blog})\n\ndef saved_blog(request, given_title):\n for blog in Blogs.objects.all():\n if blog.blog_titles == given_title:\n print(request.GET.get('deleteButton'))\n if(request.GET.get('deleteButton')):\n return HttpResponseRedirect(reverse('log:delete_saved_blog', args=(given_title,)))\n else:\n parser = etree.XMLParser(load_dtd=True, resolve_entities=True)\n tree = etree.parse('log/upload/{}.xml'.format(given_title), parser=parser)\n # extraction of information\n root = tree.getroot()\n return render(request,'log/saved_blog.html', {'blog_title':root[0][0].text, 'blog_content':root[0][1].text, 'blog_author':root[0][2].text})\n return HttpResponse(\"will show saved blogs of title:{}\".format(given_title))\n\n# solve delete problem\n\ndef delete_saved_blog(request, given_title):\n for blog in Blogs.objects.all():\n if blog.blog_titles == given_title:\n blog.delete()\n os.remove('log/upload/{}.xml'.format(given_title))\n return render(request, 'log/deleted_blog.html', {'given_title':given_title})\n return render(request, 'log/deleted_blog.html', {'given_title':given_title})","repo_name":"Phantsure/fata_hua_log_in","sub_path":"log/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18253959710","text":"import sys, os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader, Dataset\nimport time\nfrom myModel import Classifier, ImgDataset\n\nbatch_size = 128\n\noutput_name = 'w0307081007'\n\nmodel_dir = './data/'\nmodel_path = [\n'model_20200403-02-29-49.pkl',\n'model_20200407-20-03-05.pkl',\n'model_20200408-20-49-52.pkl',\n'model_20200410-02-35-27.pkl',\n'model_res_20200407-10-05-39.pkl'\n]\n\nloadfile = np.load('../data/food-11/data.npz')\ntest_x = loadfile['te_x']\n\ntest_transform = transforms.Compose([\n transforms.ToPILImage(), \n transforms.ToTensor(),\n])\ntest_set = ImgDataset(test_x, transform=test_transform)\ntest_loader = DataLoader(test_set, batch_size=batch_size, shuffle=False)\n\nmodels = []\nfor m in model_path:\n print('Loading model ' + m)\n model = torch.load(model_dir + m)\n models.append(model)\n model.eval()\n\nprediction = []\n\nwith torch.no_grad():\n for i, data in enumerate(test_loader):\n testm = models[0](data.cuda())\n for m in range(1, len(models)):\n testm.add(models[m](data.cuda()))\n # test_shape = testm.cpu().data.numpy().shape\n # np.add(test_pred, testm.cpu().data.numpy())\n # print\n # test_label = np.argmax(test_pred.cpu().data.numpy(), axis=1)\n # for y in test_label:\n # prediction.append(y)\n\n#將結果寫入 csv 檔\n'''\nwith open('./output/predict_vote_{}.csv'.format(output_name), 'w') as f:\n f.write('Id,Category\\n')\n for i, y in enumerate(prediction):\n f.write('{},{}\\n'.format(i, y))\n\nprint('predict file: predict_vote_{}.csv generated.'.format(output_name))\n'''","repo_name":"orange2120/ML_2020Spring","sub_path":"hw3/vote_test.py","file_name":"vote_test.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"11018494551","text":"\"\"\"Module for extracting and caching XMP data from image files.\"\"\"\nimport datetime\nimport os\nimport typing\n\nfrom libxmp import utils as xmputils\nfrom sqlalchemy import Binary\nfrom sqlalchemy import Boolean\nfrom sqlalchemy import Column\nfrom sqlalchemy import DateTime\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy import Integer\nfrom sqlalchemy import orm\nfrom sqlalchemy import String\nfrom sqlalchemy.ext import declarative\n\nfrom labm8.py import app\nfrom labm8.py import sqlutil\nfrom util.photolib import common\nfrom util.photolib import workspace\n\nFLAGS = app.FLAGS\n\nBase = declarative.declarative_base() # pylint: disable=invalid-name\n\n\nclass XmpCacheEntry(Base):\n \"\"\"A keyword cache entry, mapping a file to a set of keywords.\n\n Each XmpCacheEntry requires 64 (40 + 8 + 8 + ?) bytes.\n \"\"\"\n\n __tablename__ = \"files\"\n\n relpath_md5: str = Column(Binary(16), primary_key=True)\n relpath: str = Column(String(1024), nullable=False)\n mtime: int = Column(Integer, nullable=False)\n keywords_id: int = Column(Integer, ForeignKey(\"keywords.id\"), nullable=False)\n iso: int = Column(Integer, nullable=False)\n camera: str = Column(String(1024), nullable=False)\n lens: str = Column(String(1024), nullable=False)\n shutter_speed: str = Column(String(128), nullable=False)\n aperture: str = Column(String(128), nullable=False)\n focal_length_35mm: str = Column(String(128), nullable=False)\n flash_fired: bool = Column(Boolean, nullable=False)\n date_added: datetime.datetime = Column(\n DateTime, nullable=False, default=datetime.datetime.utcnow\n )\n\n keywords: \"Keywords\" = orm.relationship(\"Keywords\")\n\n def ToDict(self) -> typing.Dict[str, str]:\n return {\n \"relpath\": self.relpath,\n \"camera\": self.camera,\n \"lens\": self.lens,\n \"iso\": self.iso,\n \"shutter_speed\": self.shutter_speed,\n \"aperture\": self.aperture,\n \"focal_length_35mm\": self.focal_length_35mm,\n \"flash_fired\": self.flash_fired,\n \"keywords\": \",\".join(self.keywords.AsList()),\n }\n\n\nclass Keywords(Base):\n \"\"\"A set of image keywords.\"\"\"\n\n __tablename__ = \"keywords\"\n\n id: int = Column(Integer, primary_key=True)\n keywords: str = Column(String(4096), nullable=False, unique=True)\n\n def AsList(self) -> typing.List[str]:\n return self.keywords.split(\",\")\n\n def AsSet(self) -> typing.Set[str]:\n return set(self.AsList())\n\n\nclass Meta(Base):\n __tablename__ = \"meta\"\n\n key: str = Column(String(1024), primary_key=True)\n value: str = Column(String(1024))\n\n\nclass XmpCache(sqlutil.Database):\n \"\"\"Database of keywords\"\"\"\n\n def __init__(self, workspace_: workspace.Workspace, must_exist: bool = False):\n cache_dir = workspace_.workspace_root / \".photolib\"\n cache_dir.mkdir(exist_ok=True)\n url = f\"sqlite:///{cache_dir}/xmp.db\"\n\n super(XmpCache, self).__init__(url, Base, must_exist)\n self.session = self.MakeSession()\n self.RefreshVersion()\n\n def RefreshVersion(self):\n \"\"\"Refresh version.\"\"\"\n meta_key = \"version\"\n\n cached_version = (\n self.session.query(Meta).filter(Meta.key == meta_key).first()\n )\n cached_version_str = cached_version.value if cached_version else \"\"\n\n actual_version = Meta(key=meta_key, value=app.VERSION)\n\n if cached_version_str != actual_version.value:\n app.Log(1, \"Version has changed, emptying cache ...\")\n self.session.query(XmpCacheEntry).delete()\n self.session.query(Keywords).delete()\n if cached_version:\n self.session.delete(cached_version)\n self.session.add(actual_version)\n self.session.commit()\n\n def _CreateXmpCacheEntry(\n self, abspath: str, relpath: str, relpath_md5: str, mtime: float\n ) -> XmpCacheEntry:\n \"\"\"\n Add a new database entry for the given values.\n\n Args:\n relpath_md5: The md5sum of the workspace relpath to the file.\n mtime: Seconds since the epoch that the file was last modified.\n keywords: The set of keywords to record.\n \"\"\"\n try:\n xmp = xmputils.file_to_dict(abspath)\n lightroom_tags = xmp[\"http://ns.adobe.com/lightroom/1.0/\"]\n\n keywords = set([e[1] for e in lightroom_tags if e[1]])\n\n iso = int(\n _GetFromXmpDict(\n xmp, \"http://cipa.jp/exif/1.0/\", \"exifEX:PhotographicSensitivity\", 0\n )\n )\n\n camera_make = _GetFromXmpDict(\n xmp, \"http://ns.adobe.com/tiff/1.0/\", \"tiff:Make\"\n )\n camera_model = _GetFromXmpDict(\n xmp, \"http://ns.adobe.com/tiff/1.0/\", \"tiff:Model\"\n )\n if camera_make and camera_model:\n camera = f\"{camera_make} {camera_model}\"\n else:\n camera = \"\"\n\n shutter_speed = _GetFromXmpDict(\n xmp, \"http://ns.adobe.com/exif/1.0/\", \"exif:ExposureTime\"\n )\n aperture = _GetFromXmpDict(\n xmp, \"http://ns.adobe.com/exif/1.0/\", \"exif:FNumber\"\n )\n focal_length_35mm = _GetFromXmpDict(\n xmp, \"http://ns.adobe.com/exif/1.0/\", \"exif:FocalLengthIn35mmFilm\"\n )\n flash_fired = (\n True\n if _GetFromXmpDict(\n xmp, \"http://ns.adobe.com/exif/1.0/\", \"exif:Flash/exif:Fired\"\n )\n == \"True\"\n else False\n )\n\n lens_make = _GetFromXmpDict(\n xmp, \"http://cipa.jp/exif/1.0/\", \"exifEX:LensMake\"\n )\n lens_model = _GetFromXmpDict(\n xmp, \"http://cipa.jp/exif/1.0/\", \"exifEX:LensModel\"\n )\n if lens_make and lens_model:\n lens = f\"{lens_make} {lens_model}\"\n elif lens_make:\n lens = lens_make\n elif lens_model:\n lens = lens_model\n else:\n lens = \"\"\n except KeyError:\n app.Log(2, \"Failed to read keywords of file: `%s`\", abspath)\n keywords = []\n iso = 0\n camera = \"\"\n lens = \"\"\n shutter_speed = \"\"\n aperture = \"\"\n focal_length_35mm = \"\"\n flash_fired = False\n\n keywords_ = sqlutil.GetOrAdd(\n self.session, Keywords, keywords=\",\".join(keywords)\n )\n entry = XmpCacheEntry(\n relpath_md5=relpath_md5,\n relpath=relpath,\n mtime=int(mtime),\n keywords=keywords_,\n iso=iso,\n camera=camera,\n lens=lens,\n shutter_speed=shutter_speed,\n aperture=aperture,\n focal_length_35mm=focal_length_35mm,\n flash_fired=flash_fired,\n )\n self.session.add(entry)\n self.session.commit()\n return entry\n\n def GetOrCreateXmpCacheEntry(\n self, abspath: str, relpath: str\n ) -> XmpCacheEntry:\n relpath_md5 = common.Md5String(relpath).digest()\n mtime = int(os.path.getmtime(abspath))\n entry = (\n self.session.query(XmpCacheEntry)\n .filter(XmpCacheEntry.relpath_md5 == relpath_md5)\n .first()\n )\n\n if entry and entry.mtime == mtime:\n return entry\n elif entry and entry.mtime != mtime and not abspath.endswith(\".mov\"):\n self.session.delete(entry)\n entry = self._CreateXmpCacheEntry(abspath, relpath, relpath_md5, mtime)\n app.Log(2, \"Refreshed cached XMP metadata `%s`\", relpath)\n else:\n entry = self._CreateXmpCacheEntry(abspath, relpath, relpath_md5, mtime)\n app.Log(2, \"Cached XMP metadata `%s`\", relpath)\n\n return entry\n\n def GetLightroomKeywords(self, abspath: str, relpath: str) -> typing.Set[str]:\n \"\"\"Fetch the lightroom keywords for the given file.\n\n Nested keywords are separated using the '|' symbol.\n\n Args:\n abspath: Absolute path of the file.\n relpath: Workspace-relative path to the file.\n\n Returns:\n A set of lightroom keywords. An empty set is returned on failure.\n \"\"\"\n entry = self.GetOrCreateXmpCacheEntry(abspath, relpath)\n return entry.keywords.AsSet()\n\n\ndef _GetFromXmpDict(\n xmp: typing.Dict[str, typing.Tuple[str, str, typing.Dict[str, str]]],\n xmp_type: str,\n tag_name: str,\n default=\"\",\n):\n keywords = xmp.get(xmp_type, {})\n for tag_, val, _ in keywords:\n if tag_ == tag_name:\n return val\n return default\n","repo_name":"ChrisCummins/phd","sub_path":"util/photolib/xmp_cache.py","file_name":"xmp_cache.py","file_ext":"py","file_size_in_byte":7811,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"67"} +{"seq_id":"22873329857","text":"# These imports will only be valid when the files are all in the same location/directory\r\nimport getSongs\r\nimport insertSong\r\nimport searchVid\r\n\r\n\r\nprint(\"Enter spotify URI: \",end = '')\r\nspotifyURIKey = input()\r\nprint()\r\nprint(\"Enter youtube playlist ID: \",end='')\r\nytPlaylistKey = input()\r\n\r\n\r\nif __name__ == '__main__':\r\n print(\"Spot:\", spotifyURIKey)\r\n print(\"yt:\", ytPlaylistKey)\r\n print(\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nProgram Finished!\")\r\n\r\ngetSongs.getSpotifySongs(spotPlaylistID=spotifyURIKey)\r\nsearchVid.searchYTSongs()\r\ninsertSong.insertYTSongs(ytPlaylistID=ytPlaylistKey)\r\n\r\n\r\n\r\n\r\n","repo_name":"andrewchau2/spotifyToYT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"31859603112","text":"import sys\nsys.path.append('../toolbox/')\nfrom robot_def import *\nfrom dx200_motion_program_exec_client import *\n\nfrom RobotRaconteur.Client import *\nimport matplotlib.pyplot as plt\nimport time\n\nrobot=robot_obj('MA1440_A0',def_path='../config/MA1440_A0_robot_default_config.yml',tool_file_path='../config/scanner_tcp2.csv',\\\n\tpulse2deg_file_path='../config/MA1440_A0_pulse2deg_real.csv')\nq1=np.radians([31.1143,57.8258,10.2037,-0.4206,35.1934,-29.7721])\nq2=np.radians([38.7598,59.7069,18.4387,-45.9732,34.4456,29.4706])\nq3=np.radians([47.5995,59.7092,18.4380,-45.9742,46.3366,57.3870])\n\npose1=robot.fwd(q1)\npose2=robot.fwd(q2)\npose3=robot.fwd(q3)\n\nms=MotionSend()\n\nclient=RRN.ConnectService('rr+tcp://192.168.55.27:64238?service=scanner')\n\n\nms.exec_motions(robot,['movej'],[pose1.p],[[q1]],10,0)\nmesh=client.capture(True)\npoints1 = RRN.NamedArrayToArray(mesh.vertices)\nnp.savetxt('points1.csv',points1,delimiter=',')\npoints1=np.dot(pose1.R,points1[:,:3].T).T+np.tile(pose1.p,(len(points1),1))\n\nms.exec_motions(robot,['movej'],[pose2.p],[[q2]],10,0)\nmesh=client.capture(True)\npoints2 = RRN.NamedArrayToArray(mesh.vertices)\nnp.savetxt('points2.csv',points2,delimiter=',')\npoints2=np.dot(pose2.R,points2[:,:3].T).T+np.tile(pose2.p,(len(points2),1))\n\nms.exec_motions(robot,['movej'],[pose3.p],[[q3]],10,0)\nmesh=client.capture(True)\npoints3 = RRN.NamedArrayToArray(mesh.vertices)\nnp.savetxt('points3.csv',points3,delimiter=',')\n\npoints3=np.dot(pose3.R,points3[:,:3].T).T+np.tile(pose3.p,(len(points3),1))\n\npoints=np.vstack((points1,points2,points3))\nax = plt.figure().add_subplot(projection='3d')\nax.scatter(points[:,0],points[:,1],points[:,2])\n\n# ax1 = plt.figure().add_subplot(projection='3d')\n# ax1.scatter(points1[:,0],points1[:,1],points1[:,2])\n# ax2 = plt.figure().add_subplot(projection='3d')\n# ax2.scatter(points2[:,0],points2[:,1],points2[:,2])\n\nplt.show()","repo_name":"hehonglu123/Welding_Motoman","sub_path":"scan/scan_client.py","file_name":"scan_client.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"5665593537","text":"#la tupla es inmutable\r\n#la lista no, se guarda en 2 lugares\r\n#crando tuplas con tuple()\r\ntupla=tuple([\"dato1\", \"dato2\", \"dato3\"])\r\n\r\n#tupla \"empaquetando\"\r\ntupla=\"dato1\", \"dato2\"\r\n\r\n#tupla \"empaquetando\" con un solo dato\r\ntupla=\"dato1\",\r\n\r\nprint(tupla)","repo_name":"Katrieljs/curso-py","sub_path":"variables_2.0/tuplas.py","file_name":"tuplas.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24975755853","text":"# Operasi image pada Python \n# Instalasi paket open cv\n# pip install opencv-contrib-python \n\n# pilihan load image (contoh logo ipb)\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\nimport time\n\ndef readAndShowImg(fname):\n img = cv2.imread(fname)\n cv2.imshow(\"img\", img)\n return img\n\n\nprint(\"read images using opencv\")\nfive = cv2.imread(\"p-5.png\")\nprint(five.shape)\nprint(five.size)\n\n# cv2.imshow(\"ims\", five)\nplt.imshow(five)\ncv2.waitKey(0)\n\nimg = cv2.imread(\"ipb.png\")\n# cv2.imshow(\"img\", img)\nplt.imshow(img)\n\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# cv2.imshow(\"img\", img)\nplt.imshow(img)\n\n# mengambil nilai matriksnya\n# acces pixel of images per postion \npixels = five[100,100]\nprint(pixels)","repo_name":"adibenc/pengenalan-pola","sub_path":"p1/p1.3.py","file_name":"p1.3.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4638333719","text":"from turtle import Turtle, Screen\nimport random\n\nis_race_on = False\nscreen = Screen()\nscreen.setup(width=500, height=400)\nuser_bet = screen.textinput(\n title=\"user bet\", prompt=\"Which turtle will win the race? choose a color: \"\n)\ncolors = [\"yellow\", \"orange\", \"red\", \"green\", \"blue\", \"purple\"]\ny_pos = [-70, -40, -10, 20, 50, 80]\nall_turtles = []\n\n\n# y = -150\n# for i, color in enumerate(colors):\n# exec(f\"new_turtle_{i} = Turtle(shape='turtle')\")\n# exec(f\"new_turtle_{i}.color(f'{color}')\")\n# exec(f\"new_turtle_{i}.penup()\")\n# exec(f\"new_turtle_{i}.goto(x=-230, y=y)\")\n# y += 60\n\nif user_bet:\n is_race_on = True\n\nfor tutle_index in range(len(colors)):\n new_turtle = Turtle(shape=\"turtle\")\n new_turtle.color(colors[tutle_index])\n new_turtle.penup()\n new_turtle.goto(x=-230, y=y_pos[tutle_index])\n all_turtles.append(new_turtle)\n\nwhile is_race_on:\n for turtle in all_turtles:\n if turtle.xcor() >= 220:\n is_race_on = False\n winner_color = turtle.pencolor()\n if winner_color == user_bet:\n print(f\"You've won! {winner_color} is winning.\")\n else:\n print(f\"You've lost! {winner_color} is winning\")\n\n random_step = random.randint(0, 10)\n turtle.forward(random_step)\n\n\nscreen.exitonclick()\n","repo_name":"AngelinaBao/Python-Pro-Bootcamp","sub_path":"Turtle/turtle_racing.py","file_name":"turtle_racing.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17170928051","text":"import os.path\nimport sys \npath_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))\nsys.path.append(path_name)\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nimport train\nfrom utils.utilities import generate_roc_curve, generate_goal_rate_curve, generate_cumu_goal_curve, generate_calibration_display\nfrom utils.utilities import get_shot_array, get_goal_rate_shot_percentile\n\nfrom sklearn.calibration import calibration_curve, CalibrationDisplay\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfig = plt.figure()\ngs = GridSpec(2, 1)\nplt.rc(\"font\", size=14)\nimport seaborn as sns\nsns.set(style=\"white\")\nsns.set(style=\"whitegrid\", color_codes=True)\n\nax_calibration_curve = fig.add_subplot(111)\n\ndata_list = [['Distance from net', 'Is goal'],['Angle from net', 'Is goal'],['Distance from net', 'Angle from net', 'Is goal']]\nlabel_names = ['distance', 'angle', 'distance and angle']\n\narr_y_test, arr_x_test, arr_y_pred, arr_prob, arr_shot_percentile, arr_goal_rate, arr_goal_cumu = [], [], [], [], [], [], []\n\nfor i, data in enumerate(data_list): \n print(f\"-------------------------{data}---------------------------------\")\n clf = LogisticRegression()\n y_pred, y_prob, y_test, x_test, clf = train.train(clf, columns = data, model_name = label_names[i])\n\n # Reliabiliyty curve\n display = CalibrationDisplay.from_estimator(\n clf,\n x_test,\n y_test,\n n_bins=20,\n name=label_names[i],\n ax=ax_calibration_curve,\n )\n\n print('Confusion Matrix:')\n print(metrics.confusion_matrix(y_test, y_pred))\n arr_y_test.append(y_test)\n arr_x_test.append(x_test)\n arr_y_pred.append(y_pred)\n arr_prob.append(y_prob)\n \n shots_array = get_shot_array(y_prob, y_test)\n shot_percentile, goal_rate, goal_cumu = get_goal_rate_shot_percentile(shots_array, bin_size=1)\n\n arr_shot_percentile.append(shot_percentile)\n arr_goal_rate.append(goal_rate)\n arr_goal_cumu.append(goal_cumu)\n print(\"----------------------------------------------------------------\")\n\nax_calibration_curve.grid()\nax_calibration_curve.set_title(\"Reliability_curve_log_reg\")\n# plt.savefig(\"../../figs/\" + 'Reliability_curve_log_reg_new.png')\n# plt.show()\n\ngenerate_roc_curve(arr_y_test, arr_y_pred, arr_prob, label_names = label_names, plot_title = 'roc_curve_log_reg', save = False)\n# generate_goal_rate_curve(arr_shot_percentile, arr_goal_rate, label_names = label_names, plot_title='Goal_Rate_log_reg', save = True)\n# generate_cumu_goal_curve(arr_shot_percentile, arr_goal_cumu, label_names = label_names, plot_title='Cumulative_goals_log_reg', save = True)\n# generate_calibration_display(arr_clf, arr_x_test, arr_y_test, y_pred, y_prob, plot_name='Reliability_curve_xgb_base', label_names = label_names, save = True)\n","repo_name":"Alexia0328/NHL_Hockey_Game_Prediction","sub_path":"NHL-milestone-2/models/log_reg/log_reg.py","file_name":"log_reg.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"74870051094","text":"from typing import Any\n\nimport torch\nimport torchvision\nfrom tqdm import tqdm\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nfrom torch import nn\nimport numpy as np\nimport torch.nn.functional as F\nfrom sklearn.metrics.pairwise import cosine_similarity\n\nclass Conv2DWithLateralFeatures(nn.Module):\n def __init__(self, *args, **kwags):\n super(Conv2DWithLateralFeatures, self).__init__()\n self.lateral_mode = args[3]\n self.output_layers = args[1]\n self.alpha = .1\n self.lateral = torch.nn.parameter.Parameter(torch.ones(args[1], args[1]), requires_grad=False)\n self.lateral_storage = []\n self.conv = nn.Conv2d(*args[0:3])\n self.learned = False\n self.mode = 1\n\n def set_lateral_mode(self, mode):\n self.lateral_mode = mode\n\n def set_leared_mode(self, mode=True):\n self.learned = mode\n\n def process_lateral(self):\n\n self.lateral_storage = np.concatenate(self.lateral_storage, axis=1)\n self.lateral_storage = np.corrcoef(self.lateral_storage.reshape((self.output_layers, -1)))\n np.fill_diagonal(self.lateral_storage, 0)\n self.lateral = torch.nn.parameter.Parameter(torch.from_numpy(self.lateral_storage), requires_grad=False)\n\n def forward(self, x):\n x = self.conv(x)\n # print('f ', x.shape)\n if self.lateral_mode:\n # corrs = np.corrcoef(x.cpu().numpy().transpose((1,0,2,3)).reshape(self.output_layers,-1))\n\n q = x.cpu().numpy()\n q = ((q - q.min()) / (q.max() - q.min()))\n # corrs = np.corrcoef(q.transpose((1, 0, 2, 3)).reshape(self.output_layers, -1))\n\n self.lateral_storage.append(q.transpose((1, 0, 2, 3)))\n return x\n\n if self.learned:\n for i in range(self.output_layers):\n # tmp = self.lateral[i]\n # tmp = torch.normal(tmp.mean(), tmp.std(), tmp.shape).cuda()\n x[:, i, ...] += self.alpha * (self.lateral[i].view(1, self.lateral.shape[0], 1, 1) * x).mean(1)\n\n # x[:, i, ...] += self.alpha*x[:, i, ...]*(x.mean(axis=(0, 2, 3)) * tmp).sum()\n return x\n return x\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.lateral_mode = False\n self.learned = False\n\n self.conv1 = Conv2DWithLateralFeatures(3, 10, 5, self.lateral_mode)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = Conv2DWithLateralFeatures(10, 20, 5, self.lateral_mode)\n self.fc1 = nn.Linear(20 * 5 * 5, 50)\n self.fc2 = nn.Linear(50, 10)\n\n def set_lateral_mode(self, mode=False):\n self.lateral_mode = mode\n self.conv1.set_lateral_mode(mode)\n self.conv2.set_lateral_mode(mode)\n\n def set_mode(self, mode):\n self.conv1.mode = mode\n self.conv2.mode = mode\n\n def set_alpha(self, alpha):\n self.conv1.alpha = alpha\n self.conv2.alpha = alpha\n\n def set_learned(self, mode=True):\n self.learned = mode\n self.conv1.learned = mode\n self.conv2.learned = mode\n\n def process_lateral(self):\n self.conv1.process_lateral()\n self.conv2.process_lateral()\n pass\n\n def forward(self, x):\n # print(self.conv1(x).shape)\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 20 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return x\n","repo_name":"crazyleg/lateral_research","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38882577169","text":"from openerp import api, fields, models\nimport openerp.addons.decimal_precision as dp\n\n\nclass PurchaseDiscountPurchaseOrderLine(models.Model):\n _inherit = \"purchase.order.line\"\n\n #@api.depends('discount')\n #def _compute_amount(self):\n # prices = {}\n # for line in self:\n # if line.discount:\n # prices[line.id] = line.price_unit\n # line.price_unit *= (1 - line.discount / 100.0)\n # line.net_price = line.price_unit\n\n # super(PurchaseDiscountPurchaseOrderLine, self)._compute_amount()\n # for line in self:\n # if line.discount:\n # line.price_unit = prices[line.id]\n\n @api.depends('product_qty', 'price_unit', 'taxes_id','discount')\n def _compute_amount(self):\n for line in self:\n prices = {}\n if line.discount:\n prices[line.id] = line.price_unit\n calculo = line.price_unit*(1 - line.discount / 100.0)\n line.net_price = calculo\n taxes = line.taxes_id.compute_all(line.net_price, line.order_id.currency_id, line.product_qty,\n product=line.product_id, partner=line.order_id.partner_id)\n line.update({\n 'price_tax': taxes['total_included'] - taxes['total_excluded'],\n 'price_total': taxes['total_included'],\n 'price_subtotal': taxes['total_excluded'],\n })\n line.price_subtotal = taxes['total_excluded']\n\n else:\n line_prr = line.price_unit\n taxes = line.taxes_id.compute_all(line.price_unit, line.order_id.currency_id, line.product_qty,\n product=line.product_id, partner=line.order_id.partner_id)\n line.update({\n 'price_tax': taxes['total_included'] - taxes['total_excluded'],\n 'price_total': taxes['total_included'],\n 'price_subtotal': taxes['total_excluded'],\n })\n line.price_subtotal = taxes['total_excluded']\n\n\n net_price = fields.Float(string='Precio neto', digits_compute=dp.get_precision('Product Price'), compute='_compute_amount')\n discount = fields.Float(string='Descuento (%)', digits_compute=dp.get_precision('Discount'))\n\n _sql_constraints = [\n ('discount_limit', 'CHECK (discount <= 100.0)',\n 'Discount must be lower than 100%.'),\n ]\n","repo_name":"xmarts/purchase_discount","sub_path":"models/purchase_order.py","file_name":"purchase_order.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"3601771813","text":"#The following questions reference the students data structure below. Write the python code to answer the following questions:\nfrom statistics import mean\nfrom collections import Counter\n\nstudents = [\n {\n \"id\": \"100001\",\n \"student\": \"Ada Lovelace\",\n \"coffee_preference\": \"light\",\n \"course\": \"web development\",\n \"grades\": [70, 91, 82, 71],\n \"pets\": [{\"species\": \"horse\", \"age\": 8}],\n },\n {\n \"id\": \"100002\",\n \"student\": \"Thomas Bayes\",\n \"coffee_preference\": \"medium\",\n \"course\": \"data science\",\n \"grades\": [75, 73, 86, 100],\n \"pets\": [],\n },\n {\n \"id\": \"100003\",\n \"student\": \"Marie Curie\",\n \"coffee_preference\": \"light\",\n \"course\": \"web development\",\n \"grades\": [70, 89, 69, 65],\n \"pets\": [{\"species\": \"cat\", \"age\": 0}],\n },\n {\n \"id\": \"100004\",\n \"student\": \"Grace Hopper\",\n \"coffee_preference\": \"dark\",\n \"course\": \"data science\",\n \"grades\": [73, 66, 83, 92],\n \"pets\": [{\"species\": \"dog\", \"age\": 4}, {\"species\": \"cat\", \"age\": 4}],\n },\n {\n \"id\": \"100005\",\n \"student\": \"Alan Turing\",\n \"coffee_preference\": \"dark\",\n \"course\": \"web development\",\n \"grades\": [78, 98, 85, 65],\n \"pets\": [\n {\"species\": \"horse\", \"age\": 6},\n {\"species\": \"horse\", \"age\": 7},\n {\"species\": \"dog\", \"age\": 5},\n ],\n },\n {\n \"id\": \"100006\",\n \"student\": \"Rosalind Franklin\",\n \"coffee_preference\": \"dark\",\n \"course\": \"data science\",\n \"grades\": [76, 70, 96, 81],\n \"pets\": [],\n },\n {\n \"id\": \"100007\",\n \"student\": \"Elizabeth Blackwell\",\n \"coffee_preference\": \"dark\",\n \"course\": \"web development\",\n \"grades\": [69, 94, 89, 86],\n \"pets\": [{\"species\": \"cat\", \"age\": 10}],\n },\n {\n \"id\": \"100008\",\n \"student\": \"Rene Descartes\",\n \"coffee_preference\": \"medium\",\n \"course\": \"data science\",\n \"grades\": [87, 79, 90, 99],\n \"pets\": [{\"species\": \"cat\", \"age\": 10}, {\"species\": \"cat\", \"age\": 8}],\n },\n {\n \"id\": \"100009\",\n \"student\": \"Ahmed Zewail\",\n \"coffee_preference\": \"medium\",\n \"course\": \"data science\",\n \"grades\": [74, 99, 93, 89],\n \"pets\": [{\"species\": \"cat\", \"age\": 0}, {\"species\": \"cat\", \"age\": 0}],\n },\n {\n \"id\": \"100010\",\n \"student\": \"Chien-Shiung Wu\",\n \"coffee_preference\": \"medium\",\n \"course\": \"web development\",\n \"grades\": [82, 92, 91, 65],\n \"pets\": [{\"species\": \"cat\", \"age\": 8}],\n },\n {\n \"id\": \"100011\",\n \"student\": \"William Sanford Nye\",\n \"coffee_preference\": \"dark\",\n \"course\": \"data science\",\n \"grades\": [70, 92, 65, 99],\n \"pets\": [{\"species\": \"cat\", \"age\": 8}, {\"species\": \"cat\", \"age\": 5}],\n },\n {\n \"id\": \"100012\",\n \"student\": \"Carl Sagan\",\n \"coffee_preference\": \"medium\",\n \"course\": \"data science\",\n \"grades\": [100, 86, 91, 87],\n \"pets\": [{\"species\": \"cat\", \"age\": 10}],\n },\n {\n \"id\": \"100013\",\n \"student\": \"Jane Goodall\",\n \"coffee_preference\": \"light\",\n \"course\": \"web development\",\n \"grades\": [80, 70, 68, 98],\n \"pets\": [{\"species\": \"horse\", \"age\": 4}],\n },\n {\n \"id\": \"100014\",\n \"student\": \"Richard Feynman\",\n \"coffee_preference\": \"medium\",\n \"course\": \"web development\",\n \"grades\": [73, 99, 86, 98],\n \"pets\": [{\"species\": \"dog\", \"age\": 6}],\n },\n]\n#----------------------------------------------\n# How many students are there?\nprint('How many students are there?')\nhow_many_students = len(students)\nprint('There are ', how_many_students, 'students')\n\n#----------------------------------------------\n# How many students prefer light coffee? \n# For each type of coffee roast? ----------- come back to this one!! \n\n#students[0][\"coffee_preference\"] -- how to access each element of a dictionary in this list\n#[student for student in students if student[\"coffee_preference\"] == 'light'] -- creates list of people (dicts) who \nprint('\\nHow many students prefer light coffee?')\nnum_of_light_coffee_drinkers = len([student for student in students if student[\"coffee_preference\"] == 'light'])\nprint('There are ', num_of_light_coffee_drinkers, ' light coffee drinkers')\n\n#----------------------------------------------\n# How many types of each pet are there?\n\n#iterate over list of students (dict), iterate over list of pets (dict or list of dict)\n#create new list of the different types of pets\n #maybe create a list of all pets, then count the distinct ones\nprint('\\nHow many types of each pet are there?')\npets_ppl_have = [] #initalize list of types of pets\nfor p in students: #loop through students\n #print(p['pets'])\n for kind in p['pets']: # loop through pets key \n # print(kind['species']) # print all pets in the species dicts\n if kind['species'] not in pets_ppl_have: # check to see if pet name is unique\n pets_ppl_have.append(kind['species']) #add it to list of pets\nprint(pets_ppl_have)\nprint(\"There are \", len(pets_ppl_have), \" different types of pets\")\n\n#---------------------------------------------- \n# How many grades does each student have? \n # 4\n# Do they all have the same number of grades?\n # yes they do\nprint('\\nHow many grades does each student have?')\nx = 0 # initalize counter for student number for print chekc\nfor grade in students: #iterate over list and find grades key\n print(\"student\", x , \" has \", len(grade['grades'])) #count number of elements in that list\n x += 1\nprint('Each student has 4 grades')\n\n#----------------------------------------------\n# What is each student's grade average?\nprint('\\nWhat is each student\\'s grade average?')\nfor grade in students:\n print(grade['student'],' : ', mean(grade[\"grades\"]))\n#----------------------------------------------\n# How many pets does each student have?\nprint('\\nHow many pets does each student have?')\nfor p in students:\n print(p['student'], 'has', end = ' ')\n number_pets = 0 #set counter to 0 for each person\n for kind in p['pets']: #loop through pets dictionaries\n # print(kind['species']) # print out the types of pets they have\n number_pets += 1 #count up how many pets\n print(number_pets, 'pet(s)') # print out the count of pets\n\n#----------------------------------------------\n# How many students are in web development? data science?\n # 7 students in web development and 7 in data science\n\nprint('\\nHow many students are in web development? Data Science?')\n# find list of all types of courses\ntypes_of_courses = [c['course'] for c in students] \n# count distinct types in list \n# print(Counter(types_of_courses)) # improved way to print this out below vvv\ncourse_counts = Counter(types_of_courses)\nprint('There are ', course_counts['web development'], ' students in web development')\nprint('There are ', course_counts['data science'], ' students in data science')\n\n#----------------------------------------------\n# What is the average number of pets for students in web development?\n\n#find number of pets for each web development student\n# put values in list\n# average list\nprint('\\nWhat is the avg number of pets for students in web development?')\nweb_dev_pets = []\nfor p in students:\n if p['course'] != 'web development': #if student isn't in web dev, go to next student\n continue\n number_pets = 0 #set counter to 0 for each person\n for kind in p['pets']: #loop through pets dictionaries\n number_pets += 1 #count up how many pets\n web_dev_pets.append(number_pets)\nprint('the web development students have an average of ',\n round(mean(web_dev_pets), 2), 'pets per student' #print satement and round the mean of list\n )\n\n#----------------------------------------------\n# What is the average pet age for students in data science?\n# find pets age for all data science students, make list\n# use mean to average that list together\n\nprint('\\nWhat is the average pet age for students in data science?')\npet_ages = [] # initalize list to store ages\nfor p in students:\n if p['course'] != 'data science':\n continue\n for a in p['pets']:\n pet_ages.append(a['age'])\nprint(\"Average pet age for data science students is \", \n round(mean(pet_ages), 2))\n\n#----------------------------------------------\n# What is most frequent coffee preference for data science students?\n# find list of coffee preferences of ds students\n# do the counter thing again\n# there's probably a better way to do this\n\n# What is the most frequent coffee prefernce for data science students?\nprint('\\nWhat is most frequent coffee preference for data science students?')\ncoffee_prefs = [] # create list to store prefs\nfor c in students:\n if c['course'] != 'data science':\n continue\n else:\n coffee_prefs.append(c['coffee_preference'])\n# print(coffee_prefs)\n#this outputs a list of tuples, ordered most to least\npref_counts = (Counter(coffee_prefs)) \n#this unpacks the first tuple in the list aka the most common element\nmost_common_roast_type, count = pref_counts.most_common(1)[0] \nprint('most frequent coffee preference for data science students is\\n', \n most_common_roast_type, \" with \", count, \" people prefering that.\"\n )\n# note about .most_common it returns list a list of the items ordered from most common to least.\n\n#----------------------------------------------\n# What is the least frequent coffee preference for web development students?\nprint('\\nWhat is the least frequent coffee preference for web development students?')\ncoffee_prefs_wd = [] # set empty list for coffee preferences for web dev students\nfor c in students:\n if c['course'] != 'web development':\n continue\n else:\n coffee_prefs_wd.append(c['coffee_preference'])\n# print(coffee_prefs_wd)\npref_counts_wd = Counter(coffee_prefs_wd)\n# print(pref_counts_wd)\n#there are two least common preferences so add those tuples to a list\n#use the .most_common()[:-2-1:-1]] to get least. see documentation for clarification\nleast_common_list = pref_counts_wd.most_common()[:-2-1:-1]\n #print(least_common_list)\n#unpack each tuple from the least common list\nleastcommonwd1, lcwdcounter1 = least_common_list[0]\nleastcommonwd2, lcwdcounter2 = least_common_list[1]\nprint('The least common preferences for the web development students are ',\n leastcommonwd1, ' and ', leastcommonwd2,\n '\\nwith ', lcwdcounter1, ' students and ', lcwdcounter2,\n ' students liking those roasts respectively.'\n ) #this is a little redunant but I was practicing \n\n#----------------------------------------------\n# What is the average grade for students with at least 2 pets?\n # find students that have 2 pets\n # find the avg grade for each student with 2 pets\n # find the avg of those avgs (can you just do an average of all of their grades togeher?)\nprint('\\nWhat is the average grade for students with at least 2 pets?')\nlist_of_grades = [] #create list to hold all the grades \nfor s in students:\n if len(s['pets']) >= 2: # at least 2 pet check\n list_of_grades.extend(s['grades']) #had to use extend instead of append to make one big list\nprint(mean(list_of_grades)) #print average of all grades\n\n#----------------------------------------------\n# How many students have 3 pets?\nthree_pet_ppl = [] #create list to hold names of ppl who have 3 pets\nfor s in students:\n if len(s['pets']) == 3: # 3 pet check\n three_pet_ppl.append(s['student']) # fill in the list with the names\nprint(\"There is \", len(three_pet_ppl), ' person who has 3 pets.',\n '\\n And it is: ', three_pet_ppl[0]\n )\n\n#----------------------------------------------\n# What is the average grade for students with 0 pets?\n # find people with 0 pets \n # get their grades in a list\n # average that list \nprint('\\nWhat is the average grade for students with 0 pets?')\ngrades_zero_pet_ppl = []\nfor s in students:\n if len(s['pets']) == 0:\n grades_zero_pet_ppl.extend(s['grades'])\nprint(round(mean(grades_zero_pet_ppl), 2 ))\n\n#----------------------------------------------\n# What is the average grade for web development students? data science students?\nprint('\\nWhat is the average grade for web development students?')\ngrades_webdev = []\ngrades_datasci = []\nfor s in students:\n if s['course'] == 'web development':\n grades_webdev.extend(s['grades'])\n elif s['course'] == 'data science':\n grades_datasci.extend(s['grades'])\n else:\n print('something weird happened')\nprint(round(mean(grades_webdev), 2), ' is the average grade for web dev students')\nprint(round(mean(grades_datasci), 2), ' is the average grade for data science students')\n\n#----------------------------------------------\n# What is the average grade range (i.e. highest grade - lowest grade) for dark coffee drinkers?\n #find all grades for dark coffee drinkers\n #find range -- use max() and min()\nprint('\\nWhat is the average grade range for dark coffee drinkers?')\ndark_coffee_grades = []\nfor s in students:\n if s['coffee_preference'] == 'dark':\n dark_coffee_grades.extend(s['grades'])\n else:\n continue\nprint('The highest grade of dark coffee drinkers is ', max(dark_coffee_grades),\n '\\nThe lowest grade of dark coffee drinkers is ', min(dark_coffee_grades)\n )\n\n#----------------------------------------------\n# What is the average number of pets for medium coffee drinkers?\nprint('\\nWhat is the average number of pets for medium coffee drinkers?')\n # make list for pet numbers\n # find medium coffee drinkers and add their pet count to the list\n # average that list\nmed_coffee_pets = []\nfor s in students:\n if s['coffee_preference'] == 'medium':\n med_coffee_pets.append(len(s['pets']))\nprint('The average number of pets for medium coffee drinkers is: ', \n round(mean(med_coffee_pets), 2)\n )\n\n\n#----------------------------------------------\n# What is the most common type of pet for web development students?\n # find web dev students\n # find pet types\ncommon_pets = []\nfor s in students:\n if s['course'] == 'web development':\n for kind in s['pets']:\n common_pets.append(kind['species'])\npet_totals = Counter(common_pets)\nmost_common_pet, countp = pet_totals.most_common(1)[0]\nprint('The most common type of pet among web development students is a ',\n most_common_pet, '. \\nThere are ', countp, '.'\n )\n\n#----------------------------------------------\n# What is the average name length?\n #I'm gonna use a function for funzies. \n # create function that counts name chars minus any whitespaces\n # loop through dictionary of names\n # add length to list \n # averge that list\ndef len_of_name(full_name):\n letter_count = len(full_name) - full_name.count(' ')\n return letter_count\n\nprint('\\nWhat is the average name length?')\nname_lengths = []\nfor s in students:\n name_lengths.append(len_of_name(s['student']))\nprint('The average length of students\\' names is: ',\n round(mean(name_lengths), 2))\n\n#----------------------------------------------\n# What is the highest pet age for light coffee drinkers?\n # find all pet ages from light coffee drinkers\n # put values in a list\n # use max() to find highest\n\nprint('\\nWhat is the highest pet age for light coffee drinkers?')\n\npet_ages =[]\nfor s in students:\n if s['coffee_preference'] == 'light':\n for pet in s['pets']:\n pet_ages.append(pet['age'])\n \nprint('The highest pet age for light coffee drinkers is: ', \n max(pet_ages), 'years old.'\n )","repo_name":"HeatherOrtegaMcMillan/python-exercises","sub_path":"python_data_structure_manipulation_exercises.py","file_name":"python_data_structure_manipulation_exercises.py","file_ext":"py","file_size_in_byte":15744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73285468054","text":"import streamlit as st\nimport pandas as pd\n\n# Sidebar\nst.sidebar.markdown(\n \"\"\"\n
\n

Key Performance Indicator

\n
\n \"\"\",\n unsafe_allow_html=True\n)\n# Tampilan header dalam sidebar\nst.sidebar.markdown(\n \"\"\"\n \n \"\"\",\n unsafe_allow_html=True\n)\n\nall_df = pd.read_csv('https://raw.githubusercontent.com/nabilakarimaazka/final_project/main/dashboard/all.csv')\nrfm = pd.read_csv('https://raw.githubusercontent.com/nabilakarimaazka/final_project/main/data/rfm_.csv')\n\n# Hitung KPI dari data Anda\ntotal_revenue = all_df['price'].sum()\ntotal_customers = all_df['customer_id'].nunique()\ntotal_orders = len(all_df)\n\n# Tampilan informasi KPI\nst.sidebar.markdown(\n f\"\"\"\n
\n
Total Revenue
\n
${total_revenue:,.2f}
\n
\n \"\"\",\n unsafe_allow_html=True\n)\n\nst.sidebar.markdown(\n f\"\"\"\n
\n
Jumlah Customer
\n
{total_customers:,}
\n
\n \"\"\",\n unsafe_allow_html=True\n)\n\nst.sidebar.markdown(\n f\"\"\"\n
\n
Total Order
\n
{total_orders:,}
\n
\n \"\"\",\n unsafe_allow_html=True\n)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom babel.numbers import format_currency\n\n\n# jumlah order per bulan\ndef create_monthly_orders_df(df):\n monthly_orders_df = df.resample(rule='M', on='order_purchase_timestamp').agg({\n \"order_id\": \"nunique\",\n \"price\": \"sum\"\n })\n\n monthly_orders_df = monthly_orders_df.reset_index()\n monthly_orders_df.rename(columns={\n \"order_id\": \"order_count\",\n \"price\": \"revenue\"\n }, inplace=True)\n \n return monthly_orders_df\n\n# jumlah customer berdasarkan city\ndef create_bycity_df(df):\n bycity_df = df.groupby(by=\"customer_city\").order_id.nunique().reset_index()\n bycity_df.rename(columns={\n \"order_id\" : \"order_count\"\n }, inplace = True)\n\n return bycity_df\n\n# jumlah order berdasarkan city\ndef create_bystate_df(df):\n bystate_df = df.groupby(by=\"customer_state\").order_id.nunique().reset_index()\n bystate_df.rename(columns={\n \"order_id\" : \"order_count\"\n }, inplace = True)\n\n return bystate_df\n\n# customer_segmen\n\ndef create_segment_df(df):\n segment_df = df.groupby(by=\"customer_segment\", as_index=False).cust_id.nunique().reset_index()\n segment_df['customer_segement'] = pd.Categorical(segment_df['customer_segment'],[\n \"Lost Customer\", \"Low Value Customer\", \"Medium Value Customer\",\n \"High Value Customer\", \"Top Customer\"\n])\n\n return segment_df\n\n# waktu pembelian\n\ndef waktu_pembelian(df):\n # Hitung jumlah pembelian pada setiap jam\n waktu_df = df.groupby(\"purchase_time\").order_id.nunique().reset_index()\n return waktu_df\n\n# create_sum_order_items_df()\n\ndef create_sum_order_items_df(df):\n sum_order_items_df = df.groupby(\"product_category_name\").order_id.nunique().sort_values(ascending=False).reset_index()\n return sum_order_items_df\n\n# seller_city_df()\n\ndef seller_city_df(df):\n seller_df = df.groupby(by=\"seller_city\").order_id.nunique().reset_index()\n seller_df.rename(columns={\n \"order_id\": \"order_count\"\n }, inplace=True)\n\n# create_rfm_df()\n\ndef create_rfm_df(df):\n rfm_df = df.groupby(by=\"cust_id\", as_index=False).agg({\n \"order_purchase_timestamp\": \"max\", #mengambil tanggal order terakhir\n \"order_id\": \"count\",\n \"price\": \"sum\"\n })\n \n rfm_df.columns = [\"cust_id\", \"max_order_timestamp\", \"frequency\", \"monetary\"]\n\n rfm_df[\"max_order_timestamp\"] = rfm_df[\"max_order_timestamp\"].dt.date\n recent_date = df[\"order_purchase_timestamp\"].dt.date.max()\n rfm_df[\"recency\"] = rfm_df[\"max_order_timestamp\"].apply(lambda x: (recent_date - x).days)\n rfm_df.drop(\"max_order_timestamp\", axis=1, inplace=True)\n\n return rfm_df\n\ndatetime_columns = [\"order_purchase_timestamp\"]\nall_df.reset_index(inplace=True)\n\nfor column in datetime_columns:\n all_df[column] = pd.to_datetime(all_df[column])\n\nmin_date = all_df[\"order_purchase_timestamp\"].min()\nmax_date = all_df[\"order_purchase_timestamp\"].max()\n\nmonthly_orders_df = create_monthly_orders_df(all_df)\nbycity_df = create_bycity_df(all_df)\nbystate_df = create_bystate_df(all_df)\nsum_order_items_df = create_sum_order_items_df(all_df)\nwaktu_df = waktu_pembelian(all_df)\nrfm_df = create_rfm_df(all_df)\nsegment_df = create_segment_df(rfm)\n\n\nst.header('E-commerce Analysis Dashboard :sparkles:')\nst.subheader('Jumlah Order per Bulan')\n\nfig, ax = plt.subplots(figsize=(16, 8))\nax.plot(\n monthly_orders_df[\"order_purchase_timestamp\"],\n monthly_orders_df[\"order_count\"],\n marker='o', \n linewidth=2,\n color=\"#90CAF9\"\n)\nax.tick_params(axis='y', labelsize=20)\nax.tick_params(axis='x', labelsize=15)\n \nst.pyplot(fig)\n\nst.subheader('Jumlah Pendapatan per Bulan')\n\nfig, ax = plt.subplots(figsize=(16, 8))\nax.plot(\n monthly_orders_df[\"order_purchase_timestamp\"],\n monthly_orders_df[\"revenue\"],\n marker='o', \n linewidth=2,\n color=\"#90CAF9\"\n)\nax.tick_params(axis='y', labelsize=20)\nax.tick_params(axis='x', labelsize=15)\n \nst.pyplot(fig)\n\nst.subheader(\"Jumlah Order Berdasarkan City dan State\")\n \nfig, ax = plt.subplots(nrows=1, ncols=2, figsize=(35, 15))\n \ncolors = [\"#90CAF9\", \"#D3D3D3\", \"#D3D3D3\", \"#D3D3D3\", \"#D3D3D3\"]\n \nsns.barplot(x=\"order_count\", y=\"customer_city\", data=bycity_df.sort_values(by=\"order_count\", ascending=False).head(5), palette=colors, ax=ax[0])\nax[0].set_ylabel(None)\nax[0].set_xlabel(\"Number of Sales\", fontsize=30)\nax[0].set_title(\"Total Order Berdasarkan City\", loc=\"center\", fontsize=50)\nax[0].tick_params(axis='y', labelsize=35)\nax[0].tick_params(axis='x', labelsize=30)\n \nsns.barplot(x=\"order_count\", y=\"customer_state\", data=bystate_df.sort_values(by=\"order_count\", ascending=False).head(5), palette=colors, ax=ax[1])\nax[1].set_ylabel(None)\nax[1].set_xlabel(\"Number of Sales\", fontsize=30)\nax[1].invert_xaxis()\nax[1].yaxis.set_label_position(\"right\")\nax[1].yaxis.tick_right()\nax[1].set_title(\"Total Order Berdasarkan State\", loc=\"center\", fontsize=50)\nax[1].tick_params(axis='y', labelsize=35)\nax[1].tick_params(axis='x', labelsize=30)\n\nst.pyplot(fig)\n\nst.subheader(\"Produk Paling Banyak dan Paling Sedikit Diorder\")\n \nfig, ax = plt.subplots(nrows=1, ncols=2, figsize=(35, 15))\n \ncolors = [\"#90CAF9\", \"#D3D3D3\", \"#D3D3D3\", \"#D3D3D3\", \"#D3D3D3\"]\n \nsns.barplot(x=\"order_id\", y=\"product_category_name\", data=sum_order_items_df.sort_values(by=\"order_id\", ascending=False).head(5), palette=colors, ax=ax[0])\nax[0].set_ylabel(None)\nax[0].set_xlabel(\"Number of Sales\", fontsize=30)\nax[0].set_title(\"Best Performing Product\", loc=\"center\", fontsize=50)\nax[0].tick_params(axis='y', labelsize=35)\nax[0].tick_params(axis='x', labelsize=30)\n \nsns.barplot(x=\"order_id\", y=\"product_category_name\", data=sum_order_items_df.sort_values(by=\"order_id\", ascending=True).head(5), palette=colors, ax=ax[1])\nax[1].set_ylabel(None)\nax[1].set_xlabel(\"Number of Sales\", fontsize=30)\nax[1].invert_xaxis()\nax[1].yaxis.set_label_position(\"right\")\nax[1].yaxis.tick_right()\nax[1].set_title(\"Worst Performing Product\", loc=\"center\", fontsize=50)\nax[1].tick_params(axis='y', labelsize=35)\nax[1].tick_params(axis='x', labelsize=30)\n \nst.pyplot(fig)\n\nst.subheader('Distribusi Waktu Order Dalam 24 Jam')\n\nfig, ax = plt.subplots(figsize=(16, 8))\nax.plot(\n waktu_df[\"purchase_time\"],\n waktu_df[\"order_id\"],\n marker='o', \n linewidth=2,\n color=\"#90CAF9\"\n)\nax.tick_params(axis='y', labelsize=20)\nax.tick_params(axis='x', labelsize=15)\n \nst.pyplot(fig)\n\nst.subheader(\"Customer Terbaik Berdasarkan Parameter RFM Analysis\")\n\ncol1, col2 = st.columns(2)\n\nwith col1:\n fig, ax = plt.subplots(figsize=(20, 10))\n colors = [\"#90CAF9\", \"#90CAF9\", \"#90CAF9\", \"#90CAF9\", \"#90CAF9\"]\n\n avg_recency = round(rfm_df.recency.mean(), 1)\n st.metric(\"Rata-rata Recency (hari)\", value=avg_recency)\n\n sns.barplot(y=\"recency\", x=\"cust_id\", data=rfm_df.sort_values(by=\"recency\", ascending=True).head(5), palette=colors)\n ax.set_ylabel(None)\n ax.set_xlabel(\"cust_id\", fontsize=30)\n ax.set_title(\"By Recency (days)\", loc=\"center\", fontsize=50)\n ax.tick_params(axis='y', labelsize=30)\n ax.tick_params(axis='x', labelsize=35)\n st.pyplot(fig)\n\nwith col2:\n fig, ax = plt.subplots( figsize=(20, 10))\n colors = [\"#90CAF9\", \"#90CAF9\", \"#90CAF9\", \"#90CAF9\", \"#90CAF9\"]\n\n avg_frequency = avg_frequency = round(rfm_df.frequency.mean(), 2)\n st.metric(\"Average Frequency\", value=avg_frequency)\n\n sns.barplot( \n y=\"frequency\", \n x=\"cust_id\", \n data=rfm_df.sort_values(by=\"frequency\", ascending=False).head(5), palette=colors)\n ax.set_ylabel(None)\n ax.set_xlabel(\"cust_id\", fontsize=30)\n ax.set_title(\"By Frequency\", loc=\"center\", fontsize=50)\n ax.tick_params(axis='y', labelsize=30)\n ax.tick_params(axis='x', labelsize=35)\n st.pyplot(fig)\n\nfig, ax = plt.subplots( figsize=(20, 10))\ncolors = [\"#90CAF9\", \"#90CAF9\", \"#90CAF9\", \"#90CAF9\", \"#90CAF9\"]\n\navg_frequency = format_currency(rfm_df.monetary.mean(), \"AUD\", locale='es_CO') \nst.metric(\"Average Monetary\", value=avg_frequency)\n\nsns.barplot(y=\"monetary\", x=\"cust_id\", data=rfm_df.sort_values(by=\"monetary\", ascending=False).head(5), palette=colors)\nax.set_ylabel(None)\nax.set_xlabel(\"cust_id\", fontsize=30)\nax.set_title(\"By Monetary\", loc=\"center\", fontsize=50)\nax.tick_params(axis='y', labelsize=30)\nax.tick_params(axis='x', labelsize=35)\nst.pyplot(fig)\n\nst.subheader(\"Segmentasi Customer\")\n\nfig, ax = plt.subplots(figsize=(20, 10))\n \ncolors = [\"#D3D3D3\", \"#90CAF9\", \"#D3D3D3\", \"#D3D3D3\", \"#D3D3D3\"]\n \nsns.barplot(\n x=\"cust_id\", \n y=\"customer_segment\",\n data=segment_df.sort_values(by=\"customer_segment\", ascending=False),\n palette=colors\n )\nax.set_title(\"Number of Customer for Each Segment\", loc=\"center\", fontsize=50)\nax.set_ylabel(None)\nax.set_xlabel(None)\nax.tick_params(axis='x', labelsize=35)\nax.tick_params(axis='y', labelsize=30)\nst.pyplot(fig)\n \nst.caption('Copyright (c) Nabila Karima Azka 2023')\n","repo_name":"nabilakarimaazka/final_project","sub_path":"dashboard/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":10783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37820323073","text":"#!/usr/bin/python\n\nfrom math3d import *\nfrom svg import *\n\n# Return the vector at the lower-left corner of the the pixel at row r and\n# column c of an n-by-n linear cube map face.\n\ndef cube(r, c, n):\n return vnormalize((2.0 * float(c) / float(n) - 1.0,\n -2.0 * float(r) / float(n) + 1.0, 1.0))\n\n# Return the vector at the lower-left corner of the the pixel at row r and\n# column c of an n-by-n spherical cube map face.\n\ndef scube(r, c, n):\n a = (math.pi / 2) * float(c) / float(n) - (math.pi / 4)\n b = (math.pi / 2) * float(r) / float(n) - (math.pi / 4)\n\n return vnormalize((math.sin(a) * math.cos(b),\n -math.cos(a) * math.sin(b),\n math.cos(a) * math.cos(b)))\n\n#-------------------------------------------------------------------------------\n\ndef solid_angle3(a, b, c):\n aa = vlength(a)\n bb = vlength(b)\n cc = vlength(c)\n return vdot(a, vcross(b, c)) / (aa * bb * cc + vdot(b, c) * aa\n + vdot(a, c) * bb\n + vdot(a, b) * cc)\n\ndef solid_angle4(a, b, c, d):\n return solid_angle3(a, b, c) + solid_angle3(c, d, a)\n\n#-------------------------------------------------------------------------------\n\n# Transform and project a 3D vector into a viewport with width w and height h.\n\ns = 0.75\nw = 512\nh = 512\nM = mcompose([\n mtranslate((w/2, h/2, 0.0, 1.0)),\n mscale ((w/2, h/2, 1.0, 1.0)),\n morthogonal(-s, s, -s, s, 1.0, 10.0)\n ])\n\ndef view(v):\n return vtransform(M, v)\n\n#-------------------------------------------------------------------------------\n\ndef draw_cube_face(svg, n):\n for c in range(0, n + 1):\n svglinelist(svg, map(lambda r: view(cube(r, c, n)), range(0, n + 1)))\n for r in range(0, n + 1):\n svglinelist(svg, map(lambda c: view(cube(r, c, n)), range(0, n + 1)))\n\ndef draw_scube_face(svg, n):\n for c in range(0, n + 1):\n svglinelist(svg, map(lambda r: view(scube(r, c, n)), range(0, n + 1)))\n for r in range(0, n + 1):\n svglinelist(svg, map(lambda c: view(scube(r, c, n)), range(0, n + 1)))\n\ndef cube_solid_angle(r, c, n):\n return solid_angle4(cube(r, c, n),\n cube(r + 1, c, n),\n cube(r + 1, c + 1, n),\n cube(r, c + 1, n))\n\ndef scube_solid_angle(r, c, n):\n return solid_angle4(scube(r, c, n),\n scube(r + 1, c, n),\n scube(r + 1, c + 1, n),\n scube(r, c + 1, n))\n\ndef cube_edge_length(r, c, n):\n return vdistance(cube(r, c, n), cube(r, c + 1, n))\n\ndef scube_edge_length(r, c, n):\n return vdistance(scube(r, c, n), scube(r, c + 1, n))\n\n#-------------------------------------------------------------------------------\n\ndef write_cube_face(name, n):\n svg = svgroot(w, h)\n\n a = svggroup(svg)\n a.set(\"fill\", \"none\")\n a.set(\"stroke\", \"magenta\")\n draw_cube_face(a, n)\n\n svgwrite(svg, name)\n\ndef write_scube_face(name, n):\n svg = svgroot(w, h)\n\n b = svggroup(svg)\n b.set(\"fill\", \"none\")\n b.set(\"stroke\", \"cyan\")\n draw_scube_face(b, n)\n\n svgwrite(svg, name)\n\ndef write_both_face(name, n):\n svg = svgroot(w, h)\n\n a = svggroup(svg)\n a.set(\"fill\", \"none\")\n a.set(\"stroke\", \"magenta\")\n draw_cube_face(a, n)\n\n b = svggroup(svg)\n b.set(\"fill\", \"none\")\n b.set(\"stroke\", \"cyan\")\n draw_scube_face(b, n)\n\n svgwrite(svg, name)\n\n#-------------------------------------------------------------------------------\n# Compute the ratios of largest to smallest pixel areas\n\ndef report(s, a, b):\n print(s, a, b, a / b)\n\nn = 256\n\ndef grid(n):\n for r in range(0, n-1):\n for c in range(0, n-1):\n yield((r, c))\n\n# report(\"Cube edge length:\",\n# reduce(min, [cube_edge_length(r, c, n) for (r, c) in grid(n)]),\n# reduce(max, [cube_edge_length(r, c, n) for (r, c) in grid(n)]))\n\n# report(\"Scube edge length:\",\n# reduce(min, [scube_edge_length(r, c, n) for (r, c) in grid(n)]),\n# reduce(max, [scube_edge_length(r, c, n) for (r, c) in grid(n)]))\n\n# report(\"Cube sample area:\",\n# reduce(min, [cube_solid_angle(r, c, n) for (r, c) in grid(n)]),\n# reduce(max, [cube_solid_angle(r, c, n) for (r, c) in grid(n)]))\n\n# report(\"Scube sample area:\",\n# reduce(min, [scube_solid_angle(r, c, n) for (r, c) in grid(n)]),\n# reduce(max, [scube_solid_angle(r, c, n) for (r, c) in grid(n)]))\n\n# If these give zero, then each row and column falls along a great circle.\n# Both do.\n\nprint(reduce(max, [vplane(cube(r, 0, n), cube(r, n/2, n), cube(r, n, n))[3] for r in range(0, n+1)]))\nprint(reduce(max, [vplane(scube(r, 0, n), scube(r, n/2, n), scube(r, n, n))[3] for r in range(0, n+1)]))\n\n#-------------------------------------------------------------------------------\n# Draw figures of the cube and scube faces\n\nwrite_cube_face(\"cube.svg\", 16)\nwrite_scube_face(\"scube.svg\", 16)\nwrite_both_face(\"both.svg\", 16)\n","repo_name":"rlk/scmtiff","sub_path":"doc/src/scube.py","file_name":"scube.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"27486588471","text":"import pandas\n\n\ndef load_data(path, features):\n \"\"\"\n This function reads the data from the csv file and load the data to the main memory\n :parameters: path - the path to the csv file, features - list of relevant features that we are interested\n :returns: new_data - the upload data\n \"\"\"\n df = pandas.read_csv(path)\n data = df.to_dict(orient=\"list\")\n # filter the data by relevant features\n new_data = {}\n for feature in features:\n new_data[feature] = data[feature]\n return new_data\n\n\ndef filter_by_feature(data, feature, values):\n \"\"\"\n This function separate the data to two data by values of the feature\n that in the value's set or not in the value's set.\n :parameters: data - dictionary that his keys are the features and the values are lists of the feature's values,\n feature - name of categorical feature,\n values - set of values that the feature can fill the values.\n :returns: data1 - the data with the relevant values, data2 - the data without the relevant values.\n \"\"\"\n # creates the items of dictionaries\n data1 = {}\n data1[\"cnt\"] = []\n data1[\"t1\"] = []\n data1[\"hum\"] = []\n data1[\"season\"] = []\n data1[\"is_holiday\"] = []\n data2 = {}\n data2[\"cnt\"] = []\n data2[\"t1\"] = []\n data2[\"hum\"] = []\n data2[\"season\"] = []\n data2[\"is_holiday\"] = []\n for index, value in enumerate(data[feature]):\n if value in values:\n data1[\"cnt\"].append(data[\"cnt\"][index])\n data1[\"t1\"].append(data[\"t1\"][index])\n data1[\"hum\"].append(data[\"hum\"][index])\n data1[\"season\"].append(data[\"season\"][index])\n data1[\"is_holiday\"].append(data[\"is_holiday\"][index])\n else:\n data2[\"cnt\"].append(data[\"cnt\"][index])\n data2[\"t1\"].append(data[\"t1\"][index])\n data2[\"hum\"].append(data[\"hum\"][index])\n data2[\"season\"].append(data[\"season\"][index])\n data2[\"is_holiday\"].append(data[\"is_holiday\"][index])\n\n return data1, data2\n\n\ndef print_details(data, features, statistic_functions):\n \"\"\"\n This function prints statistics on data only by the features with using the functions in statistic_functions list.\n :parameters: data - dictionary that his keys are the features and the values are lists of the feature's values,\n features - list of features from the data,\n statistic_functions - list of statistic functions from statistics.py\n \"\"\"\n for feature in features:\n print(feature, end=\": \")\n # list of the values we want to print\n value_of_function = []\n for function in statistic_functions:\n value_of_function.append(function(data[feature]))\n print(f\"{value_of_function[0]}, {value_of_function[1]}, {value_of_function[2]}\")\n","repo_name":"ItayBachar1/Homework","sub_path":"Introduction to Data Science/HW1/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5720485819","text":"from communications.satellite_radio import Radio\nfrom drivers.gom import Gomspace\n\nradio = Radio()\ngom = Gomspace()\ntransmissionCounter = 0\n\n#Turn off power amplifier\ngom.set_pa(on=False)\nprint('Power amplifier turned off')\n\n#Set RF transmitting side to low\ngom.rf_transmitting_switch(receive=True)\nprint('RF transmitting set to low')\n\n#Turn on LNA\ngom.lna(True)\nprint('LNA turned on')\n\n#Set RF receiving side to high\ngom.rf_receiving_switch(receive=True)\nprint('RF receiving set to high')\n\nwhile True:\n message = radio.receiveSignal()\n if message is not None:\n print('Transmission #' + transmissionCounter + ' Received: ' + str(message))\n transmissionCounter += 1","repo_name":"Cislunar-Explorers/FlightSoftware6U","sub_path":"HITL-tests/flight_unit_receive.py","file_name":"flight_unit_receive.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"67"} +{"seq_id":"25684799499","text":"#!/usr/bin/env python3\n# coding=utf-8\n\npp = [('Leborn James', 98), ('Kevin Durant', 97), ('James Harden', 96), ('Stephen Curry', 95), ('Anthony Davis', 94)]\n\ns = sorted(list(map(lambda i:i[0].upper(),pp)),reverse=True)\nprint(s)\n\n\n\n'''\n将前面几个高阶函数中作为参数的函数,用 lambda 实现\n使用 lambda 和 map 获取 pp 列表中球员的名字的全大写列表并使用 sorted 函数进行降序排序(一行代码实现)\n>>> pp = [('Leborn James', 98), ('Kevin Durant', 97), ('James Harden', 96), ('Stephen Curry', 95), ('Anthony Davis', 94)]\n期望得到如下结果:\n\n['STEPHEN CURRY', 'LEBORN JAMES', 'KEVIN DURANT', 'JAMES HARDEN', 'ANTHONY DAVIS']\n'''\n","repo_name":"vulmoss/practice","sub_path":"20190720/lambda_sorted.py","file_name":"lambda_sorted.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"18076772104","text":"import json\n\ndef main():\n base_path = path_cfgs.gqa_path + \"questions/\"\n full_path = base_path + \"trainval_all_fully_inputs.json\"\n testdev_path = base_path + \"testdev_balanced_inputs.json\"\n trainval_path = base_path + \"trainval_balanced_inputs.json\"\n subm_path = base_path + \"submission_inputs.json\"\n \n annos_full = json.load(open(full_path, 'r'))\n annos_subm = json.load(open(subm_path, 'r'))\n annos_trainval = json.load(open(trainval_path, 'r'))\n annos_testdev = json.load(open(testdev_path, 'r'))\n\n # annos = annos_full\n annos = annos_trainval + annos_testdev + annos_full + annos_subm\n\n print(len(annos))\n\n vocab = {}\n vocab[\"[PAD]\"] = 0\n vocab[\"[EOS]\"] = 1\n vocab[\"[UNK]\"] = 2\n vocab[\"[SOS]\"] = 3\n for idx, ann in enumerate(annos):\n prog = ann[3]\n for p in prog: \n for i in range(1, len(p)):\n if p[i] is not None:\n if p[i] not in vocab:\n vocab[p[i]] = len(vocab)\n\n print(len(vocab))\n\n output = './full_vocab_gqa_all.json'\n with open(output, 'w') as f:\n json.dump(vocab, f)\n\nif __name__ == \"__main__\":\n main()","repo_name":"FujitsuResearch/transformer_module_networks","sub_path":"make_vocab.py","file_name":"make_vocab.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72282534292","text":"from .trainer import Trainer\nimport numpy as np\nimport torch.nn.functional as F\nimport torch\nfrom copy import deepcopy\n\n\nclass Client(object):\n def __init__(self, client_idx, nTrain, local_train_data, local_test_data, model, args):\n \"\"\"\n A client\n ---\n Args\n client_idx: index of the client\n nTrain: number of train dataset of the client\n local_train_data: train dataset of the client\n local_test_data: test dataset of the client\n model: given model for the client\n args: arguments for overall FL training\n \"\"\"\n self.client_idx = client_idx\n self.test_data = local_test_data\n self.device = args.device\n self.trainer = Trainer(model, args)\n self.num_epoch = args.num_epoch # E: number of local epoch\n self.nTrain = nTrain\n self.loss_div_sqrt = args.loss_div_sqrt\n self.loss_sum = args.loss_sum\n\n self.labeled_indices = [*range(nTrain)]\n self.labeled_data = local_train_data # train_data\n\n\n def train(self, global_model):\n \"\"\"\n train each client\n ---\n Args\n global_model: given current global model\n Return\n result = model, loss, acc\n \"\"\"\n # SET MODEL\n self.trainer.set_model(global_model)\n\n # TRAIN\n if self.num_epoch == 0: # no SGD updates\n result = self.trainer.train_E0(self.labeled_data)\n else:\n result = self.trainer.train(self.labeled_data)\n #result['model'] = self.trainer.get_model()\n\n # total loss / sqrt (# of local data)\n if self.loss_div_sqrt: # total loss / sqrt (# of local data)\n result['metric'] *= np.sqrt(len(self.labeled_data)) # loss * n_k / np.sqrt(n_k)\n elif self.loss_sum:\n result['metric'] *= len(self.labeled_data) # total loss\n \n return result\n\n def test(self, model, test_on_training_data=False):\n # TEST\n if test_on_training_data:\n # test on training dataset\n result = self.trainer.test(model, self.labeled_data)\n else:\n # test on test dataset\n result = self.trainer.test(model, self.test_data)\n return result\n\n def get_client_idx(self):\n return self.client_idx","repo_name":"euphoria0-0/Active-Client-Selection-for-Communication-efficient-Federated-Learning","sub_path":"src/FL_core/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"67"} +{"seq_id":"7081580092","text":"#leetcode : Remove Duplicate Letters\n# Input: s = \"bcabc\"\n# Output: \"abc\"\n# Input: s = \"bcab\"\n# Output: \"bca\"\n\ndef remove_dup(s):\n count = {}\n vis = set()\n st = []\n\n for c in s:\n if c not in count:\n count[c] = 0\n count[c] +=1\n \n for c in s:\n if c not in vis:\n while st and st[-1] > c and count[st[-1]] > 0:\n vis.remove(st.pop())\n st.append(c)\n vis.add(c)\n count[c] -=1\n st = ''.join(st)\n return st\n\n\ns = \"bcabc\"\nprint(remove_dup(s))","repo_name":"ngtuetam/dsa-notes","sub_path":"strings/remove_duplicate_letters.py","file_name":"remove_duplicate_letters.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13610678087","text":"#!/usr/bin/env python3\n\n\"\"\"\nA prototype floor-layout generating application, developed as a part\nof the \"Semantic-driven graph transformations in floor plan design\"\nresearch paper.\n\"\"\"\n\nimport neo4j, cairo\n\nfrom sys import argv, stdout\nfrom math import ceil\nfrom random import choice, randint, shuffle\nfrom collections import namedtuple\nfrom types import SimpleNamespace\n\nFontExtents = namedtuple('FontExtents', 'ascent descent height max_x_advance max_y_advance')\n\nclass GraphGrammar:\n \"\"\"\n Base class for grammars which transform Neo4j graphs.\n \"\"\"\n\n def __init__(self, driver):\n self.driver = driver\n self.db = None\n\n def dump_graph(self, flog=stdout):\n flog.write('dumping nodes and relationships...\\n')\n with self.driver.session() as sess:\n res = sess.run('MATCH (n) RETURN n')\n for r in res:\n flog.write(repr(r[0]))\n flog.write('\\n')\n res.consume()\n res = sess.run('MATCH () -[r]-> () RETURN r')\n for r in res:\n flog.write(repr(r[0]))\n flog.write('\\n')\n res.consume()\n flog.write('... done\\n')\n\n def query(self, q, *args, **kwargs):\n q = q.strip()\n with self.driver.session() as sess:\n result = sess.run(q, *args, **kwargs)\n records = [ r for r in result ]\n result.consume()\n return records\n\n def create_start_graph(self):\n self.query('CREATE ()')\n return 'initial vertex created'\n\n def generate(self, flog=stdout, on_change=None):\n # Find methods which implement grammar rules.\n rules = list()\n for s in dir(self):\n if s.startswith('rule_'):\n m = getattr(self, s, None)\n if callable(m):\n rules.append( (s[5:], m) )\n if len(rules) == 0:\n raise RuntimeError('this grammar has no rules')\n # Initialize the database.\n self.query('MATCH (n) DETACH DELETE n')\n msg = self.create_start_graph()\n flog.write('start_graph: {}\\n'.format(msg))\n if on_change is not None:\n on_change()\n # Apply randomly chosen rules.\n candidates = list(rules)\n while len(candidates) > 0:\n i = randint(0, len(candidates) - 1)\n (name, meth) = candidates[i]\n del candidates[i]\n msg = meth()\n if msg is None:\n flog.write('{}: no match found\\n'.format(name))\n else:\n flog.write('{}: {}\\n'.format(name, msg))\n if on_change is not None:\n on_change()\n candidates = list(rules)\n flog.write('done: no rule can be applied\\n')\n\n\nclass FloorLayoutGrammar(GraphGrammar):\n \"\"\"\n Base class providing helper methods used to implement floor-layout\n rules. Layout visualization methods are defined here, too.\n\n Every rectangular area corresponds to a CP-graph vertex with four\n bonds, which in turn corresponds to five nodes in the database. One\n node represents the area as a whole. It is connected by relations\n named b1 ... b4 to four bond nodes representing its walls, starting\n with the northern wall and proceeding clockwise.\n\n Bond nodes belonging to two different areas can be connected\n by relations named acc, adj or emb. Which bond is the source and\n which is the target does not matter, because these relations are\n undirected from the semantic point of view.\n\n Every bond node has attributes storing wall endpoints' locations,\n with x1 <= x2 and y1 <= y2. A standard Cartesian coordinate system\n with X axis pointed rightward and Y axis going up is used. Up is\n north, right is east, etc.\n \"\"\"\n\n def __init__(self, driver, layout_width=10, layout_height=10, **kwargs):\n super().__init__(driver)\n self.layout_width = int(layout_width)\n self.layout_height = int(layout_height)\n self.drawing_parameters = SimpleNamespace()\n self.drawing_parameters.__dict__.update(self.default_drawing_parameters.__dict__)\n self.drawing_parameters.__dict__.update(**kwargs)\n\n def query_match_rect(self, label=None, condition=None):\n \"\"\"\n Find areas with a given label, which fulfill a given condition.\n Label and/or condition can be left unspecified. If given, the\n condition needs to be a valid Neo4j boolean expression, which\n can use identifiers n b1 b2 b3 b4 to refer to the matched nodes.\n\n Returns a list of records with five fields: n (which includes\n n.id), llx, lly, urx, ury.\n \"\"\"\n\n if label is not None:\n s1 = ':`' + label + '`'\n else:\n s1 = ''\n if condition is not None:\n s2 = 'WHERE ' + condition + '\\n'\n else:\n s2 = ''\n return self.query('''\nMATCH (n{0}),\n (n) -[:b1]-> (b1:bond), (n) -[:b2]-> (b2:bond),\n (n) -[:b3]-> (b3:bond), (n) -[:b4]-> (b4:bond)\n{1}RETURN n, b3.x1, b3.y1, b1.x2, b1.y2\n '''.format(s1, s2))\n\n def query_delete_rect(self, main_node_id):\n return self.query('''\nMATCH (n),\n (n) -[:b1]-> (b1:bond), (n) -[:b2]-> (b2:bond),\n (n) -[:b3]-> (b3:bond), (n) -[:b4]-> (b4:bond)\nWHERE ID(n) = {i}\nDETACH DELETE n, b1, b2, b3, b4\n ''', i=main_node_id)\n\n NodeAndBondIds = namedtuple('NodeAndBondIds', ['id', 'b1_id', 'b2_id', 'b3_id', 'b4_id'])\n\n def query_create_rect(self, label, llx, lly, urx, ury):\n rs = self.query('''\nCREATE (n:`{label}` {{ area: ({urx} - {llx}) * ({ury} - {lly}) }}),\n (n) -[:b1]-> (b1:bond {{ x1: {llx}, y1: {ury}, x2: {urx}, y2: {ury} }}),\n (n) -[:b2]-> (b2:bond {{ x1: {urx}, y1: {lly}, x2: {urx}, y2: {ury} }}),\n (n) -[:b3]-> (b3:bond {{ x1: {llx}, y1: {lly}, x2: {urx}, y2: {lly} }}),\n (n) -[:b4]-> (b4:bond {{ x1: {llx}, y1: {lly}, x2: {llx}, y2: {ury} }})\nRETURN ID(n), ID(b1), ID(b2), ID(b3), ID(b4)\n '''.format(label=label, llx=llx, lly=lly, urx=urx, ury=ury))\n return self.NodeAndBondIds( *(rs[0]) )\n\n def query_create_edge(self, label, source_id, destination_id):\n self.query('''\nMATCH (n), (m)\nWHERE ID(n) = {i} AND ID(m) = {j}\nCREATE (n) -[:{t}]-> (m)\n '''.format(t=label, i=source_id, j=destination_id))\n\n def query_embed_eastern(self, old_rect_id, new_rect_id):\n \"\"\"\n Embed the eastern bond of the newly created sub-area by\n connecting it to selected bonds of the original area's\n context.\n\n To do that, first find relations connecting the eastern bond\n of the original area to western bonds of other areas (this\n implies that these other areas are geometrically adjacent).\n These bonds are the context. Then, check which context bonds\n are overlapping (in the geometric sense) the eastern bond of\n the new area, and create \"emb\" relations connecting them to\n this newly created bond.\n\n This method assumes that the sub-area given as the argument is\n on the eastern side of the original area, it does not verify\n this fact (which could be done by checking if in all bonds\n attributes x1 and x2 have a single, identical value).\n \"\"\"\n\n self.query('''\nMATCH (old) -[:b2]-> (old2:bond) -- (ctx4:bond),\n (new) -[:b2]-> (new2:bond)\nWHERE ID(old) = {0} AND ID(new) = {1} AND\n NOT (new2.y2 <= ctx4.y1 OR new2.y1 >= ctx4.y2)\nCREATE (new2) -[:emb]-> (ctx4)\nRETURN ID(ctx4)\n '''.format(old_rect_id, new_rect_id))\n\n def query_embed_western(self, old_rect_id, new_rect_id):\n \"\"\"See query_embed_eastern().\"\"\"\n\n self.query('''\nMATCH (old) -[:b4]-> (old4:bond) -- (ctx2:bond),\n (new) -[:b4]-> (new4:bond)\nWHERE ID(old) = {0} AND ID(new) = {1} AND\n NOT (new4.y2 <= ctx2.y1 OR new4.y1 >= ctx2.y2)\nCREATE (new4) -[:emb]-> (ctx2)\nRETURN ID(ctx2)\n '''.format(old_rect_id, new_rect_id))\n\n\n def create_start_graph(self):\n self.query_create_rect('S', 0, 0, self.layout_width, self.layout_height)\n return 'initial area created, size {0} x {1} units'.format(\n self.layout_width, self.layout_height)\n\n # --------------------------------------------------------------------------------------------\n\n default_drawing_parameters = SimpleNamespace(\n layout_unit = 18, # 18 pt == 1/4 in == 6.35 mm\n line_width = 0.5,\n font_size = 7,\n page_margin = 1,\n room_padding = 0,\n draw_doors = True,\n draw_potential_doors = True,\n door_halfwidth = 6,\n doorjamb_halfdepth = 2,\n draw_edges = False,\n draw_grid = False)\n\n def save_pdf(self, fname):\n self.__create_pdf_surface(fname)\n self.__draw_page(self.__pdf_context)\n self.__pdf_surface.show_page()\n self.__destroy_pdf_surface()\n\n def __create_pdf_surface(self, fname):\n u = self.drawing_parameters.layout_unit\n m = self.drawing_parameters.page_margin\n self.__pdf_surface = cairo.PDFSurface(fname, self.layout_width * u + 2 * m, self.layout_height * u + 2 * m)\n self.__pdf_context = self.__make_context(self.__pdf_surface)\n\n def __destroy_pdf_surface(self):\n del self.__pdf_context\n self.__pdf_surface.finish()\n del self.__pdf_surface\n\n def save_png(self, fname, ppi=72):\n self.__create_img_surface(ppi)\n self.__draw_page(self.__img_context)\n self.__img_surface.write_to_png(fname)\n self.__destroy_img_surface()\n\n def __create_img_surface(self, ppi, color=(1, 1, 1)):\n scale = ppi / 72.0\n u = self.drawing_parameters.layout_unit\n m = self.drawing_parameters.page_margin\n self.__img_surface = cairo.ImageSurface(cairo.FORMAT_RGB24,\n ceil(scale * (self.layout_width * u + 2 * m)),\n ceil(scale * (self.layout_height * u + 2 * m)))\n self.__img_context = self.__make_context(self.__img_surface, scale=scale, paint_color=color)\n\n def __destroy_img_surface(self):\n del self.__img_context\n del self.__img_surface\n\n def __make_context(self, surface, scale=1.0, paint_color=None):\n ctx = cairo.Context(surface)\n if scale != 1.0:\n ctx.scale(scale, scale)\n if paint_color is not None:\n ctx.set_source_rgb(*paint_color)\n ctx.paint()\n ctx.set_source_rgb(0, 0, 0)\n ctx.set_line_width(self.drawing_parameters.line_width)\n return ctx\n\n def generate_and_multipage_save(self, fbase, ppi=72, **kwargs):\n self.__multipage_fbase = fbase\n self.__multipage_ppi = ppi\n self.__multipage_no = 0\n self.__create_pdf_surface(fbase + '.pdf')\n self.generate(on_change=self.__multipage_callback, **kwargs)\n self.__destroy_pdf_surface()\n\n def __multipage_callback(self):\n self.__draw_page(self.__pdf_context)\n self.__pdf_surface.show_page()\n self.__multipage_no += 1\n fname = self.__multipage_fbase + '-' + str(self.__multipage_no) + '.png'\n self.save_png(fname, self.__multipage_ppi)\n\n def __draw_page(self, ctx):\n\n def layout2cairo(x, y):\n p = self.drawing_parameters\n return (p.page_margin + x * p.layout_unit,\n p.page_margin + (self.layout_height - y) * p.layout_unit)\n\n # Get rectangle nodes, store them for later processing.\n rooms = { }\n rs = self.query('''\nMATCH (b1:bond) <-[:b1]- (n) -[:b3]-> (b3:bond)\nRETURN n, b3.x1, b3.y1, b1.x2, b1.y2\n ''')\n for r in rs:\n assert len(r[0].labels) == 1\n assert r[0].id not in rooms\n rooms[ r[0].id ] = SimpleNamespace(\n n = r[0],\n label = [ x for x in r[0].labels ][0],\n llx = r[1],\n lly = r[2],\n urx = r[3],\n ury = r[4])\n\n # Get bond-bond relations and their associated nodes, calculate and store\n # wall segments shared by adjacent rooms.\n segments_acc = [ ]\n segments_adj = [ ]\n segments_emb = [ ]\n rs = self.query('''\nMATCH (n) --> (b:bond) -[e]-> (c:bond) <-- (m)\nWHERE NOT 'bond' IN labels(n) AND NOT 'bond' IN labels(m)\nRETURN type(e), b, c, n, m\n ''')\n for (rel, b, c, n, m) in rs:\n llx = max(b['x1'], c['x1'])\n lly = max(b['y1'], c['y1'])\n urx = min(b['x2'], c['x2'])\n ury = min(b['y2'], c['y2'])\n assert (llx == urx and lly < ury) or (lly == ury and llx < urx)\n segment = SimpleNamespace(\n rel = rel,\n between = { n.id, m.id },\n llx = llx,\n lly = lly,\n urx = urx,\n ury = ury)\n if rel == 'acc':\n segments_acc.append(segment)\n elif rel == 'adj':\n segments_adj.append(segment)\n elif rel == 'emb':\n segments_emb.append(segment)\n else:\n assert False\n\n # Draw background grid.\n if self.drawing_parameters.draw_grid:\n ctx.save()\n ctx.set_source_rgb(0.9, 0.9, 0.9)\n for i in range(self.layout_width + 1):\n ctx.move_to( *layout2cairo(i, 0) )\n ctx.line_to( *layout2cairo(i, self.layout_height) )\n for i in range(self.layout_height + 1):\n ctx.move_to( *layout2cairo(0, i) )\n ctx.line_to( *layout2cairo(self.layout_width, i) )\n ctx.stroke()\n ctx.restore()\n\n def draw_door_list(doors, wdx, wdy, jdx, jdy, offx, offy, north=False):\n for i in range(len(doors)):\n (x, y) = layout2cairo(doors[i].x, doors[i].y)\n if i > 0 or not north:\n ctx.line_to(x - wdx + offx, y - wdy + offy)\n ctx.line_to(x - wdx + jdx + offx, y - wdy + jdy + offy)\n ctx.move_to(x + wdx + jdx + offx, y + wdy + jdy + offy)\n ctx.line_to(x + wdx + offx, y + wdy + offy)\n\n # Draw walls with door openings (if the drawing parameters allow).\n if self.drawing_parameters.draw_doors:\n for room in rooms.values():\n north_doors = [ ]\n east_doors = [ ]\n south_doors = [ ]\n west_doors = [ ]\n for s in segments_acc:\n if room.n.id in s.between:\n d = SimpleNamespace(\n x = (s.llx + s.urx) / 2.0,\n y = (s.lly + s.ury) / 2.0)\n if d.y == room.ury:\n north_doors.append(d)\n elif d.x == room.urx:\n east_doors.append(d)\n elif d.y == room.lly:\n south_doors.append(d)\n elif d.x == room.llx:\n west_doors.append(d)\n else:\n assert False\n # Sort door lists in the drawing order.\n north_doors.sort(key=lambda d: d.x)\n east_doors.sort(key=lambda d: -d.y)\n south_doors.sort(key=lambda d: -d.x)\n west_doors.sort(key=lambda d: d.y)\n # Drawing algorithm starts with the northern wall...\n o = self.drawing_parameters.room_padding\n w = self.drawing_parameters.door_halfwidth\n j = self.drawing_parameters.doorjamb_halfdepth\n if len(north_doors) == 0:\n (x, y) = layout2cairo((room.llx + room.urx) / 2.0, room.ury)\n ctx.move_to(x, y + o)\n else:\n draw_door_list(north_doors, w, 0, 0, j, 0, o, north=True)\n (x, y) = layout2cairo(room.urx, room.ury)\n ctx.line_to(x - o, y + o)\n # ... then line continues along the eastern wall, ...\n draw_door_list(east_doors, 0, w, -j, 0, -o, 0)\n (x, y) = layout2cairo(room.urx, room.lly)\n ctx.line_to(x - o, y - o)\n # ... southern, ...\n draw_door_list(south_doors, -w, 0, 0, -j, 0, -o)\n (x, y) = layout2cairo(room.llx, room.lly)\n ctx.line_to(x + o, y - o)\n # ... western, ...\n draw_door_list(west_doors, 0, -w, j, 0, o, 0)\n (x, y) = layout2cairo(room.llx, room.ury)\n ctx.line_to(x + o, y + o)\n # ... and back to northern.\n if len(north_doors) == 0:\n # 3/4 instead of 1/2, because last line segment needs to overlap the first.\n (x, y) = layout2cairo((room.llx + 3 * room.urx) / 4.0, room.ury)\n ctx.line_to(x, y + o)\n else:\n (x, y) = layout2cairo(north_doors[0].x, north_doors[0].y)\n ctx.line_to(x - w, y + o)\n ctx.line_to(x - w, y + j + o)\n ctx.stroke()\n\n # Draw rhombuses where door openings may be created by the designer.\n if self.drawing_parameters.draw_potential_doors:\n o = self.drawing_parameters.room_padding\n w = self.drawing_parameters.door_halfwidth\n j = self.drawing_parameters.doorjamb_halfdepth\n for s in segments_emb:\n x = (s.llx + s.urx) / 2.0\n y = (s.lly + s.ury) / 2.0\n (x, y) = layout2cairo(x, y)\n if s.lly == s.ury:\n # horizontal wall segment\n ctx.move_to(x - w, y - o)\n ctx.line_to(x, y - j - o)\n ctx.line_to(x + w, y - o)\n ctx.line_to(x + w, y + o)\n ctx.line_to(x, y + j + o)\n ctx.line_to(x - w, y + o)\n ctx.close_path()\n else:\n ctx.move_to(x + o, y - w)\n ctx.line_to(x + j + o, y)\n ctx.line_to(x + o, y + w)\n ctx.line_to(x - o, y + w)\n ctx.line_to(x - j - o, y)\n ctx.line_to(x - o, y - w)\n ctx.close_path()\n # ctx.save()\n # ctx.set_source_rgb(0.7, 0.7, 1.0)\n # ctx.fill_preserve()\n # ctx.restore()\n ctx.stroke()\n\n # Draw room/area labels using Cairo toy text API, and if the drawing parameters hide doors\n # then draw continuous walls, too.\n ctx.select_font_face('Bitstream Vera Serif', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)\n ctx.set_font_size(self.drawing_parameters.font_size)\n font_ext = FontExtents._make( ctx.font_extents() )\n for r in rooms.values():\n label = r.label\n area = str(r.n['area']) + ' m²'\n # Note: Cairo has the Y axis pointing down, \"lower left\" and \"upper right\" corners\n # will be different, data from the graph model needs to be converted!\n (llx, ury) = layout2cairo(r.llx, r.lly)\n (urx, lly) = layout2cairo(r.urx, r.ury)\n if not self.drawing_parameters.draw_doors:\n o = self.drawing_parameters.room_padding\n ctx.rectangle(llx + o, lly + o, urx - llx - 2 * o, ury - lly - 2 * o)\n ctx.stroke()\n te1 = ctx.text_extents(label)\n te2 = ctx.text_extents(area)\n x_text = (llx + urx) / 2.0\n y_text = (lly + ury) / 2.0 - 0.25 * font_ext.height\n ctx.move_to(x_text - te1.x_advance / 2.0, y_text)\n ctx.show_text(label)\n y_text += 1.1 * font_ext.height\n ctx.move_to(x_text - te2.x_advance / 2.0, y_text)\n ctx.show_text(area)\n\n def draw_relation(seg):\n x = (seg.llx + seg.urx) / 2.0\n y = (seg.lly + seg.ury) / 2.0\n (x, y) = layout2cairo(x, y)\n if seg.lly == seg.ury:\n # horizontal wall segment => vertical line\n ctx.move_to(x, y - 0.3 * self.drawing_parameters.layout_unit)\n ctx.rel_line_to(0, 0.6 * self.drawing_parameters.layout_unit)\n else:\n ctx.move_to(x - 0.3 * self.drawing_parameters.layout_unit, y)\n ctx.rel_line_to(0.6 * self.drawing_parameters.layout_unit, 0)\n ctx.stroke()\n\n # Draw semi-transparent lines representing relations.\n if self.drawing_parameters.draw_edges:\n ctx.save()\n ctx.set_line_width(0.2 * self.drawing_parameters.layout_unit)\n ctx.set_line_cap(cairo.LINE_CAP_ROUND)\n for s in segments_acc:\n ctx.set_source_rgba(0.0, 1.0, 0.0, 0.5)\n draw_relation(s)\n for s in segments_adj:\n ctx.set_source_rgba(1.0, 0.0, 0.0, 0.5)\n draw_relation(s)\n for s in segments_emb:\n ctx.set_source_rgba(1.0, 1.0, 0.0, 0.5)\n draw_relation(s)\n ctx.restore()\n\n\nclass ExampleGrammar(FloorLayoutGrammar):\n \"\"\"\n A working example of a floor layout grammar, which implements graph\n rules displayed in Fig. 7 in the paper. All methods follow the same\n sequence of steps:\n\n 1) Find a match for rule's left-hand side and remember it for\n later. In this grammar all rules have a single area as their LHS;\n remembering a single reference to the Neo4j node representing\n this area is sufficient.\n\n 2) Determine dimensions of sub-areas. Do it at random, but ensure\n that resulting areas won't be too small.\n\n 3) Create nodes for areas and bonds on the RHS. Create relations\n representing connections between them as specified by the RHS.\n\n 4) Embed newly created sub-areas, that is, connect each new area\n to areas which were geometrically adjacent to the original matched\n area and are adjacent to this sub-area.\n\n 5) Remove five nodes which represent the matched area and its bonds,\n and remove relations incident to these five nodes.\n\n Step (4) is implemented in a simplified way. Since the grammar is\n very simple, it is obvious that, for example, a recreation area\n will never have any northern, southern or western neighbours. So,\n in rules which divide a recreation area, embedding is done only\n on the eastern side.\n \"\"\"\n\n def rule_p1(self):\n \"\"\"\n Split S into two rooms sandwiched between two areas.\n \"\"\"\n\n # Minimum and maximum rectangle sizes, etc:\n rec_xsize_min = 3\n hall_xsize = 2\n slp_xsize_min = 3\n kit_ysize_min = 2\n kit_ysize_max = 4\n xsize_min = rec_xsize_min + hall_xsize + slp_xsize_min\n ysize_min = 1 + kit_ysize_min\n\n # Find the starting area/rectangle:\n cond = 'b1.x2 - b1.x1 >= {0} AND b2.y2 - b2.y1 >= {1}'.format(xsize_min, ysize_min)\n rs = self.query_match_rect('S', cond)\n if len(rs) == 0:\n return None\n (s, llx, lly, urx, ury) = choice(rs)\n\n # Calculate output rectangle sizes in the X direction:\n xsize = urx - llx\n extra = xsize - xsize_min\n rec_xsize = rec_xsize_min + randint(0, extra)\n slp_xsize = xsize - rec_xsize - hall_xsize\n # ... and in the Y direction:\n ysize = ury - lly\n extra = ysize - 1 - kit_ysize_min\n kit_ysize = kit_ysize_min + randint(0, min(extra, kit_ysize_max - kit_ysize_min))\n hal_ysize = ysize - kit_ysize\n\n # Create replacement subrectangles:\n ra = self.query_create_rect('Recreation area', llx, lly, llx + rec_xsize, ury)\n h = self.query_create_rect('hall', llx + rec_xsize, lly, urx - slp_xsize, lly + hal_ysize)\n k = self.query_create_rect('kitchen', llx + rec_xsize, ury - kit_ysize, urx - slp_xsize, ury)\n sa = self.query_create_rect('Sleeping area', urx - slp_xsize, lly, urx, ury)\n self.query_create_edge('adj', ra.b2_id, h.b4_id)\n self.query_create_edge('adj', ra.b2_id, k.b4_id)\n self.query_create_edge('acc', h.b1_id, k.b3_id)\n self.query_create_edge('adj', sa.b4_id, h.b2_id)\n self.query_create_edge('adj', sa.b4_id, k.b2_id)\n\n # No embedding required because S has no neighbours.\n\n # Remove the original rectangle:\n self.query_delete_rect(s.id)\n\n return 'sub-areas created, cuts at X={0}, X={1}, Y={2}'.format(\n llx + rec_xsize, urx - slp_xsize, lly + hal_ysize)\n\n def rule_p2(self):\n \"\"\"\n Split a sleeping area (sa) into a bedroom (bed1), a bathroom\n (bath) and another bedroom (bed2).\n \"\"\"\n\n bed_ysize_min = 2\n bath_ysize_min = 1\n bath_ysize_max = 2\n ysize_min = 2 * bed_ysize_min + bath_ysize_min\n\n rs = self.query_match_rect('Sleeping area', 'b2.y2 - b2.y1 >= {0}'.format(ysize_min))\n if len(rs) == 0:\n return None\n (sa, llx, lly, urx, ury) = choice(rs)\n\n extra = (ury - lly) - 2 * bed_ysize_min - bath_ysize_min\n bath_ysize = bath_ysize_min + randint(0, min(extra, bath_ysize_max - bath_ysize_min))\n extra = (ury - lly) - 2 * bed_ysize_min - bath_ysize\n bed1_ysize = bed_ysize_min + randint(0, extra)\n\n bed1 = self.query_create_rect('bedroom', llx, lly, urx, lly + bed1_ysize)\n bath = self.query_create_rect('bathroom', llx, lly + bed1_ysize, urx, lly + bed1_ysize + bath_ysize)\n bed2 = self.query_create_rect('bedroom', llx, lly + bed1_ysize + bath_ysize, urx, ury)\n self.query_create_edge('acc', bed1.b1_id, bath.b3_id)\n self.query_create_edge('adj', bath.b1_id, bed2.b3_id)\n\n self.query_embed_western(sa.id, bed1.id)\n self.query_embed_western(sa.id, bath.id)\n self.query_embed_western(sa.id, bed2.id)\n\n self.query_delete_rect(sa.id)\n\n return 'sub-areas created, cuts at Y={0}, Y={1}'.format(\n lly + bed1_ysize, lly + bed1_ysize + bath_ysize)\n\n def rule_p3(self):\n \"\"\"\n Split a sleeping area (sa) into a bathroom (bath) and a bedroom\n (bed).\n \"\"\"\n\n bed_ysize_min = 2\n bath_ysize_min = 1\n bath_ysize_max = 2\n ysize_min = bed_ysize_min + bath_ysize_min\n\n rs = self.query_match_rect('Sleeping area', 'b2.y2 - b2.y1 >= {0}'.format(ysize_min))\n if len(rs) == 0:\n return None\n (sa, llx, lly, urx, ury) = choice(rs)\n\n extra = (ury - lly) - bed_ysize_min - bath_ysize_min\n bath_ysize = bath_ysize_min + randint(0, min(extra, bath_ysize_max - bath_ysize_min))\n\n bath = self.query_create_rect('bathroom', llx, lly, urx, lly + bath_ysize)\n bed = self.query_create_rect('bedroom', llx, lly + bath_ysize, urx, ury)\n self.query_create_edge('adj', bath.b1_id, bed.b3_id)\n\n self.query_embed_western(sa.id, bath.id)\n self.query_embed_western(sa.id, bed.id)\n\n self.query_delete_rect(sa.id)\n\n return 'sub-areas created, cut at Y={0}'.format(lly + bath_ysize)\n\n def rule_p4(self):\n \"\"\"\n Split a recreation area (ra) into a living room (liv) and\n a terrace (ter).\n \"\"\"\n\n liv_ysize_min = 2\n ter_ysize_min = 1\n ter_ysize_max = 3\n ysize_min = liv_ysize_min + ter_ysize_min\n\n rs = self.query_match_rect('Recreation area', 'b2.y2 - b2.y1 >= {}'.format(ysize_min))\n if len(rs) == 0:\n return None\n (ra, llx, lly, urx, ury) = choice(rs)\n\n extra = (ury - lly) - liv_ysize_min - ter_ysize_min\n ter_ysize = ter_ysize_min + randint(0, min(extra, ter_ysize_max - ter_ysize_min))\n\n liv = self.query_create_rect('living room', llx, lly, urx, ury - ter_ysize)\n ter = self.query_create_rect('terrace', llx, ury - ter_ysize, urx, ury)\n self.query_create_edge('acc', liv.b1_id, ter.b3_id)\n\n self.query_embed_eastern(ra.id, liv.id)\n self.query_embed_eastern(ra.id, ter.id)\n\n self.query_delete_rect(ra.id)\n\n return 'sub-areas created, cut at Y={}'.format(ury - ter_ysize)\n\n def rule_p5(self):\n \"\"\"\n Split a recreation area (ra) into a living room (liv), a dining\n room (din) and a terrace (ter).\n \"\"\"\n\n liv_ysize_min = 2\n din_ysize_min = 2\n ter_ysize_min = 1\n ter_ysize_max = 3\n ysize_min = liv_ysize_min + din_ysize_min + ter_ysize_min\n\n rs = self.query_match_rect('Recreation area', 'b2.y2 - b2.y1 >= {}'.format(ysize_min))\n if len(rs) == 0:\n return None\n (ra, llx, lly, urx, ury) = choice(rs)\n\n extra = (ury - lly) - liv_ysize_min - din_ysize_min - ter_ysize_min\n ter_ysize = ter_ysize_min + randint(0, min(extra, ter_ysize_max - ter_ysize_min))\n extra = (ury - lly) - liv_ysize_min - din_ysize_min - ter_ysize\n liv_ysize = liv_ysize_min + randint(0, extra)\n\n liv = self.query_create_rect('living room', llx, lly, urx, lly + liv_ysize)\n din = self.query_create_rect('dining room', llx, lly + liv_ysize, urx, ury - ter_ysize)\n ter = self.query_create_rect('terrace', llx, ury - ter_ysize, urx, ury)\n self.query_create_edge('acc', liv.b1_id, din.b3_id)\n self.query_create_edge('acc', din.b1_id, ter.b3_id)\n\n self.query_embed_eastern(ra.id, liv.id)\n self.query_embed_eastern(ra.id, din.id)\n self.query_embed_eastern(ra.id, ter.id)\n\n self.query_delete_rect(ra.id)\n\n return 'sub-areas created, cuts at Y={0}, Y={1}'.format(\n lly + liv_ysize, ury - ter_ysize)\n\n def rule_p6(self):\n \"\"\"\n Split a recreation area (ra) into a living room (liv) and\n a dining room (din).\n \"\"\"\n\n # Minimum acceptable rectangle dimensions in the Y direction:\n liv_ysize_min = 2\n din_ysize_min = 2\n ysize_min = liv_ysize_min + din_ysize_min\n\n # Find a rectangle representing a recreation area:\n rs = self.query_match_rect('Recreation area', 'b2.y2 - b2.y1 >= {}'.format(ysize_min))\n if len(rs) == 0:\n return None\n (ra, llx, lly, urx, ury) = choice(rs)\n\n # Pick the living room's Y-dimension:\n extra = (ury - lly) - liv_ysize_min - din_ysize_min\n liv_ysize = liv_ysize_min + randint(0, extra)\n\n # Create replacement rectangles and edges:\n liv = self.query_create_rect('living room', llx, lly, urx, lly + liv_ysize)\n din = self.query_create_rect('dining room', llx, lly + liv_ysize, urx, ury)\n self.query_create_edge('acc', liv.b1_id, din.b3_id)\n\n # Embed newly created rectangles:\n self.query_embed_eastern(ra.id, liv.id)\n self.query_embed_eastern(ra.id, din.id)\n\n # Remove the original rectangle and its incident edges:\n self.query_delete_rect(ra.id)\n\n return 'sub-areas created, cut at Y={0}'.format(lly + liv_ysize)\n\n\ndef main():\n driver = neo4j.Driver('bolt://localhost:7687', auth=('neo4j', 'neo4j'))\n g = ExampleGrammar(driver, draw_grid=True)\n # g = ExampleGrammar(driver, room_padding=1, draw_edges=True)\n with open('deriv.log', 'w') as f:\n g.generate_and_multipage_save('deriv', ppi=288, flog=f)\n # f.write('\\n')\n # g.dump_graph(flog=f)\n g.save_pdf('final.pdf')\n g.save_png('final.png', ppi=288)\n driver.close()\n\nif __name__ == '__main__':\n main()\n","repo_name":"palacz-uj/flgen2021","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":31578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"8308150152","text":"import os\nimport tempfile\nimport unittest\nfrom unittest.mock import patch\nimport subprocess\nimport shutil\n\nfrom scripts.import_sd.workflow import Workflow\nfrom scripts.import_sd.photo import Photo\nfrom scripts.import_sd.validator import Validator\nfrom scripts.import_sd.sd import SDCard\nfrom scripts.import_sd.queue import Queue\nfrom scripts.import_sd.operations import CopyOperation\n\nclass TestWorkflow(unittest.TestCase):\n\tdef setUp(self):\n\t\t# Paths\n\t\tself.data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')\n\t\tself.test_data_path = os.path.join(self.data_path, 'test_data')\n\t\tself.sample_image_path = os.path.join(self.data_path, \"_ARW_2544.arw\")\n\t\tself.sd_card_path = os.path.join(self.test_data_path, 'sd_card')\n\t\tself.base_path = os.path.join(self.test_data_path, 'network')\n\t\tself.jpg_path = os.path.join(self.test_data_path, 'jpgs')\n\t\tself.empty_path = os.path.join(self.test_data_path, 'empty')\n\t\tself.backup_path = os.path.join(self.test_data_path, 'backup_network')\n\t\tself.list_path = os.path.join(self.test_data_path, 'file_list.txt')\n\t\t\n\t\t# Ensure sd_card_path, network_path and backup_network_path all exist\n\t\tos.makedirs(self.data_path, exist_ok=True)\n\t\tos.makedirs(self.test_data_path, exist_ok=True)\n\t\tos.makedirs(self.sd_card_path, exist_ok=True)\n\t\tos.makedirs(self.base_path, exist_ok=True)\n\t\tos.makedirs(self.jpg_path, exist_ok=True)\n\t\tos.makedirs(self.empty_path, exist_ok=True)\n\t\tos.makedirs(self.backup_path, exist_ok=True)\n\t\tself.temp_dir = tempfile.mkdtemp()\n\n\t\tself.files = [\n\t\t\tos.path.join(self.sd_card_path, \"img_001.jpg\"),\n\t\t\tos.path.join(self.sd_card_path, \"img_002.jpg\"),\n\t\t\tos.path.join(self.sd_card_path, \"img_003.jpg\"),\n\t\t\tos.path.join(self.base_path, \"img_001.jpg\"),\n\t\t\tos.path.join(self.base_path, \"img_002.jpg\"),\n\t\t]\n\t\tself.file_contents = [\n\t\t\t\"test data\",\n\t\t\t\"test data\",\n\t\t\t\"test data\",\n\t\t\t\"test data\",\n\t\t\t\"different data\",\n\t\t]\n\n\t\t# Create files\n\t\tfor file, contents in zip(self.files, self.file_contents):\n\t\t\twith open(file, 'w') as f:\n\t\t\t\tf.write(contents)\n\n\t\twith open(self.list_path, 'w') as f:\n\t\t\tfor file in self.files:\n\t\t\t\tf.write(file + '\\n')\n\n\t\tself.sd_card = SDCard(self.sd_card_path)\n\t\tself.workflow = Workflow(self.base_path, self.jpg_path, self.backup_path, 'arw', self.sd_card)\n\n\tdef tearDown(self):\n\t\tfor file in self.files:\n\t\t\tos.remove(file)\n\t\tshutil.rmtree(self.temp_dir)\n\t\tshutil.rmtree(self.test_data_path)\n\n\tdef _same_path(self, path1, path2):\n\t\t\"\"\"\n\t\tCheck that the paths are the same, after being normalized and removing the trailing slash\n\t\t\"\"\"\n\t\treturn os.path.normpath(path1).rstrip('/') == os.path.normpath(path2).rstrip('/')\n\n\tdef test_init(self):\n\t\tself.assertTrue(self._same_path(self.workflow.base_path, self.base_path), msg=\"base_path not set correctly\")\n\t\tself.assertTrue(self._same_path(self.workflow.jpg_path, self.jpg_path), msg=\"jpg_path not set correctly\")\n\t\tself.assertTrue(self._same_path(self.workflow.backup_path, self.backup_path), msg=\"backup_path not set correctly\")\n\t\tself.assertEqual(self.workflow.sd_card, self.sd_card, msg=\"sd_card not set correctly\")\n\t\tself.assertIsInstance(self.workflow.sd_card, SDCard, msg=\"sd_card not set correctly\")\n\n\tdef test_sd_card_property(self):\n\t\tself.assertEqual(self.workflow.sd_card, self.sd_card, msg=\"sd_card not set correctly\")\n\t\tself.assertTrue(self._same_path(self.workflow.sd_card.path, self.sd_card.path), msg=\"sd_card not set correctly\")\n\t\tself.assertIsInstance(self.workflow.sd_card, SDCard, msg=\"sd_card is not an SD Card\")\n\n\t\twith patch.object(os.path, 'exists', return_value=False):\n\t\t\twith self.assertRaises(FileNotFoundError):\n\t\t\t\t_ = Workflow(self.base_path, self.jpg_path, self.backup_path).sd_card\n\n\tdef test_path_properties(self):\n\t\t# Valid path\n\t\tself.workflow.base_path = self.empty_path\n\t\tself.assertTrue(self._same_path(self.workflow.base_path, os.path.join(self.empty_path, '')), msg=\"base_path not set correctly\")\n\n\t\t# Invalid path\n\t\twith self.assertRaises(FileNotFoundError):\n\t\t\tself.workflow.base_path = os.path.join(self.empty_path, 'non_existent_folder')\n\n\t\t# Test similar behavior for jpg_path and backup_path\n\t\tself.workflow.jpg_path = self.empty_path\n\t\tself.assertTrue(self._same_path(self.workflow.jpg_path, os.path.join(self.empty_path, '')), msg=\"jpg_path not set correctly\")\n\n\t\twith self.assertRaises(FileNotFoundError):\n\t\t\tself.workflow.jpg_path = os.path.join(self.empty_path, 'non_existent_folder')\n\n\t\tself.workflow.backup_path = self.empty_path\n\t\tself.assertTrue(self._same_path(self.workflow.backup_path, os.path.join(self.empty_path, '')), msg=\"backup_path not set correctly\")\n\n\t\twith self.assertRaises(FileNotFoundError):\n\t\t\tself.workflow.backup_path = os.path.join(self.empty_path, 'non_existent_folder')\n\n\tdef test_bucket_path_property_fail(self):\n\t\twith patch.object(Validator, 'is_writeable', return_value=False):\n\t\t\twith self.assertRaises(PermissionError):\n\t\t\t\t_ = self.workflow.bucket_path\n\n\tdef test_run(self):\n\t\twith patch.object(Validator, 'is_dir', return_value=True), \\\n\t\t\t patch.object(Validator, 'is_writeable', return_value=True), \\\n\t\t\t patch.object(self.workflow, 'queue_files', return_value=Queue()), \\\n\t\t\t patch.object(self.workflow, 'copy_from_list', return_value=True), \\\n\t\t\t patch.object(self.workflow, 'organize_files', return_value={'/a/img.jpg': '/b/img.jpg'}), \\\n\t\t\t patch.object(Validator, 'validate_checksum_list', return_value=True):\n\t\t\t# Successful run\n\t\t\tself.assertTrue(self.workflow.run(), msg=\"Workflow should have run successfully\")\n\n\t\twith patch.object(Validator, 'is_dir', return_value=False):\n\t\t\t# Invalid paths\n\t\t\tself.assertFalse(self.workflow.run(), msg=\"Workflow should have failed due to invalid paths\")\n\n\t\twith patch.object(Validator, 'is_dir', return_value=True), \\\n\t\t\t patch.object(Validator, 'is_writeable', return_value=False):\n\t\t\t# Unwritable paths\n\t\t\tself.assertFalse(self.workflow.run(), msg=\"Workflow should have failed due to unwritable paths\")\n\n\tdef test_copy_from_list(self):\n\t\tlist_path = self.list_path\n\t\tdestination_path = self.backup_path\n\t\tchecksums_before = {\"file1\": \"checksum1\"}\n\t\toperation = CopyOperation.TERACOPY\n\n\t\twith patch.object(self.workflow, 'teracopy_from_list', return_value=True), \\\n\t\t\t patch.object(Validator, 'validate_checksums', return_value=True):\n\t\t\tself.assertTrue(self.workflow.copy_from_list(list_path, destination_path, checksums_before, operation), msg=\"Copy should have succeeded\")\n\n\t\t# Copy failure\n\t\twith patch.object(self.workflow, 'teracopy_from_list', return_value=False), \\\n\t\t\t patch.object(Validator, 'validate_checksums', return_value=True), \\\n\t\t\t patch('builtins.input', return_value='y'):\n\t\t\tself.assertFalse(self.workflow.copy_from_list(list_path, destination_path, checksums_before, operation), msg=\"Copy should have failed\")\n\n\t\t# Checksum validation failure\n\t\twith patch.object(self.workflow, 'teracopy_from_list', return_value=True), \\\n\t\t\t patch.object(Validator, 'validate_checksums', return_value=False), \\\n\t\t\t patch('builtins.input', return_value='y'):\n\t\t\tself.assertFalse(self.workflow.copy_from_list(list_path, destination_path, checksums_before, operation), msg=\"Checksum validation should have failed\")\n\n\tdef test_rsync_fail(self):\n\t\tsource_path = self.sd_card_path\n\t\tdestination_path = os.path.join(self.empty_path, '/destination/')\n\t\tself.workflow.rsync(source_path, destination_path)\n\n\t\t# Rsync failed\n\t\twith patch.object(subprocess, 'check_call', side_effect=subprocess.CalledProcessError(-1, \"\")):\n\t\t\tself.assertFalse(self.workflow.rsync(source_path, destination_path), msg=\"Rsync should have failed\")\n\n\tdef test_rsync_succeed(self):\n\t\tsource_path = self.sd_card_path\n\t\tdestination_path = self.base_path\n\t\tself.workflow.rsync(source_path, destination_path)\n\n\t\twith patch.object(subprocess, 'check_call', return_value = 1000):\n\t\t\tself.assertTrue(self.workflow.rsync(source_path, destination_path), msg=\"Rsync should have succeeded\")\n\n\tdef test_teracopy_succeed(self):\n\t\tsource_path = self.sd_card_path\n\t\tdestination_path = self.base_path\n\t\twith patch.object(subprocess, 'check_call', return_value = 1000):\n\t\t\tself.assertTrue(self.workflow.teracopy(source_path, destination_path), msg=\"Teracopy should have succeeded\")\n\n\tdef test_teracopy_fail(self):\n\t\tsource_path = self.sd_card_path\n\t\tdestination_path = os.path.join(self.empty_path, '/destination/')\n\t\t# Teracopy failed\n\t\twith patch('subprocess.check_call', side_effect=subprocess.CalledProcessError(-1, \"\")):\n\t\t\tself.assertFalse(self.workflow.teracopy(source_path, destination_path), msg=\"Teracopy should have failed\")\n\n\tdef test_queue_files(self):\n\t\t# Test the logic inside queue_files\n\t\tfiles = self.workflow.queue_files()\n\t\tself.assertIsInstance(files, Queue, msg=\"Files should be a Queue.\")\n\n\tdef test_organize_files(self):\n\t\t# Create files in the bucket, so they can be organized\n\t\tfiles = [ 'img_001.jpg', 'img_002.jpg', 'img_003.jpg', 'img_001.arw' ]\n\t\tpaths = []\n\t\tfor file in files:\n\t\t\tpath = os.path.join(self.workflow.bucket_path, file)\n\t\t\twith open(path, 'w') as f:\n\t\t\t\tpaths.append(path)\n\t\t\t\tf.write(path)\n\n\t\tresults = self.workflow.organize_files()\n\t\tself.assertIsInstance(results, dict, msg=\"Results should be a dict.\")\n\t\t# Contents should include all of self.files as keys, with a new path as values\n\t\tself.assertEqual(len(results.keys()), len(files), msg=\"Results should include all files.\")\n\t\tfor file in paths:\n\t\t\tself.assertIn(file, results.keys(), msg=\"Results should include all files.\")\n\t\t\tself.assertIsInstance(results[file], str, msg=\"Results should include all files.\")\n\t\t\t# Contents of the copied file should be the same as the original\n\t\t\twith open(results[file], 'r') as f:\n\t\t\t\tself.assertEqual(f.read(), file, msg=\"Contents of the copied file should be the same as the original.\")","repo_name":"avranu/ImageInn","sub_path":"scripts/tests/test_workflow.py","file_name":"test_workflow.py","file_ext":"py","file_size_in_byte":9665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"30829499820","text":"from functools import partial\nfrom typing import Any, Callable, TypeVar, cast\n\nfrom pydantic import ValidationError\n\nfrom .fp import Bad, Good, OneOf, StopBadIteration\nfrom .issue import Issue\n\nG = TypeVar('G') # pylint: disable=invalid-name\n\n\ndef issue( # noqa: WPS211\n message: str,\n description: str | None = None,\n cause: Exception | None = None,\n context: object | None = None,\n include_traceback: bool = True,\n) -> OneOf[Issue, Any]:\n \"\"\"Shortcut to create a Bad OneOf containing an Issue.\n\n Args:\n message: The issue message.\n description: Optional description.\n cause: Optional exception that caused the issue.\n context: Optional dictionary to provide extra information.\n include_traceback: Defaults to true to provide the stack trace.\n\n Returns:\n An instance of an `Issue`.\n \"\"\"\n inst = Issue(message, description, cause, context, include_traceback)\n return Bad(inst)\n\n\ndef one_of(comp: Callable[[], list[G]]) -> OneOf[Any, G]:\n \"\"\"Handle the \"Good\" value of a `OneOf`.\n\n To be used so that we may iterate over OneOf objects that may raise\n the `StopBadIteration` exception.\n\n Args:\n comp: A lambda function returning an array with a single value.\n\n Returns:\n A `OneOf` with the value returned from `comp`.\n \"\"\"\n res = None\n try:\n res = comp()\n except StopBadIteration as ex:\n return cast(Bad, ex.bad)\n except ValidationError as ex:\n return issue('pydantic validation error', cause=ex)\n except Exception as ex:\n return issue('one_of caught exception', cause=ex)\n if res:\n return Good(res[0])\n # LOOK AT ME - you may be here because a mock is not returning a OneOf.\n return issue('one_of empty response - iteration missing a OneOf')\n\n\ndef to_one_of(\n callback: Callable[[], Any],\n message: str,\n context: object | None = None,\n) -> OneOf[Issue, int]:\n \"\"\"Wrap a python call in a `OneOf`.\n\n Args:\n callback: A lambda function with a simple python statement.\n message: An error message in case the statement raises an exception.\n context: Additional error context.\n\n Returns:\n A `OneOf` containing an `Issue` if the callback raises an error.\n \"\"\"\n try:\n callback()\n except Exception as ex:\n return issue(message, cause=ex, context=context)\n return Good(0)\n\n\ndef non_issue(inst: OneOf[Issue, G]) -> G:\n \"\"\"Obtain the value of the `OneOf` as if it was a Good value.\n\n Warning: This should only be used provided that we know for sure\n that we are not dealing with a `Bad` value.\n\n Args:\n inst: A OneOf.\n\n Returns:\n The value stored in the OneOf.\n \"\"\"\n # The assert statement can go away with the -O flag.\n assert not inst.is_bad # noqa: S101\n return cast(G, inst.value)\n\n\ndef _hone(\n msg: str,\n context: object,\n description: str,\n include_traceback: bool,\n iss: Exception,\n) -> OneOf[Issue, Any]:\n return issue(\n msg,\n cause=iss,\n context=context,\n description=description,\n include_traceback=include_traceback,\n )\n\n\ndef hone(\n msg: str,\n context: object | None = None,\n description: str | None = None,\n include_traceback: bool = True,\n) -> Callable[[Issue], OneOf[Issue, Any]]:\n \"\"\"Create a function to repackage the issue with a new message and context.\n\n Args:\n msg: The new message.\n context: The new context.\n description: The new description.\n include_traceback: Whether to include the traceback.\n\n Returns:\n A function that takes an issue and returns a new issue.\n \"\"\"\n return partial(_hone, msg, context, description, include_traceback)\n","repo_name":"jmlopez-rod/m","sub_path":"packages/python/m/core/one_of.py","file_name":"one_of.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"6133758527","text":"# -*- coding: utf-8 -*-\n\n# This is where you would add additional functionality to your node, \n# bound to certain URLs in urls.py\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.template import Context, Template\nfrom django.template.loader import get_template\nfrom django.shortcuts import render, get_object_or_404\n\nimport node.models as models# this imports models.py from the same directory as this file\n\nfrom django.db.models import Q\n\n# this function fetches energyscan data from the db and is defined as a function\n# because it is needed several times throughout this file\n\ndef get_ES_from_db(id):\n \"\"\" Grab energyscan data from database \"\"\"\n energyscan = get_object_or_404(models.Energyscan, pk=id)\n ES_list = energyscan.energyscan_data.split()\n k = 0\n xs = []\n ys = []\n for datapoint in ES_list:\n datapoint = datapoint.replace(',','.')\n #even -> x-value\n if k % 2 == 0:\n xs.append(float(datapoint))\n #odd -> y-value\n else:\n ys.append(float(datapoint))\n k = k + 1\n\n #we end at this point, because the further handling of the data depends on the function\n\n return energyscan, xs, ys\n\ndef show_energyscan(request, id):\n \"\"\" Fill the normal template to show ES on the webinterface \"\"\"\n # get data from db\n energyscan, xs, ys = get_ES_from_db(id)\n xs = list(map(str, xs))\n ys = list(map(str, ys))\n k = 0\n stringarray = []\n for x in xs:\n stringarray.append('[%s, %s]'%(x, ys[k]))\n k = k + 1\n\n energyscan.daten = \" ,\".join(stringarray)\n\n #sources:\n authorlist = []\n source = models.Source.objects.filter(id__exact=energyscan.source.id).get()\n for author in source.authors.all():\n authorlist.append(u'%s, %s'%(author.lastname, author.firstname))\n\n energyscan.authorlist = \"; \".join(authorlist)\n\n t = 'node/energyscan_view.html'\n c = {'es':energyscan}\n return HttpResponse(render(request, t, c))\n\ndef compare_energyscan(request, id1, id2):\n \"\"\" Compare two ES on the webinterface \"\"\"\n # get data from db\n energyscan1, xs1, ys1 = get_ES_from_db(id1)\n energyscan2, xs2, ys2 = get_ES_from_db(id2)\n\n stringarray1 = []\n stringarray2 = []\n\n #compare scans - multiply items of second with factor between max(1) and max(2)\n factor = max(ys1) / max(ys2)\n ys2[:] = [x*factor for x in ys2]\n energyscan2.factor = \"%.2f\" % factor\n\n #prepare scan1 for text-format\n\n xs1 = list(map(str, xs1))\n ys1 = list(map(str, ys1))\n k = 0\n for x in xs1:\n stringarray1.append('[%s, %s]'%(x, ys1[k]))\n k = k + 1\n\n energyscan1.daten = \" ,\".join(stringarray1)\n\n #prepare scan2 for text-format\n\n xs2 = list(map(str, xs2))\n ys2 = list(map(str, ys2))\n k = 0\n for x in xs2:\n stringarray2.append('[%s, %s]'%(x, ys2[k]))\n k = k + 1\n\n energyscan2.daten = \" ,\".join(stringarray2)\n\n #sources:\n authorlist = []\n source = models.Source.objects.filter(id__exact=energyscan1.source.id).get()\n for author in source.authors.all():\n authorlist.append(u'%s, %s'%(author.lastname, author.firstname))\n\n energyscan1.authorlist = \"; \".join(authorlist)\n\n authorlist = []\n source = models.Source.objects.filter(id__exact=energyscan2.source.id).get()\n for author in source.authors.all():\n authorlist.append(u'%s, %s'%(author.lastname, author.firstname))\n\n energyscan2.authorlist = \"; \".join(authorlist)\n\n\n #render and return\n\n t = 'node/energyscan_compare.html'\n c = {'es1':energyscan1, 'es2':energyscan2}\n html = render(request, t, c)\n return HttpResponse(html)\n\ndef contact(request):\n contactdetails = {'name':'Johannes Postler', 'email':'johannes.postler@uibk.ac.at'}\n t = 'node/contact.html'\n c = {'contact':contactdetails}\n html = render(request, t, c)\n return HttpResponse(html)\n\ndef export_ascii(request, id):\n \"\"\" Export ES to ASCII file \"\"\"\n #get data from db\n energyscan, xs, ys = get_ES_from_db(id)\n \n stringarray = []\n k = 0\n for x in xs:\n stringarray.append('%f\\t%f'%(x, ys[k]))\n k = k + 1\n\n energyscan.daten = \"\\r\\n\".join(stringarray)\n\n t = 'node/ascii_export.txt'\n c = {'es':energyscan}\n filename = \"ES_\" + str(energyscan.species) + \"_from_\" + str(energyscan.origin_species) + \".txt\"\n html = render(request, t, c)\n resp = HttpResponse(html, content_type='text/plain')\n resp['Content-Disposition'] = 'attachment; filename=%s' % filename\n return resp\n","repo_name":"VAMDC/NodeSoftware","sub_path":"nodes/IDEADB/node/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"67"} +{"seq_id":"15500561863","text":"import re\nfrom sys import stdin\n \nfor line in stdin.readlines():\n if '//' in line:\n blocks = re.split('//', line)\n blocks[0] = re.sub('->', '.', blocks[0])\n print('//'.join(blocks))\n else:\n print(re.sub('->', '.', line))\n","repo_name":"Chiki1601/Hackerearth-Solutions","sub_path":"Algorithms/String Algorithms/Basics of String Manipulation/Compiler Version.py","file_name":"Compiler Version.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"67"} +{"seq_id":"12224324712","text":"# -*- coding: utf-8 -*-#\nimport ConfigParser\n\n## --------------------------------------------------------------\n## PARSE CONFIG FILE\n## --------------------------------------------------------------\n\nclass Config_Parser(object):\n\n\t## Constructor\n\tdef __init__(self, config_file):\n\t\tself.configfile = config_file\n\t\tself.config = ConfigParser.ConfigParser()\n\t\tself.config.read(self.configfile)\n\t\t#try:\n\t\t#\tconfig.read(config_file)\n\t\t#except:\n\t\t#\tprint \"Error while trying to read config file. Check if 'sb_client.conf' exists in the same folder as the program file.\"\n\n\t\tself.boxPath = self.config.get('main', 'path')\n\t\tself.clientName = self.config.get('main', 'name')\n\n\t\tself.serverHostname = self.config.get('server', 'host')\n\t\tself.serverIP = self.config.get('server', 'ip')\n\t\tself.serverPort = int(self.config.get('server', 'port'))\n\n\tdef writeConfig(self, path, name, ip):\n\t\tself.config.set('main', 'path', path)\n\t\tself.config.set('main', 'name', name)\n\t\tself.config.set('server', 'ip', ip)\n\t\twith open(self.configfile, 'wb') as configfile:\n\t\t\tself.config.write(configfile)","repo_name":"martinzellner/sourceBox","sub_path":"sourcebox-client/config_parser.py","file_name":"config_parser.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69804723093","text":"import tkinter\nfrom tkinter import Label\nfrom tkinter import Entry\nfrom tkinter import StringVar\nfrom tkinter import messagebox\nfrom tkinter import filedialog\nfrom pathlib import Path\nfrom tkinter import Button\nfrom subprocess import call\nfrom subprocess import check_output\nimport os\nimport os.path\nimport platform\nimport linecache\nimport sys\nfrom pathlib import Path\nimport difflib\nfrom difflib import SequenceMatcher\nimport datetime\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\ndef runFile(string, directoryFileList):\n\tif string in directoryFileList==False:\n\t\treturn \"Incorrect File Name\"\n\tout = check_output([\"python3\", string])\n\treturn out\n\ndef noSpacesNoQuote(stringx):\n\tfor i in range(0, len(stringx)):\n\t\tif(stringx[i]==\" \" or stringx[i]==\"'\" or stringx[i]=='\"'):\n\t\t\tstringx = stringx[i+1::]\n\t\telse:\n\t\t\tbreak\n\tfor i in range(len(stringx), 0):\n\t\tif(stringx[i]==\" \"):\n\t\t\tstringx = stringx[::i-1]\n\t\telse:\n\t\t\tbreak\n\treturn stringx\n\ndef findFile(fileKey, directory, folderPath):\n\tfor path in directory:\n\t\tnumCompare = path[6]+path[7]\n\t\tif(len(fileKey))>2:\n\t\t\tnumCompare=path[6]+path[7]+path[8]\n\t\tif(numCompare==fileKey):\n\t\t\treturn path\n\n\treturn -1\ndef getTime(fileKey, directory, folderPath):\n\tfor path in directory:\n\t\tnumCompare = path[6]+path[7]\n\t\tif(numCompare==fileKey):\n\t\t\tt = os.path.getmtime(folderPath+'/'+path)\n\t\t\ttimeStamp = str(datetime.datetime.fromtimestamp(t))\n\t\t\treturn timeStamp\n\n\ndef grade(string1, string2):\n\tstring1 = string1.lower()\n\tstring2 = string2.lower()\n\tstring1 = noSpacesNoQuote(string1)\n\tstring2 = noSpacesNoQuote(string2)\n\tstring1 = str(string1)\n\tstring2 = str(string2)\n\n\tsim = similar(string1, string2)\n\t\n\treturn sim\n\ndef pathException(path):\n\tif path!=\"\":\n\t\tprint(\"you picked: \"+path)\n\telse:\n\t\tprint(\"Exited, please pick a location\")\n\treturn\n#returns just the fileName & not the path\ndef pathToFileName(name):\n\tnew_name=\"\"\n\ti = len(name)-1\n\twhile name[i]!=\"/\":\n\t\tnew_name=new_name+name[i]\n\t\ti=i-1\n\t##reverse the string\n\treturn new_name[::-1]\n\ndef errorWindow(string):\n\tmessagebox.showerror('User Error', string)\n\treturn\ndef findSemiColonCount(file_name, key):\n\top = open(file_name, 'r')\n\tgetLine = linecache.getline(file_name, 1)\n\tprint(getLine)\n\tfindKey = getLine.find(key) #finds the key\n\tif(findKey==-1): return -1\n\tprint(\"FINDKEY: \"+str(findKey))\n\tsemiCount = 1\n\t##now we have location of the key\n\tprint(getLine[0:findKey+1]) \n\tcurrentString = getLine[0:findKey+1]\n\tprint(\"Hup: \"+currentString)\n\tprint(\"Finding key\")\n\tsemiCount = currentString.count(\";\")\n\tprint(semiCount)\n\top.close()\n\treturn semiCount\n\ndef skipToSemi(semiCount,line):\n\tcnt = 0\n\ti=0\n\twhile cnt!=semiCount:\n\t\tloc = line.find(\";\")\n\t\tcnt=cnt+1\n\t\tline = line[loc+1::]\n\t\ti=loc+1+i\n\tprint(\"DEBUG: \"+str(i))\n\treturn i \n\n# hide main window\ndef main():\n\n\t#Filetypes\n\tftypes = [\n \t('Python code files', '*.py'), \n \t('Perl code files', '*.pl;*.pm'), # semicolon trick\n \t('Java code files', '*.java'), \n \t('C++ code files', '*.cpp;*.h'), # semicolon trick\n \t('Text files', '*.txt'), \n \t('Excel files', '*.csv'),\n \t('All files', '*'), \n\t]\n\n\troot = tkinter.Tk()\n\tif(len(sys.argv)!=2):\n\t\tprint(\"Invalid Number of Arguments\")\n\t\treturn\n\toutputName = str(sys.argv[1])+\".txt\"\n\troot.withdraw()\n\n\tx = input(\"Select csv_file--->Press Enter to Continue\")\n\t\n\tcsv_file = filedialog.askopenfilename(title = \"Ask for csv file\", filetypes=ftypes)\n\tpathException(csv_file)\n\t\n\tx = input(\"Select Answer File--->Press Enter to Continue\")\n\troot.filename = filedialog.askopenfilename(initialdir = \n\t\t\"/\",title = \"Select Answer File\",filetypes = ftypes)\n\tpathException(root.filename)\n\n\tif csv_file==\"\" or root.filename==\"\":\n\t\terrorWindow(\"Chosen file error, exiting...\")\n\t\treturn\n\tf = open(outputName,\"w+\")\n\n\n\t######----------------------Traverse Answer File----------------------######\n\n\tanswer = open(root.filename, \"r\")\n\texpectedFileName = linecache.getline(root.filename, 1)\n\texpectedFileName=expectedFileName.rstrip('\\n')\n\texpectedOutput =\"\"\n\n\tindice = 2\n\tgetLineAnswer = linecache.getline(root.filename, indice)\n\twhile getLineAnswer:\n\t\texpectedOutput =expectedOutput+getLineAnswer\n\t\tindice=indice+1\n\t\tgetLineAnswer= linecache.getline(root.filename, indice)\n\n\tanswer.close()\n\n\tx = input(\"Select Student File Folder--->Press Enter to Continue\")\n\tfolder = filedialog.askdirectory(title = \"All Student Submissions For This HW\")\n\tpathException(folder)\n\tpathlist = Path(folder).glob('**/*.py')\n\n\n\t######----------------------Traverse CSV File----------------------######\n\n\n\t#This loop will ignore the file if the submission number is blank*\n\t#This loop will add the student to be checked only if they submitted a .py file\n\n\tnotPyFile=[]\n\tstudentIDS = [] #refers to the user id\n\tstudentSubmissionNumber = [] #refers to the student submission number \n\tkey = '\"en\";\"' #this is the part that has the ID\n\tgetZero = '\"ext\"\":\"\"py\"'\n\tprint(\"the key is: \"+key) \n\n\tsemCount = findSemiColonCount(csv_file, '\"Enter your iCode student ID:\"')\n\n\tprint(\"SemiCount: \"+str(semCount))\n\ti=2\n\tgetLine = linecache.getline(csv_file, i)\n\twhile getLine: #read in all lines\n\t\t#print(getLine)\n\t\tstrt = getLine.find(key) #find the key \n\n\t\tstudentGetsZero = False\n\t\tif getLine.find(getZero)==-1: \n\t\t\tstudentGetsZero=True\n\n\t\tnumber = \"\"\n\t\tID = \"\"\n\t\tloc = skipToSemi(semCount, getLine) \n\t\tprint(\"length of string: \"+str(len(getLine)))\n\t\tprint(\"LOC: \"+str(loc))\n\t\tloc=loc+1\n\t\ttry:\n\t\t\twhile getLine[loc]!='\"':\n\t\t\t\tprint(\"Test--\"+getLine[loc])\n\t\t\t\tif(loc==len(getLine)-1): \n\t\t\t\t\tID=ID+getLine[loc]\n\t\t\t\t\tbreak\n\t\t\t\tID = ID+getLine[loc]\n\t\t\t\tloc=loc+1\n\t\texcept:\n\t\t\tprint(\"BAD FILE INPUT\")\n\n\n\t\tID = ID[0::]\n\t\tstrt=1\n\t\twhile getLine[strt]!='\"':\n\t\t\tnumber = number+getLine[strt]\n\t\t\tstrt=strt+1\n\n\t\tprint(\"Number:::::::\"+number)\n\t\tprint(\"ID::::::::\"+ID)\n\n\t\tif(studentGetsZero):\n\t\t\tnotPyFile.append(ID)\n\t\t\tprint(\"Added \"+ID+\" to pyList*********************************************\")\n\t\t\tprint(\"Student_ID:\"+ID)\n\t\t\tprint(\"Submission:\"+number)\n\t\tif(((ID!=\"\" and ID!=\";\" and ID!=\" \" and ID!=\" \") and studentGetsZero==False)):\n\t\t\t\n\n\t\t\tif ID in studentIDS:\n\t\t\t\treplaceID = studentIDS.index(ID)\n\t\t\t\tstudentIDS.pop(replaceID)\n\n\t\t\tstudentIDS.append(ID)\n\t\t\tstudentSubmissionNumber.append(number)\n\t\t\tprint(\"Student_ID:\"+ID)\n\t\t\tprint(\"Length:\"+str(len(ID)))\n\t\t\tprint(\"Submission:\"+number)\n\t\ti=i+1\n\t\tgetLine = linecache.getline(csv_file, i)\n\t\tprint()\n\t\tprint(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n\t\tprint()\n\n\n\n\t######----------------------Traverse CSV File----------------------######\n\n\t######----------------------Now do the grading----------------------######\n\n\t#if another correct submission was not for the same student then\n\t#print that the student gets a zero in the output file\n\tprint(\"These many students didn't submit .py files: \"+str(len(notPyFile)))\n\tindex = 0\n\n\tf.write(expectedFileName+\"\\n\\n\")\n\n\twhile index \"+folder)\n\n\tfiles = os.listdir(folder)\n\n\tfor i in range(0, len(files)):\n\t\tprint(files[i])\n\n\tmypath = Path().absolute()\n\tprint(\"mypath\"+str(mypath))\n\tsys.path.append(os.path.join(os.path.dirname(folder), \"..\"))\n\tos.path.abspath(folder)\n\n\n\n\tfor i in range(0, len(studentSubmissionNumber)):\n\t\tprint(i) \n\t\tif (int(studentSubmissionNumber[i])<10): #submission is less than ten\n\t\t\t#runFileName = \"0000\"+studentSubmissionNumber[i]+\"_0\"+studentSubmissionNumber[i]+\"_00-\"\n\t\t\t#runFileName=runFileName+expectedFileName\n\t\t\tfileSubmission = \"0\"+studentSubmissionNumber[i]\n\t\t\trunFileName=findFile(fileSubmission, files, folder)\n\t\t\ttimeStamp = getTime(fileSubmission, files, folder)\n\t\t\tif(runFileName==-1):\n\t\t\t\tcontinue\n\t\t\tprint(\"File to Run: \"+runFileName)\n\t\tif (int(studentSubmissionNumber[i])<=99 and (int(studentSubmissionNumber[i])>=10)): #10-99\n\t\t\t#runFileName = \"000\"+studentSubmissionNumber[i]+\"_\"+studentSubmissionNumber[i]+\"_00-\"\n\t\t\t#runFileName=runFileName+expectedFileName\n\t\t\tfileSubmission = studentSubmissionNumber[i]\n\t\t\trunFileName=findFile(fileSubmission, files, folder)\n\t\t\ttimeStamp = getTime(fileSubmission, files, folder)\n\t\t\tif(runFileName==-1):\n\t\t\t\tcontinue\n\t\t\tprint(\"File to Run: \"+runFileName)\n\t\tif (int(studentSubmissionNumber[i])<=999 and (int(studentSubmissionNumber[i])>=100)): #100-999\n\t\t\t#do something here\n\t\t\t#runFileName = \"00\"+studentSubmissionNumber[i]+\"_\"+studentSubmissionNumber[i]+\"_00-\"\n\t\t\t#runFileName=runFileName+expectedFileName\n\t\t\tfileSubmission = studentSubmissionNumber[i]\n\t\t\trunFileName=findFile(fileSubmission, files, folder)\n\t\t\ttimeStamp = getTime(fileSubmission, files, folder)\n\t\t\tif(runFileName==-1):\n\t\t\t\tcontinue\n\t\t\tprint(\"File to Run: \"+runFileName)\n\n\n\t\texists = runFileName in files\n\t\trunFileName=folder+\"/\"+runFileName\n\t\tif runFileName.find(expectedFileName)==-1:\n\t\t\tf.write(\"User: \"+studentIDS[i]+\" gets a 0%\\n\")\n\t\t\tf.write(\"Submitted: Wrong File/Wrong Name/Bad Submission\\n\\n\")\n\t\t\tcontinue\n\t\tif exists == False:\n\t\t\tprint(studentIDS[i]+\" has wrong filename gets 0%\")\n\t\t\tf.write(\"User: \"+\"Entered Bad Filename\"+\" gets a 0%\\n\\n\")\n\n\t\t\tcontinue\n\t\toutputFromFile=\"\"\n\t\tif exists == True:\n\t\t\ttry:\n\t\t\t\toutputFromFile = runFile(runFileName, files)\n\t\t\t\tprint(\"Running \"+runFileName)\n\t\t\t\tprint(\"Output: \"+str(outputFromFile))\n\t\t\texcept:\n\t\t\t\tprint(studentIDS[i]+\" has wrong syntax gets 0%\")\n\t\t\t\tif(len(studentIDS[i])<=2):\n\t\t\t\t\tf.write(\"User: \"+studentIDS[i]+\" gets a 0%\\n\")\n\t\t\t\telse:\n\t\t\t\t\tf.write(\"User: \"+\"[Did not provide ID]\"+\" gets a 0%\\n\")\n\t\t\t\tf.write(\"Submitted: Wrong File/Wrong Name/Bad Submission/Invalid Syntax in File\\n\\n\")\n\t\tgrade1 = grade(outputFromFile, expectedOutput)\n\t\tgrade1 =round(grade1,4)\n\t\tcertainRatio = .023\n\t\tgradeString = str((grade1+certainRatio)*100)+\"%\"\n\t\tprint(gradeString)\n\t\tf.write(\"User: \"+studentIDS[i]+\" gets a \"+gradeString+\"%\\n\")\n\t\tf.write(\"Submitted--> \"+timeStamp+\"\\n\\n\")\n\t\tprint(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n\t\t\n\t\t\n\tf.close()\n\t#what I have left is to read the right directory\n\t#get the grades \n\nmain()\n","repo_name":"bhavsingh2017/iCodeProjects","sub_path":"BashGrader/autoGrade.py","file_name":"autoGrade.py","file_ext":"py","file_size_in_byte":10355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"10235416788","text":"from typing import Any, Union\nimport re\n\nHELP = \"\"\"\n# COMMANDS (case-insensitive) #\n\nhelp - display help menu\nquit - quit game\ngo [place] - go to a location or room\ncheck [clue] - investigate a clue\ntake [clue] - take a clue if possible\nmap - see available locations\nwhere am I - see available rooms\nlook around - investigate current room\nbag - see inventory\nuse [clue] - use an item (if possible)\"\"\"\n\n# Errors\nclass ConstructionError(Exception):\n pass\n\n# AdventureObject definition (Base Class)\nclass AdventureObject:\n def __init__(self, **data) -> None:\n self._data = data.copy()\n self._validate()\n \n def __repr__(self) -> str:\n return str(self._data)\n\n # Validates the object against its own required attributes\n def _validate(self) -> None:\n if hasattr(self, \"_required_attrs\"):\n for attr in self._required_attrs:\n if not attr[0] in self._data:\n raise ConstructionError(f\"{type(self).__name__} object missing attribute {attr[0]}\")\n else:\n typ = type(self._data[attr[0]])\n if typ != attr[1]:\n raise ConstructionError(f\"Invalid type for \\\"{attr[0]}\\\" attribute in {type(self).__name__} object (expected {str(attr[1].__name__)}, got {str(typ.__name__)})\")\n \n if not hasattr(self, \"prefix\"):\n self.set(\"prefix\", \"\")\n \n # setters and getters\n def get(self, attr) -> Any:\n return self._data[attr]\n \n def set(self, attr, value) -> None:\n self._data[attr] = value\n \n # used for key indexing\n def id(self) -> str:\n return self.get(\"name\").lower()\n \n def rename(self, name: str) -> None:\n self.set(\"name\", name)\n\n # String for printing relevant info for user\n def describe(self, is_current=False, include_details=False) -> str:\n current = \" (current)\" if is_current else \"\"\n details = \"\\n\" + self.get(\"desc\") if include_details else \"\"\n return self.get(\"prefix\") + self.get(\"name\") + current + details\n\n\nclass Clue(AdventureObject):\n def __init__(self, **data) -> None:\n self._required_attrs = [\n (\"name\", str),\n (\"desc\", str),\n (\"is_item\", bool)\n ]\n\n super().__init__(**data)\n\n self.set(\"prefix\", \"~ \")\n\n\nclass Room(AdventureObject):\n def __init__(self, **data) -> None:\n self._required_attrs = [\n (\"name\", str),\n (\"desc\", str),\n (\"clues\", dict)\n ]\n\n super().__init__(**data)\n\n self.set(\"prefix\", \"* \")\n\n self.set(\"is_default\", False)\n self.set(\"is_open\", False)\n self.set(\"is_locked\", False)\n \n def __getitem__(self, key: str) -> Clue:\n clues = self.get(\"clues\")\n if key in clues:\n return clues[key]\n else:\n return None\n \n def __iter__(self):\n return iter(self.get(\"clues\").values())\n \n # Sets self as default room within location\n def default(self):\n self.set(\"is_default\", True)\n return self\n\n # Push & Pop clues from _data[\"clues\"]\n def push(self, clue: Clue) -> Clue:\n self.get(\"clues\")[clue.id()] = clue\n return clue\n\n def pop(self, key: str) -> None:\n return self.get(\"clues\").pop(key, None)\n \n # Locked rooms cannot be opened until unlocked\n def lock(self):\n self.set(\"is_locked\", True)\n return self\n\n def unlock(self):\n self.set(\"is_locked\", False)\n return self\n\n # String for printing relevant Room info for user\n def describe(self, is_current=False, include_details=False, include_clues=False) -> str:\n output = super().describe(is_current, include_details)\n\n if not include_clues:\n return output\n else:\n clue_names = [clue.get(\"prefix\") + clue.get(\"name\") for clue in self]\n return output + \"\\n\\n\" + \"\\n\".join(clue_names)\n\n\nclass Location(AdventureObject):\n def __init__(self, **data) -> None:\n self._required_attrs = [\n (\"name\", str),\n (\"desc\", str),\n (\"rooms\", dict)\n ]\n\n super().__init__(**data)\n\n self.set(\"prefix\", \"** \")\n self.set(\"is_default\", False)\n \n def __getitem__(self, key: str) -> Room:\n rooms = self.get(\"rooms\")\n if key in rooms:\n return rooms[key]\n else:\n return None\n \n def __iter__(self):\n return iter(self.get(\"rooms\").values())\n \n # Sets self as default Location on game start\n def default(self):\n self.set(\"is_default\", True)\n return self\n \n # Returns default room (used on Location change)\n def get_default(self) -> Room:\n for room in self:\n if room.get(\"is_default\"): return room\n \n # Push new rooms to _data[\"rooms\"]. Pop not required as rooms are never removed\n def push(self, room: Room) -> Room:\n self.get(\"rooms\")[room.id()] = room\n return room\n\n # String for printing relevant Location info for user\n def describe(self, is_current=False, include_details=False, include_rooms=False) -> str:\n output = super().describe(is_current, include_details)\n\n if not include_rooms:\n return output\n else:\n room_names = [room.get(\"name\") for room in self]\n return output + \"\\n\\n\" + \"\\n\".join(room_names)\n\n\nclass TextAdventure(AdventureObject):\n def __init__(self, **data) -> None:\n self._required_attrs = [\n (\"title\", str),\n (\"locations\", dict)\n ]\n\n super().__init__(**data)\n\n self.set(\"inventory\", {})\n self.set(\"actions\", {})\n self.update_default_location()\n self.update_default_room()\n \n def __call__(self, display_help=False) -> Any:\n if display_help:\n print(self.cmd(\"help\"))\n\n player_cmd = self._parse_cmd(input(\"\\n>> \"))\n cmd = self.cmd(player_cmd[\"name\"], player_cmd[\"arg\"])\n\n if player_cmd[\"name\"] == \"quit\":\n quit()\n elif player_cmd is not None and cmd is not None:\n print(cmd)\n else:\n print(\"Invalid command. Type 'help' for a list of valid commands.\")\n\n return self()\n\n def __getitem__(self, key: str) -> Location:\n locations = self.get(\"locations\")\n if key in locations:\n return locations[key]\n else:\n return None\n \n def __iter__(self):\n return iter(self.get(\"locations\").values())\n\n # Parses a command and its argument into dictionary\n # which is then used in __call__ to evaluate results of user input\n def _parse_cmd(self, cmd_str: str) -> dict:\n cmd_name = re.search(\"^[a-zA-Z]+\", cmd_str)\n cmd_arg = re.search(\"(?<=[a-zA-Z]\\\\s)([a-zA-Z]+\\\\s*)+\", cmd_str)\n\n if cmd_name is not None:\n cmd_arg = \"\" if cmd_arg is None else cmd_arg.group()\n return {\n \"name\": cmd_name.group().lower(),\n \"arg\": cmd_arg.lower()\n }\n else:\n return {\n \"name\": None,\n \"arg\": None\n }\n\n # Performs commands of a specified name and optional argument\n # choosing from a list of functions.\n # This allows easy addition of new commands by simply defining a new function\n def cmd(self, name: str, arg=None) -> str:\n # quits game\n def quit(arg=None) -> str:\n return \"Exiting...\"\n \n # displays help menu (defined top)\n def help(arg=None) -> str:\n return HELP\n \n # shows \"map\" of available locations\n def map(arg=None) -> str:\n location_names = []\n for location in self:\n if location.id() == self.get(\"current_location\").id():\n location_names.append(location.describe(is_current=True))\n else:\n location_names.append(location.describe())\n \n return \"\\n\".join(location_names)\n \n # prints current location + description, plus list of rooms\n def where(arg=None) -> str:\n location = self.get('current_location')\n\n room_names = []\n for room in self[location.id()]:\n if room.id() == self.get(\"current_room\").id():\n room_names.append(room.describe(is_current=True))\n else:\n room_names.append(room.describe())\n \n return location.describe(include_details=True) + \"\\n\\n\" + \"\\n\".join(room_names)\n\n # prints current room + description, plus list of clues\n def look(arg=None) -> str:\n room = self.get(\"current_room\")\n clue_names = [clue.describe() for clue in room]\n \n return room.describe(include_details=True) + \"\\n\\n\" + \"\\n\".join(clue_names)\n\n # prints list of clues in inventory\n def bag(arg=None) -> str:\n if len(self.get(\"inventory\")) == 0:\n return \"Your bag is empty.\"\n else:\n item_names = [item.describe() for item in self.get(\"inventory\").values()]\n return \"\\n\".join(item_names)\n\n # prints description of given clue\n def check(clue_name: str) -> str:\n room = self.get(\"current_room\")\n clue = None\n\n if clue_name in room.get(\"clues\"):\n clue = room[clue_name]\n elif clue_name in self.get(\"inventory\"):\n clue = self.get(\"inventory\")[clue_name]\n \n if clue is not None:\n return clue.get(\"desc\")\n else:\n return \"You see no clues of that description.\"\n\n # changes current room or location\n def go(place_name: str) -> str:\n current_location = self.get(\"current_location\")\n current_room = self.get(\"current_room\")\n\n if place_name == current_location.id() or place_name == current_room.id():\n return \"You are already at that location.\"\n\n elif place_name in current_location.get(\"rooms\"):\n location_name = current_location.id()\n room = self[location_name][place_name]\n\n if room.get(\"is_locked\"):\n return f\"The {place_name} is locked.\"\n\n self.set(\"current_room\", room)\n\n return f\"Entering {place_name}...\"\n \n elif place_name in self.get(\"locations\"):\n self.set(\"current_location\", self[place_name])\n self.update_default_room()\n\n return f\"Travelling to {place_name}...\"\n \n else:\n return \"That location does not exist.\"\n\n # removes given clue from room and adds it to inventory\n def take(clue_name: str) -> str:\n room = self.get(\"current_room\")\n clue = room[clue_name]\n \n if clue is not None:\n if clue.get(\"is_item\"):\n self.get(\"inventory\")[clue_name] = room.pop(clue_name)\n \n return f\"You take the {clue_name}.\"\n else:\n return f\"You can't find a way to take the {clue_name}.\"\n else:\n return \"You can't find a clue with that name.\"\n \n # Use a clue if applicable\n def use(clue_name: str) -> str:\n if clue_name not in self.get(\"inventory\"):\n return \"You don't have any clues of that name in your inventory.\"\n \n if clue_name not in self.get(\"actions\"):\n return \"You don't think you can use this.\"\n \n action = self.get(\"actions\")[clue_name]\n\n action_requires_clue = action[\"requires\"][\"clue\"]\n action_requires_room = action[\"requires\"][\"room\"]\n action_creates_clue = action[\"creates\"][\"clue\"]\n action_creates_room = action[\"creates\"][\"room\"]\n action_unlocks_room = action[\"unlocks\"][\"room\"]\n action_location_id = action[\"creates\"][\"in_location\"]\n action_room_id = action[\"creates\"][\"in_room\"]\n\n success = False\n\n if not action_requires_clue and not action_requires_room:\n success = True\n \n if action_requires_clue and not action_requires_room:\n if action_requires_clue.id() in self.get(\"inventory\"):\n success = True\n \n if action_requires_room and not action_requires_clue:\n if action_requires_room.id() == self.get(\"current_room\").id():\n success = True\n \n if action_requires_clue and action_requires_room:\n if action_requires_clue.id() in self.get(\"inventory\") and action_requires_room.id() == self.get(\"current_room\").id():\n success = True\n \n if success:\n if action_creates_clue:\n self[action_location_id][action_room_id].push(action_creates_clue)\n if action_creates_room:\n self[action_location_id].push(action_creates_room)\n if action_unlocks_room:\n action_unlocks_room.unlock()\n \n return action[success]\n\n if name in locals():\n return locals()[name](arg)\n else:\n return None\n \n # Default location / room getters and updaters\n def get_default_location(self) -> Location:\n for location in self:\n if location.get(\"is_default\"): return location\n \n def get_default_room(self) -> Room:\n for room in self.get(\"current_location\"):\n if room.get(\"is_default\"): return room\n\n def update_default_location(self) -> None:\n self.set(\"current_location\", self.get_default_location())\n \n def update_default_room(self) -> None:\n self.set(\"current_room\", self.get_default_room())\n \n # adds a new action to _data[\"actions\"] for evalution by cmd(\"use\", CLUE_NAME)\n def add_action(self,\n use_clue_id: str,\n requires_clue: Clue,\n requires_room: Room,\n creates_clue: Clue,\n creates_room: Room,\n unlocks_room: Room,\n in_location_id: str,\n in_room_id: str,\n success_message: str,\n default_message: str) -> None:\n\n action = {\n \"requires\": {\n \"clue\": False,\n \"room\": False\n },\n \"creates\": {\n \"clue\": False,\n \"room\": False,\n \"in_room\": None,\n \"in_location\": None\n },\n \"unlocks\": {\n \"room\": False\n },\n True: success_message,\n False: default_message\n }\n\n if requires_clue is not None:\n action[\"requires\"][\"clue\"] = requires_clue\n \n if requires_room is not None:\n action[\"requires\"][\"room\"] = requires_room\n \n if creates_clue is not None:\n action[\"creates\"][\"clue\"] = creates_clue\n action[\"creates\"][\"in_location\"] = in_location_id\n action[\"creates\"][\"in_room\"] = in_room_id\n \n if creates_room is not None:\n action[\"creates\"][\"room\"] = creates_room\n action[\"creates\"][\"in_location\"] = in_location_id\n action[\"creates\"][\"in_room\"] = in_room_id\n \n if unlocks_room is not None:\n action[\"unlocks\"][\"room\"] = unlocks_room\n \n self.get(\"actions\")[use_clue_id] = action\n\n# defining clues\ncl_old_key = Clue(\n name=\"Old Key\",\n desc=\"A Key. Looks old.\",\n is_item=True\n)\ncl_stained_wall = Clue(\n name=\"Stained Wall\",\n desc=\"There's a stain on the wall.\",\n is_item=False\n)\ncl_painting = Clue(\n name=\"Painting\",\n desc=\"There's a painting of a smol doggo.\",\n is_item=False\n)\ncl_phone = Clue(\n name=\"Phone\",\n desc=\"It's unplugged.\",\n is_item=True\n)\ncl_dumpster = Clue(\n name=\"Dumpster\",\n desc=\"For some reason, it's locked.\",\n is_item=False\n)\ncl_snowglobe = Clue(\n name=\"Snowglobe\",\n desc=\"\\'For Melinda\\' is engraved on its plaque.\",\n is_item=True\n)\ncl_note = Clue(\n name=\"Note\",\n desc=\"A small note, in the shape of a key.\",\n is_item=True\n)\n\n# defining rooms\nrm_hallway = Room(\n name=\"Hallway\",\n desc=\"Just a regular old hallway.\",\n clues={\n cl_phone.id(): cl_phone,\n cl_painting.id(): cl_painting\n }\n)\nrm_bedroom = Room(\n name=\"Bedroom\",\n desc=\"Looks like a room. Smells like one too.\",\n clues={\n cl_old_key.id(): cl_old_key,\n cl_stained_wall.id(): cl_stained_wall\n }\n)\nrm_dark_alley = Room(\n name=\"Dark Alley\",\n desc=\"Well lit, despite the name.\",\n clues={\n cl_dumpster.id(): cl_dumpster,\n cl_snowglobe.id(): cl_snowglobe\n }\n)\n\n# defining locations\nln_house = Location(\n name=\"House\",\n desc=\"Smells like a house.\",\n rooms={\n rm_hallway.id(): rm_hallway.default(),\n rm_bedroom.id(): rm_bedroom.lock()\n }\n)\nln_street = Location(\n name=\"Street\",\n desc=\"Looks dark, but it's midday.\",\n rooms={\n rm_dark_alley.id(): rm_dark_alley.default()\n }\n)\nln_street_2 = Location(\n name=\"Street\",\n desc=\"Looks dark, but it's midday.\",\n rooms={\n rm_dark_alley.id(): rm_dark_alley.default()\n }\n)\n\n# defining text adventure\ntest_adv = TextAdventure(\n title=\"TITLE\",\n locations={\n ln_house.id(): ln_house.default(),\n ln_street.id(): ln_street\n }\n)\n\n# adding actions\ntest_adv.add_action(\n \"phone\",\n None,\n None,\n cl_note,\n None,\n None,\n \"street\",\n \"dark alley\",\n \"Despite being unplugged, the phone works because it's a mobile phone. Someone on the other end says 'I've left a note for you somewhere.' Before you can reply, they hang up.\",\n \"\"\n)\ntest_adv.add_action(\n \"note\",\n cl_note,\n rm_hallway,\n None,\n None,\n rm_bedroom,\n None,\n None,\n \"You hear a door unlock upstairs.\",\n \"After some fiddling, you come to the conclusion that this item won't work here.\"\n)\n\n# run game, print help menu on start\ntest_adv(True)","repo_name":"nozmos/python_adventure","sub_path":"python_adventure.py","file_name":"python_adventure.py","file_ext":"py","file_size_in_byte":16237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71673173335","text":"# Create your views here.\n\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.generic.base import View\nfrom django.http import HttpResponseRedirect, HttpResponseForbidden\nfrom django.core.urlresolvers import reverse\n\nfrom communities.models import *\n\ndef list(request):\n communities = None\n if \"loc\" in request.GET:\n communities = Community.objects.filter(location=loc)\n else:\n communities = Community.objects.all()\n\n return render(request, \"c_list.html\", {\"communities\":communities})\n\nclass new(View):\n def get(self, request, invalid=False):\n if not request.user.is_authenticated():\n return HttpResponseForbidden()\n\n form = NewCommunityForm()\n return render(request, \"c_new.html\", {\"form\":form, \"invalid\": invalid})\n\n def post(self, request):\n if not request.user.is_authenticated():\n return HttpResponseForbidden()\n \n form = NewCommunityForm(request.POST)\n if form.is_valid():\n community = Community()\n community.owner = request.user\n community.title = form.cleaned_data[\"title\"]\n community.location = form.cleaned_data[\"location\"]\n community.slogan = form.cleaned_data[\"slogan\"]\n community.description= form.cleaned_data[\"description\"]\n\n community.save()\n return HttpResponseRedirect(reverse(\"communities_details\", args=(community.id,)))\n else:\n return get(request, invalid=True)\n\ndef details(request, id):\n community = get_object_or_404(Community, id=id)\n\n return render(request, \"c_details.html\", {\"community\":community})\n\nclass enroll(View):\n def get(self, request, id):\n if not request.user.is_authenticated():\n return HttpResponseForbidden()\n\n community = get_object_or_404(Community, id=id)\n return render(request, \"c_enroll.html\", {\"community\":community})\n\n def post(self, request, id):\n if not request.user.is_authenticated():\n return HttpResponseForbidden()\n\n community = get_object_or_404(Community, id=id)\n membership = Membership(community=community)\n membership.member = request.user\n\n if request.POST[\"enroll\"] == True:\n membership.save()\n\n return HttpResponseRedirect(reverse(\"communities_details\", args=(id,)))\n\ndef manage(request, id):\n \n community = get_object_or_404(Community, id=id)\n if request.method == 'GET':\n form = NewCommunityForm(instance=community)\n\n return render(request, \"c_manage.html\", {\"community\":community, \"form\":form, \"invalid\":False})\n else:\n form = NewCommunityForm(request.POST, instance=community)\n if form.is_valid():\n form.save()\n\n return HttpResponseRedirect(reverse(\"communities_details\", args=(id,)))\n else:\n return render(request, \"c_manage.html\", {\"community\":community, \"form\":form, \"invalid\":True})\n\n","repo_name":"itsbilal/aurora","sub_path":"communities/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"72801958933","text":"from flask import Flask\nfrom flask import request\nimport flask\nimport mongodb\nfrom bson import json_util\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello():\n\tmongoPoll = mongodb.MongoPoll()\n\tret = mongoPoll.getStats()\n\treturn flask.jsonify(ret)\n\n@app.route('/history')\ndef history():\n\tmongoPoll = mongodb.MongoPoll()\n\tquery = {}\n\tlimit = request.args.get('limit')\n\tif limit : \n\t\tquery['limit'] = int(limit)\n\thistory = mongoPoll.getHistory(query)\n\treturn json_util.dumps(history)\n\nif __name__ == '__main__':\n\tapp.debug = True\n\tapp.run()\n\n","repo_name":"knuthp/spartid-poll2db","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"36612523854","text":"from django import forms\nfrom .models import EnrolledPupil\n\n\nclass UploadPupilForm(forms.ModelForm):\n\n \"\"\"\n Form for recipe review\n \"\"\"\n class Meta:\n \"\"\"\n Form has field of body from Review model\n \"\"\"\n model = EnrolledPupil\n fields = (\n 'pupil_last_name', 'pupil_first_name', \n 'school_name', 'teacher_name', 'school_roll_no',\n 'pupil_id', 'approved', )\n","repo_name":"davidcalikes/passport","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39340173025","text":"from itertools import combinations\n\n\ndef solution(numbers):\n answer = []\n indexList = [i for i in range(len(numbers))]\n choice = list(combinations(indexList, 2))\n\n for a, b in choice:\n result = numbers[a] + numbers[b]\n if result not in answer:\n answer.append(result)\n\n answer.sort()\n\n return answer\n","repo_name":"YongsHub/TIL","sub_path":"Algorithm/Programmers level 1/두 개 뽑아서 더하기.py","file_name":"두 개 뽑아서 더하기.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74505418141","text":"#### Caleb Keller ###\r\n#### Hangman 1.0 ####\r\n#### 10/13/2020 #####\r\n#imports\r\nimport random\r\n#Hangman art and lives.\r\nHANGMAN = (\r\n\"\"\"\r\n|-------------\r\n| |\r\n| \r\n| \r\n| \r\n| \r\n| \r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|______________\r\n\"\"\",\r\n\"\"\"\r\n|-------------\r\n| |\r\n| ___\r\n| / \\\\\r\n| \\\\___/\r\n| |\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|\r\n|______________\r\n\"\"\",\r\n\"\"\"\r\n|-------------\r\n| |\r\n| ___\r\n| / \\\\\r\n| \\\\___/\r\n| |\r\n| |\r\n| |\r\n| |\r\n| |\r\n| \r\n|\r\n|\r\n|\r\n|\r\n|\r\n|______________\r\n\"\"\",\r\n\"\"\"\r\n|-------------\r\n| |\r\n| ___\r\n| / \\\\\r\n| \\\\___/\r\n| |\r\n| |\r\n| |\r\n| |\r\n| |\r\n| /\r\n| /\r\n| /\r\n| /\r\n|\r\n|\r\n|______________\r\n\"\"\",\r\n\"\"\"\r\n|-------------\r\n| |\r\n| ___\r\n| / \\\\\r\n| \\\\___/\r\n| |\r\n| |\r\n| |\r\n| |\r\n| |\r\n| / \\\\\r\n| / \\\\\r\n| / \\\\\r\n| / \\\\\r\n|\r\n|\r\n|______________\r\n\"\"\",\r\n\"\"\"\r\n|-------------\r\n| |\r\n| ___\r\n| / \\\\\r\n| \\\\___/\r\n| |\r\n| |\\\\\r\n| | \\\\\r\n| | \\\\\r\n| | \\\\\r\n| / \\\\\r\n| / \\\\\r\n| / \\\\\r\n| / \\\\\r\n|\r\n|\r\n|______________\r\n\"\"\",\r\n\"\"\"\r\n|-------------\r\n| |\r\n| ___\r\n| / \\\\\r\n| \\\\___/\r\n| |\r\n| /|\\\\\r\n| / | \\\\\r\n| / | \\\\\r\n| / | \\\\\r\n| / \\\\\r\n| / \\\\\r\n| / \\\\\r\n| / \\\\\r\n|\r\n|\r\n|______________\r\n\"\"\"\r\n )\r\n#Initialize variables for life amounts (MAX_WRONG), words,\r\n# a random word, what was guessed so far, etc.\r\nMAX_WRONG = len(HANGMAN) - 1\r\nWORDS = (\"ARGUMENT\", \"CLASS\", \"IDE\", \"STRING\", \"DEBUGGER\")\r\nword=random.choice(WORDS)\r\nso_far = \" _ \"*len(word)\r\nused = []\r\nwrong = 0\r\nprint(\"Welcome to Hangman. Good luck!\")\r\n#A statement making it so the game will run until you win or lose.\r\nwhile wrong < MAX_WRONG and so_far!= word:\r\n print(\"\\nIncorrect Letters: \", HANGMAN[wrong])\r\n print(\"\\nWord:\\n\",so_far)\r\n print(\"\\nUsed Letters:\\n\", used)\r\n\r\n guess = input(\"\\n\\nEnter Your Guess: \")\r\n guess = guess.upper()\r\n while guess in used:\r\n print(\"You've already guessed the letter\", guess)\r\n guess = input(\"\\n\\nEnter Your Guess: \")\r\n guess = guess.upper()\r\n used.append(guess)\r\n#Figures out if the guessed letter is in the word or not.\r\n if guess in word:\r\n print(\"\\nYes\", guess, \"is in the word!\")\r\n new = \"\"\r\n for i in range(len(word)):\r\n if guess == word[i]:\r\n new+=guess\r\n else:\r\n new+=so_far[i]\r\n so_far = new\r\n else:\r\n print(\"\\nSorry\", guess, \"isn't in the word.\")\r\n wrong += 1\r\n#This is to check if you win or lose.\r\nif wrong == MAX_WRONG:\r\n print(HANGMAN[wrong])\r\n print(\"\\nSo far the word is\", so_far)\r\n print(\"You lost...\")\r\nelse:\r\n print(HANGMAN[wrong])\r\n print(\"\\nYou guessed it!\")\r\n print(\"\\nThe word was:\\n\", so_far)\r\n if so_far == WORDS[0]:\r\n print(\"Definition: A value passed to a function when calling the function.\")\r\n if so_far == WORDS[1]:\r\n print(\"Definition: An object constructor or \\\"blueprint\\\" for creating objects.\")\r\n if so_far == WORDS[2]:\r\n print(\"Definition: An Integrated Development Enviornment, or a program dedicated to software development.\")\r\n if so_far == WORDS[3]:\r\n print(\"Definition: A line of text in code surrounded by quote marks.\")\r\n if so_far == WORDS[4]:\r\n print(\"Definition: A program that can help you find out what's going on and fix errors in a program.\")\r\ninput(\"\\n\\nPress enter key to exit.\")\r\n\r\n","repo_name":"Randomperson999/Python-2020","sub_path":"Earlier/Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"34709348853","text":"from tkinter import *\n\nroot = Tk()\nnumber = IntVar()\n\ndef increment():\n value = number.get() + 1\n number.set(value)\n\n\nlabel = Label(root, textvariable=number).pack()\nplus_button = Button(root, text=\"Increment\", command=increment).pack()\n\nroot.mainloop()","repo_name":"amortimer20/python-stuff","sub_path":"tkinter/demo-apps/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17530790967","text":"\n# coding: utf-8\n\n# # Introduction\n# \n# FIFA, also known as FIFA Football or FIFA Soccer, is a series of association football video games or football simulator, released annually by Electronic Arts under the EA Sports label.\n\n# In[1]:\n\n\nimport os\nimport time\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# In[2]:\n\n\ndirectory = os.getcwd()\n\n\n# In[3]:\n\n\nos.chdir(directory + '//data')\n\n\n# In[4]:\n\n\nattribute = pd.read_csv('PlayerAttributeData.csv', low_memory=False)\npersonal = pd.read_csv('PlayerPersonalData.csv', low_memory=False)\nposition = pd.read_csv('PlayerPlayingPositionData.csv', low_memory=False)\ncomplete_data = pd.read_csv(\"CompleteDataset.csv\", low_memory=False)\n\n\n# **Make a copy of the data frame**\n\n# In[5]:\n\n\nattribute_df = attribute.copy()\npersonal_df = personal.copy()\nposition_df = position.copy()\ncomplete_data_df = complete_data.copy()\n\n\n# ### Assess\n\n# In[6]:\n\n\nattribute_df.head()\n\n\n# In[7]:\n\n\npersonal_df.head()\n\n\n# In[8]:\n\n\nposition_df.head()\n\n\n# In[9]:\n\n\ncomplete_data_df.head()\n\n\n# **Quality**\n# \n# ##### `attribute_df` table\n# - Remove unmaned column\n# - Numeric data types are string\n# - ID should be sting not integer\n# - Values have an additon numbers with them too. e.g. For `ID` `213661` has acceleration as `70+9`\n# \n# ##### `personal_df` table\n# - Remove unmaned column\n# - Numeric data type are string\n# - ID should be sting not integer\n# \n# ##### `position_df` table\n# - Remove unmaned column\n# - Numeric data type are string\n# - ID should be sting not integer\n# \n# ##### `complete_data_df` table\n# - Remove unmaned column\n# - Numeric data type are string\n# - ID should be sting not integer\n# \n# **Tidiness**\n\n# In[10]:\n\n\nattribute_df.info()\n\n\n# In[11]:\n\n\npersonal_df.info()\n\n\n# In[12]:\n\n\nposition_df.info()\n\n\n# In[13]:\n\n\ncomplete_data_df.info()\n\n\n# ### Cleaning\n\n# ##### `attribute_df` , `personal_df`, `position_df` : **Remove columns**\n# \n# **Define:**\n# \n# The unwanted columns should be removed\n# \n# **Code:**\n\n# In[14]:\n\n\nattribute_df = attribute_df.drop(['Unnamed: 0'], axis=1)\npersonal_df = personal_df.drop(['Unnamed: 0', 'Unnamed: 0.1'], axis=1)\nposition_df = position_df.drop(['Unnamed: 0'], axis=1)\ncomplete_data_df = complete_data_df.drop(['Unnamed: 0'], axis=1)\n\n\n# **Test**\n\n# In[15]:\n\n\nattribute_df.head(2)\n\n\n# In[16]:\n\n\npersonal_df.head(2)\n\n\n# In[17]:\n\n\nposition_df.head(2)\n\n\n# In[18]:\n\n\ncomplete_data_df.head(2)\n\n\n# In[19]:\n\n\nattribute_df[attribute_df.ID==213661]\n\n\n# In[20]:\n\n\nattribute_df.iloc[309]\n\n","repo_name":"rohit-yadav/fifa-18","sub_path":"fifa18.py","file_name":"fifa18.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"17168073994","text":"print (\"Import Line module\")\nimport cv2\nimport numpy as np\n\ndef Line(frame):\n center = 0\n #dst = np.zeros_like(frame)\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n mean = np.mean(gray)\n adj = mean*0.7\n if adj > 80:\n adj = 80\n if adj < 20:\n adj = 20\n mask_white = cv2.inRange(gray, mean+adj, 255)\n #mask_white = mask_white[100:120,:] #(20,480)\n __, contours,_ = cv2.findContours(mask_white,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n for cnt in contours:\n if (cv2.contourArea(cnt) > 150):\n x,y,w,h = cv2.boundingRect(cnt)\n center = int(x+w/2)\n return center\n","repo_name":"fpt-corp/DiRa","sub_path":"DiRa_Software/Reference/Source code final 2018-2019/MTA-R4F-Digital_race_2019/src_25_5_13_56/r4f/src/modules/Line.py","file_name":"Line.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"69"} +{"seq_id":"38006368932","text":"from django.db import models\n\n# Create your models here.\nclass BlogPost(models.Model):\n\ttitle=models.CharField(max_length=150)\n\tblog_type_choices=(\n\t\t('Programming',(\n\t\t\t\t('PYTHON','python'),\n\t\t\t\t('CPP','c++'),\n\t\t\t\t('C','c'),\n\t\t\t\t('DJANGO','django'),\n\t\t\t\t('RUBY','ruby'),\n\t\t\t)\n\t\t),\n\t\t('Job Hunting',(\n\t\t\t\t('BUS','Business'),\n\t\t\t\t('CMPT','Computing Science'),\n\t\t\t\t('ENEG','Engineering'),\n\t\t\t)\n\t\t),\n\t\t('LIFE','Life'),\n\t)\n\tblog_type=models.CharField(max_length=20,choices=blog_type_choices)\n\tbody=models.TextField()\n\ttimestamp=models.DateTimeField()\n\tdef __unicode__(self):\n\t\treturn self.title\n\tsearch_fields = ['title']\n\tdate_hierarchy = 'timestamp'\n\t","repo_name":"ccjinyang/mysite","sub_path":"mysite/myblog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"835144623","text":"import pandas as pd\nimport os\n\n# Obtener la ruta del script actual\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\n\n# Crear la carpeta \"mapa_html\" si no existe\nfolder_path = os.path.join(current_path, 'datasets')\nos.makedirs(folder_path, exist_ok=True)\n\n# Ruta del archivo HTML en la carpeta \"mapa_html\"\nfile_read = os.path.join(folder_path, 'ZoneA.dat')\n\ndata=pd.read_csv(file_read)\n\n#extraer coordenadas\ncoordenadas=[] # definir una lista para guardar las coordenadas\n#ciclo para OBTENER coordenadas\nfor d in range(9,len(data)):\n x=(data.iloc[d,0]).split(' ')[0];y=(data.iloc[d,0]).split(' ')[1]\n z=(data.iloc[d,0]).split(' ')[4]\n coordenadas.append([x,y,z])\n\nfor d in range(9,len(data)):\n x=float(data.iloc[d,0].split(' ')[0]);y=float(data.iloc[d,0].split(' ')[1])\n z=float(data.iloc[d,0].split(' ')[4]) #leer la permeabilidad en la posicion 4\n coordenadas.append([x,y,z])\n\n#leer el fichero usando el modulo de geoestadistica\nfrom geostatsmodels import utilities\n#leer datos\nfile='ZoneA.dat'\nz = utilities.readGeoEAS(path+file)\ndata = z[:,[0,1,2]]","repo_name":"marianoq/web_python_django","sub_path":"python_DATA/leer_dat.py","file_name":"leer_dat.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12096568639","text":"# -*- coding:utf-8 -*-\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport json\n\nplt.rcParams['font.family'] = 'Malgun Gothic'\n\nwith open('pet_salon.json', 'r', encoding='utf-8') as f:\n petsalon_json = json.load(f)\ngus = petsalon_json.keys()\ncnt_dict = {}\nfor gu in gus:\n cnt = len(petsalon_json[gu])\n cnt_dict[gu] = cnt\ndf = pd.DataFrame.from_dict([cnt_dict])\n\ntot = 0\nfor i in range(len(df.values[0])):\n tot += df.values[0][i]\n\npet_salon = df.columns.values\npet_salon_data = df.values\npet_salon_score = pd.DataFrame(pet_salon_data[0],index=pet_salon, columns=['salon'])\n# print(pet_salon_score)","repo_name":"Ljaewon-123/Multicampus-boot-camp","sub_path":"Visual_Project/real_real_final/pet_service/analysis/pet_salon.py","file_name":"pet_salon.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11443799722","text":"valores = []\nvalores_impares = []\nvalores_pares = []\n\nwhile True:\n valor = int(input('Digite um número: '))\n valores.append(valor)\n if valor % 2 == 0:\n valores_pares.append(valor)\n else:\n valores_impares.append(valor)\n s_n = str(input('Quer continuar ? [S/N] ')).upper().split()[0]\n if s_n == 'N':\n break\n\nprint(f'A lista completa é {valores}.')\nprint(f'A lista de pares é {valores_pares}.')\nprint(f'A lista de impares é {valores_impares}.')","repo_name":"AlexandroZP/python","sub_path":"Curso_em_video/Mundo_3/exercicios/ex082.py","file_name":"ex082.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"8166631966","text":"import re\n\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import validate_ipv4_address, validate_ipv6_address\n\n\nRE_NAME = re.compile(r'^([\\w]{1,2}|[\\w][\\w-]{0,61}[\\w])'\n r'([.]([\\w]{1,2}|[\\w][\\w-]{0,61}[\\w]))*[.]?$')\n\n\ndef validate_parameters(type, parameters):\n parameters_validators = RECORD_TYPES.get(type.lower())\n if parameters is None:\n return parameters\n new_parameters = {}\n for name, validator in parameters_validators.iteritems():\n if name not in parameters:\n raise ValidationError({'parameters': ['Missing type parameter: %r' % name]})\n else:\n try:\n validated = validator(parameters[name])\n if validated is not None:\n new_parameters[name] = validated\n else:\n new_parameters[name] = parameters[name]\n except ValidationError as err:\n raise ValidationError({'parameters.%s' % name: err.messages})\n return new_parameters\n\n\ndef validate_name(value):\n value = str(value)\n if len(value) > 255:\n raise ValidationError('Name is too long')\n elif not RE_NAME.match(value):\n raise ValidationError('Bad name')\n\n\ndef validate_int(value):\n value = int(value)\n if not 0 <= value <= 65535:\n raise ValidationError('Bad value, must be between the range 0-65535')\n\n\nRECORD_TYPES = {'a': {'ip': validate_ipv4_address},\n 'aaaa': {'ipv6': validate_ipv6_address},\n 'cname': {'name': validate_name},\n 'mx': {'pref': validate_int, 'name': validate_name},\n 'ns': {'name': validate_name},\n 'srv': {'priority': validate_int, 'weight': validate_int,\n 'port': validate_int, 'target': validate_name},\n 'txt': {'text': lambda x:x},\n 'hinfo': {'hardware': lambda x:x, 'os': lambda x:x},\n 'ptr': {'name': validate_name},\n 'spf': {'text': lambda x:x},\n 'include': {'zone': validate_name}}\n","repo_name":"NaPs/restdns","sub_path":"restdns/record_types.py","file_name":"record_types.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"30524913906","text":"from typing import Generator\n\nfrom natsort import natsort_keygen\nfrom pyjkernel import JKRArchive, JKRArchiveFile\nfrom pymsb import LMSDocument, LMSMessage, LMSFlows, LMSEntryNode, LMSMessageNode, LMSBranchNode\nfrom adapter_smg2 import SuperMarioGalaxy2Adapter\nimport pymsb\n\n__all__ = [\"LMSAccessor\"]\n\n\nclass LMSAccessor:\n __LABEL_SORT_KEY__ = natsort_keygen(key=lambda e: e.label)\n\n def __init__(self, name: str, archive: JKRArchive, adapter: type[SuperMarioGalaxy2Adapter]):\n \"\"\"\n Creates a new ``LMSAccessor`` with the specified name and adapter. The given archive will be used to retrieve\n contents from and save files to. If there are no MSBT or MSBF files, blank new holders will be constructed.\n Otherwise, the messages and flowcharts will be constructed from the files.\n\n :param name: the name of MSBT and MSBF files.\n :param archive: the RARC archive.\n :param adapter: the adapter maker used to construct the game-specific adapter.\n \"\"\"\n self._name_: str = name\n self._archive_: JKRArchive = archive\n self._document_: LMSDocument\n self._flows_: LMSFlows\n\n msbt_path = create_msbt_file_path(self._archive_, self._name_)\n msbf_path = create_msbf_file_path(self._archive_, self._name_)\n\n if self._archive_.directory_exists(msbt_path):\n self._document_ = pymsb.msbt_from_buffer(adapter, self._archive_.get_file(msbt_path).data)\n else:\n self._document_ = LMSDocument(adapter)\n\n if self._archive_.directory_exists(msbf_path):\n self._flows_ = pymsb.msbf_from_buffer(adapter, self._archive_.get_file(msbf_path).data)\n self._link_flowcharts_with_message_labels_()\n else:\n self._flows_ = LMSFlows(adapter)\n\n @property\n def name(self) -> str:\n \"\"\"Returns the accessor's name.\"\"\"\n return self._name_\n\n @property\n def archive(self) -> JKRArchive:\n \"\"\"Returns the parent archive.\"\"\"\n return self._archive_\n\n @property\n def messages(self) -> list[LMSMessage]:\n \"\"\"Returns the list of messages.\"\"\"\n return self._document_.messages\n\n @property\n def flowcharts(self) -> list[LMSEntryNode]:\n \"\"\"Returns the list of flowcharts.\"\"\"\n return self._flows_.flowcharts\n\n # ------------------------------------------------------------------------------------------------------------------\n\n def get_message(self, label: str) -> LMSMessage:\n \"\"\"\n Retrieves the message entry with the specified label. If there's no associated entry, a KeyError will be thrown.\n\n :param label: the message's label.\n :return: the message entry.\n \"\"\"\n for message in self.messages:\n if message.label == label:\n return message\n\n raise KeyError(f\"No message labeled {label} found!\")\n\n def new_message(self, label: str) -> LMSMessage:\n \"\"\"\n Creates and returns a new message entry using the given label and adds it to the list of messages. If an entry\n with the same label already exists, an LMSException will be thrown.\n\n :param label: the new message's label.\n :return: the new message entry.\n \"\"\"\n return self._document_.new_message(label)\n\n def delete_message(self, label: str) -> bool:\n \"\"\"\n Tries to delete the message entry with the specified label. If there's at least one flow node that references\n this label, the entry won't be removed. If there's no entry with such label, a KeyError will be thrown.\n\n :param label: the message's label that should be deleted.\n :return: True if the message was deleted, otherwise False.\n \"\"\"\n # Don't delete message if referenced by a flow node\n for flowchart in self.flowcharts:\n for node in filter(lambda n: type(n) == LMSMessageNode, flattened_nodes(flowchart)):\n if node.message_label == label:\n return False\n\n # Find index of message associated with label\n index = -1\n\n for i, message in enumerate(self.messages):\n if message.label == label:\n index = i\n break\n\n if index == -1:\n raise KeyError(f\"No message labeled {label} found!\")\n\n # If allowed, remove the actual entry\n self.messages.pop(index)\n return True\n\n def rename_message(self, old_label: str, new_label: str) -> bool:\n \"\"\"\n Tries to rename the message entry with the specified labels. If the two labels are the same, nothing is done,\n but True is returned. If there's at least one other message entry whose name is the same as the new label, False\n will be returned and no renaming occurs. Otherwise, the old label will be renamed to the new label. This also\n affects all flow nodes. If there's no entry with such label, a KeyError will be thrown.\n\n :param old_label: the label of the message whose name should be renamed.\n :param new_label: the new name.\n :return: True if the labels are the same or if renaming was successful, otherwise False.\n \"\"\"\n if old_label == new_label:\n return True\n\n # Find message entry associated with label\n associated_message: LMSMessage | None = None\n\n for message in self.messages:\n if message.label == old_label:\n associated_message = message\n elif message.label == new_label:\n return False\n\n if associated_message is None:\n raise KeyError(f\"No message labeled {old_label} found!\")\n\n # Update message entry's label and flow node references\n associated_message.label = new_label\n\n for flowchart in self.flowcharts:\n for node in filter(lambda n: type(n) == LMSMessageNode, flattened_nodes(flowchart)):\n if node.message_label == old_label:\n node.message_label = new_label\n\n return True\n\n def sort_messages(self):\n \"\"\"Sorts all messages by their labels in natural ascending order.\"\"\"\n self._document_.messages.sort(key=self.__LABEL_SORT_KEY__)\n\n # ------------------------------------------------------------------------------------------------------------------\n\n def get_flowchart(self, label: str) -> LMSEntryNode:\n \"\"\"\n Retrieves the flowchart with the specified label. If there's no associated flowchart, a KeyError will be thrown.\n\n :param label: the flowchart's label.\n :return: the flowchart.\n \"\"\"\n for flowchart in self.flowcharts:\n if flowchart.label == label:\n return flowchart\n\n raise KeyError(f\"No flowchart labeled {label} found!\")\n\n def new_flowchart(self, label: str) -> LMSEntryNode:\n \"\"\"\n Creates and returns a new flowchart using the given label and adds it to the list of flowcharts. If a flowchart\n with the same label already exists, an LMSException will be thrown.\n\n :param label: the new message's label.\n :return: the new flowchart.\n \"\"\"\n return self._flows_.new_flowchart(label)\n\n def delete_flowchart(self, label: str) -> bool:\n \"\"\"\n Tries to delete the flowchart with the specified label. This always returns True. If there's no flowchart with\n such label, a KeyError will be thrown.\n\n :param label: the flowchart's label that should be deleted.\n :return: always True.\n \"\"\"\n # Find index of message associated with label\n index = -1\n\n for i, flowchart in enumerate(self.flowcharts):\n if flowchart.label == label:\n index = i\n break\n\n if index == -1:\n raise KeyError(f\"No flowchart labeled {label} found!\")\n\n # Remove the actual entry\n self.flowcharts.pop(index)\n return True\n\n def rename_flowchart(self, old_label: str, new_label: str) -> bool:\n return False\n\n def sort_flowcharts(self):\n \"\"\"Sorts all flowcharts by their labels in natural ascending order.\"\"\"\n self._flows_.flowcharts.sort(key=self.__LABEL_SORT_KEY__)\n\n # ------------------------------------------------------------------------------------------------------------------\n\n def save(self):\n \"\"\"\n Packs the messages and flowcharts and saves them to their respective MSBT/MSBF files in the archive. If either\n has no entries, the respective files won't be created or will be removed if they exist.\n \"\"\"\n msbt_file: JKRArchiveFile\n msbf_file: JKRArchiveFile\n msbt_path = create_msbt_file_path(self._archive_, self._name_)\n msbf_path = create_msbf_file_path(self._archive_, self._name_)\n\n # Always pack and keep MSBT\n if not self._archive_.directory_exists(msbt_path):\n msbt_file = self._archive_.create_file(msbt_path)\n else:\n msbt_file = self._archive_.get_file(msbt_path)\n\n msbt_file.data = self._document_.makebin()\n\n # Pack and keep MSBF if and only if there is at least one flowchart\n if len(self._flows_.flowcharts) > 0:\n if not self._archive_.directory_exists(msbf_path):\n msbf_file = self._archive_.create_file(msbf_path)\n else:\n msbf_file = self._archive_.get_file(msbf_path)\n\n self._link_flowcharts_with_message_indexes_()\n msbf_file.data = self._flows_.makebin()\n\n elif self._archive_.directory_exists(msbf_path):\n self._archive_.remove_file(msbf_path)\n\n def delete(self):\n \"\"\"\n Clears all message entries, flowcharts, and removes associated MSBT and MSBF files in the archive.\n \"\"\"\n msbt_path = create_msbt_file_path(self._archive_, self._name_)\n msbf_path = create_msbf_file_path(self._archive_, self._name_)\n\n self.messages.clear()\n self.flowcharts.clear()\n\n if self._archive_.directory_exists(msbt_path):\n self._archive_.remove_file(msbt_path)\n\n if self._archive_.directory_exists(msbf_path):\n self._archive_.remove_file(msbf_path)\n\n def _link_flowcharts_with_message_labels_(self):\n for flowchart in self.flowcharts:\n for node in filter(lambda n: type(n) == LMSMessageNode, flattened_nodes(flowchart)):\n node.message_label = self.messages[node.msbt_entry_idx].label\n\n def _link_flowcharts_with_message_indexes_(self):\n message_labels = [m.label for m in self.messages]\n\n for flowchart in self.flowcharts:\n for node in filter(lambda n: type(n) == LMSMessageNode, flattened_nodes(flowchart)):\n node.msbt_entry_idx = message_labels.index(node.message_label)\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# Helper functions for MSBT/MSBF files\n\ndef flattened_nodes(flowchart: LMSEntryNode) -> Generator:\n \"\"\"\n Generator that yields the flow nodes in the given flowchart. This is done using breadth-first search, starting at\n the root node. Every flow node will be yielded exactly once, even if they are referenced more than once.\n\n :param flowchart: the flowchart.\n :return: the next flow node.\n \"\"\"\n remaining = [flowchart]\n marked = set()\n\n while len(remaining) > 0:\n current_node = remaining.pop(0)\n next_node = current_node.next_node\n marked.add(current_node)\n\n if next_node is not None and next_node not in marked:\n remaining.append(next_node)\n\n if type(current_node) == LMSBranchNode:\n next_node = current_node.next_node_else\n\n if next_node is not None and next_node not in marked:\n remaining.append(next_node)\n\n yield current_node\n\n\ndef create_msbt_file_path(archive: JKRArchive, lms_name: str) -> str:\n \"\"\"\n Constructs the MSBT file path to the LMS document in the given archive.\n\n :param archive: the archive.\n :param lms_name: the LMS document's name\n :return: the file path.\n \"\"\"\n return f\"{archive.root_name}/{lms_name}.msbt\"\n\n\ndef create_msbf_file_path(archive: JKRArchive, lms_name: str) -> str:\n \"\"\"\n Constructs the MSBF file path to the LMS flows in the given archive.\n\n :param archive: the archive.\n :param lms_name: the LMS flows' name\n :return: the file path.\n \"\"\"\n return f\"{archive.root_name}/{lms_name}.msbf\"\n","repo_name":"SunakazeKun/galaxymsbt","sub_path":"msbtaccess.py","file_name":"msbtaccess.py","file_ext":"py","file_size_in_byte":12529,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"16759002998","text":"from PyPDF2 import PdfFileReader, PdfFileWriter\nfrom _gen_stamp import *\nimport os\n\n\ndef stamp_document(code, origin_path, file_name, destination_path):\n \"\"\"\n Creating & inserting stamp to the single file in the `origin_path`.\n \"\"\"\n from_path = os.path.join(origin_path, file_name)\n doc_num = file_name[:3]\n new_pdf = PdfFileReader(open(from_path, \"rb\"),strict=False)\n n_page = new_pdf.numPages\n output = PdfFileWriter()\n for i in range(n_page):\n pageobj = new_pdf.getPage(i)\n _, _, x, y = pageobj.mediaBox\n stamp = generate_stamp(x, y, code, doc_num, i + 1)\n pageobj.mergePage(stamp)\n output.addPage(pageobj)\n to_path = os.path.join(destination_path, file_name)\n outputStream = open(to_path, \"wb\")\n output.write(outputStream)\n outputStream.close()\n","repo_name":"Seonu-Lim/Dobby","sub_path":"src/_stamper.py","file_name":"_stamper.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"398304708","text":"import mediapipe\nimport cv2\nfrom protobuf_to_dict import protobuf_to_dict\n\n \ndrawingModule = mediapipe.solutions.drawing_utils\nhandsModule = mediapipe.solutions.hands\n\ncap = cv2.VideoCapture(0)\nfourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\n\nwith handsModule.Hands(static_image_mode=False, min_detection_confidence=0.7, min_tracking_confidence=0.7, max_num_hands=2) as hands:\n\n while True:\n ret, frame = cap.read()\n #frame = cv2.imread('C:/Users/saikk/Pictures/Camera Roll/Laptop camera image.jpg', 0)\n frame1 = cv2.resize(frame, (640, 480))\n results = hands.process(cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB))\n \n if results.multi_hand_landmarks != None:\n for handLandmarks in results.multi_hand_landmarks:\n drawingModule.draw_landmarks(frame1, handLandmarks, handsModule.HAND_CONNECTIONS)\n \n for landmark in results.multi_hand_landmarks:\n c = 0\n sum_x = 0\n sum_y = 0\n for i in landmark.landmark:\n sum_x+=i.x\n sum_y+=i.y\n c+=1\n avg_x = sum_x/c\n avg_y = sum_y/c\n print(c)\n if(avg_x1.2):\n print('MOVE DOWN')\n elif(avg_x>avg_y and avg_x+avg_y<1.2):\n print('MOVE UP')\n elif(avg_x>avg_y and avg_x+avg_y>1.2):\n print('MOVE LEFT')\n \n cv2.imshow(\"Frame\", frame1);\n key = cv2.waitKey(1) & 0xFF\n \n if key == ord(\"q\"):\n break\ncv2.destroyAllWindows()\n","repo_name":"saikk9834/Hand-Gesture-Recognition-for-Hand-Steerable-Light-System-using-Nvidia-Jetson-Nano","sub_path":"simple hand tracker.py","file_name":"simple hand tracker.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"71386296220","text":"import PySimpleGUI as sg\nfrom random import choice\n\n# \n# ____ _ ____ _ _ \n# | _ \\(_) ___ ___ | _ \\ ___ | | | ___ _ __ \n# | | | | |/ __/ _ \\ | |_) / _ \\| | |/ _ \\ '__|\n# | |_| | | (_| __/ | _ < (_) | | | __/ | \n# |____/|_|\\___\\___| |_| \\_\\___/|_|_|\\___|_| \n# \n# \n\ndados = ['\\u2680', '\\u2681', '\\u2682', '\\u2683', '\\u2684', '\\u2685']\n\ndef jogada():\n return choice(dados)\n \nsg.theme('DarkAmber')\n\nlayout = [\n [sg.Text(jogada(), key='-dado1-', font=('Arial', 180)),\n sg.Text(jogada(), key='-dado2-', font=('Arial', 180))],\n [sg.Stretch(),\n sg.Button('Nova_Jogada'),\n sg.Button('Regras_do_Jogo'),\n sg.Button('Sair_do_Jogo'),\n sg.Stretch()]\n ]\n\nwindow = sg.Window('Jogo de Dados', layout)\n\nwhile True:\n event, values = window.read()\n if event == sg.WINDOW_CLOSED or event == 'Sair_do_Jogo':\n break\n elif event == 'Nova_Jogada':\n window['-dado1-'].update(jogada())\n window['-dado2-'].update(jogada())\n elif event == 'Regras_do_Jogo':\n sg.Popup('REGRAS DO JOGO',\n '''\n1 - Através de sorteio do tipo 'Cara ou Coroa' ou 'Par ou Ímpar' decide quem vai começar o jogo...\n2 - O primeiro jogador abre o software e anota a pontuação contando e somando os pontos dos dois dados...\n3 - O jogadores seguintes clicam em nova jogada e também anotam a pontuação...\n4 - A quantidade de jogada pode ser decidida previamente...\n5 - Ganha o jogador que fizer a melhor pontuação...\n6 - Se houver empate, joga-se novas partidas até que decida o vencedor...\n\nEste jogo foi criado inteiramente em Python por Elizeu Barbosa Abreu...\nLinkedin -> https://www.linkedin.com/in/elizeu-barbosa-abreu-69965b218/\nGitHub -> https://github.com/elizeubarbosaabreu\n''')\n \nwindow.close()\n \n","repo_name":"elizeubarbosaabreu/Dice-Roller","sub_path":"App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"1019143313","text":"from __future__ import annotations\nimport cv2\nimport numpy as np\nimport pandas as pd\n\nclass VideoRecorder:\n \"\"\"\n Handler for recording data\n\n Parameters\n ----------\n filename : name of the video file to be saved\n resolution : resolution of recorded video\n\n Attributes\n ----------\n filename : name of the video file to be saved\n resolution : resolution of recorded video\n out : output video writer object\n\n \"\"\"\n\n def __init__(self, filename, resolution):\n self.filename = filename\n self.resolution = (resolution, resolution)\n\n def __enter__(self) -> VideoRecorder:\n self.out = cv2.VideoWriter(f\"{self.filename}.mp4\", cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30, self.resolution)\n\n self.boxes = []\n self.classes = []\n self.scores = []\n self.distances = []\n\n self.focal_v = []\n self.focal_h = []\n self.weights = []\n self.calibrated = []\n\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\n self.out.release()\n df = pd.DataFrame({\"boxes\": self.boxes, \"classes\": self.classes, \"scores\": self.scores,\n \"distances\": self.distances, \"focal_vertical\": self.focal_v,\n \"focal_horizontal\": self.focal_h, \"weights\": self.weights, \"calibrated\": self.calibrated})\n\n df.to_pickle(f\"{self.filename}.pickle\")\n\n def log(self, boxes, classes, scores, distances, focal_v, focal_h, weights, calibrated):\n self.boxes.append(boxes)\n self.classes.append(classes)\n self.scores.append(scores)\n self.distances.append(distances)\n\n self.focal_v.append(focal_v)\n self.focal_h.append(focal_h)\n self.weights.append(weights)\n self.calibrated.append(calibrated)\n\n def write(self, frame: np.ndarray) -> None:\n self.out.write(cv2.resize(frame, self.resolution))\n","repo_name":"PWiercioch/Master-Thesis","sub_path":"Application/video_recorder.py","file_name":"video_recorder.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4200998933","text":"from twilio.rest import Client #Chama a classe cliente do modulo twilio.rest\n\n\n# SID da sua conta, encontre em twilio.com/console\naccount_sid = \"AC7efb7150287d452fc8725df8d1daac07\"\n# Seu Auth Token, encontre em twilio.com/console\nauth_token = \"8ccd6cc5cd06ed324d58acdfd6b918b3\"\n\nclient = Client(account_sid, auth_token) #Instancia a classe cliente e chama o construtor passando dois parametros\n\n\n\ncall = client.calls.create(\n to=\"+5535984434914\", \n from_=\"+554139075373\",\n url=\"https://handler.twilio.com/twiml/EH93cee988cf07f6624e09d2813dc88898\"\n )\n\nprint(call.sid)","repo_name":"FabricioPP/LearnPython","sub_path":"twilio_call_test/twilio_teste.py","file_name":"twilio_teste.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28422622490","text":"import numpy as np\n\n_gaussTri3Xsi = np.array([0.166666666666667,0.666666666666667,0.166666666666667])\n_gaussTri3Eta = np.array([0.166666666666667,0.166666666666667,0.666666666666667])\n_gaussTri3Weight = np.array([0.166666666666667,0.166666666666667,0.166666666666667])\n\n_gaussEdg2Xsi = np.array([-0.5773502691896257, 0.5773502691896257])\n_gaussEdg2Weight = np.array([1.0,1.0])\n\nclass IntegrationRule(object):\n\n def __init__(self,elementType,n):\n if (elementType == \"Triangle\" and n == 3) :\n self.name = \"Gauss with 3 points\"\n self.n = n\n self.xsi = _gaussTri3Xsi\n self.eta = _gaussTri3Eta\n self.weight = _gaussTri3Weight\n elif (elementType == \"Edge\" and n == 2) :\n self.name = \"Gauss with 2 points\"\n self.n = n\n self.xsi = _gaussEdg2Xsi\n self.weight = _gaussEdg2Weight\n else :\n self.name = \"Unknown rule\"\n self.n = 0\n\n def printf(self):\n print(\" Integration rule : %s \" % self.name)\n print(\" Number of nodes = %d \" % self.n)\n print(\" xsi = \",self.xsi)\n print(\" eta = \",self.eta)\n print(\" weights = \",self.weight)\n\n# -------------------------------------------------------------------------\n \nclass Mesh(object):\n \n def __init__(self,fileName,R):\n with open(fileName,\"r\") as f :\n self.nNode = int(f.readline().split()[3])\n self.xyz = np.array(list(list(float(w) for w in f.readline().split()[2:]) for i in range(self.nNode)))\n self.nElem = int(f.readline().split()[3])\n self.elem = np.array(list(list(int(w) for w in f.readline().split()[2:]) for i in range(self.nElem)))\n self.xStar = self.xyz[:,0]\n self.yStar = self.xyz[:,1]\n self.zStar = self.xyz[:,2] \n self.xy = np.array(list(list(np.array([2*R*self.xStar[i] / (R + self.zStar[i]),2*R*self.yStar[i] / (R + self.zStar[i])]) for i in range(self.nNode))))\n self.x = self.xy[:,0]\n self.y = self.xy[:,1] \n self.lola = np.array(list(list(np.array([np.arctan2(self.yStar[i],self.xStar[i])*180/np.pi,np.arcsin(self.zStar[i]/R)*180/np.pi]) for i in range(self.nNode))))\n self.longitude = self.lola[:,0]\n self.latitude = self.lola[:,1] \n \n def printf(self):\n print(\"Number of nodes %d\" % self.nNode)\n print(\"\")\n print(\"Mesh (3D) xStar yStar zStar\")\n for i in range(self.nNode):\n print(\"%6d : %14.7e %14.7e %14.7e\" % (i,*self.xyz[i,:]))\n print(\"\")\n print(\"Mesh (2D) x y\")\n for i in range(self.nNode):\n print(\"%6d : %14.7e %14.7e\" % (i,*self.xy[i,:]))\n print(\"\")\n print(\" Longitude Latitude\")\n for i in range(self.nNode):\n print(\"%6d : %14.7e %14.7e\" % (i,*self.lola[i,:]))\n print(\"\")\n print(\"Number of triangles %d\" % self.nElem)\n for i in range(self.nElem):\n print(\"%6d : %6d %6d %6d\" % (i,*self.elem[i,:]))\n \n# -------------------------------------------------------------------------\n \nclass Edges(object):\n\n def __init__(self,mesh):\n self.mesh = mesh\n self.nEdges = mesh.nElem * 3\n self.nBoundary = 0\n self.edges = [[0 for i in range(4)] for i in range(self.nEdges)]\n for i in range (mesh.nElem) :\n for j in range(3) :\n id = i*3 + j\n self.edges[id][0] = mesh.elem[i][j]\n self.edges[id][1] = mesh.elem[i][(j+1)%3]\n self.edges[id][2] = i\n self.edges[id][3] = -1\n self.edges.sort(key = lambda item : -(min(item[0:2])*self.nEdges)-max(item[0:2]))\n index = 0\n for i in range(self.nEdges) :\n if (self.edges[i][0:2] != self.edges[i-1][1::-1]) :\n self.edges[index] = self.edges[i]\n index += 1\n else :\n self.edges[index-1][3] = self.edges[i][2]\n del self.edges[index:]\n self.edges.sort(key = lambda item : item[3])\n self.nBoundary = 2*index - self.nEdges\n self.nEdges = index\n\n def printf(self):\n print(\"Number of edges %d\" % self.nEdges)\n print(\"Number of boundary edges %d\" % self.nBoundary)\n for i in range(self.nEdges):\n print(\"%6d : %4d %4d : %4d %4d\" % (i,*self.edges[i]))\n\n# -------------------------------------------------------------------------\n \nclass Tsunami(object):\n \n def __init__(self,fileName,R,U,V,E):\n self.mesh = Mesh(fileName,R);\n self.edges = Edges(self.mesh);\n self.U = U;\n self.V = V;\n self.E = E; \n \n def writeFile(self,fileName):\n nElem = self.E.shape[0]; \n with open(fileName,\"w\") as f :\n f.write(\"Number of elements %d\\n\" % nElem)\n for i in range(nElem):\n f.write(\"%6d : %14.7e %14.7e %14.7e\\n\" % (i,*E[i,:]))\n print(\" === iteration %6d : writing %s ===\" % (iter,fileName))\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","repo_name":"romaingrx/Tsunami-simulator","sub_path":"src/Calculator/femTsunami.py","file_name":"femTsunami.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"18495166662","text":"\"\"\"\nFor simplicity in the implementation, we do not allow (or take into consideration) the sharing \nof feature extractors between policies and Q networks, algorithms that do require the \nsharing extractors (for example, CARE) should maintain its own extractor in its respective algorithm class\n\"\"\"\nfrom typing import Any, Dict, List, Optional, Type, Union, Tuple\n\nimport gym\nimport torch as th\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom stable_baselines3.dqn.policies import DQNPolicy\nfrom stable_baselines3.common.distributions import (\n Distribution,\n CategoricalDistribution,\n make_proba_distribution,\n)\nfrom stable_baselines3.common.utils import get_schedule_fn\nfrom stable_baselines3.common.policies import BasePolicy, ContinuousCritic, BaseModel\nfrom stable_baselines3.common.torch_layers import (\n BaseFeaturesExtractor,\n FlattenExtractor,\n create_mlp,\n)\n\n\nclass DiscretePolicy(BasePolicy):\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n net_arch: List[int],\n features_extractor: nn.Module,\n features_dim: int,\n activation_fn: Type[nn.Module] = nn.ReLU,\n normalize_images: bool = True,\n ):\n super().__init__(\n observation_space,\n action_space,\n features_extractor=features_extractor,\n normalize_images=normalize_images,\n )\n assert isinstance(net_arch, list)\n\n self.net_arch = net_arch\n self.features_extractor = features_extractor\n self.activation_fn = activation_fn\n self.features_dim = features_dim\n self.action_dim = self.action_space.n # number of actions\n self.action_dist = make_proba_distribution(action_space)\n self.pi, self.action_net = None, None\n\n self._build()\n\n def _build_pi(self) -> None:\n pi = create_mlp(\n self.features_dim, self.net_arch[-1], self.net_arch[:-1], self.activation_fn\n )\n self.pi = nn.Sequential(*pi)\n\n def _build(self) -> None:\n self._build_pi()\n\n self.action_net = self.action_dist.proba_distribution_net(\n latent_dim=self.net_arch[-1]\n )\n\n def forward(self, obs: th.Tensor) -> th.Tensor:\n features = self.extract_features(obs)\n latent_pi = self.pi(features)\n\n logits = self.action_net(latent_pi)\n return logits\n\n def logits(self, obs: th.Tensor) -> th.Tensor:\n features = self.extract_features(obs)\n latent_pi = self.pi(features)\n\n logits = self.action_net(latent_pi)\n return logits\n\n def _get_distribution_from_logit(self, logits: th.Tensor) -> Distribution:\n return self.action_dist.proba_distribution(action_logits=logits)\n\n def get_distribution(self, obs: th.Tensor) -> Distribution:\n logits = self(obs)\n return self._get_distribution_from_logit(logits)\n\n def _predict(\n self, observation: th.Tensor, deterministic: bool = False\n ) -> th.Tensor:\n return self.get_distribution(observation).get_actions(\n deterministic=deterministic\n )\n\n def action_log_prob(self, obs: th.Tensor, return_ent=True) -> th.Tensor:\n logits = self(obs)\n probs = F.softmax(logits, dim=1)\n if not return_ent:\n ent = None\n else:\n ent = self._get_distribution_from_logit(logits).entropy()\n\n return probs, ent\n\n\nclass DiscreteActor(BasePolicy):\n \"\"\"\n Wrapper class for discrete actor\n \"\"\"\n\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n features_extractor_class: nn.Module,\n features_extractor_kwargs: Optional[Dict[str, Any]] = None,\n net_arch: Optional[List[int]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n normalize_images: bool = True,\n ):\n super().__init__(\n observation_space,\n action_space,\n features_extractor_class,\n features_extractor_kwargs,\n )\n self.net_arch = net_arch\n self.activation_fn = activation_fn\n self.net_args = {\n \"observation_space\": self.observation_space,\n \"action_space\": self.action_space,\n \"net_arch\": net_arch,\n \"activation_fn\": self.activation_fn,\n \"normalize_images\": normalize_images,\n }\n\n self.policy = None\n self._build()\n\n def _build(self):\n policy_args = self._update_features_extractor(self.net_args)\n self.policy = DiscretePolicy(**policy_args)\n\n def _predict(\n self, observation: th.Tensor, deterministic: bool = False\n ) -> th.Tensor:\n return self.policy._predict(observation, deterministic)\n\n def forward(self, observation: th.Tensor):\n return self._predict(observation)\n\n def logits(self, obs: th.Tensor) -> th.Tensor:\n logits = self.policy.logits(obs)\n return logits\n\n def action_log_prob(self, obs: th.Tensor, return_ent=True) -> th.Tensor:\n return self.policy.action_log_prob(obs, return_ent)\n\n def _get_distribution_from_logit(self, logits: th.Tensor) -> Distribution:\n return self.policy._get_distribution_from_logit(logits)\n\n def get_distribution(self, obs: th.Tensor) -> Distribution:\n return self.policy.get_distribution(obs)\n\n\nclass DiscreteTwinDelayedDoubleQNetworks(BasePolicy):\n \"\"\"\n Double Q Network with delayed target networks\n with total of four Q Networks at its core\n \"\"\"\n\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n features_extractor_class: nn.Module,\n features_extractor_kwargs: Optional[Dict[str, Any]] = None,\n net_arch: Optional[List[int]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n normalize_images: bool = True,\n ):\n super().__init__(\n observation_space,\n action_space,\n normalize_images=normalize_images,\n features_extractor_class=features_extractor_class,\n features_extractor_kwargs=features_extractor_kwargs,\n )\n\n self.net_arch = net_arch\n self.activation_fn = activation_fn\n self.normalize_images = normalize_images\n\n self.net_args = {\n \"observation_space\": self.observation_space,\n \"action_space\": self.action_space,\n \"net_arch\": self.net_arch,\n \"activation_fn\": self.activation_fn,\n \"normalize_images\": normalize_images,\n \"features_extractor_class\": features_extractor_class,\n \"features_extractor_kwargs\": features_extractor_kwargs,\n \"lr_schedule\": get_schedule_fn(1), # dummy learning schedule, do not matter\n }\n\n self.q1_net, self.q2_net = None, None\n self._build()\n\n def _build(self) -> None:\n self.q1_net = self.make_dqn()\n self.q2_net = self.make_dqn()\n\n def make_dqn(self) -> DQNPolicy:\n dqn_net = DQNPolicy(**self.net_args)\n # discard optimizer of DQN, as we will have the optimizer in other class\n dqn_net.optimizer = None\n return dqn_net\n\n def forward(self, obs: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:\n return self.q1_net.q_net(obs), self.q2_net.q_net(obs)\n\n def _predict(self, obs: th.Tensor, deterministic: bool = True) -> Tuple[th.Tensor, th.Tensor]:\n return th.minimum(*self.forward(obs))\n\n def critic_target(self, obs: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:\n return self.q1_net.q_net_target(obs), self.q2_net.q_net_target(obs)\n\n def critic(self, obs: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:\n return self.q1_net.q_net(obs), self.q2_net.q_net(obs)\n\n def critic_target_parameters(self):\n \"\"\"\n Return list of parameters of the target networks\n This will be helpful when making optimizers or polyak update\n \"\"\"\n return list(self.q1_net.q_net_target.parameters()) + list(\n self.q2_net.q_net_target.parameters()\n )\n\n def critic_parameters(self):\n \"\"\"\n Return list of parameters of the target networks\n This will be helpful when making optimizers or polyak update\n \"\"\"\n return list(self.q1_net.q_net.parameters()) + list(\n self.q2_net.q_net.parameters()\n )\n\n\nclass ContinuousTwinDelayedDoubleQNetworks(BasePolicy):\n \"\"\"\n Twin delayed Double Q networks for continuous action space\n \"\"\"\n\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n features_extractor_class: nn.Module,\n features_extractor_kwargs: Optional[Dict[str, Any]] = None,\n net_arch: Optional[List[int]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n normalize_images: bool = True,\n ):\n super().__init__(\n observation_space,\n action_space,\n normalize_images=normalize_images,\n features_extractor_class=features_extractor_class,\n features_extractor_kwargs=features_extractor_kwargs,\n )\n\n self.net_arch = net_arch\n self.activation_fn = activation_fn\n self.normalize_images = normalize_images\n\n self.net_args = {\n \"observation_space\": self.observation_space,\n \"action_space\": self.action_space,\n \"net_arch\": self.net_arch,\n \"activation_fn\": self.activation_fn,\n \"normalize_images\": normalize_images,\n \"features_extractor_class\": features_extractor_class,\n \"features_extractor_kwargs\": features_extractor_kwargs,\n }\n\n self.critic, self.target_critic = None, None\n\n self._build()\n\n def _build(self) -> None:\n self.critic = self.make_critic()\n self.critic_target = self.make_critic()\n self.critic_target.load_state_dict(self.critic.state_dict())\n\n # Target networks should always be in eval mode\n self.critic_target.set_training_mode(False)\n\n def make_critic(self, features_extractor: Optional[BaseFeaturesExtractor] = None) -> ContinuousCritic:\n critic_kwargs = self._update_features_extractor(self.net_args, features_extractor)\n return ContinuousCritic(**critic_kwargs).to(self.device)\n\n def critic_target_parameters(self):\n return self.critic_target.parameters()\n\n def critic_parameters(self):\n return self.critic.parameters()\n\n def forward(self, obs: th.Tensor) -> th.Tensor:\n \"\"\"\n Predict the q-values.\n\n :param obs: Observation\n :return: The estimated Q-Value for each action.\n \"\"\"\n return self.critic(obs)\n","repo_name":"giangbang/RL-algorithms-on-SB3","sub_path":"common/policies.py","file_name":"policies.py","file_ext":"py","file_size_in_byte":10891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"16377308263","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nv1.0\r\npureExtractorV1.3을 바탕으로 만듬.\r\n일단 임시코드이며, 머리만 체크함. 추후 확장 예정임.\r\n\r\nv1.1 0511\r\n모든 어트리뷰트로 확장함.\r\n숄더백, 백팩 수정해야함.(cvat 라벨에서 수정하고 코드에서도 수정할것_수정완료)\r\n\r\nv1.1 0629\r\n가방이 두개 있는 경우 버림.\r\n\r\n\"\"\"\r\n\r\nimport os\r\nimport xml.etree.ElementTree as ET\r\nimport shutil\r\nfrom xml.dom import minidom\r\nimport cv2\r\n\r\n\r\ncvatxmlRootpath = r\"C:\\Users\\kth\\Documents\\카카오톡 받은 파일\\0708어또리뷰또\\통합cvatxmls\"\r\nnewImageRootpath = os.path.join(cvatxmlRootpath, \"..\")\r\n\r\n\r\nonlyStatistics = True\r\n\r\n\r\n## 이미지 원본 있는 패스.\r\nimageRootpath = r\"F:\\Annotation_tasks\"\r\n\r\n\r\n\r\nall_newImageRootpath = os.path.join(newImageRootpath, \"common\", \"common_images\")\r\nhead_newImageRootpath = os.path.join(newImageRootpath, \"head\",\"head_images\")\r\nupper_newImageRootpath = os.path.join(newImageRootpath, \"upper\",\"upper_images\")\r\nlower_newImageRootpath = os.path.join(newImageRootpath, \"lower\",\"lower_images\")\r\n\r\n\r\nif not onlyStatistics:\r\n os.makedirs(all_newImageRootpath,exist_ok=True)\r\n os.makedirs(head_newImageRootpath,exist_ok=True)\r\n os.makedirs(upper_newImageRootpath,exist_ok=True)\r\n os.makedirs(lower_newImageRootpath,exist_ok=True)\r\n\r\n\r\n\r\n\r\ndef readBoodreturnInt(Bool):\r\n if Bool == \"false\":\r\n return 0\r\n else:\r\n return 1\r\n \r\n \r\ndef getImagePath(file):\r\n file= file.strip()\r\n for (path, dir, files) in os.walk(imageRootpath):\r\n for filename in files:\r\n filename = filename.strip()\r\n if filename == file:\r\n return os.path.join(path, filename)\r\n\r\n\r\ndef naming(name):\r\n name = str(name)\r\n if len(name) == 1:\r\n return \"000000\"+name\r\n elif len(name) == 2:\r\n return \"00000\"+name\r\n elif len(name) == 3:\r\n return \"0000\" + name\r\n elif len(name) == 4:\r\n return \"000\" + name\r\n elif len(name) == 5:\r\n return \"00\" + name\r\n elif len(name) == 6:\r\n return \"0\" + name\r\n else:\r\n return name\r\n \r\n\r\n\r\ndef readCvatxml():\r\n startFrameNumber = 0\r\n \r\n if not onlyStatistics:\r\n allAttributeFile = open(os.path.join(all_newImageRootpath, \"..\", \"common_attribute_annotation.txt\"), \"w\")\r\n headAttributeFile = open(os.path.join(head_newImageRootpath, \"..\", \"head_attribute_annotation.txt\"), \"w\")\r\n upperAttributeFile = open(os.path.join(upper_newImageRootpath, \"..\", \"upper_attribute_annotation.txt\"), \"w\")\r\n lowerAttributeFile = open(os.path.join(lower_newImageRootpath, \"..\", \"lower_attribute_annotation.txt\"), \"w\")\r\n #f = open(os.path.join(newImageRootpath, \"dfdf.txt\"), \"w\")\r\n\r\n \r\n\r\n cvatxmllist = os.listdir(cvatxmlRootpath)\r\n cvatxmlNameList = []\r\n for line in cvatxmllist:\r\n cvatxmlNameList.append(line[:-4])\r\n\r\n \r\n for cvatxml in cvatxmllist:\r\n if cvatxml.endswith(\".xml\"):\r\n tree = ET.parse(os.path.join(cvatxmlRootpath, cvatxml))\r\n note = tree.getroot()\r\n \r\n \r\n \r\n \r\n for image in note.findall(\"image\"):\r\n imageName= image.get(\"name\")\r\n #_id = image.get(\"id\")\r\n \r\n ## 기본적으로 한개도 안쳐져있는 경우 cvatxmls에 기록이 안됨.\r\n \r\n \r\n ### 가방이 두개 있는 경우 버림.\r\n MOREBAG = False\r\n bagdk = 0\r\n plasticbag = 0\r\n shoulderbag = 0\r\n totebag = 0\r\n backpack = 0\r\n for box in image.findall(\"box\"):\r\n label = box.get(\"label\")\r\n if label == \"all\":\r\n for attribute in box.findall(\"attribute\"):\r\n if attribute.get(\"name\") == \"unknown_bag\":\r\n unknown_bag = attribute.text\r\n unknown_bag = readBoodreturnInt(unknown_bag)\r\n bagdk = unknown_bag\r\n elif attribute.get(\"name\") == \"plasticbag\":\r\n plasticbag = attribute.text\r\n plasticbag = readBoodreturnInt(plasticbag)\r\n elif attribute.get(\"name\") == \"shoulderbag\":\r\n shoulderbag = attribute.text\r\n shoulderbag = readBoodreturnInt(shoulderbag)\r\n elif attribute.get(\"name\") == \"handbag\":\r\n handbag = attribute.text\r\n handbag = readBoodreturnInt(handbag)\r\n totebag = handbag\r\n elif attribute.get(\"name\") == \"backpack\":\r\n backpack = attribute.text\r\n backpack = readBoodreturnInt(backpack)\r\n if plasticbag + shoulderbag + totebag + backpack + bagdk >= 2 :\r\n MOREBAG = True\r\n if MOREBAG == True:\r\n continue\r\n #---------------------\r\n \r\n ### 라벨 개수 4개 아니면 버림.\r\n if not (len(image.findall(\"box\")) == 4):\r\n #print(imageName)\r\n continue\r\n #--------------------\r\n \r\n \r\n ### 4개여도 같은 박스중첩이 있을 경우 버림. \r\n labelList = []\r\n for box in image.findall(\"box\"):\r\n labelList.append(box.get(\"label\"))\r\n if not (len(set(labelList)) == 4):\r\n #print(imageName)\r\n continue\r\n #-------------------\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n for box in image.findall(\"box\"):\r\n label = box.get(\"label\")\r\n \r\n \r\n if label == \"all\":\r\n xtl = int(float(box.get(\"xtl\")))\r\n ytl = int(float(box.get(\"ytl\")))\r\n xbr = int(float(box.get(\"xbr\")))\r\n ybr = int(float(box.get(\"ybr\")))\r\n xlen = abs(xtl-xbr)\r\n ylen = abs(ytl-ybr)\r\n \r\n \r\n if not onlyStatistics:\r\n shutil.copy(getImagePath(imageName), \"temp_image.jpg\")\r\n img = cv2.imread(\"temp_image.jpg\", cv2.IMREAD_COLOR)\r\n #img = cv2.imread(os.path.join(getImagePath(imageName)), cv2.IMREAD_COLOR)\r\n \r\n \r\n src = img.copy()\r\n croped = src[ytl:ybr, xtl:xbr]\r\n cv2.imwrite(os.path.join(all_newImageRootpath,naming(startFrameNumber)+\".jpg\"), croped)\r\n for attribute in box.findall(\"attribute\"):\r\n if attribute.get(\"name\") == \"gender\":\r\n gender = attribute.text\r\n if gender == \"male\":\r\n man, woman, unknown_gender = 1,0,0\r\n elif gender == \"female\":\r\n man, woman, unknown_gender = 0,1,0\r\n else: ##unknown gender\r\n man, woman, unknown_gender = 0,0,1\r\n \r\n \r\n elif attribute.get(\"name\") == \"age\":\r\n age = attribute.text\r\n if age == \"20~70\":\r\n infant,clild,teenager,adult,oldperson = 0,0,0,1,0\r\n elif age == \"0~7\":\r\n infant,clild,teenager,adult,oldperson = 1,0,0,0,0\r\n elif age == \"8~13\":\r\n infant,clild,teenager,adult,oldperson = 0,1,0,0,0\r\n elif age == \"14~19\":\r\n infant,clild,teenager,adult,oldperson = 0,0,1,0,0\r\n else: ## 70~\r\n infant,clild,teenager,adult,oldperson = 0,0,0,0,1\r\n \r\n \r\n elif attribute.get(\"name\") == \"bag_color_unknown\":\r\n bag_color_unknown = attribute.text\r\n bag_color_unknown = readBoodreturnInt(bag_color_unknown)\r\n \r\n elif attribute.get(\"name\") == \"bag_white\":\r\n bag_white = attribute.text\r\n bag_white = readBoodreturnInt(bag_white)\r\n \r\n elif attribute.get(\"name\") == \"bag_black\":\r\n bag_black = attribute.text\r\n bag_black = readBoodreturnInt(bag_black)\r\n \r\n elif attribute.get(\"name\") == \"bag_grey\":\r\n bag_grey = attribute.text\r\n bag_grey = readBoodreturnInt(bag_grey)\r\n \r\n elif attribute.get(\"name\") == \"bag_pink\":\r\n bag_pink = attribute.text\r\n bag_pink = readBoodreturnInt(bag_pink)\r\n \r\n elif attribute.get(\"name\") == \"bag_brown\":\r\n bag_brown = attribute.text\r\n bag_brown = readBoodreturnInt(bag_brown)\r\n \r\n elif attribute.get(\"name\") == \"bag_blue\":\r\n bag_blue = attribute.text\r\n bag_blue = readBoodreturnInt(bag_blue)\r\n \r\n elif attribute.get(\"name\") == \"bag_green\":\r\n bag_green = attribute.text\r\n bag_green = readBoodreturnInt(bag_green)\r\n \r\n elif attribute.get(\"name\") == \"bag_yellow\":\r\n bag_yellow = attribute.text\r\n bag_yellow = readBoodreturnInt(bag_yellow)\r\n \r\n elif attribute.get(\"name\") == \"bag_red\":\r\n bag_red = attribute.text\r\n bag_red = readBoodreturnInt(bag_red)\r\n \r\n elif attribute.get(\"name\") == \"unknown_bag\":\r\n unknown_bag = attribute.text\r\n unknown_bag = readBoodreturnInt(unknown_bag)\r\n bagdk = unknown_bag\r\n \r\n elif attribute.get(\"name\") == \"plasticbag\":\r\n plasticbag = attribute.text\r\n plasticbag = readBoodreturnInt(plasticbag)\r\n \r\n elif attribute.get(\"name\") == \"shoulderbag\":\r\n shoulderbag = attribute.text\r\n shoulderbag = readBoodreturnInt(shoulderbag)\r\n \r\n elif attribute.get(\"name\") == \"handbag\":\r\n handbag = attribute.text\r\n handbag = readBoodreturnInt(handbag)\r\n totebag = handbag\r\n \r\n elif attribute.get(\"name\") == \"backpack\":\r\n backpack = attribute.text\r\n backpack = readBoodreturnInt(backpack)\r\n \r\n elif attribute.get(\"name\") == \"bagless\":\r\n bagless = attribute.text\r\n bagless = readBoodreturnInt(bagless)\r\n bagnone = bagless\r\n\r\n ALL_classes = \"{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}\".format(man,woman,unknown_gender,infant,clild,teenager,adult,oldperson,backpack,totebag,shoulderbag,plasticbag,bagdk,bagnone, bag_red, bag_yellow, bag_green, bag_blue, bag_brown, bag_pink, bag_grey, bag_black, bag_white, bag_color_unknown)\r\n #classesCOMmon = ['man','woman','genderdk','infant','clild','teenager','adult','oldperson','backpack','totebag','shoulderbag','plasticbag','bagdk','bagnone','begred','begyellow','beggreen','begblue','begbrown','begpink','beggray','begblack','begwhite','begcolordk'] \r\n if not onlyStatistics:\r\n allAttributeFile.write(ALL_classes+\"\\n\")\r\n \r\n \r\n elif label == \"head\":\r\n xtl = int(float(box.get(\"xtl\")))\r\n ytl = int(float(box.get(\"ytl\")))\r\n xbr = int(float(box.get(\"xbr\")))\r\n ybr = int(float(box.get(\"ybr\")))\r\n xlen = abs(xtl-xbr)\r\n ylen = abs(ytl-ybr)\r\n \r\n if not onlyStatistics:\r\n shutil.copy(getImagePath(imageName), \"temp_image.jpg\")\r\n img = cv2.imread(\"temp_image.jpg\", cv2.IMREAD_COLOR)\r\n #img = cv2.imread(os.path.join(getImagePath(imageName)), cv2.IMREAD_COLOR)\r\n \r\n src = img.copy()\r\n croped = src[ytl:ybr, xtl:xbr]\r\n cv2.imwrite(os.path.join(head_newImageRootpath,naming(startFrameNumber)+\".jpg\"), croped)\r\n for attribute in box.findall(\"attribute\"):\r\n \r\n if attribute.get(\"name\") == \"hair\":\r\n hair = attribute.text\r\n if hair == \"short\":\r\n short, long, bald, hairdk = 1,0,0,0\r\n elif hair == \"long\":\r\n short, long, bald, hairdk = 0,1,0,0\r\n elif hair == \"bald\":\r\n short, long, bald, hairdk = 0,0,1,0\r\n elif hair == \"unknown\":\r\n short, long, bald, hairdk = 0,0,0,1\r\n \r\n \r\n elif attribute.get(\"name\") == \"hat_red\":\r\n hat_red = attribute.text\r\n hat_red = readBoodreturnInt(hat_red)\r\n \r\n \r\n elif attribute.get(\"name\") == \"hat_yellow\":\r\n hat_yellow = attribute.text\r\n hat_yellow = readBoodreturnInt(hat_yellow)\r\n \r\n elif attribute.get(\"name\") == \"hat_green\":\r\n hat_green = attribute.text\r\n hat_green = readBoodreturnInt(hat_green)\r\n \r\n elif attribute.get(\"name\") == \"hat_blue\":\r\n hat_blue = attribute.text\r\n hat_blue = readBoodreturnInt(hat_blue)\r\n \r\n elif attribute.get(\"name\") == \"hat_brown\":\r\n hat_brown = attribute.text\r\n hat_brown = readBoodreturnInt(hat_brown)\r\n \r\n elif attribute.get(\"name\") == \"hat_pink\":\r\n hat_pink = attribute.text\r\n hat_pink = readBoodreturnInt(hat_pink)\r\n \r\n elif attribute.get(\"name\") == \"hat_grey\":\r\n hat_grey = attribute.text\r\n hat_grey = readBoodreturnInt(hat_grey)\r\n \r\n elif attribute.get(\"name\") == \"hat_black\":\r\n hat_black = attribute.text\r\n hat_black = readBoodreturnInt(hat_black)\r\n \r\n elif attribute.get(\"name\") == \"hat_white\":\r\n hat_white = attribute.text\r\n hat_white = readBoodreturnInt(hat_white)\r\n \r\n elif attribute.get(\"name\") == \"hat_color_unknown\":\r\n hat_color_unknown = attribute.text\r\n hat_color_unknown = readBoodreturnInt(hat_color_unknown)\r\n \r\n elif attribute.get(\"name\") == \"hat\":\r\n hat = attribute.text\r\n if hat == \"hatless\":\r\n cap, visor, novisor, helmat, hood, nohat, hatdk = 0,0,0,0,0,1,0\r\n \r\n #어노테이터 실수 제거 코드.\r\n hat_red, hat_yellow, hat_green, hat_blue, hat_brown, hat_pink, hat_grey, hat_black, hat_white, hat_color_unknown = 0,0,0,0,0, 0,0,0,0,0\r\n \r\n elif hat == \"cap\":\r\n cap, visor, novisor, helmat, hood, nohat, hatdk = 1,0,0,0,0,0,0\r\n elif hat == \"brimmed\":\r\n cap, visor, novisor, helmat, hood, nohat, hatdk = 0,1,0,0,0,0,0\r\n elif hat == \"brimless\":\r\n cap, visor, novisor, helmat, hood, nohat, hatdk = 0,0,1,0,0,0,0\r\n elif hat == \"helmat\":\r\n cap, visor, novisor, helmat, hood, nohat, hatdk = 0,0,0,1,0,0,0\r\n elif hat == \"hood\":\r\n cap, visor, novisor, helmat, hood, nohat, hatdk = 0,0,0,0,1,0,0\r\n elif hat == \"unknown\":\r\n cap, visor, novisor, helmat, hood, nohat, hatdk = 0,0,0,0,0,0,1\r\n\r\n HEAD_classes = \"{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}\".format(cap, visor, novisor, helmat, hood, nohat, hatdk,hat_red,hat_yellow,hat_green,hat_blue,hat_brown,hat_pink,hat_grey,hat_black,hat_white,hat_color_unknown, short, long, bald, hairdk)\r\n #classesHEad = ['cap','visor','nonvisor','helmat','hood','nohat','hatdk','hatred','hatyellow','hatgreen','hatblue','hatbrown','hatpink','hatgray','hatblack','hatwhite','hatcolordk','shot','long','bald','hairdk']\r\n if not onlyStatistics:\r\n headAttributeFile.write(HEAD_classes+\"\\n\")\r\n\r\n elif label == \"upper\":\r\n xtl = int(float(box.get(\"xtl\")))\r\n ytl = int(float(box.get(\"ytl\")))\r\n xbr = int(float(box.get(\"xbr\")))\r\n ybr = int(float(box.get(\"ybr\")))\r\n xlen = abs(xtl-xbr)\r\n ylen = abs(ytl-ybr)\r\n \r\n if not onlyStatistics:\r\n shutil.copy(getImagePath(imageName), \"temp_image.jpg\")\r\n img = cv2.imread(\"temp_image.jpg\", cv2.IMREAD_COLOR)\r\n #img = cv2.imread(os.path.join(getImagePath(imageName)), cv2.IMREAD_COLOR)\r\n\r\n src = img.copy()\r\n croped = src[ytl:ybr, xtl:xbr]\r\n cv2.imwrite(os.path.join(upper_newImageRootpath,naming(startFrameNumber)+\".jpg\"), croped)\r\n for attribute in box.findall(\"attribute\"):\r\n\r\n if attribute.get(\"name\") == \"top_white\":\r\n top_white = attribute.text\r\n top_white = readBoodreturnInt(top_white)\r\n \r\n elif attribute.get(\"name\") == \"top_color_unknown\":\r\n top_color_unknown = attribute.text\r\n top_color_unknown = readBoodreturnInt(top_color_unknown)\r\n \r\n elif attribute.get(\"name\") == \"top_black\":\r\n top_black = attribute.text\r\n top_black = readBoodreturnInt(top_black)\r\n \r\n elif attribute.get(\"name\") == \"top_color_unknown\":\r\n top_color_unknown = attribute.text\r\n top_color_unknown = readBoodreturnInt(top_color_unknown)\r\n\r\n elif attribute.get(\"name\") == \"top_grey\":\r\n top_grey = attribute.text\r\n top_grey = readBoodreturnInt(top_grey)\r\n \r\n elif attribute.get(\"name\") == \"top_pink\":\r\n top_pink = attribute.text\r\n top_pink = readBoodreturnInt(top_pink)\r\n \r\n elif attribute.get(\"name\") == \"top_brown\":\r\n top_brown = attribute.text\r\n top_brown = readBoodreturnInt(top_brown)\r\n \r\n elif attribute.get(\"name\") == \"top_blue\":\r\n top_blue = attribute.text\r\n top_blue = readBoodreturnInt(top_blue)\r\n \r\n elif attribute.get(\"name\") == \"top_green\":\r\n top_green = attribute.text\r\n top_green = readBoodreturnInt(top_green)\r\n \r\n elif attribute.get(\"name\") == \"top_yellow\":\r\n top_yellow = attribute.text\r\n top_yellow = readBoodreturnInt(top_yellow)\r\n \r\n elif attribute.get(\"name\") == \"top_red\":\r\n top_red = attribute.text\r\n top_red = readBoodreturnInt(top_red)\r\n \r\n elif attribute.get(\"name\") == \"top\":\r\n top = attribute.text\r\n if top == \"long_sleeve\":\r\n long_sleeve, short_sleeve, unknown_sleeve = 1,0,0\r\n elif top == \"short_sleeve\":\r\n long_sleeve, short_sleeve, unknown_sleeve = 0,1,0\r\n else: ##unknown sleeve\r\n long_sleeve, short_sleeve, unknown_sleeve = 0,0,1\r\n longshirt = long_sleeve\r\n shortshirt = short_sleeve\r\n \r\n UPPER_classes = \"{}{}{}{}{}{}{}{}{}{}{}{}{}\".format(longshirt,shortshirt, unknown_sleeve, top_red,top_yellow,top_green,top_blue,top_brown,top_pink,top_grey,top_black,top_white,top_color_unknown)\r\n \r\n if not onlyStatistics:\r\n upperAttributeFile.write(UPPER_classes+\"\\n\")\r\n \r\n elif label == \"lower\":\r\n xtl = int(float(box.get(\"xtl\")))\r\n ytl = int(float(box.get(\"ytl\")))\r\n xbr = int(float(box.get(\"xbr\")))\r\n ybr = int(float(box.get(\"ybr\")))\r\n xlen = abs(xtl-xbr)\r\n ylen = abs(ytl-ybr)\r\n \r\n if not onlyStatistics:\r\n shutil.copy(getImagePath(imageName), \"temp_image.jpg\")\r\n img = cv2.imread(\"temp_image.jpg\", cv2.IMREAD_COLOR)\r\n #img = cv2.imread(os.path.join(getImagePath(imageName)), cv2.IMREAD_COLOR)\r\n src = img.copy()\r\n croped = src[ytl:ybr, xtl:xbr]\r\n cv2.imwrite(os.path.join(lower_newImageRootpath,naming(startFrameNumber)+\".jpg\"), croped)\r\n for attribute in box.findall(\"attribute\"):\r\n \r\n if attribute.get(\"name\") == \"bottom_color_unknown\":\r\n bottom_color_unknown = attribute.text\r\n bottom_color_unknown = readBoodreturnInt(bottom_color_unknown)\r\n \r\n elif attribute.get(\"name\") == \"bottom_white\":\r\n bottom_white = attribute.text\r\n bottom_white = readBoodreturnInt(bottom_white)\r\n \r\n elif attribute.get(\"name\") == \"bottom_black\":\r\n bottom_black = attribute.text\r\n bottom_black = readBoodreturnInt(bottom_black)\r\n \r\n elif attribute.get(\"name\") == \"bottom_grey\":\r\n bottom_grey = attribute.text\r\n bottom_grey = readBoodreturnInt(bottom_grey)\r\n \r\n elif attribute.get(\"name\") == \"bottom_pink\":\r\n bottom_pink = attribute.text\r\n bottom_pink = readBoodreturnInt(bottom_pink)\r\n \r\n elif attribute.get(\"name\") == \"bottom_brown\":\r\n bottom_brown = attribute.text\r\n bottom_brown = readBoodreturnInt(bottom_brown)\r\n \r\n elif attribute.get(\"name\") == \"bottom_blue\":\r\n bottom_blue = attribute.text\r\n bottom_blue = readBoodreturnInt(bottom_blue)\r\n \r\n elif attribute.get(\"name\") == \"bottom_green\":\r\n bottom_green = attribute.text\r\n bottom_green = readBoodreturnInt(bottom_green)\r\n \r\n elif attribute.get(\"name\") == \"bottom_yellow\":\r\n bottom_yellow = attribute.text\r\n bottom_yellow = readBoodreturnInt(bottom_yellow)\r\n \r\n elif attribute.get(\"name\") == \"bottom_red\":\r\n bottom_red = attribute.text\r\n bottom_red = readBoodreturnInt(bottom_red)\r\n \r\n elif attribute.get(\"name\") == \"bottom\":\r\n bottom = attribute.text\r\n if bottom == \"long_pants\":\r\n long_pants, short_pants, long_skirt, short_skirt, unknown_bottom = 1,0,0,0,0\r\n elif bottom == \"short_pants\":\r\n long_pants, short_pants, long_skirt, short_skirt, unknown_bottom = 0,1,0,0,0\r\n elif bottom == \"long_skirt\":\r\n long_pants, short_pants, long_skirt, short_skirt, unknown_bottom = 0,0,1,0,0\r\n elif bottom == \"short_skirt\":\r\n long_pants, short_pants, long_skirt, short_skirt, unknown_bottom = 0,0,0,1,0\r\n else: # unknown bottom\r\n long_pants, short_pants, long_skirt, short_skirt, unknown_bottom = 0,0,0,0,1\r\n elif attribute.get(\"name\") == \"shoes_color\":\r\n shoes_color = attribute.text\r\n if shoes_color == \"shoes_red\":\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 1,0,0,0,0,0,0,0,0,0\r\n elif shoes_color == \"shoes_yellow\":\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 0,1,0,0,0,0,0,0,0,0\r\n elif shoes_color == \"shoes_green\":\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 0,0,1,0,0,0,0,0,0,0\r\n elif shoes_color == \"shoes_blue\":\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 0,0,0,1,0,0,0,0,0,0\r\n elif shoes_color == \"shoes_brown\":\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 0,0,0,0,1,0,0,0,0,0\r\n elif shoes_color == \"shoes_pink\":\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 0,0,0,0,0,1,0,0,0,0\r\n elif shoes_color == \"shoes_grey\":\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 0,0,0,0,0,0,1,0,0,0\r\n elif shoes_color == \"shoes_black\":\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 0,0,0,0,0,0,0,1,0,0\r\n elif shoes_color == \"shoes_white\":\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 0,0,0,0,0,0,0,0,1,0\r\n else: #shoes_color_unknown\r\n shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown = 0,0,0,0,0,0,0,0,0,1\r\n \r\n LOWER_classes = \"{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}\".format(long_pants, short_pants, long_skirt, short_skirt, unknown_bottom, bottom_red, bottom_yellow, bottom_green, bottom_blue, bottom_brown, bottom_pink, bottom_grey, bottom_black, bottom_white, bottom_color_unknown,shoes_red, shoes_yellow, shoes_green, shoes_blue, shoes_brown, shoes_pink, shoes_grey, shoes_black, shoes_white, shoes_unknown)\r\n \r\n if not onlyStatistics:\r\n lowerAttributeFile.write(LOWER_classes+\"\\n\")\r\n else:\r\n #print(label)\r\n pass\r\n\r\n startFrameNumber += 1\r\n\r\n if not onlyStatistics: \r\n allAttributeFile.close()\r\n headAttributeFile.close() \r\n upperAttributeFile.close()\r\n lowerAttributeFile.close()\r\n \r\n# f.close()\r\n \r\n print(\"완료\")\r\n \r\n\r\nreadCvatxml()\r\n\r\nwhile True:\r\n pass\r\n\r\n \r\n \r\n \r\n \r\n\r\n","repo_name":"sgyeong97/data-parsing","sub_path":"attribute/makeAttributeDataset_v1.1.py","file_name":"makeAttributeDataset_v1.1.py","file_ext":"py","file_size_in_byte":33158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74607180060","text":"import os\nimport sys\nimport torch\nimport argparse\nimport torch.optim as optim\nimport numpy as np\nfrom scipy.stats import pearsonr\n\nfrom supervised_encoder_models.task_dataloader import TaskFolder, rnacompete_all_rbps, \\\n read_rnacompete_datafile, rnacompete_train_datapath, rnacompete_test_datapath\nfrom supervised_encoder_models.supervised_encoder_model import FULL_ENC_Model\nimport lib.plot_utils, lib.logger\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--save_dir', type=str, default='mlp')\nparser.add_argument('--rbp_name', type=str, default='PTB')\nparser.add_argument('--hidden_size', type=eval, default=256)\nparser.add_argument('--batch_size', type=int, default=32)\nparser.add_argument('--mode', type=str, default='lstm')\nparser.add_argument('--lr', type=float, default=4e-4)\nparser.add_argument('--epoch', type=int, default=100)\nparser.add_argument('--normalize_target', type=eval, default=True, choices=[True, False])\n\n\ndef evaluate(loader):\n all_loss = 0.\n size = loader.size\n all_preds = []\n all_label = []\n\n with torch.no_grad():\n for batch_input, batch_label in loader:\n # compute various metrics\n ret_dict = model(batch_input, batch_label)\n all_loss += ret_dict['loss'].item()\n\n all_preds.append(ret_dict['preds'])\n all_label.extend(batch_label)\n\n all_loss /= size\n pearson_corr = pearsonr(np.array(all_label)[:, 0], np.concatenate(all_preds, axis=0)[:, 0])[0]\n\n return all_loss, pearson_corr\n\n\nif __name__ == \"__main__\":\n\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n args = parser.parse_args()\n print(args)\n rbp_name = args.rbp_name\n if rbp_name == 'all':\n pass\n all_rbps = rnacompete_all_rbps\n else:\n assert rbp_name in rnacompete_all_rbps\n all_rbps = [rbp_name]\n\n preprocess_type = args.mode\n input_size = 128 # latent dimension\n output_size = 1\n train_val_split_ratio = 0.1\n\n for rbp_name in all_rbps:\n\n train_datapath_filled = rnacompete_train_datapath.format(rbp_name)\n test_datapath_filled = rnacompete_test_datapath.format(rbp_name)\n\n train_seq, train_targets = read_rnacompete_datafile(train_datapath_filled)\n test_seq, test_targets = read_rnacompete_datafile(test_datapath_filled)\n train_targets = np.array(train_targets)[:, None]\n test_targets = np.array(test_targets)[:, None]\n\n if args.normalize_target is True:\n print('Note: normalizing training targets to [0, 1]')\n offset = np.min(train_targets)\n diff = np.max(train_targets) - offset\n\n train_targets = (np.array(train_targets) - offset) / diff\n test_targets = (np.array(test_targets) - offset) / diff\n loss_type = 'binary_ce'\n else:\n loss_type = 'mse'\n\n valid_idx = np.random.choice(np.arange(len(train_targets)), int(len(train_targets) * train_val_split_ratio),\n replace=False)\n valid_idx = np.array(valid_idx)\n train_idx = np.setdiff1d(np.arange(len(train_targets)), valid_idx)\n\n valid_seq = np.array(train_seq)[valid_idx]\n valid_targets = np.array(train_targets)[valid_idx]\n val_size = len(valid_seq)\n\n train_seq = np.array(train_seq)[train_idx]\n train_targets = np.array(train_targets)[train_idx]\n train_size = len(train_seq)\n\n save_dir = os.path.join('full-rnacompete-regressor', args.save_dir, rbp_name)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n else:\n continue\n\n outfile = open(os.path.join(save_dir, '%s.out' % (args.save_dir)), \"w\")\n sys.stdout = outfile\n sys.stderr = outfile\n\n model = FULL_ENC_Model(input_size, args.hidden_size, output_size, device=device,\n vae_type=preprocess_type, loss_type=loss_type).to(device)\n print(model)\n import torch.nn as nn\n\n for param in model.parameters():\n if param.dim() == 1:\n nn.init.constant_(param, 0)\n elif param.dim() >= 2:\n nn.init.xavier_normal_(param)\n\n print(\"Model #Params: %dK\" % (sum([x.nelement() for x in model.parameters()]) / 1000,))\n optimizer = optim.Adam(model.parameters(), lr=args.lr)\n\n from importlib import reload\n\n reload(lib.plot_utils)\n lib.plot_utils.set_output_dir(save_dir)\n lib.plot_utils.suppress_stdout()\n\n all_fields = ['epoch', 'train_loss', 'valid_loss', 'train_pearson_corr', 'valid_pearson_corr']\n\n logger = lib.logger.CSVLogger('run.csv', save_dir, all_fields)\n\n best_valid_loss = np.inf\n best_valid_weight_path = None\n\n train_loader = TaskFolder(train_seq, train_targets, args.batch_size, shuffle=True,\n preprocess_type=preprocess_type, num_workers=8)\n valid_loader = TaskFolder(valid_seq, valid_targets, args.batch_size, shuffle=False,\n preprocess_type=preprocess_type, num_workers=8)\n test_loader = TaskFolder(test_seq, test_targets, args.batch_size, shuffle=False,\n preprocess_type=preprocess_type, num_workers=8)\n last_improved = 0\n last_2_epochs = []\n for epoch in range(1, args.epoch + 1):\n if last_improved >= 20:\n print('Have\\'t improved for %d epochs' % (last_improved))\n break\n\n # training loop\n model.train()\n for batch_input, batch_label in train_loader:\n model.zero_grad()\n ret_dict = model(batch_input, batch_label)\n loss = ret_dict['loss'] / ret_dict['nb_preds']\n # print(sum(np.argmax(ret_dict['preds'], axis=-1) == np.array(batch_label)) / ret_dict['nb_preds'])\n loss.backward()\n optimizer.step()\n\n model.eval()\n # validation loop\n train_loss, train_pearson_corr = evaluate(train_loader)\n valid_loss, valid_pearson_corr = evaluate(valid_loader)\n\n lib.plot_utils.plot('train_loss', train_loss)\n lib.plot_utils.plot('train_pearson_corr', train_pearson_corr)\n lib.plot_utils.plot('valid_loss', valid_loss)\n lib.plot_utils.plot('valid_pearson_corr', valid_pearson_corr)\n\n lib.plot_utils.set_xlabel_for_tick(index=0, label='epoch')\n lib.plot_utils.flush()\n lib.plot_utils.tick(index=0)\n\n print(\n 'Epoch %d, train_loss: %.2f, train_pearson_corr: %2f, '\n 'valid_loss: %.2f, valid_pearson_corr: %.2f' %\n (epoch, train_loss, train_pearson_corr,\n valid_loss, valid_pearson_corr))\n\n logger.update_with_dict({\n 'epoch': epoch, 'train_loss': train_loss, 'valid_loss': valid_loss,\n 'train_pearson_corr': train_pearson_corr, 'valid_pearson_corr': valid_pearson_corr\n })\n\n if valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n if len(last_2_epochs) >= 2:\n to_remove_epoch = last_2_epochs.pop(0)\n os.remove(os.path.join(save_dir, \"model.epoch-\" + str(to_remove_epoch)))\n last_2_epochs.append(epoch)\n best_valid_weight_path = os.path.join(save_dir, \"model.epoch-\" + str(epoch))\n torch.save(\n {'model_weights': model.state_dict(),\n 'opt_weights': optimizer.state_dict()},\n best_valid_weight_path)\n print('Validation loss improved, saving current weights to path:', best_valid_weight_path)\n last_improved = 0\n else:\n last_improved += 1\n\n if best_valid_weight_path is not None:\n print('Loading best weights from: %s' % (best_valid_weight_path))\n model.load_state_dict(torch.load(best_valid_weight_path)['model_weights'])\n\n model.eval()\n test_loss, test_pearson_corr = evaluate(test_loader)\n print('Test pearson corr:', test_pearson_corr)\n\n logger.close()\n","repo_name":"HarveyYan/GraphDesigningRNAs","sub_path":"train_rnacompete_fully_supervised_regressor.py","file_name":"train_rnacompete_fully_supervised_regressor.py","file_ext":"py","file_size_in_byte":8255,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"73614072220","text":"from flask import Flask\r\nimport json\r\nimport requests\r\n\r\napp = Flask(__name__) \r\n\r\n@app.route(\"/data1\")\r\ndef FlaskData():\r\n keyValue =r\"tzNdpBB6EDyPn7B1MHodkDLXb5d7rQeJ1JFMfxvFMDxnyw9ii0Kei8Lvvi946HnnhuJNqb%2FJLfkGEUbSddqSMg%3D%3D\"\r\n\r\n dataURL = \"https://api.odcloud.kr/api/apnmOrg/v1/list?\"\r\n dataURL += \"page=\" + str(1) + \"&perPage=\" + str(10)\r\n dataURL += \"&cond\" + r\"%5BorgZipaddr%3A%3ALIKE%5D=%EC%84%B1%EB%B6%81%EA%B5%AC\"\r\n dataURL += \"&serviceKey=\" + keyValue\r\n\r\n dataResult = requests.get(dataURL)\r\n\r\n result = json.loads(dataResult.text)\r\n #result2 = json.dumps(result, ensure_ascii=False, indent=5)\r\n try:\r\n changeFile = open(\"FlaskLab\\\\mydata.json\", \"w\", encoding=\"utf-8\")\r\n result2 = json.dump(result, changeFile, ensure_ascii=False, indent=5) \r\n except Exception as error:\r\n print(\"오류 : \" + error) \r\n else:\r\n changeFile.close()\r\n #print(result)\r\n \r\n return result\r\n","repo_name":"gimdaun/Cloud-MSA","sub_path":"20220124_모듈시험/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"12971509904","text":"# Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.\n#\n# Example 1:\n#\n# Input: [3,2,1,5,6,4] and k = 2\n# Output: 5\n# Example 2:\n#\n# Input: [3,2,3,1,2,4,5,5,6] and k = 4\n# Output: 4\n# Note:\n# You may assume k is always valid, 1 ≤ k ≤ array's length.\n\n\nclass Solution(object):\n def partition(self, nums, l, r):\n pivot = nums[r]\n lo = l\n for k in range(l, r+1):\n if nums[k] < pivot:\n nums[k], nums[lo] = nums[lo], nums[k]\n lo+=1\n nums[lo], nums[r] = nums[r], nums[lo]\n return lo\n def findKthLargest(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n n = len(nums)\n i = 0\n j = n - 1\n pos = self.partition(nums, i, j)\n if pos == n - k:\n return nums[pos]\n elif pos > n - k:\n return self.findKthLargest(nums[:pos], k - (n - pos) )\n else:\n return self.findKthLargest(nums[pos+1:], k)\n","repo_name":"mokshithpyla/DS-Algo","sub_path":"LeetCode/Medium/KthLargestNumber.py","file_name":"KthLargestNumber.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9419964837","text":"from Bio import SeqIO\nimport numpy as np\nimport sys\n\n'''\nUsage:\npython 6_replace_snp.py intersectSNP.txt peakSequence.fa peakMatrix.txt output.fa\n'''\n\nintersectSNPDir = sys.argv[1]\npeakSeqDir = sys.argv[2]\npeakDir = sys.argv[3]\noutDir = sys.argv[4]\n\nSNP = np.loadtxt(intersectSNPDir, dtype=\"str\")\n\n#peakName = \"/home/malab14/research/00DeepTFBS/00results/00peakSeq/positive/ZFHD_tnt-ATHB34_colamp_a.positive.fa\"\npeakSeq = SeqIO.parse(peakSeqDir, \"fasta\")\n\npeakSeqDict = {}\nfor fasta in peakSeq:\n name, sequence = fasta.id, fasta.seq.tostring()\n peakSeqDict[name] = sequence\n\n\npeakMat = np.loadtxt(peakDir, dtype=\"str\")\nstartPos = peakMat[:, 1].astype(int)\nendPos = peakMat[:, 2].astype(int)\nchrVec = peakMat[:, 0]\nresSeq = open(outDir, \"w\")\nresMat = open(sys.argv[5], \"w\")\nfor line in SNP:\n curPos = int(line[2])\n curChr = line[0][-1]\n tt = np.intersect1d(np.where(startPos <= curPos),\n np.where(endPos >= curPos))\n idx = np.intersect1d(tt, np.where(chrVec == \"chr\"+str(curChr)))\n idx = idx.astype(int)\n for j in idx:\n peak = peakMat[j]\n curStart = int(peak[1])\n curEnd = int(peak[2])\n seqID = \"peak_\" + str(j + 1)\n peakID = seqID + \"_\" + str(curChr) + \":\" + str(int(peak[1]) + 1) + \"-\" + str(peak[2])\n curSeq = peakSeqDict[peakID]\n RP = curPos - curStart - 1\n Ref = line[3]\n Alt = line[4]\n if curStart != 0:\n if Ref == curSeq[RP]:\n if len(Ref) == 1 and len(Alt) == 1:\n curSeq = list(curSeq)\n curSeq[RP] = Alt\n curSeq = ''.join(curSeq)\n resSeq.write(\">\" + peakID + \";SNP_position:\" + str(\n curPos) + \";Ref:\" + Ref + \";Alt:\" + Alt + \"\\n\" + curSeq + \"\\n\")\n resMat.write(str(curChr) + \"\\t\" + str(curPos) + \"\\t\" + peakID + \"\\n\")\n else:\n if Ref == curSeq[RP]:\n if len(Ref) == 1 and len(Alt) == 1:\n seqLen = curEnd - curStart\n RP = RP + (201 - seqLen)\n print(Ref)\n curSeq = list(curSeq)\n print(curSeq[RP])\n curSeq[RP] = Alt\n curSeq = ''.join(curSeq)\n resSeq.write(\">\" + peakID + \";SNP_position:\" + str(\n curPos) + \";Ref:\" + Ref + \";Alt:\" + Alt + \"\\n\" + curSeq + \"\\n\")\n resMat.write(str(curChr) + \"\\t\" + str(curPos) + \"\\t\" + peakID + \"\\n\")\nresSeq.close()\nresMat.close()\n\n\n\n\n\n# t = 0\n# posSeq = open(\"/home/malab14/research/00DeepTFBS/00results/00peakSeq/positive_replaceSNP.fa\", \"w\")\n# for fasta in peakSeq:\n# name, sequence = fasta.id, fasta.seq.tostring()\n# sequence = list(sequence)\n# curChr = re.split(r'[_:-]', name)[2]\n# curChr = \"Chr\" + curChr\n# Start = int(re.split(r'[_:-]', name)[3])\n# End = int(re.split(r'[_:-]', name)[4])\n# idx = np.where(SNP[:,3] == curChr)\n# #Find first column contain \"Chr\"\n# #idx = np.flatnonzero(np.core.defchararray.find(SNP[:,0], Chr)!=-1)\n# curSNP = SNP[idx]\n# position = curSNP[:,4].astype(int)\n# resIdx = np.intersect1d(np.where(position >= Start), np.where(position <= End))\n# t = t+1\n# if resIdx.shape[0] == 0:\n# continue\n# else:\n# resSNP = curSNP[resIdx]\n# for record in resSNP:\n# curPos = int(record[4])\n# sequence[curPos-Start] = record[2]\n#\n# sequence = ''.join(sequence)\n# print(t)\n#\n# posSeq.write(\">\" + name + \";\" + ';'.join(list(resSNP[:,0].astype(str))) + \"\\n\" + sequence + \"\\n\")\n#\n#\n# posSeq.close()\n#\n#\n","repo_name":"jingjingzhai/DeepTFBS","sub_path":"6_replace_snp.py","file_name":"6_replace_snp.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36649244980","text":"class Node():\n def __init__(self, element):\n self.node_left = None\n self.node_right = None\n self.element = element\n\nclass Tree():\n def __init__(self):\n self.root_node = None\n\n def in_order(self):\n if self.root_node == None:\n raise Exception(\"Elements not inserted\")\n\n return self._in_order(self.root_node)\n\n def insert(self, element):\n raise NotImplementedError(\"method not implemented\")\n\n def _in_order(self, node):\n # Set current to root of binary tree \n elements = []\n current = node \n stack = [] # initialize stack \n done = 0 \n \n while True: \n \n # Reach the left most Node of the current Node \n if current is not None: \n \n # Place pointer to a tree node on the stack \n # before traversing the node's left subtree \n stack.append(current) \n \n current = current.node_left \n \n \n # BackTrack from the empty subtree and visit the Node \n # at the top of the stack; however, if the stack is \n # empty you are done \n elif(stack): \n current = stack.pop() \n elements.append(current.element) # Python 3 printing \n \n # We have visited the node and its left \n # subtree. Now, it's right subtree's turn \n current = current.node_right \n \n else: \n break\n\n return elements\n","repo_name":"jadsonlucio/Faculdade","sub_path":"Atividades disciplinas/6 periodo/PAA/sorting algorithms/sort_algorithms/tree_sort/trees/tree_interface.py","file_name":"tree_interface.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21843619599","text":"'''\nInitializes the app and sets up all the routes\n'''\n\nimport os\n\n## Sentry ##\nimport sentry_sdk\nfrom sentry_sdk.integrations.flask import FlaskIntegration\n\n## App\nfrom flask import Flask\n# from werkzeug.middleware.proxy_fix import ProxyFix\nfrom config import *\nfrom app.api import blueprint as api\n\ndef create_app(testing=False):\n '''\n Create and configure the app\n '''\n app = Flask(__name__)\n environment = app.config['ENV']\n\n # Load in some extra configs\n if testing or environment == 'test':\n app.config.from_object(TestingConfig())\n elif environment == 'production':\n app.config.from_object(ProductionConfig())\n # Set up Sentry\n sentry_sdk.init(os.environ.get('SENTRY_DSN'), integrations=[FlaskIntegration()])\n elif environment == 'staging':\n app.config.from_object(StagingConfig())\n # Set up Sentry\n sentry_sdk.init(os.environ.get('SENTRY_DSN'), integrations=[FlaskIntegration()])\n elif environment == 'development':\n app.config.from_object(DevelopmentConfig())\n else:\n # Load the defaults\n app.config.from_object(Config())\n\n # This a legacy config - not sure if we need it anymore?\n # app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1, x_proto=1)\n\n ### ROUTES ###\n app.register_blueprint(api, url_prefix='/api/v1')\n\n return app\n","repo_name":"mondaine-esdl/etm-esdl","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"10604140498","text":"import matplotlib.pyplot as plt\nimport PyLeech.Utils.CrawlingDatabaseUtils as CDU\nimport PyLeech.Utils.NLDUtils as NLD\nimport numpy as np\nimport scipy.signal as spsig\nimport PyLeech.Utils.AbfExtension as abfe\nimport PyLeech.Utils.burstUtils\nfrom PyLeech.Utils.unitInfo import UnitInfo\nimport PyLeech.Utils.filterUtils as filterUtils\nimport PyLeech.Utils.burstUtils as burstUtils\n\n\n\n\n\nif __name__ == \"__main__\":\n\n binning_dt = .5\n spike_kernel_sigma = 3\n\n cdd = CDU.loadDataDict()\n\n del cdd[\"RegistrosDP_PP/NS_DP_PP_0.pklspikes\"]\n del cdd[\"RegistrosDP_PP/NS_T_DP_PP_0_cut.pklspikes\"]\n del cdd[\"RegistrosDP_PP/NS_T_DP_PP_1.pklspikes\"]\n del cdd[\"RegistrosDP_PP/2019_01_28_0001.pklspikes\"]\n\n\n for fn, data in cdd.items():\n\n try:\n ns_channel = [key for key, items in data['channels'].items() if 'NS' == items][0]\n print(\"Running %s\" % fn)\n except IndexError:\n continue\n\n arr_dict, time_vector1, fs = abfe.getArraysFromAbfFiles(fn, ['Vm1'])\n\n NS_kernel = PyLeech.Utils.burstUtils.generateGaussianKernel(sigma=spike_kernel_sigma, time_range=20, dt_step=1 / fs)\n conv_NS = spsig.fftconvolve(arr_dict[ns_channel], NS_kernel, mode='same')[::int(binning_dt * fs)]\n time_vector1 = time_vector1[::int(binning_dt * fs)]\n del arr_dict\n\n\n burst_object = UnitInfo(fn, 'RegistrosDP_PP', 'load')\n\n good_neurons = [neuron for neuron, neuron_dict in data['neurons'].items() if neuron_dict['neuron_is_good']]\n\n spike_freq_array = burstUtils.processSpikeFreqDict(burst_object.spike_freq_dict, step=int(binning_dt * fs) / fs,\n num=conv_NS.shape[0],\n time_length=burst_object.time[-1])\n\n\n\n\n smoothed_sfd = {}\n kernel = PyLeech.Utils.burstUtils.generateGaussianKernel(sigma=spike_kernel_sigma, time_range=20, dt_step=binning_dt)\n for key, items in spike_freq_array.items():\n smoothed_sfd[key] = np.array([items[0], spsig.fftconvolve(items[1], kernel, mode='same')])\n burst_array = []\n\n fig, ax_list = burstUtils.plotFreq(smoothed_sfd, scatter_plot=False, color_dict='single_color',\n draw_list=good_neurons,\n optional_trace=[time_vector1, conv_NS])\n fig.suptitle(fn)\n\n kernel = PyLeech.Utils.burstUtils.generateGaussianKernel(sigma=spike_kernel_sigma, time_range=20, dt_step=binning_dt)\n N_neurons = len(list(spike_freq_array)) + 1\n burst_array.append(conv_NS)\n fig = plt.figure()\n fig1 = plt.figure()\n\n j = 1\n for key, items in spike_freq_array.items():\n smoothed_spikes = np.array([items[0], spsig.fftconvolve(items[1], kernel, mode='same')])\n # filterUtils.plotSpectrums(smoothed_spikes[1]-smoothed_spikes[1].mean(), sampling_rate=1/binning_dt, nperseg=1000000, pltobj=ax[j])\n f, pxx = filterUtils.getFreqSpectrum(smoothed_spikes[1]-smoothed_spikes[1].mean(), sampling_rate=1/binning_dt, nperseg=1000000)\n if j == 1:\n ax = fig.add_subplot(N_neurons, 1, j)\n else:\n ax = fig.add_subplot(N_neurons, 1, j, sharex=ax)\n ax1 = fig1.add_subplot(N_neurons, 1, j, sharex=ax)\n ax.semilogy(f, pxx)\n ax1.plot(f, pxx)\n j += 1\n\n # filterUtils.plotSpectrums(conv_NS - conv_NS.mean(), sampling_rate=1/binning_dt, nperseg=1000000, pltobj=ax[j])\n filterUtils.getFreqSpectrum(conv_NS - conv_NS.mean(), sampling_rate=1/binning_dt, nperseg=1000000)\n\n ax = fig.add_subplot(N_neurons, 1, j, sharex=ax)\n ax1 = fig1.add_subplot(N_neurons, 1, j, sharex=ax)\n\n ax.semilogy(f, pxx)\n ax1.plot(f, pxx)\n fig.suptitle(fn)\n fig1.suptitle(fn)","repo_name":"asmerlinsky/PyLeech","sub_path":"Analysis/multiganglion_FFT.py","file_name":"multiganglion_FFT.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"27347120133","text":"from rest_framework import viewsets\nfrom api.models.scrap_models import Scrap\nfrom api.serializers.scrap_serializer import (\n ScrapSerializer, ScrapCampaignSerializer,\n ScrapArticleSerializer)\nfrom api.permission import *\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom django.contrib.auth import get_user_model\n\nCAMPAIGN = 1\nARTICLE = 2\n\nclass ScrapViewSet(viewsets.ModelViewSet):\n queryset = Scrap.objects.all()\n serializer_class = ScrapSerializer\n permission_classes = (permissions.IsAuthenticated,)\n\n def list(self, request):\n user = request.user.id\n queryset = Scrap.objects.filter(user=request.user.id)\n\n serializer = ScrapSerializer(queryset, many=True, context={\"request\": request})\n return Response(serializer.data)\n\n def create(self, request, *args, **kwargs):\n kind = request.data['kind']\n if kind is CAMPAIGN:\n if 'campaign' not in request.data:\n return Response({\"message\": \" should contain \\\"campaign\\\" value\"},\n status=status.HTTP_400_BAD_REQUEST)\n \n id = str(request.user.id) + \"_campaign_\" + str(request.data['campaign'])\n newData = request.data\n newData['id'] = id\n write_serializer = ScrapCampaignSerializer(data=newData)\n elif kind is ARTICLE:\n if 'article' not in request.data:\n return Response({\"message\": \" should contain \\\"article\\\" value\"},\n status=status.HTTP_400_BAD_REQUEST)\n \n id = str(request.user.id) + \"_article_\" + str(request.data['article'])\n newData = request.data\n newData['id'] = id\n write_serializer = ScrapArticleSerializer(data=newData)\n else:\n return Response({\"message\": \"\\\"kind\\\" value error\"},\n status=status.HTTP_400_BAD_REQUEST)\n write_serializer.is_valid(raise_exception=True)\n instance = self.perform_create(write_serializer)\n\n read_serializer = ScrapSerializer(instance, context={\"request\": request})\n return Response(read_serializer.data, status=status.HTTP_201_CREATED)\n\n def perform_create(self, serializer):\n return serializer.save(user=self.request.user)\n\n# class FeedViewSet(viewsets.ModelViewSet):\n# queryset = Feed.objects.all()\n# serializer_class = FeedReadSerializer\n# permission_classes = (permissions.IsAuthenticated,)\n\n# def list(self, request):\n# queryset = Feed.objects.all()\n\n# user = request.user.id\n# query = request.query_params.get('status', None)\n# complete = False\n# if query is None:\n# return Response({\"message\": \"status query should be needed\"},\n# status=status.HTTP_400_BAD_REQUEST)\n# else:\n# if query == STATUS_PROGRESS:\n# complete = False\n# start, end = calc_today()\n# queryset = queryset.filter(\n# user=user, complete=complete,\n# created__gte=start, created__lte=end)\n# elif query == STATUS_COMPLETE:\n# complete = True\n# queryset = queryset.filter(user=user, complete=complete)\n# else:\n# return Response({\"message\": \"Invalid query\"},\n# status=status.HTTP_400_BAD_REQUEST)\n\n# serializer = FeedReadSerializer(queryset, many=True, context={\"request\": request})\n# return Response(serializer.data)\n\n# def retrieve(self, request, pk=None):\n# try:\n# feed = Feed.objects.get(pk=pk)\n# except:\n# return Response(status=status.HTTP_404_NOT_FOUND)\n\n# serializer = FeedRetreiveSerializer(feed, context={\"request\": request})\n# return Response(serializer.data)\n\n# def create(self, request, *args, **kwargs):\n# write_serializer = FeedWriteSerializer(data=request.data)\n# write_serializer.is_valid(raise_exception=True)\n# instance = self.perform_create(write_serializer)\n\n# read_serializer = FeedReadSerializer(instance, context={\"request\": request})\n# return Response(read_serializer.data, status=status.HTTP_201_CREATED)\n\n# def partial_update(self, request, pk=None):\n# if not 'result' in request.data.keys():\n# return Response({\"message\": \"result can not be empty\"},\n# status=status.HTTP_400_BAD_REQUEST)\n\n# instance = self.queryset.get(pk=pk)\n# if instance is None:\n# return Response(status=status.HTTP_404_NOT_FOUND)\n\n# firstComplete = False\n# if not instance.complete:\n# firstComplete = True\n \n# request.data[\"complete\"] = True\n# serializer = FeedUpdateSerializer(\n# instance, data=request.data,\n# partial=True, context={\"request\": request})\n# serializer.is_valid(raise_exception=True)\n# serializer.save()\n\n# # Earth level uypdate logic\n# if firstComplete:\n# userModel = get_user_model()\n# userInstance = userModel.objects.get(email=request.user.email)\n# newEarthLevel = increase_earthLevel(userInstance.earthLevel)\n# if newEarthLevel is not userInstance.earthLevel:\n# userInstance.earthLevel = newEarthLevel\n# userInstance.save()\n\n# read_serializer = FeedReadSerializer(instance, context={\"request\": request})\n# return Response(read_serializer.data, status=status.HTTP_202_ACCEPTED)\n\n# def perform_create(self, serializer):\n# return serializer.save(user=self.request.user)\n\n# def get_permissions(self):\n# if self.request.method == 'PATCH':\n# self.permission_classes = (permissions.IsAuthenticated, IsOwnerFeed)\n# return super(FeedViewSet, self).get_permissions()\n","repo_name":"desingdeveloperdayday/PickedUpMole_ForEarthForUs","sub_path":"backend/ForEarthForUs_backend/api/views/scrap_views.py","file_name":"scrap_views.py","file_ext":"py","file_size_in_byte":5929,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"69"} +{"seq_id":"43592740232","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom pylab import mpl\r\nimport math\r\nimport time\r\nimport numpy as np\r\nmpl.rcParams['axes.unicode_minus'] = False\r\nfrom pandas.core.frame import DataFrame\r\nimport matplotlib.pyplot as plt\r\n#from scipy.optimize import curve_fit\r\nimport numpy as np\r\n\r\nplt.rcParams['font.sans-serif'] = ['SimHei']\r\nplt.rcParams['font.family'] = 'sans-serif'\r\nplt.rcParams['axes.unicode_minus'] = False\r\n\r\npath = 'E:/zuoye/assignment1/assignment1/data/filtered data/new_id/id 45.csv'\r\n\r\nxdata1 = []\r\n# Read csv file using pandas library under python\r\ndata = pd.read_csv(path)\r\n\r\nydata1 = data['kp'] # vehicle location\r\nydata_preceding = data['leader_kp'] # front car position\r\nlength_preceding = data['leader_length'] # Front car length\r\nv_preceding=data['leader_velocity']/3.6 # Speed of the car ahead\r\n\r\nfor i in range(len(ydata1)):\r\n xdata1.append(0.1 * i)\r\nerror = []\r\nT_temp = []\r\n\r\n# starting IDM\r\n\r\nS = 3.897155762 # static distance\r\nT = 0.81 # headway\r\naMax = 2.445007324 # maximum expected acceleration\r\nbMax = 1.039291382 # maximum expected deceleration\r\nV0 = 26.25274658 # m/s Desired free flow velocity\r\nreaction_time = 5 # Reaction time\r\nxVelocity = data['velocity']/3.6 # km/h to m/s\r\nV = [0 for i in range(len(xdata1))] # measured vehicle speed\r\nA = [0 for i in range(len(xdata1))] # measured vehicle acceleration\r\nV[0 + reaction_time] = xVelocity[0 + reaction_time] \r\nydata_yuce = [0 for i in range(len(xdata1))] # predicted vehicle position\r\nydata_yuce[0 + reaction_time] = ydata1[0 + reaction_time]\r\n\r\n# Predict vehicle position with time as a loop\r\nfor i in range(len(xdata1) - 1 - reaction_time):\r\n canshu1 = (V[i + reaction_time] / V0)\r\n canshu2 = S + V[i + reaction_time] * T + (\r\n V[i + reaction_time] * (V[i + reaction_time] - v_preceding[i]) / 2 * ((aMax * bMax) ** 0.5))\r\n canshu3 = ydata_preceding[i] - length_preceding[i] - ydata_yuce[i + reaction_time]\r\n A[i + reaction_time] = aMax * (1 - canshu1 ** 4 - (canshu2 / canshu3) ** 2)\r\n V[i + 1 + reaction_time] = V[i + reaction_time] + A[i + reaction_time] * 0.1\r\n if ydata1[0] < ydata1[5]:\r\n ydata_yuce[i + 1 + reaction_time] = ydata_yuce[i + reaction_time] + 0.5 * A[\r\n i + reaction_time] * 0.1 ** 2 + V[i + reaction_time] * 0.1\r\n else:\r\n ydata_yuce[i + 1 + reaction_time] = ydata_yuce[i + reaction_time] - 0.5 * A[\r\n i + reaction_time] * 0.1 ** 2 - V[i + reaction_time] * 0.1\r\n\r\nydata_yuce_temp = ydata_yuce[reaction_time:-reaction_time]\r\nV_temp = V[reaction_time:-reaction_time]\r\nA_temp = A[reaction_time:-reaction_time]\r\n\r\nydata_preceding_temp = ydata_preceding[reaction_time:-reaction_time] # measured front car position\r\nydata1_temp = ydata1[reaction_time:-reaction_time] # predicted car position\r\nxdata1_temp = xdata1[reaction_time:-reaction_time] # time\r\n\r\n\r\nc={\"Velocity\" : V_temp,\r\n \"Acceleration\" : A_temp,\r\n \"front car position\":ydata_preceding_temp,\r\n \"following car position\" : ydata1_temp,\r\n \"time\":xdata1_temp\r\n }#将列表a,b转换成字典\r\ndata2=DataFrame(c)\r\nprint(data2)\r\ndata2.to_csv('E:/zuoye/IDMdata/IDMdata_for_45.csv')\r\n#print(ydata_preceding_temp)\r\n# def Fig():\r\n\r\n# plt.figure('The difference between measured and predicted trajectories')\r\n# plt.plot(xdata1_temp, ydata1_temp, label='Measured_car')\r\n# plt.plot(xdata1_temp, ydata_preceding_temp, label='Preceding_car')\r\n# # plt.plot(xdata1_temp, V_temp, label='Predicting_car',color='r')\r\n# # plt.plot(S, error, label='Predicting_car')\r\n# plt.title(u\"id 751 Variation=9.99\", size=30)\r\n# plt.legend(fontsize=25)\r\n# plt.xlabel(u't(s)', size=30)\r\n# plt.ylabel(u'x(m)', size=30)\r\n# plt.tick_params(labelsize=23)\r\n# # plt.savefig('C:\\\\Users\\\\yangyukuan\\\\Desktop\\\\data_nyj\\\\12.11\\\\cte误差.jpg')\r\n# plt.show()\r\n# print(\"all picture is starting\")\r\n\r\n\r\n# Fig()\r\n","repo_name":"ShuaiWangAI/TIL6010-Python-Programming-Final-Project-Group-06","sub_path":"Intelligent Driver Model for assignment 1.py","file_name":"Intelligent Driver Model for assignment 1.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9707060468","text":"import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nfrom datetime import datetime\n\nclass Clock(QWidget):\n on_minute = pyqtSignal()\n on_day = pyqtSignal()\n\n def __init__(self):\n super(Clock, self).__init__()\n self.time = datetime.now() \n self.time_widget = QLabel()\n\n text_style = r\"QLabel {color: white; padding: 0px; margin: 0px;}\"\n self.time_widget.setParent(self)\n self.time_widget.setFont(QFont('Roboto', 100))\n self.time_widget.setStyleSheet(text_style)\n\n self.timer = QTimer()\n self.timer.timeout.connect(self.update_time)\n self.timer.start(500)\n\n self.draw_time()\n \n def update_time(self):\n prev_time = self.time\n self.time = datetime.now()\n if prev_time.minute != self.time.minute:\n self.draw_time()\n self.on_minute.emit()\n\n if prev_time.day != self.time.day:\n self.on_day.emit()\n \n def draw_time(self):\n fmt = '%-I:%M' if sys.platform == 'linux' else '%#I:%M'\n self.time_widget.setText(self.time.strftime(fmt))","repo_name":"zuhairp/smartframe","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"15188422412","text":"import time \n\n\ndef reply():\n print()\n print(\"I'll give you a moment.\")\n print()\n\n\ndef food(question):\n valid = False\n while not valid:\n response = input(question).lower()\n\n if response == \"Sea Salt Crackers\" or response == \"A\":\n response = \"Sea Salt Crackers\"\n return response\n\n elif response == \"Griffins Snax\" or response == \"B\":\n response = \"Griffins Snax\"\n return response\n\n elif response == \"Pizza Shapes\" or response == \"C\":\n response = \"Pizza Shapes\"\n\n elif response == \"Arnotts Cheds\" or response == \"D\":\n response = \"Arnotts Cheds\"\n\n elif response == \"Rosemary Wheat\" or response == \"E\":\n response = \"Rosemary Wheat\"\n\n elif response == \"Original Rice Crackers\" or response == \"F\":\n response = \"Original Rice Crackers\"\n\n else:\n print (\"Choose an item from the Menu please.\")\n\n\n\n\n\ndef yes_no(question):\n valid = False\n while not valid:\n response = input(question).lower()\n\n if response == \"yes\" or response == \"y\":\n response = \"yes\"\n return response\n\n elif response == \"no\" or response == \"n\":\n response = \"no\"\n return response\n\n else:\n print (\"Please type yes/no\")\n\n\n\nwant_order = yes_no(\"Would you like to order now? \")\nif want_order == \"no\" or want_order == \"n\":\n reply()\n time.sleep(10)\n want_order = yes_no(\"Would you like to order now? \")\nif want_order == \"no\" or want_order == \"n\":\n reply()\n time.sleep(10)\n want_order = yes_no(\"Would you like to order now? \")\n \n \n\nif want_order == \"yes\" or want_order == \"y\":\n print()\n\nwould_like = food (\"What can I get you today?\")\n\nif would_like == \"Sea Salt Crackers\" or would_like == \"A\":\n print(\"That will come to a total of $2.00.\")\n\nif would_like == \"Griffins Snax\" or would_like == \"B\":\n print(\"That will come to a total of $2.50.\")\n\nif would_like == \"Pizza Shapes\" or would_like == \"C\":\n print(\"That will come to a total of $3.30.\")\n\nif would_like == \"Arnotts Cheds\" or would_like == \"D\":\n print(\"That will come to a total of $3.99.\")\n\nif would_like == \"Rosemary Wheat\" or would_like == \"E\":\n print(\"That will come to a total of $2.00.\")\n\nif would_like == \"Original Rice Crackers\" or would_like == \"F\":\n print(\"That will come to a total of $1.65.\")\n\n\n\n \n\n ","repo_name":"finnthorley/Snack-Price","sub_path":"Ordering_v2.py","file_name":"Ordering_v2.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21341342677","text":"\"\"\"\nGiven two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is\nthe inorder traversal of the same tree, construct and return the binary tree.\n\nInspiration of solution\nhttps://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solutions/34579/python-short-recursive-solution/\n\nSolution is recursive where we will divide the problem at each stage by basic optimisations\n\"\"\"\nfrom Tree.Node import TreeNode\n\n\ndef solution(preorder, inorder):\n # first node in preorder is always root\n # making base condition as validation becoz we are trimming the inorder at every call\n if inorder:\n ind = inorder.index(preorder.pop(0))\n root = TreeNode(inorder[ind])\n # we will divide the inorder as that had root in middle\n root.left = solution(preorder, inorder[0:ind])\n root.right = solution(preorder, inorder[ind+1:])\n return root\n\n\n","repo_name":"prakharkohq/Practice","sub_path":"Tree/leadcoding/MED_Construct_tree_from_in_pre.py","file_name":"MED_Construct_tree_from_in_pre.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41508716524","text":"# -*- coding: utf-8 -*-\nimport os,sys\n\n# Import Qt modules\nfrom PyQt4.QtCore import * \nfrom PyQt4.QtGui import *\nfrom model import *\nfrom utils import _date_from_str\n\n# Import the compiled UI module\nsys.path.append(\"ui\")\nfrom new_manufacter_form_ui import Ui_new_manufacter_form\n\n\nclass NewManufacterForm(QFrame):\n\tdef __init__(self, parent):\n\t\tQFrame.__init__(self)\n\t\tself.ui = Ui_new_manufacter_form()\n\t\tself.ui.setupUi(self)\n\t\tself.parent = parent\n\t\tself.setWindowTitle(QString.fromUtf8('Добавить нового производителя'))\n\t\tQObject.connect(self.ui.ok_btn, SIGNAL(\"clicked()\"), self.addManufacter)\n\t\t\n\tdef addManufacter(self):\n\t\tmanufacter = Manufacter(str(self.ui.manufacter_name.text().toUtf8()), str(self.ui.manufacter_country.text().toUtf8()))\n\t\ts = Session()\n\t\ts.add(manufacter)\n\t\ts.commit()\n\t\ts.close()\n\t\tself.emit(SIGNAL(\"manufacterAdded()\"))\n\t\tself.close()","repo_name":"thefrolov/open-drug-store","sub_path":"new_manufacter_form.py","file_name":"new_manufacter_form.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74946337819","text":"import numpy as np\n\nfrom ..traces.abstract_reader import AbstractReader\nfrom ..traces.trace_header_set import build_trace_header_set\nimport estraces\nimport numpy as _np\n\n\ndef read_ths_from_multiple_ths(*args, **kwargs):\n \"\"\"Build and returns a :class:`TraceHeaderSet` instance as the concatenation of all input THSs.\n\n Args:\n args: some `TraceHeaderSet` objects.\n kwargs: some `TraceHeaderSet` objects.\n\n You can pass a headers dict argument to override inconsistent headers between trace header sets or add custom values.\n\n Note:\n shape and metadata must be consistent between each ths.\n\n Returns:\n (:obj:`TraceHeaderSet`)\n\n \"\"\"\n return build_trace_header_set(\n reader=ConcatFormatReader(*args, **kwargs),\n name='Concat Format THS'\n )\n\n\nclass ConcatFormatReader(AbstractReader):\n\n def __init__(self, *args, **kwargs):\n\n headers = kwargs.pop('headers', {})\n all_args = dict(**{f'ths_{i}': arg for i, arg in enumerate(args)}, **kwargs)\n self._check_are_trace_header_sets(all_args)\n self._check_metadata_consistency(all_args)\n self._check_sample_shapes_and_dtype_consistency(all_args)\n self._check_metadata_shapes_and_dtype_consistency(all_args)\n self._headers = self._check_headers(all_args, headers)\n\n self.ths_list = list(all_args.values())\n self._ths_dict = all_args\n self._trace_size = self.ths_list[0]._reader.get_trace_size(0)\n self._trace_dtype = self.ths_list[0].samples[0].dtype\n self._metas_infos = self._get_metadatas_infos()\n\n self._sizes = [len(ths) for ths in self.ths_list]\n self._size = _np.sum(self._sizes)\n\n self._sub_traceset_indices = _np.arange(self._size)\n\n @staticmethod\n def _check_are_trace_header_sets(thss_dict):\n for key in thss_dict.keys():\n if not isinstance(thss_dict[key], estraces.TraceHeaderSet):\n raise TypeError(f'{key} argument must be a `TraceHeaderSet` object, not `{type(thss_dict[key])}`.')\n\n @staticmethod\n def _check_metadata_consistency(thss_dict):\n key0 = list(thss_dict.keys())[0]\n set0 = set(thss_dict[key0]._reader.metadatas_keys)\n for key in thss_dict.keys():\n set1 = set(thss_dict[key]._reader.metadatas_keys)\n if set0 != set1:\n raise ValueError(f'Inconsistent metadatas between: {key0}, {set0} and {key}, {set1}')\n\n @staticmethod\n def _check_headers(thss_dict, headers={}):\n ths_0 = list(thss_dict.values())[0]\n set_0 = set(ths_0.headers.keys())\n for key, ths in thss_dict.items():\n if ths == ths_0:\n continue\n set_1 = set(ths.headers.keys())\n if set_0 != set_1:\n diff = set_0.difference(set_1)\n for key in diff:\n if key not in headers:\n raise ValueError(\n f'Inconsistent headers, {key} missing from one ths.\\\n You should override headers values by passing a headers dict to the constructor.'\n )\n for k in set_0:\n if k not in headers:\n val_1 = ths.headers[k]\n val_2 = ths_0.headers[k]\n equal = _np.array_equal(val_1, val_2) if isinstance(val_1, _np.ndarray) else val_1 == val_2\n if not equal:\n raise ValueError(\n f'Inconsistent headers values between {ths_0} and {ths} for header {k}.\\\n You should override headers values by passing a headers dict to the constructor.'\n )\n headers[k] = val_1\n return headers\n\n @staticmethod\n def _check_sample_shapes_and_dtype_consistency(thss_dict):\n key0 = list(thss_dict.keys())[0]\n ths0 = thss_dict[key0]\n for key in thss_dict.keys():\n ths1 = thss_dict[key]\n if ths0._reader.get_trace_size(0) != ths1._reader.get_trace_size(0):\n raise ValueError(f'Inconsistent samples shapes: samples length is {ths0._reader.get_trace_size(0)} for {key0} and samples length '\n f'is {ths1._reader.get_trace_size(0)} for {key}')\n if ths0[0].samples[0].dtype != ths1[0].samples[0].dtype:\n raise ValueError(f'Inconsistent samples dtypes: samples dtype is {ths0[0].samples[0].dtype} for {key0} and samples dtype '\n f'is {ths1[0].samples[0].dtype} for {key}')\n\n @staticmethod\n def _check_metadata_shapes_and_dtype_consistency(thss_dict):\n key0 = list(thss_dict.keys())[0]\n ths0 = thss_dict[key0]\n metas0 = list(ths0.metadatas)\n for key in thss_dict.keys():\n ths1 = thss_dict[key]\n for meta in metas0:\n meta0 = ths0[0].metadatas[meta]\n meta1 = ths1[0].metadatas[meta]\n dtype0 = ConcatFormatReader._get_meta_dtype(meta0)\n dtype1 = ConcatFormatReader._get_meta_dtype(meta1)\n if dtype0.kind != dtype1.kind:\n raise ValueError(f'Inconsistent {meta} dtypes: {meta} dtype is {dtype0} for {key0} and {meta} dtype '\n f'is {dtype1} for {key}')\n if dtype0.kind != 'U':\n if len(meta0) != len(meta1):\n raise ValueError(f'Inconsistent {meta} shapes: {meta} length is {len(meta0)} for {key0} and {meta} length '\n f'is {len(meta1)} for {key}')\n\n @staticmethod\n def _get_meta_dtype(meta):\n try:\n dtype = meta.dtype\n if dtype.kind == 'O':\n meta = meta.flat[0]\n raise AttributeError\n return meta.dtype\n except AttributeError:\n if not isinstance(meta, str):\n raise TypeError(f'Metadata type not supported: {type(meta)}')\n return _np.dtype(f' rez.dtype.itemsize:\n rez = rez.astype(data_dtype)\n rez[result_indices] = data\n if is_int_trace_id:\n rez = rez[0]\n return rez\n\n def fetch_samples(self, traces, frame):\n if frame is None:\n frame = slice(None)\n if traces is None:\n traces = slice(len(self))\n if isinstance(traces, int):\n traces = slice(traces, traces + 1)\n if isinstance(frame, int):\n if frame < 0:\n frame = slice(frame, None)\n else:\n frame = slice(frame, frame + 1)\n\n original_traces_indices_per_set, indices_per_set, length = self._convert_traces_indices_to_list_of_raw_traces_indices_per_set(traces)\n rez = np.empty(shape=(length, self._trace_size), dtype=self._trace_dtype)\n rez = rez[:, frame]\n for indices, result_indices, ths in zip(original_traces_indices_per_set, indices_per_set, self.ths_list):\n if len(indices):\n data = ths.samples[indices, frame]\n rez[result_indices] = data\n return rez\n\n def __getitem__(self, key):\n super().__getitem__(key)\n\n if isinstance(key, int):\n key = [key]\n\n new_sub_traceset_indices = self._sub_traceset_indices[key]\n new_reader = ConcatFormatReader(**self._ths_dict)\n new_reader._sub_traceset_indices = new_sub_traceset_indices\n new_reader._size = len(new_sub_traceset_indices)\n\n return new_reader\n\n @property\n def metadatas_keys(self):\n return self.ths_list[0]._reader.metadatas_keys\n\n @property\n def headers_keys(self):\n return self._headers.keys()\n\n def fetch_header(self, key):\n return self._headers[key]\n\n def get_trace_size(self, trace_id):\n return self._trace_size\n\n def __repr__(self):\n return self.__str__()\n\n def __str__(self):\n return f'Concat format reader of {self.ths_list} with {len(self)} traces.'\n","repo_name":"eshard/estraces","sub_path":"estraces/formats/concat_format.py","file_name":"concat_format.py","file_ext":"py","file_size_in_byte":10024,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"69"} +{"seq_id":"21992032159","text":"# This program will scrape the 7-day forecast of the weather for Boston\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n# Make request to web page\r\npage = requests.get(\"https://weather.com/weather/today/l/d7f5a4af529e40b0a82d339e5467e89458e5ad5e2cf0ffdd05c853ed3e98fd38\")\r\n\r\n# Create soup object to parse web page\r\nsoup = BeautifulSoup(page.content, 'html.parser')\r\n\r\n# Find id tag on the HTML block I need\r\nlook_ahead = soup.find(id=\"main-LookingAhead-b39982dc-b828-42f9-9ca4-3d6686c1bb83\")\r\n# print(look_ahead)\r\n\r\n# Need to id all elements with class = looking-ahead\r\nforecast_items = look_ahead.find(class_=\"looking-ahead\")\r\n# print(forecast_items)\r\n\r\n# Get the content from that class, and dig deeper to find where the content is hidden\r\n# in class = looking-ahead; class = today-daypart-content,\r\ncontent = forecast_items.find(class_=\"today-daypart-content\")\r\nprint(content)\r\n\r\nperiod = content.find(class_=\"today-daypart-title\").get_text()\r\nshort_desc = content.find(class_=\"today-daypart-wxphrase\").get_text()\r\nhi_low = content.find(class_=\"today-daypart-hilo\").get_text()\r\ntemp = content.find(class_=\"today-daypart-temp\").get_text()\r\nprecip = content.find(class_=\"today-daypart-precip\").get_text()\r\n\r\n# print(period) # Today\r\n# print(short_desc)\r\n# print(hi_low)\r\n# print(temp)\r\n# print(precip)\r\n#\r\n# print(f\"In Hyderabad {period}, the weather looks like this: \")\r\n# print(f\"Conditions: {short_desc}\")\r\n# print(f\"High/Low: {hi_low}\")\r\n# print(f\"Temp: {temp}\")\r\n# print(f\"Chance of rain: {precip}\")\r\n\r\n\r\n# Pull the information for the rest of the periods\r\nperiods = forecast_items.select(\".today-daypart-content .today-daypart-title\")\r\n\r\nperiod_names = [item.get_text() for item in periods]\r\nshort_descs = [item.get_text() for item in forecast_items.select(\".today-daypart-content .today-daypart-wxphrase\")]\r\nhi_lows = [item.get_text() for item in forecast_items.select(\".today-daypart-content .today-daypart-hilo\")]\r\ntemps = [item.get_text() for item in forecast_items.select(\".today-daypart-content .today-daypart-temp\")]\r\nprecips = [item.get_text() for item in forecast_items.select(\".today-daypart-content .today-daypart-precip\")]\r\n\r\nprint(period_names)\r\nprint(short_descs)\r\nprint(hi_lows)\r\nprint(temps)\r\nprint(precips)\r\n\r\n# Import into pandas DF\r\nimport pandas as pd\r\nweather = pd.DataFrame({\r\n \"Period\": period_names,\r\n \"Short_Desc\": short_descs,\r\n \"High/Low\" : hi_lows,\r\n \"Temp\": temps,\r\n \"Chance of rain\" : precips\r\n})\r\n\r\nprint(weather)\r\n\r\n# Do some analysis on the data.\r\n#\r\n# Find the mean temp\r\ntemp_nums = weather[\"Temp\"].str.extract(\"(?P\\d+)\", expand=False)\r\n# Create a new column called \"Temp num, that only has the number\r\nweather[\"Temp num\"] = temp_nums.astype('int')\r\nmean_temp = weather[\"Temp num\"].mean()\r\n\r\nprint(temp_nums)\r\nprint(weather)\r\nprint(\"Mean Temp: \", mean_temp)\r\n\r\n# Find the ones that happen at night\r\nis_night = weather[\"High/Low\"].str.contains(\"Low\")\r\nweather[\"is_night\"] = is_night\r\nprint(weather)","repo_name":"mreddy787/Webscraping","sub_path":"WebScrape_Hyd_Weather.py","file_name":"WebScrape_Hyd_Weather.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21833050596","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport asyncio\nimport asynctest\nimport pytest\n\nfrom asynctest.mock import patch\nfrom metadoc.extract.pos import do_train, AveragedPerceptronTagger\n\nclass MetadocPerceptronTest(asynctest.TestCase):\n def setUp(self):\n return\n\n @asynctest.ignore_loop\n def test_init(self):\n self.perceptron_tagger = AveragedPerceptronTagger(autoload=True)\n tags = self.perceptron_tagger.tag(\"Rami Eid is studying at Stony Brook University in NY\")\n assert len(tags) == 10\n\n @asynctest.ignore_loop\n def test_string_ends_with_nnp(self):\n self.perceptron_tagger = AveragedPerceptronTagger(autoload=True)\n test_sentence = \"The extraordinary phenomenon of fake news spread by Facebook and other \\\n social media during the 2016 presidential election has been largely portrayed as a lucky break for Donald Trump\"\n\n tags = self.perceptron_tagger.tag(test_sentence)\n entities = self.perceptron_tagger.named_entities(tags)\n \n assert tags[len(tags)-1][1] == \"NNP\"\n assert \"Donald Trump\" in entities\n\n @asynctest.ignore_loop\n @patch('metadoc.extract.pos.pickle.load')\n def test_no_pickle_found(self, _mocked_func):\n _mocked_func.side_effect = IOError('foo')\n with pytest.raises(IOError):\n AveragedPerceptronTagger(autoload=True)\n","repo_name":"fanmatics/metadoc","sub_path":"tests/test_pos.py","file_name":"test_pos.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"69"} +{"seq_id":"29313566463","text":"import json\nimport os\nfrom functools import partial\n\nimport mock\nimport trio\nfrom PortThreadManager import PortThreadManager\n\n\nclass TestRedeploy:\n \"\"\"\n Test that runs the PTM file with different configs,\n to check that configuration changes are handled correctly.\n \"\"\"\n\n async def test_redeploy(self, mocker, nursery):\n man = PortThreadManager()\n\n m1 = mocker.patch.object(man.db, \"getConfig\")\n with open(\"../../config/default_hp_config.json\") as f:\n m1.return_value = json.load(f)\n\n mocker.patch.object(man.db, \"saveAlertObject\")\n mocker.patch.object(man.db, \"watchConfig\")\n\n man_ctx = await nursery.start(man.activate)\n\n # Need time to make sure everything initially deploys\n await trio.sleep(5)\n\n # Socket testing with senddata.json\n assert len(man.config.services) == 2\n assert 80 in man.config.open_ports\n assert 22 in man.config.open_ports\n\n assert (\n man.processList[80].port == 80\n and man.processList[80].isRunning\n and man.processList[22].port == 22\n and man.processList[22].isRunning\n )\n\n # Cleaning\n man_ctx.cancel() # clean tasks\n man.processList = dict() # clean listener objects\n\n s2 = mocker.patch.object(man.db, \"getConfig\")\n with open(\"./test/defaults_altered.json\") as f:\n s2.return_value = json.load(f)\n\n mocker.patch.object(man.db, \"saveAlertObject\")\n\n # Redeploying\n man_ctx = await nursery.start(\n partial(man.activate, updateSniffer=True, updateOpenPorts=True,)\n )\n\n await trio.sleep(2)\n\n assert len(man.config.services) == 1\n assert 2223 in man.config.open_ports\n\n assert (\n man.processList[2223].port == 2223\n and man.processList[2223].isRunning\n )\n\n man_ctx.cancel() # clean tasks\n man.processList = dict() # clean listener objects","repo_name":"ReplayProject/ReplayHoneypots","sub_path":"honeypots/honeypot/test/test_PTM.py","file_name":"test_PTM.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"67"} +{"seq_id":"4975662343","text":"import socket\nimport ssl\nimport os\n\nclass server_ssl:\n def build_listen(self):\n # 生成SSL上下文\n context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n # 加载服务器所用证书和私钥\n context.load_cert_chain('cert/server.crt', 'cert/server_rsa_private.pem.unsecure')\n server_path='server_files/'\n # 监听端口\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:\n sock.bind(('localhost', 8000))\n sock.listen(5)\n # 将socket打包成SSL socket,其主要工作是完成密钥协商\n with context.wrap_socket(sock, server_side=True) as ssock:\n client_socket, addr = ssock.accept()\n msg = client_socket.recv(1024).decode(\"utf-8\")\n print(f\"receive msg from client {addr}:{msg}\")\n msg = f\"yes , you have client_socketect with server.\\n\".encode(\"utf-8\")\n client_socket.send(msg)\n while True:\n file_name = client_socket.recv(1024).decode('utf-8')\n if not os.path.isfile(server_path+file_name):\n client_socket.send('not found file'.encode(\"utf-8\"))\n continue\n with open(server_path+file_name, 'rb') as file:\n client_socket.send(f'{os.stat(server_path+file_name).st_size}'.encode('utf-8'))\n while True:\n data=file.read(1024)\n try:\n client_socket.send(data)\n except ssl.SSLEOFError:\n pass\n if not data:\n print(\"transmit complete\")\n break\n client_socket.close()\n\nif __name__ == \"__main__\":\n server = server_ssl()\n server.build_listen()","repo_name":"ilrewrite/sockt-ssl-","sub_path":"server_and_client/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19965870257","text":"#!/usr/bin/env python\n\n# WS server example that synchronizes state across clients\n#收到什么发什么给所有连接端\nimport asyncio\nimport json\nimport websockets\n\nUSERS = set()\n\ndef users_event():\n return json.dumps({'type': 'users', 'count': len(USERS)})\n\nasync def notify_users():\n if USERS: # asyncio.wait doesn't accept an empty list\n message = users_event()\n await asyncio.wait([user.send(message) for user in USERS])\n \nasync def notify_all(message):\n if USERS: # asyncio.wait doesn't accept an empty list\n #message = state_event()\n await asyncio.wait([user.send(message) for user in USERS])\n \nasync def register(websocket):\n USERS.add(websocket)\n await notify_users()\n\nasync def unregister(websocket):\n USERS.remove(websocket)\n await notify_users()\n\nasync def counter(websocket, path):\n # register(websocket) sends user_event() to websocket\n \n await register(websocket)\n try:\n async for message in websocket:\n await notify_all(message)\n \n finally:\n await unregister(websocket)\n \nstart_server = websockets.serve(counter, 'localhost', 6789)\nasyncio.get_event_loop().run_until_complete(start_server)\nasyncio.get_event_loop().run_forever()","repo_name":"hareruya2008/ws_server","sub_path":"ws_server.py","file_name":"ws_server.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"5782151310","text":"from torch.utils.data import Dataset, DataLoader\n\nimport numpy as np\nimport os\nimport random\nimport pickle, h5py\nimport cv2\nimport torch\nimport torch\nfrom torch.autograd import Variable\n\nimport json\nimport skimage\n# from skimage.transform import resize\n# import skimage as s\nimport pdb\nimport random\nnormal_mean = (0.5, 0.5, 0.5)\nnormal_std = (0.5, 0.5, 0.5)\nfrom torchvision import transforms\n\nfrom skimage import img_as_bool\nfrom PIL import Image\nfrom io import BytesIO\nfrom scipy.ndimage import zoom as scizoom\n\nfrom wand.image import Image as WandImage\nfrom wand.api import library as wandlibrary\nimport wand.color as WandColor\nfrom spatial_transforms import (\n Compose, Normalize, Scale, CenterCrop, CornerCrop, MultiScaleCornerCrop,\n MultiScaleRandomCrop, RandomHorizontalFlip, ToTensor)\n\n\ntry:\n import accimage\nexcept ImportError:\n accimage = None\n\n\ndef clipped_zoom(img, zoom_factor):\n h = img.shape[0]\n # ceil crop height(= crop width)\n ch = int(np.ceil(h / zoom_factor))\n\n top = (h - ch) // 2\n img = scizoom(img[top:top + ch, top:top + ch], (zoom_factor, zoom_factor, 1), order=1)\n # trim off any extra pixels\n trim_top = (img.shape[0] - h) // 2\n\n return img[trim_top:trim_top + h, trim_top:trim_top + h]\n\nimport ctypes\n\n# Tell Python about the C method\nwandlibrary.MagickMotionBlurImage.argtypes = (ctypes.c_void_p, # wand\n ctypes.c_double, # radius\n ctypes.c_double, # sigma\n ctypes.c_double) # angle\n\n\n# Extend wand.image.Image class to include method signature\nclass MotionImage(WandImage):\n def motion_blur(self, radius=0.0, sigma=0.0, angle=0.0):\n wandlibrary.MagickMotionBlurImage(self.wand, radius, sigma, angle)\n\n\n \ndef motion_blur(x, severity=1):\n c = [(10, 3), (15, 5), (15, 8), (15, 12), (20, 15)][severity - 1]\n\n output = BytesIO()\n x.save(output, format='PNG')\n x = MotionImage(blob=output.getvalue())\n\n x.motion_blur(radius=c[0], sigma=c[1], angle=np.random.uniform(-45, 45))\n\n x = cv2.imdecode(np.fromstring(x.make_blob(), np.uint8),\n cv2.IMREAD_UNCHANGED)\n\n if x.shape != (256, 256):\n return Image.fromarray(np.uint8(np.clip(x[..., [2, 1, 0]], 0, 255))) # BGR to RGB\n else: # greyscale to RGB\n return Image.fromarray(np.uint8(np.clip(np.array([x, x, x]).transpose((1, 2, 0)), 0, 255)))\n\n \ndef zoom_blur(x, severity=1):\n c = [np.arange(1, 1.11, 0.01),\n np.arange(1, 1.16, 0.01),\n np.arange(1, 1.21, 0.02),\n np.arange(1, 1.26, 0.02),\n np.arange(1, 1.31, 0.03)][severity - 1]\n\n x = (np.array(x)/255.0).astype(np.float32)\n out = np.zeros_like(x)\n for zoom_factor in c:\n out += clipped_zoom(x, zoom_factor)\n\n x = (x + out) / (len(c) + 1)\n return Image.fromarray(np.uint8(np.clip(x, 0, 1)*255.0))\n\ndef impulse_noise(x, severity=2):\n c = [.03, .06, .09, 0.17, 0.27][severity - 1]\n\n x = skimage.util.random_noise(np.array(x) / 255., mode='s&p', amount=c)\n return Image.fromarray(np.uint8(np.clip(x, 0, 1) * 255))\n\ndef shot_noise(x, severity=4):\n c = [250, 100, 50, 30, 15][severity - 1]\n\n x = np.array(x) / 255.\n return Image.fromarray(np.uint8(np.clip(np.random.poisson(x * c) / c, 0, 1) * 255))\n\ndef gaussian_noise(x, severity=1):\n c = [.08, .12, 0.18, 0.26, 0.38][severity - 1]\n\n x = np.array(x) / 255.\n return Image.fromarray(np.uint8(np.clip(x + np.random.normal(size=x.shape, scale=c), 0, 1) * 255))\n\ndef defocus_blur( x, severity=1):\n c = [(3, 0.1), (4, 0.5), (6, 0.5), (8, 0.5), (10, 0.5)][severity - 1]\n\n x = np.array(x)/255.0\n kernel = disk(radius=c[0], alias_blur=c[1])\n# *255\n channels = []\n for d in range(3):\n channels.append(cv2.filter2D(x[:, :, d], -1, kernel))\n channels = np.array(channels).transpose((1, 2, 0)) # 3x224x224 -> 224x224x3\n\n return Image.fromarray(np.uint8(np.clip(channels, 0, 1)*255))\n\n\n\ndef jpeg_compression(x, severity=1):\n c = [25, 18, 15, 10, 7][severity - 1]\n\n output = BytesIO()\n x.save(output, 'JPEG', quality=c)\n x = Image.open(output)\n\n return x\n\ndef disk(radius, alias_blur=0.1, dtype=np.float32):\n if radius <= 8:\n L = np.arange(-8, 8 + 1)\n ksize = (3, 3)\n else:\n L = np.arange(-radius, radius + 1)\n ksize = (5, 5)\n X, Y = np.meshgrid(L, L)\n aliased_disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)\n aliased_disk /= np.sum(aliased_disk)\n\n # supersample disk to antialias\n return cv2.GaussianBlur(aliased_disk, ksize=ksize, sigmaX=alias_blur)\n\n\n\n\n\nclass PackPathway(torch.nn.Module):\n \"\"\"\n Transform for converting video frames as a list of tensors.\n \"\"\"\n def __init__(self):\n super().__init__()\n\n def forward(self, frames: torch.Tensor):\n alpha = 4\n fast_pathway = frames\n # Perform temporal sampling from the fast pathway.\n slow_pathway = torch.index_select(\n frames,\n 1,\n torch.linspace(\n 0, frames.shape[1] - 1, frames.shape[1] // alpha\n ).long(),\n )\n frame_list = [slow_pathway, fast_pathway]\n return frame_list\n\nclass MotionBlur(torch.nn.Module):\n \"\"\"\n Transform for converting video frames as a list of tensors.\n \"\"\"\n def __init__(self, sev=1):\n self.sev = sev\n super().__init__()\n\n def forward(self, frames):\n frames2 = frames.permute(1, 0, 2,3 )\n t1 = transforms.ToPILImage()\n t2 = transforms.ToTensor()\n v = []\n for f in range(frames2.size()[0]):\n tmp = self.motion_blur(t1(frames2[f]), self.sev)\n v.append(t2(tmp))\n frames_list = torch.stack(v,0)\n frames_list = frames_list.permute(1, 0, 2,3 )\n return frames_list\n \n def motion_blur(self, x, severity=1):\n c = [(10, 3), (15, 5), (15, 8), (15, 12), (20, 15)][severity - 1]\n\n output = BytesIO()\n x.save(output, format='PNG')\n x = MotionImage(blob=output.getvalue())\n\n x.motion_blur(radius=c[0], sigma=c[1], angle=np.random.uniform(-45, 45))\n\n x = cv2.imdecode(np.fromstring(x.make_blob(), np.uint8),\n cv2.IMREAD_UNCHANGED)\n\n if x.shape != (224, 224):\n return Image.fromarray(np.uint8(np.clip(x[..., [2, 1, 0]], 0, 255))) # BGR to RGB\n else: # greyscale to RGB\n return Image.fromarray(np.uint8(np.clip(np.array([x, x, x]).transpose((1, 2, 0)), 0, 255)))\n\n \ndef gaussian_noise(x, severity=1):\n c = [.08, .12, 0.18, 0.26, 0.38][severity - 1]\n \n x = np.array(x) / 255.\n return Image.fromarray(np.uint8(np.clip(x + np.random.normal(size=x.shape, scale=c), 0, 1) * 255))\n\n\ndef rotate(x,deg):\n return x.rotate(deg)\n\n ","repo_name":"rose-ar/rose-ar.github.io","sub_path":"code/pert_fns.py","file_name":"pert_fns.py","file_ext":"py","file_size_in_byte":6901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"24800782180","text":"import os \nimport argparse\nimport torchio as tio\nfrom torchvision import transforms as T\nimport torch \nfrom tqdm import tqdm \nimport numpy as np\nimport torch.nn.functional as F \nfrom IPython import embed\nimport logging\nimport torch.utils.data as data\nfrom time import time\nfrom IPython import embed\n\n\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0, 1, 2, 3\"\n# from utils import npy2nii\n\nfrom detr import *\n\n\n# 创建一个logger\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n# 创建一个handler,用于将日志输出到控制台\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n\n# 创建一个handler,用于将日志写入到文件中\nfh = logging.FileHandler('/public_bme/data/xiongjl/detr/log/detr_v52nodes.log')\nfh.setLevel(logging.INFO)\n\n# 定义handler的输出格式\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nfh.setFormatter(formatter)\n\n# 将handler添加到logger中\nlogger.addHandler(ch)\nlogger.addHandler(fh)\n\n\n\n\ndef save(step, opt, model, out_path, name='model'):\n\n data = {\n 'step': step,\n 'model': model.state_dict(),\n 'opt': opt.state_dict()\n }\n\n torch.save(data, os.path.join(out_path, f'{name}-{step}.pt')) \n\n\ndef train(config):\n \n\n detr_loss = build_loss(1).cuda()\n model = DETR(backbone='resnet50', position_embedding='sine', hidden_dim=256, num_classes=1, num_queries=10)\n\n time_cuda = time()\n model.cuda()\n print(time() - time_cuda)\n \n if config.model != 'normal':\n model_path = '/public_bme/data/xiongjl/det/save/best_model-120.pt'\n model.load_state_dict(torch.load(model_path)['model'])\n\n\n optimizer = torch.optim.Adam(model.parameters(), config.lr)\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, config.scheduler_steps, gamma=config.gamma)\n \n # if config.pretrained_model:\n # model.load_state_dict(torch.load(config.pretrained_model)['model'], strict=False)\n \n best_loss = 1e4\n\n with tqdm(total=(config.total_steps)) as pbar:\n for step in range(config.total_steps):\n\n if (step) % 200 == 0:\n # if (step) % 100 == 0:\n model.eval()\n os.makedirs(config.save_dir, exist_ok=True)\n save(step, optimizer, model, config.save_dir, name=config.save_model_name)\n\n\n with torch.no_grad():\n loss_ce_loss = 0\n class_error_loss = 0\n loss_giou_loss = 0\n loss_bbox_loss = 0\n cardinality_error_loss = 0\n for i in range(20):\n \n # val_step = 1\n # embed()\n inputs, targets = data_set()\n inputs = inputs.float().cuda()\n out = model(inputs)\n valid_loss = detr_loss(out, targets)\n \n loss_ce_loss += valid_loss[\"loss_ce\"].item()\n class_error_loss += valid_loss[\"class_error\"].item()\n loss_giou_loss += valid_loss[\"loss_giou\"].item()\n loss_bbox_loss += valid_loss[\"loss_bbox\"].item()\n cardinality_error_loss += valid_loss[\"cardinality_error\"].item()\n weight_dict = detr_loss.weight_dict\n valid_loss = sum(valid_loss[k] * weight_dict[k] for k in valid_loss.keys() if k in weight_dict)\n\n # targets = targets.cuda()\n # embed()\n\n \n\n logger.info(f'valid loss_ce loss : {loss_ce_loss/20.}\\n')\n logger.info(f'valid class_error loss : {class_error_loss/20.}\\n')\n logger.info(f'valid loss_giou loss : {loss_giou_loss/20.}\\n')\n logger.info(f'valid loss_bbox loss : {loss_bbox_loss/20.}\\n')\n logger.info(f'valid cardinality_error loss : {cardinality_error_loss/20.}\\n')\n # valid_loss.append(loss.item())\n # val_step += 1\n\n # logger.info('Epoch: %d, valid_Loss: %.4f', step, np.mean(valid_loss))\n\n if best_loss > valid_loss.item():\n best_loss = valid_loss.item()\n os.makedirs(config.save_dir, exist_ok=True)\n save(step, optimizer, model, config.save_dir, name=config.best_model_name)\n \n \n pbar.set_description(f'{step} - valid: {valid_loss:.4f}\\n')\n # writer.add_scalar('valid/loss', np.mean(valid_loss), step)\n \n \n model.train()\n # batch_step = 0\n # train_loss = []\n # train_batch = next(train_loader)\n # for inputs, targets in train_dataset:\n loss_ce_loss = 0\n class_error_loss = 0\n loss_giou_loss = 0\n loss_bbox_loss = 0\n cardinality_error_loss = 0\n for i in range(20):\n inputs, targets = data_set()\n inputs = inputs.float().cuda()\n # targets = [target.cuda() for target in targets]\n\n\n out = model(inputs)\n train_loss = detr_loss(out, targets)\n weight_dict = detr_loss.weight_dict\n\n loss_ce_loss += train_loss[\"loss_ce\"].item()\n class_error_loss += train_loss[\"class_error\"].item()\n loss_giou_loss += train_loss[\"loss_giou\"].item()\n loss_bbox_loss += train_loss[\"loss_bbox\"].item()\n cardinality_error_loss += train_loss[\"cardinality_error\"].item()\n\n\n\n train_loss = sum(train_loss[k] * weight_dict[k] for k in train_loss.keys() if k in weight_dict)\n # train_loss.append(loss.item())\n optimizer.zero_grad()\n train_loss.backward()\n optimizer.step()\n lr_scheduler.step() \n \n # batch_step += 1\n # print(loss.item())\n logger.info(f'train loss_ce loss : {loss_ce_loss/20.}\\n')\n logger.info(f'train class_error loss : {class_error_loss/20.}\\n')\n logger.info(f'train loss_giou loss : {loss_giou_loss/20.}\\n')\n logger.info(f'train loss_bbox loss : {loss_bbox_loss/20.}\\n')\n logger.info(f'train cardinality_error loss : {cardinality_error_loss/20.}\\n')\n\n \n \n # loss /= len(train_loader) \n # logger.info('Epoch: %d, train_Loss: %.4f', step, np.mean(train_loss))\n # logger.info('average_train_Loss: %.4f', np.mean(train_loss)) \n pbar.set_description(f'{step} - train: {train_loss.item():.4f}\\n')\n # writer.add_scalar('train/loss', loss.item(), step)\n pbar.update(1) \n \n \n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser(description=\"detr\")\n parser.add_argument('--log_dir', default='./log')\n parser.add_argument('--seed', default=1)\n parser.add_argument('--train_batch_size', default=1)\n parser.add_argument('--valid_batch_size', default=1)\n parser.add_argument('--model_type', default=50)\n parser.add_argument('--backbone_name', default='resnet50')\n parser.add_argument('--num_classes', default=1)\n parser.add_argument('--pretrained_model', default='/public_bme/data/meilzj/Tooth/output/panoramic_xray/detects/model-52500.pt')\n parser.add_argument('--lr', default=1e-4)\n parser.add_argument('--scheduler_steps', default=10000)\n parser.add_argument('--gamma', default=0.1)\n parser.add_argument('--total_steps', default=20000)\n parser.add_argument('--valid_steps', default=1000)\n parser.add_argument('--save_freq', default=20)\n parser.add_argument('--save_dir', default='/public_bme/data/xiongjl/detr/save')\n parser.add_argument('--point_weight', default=4)\n parser.add_argument('--model', default='normal')\n parser.add_argument('--log_name', default='./log/training_50')\n parser.add_argument('--best_model_name', default='best_detrmodel50_v5_2nodes')\n parser.add_argument('--save_model_name', default='detrmodel50_v5_2nodes')\n args = parser.parse_args()\n \n train(args)\n \n \n \n","repo_name":"xiongjiuli/detr_3d","sub_path":"train_bme.py","file_name":"train_bme.py","file_ext":"py","file_size_in_byte":8411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"15023683971","text":"\"\"\"\n\"\"\"\n\nimport tensorflow as tf \nimport numpy as np\nimport pickle\nimport argparse\nimport os\n\nfrom cvision_tools import read_image, detect_face, crop_face, convert_to_gray, resize_with_pad\nfrom CohnKanadeDataset import CohnKanadeDataset\n\nimport cv2 as cv2\n\nimage_height = 64\nimage_width = 64\nimage_n_channels = 1\n\nEMOTION_DECODER_PATH = \"./model/emotion_decoder.pickle\"\nEMOTION_PREDICTION_MODEL_PATH = \"./model/emotion_model\"\n\nTEST_DATA_PATH = \"./data/test/\"\n\n\ndef prepare_image(image):\n image = np.array(image)\n face = crop_face(image)\n face = resize_with_pad(face, image_height, image_width)\n face = convert_to_gray(face)\n face = np.array(face)\n face = face.reshape(-1, image_height, image_width, image_n_channels)\n face = face.astype('float32')\n face = face / 128 - 1\n return image, face\n\n\ndef indetify_emotion(face):\n emotion_decoder = pickle.load(open(EMOTION_DECODER_PATH, 'rb'))\n\n tf.reset_default_graph()\n saver = tf.train.import_meta_graph(EMOTION_PREDICTION_MODEL_PATH + '.meta')\n graph = tf.get_default_graph()\n\n X = graph.get_tensor_by_name(\"cnn_graph_emotion/X:0\")\n Y_proba_emotion = graph.get_tensor_by_name(\"cnn_graph_emotion/Y_proba_emotion:0\")\n\n with tf.Session() as predict_sess:\n saver.restore(predict_sess, EMOTION_PREDICTION_MODEL_PATH)\n probs = Y_proba_emotion.eval(feed_dict={X: face})\n emotion_index = np.argmax(probs)\n predicted_emotion = emotion_decoder[emotion_index]\n prob_emotion = probs[0, emotion_index]\n\n print(probs)\n print( predicted_emotion )\n print(\"Confidennce={}\".format(prob_emotion))\n\n return predicted_emotion, prob_emotion\n\n\ndef display_image(image, predicted_label, prob_label, show_face_area=True, wait_time=0, image_out_path=''):\n image = resize_with_pad(image, 600, 600)\n if show_face_area:\n x, y, w, h = detect_face(image)\n cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 2)\n\n cv2.putText(image, \"{}\".format(predicted_label), (10, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2) \n cv2.putText(image, \"Prob: {:.2f}\".format(prob_label), (10, 130), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)\n cv2.imshow(\"Image\", image)\n cv2.waitKey(wait_time)\n print(image_out_path)\n if image_out_path != '':\n cv2.imwrite(image_out_path, image)\n\ndef predict_image(image_path, image_out_path=''):\n image = read_image(image_path)\n image, face = prepare_image(image)\n predicted_emotion, prob_emotion = indetify_emotion(face)\n display_image(image, predicted_emotion, prob_emotion, image_out_path=image_out_path)\n\n\ndef main():\n\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-p\", \"--path\", type=str, default=\"\", help=\"Specify the path to the input image\")\n args = vars(ap.parse_args())\n image_path = args[\"path\"]\n \n if (image_path != \"\"):\n predict_image(image_path)\n else:\n for filename in os.listdir(TEST_DATA_PATH):\n if os.path.isfile(os.path.join(TEST_DATA_PATH, filename)):\n image_path = os.path.join(TEST_DATA_PATH, filename)\n image_out_path = os.path.join( os.path.join(TEST_DATA_PATH, \"out/\"), filename)\n predict_image(image_path, image_out_path)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"kamal-rahimi/EmotionDetection","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"41449288952","text":"import scipy.signal as sig\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.signal import convolve\r\nfrom scipy.datasets import electrocardiogram\r\n\r\nALPHA_S = 40 # atenuación en dB de la banda de rechazo\r\nDELTA_F = 3 # Ancho de la ventana\r\nELECTROCARDIOGRAM_FREQUENCIES = [1, 50] # Frecuencias de interés\r\nLINE_FREQUENCY_50 = 50 # Notch\r\nLINE_FREQUENCY_60 = 60 # Notch\r\nSAMPLING_RATE = 400 # Frecuencia de muestreo\r\nMAX_DELAY = 1 # segundos\r\nMAX_NUM_TAPS = int(MAX_DELAY * SAMPLING_RATE) # cantidad máxima de taps\r\n\r\n# The electrocardiogram filter must preserve frecuencies between 0.05 and 100 Hz and remove the 50 Hz line noise\r\nbeta_kaiser = sig.kaiser_beta(ALPHA_S)\r\nDeltaOmega = 2 * np.pi * DELTA_F / SAMPLING_RATE\r\nLh = np.ceil(1 + (ALPHA_S - 8) / (2.285 * DeltaOmega)) # cálculo del orden del filtro\r\nLh = int(Lh * 1.05) # factor de seguridad correctivo\r\nassert Lh <= MAX_NUM_TAPS, 'Ajuste los parámetros del filtro' # toleramos una demora máxima de 1 segundos\r\n\r\nwindow = ('kaiser', beta_kaiser) # Ventana utilizada\r\n\r\nLh_line_supressor = Lh if Lh % 2 else Lh + 1\r\nline_supressor_50_coefficients_fir = sig.firwin(Lh_line_supressor,\r\n [LINE_FREQUENCY_50 - DELTA_F / 2, LINE_FREQUENCY_50 + DELTA_F / 2],\r\n pass_zero='bandstop', fs=SAMPLING_RATE, window=window)\r\nline_supressor_60_coefficients_fir = sig.firwin(Lh_line_supressor,\r\n [LINE_FREQUENCY_60 - DELTA_F / 2, LINE_FREQUENCY_60 + DELTA_F / 2],\r\n pass_zero='bandstop', fs=SAMPLING_RATE, window=window)\r\npass_band_ecg_coefficients_fir = sig.firwin(Lh, ELECTROCARDIOGRAM_FREQUENCIES, pass_zero=False, fs=SAMPLING_RATE,\r\n window=window)\r\n\r\n# The Pan-Tompkins filter must preserve frecuencies between 5 and 15 Hz\r\npam_topkins_coefficients_iir = sig.iirfilter(2, [5, 15], 1, 20, 'bandpass', output='sos', fs=SAMPLING_RATE)\r\n\r\n\r\ndef plot_freq_response_dlti(filter_parameters, sampling_frecuency, input_type='ba',\r\n plot_phase=False, zoom_area=None, title=None):\r\n sampling_time = 1 / sampling_frecuency\r\n if zoom_area:\r\n array_omega = 2 * np.pi * sampling_time * np.linspace(zoom_area[0], zoom_area[1], 10000)\r\n else:\r\n array_omega = None\r\n if input_type == 'sos':\r\n array_discrete_freq, freq_response = sig.sosfreqz(filter_parameters, worN=array_omega)\r\n elif input_type == 'ba' or input_type == 'zpk':\r\n sys_sig = sig.dlti(*filter_parameters)\r\n array_discrete_freq, freq_response = sys_sig.freqresp(array_omega)\r\n else:\r\n raise ValueError('imput_type must be \"ba\", \"sos\" or \"zpk\"')\r\n\r\n if plot_phase:\r\n fig_filter_response, ax_filter_response = plt.subplots(2, 1, figsize=(10, 10))\r\n ax_filter_response[0].plot(array_discrete_freq / (2 * np.pi * sampling_time),\r\n 20 * np.log10(np.abs(freq_response)))\r\n ax_filter_response[0].set_ylabel(\"dB\")\r\n ax_filter_response[0].set_xlabel(\"f\", loc='right')\r\n ax_filter_response[0].grid()\r\n ax_filter_response[1].plot(array_discrete_freq / (2 * np.pi * sampling_time), np.angle(freq_response))\r\n ax_filter_response[1].set_ylabel(r\"$\\angle H(e^{j\\Omega})$\")\r\n ax_filter_response[1].set_yticks([-np.pi + i * np.pi / 4 for i in range(9)],\r\n ['$-\\pi$', '$-\\\\frac{3}{4}\\pi$', '$-\\\\frac{1}{2}\\pi$',\r\n '$-\\\\frac{1}{4}\\pi$', '$0$', '$\\\\frac{1}{4}\\pi$',\r\n '$\\\\frac{1}{2}\\pi$', '$\\\\frac{3}{4}\\pi$', '$\\pi$'])\r\n ax_filter_response[1].set_xlabel(\"f [Hz]\", loc='right')\r\n ax_filter_response[1].grid()\r\n else:\r\n fig_filter_response, ax_filter_response = plt.subplots(1, 1, figsize=(10, 10))\r\n ax_filter_response.plot(array_discrete_freq / (2 * np.pi * sampling_time), 20 * np.log10(np.abs(freq_response)))\r\n ax_filter_response.set_ylabel(\"dB\")\r\n ax_filter_response.set_xlabel(\"f [Hz]\")\r\n ax_filter_response.grid()\r\n if title is not None:\r\n ax_filter_response.set_title(title)\r\n fig_filter_response.tight_layout()\r\n fig_filter_response.show()\r\n\r\nif __name__ == '__main__':\r\n # print(f'The order of the line supressor filter (50Hz) is: {len(line_supressor_50_coefficients_fir)}')\r\n # plot_freq_response_dlti([line_supressor_50_coefficients_fir, 1], SAMPLING_RATE, plot_phase=False)\r\n # print(f'The order of the line supressor filter (60Hz) is: {len(line_supressor_60_coefficients_fir)}')\r\n # plot_freq_response_dlti([line_supressor_60_coefficients_fir, 1], SAMPLING_RATE, plot_phase=False)\r\n # print(f'The order of the pass band filter is: {len(pass_band_ecg_coefficients_fir)}')\r\n # plot_freq_response_dlti([pass_band_ecg_coefficients_fir, 1], SAMPLING_RATE, plot_phase=False, zoom_area=[0, 3])\\\r\n # plot_freq_response_dlti(pam_topkins_coefficients_iir, SAMPLING_RATE, input_type='sos', plot_phase=False, zoom_area=[0.5, 60])\r\n # print(len(pam_topkins_coefficients_iir))\r\n # print(pam_topkins_coefficients_iir)\r\n\r\n electrocardiogram_signal = sig.resample(electrocardiogram(), int(len(electrocardiogram()) * SAMPLING_RATE / 360))\r\n #electrocardiogram_signal_filtered = sig.sosfilt(pam_topkins_coefficients_iir, electrocardiogram_signal)\r\n electrocardiogram_signal_filtered = []\r\n # manually filter the signal using the difference equation\r\n sample_buffer = np.zeros(3)\r\n filter_buffers = [np.zeros(3) for _ in range(len(pam_topkins_coefficients_iir))]\r\n\r\n for sample in electrocardiogram_signal:\r\n sample_buffer[2] = sample_buffer[1]\r\n sample_buffer[1] = sample_buffer[0]\r\n sample_buffer[0] = sample\r\n for i, (b0, b1, b2, a_0, a1, a2) in enumerate(pam_topkins_coefficients_iir):\r\n if i == 0:\r\n filter_buffers[i][2] = filter_buffers[i][1]\r\n filter_buffers[i][1] = filter_buffers[i][0]\r\n filter_buffers[i][0] = b0 * sample_buffer[0] + b1 * sample_buffer[1] + b2 * sample_buffer[2] - a1 * filter_buffers[i][1] - a2 * filter_buffers[i][2]\r\n else:\r\n filter_buffers[i][2] = filter_buffers[i][1]\r\n filter_buffers[i][1] = filter_buffers[i][0]\r\n filter_buffers[i][0] = b0 * filter_buffers[i-1][0] + b1 * filter_buffers[i-1][1] + b2 * filter_buffers[i-1][2] - a1 * filter_buffers[i][1] - a2 * filter_buffers[i][2]\r\n electrocardiogram_signal_filtered.append(filter_buffers[-1][0])\r\n plt.plot(electrocardiogram_signal_filtered[:10*SAMPLING_RATE])\r\n plt.show()\r\n\r\n input()\r\n","repo_name":"josulas/ECG_GUI","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":6764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"71630058773","text":"### data preprocessing ###\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\n\n\ndf = pd.read_csv(\"dataset/lending_club_loan_two.csv\")\ntarget_names = [\"Charged Off\", \"Fully Paid\"]\n\ndf[\"loan_repaid\"] = df[\"loan_status\"].map({\"Fully Paid\": 1, \"Charged Off\": 0})\ndf[\"term\"] = df[\"term\"].apply(lambda term: int(term[:3]))\ndf[\"earliest_cr_line\"] = df[\"earliest_cr_line\"].apply(lambda date: int(date[-4:]))\ndf[\"home_ownership\"] = df[\"home_ownership\"].replace([\"NONE\", \"ANY\"], \"OTHER\")\ndf[\"zipcode\"] = df[\"address\"].apply(lambda adress: adress[-5:])\ndf[\"mort_acc\"] = df[\"mort_acc\"].fillna(df[\"mort_acc\"].median())\n\n# drop features\ndf = df.drop(\n [\"emp_length\", \"emp_title\", \"title\", \"loan_status\", \"grade\", \"address\", \"issue_d\"],\n axis=1,\n)\n\ndf = df.dropna()\n\n# handle categorical features\ndummies = pd.get_dummies(\n df[\n [\n \"sub_grade\",\n \"home_ownership\",\n \"verification_status\",\n \"application_type\",\n \"initial_list_status\",\n \"purpose\",\n \"zipcode\",\n ]\n ],\n drop_first=True,\n)\ndf = pd.concat(\n [\n df.drop(\n [\n \"sub_grade\",\n \"home_ownership\",\n \"verification_status\",\n \"application_type\",\n \"initial_list_status\",\n \"purpose\",\n \"zipcode\",\n ],\n axis=1,\n ),\n dummies,\n ],\n axis=1,\n)\ncols = df.columns.tolist()\ncols.remove(\"loan_repaid\")\ncols.append(\"loan_repaid\")\nX = df.drop(\"loan_repaid\", axis=1).values\ny = df[\"loan_repaid\"].values\n\ntrain_x, val_x, train_y, val_y = train_test_split(X, y, test_size=0.2, random_state=42)\n\nscaler = MinMaxScaler()\ntrain_x = scaler.fit_transform(train_x)\nval_x = scaler.transform(val_x)\n\n# ### modelling ###\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix\n\nmodel = RandomForestClassifier(n_estimators=100, random_state=42)\nmodel.fit(train_x, train_y)\npredictions = (model.predict(val_x) > 0.5).astype(\"int32\")\nprint(classification_report(val_y, predictions))\nprint(confusion_matrix(val_y, predictions))\n\n# save training dataset and prediction\nassert len(cols) == np.column_stack([train_x, train_y]).shape[1]\ntrain_df = pd.DataFrame(\n np.column_stack([train_x, train_y]),\n columns=cols,\n)\ntrain_df[\"prediction\"] = (model.predict(train_x) > 0.5).astype(\"int32\")\ntrain_df[target_names[0]] = model.predict_proba(train_x)[:, 0]\ntrain_df[target_names[1]] = model.predict_proba(train_x)[:, 1]\ntrain_df.to_csv(\"dataset/train.csv\", index=False)\n\n# save validation dataset and prediction\nassert len(cols) == np.column_stack([val_x, val_y]).shape[1]\ntest_df = pd.DataFrame(np.column_stack([val_x, val_y]), columns=cols)\ntest_df[\"prediction\"] = (model.predict(val_x) > 0.5).astype(\"int32\")\ntest_df[target_names[0]] = model.predict_proba(val_x)[:, 0]\ntest_df[target_names[1]] = model.predict_proba(val_x)[:, 1]\ntest_df.to_csv(\"dataset/test.csv\", index=False)\n","repo_name":"dudeperf3ct/evidently-ai-monitoring","sub_path":"modelling.py","file_name":"modelling.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"4135709981","text":"from ExperienceReplay import Experience, Memory\nimport tensorflow as tf\nfrom keras import models\nimport numpy as np\nfrom kaggle_environments import make\nimport gc\n\nimport Networks\nfrom Agent import Agent\nfrom board import BOARD_HEIGHT, BOARD_WIDTH, is_valid_move\n\n# networks\nprimary_net: tf.keras.Sequential = Networks.create_conv2d_model()\ntarget_net: tf.keras.Sequential = Networks.create_conv2d_model()\ntarget_net.set_weights(primary_net.get_weights())\n\ndef main():\n global primary_net, target_net\n \n print('=======================================================================')\n print(tf.config.list_physical_devices('GPU'))\n print('=======================================================================')\n \n # SAVE PARAMETERS\n SAVE_FREQ = 1000\n RENDER_FREQ = 500\n RENDER_ENV = make('connectx', debug=True)\n \n # HYPERPARAMETERS\n GAMMA = 0.99\n BATCH_SIZE = 32\n REPLAY_SIZE = 10000\n LEARNING_RATE = .0001\n OPTIMIZER = tf.optimizers.SGD(LEARNING_RATE) \n SYNC_TARGET_FRAMES = 1000\n REPLAY_START_SIZE = 1000\n EPS_DECAY = .999985\n EPS_MIN = 0.02\n \n # TOGGLES\n ENABLE_RENDER = False\n ENABLE_SAVE = False\n\n # persistent parameters\n memory = Memory(REPLAY_SIZE)\n agent = Agent(memory)\n total_rewards = []\n epsilon = 1\n frames = 0\n best_mean_reward = None\n \n output = ''\n \n while True:\n frames += 1\n epsilon = max(epsilon*EPS_DECAY, EPS_MIN)\n reward = agent.step_forward(primary_net, epsilon)\n \n if frames % SAVE_FREQ == 0 and ENABLE_SAVE:\n with open(f'./stats/stats-{frames}.csv', 'w') as FILE:\n FILE.write(output)\n output = ''\n models.save_model(primary_net, f'./models/dqn-{len(total_rewards)}-{frames}.h5')\n \n \n if frames % RENDER_FREQ == 0 and ENABLE_RENDER:\n # render game from model\n for cur_agent in ['random', 'negamax']:\n RENDER_ENV.reset()\n RENDER_ENV.run([functional_agent, cur_agent])\n game_render = RENDER_ENV.render(mode='html')\n with open(f'./models/render-{cur_agent}-{len(total_rewards)}-{frames}.html', 'w') as FILE:\n FILE.write(game_render)\n \n if reward is not None:\n total_rewards.append(reward)\n mean_reward = np.mean(total_rewards[-100:])\n print(f'{frames}: {len(total_rewards)} games, mean reward {mean_reward}, epsilon {epsilon}')\n output += f'{frames},{len(total_rewards)},{mean_reward},{epsilon}\\n'\n \n # save model when best reward is improved\n if best_mean_reward is None or best_mean_reward < mean_reward:\n models.save_model(primary_net, f'./models/dqn-{len(total_rewards)}-{frames}-best.h5')\n best_mean_reward = mean_reward\n if best_mean_reward is not None:\n print(f\"Best mean reward updated: {best_mean_reward}\")\n \n # render game from model\n for cur_agent in ['random', 'negamax']:\n RENDER_ENV.reset()\n RENDER_ENV.run([functional_agent, cur_agent])\n game_render = RENDER_ENV.render(mode='html')\n with open(f'./models/render-{cur_agent}-{len(total_rewards)}-best.html', 'w') as FILE:\n FILE.write(game_render)\n \n \n # # wait for memory to fill up before learning\n if len(memory) < REPLAY_START_SIZE:\n continue\n \n # get batch of data from memory (experience replay)\n batch = agent.memory.sample(BATCH_SIZE)\n states, actions, rewards, dones, next_states = batch\n\n for state, action, reward, done, next_state in zip(states, actions, rewards, dones, next_states):\n with tf.GradientTape() as tape:\n if not done:\n reward = 0\n # get best predicted action from target network\n next_state = np.array(next_state).reshape((-1, BOARD_HEIGHT, BOARD_WIDTH))\n target_pred = target_net(next_state).numpy().tolist()[0]\n action_prime = target_pred.index(max(target_pred))\n \n # calculate q*\n primary_future_pred = tf.gather(primary_net(next_state), tf.convert_to_tensor(action_prime), axis=1)\n q_star = tf.math.add(tf.scalar_mul(GAMMA, primary_future_pred), reward)\n\n # calulate q(s,a)\n state = np.array(state).reshape((-1, BOARD_HEIGHT, BOARD_WIDTH))\n q_theta = tf.gather(primary_net(state), tf.convert_to_tensor(action), axis=1)\n\n # calculate loss \n loss = tf.square(tf.subtract(q_star, q_theta))\n # use loss to adjust gradients\n gradients = tape.gradient(loss, primary_net.trainable_variables)\n OPTIMIZER.apply_gradients(zip(gradients, primary_net.trainable_variables))\n \n garbage_collection()\n \n if frames % SYNC_TARGET_FRAMES == 0:\n target_net.set_weights(primary_net.get_weights())\n\n# functional agent for rendering games without epsilon decay\ndef functional_agent(observation, config):\n global primary_net, target_net\n \n flat_board = observation['board']\n # shape board for model input\n board = np.array(flat_board).reshape((1, BOARD_HEIGHT, BOARD_WIDTH))\n # make move based on board\n preds = primary_net(board)\n pred_list = list(preds[0].numpy())\n # create list of weighted moves and sort based on weight\n weighted_actions = [(weight, i) for i, weight in enumerate(pred_list)]\n weighted_actions.sort(key=lambda x: x[0], reverse=True)\n # find first valid move\n for _, action in weighted_actions:\n if is_valid_move(flat_board, action):\n return action\n return -1\n\ndef garbage_collection():\n gc.collect()\n tf.keras.backend.clear_session()\n \nif __name__ == '__main__':\n main()","repo_name":"jwhitlow45/qlearningconnectfour","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17282538913","text":"\n\"\"\"\nimportant sample method\n\n求 y = x^2 在[-10, 10]上的积分\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN = 1000\nres = 666.6666666667\n\n\ndef uniform_sample():\n x = np.random.uniform(-10, 10, N)\n y = x**2\n\n pi = 1 / 20\n\n inte = y.sum() / pi / N\n return np.abs(inte - res)\n\n\ndef important_sample():\n x_tmp = np.random.uniform(0, 1, N)\n p1 = np.ones_like(x_tmp)\n p1[x_tmp < 0.5] = -1\n x = np.sqrt(200 * np.abs(x_tmp - 0.5)) * p1\n\n y = x**2\n p = np.abs(x / 100)\n inte = np.sum(y / p) / N\n return np.abs(inte - res)\n\n\nn = 1000\nr1 = []\nr2 = []\nfor i in range(n):\n r1.append(uniform_sample())\n r2.append(important_sample())\n\nprint(np.sum(r1) / n)\nprint(np.sum(r2) / n)\n","repo_name":"TING2938/locker","sub_path":"python/import_sample/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28906900404","text":"'''\n给定一个字符串,找出不含有重复字符的最长子串的长度。\n\n输入: \"pwwkew\"\n输出: 3\n解释: 无重复字符的最长子串是 \"wke\",其长度为 3。\n 请注意,答案必须是一个子串,\"pwke\" 是一个子序列 而不是子串。\n\n'''\n\n# def check(string):\n# if len(string) != len(set(string)):\n# return False\n# return True\n\n# def get_son_string(stiring, son_len, lenth):\n# count = lenth - son_len + 1\n# start_index = 0\n# end_index = start_index + son_len\n# for i in range(count):\n# line = stiring[start_index:end_index]\n# if check(line):\n# return True\n# else:\n#\n# start_index += 1\n# end_index += 1\n#\n#\n# if end_index > lenth:\n# return False\n#\n#\n# class Solution:\n# def lengthOfLongestSubstring(self, s):\n# lenth = len(s)\n# son_len = lenth\n#\n#\n# while True:\n#\n# if get_son_string(s, son_len, lenth):\n# return son_len\n# else:\n# son_len -= 1\n# if son_len == 0:\n# return None\n\n# def get_son_string(line, start, count, lenth):\n# while True:\n#\n# if check(line[start:start+count]):\n# count += 1\n# if start + count > lenth:\n# return count\n# else:\n# return count\n\n# def check(string):\n# if len(string) != len(set(string)):\n# return False\n# return True\n#\n# def get_son_string(line, start, count, lenth):\n# temp = set()\n# while True:\n# temp = set(line[start:start+count])\n# if len(temp) == count:\n# count += 1\n# else:\n# return count\n#\n# class Solution:\n# def lengthOfLongestSubstring(self, s):\n# if not s:\n# return 0\n# lenth = len(s)\n# if lenth == 1:\n# return 1\n# max_num = 1\n# start = 0\n# while True:\n# max_num = get_son_string(s, start, max_num, lenth)\n#\n# if start + max_num >= lenth:\n# return max_num -1\n# start += 1\n\nclass Solution:\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n\n left = 0\n longest = 0\n last = dict()\n\n for i, char in enumerate(s):\n if (char in last) and (last[char] >= left):\n if i - left > longest:\n longest = i - left\n left = last[char] + 1\n last[char] = i\n\n if len(s) - left > longest:\n longest = len(s) - left\n\n return longest\n\na = Solution()\nprint(a.lengthOfLongestSubstring(\"abba\"))","repo_name":"longhao54/leetcode","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43677642049","text":"from setuptools import setup, Extension\nfrom platform import system\nfrom numpy import get_include\nfrom glob import glob\nimport os\nimport shutil as sh\nfrom subprocess import call\n\n\n'''\nDefine macros\n'''\n# Pass EMBEDDED flag to cmake to generate glob_opts.h file\ncmake_args = []\nembedded_flag = EMBEDDED_FLAG\ncmake_args += ['-DEMBEDDED:INT=%i' % embedded_flag]\n\n# Pass Python flag to compile interface\ndefine_macros = []\ndefine_macros += [('PYTHON', None)]\n\n# Generate glob_opts.h file by running cmake\ncurrent_dir = os.getcwd()\nos.chdir('..')\nif os.path.exists('build'):\n sh.rmtree('build')\nos.makedirs('build')\nos.chdir('build')\ncall(['cmake'] + cmake_args + ['..'], stdout=open(os.devnull, 'wb'))\nos.chdir(current_dir)\n\n'''\nDefine compiler flags\n'''\nif system() != 'Windows':\n compile_args = [\"-O3\"]\nelse:\n compile_args = []\n\n# Add additional libraries\nlibraries = []\nif system() == 'Linux':\n libraries = ['rt']\n\n'''\nInclude directory\n'''\ninclude_dirs = [get_include(), # Numpy includes\n os.path.join('..', 'include')] # OSQP includes\n\n'''\nSource files\n'''\nsources_files = ['PYTHON_EXT_NAMEmodule.c'] # Python wrapper\nsources_files += glob(os.path.join('osqp', '*.c')) # OSQP files\n\n\nPYTHON_EXT_NAME = Extension('PYTHON_EXT_NAME',\n define_macros=define_macros,\n libraries=libraries,\n include_dirs=include_dirs,\n sources=sources_files,\n extra_compile_args=compile_args)\n\n\nsetup(name='PYTHON_EXT_NAME',\n version='0.3.0',\n author='Bartolomeo Stellato, Goran Banjac',\n author_email='bartolomeo.stellato@gmail.com',\n description='This is the Python module for embedded OSQP: ' +\n 'Operator Splitting solver for Quadratic Programs.',\n install_requires=[\"numpy >= 1.7\", \"future\"],\n license='Apache 2.0',\n ext_modules=[PYTHON_EXT_NAME])\n","repo_name":"only-cr/uploading","sub_path":"WPy-3670/python-3.6.7.amd64/Lib/site-packages/osqp/codegen/files_to_generate/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1153933678","text":"import torch\nimport numpy as np\nimport argparse\nfrom config import config\nimport pickle\nfrom models.CVAE.vae_framework import VAE_Framework\nimport os\nimport json\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# 加载模型\nlog_path = config.log_dir.format(config.id)\nmodel = VAE_Framework(config).to(device)\ntest_step = config.step\nckpts_path = log_path + '/model/model_' + str(test_step) + '.pt'\nmodel.load_state_dict(torch.load(ckpts_path))\nmodel.eval()\n\n# 加载mu_k tensor\n# tensor_path = log_path + '/tensor/tensor_' + str(0) + '.pt'\n# mu_k = torch.load(tensor_path)\n# sigma_k = 2\n\nwith open(config.vocab, 'rb') as f:\n vocab = pickle.load(f)\n\ndef shift_latent_vec(num_samples, latent_dim, length, w):\n latent_vec = []\n for i in range(10,20):\n l_v = torch.randn(2, latent_dim).to(device)\n l_vec = l_v + (torch.tensor(dic_m[i]) - l_v @ w) @ w.t()\n latent_vec.append(l_vec)\n latent_vec = torch.cat(latent_vec,0)\n return latent_vec\n\ndef predict():\n word_map = json.load(open(os.path.join(config.data_folder, 'WORD_MAP.json')))\n itow = word_map['itow']\n file_name = 'COCO_train2014_000000511036' + '.npy'\n img_dir_coco = os.path.join(config.resnet_feat_dir, 'coco')\n img_path = os.path.join(img_dir_coco, file_name)\n\n print(img_path)\n img_vec = torch.Tensor(np.load(img_path)).to(device) # 根据数据集中给出的路径直接加载图像特征作为输入\n cate = [53, 53, 53, 56, 57, 57, 57, 57, 57, 57, 57]\n cate_len = len(cate) # 一个样本中的对象类别总数\n img_cate = torch.zeros(90)\n\n for k in cate:\n img_cate[k - 1] += 1\n img_cate /= cate_len\n\n img_cate = img_cate.to(device)\n img_cate_temp = img_cate.unsqueeze(0).to(device) # 90->(1,90)\n # img_cate = torch.sum(img_cate, dim=0) # (1,90) ->90\n # print(img_cate.shape)\n img_cate = img_cate.unsqueeze(1).expand([90, 150]) # 90->(90,150)\n\n latent_vec = shift_latent_vec(num_samples, config.latent_dim, config.test_length, w.cuda())\n #seq = model.generate_mutisamples(img_vec, latent_vec, num_samples)\n\n # mu = (img_cate * mu_k).to(device)\n # sigma2 = ((img_cate ** 2) * (sigma_k ** 2)).to(device)\n # mu = torch.sum(mu, dim=0, keepdim=True)\n # sigma2 = torch.sum(sigma2, dim=0, keepdim=True) # 加权求和 (1,150)\n #\n # # mu = mu.expand([num_samples, 150])\n # # sigma2 = sigma2.expand([num_samples, 150])\n #\n # latent_vec = torch.randn(mu.size()).to(device) # 隐变量随机采样\n # latent_vec *= torch.sqrt(sigma2) # scaled\n # latent_vec += mu # shifted\n\n # latent_vec = torch.randn(config.latent_dim).to(device)\n print(img_cate_temp.shape)\n\n seq = model.generate_onesample(img_vec, img_cate_temp, latent_vec)\n # seq0, seq = model.p_decoder.beam_search(img_vec, latent_vec)\n print(' '.join(list(map(lambda index: itow[str(index)], seq[1:-1]))) + '.')\n\n\ndef predict2():\n #word_map = json.load(open(os.path.join(config.data_folder, 'WORD_MAP.json')))\n #itow = word_map['itow']\n file_name = 'COCO_train2014_000000' + str(config.img) + '.npy'\n img_dir_coco = os.path.join(config.resnet_feat_dir, 'coco')\n img_path = os.path.join(img_dir_coco, file_name)\n\n print(img_path)\n num_samples = 20\n img_vec = torch.Tensor(np.load(img_path)).to(device) # 根据数据集中给出的路径直接加载图像特征作为输入\n print(img_vec.shape)\n img_vec = img_vec.unsqueeze(0).expand([num_samples, img_vec.size(0)])\n print(img_vec.shape)\n\n # cate = [72, 82]\n # cate_len = len(cate) # 一个样本中的对象类别总数\n # img_cate = torch.zeros(90)\n\n # for k in cate:\n # img_cate[k - 1] += 1\n # img_cate /= cate_len\n\n # img_cate = img_cate.to(device)\n # img_cate_temp = img_cate.to(device)\n # # img_cate = torch.sum(img_cate, dim=0) # (1,90) ->90\n # print(img_cate.shape)\n # img_cate = img_cate.unsqueeze(1).expand([90, 150]) # 90->(90,150)\n # print(img_cate.shape)\n\n latent_vec = shift_latent_vec(num_samples, config.latent_dim, config.test_length, w.cuda())\n\n # mu = (img_cate * mu_k).to(device)\n # sigma2 = ((img_cate ** 2) * (sigma_k ** 2)).to(device)\n # mu = torch.sum(mu, dim=0, keepdim=True)\n # sigma2 = torch.sum(sigma2, dim=0, keepdim=True) # 加权求和 (1,150)\n #\n # mu = mu.expand([num_samples, 150])\n # sigma2 = sigma2.expand([num_samples, 150])\n #\n # latent_vec = torch.randn(mu.size()).to(device) # 隐变量随机采样\n # latent_vec *= torch.sqrt(sigma2) # scaled\n # latent_vec += mu # shifted\n\n # latent_vec = torch.randn(config.latent_dim).to(device)\n # img_cate_temp = img_cate_temp.unsqueeze(0).expand([num_samples, img_cate_temp.size(0)]) # ([10, 90])\n # print(img_cate_temp.shape)\n\n seq = model.generate_mutisamples(img_vec, latent_vec, num_samples)\n # seq0, seq = model.p_decoder.beam_search(img_vec, latent_vec)\n # seq = model.predict_beam_search(img_feat, word_map, beam_size=params['beam_size'], max_len=params['max_len'])\n # print(' '.join(list(map(lambda index: itow[str(index)], seq[1:-1]))) + '.')\n for s in seq:\n print(vocab.idList_to_sent(s))\n\nwith torch.no_grad():\n latent_vecs = torch.load('./latent_vec.pt', map_location='cpu')\n lengths = torch.load('./length.pt', map_location='cpu')\n w = torch.load('./weight.pt', map_location='cpu')\n\n latent_vecs_dim = latent_vecs.size(-1)\n v = (latent_vecs.view(-1, latent_vecs_dim))\n l = np.array(lengths.flatten())\n w = w/torch.norm(w)\n w = w.t()\n\n p = np.array(v @ w)\n\n u = set(l)\n\n dic_m = {}\n for i in u:\n dic_m[i] = p[l==i].mean()\n\nprint(\"predict some\")\npredict2()\n\nprint(\"one\")\n#predict()\n","repo_name":"Y-Sisyphus/CVAE_Caption","sub_path":"pre.py","file_name":"pre.py","file_ext":"py","file_size_in_byte":5709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1234536845","text":"import csv\nimport random\nimport re\nimport argparse\nimport sys\nimport datetime\n\ndesc_chars = 'abcd efg hijk lmn opq rstu vw x yzA BCD EFGH IJKL MNOP QRS TUVW XYZ'\n# https://unsplash.com/s/photos/green-bean\n\ndef generate_timestamp():\n start_date = datetime.date(2000, 1, 1)\n end_date = datetime.date(2021, 11, 3)\n num_days = random.randrange((end_date - start_date).days)\n rand_date = start_date + datetime.timedelta(num_days)\n\n hour = random.randrange(24)\n minute = random.randrange(60)\n second = random.randrange(60)\n return f'{rand_date.year}-{rand_date.month:02d}-{rand_date.day:02d} {hour:02d}:{minute:02d}:{second:02d}'\n\nif __name__=='__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('out_file', help='filepath of csv data output')\n parser.add_argument('--num_lines', help='number of output data lines', type=int, default=1000)\n parser.add_argument('--starter_data', help='filepath of csv containing manually generated product data')\n parser.add_argument('--seed', help='the random seed to use', type=int)\n args = parser.parse_args()\n\n if (args.seed != None):\n random.seed(args.seed)\n\n output_file = open(args.out_file, 'w')\n\n if (args.starter_data != None):\n with open(args.starter_data, 'r') as manual_file:\n for line in manual_file.readlines():\n output_file.write(line)\n \n output_writer = csv.writer(output_file,sys.stdout, lineterminator='\\n')\n for i in range(args.num_lines):\n rating = random.randrange(1, 6)\n description = ''.join(desc_chars[random.randrange(0,len(desc_chars))] for i in range(random.randrange(0, 255)))\n description = description.strip()\n _RE_COMBINE_WHITESPACE = re.compile(r\"\\s+\")\n description = _RE_COMBINE_WHITESPACE.sub(\" \", description)\n timestamp = generate_timestamp()\n\n output_writer.writerow([rating, description,timestamp])\n output_file.close()\n","repo_name":"SW386/bean-barn","sub_path":"backend/db/scripts/generate_reviews.py","file_name":"generate_reviews.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38167911348","text":"import click\n\nfrom osint_tool.data_fetching.google import Google\nfrom osint_tool.data_fetching.linkedin import Linkedin\nfrom osint_tool.data_fetching.netcraft import Netcraft\nfrom osint_tool.data_fetching.shodan import Shodan\nfrom osint_tool.data_fetching.twitter import Twitter\nfrom osint_tool.data_fetching.whatsmyip import Whatsmyip\n\n\n@click.command()\n@click.argument('email')\ndef pwn_check(email):\n click.echo('Looking for data leaks...')\n pwnage_info = Whatsmyip(email).check_if_pwned()\n click.echo(pwnage_info)\n\n\n@click.command()\n@click.argument('url')\ndef site_report(url):\n click.echo('Checking page info...')\n netcraft = Netcraft(url)\n netcraft.get_site_report()\n Shodan().get_shodan_report(url, netcraft.get_ip_address())\n\n\n@click.command()\n@click.argument('person')\ndef person_report(person):\n click.echo('Performing Linkedin lookup...')\n Linkedin().get_person_report(person)\n click.echo('\\n\\nPerforming Twitter lookup...')\n Twitter().get_person_report(person)\n click.echo('Attempting to obtain e-mail addresses...')\n Google().get_person_emails(person)\n\n\n@click.command()\n@click.argument('mail_domain')\ndef gather_emails(mail_domain):\n click.echo(f'Gathering emails from @{mail_domain}...')\n click.echo(Google().get_emails(mail_domain))\n\n\n@click.command()\n@click.argument('prefix')\ndef gather_numbers(prefix):\n click.echo(f'Gathering phone numbers with +{prefix} prefix...')\n Google().get_phone_numbers(prefix)\n","repo_name":"rdebek/osint-tool","sub_path":"osint_tool/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"73437692693","text":"import time\nimport random\nimport bibliopixel\nfrom bibliopixel.drivers.serial_driver import *\nfrom bibliopixel.led import *\nimport pyaudio\nimport wave\nimport numpy as np\nfrom struct import unpack\nfrom math import *\n\nbibliopixel.log.setLogLevel(bibliopixel.log.DEBUG)\ndriver1 = DriverSerial(num = 600, type = LEDTYPE.WS2811, deviceID = 2)\ndriver2 = DriverSerial(num = 650, type = LEDTYPE.WS2811, deviceID = 1)\nled1 = LEDMatrix(driver1, width=50, height=12, coordMap = None, rotation=MatrixRotation.ROTATE_180, masterBrightness=100, pixelSize=(1,1))\nled2 = LEDMatrix(driver2, width=50, height=13, coordMap = None, rotation=MatrixRotation.ROTATE_180, masterBrightness=100, pixelSize=(1,1))\n\nclass audio(object):\n chunk = 4096\n s = pyaudio.PyAudio()\n sound = s.open(format = pyaudio.paInt16, channels = 2, rate = 44100, input = True, frames_per_buffer = chunk, input_device_index=2)\n \n def audioinfo(self):\n data = self.sound.read(self.chunk)\n data = unpack(\"%dh\"%(len(data)/2),data)\n data = np.array(data,dtype='h')\n data = abs(np.fft.rfft(data))\n data = data/100000\n return data\n\nclass output(object):\n def calculations(self, data, xax):\n try:\n t = int(log(data, 1.35) * log10(xax+10))\n return t\n except ValueError:\n t = 0\n return t\n\n def average(self, yax, dat):\n avg = 0\n for yax in range(yax, yax+4):\n avg = avg + dat[yax]\n return avg/4\n\n def lights(self, data):\n y = 0\n for z in range(0,50):\n\n t = self.calculations(self.average(y, data), z)\n \n if t>23:\n led1.fillRect(z,0,1,t,color=(255,0,0))\n led2.fillRect(z,0,1,t-11,color=(255,0,0))\n elif t>21:\n led1.fillRect(z,0,1,t,color=(255,255,0))\n led2.fillRect(z,0,1,t-11,color=(255,255,0))\n elif t>15:\n led1.fillRect(z,0,1,t,color=(0,255,0))\n led2.fillRect(z,0,1,t-11,color=(0,255,0))\n elif t>12:\n led1.fillRect(z,0,1,t,color=(0,0,255))\n led2.fillRect(z,0,1,t-11,color=(0,0,255))\n else:\n led1.fillRect(z,0,1,t,color=(0,0,255))\n led2.fillRect(z,0,1,t-11,color=(0,0,0))\n\n y = y + 4\n\n led1.update()\n led2.update()\n led1.all_off()\n led2.all_off()\n\nclass main(object):\n def startlights(self):\n audiooutput = audio()\n printoutput = output()\n while True:\n printoutput.lights(audiooutput.audioinfo())\n\n def config(self):\n raw_input(\"\"\"\n _____ _____ __ __ __ _____\n| _ | | ___| | \\| | | | | ___|\n| |_| | | |___ | | | | | | |___\n| ___| | ___| | |\\ | | | |___ |\n| | | |___ | | | | | | ___| |\n|_| |_____| |__| |__| |__| |_____|\n\"\"\")\n print(\"starting server\")\n self.startlights()\n\nrun = main()\nrun.config()\n","repo_name":"jimmyshi360/SpectrumAnalyzerGUI","sub_path":"CODE/modscale.py","file_name":"modscale.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41994780601","text":"def additional(seq, count):\n element = '-' + str(count) + 'a'\n index = len(seq) // 2\n seq.insert(index, element)\n seq.insert(index, element)\n print('Invalid input! Adding additional elements to the board')\n return seq\n\n\ndef play(seq, index1, index2):\n if seq[index1] == seq[index2]:\n element = seq[index1]\n seq.remove(element)\n seq.remove(element)\n print(f'Congrats! You have found matching elements - {element}!')\n else:\n print('Try again!')\n return seq\n\n\nsequence = input().split(' ')\nvalid = True\ncounter = 0\nwhile True:\n command = input()\n if command == 'end':\n break\n else:\n command = list(map(int, command.split(' ')))\n counter += 1\n if command[0] == command[1]:\n valid = False\n elif command[0] < 0 or command[0] >= len(sequence):\n valid = False\n elif command[1] < 0 or command[1] >= len(sequence):\n valid = False\n else:\n valid = True\n if not valid:\n sequence = additional(sequence, counter)\n else:\n sequence = play(sequence, command[0], command[1])\n if len(sequence) == 0:\n break\n\nif len(sequence) == 0:\n print(f'You have won in {counter} turns!')\nelse:\n current_sequence = ' '.join(sequence)\n print(f\"Sorry you lose :(\\n{current_sequence}\")\n","repo_name":"kzhelyazkov81/exam_20.08.2020","sub_path":"3_memory_game.py","file_name":"3_memory_game.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43549444654","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 19 16:38:42 2021\n\n@author: Hriday Singh, Iain Muir, and Connor Smith\n\"\"\"\n\nfrom constants import LOCAL_ROOT\n\nimport matplotlib.pyplot as plt\nfrom scipy.stats import expon\nimport pandas as pd\nimport numpy as np\nimport scipy\n\ndata = pd.read_csv(\n LOCAL_ROOT + \"Homework/HW 2/SB_box_scores_2019_without_rank.csv\"\n)\n\nteams = np.unique(pd.concat(\n [data[\"Winner\"], data[\"Loser\"]]\n))\nteams = pd.Series(\n teams\n).reset_index()\nteams[\"team_id\"] = teams[\"index\"]\n\ndata2 = data.merge(\n teams,\n left_on=\"Winner\",\n right_on=0\n)\ndata2 = data2.merge(\n teams,\n left_on=\"Loser\",\n right_on=0\n)\ndata2[\"winner_id\"] = data2[\"team_id_x\"].astype(int)\ndata2[\"loser_id\"] = data2[\"team_id_y\"].astype(int)\ndata2[\"diff\"] = data2.Pts_winner-data2.Pts_loser\n\n# Matrix of point differentials with winning team as columns and losing team as rows\npoints_matrix = np.zeros((len(teams), len(teams)))\npoints_list = []\n\nfor row in data2[[\"team_id_x\", \"team_id_y\", \"diff\"]].values:\n x, y, diff = row\n points_matrix[x, y] += min(diff + 75, 100)\n points_matrix[y, x] -= max(25 - diff, 1)\n points_list.append(diff)\n\n# Matrix of point differentials as a percentage of total point differential\npoints_matrix_props = points_matrix/points_matrix.sum(axis=0)\npoints_matrix_props[points_matrix_props == -0.] = 0\nprint(points_matrix_props)\n\ninitial_steady = np.ones(len(teams))*(1/217)\ninitial_steady = initial_steady.reshape(1, 217)\n\ncurrent = np.zeros(217).reshape(1, 217)\nepsilon = 0.05\nfor i in range(100):\n if sum(sum(initial_steady-current)) < epsilon:\n break\n else:\n current = initial_steady\n initial_steady = initial_steady.dot(points_matrix_props)\n\nranking = pd.DataFrame(np.flip(np.argsort(initial_steady[0])))\nranking.columns = [\"team_id\"]\nteam_rankings = ranking.merge(teams, left_on=\"team_id\", right_on=\"index\").loc[:, 0]\nprint(team_rankings)\n\n_, bins, _ = plt.hist(points_list, 20, density=1, alpha=0.5)\nloc, scale = expon.fit(points_list)\nbest_fit_line = scipy.stats.expon.pdf(bins, loc, scale)\nplt.plot(bins, best_fit_line)\nplt.show()\n","repo_name":"iainmuir6/Advanced-Sports-Analytics","sub_path":"Homework/HW2_Markov-Chains.py","file_name":"HW2_Markov-Chains.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"21242861683","text":"# this function uses the merger module\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nimport merger\n\nboilerFile = os.path.join('data', 'raw', 'condensingBoiler.2021-07.csv')\nweatherFile = os.path.join('data', 'raw', 'produkt_zehn_min_tu_20200209_20210811_04745.txt')\nhr = 20\n\nmerged = merger.mergeWeather(boilerFile, weatherFile)\nminTemp = 21 # minimum temperature - 10 should give everything, 20-25 should give all else\n\n# BW_VL_WW is condensing boiler feed pipe to warm water storage\nbw_vl_ww = merged.loc[merged['MeasurementId'] == 7].reset_index(drop=True)\n\nx = bw_vl_ww['TT_10'].loc[(bw_vl_ww['Timestamp'].dt.hour == hr) & (bw_vl_ww['Value'] > minTemp)]\ny = bw_vl_ww['Value'].loc[(bw_vl_ww['Timestamp'].dt.hour == hr) & (bw_vl_ww['Value'] > minTemp)]\n\nax = sns.regplot(x=x, y=y, scatter_kws={\"s\": 10})\n\nax.set(xlabel = 'Outside temperature', ylabel = 'System component temperature')\n\nplt.title(\"Condensing boiler feed to warm water storage, hour \" + str(hr))\nplt.show()","repo_name":"hattamisra/SigmaHeat-data-analysis","sub_path":"scatterplots/condensingBoilerFeed.py","file_name":"condensingBoilerFeed.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"19611414477","text":"import itertools\n\nimport utils\n\nlines = \"\"\"London to Dublin = 464\nLondon to Belfast = 518\nDublin to Belfast = 141\"\"\".splitlines()\n\nlines = utils.get_lines(__file__)\n\npairs = [l.split(\" = \") for l in lines]\npairs = [tuple([sorted(c.split(\" to \")), d]) for c, d in pairs]\n\nall_cities = [cities[0] for cities, distance in pairs]\nall_cities += [cities[1] for cities, distance in pairs]\nall_cities = set(all_cities)\n\npermutations = itertools.permutations(all_cities, len(all_cities))\n\ndistances = list()\nfor p in permutations:\n current = 0\n for i in range(len(p) - 1):\n pair = sorted(p[i : i + 2])\n for e in pairs:\n if pair == e[0]:\n distance = e[1]\n break\n current += int(distance)\n distances.append(current)\n\nprint(min(distances), max(distances))\n","repo_name":"medecau/aoc","sub_path":"2015/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"42906058517","text":"#importing relevant libraries\nfrom __future__ import annotations\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.datasets as datasets\nfrom torch.utils.data import DataLoader, TensorDataset, Subset\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport os\nimport sys\n\nsys.path.insert(0, \"..\")\n\nfrom CNN_small_architecture import CNNSmall\nfrom CNN_layers import conv_homemade\nfrom CNN_layers import maxpool_homemade\nfrom CNN_layers import batchnorm_homemade\nfrom CNN_layers import linear_layer_homemade\n\ndef tokenize(num):\n if num == 1:\n return torch.tensor(np.array([1., 0.]))\n else:\n return torch.tensor(np.array([0., 1.]))\n\n# takes a 4-dimensional tensor from the dataloader (batch_size x channel_size x height x width)\n# and turns it into a list of lists of (height x width) numpy arrays\ndef transform_input(input_batch):\n return list(input_batch.detach().numpy())\n\ndef compare(x: list[float], y: list[float]):\n \"\"\"\n compares two lists of batches with same amount of channels and returns the greatest error, the \n mean error and the variance of the error when comparing x to y. Where y is the target and x is\n the predicted value.\n\n Args:\n x (list[float]): One part of the values that must be compared \n y (list[float]): One part of the values that must be compared\n Returns:\n tuple(float,float,float): The maximum error, the mean of the mean error for each channel and\n the mean variance of the error\n \"\"\"\n\n batch_size = len(x)\n\n global_max_error = 0\n global_mean = []\n global_var = []\n global_mean_x = []\n global_rrmse = []\n\n for b in range(batch_size):\n local_max = np.amax(np.absolute(x[b] - y[b]))\n local_mean = np.mean(np.absolute(x[b] - y[b]))\n local_var = np.var(np.absolute(x[b] - y[b])) \n local_mean_x = np.mean(np.absolute(x[b]))\n global_mean_x.append(local_mean_x)\n global_mean.append(local_mean)\n global_var.append(local_var)\n global_rrmse.append(np.sqrt(np.mean(np.square(y[b]- x[b]))/np.sum(np.square(y[b]))))\n \n if local_max > global_max_error:\n global_max_error = local_max\n \n return global_max_error, np.mean(global_mean), np.mean(global_var), np.mean(global_mean_x), np.mean(global_rrmse)\n\ndef create_conv_homemade(model_conv):\n weights = model_conv.weight\n biases = model_conv.bias.detach().numpy()\n\n out_c, in_c, r, c = weights.shape\n conv1_filters = []\n\n for f in range(out_c):\n filter_ = []\n kernels = []\n\n for kernel in list(weights[f,:,:,:]):\n kernels.append(kernel.detach().numpy())\n\n filter_.append(kernels)\n filter_.append(biases[f])\n conv1_filters.append(filter_)\n \n return conv_homemade.Conv(filters=conv1_filters, in_channels=in_c)\n\ndef create_batchnorm_homemade(model_batchnorm):\n weights = model_batchnorm.weight\n biases = model_batchnorm.bias\n running_mean = model_batchnorm.running_mean\n running_var = model_batchnorm.running_var\n\n return batchnorm_homemade.BatchNorm(weights=weights, biases=biases, running_mean = running_mean, running_var = running_var)\n\ndef create_maxpool_homemade(model_maxpool):\n kernel_size = model_maxpool.kernel_size\n stride = model_maxpool.stride\n if type(model_maxpool.padding) == int:\n padding = (model_maxpool.padding, model_maxpool.padding)\n else:\n padding = model_maxpool.padding\n \n return maxpool_homemade.MaxPool(kernel_size=kernel_size, stride=stride, padding=padding)\n","repo_name":"EmilStevnsborg/bachelorprojekt","sub_path":"Python/Tests/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"12919313042","text":"import re\n\n\ndef convert(input_file_path: str, output_fil_path: str) -> None:\n # rmd=Read_MOCK_DATA // wmd=Write_MOCK_DATA\n re_str = r'(\\d+),(\\w+\\W*\\w+),(\\w+\\W?\\s?\\w+\\s?\\w+\\W*\\w*\\W*?),(\\w+)(\\@\\w*\\W?\\w+\\.?\\w+\\.?\\w+),(\\w+),(.*)'\n re_str_mod = r'\\1,\\3,\\2,\\4@ing.unlpam.edu.ar,\\7'\n with open(input_file_path, 'r', encoding=\"UTF-8\") as rmd:\n with open(output_fil_path, 'w', encoding=\"UTF-8\") as wmd:\n for line in rmd:\n line = re.sub(re_str, re_str_mod, line)\n wmd.write(line)\n\n\nif __name__ == '__main__':\n Input = r\"C:\\Users\\sebam\\Documents\\Programacion\\AyL_UNLPam\\TP_1\\MOCK_DATA.csv\"\n Output = r\"C:\\Users\\sebam\\Documents\\Programacion\\AyL_UNLPam\\TP_1\\MOCK_DATA_MOD.csv\"\n convert(Input, Output)\n","repo_name":"SebaMediza/AyL_UNLPam","sub_path":"TP_1/EL_7.py","file_name":"EL_7.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"42137988129","text":"# Question: Contains Duplicate\n# Source: https://leetcode.com/problems/contains-duplicate/\n\ndef containsDuplicate(nums=[]) -> bool:\n hashMap={}\n n=len(nums)\n for i in range(0,n): # O(n)\n if nums[i] in hashMap:\n return True\n else:\n hashMap[nums[i]]=1\n return False\n","repo_name":"jasn-armstrng/ds-algo-practice","sub_path":"3-contains-duplicate-arrays/containsDuplicate.py","file_name":"containsDuplicate.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"43631303971","text":"T = int(input())\n\nfor test_case in range(1, T+1):\n num_arr = list(map(int, input().split()))\n\n result = 0 # 결과 값을 저장할 변수를 지정해줍니다.\n sum = 0 # 모두 더한 값을 저장할 변수를 지정해줍니다.\n\n for num in num_arr:\n sum += num # 배열에서 한 숫자씩 sum에 더해줍니다.\n result = sum/len(num_arr) # 더한 값에 배열의 길이를 나눠줍니다.\n\n print('#{} {}'.format(test_case, round(result))) # 결과 값은 반올림해주는 값이므로 round를 사용해줍니다.","repo_name":"skswlgns/Algo","sub_path":"SWEA/D1/2071_평균값 구하기.py","file_name":"2071_평균값 구하기.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"4200899443","text":"import sys\nfrom datetime import datetime\nimport json\nfrom hashlib import sha256\nfrom datetime import datetime\nimport math \n\nmerkleTransactions = [] # contains merkle hashes\nmerkleTree = [None]\nnum_txn = 0\nmagicNumber_FINAL = 3652501241\ntransactions_merkle = []\ntransaction_bytes = []\nprevious_header_hash = []\n\ntxn = []\n\nfileName = sys.argv[1]\nf = open(fileName, mode='rb')\nbytes_master = f.read()\nf.close()\n\n\n\n\ndef readFile(numBytes):\n global bytes_master\n res = bytes_master[:numBytes]\n bytes_master = bytes_master[numBytes:]\n global txn\n txn += res\n return res\n\ndef compactSize(flag):\n global transaction_bytes\n b = readFile(1) # read first byte\n dec = int.from_bytes(b, 'little')\n # print(\"DEBUG dec: \", dec,b)\n if dec >= 0 and dec < 253:\n if flag:\n transaction_bytes += bytearray(b)\n return dec\n elif dec == 253:\n b = readFile(2)\n if flag:\n transaction_bytes += bytearray(b)\n return int.from_bytes(b, 'little')\n elif dec == 254:\n b = readFile(4)\n if flag:\n transaction_bytes += bytearray(b)\n return int.from_bytes(b, 'little')\n else:\n b = readFile(8)\n if flag:\n transaction_bytes += bytearray(b)\n return int.from_bytes(b, 'little')\n\n\n\nclass Preamble:\n def __init__(self):\n self.magic_number = None\n self.size = None\n def getMagicNumber(self):\n bytes = readFile(4)\n self.magic_number = int.from_bytes(bytes, 'little')\n def getSize(self):\n bytes = readFile(4)\n self.size = int.from_bytes(bytes, 'little')\n\n \n \n\n\nclass Block:\n def __init__(self, height):\n self.height = height\n self.version = None\n self.previous_hash = None\n self.merkle_hash = None\n self.timestamp = None\n self.timestamp_readable = None\n self.nbits = None\n self.nonce = None\n\n self.txn_count = None\n self.transactions = []\n \n def getHeader(self): # order matters\n # self.header = Header()\n self.getVersion()\n self.getPrevHash()\n self.getMerkleRootHash()\n self.getTime()\n self.getTimereadable()\n self.GetnBits()\n self.getNonce()\n\n def getTransaction(self):\n tran = Transaction()\n\n tran.getVersion()\n tran.getTXInput_Count()\n tran.getTXInputs()\n tran.getTXOutput_Count()\n tran.getTXOutputs()\n tran.getLockTime()\n return tran\n\n def getTransactionCount(self):\n self.txn_count = compactSize(False)\n\n # HEADER METHODS\n def getVersion(self):\n bytes_array = bytearray(readFile(4))\n bytes_array.reverse()\n self.version = int.from_bytes(bytes(bytes_array), byteorder='big')\n\n def getPrevHash(self):\n bytes_array = bytearray(readFile(32))\n bytes_array.reverse() # reverse the endianess of these bytes\n self.previous_hash = str(bytes(bytes_array).hex())\n\n def getMerkleRootHash(self):\n bytes_array = bytearray(readFile(32))\n bytes_array.reverse()\n self.merkle_hash = str(bytes(bytes_array).hex())\n def getTime(self):\n bytes = readFile(4)\n self.timestamp = int.from_bytes(bytes, 'little', signed=False)\n def getTimereadable(self):\n self.timestamp_readable = datetime.utcfromtimestamp(self.timestamp).strftime('%Y-%m-%d %H:%M:%S')\n\n def GetnBits(self):\n bytes_array = bytearray(readFile(4))\n bytes_array.reverse()\n self.nbits = bytes(bytes_array).hex()\n def getNonce(self):\n bytes = readFile(4)\n self.nonce = int.from_bytes(bytes, 'little', signed=False)\n\n\nclass TransactionOutput:\n def __init__(self):\n self.satoshis = None\n self.output_script_size = None\n self.output_script_bytes = None\n def getValue(self):\n b = readFile(8)\n self.satoshis = int.from_bytes(b, 'little')\n\n global transaction_bytes\n transaction_bytes += bytearray(bytes(b))\n def getOutScriptBytes(self):\n self.output_script_size = compactSize(True)\n\n global transaction_bytes\n\n def getOutScript(self):\n b = readFile(self.output_script_size)\n self.output_script_bytes = b.hex()\n\n global transaction_bytes\n transaction_bytes += bytearray(b)\n\n\n \n\nclass TransactionInput:\n def __init__(self):\n self.utxo_hash = None\n self.index = None\n self.input_script_size = None\n self.input_script_bytes = None\n self.sequence = None\n def getHash(self):\n bytes_array = bytearray(readFile(32))\n\n global transaction_bytes\n transaction_bytes += bytes_array\n\n bytes_array.reverse()\n self.utxo_hash = str(bytes(bytes_array).hex())\n\n def getIndex(self):\n b = readFile(4)\n self.index = int.from_bytes(b,'little')\n\n global transaction_bytes\n transaction_bytes += bytearray(b)\n\n def getInScriptBytes(self):\n self.input_script_size = compactSize(True)\n\n\n def getSignatureScript(self):\n b = readFile(self.input_script_size)\n self.input_script_bytes = b.hex()\n\n global transaction_bytes\n transaction_bytes += bytearray(bytes(b))\n\n\n def getSequence(self):\n b = readFile(4)\n self.sequence = int.from_bytes(b, 'little')\n\n global transaction_bytes\n transaction_bytes += bytearray(bytes(b))\n\n\n\nclass Blocks:\n def __init__(self):\n self.blocks = []\n self.height = None\n\n def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__, indent=4)\n\n def getBlock(self, height):\n bl = Block(height)\n bl.getHeader()\n bl.getTransactionCount()\n for _ in range(bl.txn_count):\n bl.transactions.append(bl.getTransaction())\n \n self.blocks.append(bl)\n\n def finalizeHeight(self, h):\n self.height = h\n\n\nclass Transaction:\n def __init__(self):\n self.version = None\n self.txn_in_count = None\n self.txn_inputs = []\n self.txn_out_count = None\n self.txn_outputs = []\n self.lock_time = None\n\n def getVersion(self):\n bytes_array = bytearray(readFile(4))\n global transaction_bytes\n transaction_bytes += bytes_array\n bytes_array.reverse()\n self.version = int.from_bytes(bytes(bytes_array), 'big')\n\n def getTXInput_Count(self):\n self.txn_in_count = compactSize(True)\n\n def getTXInputs(self):\n for _ in range(self.txn_in_count):\n tr = TransactionInput()\n tr.getHash()\n tr.getIndex()\n tr.getInScriptBytes()\n tr.getSignatureScript()\n tr.getSequence()\n self.txn_inputs.append(tr)\n \n def getTXOutput_Count(self):\n self.txn_out_count = compactSize(True)\n\n def getTXOutputs(self):\n for _ in range(self.txn_out_count):\n tr = TransactionOutput()\n tr.getValue()\n tr.getOutScriptBytes()\n tr.getOutScript()\n self.txn_outputs.append(tr) \n def getLockTime(self):\n b = readFile(4)\n self.lock_time = int.from_bytes(b, 'little')\n\n global transaction_bytes\n transaction_bytes += bytearray(b)\n\n transactions_merkle.append(bytes(transaction_bytes).hex())\n transaction_bytes.clear()\n\n# -------- MERKLE TREE ---------- #\ndef computeLength(num_txn):\n return pow(2, math.ceil(math.log(num_txn)/math.log(2)));\n\ndef addHashes(nums): # hash later\n global num_txn, merkleTree\n \n num_txn = len(nums) # if odd we duplicate last, if even we add normally\n length = computeLength(num_txn) # this will determine length of our necessary merkle tree array\n if length > len(merkleTree): # extend the tree\n extraNone = [None] * (length - len(merkleTree))\n merkleTree += extraNone\n for txn in nums:\n # print(\"return\", computeHash(txn))\n # print(str(txn))\n # print(txn)\n merkleTree.append(txn)\n if num_txn % 2 != 0:\n merkleTree.append(nums[-1])\n else:\n for txn in nums:\n merkleTree.append(txn)\n\ndef computeMerkleTree():\n global merkleTree\n for i in range(math.ceil(len(merkleTree)/2)-1, 0, -1): # index of where to begin our concate hash\n # merkleTree[i] = computeHash1(str(merkleTree[2*i]) + str(merkleTree[2*i+1]))\n # print(\"here\",merkleTree[2*i])\n\n merkleTree[i] = binMerkle(merkleTree[2*i], merkleTree[2*i+1])\n # print(merkleTree)\n \n # displayMerkleTree()\n\n\ndef binMerkle(txn1, txn2):\n # txn1_data = bytes.fromhex(txn1)\n # txn1_hash_bin = sha256(sha256(txn1).digest()).digest()\n # txn1_hash_hex = sha256(sha256(txn1).digest()).hexdigest()\n\n # # print(txn1_hash_hex)\n\n # # txn2_data = bytes.fromhex(txn2)\n # txn2_hash_bin = sha256(sha256(txn2).digest()).digest()\n # txn2_hash_hex = sha256(sha256(txn2).digest()).hexdigest()\n\n # print(txn2_hash_hex)\n # print(\"txn1: \",txn1, txn2)\n # print(merkleTree)\n print(merkleTree)\n # if txn1 == None:\n # parent_hash_bin=sha256(sha256(txn2).digest()).digest()\n # if txn2 == None:\n # parent_hash_bin=sha256(sha256(txn1).digest()).digest()\n # else:\n parent_hash_bin=sha256(sha256(txn1+txn2).digest()).digest()\n\n\n # parent_hash_hex=sha256(sha256(txn1_hash_bin+txn2_hash_bin).digest()).hexdigest()\n \n return parent_hash_bin\n # return sha256(sha256(txn_string).digest()).digest()\n\n\ndef binaryHash(val):\n txn1_data = bytes.fromhex(val)\n txn1_hash_bin = sha256(sha256(txn1_data).digest()).digest()\n return txn1_hash_bin\n\n\ndef displayMerkleTree():\n print(\"merkleTree\", merkleTree)\n\ndef validateMerkleHash():\n # print(transaction_bytes)\n # print(\"last\",transactions_merkle)\n # print(\"validating merkle hash\")\n hashes = []\n # for i in range(len(block.transactions)):\n # print(int.from_bytes(block.transactions[i]))\n # print(\"transactions_merkle: \", transactions_merkle)\n for i in range(len(transactions_merkle)):\n h = binaryHash(transactions_merkle[i])\n # print('\\n')\n # print(h)\n hashes.append(h)\n # print(\"hashes: \", hashes)\n addHashes(hashes)\n computeMerkleTree()\n # print(merkleTree[1])\n return merkleTree[1]\n\n#-------- MERKLE TREE SECTION ---------------#\n\ndef finalvalidate(val):\n tmp = bytearray(val)\n tmp.reverse()\n hash = ''.join(format(x, '02x') for x in tmp)\n return hash\n\ndef computeHash1(txn_string):\n # print(txn_string)\n # txn_string = bytearray(arr).hex()\n return ''.join(format(x, '02x') for x in reversed(bytearray(sha256(sha256(bytes.fromhex(txn_string)).digest()).digest())))\n\ndef computeHash(arr):\n # print(txn_string)\n txn_string = bytearray(arr).hex()\n return ''.join(format(x, '02x') for x in reversed(bytearray(sha256(sha256(bytes.fromhex(txn_string)).digest()).digest())))\n\nfile = open(fileName + \".json\", mode='w')\nbigBlock = Blocks()\nheight = 0\np_hash = None\nwhile len(bytes_master.hex()) > 0:\n \n p = Preamble()\n p.getMagicNumber()\n p.getSize()\n \n current_header_hash = bytes_master[:80]\n bigBlock.getBlock(height)\n block = bigBlock.blocks[height]\n\n prev_block = bigBlock.blocks[height - 1]\n if p.magic_number != magicNumber_FINAL: #error 1\n print(\"error 1 block \" + str(height)) \n exit()\n if str(block.version) != \"1\": #error 2\n print(\"error 2 block \" + str(height))\n exit()\n\n c_hash = computeHash(current_header_hash)\n\n if height >= 1 and str(block.previous_hash) != str(p_hash) : # error 3\n print(\"error 3 block \" + str(height))\n exit()\n\n d1 = datetime.strptime(block.timestamp_readable, \"%Y-%m-%d %H:%M:%S%f\") # error 4\n d2 = datetime.strptime(prev_block.timestamp_readable, \"%Y-%m-%d %H:%M:%S%f\")\n if height > 0 and (d2-d1).total_seconds()/3600.0 > 2:\n print(\"error 4 block \" + str(height))\n exit()\n\n for i in range(block.txn_count): # error 5\n if block.transactions[i].version != 1:\n print(\"error 5 block \" + str(height))\n exit()\n\n merkle_hash_compute = validateMerkleHash() #error 6\n if finalvalidate(merkle_hash_compute) != block.merkle_hash.strip():\n print(\"error 6 block \" + str(height))\n exit()\n\n # transaction_bytes.clear()\n # transactions_merkle.clear()\n # merkleTree.clear()\n # merkleTree.append(None)\n\n p_hash = c_hash\n height += 1\n\n transaction_bytes.clear()\n transactions_merkle.clear()\n merkleTree.clear()\n merkleTree.append(None)\n\n # if height%1000 == 0:\n # print(height)\n\n\nbigBlock.finalizeHeight(height)\nfile.write(bigBlock.toJSON())\nfile.close()\nprint(\"no errors \" + str(height) + \" blocks\")","repo_name":"2020ayao/CS4501-Crypto","sub_path":"Homework 3/btcscript.py","file_name":"btcscript.py","file_ext":"py","file_size_in_byte":12827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"14822469209","text":"import os\nfrom flask import (\n Flask\n)\nfrom bioblend.galaxy.objects import GalaxyInstance\nfrom dotenv import load_dotenv\n\nUPLOAD_FOLDER = '/app/uploaded'\nCORPUS_FOLDER = '/app/corpus'\nOUTPUTS_FOLDER = '/app/outputs'\n\n\ndef create_app(test_config=None):\n # create and configure the app\n # Galaxy Config\n load_dotenv()\n GALAXY_INSTANCE_URL = os.getenv(\"GALAXY_INSTANCE_URL\")\n GALAXY_INSTANCE_API_KEY = os.getenv(\"GALAXY_INSTANCE_API_KEY\")\n gi = GalaxyInstance(GALAXY_INSTANCE_URL, GALAXY_INSTANCE_API_KEY)\n file_library = gi.libraries.list(name=\"VisaTMPiloteData\")[0]\n\n app = Flask(__name__, instance_relative_config=True)\n\n app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n app.config['CORPUS_FOLDER'] = CORPUS_FOLDER\n app.config['OUTPUTS_FOLDER'] = OUTPUTS_FOLDER\n app.config['history_id'] = os.getenv(\"GALAXY_HISTORY_ID\") \n app.config['library_name'] = \"VisaTMPiloteData\"\n app.config['GALAXY_INSTANCE'] = gi\n\n app.config['LIBRARY_CORPUS_FOLDER'] = \"corpus\"\n app.config['LIBRARY_EXTRACTION_FOLDER'] = \"extraction\"\n app.config['LIBRARY_CLUSTERING_FOLDER'] = \"clustering\"\n\n from . import clusters\n app.register_blueprint(clusters.bp)\n from . import corpus\n app.register_blueprint(corpus.bp)\n from . import files\n app.register_blueprint(files.bp)\n from . import istex\n app.register_blueprint(istex.bp)\n from . import workflows\n app.register_blueprint(workflows.bp)\n\n return app\n","repo_name":"VisaTM/application-pilote","sub_path":"back/galaxy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39372638610","text":"'''\n'''\n#import copy\nfrom collections import deque\nimport threading\nfrom store import Base\n\n \ndef synchronized(func):\n '''Decorator to lock and unlock a method (Phillip J. Eby).\n\n @param func Method to decorate\n '''\n def wrapper(self, *__args, **__kw):\n self._lock.acquire()\n try:\n return func(self, *__args, **__kw)\n finally:\n self._lock.release()\n wrapper.__name__ = func.__name__\n wrapper.__dict__ = func.__dict__\n wrapper.__doc__ = func.__doc__\n return wrapper\n\nclass SimpleBase(Base):\n\n '''Single-process in-memory store base class.'''\n\n def __init__(self, engine, **kw):\n super(SimpleBase, self).__init__(engine, **kw)\n self._store = dict()\n\n def __getitem__(self, key):\n try:\n return self._store[key]\n except:\n raise KeyError('%s' % key)\n\n def __setitem__(self, key, value):\n self._store[key] = value\n\n def __delitem__(self, key):\n try:\n del self._store[key]\n except:\n raise KeyError('%s' % key)\n\n def __len__(self):\n return len(self._store)\n\n def keys(self):\n '''Returns a list of keys in the store.'''\n return self._store.keys()\n \nclass LRUBase(SimpleBase):\n \n def __init__(self, engine, **kw):\n super(LRUBase, self).__init__(engine, **kw)\n self._max_entries = int(kw.get('max_entries', 30))\n self._hits = 0\n self._misses = 0\n self._queue = deque()\n self._refcount = dict()\n\n def __getitem__(self, key):\n try:\n value = super(LRUBase, self).__getitem__(key)\n self._hits += 1\n except KeyError:\n self._misses +=1\n raise\n self._housekeep(key)\n return value\n \n def __setitem__(self, key, value):\n super(LRUBase, self).__setitem__(key, value)\n self._housekeep(key)\n if len(self._store) > self._max_entries:\n while len(self._store) > self._max_entries:\n k = self._queue.popleft()\n self._refcount[k] -= 1\n if not self._refcount[k]:\n super(LRUBase, self).__delitem__(k)\n del self._refcount[k]\n\n def _housekeep(self,key):\n self._queue.append(key)\n self._refcount[key] = self._refcount.get(key, 0) + 1\n if len(self._queue) > self._max_entries * 4: self._purge_queue()\n\n def _purge_queue(self):\n for i in [None] * len(self._queue):\n k = self._queue.popleft()\n if self._refcount[k] == 1:\n self._queue.append(k)\n else:\n self._refcount[k] -= 1 \n \nclass MemoryLRUCache(LRUBase):\n\n '''Thread-safe in-memory cache backend using LRU.''' \n\n def __init__(self, engine, **kw):\n super(MemoryLRUCache, self).__init__(engine, **kw)\n self._lock = threading.Condition()\n\n @synchronized\n def __setitem__(self, key, value):\n super(MemoryLRUCache, self).__setitem__(key, value)\n\n @synchronized \n def __getitem__(self, key):\n return super(MemoryLRUCache, self).__getitem__(key)\n #return copy.deepcopy(super(MemoryLRUCache, self).__getitem__(key))\n\n @synchronized\n def __delitem__(self, key):\n super(MemoryLRUCache, self).__delitem__(key)\n ","repo_name":"vilos/rstlibrary","sub_path":"src/books/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"14407813852","text":"#!/usr/bin/python3\n\"\"\"\nContains BaseModel class\n\"\"\"\n\nimport models\nfrom datetime import datetime\nimport uuid\n\n\nclass BaseModel:\n \"\"\"The BaseModel class which all future classes will be derived\"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"init method for the BaseModel class\"\"\"\n if (kwargs):\n self.__dict__ = kwargs\n del self.__dict__[\"__class__\"]\n self.updated_at = datetime.strptime(self.updated_at,\n \"%Y-%m-%dT%H:%M:%S.%f\")\n self.created_at = datetime.strptime(self.created_at,\n \"%Y-%m-%dT%H:%M:%S.%f\")\n else:\n self.id = str(uuid.uuid4())\n self.created_at = datetime.utcnow()\n self.updated_at = datetime.utcnow()\n models.storage.new(self)\n\n def __str__(self):\n \"\"\"The string of the object\"\"\"\n s = f\"[{self.__class__.__name__}] ({self.id}) <{self.__dict__}>\"\n return (s)\n\n def save(self):\n \"\"\"updates the public instance attribute updated_at with\n the current datetime\"\"\"\n self.updated_at = datetime.now()\n models.storage.new(self)\n models.storage.save()\n\n def to_dict(self):\n \"\"\"returns a dictionary containing all keys/values of __dict__\n of the instance\"\"\"\n dict_ = self.__dict__.copy()\n dict_[\"__class__\"] = self.__class__.__name__\n dict_[\"created_at\"] = self.created_at.isoformat()\n dict_[\"updated_at\"] = self.updated_at.isoformat()\n return (dict_)\n","repo_name":"ASamyAbdelrahman/AirBnB_clone","sub_path":"models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"214281639","text":"#!/usr/bin/env python\n\n\"\"\"Unicorn configuration\"\"\"\nWAIT_BETWEEN_SEC = 120\nSCROLL_TEXT = \"Always Do What You Are Afraid To Do!\"\nSCROLL_TEXT_RND = {0:\"Always do what you are afraid to do!\",\n 1:\"It is nice to be important, but it is important to be nice!\",\n 2:\"The journey of a thousand miles begins with one step!\",\n 3:\"Laziness means more work in the long run!\",\n 4:\"Doubt kill more dreams than failure ever could!\",\n 5:\"Never spend money before you have it!\"}\nSTARFIELD_LENGHT = 3000\nCANDLE_LENGHT = 500\nMATRIX_LENGHT = 700\nIMAGE_LENGHT = 500\nIMAGE_NAME = \"lofi.png\"\n","repo_name":"Ecke2222/unicornhd_random2","sub_path":"unicorn_config.py","file_name":"unicorn_config.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"38994825350","text":"\"\"\"\n在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。\n请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。\n\"\"\"\n\n\n# -*- coding:utf-8 -*-\nclass Solution:\n \"\"\"二维数组中的任意一个数,它左边的数都比它小,它上边的数都比它小,所以可以从矩阵的左下方开始出发\n 若数大于target,则向上移动,小于target,则向右移动。\n \"\"\"\n def Find(self, target, array):\n # 行数\n m = len(array)\n # 特判\n if m == 0:\n return False\n n = len(array[0])\n # 最下面一行\n row = m - 1\n # 第一列\n col = 0\n # 遍历数组,当行大于等于0,列小于n\n while row >= 0 and col < n:\n # 当target小,则向上移动\n if array[row][col] > target:\n row -= 1\n # 当target大,则向右移动\n elif array[row][col] < target:\n col += 1\n else:\n return True\n return False\n\n","repo_name":"lidianxiang/jianzhi-offer","sub_path":"二维数组中的查找.py","file_name":"二维数组中的查找.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"17337425601","text":"import json\nimport boto3\n\nclient = boto3.client('dynamodb')\n\ndef lambda_handler(event, context):\n data = client.put_item(\n TableName='flights',\n Item={\n 'id': {\n 'S': 'AA962'\n },\n 'aircraft_prefix': {\n 'S': 'N930NN'\n },\n 'pilot_name': {\n 'S': 'Deep, John'\n },\n 'max_load':{\n 'N': '136.9'\n },\n 'route':{\n 'S': 'GRU-DFW'\n }\n }\n )\n\n return {\n 'statusCode': 200,\n 'body': json.dumps('Successfully created items!')\n }","repo_name":"LeticiaVitoriaa/TableVoo_LambdaDynamoDB","sub_path":"AddItemFlights.py","file_name":"AddItemFlights.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"1512658634","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport pandas as pd\n\n\ndef getArticleTitle_100_df(search_word):\n label = [0] * 100\n\n my_title_dic = {\"title\": [], \"link\": [], \"label\": label}\n\n # search_word = \"뉴욕증시\"\n\n search_word_decoding = requests.utils.unquote(search_word)\n\n for i in range(10):\n num = i * 10 + 1\n\n url = \"https://search.naver.com/search.naver?&where=news&query=\" + search_word_decoding + \"&sm=tab_pge&sort=0&photo=0&field=0&reporter_article=&pd=0&ds=&de=&docid=&nso=so:r,p:all,a:all&mynews=0&cluster_rank=23&start=\" + str(\n num)\n\n req = requests.get(url)\n\n soup = BeautifulSoup(req.text, 'lxml')\n\n titles = soup.select(\"a._sp_each_title\")\n\n links = soup.select(\"a._sp_each_title\")\n\n for title in titles:\n title_data = title.text\n title_data = re.sub('[-=+,#/\\?:^$.@*\\\"※~&%ㆍ!』\\\\‘|\\(\\)\\[\\]\\<\\>`\\'…\\\"\\“》]', '', title_data)\n my_title_dic['title'].append(title_data)\n\n for link in links:\n my_title_dic['link'].append(link.get('href'))\n\n my_title_df = pd.DataFrame(my_title_dic)\n\n return my_title_df","repo_name":"SOMJANG/FRANEE","sub_path":"get_article_titles.py","file_name":"get_article_titles.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"67"} +{"seq_id":"70460915735","text":"#!/bin/python3\n\nfrom utils import gen_deck\nfrom card_systems import LetnerSystem\n\ndef main():\n # RULES:\n # NONE = SKIP\n # TRUE = CORRECT\n # FALSE = INCORRECT\n\n file = \"test.csv\"\n\n LetnerSystem(gen_deck(file)).run()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"radinals/flashcards","sub_path":"flashcards.py","file_name":"flashcards.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"70501101014","text":"import numpy as np\nimport torch\nimport torch.nn as nn\n\n\nclass Conv3DUnet(nn.Module):\n def __init__(self, in_filters, out_filters, kernel_size=3):\n super().__init__()\n self.in_filters = in_filters\n self.out_filters = out_filters\n self.kernel_size = kernel_size\n\n self.conv_1 = nn.Conv3d(in_channels=in_filters, out_channels=out_filters, kernel_size=self.kernel_size,\n stride=1, padding=1, padding_mode='zeros', bias=False)\n self.batch_1 = nn.BatchNorm3d(num_features=out_filters)\n self.act_1 = nn.LeakyReLU()\n self.conv_2 = nn.Conv3d(in_channels=out_filters, out_channels=out_filters, kernel_size=self.kernel_size,\n stride=1, padding=1, padding_mode='zeros', bias=False)\n self.batch_2 = nn.BatchNorm3d(num_features=out_filters)\n self.act_2 = nn.LeakyReLU()\n\n def forward(self, x):\n x = self.conv_1(x)\n x = self.batch_1(x)\n x = self.act_1(x)\n x = self.conv_2(x)\n x = self.batch_2(x)\n x = self.act_2(x)\n return x\n\n\nclass Encoder3DUnet(nn.Module):\n def __init__(self, base_filters):\n super().__init__()\n self.base_filters = base_filters\n\n self.conv_d1 = Conv3DUnet(in_filters=1, out_filters=base_filters)\n self.pool_d1 = nn.MaxPool3d(kernel_size=(2, 2, 2))\n self.conv_d2 = Conv3DUnet(in_filters=base_filters, out_filters=base_filters * np.power(2, 1))\n self.pool_d2 = nn.MaxPool3d(kernel_size=(2, 2, 2))\n self.conv_d3 = Conv3DUnet(in_filters=base_filters * np.power(2, 1), out_filters=base_filters * np.power(2, 2))\n self.pool_d3 = nn.MaxPool3d(kernel_size=(2, 2, 2))\n self.conv_d4 = Conv3DUnet(in_filters=base_filters * np.power(2, 2), out_filters=base_filters * np.power(2, 3))\n\n def forward(self, x):\n conv_1 = self.conv_d1(x)\n pool1 = self.pool_d1(conv_1)\n conv_2 = self.conv_d2(pool1)\n pool2 = self.pool_d2(conv_2)\n conv_3 = self.conv_d3(pool2)\n pool3 = self.pool_d3(conv_3)\n conv_4 = self.conv_d4(pool3)\n return conv_1, conv_2, conv_3, conv_4\n\n\nclass Decoder3DUnet(nn.Module):\n def __init__(self, base_filters):\n super().__init__()\n self.up_u0 = nn.Upsample(scale_factor=(2, 2, 2), mode='trilinear', align_corners=False)\n self.conv_u0 = Conv3DUnet(in_filters=base_filters * np.power(2, 3) + base_filters * np.power(2, 2),\n out_filters=base_filters * np.power(2, 2))\n self.up_u1 = nn.Upsample(scale_factor=(2, 2, 2), mode='trilinear', align_corners=False)\n self.conv_u1 = Conv3DUnet(in_filters=base_filters * np.power(2, 2) + base_filters * np.power(2, 1),\n out_filters=base_filters * np.power(2, 1))\n self.up_u2 = nn.Upsample(scale_factor=(2, 2, 2), mode='trilinear', align_corners=False)\n self.conv_u2 = Conv3DUnet(in_filters=base_filters * np.power(2, 1) + base_filters * np.power(2, 0),\n out_filters=base_filters)\n\n def forward(self, x):\n up3 = self.up_u0(x[3])\n concat4 = torch.cat([x[2], up3], axis=1)\n conv_up1 = self.conv_u0(concat4)\n up4 = self.up_u1(conv_up1)\n concat5 = torch.cat([x[1], up4], axis=1)\n conv_up2 = self.conv_u1(concat5)\n up6 = self.up_u2(conv_up2)\n concat7 = torch.cat([x[0], up6], axis=1)\n return self.conv_u2(concat7)\n\n\nclass Classification3DUnet(nn.Module):\n def __init__(self, base_filters):\n super().__init__()\n self.conv = nn.Conv3d(in_channels=base_filters, out_channels=1, kernel_size=1,\n stride=1, padding=0)\n self.act = nn.Sigmoid()\n\n def forward(self, x):\n conv_c = self.conv(x)\n return conv_c # self.act(conv_c)\n\n\nclass Classification3DUnetMulti(Classification3DUnet):\n def __init__(self, base_filters, n_classes):\n super(Classification3DUnetMulti, self).__init__(base_filters)\n self.conv = nn.Conv3d(in_channels=base_filters, out_channels=n_classes, kernel_size=1,\n stride=1, padding=0)\n","repo_name":"aledelmo/KDCompression","sub_path":"network/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"16249637945","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\nfrom rasa_core_sdk.events import AllSlotsReset\nfrom rasa_core_sdk.events import Restarted\nfrom rasa_core_sdk.events import FollowupAction\nfrom rasa_sdk import Action\nfrom rasa_sdk.events import SlotSet\nimport zomatopy\nimport json\nimport smtplib \n\nemail_response=\"\"\napp_response = \"\"\n\nclass ActionSearchRestaurants(Action):\n\tdef name(self):\n\t\treturn 'action_search_restaurants'\n\n\tdef filterRestaurantsOnBudget(self, budget, restaurants):\n\t\tglobal email_response\n\t\tglobal app_response\n\t\trangeMin = 0\n\t\trangeMax = 999999\n\t\t# print(\"################ budget: \",budget)\n\t\ttry:\n\t\t\tprice = int(budget)\n\t\t\tif price == 1:\n\t\t\t\trangeMax = 300\n\t\t\telif price == 2:\n\t\t\t\trangeMin = 300\n\t\t\t\trangeMax = 700\n\t\t\telif price == 3:\n\t\t\t\trangeMax = 700\n\t\t\telif price <= 300:\n\t\t\t\trangeMax = 300\n\t\t\telif price <= 700 and price >= 300:\n\t\t\t\trangeMin = 300\n\t\t\t\trangeMax = 700\n\t\t\telse:\n\t\t\t\trangeMin = 700\n\t\texcept Exception as e:\n\t\t\tprint(\"Setting default budget as exception: \",e)\n\t\t\t# default budget \n\t\t\trangeMin = 300\n\t\t\trangeMax = 700\n\n\t\t#sort function right\n\t\t# print(\"before sort!!\",len(restaurants))\n\t\trestaurants = sorted(restaurants,key=lambda x: float(x['restaurant']['user_rating']['aggregate_rating']), reverse=True)\n\t\tres_email = []\n\t\tres_app = []\n\t\tcnt = 1\n\t\t# print(\"reached here!!\",len(restaurants))\n\t\t# print(restaurants[0])\n\t\tfor restaurant in restaurants:\n\t\t\tavg_c_2 = restaurant['restaurant']['average_cost_for_two']\n\t\t\tif avg_c_2 <= rangeMax and avg_c_2 >= rangeMin:\n\t\t\t\tif(cnt == 1 ):\n\t\t\t\t\tres_app.append(\"\\n Showing you top rated restaurants: \\n\")\n\t\t\t\tres_email.append( str(cnt)+ \". \" + restaurant['restaurant']['name'] + \" in \" + restaurant['restaurant']['location']['address'] + \" with average budget of \" + str(restaurant['restaurant']['average_cost_for_two']) + \" has been rated \" + restaurant['restaurant']['user_rating']['aggregate_rating'] + \"/5 .\" )\n\t\t\t\tres_app.append( str(cnt)+ \". \"+ restaurant['restaurant']['name'] + \" in \" + restaurant['restaurant']['location']['address'] + \" has been rated \" + restaurant['restaurant']['user_rating']['aggregate_rating'] + \"/5 .\" )\n\t\t\t\tcnt=cnt+1\n\t\temail_response = \"\\n\".join(res_email[0:min(10,len(res_email))])\t\n\t\tapp_response = \"\\n\".join(res_app[0:min(6,len(res_app))])\n\t\t\n\t\tif(len(res_app)==0):\n\t\t\tapp_response += \"Oops! no restaurant found for this query. Search results = 0\"\n\t\tif(len(res_app)<5):\n\t\t\tapp_response += \"\\n \\nFor more results please search in higher budget range...\\n \\n\"\n\t\tif(len(email_response)<10):\n\t\t\temail_response += \"\\n \\nFor more results please search in higher budget range...\\n \\n\"\n\t\treturn app_response\n\n\t\t\n\tdef run(self, dispatcher, tracker, domain):\n\t\tconfig={ \"user_key\":\"f4924dc9ad672ee8c4f8c84743301af5\"}\n\t\tzomato = zomatopy.initialize_app(config)\n\n\t\tloc = tracker.get_slot('location')\n\t\tcuisine = tracker.get_slot('cuisine').lower()\n\t\tbudget = tracker.get_slot('budget')\n\t\t#print(\"################ vals: \",loc,cuisine,budget)\n\t\tlocation_detail=zomato.get_location(loc, 1)\n\t\td1 = json.loads(location_detail)\n\t\tlat=d1[\"location_suggestions\"][0][\"latitude\"]\n\t\tlon=d1[\"location_suggestions\"][0][\"longitude\"]\n\t\tcuisines_dict={'american':1,'mexican':73,'italian':55,'thai':95,'chinese':25,'north indian':50,'cafe':30,'bakery':5,'biryani':7,'south indian':85}\n\t\tresults=zomato.restaurant_search(\"\", lat, lon, str(cuisines_dict.get(cuisine)), 100000)\n\t\t# print(lat,lon,cuisine)\n\t\tres = json.loads(results)\n\t\tresponse=\"\"\n\t\tif res['results_found'] == 0:\n\t\t\tresponse = \"no results\"\n\t\telse:\n\t\t\t# print(\"results found: \",res['results_found']\n\t\t\tresponse = self.filterRestaurantsOnBudget(budget, res['restaurants'])\n\t\tdispatcher.utter_message(\"\\n\"+response)\n\t\treturn [SlotSet('location',loc)]\n\n\n\ntierOneTwoCities = [\"Ahmedabad\",\"Bangalore\",\"Chennai\",\"Delhi\",\"Hyderabad\",\"Kolkata\",\"Mumbai\",\"Pune\",\"Agra\",\"Ajmer\",\"Aligarh\",\"Allahabad\",\"Amravati\"\n,\"Amritsar\",\"Asansol\",\"Aurangabad\",\"Bareilly\",\"Belgaum\",\"Bhavnagar\",\"Bhiwandi\",\"Bhopal\",\"Bhubaneswar\",\"Bikaner\",\"Bokaro Steel City\",\n\"Chandigarh\",\"Coimbatore\",\"Cuttack\",\"Dehradun\",\"Dhanbad\",\"Durg-Bhilai Nagar\",\"Durgapur\",\"Erode\",\"Faridabad\",\"Firozabad\",\"Ghaziabad\",\n\"Gorakhpur\",\"Gulbarga\",\"Guntur\",\"Gurgaon\",\"Guwahati\",\"Gwalior\",\"Hubli-Dharwad\",\"Indore\",\"Jabalpur\",\"Jaipur\",\"Jalandhar\",\"Jammu\",\n\"Jamnagar\",\"Jamshedpur\",\"Jhansi\",\"Jodhpur\",\"Kannur\",\"Kanpur\",\"Kakinada\",\"Kochi\",\"Kottayam\",\"Kolhapur\",\"Kollam\",\"Kota\",\"Kozhikode\",\"Kurnool\",\"Lucknow\",\"Ludhiana\",\n\"Madurai\",\"Malappuram\",\"Mathura\",\"Goa\",\"Mangalore\",\"Meerut\",\"Moradabad\",\"Mysore\",\"Nagpur\",\"Nanded\",\"Nashik\",\"Nellore\",\"Noida\",\"Palakkad\",\n\"Patna\",\"Pondicherry\",\"Raipur\",\"Rajkot\",\"Rajahmundry\",\"Ranchi\",\"Rourkela\",\"Salem\",\"Sangli\",\"Siliguri\",\"Solapur\",\"Srinagar\",\"Sultanpur\",\"Surat\",\n\"Thiruvananthapuram\",\"Thrissur\",\"Tiruchirappalli\",\"Tirunelveli\",\"Tiruppur\",\"Ujjain\",\"Vijayapura\",\"Vadodara\",\"Varanasi\",\n\"Vasai-Virar City\",\"Vijayawada\",\"Visakhapatnam\",\"Warangal\"]\n\nallowed_cities = [ city.lower() for city in tierOneTwoCities ]\n\nclass ActionValidateLocation(Action):\n\tdef name(self):\n\t\treturn 'action_check_location'\n\n\tdef run(self, dispatcher, tracker, domain):\n\t\tconfig={ \"user_key\":\"f4924dc9ad672ee8c4f8c84743301af5\"}\n\t\tzomato = zomatopy.initialize_app(config)\n\t\n\t\tloc = tracker.get_slot('location')\n\t\tcity = str(loc)\n\t\tif city.lower() in allowed_cities:\n\t\t\treturn [SlotSet('location_match',\"one\")]\n\t\telse:\n\t\t\tzomato = zomatopy.initialize_app(config)\n\t\t\t# return [SlotSet('location_match',\"zero\")]\n\t\t\ttry:\n\t\t\t\tresults = zomato.get_city_ID(city)\n\t\t\t\treturn [SlotSet('location_match',\"one\")]\n\t\t\texcept:\n\t\t\t\t# dispatcher.utter_template(, tracker)\n\t\t\t\treturn [SlotSet('location_match',\"zero\"),FollowupAction(\"utter_sorry_dont_operate\")]\n\n\n# Email list of 10 restaurants\nclass ActionSendEmail(Action):\n\tdef name(self):\n\t\treturn 'action_send_email'\n\n\tdef run(self, dispatcher, tracker, domain):\n\t\temail = tracker.get_slot('email')\n\t\tglobal email_response\n\t\tglobal app_response\n\t\ts = smtplib.SMTP('smtp.gmail.com', 587) \n\t\ts.starttls() \n\t\ts.login(\"foodiesahitya@gmail.com\", \"test1234@1\")\n\t\tmessage = \"The details of all the restaurants you inquried: \\n \\n\"\n\t\tmessage += email_response\n\t\tmessage = 'Subject: {}\\n\\n{}'.format(\"Foodie says Hi !!\", message)\n\t\ttry:\n\t\t\ts.sendmail(\"foodiesahitya@gmail.com\", str(email), message)\n\t\t\ts.quit()\n\t\texcept:\n\t\t\tdispatcher.utter_message(email)\n\t\temail_response = \"\"\n\t\tapp_response = \"\"\n\t\treturn [AllSlotsReset()]\n\n","repo_name":"sritam94/Restaraunt-Chatbot","sub_path":"actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":6418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"37395843696","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 2 07:32:51 2019\n\n@author: Nadav\n\"\"\"\n\n# https://scikit-learn.org/stable/modules/svm.html\nfrom sklearn import svm\nX = [[0, 0], [1, 1]]\ny = [0, 1]\nclf = svm.SVC(gamma='scale')\nclf.fit(X, y) \nA = clf.predict([[1., 2.]])","repo_name":"NadavSegal/MyPython","sub_path":"CourseAnalyticsModeling/HW1.py","file_name":"HW1.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"39537912135","text":"\"\"\"\nUSAGE: python3 migrate_scripts/irbuildertomuctx.py < src/main/scala/uvm/ir/irbuilder/IRBuilder.scala | xclip -selection c\n\nAnd then paste the result into src/main/scala/uvm/refimpl/MuCtxIRBuilderPart.scala\n\nUse pbcopy on Mac.\n\"\"\"\n\nimport re\nimport sys\n\nbegin = \"SCRIPT: BEGIN HERE\"\nend = \"SCRIPT: END HERE\"\n\nreplaces = [(re.compile(x), y) for (x,y) in [\n (r'BN', 'MuBundleNode'),\n (r'(CN|ChildNode)\\[(_\\s*<:\\s*)?Identified\\]', 'MuChildNode'),\n (r'(CN|ChildNode)\\[(_\\s*<:\\s*)?IdentifiedSettable\\]', 'MuChildNode'),\n (r'(CN|ChildNode)\\[Type\\w*\\]', 'MuTypeNode'),\n (r'(CN|ChildNode)\\[Abstract\\w+Type\\]', 'MuTypeNode'),\n (r'(CN|ChildNode)\\[FuncSig\\]', 'MuFuncSigNode'),\n (r'(CN|ChildNode)\\[Const\\w+\\]', 'MuConstNode'),\n (r'(CN|ChildNode)\\[GlobalCell\\]', 'MuGlobalNode'),\n (r'(CN|ChildNode)\\[Function\\]', 'MuFuncNode'),\n (r'(CN|ChildNode)\\[ExposedFunc\\]', 'MuExpFuncNode'),\n (r'(CN|ChildNode)\\[FuncVer\\]', 'MuFuncVerNode'),\n (r'(CN|ChildNode)\\[BasicBlock\\]', 'MuBBNode'),\n (r'(CN|ChildNode)\\[BB\\]', 'MuBBNode'),\n (r'(CN|ChildNode)\\[SSAVariable\\]', 'MuVarNode'),\n (r'(CN|ChildNode)\\[Var\\]', 'MuVarNode'),\n (r'(CN|ChildNode)\\[LocalVariable\\]', 'MuLocalVarNode'),\n (r'(CN|ChildNode)\\[NorParam\\]', 'MuNorParamNode'),\n (r'(CN|ChildNode)\\[ExcParam\\]', 'MuExcParamNode'),\n (r'(CN|ChildNode)\\[InstResult\\]', 'MuInstResNode'),\n (r'(CN|ChildNode)\\[Inst\\w+\\]', 'MuInstNode'),\n (r'(CN|ChildNode)\\[HasKeepaliveClause\\]', 'MuInstNode'),\n ]]\n\nsig = re.compile(r'^( def\\s+(\\w+)\\s*\\(([^)]*)\\):\\s+\\w+\\s+=)', re.MULTILINE)\narg = re.compile(r'(\\w*):\\s+([a-zA-Z0-9\\[\\]]+)')\nnode_like = re.compile(r'Mu\\w+Node')\nnode_seq_like = re.compile(r'Seq\\[Mu\\w+Node\\]')\n\nlines = sys.stdin.read().splitlines()\nl1 = [n for (n,l) in enumerate(lines) if begin in l][0]\nl2 = [n for (n,l) in enumerate(lines) if end in l][0]\n\ntext = \"\\n\".join(lines[l1+1:l2])\n\nfor p, t in replaces:\n text = p.sub(t, text)\n\n#print(text)\n\n#sys.exit(0)\n\nfor whole, name, arglist in sig.findall(text):\n print(whole, \"{\")\n argnames = []\n for an,at in arg.findall(arglist):\n argnames.append(an)\n #print(an, at)\n if node_seq_like.match(at) is not None:\n print(' for((n,i) <- {}.zipWithIndex) require(!n.isNull, \"{}[%d] must not be NULL\".format(i))'.format(an, an))\n elif node_like.match(at) is not None:\n print(' require(!{}.isNull, \"{} must not be NULL\")'.format(an, an))\n if name.startswith(\"new\"):\n print(' addHandle(irBuilder.{}({}))'.format(name, \", \".join(argnames)))\n else:\n print(' irBuilder.{}({})'.format(name, \", \".join(argnames)))\n print(\" }\")\n print()\n #print(whole, name, args)\n #for n,a in sig.findall(line):\n #args = arg_name.findall(a)\n #print(\" addHandle(irBuilder.{}({}))\".format(n, \", \".join(args)))\n \n\n","repo_name":"microvm/microvm-refimpl2","sub_path":"migrate_scripts/irbuildertomuctx.py","file_name":"irbuildertomuctx.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"67"} +{"seq_id":"33059160196","text":"# -*- coding: utf-8 -*-\ntry:\n from contextlib import nullcontext\nexcept ImportError:\n from contextlib2 import nullcontext\n\nimport pytest\n\nimport mincepy\nfrom mincepy.testing import Car\nimport mincepy.testing\nfrom . import utils\n\n# pylint: disable=invalid-name\n\n\ndef insert_cars(historian: mincepy.Historian, num=100, in_transaction=False):\n \"\"\"Insert a number of cars into the database, optionally in a transaction so they all get\n inserted in one go.\"\"\"\n if in_transaction:\n ctx = historian.transaction()\n else:\n ctx = nullcontext()\n\n with ctx:\n for _ in range(num):\n historian.save(mincepy.testing.Car())\n\n\ndef find(historian, **kwargs):\n # Have to wrap the find method like this because it returns a generator and won't necessarily\n # fetch from the db unless we iterate it\n return tuple(historian.find(**kwargs))\n\n\ndef test_benchmark_insertions_individual(historian: mincepy.Historian, benchmark):\n benchmark(insert_cars, historian, in_transaction=False)\n\n\ndef test_benchmark_insertions_transaction(historian: mincepy.Historian, benchmark):\n benchmark(insert_cars, historian, in_transaction=True)\n\n\n@pytest.mark.parametrize(\"num\", [10**i for i in range(5)])\ndef test_find_cars(historian: mincepy.Historian, benchmark, num):\n \"\"\"Test finding a car as a function of the number of entries in the database\"\"\"\n # Put in the one we want to find\n historian.save(Car(\"honda\", \"green\"))\n\n # Put in the correct number of random other entries\n for _ in range(num):\n historian.save(Car(utils.random_str(10), utils.random_str(5)))\n\n result = benchmark(find, historian, state=dict(make=\"honda\", colour=\"green\"))\n assert len(result) == 1\n\n\n@pytest.mark.parametrize(\"num\", [10**i for i in range(5)])\ndef test_find_many_cars(historian: mincepy.Historian, benchmark, num):\n \"\"\"Test finding a car as a function of the number of entries in the database\"\"\"\n # Put in the correct number of random other entries\n for _ in range(num):\n historian.save(Car(utils.random_str(10), utils.random_str(5)))\n\n result = benchmark(find, historian)\n assert len(result) == num\n\n\n@pytest.mark.parametrize(\"num\", [5**i for i in range(1, 4)])\ndef test_load_cars(historian: mincepy.Historian, benchmark, num):\n \"\"\"Test finding a car as a function of the number of entries in the database\"\"\"\n # Put in the correct number of random other entries\n car_ids = []\n for _ in range(num):\n car_ids.append(historian.save(Car(utils.random_str(10), utils.random_str(5))))\n\n result = benchmark(historian.load, *car_ids)\n assert len(result) == len(car_ids)\n","repo_name":"muhrin/mincepy","sub_path":"test/test_benchmarks.py","file_name":"test_benchmarks.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"67"} +{"seq_id":"1060951073","text":"import requests\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.metrics import pairwise_distances_argmin_min\n\n# Spotify API credentials\nclient_id = 'YOUR_CLIENT_ID'\nclient_secret = 'YOUR_CLIENT_SECRET'\n\n# Get access token\ndef get_access_token():\n auth_url = 'https://accounts.spotify.com/api/token'\n auth_data = {\n 'grant_type': 'client_credentials',\n 'client_id': client_id,\n 'client_secret': client_secret\n }\n response = requests.post(auth_url, data=auth_data)\n access_token = response.json()['access_token']\n return access_token\n\n# Search for songs\ndef search_songs(query, limit=50):\n search_url = 'https://api.spotify.com/v1/search'\n access_token = get_access_token()\n headers = {\n 'Authorization': f'Bearer {access_token}'\n }\n params = {\n 'q': query,\n 'type': 'track',\n 'limit': limit\n }\n response = requests.get(search_url, headers=headers, params=params)\n songs = response.json()['tracks']['items']\n return songs\n\n# Retrieve audio features for a song\ndef get_audio_features(song_id):\n features_url = f'https://api.spotify.com/v1/audio-features/{song_id}'\n access_token = get_access_token()\n headers = {\n 'Authorization': f'Bearer {access_token}'\n }\n response = requests.get(features_url, headers=headers)\n audio_features = response.json()\n return audio_features\n\n# Collect song details and audio features\ndef collect_songs_data(query, num_songs):\n songs_data = []\n while num_songs > 0:\n limit = min(num_songs, 50) # API limit is 50 songs per request\n songs = search_songs(query, limit=limit)\n for song in songs:\n song_id = song['id']\n audio_features = get_audio_features(song_id)\n songs_data.append({\n 'song_id': song_id,\n 'name': song['name'],\n 'artists': ', '.join([artist['name'] for artist in song['artists']]),\n 'album': song['album']['name'],\n 'danceability': audio_features['danceability'],\n 'energy': audio_features['energy'],\n 'valence': audio_features['valence'],\n # Add more features as per your requirements\n })\n num_songs -= 1\n if num_songs <= 0:\n break\n songs_df = pd.DataFrame(songs_data)\n return songs_data\n\n# Remove outliers using z-score\ndef remove_outliers(dataframe, features):\n z_scores = np.abs((dataframe[features] - dataframe[features].mean()) / dataframe[features].std())\n filtered_df = dataframe[(z_scores < 3).all(axis=1)] # Adjust the z-score threshold as needed\n return filtered_df\n\n# Preprocess the data to normalize selected features\ndef preprocess_data(dataframe, features):\n # Standardize the selected features using StandardScaler\n scaler = StandardScaler()\n dataframe[features] = scaler.fit_transform(dataframe[features])\n return dataframe\n\n#Custom Transformer for Feature Selection\nclass FeatureSelector(BaseEstimator, TransformerMixin):\n def __init__(self, feature_names):\n self.feature_names = feature_names\n \n def fit(self, X, y=None):\n return self\n \n def transform(self, X):\n return X[self.feature_names]\n\n# Apply K-means clustering to the data\ndef apply_kmeans(dataframe, features, num_clusters):\n X = dataframe[features].values\n kmeans = KMeans(n_clusters=num_clusters, random_state=42)\n kmeans.fit(X)\n labels = kmeans.labels_\n return labels\n\n# Determine optimal features using GridSearchCV\ndef determine_features(dataframe, num_clusters):\n pipeline = Pipeline([\n ('selector', FeatureSelector(feature_names=dataframe.columns[4:])),\n ('kmeans', KMeans(n_clusters=num_clusters, random_state=42))\n ])\n \n # Define the parameter grid for GridSearchCV\n param_grid = {\n 'selector__feature_names': [\n ['danceability', 'energy', 'valence'],\n ['danceability', 'energy', 'valence', 'acousticness'],\n ['danceability', 'energy', 'valence', 'acousticness', 'instrumentalness'],\n ]\n }\n \n # Perform GridSearchCV to determine the optimal features\n grid_search = GridSearchCV(pipeline, param_grid=param_grid, cv=5)\n grid_search.fit(dataframe, dataframe['cluster'])\n \n # Get the best feature combination\n best_features = grid_search.best_params_['selector__feature_names']\n \n return best_features\n\n# Function to generate playlist based on K-means clustering\ndef generate_playlist(song, dataframe, features, num_clusters, num_songs=100):\n input_song = preprocess_data(pd.DataFrame([song]), features)\n cluster_labels = apply_kmeans(dataframe, features, num_clusters)\n input_cluster = pairwise_distances_argmin_min(input_song[features].values, dataframe[features].values)[0][0]\n cluster_songs = dataframe[dataframe['cluster'] == input_cluster].copy()\n cluster_songs = cluster_songs.sample(frac=1, random_state=42) # Shuffle the songs\n cluster_songs = cluster_songs[cluster_songs['song_id'] != song['song_id']]\n playlist = cluster_songs.head(num_songs).copy()\n \n return playlist\n\n# Example usage\nquery = 'pop'\nnum_songs = 10000\nnum_clusters = 5 # Specify the desired number of clusters\n\n# Collect song details and audio features\nsongs_data = collect_songs_data(query, num_songs)\n\n# Create a DataFrame from the collected data\nsongs_df = pd.DataFrame(songs_data)\n\n# Remove outliers using z-score for selected features\nfeatures_to_remove_outliers = ['danceability', 'energy', 'valence'] # Add more features as needed\nfiltered_df = remove_outliers(songs_df, features_to_remove_outliers)\n\n# Preprocess the data to normalize selected features\nfeatures_to_normalize = ['danceability', 'energy', 'valence'] # Add more features as needed\npreprocessed_df = preprocess_data(filtered_df, features_to_normalize)\n\n# Determine optimal features using GridSearchCV\nbest_features = determine_features(preprocessed_df, num_clusters)\n\n# Apply K-means clustering to the preprocessed data using the optimal features\ncluster_labels = apply_kmeans(preprocessed_df, best_features, num_clusters)\n\n# Add cluster labels to the DataFrame\npreprocessed_df['cluster'] = cluster_labels\n\n# Generate a playlist based on a sample song\nsample_song = preprocessed_df.sample(n=1).iloc[0]\nplaylist = generate_playlist(sample_song, preprocessed_df, best_features, num_clusters, num_songs=100)\n\n# Print the resulting playlist\nprint(playlist[['name', 'artists']])","repo_name":"ronitrjain/Spotify-Sort","sub_path":"spotifysort.py","file_name":"spotifysort.py","file_ext":"py","file_size_in_byte":6777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"69889142615","text":"from tkinter import *\r\nfrom PIL import ImageTk,Image\r\nfrom tkinter import messagebox\r\nimport sqlite3\r\n\r\ndef enrolStudent():\r\n root = Tk()\r\n root.title(\"Student Enrolment\")\r\n root.geometry(\"400x550\")\r\n root.configure(background=\"Wheat\")\r\n global nameList\r\n global courseList\r\n courseList = []\r\n nameList = []\r\n\r\n def main():\r\n conn = sqlite3.connect(\"studentdetail.sqlite\")\r\n cursor = conn.cursor()\r\n cursor.execute(\"CREATE TABLE IF NOT EXISTS enrolcourse(name TEXT,coursename TEXT)\")\r\n cursor.execute(\"SELECT * FROM student\")\r\n for _id,name,email,gender,coursename in cursor:\r\n if name in nameList:\r\n pass\r\n else:\r\n nameList.append(str(name))\r\n \r\n cursor.execute(\"SELECT * FROM courseOffering\")\r\n index=1\r\n for _id,coursename,student,date,credittransferable, in cursor:\r\n if coursename in courseList:\r\n pass\r\n else:\r\n courseList.append(str(coursename))\r\n coursename_listbox.insert(END,str(index) + \" ) \" + str(coursename))\r\n index +=1\r\n \r\n\r\n\r\n def popUpEdit():\r\n response = messagebox.askyesno(\"Confirmation\",\"Confirm to enrol student?\")\r\n if response == 1:\r\n enrolStudent()\r\n name.delete(\"0\",END)\r\n elif response == 0:\r\n name.delete(\"0\",END)\r\n\r\n def popUpDelete():\r\n response = messagebox.askyesno(\"Confirmation\",\"Confirm to de-enrol student?\")\r\n if response == 1:\r\n deenrolStudent()\r\n name.delete(\"0\",END)\r\n elif response == 0:\r\n name.delete(\"0\",END)\r\n\r\n def enrolStudent():\r\n main()\r\n student = name.get()\r\n anchors = coursename_listbox.get(ANCHOR)\r\n coursename = anchors[4:]\r\n conn = sqlite3.connect(\"studentdetail.sqlite\")\r\n cursor = conn.cursor()\r\n if coursename != \"\":\r\n if student in nameList:\r\n select=(\"INSERT INTO enrolcourse VALUES (?,?)\")\r\n cursor.execute(select,(student,coursename))\r\n cursor.connection.commit()\r\n else:\r\n response = messagebox.showerror(\"Error\",\"Student not exist\")\r\n else:\r\n response = messagebox.showerror(\"Error\",\"Course is not selected\")\r\n \r\n def deenrolStudent():\r\n main()\r\n anchors = coursename_listbox.get(ANCHOR)\r\n coursename = anchors[4:]\r\n student = name.get()\r\n conn = sqlite3.connect(\"studentdetail.sqlite\")\r\n cursor = conn.cursor()\r\n if coursename != \"\":\r\n if student in nameList:\r\n select=(\"DELETE FROM enrolcourse WHERE name = ? and coursename = ?\")\r\n cursor.execute(select,(student,coursename))\r\n cursor.connection.commit()\r\n else:\r\n response = messagebox.showerror(\"Error\",\"Student not exist\")\r\n else:\r\n response = messagebox.showerror(\"Error\",\"Course is not selected\")\r\n \r\n \r\n title_label = Label(root, relief = \"sunken\", bg=\"Tan\",font=(\"Times\",15),fg=\"white\",text = \"-\"*10 + \"ENROL/DE-ENROL STUDENT\" + \"-\"*10,)\r\n title_label.grid(row=0 , column=0, columnspan=2,pady=10)\r\n name_label = Label(root ,font=(\"Times\",12), text = \"Name :\", bg=\"Tan\",fg=\"white\")\r\n name_label.grid(row=3, column=0,sticky=W,padx=10,pady=(30,0))\r\n name = Entry(root, width =30, background = \"Lavender\",bg=\"ivory\")\r\n name.grid(row=4, column=0, padx=10, pady=10, sticky=W)\r\n coursename_label = Label(root , bg=\"Tan\",font=(\"Times\",12), text = \"Short Course :\",fg=\"white\",justify=\"left\")\r\n coursename_label.grid(row=1, column=0, sticky=NW, pady=(20,5),padx=10)\r\n coursename_listbox = Listbox(root,width=35,height=15,bg=\"ivory\")\r\n coursename_listbox.grid(row=2, column=0,columnspan=2, sticky=W, pady=10,padx=10)\r\n deenrol_btn = Button(root,bg=\"Tan\",fg=\"white\", text=\"De-enrol\", command = popUpDelete)\r\n deenrol_btn.grid(row=5, column=0,pady=10,padx=90)\r\n enrol_btn = Button(root,bg=\"Tan\",fg=\"white\", width=6,text=\"Enrol\",command=popUpEdit)\r\n enrol_btn.grid(row=5, column=0, pady=10,sticky=\"W\",padx=10)\r\n\r\n main() \r\n\r\n \r\n \r\n \r\n \r\n","repo_name":"sinhantwenty8/School-Management","sub_path":"Enrolstudent.py","file_name":"Enrolstudent.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"13796928228","text":"import pandas as pd \nfrom pandasql import sqldf \n\nclass FileParser: \n \n def read_file_to_dataframe(self):\n df = pd.read_csv(self.file_directory, \n delimiter=self.column_delimiter, \n skiprows=self.skip_rows, \n skipfooter=self.skip_last_rows,\n header=None,\n nrows=self.limit_rows)\n \n df.columns = [f\"c{index + 1}\" for index, _ in enumerate(df.columns)]\n self.df = df\n \n def execute_sql_in_dataframe(self, query):\n file = self.df\n return sqldf(query, locals())\n \n def __init__(self, file_directory, column_delimiter, skip_rows = 0, skip_last_rows = 0, limit_rows = None):\n self.file_directory = file_directory\n self.column_delimiter = column_delimiter\n self.skip_rows = skip_rows\n self.skip_last_rows = skip_last_rows\n self.limit_rows = None if limit_rows == 0 else limit_rows\n self.df = None","repo_name":"Guisilcol/sql-in-file","sub_path":"src/modules/Parsers/FileParser.py","file_name":"FileParser.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28061247721","text":"# -*- coding : utf-8 -*-\n\n\"\"\"\n* What is this module about?\nIt consists of nine module applied to lauren classification and\nfunction packaging the process of parameter tuning, trains and evaluatation.\n\n* References:\nhttp://scikit-learn.org/stable/supervised_learning.html#supervised-learning\n\"\"\"\n\nfrom data_process.Dimension_reduction import Feature_selection\n\nimport sys\nimport parameter_op as pm\nsys.path.append(\".\")\nimport os\nfrom datetime import datetime\nos.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'\nfrom utility.entropy_estimators import midd\n\nimport numpy as np\n# from xgboost.sklearn import XGBClassifier\nfrom sklearn import svm, linear_model, tree, neighbors, neural_network, ensemble, naive_bayes\nfrom sklearn.metrics import classification_report\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.model_selection import cross_val_score, GridSearchCV\nfrom sklearn.metrics import roc_curve, roc_auc_score\nimport matplotlib.pyplot as plt\n# import pydotplus\n\n\nclass PredictModel(object):\n def __init__(self):\n # Feature_selection.__init__(self)\n # self.dataset = dataset\n self.dataset = []\n self.labels = []\n self.titles = []\n self.classifier = None\n self.model_name = \"\"\n\n def feature_reduction(self, dataset, titles, labels, thresh):\n \"\"\"\n Select feature by information gain method.\n \"\"\"\n feature_oper = Feature_selection()\n new_dataset, new_titles = feature_oper.feature_select(dataset, titles, labels, thresh)\n return new_dataset, new_titles\n\n def feature_reduction_sec(self, dataset, titles, feat_impace_file, topNums, commonModel_bottom):\n \"\"\"\n Select feature by common gene estimated by several models.\n \"\"\"\n feature_oper = Feature_selection()\n new_dataset, new_titles = feature_oper.sec_feature_select(\n dataset, titles, feat_impace_file, topNums, commonModel_bottom\n )\n return new_dataset, new_titles\n\n def set_params(self, kwargs):\n self.classifier.set_params(**kwargs)\n\n def load_data(self, mut_analyse_file):\n matrix, labels, titles = [], [], []\n with open(mut_analyse_file, \"r\") as f1:\n for lineno, line in enumerate(f1):\n data_array = line.strip(\"\\n\").split(\"\\t\")\n if lineno > 0:\n if data_array[-1]:\n labels.append(int(data_array[-1]))\n # matrix.append([float(x) for x in data_array[:-1]])\n # else:\n # titles = data_array[:-1]\n matrix.append([int(x) for x in data_array[1:-4]])\n else:\n titles = data_array[1:-4]\n self.dataset = np.array(matrix)\n self.titles = np.array(titles)\n self.labels = labels\n\n def param_tune(self, tuned_parameters, dataset, labels, scores_method):\n X_train, X_test, y_train, y_test = train_test_split(\n dataset, labels, test_size=pm._setAside_partionRatio, stratify=labels\n )\n for score in scores_method:\n print(\"# Tuning hyper-parameters for {}\\n\".format(score))\n\n clf = GridSearchCV(\n estimator=self.classifier, param_grid=tuned_parameters, cv=pm._crossVal_fold, scoring=score\n )\n clf.fit(dataset, labels)\n print(\"Grid scores on development set:\\n\")\n for params, mean_score, scores in clf.grid_scores_:\n print(\"Accuracy: %0.3f (+/-%0.03f) for parameter: %r\"\n % (mean_score, scores.std() * 2, params))\n\n print(\"\\nBest parameters and scores set found on development set by {}:\\n\".format(score))\n print(\"--->Accuracy: {:.3f}, parameter: {}\\n\".format(clf.best_score_, clf.best_params_))\n\n print(\"Detailed classification report:\\n\")\n print(\">The model is trained on the full development set.\")\n print(\">The scores are computed on the full evaluation set.\\n\")\n y_true, y_pred = y_test, clf.predict(X_test)\n print(classification_report(y_true, y_pred))\n print()\n\n self.classifier = clf.best_estimator_\n\n def train(self, train_set, train_labels):\n self.classifier.fit(train_set, train_labels)\n\n def predict(self, val_set):\n return self.classifier.predict(val_set)\n\n def evaluate(self, dataset, labels):\n scores = np.zeros(1)\n em, fold, it, pr = pm._estimate_method, pm._crossVal_fold, pm._setAside_iterTimes, pm._setAside_partionRatio\n if em == \"cross_val\":\n scores = cross_val_score(self.classifier, dataset, labels, cv=fold).reshape(fold, )\n print(scores)\n print(\"Val_Accuracy and Train_Accuracy of model {}: {:.4f}(+/- {:f})\".format(\n self.model_name, scores[:].mean(), scores[:].std())\n )\n elif em == \"set_aside\":\n scores = np.zeros((it,))\n train_scores = np.zeros((it,))\n for i in range(it):\n X_train, X_test, Y_train, Y_test = train_test_split(dataset, labels, test_size=pr)\n self.train(X_train, Y_train)\n val_acc = self.classifier.score(X_test, Y_test)\n train_acc = self.classifier.score(X_train, Y_train)\n scores[i] = val_acc\n train_scores[i] = train_acc\n print(\n \"---> Loop {:d}\\n\\tVal_Accuracy: {:.4f}\\tTrain_Accuracy: {:.4f}\".format(i + 1, val_acc, train_acc))\n print(\"Val_Accuracy and Train_Accuracy of model {}:\\n\\t{:.4f}(+/- {:f})\\t{:.4f}(+/- {:f})\".format(\n self.model_name, scores[:].mean(), scores[:].std(), train_scores[:].mean(), train_scores[:].std())\n )\n else:\n print(\"ERROR, p`lease set method in [set_aside, cross_val]\")\n return scores\n\n def visualize(self, **kwargs):\n pass\n\n def evaluate_roc(self, dataset, labels):\n X_train, X_test, Y_train, Y_test = train_test_split(dataset, labels, test_size=pm._setAside_partionRatio)\n self.train(X_train, Y_train)\n Y_pred = self.predict(X_test)\n auc_score = roc_auc_score(Y_test, Y_pred)\n # print(\"AUC on validataion set of model {}: {:.4f}\".format(self.model_name, auc_score))\n fpr, tpr, _ = roc_curve(Y_test, Y_pred)\n plt.figure()\n plt.plot([0, 1], [0, 1], 'k--')\n plt.plot(fpr, tpr, label=self.model_name)\n plt.xlabel('False positive rate')\n plt.ylabel('True positive rate')\n plt.title('ROC curve with AUC({:.4f})'.format(auc_score.item()))\n plt.legend(loc='best')\n plt.show()\n return auc_score\n\n def feature_select(self, **kwargs):\n pass\n\n def save_model(self, mut_analyse_file):\n pass\n\n\nclass LR(PredictModel):\n def __init__(self, **kwargs):\n PredictModel.__init__(self)\n self.classifier = linear_model.LogisticRegression(\n C=0.001, penalty=\"l2\", tol=0.001, solver=\"liblinear\"\n )\n self.model_name = \"LR\"\n\n def feature_select(self):\n coef_array = [(cf, i) for i, cf in enumerate(self.classifier.coef_[0])]\n coef_array.sort(key=lambda x: abs(x[0]), reverse=True)\n return [\"LR\"] + [\"{:s}({:.6f})\".format(self.titles[ind[1]], ind[0]) for ind in coef_array]\n\n\nclass SVM(PredictModel):\n def __init__(self):\n PredictModel.__init__(self)\n self.classifier = svm.SVC(\n gamma=0.01, C=0.907, kernel=\"linear\", coef0=0.54, degree=2,\n )\n self.model_name = \"SVM\"\n\n # def visualize(self):\n # y, x = [], []\n # external = 1.0\n # plt.figure()\n # self.dataset, self.titles = self.feature_reduction(self.dataset, self.titles, self.labels, Parameter.infoGain_thresh)\n # for i in range(1, 1001):\n # Parameter.SVM_C = i / external\n # x.append(Parameter.SVM_C)\n # self.set_params(kernel_string=Parameter.SVM_kernel, gamma=Parameter.SVM_gamma, c=Parameter.SVM_C)\n # print(\"-> Parameter status:\\tC({0:f})\".format(Parameter.SVM_C), end = \"\\n\\t\")\n # score = self.evaluate(self.dataset, self.labels).mean()\n # y.append(score)\n # plt.plot(x, y)\n # plt.title(\"plot for the relationship of C and prediction accuracy in linear kernel\")\n # plt.legend(loc = \"upper right\")\n # plt.xlabel(\"C/{:f}\".format(1/external))\n # plt.ylabel(\"Accuracy/1\")\n # plt.grid(x)\n # plt.show()\n\n def feature_select(self):\n coef_array = [(cf, i) for i, cf in enumerate(self.classifier.coef_[0])]\n coef_array.sort(key=lambda x: abs(x[0]), reverse=True)\n return [\"SVM\"] + [\"{:s}({:.6f})\".format(self.titles[ind[1]], ind[0]) for ind in coef_array]\n\n\nclass Decision_Tree(PredictModel):\n def __init__(self):\n PredictModel.__init__(self)\n # Scikit-learn uses an small optimised version of the CART algorithm\n self.classifier = tree.DecisionTreeClassifier()\n self.model_name = \"Decision_Tree\"\n\n # seems that this function does not make sense.\n def visualize(self, mut_analyse_file):\n dot_data = tree.export_graphviz(self.classifier, out_file=None, feature_names=self.titles,\n special_characters=True)\n graph = pydotplus.graph_from_dot_data(dot_data)\n graph.write_pdf(mut_analyse_file)\n return\n\n\nclass Bernoulli_Bayes(PredictModel):\n def __init__(self):\n PredictModel.__init__(self)\n self.classifier = naive_bayes.BernoulliNB(\n alpha=0.01, class_prior=None\n )\n self.model_name = \"Bernoulli_Bayes\"\n\n def feature_select(self):\n log_prob_pos = self.classifier.feature_log_prob_\n real_prob_pos = np.exp(log_prob_pos)\n real_prob_neg = 1 - real_prob_pos\n P_Y1 = float(sum(self.labels)) / len(self.labels)\n P_Y0 = 1 - P_Y1\n infoEnt = -1 * (P_Y1 * np.log(P_Y1) + P_Y0 * np.log(P_Y0))\n\n ce = []\n for i in range(real_prob_pos.shape[1]):\n P_X1 = np.sum(self.dataset[:, i], axis=0) / self.dataset.shape[0]\n P_X0 = 1 - P_X1\n ce.append((abs(P_X1 - P_X0), i))\n\n ce.sort(key=lambda x: x[0], reverse=True)\n content = [\"BNBayes\"] + [\"{}({:.6f})\".format(self.titles[x[1]], x[0]) for x in ce]\n\n return content\n\n\nclass Xgboost(PredictModel):\n '''\n waiting for that the package installed successfully.\n '''\n\n def __init__(self):\n PredictModel.__init__(self)\n self.classifier = XGBClassifier(\n learning_rate=0.1, n_estimators=140, max_depth=5, min_child_weight=1,\n gamma=0, subsample=0.8, colsample_bytree=0.8, objective=\"binary:logistic\"\n )\n self.model_name = \"Xgboost\"\n\n\nclass RandomForest(PredictModel):\n def __init__(self):\n PredictModel.__init__(self)\n self.classifier = ensemble.RandomForestClassifier(\n n_estimators=22, max_depth=None, min_samples_split=2,\n random_state=0, max_features=0.1, criterion=\"gini\"\n )\n self.model_name = \"RandomForest\"\n\n def feature_select(self):\n feature_impt = self.classifier.feature_importances_\n indices = np.argsort(feature_impt)[::-1]\n # feature_impt.sort(key = lambda x: x[0], reverse=True)\n return [\"RandomForest\"] + [\"{:s}({:.6f})\".format(self.titles[indices[f]], feature_impt[indices[f]]) for f in\n range(feature_impt.shape[0])]\n\n\nclass GBDT(PredictModel):\n def __init__(self):\n PredictModel.__init__(self)\n self.classifier = ensemble.GradientBoostingClassifier(\n n_estimators=45, learning_rate=0.1,\n max_features=45, loss=\"exponential\"\n )\n self.model_name = \"GBDT\"\n\n def feature_select(self):\n feature_impt = [(cf, i) for i, cf in enumerate(self.classifier.feature_importances_)]\n feature_impt.sort(key=lambda x: x[0], reverse=True)\n return [\"GBDT\"] + [\"{:s}({:.6f})\".format(self.titles[ind[1]], ind[0]) for ind in feature_impt]\n\n\nclass KNN(PredictModel):\n def __init__(self):\n PredictModel.__init__(self)\n self.classifier = neighbors.KNeighborsClassifier(\n n_neighbors=12, algorithm=\"auto\"\n )\n self.model_name = \"KNN\"\n\n\nclass ShallowNetwork(PredictModel):\n def __init__(self):\n PredictModel.__init__(self)\n self.classifier = neural_network.MLPClassifier(\n solver=\"lbfgs\", alpha=0.0,\n hidden_layer_sizes=(4, 7), activation=\"relu\"\n )\n self.model_name = \"ShallowNetwork\"\n\n\ndef model_para_tune(mut_analyse_file, models_tuned_parameters, scores, model_array, method, **kwargs):\n classifiers = []\n for model_name in model_array:\n clf = eval(\"{}()\".format(model_name))\n clf.load_data(mut_analyse_file)\n if method == \"thresh\":\n clf.dataset, clf.titles = clf.feature_reduction(clf.dataset, clf.titles, clf.labels, kwargs[\"threshold\"])\n elif method == \"count\":\n clf.dataset, clf.titles = clf.feature_reduction_sec(\n clf.dataset, clf.titles, kwargs[\"feature_sort\"], kwargs[\"topNums\"], kwargs[\"commonModel_bottom\"]\n )\n else:\n print(\"ERROR!!!\")\n clf.param_tune(models_tuned_parameters[model_name], clf.dataset, clf.labels, scores)\n classifiers.append(clf)\n return classifiers\n\n\ndef evaluate_model(classifiers):\n scores = []\n for clf in classifiers:\n scores.append(clf.evaluate(clf.dataset, clf.labels))\n return scores\n\n\ndef chara_im_assess_by_ml(classifiers, valid_modelnames, mutation_sort_file):\n feat_matrix = []\n for clf in classifiers:\n if clf.model_name in valid_modelnames:\n clf.train(clf.dataset, clf.labels)\n feat_matrix.append(clf.feature_select())\n feat_matrix = list(zip(*feat_matrix))\n with open(mutation_sort_file, \"w\") as f1:\n for line in feat_matrix:\n f1.write(\"\\t\".join(line) + \"\\n\")\n return feat_matrix\n\n\ndef visualize(x, y, model_array, xlabel, ylabel, outputFile):\n plt.figure()\n for i in range(len(model_array)):\n plt.plot(x, y[i], label=model_array[i])\n plt.title(\"Accuracy Curve of ml_model\")\n plt.legend(loc=\"upper right\")\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.grid(True, linestyle=\":\")\n plt.show()\n plt.savefig(outputFile)\n y = list(zip(*y))\n with open(os.path.splitext(outputFile)[0] + \".txt\", \"w\") as f1:\n for ind in range(len(x)):\n f1.write(\"\\t\".join([str(x[ind])] + [str(m) for m in y[ind]]) + \"\\n\")\n return True\n\n\ndef find_common(mutation_sort_file, mutation_sort_file_by_common):\n matrix = []\n with open(mutation_sort_file, \"r\") as f1:\n for lineno, line in enumerate(f1):\n if lineno >= 1:\n matrix.append([ele.split(\"(\")[0] for ele in line.strip(\"\\n\").split(\"\\t\")])\n total_feature_nums, match_dict, model_nums = len(matrix), {}, len(matrix[0])\n for common_totals in range(1, total_feature_nums + 1):\n common_set = set([line[0] for line in matrix[:common_totals]])\n for j in range(1, model_nums):\n common_set &= set([line[j] for line in matrix[:common_totals]])\n for feature in common_set:\n if feature not in match_dict:\n match_dict[feature] = common_totals\n sort_by_commonNums = sorted([[key, str(value)] for key, value in match_dict.items()], key=lambda x: int(x[1]))\n with open(mutation_sort_file_by_common, \"w\") as f2:\n f2.write(\"Feature\\tUnique_common_nums\\n\")\n for line in sort_by_commonNums:\n f2.write(\"\\t\".join(line) + \"\\n\")\n return True\n\n\ndef estimate_roughly(model_array, mut_dataset_file, directory):\n # Determine the threshold range of correlation scores.\n if not os.path.exists(directory):\n os.mkdir(directory)\n feat_screen_by_corr, scores = os.path.join(directory, \"feat_screen_by_correlation.table\"), []\n featOp = Feature_selection()\n featOp.load_data(mut_dataset_file)\n featOp.output_corr(feat_screen_by_corr)\n with open(feat_screen_by_corr, \"r\") as f1:\n for lineno, line in enumerate(f1):\n if lineno >= 1:\n scores.append(float(line.strip().split(\"\\t\")[3]))\n max_score, min_score = max(scores), min(scores)\n\n paras, scores, valid_models = pm._hyper_paras, pm._scores, pm._valid_modelnames\n feat_screen_by_model = os.path.join(directory, \"feat_screen_by_model.table\")\n x, y = [], [[] for _ in range(len(model_array))]\n i = int(min_score * 100)\n while i < int(max_score * 100):\n st = datetime.now()\n\n score_thresh, x = i / 100.0, x + [i / 100.0]\n clfs = model_para_tune(mut_dataset_file, paras, scores, model_array, \"thresh\", threshold=score_thresh)\n performs = evaluate_model(clfs)\n for j in range(len(model_array)):\n y[j].append(performs[j].mean())\n\n i += 1\n ed = datetime.now()\n print('With threshold {0:.4f}, Runtime: {1}s'.format(score_thresh, str(ed - st).split(\".\")[0]))\n\n # Make use of the last maximum location to evaluate character power\n ind = 0\n for i in range(len(y[0])):\n if y[0][i] > y[0][ind]:\n ind = i\n score_thresh = x[ind]\n clfs = model_para_tune(mut_dataset_file, paras, scores, model_array, \"thresh\", threshold=score_thresh)\n chara_im_assess_by_ml(clfs, valid_models, feat_screen_by_model)\n\n xlabel, ylabel, outputImg = \"Threshold of Combined Score\", \"Accuracy\", os.path.join(directory,\n \"accuracy_trend_by_thresh.png\")\n visualize(x, y, model_array, xlabel, ylabel, outputImg)\n return feat_screen_by_model, outputImg\n\n\ndef estimate_meticulously(model_array, mut_dataset_file, feat_screen_by_model, directory):\n if not os.path.exists(directory):\n os.mkdir(directory)\n with open(feat_screen_by_model, \"r\") as f1:\n upper = len(f1.readlines()) - 1\n\n paras, scores, common_models = pm._assigned_hyper_paras_1, pm._scores, pm._commonModel_bottom\n x, y = [], [[] for _ in range(len(model_array))]\n for i in range(1, upper + 1):\n st = datetime.now()\n\n topNums, flag = i, True\n meta_model = PredictModel()\n meta_model.load_data(mut_dataset_file)\n meta_model.dataset, meta_model.titles = meta_model.feature_reduction_sec(\n meta_model.dataset, meta_model.titles, feat_screen_by_model, topNums, common_models\n )\n feature_nums = meta_model.dataset.shape[1]\n if feature_nums <= 1 or (len(x) > 0 and feature_nums == x[-1]):\n continue\n else:\n clfs = model_para_tune(\n mut_dataset_file, paras, scores, model_array, \"count\", feature_sort=feat_screen_by_model,\n topNums=topNums, commonModel_bottom=common_models\n )\n performs = evaluate_model(clfs)\n x.append(feature_nums)\n for j in range(len(model_array)):\n y[j].append(performs[j].mean())\n\n ed = datetime.now()\n print('Top {0} gene set, {1} genes remained. all models passed, Runtime: {2}s'.format(\n i, feature_nums, str(ed - st).split(\".\")[0])\n )\n\n xlabel, ylabel, outputImg = \"Num of Remained Features\", \"Accuracy\", os.path.join(directory,\n \"accuracy_trend_by_count.png\")\n feat_sort_by_model = os.path.join(directory, \"feature_sort_by_model.table\")\n visualize(x, y, model_array, xlabel, ylabel, outputImg)\n find_common(feat_screen_by_model, feat_sort_by_model)\n return feat_sort_by_model\n\n\n__end__ = \"yes\"\n\nif __name__ == \"__main__\":\n # print(__doc__)\n # parameter of mutation sites\n # mut_dataset_file = \"D:\\\\Project_JY\\\\gastricCancer\\\\Data\\\\mutation_identify\\\\datasetOfPathology_pos.table\"\n # threshold = 1.40\n # output_dir = \"D:\\\\Project_JY\\\\gastricCancer\\\\Result\\\\pos\"\n\n # parameter of gene\n mut_dataset_file = \"D:\\\\Project_JY\\\\gastricCancer\\\\Data\\\\input_dataset\\\\gene\\\\datasetOfPathology_lauren_gene_1.table\"\n threshold = 0.2\n output_dir = \"D:\\\\Project_JY\\\\gastricCancer\\\\Result\\\\lauren\\\\gene\"\n train_dataset_file = \"D:\\\\Project_JY\\\\gastricCancer\\\\Data\\\\input_dataset\\\\gene\\\\dataset_geneFeat_train.table\"\n valid_dataset_file = \"D:\\\\Project_JY\\\\gastricCancer\\\\Data\\\\input_dataset\\\\gene\\\\dataset_geneFeat_valid.table\"\n\n # parameter of tcga gene\n # mut_dataset_file = \"D:\\\\Project_JY\\\\gastricCancer\\\\Data\\\\input_dataset\\\\TCGA\\\\dataset_geneFeat_from_tcga.table\"\n # threshold = 1.40\n # output_dir = \"D:\\\\Project_JY\\\\gastricCancer\\\\Result\\\\lauren\\\\tcga_gene\"\n\n # model_array = [\"LR\", \"SVM\", \"Decision_Tree\", \"Bernoulli_Bayes\", \"Xgboost\", \"RandomForest\", \"GBDT\", \"KNN\",\n # \"ShallowNetwork\"]\n model_name = \"LR\"\n model_array, paras, scores = [model_name], pm._hyper_paras, pm._scores\n clf = eval(\"{}()\".format(model_name))\n clf.load_data(mut_dataset_file)\n\n\n # clf_l = eval(\"{}()\".format(model_name))\n # clf_l.load_data(valid_dataset_file)\n # clf.dataset, clf.titles = clf.feature_reduction(clf.dataset, clf.titles, clf.labels, threshold)\n # titles_dict = dict([(clf_l.titles[i], i) for i in range(clf_l.titles.shape[0])])\n # feature_select_index = [\n # titles_dict[clf.titles[i]] for i in range(len(clf.titles))\n # ]\n # clf_l.dataset, clf_l.titles = clf_l.dataset[:, feature_select_index], clf.titles\n #\n # clf.param_tune(paras[model_name], clf.dataset, clf.labels, scores)\n # # clf.set_params({\"C\":0.018, \"penalty\":\"l2\"})\n # clf.train(clf.dataset, clf.labels)\n # print(\"Train Accuracy: {}\".format(clf.classifier.score(clf.dataset, clf.labels)))\n # print(\"Valid Accuracy: {}\".format(clf.classifier.score(clf_l.dataset, clf_l.labels)))\n\n # feat_screen_by_model, img1 = estimate_roughly(model_array, train_dataset_file, output_dir)\n # estimate_meticulously(model_array, mut_dataset_file, feat_screen_by_model, output_dir_pos)\n","repo_name":"WenzhengFang/GastricCancer","sub_path":"model/ml_packages_Lauren.py","file_name":"ml_packages_Lauren.py","file_ext":"py","file_size_in_byte":22216,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"67"} +{"seq_id":"73805839252","text":"from rest_framework import serializers\n\nfrom accounts.models import Profile\n\nclass UpdateProfileSerializer(serializers.ModelSerializer):\n\n profile_image = serializers.ImageField(max_length=350, required=False)\n\n class Meta:\n model = Profile\n fields = ['id', 'roll_no', 'first_name', 'last_name', 'gender',\n 'batch', 'programme', 'dob', 'contact_no', 'alt_email',\n 'street_address1', 'street_address2', 'city', 'state',\n 'pincode', 'profile_image']","repo_name":"garg3133/JagratiWebApp","sub_path":"home/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"67"} +{"seq_id":"26039424890","text":"ventes = float(input(\"Entrez le montant total des ventes pour le mois : \"))\n\nif ventes < 0:\n print(\"Erreur: le montant des ventes ne peut pas être négatif.\")\nelse:\n if ventes < 1000:\n taux_commission = 0.025\n elif ventes <= 5000:\n taux_commission = 0.05\n else:\n taux_commission = 0.075\n\n commission = ventes * taux_commission\n remuneration = commission + 5000 # 5000 $ est le salaire de base\n print(\"La rémunération du vendeur est de {0:.2f}$\".format(remuneration))\n","repo_name":"degenio/livre_exercices_python","sub_path":"03_chapitre_tests/exercice_3.9.py","file_name":"exercice_3.9.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"28067725377","text":"def sortedSquaredArraySlow(nums):\n # This for loop takes linear time\n for i in range(len(nums)):\n nums[i] **= 2\n\n # The sort method is always a slow solution as it takes O(N * log(N))\n # This makes the solution slower\n nums.sort()\n return nums\n\n\ndef sortedSquaredArray(nums):\n result = [0] * len(nums)\n\n left = 0\n right = len(nums) - 1\n\n # In this case we do it in linear time\n for i in range(len(nums) - 1, -1, -1):\n if abs(nums[left]) >= abs(nums[right]):\n result[i] = nums[left] ** 2\n left += 1\n\n else:\n result[i] = nums[right] ** 2\n right -= 1\n\n return result\n\n\nprint(sortedSquaredArray([-7, -3, -1, 4, 8, 12]))\n","repo_name":"codexcod/AlgorithmsAndDataStructures","sub_path":"SortedSquaredArray.py","file_name":"SortedSquaredArray.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"25318878800","text":"import numpy as np\nimport pandas as pd\nNUM_CHUNK = 34\n\n# load labelevents table and get the number of each item\ndef count_label_events():\n label_events = pd.read_csv('./raw_data/LABEVENTS.csv.gz')\n label_counts = label_events.groupby('ITEMID').count().sort_values(by=[\"ROW_ID\"],ascending =False)\n label_counts.to_csv(\"./raw_data/LabCounts.csv\")\n print(\"LabCounts.csv saved.\")\n\n# load ouputevents table and get the number of each item\ndef count_output_events():\n output_events = pd.read_csv('./raw_data/OUTPUTEVENTS.csv.gz')\n output_counts = output_events.groupby('ITEMID').count().sort_values(by=[\"ROW_ID\"],ascending =False)\n output_counts.to_csv(\"./raw_data/OutputCounts.csv\")\n print(\"OutputCounts.csv saved.\")\n\n# load chartevents table and get the number of each item\ndef count_chart_events(): \n filename = \"./raw_data/CHARTEVENTS.csv.gz\"\n chunksize = 10000000\n counter = 0\n # split chartevents table intp multiple chunks\n for chunk in pd.read_csv(filename, chunksize=chunksize):\n chunk.to_csv(\"./raw_data/ChartChunk\"+str(counter)+\".csv\")\n print(\"ChartChunk\"+str(counter)+\" saved.\")\n counter = counter+1\n NUM_CHUNK = counter\n\n # count the number of each item in each chunk and save the result\n counter = 0\n for chunk in pd.read_csv(filename, chunksize=chunksize):\n chunk_count = chunk.groupby('ITEMID').count()\n chunk_count.to_csv(\"./raw_data/ChunkCount\"+str(counter)+\".csv\")\n counter = counter+1\n print(\"ChunkCount\"+str(counter)+\" saved.\")\n\n # load all ChunkCount*.csv files and calculate the total count of each item\n filename = \"./raw_data/ChunkCount0.csv\"\n total_counts = pd.read_csv(filename)\n for counter in range(1,counter):\n filename = \"./raw_data/ChunkCount\"+str(counter)+\".csv\"\n temp = pd.read_csv(filename)\n total_counts = total_counts.append(temp)\n print(\"Finished loading ChunkCount\"+str(counter))\n total_counts = total_counts.groupby(\"ITEMID\").sum()\n total_counts = total_counts.sort_values(by=[\"ROW_ID\"],ascending =False)\n total_counts.to_csv(\"./raw_data/ChunkTotalCount.csv\")\n print(\"Saved the total count into ChunkTotalCount.csv\")\n\n\ndef save_output_events():\n # load the ouput events items corresponding to SAP-II \n filename = \"./raw_data/OUTPUTEVENTS.csv.gz\"\n item_list_sap = [40055, 43175, 40069, 40094, 40715, 40473, 40085, 40057, 40056, 40405, 40428, 40086, 40096, 40651, 226559, 226560, 226561, 226584, 226563, 226564, 226565, 226567, 226557, 226558, 227488, 227489]\n lab = pd.read_csv(filename)\n for ITEMID in item_list_sap:\n item= lab[lab[\"ITEMID\"]== ITEMID][[\"ROW_ID\",\"SUBJECT_ID\",\"HADM_ID\",\"ITEMID\",\"CHARTTIME\",\"VALUE\",\"VALUEUOM\"]]\n item.to_csv(\"./raw_data/rawTemp\"+str(ITEMID)+\".csv\")\n print(\"Saved rawTemp\"+str(ITEMID)+\".csv\")\n \n # load 2 ouput events items with least missing values\n item_list = [40055, 40069]\n lab = pd.read_csv(filename)\n for ITEMID in item_list:\n if ITEMID not in item_list_sap:\n item= lab[lab[\"ITEMID\"]== ITEMID][[\"ROW_ID\",\"SUBJECT_ID\",\"HADM_ID\",\"ITEMID\",\"CHARTTIME\",\"VALUE\",\"VALUEUOM\"]]\n item.to_csv(\"./raw_data/rawTemp\"+str(ITEMID)+\".csv\")\n print(\"Saved rawTemp\"+str(ITEMID)+\".csv\")\n\n# load the lab events items corresponding to SAP-II \ndef save_lab_sap_events():\n filename = \"./raw_data/LABEVENTS.csv.gz\"\n item_list_sap = [50821, 50816, 51006, 51300, 51301, 50882, 950824, 50983, 50822, 50971, 50885]\n lab = pd.read_csv(filename)\n for ITEMID in item_list_sap:\n item= lab[lab[\"ITEMID\"]== ITEMID][[\"ROW_ID\",\"SUBJECT_ID\",\"HADM_ID\",\"ITEMID\",\"CHARTTIME\",\"VALUE\",\"VALUENUM\",\"VALUEUOM\"]]\n item.to_csv(\"./raw_data/rawTemp\"+str(ITEMID)+\".csv\")\n print(\"Saved rawTemp\"+str(ITEMID)+\".csv\")\n \n# load 20 lab events items with least missing values\ndef save_lab_other_events():\n item_list_sap = [50821, 50816, 51006, 51300, 51301, 50882, 950824, 50983, 50822, 50971, 50885]\n item_list = [51221, 50912, 50902, 51265, 50868, 51222, 50931, 51249, 51279, 51248,\n 51006, 51301, 50882, 50983, 50822, 50971,50885, 50821, 50816]\n filename = \"./raw_data/LABEVENTS.csv.gz\"\n lab = pd.read_csv(filename)\n for ITEMID in item_list:\n if ITEMID not in item_list_sap:\n item= lab[lab[\"ITEMID\"]== ITEMID][[\"ROW_ID\",\"SUBJECT_ID\",\"HADM_ID\",\"ITEMID\",\"CHARTTIME\",\"VALUE\",\"VALUENUM\",\"VALUEUOM\"]]\n item.to_csv(\"./raw_data/rawTemp\"+str(ITEMID)+\".csv\")\n print(\"Saved rawTemp\"+str(ITEMID)+\".csv\")\n \n\ndef save_chart_events():\n # load the chart events items corresponding to SAP-II \n item_list_sap = [723, 454, 184, 223900, 223901, 220739,\n 51, 442, 455, 6701, 220179, 220050,\n 211, 220045, 678, 223761, 676, 223762,\n 223835, 3420, 3422, 190]\n filename = \"./raw_data/ChartChunk0.csv\"\n for ITEMID in item_list_sap:\n item = pd.read_csv(filename)\n item = item[item[\"ITEMID\"]== ITEMID][[\"ROW_ID\",\"SUBJECT_ID\",\"HADM_ID\",\"ICUSTAY_ID\",\"ITEMID\",\"CHARTTIME\",\"VALUE\",\"VALUENUM\",\"VALUEUOM\"]]\n for counter in range(1, NUM_CHUNK):\n filename = \"./raw_data/ChartChunk\"+str(counter)+\".csv\"\n temp = pd.read_csv(filename)\n temp = temp[temp[\"ITEMID\"]== ITEMID][[\"ROW_ID\",\"SUBJECT_ID\",\"HADM_ID\",\"ICUSTAY_ID\",\"ITEMID\",\"CHARTTIME\",\"VALUE\",\"VALUENUM\",\"VALUEUOM\"]]\n item = item.append(temp)\n item.to_csv(\"./raw_data/rawTemp\"+str(ITEMID)+\".csv\")\n print(\"Saved rawTemp\"+str(ITEMID)+\".csv\")\n\n # load 50 chart events items with least missing values\n item_list = [646, 618, 212, 161, 128, 550, 1125, 159,\n 1484, 51, 8368, 52, 5815, 8549, 5820,8554,5819,8553,\n 834, 3450, 8518, 3603, 581, 3609, 8532,455, 8441, 456,\n 31, 5817, 8551, 113, 1703, 467, 80, 1337, 674, 432,\n 5813, 8547,617, 210, 637, 184, 723, 454, 198, 707,\n 704, 479, 54, 32, 547, 154, 676, 442, 678, 3420]\n filename = \"./raw_data/ChartChunk0.csv\"\n for ITEMID in item_list:\n if ITEMID not in item_list_sap: \n item = pd.read_csv(filename)\n item = item[item[\"ITEMID\"]== ITEMID][[\"ROW_ID\",\"SUBJECT_ID\",\"HADM_ID\",\"ICUSTAY_ID\",\"ITEMID\",\"CHARTTIME\",\"VALUE\",\"VALUENUM\",\"VALUEUOM\"]]\n for counter in range(1, NUM_CHUNK):\n filename = \"./raw_data/ChartChunk\"+str(counter)+\".csv\"\n temp = pd.read_csv(filename)\n temp = temp[temp[\"ITEMID\"]== ITEMID][[\"ROW_ID\",\"SUBJECT_ID\",\"HADM_ID\",\"ICUSTAY_ID\",\"ITEMID\",\"CHARTTIME\",\"VALUE\",\"VALUENUM\",\"VALUEUOM\"]]\n item = item.append(temp)\n item.to_csv(\"./raw_data/rawTemp\"+str(ITEMID)+\".csv\")\n print(\"Saved rawTemp\"+str(ITEMID)+\".csv\")\n\n\nif __name__ == \"__main__\":\n count_label_events()\n count_output_events()\n count_chart_events()\n save_output_events()\n print(\"Finish saving all output events.\")\n save_lab_sap_events()\n save_lab_other_events()\n print(\"Finish saving all lab events.\")\n save_chart_events()\n","repo_name":"wolight/733MIMIC_analysis","sub_path":"load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":7122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"41086760483","text":"from scipy import *\nfrom newton import newton\nfrom matplotlib import pyplot\n\n\n# Define your functions to test Newton on. You'll need to\n# define two other functions for f(x) = x and f(x) = sin(x) + cos(x**2)\n\ndef f1(x, d):\n if d == 0:\n return x ** 2\n elif d == 1:\n return 2 * x\n\n\ndef f2(x, d):\n if d == 0:\n return x\n elif d == 1:\n return 1\n\n\ndef f3(x, d):\n if d == 0:\n return sin(x) + cos(x ** 2)\n elif d == 1:\n return cos(x) - 2 * x * sin(x ** 2)\n\n\n# We use this function to determine whether our function converges linearly.\n# If the values are consistently between 1 & 0 we can say the function converges linearly.\ndef calculate_k1(data):\n k1_values = []\n for i in range(0, len(data) - 2):\n err1 = abs(data[i + 2] - data[i + 1])\n err2 = abs(data[i + 1] - data[i])\n k1_values.append(err1 / err2)\n return k1_values\n\n\ndef calculate_k2(data):\n k2_values = []\n for i in range(0, len(data) - 2):\n err1 = abs(data[i + 2] - data[i + 1])\n err2 = abs(data[i + 1] - data[i]) ** 2\n k2_values.append(err1 / err2)\n return k2_values\n\n\nfcn_list = [f1, f2, f3]\n\ni = 0\nx0 = -0.5\nfor fcn in fcn_list:\n data = newton(fcn, x0, (10 ** -10), 50)\n\n # Here, you can post-process data, and test convergence rates\n h = linspace(1, 0, len(data[:, 1])) # len(k))\n pyplot.figure(i + 1)\n pyplot.loglog(h, h, h, h ** 2, h, data[:, 1])\n pyplot.xlabel('1 > x > 0')\n pyplot.ylabel('Error in approximation')\n pyplot.legend(['linear', 'quadratic', 'data']) # pyplot.show() #\n pyplot.savefig('fig' + str(i) + '.png', dpi=500, format='png', bbox_inches='tight', pad_inches=0.0)\n\n k1 = calculate_k1(data[:, 0])\n k2 = calculate_k2(data[:, 0])\n\n h = linspace(0, 1, len(k1))\n pyplot.figure(i + 4)\n pyplot.plot(h, h, h, k1)\n pyplot.xlabel('0 < x < 1')\n pyplot.ylabel('linearly convergent: k values')\n pyplot.legend(['y=x', 'data'])\n pyplot.savefig('k1_fig' + str(i) + '.png', dpi=500, format='png', bbox_inches='tight', pad_inches=0.0)\n\n h = linspace(0, 1, len(k2))\n pyplot.figure(i + 4)\n pyplot.plot(h, h, h, k2)\n pyplot.xlabel('0 < x < 1')\n pyplot.ylabel('quadratically convergent: k values')\n pyplot.legend(['y=x', 'data'])\n pyplot.savefig('k2_fig' + str(i) + '.png', dpi=500, format='png', bbox_inches='tight', pad_inches=0.0)\n\n # Also, use your skills from the last lab, and use savetxt() to dump\n # data and/or convergence rates to a text file\n savetxt('data' + str(i) + '.tex', data, fmt='%.5e', delimiter=' & ', newline='\\\\\\\\\\n')\n savetxt('k1_data' + str(i) + '.tex', k1, fmt='%.5e', delimiter=' & ', newline='\\\\\\\\\\n')\n savetxt('k2_data' + str(i) + '.tex', k2, fmt='%.5e', delimiter=' & ', newline='\\\\\\\\\\n')\n\n i += 1\n","repo_name":"jacobdhurst/Coursework","sub_path":"CS471-ScientificComputing/Homework2/code/drive_newton.py","file_name":"drive_newton.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"20041440425","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 23 15:42:22 2016\n\n@author: emg\n\"\"\"\n\nimport pandas as pd\n\ndf = pd.read_csv('/Users/emg/Programmming/GitHub/dissertation/data_handling/practice_data.csv', index_col=0)\n\nlink_ids = test.link_id.str.split('_', expand=True)[1].sort_values()\nparent_ids = test.p_id.sort_values()\n\n# check that parent comments in dataset\n\nx = parent_ids.isin(link_ids)\n\n\ndf['p_in_list'] = df.parent_id.isin(df.link_id)\ndf.sum()['p_in_list'] # 310\n\n\n# top level comment\n# parent id t1 = top, t3 = not\n# create varaible for t1 or t3\n# then convert to binart\np = df.parent_id.str.split('_', expand=True)\ndf['p_level'] = p[0]\ndf['p_id'] = p[1]\nx = pd.get_dummies(df['p_level'])\ndf['top'] = x['t1']\ndf['not_top'] = (df['top'] - 1) * -1\n\ndf['mod'] = pd.get_dummies(df['distinguished'])\ndf['not_mod'] = (df['mod'] - 1) * -1\n\nall_tops = df[df.p_level=='t1']\nall_tops['top_count'] = all_tops.groupby('subreddit')['subreddit'].transform('count')\nsub_tops = all_tops.drop_duplicates(subset='subreddit')\n\ndf['top_count'] = all_tops.top_count\n\ndf.to_csv('practice_data.csv')\n","repo_name":"ellamguest/dissertation","sub_path":"data_handling/top_data.py","file_name":"top_data.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"67"} +{"seq_id":"16262216559","text":"# yahoo finance\n# https://finance.yahoo.com/quote/%5EN225/history?period1=1472655600&period2=1567263600&interval=1d&filter=history&frequency=1d\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\nfrom pandas.plotting import autocorrelation_plot\nfrom pandas.plotting import scatter_matrix\n# ダウンロードしてきたやつ\n# INDEIES = [\"N225\", # Nikkei 225, Japan\n# \"HSI\", # Hang Seng, Hong Kong\n# \"GDAXI\", # DAX, German\n# \"DJI\", # Dow, US\n# \"GSPC\", # S&P 500, US\n# \"BVSP\", # BOVESPA, Brazil\n# \"IXIC\" # IXIC\n# ]\n\nINDEIES = [\n \"HSI\",\n \"GSPC\", # S&P 500, US\n # \"N225\",\n \"BVSP\",\n \"IXIC\"\n ]\n\ndef study():\n closing = pd.DataFrame()\n closing_bk = pd.DataFrame()\n for index in INDEIES:\n # na_valuesは文字列\"null\"のとき空として扱う CSVみるとnullって書いてあります。\n df = pd.read_csv(\"./data/\" + index + \".csv\", na_values=[\"null\"])\n df[\"Date\"] = pd.to_datetime(df[\"Date\"])\n df = df.set_index(\"Date\")\n closing[index] = df[\"Close\"]\n closing_bk[index] = df[\"Close\"]\n print(\"original:\", closing[index])\n #空の部分は古いので埋める。\n closing = closing.fillna(method=\"ffill\")\n print(closing.describe())\n for index in INDEIES:\n closing[index] = closing[index] / max(closing[index])\n closing_bk[index] = closing_bk[index] / max(closing_bk[index])\n closing[index] = np.log(closing[index] / closing[index].shift())\n # 关闭下面的2行,相关度就会下降,还是打开的好。1表示完成相关,-1表示完全不相关\n if index is not \"HSI\": # これと\n closing[index] = closing[index].shift() # これ追加\n\n print(\"start--显示相关度--:\\n\", closing.corr()[\"HSI\"])\n print(\"end--------------\")\n # start ------------:\n # HSI 1.000000\n # GSPC 0.329244\n # BVSP 0.257701\n # IXIC 0.322970\n # Name: HSI, dtype: float64\n\n #グラフ表示\n closing.plot()\n # plt.show()\n\n #自己相関\n fig = plt.figure()\n # 通过设定width和height来设定输出图片的尺寸\n fig.set_figwidth(5)\n fig.set_figheight(5)\n for index in INDEIES:\n autocorrelation_plot(closing[index], label=index)\n # plt.show()\n\n # sin図\n fig = plt.figure()\n # 通过设定width和height来设定输出图片的尺寸\n fig.set_figwidth(5)\n fig.set_figheight(5)\n for index in INDEIES:\n x = closing_bk[index]\n print(\"x:\", x)\n y = np.sin(x)\n print(\"y:\", y)\n plt.plot(x, y)\n # plt.show()\n\n #散布図行列\n # 通过设定figsize来设定输出图片的尺寸\n scatter_matrix(closing, figsize=(20, 20), diagonal='kde')\n plt.show()\n\n\nif __name__ == \"__main__\":\n study()\n","repo_name":"qiulongquan/keras_sample","sub_path":"OANDA_sample/v20-python-samples/goognet.py","file_name":"goognet.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"27307983386","text":"from flask_sqlalchemy import SQLAlchemy\r\nfrom flask import Flask, render_template, request\r\n\r\napp = Flask(__name__)\r\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cadastros.db'\r\ndb = SQLAlchemy(app)\r\n\r\nclass Cadastro(db.Model):\r\n __tablename__ = 'cadastro'\r\n id = db.Column(db.Integer, primary_key=True)\r\n codigo = db.Column(db.String(10))\r\n nome = db.Column(db.String(100))\r\n cargo = db.Column(db.String(100))\r\n loja = db.Column(db.String(100))\r\n salario = db.Column(db.Float)\r\n\r\n def __init__(self, codigo, nome, cargo, loja, salario):\r\n self.codigo = codigo\r\n self.nome = nome\r\n self.cargo = cargo\r\n self.loja = loja\r\n self.salario = salario\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n@app.route('/cadastro', methods=['POST'])\r\ndef cadastrar():\r\n codigo = request.form['codigo']\r\n nome = request.form['nome']\r\n cargo = request.form['cargo']\r\n loja = request.form['loja']\r\n salario = request.form['salario']\r\n\r\n novo_cadastro = Cadastro(codigo=codigo, nome=nome, cargo=cargo, loja=loja, salario=salario)\r\n db.session.add(novo_cadastro)\r\n db.session.commit()\r\n\r\n return \"Cadastro realizado com sucesso!\"\r\n\r\n@app.route('/empregados')\r\ndef listar_empregados():\r\n empregados = Cadastro.query.all()\r\n return render_template('cadastros.html', empregados=empregados)\r\n\r\nif __name__ == '__main__':\r\n with app.app_context():\r\n db.create_all()\r\n app.run()\r\n","repo_name":"ErickSantiago0013/TESTE01","sub_path":"FALTAS/projetos/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"42894426984","text":"n = int(input())\nabn = [list(map(int, input().split())) for _ in range(n)]\ninfo_n = []\nsum_aoki = 0\nfor ab in abn:\n c = ab[0] + ab[1]\n d = ab[0] * 2 + ab[1]\n info_n.append([ab[0], ab[1], c, d])\n sum_aoki += ab[0]\n\ninfo_n = sorted(info_n, key=lambda x: x[3], reverse=True)\ncount = 0\nvote_t = 0\nvote_a = sum_aoki\nfor info in info_n:\n vote_t += info[2]\n vote_a -= info[0]\n count += 1\n if vote_t > vote_a:\n break\nprint(count)\n","repo_name":"atariso/atcoder","sub_path":"contest/ABC_187_0102/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73182521181","text":"# Simple script that can run without instruements\n\nfrom pyslave.data import xy\n\nfig, ax = subplots()\nvalues_to_scan = np.linspace(0,1,100)\nvalues_measured = ones_like(values_to_scan)*nan\n\n#main\nfor i, x in enumerate(values_to_scan) :\n # Fake measurement\n values_measured[i] = sin(x)\n #disp('Step #{0}'.format(i))\n\n # Plot the data\n ax.clear()\n ax.plot(values_to_scan, values_measured)\n #draw\n\n #looptime?\n #pause?\n #abort?\n\n# Save data\ndata = xy(x=values_to_scan, y=values_measured)\ndata.save('mydata.txt')\n","repo_name":"NS2LPS/pyslave","sub_path":"pyslave/examples/simple_plot.py","file_name":"simple_plot.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"27724650808","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nEste é um arquivo de script temporário.\n\"\"\"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nx = [1, 2, 3, 4, 5, 6, 7]\ny = [0, 0, 0, 0, 0, 0, 0]\nfor i in x:\n y[i - 1] = -4 * i + 1,5\n i = i + 1\n\nplt.plot(y, 'k-D')\n \n","repo_name":"brbxd/Codigos","sub_path":"Python/code12.py","file_name":"code12.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"32220151980","text":"#! /usr/bin/env python\nimport serial\nimport urllib2\nimport json\nimport argparse\nimport logging\nimport os\nimport time\nimport signal\nimport sys\nfrom pprint import pprint\n\ndef exit_handler(signal, frame):\n sys.exit(0)\n\ndef health(myteam, theirteam, final):\n if (final):\n if (myteam>theirteam):\n return 'w'\n if (myteam==theirteam):\n return 't'\n return 'l' \n if (myteam==theirteam):\n return 'c'\n if (myteam-theirteam>9):\n return 'e'\n if (myteam-theirteam>0):\n return 'd'\n if (theirteam-myteam>9):\n return 'a'\n if (theirteam-myteam>0):\n return 'b'\n\nsignal.signal(signal.SIGINT, exit_handler)\nsignal.signal(signal.SIGTERM, exit_handler)\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(\n description='Script to fetch sports scores and push to serial port'\n )\n\n parser.add_argument(\n '-d', '--device',\n help='device name',\n type=str,\n default=\"/dev/tty.usbserial-AD0265VB\"\n )\n\n parser.add_argument(\n '-t', '--team',\n help='team name',\n type=str,\n default=\"OAK\"\n )\n\n\n parser.add_argument(\n '-v', '--verbose',\n help='verbose output',\n action=\"store_true\"\n )\n\n parser.add_argument(\n '--once',\n help='run once',\n action=\"store_true\"\n )\n\n parser.add_argument(\n '--delay',\n help='refresh delay',\n type=int,\n default=5\n )\n\n args = parser.parse_args()\n\n logging.basicConfig(\n format='%(asctime)s %(levelname)s: %(message)s',\n level = logging.DEBUG if args.verbose else logging.ERROR\n )\n\n API_URL = \"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D%22http%3A%2F%2Fwww.nfl.com%2Fliveupdate%2Fscorestrip%2Fss.xml%22%20%20and%20itemPath%3D%22%2F%2Fg%5B%40h%3D'\" + args.team + \"'%20or%20%40v%3D'\" + args.team + \"'%5D%5B1%5D%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=\"\n\n ser = serial.Serial(\n port = args.device,\n baudrate = 9600,\n parity = serial.PARITY_NONE,\n stopbits = serial.STOPBITS_ONE,\n bytesize = serial.EIGHTBITS\n )\n time.sleep(1)\n\n state = False\n while ( True ):\n scores = {}\n isfinal = False\n request = urllib2.Request( API_URL )\n response = urllib2.urlopen( request )\n data = json.loads( response.read() )\n\n results = data[ 'query' ]['results']\n scores[results['g']['h']] = int(results['g']['hs'])\n scores[results['g']['v']] = int(results['g']['vs'])\n if (results['g']['q'] == 'F'):\n isfinal = True\n else:\n isfinal = False\n pprint(scores)\n\n\n logging.debug( 'Sending to {device}: {char}'.format( device = args.device, char = state ) )\n ser.write( health (scores['OAK'], scores['WAS'], isfinal) )\n\n if ( args.once ):\n break\n \n time.sleep( args.delay )","repo_name":"melissaw/SportsFanCap","sub_path":"GetScore.py","file_name":"GetScore.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28281661103","text":"import os\nimport random\nimport datetime\nimport shutil\nimport glob2\nimport queue\nfrom chinese_calendar import is_workday\nfrom datetime import timedelta\n\nbegin_str = \"2022/07/30\"\nend_str = \"2022/11/19\"\nbegin_hour = 9\nend_hour = 17\nis_955 = True\nsrc_root = \"D:/project_2022/code\"\ndis_root = \"D:/project_2022/empty\"\ndate_template = \"%Y/%m/%d\"\ntime_template = \"%02d.%02d\"\n\nbegin = datetime.datetime.strptime(begin_str, date_template)\nend = datetime.datetime.strptime(end_str, date_template)\nchoose = begin\nchoose_str = choose.strftime(date_template)\n\nwork_list = []\nwhile choose_str != end_str:\n choose_str = choose.strftime(date_template)\n work = True\n if is_955 and not is_workday(choose):\n work = False\n\n if not work:\n choose = choose + timedelta(days=1)\n continue\n\n times = random.randint(2, 3)\n\n for i in range(times):\n hour = random.randint(9, 17)\n minute = random.randint(0, 59)\n work_list.append([choose_str, time_template % (hour, minute)])\n\n choose = choose + timedelta(days=1)\nprint(work_list)\nprint(len(work_list))\n\ntask_list = []\ncode_list = glob2.glob(src_root+'/**')\nfor code_file in code_list:\n if os.path.isdir(code_file):\n continue\n src_dir = os.path.dirname(code_file)\n dis_file = code_file.replace(src_root, dis_root)\n dis_dir = src_dir.replace(src_root, dis_root)\n\n if not os.path.exists(dis_dir):\n os.makedirs(dis_dir)\n shutil.copy(code_file, dis_file)\n task_list.append([dis_file.replace(dis_root, '').replace(\"\\\\\", '/').strip('/'), os.path.basename(dis_file)])\nprint(task_list)\nprint(len(task_list))\n\nbase_commit_times = len(task_list)//len(work_list)\nif base_commit_times == 0:\n base_commit_times = 1\n commit_time_sum = len(task_list)\nelse:\n commit_time_sum = len(work_list)\ncommit_list = [base_commit_times for i in range(commit_time_sum)]\nmore_commit = len(task_list)-len(work_list) * base_commit_times\nif more_commit > 0:\n for i in range(more_commit):\n commit_list[i] += 1\n\nrandom.shuffle(commit_list)\n\nprint(commit_list)\nprint(sum(commit_list))\n\ntask_queue = queue.Queue()\nfor task in task_list:\n task_queue.put(task)\n\ntime_queue = queue.Queue()\nfor time in work_list:\n time_queue.put(time)\n\nfor commit_time in commit_list:\n time = time_queue.get()\n os.system('time {}'.format(time[1]))\n os.system('date {}'.format(time[0]))\n for i in range(commit_time):\n task = task_queue.get()\n os.system(\n f'cd {dis_root} && git add {task[0]}')\n os.system(\n f'cd {dis_root} && git commit -m \"add {task[1]}\" ')\n\n","repo_name":"mac404-icu/git_water","sub_path":"git_upload.py","file_name":"git_upload.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"11921705241","text":"from BeautifulSoup import BeautifulSoup\nimport mechanize\nimport smtplib\nfrom StringIO import StringIO\nfrom PIL import Image\nfrom CaptchaParser import CaptchaParser\nfrom pprint import pprint\nimport cookielib\nimport json\nimport textmyself\nimport sys, getopt\nfrom clint.textui import colored, puts\nfrom clint import arguments\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n\nimport os\nREGNO = ''\nPASSWORD = ''\nfacultyInfo = []\n\n\ndef login():\n br = mechanize.Browser()\n br.set_handle_redirect(True)\n br.set_handle_referer(True)\n cj = cookielib.CookieJar()\n br.set_cookiejar(cj)\n response = br.open('https://vtop.vit.ac.in/student/stud_login.asp')\n html = response.read()\n soup = BeautifulSoup(html)\n im = soup.find('img', id='imgCaptcha')\n image_response = br.open_novisit(im['src'])\n img = Image.open(StringIO(image_response.read()))\n parser = CaptchaParser()\n captcha = parser.getCaptcha(img)\n br.select_form('stud_login')\n br.form['regno'] = REGNO\n br.form['passwd'] = PASSWORD\n br.form['vrfcd'] = str(captcha)\n br.submit()\n if br.geturl() == 'https://vtop.vit.ac.in/student/home.asp':\n puts(colored.yellow(\"LOGIN SUCCESSFUL\"))\n return br\n else:\n return None\n\n\ndef parseFacultyPage(br, facultyID):\n if br is None:\n return None\n\n br.open('https://vtop.vit.ac.in/student/stud_home.asp')\n response = br.open('https://vtop.vit.ac.in/student/class_message_view.asp?sem=' + facultyID)\n html = response.read()\n soup = BeautifulSoup(html)\n tables = soup.findAll('table')\n\n # Extracting basic information of the faculty\n infoTable = tables[0].findAll('tr')\n name = infoTable[2].findAll('td')[0].text\n if (len(name) is 0):\n return None\n subject = infoTable[2].findAll('td')[1].text\n msg = infoTable[2].findAll('td')[2].text\n sent = infoTable[2].findAll('td')[3].text\n emailmsg = 'Subject: New VIT Email' + msg\n\n with open('output/WS.json') as data_file:\n data = json.load(data_file)\n if data[\"date\"] == sent or data['message'] == msg:\n outputpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output')\n if os.path.isdir(outputpath) is False:\n os.makedirs(outputpath)\n result = {'name': name, 'subject': subject, 'message': msg, 'date': sent}\n with open('output/' + str(facultyID) + '.json', 'w') as outfile:\n json.dump(result, outfile, indent=4)\n print('email already sent')\n return result\n\n else:\n outputpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output')\n if os.path.isdir(outputpath) is False:\n os.makedirs(outputpath)\n result = {'name': name, 'subject': subject, 'message': msg, 'date': sent}\n with open('output/' + str(facultyID) + '.json', 'w') as outfile:\n json.dump(result, outfile, indent=4)\n you = \"rahulkapoorbbps@outlook.com\"\n me = \"hootpile@gmail.com\"\n s = smtplib.SMTP('smtp.gmail.com', 587)\n s.ehlo()\n s.starttls()\n s.login('hootpile@gmail.com','rahulkapoor23')\n s.sendmail(me, you, emailmsg)\n s.quit()\n print('sent email and text message')\n textmyself.textmyself(msg)\n return result\n\n\ndef aggregate():\n br = login()\n result = parseFacultyPage(br, \"WS\")\n if result is not None:\n puts(colored.green(\"Parsed a new fucking Message\"))\n else:\n puts(colored.red('There is nothing new available.'))\n\n\nif __name__ == '__main__':\n args = arguments.Args()\n REGNO = args.get(0)\n PASSWORD = args.get(1)\n aggregate()\n","repo_name":"rahulkapoor90/AutomateVIT","sub_path":"Get new Faculty message/parseFacultyInfo.py","file_name":"parseFacultyInfo.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"31087573265","text":"# -*- coding: utf-8 -*-\nimport os, sys\nimport yaml\nimport subprocess\nimport json\nimport pathlib\nfrom multiprocessing import Pool\nimport re\nimport time\nfrom netaddr import *\nimport geoip2.database\nimport ssdeep\nfrom hdfs import InsecureClient\n\nclass pcap_parser:\n def __init__ (self, pcap):\n self.pcap = pcap\n self.pcap_json = list()\n self.city_reader = geoip2.database.Reader('/home/antslab/GeoIP2-DB/GeoIP2-City_20200526/GeoIP2-City.mmdb')\n self.domain_reader = geoip2.database.Reader('/home/antslab/GeoIP2-DB/GeoIP2-Domain_20200526/GeoIP2-Domain.mmdb')\n self.isp_reader = geoip2.database.Reader('/home/antslab/GeoIP2-DB/GeoIP2-ISP_20200526/GeoIP2-ISP.mmdb')\n self.city_reader_response = dict()\n self.domain_reader_response = dict()\n self.isp_reader_response = dict()\n try:\n with open(os.path.join('src','settings.yml'), 'r', encoding='utf-8') as v:\n self.yaml = yaml.safe_load(v)\n except:\n return None\n\n def proc(self):\n self.parse()\n for record in self.json:\n # 將packet中的payload convert to ssdeep hash value\n try:\n record['_source']['layers']['tcp.payload'][0] = ssdeep.hash(record['_source']['layers']['tcp.payload'][0])\n record['_source']['layers']['tcp.payload'].append(record['_source']['layers']['frame.time_epoch'][0])\n record['_source']['layers']['tcp.payload'].append(record['_source']['layers']['tcp.len'][0])\n except:\n pass\n try:\n if self.IOfilter(record['_source']['layers']['ip.dst'][0]): # ip.src is external\n record['_source']['layers']['isInternal'] = False\n # get external ip geoinfo(ip.src)\n record = self.getGeoInfo(record, record['_source']['layers']['ip.src'][0], self.city_reader, self.domain_reader, self.city_reader_response, self.domain_reader_response)\n self.pcap_json.append(record)\n else: # ip.src is internal\n record['_source']['layers']['isInternal'] = True\n # get external ip geoinfo(ip.dst)\n record = self.getGeoInfo(record, record['_source']['layers']['ip.dst'][0], self.city_reader, self.domain_reader, self.city_reader_response, self.domain_reader_response)\n self.pcap_json.append(record)\n except:\n pass\n return self.pcap_json\n \n def parse(self):\n cmd = [\"tshark\",\"-r\",self.pcap, \"-T\", \"json\", \"-e\", \"frame.time_epoch\", \"-e\",\"frame.number\",\"-e\",\"frame.time\",\"-e\",\"frame.protocols\",\"-e\",\"ip.src\",\"-e\",\"ip.dst\",\"-e\",\"ip.proto\",\"-e\",\"tcp.srcport\",\"-e\",\"tcp.dstport\",\"-e\",\"frame.len\",\"-e\", \"udp.length\", \"-e\",\"tcp.len\", \"-e\", \"tcp.hdr_len\", \"-e\", \"udp.srcport\", \"-e\", \"udp.dstport\", \"-e\", \"icmp.length\", \"-e\", \"icmp.length.original_datagram\", \"-e\", \"tcp.payload\"]\n p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stdin = subprocess.PIPE)\n (output, err) = p.communicate()\n self.json = json.loads(output)\n \n def IOfilter(self, ip):\n isInbound = False\n for netrange in self.yaml['Trap']:\n if IPAddress(ip) in IPNetwork(netrange):\n isInbound = True\n break\n return isInbound\n \n def getGeoInfo(self, record, ip, city_reader, domain_reader, city_reader_response, domain_reader_response):\n # city_info\n if ip in city_reader_response:\n try:\n record['_source']['layers']['country'] = city_reader_response[ip].country.name\n except:\n record['_source']['layers']['country'] = None\n try:\n # domain_info\n record['_source']['layers']['domain'] = domain_reader_response[ip].domain\n except:\n record['_source']['layers']['domain'] = None\n try:\n # isp_info\n record['_source']['layers']['isp'] = isp_reader_response[ip].isp\n except:\n record['_source']['layers']['isp'] = None\n else:\n try:\n city_response = city_reader.city(ip)\n self.city_reader_response[ip] = city_response\n record['_source']['layers']['country'] = city_response.country.name\n except: # AddressNotFoundError & ValueError\n record['_source']['layers']['country'] = None\n # domain_info\n try:\n domain_response = domain_reader.domain(ip)\n self.domain_reader_response[ip] = domain_response\n record['_source']['layers']['domain'] = domain_response.domain\n except:\n record['_source']['layers']['domain'] = None\n \n # isp_info\n try:\n isp_response = isp_reader.isp(ip)\n self.isp_reader_response[ip] = isp_response\n record['_source']['layers']['isp'] = isp_response.isp\n except:\n record['_source']['layers']['isp'] = None\n \n return record\n\ndef write2local(pcap, timestamp, pcap_json):\n folder = pcap[:pcap.rfind('.')]\n pathlib.Path(folder).mkdir(parents=True, exist_ok=True)\n with open(os.path.join(folder, timestamp +'.json'), 'w') as f:\n json.dump(pcap_json, f)\n\ndef write2HDFS(folder, timestamp, pcap_json):\n client_hdfs = InsecureClient('http://192.168.50.123:9870', user='hdfs')\n output_path = os.path.join(folder, timestamp + '.json')\n client_hdfs.write(output_path, json.dumps(pcap_json))\n \ndef multiprocessing_parser(pcap, date, ISP):\n s_time = time.time()\n p = pcap_parser(pcap)\n timestamp = pcap.split(\".\")[-1]\n pcap_json = p.proc()\n folder_basename = \"pcap_json\"\n folder = os.path.join(folder_basename, date, ISP)\n write2HDFS(folder, timestamp, pcap_json)\n \nif __name__==\"__main__\":\n s_time = time.time()\n #pcap_dir_path = \"/home/antslab/NAS2_RAID6/pcap_process/2020_01_06/中華電信/snort.2020-01-06_dir/\"\n pcap_dir_path = sys.argv[1]\n ISP = pcap_dir_path.split(\"/\")[-3]\n date = pcap_dir_path.split(\"/\")[-4]\n file_regex = r'snort\\.log\\.[\\d]+'\n pcap_files = sorted([(os.path.join(pcap_dir_path, file), date, ISP) for file in os.listdir(pcap_dir_path) if re.match(file_regex, file)])\n with Pool(processes=8) as p:\n p.starmap(multiprocessing_parser, pcap_files)\n p.close()\n p.join()\n print(\"Total time:\", time.time()-s_time)\n","repo_name":"tychen5/PacketAnalysis","sub_path":"parser_v2.py","file_name":"parser_v2.py","file_ext":"py","file_size_in_byte":6579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"15873812773","text":"import sys\nsys.setrecursionlimit(100000)\n\ninput = sys.stdin.readline\n\ndef dfs(idx, d):\n\n visit[idx] = 1\n depth[idx] = d\n\n for node, dist in tree[idx]:\n if not visit[node]:\n parent[node] = (idx, dist)\n dfs(node, d+1)\n\nn = int(input())\ntree = [list() for _ in range(n+1)]\n\nfor _ in range(n-1):\n a, b, d = map(int, input().split())\n tree[a].append((b, d))\n tree[b].append((a, d))\n\nvisit = [0]*(n+1)\ndepth = [0]*(n+1)\nparent = [tuple() for _ in range(n+1)]\ndfs(1, 0)\n\nminMax = [dict() for i in range(n+1)]\nfor i in range(n, -1, -1):\n node = i\n MIN, MAX = 1000000, 0\n while parent[node]:\n node, dist = parent[node]\n MIN, MAX = min(MIN, dist), max(MAX, dist)\n minMax[i][node] = (MIN, MAX)\n\nk = int(input())\nanswer = []\nfor _ in range(k):\n a, b, = map(int, input().split())\n sA, sB = a, b\n if depth[a] < depth[b]: a, b = b, a\n gap = depth[a]-depth[b]\n while gap:\n a = parent[a][0]\n gap -= 1\n\n while a!=b:\n a = parent[a][0]\n b = parent[b][0]\n\n minA, maxA = minMax[sA][a] if sA!=a else (1000000, 0)\n minB, maxB = minMax[sB][b] if sB!=b else (1000000, 0)\n MIN, MAX = min(minA, minB), max(maxA, maxB)\n answer.append(str(MIN)+\" \"+str(MAX))\n\nprint(\"\\n\".join(answer))","repo_name":"HighMoon0118/BJ_Problems","sub_path":"스터디/BJ_3176.py","file_name":"BJ_3176.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"17551261868","text":"\n\n\nimport googleapiclient.discovery\n\n\nvideo_id = \"xZn_JrIHfDE\"\n\n\nyoutube = googleapiclient.discovery.build(\"youtube\", \"v3\", developerKey = \"AIzaSyBOBGXZBxLxvaTDtIwLz3DC8TNZl7BKZCc\")\n\ndesc_dic = []\n\ntry:\n request = youtube.commentThreads().list( part=\"snippet,replies\", videoId = video_id )\n res = request.execute()\n response = res\n \n for key in res.keys():\n ncoms =(res['pageInfo']['totalResults'])\n for i in range(0,ncoms):\n rpcom = (res['items'][i]['snippet']['topLevelComment'] ['snippet']['textOriginal'])\n print(rpcom) \n \n \n \nexcept:\n print(\"No comments Available\",video_id)\n \n\nprint(desc_dic)\n","repo_name":"Saida-Marzouk/Sentiment-Analysis-youtube-comments","sub_path":"get_comment_vedio.py","file_name":"get_comment_vedio.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39551464531","text":"#!/usr/bin/env python\n\n# url: http://wiki.ros.org/dynamic_reconfigure/Tutorials/SettingUpDynamicReconfigureForANode%28python%29\nimport rospy\n\nfrom dynamic_reconfigure.server import Server\nfrom arduino_msgs.cfg import LI3DSArduinoConfig\n\ndef callback(config, level):\n rospy.loginfo(\"\"\"Reconfigure Request: {camlight_time_between_pics}\"\"\".format(**config))\n return config\n\nif __name__ == \"__main__\":\n rospy.init_node(\"arduino_msgs\", anonymous=True)\n\n srv = Server(LI3DSArduinoConfig, callback)\n rospy.spin()\n","repo_name":"YQBaobao/scrapy-pyqt5","sub_path":"nodes/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73317206299","text":"import json\ndef rangemaker(name,start,end):\n\twith open('vals.json','r') as file:\n\t\tcur_data = json.loads(file.read())\t\n\t\tlst = cur_data.get(name)#cur_data.get(\"squ\")\n\t\tif len(lst)==0 or lst[0] not in range(start,end+1) or lst[-1] not in range(start,end+1):\n\t\t\tlst = list(range(start,end+1))\n\t\treturn lst,cur_data\n\ndef write_range(name,lst,cur_data):\n\twith open('vals.json','w') as f:\n\t\tcur_data[name] = lst\n\t\tf.write(json.dumps(cur_data,indent=2))\n","repo_name":"AshGaur/aptishorttricks","sub_path":"ranger.py","file_name":"ranger.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1413610168","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom rest_framework import generics, permissions, viewsets\nfrom .serializers import UserDataSerializer, RegisterSerializer, UserSerializer\nfrom .models import UserModel\nfrom rest_framework.response import Response\nimport requests\n\n\ndef get_ip(request):\n adress = request.META.get('HTTP_X_FORWARDED_FOR')\n if adress:\n ip = adress.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\n\ndef get_geolocation(request):\n access_key = 'd479f51305bbe0eface1532fecf88001'\n ip = get_ip(request)\n url = f\"http://api.ipstack.com/{ip}?access_key={access_key}\"\n response = requests.get(url)\n response.raise_for_status()\n rawData = response.json()\n ip = rawData['ip']\n continent_name = rawData['continent_name']\n country_name = rawData['country_name']\n region_name = rawData['region_name']\n city = rawData['city']\n zip = rawData['zip']\n latitude = rawData['latitude']\n longitude = rawData['longitude']\n saveNow = UserModel(\n continent_name=continent_name,\n country_name=country_name,\n region_name=region_name,\n city=city,\n zip=zip,\n latitude=latitude,\n longitude=longitude,\n )\n saveNow.save()\n api_response = {\n 'continent_name': continent_name,\n 'country_name': country_name,\n 'region_name': region_name,\n 'zip': zip,\n 'latitude': latitude,\n 'longitude': longitude,\n }\n return JsonResponse(api_response)\n\n\ndef get_geolocation_input_ip(request, ip_input):\n access_key = 'd479f51305bbe0eface1532fecf88001'\n url = f\"http://api.ipstack.com/{ip_input}?access_key={access_key}\"\n response = requests.get(url)\n response.raise_for_status()\n rawData = response.json()\n ip = rawData['ip']\n continent_name = rawData['continent_name']\n country_name = rawData['country_name']\n region_name = rawData['region_name']\n city = rawData['city']\n zip = rawData['zip']\n latitude = rawData['latitude']\n longitude = rawData['longitude']\n saveNow = UserModel(\n continent_name=continent_name,\n country_name=country_name,\n region_name=region_name,\n city=city,\n zip=zip,\n latitude=latitude,\n longitude=longitude,\n )\n saveNow.save()\n api_response = {\n 'continent_name': continent_name,\n 'country_name': country_name,\n 'region_name': region_name,\n 'zip': zip,\n 'latitude': latitude,\n 'longitude': longitude,\n }\n return JsonResponse(api_response)\n\n\nclass AllUsersView(viewsets.ModelViewSet):\n queryset = UserModel.objects.all()\n serializer_class = UserDataSerializer\n permission_classes = [permissions.AllowAny]\n\n\nclass RegisterView(generics.GenericAPIView):\n permission_classes = [permissions.AllowAny]\n serializer_class = RegisterSerializer\n\n def post(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = serializer.save()\n return Response({\n \"user\": UserSerializer(user, context=self.get_serializer_context()).data,\n \"message\": \"User created\",\n })\n\n\nclass ProfileView(generics.GenericAPIView):\n permission_classes = [permissions.IsAuthenticated]\n serializer_class = UserSerializer\n\n def get(self, request, *args, **kwargs):\n return Response({\n \"user\": UserSerializer(request.user, context=self.get_serializer_context()).data,\n })\n","repo_name":"OlegKaliadka/geo_api_data","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35345420809","text":"from django.urls import include, path\n\nfrom rest_framework.routers import DefaultRouter\n\nfrom . import views\n\n# Create a router and register our viewsets with it.\nrouter = DefaultRouter()\nrouter.register(r'posts', views.PostViewSet)\nrouter.register(r'comments', views.CommentViewSet)\nrouter.register(r'users', views.UserViewSet)\n\nurlpatterns = [\n path('', include(router.urls)),\n\n path('dj-rest-auth/', include('dj_rest_auth.urls')),\n path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),\n]\n\nurlpatterns += [\n path('api-auth/', include('rest_framework.urls')),\n]\n","repo_name":"stnslvrzhk/practice","sub_path":"drfapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"8473676570","text":"import sys, copy, optparse, random, re\n\n#a dictionary of all of the xmlns prefixes in a standard inkscape doc\nNSS = {\nu'sodipodi' :u'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',\nu'cc' :u'http://web.resource.org/cc/',\nu'svg' :u'http://www.w3.org/2000/svg',\nu'dc' :u'http://purl.org/dc/elements/1.1/',\nu'rdf' :u'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\nu'inkscape' :u'http://www.inkscape.org/namespaces/inkscape',\nu'xlink' :u'http://www.w3.org/1999/xlink'\n}\n\n#a dictionary of unit to user unit conversion factors\nuuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'pc':15.0}\ndef unittouu(string):\n '''Returns returns userunits given a string representation of units in another system'''\n unit = re.compile('(%s)$' % '|'.join(uuconv.keys()))\n param = re.compile(r'(([-+]?[0-9]+(\\.[0-9]*)?|[-+]?\\.[0-9]+)([eE][-+]?[0-9]+)?)')\n\n p = param.match(string)\n u = unit.search(string) \n if p:\n retval = float(p.string[p.start():p.end()])\n else:\n retval = 0.0\n if u:\n try:\n return retval * uuconv[u.string[u.start():u.end()]]\n except KeyError:\n pass\n return retval\n\ntry:\n import xml.dom.ext\n import xml.dom.minidom\n import xml.dom.ext.reader.Sax2\n import xml.xpath\nexcept:\n sys.exit('The inkex.py module requires PyXML. Please download the latest version from .')\n\ndef debug(what):\n sys.stderr.write(str(what) + \"\\n\")\n return what\n\ndef check_inkbool(option, opt, value):\n if str(value).capitalize() == 'True':\n return True\n elif str(value).capitalize() == 'False':\n return False\n else:\n raise OptionValueError(\"option %s: invalid inkbool value: %s\" % (opt, value))\n\nclass InkOption(optparse.Option):\n TYPES = optparse.Option.TYPES + (\"inkbool\",)\n TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)\n TYPE_CHECKER[\"inkbool\"] = check_inkbool\n\n\nclass Effect:\n \"\"\"A class for creating Inkscape SVG Effects\"\"\"\n def __init__(self, *args, **kwargs):\n self.id_characters = '0123456789abcdefghijklmnopqrstuvwkyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n self.document=None\n self.ctx=None\n self.selected={}\n self.doc_ids={}\n self.options=None\n self.args=None\n self.use_minidom=kwargs.pop(\"use_minidom\", False)\n self.OptionParser = optparse.OptionParser(usage=\"usage: %prog [options] SVGfile\",option_class=InkOption)\n self.OptionParser.add_option(\"--id\",\n action=\"append\", type=\"string\", dest=\"ids\", default=[], \n help=\"id attribute of object to manipulate\")\n def effect(self):\n pass\n def getoptions(self,args=sys.argv[1:]):\n \"\"\"Collect command line arguments\"\"\"\n self.options, self.args = self.OptionParser.parse_args(args)\n def parse(self,file=None):\n \"\"\"Parse document in specified file or on stdin\"\"\"\n reader = xml.dom.ext.reader.Sax2.Reader()\n try:\n try:\n stream = open(file,'r')\n except:\n stream = open(self.args[-1],'r')\n except:\n stream = sys.stdin\n if self.use_minidom:\n self.document = xml.dom.minidom.parse(stream)\n else:\n self.document = reader.fromStream(stream)\n self.ctx = xml.xpath.Context.Context(self.document,processorNss=NSS)\n stream.close()\n def getposinlayer(self):\n ctx = xml.xpath.Context.Context(self.document,processorNss=NSS)\n #defaults\n self.current_layer = self.document.documentElement\n self.view_center = (0.0,0.0)\n\n layerattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:current-layer',self.document,context=ctx)\n if layerattr:\n layername = layerattr[0].value\n layer = xml.xpath.Evaluate('//g[@id=\"%s\"]' % layername,self.document,context=ctx)\n if layer:\n self.current_layer = layer[0]\n\n xattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cx',self.document,context=ctx)\n yattr = xml.xpath.Evaluate('//sodipodi:namedview/@inkscape:cy',self.document,context=ctx)\n if xattr and yattr:\n x = xattr[0].value\n y = yattr[0].value\n if x and y:\n self.view_center = (float(x),float(y))\n def getselected(self):\n \"\"\"Collect selected nodes\"\"\"\n for id in self.options.ids:\n path = '//*[@id=\"%s\"]' % id\n for node in xml.xpath.Evaluate(path,self.document):\n self.selected[id] = node\n def getdocids(self):\n docIdNodes = xml.xpath.Evaluate('//@id',self.document,context=self.ctx)\n for m in docIdNodes:\n self.doc_ids[m.value] = 1\n def output(self):\n \"\"\"Serialize document into XML on stdout\"\"\"\n xml.dom.ext.Print(self.document)\n def affect(self):\n \"\"\"Affect an SVG document with a callback effect\"\"\"\n self.getoptions()\n self.parse()\n self.getposinlayer()\n self.getselected()\n self.getdocids()\n self.effect()\n self.output()\n \n def uniqueId(self, old_id, make_new_id = True):\n new_id = old_id\n if make_new_id:\n while new_id in self.doc_ids:\n new_id = \"%s%s\" % (new_id,random.choice(self.id_characters))\n self.doc_ids[new_id] = 1\n return new_id\n def xpathSingle(self, path):\n try:\n retval = xml.xpath.Evaluate(path,self.document,context=self.ctx)[0]\n except:\n debug(\"No matching node for expression: %s\" % path)\n retval = None\n return retval\n \n","repo_name":"NirBenTalLab/proorigami-cde-package","sub_path":"cde-root/usr/local/apps/inkscape/share/inkscape/extensions/inkex.py","file_name":"inkex.py","file_ext":"py","file_size_in_byte":5722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9711829768","text":"class Solution:\n def isMonotonic(self, nums: List[int]) -> bool:\n inc = dec = True\n for i in range(1, len(nums)):\n if nums[i] > nums[i-1]:\n dec = False\n elif nums[i] < nums[i-1]:\n inc = False\n \n if not inc and not dec:\n return False\n return True\n # def increasing(nums):\n # inc = True\n # for i in range(1, len(nums)):\n # if nums[i] < nums[i-1]:\n # inc = False\n # return inc\n \n # def decreasing(nums):\n # dec = True\n # for i in range(1, len(nums)):\n # if nums[i] > nums[i-1]:\n # dec = False\n # return dec\n \n # return increasing(nums) or decreasing(nums)\n\n \n ","repo_name":"jinaypanchal/LeetCode","sub_path":"0932-monotonic-array/0932-monotonic-array.py","file_name":"0932-monotonic-array.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72713052381","text":"import requests\nimport json\nimport logging\nimport emoji\nimport holidays\nimport datetime\nfrom datetime import timedelta\nfrom Web_Server.web_config import CONFIG_FILE\nfrom System_func.send_telegram_message import Alert\nfrom HappyFox.ticket_utils import TicketUtils\nfrom logger.log_config import setup_logger, get_abs_log_path\n\n\n# Указываем настройки логов для нашего файла с классами\nhf_class_error_logger = setup_logger('HF_class_Error', get_abs_log_path('hf_class-errors.log'), logging.ERROR)\nhf_class_info_logger = setup_logger('HF_class_Info', get_abs_log_path('hf_class-info.log'), logging.INFO)\n\n# Создаем объект класса Alert\nalert = Alert()\n\n\ndef is_business_day(date):\n ru_holidays = holidays.RU()\n if date.weekday() >= 5 or date in ru_holidays:\n return False\n return True\n\n\nclass HappyFoxConnector:\n def __init__(self, config_file):\n try:\n with open(config_file, 'r', encoding='utf-8-sig') as f:\n data_config = json.load(f)\n except FileNotFoundError as error_message:\n hf_class_error_logger.error(f\"Конфигурационный файл не найден: {config_file}. Error: {error_message}\")\n raise\n except json.JSONDecodeError as error_message:\n hf_class_error_logger.error(f\"Ошибка декодирования JSON файла из конфигурации: {config_file}. Error: {error_message}\")\n raise\n self.api_endpoint = data_config['HAPPYFOX_SETTINGS']['API_ENDPOINT']\n self.api_key = data_config['HAPPYFOX_SETTINGS']['API_KEY']\n self.api_secret = data_config['HAPPYFOX_SETTINGS']['API_SECRET']\n self.headers = {'Content-Type': 'application/json'}\n\n\n def get_filtered_tickets(self, start_date, end_date, contact_group_id):\n \"\"\"\n Функция для получения списка тикетов, отфильтрованных по заданным параметрам:\n start_date (str): начальная дата диапазона времени для фильтрации тикетов\n end_date (str): конечная дата диапазона времени для фильтрации тикетов\n contact_group_id (int): ID группы контактов для фильтрации тикетов\n \"\"\"\n url = f\"{self.api_endpoint}/tickets/\"\n page = 1\n all_tickets = []\n\n while True:\n params = {\n 'q': f'last-staff-replied-on-or-after:\"{start_date}\" last-staff-replied-on-or-before:\"{end_date}\"',\n 'page': page,\n 'size': 50\n }\n\n try:\n response = requests.get(url, params=params, auth=(self.api_key, self.api_secret), headers=self.headers, timeout=10)\n response.raise_for_status()\n except requests.exceptions.HTTPError as error_message:\n hf_class_error_logger.error(f\"Ошиба HTTP запроса: {error_message}\")\n break\n except requests.exceptions.Timeout as error_message:\n hf_class_error_logger.error(f\"Ошибка тайм-аута: {error_message}\")\n break\n except requests.exceptions.RequestException as error_message:\n hf_class_error_logger.error(f\"Общая ошибка: {error_message}\")\n break\n\n data = response.json()\n tickets = data['data']\n\n for ticket in tickets:\n if 'user' in ticket and ticket['user'] is not None:\n user = ticket['user']\n if 'contact_groups' in user:\n contact_groups = user['contact_groups']\n if any(contact_group['id'] == contact_group_id for contact_group in contact_groups):\n all_tickets.append(ticket)\n\n if data['page_info']['count'] < 50:\n break\n page += 1\n hf_class_info_logger.info('Вывод тикеты отправлены')\n return all_tickets\n\n\n def get_tickets(self):\n \"\"\"Функция проверки тикетов, у которых нет ответа\"\"\"\n hf_class_info_logger.info('Задача запущена (информация о не отвеченных тикетах за 3 дня)')\n params = {\n 'category': '1',\n 'status': '_pending',\n }\n url = self.api_endpoint + '/tickets/?size=1&page=1'\n try:\n response = requests.get(url, auth=(self.api_key, self.api_secret), headers=self.headers, params=params, timeout=10)\n try:\n response.raise_for_status()\n except requests.exceptions.HTTPError as error_message:\n hf_class_error_logger.error(\"Ошибка HTTP запроса: %s\", error_message)\n return\n except requests.exceptions.Timeout as error_message:\n hf_class_error_logger.error(\"Ошибка тайм-аута: %s\", error_message)\n except requests.exceptions.RequestException as error_message:\n hf_class_error_logger.error(\"Общая ошибка: %s\", error_message)\n \n data_res = response.json()\n page_info = data_res.get('page_info')\n last_index = page_info.get('last_index')\n if last_index == 0:\n print('Нет тикетов')\n else:\n for page in range(last_index):\n url = self.api_endpoint + f'/tickets/?size=1&page={page + 1}'\n # проверка на доступность сервера, если сервер недоступен, выводит ошибку\n try:\n response = requests.get(url, auth=(self.api_key, self.api_secret), headers=self.headers, params=params, timeout=10)\n try:\n response.raise_for_status()\n except requests.exceptions.HTTPError as error_message:\n hf_class_error_logger.error(\"Ошибка HTTP запроса: %s\", error_message)\n return\n except requests.exceptions.Timeout as error_message:\n hf_class_error_logger.error(\"Ошибка тайм-аута: %s\", error_message)\n except requests.exceptions.RequestException as error_message:\n hf_class_error_logger.error(\"Общая ошибка: %s\", error_message)\n data = response.json()\n for ticket_data in data.get('data'):\n self.process_ticket(ticket_data)\n\n\n def get_open_tickets(self):\n \"\"\"Функция получения информации об открытых тикетах\"\"\"\n hf_class_info_logger.info('Задача запущена (информация об открытых тикетах)')\n params = {\n 'category': '1',\n 'status': '_pending',\n }\n url = self.api_endpoint + '/tickets/?size=1&page=1'\n try:\n response = requests.get(url, auth=(self.api_key, self.api_secret), headers=self.headers, params=params, timeout=10)\n try:\n response.raise_for_status()\n except requests.exceptions.HTTPError as error_message:\n hf_class_error_logger.error(\"Ошибка HTTP запроса: %s\", error_message)\n return\n except requests.exceptions.Timeout as error_message:\n hf_class_error_logger.error(\"Ошибка тайм-аута: %s\", error_message)\n except requests.exceptions.RequestException as error_message:\n hf_class_error_logger.error(\"Общая ошибка: %s\", error_message)\n \n data_res = response.json()\n page_info = data_res.get('page_info')\n last_index = page_info.get('last_index')\n if last_index == 0:\n print('Нет открытых тикетов')\n else:\n for page in range(last_index):\n url = self.api_endpoint + f'/tickets/?size=1&page={page + 1}'\n # проверка на доступность сервера, если сервер недоступен, выводит ошибку\n try:\n response = requests.get(url, auth=(self.api_key, self.api_secret), headers=self.headers, params=params, timeout=10)\n try:\n response.raise_for_status()\n except requests.exceptions.HTTPError as error_message:\n hf_class_error_logger.error(\"Ошибка HTTP запроса: %s\", error_message)\n return\n except requests.exceptions.Timeout as error_message:\n hf_class_error_logger.error(\"Ошибка тайм-аута: %s\", error_message)\n except requests.exceptions.RequestException as error_message:\n hf_class_error_logger.error(\"Общая ошибка: %s\", error_message)\n data = response.json()\n for ticket_data in data.get('data'):\n self.process_open_ticket(ticket_data)\n\n\n def process_open_ticket(self, ticket_data):\n \"\"\"Функция по формированию данных об открытом тикете\"\"\"\n try:\n ticket_id = ticket_data.get('id')\n subject = ticket_data.get('subject')\n contact_groups = ticket_data.get('user', {}).get('contact_groups', [])\n company = contact_groups[0].get('name', 'Компания отсутствует') if contact_groups else 'Компания отсутствует'\n status = ticket_data.get('status').get('name')\n # Измененный код для избежания ошибки при отсутствии назначенного исполнителя\n assigned_to = ticket_data.get('assigned_to')\n assigned_name = assigned_to.get('name') if assigned_to else 'Нет исполнителя'\n\n # Получаем последнее сообщение из массива \"updates\"\n updates = ticket_data.get('updates', [])\n if not updates:\n hf_class_error_logger.error(\"Нет доступных обновлений для тикета с ID: %s\", ticket_id)\n return\n\n last_message = None\n last_message_time = None\n for update in reversed(updates):\n message = update.get('message')\n if message:\n text = message.get('text')\n if text:\n last_message = text\n last_message_time = datetime.datetime.strptime(update['timestamp'], \"%Y-%m-%d %H:%M:%S\")\n break\n\n if not last_message or not last_message_time:\n hf_class_error_logger.error(\"Нет доступной информации о последнем сообщении для тикета с ID: %s\", ticket_id)\n return\n\n index = None\n # Проверяем наличие фразы \"С уважением\" в тексте сообщения\n if 'с уважением' in last_message.lower():\n index = last_message.lower().index('с уважением')\n # Если фраза \"С уважением\" не найдена, ищем фразу \"From: Boardmaps Customer Support\"\n elif 'from: boardmaps customer support' in last_message.lower():\n index = last_message.lower().index('from: boardmaps customer support')\n\n if index is not None:\n # Обрезаем сообщение до найденной фразы\n last_message = last_message[:index]\n\n # Обрезаем сообщение до 500 символов\n truncated_message = last_message[:500] + '...' if last_message and len(last_message) > 500 else last_message\n\n today = datetime.date.today()\n last_message_date = last_message_time.date()\n\n # Вычисляем количество рабочих дней между текущей датой и датой последнего сообщения\n business_days = 0\n while today > last_message_date:\n if is_business_day(last_message_date):\n business_days += 1\n last_message_date += datetime.timedelta(days=1)\n\n if business_days > 7:\n date_emoji = emoji.emojize(':no_entry:')\n elif business_days > 3:\n date_emoji = emoji.emojize(':firecracker:')\n else:\n date_emoji = emoji.emojize(':eight_o’clock:')\n\n ticket_info = (\n f\"{emoji.emojize(':eyes:')} Тема: {subject}\\n\"\n f\"{emoji.emojize(':department_store:')} Компания: {company}\\n\"\n f\"{emoji.emojize(':credit_card:')} Статус: {status}\\n\"\n f\"{emoji.emojize(':disguised_face:')} Назначен: {assigned_name}\\n\"\n f\"{date_emoji} Дата: {last_message_time.strftime('%d-%m-%Y %H:%M')}\\n\"\n f\"{emoji.emojize(':envelope_with_arrow:')} Сообщение:\\n\\n\"\n f\"{truncated_message}\"\n )\n # открываем файл и загружаем данные\n with open(CONFIG_FILE, 'r', encoding='utf-8-sig') as file:\n data = json.load(file)\n # извлекаем значения GROUP_TICKETS из SEND_ALERT\n chat_id = data['SEND_ALERT']['GROUP_TICKETS']\n\n # Отправляем сообщение в телеграм-группу\n if alert.send_telegram_message(chat_id, ticket_info):\n hf_class_info_logger.info('Информация об открытом тикете отправлена в группу: %s', chat_id)\n else:\n hf_class_error_logger.error(\"Ошибка отправки информации о тикете с ID: %s в группу: %s\", ticket_id, chat_id)\n\n except Exception as error_message:\n hf_class_error_logger.error(\"Произошла ошибка при обработке тикета с ID: %s - %s\", ticket_id, str(error_message))\n\n\n def process_ticket(self, ticket_data):\n \"\"\"Функция по формированию данных из тикета\"\"\"\n status = ticket_data.get('status').get('behavior')\n # Узнаём в работе ли ещё тикет\n if status == \"pending\":\n ticket_id = ticket_data.get('id')\n priority_info = ticket_data.get('priority')\n priority_name = priority_info.get('name')\n user_info = ticket_data.get('user')\n contact_info = user_info.get('contact_groups')\n assigned_to = ticket_data.get('assigned_to')\n # Проверяем, что значение для поля last_staff_reply_at существует\n if ticket_data.get('last_staff_reply_at'):\n reple_client_time = ticket_data.get('last_staff_reply_at')\n time_difference = TicketUtils.get_time_diff(reple_client_time)\n # Проверяем, что в тикете нет ответа более 3х дней\n if time_difference >= timedelta(days=3):\n name_info = TicketUtils.get_contact_name(contact_info)\n assigned_name = TicketUtils.get_assigned_name(assigned_to)\n # print(f\"Время последнего ответа клиента в тикете {time_difference}\")\n\n ticket_message = (f'Ожидание ответа клиента более 3-х дней.\\nНомер тикета:: {ticket_id}\\nПриоритет: {priority_name}\\nНазвание клиента: {name_info}\\nНазначен: {assigned_name}')\n\n # Получаем chat_id для отправки сообщения\n alert_chat_id = TicketUtils.get_alert_chat_id(assigned_name)\n \n # Отправляем сообщение в телеграм-бот\n alert.send_telegram_message(alert_chat_id, ticket_message)\n hf_class_info_logger.info('Сотруднику: %s в чат отправлена информация о 3х дневном неотвеченном тикете: %s', assigned_name, ticket_id)\n","repo_name":"NjemTop/hf_bot_tg","sub_path":"HappyFox/happyfox_class.py","file_name":"happyfox_class.py","file_ext":"py","file_size_in_byte":16782,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28186515808","text":"import sys\nsys.setrecursionlimit(50000) # 재귀제한높이설정(기본값이상으로 안해주면 런타임에러) ※기본값:1000\n\n\ndef read():\n return sys.stdin.readline().strip()\n\n\ndef dfs(v):\n visited[v] = True\n for i in graph[v]:\n if not visited[i]:\n dfs(i)\n\n\nn, m = map(int, read().split())\n\ngraph = [[] for i in range(n+1)]\nvisited = [False for i in range(n+1)]\n\n\nfor i in range(m):\n u, v = map(int, read().split())\n graph[u].append(v)\n graph[v].append(u)\n\n\ncnt = 0\nfor i in range(1, n+1):\n if not visited[i]:\n dfs(i)\n cnt += 1\n\nprint(cnt)\n","repo_name":"jinukix/Algorithm_py","sub_path":"BAEKJOON/11724 연결 요소의 개수.py","file_name":"11724 연결 요소의 개수.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"73915248218","text":"from chempy import Substance, balance_stoichiometry\nfrom fastapi import FastAPI\nfrom classes import Stoichiometry\nimport json\n\napp = FastAPI()\n\ndef responseTemplate(error: bool, message: str, data):\n return {\"error\": error, \"message\": message, \"data\": json.dumps(data, sort_keys=True)}\n\n@app.get(\"/substance/{substance}\")\ndef read_substance(substance: str):\n try:\n substanceRes = Substance.from_formula(substance)\n substance_data = {\n \"name\": substanceRes.name,\n \"htmlName\": str(substanceRes.html_name),\n \"unicodeName\": substanceRes.unicode_name,\n \"composition\": str(substanceRes.composition),\n \"mass\": str(substanceRes.mass),\n \"molarMass\": str(substanceRes.molar_mass()),\n }\n print(substance_data)\n return responseTemplate(False, f\"Información del {substanceRes.name}\", substance_data)\n except Exception as e:\n return responseTemplate(True, \"Formula inválida\", None)\n\n\n@app.post(\"/balance-stoichiometry\")\nasync def balanceStoichiometry(stoichiometry: Stoichiometry):\n try:\n reac, prod = balance_stoichiometry(stoichiometry.left, stoichiometry.right)\n print(reac, prod)\n return responseTemplate(False, \"\", {\"reactants\": reac, \"products\": prod})\n except Exception as e:\n return responseTemplate(True, str(e), None)\n","repo_name":"tomasschus/chemistry","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"9001317446","text":"from pyspark import SparkContext, SparkConf # pyspark==3.2.0\n\ndef main():\n conf = SparkConf()\n sc = SparkContext(conf=conf)\n distFile = sc.textFile(\"hdfs://localhost:9000/user/azureuser/input/\")\n count = distFile.flatMap(lambda line: line.split(\" \")).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b).sortByKey()\n count.saveAsTextFile(\"hdfs://localhost:9000/user/azureuser/output\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"marsup13/CCF_Lab2_Fall2021","sub_path":"spark.py","file_name":"spark.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"22787454524","text":"import sys\n\nfilename = sys.argv[1]\nnew_filename = filename[0:filename.rfind('.')] + \"_unique.txt\"\n\nwords = set()\nwith open(filename, 'r') as f:\n\tfor line in f.readlines():\n\t\tfor word in line.split():\n\t\t\twords.add(word.lower())\n\nwith open(new_filename, 'w') as f:\n\tfor word in sorted(words):\n\t\tf.write(word + \"\\n\")\n","repo_name":"tklovett/MaudeMiner","sub_path":"scripts/word_unique.py","file_name":"word_unique.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"25886856327","text":"import os\n\ndef create_output_filepath(input_path, output_path=None, suffix='new'):\n \"\"\" Given an input filepath [option given an output dir path], create an\n output filepath with a new suffix.\n \"\"\"\n # define output filename\n fname_in, ext = os.path.splitext(os.path.basename(input_path))\n fname_out = fname_in + '_' + suffix + ext\n # define output path\n if output_path is not None:\n outfile = os.path.join(output_path, fname_out)\n else:\n outfile = os.path.join(os.path.dirname(input_path), fname_out)\n\n return outfile\n","repo_name":"drewthayer/py-utils","sub_path":"py_utils/io/filehandling.py","file_name":"filehandling.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"18931457831","text":"from collections import OrderedDict\nfrom flask import Blueprint, jsonify, Response\nfrom flask import current_app as app\nfrom zaifbot.errors import InvalidRequest\n\nresource = Blueprint('strategies', __name__, url_prefix='/strategies')\n\n\n@resource.route('/', methods=['GET'])\ndef index():\n strategy_list = list()\n trade_count = 0\n total_profit = 0\n rv = OrderedDict()\n\n strategies = app.portfolio.collect_strategies()\n for strategy in strategies:\n info = strategy.get_info()\n strategy_list.append(info)\n trade_count += info['trade_count']\n total_profit += info['profit']\n\n rv['strategies'] = strategy_list\n rv['total_trades'] = trade_count\n rv['total_profit'] = total_profit\n\n res = jsonify(rv)\n return res\n\n\n@resource.route('/', methods=['GET'])\ndef show(id_):\n strategy = app.portfolio.find_strategy(id_)\n if strategy:\n res = jsonify(strategy.get_info())\n return res\n raise InvalidRequest('strategy not found', status_code=404)\n\n\n@resource.route('/', methods=['PATCH'])\ndef stop(id_):\n strategy = app.portfolio.find_strategy(id_)\n if strategy is None:\n raise InvalidRequest('strategy not found', status_code=404)\n\n strategy.stop()\n res = Response()\n res.status_code = 204\n return res\n\n\n@resource.route('/', methods=['DELETE'])\ndef remove(id_):\n strategy = app.portfolio.find_strategy(id_)\n if strategy is None:\n raise InvalidRequest('strategy not found', status_code=404)\n\n if strategy.is_alive():\n raise InvalidRequest('still strategy is alive', status_code=409)\n\n app.portfolio.remove(id_)\n res = Response()\n res.status_code = 204\n return res\n\n\n@resource.route('//suspend', methods=['PUT'])\ndef suspend(id_):\n strategy = app.portfolio.find_strategy(id_)\n if strategy is None:\n raise InvalidRequest('strategy not found', status_code=404)\n\n strategy.pause()\n res = Response()\n res.status_code = 204\n return res\n\n\n@resource.route('//suspend', methods=['DELETE'])\ndef restart(id_):\n strategy = app.portfolio.find_strategy(id_)\n if strategy is None:\n raise InvalidRequest('strategy not found', status_code=404)\n strategy.restart()\n res = Response()\n res.status_code = 204\n return res\n","repo_name":"techbureau/zaifbot","sub_path":"zaifbot/web/resources/strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"69"} +{"seq_id":"11638838234","text":"import torch\nimport torchvision\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.utils.data as Data\nimport numpy as np\nfrom tensorboardX import SummaryWriter\n\n\nBATCH_SIZE = 64\nLR = 0.005\nEPOCH = 2\n#每个batch_size的shape:[64,1,28,28]\n\n\ndef get_data():\n train_data = torchvision.datasets.MNIST(\n root=\"./mnist\",\n train=True,\n transform=torchvision.transforms.ToTensor(),\n download=True\n )\n\n test_data = torchvision.datasets.MNIST(\n root=\"./mnist\",\n transform=torchvision.transforms.ToTensor(),\n train=False\n )\n\n # 划分训练集&验证集\n train_data, val_data = Data.random_split(train_data, [50000, 10000])\n\n train_loader = Data.DataLoader(train_data, BATCH_SIZE, shuffle=True)\n val_loader = Data.DataLoader(val_data, BATCH_SIZE, shuffle=True)\n test_loader = Data.DataLoader(test_data, BATCH_SIZE, shuffle=True)\n\n return train_loader, val_loader, test_loader\n\n\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__() #前面都是规定结构\n\n #第一个卷积层\n self.conv1 = nn.Sequential(\n nn.Conv2d(\n in_channels=1,#灰度图,channel=1\n out_channels=16,#自己设定\n kernel_size=3,#卷积核大小\n stride=1,#步长\n padding=1\n ),\n nn.ReLU(),#激活函数\n nn.MaxPool2d(kernel_size=2)#池化降维,取2*2窗口最大值, 宽、高减半,channel不变\n )#shape:[16,14,14]\n\n\n\n self.conv2 = nn.Sequential(\n nn.Conv2d(\n in_channels=16,\n out_channels=32,\n kernel_size=3,\n stride=1,\n padding=1\n ),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2)\n )#shape:[32,7,7]\n\n\n #定义全连接层\n self.prediction = nn.Linear(32*7*7, 10)\n\n #向前传播\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = x.view(x.size(0), -1)\n output = self.prediction(x)\n return output\n\n\n\ndef train(train_loader, val_loader, test_loader):\n # 创建网络\n cnn = CNN()\n\n # 大数据常用Adam优化器,参数需要model的参数,以及lr\n optimizer = torch.optim.Adam(cnn.parameters(), LR)\n # 定义损失函数,交叉熵\n loss_func = nn.CrossEntropyLoss()\n\n logger = SummaryWriter(log_dir=\"data/choose\")\n\n # 训练阶段\n for epoch in range(EPOCH):\n print(\"epoch:\", epoch)\n # step: 在第几个BATCH_SIZE\n # batch_x: 训练集的图像\n # batch_y: 训练集的标签\n for step, (batch_x, batch_y) in enumerate(train_loader):\n global_iter_num = epoch * len(train_loader)+step+1\n # model只接受Variable的数据,需要先转化\n b_x = Variable(batch_x)\n b_y = Variable(batch_y)\n output = cnn(b_x)\n # 计算误差\n loss = loss_func(output, b_y)\n #将梯度变为零\n optimizer.zero_grad()\n # 反向传播\n loss.backward()\n # 优化参数\n optimizer.step()\n if global_iter_num % 50 == 0:\n #test\n acc_sum = []\n acc_val_sum = []\n for i, (test_x, test_y) in enumerate(test_loader):\n test_x = Variable(test_x)\n test_y = Variable(test_y)\n test_output = cnn(test_x)\n pre_y = torch.max(test_output,1)[1].data.squeeze()\n acc = float((pre_y == test_y).sum())/float(test_y.size(0))\n acc_sum.append(acc)\n for i, (val_x, val_y) in enumerate(val_loader):\n val_x = Variable(val_x)\n val_y = Variable(val_y)\n val_output = cnn(val_x)\n pre_y = torch.max(val_output, 1)[1].data.squeeze()\n val_acc = float((pre_y == val_y).sum())/float(val_y.size(0))\n acc_val_sum.append(val_acc)\n print(\"global_step:\", global_iter_num, \"| train loss:%.4f\" % loss.data, \"|validation accuracy:%.4f\"%np.mean(acc_val_sum), \"|test accuracy:%.4f\" % np.mean(acc_sum))\n logger.add_scalar(\"train loss\", loss.data, global_step=global_iter_num)\n logger.add_scalar(\"validation accuracy\", np.mean(acc_val_sum), global_step=global_iter_num)\n logger.add_scalar(\"test accuracy\", np.mean(acc_sum), global_step=global_iter_num)\n\n for name, param in cnn.named_parameters():\n logger.add_histogram(name, param.data.numpy(), global_step=global_iter_num)\n\n\n\n\n\n\ndef main():\n train_loader, val_loader, test_loader = get_data()\n train(train_loader, val_loader, test_loader)\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n","repo_name":"JennyJiang118/NN","sub_path":"CNN_main.py","file_name":"CNN_main.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41367553521","text":"#!/usr/bin/env python\n#\n# This function is intended to be used as 'cholupdate' in MATLAB\n# Author: Fangtong Liu\n# Date: 05/10/2020\n#\n\nimport numpy as np\n\n\ndef givens(a, b):\n # find a Givens rotation\n if b == 0:\n c = 1\n s = 0\n elif abs(b) > abs(a):\n tau = - a / b\n s = 1 / np.sqrt(1 + tau ** 2)\n c = s * tau\n else:\n tau = - b / a\n c = 1 / np.sqrt(1 + tau ** 2)\n s = c * tau\n return np.array([[c, -s], [s, c]])\n\n\ndef cholupdate(Rold, x):\n # Cholesky update, uding GIvens rotations\n Rold = Rold.T\n n = Rold.shape[0]\n R = np.hstack((Rold, x.reshape(n, 1)))\n\n for k in range(n):\n g = givens(R[k, k], R[k, n])\n R[:, [k, n]] = np.dot(R[:, [k, n]], g.T)\n for i in range(n):\n if R[i, k] > 0:\n R[i, k] = -R[i, k]\n R[k, k] = abs(R[k, k])\n return R[:, 0:n].T\n","repo_name":"UMich-CURLY-teaching/UMich-ROB-530-public","sub_path":"code-examples/Python/slam/cholupdate_function.py","file_name":"cholupdate_function.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":561,"dataset":"github-code","pt":"69"} +{"seq_id":"18381680940","text":"\"\"\"\nInterface to LGA\n\nAuthor: Marco Biasini\n\"\"\"\nimport tempfile\nimport os\nfrom ost import io\nimport subprocess\nfrom ost import geom\nfrom ost import settings\n\ndef _FindLGABinary(lga_bin):\n return settings.Locate('lga', explicit_file_name=lga_bin, \n env_name='LGA_BINARY')\n\ndef _PrepareInput(pdb1, pdb2, output_pdb):\n \"\"\"\n Deal with the brain-dead input requirements of LGA.\n \"\"\"\n mol1=os.path.basename(os.path.splitext(pdb1)[0])\n mol2=os.path.basename(os.path.splitext(pdb2)[0]) \n os.system('echo MOLECULE %s > %s' % (mol1, output_pdb))\n os.system('cat %s >> %s' % (pdb1, output_pdb))\n os.system('echo \"\\n\" >> %s' % (output_pdb)) \n os.system('echo MOLECULE %s >> %s' % (mol2, output_pdb))\n os.system('cat %s >> %s' % (pdb2, output_pdb)) \n\nclass GDTResult:\n def __init__(self, rotation, shift, gdt_ts, gdt_ha):\n self.rotation=rotation\n self.shift=shift\n self.gdt_ts=gdt_ts\n self.gdt_ha=gdt_ha\n def GetTransform(self):\n transform=geom.Mat4()\n transform.PasteTranslation(self.shift)\n return transform*geom.Mat4(self.rotation)\n\ndef _ParseRotationAndShift(lines):\n t=[l.split() for l in lines]\n rot=geom.Mat3()\n shift=geom.Vec3()\n for i, x in enumerate(t):\n rot[(i, 0)]=+float(x[2])\n rot[(i, 1)]=+float(x[6])\n rot[(i, 2)]=+float(x[10])\n shift[i]=float(x[14])\n return rot, shift\n\ndef _ParseGDTSection(section, residue_count):\n cutoffs=[float(e) for e in section[0].split()[2:]]\n num_ca=[int(e) for e in section[1].split()[2:]]\n gdt_ts=[float(e) for e in section[2].split()[2:]]\n scores=dict(list(zip(cutoffs, gdt_ts)))\n numbers=dict(list(zip(cutoffs, num_ca)))\n factor=(1.0/(4*residue_count))*100\n ts_cutoffs=(1.0, 2.0, 4.0, 8.0)\n ha_cutoffs=(0.5, 1.0, 2.0, 4.0) \n gdt_ts=(sum([numbers[c] for c in ts_cutoffs]))*factor\n gdt_ha=(sum([numbers[c] for c in ha_cutoffs]))*factor \n return gdt_ts, gdt_ha \n\ndef _ParseLGAOutput(output, residue_count):\n result=GDTResult(geom.Mat3(), geom.Vec3(), 0.0, 0.0)\n found_gdt_section=False\n found_transform_section=False\n for index, line in enumerate(output):\n if line.startswith('GLOBAL_DISTANCE_TEST'): \n next_lines=output[index+1:index+5]\n result.gdt_ts, result.gdt_ha=_ParseGDTSection(next_lines, residue_count)\n found_gdt_section=True \n if line.startswith('Unitary ROTATION matrix'):\n next_lines=output[index+1:index+4]\n result.rotation, result.shift=_ParseRotationAndShift(next_lines)\n found_transform_section=True\n break\n assert found_transform_section and found_gdt_section\n return result\n \ndef GDT(pdb1, pdb2, chain1='', chain2='', reference_length=None, lga_bin=None):\n \"\"\"\n Calculate GDT value between pdb1 and pdb2. It is assumed that the\n corresponding residues in pdb1 and pdb2 have the same residue numbers.\n \"\"\"\n lga_bin=_FindLGABinary(lga_bin) \n temp_d=tempfile.mkdtemp(prefix='lga_gdt_ts_')\n for d in ('MOL2', 'TMP', 'RESULTS'):\n os.mkdir(os.path.join(temp_d, d))\n\n if not chain1:\n chain1=pdb1.chains[0].name\n if not chain2:\n chain2=pdb2.chains[0].name\n pdb_one_name=os.path.join(temp_d, 'MOL2', 'one.pdb')\n pdb_two_name=os.path.join(temp_d, 'MOL2', 'two.pdb')\n io.SaveEntity(pdb1, pdb_one_name)\n io.SaveEntity(pdb2, pdb_two_name)\n _PrepareInput(pdb_one_name, pdb_two_name, \n os.path.join(temp_d, 'MOL2', 'input.pdb'))\n output_file=os.path.join(temp_d, 'out.txt')\n ch1, ch2=('', '')\n if len(chain1.strip()): ch1=' -ch1:%s ' % chain1\n if len(chain2.strip()): ch2=' -ch2:%s ' % chain2\n \n params=(temp_d, lga_bin, 'input.pdb', ch1, ch2) \n command='cd %s; %s %s %s%s-ie -3 -d:4 -sda'\n\n expanded_cmd=command % params\n lga_proc=subprocess.Popen(expanded_cmd, shell=True, \n stdout=subprocess.PIPE)\n stdout, _ = lga_proc.communicate()\n\n length=reference_length or max(pdb1.residue_count, pdb2.residue_count)\n result=_ParseLGAOutput(stdout.decode().splitlines(), reference_length)\n os.system('rm -r %s' % temp_d)\n return result\n","repo_name":"sailfish009/openstructure","sub_path":"modules/bindings/pymod/lga.py","file_name":"lga.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"11176806463","text":"import sys\r\n\r\ndef one_digit(num): \r\n num_str = str(num)\r\n val = 0\r\n while len(num_str) > 1:\r\n for i in num_str: \r\n val += int(i) \r\n num_str = str(val)\r\n val = 0\r\n return int(num_str)\r\n\r\ndef sum_letter(word):\r\n word = word.lower()\r\n sum_let = 0\r\n for i in word:\r\n if i.isalpha():\r\n sum_let += ord(i) - 96 \r\n return one_digit(sum_let)\r\n\r\nline = sys.stdin.readline()\r\nname_one = 0\r\nname_two = 0\r\n\r\nwhile line:\r\n name_one = sum_letter(line)\r\n line = sys.stdin.readline()\r\n name_two = sum_letter(line)\r\n if name_one > name_two:\r\n print('{:.2f}'.format(round(100*name_two/name_one,2)).zfill(2),\"%\")\r\n else:\r\n print('{:.2f}'.format(round(100*name_one/name_two,2)).zfill(2),\"%\")\r\n line = sys.stdin.readline()\r\n\r\n\r\n","repo_name":"perezmtzdavid/uHunt","sub_path":"10424.py","file_name":"10424.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"21409615004","text":"# -*- coding: utf-8 -*-\nimport zerorpc\nfrom flask.globals import LocalProxy\nfrom django.http import HttpRequest\nimport ujson\nimport datetime\nfrom functools import wraps\n\n\n\"\"\"RPC客户端模块\"\"\"\n\n\nclass Resp(dict):\n \"\"\"\n 定制的返回体\n \"\"\"\n def __bool__(self):\n if self.get(\"message\") == \"success\":\n return True\n else:\n return False\n\n\ndef check_request(req: object):\n init = {\n \"ip\": \"\",\n \"user_agent\": \"\",\n \"user_id\": 0,\n \"host\": \"\",\n \"path\": \"\",\n \"method\": \"\",\n \"web_framework\": \"\",\n \"get_args\": dict(),\n \"post_args\": dict(),\n \"json_args\": dict(),\n }\n if isinstance(req, LocalProxy):\n \"\"\"flask请求\"\"\"\n init['web_framework'] = \"flask\"\n elif isinstance(req, HttpRequest):\n \"\"\"django的请求\"\"\"\n ip = req.META['HTTP_X_FORWARDED_FOR'] if req.META.get('HTTP_X_FORWARDED_FOR') else req.META['REMOTE_ADDR']\n user_agent = req.META['HTTP_USER_AGENT']\n authorization = req.META.get('HTTP_AUTHORIZATION') # 可能是None\n path = req.path\n get_args = req.GET.dict()\n method = req.method.lower()\n post_args = req.POST.dict()\n try:\n json_args = ujson.loads(req.body)\n except Exception as e:\n print(e)\n json_args = dict()\n finally:\n pass\n init['web_framework'] = \"django\"\n init['ip'] = ip\n init['user_agent'] = user_agent\n init['authorization'] = authorization\n init['user_id'] = 0\n init['host'] = req.get_host()\n init['path'] = path\n init['method'] = method\n init['get_args'] = get_args\n init['post_args'] = post_args\n init['json_args'] = json_args\n else:\n web_framework = req.__class__.__name__\n ms = \"未意料的请求体类型: {}\".format(web_framework)\n raise ValueError(ms)\n","repo_name":"SYYDSN/py_projects","sub_path":"django_01/pools/rpc_client_auth.py","file_name":"rpc_client_auth.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35058709915","text":"class Restaurants():\n def __init__(self, restaurant_name, cuisine_type):\n # initialize restaurant and cuisine attributes\n self.restaurant = restaurant_name\n self.cuisine = cuisine_type\n\n def describe_restaurant(self):\n print(f\"{self.restaurant.title()} serves {self.cuisine.title()} food.\")\n\n def open_restuarant(self):\n print(f\"{self.restaurant.title()} is open!\")\n\n\n#creating an instance my_restaurant\nmy_restaurant = Restaurants('Tijuana taxi co.', 'mexican')\nmy_restaurant.describe_restaurant()\nmy_restaurant.open_restuarant()\n\n\nprint('\\n')\n#create a new instance for joes restaurant\njoes_restaurant = Restaurants('olive garden', 'italian')\njoes_restaurant.describe_restaurant()\n\n\n#one more instance for fun\nprint('\\n')\nsteves_restaurant = Restaurants('Benihana', 'japanese')\nsteves_restaurant.describe_restaurant()","repo_name":"jmast02/PythonCrashCourse","sub_path":"restaurant.py","file_name":"restaurant.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35391503201","text":"import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider\nimport argparse\nfrom uavdataset import UAVDataset\nmatplotlib.use('webagg')\n\n__author__ = \"steffen.schieler@tu-ilmenau.de, FG EMS\"\n__credits__ = \"Zhixiang Zhao, Carsten Smeenk\"\n__all__ = [\"UAVDataset\"]\n\n\nMARKER_STYLE = dict(\n linestyle=\"none\",\n markersize=10,\n marker=\"o\",\n fillstyle=\"none\",\n markeredgewidth=1.5,\n color=\"none\",\n markerfacecolor=\"none\",\n markerfacecoloralt=\"none\",\n markeredgecolor=\"red\",\n)\n\n\ndef get_channel(x: np.ndarray, start_idx: int, window_slowtime: int, filter_clutter: bool=False) -> np.ndarray:\n if start_idx > x.shape[0] - window_slowtime:\n raise ValueError(\n \"Start index must be smaller than the number of slowtime samples minus the window size.\")\n\n x = x[start_idx:start_idx+window_slowtime, :]\n if filter_clutter:\n x = np.diff(x, n=1, axis=0)\n \n y = np.fft.fftshift(np.fft.fft(np.fft.ifft(x, axis=1), axis=0), axes=0)\n y /= np.linalg.norm(y)\n\n return y\n\n\ndef get_groundtruth(x: np.ndarray, start_idx: int, window_slowtime: int):\n if start_idx > x.shape[0] - window_slowtime:\n raise ValueError(\n \"Start index must be smaller than the number of slowtime samples minus the window size.\")\n\n delay = x[start_idx+window_slowtime//2, 0]\n doppler = x[start_idx+window_slowtime//2, 1]\n\n return np.array([delay, doppler])\n\n\ndef get_data(channel: np.ndarray, groundtruth: np.ndarray, window_slowtime: int, start_idx: int):\n channel = get_channel(channel, start_idx, window_slowtime)\n groundtruth = get_groundtruth(groundtruth, start_idx, window_slowtime)\n return channel, groundtruth\n\n\ndef update_fig(fig: plt.Figure, ax: plt.Axes, channel: np.ndarray, groundtruth: np.ndarray):\n ax.clear()\n ax.imshow(20*np.log10(np.abs(channel)), aspect=\"auto\",\n cmap=\"inferno\", vmin=-100, vmax=0, extent=[0, 16e-6, +1/(2*320e-6), -1/(2*320e-6)])\n ax.plot(groundtruth[0], groundtruth[1], **MARKER_STYLE)\n ax.set_xlabel(\"Delay [s]\")\n ax.set_ylabel(\"Doppler-Shift [Hz]\")\n fig.canvas.draw_idle()\n return fig, ax\n\n\ndef update(fig: plt.Figure, ax: plt.Axes, channel: np.ndarray, groundtruth: np.ndarray, window_slowtime: int, start_idx: int):\n channel_window, groundtruth_window = get_data(\n channel, groundtruth, window_slowtime, start_idx)\n update_fig(fig, ax, channel_window, groundtruth_window)\n\n\ndef main(args):\n dataset = UAVDataset(args.channel_file, args.target_file)\n channel = dataset.channel\n groundtruth = dataset.groundtruth\n window_slowtime = args.window\n num_windows = (channel.shape[0] - window_slowtime) // window_slowtime\n\n fig, ax = plt.subplots(\n 1, 3,\n figsize=(10, 5),\n tight_layout=True,\n gridspec_kw={\"width_ratios\": [0.05, 1, 0.05]}\n )\n update(fig, ax[1], channel, groundtruth, window_slowtime, 0)\n cbar = plt.colorbar(ax[1].get_images()[0],\n cax=ax[2], orientation=\"vertical\")\n cbar.set_label(\"Normalized Power [dB]\")\n sample_slider = Slider(\n ax=ax[0],\n label=\"Index\",\n valmin=1,\n valmax=num_windows,\n valinit=1,\n valstep=1,\n orientation=\"vertical\",\n )\n sample_slider.on_changed(lambda slider_value: update(\n fig, ax[1], channel, groundtruth, window_slowtime, slider_value*window_slowtime))\n plt.show()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Plotting script for the UAV dataset.\"\n )\n parser.add_argument(\n \"-c\", \"--channel-file\", help=\"Path to the channel file.\", default=\"1to2_H15_V11_VGH0_channel.h5\",\n )\n parser.add_argument(\n \"-t\", \"--target-file\", help=\"Path to the target file.\", default=\"1to2_H15_V11_VGH0_target.h5\",\n )\n parser.add_argument(\n \"-w\",\n \"--window\",\n help=\"Length of the slow time window.\",\n type=int,\n default=100,\n )\n args = parser.parse_args()\n\n main(args)\n","repo_name":"EMS-TU-Ilmenau/isac-uav-dataset","sub_path":"snippets/plot_receiver.py","file_name":"plot_receiver.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"20949514711","text":"import os.path as osp\nfrom setuptools import setup, find_packages\nfrom setuptools.command.test import test as TestCommand\nimport sys\n\n\nclass PyTest(TestCommand):\n user_options = [('pytest-args=', 'a', \"Arguments to pass to pytest\")]\n\n def initialize_options(self):\n TestCommand.initialize_options(self)\n self.pytest_args = ''\n\n def run_tests(self):\n import shlex\n # import here, cause outside the eggs aren't loaded\n import pytest\n errno = pytest.main(shlex.split(self.pytest_args))\n sys.exit(errno)\n\n\ndef readme():\n with open('README.rst') as f:\n return f.read()\n\n\nsetup(name='latlon-utils',\n version='0.0.7',\n description=('Retrieve WorldClim climate and other information for '\n 'lat-lon grid cells'),\n long_description=readme(),\n long_description_content_type=\"text/x-rst\",\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Topic :: Scientific/Engineering :: GIS',\n 'Topic :: Scientific/Engineering',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n 'Operating System :: OS Independent',\n ],\n keywords='worldclim geo-countries latitude longitude',\n url='https://github.com/Chilipp/latlon-utils',\n author='Philipp S. Sommer',\n author_email='philipp.sommer@hereon.de',\n license=\"GPLv3\",\n packages=find_packages(exclude=['docs', 'tests*', 'examples']),\n install_requires=[\n 'netCDF4',\n 'shapely',\n 'pandas',\n ],\n package_data={'latlon-utils': [\n osp.join('latlon_utils', 'data', '*'),\n ]},\n include_package_data=True,\n tests_require=['pytest', 'rasterio', 'xarray', 'pytest-cov'],\n cmdclass={'test': PyTest},\n zip_safe=False)\n","repo_name":"Chilipp/latlon-utils","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"73573852380","text":"import os\nimport sys\nimport re\nimport commands\nimport nipype.pipeline.engine as pe\nimport nipype.interfaces.utility as util\n\n\ndef compute_fisher_z_score(correlation_file):\n\n \"\"\"\n Computes the fisher z transform of the input correlation map\n If the correlation map contains data for multiple ROIs then \n the function returns z score for each ROI as a seperate nifti \n file\n\n\n Parameters\n ----------\n\n correlation_file: string\n Input correlations file\n \n\n Returns\n -------\n\n out_file : list (nifti files)\n list of z_scores for mask or ROI\n \"\"\"\n\n import nibabel as nb\n import numpy as np\n import os\n\n corr_img = nb.load(correlation_file)\n corr_data = corr_img.get_data()\n\n hdr = corr_img.get_header()\n\n corr_data = np.log((1 + corr_data)/(1 - corr_data)) / 2.0\n\n dims = corr_data.shape\n\n out_file = []\n\n if len(dims) == 5:\n\n x, y, z, one, roi_number = dims\n\n corr_data = np.reshape(corr_data, (x*y*z, roi_number), order='F')\n\n for i in range(0, roi_number):\n\n sub_data = np.reshape(corr_data[:, i], (x, y, z), order='F')\n\n sub_img = nb.Nifti1Image(sub_data, header=corr_img.get_header(), affine=corr_img.get_affine())\n\n sub_z_score_file = os.path.join(os.getcwd(), 'z_score_ROI_%d.nii.gz' % (i+1))\n\n sub_img.to_filename(sub_z_score_file)\n\n out_file.append(sub_z_score_file)\n\n else:\n\n z_score_img = nb.Nifti1Image(corr_data, header=hdr, affine=corr_img.get_affine())\n\n z_score_file = os.path.join(os.getcwd(), 'z_score.nii.gz')\n\n z_score_img.to_filename(z_score_file)\n\n out_file.append(z_score_file)\n\n\n return out_file\n","repo_name":"briancheung/C-PAC","sub_path":"CPAC/sca/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"21837860259","text":"from src.Base.Evaluation.Evaluator import EvaluatorHoldout\nfrom src.Utils.load_ICM import load_ICM\nfrom src.Utils.load_URM import load_URM\nfrom src.Utils.ICM_preprocessing import *\n\nURM_all = load_URM(\"../../../in/data_train.csv\")\nICM_all = load_ICM(\"../../../in/data_ICM_title_abstract.csv\")\nfrom src.Data_manager.split_functions.split_train_validation_random_holdout import \\\n split_train_in_two_percentage_global_sample\n\nURM_train, URM_validation = split_train_in_two_percentage_global_sample(URM_all, train_percentage=0.80)\n\nevaluator_validation = EvaluatorHoldout(URM_validation, cutoff_list=[10], verbose=False)\n\nfrom src.EASE_R.EASE_R_CBF_Recommender import EASE_R_CBF_Recommender\nfrom bayes_opt import BayesianOptimization\n\nbinarize_ICM(ICM_all)\n\nICM_all = combine(ICM_all, URM_train)\n\neaserCBF_recommender = EASE_R_CBF_Recommender(URM_train=URM_train, ICM_train=ICM_all, verbose=False)\n\ntuning_params = {\n \"topK\": (10, 150),\n \"l2_norm\": (1e2, 1e5)\n}\n\n\ndef BO_func(\n topK,\n l2_norm\n):\n easerCBF_recommender.fit(topK=int(topK), l2_norm=l2_norm)\n result_dict, _ = evaluator_validation.evaluateRecommender(easerCBF_recommender)\n\n return result_dict[10][\"MAP\"]\n\n\noptimizer = BayesianOptimization(\n f=BO_func,\n pbounds=tuning_params,\n verbose=5,\n random_state=5,\n)\n\noptimizer.maximize(\n init_points=5,\n n_iter=3,\n)\n\nimport json\n\nwith open(\"logs/FeatureCombined\" + easerCBF_recommender.RECOMMENDER_NAME + \"_logs.json\", 'w') as json_file:\n json.dump(optimizer.max, json_file)\n","repo_name":"Alexdruso/recsys-challenge-2020-polimi","sub_path":"parameter_tuning/Hybrids/FeatureCombinedEaseR/FeatureCombinedEASERCBF_tuning.py","file_name":"FeatureCombinedEASERCBF_tuning.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"17685958296","text":"import struct\nfrom collections import namedtuple\nimport numpy as np\nfrom figures import *\nfrom lights import *\nfrom math import cos, sin, tan, pi\nfrom obj import Obj\nfrom numba import jit, cuda\n\nSTEPS = 1\nMAX_RECURSION_DEPTH = 4\n\nV2 = namedtuple('Point2', ['x', 'y'])\nV3 = namedtuple('Point3', ['x', 'y', 'z'])\nV4 = namedtuple('Point4', ['x', 'y', 'z', 'w'])\n\n\ndef char(c):\n # 1 byte\n return struct.pack('=c', c.encode('ascii'))\n\n\ndef word(w):\n # 2 bytes\n return struct.pack('=h', w)\n\n\ndef dword(d):\n # 4 bytes\n return struct.pack('=l', d)\n\n\ndef color(r, g, b):\n return bytes([int(b * 255),\n int(g * 255),\n int(r * 255)])\n\n\ndef baryCoords(A, B, C, P):\n\n areaPBC = (B.y - C.y) * (P.x - C.x) + (C.x - B.x) * (P.y - C.y)\n areaPAC = (C.y - A.y) * (P.x - C.x) + (A.x - C.x) * (P.y - C.y)\n areaABC = (B.y - C.y) * (A.x - C.x) + (C.x - B.x) * (A.y - C.y)\n\n try:\n # PBC / ABC\n u = areaPBC / areaABC\n # PAC / ABC\n v = areaPAC / areaABC\n # 1 - u - v\n w = 1 - u - v\n except:\n return -1, -1, -1\n else:\n return u, v, w\n\n\ndef matrix(rows, columns, anyList):\n matrix = []\n for m in range(rows):\n ListRow = []\n for k in range(columns):\n ListRow.append(anyList[rows * m + k])\n matrix.append(ListRow)\n return matrix\n\n\nclass Raytracer(object):\n def __init__(self, width, height):\n\n self.width = width\n self.height = height\n\n self.fov = 60\n self.nearPlane = 0.1\n self.camPosition = V3(0, 0, 0)\n\n self.scene = []\n self.lights = []\n\n self.envMap = None\n self.active_shader = None\n\n self.clearColor = color(0, 0, 0)\n self.currColor = color(1, 1, 1)\n\n self.glViewMatrix()\n self.glViewport(0, 0, self.width, self.height)\n\n self.glClear()\n\n def glViewport(self, posX, posY, width, height):\n self.vpX = posX\n self.vpY = posY\n self.vpWidth = width\n self.vpHeight = height\n\n self.viewportMatrix = matrix(4, 4, [width/2, 0, 0, posX+width/2,\n 0, height/2, 0, posY+height/2,\n 0, 0, 0.5, 0.5,\n 0, 0, 0, 1])\n self.glProjectionMatrix()\n\n def glClearColor(self, r, g, b):\n self.clearColor = color(r, g, b)\n\n def glColor(self, r, g, b):\n self.currColor = color(r, g, b)\n\n def glClear(self):\n self.pixels = [[self.clearColor for y in range(self.height)]\n for x in range(self.width)]\n\n def glClearViewport(self, clr=None):\n for x in range(self.vpX, self.vpX + self.vpWidth):\n for y in range(self.vpY, self.vpY + self.vpHeight):\n self.glPoint(x, y, clr)\n\n def glPoint(self, x, y, clr=None): # Window Coordinates\n if (0 <= x < self.width) and (0 <= y < self.height):\n self.pixels[x][y] = clr or self.currColor\n\n def scene_intersect(self, orig, dir, sceneObj):\n depth = float('inf')\n intersect = None\n\n for obj in self.scene:\n hit = obj.ray_intersect(orig, dir)\n if hit != None:\n if sceneObj != hit.sceneObj:\n if hit.distance < depth:\n intersect = hit\n depth = hit.distance\n\n return intersect\n\n def cast_ray(self, orig, dir, sceneObj=None, recursion=0):\n intersect = self.scene_intersect(orig, dir, sceneObj)\n\n if intersect == None or recursion >= MAX_RECURSION_DEPTH:\n if self.envMap:\n return self.envMap.getEnvColor(dir)\n else:\n return (self.clearColor[0] / 255,\n self.clearColor[1] / 255,\n self.clearColor[2] / 255)\n\n material = intersect.sceneObj.material\n\n finalColor = np.array([0, 0, 0])\n objectColor = np.array([material.diffuse[0],\n material.diffuse[1],\n material.diffuse[2]])\n\n if material.matType == OPAQUE:\n for light in self.lights:\n diffuseColor = light.getDiffuseColor(intersect, self)\n specColor = light.getSpecColor(intersect, self)\n shadowIntensity = light.getShadowIntensity(intersect, self)\n\n lightColor = (diffuseColor + specColor) * (1 - shadowIntensity)\n\n finalColor = np.add(finalColor, lightColor)\n\n elif material.matType == REFLECTIVE:\n reflect = reflectVector(intersect.normal, np.array(dir) * -1)\n reflectColor = self.cast_ray(\n intersect.point, reflect, intersect.sceneObj, recursion + 1)\n reflectColor = np.array(reflectColor)\n\n specColor = np.array([0, 0, 0])\n for light in self.lights:\n specColor = np.add(\n specColor, light.getSpecColor(intersect, self))\n\n finalColor = reflectColor + specColor\n\n elif material.matType == TRANSPARENT:\n outside = np.dot(dir, intersect.normal) < 0\n bias = intersect.normal * 0.001\n\n specColor = np.array([0, 0, 0])\n for light in self.lights:\n specColor = np.add(\n specColor, light.getSpecColor(intersect, self))\n\n reflect = reflectVector(intersect.normal, np.array(dir) * -1)\n reflectOrig = np.add(intersect.point, bias) if outside else np.subtract(\n intersect.point, bias)\n reflectColor = self.cast_ray(\n reflectOrig, reflect, None, recursion + 1)\n reflectColor = np.array(reflectColor)\n\n kr = fresnel(intersect.normal, dir, material.ior)\n\n refractColor = np.array([0, 0, 0])\n if kr < 1:\n refract = refractVector(intersect.normal, dir, material.ior)\n refractOrig = np.subtract(\n intersect.point, bias) if outside else np.add(intersect.point, bias)\n refractColor = self.cast_ray(\n refractOrig, refract, None, recursion + 1)\n refractColor = np.array(refractColor)\n\n finalColor = reflectColor * kr + \\\n refractColor * (1 - kr) + specColor\n\n finalColor *= objectColor\n\n if material.texture and intersect.texcoords:\n texColor = material.texture.getColor(\n intersect.texcoords[0], intersect.texcoords[1])\n if texColor is not None:\n finalColor *= np.array(texColor)\n\n r = min(1, finalColor[0])\n g = min(1, finalColor[1])\n b = min(1, finalColor[2])\n\n return (r, g, b)\n\n # Load OBJ\n def glViewMatrix(self, translate=V3(0, 0, 0), rotate=V3(0, 0, 0)):\n self.camMatrix = self.glCreateObjectMatrix(translate, rotate)\n self.viewMatrix = np.linalg.inv(self.camMatrix)\n\n def glProjectionMatrix(self, n=0.1, f=1000, fov=60):\n aspectRatio = self.vpWidth / self.vpHeight\n t = tan((fov * pi / 180) / 2) * n\n r = t * aspectRatio\n\n self.projectionMatrix = np.matrix([[n/r, 0, 0, 0],\n [0, n/t, 0, 0],\n [0, 0, -(f+n)/(f-n), -\n (2*f*n)/(f-n)],\n [0, 0, -1, 0]])\n\n def glCreateObjectMatrix(self, translate=V3(0, 0, 0), rotate=V3(0, 0, 0), scale=V3(1, 1, 1)):\n\n translation = np.matrix([[1, 0, 0, translate.x],\n [0, 1, 0, translate.y],\n [0, 0, 1, translate.z],\n [0, 0, 0, 1]])\n\n rotation = self.glCreateRotationMatrix(rotate.x, rotate.y, rotate.z)\n\n scaleMat = np.matrix([[scale.x, 0, 0, 0],\n [0, scale.y, 0, 0],\n [0, 0, scale.z, 0],\n [0, 0, 0, 1]])\n\n return translation * rotation * scaleMat\n\n def glCreateRotationMatrix(self, pitch=0, yaw=0, roll=0):\n\n pitch *= pi/180\n yaw *= pi/180\n roll *= pi/180\n\n pitchMat = np.matrix([[1, 0, 0, 0],\n [0, cos(pitch), -sin(pitch), 0],\n [0, sin(pitch), cos(pitch), 0],\n [0, 0, 0, 1]])\n\n yawMat = np.matrix([[cos(yaw), 0, sin(yaw), 0],\n [0, 1, 0, 0],\n [-sin(yaw), 0, cos(yaw), 0],\n [0, 0, 0, 1]])\n\n rollMat = np.matrix([[cos(roll), -sin(roll), 0, 0],\n [sin(roll), cos(roll), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n\n return pitchMat * rollMat * yawMat\n\n def glTransform(self, vertex, matrix):\n v = V4(vertex[0], vertex[1], vertex[2], 1)\n vt = matrix @ v\n vt = vt.tolist()[0]\n vf = V3(vt[0] / vt[3],\n vt[1] / vt[3],\n vt[2] / vt[3])\n\n return vf\n\n def glCamTransform(self, vertex):\n v = V4(vertex[0], vertex[1], vertex[2], 1)\n vt = self.viewportMatrix @ self.projectionMatrix @ self.viewMatrix @ v\n vt = vt.tolist()[0]\n vf = V3(vt[0] / vt[3],\n vt[1] / vt[3],\n vt[2] / vt[3])\n\n return vf\n\n def glDirTransform(self, dirVector, rotMatrix):\n v = V4(dirVector[0], dirVector[1], dirVector[2], 0)\n vt = rotMatrix @ v\n vt = vt.tolist()[0]\n vf = V3(vt[0],\n vt[1],\n vt[2])\n\n return vf\n\n def glTriangle_bc(self, A, B, C, verts=(), texCoords=(), normals=(), clr=None):\n # bounding box\n minX = round(min(A.x, B.x, C.x))\n minY = round(min(A.y, B.y, C.y))\n maxX = round(max(A.x, B.x, C.x))\n maxY = round(max(A.y, B.y, C.y))\n\n edge1 = np.subtract(verts[1], verts[0])\n edge2 = np.subtract(verts[2], verts[0])\n\n triangleNormal = np.cross(edge1, edge2)\n triangleNormal = triangleNormal / np.linalg.norm(triangleNormal)\n\n deltaUV1 = np.subtract(texCoords[1], texCoords[0])\n deltaUV2 = np.subtract(texCoords[2], texCoords[0])\n f = 1 / (deltaUV1[0] * deltaUV2[1] - deltaUV2[0] * deltaUV1[1])\n\n tangent = [f * (deltaUV2[1] * edge1[0] - deltaUV1[1] * edge2[0]),\n f * (deltaUV2[1] * edge1[1] - deltaUV1[1] * edge2[1]),\n f * (deltaUV2[1] * edge1[2] - deltaUV1[1] * edge2[2])]\n tangent = tangent / np.linalg.norm(tangent)\n\n bitangent = np.cross(triangleNormal, tangent)\n bitangent = bitangent / np.linalg.norm(bitangent)\n\n for x in range(minX, maxX + 1):\n for y in range(minY, maxY + 1):\n\n u, v, w = baryCoords(A, B, C, V2(x, y))\n\n if 0 <= u and 0 <= v and 0 <= w:\n\n z = A.z * u + B.z * v + C.z * w\n\n if 0 <= x < self.width and 0 <= y < self.height:\n if z < self.zbuffer[x][y] and -1 <= z <= 1:\n self.zbuffer[x][y] = z\n\n if self.active_shader:\n r, g, b = self.active_shader(self,\n baryCoords=(\n u, v, w),\n vColor=clr or self.currColor,\n texCoords=texCoords,\n normals=normals,\n triangleNormal=triangleNormal,\n tangent=tangent,\n bitangent=bitangent)\n\n self.glPoint(x, y, color(r, g, b))\n else:\n self.glPoint(x, y, clr)\n\n def glClear(self):\n self.pixels = [[self.clearColor for y in range(self.height)]\n for x in range(self.width)]\n\n self.zbuffer = [[float('inf') for y in range(self.height)]\n for x in range(self.width)]\n\n def glLoadModel(self, filename, translate=V3(0, 0, 0), rotate=V3(0, 0, 0), scale=V3(1, 1, 1)):\n model = Obj(filename)\n modelMatrix = self.glCreateObjectMatrix(translate, rotate, scale)\n rotationMatrix = self.glCreateRotationMatrix(\n rotate[0], rotate[1], rotate[2])\n\n for face in model.faces:\n vertCount = len(face)\n\n v0 = model.vertices[face[0][0] - 1]\n v1 = model.vertices[face[1][0] - 1]\n v2 = model.vertices[face[2][0] - 1]\n\n v0 = self.glTransform(v0, modelMatrix)\n v1 = self.glTransform(v1, modelMatrix)\n v2 = self.glTransform(v2, modelMatrix)\n\n A = self.glCamTransform(v0)\n B = self.glCamTransform(v1)\n C = self.glCamTransform(v2)\n\n vt0 = model.texcoords[face[0][1] - 1]\n vt1 = model.texcoords[face[1][1] - 1]\n vt2 = model.texcoords[face[2][1] - 1]\n\n vn0 = model.normals[face[0][2] - 1]\n vn1 = model.normals[face[1][2] - 1]\n vn2 = model.normals[face[2][2] - 1]\n vn0 = self.glDirTransform(vn0, rotationMatrix)\n vn1 = self.glDirTransform(vn1, rotationMatrix)\n vn2 = self.glDirTransform(vn2, rotationMatrix)\n\n self.glTriangle_bc(A, B, C,\n verts=(v0, v1, v2),\n texCoords=(vt0, vt1, vt2),\n normals=(vn0, vn1, vn2))\n\n def glRender(self):\n # Proyeccion\n t = tan((self.fov * np.pi / 180) / 2) * self.nearPlane\n r = t * self.vpWidth / self.vpHeight\n\n for y in range(self.vpY, self.vpY + self.vpHeight + 1, STEPS):\n for x in range(self.vpX, self.vpX + self.vpWidth + 1, STEPS):\n # Pasar de coordenadas de ventana a\n # coordenadas NDC (-1 a 1)\n Px = ((x + 0.5 - self.vpX) / self.vpWidth) * 2 - 1\n Py = ((y + 0.5 - self.vpY) / self.vpHeight) * 2 - 1\n\n Px *= r\n Py *= t\n\n direction = V3(Px, Py, -self.nearPlane)\n direction = direction / np.linalg.norm(direction)\n\n rayColor = self.cast_ray(self.camPosition, direction)\n\n if rayColor is not None:\n rayColor = color(rayColor[0], rayColor[1], rayColor[2])\n self.glPoint(x, y, rayColor)\n\n def glFinish(self, filename):\n with open(filename, \"wb\") as file:\n # Header\n file.write(bytes('B'.encode('ascii')))\n file.write(bytes('M'.encode('ascii')))\n file.write(dword(14 + 40 + (self.width * self.height * 3)))\n file.write(dword(0))\n file.write(dword(14 + 40))\n\n # InfoHeader\n file.write(dword(40))\n file.write(dword(self.width))\n file.write(dword(self.height))\n file.write(word(1))\n file.write(word(24))\n file.write(dword(0))\n file.write(dword(self.width * self.height * 3))\n file.write(dword(0))\n file.write(dword(0))\n file.write(dword(0))\n file.write(dword(0))\n\n # Color table\n for y in range(self.height):\n for x in range(self.width):\n file.write(self.pixels[x][y])\n","repo_name":"JorgeCab2711/Proyecto-Graficos","sub_path":"gl.py","file_name":"gl.py","file_ext":"py","file_size_in_byte":15805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4396091183","text":"# Asuryani Wargear Data\n\n\nwargear = [\n { # Agoniser\n \"name\":\"Agoniser\",\n \"points\":2,\n },\n { # Blast Pistol\n \"name\":\"Blast Pistol\",\n \"points\":2,\n },\n { # Blaster\n \"name\":\"Blaster\",\n \"points\":3,\n },\n { # Dark Lance\n \"name\":\"Dark Lance\",\n \"points\":4,\n },\n { # Hekatarii Blade\n \"name\":\"Hekatarii Blade\",\n \"points\":0,\n },\n { # Hydra Gauntlets\n \"name\":\"Hydra Gauntlets\",\n \"points\":2,\n },\n { # Phantasm Grenade Launcher\n \"name\":\"Phantasm Grenade Launcher\",\n \"points\":1,\n },\n { # Plasma Grenade\n \"name\":\"Plasma Grenade\",\n \"points\":0,\n },\n { # Power Sword\n \"name\":\"Power Sword\",\n \"points\":2,\n },\n { # Razorflails\n \"name\":\"Razorflails\",\n \"points\":2,\n },\n { # Shardnet and Impaler\n \"name\":\"Shardnet and Impaler\",\n \"points\":2,\n },\n { # Shredder\n \"name\":\"Shredder\",\n \"points\":1,\n },\n { # Splinter Cannon\n \"name\":\"Splinter Cannon\",\n \"points\":3,\n },\n { # Splinter Pistol\n \"name\":\"Splinter Pistol\",\n \"points\":0,\n },\n { # Splinter Rifle\n \"name\":\"Splinter Rifle\",\n \"points\":0,\n },\n],","repo_name":"Purple-Wolves-Studio/WH40K_KillTeam_v1","sub_path":"Factions/Drukhari/Wargear.py","file_name":"Wargear.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35200771510","text":"import numpy as np\nfrom PIL import Image\nimport PIL.ImageDraw as ImageDraw\nimport PIL.ImageFont as ImageFont\nfrom .common_utils import *\nfrom random import seed\nfrom random import random, randint\nimport math\nimport matplotlib.pyplot as plt\nimport librosa\n\ndef get_text_mask(for_image, sz=20):\n font_fname = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'\n font_size = sz\n font = ImageFont.truetype(font_fname, font_size)\n\n img_mask = Image.fromarray(np.array(for_image)*0+255)\n draw = ImageDraw.Draw(img_mask)\n draw.text((128, 128), \"hello world\", font=font, fill='rgb(0, 0, 0)')\n\n return img_mask\n\ndef get_bernoulli_mask(for_image, zero_fraction=0.95):\n img_mask_np=(np.random.random_sample(size=pil_to_np(for_image).shape) > zero_fraction).astype(int)\n img_mask = np_to_pil(img_mask_np)\n\n return img_mask\n\n#def generate_mask(input_dimensions, context, s = 30, min_length = 1, max_length = 50, probability = 0.5): #context = how much data before and after a hole, masking_type = vertical | total\n # mask = np.ones(input_dimensions)\n # len = 0\n # seed(s)\n # i = context\n # j = context\n # while (i < input_dimensions[1]-context):\n # if (random() < probability):\n # len = randint(min_length, max_length)\n # for j in range(0, len):\n # mask[:,i+j] = 0\n # i += len + context\n # continue\n # i += 1\n # return mask\n\ndef generate_mask(input_dimensions, type): #, context):\n\n # at sr=22050 n_fft=2048 hop_length=n_fft/4 1 time frame corresponds to more or less 20ms\n\n if type == 'short':\n len = 3\n context = 10\n elif type == 'mid':\n len = 6\n context = 60\n elif type == 'long':\n len = 10\n context = 90\n\n mask = np.ones(input_dimensions)\n i = context\n j = context\n while (i < input_dimensions[1]-context):\n for j in range(0, len):\n mask[:,i+j] = 0\n i += len + context\n return mask\n\ndef separate_spectrogram(spectrogram, input_type, sr):\n if input_type == 'mag-phase':\n return np.abs(spectrogram), np.angle(spectrogram)\n elif input_type == 'real-imag':\n return spectrogram.real, spectrogram.imag\n elif input_type == 'mag-ifreq':\n ifreq = np.diff(np.unwrap(np.angle(spectrogram)))\n ifreq = np.column_stack((np.angle(spectrogram)[:,0], ifreq))\n return np.abs(spectrogram), ifreq\n\ndef crop_spectrogram(spectrogram, dim_div_by):\n return spectrogram[0:(spectrogram.shape[0]//dim_div_by)*dim_div_by,0:(spectrogram.shape[1]//dim_div_by)*dim_div_by]\n\ndef aggregate(X_a, X_b, aggregation):\n if aggregation == 'stack':\n return np.stack((X_a, X_b))\n elif aggregation == 'concat':\n return np.concat((X_a, X_b)) # TODO\n\ndef disaggregate(X, aggregation):\n if aggregation == 'stack':\n return X[0], X[1]\n elif aggregation == 'concat':\n return X[0], X[1] # TODO\n\ndef reconstruct_spectrogram(X_a, X_b, input_type, sr):\n if input_type == 'mag-phase':\n return X_a * np.exp(1j*X_b)\n elif input_type == 'real-imag':\n return X_a + 1j*X_b\n elif input_type == 'mag-ifreq':\n return X_a * np.exp(1j*np.cumsum(X_b, axis=1))\n\ndef nmse(original, reconstructed):\n return 10*math.log10(np.linalg.norm(reconstructed - original)**2/(np.linalg.norm(original)**2))\n\n# def scale(X, min, max):\n# return min + ((X - np.min(X))*(max - min))/(np.max(X) - np.min(X))\n\ndef save_plots(path, original_a, original_b, reconstructed_a, reconstructed_b, input_type, sample_rate):\n if input_type == 'mag-phase':\n plt.figure(figsize=(14,10))\n librosa.display.specshow(librosa.amplitude_to_db(original_a), sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/original_mag.png')\n\n plt.figure(figsize=(14,10))\n librosa.display.specshow(original_b, sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/original_phase.png')\n\n plt.figure(figsize=(14,10))\n librosa.display.specshow(librosa.amplitude_to_db(reconstructed_a), sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/reconstructed_mag.png')\n\n plt.figure(figsize=(14,10))\n librosa.display.specshow(reconstructed_b, sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/reconstructed_phase.png')\n\n elif input_type == 'real-imag':\n plt.figure(figsize=(14,10))\n librosa.display.specshow(librosa.amplitude_to_db(original_a), sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/original_real.png')\n\n plt.figure(figsize=(14,10))\n librosa.display.specshow(librosa.amplitude_to_db(original_b), sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/original_imag.png')\n\n plt.figure(figsize=(14,10))\n librosa.display.specshow(librosa.amplitude_to_db(reconstructed_a), sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/reconstructed_real.png')\n\n plt.figure(figsize=(14,10))\n librosa.display.specshow(librosa.amplitude_to_db(reconstructed_b), sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/reconstructed_imag.png')\n\n elif input_type == 'mag-ifreq':\n plt.figure(figsize=(14,10))\n librosa.display.specshow(librosa.amplitude_to_db(original_a), sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/original_mag.png')\n\n plt.figure(figsize=(14,10))\n librosa.display.specshow(original_b, sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/original_ifreq.png')\n\n plt.figure(figsize=(14,10))\n librosa.display.specshow(librosa.amplitude_to_db(reconstructed_a), sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/reconstructed_mag.png')\n\n plt.figure(figsize=(14,10))\n librosa.display.specshow(reconstructed_b, sr=sample_rate, x_axis='time', y_axis='log', cmap='viridis')\n plt.colorbar()\n plt.savefig(path + '/reconstructed_ifreq.png')\n\n plt.close('all')\n","repo_name":"fmiotello/dpai","sub_path":"src/utils/inpainting_utils.py","file_name":"inpainting_utils.py","file_ext":"py","file_size_in_byte":6533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39789747347","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nfrom skimage import io\nimport numpy as np\nimport os\n\nimport sys\n\n# In[2]:\n\n\n# In[3]:\ndef main(argv):\n\n\tX = []\n\tX_pick = []\n\n\n\t# In[4]:\n\n\n\tfor i in range(415):\n\t\timg = io.imread(argv[0]+'/'+str(i)+'.jpg')\n\t\tX.append(img.flatten())\n\n\timg_pick = io.imread(argv[0]+'/'+argv[1])\n\tX_pick.append(img_pick.flatten())\n\t# In[5]:\n\n\n\tX = np.array(X)\n\tX_pick = np.array(X_pick)\n\t\n\t\n\n\n\t# In[6]:\n\n\n\tpics_matrix = X.copy()\n\n\n\t# In[7]:\n\n\n\n\tmu = np.mean(pics_matrix, axis=0)\n\tx = pics_matrix - mu\n\tX_pick = X_pick - mu\n\teigen_faces, sigma, v = np.linalg.svd(x.T, full_matrices=False)\n\n\t# In[13]:\n\n\tpicked_faces = eigen_faces[:,:4]\n\n\n\t# In[19]:\n\n\n\n\tpic = np.dot(X_pick, picked_faces)\n\tpics = np.dot(pic, picked_faces.T)\n\tpics += mu.flatten()\n\tpics -= np.min(pics)\n\tpics /= np.max(pics)\n\n\tpics = (pics * 255).astype(np.uint8)\n\n\tio.imsave('reconstrcution.jpg' ,pics.reshape(600,600,3))\n\n\n\n\n\n\n# In[133]:\n\nif __name__ == '__main__': \n sys.exit(main(sys.argv[1:]))\n\n\n","repo_name":"r06521601/ML2018SPRING","sub_path":"hw4/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"28195699464","text":"import sys\n\nfrom speech_to_text import *\nfrom chatgpt_response import *\n\nif __name__ == \"__main__\":\n\n while True:\n # Convert voice to text\n print(\"Listening for search query...\")\n voice_text = ListenAudio().take_command()\n\n if voice_text:\n print(f\"You want to search for: {voice_text}\")\n\n # Use the text to chat with GPT\n response = ChatGPTResponse().get_response(voice_text)\n\n print(\"Here is the chat gpt response:\")\n print(response)\n else:\n print(\"Error in responding or recognizing voice. Please try again!\")\n \n print('Do you want to make another search')\n reply = ListenAudio().take_command()\n print(reply)\n if(s in reply.lower() for s in ['yes','continue']):\n continue\n print(\"Exiting the program...\")\n sys.exit(0)\n\n\t\t \n","repo_name":"maheshsoundar/chatgpt_voice_search","sub_path":"speech_to_search.py","file_name":"speech_to_search.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13220652442","text":"import math\r\nimport cv2\r\nimport mediapipe as mp\r\nmp_drawing = mp.solutions.drawing_utils\r\nmp_holistic = mp.solutions.holistic\r\n\r\ncap = cv2.VideoCapture('side.mp4')\r\npTime = 0\r\n\r\ncv2.namedWindow(\"window\", cv2.WINDOW_AUTOSIZE) \r\ninitelbow = 999999\r\nmaxdrop = 0\r\n\r\ninitialear = 999999\r\nmaxhead = 0\r\n\r\n\r\nwith mp_holistic.Holistic(\r\n min_detection_confidence=0.5,\r\n min_tracking_confidence=0.5) as holistic:\r\n while cap.isOpened():\r\n success, image = cap.read()\r\n if not success:\r\n print(\"Ignoring empty camera frame.\")\r\n # If loading a video, use 'break' instead of 'continue'.\r\n break\r\n\r\n# Flip the image horizontally for a later selfie-view display, and convert\r\n # the BGR image to RGB.\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\n # To improve performance, optionally mark the image as not writeable to\r\n # pass by reference.\r\n \r\n image_height, image_width, _ = image.shape\r\n image.flags.writeable = False\r\n results = holistic.process(image)\r\n\r\n # Draw landmark annotation on the image.\r\n image.flags.writeable = True\r\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\r\n \r\n mp_drawing.draw_landmarks(\r\n image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS)\r\n \r\n rex = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_ELBOW].x \r\n rey = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_ELBOW].y \r\n \r\n rwx = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_WRIST].x\r\n rwy = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_WRIST].y\r\n \r\n myrads = math.atan2(rwy - rey, rwx - rex)\r\n mydegs = math.degrees(myrads)\r\n mydegs = abs(mydegs)\r\n mydegs = round(mydegs)\r\n \r\n if (initelbow == 999999):\r\n initelbow = rey\r\n elbowdrop = rey / initelbow\r\n #print(elbowdrop)\r\n elbowpercent = (1 - elbowdrop) * 100\r\n elbowpercent = round(elbowpercent)\r\n \r\n if (elbowpercent < maxdrop):\r\n maxdrop = elbowpercent\r\n \r\n \r\n eary = results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_EAR].y \r\n if (initialear == 999999):\r\n initialear = eary\r\n \r\n headrop = eary / initialear\r\n headpercent = (1 - headrop) * 100\r\n headpercent = round(headpercent)\r\n \r\n if (headpercent < maxhead):\r\n maxhead = headpercent\r\n \r\n cv2.putText(image, 'Elbow Angle = ' + str(int(mydegs)), (50,50), cv2.FONT_HERSHEY_SIMPLEX,0.75,(255,0,0), 3)\r\n cv2.putText(image, 'Current Elbow Drop = ' + str(int(elbowpercent)) + '%', (50,100), cv2.FONT_HERSHEY_SIMPLEX,0.75,(255,0,0), 3)\r\n cv2.putText(image, 'Max Elbow Drop = ' + str(int(maxdrop)) + '%', (50,150), cv2.FONT_HERSHEY_SIMPLEX,0.75,(255,0,0), 3)\r\n cv2.putText(image, 'Current Head Drop = ' + str(int(headpercent)) + '%', (50,200), cv2.FONT_HERSHEY_SIMPLEX,0.75,(255,0,0), 3)\r\n cv2.putText(image, 'Max Head Drop = ' + str(int(maxhead)) + '%', (50,250), cv2.FONT_HERSHEY_SIMPLEX,0.75,(255,0,0), 3) \r\n \r\n cv2.imshow(\"window\", image)\r\n \r\n #print(mydegs)\r\n #print(\r\n # f'Right Elbow coordinates: ('\r\n # f'{results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_ELBOW].x * image_width}, '\r\n # f'{results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_ELBOW].y * image_height})'\r\n # )\r\n \r\n #print(\r\n # f'Right Wrist coordinates: ('\r\n # f'{results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_WRIST].x * image_width}, '\r\n # f'{results.pose_landmarks.landmark[mp_holistic.PoseLandmark.RIGHT_WRIST].y * image_height})'\r\n # )\r\n \r\n \r\n \r\n if cv2.waitKey(5) & 0xFF == 27:\r\n break\r\n \r\ncap.release()","repo_name":"samkorte/pool","sub_path":"pool-pose.py","file_name":"pool-pose.py","file_ext":"py","file_size_in_byte":3720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"13796134903","text":"# Import all library\nimport os\nimport tensorflow as tf\nimport numpy as np\nimport json\nfrom PIL import Image\n\n# Function to load model\ndef load_model():\n model = tf.keras.models.load_model('model_dir/model.h5')\n return model\n\n# Function to predict image\ndef predict_image(path):\n img = tf.keras.utils.load_img(\n path, target_size=(150, 150)\n )\n\n img_array = tf.keras.utils.img_to_array(img)\n img_array = tf.expand_dims(img_array, axis=0)\n\n predictions = model.predict(img_array)\n score = tf.nn.softmax(predictions[0])\n\n return np.argmax(predictions)\n\n# Function to decode label\ndef label_decode(result):\n\n with open('fresh_rotten_dic.json', 'r') as file:\n labels = json.load(file)\n\n for key, value in labels.items():\n if str(result) == key:\n return value\n\n\n# run test.py\nif __name__ == \"__main__\":\n model = load_model()\n result = predict_image(input(\"Input path of the image: \"))\n last_result = label_decode(result)\n print(\"This Fruits is: {}\".format(last_result))\n","repo_name":"nurmuhimawann/C22-098-Fruity-Website","sub_path":"notebooks/tf_test.py","file_name":"tf_test.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"69"} +{"seq_id":"31932685180","text":"from pylab import *\nfrom scipy.io import wavfile\nimport sys\nname = sys.argv[1]\n\nfigure(figsize=(8,5))\n(sr,sig) = wavfile.read(name)\nstart = 44100\ndur = 100\nwave = sig[start:dur+start]\nwave = 0.9*wave/float(max(wave))\ndirac = zeros(dur)\nfor i in range(0,len(dirac)):\n if i%5 == 0:\n dirac[i] = 1\n\n\nplot(wave*15, 'k', linewidth=2)\nxlim(0,dur)\nquantised = round_((dirac*wave)*15)\nmarkerline, stemlines, baseline = stem(quantised, 'k', markerfmt=' ')\nsetp(baseline, 'color', 'k', 'linewidth', 1)\nxlim(0,dur)\nylim(-16, 15)\nxticks([])\nyticks(arange(-16,16,1), [\"%d\" % (x) for x in range(0,33)])\ngrid()\ntight_layout()\nshow()\n","repo_name":"vlazzarini/instruments","sub_path":"misc/quantising.py","file_name":"quantising.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"69"} +{"seq_id":"13634750992","text":"from django.urls import path\n\nfrom .views import edit_account_info, edit_payment_info, create_stellar_account, claim_balance, edit_profile_page, view_user\n#albedo_get_public_key\n\nurlpatterns = [\n path('edit-account/', edit_account_info, name='edit-account'),\n path('edit-payment-info/', edit_payment_info, name='edit-payment-info'),\n path('edit-payment-info/create-account-stellar', create_stellar_account, name='create-account-stellar'),\n path('claim-balance//', claim_balance, name='claim-balance'),\n path('user//', view_user, name='view-user'),\n path('edit-profile-page', edit_profile_page, name='edit-profile-page'),\n# path('albedo-public-key/', albedo_get_public_key, name='albedo-public-key'),\n]\n","repo_name":"MatejMecka/fundmyspace","sub_path":"djangox/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"1658922034","text":"from celligner.params import *\nfrom celligner import limma\n\nfrom sklearn.decomposition import PCA, IncrementalPCA\nfrom sklearn.linear_model import LinearRegression\nimport sklearn.metrics as metrics\nimport umap.umap_ as umap\n\nimport scanpy as sc\nfrom anndata import AnnData\n\nimport os\nimport pickle\nimport gc\n\nimport pandas as pd\nimport numpy as np\n\n#from contrastive import CPCA\nimport mnnpy\n\n\nclass Celligner(object):\n def __init__(\n self,\n topKGenes=TOP_K_GENES,\n pca_ncomp=PCA_NCOMP,\n cpca_ncomp=CPCA_NCOMP,\n louvain_kwargs=LOUVAIN_PARAMS,\n mnn_kwargs=MNN_PARAMS,\n umap_kwargs=UMAP_PARAMS,\n mnn_method=\"mnn_marioni\",\n low_mem=False,\n ):\n \"\"\"\n Initialize Celligner object\n\n Args:\n topKGenes (int, optional): see params.py. Defaults to 1000.\n pca_ncomp (int, optional): see params.py. Defaults to 70.\n cpca_ncomp (int, optional): see params.py. Defaults to 4.\n louvain_kwargs (dict, optional): see params.py\n mnn_kwargs (dict, optional): see params.py \n umap_kwargs (dict, optional): see params.py\n mnn_method (str, optional): Only default \"mnn_marioni\" supported right now.\n low_mem (bool, optional): adviced if you have less than 32Gb of RAM. Defaults to False.\n \"\"\"\n \n self.topKGenes = topKGenes\n self.pca_ncomp = pca_ncomp\n self.cpca_ncomp = cpca_ncomp\n self.louvain_kwargs = louvain_kwargs\n self.mnn_kwargs = mnn_kwargs\n self.umap_kwargs = umap_kwargs\n self.mnn_method = mnn_method\n self.low_mem = low_mem\n\n self.ref_input = None\n self.ref_clusters = None\n self.ref_de_genes = None\n \n self.target_input = None\n self.target_clusters = None\n self.target_de_genes = None\n\n self.de_genes = None\n self.cpca_loadings = None\n self.cpca_explained_var = None\n self.combined_output = None\n \n self.umap_reduced = None\n self.output_clusters = None\n self.tumor_CL_dist = None\n\n\n def __checkExpression(self, expression, is_reference):\n \"\"\"\n Checks gene overlap with reference, checks for NaNs, then does mean-centering.\n\n Args:\n expression (pd.Dataframe): expression data as samples (rows) x genes (columns)\n is_reference (bool): whether the expression is a reference or target\n\n Raises:\n ValueError: if some common genes are missing from the expression dataset\n ValueError: if the expression matrix contains nan values\n\n Returns:\n (pd.Dataframe): the expression matrix\n \"\"\"\n # Check gene overlap\n if expression.loc[:, expression.columns.isin(self.common_genes)].shape[1] < len(self.common_genes):\n if not is_reference:\n raise ValueError(\"Some genes from reference dataset not found in target dataset\")\n else:\n raise ValueError(\"Some genes from previously fit target dataset not found in new reference dataset\")\n \n expression = expression.loc[:, self.common_genes].astype(float)\n \n # Raise issue if there are any NaNs in the expression dataframe\n if expression.isnull().values.any():\n raise ValueError(\"Expression dataframe contains NaNs\")\n\n # Mean center the expression dataframe\n expression = expression.sub(expression.mean(0), 1)\n \n return expression\n\n\n def __cluster(self, expression):\n \"\"\"\n Cluster expression in (n=70)-dimensional PCA space using a shared nearest neighbor based method\n\n Args:\n expression (pd.Dataframe): expression data as samples (rows) x genes (columns)\n\n Returns:\n (list): cluster label for each sample\n \"\"\"\n # Create anndata object\n adata = AnnData(expression, dtype='float64')\n\n # Find PCs\n print(\"Doing PCA..\")\n sc.tl.pca(adata, n_comps=self.pca_ncomp, zero_center=True, svd_solver='arpack')\n\n # Find shared nearest neighbors (SNN) in PC space\n # Might produce different results from the R version as ScanPy and Seurat differ in their implementation.\n print(\"Computing neighbors..\")\n sc.pp.neighbors(adata, knn=True, use_rep='X_pca', n_neighbors=20, n_pcs=self.pca_ncomp)\n \n print(\"Clustering..\")\n sc.tl.louvain(adata, use_weights=True, **self.louvain_kwargs)\n fit_clusters = adata.obs[\"louvain\"].values.astype(int)\n \n del adata\n gc.collect()\n\n return fit_clusters\n\n\n def __runDiffExprOnClusters(self, expression, clusters):\n \"\"\"\n Runs limma (R) on the clustered data.\n\n Args:\n expression (pd.Dataframe): expression data\n clusters (list): the cluster labels (per sample)\n\n Returns:\n (pd.Dataframe): limmapy results\n \"\"\"\n\n n_clusts = len(set(clusters))\n print(\"Running differential expression on \" + str(n_clusts) + \" clusters..\")\n clusts = set(clusters) - set([-1])\n \n # make a design matrix\n design_matrix = pd.DataFrame(\n index=expression.index,\n data=np.array([clusters == i for i in clusts]).T,\n columns=[\"C\" + str(i) + \"C\" for i in clusts],\n )\n design_matrix.index = design_matrix.index.astype(str).str.replace(\"-\", \".\")\n design_matrix = design_matrix[design_matrix.sum(1) > 0]\n \n # creating the matrix\n data = expression.T\n data = data[data.columns[clusters != -1].tolist()]\n \n # running limmapy\n print(\"Running limmapy..\")\n res = (\n limma.limmapy()\n .lmFit(data, design_matrix)\n .eBayes(trend=False)\n .topTable(number=len(data)) \n .iloc[:, len(clusts) :]\n )\n return res.sort_values(by=\"F\", ascending=False)\n \n\n def __runCPCA(self, centered_ref_input, centered_target_input):\n \"\"\"\n Perform contrastive PCA on the centered reference and target expression datasets\n\n Args:\n centered_ref_input (pd.DataFrame): reference expression matrix where the cluster mean has been subtracted\n centered_target_input (pd.DataFrame): target expression matrix where the cluster mean has been subtracted\n\n Returns:\n (ndarray, ncomponents x ngenes): principal axes in feature space\n (ndarray, ncomponents,): variance explained by each component\n\n \"\"\"\n target_cov = centered_target_input.cov()\n ref_cov = centered_ref_input.cov()\n if not self.low_mem:\n pca = PCA(self.cpca_ncomp, svd_solver=\"randomized\", copy=False)\n else: \n pca = IncrementalPCA(self.cpca_ncomp, copy=False, batch_size=1000)\n \n pca.fit(target_cov - ref_cov)\n return pca.components_, pca.explained_variance_\n\n\n def fit(self, ref_expr):\n \"\"\"\n Fit the model to the reference expression dataset - cluster + find differentially expressed genes.\n\n Args:\n ref_expr (pd.Dataframe): reference expression matrix of samples (rows) by genes (columns), \n where genes are ensembl gene IDs. Data should be log2(X+1) TPM data. \n In the standard Celligner pipeline this the cell line data.\n\n Raises:\n ValueError: if only 1 cluster is found in the PCs of the expression\n \"\"\"\n \n self.common_genes = list(ref_expr.columns)\n self.ref_input = self.__checkExpression(ref_expr, is_reference=True)\n \n # Cluster and find differential expression for reference data\n self.ref_clusters = self.__cluster(self.ref_input)\n if len(set(self.ref_clusters)) < 2:\n raise ValueError(\"Only one cluster found in reference data, no differential expression possible\")\n self.ref_de_genes = self.__runDiffExprOnClusters(self.ref_input, self.ref_clusters)\n\n return self\n\n\n def transform(self, target_expr=None, compute_cPCs=True):\n \"\"\"\n Align samples in the target dataset to samples in the reference dataset\n\n Args:\n target_expr (pd.Dataframe, optional): target expression matrix of samples (rows) by genes (columns), \n where genes are ensembl gene IDs. Data should be log2(X+1) TPM data.\n In the standard Celligner pipeline this the tumor data (TCGA). \n Set to None if re-running transform with new reference data.\n compute_cPCs (bool, optional): if True, compute cPCs from the fitted reference and target expression. Defaults to True.\n\n Raises:\n ValueError: if compute_cPCs is True but there is no reference input (fit has not been run)\n ValueError: if compute_cPCs is False but there are no previously computed cPCs available (transform has not been previously run)\n ValueError: if no target expression is provided and there is no previously provided target data\n ValueError: if no target expression is provided and compute_cPCs is true; there is no use case for this\n ValueError: if there are not enough clusters to compute DE genes for the target dataset\n \"\"\"\n\n if self.ref_input is None and compute_cPCs:\n raise ValueError(\"Need fitted reference dataset to compute cPCs, run fit function first\")\n\n if not compute_cPCs and self.cpca_loadings is None:\n raise ValueError(\"No cPCs found, transform needs to be run with compute_cPCs==True at least once\")\n\n if target_expr is None and self.target_input is None:\n raise ValueError(\"No previous data found for target, transform needs to be run with target expression at least once\")\n\n if not compute_cPCs and target_expr is None:\n raise ValueError(\"No use case for running transform without new target data when compute_cPCs==True\")\n\n if compute_cPCs:\n \n if target_expr is not None:\n \n self.target_input = self.__checkExpression(target_expr, is_reference=False)\n\n # Cluster and find differential expression for target data\n self.target_clusters = self.__cluster(self.target_input)\n if len(set(self.target_clusters)) < 2:\n raise ValueError(\"Only one cluster found in reference data, no differential expression possible\")\n self.target_de_genes = self.__runDiffExprOnClusters(self.target_input, self.target_clusters)\n\n # Union of the top 1000 differentially expressed genes in each dataset\n self.de_genes = pd.Series(list(self.ref_de_genes[:self.topKGenes].index) +\n list(self.target_de_genes[:self.topKGenes].index)).drop_duplicates().to_list()\n\n else:\n print(\"INFO: No new target expression provided, using previously provided target dataset\")\n\n # Subtract cluster average from cluster samples\n centered_ref_input = pd.concat(\n [\n self.ref_input.loc[self.ref_clusters == val] - self.ref_input.loc[self.ref_clusters == val].mean(axis=0)\n for val in set(self.ref_clusters)\n ]\n ).loc[self.ref_input.index]\n \n centered_target_input = pd.concat(\n [\n self.target_input.loc[self.target_clusters == val] - self.target_input.loc[self.target_clusters == val].mean(axis=0)\n for val in set(self.target_clusters)\n ]\n ).loc[self.target_input.index]\n \n # Compute contrastive PCs\n print(\"Running cPCA..\")\n self.cpca_loadings, self.cpca_explained_var = self.__runCPCA(centered_ref_input, centered_target_input)\n\n del centered_ref_input, centered_target_input\n gc.collect()\n\n print(\"Regressing top cPCs out of reference dataset..\")\n # Take the residuals of the linear regression of ref_input with the cpca_loadings\n transformed_ref = (self.ref_input - \n LinearRegression(fit_intercept=False)\n .fit(self.cpca_loadings.T, self.ref_input.T)\n .predict(self.cpca_loadings.T)\n .T\n )\n\n # Using previously computed cPCs - for multi-dataset alignment\n else:\n \n # Allow some genes to be missing in new target dataset\n missing_genes = list(self.ref_input.loc[:, ~self.ref_input.columns.isin(target_expr.columns)].columns)\n if len(missing_genes) > 0:\n print('WARNING: %d genes from reference dataset not found in new target dataset, subsetting to overlap' % (len(missing_genes)))\n # Get index of dropped genes\n drop_idx = [self.ref_input.columns.get_loc(g) for g in missing_genes]\n \n # Filter refence dataset\n self.ref_input = self.ref_input.loc[:, self.ref_input.columns.isin(target_expr.columns)]\n self.common_genes = list(self.ref_input.columns)\n\n # Drop cPCA loadings for genes that were filtered out\n self.cpca_loadings = np.array([np.delete(self.cpca_loadings[n], drop_idx) for n in range(self.cpca_ncomp)])\n \n # Check if genes need to be dropped from DE list\n overlap = self.ref_input.loc[:, self.ref_input.columns.isin(self.de_genes)]\n if overlap.shape[1] < len(self.de_genes):\n print('WARNING: dropped genes include %d differentially expressed genes that may be important' % (len(self.de_genes) - overlap.shape[1]))\n temp = pd.Series(self.de_genes)\n self.de_genes = temp[temp.isin(self.ref_input.columns)].to_list()\n\n self.target_input = self.__checkExpression(target_expr, is_reference=False)\n transformed_ref = self.ref_input\n \n # Only need to regress out of target dataset if using previously computed cPCs\n print(\"Regressing top cPCs out of target dataset..\")\n transformed_target = (self.target_input - \n LinearRegression(fit_intercept=False)\n .fit(self.cpca_loadings.T, self.target_input.T)\n .predict(self.cpca_loadings.T)\n .T\n )\n\n # Do MNN \n print(\"Doing the MNN analysis using Marioni et al. method..\")\n # Use top DE genes only\n varsubset = np.array([1 if i in self.de_genes else 0 for i in self.target_input.columns]).astype(bool)\n target_corrected, self.mnn_pairs = mnnpy.marioniCorrect(\n transformed_ref,\n transformed_target,\n var_index=list(range(len(self.ref_input.columns))),\n var_subset=varsubset,\n **self.mnn_kwargs,\n )\n\n if compute_cPCs:\n self.combined_output = pd.concat([target_corrected, transformed_ref])\n else: # Append at the end for multi-dataset alignment case\n self.combined_output = pd.concat([transformed_ref, target_corrected])\n \n del target_corrected\n gc.collect()\n\n print('Done')\n\n return self\n\n\n def computeMetricsForOutput(self, umap_rand_seed=14, UMAP_only=False, model_ids=None, tumor_ids=None):\n \"\"\"\n Compute UMAP embedding and optionally clusters and tumor - model distance.\n \n Args:\n UMAP_only (bool, optional): Only recompute the UMAP. Defaults to False.\n umap_rand_seed (int, optional): Set seed for UMAP, to try an alternative. Defaults to 14.\n model_ids (list, optional): model IDs for computing tumor-CL distance. Defaults to None, in which case the reference index is used.\n tumor_ids (list, optional): tumor IDs for computing tumor-CL distance. Defaults to None, in which case the target index is used.\n \n Raises:\n ValueError: if there is no corrected expression matrix\n \"\"\"\n if self.combined_output is None:\n raise ValueError(\"No corrected expression matrix found, run this function after transform()\")\n\n print(\"Computing UMAP embedding...\")\n # Compute UMAP embedding for results\n pca = PCA(self.pca_ncomp)\n pcs = pca.fit_transform(self.combined_output)\n \n umap_reduced = umap.UMAP(**self.umap_kwargs, random_state=umap_rand_seed).fit_transform(pcs)\n self.umap_reduced = pd.DataFrame(umap_reduced, index=self.combined_output.index, columns=['umap1','umap2'])\n\n if not UMAP_only:\n \n print('Computing clusters..')\n self.output_clusters = self.__cluster(self.combined_output)\n\n print(\"Computing tumor-CL distance..\")\n pcs = pd.DataFrame(pcs, index=self.combined_output.index)\n if model_ids is None: model_ids = self.ref_input.index\n if tumor_ids is None: tumor_ids = self.target_input.index\n model_pcs = pcs[pcs.index.isin(model_ids)]\n tumor_pcs = pcs[pcs.index.isin(tumor_ids)]\n \n self.tumor_CL_dist = pd.DataFrame(metrics.pairwise_distances(tumor_pcs, model_pcs), index=tumor_pcs.index, columns=model_pcs.index)\n \n return self\n\n\n def makeNewReference(self):\n \"\"\"\n Make a new reference dataset from the previously transformed reference+target datasets. \n Used for multi-dataset alignment with previously computed cPCs and DE genes.\n \n \"\"\"\n self.ref_input = self.combined_output\n self.target_input = None\n return self\n \n \n def save(self, file_name):\n \"\"\"\n Save the model as a pickle file\n\n Args:\n file_name (str): name of file in which to save the model\n \"\"\"\n # save the model\n with open(os.path.normpath(file_name), \"wb\") as f:\n pickle.dump(self, f)\n\n\n def load(self, file_name):\n \"\"\"\n Load the model from a pickle file\n\n Args:\n file_name (str): pickle file to load the model from\n \"\"\"\n with open(os.path.normpath(file_name), \"rb\") as f:\n model = pickle.load(f)\n self.__dict__.update(model.__dict__)\n return self","repo_name":"broadinstitute/celligner","sub_path":"celligner/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18471,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"69"} +{"seq_id":"4860126941","text":"import constants\nfrom game.scripting.action import Action\nfrom game.shared.point import Point\nimport raylib #import all needed info for sound\n\n#initialize audio device\nraylib.InitAudioDevice()\n#encode file to be read by raylib for game sounds\nif constants.OS.lower() == \"darwin\":\n sound = raylib.LoadSound(\"aliens/game/sounds/player_sound.wav\".encode('ascii'))\nelif constants.OS.lower() == \"windows\":\n sound = raylib.LoadSound(\"aliens\\game\\sounds\\player_sound.wav\".encode('ascii'))\n\n\nclass ControlActorsAction(Action):\n \"\"\"\n An input action that controls the player movement left and right\n \n The responsibility of ControlActorsAction is to get the direction and move the player left and right\n\n Attributes:\n _keyboard_service (KeyboardService): An instance of KeyboardService.\n \"\"\"\n\n def __init__(self, keyboard_service):\n \"\"\"Constructs a new ControlActorsAction using the specified KeyboardService.\n \n Args:\n keyboard_service (KeyboardService): An instance of KeyboardService.\n \"\"\"\n self._keyboard_service = keyboard_service\n self._direction = Point(constants.CELL_SIZE, 0)\n\n def execute(self, cast, script):\n \"\"\"Executes the control actors action.\n\n Args:\n cast (Cast): The cast of Actors in the game.\n script (Script): The script of Actions in the game.\n \"\"\"\n\n # get player and bullets for use in the method\n player = cast.get_first_actor(\"player\")\n bullet = cast.get_first_actor(\"bullets\")\n\n # The default is that the player is not moving\n self._direction = Point(0,0)\n player.set_velocity(self._direction) \n\n # Move the player left if they hit the left arrow\n if self._keyboard_service.is_key_down(constants.LT):\n self._direction = Point(-constants.CELL_SIZE, 0)\n player.set_velocity(self._direction)\n # play sound\n raylib.PlaySound(sound)\n \n # Move the player right if they hit the right arrow\n if self._keyboard_service.is_key_down(constants.RT):\n self._direction = Point(constants.CELL_SIZE, 0)\n player.set_velocity(self._direction)\n # play sound\n raylib.PlaySound(sound)\n\n # Fire bullet if the spacebar is pressed\n if self._keyboard_service.is_key_down('space'):\n bullet.create_bullet(cast)\n # play sound\n # raylib.PlaySound(sound) # Can be commented or uncommented if desired, depending on desire for more sounds.\n\n \n ","repo_name":"nikasparks/cse210_final","sub_path":"aliens/game/scripting/control_actors_action.py","file_name":"control_actors_action.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4381495306","text":"import yaml\n\n\nORDER = ['name', 'type', 'lat', 'long', 'address', 'description', 'link']\ndatafiles = ['africa', 'america', 'asia', 'australia', 'europe']\n\n\ndef _custom_dictorder(self, data):\n items = sorted(data.items(), key=lambda d: ORDER.index(d[0]))\n return self.represent_mapping('tag:yaml.org,2002:map', items)\n\n\ndef _custom_listorder(self, data):\n data = sorted(data, key=lambda d: d['name'])\n return self.represent_list(data)\n\n\nyaml.add_representer(dict, _custom_dictorder)\nyaml.add_representer(list, _custom_listorder)\n","repo_name":"DLu/ros_map","sub_path":"location_data.py","file_name":"location_data.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"69"} +{"seq_id":"35496806007","text":"'''\n@Author: Dongze Yang\n@LastEditors: Dongze Yang\n'''\n\nimport sys,socket\n\nif len(sys.argv) != 2:\n print (\"Benutzung %s \" % sys.argv[0])\n sys.exit(1)\nprog,port = sys.argv\ntry:\n n_port = int(port)\nexcept:\n print (\"%s ist kein gueltiger Port\"%port)\n sys.exit(1)\ntry:\n s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n s.bind((\"\", n_port))\n msg,adr = s.recvfrom(1000)\n print (\"Empfange von Host %s, port %d: %s\"%(adr[0], adr[1], msg))\n s.sendto(\"+++ \" + msg + \" +++\", adr)\nexcept:\n print (\"Netzwerkfehler\")\n sys.exit(1)","repo_name":"ydzat/Workspace","sub_path":"Rechnernetze/code/opalUDP/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74940653338","text":"\"\"\"A module for breadth-first traversal of trees.\"\"\"\n\nfrom collections import deque\nfrom typing import Iterable\nfrom tree import T\n\n\ndef bf_order(t: T | None) -> Iterable[int]:\n \"\"\"Breadth-first traversal of a tree.\n\n >>> tree = T(2, T(1, None, None), T(4, T(3, None, None), T(5, None, None)))\n >>> list(bf_order(tree))\n [2, 1, 4, 3, 5]\n \"\"\"\n order = []\n q = []\n\n while(True):\n if t:\n order.append(t.val)\n q.append(t.left)\n q.append(t.right)\n t = q.pop(0)\n elif q:\n t = q.pop(0)\n else:\n break\n\n\n \n return order\n","repo_name":"birc-gsa-2022/tree-traversal-python-marse00","sub_path":"src/bft.py","file_name":"bft.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"37603404246","text":"import numpy as np\nimport random\nclass Nancy:\n\n def __init__(self):\n\n self.learning_rate = 1e-4\n self.reward_discount = 0.99\n self.rewards = [] # rewards\n self.inputs = [] # inputs that Nancy uses to predict moves\n self.hidden_states = [] # hidden layer values\n self.actions = [] # predictions made by Nancy\n self.weights = [0] * 2\n self.weights[0] = np.random.randn(729, 81) / np.sqrt(81)\n self.weights[1] = np.random.randn(81, 729) / np.sqrt(729)\n self.biases = [np.random.randn(729, 1), np.random.randn(81, 1)]\n\n def make_local_move(self, board):\n gx, gy = board.gx, board.gy\n spot = board.board[gx][gy]\n if isinstance(spot, str):\n return self.make_global_move(board)\n\n board_vec = self.flatten(board.board)\n predicted_moves = self.predict_move(board_vec, gx, gy)\n # print(predicted_moves)\n pos = predicted_moves[0][1] % 9\n y = pos % 3\n x = pos // 3\n i = 1\n while not spot.is_move_valid(x, y):\n i += 1\n print(i)\n pos = predicted_moves[i][1] % 9\n y = pos % 3\n x = pos // 3\n return x, y\n \n def forward_pass(self, board_vec):\n\n hidden = np.dot(self.weights[0], board_vec.T) + self.biases[0]\n hidden_transform = self.sigmoid(hidden)\n self.hidden_states.append(hidden_transform)\n log_probs = np.dot(self.weights[1], hidden_transform) + self.biases[1]\n prediction = self.sigmoid(log_probs.T)\n self.actions.append(prediction)\n return prediction\n\n def backprop(self, pred, labels):\n \n prediction_grad = np.dot(grad, pred - grad)\n \n def predict_move(self, board_vec, gx, gy):\n predict = self.forward_pass(board_vec)\n x_start = 27 * gx\n y_start = 9 * gy\n tttboard_range = [x_start + y_start + i for i in range(9)]\n # print(tttboard_range)\n ttt_sample = predict[0][tttboard_range[0] : tttboard_range[-1] + 1]\n # print(ttt_sample)\n pairs = [(ttt_sample[i], tttboard_range[i]) for i in range(9)]\n pairs.sort(key=lambda x : x[0])\n return pairs\n \n def sigmoid(self, x):\n return 1.0 / (1.0 + np.exp(-x))\n\n def sigmoid_grad(self, x):\n sig = self.sigmoid(x)\n return sig * (1.0 - sig)\n\n def flatten(self, board):\n \n board_vec = np.zeros((3, 3, 3, 3))\n for i in range(3):\n for j in range(3):\n spot = board[i][j]\n if not isinstance(spot, str):\n for k in range(3):\n for l in range(3):\n if board[i][j].tttboard[k][l] == 'X':\n board_vec[i][j][k][l] = 1.0\n elif board[i][j].tttboard[k][l] == 'O':\n board_vec[i][j][k][l] = -1.0\n board_vec = np.reshape(board_vec, (1, 81))\n return board_vec\n\n def make_global_move(self, board):\n # random for now till i figure something out\n rand_int = random.randint(0, 8)\n gy = rand_int % 3\n gx = rand_int // 3\n while not board.is_global_coord_valid(gx, gy):\n rand_int = random.randint(0, 8)\n gy = rand_int % 3\n gx = rand_int // 3\n \n return gx, gy","repo_name":"prathamdesai13/UTTT","sub_path":"Agents/Nancy.py","file_name":"Nancy.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"72136288220","text":"#coding:UTF-8\r\nx = 666\r\nl = []\r\ncont = 0 \r\nwhile x!=0:\r\n x = int(input(\"\"))\r\n for i in range (1,x+1):\r\n l.append(i)\r\n l[i-1] = str(l[i-1])\r\n i=i+1\r\n l = \" \".join(l)\r\n if x!=0:\r\n print(l)\r\n t=[]","repo_name":"ttszin/URI","sub_path":"ex1146uri.py","file_name":"ex1146uri.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"971339200","text":"from mstrio.utils.helper import response_handler\n\n\ndef create_folder(connection, name, parent_id, description, error_msg=None):\n \"\"\"Create a folder.\n\n Args:\n connection: MicroStrategy REST API connection object\n name (string): name of folder to create\n parent_id (string): id of folder in which new folder will be created\n description (string, optional): description of folder to create\n error_msg (string, optional): Custom Error Message for Error Handling\n\n Returns:\n Complete HTTP response object.\n \"\"\"\n\n body = {\n \"name\": name,\n \"description\": description,\n \"parent\": parent_id,\n }\n response = connection.session.post(url=connection.base_url + '/api/folders',\n headers={'X-MSTR-ProjectID': connection.project_id},\n json=body)\n if not response.ok:\n if error_msg is None:\n error_msg = \"Error while creating the folder\"\n response_handler(response, error_msg)\n return response\n","repo_name":"pimentad2020/mstrio-py","sub_path":"mstrio/api/folders.py","file_name":"folders.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"69"} +{"seq_id":"21306563735","text":"import time\nfrom machine import Pin, I2C\nfrom micropython_shtc3 import shtc3\n\ni2c = I2C(1, sda=Pin(2), scl=Pin(3)) # Correct I2C pins for RP2040\nsht = shtc3.SHTC3(i2c)\n\nsht.power_mode = shtc3.NORMAL\n\n# After running this example you might need to power-off and on\n# the sensor. If you try to use the sensor afterward you might get\n# and EIO error\n\nwhile True:\n for power_mode in shtc3.power_mode_values:\n print(\"Current Operation mode setting: \", sht.power_mode)\n for _ in range(10):\n temp = sht.temperature\n print(f\"Temperature: {temp:0.1f}°C\")\n print()\n time.sleep(0.5)\n sht.power_mode = power_mode\n","repo_name":"jposada202020/MicroPython_SHTC3","sub_path":"examples/shtc3_power_mode.py","file_name":"shtc3_power_mode.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"35685700426","text":"from typing import Union, List\n\nimport torch\nfrom torch.nn import Embedding\n\nfrom custom_nodes.KepPromptLang.lib.action.base import Action, MultiArgAction\nfrom custom_nodes.KepPromptLang.lib.actions.action_utils import get_embedding\nfrom custom_nodes.KepPromptLang.lib.parser.prompt_segment import PromptSegment\nfrom custom_nodes.KepPromptLang.lib.parser.registration import register_action\n\n\nclass DiffAction(MultiArgAction):\n grammar = 'diff(\" arg (\"|\" arg)* \")\"'\n chars = [\"-\", \"-\"]\n\n display_name = \"Difference\"\n action_name = \"diff\"\n description = \"Subtracts the segments in the order they are given. The first segment is subtracted from the second, then the third from the result, and so on.\"\n usage_examples = [\n \"diff(The cat is|The dog is)\",\n \"diff(Cat|Dog)\",\n \"sum(diff(king|man)|woman)\",\n ]\n\n def __init__(self, args: List[List[Union[PromptSegment, Action]]]):\n super().__init__(args)\n self.base_arg = args[0]\n self.additional_args = args[1:]\n\n\n def token_length(self) -> int:\n # Sum adds to the embeddings of the base segment, so the length is the length of the base segment\n return sum(seg_or_action.token_length() for seg_or_action in self.base_arg)\n\n def get_result(self, embedding_module: Embedding) -> torch.Tensor:\n # Calculate the embeddings for the base segment\n all_base_embeddings = [\n get_embedding(seg_or_action, embedding_module)\n for seg_or_action in self.base_arg\n ]\n\n result = torch.cat(all_base_embeddings, dim=1)\n\n for arg in self.additional_args:\n all_arg_embeddings = [\n get_embedding(seg_or_action, embedding_module) for seg_or_action in arg\n ]\n\n arg_embedding = torch.cat(all_arg_embeddings, dim=1)\n\n if (\n arg_embedding.shape[-2] == 1\n or result.shape[-2] == arg_embedding.shape[-2]\n ):\n result = result.sub(arg_embedding)\n else:\n print(\n \"WARNING: shape mismatch when trying to apply sum, arg will be averaged\"\n )\n result = result.sub(torch.mean(arg_embedding, dim=1, keepdim=True))\n\n return result\n\n # def __repr__(self):\n # return f\"sum(\\n\\tbase_segment={self.base_segment},\\n\\tadditional_args={self.additional_args}\\n)\"\n def __repr__(self) -> str:\n return f\"sum({', '.join(map(str, self.additional_args))})\"\n\n def depth_repr(self, depth=1):\n out = \"NudgeAction(\\n\"\n if isinstance(self.base_arg, Action):\n base_segment_repr = self.base_arg.depth_repr(depth + 1)\n out += \"\\t\" * depth + f\"base_segment={base_segment_repr}\\n\"\n else:\n out += \"\\t\" * depth + f\"base_segment={self.base_arg.depth_repr()},\\n\"\n\n if isinstance(self.additional_args, Action):\n target_repr = self.additional_args.depth_repr(depth + 1)\n out += \"\\t\" * depth + f\"target={target_repr},\\n\"\n else:\n out += \"\\t\" * depth + f\"target={self.additional_args.depth_repr()},\\n\"\n out += \"\\t\" * depth + f\"weight={self.weight},\\n\"\n out += \"\\t\" * (depth - 1) + \")\"\n return out\n\n","repo_name":"M1kep/KepPromptLang","sub_path":"lib/actions/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"4832269302","text":"import random\nfrom time import time\nfrom matplotlib import pyplot as plot\nfrom guppy import hpy\nfrom question3a import FindMax\nfrom question3b import ToLower\nfrom question3c import SortLs\n\n# Question 1\n# Time Graph\n# create list of length 100\nmy_lst = list(range(1, 101))\n\n\n# create function called time_f\ndef time_f(array):\n #create an empty list\n new_lst = [] \n\n for i in range(1, len(array) + 1):\n sub_list = array[0:i]\n start_time = time()\n FindMax(sub_list)\n end_time = time()\n tim_diff = end_time - start_time\n #we append the diff in time in the new list\n new_lst.append(tim_diff)\n return new_lst\n\n\ntms_tkn = time_f(my_lst)\n\n# plotting the graph\nplot.title(\"Input Size vs Time taken for FindMax\")\nplot.xlabel(\"Size\")\nplot.ylabel(\"Time\")\nplot.plot(my_lst, tms_tkn)\nplot.show()\n\n#Space graph\n\n# creating session context\nh = hpy()\n\n\n# create function\ndef tk_sp(array):\n #empty lst named space_tkn\n space_tkn = []\n\n for i in range(1, len(array) + 1):\n sub_list = array[0:i]\n h.setrelheap()\n FindMax(sub_list)\n raw_string = repr(h)\n raw_string = raw_string.split()\n space = raw_string[10]\n space_tkn.append(space)\n return space_tkn\n\n\nspace_tkn = tk_sp(my_lst)\n\n# plot graph\nplot.title(\"Input Size vs Space taken Find Max\")\nplot.xlabel(\"Input size\")\nplot.ylabel(\"Space taken\")\nplot.plot(my_lst, space_tkn)\nplot.show()\n\n\n# Question 3\n# Time Graph\n# create list of length 100\ncr_int_ls = random.sample(range(1, 101), 100)\n\n# create function\n\n\ndef tk_tm(array):\n tk_tmn = []\n\n for i in range(1, len(array) + 1):\n sub_list = array[0:i]\n start_time = time()\n SortLs(sub_list)\n end_time = time()\n tm_df = end_time - start_time\n tk_tmn.append(tm_df)\n return tk_tmn\n\n\ntms_tkn = tk_tm(cr_int_ls)\n\n# plot graph\nplot.title(\"Input Size vs Time take Sortls\")\nplot.xlabel(\"Input size\")\nplot.ylabel(\"Time taken\")\nplot.plot(cr_int_ls, tms_tkn)\nplot.show()\n\n\n","repo_name":"DaviMbugua/DSA_map_plotting","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"71673262300","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.figure(1)\nax1 = plt.subplot()\nplt.sca(ax1)\nplt.plot(np.linspace(20,200,10),[20,29,40,55,67,74,82,88,90,94],c='r',linestyle='--',marker='o')\nplt.xlabel('Number of people')\nplt.ylabel('Leaving time')\nax1.set_ylim(0,100)\n\nplt.figure(2)\nax1 = plt.subplot()\nplt.sca(ax1)\nplt.plot(np.linspace(1,5,5),[123,115,105,90,60],c='r',linestyle='--',marker='o')\nplt.xlabel('Width of gate')\nplt.ylabel('Leaving time')\nax1.set_ylim(30,150)\n\nplt.figure(3)\nax1 = plt.subplot()\nplt.sca(ax1)\nplt.plot(np.linspace(1,10,5),[88 / 50,66/ 50,50/ 50,46/ 50,44/ 50],c='r',linestyle='--',marker='o')\nplt.xlabel('Expect speed')\nplt.ylabel('Leaving dense')\nax1.set_ylim(0.5,2)\n\nplt.show()","repo_name":"huangjihui511/SF-model-homework-of-BUAA","sub_path":"draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"73307411100","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom lxml import etree\nfrom scrapy import Selector\n\nfrom Lyf.items import LyfItem\n\n\nclass SpiderSpider(scrapy.Spider):\n name = 'lyf'\n\n def __init__(self):\n self.start_urls = ['http://soso.nipic.com/?q=刘亦菲&f=JPG&g=0&w=0&h=0&p=0&or=0&sort=5&k=0&page=1']\n\n def start_requests(self):\n for page in range(45):\n page += 1\n url = 'http://soso.nipic.com/?q=刘亦菲&f=JPG&g=0&w=0&h=0&p=0&or=0&sort=5&k=0&page=%s' % page\n yield scrapy.Request(url=url, callback=self.parse, dont_filter=True,meta={\"name\":page})\n\n def parse(self, response):\n hxs = etree.HTML(response.body)\n urls = hxs.xpath('//li[@class=\"new-search-works-item\"]/a/@href')\n items = []\n for index in urls:\n item = LyfItem()\n item['link_url'] = index\n items.append(item)\n\n for item in items:\n yield scrapy.Request(url=item['link_url'], meta={'item': item}, callback=self.parse2)\n\n def parse2(self, response):\n item = response.meta['item']\n item['link_url'] = response.url\n hxs = Selector(response)\n image_url = hxs.xpath(\n '//div[@id=\"static\"] [@class=\"show-img-section overflow-hidden align-center\"]/img/@src').extract()\n item['img_url'] = image_url\n yield item","repo_name":"xmyanlin/pythonSpider","sub_path":"Lyf/spiders/scrapy.py","file_name":"scrapy.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"39195055597","text":"from django.urls import path, include\nfrom django.contrib.auth import views as auth_views\nfrom django.conf.urls import *\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name=\"index\"),\n path('holidays/', views.holidays, name=\"holidays\"),\n path('my_requests/', views.my_requests.as_view(), name='my_requests'),\n path('profile/', views.profile, name=\"profile\"),\n path('login', auth_views.LoginView.as_view(template_name='timesheets/login.html'), name='login'),\n path('logout', auth_views.LogoutView.as_view(template_name='timesheets/logout.html'), name='logout'),\n path('profile/', views.profile, name=\"profile\"),\n\tpath('timesheet/', views.TimesheetDetailView.as_view(), name=\"timesheet\"),\n path('day_detail///', views.day_view, name=\"day_detail\"),\n path('jobs/delete//', views.JobDeleteView.as_view(), name='job_delete'),\n]","repo_name":"ObiekweAgbu/timesheets","sub_path":"timesheets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74638549018","text":"#!/usr/bin/env python\n# coding:utf-8\n\nimport time\nimport RPi.GPIO as GPIO\n\ndef led_pwm():\n LED1 = 18 # LED1 --> GPIO1(BCM:18,Physical:12)\n\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(LED1, GPIO.OUT)\n GPIO.output(LED1, GPIO.LOW)\n\n p18 = GPIO.PWM(LED1, 100) # LED1の周波数設定(100Hz)\n p18.start(0) # デューティ比 0 でPWM出力開始\n\n try:\n while 1:\n # 0〜100まで10段階でデューティ比を設定(プラス方向)\n for dc in range(0, 100, 10):\n p18.ChangeDutyCycle(dc)\n time.sleep(0.5)\n\n # 100〜0まで10段階でデューティ日を設定(マイナス方向)\n for dc in range(100, 0, -10):\n p18.ChangeDutyCycle(dc)\n time.sleep(0.5)\n\n except KeyboardInterrupt:\n print ('key interrupt')\n\n p18.stop() # PWM出力を停止\n\n GPIO.cleanup()\n\nif __name__ == \"__main__\":\n led_pwm()\n","repo_name":"yuzuafro/raspi_handson","sub_path":"src/led_pwm.py","file_name":"led_pwm.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"ja","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"25749816898","text":"\"\"\"\n9. Faça um Programa que leia três números e mostre-os em ordem decrescente.\n\"\"\"\n\na = 30\nb = 20\nc = 10\n\nif a > c:\n a, c = c, a\n\nif a > b:\n a, b = b, a\n\nif b > c:\n b, c = c, b\n\nprint('A ordem decrescente é: {}, {} e {}'.format(a, b, c))\n","repo_name":"thiagofb84jp/python-exercises","sub_path":"pythonCourseUdemu/algoritmosExercicios/estruturaDeDecisao/exercicio09.py","file_name":"exercicio09.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"20048956510","text":"from flask import Blueprint, render_template, request, session\nfrom utilities.db.db_manager import dbManager\nfrom datetime import datetime\n\n\n# payment blueprint definition\npayment = Blueprint('payment', __name__, static_folder='static', static_url_path='/payment', template_folder='templates')\n\n\n# Routes\n@payment.route('/payment')\ndef index():\n ShoppingCartID = session.get('ShoppingCartID')\n totalPriceResult = dbManager.fetch('''SELECT SUM(Amount*Price) totalPrice FROM products_prices as pp JOIN products as p on pp.ProductName=p.ProductName where ShoppingCartID=%s;''', (ShoppingCartID,))\n email = session.get('Email')\n customer = dbManager.fetch('SELECT * FROM customers WHERE Email=%s', (email,))\n return render_template('payment.html', total_Price = totalPriceResult[0].totalPrice, customer=customer[0])\n\n@payment.route('/payment-form', methods=['POST'])\ndef form():\n\n if request.method == 'POST':\n email = request.form['email']\n phone = request.form['phone']\n address_street = request.form['address-street']\n address_number = request.form['address-number']\n city = request.form['city']\n zip = request.form['zip']\n customer_update = dbManager.commit('UPDATE customers SET City=%s, Street=%s, StreetNumber=%s, ZipCode=%s, PhoneNumber=%s WHERE Email = %s', (city, address_street, address_number, zip, phone, email))\n id = request.form['id']\n card_number = request.form['cardnumber']\n cvv = request.form['cvv']\n exp_month = request.form['exp-month']\n exp_year = request.form['exp-year']\n comment = request.form['comment']\n ShoppingCartID = session.get('ShoppingCartID')\n Date = datetime.today().strftime('%y-%m-%d')\n totalPriceResult = dbManager.fetch('''SELECT SUM(Amount*Price) totalPrice FROM products_prices as pp JOIN products as p on pp.ProductName=p.ProductName where ShoppingCartID=%s;''', (ShoppingCartID,))\n totalPrice = totalPriceResult[0].totalPrice\n maxID = dbManager.fetch('SELECT max(OrderID) AS max FROM orders')\n if maxID[0].max :\n OrderID= maxID[0].max+1\n else:\n OrderID=1\n Order_table = dbManager.commit('INSERT into orders VALUES (%s,%s, %s, %s, %s, %s, %s, %s, %s, %s)', (OrderID, id, card_number, cvv, exp_month, exp_year, comment, ShoppingCartID, Date, totalPrice))\n if Order_table:\n product_delete = dbManager.fetch('SELECT productID FROM products WHERE ShoppingCartID = %s', (ShoppingCartID,))\n if product_delete:\n for i in range(len(product_delete)):\n row1 = dbManager.commit('DELETE from box_flavours where ProductID = %s', (product_delete[i].productID,))\n row2 = dbManager.commit('DELETE from icecream_sandwiches where ProductID = %s', (product_delete[i].productID,))\n row3 = dbManager.commit('DELETE from yogurtbox_toppings where ProductID = %s', (product_delete[i].productID,))\n row4 = dbManager.commit('DELETE from products where ProductID = %s', (product_delete[i].productID,))\n return render_template('confirmOrder.html')\n elif request.method == 'GET':\n return render_template('payment.html')","repo_name":"elenacherni/GlideryShop","sub_path":"pages/payment/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"31998366860","text":"from argparse import ArgumentParser\nfrom pytorch_lightning.trainer import Trainer\nfrom pytorch_lightning.loggers import WandbLogger\nfrom src.module import NeRFModule\n\n\ndef main(args):\n wandb_logger = None\n\n # Create the trainer\n if args.logger == False:\n logger = False\n else:\n # Create logger object\n wandb_logger = WandbLogger(project=\"nerf\")\n logger = wandb_logger\n trainer = Trainer.from_argparse_args(\n args,\n logger=logger,\n )\n\n # Create the model\n model = NeRFModule(args, wandb_logger)\n\n # Train the model\n trainer.fit(model)\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n\n # Program specific arguments\n parser.add_argument(\"data_dir\", type=str, help=\"path to dataset\")\n parser.add_argument(\n \"--batch_size\", type=int, default=4096, help=\"batch size to train with\"\n )\n parser.add_argument(\n \"--scale\", type=float, default=1.0, help=\"scaling factor for images\"\n )\n parser.add_argument(\n \"--valid_count\",\n type=int,\n default=-1,\n help=\"how many images to use for validation (-1 for all)\",\n )\n parser.add_argument(\n \"--img_list\",\n nargs=\"*\",\n type=int,\n default=[],\n help=\"indices of subset of images to consider while training\",\n )\n\n # Model specific arguments\n parser = NeRFModule.add_model_specific_args(parser)\n\n # Trainer specific arguments\n parser = Trainer.add_argparse_args(parser)\n\n # Parse all arguments\n args = parser.parse_args()\n\n main(args)\n","repo_name":"ishaanshah/nerf","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"8949838916","text":"# -*- coding: utf-8 -*-\n# pylint: skip-file\n# type: ignore\n\"\"\"Configuration file for the Sphinx documentation builder.\n\nThis file only contain a selection of the most common options. For a\nfull list see the documentation: http://www.sphinx-doc.org/en/master/config\n\n\"\"\"\nimport os\nfrom pathlib import Path\n\nDOCS_DIR = Path(__file__).parent.parent.resolve()\nROOT_DIR = DOCS_DIR.parent\nSRC_DIR = DOCS_DIR / \"source\"\n\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\nproject = \"generic-template\"\ncopyright = \"2022, Kyle Finley\"\nauthor = \"Kyle Finley\"\nrelease = \"0.0.0\"\nversion = release\n\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\nadd_function_parentheses = True\nadd_module_names = True\ndefault_role = None\nexclude_patterns = []\nextensions = [\n \"recommonmark\",\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosectionlabel\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.viewcode\",\n \"sphinx_copybutton\",\n \"sphinx_design\",\n \"sphinxcontrib.apidoc\",\n]\nhighlight_language = \"default\"\nintersphinx_mapping = {}\nlanguage = None\nmaster_doc = \"index\"\nneeds_extensions = {}\nneeds_sphinx = \"4.2\"\nnitpicky = False\nprimary_domain = \"py\"\npygments_style = \"material\" # syntax highlighting style\nrst_epilog = \"\" # appended to the end of each rendered file\nrst_prolog = \"\" # appended to the end of each rendered file\nsource_suffix = {\n \".rst\": \"restructuredtext\",\n \".txt\": \"restructuredtext\",\n \".md\": \"markdown\",\n}\ntemplates_path = [\"_templates\"]\n\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\nhtml_codeblock_linenos_style = \"inline\"\nhtml_css_files = [\"css/custom.css\"]\nhtml_favicon = None\nhtml_js_files = [\"js/custom.js\"]\nhtml_logo = None\nhtml_theme = \"furo\" # theme to use for HTML and HTML Help pages\nhtml_theme_options = {}\nhtml_short_title = f\"{project} v{release}\"\nhtml_title = f\"{project} v{release}\"\nhtml_show_copyright = True\nhtml_show_sphinx = True\nhtml_static_path = [\"_static\"] # dir with static files relative to this dir\n\n\n# -- Options for sphinx-apidoc -----------------------------------------------\n# https://www.sphinx-doc.org/en/master/man/sphinx-apidoc.html#environment\nos.environ[\"SPHINX_APIDOC_OPTIONS\"] = \"members\"\n\n\n# -- Options of sphinx.ext.autodoc -------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#configuration\nautoclass_content = \"class\"\nautodoc_class_signature = \"separated\"\nautodoc_default_options = {\n \"inherited-members\": True, # show all inherited members\n \"member-order\": \"bysource\",\n \"members\": True,\n \"show-inheritance\": True,\n}\nautodoc_type_aliases = {}\nautodoc_typehints = \"signature\"\n\n\n# -- Options for sphinx.ext.autosectionlabel ---------------------------------\n# https://www.sphinx-doc.org/en/master/usage/extensions/autosectionlabel.html\nautosectionlabel_prefix_document = True\nautosectionlabel_maxdepth = None\n\n\n# -- Options for sphinx.ext.napoleon ----------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html\nnapoleon_google_docstring = True\nnapoleon_include_init_with_doc = False\nnapoleon_type_aliases = autodoc_type_aliases\n\n\n# -- Options for sphinxcontrib.apidoc ---------------------------------------\n# https://github.com/sphinx-contrib/apidoc\napidoc_excluded_paths = [\n \".demo\",\n \".venv\",\n \"docs\",\n \"node_modules\",\n \"test*\",\n \"typings\",\n]\napidoc_extra_args = [f\"--templatedir={SRC_DIR / '_templates/apidocs'}\"]\napidoc_module_dir = \"../../\"\napidoc_module_first = True\napidoc_output_dir = \"apidocs\"\napidoc_separate_modules = True\napidoc_toc_file = \"index\"\n","repo_name":"ITProKyle/generic-template","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"69"} +{"seq_id":"19228643706","text":"from Tkinter import *\r\nimport ttk\r\n\r\nventana=Tk()\r\nnotebook=ttk. Notebook(ventana)\r\nnotebook.pack(fill=\"both\", expand=\"yes\")\r\npes0=ttk.Frame(notebook)\r\npes1=ttk.Frame(notebook)\r\nnotebook.add(pes0,text=\"titulo 1\")\r\nnotebook.add(pes1,text=\"titulo 2\")\r\nventana.geometry(\"300x300\")\r\nventana.mainloop()","repo_name":"CALS1/Python_concepts","sub_path":"ejemplo de ventanas.py","file_name":"ejemplo de ventanas.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29437139847","text":"from PyQt6.QtWidgets import QPushButton\n\n\n\nclass Insert_all_button(QPushButton):\n def __init__(self, text, summ, activeQLineEdit):\n super().__init__(text = text)\n self.summ = int(summ)\n self.activeQLineEdit = activeQLineEdit\n self.clicked.connect(self.func)\n\n def func(self, e):\n self.activeLine = self.activeQLineEdit.getActiveLine()\n\n if self.activeLine.nameLine == \"Cash\":\n self.numb = self.summ - self.activeQLineEdit.getCardMoney()\n self.activeLine.setText(str(self.numb))\n else:\n self.numb = self.summ - self.activeQLineEdit.getCashMoney()\n self.activeLine.setText(str(self.numb))","repo_name":"SelfMullerMikhail/PyQT_pass_copy","sub_path":"widgets/main_window/pay_window/insert_all_button.py","file_name":"insert_all_button.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"37616211336","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@FileName : check.py\n@Description : 检查各种条件\n@Author : 齐鲁桐\n@Email : qilutong@yahoo.com\n@Time : 2019-12-23 下午11:32\n@Modify : None\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport os\n\n\ndef chk_sep(path):\n \"\"\"\n 判断路径字符串末尾是否有分隔符\n :param path: 要检查的路径\n :return: 布尔值\n \"\"\"\n if path[-1] != os.path.sep:\n return False\n else:\n return True\n\n\ndef chk_dir(directory):\n \"\"\"\n 判断目录是否存在\n :param directory: 目录路径\n :return:\n \"\"\"\n if os.path.exists(directory):\n if os.path.isdir(directory):\n print(\"目录{}已经存在\".format(directory))\n return True\n else:\n print(\"路径{}存在,但并不是目录\".format(directory))\n return False\n else:\n print(\"目录{}不存在\".format(directory))\n return False\n\n\ndef chk_file(file_name):\n \"\"\"\n 判断文件是否存在\n :param file_name: 文件路径\n :return:\n \"\"\"\n if os.path.exists(file_name):\n if os.path.isfile(file_name):\n print(\"文件{}已经存在\".format(file_name))\n return True\n else:\n print(\"路径{}存在,但并不是文件\".format(file_name))\n return False\n else:\n print(\"文件{}不存在\".format(file_name))\n return False\n\n\nif __name__ == '__main__':\n a = ['aaa', 'bbb', 'ccc']\n path1 = os.path.sep.join(a)\n path2 = os.path.sep.join(a) + os.path.sep\n print(chk_sep(path1))\n print(chk_sep(path2))\n","repo_name":"qilutong/pyutil","sub_path":"pyutil/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2747912037","text":"import time\nimport os\nimport argparse\nimport re\n\n\n\n\ndef main():\n #python Step_2_run_fastqQC.py -sampleId SRR6388218 -jobDir GSE108256_res\n print('Running step 2 FastQC')\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-sampleId\", \"--sampleId\", help=\"Proivde sample Id\")\n parser.add_argument(\"-jobDir\", \"--jobDir\", help=\"Proivde jobDir\")\n args = parser.parse_args()\n\n fastqDir = args.jobDir + '/' + args.sampleId + '/fastq_files/'\n #make the fast QC directory\n qcDir = args.jobDir + '/' + args.sampleId + '/fastQC'\n os.system('mkdir ' + qcDir)\n\n fastQCCmd = '/home/rami/hdd/tools/fastqc/FastQC/fastqc '\n #get the fastq files\n for file in os.listdir(fastqDir):\n cmd = fastQCCmd + ' ' + fastqDir + file + ' -o ' + qcDir\n print('fastqQC cmd:', cmd)\n os.system(cmd)\n\n \n\n\nmain()\n","repo_name":"LiuzLab/mecp2sca1","sub_path":"Step_2_run_fastqQC.py","file_name":"Step_2_run_fastqQC.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74657446300","text":"from graph_dataset.trust_and_reputation import settings\nfrom graph_dataset.trust_and_reputation.tools import Tools\n\n\nclass TrustComputation:\n\n def __init__(self, neo, transaction_computation_instance):\n self.neo = neo\n self.trust_repository = {}\n self.trust_object = {}\n self.overall_trust_iots = {}\n self.mean_trust = {}\n self.transaction_core = transaction_computation_instance\n\n def compute_trust_instances(self, start_instance, final_instance, context, file_format, size, community):\n list_transactions = self.transaction_core.list_transactions\n # check which trust score to compute\n if (start_instance, final_instance) not in list_transactions:\n trust_score = settings.INITIAL_TRUST_VALUE\n else:\n # if there is no transaction with those context and file format, it returns the initial trust value\n if (context, file_format) not in list_transactions[(start_instance, final_instance)]:\n trust_score = settings.INITIAL_TRUST_VALUE\n else:\n # check if instances are in the same network\n if self.neo.object_in_the_same_network(start_instance, final_instance):\n trust_score = self.compute_trust_instances_engine(start_instance, final_instance, context,\n file_format, size, community)\n else:\n shortest_path = self.neo.get_shortest_path_instances(start_instance, final_instance)\n trust_score = self.compute_trust_instance_different_network(shortest_path, context, file_format,\n size, community)\n trust_score = Tools.compute_resilience_system(self.neo.resilience_system_nodes, trust_score, start_instance)\n self.update_trust_repository(start_instance, final_instance, context, file_format, trust_score)\n return trust_score\n\n def compute_trust_instances_engine(self, start_instance, final_instance, context, file_format, size, community):\n list_transactions = self.transaction_core.list_transactions\n # if instances have never communicated before\n transactions_to_watch = list_transactions[(start_instance, final_instance)][(context, file_format)]\n success_number = 0.\n for t in transactions_to_watch:\n if t.success == 1:\n success_number += 1.\n success_fraction = success_number / len(transactions_to_watch)\n if (context, file_format) not in self.transaction_core.maxNumTranSet[community]:\n transet_fraction_den = 1.\n else:\n transet_fraction_den = float(self.transaction_core.maxNumTranSet[community][(context, file_format)])\n transet_fraction = len(transactions_to_watch) / transet_fraction_den\n actual_max_size = float(self.transaction_core.maxSize[community][(context, file_format)])\n if size > actual_max_size:\n size_fraction = 1.\n else:\n size_fraction = size / actual_max_size\n trust_score = (settings.ALPHA * success_fraction +\n settings.BETA * transet_fraction +\n settings.GAMMA * size_fraction) / \\\n (settings.ALPHA + settings.BETA + settings.GAMMA)\n return trust_score\n\n def compute_trust_instance_different_network(self, shortest_path, context, file_format, size, community):\n list_transactions = self.transaction_core.list_transactions\n trust_score = 1.\n for (start_instance, final_instance) in shortest_path:\n if (start_instance, final_instance) not in list_transactions:\n trust_score *= settings.INITIAL_TRUST_VALUE\n else:\n if (context, file_format) not in list_transactions:\n trust_score *= settings.INITIAL_TRUST_VALUE\n else:\n start_instance = start_instance[\"code\"]\n final_instance = final_instance[\"code\"]\n if (start_instance, final_instance) in self.trust_repository:\n if (context, file_format) in self.trust_repository[(start_instance, final_instance)]:\n trust_score *= self.trust_repository[(start_instance, final_instance)][(context, file_format)]\n else:\n trust_score *= self.compute_trust_instances_engine(start_instance[\"code\"],\n final_instance[\"code\"],\n context, file_format, size, community)\n else:\n trust_score *= self.compute_trust_instances_engine(start_instance[\"code\"],\n final_instance[\"code\"],\n context, file_format, size,\n community)\n return trust_score\n\n def update_trust_repository(self, start_instance, final_instance, context, file_format, trust_instances):\n if (start_instance, final_instance) not in self.trust_repository:\n self.trust_repository[(start_instance, final_instance)] = {}\n self.mean_trust[(start_instance, final_instance)] = {}\n if (context, file_format) not in self.mean_trust[(start_instance, final_instance)]:\n self.mean_trust[(start_instance, final_instance)][(context, file_format)] = []\n self.trust_repository[(start_instance, final_instance)][(context, file_format)] = trust_instances\n self.mean_trust[(start_instance, final_instance)][(context, file_format)].append(trust_instances)\n\n def get_trust_instances(self, ins_start, ins_finish, context, file_format):\n found = False\n trust = settings.INITIAL_TRUST_VALUE\n if (ins_start, ins_finish) in self.trust_repository:\n if (context, file_format) in self.trust_repository[(ins_start, ins_finish)]:\n found = True\n trust = self.trust_repository[(ins_start, ins_finish)][(context, file_format)]\n if not found:\n if (ins_start, ins_finish) not in self.trust_repository:\n self.trust_repository[(ins_start, ins_finish)] = {}\n self.trust_repository[(ins_start, ins_finish)][(context, file_format)] = trust\n return trust\n\n def compute_trust_object_to_iot(self):\n trust_objects_to_iot = {}\n index_to_fill = []\n objects_with_instances = self.neo.objects_with_instances\n for obj in objects_with_instances:\n trust_objects_to_iot[obj] = {}\n list_instances = objects_with_instances[obj]\n list_community_of_object = []\n for instance in list_instances:\n list_community_of_object.append(self.neo.get_community_from_instance(instance))\n for community in range(1, self.neo.number_of_communities + 1):\n if str(community) in list_community_of_object:\n trust_objects_to_iot[obj][str(community)] = {}\n instances_community = self.neo.get_instances_from_community(str(community))\n occurrences = {}\n for obj_instance in list_instances:\n for instance in instances_community:\n if (obj_instance, instance) in self.trust_repository:\n for cff in self.trust_repository[(obj_instance, instance)]:\n if cff not in trust_objects_to_iot[obj][str(community)]:\n trust_objects_to_iot[obj][str(community)][cff] = 0.\n occurrences[cff] = 0\n trust_objects_to_iot[obj][str(community)][cff] = \\\n trust_objects_to_iot[obj][str(community)][cff] + \\\n self.trust_repository[(obj_instance, instance)][cff]\n occurrences[cff] = occurrences[cff] + 1\n for cff in occurrences:\n trust_objects_to_iot[obj][str(community)][cff] = trust_objects_to_iot[obj][str(community)][\n cff] / \\\n occurrences[cff]\n else:\n index_to_fill.append((obj, str(community)))\n # compute trust to iots from the point of view of objects that have no instance in those iots.\n for (obj, community_to_trust) in index_to_fill:\n list_instances = objects_with_instances[obj]\n trust_obj = {}\n occurrences = {}\n for instance in list_instances:\n trust_objects_to_iot[obj][community_to_trust] = {}\n mine_community = self.neo.get_community_from_instance(instance)\n for cff in self.overall_trust_iots[(mine_community, community_to_trust)]:\n if cff in trust_objects_to_iot[obj][mine_community]:\n if cff not in trust_objects_to_iot[obj][community_to_trust]:\n trust_objects_to_iot[obj][community_to_trust][cff] = 0.\n trust_obj[cff] = 0.\n occurrences[cff] = 0\n trust_obj[cff] = trust_obj[cff] + trust_objects_to_iot[obj][mine_community][cff] * \\\n self.overall_trust_iots[(mine_community, community_to_trust)][cff]\n occurrences[cff] = occurrences[cff] + 1\n for cff in trust_obj:\n trust_objects_to_iot[obj][community_to_trust][cff] = trust_obj[cff] / occurrences[cff]\n return trust_objects_to_iot\n\n def compute_overall_trust_iots(self):\n for comm_1 in range(1, self.neo.number_of_communities + 1):\n for comm_2 in range(1, self.neo.number_of_communities + 1):\n if comm_1 != comm_2:\n objects_first_community = self.neo.get_objects_from_community(str(comm_1))\n objects_second_community = self.neo.get_objects_from_community(str(comm_2))\n self.overall_trust_iots[(str(comm_1), str(comm_2))] = self.compute_trust_iots(objects_first_community,\n objects_second_community)\n\n def compute_trust_iots(self, objects_iot_1, objects_iot_2):\n trust_iots = {}\n occurrences = {}\n for obj_iot_1 in objects_iot_1:\n for obj_iot_2 in objects_iot_2:\n if (obj_iot_1, obj_iot_2) in self.trust_object:\n for cff in self.trust_object[(obj_iot_1, obj_iot_2)]:\n if cff not in trust_iots:\n trust_iots[cff] = 0.\n occurrences[cff] = 0\n trust_iots[cff] = trust_iots[cff] + self.trust_object[(obj_iot_1, obj_iot_2)][cff]\n occurrences[cff] = occurrences[cff] + 1\n for cff in trust_iots:\n trust_iots[cff] = trust_iots[cff] / (occurrences[cff] + len(objects_iot_1))\n return trust_iots\n\n def compute_trust_objects(self):\n list_objects = self.neo.objects_with_instances\n for start_object in list_objects:\n for final_object in list_objects:\n if start_object != final_object:\n sum_values = {}\n occurrences = {}\n start_object_instances = list_objects[start_object]\n final_object_instances = list_objects[final_object]\n for start_instance in start_object_instances:\n for final_instance in final_object_instances:\n if (start_instance, final_instance) in self.trust_repository:\n for (context, file_format) in self.trust_repository[(start_instance, final_instance)]:\n if (context, file_format) not in sum_values:\n sum_values[(context, file_format)] = 0.\n occurrences[(context, file_format)] = 0\n sum_values[(context, file_format)] = sum_values[(context, file_format)] + \\\n self.trust_repository[(start_instance, final_instance)][(context, file_format)]\n occurrences[(context, file_format)] = occurrences[(context, file_format)] + 1\n if sum_values:\n self.trust_object[(start_object, final_object)] = {}\n for (context, file_format) in sum_values:\n self.trust_object[(start_object, final_object)][(context, file_format)] = \\\n sum_values[(context, file_format)] / occurrences[(context, file_format)]\n","repo_name":"lucav48/miot-simulator","sub_path":"graph_dataset/trust_and_reputation/computation_core/TrustComputation.py","file_name":"TrustComputation.py","file_ext":"py","file_size_in_byte":13375,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"30066155929","text":"from collections import namedtuple as nt\n\nPoint = nt('Point', ['x', 'y'])\np1 = Point(0, 2)\np2 = Point(x=3, y=-1)\n\ntable = []\nwith open('collections2.csv') as fh_in:\n Table = nt('Table', fh_in.readline().rstrip().split(','))\n for line in fh_in.readlines():\n table += [Table(*line.rstrip().split(','))]\n","repo_name":"Sokoloff-M/scripts","sub_path":"collections2.py","file_name":"collections2.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"26273995747","text":"from hierarc.LensPosterior.anisotropy_config import AnisotropyConfig\nimport unittest\nimport pytest\n\n\nclass TestAnisotropyConfig(object):\n\n def setup(self):\n self.r_eff = 2\n self.config_om = AnisotropyConfig(anisotropy_model='OM', r_eff=self.r_eff)\n self.config_gom = AnisotropyConfig(anisotropy_model='GOM', r_eff=self.r_eff)\n self.config_const = AnisotropyConfig(anisotropy_model='const', r_eff=self.r_eff)\n\n def test_kwargs_anisotropy_base(self):\n kwargs = self.config_om.kwargs_anisotropy_base\n assert kwargs['r_ani'] == self.r_eff\n\n kwargs = self.config_gom.kwargs_anisotropy_base\n assert kwargs['r_ani'] == self.r_eff\n assert kwargs['beta_inf'] == 1\n\n kwargs = self.config_const.kwargs_anisotropy_base\n assert kwargs['beta'] == 0.1\n\n def test_ani_param_array(self):\n ani_param_array = self.config_om.ani_param_array\n assert len(ani_param_array) == 6\n\n ani_param_array = self.config_gom.ani_param_array\n assert len(ani_param_array[0]) == 6\n assert len(ani_param_array[1]) == 4\n\n ani_param_array = self.config_const.ani_param_array\n assert len(ani_param_array) == 7\n\n def test_anisotropy_kwargs(self):\n a_ani = 2\n beta_inf = 0.5\n kwargs = self.config_om.anisotropy_kwargs(a_ani)\n assert kwargs['r_ani'] == a_ani * self.r_eff\n\n kwargs = self.config_gom.anisotropy_kwargs(a_ani, beta_inf)\n assert kwargs['r_ani'] == a_ani * self.r_eff\n assert kwargs['beta_inf'] == beta_inf\n\n kwargs = self.config_const.anisotropy_kwargs(a_ani)\n assert kwargs['beta'] == a_ani\n\n\nclass TestRaise(unittest.TestCase):\n\n def test_raise(self):\n\n with self.assertRaises(ValueError):\n AnisotropyConfig(anisotropy_model='BAD', r_eff=1)\n\n with self.assertRaises(ValueError):\n conf = AnisotropyConfig(anisotropy_model='OM', r_eff=1)\n conf._anisotropy_model = 'BAD'\n kwargs = conf.kwargs_anisotropy_base\n\n with self.assertRaises(ValueError):\n conf = AnisotropyConfig(anisotropy_model='OM', r_eff=1)\n conf._anisotropy_model = 'BAD'\n kwargs = conf.anisotropy_kwargs(a_ani=1, beta_inf=1)\n\n\nif __name__ == '__main__':\n pytest.main()\n","repo_name":"sibirrer/hierArc","sub_path":"test/test_LensPosterior/test_anisotropy_config.py","file_name":"test_anisotropy_config.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"69"} +{"seq_id":"8169416050","text":"import re, string\r\na=input() \r\nif len(a) <= 300:\r\n \r\n w=[]\r\n a=a.split()\r\n\r\n\r\n\r\n res = {i : a.count(i) for i in set(a)}\r\n \r\n\r\n for i in sorted (res.keys()) : \r\n\r\n w.append(i)\r\n w.pop(0)\r\n \r\n \r\n for i in w :\r\n t=list(res.values())[list(res.keys()).index(i)] \r\n \r\n print(\"{}:{}\".format(i,t))\r\n","repo_name":"naveenbskn/python","sub_path":"22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"40665673342","text":"class Solution:\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n hashMap = {}\n sizeNum1 = len(nums1)\n sizeNum2 = len(nums2)\n res = []\n \n for i in range(sizeNum1):\n \n hashMap[nums1[i]] = 1\n \n keys = hashMap.keys()\n \n for j in range(sizeNum2):\n if nums2[j] in keys and nums2[j] not in res:\n res.append(nums2[j])\n \n return res","repo_name":"Shakileash5/leetCode","sub_path":"intersection-of-two-arrays/intersection-of-two-arrays.py","file_name":"intersection-of-two-arrays.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"38608799755","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 24 21:54:10 2015\n\n@author: luis\n\"\"\"\n\nimport sqlite3\n\n#create a new database if the database doesn't already exist\nconn=sqlite3.connect('new.db')\n#conn=sqlite3.connect(\":memory:\")\n\n#get a cursor object\ncursor=conn.cursor()\n\ncursor.execute(\"INSERT INTO population VALUES('New York City',\\\n'NY',8200000)\")\ncursor.execute(\"INSERT INTO population VALUES('San Francisco',\\\n'CA',80000)\")\n\nconn.commit()\nconn.close()\n","repo_name":"LuisSoares/realpython","sub_path":"sql/sqla.py","file_name":"sqla.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"36690910461","text":"import sys\nsys.path.append(\"/Users/pawan/Documents/Elucidata/Knowledge_Graphs/biomedical_ontology/biomedical_ontologies_kg/\")\nimport pandas as pd\nfrom dotenv import load_dotenv\nfrom scripts.create_db import save_to_db,read_from_db,add_table_name\n\nload_dotenv()\ndef main_gene_pathway():\n \"\"\"\n gobp = pd.read_csv('gobp.csv')\n gocc = pd.read_csv('gocc.csv')\n gomf = pd.read_csv('gomf.csv')\n hpo = pd.read_csv('hpo.csv')\n\n final = pd.DataFrame()\n\n for types in [gobp, gocc, gomf, hpo]: \n temp = types[[\"gs_exact_source\",\"gene_symbol\",\"gs_subcat\"]]\n temp = temp.drop_duplicates().reset_index(drop=True)\n print(temp.head())\n final = pd.concat([final, temp])\n\n final.rename(columns={'gs_exact_source':'pathway_id'}).to_csv(\"pathway_gene_map.csv\")\n \"\"\"\n final_df = pd.read_csv('ontologies/pathway_gene_map.csv')\n final_df['relation'] = 'associated_with'\n genes = read_from_db(\"gene__nodes\")\n pathway = read_from_db(\"pathway__nodes\")\n final_df = pd.merge(final_df, genes[['gene_id','gene_symbol']], on='gene_symbol')[['gene_id','pathway_id','relation']]\n \n add_table_name([\"gene__associated_with__relation\",'gene','pathway','associated_with','not_mapped'])\n save_to_db(final_df, \"gene__associated_with__relation\")\n\n# main\nif __name__ == '__main__':\n main_gene_pathway()","repo_name":"pverma12394/knowledge_graph","sub_path":"ontology/pathway_gene.py","file_name":"pathway_gene.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33487222613","text":"\"\"\"\n Dave Skura\n\n\tConnect to MySQL/Postgres\n\tConnect to local sqlite_db\n\tread table details\n\tcalc metrics \n\tload metrics to table in sqlite cache tables\n\t\n\n\"\"\"\nimport logging\nimport sys\nimport readchar\n\nfrom PostgresTableAnalysis import runner as Postgres_runner\nfrom MySQLTableAnalysis import runner as MySQL_runner\n\n\nif __name__ == '__main__':\n\tlogging.basicConfig(level=logging.INFO)\n\tlogging.info(\" Starting Table Analysis\") # \n\n\tprint('Which database do you want to analyze ?')\n\tprint('1. Postgres')\n\tprint('2. MySQL')\n\tselectchar = readchar.readchar()\n\tif selectchar.upper() == '1':\n\t\tPostgres_runner('public','tableowners')\n\telif selectchar.upper() == '2':\n\t\tMySQL_runner('world','city')\n\telse:\n\t\tsys.exit(0)\n\n","repo_name":"daveskura/davex","sub_path":"src/davex/TableAnalysis.py","file_name":"TableAnalysis.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"5410164694","text":"# Персонажи книги Гарри Поттер\n# Опишем словарем, списком и множеством\n\n# Составим список персонажей, можно обращатсья по индексу элемента начиная с 0 и при необходимости перебирать и изменять список\nhogwarts_students = ['Harry Potter', 'Hermione Granger', 'Ron Weasly']\n\n# Поиск элемента возможен по индексу:\nprint(hogwarts_students[0]) \n# Вывод: Harry Potter\n\n# Изменение списка (удаление элемента)\nhogwarts_students.remove(\"Harry Potter\")\nprint(hogwarts_students) \n# Вывод: ['Hermione Granger', 'Ron Weasly']\n\n\n# То же самое можно описать множеством.\nhogwarts_students = {'Harry Potter', 'Hermione Granger', 'Ron Weasly'}\n# Обращаться по номеру уже нельзя, но можно убрать дубли, если они вдруг есть:\nhogwarts_students = {'Harry Potter', 'Hermione Granger', 'Ron Weasly', 'Ron Weasly'}\nprint(hogwarts_students) \n# Вывод: {'Harry Potter', 'Ron Weasly', 'Hermione Granger'}\n# Также можно найти пересечения между двумя множествами и сразу убрать дубли например:\n# Первое множество, ученики Хогвартса\nhogwarts_students = {'Harry Potter', 'Hermione Granger', 'Ron Weasly'}\n# Второе множество - члены семьи Гарри\nharrys_family = {'Harry Potter', 'Dudley Dursley', 'Vernon Dursley', 'Petunia Dursley'}\n# Вычислим, кто из семьи Гарри попал в Хогвартс через пересечение множеств\nwho_is_in_hogwarts = hogwarts_students & harrys_family\nprint(who_is_in_hogwarts)\n# Вывод: {'Harry Potter'}\n\n# Применим словари:\n# Ученики по факультетам, для примера уникальные ключи - имена учеников\nfaculty = {'Harry Potter': 'Gryffindor', 'Hermione Granger': 'Gryffindor', 'Ron Weasly': 'Gryffindor', 'Drako Malfoy': 'Slytherin'}\n\n# Можно искать по ключу, например найдем факультет на котором учится Гарри\nprint(faculty['Harry Potter'])\n# Вывод: Gryffindor\n\n# Можем добавить в словарь новую запись, нужно чтоб ключ был уникальным, иначе перезапишется значение у текущего ключа:\nfaculty['Vincent Crabbe'] = 'Slytherin'\n\nprint(faculty)\n# Вывод:\n# {'Harry Potter': 'Gryffindor', 'Hermione Granger': 'Gryffindor', 'Ron Weasly': 'Gryffindor', 'Drako Malfoy': 'Slytherin', 'Vincent Crabbe': 'Slytherin'}","repo_name":"Katusss/python_AAS22","sub_path":"Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"74803331420","text":"import socket\nimport struct\nfrom thingset.packet import TSPacket, SingleFrame\n\nclass CANsocket(object):\n FMT = ' 0:\n assert stamp != \"FILLER\"\n\n\ndef test_to_idleon_companion(exporter):\n exported = exporter.to_idleon_companion()\n for key, value in exported.items():\n assert value, f\"{key} is empty\"\n for statue_name in exported[\"statues\"]:\n assert statue_name.endswith(\" Statue\")\n\n\ndef test_get_empties_error():\n with pytest.raises(ValueError):\n get_empties([])\n\n\ndef test_get_empties(exporter):\n cogs = exporter.cog_order\n empties = get_empties(cogs)\n\n assert len(empties) == cogs[:96].count(\"Blank\")\n for slot in empties:\n assert slot.keys() == {\"empties_x\", \"empties_y\"}\n assert slot[\"empties_x\"] in range(12)\n assert slot[\"empties_y\"] in range(8)\n\n\n@pytest.mark.parametrize(\n (\"name\", \"cog_type\"),\n [\n (\"Blank\", None),\n (\"Player_\", \"Character\"),\n (\"Player_XYZ\", \"Character\"),\n (\"CogY\", \"Yang_Cog\"),\n (\"CogZ\", \"Omni_Cog\"),\n (\"Cog1A00\", \"Cog\"),\n (\"XYZ\", \"Cog\"),\n (\"_\", \"Cog\"),\n ],\n)\ndef test_get_cog_type(name, cog_type):\n assert cog_type == get_cog_type(name)\n\n\n@pytest.mark.parametrize((\"direction\", \"cog_type\"), cog_type_map.items())\ndef test_get_cog_type_directions(direction, cog_type):\n assert f\"{cog_type}_Cog\" == get_cog_type(f\"CogABC{direction}\")\n\n\n@pytest.mark.xfail\ndef test_get_cog_data():\n raise NotImplementedError\n\n\ndef test_to_cogstruction(exporter):\n for key, value in exporter.to_cogstruction().items():\n assert value, f\"{key} is empty\"\n","repo_name":"desophos/idleon-saver","sub_path":"tests/test_export.py","file_name":"test_export.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"69"} +{"seq_id":"3555165020","text":"def Restart():\n \"\"\"Function To Restart The Game Again.The entire script is in this \n function.\"\"\"\n import pickle\n from random import randint\n def random_mouse(extent):\n \"\"\"Function to get 2 random integers as the mouse row and column.\n It takes an input which extends its range upon the size of the grid\"\"\" \n mouses_row = randint(1,extent)\n mouses_coloumn = randint(1,extent)\n #print(mouses_row)\n #print(mouses_coloumn)\n return [mouses_row,mouses_coloumn]\n \n def developing_lists(column_rows):\n \"\"\"\"Function to develop lists, this function takes an input of the size\n of the board(int) and develops lists accordingly\"\"\"\n rows = column_rows \n columns = column_rows \n lists = [0] * rows\n for i in range(columns):\n lists[i] = [0] * rows\n return lists\n \n def print_board(board_size,lists,guess_row,guess_coloumn,steps,acquired_level):\n \"\"\"\"Function to print the board.When this function is executed it\n prints the lists in the form of a board. It takes an input the board size(int) \n lists , guess_row(int) , guess_coloumn(int) , steps(int) , acquired_level(int)which the user has selected\"\"\"\n \n column_rows = board_size\n a = developing_lists(column_rows)\n for column_heading in range(board_size + 1):\n print(column_heading , end = \" \")\n print(\" \")\n if acquired_level == 5 :\n for i in range(board_size):\n print((i+1),*lists[i] , sep = \" \")\n \n\n if lists[guess_row - 1][guess_coloumn - 1] == steps or lists[guess_row -1 ][guess_coloumn - 1] == \"X\":\n for i in range(board_size):\n print((i+1),*lists[i] , sep = \" \")\n else: \n a[guess_row - 1][guess_coloumn - 1] != steps or a[guess_row - 1][guess_coloumn - 1] != \"X\"\n for i in range(board_size):\n print((i+1),*a[i] , sep = \" \") \n \n def actual_steps(asked_row,asked_coloumn,mouse_rows,mouses_coloumns):\n \"\"\"Function to calculate the steps away from the mouse. It takes four \n inputs(int) and Returns the number of steps or the shortest distance.\"\"\" \n if asked_row >= mouse_rows and asked_coloumn >= mouses_coloumns:\n spaces = (asked_row - mouse_rows) + (asked_coloumn - mouses_coloumns)\n return spaces\n elif mouse_rows >= asked_row and mouses_coloumns >= asked_coloumn:\n spaces = (mouse_rows - asked_row) + (mouses_coloumns - asked_coloumn)\n return spaces\n elif asked_row >= mouse_rows and mouses_coloumns >= asked_coloumn:\n spaces = (asked_row - mouse_rows) + (mouses_coloumns - asked_coloumn)\n return spaces\n else : \n mouse_rows >= asked_row and asked_coloumn >= mouses_coloumns\n spaces = (mouse_rows - asked_row) + (asked_coloumn - mouses_coloumns)\n return spaces\n \n def save_score(points,selectedlevel):\n \"\"\"Function to save your score.This function saves the points in a \n file to view later. It takes two inputs points(int) and selectedlevel(int)\n and saves it to a file.\"\"\"\n if selectedlevel == 1:\n selectedlevel = \"EASY\"\n elif selectedlevel == 2:\n selectedlevel = \"MEDIUM\"\n elif selectedlevel == 3:\n selectedlevel = \"HARD\"\n savescores = input(\"Would you like to save your score ? (Y/N)\")\n permitted = [\"y\",\"Y\",\"n\",\"N\"]\n if savescores not in permitted:\n print(\"YOU CAN ONLY PRESS Y OR N\")\n save_score(points,selectedlevel)\n if savescores == \"y\" or savescores == \"Y\":\n f = open(\"Mouse_hunter_scores.txt\",\"a\")\n a = f.write(input(\"Enter your name :\") + \" : \" + str(points) + \" : \" \n + (selectedlevel) + \"\\n\")\n f.close\n return a\n elif savescores == \"n\" or savescores == \"N\":\n return \"\"\n \n def points_scored(guess_es,selectedlevel):\n \"\"\"Function to calculate the points user has scored. It takes inputs \n the number of guesses(int) , selectedlevel(int) and outputs the points scored(int).\"\"\"\n points = 1100\n for i in range(1,guess_es+1):\n points = points - 100\n print(\"you have scored \" + str(points) + \" points \")\n save_score(points,selectedlevel)\n \n \n def user_move(selected_level):\n \"\"\" Function to ask the users to guess the row and column and display\n if the mouse is on that row and column It takes an input the selected \n level(int) and displays the board size and guesses accordingly. \"\"\"\n try:\n acquired_level = selected_level\n steps = 0\n if acquired_level == 5:\n save_game_file = open(\"Mouse_hunter_save.txt\", \"rb\")\n saved_game_list = lists = pickle.load(save_game_file)\n mouses_row = pickle.load(save_game_file)\n mouses_coloumn = pickle.load(save_game_file)\n guesses = pickle.load(save_game_file)\n selected_level = pickle.load(save_game_file)\n steps = pickle.load(save_game_file)\n board_size =pickle.load(save_game_file)\n chances_and_boardsize = {1:[8,5],2:[5,7],3:[4,9],4:[4,5],5:[]}\n chances_and_boardsize[5] = [guesses,board_size]\n permitted = [1,2,3,4]\n if acquired_level in permitted:\n chances_and_boardsize = {1:[8,5],2:[5,7],3:[4,9],4:[4,5]} \n for i in chances_and_boardsize:\n if i == acquired_level:\n given_chances = chances_and_boardsize[i][0] \n board_size = chances_and_boardsize[i][1]\n lists = developing_lists(board_size)\n guess = 1\n if acquired_level == 5:\n print_board(board_size,saved_game_list,mouses_row,mouses_coloumn,steps,acquired_level)\n if acquired_level in permitted:\n print_board(board_size,lists,guess,guess,steps,acquired_level)\n if selected_level == 4:\n mouses_row = int(input(\"select a row to hide ? : \"))\n mouses_coloumn = int(input(\"select a column to hide ? : \"))\n allowed = [1,2,3] \n if acquired_level in allowed:\n t = random_mouse(board_size)\n mouses_row = t[0]\n mouses_coloumn = t[1]\n guesses = 1\n print (\"you will get \" +(str(given_chances))+ \" guesses to find the mouse(X)\")\n while guesses <= given_chances:\n permitted = [1,2,3]\n print(\"guess...\" + str(guesses))\n if selected_level not in permitted:\n guess_row = randint(1,5)\n guess_coloumn = randint(1,5)\n if selected_level in permitted:\n if guesses >= 2:\n save_game = input(\"Save Game : ? (Y/N)\")\n if save_game == \"y\" or save_game == \"Y\":\n save_game_file = open(\"Mouse_hunter_save.txt\",\"wb\")\n pickle.dump(lists,save_game_file)\n pickle.dump(mouses_row,save_game_file)\n pickle.dump(mouses_coloumn,save_game_file)\n pickle.dump(guesses,save_game_file)\n pickle.dump(selected_level,save_game_file)\n pickle.dump(steps,save_game_file)\n pickle.dump(board_size,save_game_file)\n save_game_file.close\n break\n guess_row = int(input(\"guess the row : \"))\n guess_coloumn = int(input(\"guess the coloumn : \"))\n if guess_row > board_size or guess_coloumn > board_size:\n print(\"SELECTED ROW OR COLUMN OUT OF RANGE !!\")\n user_move(selected_level)\n if guess_row == 0 or guess_coloumn == 0:\n print(\"SELECTED ROW OR COLUMN OUT OF RANGE !!\")\n user_move(selected_level)\n if guess_row == mouses_row and guess_coloumn == mouses_coloumn:\n lists[mouses_row - 1] .pop(mouses_coloumn - 1)\n lists[mouses_row - 1].insert(mouses_coloumn - 1,\"X\")\n print_board(board_size,lists,guess_row,guess_coloumn,steps,acquired_level)\n print(\"congratulations you caught the mouse in \" +str(guesses)+\" guess\")\n if selected_level != 4:\n points_scored(guesses,selected_level)\n play_again = input(\"would you like to restart ? (Y/N)\")\n if play_again == \"Y\" or play_again == \"y\":\n Restart()\n if play_again == \"N\" or play_again == \"n\":\n break\n break\n elif guess_row != mouses_row or guess_coloumn != mouses_coloumn:\n if guess_row <= board_size or guess_coloumn <= board_size:\n lists[guess_row - 1].pop(guess_coloumn - 1)\n steps = actual_steps(guess_row,guess_coloumn,mouses_row,mouses_coloumn)\n lists[guess_row - 1].insert(guess_coloumn - 1,steps)\n guesses = guesses + 1\n print_board(board_size,lists,guess_row,guess_coloumn,steps,acquired_level)\n else :\n points = 0 \n lists[mouses_row - 1] .pop(mouses_coloumn - 1)\n lists[mouses_row - 1].insert(mouses_coloumn - 1,\"X\")\n print_board(board_size,lists,guess_row,guess_coloumn,steps,acquired_level)\n print(\"YOU RAN OUT OF GUESSES => GAME OVER\")\n print(\"you have scored \" + str(points) + \" points \")\n if selected_level != 4:\n save_score(points,selected_level)\n play_again = input(\"would you like to restart ? (Y/N)\")\n if play_again == \"Y\" or play_again == \"y\":\n Restart()\n except ValueError:\n print(\"YOU CAN ONLY ENTER A NUMBER !!\")\n user_move(selected_level)\n\n def welcome_screen():\n \"\"\" Function to print the welcome screen for the game \"\"\"\n print(\" \"*18 , \"*\"*40)\n print(\" \"*18, \"| (\\___/) MOUSE-HUNTERZ |\")\n print(\" \"*18, \"| |O O\\ |\")\n print(\" \"*18, \"| / \\./ \\ CREATED BY |\")\n print(\" \"*18, \"| / \\ :FAIZAAN: |\")\n print(\" \"*18, \"| } ' ' } / |\")\n print(\" \"*18, \"| | / \\____/ |\")\n print(\" \"*18, \"| _\\_______\\_/ |\")\n print(\" \"*18,\"*\"*40)\n print(\" \"*27,\"PRESS S TO START GAME \\n\",\" \"*25,\"PRESS R TO SEE RANKINGS \\n\",\" \"*25,\"PRESS I FOR INSTRUCTIONS \\n\",\" \"*18,\"*\"*40)\n start_options = input()\n permitted = [\"s\",\"S\",\"R\",\"r\",\"i\",\"I\"]\n if start_options not in permitted:\n print(\"YOU CAN ONLY SELECT THE GIVEN OPTIONS\")\n welcome_screen()\n if start_options == \"S\" or start_options == \"s\":\n print(\"SELECT A LEVEL => :::(1)EASY (2)MEDIUM (3)HARD (4)AI (5)LOAD GAME:::\")\n select_level = int(input())\n if select_level <= 5 and select_level > 0:\n user_move(select_level)\n if select_level > 5:\n print(\"YOU CAN ONLY ENTER THE GIVEN NUMBERS\")\n welcome_screen()\n elif start_options == \"r\" or start_options == \"R\":\n with open(\"Mouse_hunter_scores.txt\",\"r+\") as ranks_file:\n ranks_file = ranks_file.readlines()\n for rankings in ranks_file:\n print(rankings)\n welcome_screen()\n if start_options == \"i\" or start_options == \"I\":\n print(\" \"*16 , \"STARTING OF THE GAME,THE MOUSE WILL BE RANDOMLY \\n PLACED ON THE GRID. YOU HAVE TO FIND THE MOUSE BE SELECTING THE ROW AND COLUMN. YOU CAN ALSO CHOOSE ON WHICH LEVEL YOU WOULD LIKE TO PLAY WHICH WOULD CHANGE THE NUMBER OF LIVES AND SIZE OF THE GRID. SELECTING (AI) GIVES YOU THE ABILITY TO HIDE THE MOUSE AND THE COMPUTER TO FIND IT. AFTER EACH GUESS YOU CAN SAVE YOUR PROGRESS AND PLAY LATER. \")\n welcome_screen()\n welcome_screen()\nRestart()","repo_name":"faiz687/MouseHunter","sub_path":"Main/Mouse_hunter.py","file_name":"Mouse_hunter.py","file_ext":"py","file_size_in_byte":11194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"35902431163","text":"#!/usr/bin/env python3\n# python imports\nimport random\nimport socket\nimport uuid\nimport base64\nimport os\nimport time\nimport zipfile\n# specific imports\nfrom BroBot import CTFBotBro\nfrom JokerBot import CTFBotJoker\nfrom LazyBot import CTFBotLazy\nfrom SupervisorBot import CTFSupervisor\nfrom datatypes import DataEntry\nfrom tech_support import BadWordException\nfrom queue import Queue\nfrom threading import Thread\n# own modules\nimport secWrap\n\n\n# server values\nIP = '0.0.0.0'\nPORT = 65533\n# thread env\nTHREADS = []\nENCODING = 'utf-8'\nDATA_QUEUE = Queue()\nREG_QUEUE = Queue()\n\n# dirs\nDATA_DIR = 'data/'\nCONFIG_DIR = DATA_DIR + 'bot/'\nREG_DIR = DATA_DIR + 'reg/'\n\n# populate room mapping\nroom_map = {\n 'Living room': '1',\n 'Dining room': '2',\n 'Sex dungeon': '3',\n 'Flag room': '4',\n 'Test room': '5',\n 'Bed room': '6',\n 'Computer room': '7',\n 'Vestibule': '8',\n 'Garage': '9',\n 'Garden': '10'\n}\n\nTECH_SUPPORT_LOOP = [CTFBotBro, CTFBotBro, CTFBotBro, CTFBotBro, CTFBotBro, CTFBotLazy, CTFBotJoker]\n\n\nclass InvalidChoiceException(Exception):\n pass\n\n\ndef query_room_temp(room):\n with open(DATA_DIR + DATA_DIR + room_map[room], \"r\") as f:\n result = ''\n for line in f.readlines():\n try:\n addition = line.split('\\t')\n room = addition[0].split(':')[0]\n ident = addition[0].split(':')[1].split(' - ')[0]\n cypher = secWrap.encrypt(get_pub_key(ident, room), addition[1])\n result += addition[0] + '\\t' + cypher + '\\n'\n except Exception as ex:\n result += line\n return result\n\n\ndef get_pub_key(ident, room):\n with open(REG_DIR + room + '/' + ident + '_pub.pem') as file:\n return file.read()\n\ndef get_priv_key(ident, room):\n with open(REG_DIR + room + '/' + ident + '_priv.pem') as file:\n return file.read()\n\n\nclass QueueWorker(Thread):\n def __init__(self):\n super().__init__()\n self.joined = False\n\n @staticmethod\n def append_values(value, file, directory):\n with open(directory + file, \"a\") as f:\n f.writelines(value)\n\n def run(self):\n while True:\n if not REG_QUEUE.empty():\n data = REG_QUEUE.get()\n self.append_values(data[2], '{}_priv.pem'.format(data[0]), REG_DIR + data[1] + '/')\n self.append_values(data[3], '{}_pub.pem'.format(data[0]), REG_DIR + data[1] + '/')\n\n elif not DATA_QUEUE.empty():\n data = DATA_QUEUE.get()\n line = data.cli_string()\n ident = line.split(':')[1].split(' - ')[0]\n room = line.split(':')[0]\n try:\n self.append_values(line + get_pub_key(ident, room) + '\\n\\n', room_map[data.cli_string().split(':')[0]], DATA_DIR + DATA_DIR)\n self.append_values(line, '9', CONFIG_DIR)\n except Exception as e:\n pass\n\n else:\n if self.joined:\n break\n else:\n time.sleep(1)\n\n def join(self, timeout=None):\n self.joined = True\n\n\nclass Cleaner(Thread):\n def __init__(self):\n super().__init__()\n self.joined = False\n\n def run(self):\n while True:\n \"\"\"\n Removes files from the passed in path that are older than an hour\n \"\"\"\n time_in_secs = time.time() - (60 * 60)\n path = REG_DIR\n for root, dirs, files in os.walk(path, topdown=False):\n for file_ in files:\n full_path = os.path.join(root, file_)\n stat = os.stat(full_path)\n\n if stat.st_mtime <= time_in_secs:\n try:\n if os.path.exists(full_path):\n os.remove(full_path)\n except OSError:\n print(\"[*] TempSense: Unable to remove file: %s\" % full_path)\n\n if self.joined:\n break\n else:\n time.sleep(60*15)\n\n def join(self, timeout=None):\n self.joined = True\n\n\nclass ClientThread(Thread):\n def __init__(self, socket):\n super().__init__()\n self.conn = socket\n self.buffer_size = 2048\n\n self.room = None\n self.registered = False\n self.id = socket.getpeername()[0]\n self.transgressions = 0\n print(\"[+] New server socket thread started for \" + IP + \":\" + str(PORT))\n\n def run(self):\n while True:\n try:\n self.transmit(\n 'Welcome to the Temperature Sensor Station! What would you like to do?\\n[1] Register\\n[2] Query room\\n[3] Submit temperature\\n[4] Help\\n\\n>')\n data = self.recieve()\n if data == b'1\\n':\n try:\n if not self.registered:\n self.register_loop()\n else:\n self.transmit('Your name is {}.\\n'.format(self.id))\n\n except InvalidChoiceException:\n break\n elif data == b'2\\n':\n data = self.generate_room_names()\n self.transmit('Which room to query?\\n' + data)\n while True:\n data = self.recieve().decode(ENCODING).rstrip('\\n')\n for room, number in room_map.items():\n if data == number:\n try:\n self.transmit(query_room_temp(room))\n except FileNotFoundError:\n self.transmit('No current data available!\\n')\n break\n\n elif data == b'3\\n':\n self.transmit('%s' % 'Pass the data base64 encoded.\\n')\n self.submit_loop()\n elif data == b'4\\n':\n if self.transgressions == 3:\n self.help_loop(supervisor=True)\n elif self.transgressions > 3:\n self.transmit(\n 'It seems you have been banned. Abusers will not be tolerated. Have a nice day!\\n')\n break\n else:\n self.transmit(\n 'Unfortunately we are very short on manpower... So let our electronic members help you with your question.\\nFor QA reasons your conversation will be recorded. You are now connected:\\n')\n self.help_loop()\n elif data == b'':\n self.finalize_connection()\n except Exception as ex:\n self.finalize_connection()\n break\n\n def register_loop(self):\n self.transmit('What room are you in?\\n')\n self.transmit(self.generate_room_names())\n data = self.recieve().decode(ENCODING).rstrip('\\n')\n if data in room_map.values():\n self.room = [room for room in room_map.keys() if room_map[room] == data][0]\n self.id = uuid.uuid4()\n self.registered = True\n priv, pub = secWrap.generate_key_pair()\n self.transmit('ID: {}\\n'.format(self.id))\n self.transmit('PubKey: \\n{}\\n'.format(pub))\n self.transmit('Provide ID for PrivKey:')\n data = self.recieve()\n if str(self.id) in data.decode(ENCODING):\n self.transmit('PrivKey: \\n{}\\n'.format(priv))\n self.transmit('End of register phase.\\n')\n REG_QUEUE.put([self.id, self.room, priv, pub])\n else:\n raise InvalidChoiceException()\n\n def submit_loop(self):\n data = self.recieve()\n try:\n data = base64.b64decode(data.decode(encoding=ENCODING))\n de = DataEntry()\n de.jinit(data)\n DATA_QUEUE.put(de)\n self.transmit('Your data has been received and will be processed soon.\\n')\n except TypeError as er:\n self.transmit('\\nThere was an error decoding your data.\\n')\n except Exception as jde:\n self.transmit('\\nYour JSON file seems corrupted.\\n')\n\n def help_loop(self, supervisor=False):\n if supervisor:\n self.support = CTFSupervisor()\n else:\n self.support = random.choice(TECH_SUPPORT_LOOP)()\n self.transmit('TS:' + self.support.process_sentence('Hi') + '\\n>')\n while True:\n try:\n data = self.recieve()\n self.transmit('TS:' + self.support.process_sentence(str(data, encoding=ENCODING)) + '\\n>')\n except BadWordException as e:\n self.transmit(\n 'TS: ' + 'I do not fancy that tone. Come back when you\\'ve learned to speak in a more civilized manner.' + '\\n>')\n self.transgressions += 1\n break\n\n def transmit(self, text):\n print(text)\n text = text\n if isinstance(text, bytes):\n self.conn.sendall(text)\n else:\n self.conn.sendall(bytes(text, ENCODING))\n\n def recieve(self):\n data = self.conn.recv(self.buffer_size)\n print(data.decode(ENCODING))\n return data\n\n def finalize_connection(self):\n try:\n self.transmit('\\nToo bad. Closing connestion.\\n')\n self.conn.close()\n except:\n try:\n self.conn.close()\n except:\n pass\n\n\n def generate_room_names(self):\n data = ''\n for room in room_map.keys():\n data += '[{}] {}\\n'.format(room_map[room], room)\n data += '[11] Back\\n\\n>'\n return data\n\n\ndef serv_start():\n tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n tcp_server.bind((IP, PORT))\n if not os.path.exists(DATA_DIR) and not os.path.exists(CONFIG_DIR):\n os.makedirs(DATA_DIR)\n os.makedirs(DATA_DIR + DATA_DIR)\n os.makedirs(REG_DIR)\n os.makedirs(CONFIG_DIR)\n for room in room_map.keys():\n os.makedirs(REG_DIR + room)\n with zipfile.ZipFile('bot_speech.zip', 'r') as zip_arch:\n zip_arch.extractall(CONFIG_DIR)\n if not os.path.exists('nltk_data'):\n with zipfile.ZipFile('nltk_data.zip', 'r') as zip_arch:\n zip_arch.extractall()\n\n qworker = QueueWorker()\n qworker.name = 'qWorker'\n qworker.start()\n\n cleaner = Cleaner()\n cleaner.name = 'Cleaner'\n cleaner.start()\n\n tcp_server.listen(50)\n while True:\n try:\n print(\"[*] TempSense: Waiting for connections from TCP clients...\")\n sock, addr = tcp_server.accept()\n newthread = ClientThread(sock)\n newthread.start()\n THREADS.append(newthread)\n except:\n for thread in THREADS:\n thread.finalize_connection()\n thread.join(timeout=10)\n break\n\n\nif __name__ == \"__main__\":\n serv_start()\n","repo_name":"fausecteam/faustctf-2017-tempsense","sub_path":"src/ServiceLogic.py","file_name":"ServiceLogic.py","file_ext":"py","file_size_in_byte":11179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"25846710701","text":"import os\nfrom flask import Flask, request, redirect, url_for, jsonify\nfrom werkzeug.utils import secure_filename\nfrom flask import send_from_directory\nfrom flask import flash, render_template\n\nUPLOAD_FOLDER = '/Users/amir/projects/PycharmProjects/carpsweb'\nALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\ndef get_resource_as_string(name, charset='utf-8'):\n with app.open_resource(name) as f:\n return f.read().decode(charset)\n\napp.jinja_env.globals['get_resource_as_string'] = get_resource_as_string\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\ncities = []\n\n@app.route('/cities', methods=['GET'])\ndef cities():\n return jsonify(['Amir', 'Ehsan'])\n\n@app.route('/cities', methods=['POST'])\ndef insert_city():\n requested_data = request.form['name']\n return jsonify(requested_data)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return render_template(\"matched.html\", filename=filename)\n # return redirect(url_for('uploaded_file', filename=filename))\n return render_template(\"index.html\")\n\n@app.route('/uploads/')\ndef uploaded_file(filename):\n return send_from_directory(app.config['UPLOAD_FOLDER'],\n filename)\n\n\n# photos = []\n#\n# @app.route('/')\n# def hello_world():\n# return 'Hello World!'\n#\n# @app.route('/delete/')\n# def delete_photo(name):\n# photos.remove(name)\n# return \" \".join(f for f in photos)\n#\n# @app.route('/insert/')\n# def add_photo(name):\n# photos.append(name)\n# return jsonify({'photos': photos})\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"ghamarian/carpsweb","sub_path":"carpsweb.py","file_name":"carpsweb.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19199613100","text":"class Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n if len(nums) == 1:\n return nums[0]\n k = len(nums)//2\n # print(nums[k::-1])\n # print(nums[:k:-1])\n \n # left subArray\n lSum = self.maxSubArray(nums[:k])\n # right subArray\n rSum = self.maxSubArray(nums[k:]) \n \n cSum = self.crossMaxSubArray(nums, k)\n return max(lSum, rSum, cSum)\n \n def crossMaxSubArray(self, nums: List[int], mid: int) -> int:\n rSum = lSum = -10**5\n total = 0\n for n in nums[mid-1::-1]:\n total += n\n if total > lSum:\n lSum = total\n \n total = 0\n for n in nums[mid:]:\n total += n\n if total > rSum:\n rSum = total\n \n return lSum + rSum\n\n \n \n ","repo_name":"liver121888/leetcode","sub_path":"0053-maximum-subarray/0053-maximum-subarray.py","file_name":"0053-maximum-subarray.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"ceb","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"4429151280","text":"from django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nimport datetime as dt\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import SignupForm, UserProfileForm, PostForm, CommentForm, BusinessForm\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import get_object_or_404\nfrom .models import UserProfile, Neighborhood,Business,Location, Comment,Post\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom django.db import IntegrityError\n\n# Create your views here.\n\ndef signup(request):\n name = \"Sign Up\"\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n form.save()\n email = form.cleaned_data.get('email')\n name = form.cleaned_data.get('username')\n send_mail(\n 'Welcome to Mini-Insta.',\n f'Hello {name},\\n '\n 'Welcome to the Nighbourhood.',\n 'nkamotho69@gmail.com',\n [email],\n fail_silently=False,\n )\n return redirect('index')\n else:\n form = SignUpForm()\n return render(request, 'registration/registration_form.html', {'form': form, 'name': name})\n\n@login_required(login_url='/accounts/login/')\ndef home(request):\n current_user = request.user\n try:\n profile = UserProfile.objects.get(user = current_user)\n except:\n return redirect('new_profile',username = current_user.username)\n\n try:\n posts = Post.objects.filter(neighborhood = profile.neighborhood)\n except:\n posts = None\n\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.user = current_user\n post.neighborhood = profile.neighborhood\n post.type = request.POST['type']\n post.save()\n\n if post.type == '1':\n recipients = UserProfile.objects.filter(neighborhood=post.neighborhood)\n for recipient in recipients:\n send_a_email(post.title,post.content,recipient.email)\n\n return redirect('post')\n else:\n form = PostForm()\n return render(request,'index.html',{\"posts\":posts,\"profile\":profile,\"form\":form})\n\n@login_required(login_url='/accounts/login/')\ndef new_profile(request,username):\n current_user = request.user\n if request.method == 'POST':\n try:\n profile = UserProfile.objects.get(user=current_user)\n form = UserProfileForm(request.POST,instance=profile)\n if form.is_valid():\n profile = form.save(commit=False)\n profile.user = current_user\n profile.save()\n return redirect('index')\n except:\n form = UserProfileForm(request.POST)\n if form.is_valid():\n profile = form.save(commit=False)\n profile.user = current_user\n profile.save()\n return redirect('index')\n else:\n if UserProfile.objects.filter(id=1):\n profile = UserProfile.objects.get(user=current_user)\n form = UserProfileForm(instance=profile)\n else:\n form = UserProfileForm()\n return render(request,'profile/new_profile.html',{\"form\":form})\n\n@login_required(login_url='/accounts/login/')\ndef search(request):\n current_user = request.user\n if 'search' in request.GET and request.GET[\"search\"]:\n search_term = request.GET.get(\"search\")\n business = Business.objects.filter(name__icontains=search_term)\n return render(request,'search.html',{'business':business})\n else:\n message = \"You haven't searched for any term\"\n return render(request, 'search.html',{\"message\":message})\n\n@login_required(login_url='/accounts/login/')\ndef post(request,id):\n post = Post.objects.get(id=id)\n comments = Comment.objects.filter(post=post)\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.user = request.user\n comment.post = post\n comment.save()\n return redirect('post',id = post.id)\n else:\n form = CommentForm()\n return render(request,'post.html',{\"post\":post,\"comments\":comments,\"form\":form})\n\n@login_required(login_url='/accounts/login/')\ndef business(request):\n current_user = request.user\n neighborhood = UserProfile.objects.get(user = current_user).neighborhood\n if request.method == 'POST':\n form = BusinessForm(request.POST)\n if form.is_valid():\n business = form.save(commit=False)\n business.user = current_user\n business.neighborhood = neighborhood\n business.save()\n return redirect('business')\n else:\n form = BusinessForm()\n\n try:\n business = Business.objects.filter(neighborhood = neighborhood)\n except:\n business = None\n\n return render(request,'business.html',{\"business\":business,\"form\":form})\n\nclass BusinessList(APIView):\n def get(self, request, format=None):\n all_businesses = Business.objects.all()\n serializers = BusinessSerializer(all_businesses, many=True)\n return Response(serializers.data)\n\n ","repo_name":"kiira254/neighbourhood","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"29975847317","text":"import sqlalchemy\nimport os\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect)\n\napp = Flask(__name__)\n\nfrom flask_sqlalchemy import SQLAlchemy\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', '') or \"sqlite:///ORD_Delays.sqlite\"\n\n# Remove tracking modifications\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\nengine = create_engine(\"sqlite:///ORD_Delays.sqlite\")\n\nBase = automap_base()\n\nBase.prepare(engine, reflect=True)\n\nDelays = Base.classes.ordtable\n\n@app.route(\"/\")\ndef index():\n \n return render_template(\"index.html\")\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"meghanvl/Weather_Delays","sub_path":"flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19278325192","text":"__author__ = 'uid41624'\nimport os,sys\nimport sys\n\nsys.path.insert(0, 'utils/Labels')\nfrom main.utils.mfc510.data_load.insert_raw_chips import insert_raw_chips\nfrom PyQt5.QtCore import *\nfrom PyQt5 import QtWidgets\nfrom PyQt5 import QtCore, QtGui\nimport threading\nfrom .DataMapping import DataBaseDataMapper\nfrom PyQt5.QtWidgets import QCompleter\nfrom PyQt5.QtCore import QStringListModel\nfrom .SignDescription import SignDescription\nfrom PyQt5.QtCore import pyqtSignal\nimport sys\n\n\ndef clickable(widget):\n\n class Filter(QObject):\n\n clicked = pyqtSignal()\n\n def eventFilter(self, obj, event):\n\n if obj == widget:\n if event.type() == QEvent.MouseButtonRelease:\n if obj.rect().contains(event.pos()):\n self.clicked.emit()\n # The developer can opt for .emit(obj) to get the object within the slot.\n return True\n\n return False\n\n filter = Filter(widget)\n widget.installEventFilter(filter)\n return filter.clicked\n\nclass pySignal(QObject):\n message = pyqtSignal(str)\n\nclass StartQT4:\n \"\"\"docstring for StartQT4\"\"\"\n ExtractionComplete = pyqtSignal()\n\n def __init__(self, ui,parent=None):\n\n self.SignListFlag=False\n self.parent = parent\n self.ui = ui\n self.DataBaseDataMapperI = DataBaseDataMapper()\n self.SignDescription= SignDescription()\n self.SignList=[]\n self.CountryList=[]\n self.selectedAttribs = {}\n self.SelectedCountryList=[]\n self.SelectedSignList=[]\n self.threadActive = False\n self.ui.dumpImages.clicked.connect(self.dumpCheck)\n self.pySignal=pySignal()\n self.lightCondition=None\n self.pySignal.message.connect(self.displayMessage)\n self.dump_raw_chips=insert_raw_chips(self)\n # self.pySignal.extraction_complete.connect(self.onExtractionComplete)\n#\n# self.ui.Edit.connect(self.ui.Edit, QtCore.SIGNAL(\"clicked()\"), self.EditFunc)\n# # self.ui.SelectSign.connect(self.ui.SelectSign,QtCore.SIGNAL(\"clicked()\"),lambda : self.DispDetails(str(self.ui.signSelect.text())))\n# self.ui.dumpImages_Chips.clicked.connect(self.dumpChips)\n self.ui.SignlistButton.clicked.connect(self.appendSignList)\n self.ui.SelectSign_image.clicked.connect(self.appendSignList_image)\n self.ui.CntryButton.clicked.connect(self.selectCountry)\n self.ui.CountryList.itemActivated.connect(self.deleteItemsCountryList)\n self.ui.CountryList_image.itemActivated.connect(self.deleteItemsCountryList)\n self.ui.SignList.itemActivated.connect(self.deleteItemsfromSignList)\n self.ui.SignList_image.itemActivated.connect(self.deleteItemsfromSignList)\n self.ui.Extract.clicked.connect(self.threading)\n\n self.ui.browseSignList.clicked.connect(self.onBrowseSignFileClicked)\n self.ui.selectSignFile.clicked.connect(self.readSignFromFile)\n\n self.ui.browseSignListForLabels.clicked.connect(lambda :self.onBrowseSignFileClicked(None))\n self.ui.selectSignListForLabels.clicked.connect(lambda :self.readSignFromFile(None))\n\n self.ui.browse.clicked.connect(self.onBrowseButtonClick)\n self.ui.connectToColl.clicked.connect(self.OnconnectToMongoClick)\n\n self.ui.ConnectToMongoDB.clicked.connect(self.OnconnectToMongoClick)\n self.ui.Update.clicked.connect( self.onUpdateButtonClick)\n self.ui.Extract_all.clicked.connect(self.threadingAll)\n\n self.ui.SelectAllCountry.clicked.connect(lambda :self.SelectAllCountry(None))\n self.ui.SelectAllCountry_image.clicked.connect(self.SelectAllCountry)\n\n self.ui.SelectAllSigns.clicked.connect(lambda :self.SelectAllSigns(None))\n self.ui.SelectAllSigns_image.clicked.connect(lambda :self.SelectAllSigns(\"image\"))\n\n\n def dumpCheck(self):\n if self.ui.lightConditionDay.isChecked() ==self.ui.lightConditionNight.isChecked() :\n self.lightCondition = None\n\n elif self.ui.lightConditionNight.isChecked():\n self.lightCondition=\"Night\"\n elif self.ui.lightConditionDay.isChecked():\n self.lightCondition=\"Day\"\n if self.ui.rawBox.isChecked() and self.ui.chipsBox.isChecked():\n self.dump_raw_chips.dumpRawChipsThread()\n elif self.ui.rawBox.isChecked():\n self.dump_raw_chips.dumpRawThreads()\n elif self.ui.chipsBox.isChecked():\n self.dump_raw_chips.dumpChipsThread()\n\n\n def getCount(self,query):\n # self.count =\n return self.DataBaseDataMapperI.MongoDbI.find(query).count()\n\n def SortedSignlistUpdate(self):\n if self.threadActive:\n self.errorMessage()\n else:\n\n items=[]\n item=[]\n for index in xrange(self.ui.SignListDesc.count()):\n items.append(self.ui.SignListDesc.item(index))\n for i in items:\n if i.text() in self.SignList:\n item.append(i.text())\n self.SelectedSignList= self.SelectedSignList+item\n self.ui.SignList.clear()\n self.SelectedSignList=list(set(self.SelectedSignList))\n self.ui.SignList.addItems(self.SelectedSignList)\n self.ui.signSelect.clear()\n\n #@pyqtSlot()\n def Error(self,msg):\n self.displayMessage(msg)\n # self.displayMessage(\"Provide SQL PATH\")\n\n # @pyqtSlot()\n def onExtractionComplete(self):\n self.displayMessage(\"Extraction Complete\")\n\n\n\n\n def comboFieldSlot(self,item):\n self.ui.comboFieldValue.clear()\n\n dropDownList=self.DataBaseDataMapperI.getList()\n i=0\n\n for attribs in dropDownList:\n for values in attribs[str(self.ui.comboField.currentText())]:\n self.ui.comboFieldValue.addItem(values)\n\n\n\n\n\n\n def readSignFromFile(self,type):\n absentSigns=[]\n absentSignsFile=open(\"SignsNotPresentInLookUp.txt\",'w')\n if type==None:\n filePath=self.ui.SelectSignFileForLabels.text()\n else:\n\n filePath=self.ui.SelectSignFile.text()\n file=open(filePath,'r')\n content=file.readlines()\n signList=[x.strip() for x in content]\n self.SelectedSignList.clear()\n for sign in signList:\n if sign in self.SignList:\n self.SelectedSignList.append(sign)\n else:\n absentSignsFile.write(str(sign))\n absentSignsFile.write('\\n')\n absentSignsFile.close()\n\n\n\n if type==None:\n self.ui.SignList.clear()\n self.ui.SignList.addItems(self.SelectedSignList)\n else:\n self.ui.SignList_image.clear()\n self.ui.SignList_image.addItems(self.SelectedSignList)\n\n def errorMessage(self):\n self.pySignal.message.emit(\"Request can not be processed \")\n\n\n\n\n def SelectAllCountry(self,type):\n if type is not None:\n self.ui.CountryList_image.clear()\n self.SelectedCountryList = list(self.CountryList)\n self.SelectedCountryList = list(set(self.SelectedCountryList))\n # self.SelectedCountryList = list(set(self.SelectedCountryList))\n self.ui.CountryList_image.addItems(self.SelectedCountryList)\n\n\n if self.threadActive:\n self.errorMessage()\n else:\n self.ui.CountryList.clear()\n\n self.SelectedCountryList= list(self.CountryList)\n self.SelectedCountryList=list(set(self.SelectedCountryList))\n # self.SelectedCountryList=list(set(self.SelectedCountryList))\n self.ui.CountryList.addItems(self.SelectedCountryList)\n\n def SelectAllSigns(self,type=None):\n if type is not None:\n self.ui.SignList_image.clear()\n self.SelectedSignList = list(self.SignList)\n self.SelectedSignList = list(set(self.SelectedSignList))\n self.ui.SignList_image.addItems(self.SelectedSignList)\n self.SelectedSignList.clear()\n if self.threadActive:\n self.errorMessage()\n else:\n self.ui.SignList.clear()\n self.SelectedSignList=list(self.SignList)\n self.SelectedSignList=list(set(self.SelectedSignList))\n\n self.ui.SignList.addItems(self.SelectedSignList)\n self.ui.SignList_image.addItems(self.SelectedSignList)\n\n def deleteItemsfromSignList(self,item):\n if self.threadActive:\n self.errorMessage()\n else:\n val=item.text()\n if len(self.SelectedSignList)==0:\n self.SelectedSignList = list(self.SignList)\n\n self.SelectedSignList = list(set(self.SelectedSignList))\n\n self.SelectedSignList.remove(val)\n # self.appendSignList()\n self.SelectedSignList=list(set(self.SelectedSignList))\n self.ui.SignList.clear()\n self.ui.SignList_image.clear()\n self.ui.SignList.addItems(self.SelectedSignList)\n self.ui.SignList_image.addItems(self.SelectedSignList)\n\n\n def MapAllData(self):\n sqlLitePath = self.ui.SqlitePath.toPlainText()\n if not sqlLitePath:\n self.pySignal.message.emit(\"Provide SQL PATH \")\n else:\n # t=threading.Thread(target=self.DataBaseDataMapperI.extractLabels,args=(str(sqlLitePath),self.CountryList,self.SignList))\n # #retVal = self.DataBaseDataMapperI.extractLabels(str(sqlLitePath),self.CountryList,self.SignList)\n # retVal=t.get()\n # t.start()\n # t.join()\n\n retVal= self.DataBaseDataMapperI.extractLabels(str(sqlLitePath),self.CountryList,self.SignList)\n\n\n\n # if not retVal:\n # self.displayMessage(\"Mapped Sequence is not present\")\n self.pySignal.extraction_complete.emit()\n self.SelectedCountryList=[]\n self.SelectedSignList= []\n self.ui.SignList.clear()\n self.ui.CountryList.clear()\n\n def threadingAll(self):\n if self.threadActive:\n self.errorMessage()\n else:\n self.threadActive = True\n result = threading.Thread(target=self.MapAllData)\n result.start()\n\n\n def threading(self):\n\n if self.threadActive:\n self.errorMessage()\n else:\n self.threadActive=True\n result=threading.Thread(target=self.MapData)\n result.start()\n\n def MapData(self):\n\n sqlLitePath = self.ui.SqlitePath.toPlainText()\n if not sqlLitePath:\n self.pySignal.message.emit(\"Provide SQL PATH\")\n # self.pySignal.error.emit()\n else:\n retVal = self.DataBaseDataMapperI.extractLabels(str(sqlLitePath),self.SelectedCountryList,self.SelectedSignList)\n try:\n # if not retVal:\n # self.displayMessage(\"Mapped Sequence is not present\")\n self.SelectedCountryList=[]\n self.SelectedSignList= []\n self.pySignal.message.emit(\"Extraction Complete \")\n # self.ExtractionComplete.emit()\n self.ui.SignList.clear()\n\n self.ui.CountryList.clear()\n except:\n pass\n self.threadActive = False\n\n\n def CountryselectUpdate(self, item):\n if self.threadActive:\n self.errorMessage()\n else:\n val=item.text()\n self.SelectedCountryList.append(str(val))\n self.ui.CountryList.clear()\n self.ui.CountryList_image.clear()\n self.SelectedCountryList=list(set(self.SelectedCountryList))\n self.ui.CountryList.addItems(self.SelectedCountryList)\n self.ui.CountryList_image.addItems(self.SelectedCountryList)\n\n\n def deleteItemsCountryList(self,item):\n if self.threadActive:\n self.errorMessage()\n else:\n val=item.text()\n self.SelectedCountryList.remove(val)\n self.ui.CountryList.clear()\n self.ui.CountryList_image.clear()\n self.SelectedCountryList= list(set(self.SelectedCountryList))\n self.ui.CountryList.addItems(self.SelectedCountryList)\n self.ui.CountryList_image.addItems(self.SelectedCountryList)\n\n\n def selectCountry(self):\n if self.threadActive:\n self.errorMessage()\n else:\n\n val=self.ui.SelectCountry.text()\n if val:\n self.ui.SelectCountry.clear()\n self.ui.CountryList.clear()\n self.SelectedCountryList.append(str(val))\n self.SelectedCountryList = list(set(self.SelectedCountryList))\n self.ui.CountryList.addItems(self.SelectedCountryList)\n self.ui.CountryList_image.addItems(self.SelectedCountryList)\n else:\n pass\n\n def appendSignList(self):\n if self.threadActive:\n self.errorMessage()\n else:\n val = self.ui.SelectSignClass.text()\n if val:\n self.SelectedSignList.append(str(val))\n self.ui.SelectSignClass.clear()\n\n self.ui.SignList_image.clear()\n self.SelectedSignList= list(set(self.SelectedSignList))\n self.ui.SignList.addItems(self.SelectedSignList)\n self.ui.SignList_image.addItems(self.SelectedSignList)\n else:\n pass\n\n def appendSignList_image(self):\n if self.threadActive:\n self.errorMessage()\n else:\n val = self.ui.SelectSignClass_image.text()\n if val:\n self.SelectedSignList.append(str(val))\n self.ui.SelectSignClass_image.clear()\n\n self.ui.SignList_image.clear()\n self.SelectedSignList = list(set(self.SelectedSignList))\n self.ui.SignList.addItems(self.SelectedSignList)\n self.ui.SignList_image.addItems(self.SelectedSignList)\n else:\n pass\n\n def onBrowseButtonClick(self):\n if self.threadActive:\n self.errorMessage()\n else:\n selectedFile = QtWidgets.QFileDialog.getOpenFileName(self.ui,\"Select SqlLite File\",\"\", \"*.sqlite\")\n if(selectedFile):\n self.ui.SqlitePath.setText(selectedFile[0])\n\n\n # selectedFile = QtGui.QFileDialog.getExistingDirectory(self, \"Select Path\" )\n\n def onBrowseSignFileClicked(self,type):\n selectedFile = QtWidgets.QFileDialog.getOpenFileName(self.ui, \"Select File\", \"\", \"*.txt\")\n if type==None:\n\n if (selectedFile):\n self.ui.SelectSignFileForLabels.setText(selectedFile[0])\n\n else:\n\n if(selectedFile):\n self.ui.SelectSignFile.setText(selectedFile[0])\n\n\n\n def SignlistUpdate(self, item):\n if self.threadActive:\n self.errorMessage()\n else:\n val=item.text()\n self.SelectedSignList.append(str(val))\n self.ui.SignList.clear()\n self.ui.SignList_image.clear()\n self.SelectedSignList=list(set(self.SelectedSignList))\n self.ui.SignList.addItems(self.SelectedSignList)\n self.ui.SignList_image.addItems(self.SelectedSignList)\n\n def OnconnectToMongoClick(self):\n if self.ui.radioMain.isChecked():\n self.signType='mainSign'\n elif self.ui.radioPVS.isChecked():\n self.signType='PVS'\n elif self.ui.radioSupplS.isChecked():\n self.signType='supplSign'\n if self.threadActive:\n self.errorMessage()\n else:\n\n self.mongoDBName = self.ui.MongoDataBase.toPlainText()\n\n if self.mongoDBName == \"\":\n self.displayMessage(\"Mongo DB Name is Not mentioned\")\n return\n\n HostName = self.ui.Host.toPlainText()\n if HostName == \"\":\n self.displayMessage(\"Host Name is Not mentioned\")\n return\n\n self.CollectionName = self.ui.collectionName.toPlainText()\n self.lookUp = self.CollectionName + \"_lookUp\"\n DataBasePort = self.ui.Port.toPlainText()\n if DataBasePort == \"\":\n self.displayMessage(\"DataBase Port is Not mentioned\")\n return\n else:\n try:\n PortNumber = int(DataBasePort)\n except Exception:\n self.displayMessage(\"Port should be a number\")\n pass\n UserName = self.ui.UserName.toPlainText()\n Password = self.ui.Password.toPlainText()\n self.mongoUri = 'mongodb://'\n if UserName and Password:\n self.mongoUri += str(UserName) + ':' + str(Password) + '@'\n\n self.mongoUri += str(HostName) + ':' + str(PortNumber)\n\n self.mongoDBName=str(self.mongoDBName)\n\n isConnectionSuccess = self.DataBaseDataMapperI.performMongoDBConnection(self.mongoUri\n ,str(self.mongoDBName)\n ,str(self.CollectionName)\n )\n self.DataBaseDataMapperI.getSignType(self.signType)\n\n if not isConnectionSuccess:\n self.displayMessage(self.DataBaseDataMapperI.getMongoDBConnectionError())\n else :\n\n if self.CollectionName != '':\n try:\n self.getUpdatedCountryAndSignList()\n\n except:\n self.pySignal.message.emit(\"Update LookUp collections\")\n\n else:\n self.pySignal.message.emit(\"Successfully Connected to Mongo DB\")\n\n\n\n def upDateLookUp(self):\n sqlLitePath = self.ui.SqlitePath.toPlainText()\n if sqlLitePath:\n if self.DataBaseDataMapperI.isMongoDBConnected():\n # perform Function Calls\n self.updateSensorList(sqlLitePath)\n self.updateCountryList(sqlLitePath)\n self.updateSignClass(sqlLitePath)\n self.updateSequenceList(sqlLitePath)\n self.updateMappedSignList(sqlLitePath)\n self.pySignal.message.emit(\"LookUp updated\")\n else:\n self.pySignal.message.emit(\"MongoDB is not Connected\")\n else:\n\n self.pySignal.message.emit(\"Provide SQL PATH\")\n\n def onUpdateButtonClick(self):\n if self.threadActive:\n self.errorMessage()\n else:\n\n t=threading.Thread(target=self.upDateLookUp)\n t.start()\n\n\n def updateCountryList(self, sqlLitePath):\n if self.threadActive:\n self.errorMessage()\n else:\n if self.ui.countryListCheckBox.isChecked():\n self.DataBaseDataMapperI.mapCountryData(str(sqlLitePath))\n\n def updateSignClass(self, sqlLitePath):\n if self.threadActive:\n self.errorMessage()\n else:\n if self.ui.signClassCheckBox.isChecked():\n self.DataBaseDataMapperI.mapSignClassData(str(sqlLitePath))\n\n def updateSequenceList(self, sqlLitePath):\n if self.threadActive:\n self.errorMessage()\n else:\n if self.ui.sequenceListCheckBox.isChecked():\n self.DataBaseDataMapperI.updateSequenceList(str(sqlLitePath))\n\n def updateSensorList(self, sqlLitePath):\n if self.threadActive:\n self.errorMessage()\n else:\n if self.ui.sensorListCheckBox.isChecked():\n self.DataBaseDataMapperI.updateSensorList(str(sqlLitePath))\n\n def updateMappedSignList(self, sqlLitePath):\n if self.threadActive:\n self.errorMessage()\n else:\n if self.ui.mappedSequenceCheckBox.isChecked():\n self.DataBaseDataMapperI.mappedSequenceData(sqlLitePath)\n\n def displayMessage(self, MessageToDisplay):\n msg = QtWidgets.QMessageBox()\n msg.setIcon(QtWidgets.QMessageBox.Warning)\n\n msg.setText(MessageToDisplay)\n msg.setWindowTitle(\"Mongo DB Connection\")\n msg.setStandardButtons(QtWidgets.QMessageBox.Ok)\n msg.exec_()\n\n def getUpdatedCountryAndSignList(self):\n self.CountryList[:] = []\n self.SignList[:] = []\n self.ui.CountryListV.clear()\n self.ui.SignListV.clear()\n cursor = self.DataBaseDataMapperI.GetSignList()\n countryCursor =self.DataBaseDataMapperI.GetCountryList()\n\n for obj in countryCursor[\"Country List\"]:\n self.CountryList.append(str(obj))\n\n for obj in cursor[\"Sign List\"]:\n self.SignList.append(str(obj))\n\n self.ui.CountryListV.addItems(self.CountryList)\n self.ui.CountryListV_image.addItems(self.CountryList)\n self.ui.CountryListV.itemActivated.connect(self.CountryselectUpdate)\n self.ui.CountryListV_image.itemActivated.connect(self.CountryselectUpdate)\n self.ui.SignListV.addItems(self.SignList)\n self.ui.SignListV_image.addItems(self.SignList)\n self.ui.SignListV.itemActivated.connect(self.SignlistUpdate)\n self.ui.SignListV_image.itemActivated.connect(self.SignlistUpdate)\n completer = QCompleter()\n completerCountry=QCompleter()\n\n self.ui.SelectSignClass.setCompleter(completer)\n self.ui.SelectSignClass_image.setCompleter(completer)\n model=QStringListModel()\n completer.setModel(model)\n model.setStringList(self.SignList)\n self.ui.SelectCountry.setCompleter(completerCountry)\n self.ui.SelectCountry_image.setCompleter(completerCountry)\n modelCountry=QStringListModel()\n completerCountry.setModel(modelCountry)\n modelCountry.setStringList(self.CountryList)\n\nif __name__ == '__main__':\n\n app = QtGui.QApplication(sys.argv)\n myapp = StartQT4()\n font=QtGui.QFont(myapp)\n myapp.show()\n app.exec_()","repo_name":"shinsvarghese/four_season","sub_path":"main/utils/Labels/LabelConverter.py","file_name":"LabelConverter.py","file_ext":"py","file_size_in_byte":22089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"2642722281","text":"# -*- coding:utf-8 -*-\nimport asyncio\nimport configparser\nimport datetime\nimport logging\nimport math\nimport multiprocessing\nimport os\nimport time\nimport traceback\n\nimport websockets\nfrom apscheduler.schedulers.blocking import BlockingScheduler\n\nfrom tg.bot import main as tg_bot\nfrom trade import hot_coin_func_trade, utils\nfrom trade.alert_price import alert_price\nfrom trade.cancel_over_order import cancel_over_order\nfrom trade.default_config import config\nfrom trade.fill_depth import fill_depth\nfrom trade.fork_trade import fork_trade\nfrom trade.hot_coin_api import HotCoin\nfrom trade.jump_depth import jump_depth\nfrom utils.account_info import accountClass\nfrom utils.config_loader import config as new_config\nfrom utils.logger_init import init_logger\nfrom utils.remind_func import remind_tg\n\nraw_config_path = os.path.join(os.path.dirname(__file__), 'config.ini')\nlogger = logging.getLogger(__name__)\n\ninit_logger(__file__)\n\n\ndef cancel_pool(hot_coin):\n while True:\n try:\n hot_coin_func_trade.adjustable_cancel(hot_coin)\n except Exception as e:\n traceback.print_exc()\n time.sleep(2)\n\n\ndef save_trades_pool(hot_coin):\n while True:\n try:\n hot_coin_func_trade.save_trades(hot_coin, config['trade_data_dir'])\n except Exception as e:\n traceback.print_exc()\n time.sleep(60 * 10) # 每10分钟获取最新订单信息并存储\n\n\ndef print_trade_pool():\n while True:\n try:\n end_day = utils.get_now_time_str(time_format='%Y%m%d')\n end_time = f'{end_day}{config[\"report_hour\"]:02d}0000'\n if utils.get_now_time_str() < end_time:\n if config['debug']:\n time.sleep(10)\n else:\n time.sleep(60 * 60) # 每60分钟尝试输出报告\n continue\n start_time = f'{utils.cal_date(end_day, -1)}{config[\"report_hour\"]:02d}0000'\n hot_coin_func_trade.print_trade_report(\n input_dir=config['trade_data_dir'],\n output_dir=config['trade_report_dir'],\n start_time=start_time, end_time=end_time)\n except Exception as e:\n traceback.print_exc()\n if config['debug']:\n time.sleep(10)\n else:\n time.sleep(60 * 60)\n\n\ndef print_cancel_pool():\n while True:\n try:\n end_day = utils.get_now_time_str(time_format='%Y%m%d')\n end_time = f'{end_day}{config[\"report_hour\"]:02d}0000'\n if utils.get_now_time_str() < end_time:\n if config['debug']:\n time.sleep(10)\n else:\n time.sleep(60 * 60) # 每60分钟尝试输出报告\n continue\n start_time = f'{utils.cal_date(end_day, -1)}{config[\"report_hour\"]:02d}0000'\n hot_coin_func_trade.print_cancel_report(\n input_dir=config['cancel_data_dir'],\n output_dir=config['cancel_report_dir'],\n start_time=start_time, end_time=end_time)\n except Exception as e:\n traceback.print_exc()\n if config['debug']:\n time.sleep(10)\n else:\n time.sleep(60 * 60)\n\n\ndef wave_trade_pool(hot_coin):\n while True:\n try:\n # 自动波动交易\n if config['wave_trade_auto_on']:\n start_day = utils.get_now_time_str(time_format='%Y%m%d')\n # generate auto config\n wave_num = utils.random_num(\n min_val=config['wave_trade_auto_min_action_num'],\n max_val=config['wave_trade_auto_max_action_num'] + 1,\n num=1,\n sigma=1)[0]\n now_time = utils.get_now_time_str(time_format='%Y%m%d%H%M%S')\n end_time = f\"{start_day}235959\"\n wave_times = utils.random_num(\n min_val=int(now_time),\n max_val=int(end_time),\n num=int(wave_num),\n sigma=1)\n wave_percentages = utils.random_num(\n min_val=config['wave_trade_auto_min_percentage'],\n max_val=config['wave_trade_auto_max_percentage'],\n num=int(wave_num),\n sigma=10000)\n while True:\n now_day = utils.get_now_time_str(time_format='%Y%m%d')\n if now_day > start_day:\n break\n now_time = utils.get_now_time_str(time_format='%Y%m%d%H%M%S')\n for index, start_time in enumerate(wave_times):\n print(start_time)\n print(now_time)\n if int(now_time) > start_time and int(now_time) - int(start_time) < 60:\n # time check pass\n print('ok')\n wave_percentage = wave_percentages[index]\n duration_time = utils.random_num(1, 60)\n action_num = utils.random_num(1, 3)\n hot_coin_func_trade.target_trade_allocation(hot_coin, wave_percentage, duration_time,\n action_num)\n time.sleep(61)\n time.sleep(10)\n elif config['wave_trade_manual_on']:\n # 手动配置的波动交易\n assert len(config['wave_trade_start_times']) == len(config['wave_trade_percentages'])\n assert len(config['wave_trade_start_times']) == len(config['wave_trade_duration_times'])\n assert len(config['wave_trade_start_times']) == len(config['wave_trade_action_nums'])\n now_time = utils.get_now_time_str(time_format='%Y%m%d%H%M%S')\n for index, start_time in enumerate(config['wave_trade_start_times']):\n start_time = utils.time_format_change(start_time, config['wave_trade_time_format'])\n if config['wave_trade_repeat_evenyday']:\n start_time = f\"{utils.get_now_time_str(time_format='%Y%m%d')}{start_time[-6:]}\"\n print(start_time)\n print(now_time)\n if now_time > start_time and int(now_time) - int(start_time) < 60:\n # time check pass\n # print('ok')\n wave_percentage = config['wave_trade_percentages'][index]\n duration_time = config['wave_trade_duration_times'][index]\n action_num = config['wave_trade_action_nums'][index]\n hot_coin_func_trade.target_trade_allocation(hot_coin, wave_percentage, duration_time,\n action_num)\n time.sleep(61)\n except Exception as e:\n traceback.print_exc()\n time.sleep(10)\n\n\n# async func\ndef func(hot_coin, target_func):\n while True:\n try:\n logging.info(\"Start main func...\")\n\n async def main_logic():\n async with websockets.connect(new_config.WEBSOCKETS_API, ping_interval=None) as websocket:\n await target_func(hot_coin, websocket)\n\n asyncio.get_event_loop().run_until_complete(main_logic())\n except Exception as e:\n traceback.print_exc()\n logging.warning(\"Main func failed, restart\")\n\n\ndef run_sched():\n sched = BlockingScheduler(timezone=\"Asia/Shanghai\")\n\n # 输出时间\n # @sched.scheduled_job('cron', minute=0, hour='*/8')\n # # @sched.scheduled_job('interval', seconds=5)\n # def job():\n # gen_volume_report()\n # gen_assets_report()\n # gen_analyze_report()\n\n @sched.scheduled_job('interval', seconds=60)\n def check_status():\n print_prefix = f'[Status Check]'\n try:\n new_config.load_config()\n logger.info(f'{print_prefix}')\n new_hot_coin = HotCoin(symbol=new_config.SYMBOL)\n ticker_data = new_hot_coin.get_ticker()\n if 'msg' in ticker_data:\n logger.warning(f'{print_prefix} 交易量获取失败 {ticker_data}')\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'交易量获取失败,请检查IP是否被封禁,API错误信息 {ticker_data[\"msg\"]}')\n else:\n current_time = datetime.datetime.now().timestamp() * 1000\n minutes_vol = 0\n for item in ticker_data:\n if float(item['idx']) <= current_time - ((new_config.alert_vol_count_minute + 1) * 60 * 1000):\n break\n minutes_vol += float(item['vol'])\n if minutes_vol < new_config.alert_vol_min:\n logger.warning(f'{print_prefix} 交易量异常,{new_config.alert_vol_count_minute}分钟内交易 {minutes_vol},'\n f'小于设定最小值{new_config.alert_vol_min}')\n remind_tg(new_config.ALERT_PRICE_TG_CHAT,\n f'#{new_config.SYMBOL_NAME} \\n'\n f'检测到最近{new_config.alert_vol_count_minute}分钟交易量低于预警交易量{new_config.alert_vol_min}\\n'\n f'交易量总计{round(minutes_vol, 4)}')\n else:\n logger.info(f'{print_prefix} 交易量正常,{new_config.alert_vol_count_minute}分钟内交易 {minutes_vol},'\n f'大于设定最小值{new_config.alert_vol_min}')\n except Exception as e:\n logger.exception(e)\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'{print_prefix} 遇到未知错误: ' + str(e))\n\n @sched.scheduled_job('interval', seconds=60)\n def check_account_balance_status():\n print_prefix = f'[Account Balance Check]'\n try:\n new_config.load_config()\n logger.info(f'{print_prefix}')\n\n # BOT余额检查\n new_hot_coin = HotCoin(symbol=new_config.SYMBOL)\n new_hot_coin.auth(key=new_config.ACCESS_KEY, secret=new_config.SECRET_KEY)\n account_info_data = new_hot_coin.get_account_info()\n if 'balances' in account_info_data:\n usdt_balance = 0\n usdt_free_balance = 0\n coin_balance = 0\n coin_free_balance = 0\n for item in account_info_data['balances']:\n if item['asset'] == 'USDT':\n usdt_balance = float(item['free']) + float(item['locked'])\n usdt_free_balance = float(item['free'])\n logger.info(f'{print_prefix} 当前Bot账户USDT余额:{usdt_balance}')\n break\n for item in account_info_data['balances']:\n if item['asset'] == str(new_config.SYMBOL_NAME).upper():\n coin_balance = float(item['free']) + float(item['locked'])\n coin_free_balance = float(item['free'])\n logger.info(f'{print_prefix} 当前Bot账户{new_config.SYMBOL_NAME}余额:{coin_balance}')\n break\n sub_usdt_balance = accountClass.BOT_USDT_BALANCE - usdt_balance\n sub_coin_balance = accountClass.BOT_COIN_BALANCE - coin_balance\n if accountClass.BOT_USDT_BALANCE == 0:\n accountClass.BOT_USDT_BALANCE = usdt_balance\n accountClass.BOT_COIN_BALANCE = coin_balance\n remind_tg(new_config.REPORT_TG_CHAT, f'#报告\\n'\n f'[Bot账户]\\n'\n f'当前USDT余额:{round(usdt_balance, 2)}\\n'\n f'可用USDT余额:{round(usdt_free_balance, 2)}\\n'\n f'当前{new_config.SYMBOL_NAME}余额:{round(coin_balance, 2)}\\n'\n f'可用{new_config.SYMBOL_NAME}余额:{round(coin_free_balance, 2)}')\n elif datetime.datetime.now().minute == 0:\n accountClass.BOT_USDT_BALANCE = usdt_balance\n accountClass.BOT_COIN_BALANCE = coin_balance\n remind_tg(new_config.REPORT_TG_CHAT, f'#报告\\n'\n f'[Bot账户]\\n'\n f'当前USDT余额:{round(usdt_balance, 2)}\\n'\n f'可用USDT余额:{round(usdt_free_balance, 2)}\\n'\n f'USDT总余额减少:{round(sub_usdt_balance, 2)}\\n'\n f'当前{new_config.SYMBOL_NAME}余额:{round(coin_balance, 2)}\\n'\n f'可用{new_config.SYMBOL_NAME}余额:{round(coin_free_balance, 2)}\\n'\n f'{new_config.SYMBOL_NAME}总余额减少:{round(sub_coin_balance, 2)}\\n'\n f'USDT/{new_config.SYMBOL_NAME}:{0 if sub_coin_balance == 0 else round(sub_usdt_balance / sub_coin_balance, 4)}')\n else:\n if sub_usdt_balance > new_config.alert_usdt_balance_over_amount:\n logger.warning(f'{print_prefix} [Bot账户] USDT余额异常\\n'\n f'当前USDT余额:{usdt_balance}\\n'\n f'可用USDT余额:{usdt_free_balance}\\n'\n f'USDT总余额减少:{sub_usdt_balance}')\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'#预警\\n'\n f'[Bot账户] USDT余额异常\\n'\n f'当前USDT余额:{round(usdt_balance, 2)}\\n'\n f'可用USDT余额:{round(usdt_free_balance, 2)}\\n'\n f'USDT总余额减少:{round(sub_usdt_balance, 2)}')\n else:\n logger.warning(f'{print_prefix} 账户信息获取失败 {account_info_data}')\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, '账户信息获取失败,请检查IP是否被封禁')\n\n # 用户余额检查\n for index in range(len(new_config.OTHER_ACCESS_KEYS)):\n new_hot_coin.auth(key=new_config.OTHER_ACCESS_KEYS[index], secret=new_config.OTHER_SECRET_KEYS[index])\n account_info_data = new_hot_coin.get_account_info()\n if 'balances' in account_info_data:\n usdt_balance = 0\n usdt_free_balance = 0\n coin_balance = 0\n coin_free_balance = 0\n for item in account_info_data['balances']:\n if item['asset'] == 'USDT':\n usdt_balance = float(item['free']) + float(item['locked'])\n usdt_free_balance = float(item['free'])\n logger.info(f'{print_prefix} 当前人工账户{index + 1} USDT余额:{usdt_balance}')\n break\n for item in account_info_data['balances']:\n if item['asset'] == str(new_config.SYMBOL_NAME).upper():\n coin_balance = float(item['free']) + float(item['locked'])\n coin_free_balance = float(item['free'])\n logger.info(f'{print_prefix} 当前人工账户{index + 1} {new_config.SYMBOL_NAME}余额:{coin_balance}')\n break\n\n if len(accountClass.OTHER_ACCOUNT_USDT_BALANCE) == index:\n accountClass.OTHER_ACCOUNT_USDT_BALANCE.append(0)\n accountClass.OTHER_ACCOUNT_COIN_BALANCE.append(0)\n\n sub_usdt_balance = accountClass.OTHER_ACCOUNT_USDT_BALANCE[index] - usdt_balance\n sub_coin_balance = accountClass.OTHER_ACCOUNT_COIN_BALANCE[index] - coin_balance\n if accountClass.OTHER_ACCOUNT_USDT_BALANCE[index] == 0:\n accountClass.OTHER_ACCOUNT_USDT_BALANCE[index] = usdt_balance\n accountClass.OTHER_ACCOUNT_COIN_BALANCE[index] = coin_balance\n remind_tg(new_config.REPORT_TG_CHAT, f'#报告\\n'\n f'[人工账户{index + 1}]\\n'\n f'当前USDT余额:{round(usdt_balance, 2)}\\n'\n f'可用USDT余额:{round(usdt_free_balance, 2)}\\n'\n f'当前{new_config.SYMBOL_NAME}余额:{round(coin_balance, 2)}\\n'\n f'可用{new_config.SYMBOL_NAME}余额:{round(coin_free_balance, 2)}')\n elif datetime.datetime.now().minute == 0:\n accountClass.OTHER_ACCOUNT_USDT_BALANCE[index] = usdt_balance\n accountClass.OTHER_ACCOUNT_COIN_BALANCE[index] = coin_balance\n remind_tg(new_config.REPORT_TG_CHAT, f'#报告\\n'\n f'[人工账户{index + 1}]\\n'\n f'当前USDT余额:{round(usdt_balance, 2)}\\n'\n f'可用USDT余额:{round(usdt_free_balance, 2)}\\n'\n f'USDT总余额减少:{round(sub_usdt_balance, 2)}\\n'\n f'当前{new_config.SYMBOL_NAME}余额:{round(coin_balance, 2)}\\n'\n f'可用{new_config.SYMBOL_NAME}余额:{round(coin_free_balance, 2)}\\n'\n f'{new_config.SYMBOL_NAME}总余额减少:{round(sub_coin_balance, 2)}\\n'\n f'USDT/{new_config.SYMBOL_NAME}:{0 if sub_coin_balance == 0 else round(sub_usdt_balance / sub_coin_balance, 4)}')\n else:\n if sub_usdt_balance > new_config.alert_usdt_balance_over_amount:\n logger.warning(f'{print_prefix} [人工账户{index + 1}] USDT余额异常\\n'\n f'当前USDT余额:{usdt_balance}\\n'\n f'可用USDT余额:{usdt_free_balance}\\n'\n f'USDT总余额减少:{sub_usdt_balance}')\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'#预警\\n'\n f'[人工账户{index + 1}] USDT余额异常\\n'\n f'当前USDT余额:{round(usdt_balance, 2)}\\n'\n f'可用USDT余额:{round(usdt_free_balance, 2)}\\n'\n f'USDT总余额减少:{round(sub_usdt_balance, 2)}')\n else:\n logger.warning(f'{print_prefix} 账户信息获取失败 {account_info_data}')\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'账户信息获取失败: {account_info_data}')\n except Exception as e:\n logger.exception(e)\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'{print_prefix} 遇到未知错误: ' + str(e))\n\n @sched.scheduled_job('interval', seconds=30)\n def cancelOldOrder():\n print_prefix = f'[cancelOldOrder]'\n try:\n new_config.load_cancel_config()\n logger.info(f'{print_prefix}')\n new_hot_coin = HotCoin(symbol=new_config.SYMBOL)\n new_hot_coin.auth(key=new_config.ACCESS_KEY, secret=new_config.SECRET_KEY)\n toCancelOrders = []\n currentOrderData = new_hot_coin.get_open_order(1000)\n if 'list' in currentOrderData:\n # logger.debug(len(currentOrderData['list']))\n # logger.debug(currentOrderData['list'])\n if len(currentOrderData['list']) > 0:\n nowTimestamp = datetime.datetime.now().timestamp()\n logger.debug(nowTimestamp)\n for item in currentOrderData['list']:\n orderTimestamp = item['time']\n if orderTimestamp < (nowTimestamp - new_config.cancel_before_order_minutes * 60) * 1000:\n toCancelOrders.append(item['orderId'])\n if len(toCancelOrders) > 0:\n for item in toCancelOrders:\n logger.info(f'{print_prefix} 撤销委托单ID => {item}')\n logger.info(new_hot_coin.cancel_order(item))\n else:\n logger.warning(f'{print_prefix} 委托单数据获取错误, {currentOrderData}')\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'{print_prefix} 委托单数据获取错误: {currentOrderData}')\n except Exception as e:\n logger.exception(e)\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'{print_prefix} 遇到未知错误: ' + str(e))\n\n @sched.scheduled_job('interval', seconds=300)\n def auto_fork_config():\n print_prefix = f'[Auto Fork Config]'\n try:\n new_config.load_config()\n logger.info(f'{print_prefix}')\n if not new_config.auto_fork_trade_config_on:\n logger.info(f'{print_prefix} 未开启')\n return\n new_hot_coin = HotCoin(symbol=new_config.SYMBOL)\n ticker_data = new_hot_coin.get_ticker()\n if 'msg' not in ticker_data:\n current_time = datetime.datetime.now().timestamp() * 1000\n skip_vol = 0\n skip_time = math.fmod(current_time, new_config.target_vol_interval_minutes * 60 * 1000)\n for item in ticker_data:\n logger.debug(item)\n if float(item['idx']) <= current_time - skip_time:\n break\n skip_vol += float(item['vol'])\n if skip_vol <= 0:\n logger.info(f'{print_prefix} 已产生交易量为0')\n return False\n logger.info(f'{print_prefix} 已度过时间 => {skip_time / 1000 / 60} 分钟')\n logger.info(f'{print_prefix} 已产生交易量 => {skip_vol}')\n time_scale = new_config.target_vol_interval_minutes * 60 * 1000 / skip_time\n logger.info(f'{print_prefix} 预计交易量 => {skip_vol * time_scale}')\n logger.info(f'{print_prefix} 目标交易量 => {new_config.target_vol}')\n vol_scale = new_config.target_vol / (skip_vol * time_scale)\n logger.info(f'{print_prefix} vol_scale => {vol_scale}')\n\n logger.info(f'{print_prefix} fork_trade_random_amount_min => {new_config.fork_trade_random_amount_min}')\n logger.info(f'{print_prefix} fork_trade_random_amount_max => {new_config.fork_trade_random_amount_max}')\n\n new_config.fork_trade_random_amount_min = max(new_config.fork_trade_random_amount_min_min,\n vol_scale * new_config.fork_trade_random_amount_min)\n new_config.fork_trade_random_amount_min = min(new_config.fork_trade_random_amount_min_max,\n new_config.fork_trade_random_amount_min)\n\n new_config.fork_trade_random_amount_max = max(new_config.fork_trade_random_amount_max_min,\n vol_scale * new_config.fork_trade_random_amount_max)\n new_config.fork_trade_random_amount_max = min(new_config.fork_trade_random_amount_max_max,\n new_config.fork_trade_random_amount_max)\n\n raw_config = configparser.ConfigParser()\n raw_config.read(raw_config_path, encoding='utf-8')\n raw_config['Trade']['fork_trade_random_amount_min'] = str(new_config.fork_trade_random_amount_min)\n raw_config['Trade']['fork_trade_random_amount_max'] = str(new_config.fork_trade_random_amount_max)\n with open(raw_config_path, 'w') as configfile:\n raw_config.write(configfile)\n logger.info(f'{print_prefix} new fork_trade_random_amount_min => {new_config.fork_trade_random_amount_min}')\n logger.info(f'{print_prefix} new fork_trade_random_amount_max => {new_config.fork_trade_random_amount_max}')\n else:\n logger.warning(f'{print_prefix} 交易量获取失败 {ticker_data}')\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'交易量获取失败,请检查IP是否被封禁,API错误信息 {ticker_data[\"msg\"]}')\n except Exception as e:\n logger.exception(e)\n remind_tg(new_config.ALERT_PRICE_TG_CHAT, f'{print_prefix} 遇到未知错误: ' + str(e))\n sched.start()\n\n\n# BlockingScheduler\n# sched.add_job(job, 'cron', minutes='*/2')\n\nnew_config.load_all_config()\n\nif __name__ == '__main__':\n hot_coin = HotCoin(symbol=new_config.SYMBOL)\n hot_coin.auth(key=new_config.ACCESS_KEY, secret=new_config.SECRET_KEY)\n multiprocessing.set_start_method('spawn')\n pool = multiprocessing.Pool(processes=14)\n pool.apply_async(func, (hot_coin, hot_coin_func_trade.self_trade,))\n pool.apply_async(func, (hot_coin, hot_coin_func_trade.cross_trade,))\n pool.apply_async(cancel_pool, (hot_coin,))\n pool.apply_async(save_trades_pool, (hot_coin,))\n pool.apply_async(print_trade_pool)\n pool.apply_async(print_cancel_pool)\n pool.apply_async(wave_trade_pool, (hot_coin,))\n # pool.apply_async(func, (hot_coin, period_trade.period_trade,))\n pool.apply_async(func, (hot_coin, alert_price,))\n pool.apply_async(func, (hot_coin, fork_trade,))\n pool.apply_async(func, (hot_coin, jump_depth,))\n pool.apply_async(func, (hot_coin, fill_depth,))\n pool.apply_async(func, (hot_coin, cancel_over_order,))\n pool.apply_async(run_sched)\n pool.apply_async(tg_bot)\n pool.close()\n pool.join()\n","repo_name":"ccsubia/vaex-auto-trade-v2","sub_path":"src/trade_main.py","file_name":"trade_main.py","file_ext":"py","file_size_in_byte":27071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"19349639850","text":"import networkx as nx\n\ndef dfs_topological_sort(graph):\n \"\"\"\n Compute one topological sort of the given directed graph.\n \"\"\"\n \n # La solucion que retorna esta función es un diccionario de Python.\n # * La clave del diccionario es el número del nodo\n # * El valor es el orden topologico asignado a ese nodo\n # \n # Por ejemplo, si tenemos el siguiente grafo dirigido con 3 vertices:\n # 3 ---> 2 ---> 1\n # ... el orden topologico es:\n # El vértice 3 va en la primera posición\n # El vértice 2 en la segunda posición\n # El vértice 1 en la tercera posición\n # Se devuelve\n # {1: 3, 2: 2, 3: 1}\n\n solution = dict()\n\n\n Visitado = []\n Pila = []\n Comienzo = [x for x in graph.nodes if graph.in_degree(x) == 0]#metemos los nodos donde su adyacente sea solo de salida, y no de entrada\n \n \n \n def dfs(graph, inicial, Visitado, Pila):\n if inicial in Visitado:\n return Pila, Visitado\n \n if graph.out_degree(inicial) == 0:\n # nodo y todas sus ramas han sido visitadas\n Pila.append(inicial)\n Visitado.append(inicial)\n return Pila, Visitado\n \n # recorre todas las ramas\n for node in graph[inicial]:\n if node in Visitado:\n continue\n Pila, Visitado = dfs(graph, node, Visitado, Pila)\n \n # ahora insertamos en pila, si no esta visitiado\n if inicial not in Visitado:\n Pila.append(inicial)\n Visitado.append(inicial)\n \n return Pila, Visitado\n \n \n for i in Comienzo:\n Pila, Visitado = dfs(graph, i, Visitado, Pila)\n \n for i in graph.nodes():\n solution[i]=Pila.pop()\n\n return solution\n","repo_name":"AcoranGonzalezMoray/Algoritmo-Topological-Sort","sub_path":"solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"20501632349","text":"# @Date : 15:09 08/21/2021\n# @Author : ClassicalPi\n# @FileName: 4.py\n# @Software: PyCharm\n#\n# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可\n#\n# 计算最小航行费用\n# @param input int整型二维数组 二维网格\n# @return int整型\n#\nimport sys\nclass Solution:\n def minSailCost(self , input ):\n cache = {}\n costMap = {\n 0:2,\n 1:1,\n 2:sys.maxsize\n }\n def recur(cur_row:int,cur_column:int,row:int,column:int):\n if cur_row == row - 1 and cur_column == column - 1:\n return costMap[input[cur_row][cur_column]]\n if input[cur_row][cur_column] == 2 and not(cur_row == 0 and cur_column ==0):\n return sys.maxsize\n temp = 1\n if input[cur_row][cur_column] == 0:\n temp = 2\n if cur_row == 0 and cur_column ==0:\n temp = 0\n ret = [sys.maxsize]\n if cur_row + 1 < row:\n if cache.get((cur_row+1,cur_column),-1) == -1:\n res = recur(cur_row+1,cur_column,row,column)\n cache[(cur_row+1,cur_column)] = res\n ret.append(res)\n else:\n ret.append(cache[(cur_row+1,cur_column)])\n if cur_column + 1 < column:\n if cache.get((cur_row,cur_column+1),-1) == -1:\n res = recur(cur_row,cur_column+1,row,column)\n cache[(cur_row,cur_column+1)] = res\n ret.append(res)\n else:\n ret.append(cache[(cur_row,cur_column+1)])\n return min(ret) + temp\n res = recur(0,0,len(input),len(input[0]))\n if res >= sys.maxsize:\n return -1\n # res -= costMap[input[0][0]]\n return res\n\nif __name__ == '__main__':\n S = Solution()\n print(S.minSailCost([[2,1,1,1,0],[0,1,0,1,0],[1,1,2,1,1],[0,2,0,0,1]]))","repo_name":"GuoYunZheSE/Leetcode","sub_path":"Contest/20210821/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"69"} +{"seq_id":"3501862622","text":"import cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(0)\n\n\n\n\nlower_blue = np.array([90,50, 20], dtype=np.uint8)\nupper_blue = np.array([140,255, 255], dtype=np.uint8)\n\nlower_yellow = np.array([20,113, 20], dtype=np.uint8)\nupper_yellow = np.array([40,255, 255], dtype=np.uint8)\n\nlower_green = np.array([45,85, 20], dtype=np.uint8)\nupper_green= np.array([77,255, 255], dtype=np.uint8)\n\nlower_red1 = np.array([1,100, 50], dtype=np.uint8)\nupper_red1= np.array([5,100, 255], dtype=np.uint8)\n\nlower_red2 = np.array([175,100, 50], dtype=np.uint8)\nupper_red2= np.array([179,255, 255], dtype=np.uint8)\n\n\nblue = {\n 'color': (255,0,0),\n 'pos': (0,50),\n 'text': 'Blue'\n }\nred = {\n 'color': (0,0,255),\n 'pos': (140,50),\n 'text': 'Red'\n }\nyellow = {\n 'color': (0,255,255),\n 'pos': (270,50),\n 'text': 'Yellow'\n }\ngreen = {\n 'color': (0,255,0),\n 'pos': (460,50),\n 'text': 'Green'\n }\n\n\n\ndef drawTexts():\n\n cv2.rectangle(frame,(0,0),(640,55), 0,-1)\n cv2.putText(frame, blue['text'],blue['pos'],0,2,(255,255,255),2,cv2.LINE_AA)\n cv2.putText(frame,red['text'],red['pos'],0,2,(255,255,255),2,cv2.LINE_AA)\n cv2.putText(frame,yellow['text'],yellow['pos'],0,2,(255,255,255),2,cv2.LINE_AA)\n cv2.putText(frame,green['text'],green['pos'],0,2,(255,255,255),2,cv2.LINE_AA)\n\ndef drawMatches(mask,color):\n cnts,_ = cv2.findContours(mask,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\n\n\n for c in cnts:\n a = cv2.contourArea(c)\n if a>1000:\n\n #Calculate moments to get center\n M = cv2.moments(c)\n\n #Get coordinates of the center of the object\n cX = int(M[\"m10\"] / M[\"m00\"])\n cY = int(M[\"m01\"] / M[\"m00\"])\n new_c = cv2.convexHull(c)\n\n cv2.drawContours(frame,[new_c],0,(0,0,255),2,cv2.LINE_AA)\n cv2.circle(frame,(cX,cY),5,(255,255,255),-1)\n cv2.putText(frame,color['text'],color['pos'],0,2,color['color'],2, cv2.LINE_AA)\n return\n\n\n\nwhile True:\n ret, frame = cap.read()\n if not ret:\n break\n drawTexts()\n\n frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n blueMask = cv2.inRange(frame_hsv, lower_blue, upper_blue)\n yellowMask = cv2.inRange(frame_hsv, lower_yellow, upper_yellow)\n greenMask = cv2.inRange(frame_hsv, lower_green, upper_green)\n redMask1 = cv2.inRange(frame_hsv, lower_red1, upper_red1)\n redMask2 = cv2.inRange(frame_hsv, lower_red2, upper_red2)\n\n redMask = cv2.add(redMask1,redMask2)\n \n drawMatches(blueMask, blue)\n drawMatches(yellowMask,yellow)\n drawMatches(greenMask,green)\n drawMatches(redMask,red)\n\n \n\n \n\n\n cv2.imshow(\"Video\", frame)\n\n\n if (cv2.waitKey(1) & 0xFF == ord('q')):\n break\n\ncap.release()\ncv2.destroyAllWindows()","repo_name":"Alefig12/opencv-learning","sub_path":"day02/8-colorTracking.py","file_name":"8-colorTracking.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"69"} +{"seq_id":"1585950466","text":"import backendtools\nimport redis\n\nbroker = 'broker.hivemq.com'\nport = 1883\nvalue_types = [\"vehicle-gap-time\", \"vehicle-count\", \"vehicle-speed\", \"CreateUtc\"]\ndata_template = {'vehicle-gap-time': [], 'vehicle-speed': [], 'vehicle-count': [], 'time': []}\n\n\ndef main():\n df = backendtools.read_csv(\"detectors-simulated.csv\")\n detector_topics = df['topics'].values.tolist()\n detector_ids=df['id'].values.tolist()\n value_types = [\"vehicle-gap-time\", \"vehicle-count\", \"vehicle-speed\"]\n active_topics=[]\n for each_topic in detector_topics:\n for each_type in value_types:\n active_topics.append((each_topic + each_type,0))\n\n db = redis.Redis()\n backendtools.initialize_db(db, detector_ids, data_template)\n\n client = backendtools.connect_mqtt(broker, port)\n client.user_data_set(db)\n client.subscribe(active_topics)\n\n client.on_message = backendtools.on_message\n client.loop_forever()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jhanmtl/mtl-realtime-traffic-mqtt","sub_path":"backend/mqtt_sim/collect_sim.py","file_name":"collect_sim.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"69"} +{"seq_id":"4350229366","text":"\"Test functions for loading distributed generation scenario data\"\n\nfrom pathlib import Path\nimport pandas as pd\nimport pytest\n\nfrom powergenome.distributed_gen import (\n load_region_pop_frac,\n interp_dg,\n distributed_gen_profiles,\n)\n\nCWD = Path.cwd()\nDATA_FOLDER = CWD / \"tests\" / \"data\" / \"dist_gen\"\n\n\ndef test_load_pop_frac():\n fn = \"ipm_state_pop_weight_20220329.csv\"\n pop_frac = load_region_pop_frac(path_in=DATA_FOLDER, fn=fn)\n\n fn = \"ipm_state_pop_weight_20220329.parquet\"\n pop_frac = load_region_pop_frac(path_in=DATA_FOLDER, fn=fn)\n\n\ndef test_interp():\n year1 = 2020\n year2 = 2030\n data = {\n \"time_index\": [0, 1, 2, 3] * 2,\n \"year\": [year1] * 4 + [year2] * 4,\n \"region_distpv_mwh\": [0] * 4 + [10] * 4,\n }\n df = pd.DataFrame(data)\n\n target_year = 2025\n interp_results = interp_dg(df, year1, year2, target_year)\n assert interp_results.mean() == 5\n\n target_year = 2027\n interp_results = interp_dg(df, year2, year1, target_year)\n assert interp_results.mean() == 7\n\n target_year = 2030\n interp_results = interp_dg(df, year1, year2, target_year)\n assert interp_results.mean() == 10\n\n target_year = 2020\n interp_results = interp_dg(df, year1, year2, target_year)\n assert interp_results.mean() == 0\n\n\ndef test_distributed_gen_profiles():\n profile_fn = \"nrel_cambium_distr_pv_2022_slim.parquet\"\n scenario = \"MidCase\"\n\n dg = distributed_gen_profiles(\n profile_fn=profile_fn,\n year=2025,\n scenario=scenario,\n regions=[\"WECC_PNW\", \"WECC_MT\"],\n path_in=DATA_FOLDER,\n )\n assert not dg.empty\n assert len(dg.columns) == 2\n assert dg.mean().mean() > 0\n\n dg = distributed_gen_profiles(\n profile_fn=profile_fn,\n year=2024,\n scenario=scenario,\n regions=[\"WECC_PNW\", \"WECC_SNV\", \"WECC_NNV\"],\n path_in=DATA_FOLDER,\n region_aggregations={\"NV\": [\"WECC_SNV\", \"WECC_NNV\"]},\n )\n assert not dg.empty\n assert len(dg.columns) == 2\n assert dg.mean().mean() > 0\n\n with pytest.raises(ValueError):\n dg = distributed_gen_profiles(\n profile_fn=profile_fn,\n year=2025,\n scenario=\"invalid\",\n regions=[\"WECC_PNW\", \"WECC_MT\"],\n path_in=DATA_FOLDER,\n )\n\n with pytest.raises(KeyError):\n dg = distributed_gen_profiles(\n profile_fn=profile_fn,\n year=2025,\n scenario=scenario,\n regions=[\"invalid\"],\n path_in=DATA_FOLDER,\n )\n\n with pytest.raises(KeyError):\n dg = distributed_gen_profiles(\n path_in=None,\n profile_fn=profile_fn,\n year=2025,\n scenario=scenario,\n regions=[\"invalid\"],\n )\n","repo_name":"PowerGenome/PowerGenome","sub_path":"tests/dist_gen_test.py","file_name":"dist_gen_test.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","stars":176,"dataset":"github-code","pt":"69"} +{"seq_id":"42810899864","text":"# No Tree class, a Tree is basically nodes referencing each other\r\nclass TreeNode:\r\n def __init__(self, data, children=[],h=0):\r\n self.data = data\r\n self.children=children\r\n self.height = h # height is currently not used, it is kept in the code for possible use in the future\r\n\r\n def __str__(self):\r\n string = self.data\r\n return string\r\n\r\n def set_child(self, child):\r\n self.children = [child]\r\n child.height = self.height + 1\r\n\r\n def set_children(self, left, right):\r\n self.children = [left, right]\r\n left.height = self.height + 1\r\n right.height = self.height + 1\r\n\r\n\r\ndef CTL_conversion(root: TreeNode): # Take the root of the tree as input\r\n # Check if there are syntax that can be converted\r\n frontier = []\r\n if root.data == \"IMPLIES\": # Translate D->C into \"not(D) OR C\"\r\n root.data = \"OR\"\r\n temp = root.children[0]\r\n temp2 = root.children[1]\r\n negation = not_of(temp)\r\n root.set_children(negation,temp2)\r\n frontier.append(temp)\r\n frontier.append(temp2)\r\n if root.data == \"AX\":\r\n root.data = \"NOT\"\r\n temp = root.children[0]\r\n negation = not_of(temp)\r\n exist_next = TreeNode(\"EX\")\r\n root.set_child(exist_next)\r\n exist_next.set_child(negation)\r\n frontier.append(temp)\r\n if root.data == \"EF\":\r\n ef2eu(root,frontier)\r\n if root.data == \"AG\":\r\n ef = TreeNode(\"EF\")\r\n temp = root.children[0]\r\n root.set_child(ef)\r\n ef.set_child(temp)\r\n root.data=\"NOT\"\r\n ef2eu(ef,frontier)\r\n if root.data == \"AU\":\r\n p1 = root.children[0]\r\n p2 = root.children[1]\r\n notp1 = not_of(p1)\r\n notp2 = not_of(p2)\r\n theAnd = and_of(notp1, notp2)\r\n eu = eu_of(notp2, theAnd)\r\n eg = eg_of(notp2)\r\n theOr = or_of(eu, eg)\r\n root.data = \"NOT\"\r\n root.set_child(theOr)\r\n frontier.append(p1)\r\n frontier.append(p2)\r\n if root.data == \"EG\":\r\n root.data=\"NOT\"\r\n af = TreeNode(\"AF\")\r\n temp = root.children[0]\r\n root.set_child(af)\r\n af.set_child(not_of(temp))\r\n frontier.append(temp)\r\n else:\r\n for i in root.children:\r\n frontier.append(i)\r\n # ***** recursive call for all children of the root *****\r\n if frontier:\r\n for i in frontier:\r\n CTL_conversion(i)\r\n return 0\r\n\r\n# methods that are called by CTL_conversion\r\n\r\ndef ef2eu(node: TreeNode, frontier):\r\n node.data = \"EU\"\r\n temp = node.children[0]\r\n tru = TreeNode(\"TRUE\")\r\n node.set_children(tru, temp)\r\n frontier.append(temp)\r\n\r\n# Operators are nodes in this data structure, below are functions that make \"Operator Nodes\"\r\n# It's here to make coding easier\r\ndef not_of(node: TreeNode):\r\n # take a node as input, return a node whose data is \"not\" and have the input node as single child\r\n negation=TreeNode(\"NOT\")\r\n negation.set_child(node)\r\n return negation\r\n\r\ndef and_of(phi1:TreeNode,phi2:TreeNode):\r\n AND=TreeNode(\"AND\")\r\n AND.set_children(phi1,phi2)\r\n return AND\r\n\r\ndef or_of(phi1:TreeNode,phi2:TreeNode):\r\n OR=TreeNode(\"OR\")\r\n OR.set_children(phi1,phi2)\r\n return OR\r\n\r\ndef eu_of(phi1:TreeNode,phi2:TreeNode):\r\n eu=TreeNode(\"EU\")\r\n eu.set_children(phi1,phi2)\r\n return eu\r\n\r\ndef eg_of(node: TreeNode):\r\n eg=TreeNode(\"EG\")\r\n eg.set_child(node)\r\n return eg\r\n\r\ndef af_of(node: TreeNode):\r\n af=TreeNode(\"AF\")\r\n af.set_child(node)\r\n return af\r\n\r\ndef ex_of(node: TreeNode):\r\n ex=TreeNode(\"EX\")\r\n ex.set_child(node)\r\n return ex\r\n\r\ndef ef_of(node: TreeNode):\r\n res=TreeNode(\"EF\")\r\n res.set_child(node)\r\n return res\r\n\r\ndef ag_of(node: TreeNode):\r\n res=TreeNode(\"AG\")\r\n res.set_child(node)\r\n return res\r\n\r\ndef au_of(node: TreeNode, node2: TreeNode):\r\n res=TreeNode(\"AU\")\r\n res.set_children(node, node2)\r\n return res\r\n\r\ndef ax_of(node: TreeNode):\r\n res=TreeNode(\"AX\")\r\n res.set_child(node)\r\n return res\r\n\r\ndef implies_of(node: TreeNode, node2: TreeNode):\r\n res=TreeNode(\"IMPLIES\")\r\n res.set_children(node, node2)\r\n return res\r\n\r\n# *** of-functions ENDS ***\r\n\r\ndef toString(node):\r\n if len(node.children)==0:\r\n return node.data\r\n if len(node.children)==1:\r\n return node.data+\"(\"+toString(node.children[0])+\")\"\r\n if len(node.children)==2:\r\n return toString(node.children[0])+\" \"+node.data+\" \"+toString(node.children[1])\r\n\r\n\r\n","repo_name":"Zhanjun-Li/Python-Model-Checker","sub_path":"Python Model Checker/CTL.py","file_name":"CTL.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"23252229978","text":"import cv2\n\ndata = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\n# img = cv2.imread('img1.jpg')\n# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# faces = data.detectMultiScale(gray)\n# for (x, y, w, h) in faces:\n# cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)\n# cv2.imshow('img',img)\n# cv2.waitKey()\n\ncap = cv2.VideoCapture(0)\nwhile(True):\n suframe, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = data.detectMultiScale(gray)\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n cv2.imshow('img',frame)\n key=cv2.waitKey(1)\n if(key==ord('Q') or key==ord('q')):\n break\ncap.release()\ncv2.destroyAllWindows()\n\nprint(\"finished\")","repo_name":"Luckyhv/face-recognition","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"41635364543","text":"import numpy as np \nimport pandas as pd \nimport geopandas as gpd\nimport shapely as shp\nfrom shapely.geometry import Point\nfrom sklearn.neighbors import NearestNeighbors\nfrom shapely.ops import nearest_points\nfrom copy import deepcopy\n\n\"\"\"\nGLOBAL VARIABLES\n\"\"\"\nCOUNTY_SHP_FILE = \"data/UScounties/UScounties.shp\"\nBANNED_STATES = ['Arkansas','Alabama','Idaho','Kentucky','Louisiana','Kentucky','Mississippi','Missouri','Oklahoma','South Dakota','Tenesee','Texas','West Virginia','Wisconsin']\nEPSG = 4\n\n\n\"\"\"load_state_bounds(): given a shp file of county locations, return a GeoDataFrame with the states as rows\n input:\n COUNTY_SHP_FILE: the path to a shp file containing us county data\n EPSG: the ESPG id of the coordinate reference system to use\n\"\"\"\ndef load_state_bounds(COUNTY_SHP_FILE,EPSG=4326):\n df_county = gpd.read_file(COUNTY_SHP_FILE)\n df_county = df_county.to_crs(f\"EPSG:{EPSG}\")\n df_county = df_county[~df_county['STATE_NAME'].isin(['Alaska','Hawaii'])]#remove Alaska and Hawai\n df_state = df_county.dissolve(by = \"STATE_NAME\")['geometry'].reset_index()#[['STATE_NAME','geometry']]#aggregate by stateI\n return df_state\n\n\"\"\"\nrandom_points_within_polygon(); raturns a list of n points within a given polygon\n inputs: \n polygon: a polygon from which to generate points inaside of \n number: the number of points to generate\n output:\n points: a row of a GeoDataFrame, each row should contain one individual in the population\n df2: a seperate dataframe with facility placements in it\n\"\"\"\ndef nearest(row,df2,geom1_col = 'geometry'):\n #find the geometry that is closest\n geom_union = df2.unary_union#create a multipoint with all facility placements\n return nearest_points(row[geom1_col],geom_union)[1]#find the nearest facility to each ind in the population\n\ndef get_distance(row,geom1_col,geom2_col):\n return row[geom1_col].distance(row[geom2_col])\n\n\n\"\"\"\ncalc_facility_distance(): takes in a df of population and facility placements, returns a df the nearest facility to each individual and the distance\ninput:\n df1: a datafame with Shapley.geometry.Point objects for each individual in the population\n df2: a datafame with Shapley.geometry.Point objects for each facility\n geom1_col: the column in that contains the point objects\n geom2_col: the column in that contains the point objects\nreturns: \n concat_df: a df with the position of each indiviudal, its nearest facility and the distance\n\"\"\"\ndef calc_facility_distance(df1,df2,geom1_col='geometry',geom2_col=\"geometry\"):\n #calculate the nearest facilty to each member of the population\n nearest_fac_series = gdf_pop.apply(nearest,df2=df2,geom1_col=geom1_col,axis = 1)\n #reformat nearest facility data into a df\n nearest_fac_df = nearest_fac_series.reset_index().rename(columns = {0:\"nearest_fac\"}).set_geometry(\"nearest_fac\")\n #calculate the distance between each individual and the nearest facility\n distance_df=gdf_pop['geometry'].distance(nearest_fac_df).reset_index().rename(columns = {0:\"distance\"})\n #join all data and return\n concat_df = pd.concat([gdf_pop,nearest_fac_df,distance_df],axis = 1).drop(\"index\",axis = 1)\n return concat_df\n\n\"\"\"\ncalculate the objective function(dist^beta) for each facility. return the result as a dataframe\n\"\"\"\ndef objective_function(df,value_col,groupby_col,beta=1):\n df['weighted_dist'] = df[value_col]**beta#take the distance to an exponential\n df = df.groupby(df[groupby_col].to_wkt()).agg(total_fac_weighted_dist = ('weighted_dist',sum))\n return df['total_fac_weighted_dist'].sum()\n\n\"\"\"\nmove_agents: generate a new facility location df with a random subset of agents moved to new locations\n inputs:\n my_fac_placement: a geodataframe with the locations of our facilties\n num_replacements: the number of agents to move\n output:\n fac_placement_df_test: a df with the location of our facilites with a subset moved to new random locations\n\"\"\"\ndef move_agents(my_fac_placements_df,num_replacements):\n fac_placements_df_test = deepcopy(fac_placements_df)#deepcopy the facility placement list\n num_fac = fac_placements_df.shape[0]#get the number of facilities\n #get new trial facility locations\n new_points = random_points_within_polygon(us_border,num_replacements)\n #pick facilities to move\n inds_to_change = np.random.choice(np.arange(num_fac),num_replacements)\n #iterate through the list of possibilites, change as needed\n for i,ind in enumerate(inds_to_change):\n print(f\"i:f{i}\")\n fac_placements_df_test.loc[ind,'geometry'] = new_points.geometry.values[i]\n return fac_placements_df_test\n \n\n\"\"\"\"\ninit the model for a single facility\n\"\"\"\n#load county data \ndf_pop = pd.read_csv(\"data/simulated_pop_points.csv\")\ngdf_pop = gpd.GeoDataFrame(df_pop,geometry = gpd.points_from_xy(df_pop.lon,df_pop.lat)).rename(columns = {\"Unnamed: 0\":\"index\"})#.rename(columns ={\" Unnamed: 0\",'index'})#generate initial facility placement\n#load state boundaries\ndf_state = load_state_bounds(COUNTY_SHP_FILE)\ndf_state_legal = df_state[~df_state['STATE_NAME'].isin(BANNED_STATES)]\n#pull out polygon\nus_border = df_state.dissolve().geometry.values[0]#extract shapley polygons from dataframe\n#cut down to subset of states with legalized facilites\nus_legal_border = df_state.dissolve().geometry.values[0]#extract shapley polygon from dataframe\nfac_placements_df = random_points_within_polygon(us_border,100).reset_index()#\n\n#calculate the distance to the nearest facility\nfac_pop_dist_df = calc_facility_distance(gdf_pop,fac_placements_df)\nobjective_function_val = objective_function(fac_pop_dist_df,'distance','nearest_fac')\n\n\n\n \n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"WillHWThompson/MOCSFacilityPlacement","sub_path":"gen_population.py","file_name":"gen_population.py","file_ext":"py","file_size_in_byte":6423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"69"} +{"seq_id":"33779332520","text":"\"\"\"\nFunctions to unpack Simrad EK60 .raw files\nModification from original source cited below included:\n- python 3.6 compatibility\n- stripped off mi-instrument dependency to make the code standalone\n\nTo be added:\n- need a generic .raw filename parser\n- restore logging function\n- restore exception handler\n\nOriginal parser code sources was from:\noceanobservatories/mi-instrument @https://github.com/oceanobservatories/mi-instrument\nOriginal author Ronald Ronquillo & Richard Han\n\n\"\"\"\n\n\nfrom collections import defaultdict\nfrom struct import unpack_from, unpack\nimport numpy as np\nimport os\nimport re\nimport h5py\nfrom datetime import datetime as dt\nfrom matplotlib.dates import date2num\nfrom base_def import BaseEnum\n\n\n# Set contants for unpacking .raw files\nBLOCK_SIZE = 1024*4 # Block size read in from binary file to search for token\nLENGTH_SIZE = 4\nDATAGRAM_HEADER_SIZE = 12\nCONFIG_HEADER_SIZE = 516\nCONFIG_TRANSDUCER_SIZE = 320\n\n# set global regex expressions to find all sample, annotation and NMEA sentences\nSAMPLE_REGEX = b'RAW\\d{1}'\nSAMPLE_MATCHER = re.compile(SAMPLE_REGEX, re.DOTALL)\n\n# Reference time \"seconds since 1900-01-01 00:00:00\"\nREF_TIME = date2num(dt(1900, 1, 1, 0, 0, 0))\n\n# ---------- NEED A GENERIC FILENAME PARSER -------------\n# Common EK60 *.raw filename format\n# EK60_RAW_NAME_REGEX = r'(?P\\S*)_*OOI-D(?P\\d{8})-T(?P