diff --git "a/4156.jsonl" "b/4156.jsonl"
new file mode 100644--- /dev/null
+++ "b/4156.jsonl"
@@ -0,0 +1,1281 @@
+{"seq_id":"22865078745","text":"import jieba\ntxt = open(\"三国演义.txt\",'r',encoding='utf-8').read()\nexcludes = {\"将军\",\"却说\",\"荆州\",\"二人\",\"不可\",\n \"不能\",\"如此\",\"商议\",\"如何\",\"主公\",\n \"军士\",\"左右\",\"军马\",\"引兵\",\"次日\",\n \"大喜\",\"天下\",\"东吴\"}#通过结果,去掉排在前面但又不是人名的词\nwords = jieba.lcut(txt)#将文本进行分词并返回一个列表\ncounts = {}#利用字典数据类型对结果进行存储\nfor word in words:\n if len(word) ==1:\n continue\n elif word ==\"诸葛亮\" or word == \"孔明曰\":#将jieba识别出来的“别名”进行统一\n rword = \"孔明\"\n elif word == \"关公\" or word == \"云长\":\n rword = \"关羽\"\n elif word == \"玄德\" or word == \"玄德曰\":\n rword = \"刘备\"\n elif word == \"孟德\" or word == \"丞相\":\n rword = \"曹操\"\n else:\n rword = word\n counts[rword] = counts.get(rword,0) +1 #遍历,统计每个单词出现的次数\nfor word in excludes:\n del counts[word]\nitems = list(counts.items())#取出所有键值对并存入列表中\nitems.sort(key=lambda x:x[1],reverse=True)#按照词频由大到小的顺序排列\nfor i in range(8):\n word,count = items[i]\n print(\"{:<10}{:>5}\".format(word,count))\n","repo_name":"sssswf/pythonLearningDiary","sub_path":"python入门案例/三国演义人物出场次数统计.py","file_name":"三国演义人物出场次数统计.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"28442979349","text":"import json\nimport urllib\nfrom model import User, Movie, connect_to_db, db\nfrom server import app\n\n\ndef load_movies():\n\n my_results = json.load(urllib.urlopen(\"https://www.kimonolabs.com/api/6vk1k5hu?apikey=f2jrKtObW1sW7y1aJxhCHwTqiTCMzSYR\"))\n\n collection1_list = my_results['results']['collection1']\n\n for i in collection1_list:\n title = i['title']['text']\n genre = i['genre']\n length = i['length']\n image_link = i['image']['src']\n\n new_movie = Movie(\n title=title,\n genre=genre,\n length=length,\n image_link=image_link)\n\n db.session.add(new_movie)\n db.session.commit()\n\n\nif __name__ == \"__main__\":\n connect_to_db(app)\n db.create_all()\n load_movies()\n","repo_name":"karenwsit/FilmsToFriends","sub_path":"seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24559733011","text":"#!/usr/bin/python3\n\n# UI imports\nfrom PyQt5 import QtWidgets, QtCore, QtGui\nfrom PyQt5.QtCore import QTimer\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\n\n# ROS imports\nimport rospy\nfrom rospkg import RosPack\nfrom std_msgs.msg import Bool\nfrom actionlib_msgs.msg import GoalID\n\n# misc imports\nimport sys\nimport signal\nimport argparse\nimport yaml\n\n\n\ndef signal_handler():\n\tQApplication.quit()\n\tsys.exit(0)\n\n# Generated usigng pyuic5 >>>>>>>>>>>>>\nclass Ui_main_window(object):\n\tdef setupUi(self, main_window):\n\t\tmain_window.setObjectName(\"main_window\")\n\t\tmain_window.resize(625, 477)\n\t\tmain_window.setStyleSheet(\"background-color: rgb(220, 220, 220);\")\n\t\tself.centralwidget = QtWidgets.QWidget(main_window)\n\t\tself.centralwidget.setObjectName(\"centralwidget\")\n\t\tself.start = QtWidgets.QPushButton(self.centralwidget)\n\t\tself.start.setGeometry(QtCore.QRect(30, 60, 251, 141))\n\t\tfont = QtGui.QFont()\n\t\tfont.setFamily(\"Tibetan Machine Uni\")\n\t\tfont.setPointSize(26)\n\t\tfont.setBold(False)\n\t\tfont.setItalic(False)\n\t\tfont.setWeight(50)\n\t\tself.start.setFont(font)\n\t\tself.start.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n\t\tself.start.setAutoFillBackground(False)\n\t\tself.start.setStyleSheet(\"background-color: rgb(138, 226, 52);\")\n\t\tself.start.setObjectName(\"start\")\n\t\tself.stop = QtWidgets.QPushButton(self.centralwidget)\n\t\tself.stop.setGeometry(QtCore.QRect(340, 60, 251, 141))\n\t\tfont = QtGui.QFont()\n\t\tfont.setFamily(\"Tibetan Machine Uni\")\n\t\tfont.setPointSize(26)\n\t\tfont.setBold(False)\n\t\tfont.setItalic(False)\n\t\tfont.setWeight(50)\n\t\tself.stop.setFont(font)\n\t\tself.stop.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n\t\tself.stop.setAutoFillBackground(False)\n\t\tself.stop.setStyleSheet(\"background-color: rgb(239, 41, 41);\")\n\t\tself.stop.setObjectName(\"stop\")\n\t\tself.resume = QtWidgets.QPushButton(self.centralwidget)\n\t\tself.resume.setGeometry(QtCore.QRect(30, 260, 251, 141))\n\t\tfont = QtGui.QFont()\n\t\tfont.setFamily(\"Tibetan Machine Uni\")\n\t\tfont.setPointSize(26)\n\t\tfont.setBold(False)\n\t\tfont.setItalic(False)\n\t\tfont.setWeight(50)\n\t\tself.resume.setFont(font)\n\t\tself.resume.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n\t\tself.resume.setAutoFillBackground(False)\n\t\tself.resume.setStyleSheet(\"background-color: rgb(252, 233, 79);\")\n\t\tself.resume.setObjectName(\"resume\")\n\t\tself.home = QtWidgets.QPushButton(self.centralwidget)\n\t\tself.home.setGeometry(QtCore.QRect(340, 260, 251, 141))\n\t\tfont = QtGui.QFont()\n\t\tfont.setFamily(\"Tibetan Machine Uni\")\n\t\tfont.setPointSize(26)\n\t\tfont.setBold(False)\n\t\tfont.setItalic(False)\n\t\tfont.setWeight(50)\n\t\tself.home.setFont(font)\n\t\tself.home.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n\t\tself.home.setAutoFillBackground(False)\n\t\tself.home.setStyleSheet(\"background-color: rgb(114, 159, 207);\")\n\t\tself.home.setObjectName(\"home\")\n\t\tmain_window.setCentralWidget(self.centralwidget)\n\n\t\tself.retranslateUi(main_window)\n\t\tQtCore.QMetaObject.connectSlotsByName(main_window)\n\n\tdef retranslateUi(self, main_window):\n\t\t_translate = QtCore.QCoreApplication.translate\n\t\tmain_window.setWindowTitle(_translate(\"main_window\", \"UR5 Control | Start-Stop-Resume-Home\"))\n\t\tself.start.setText(_translate(\"main_window\", \"START\"))\n\t\tself.stop.setText(_translate(\"main_window\", \"STOP\"))\n\t\tself.resume.setText(_translate(\"main_window\", \"RESUME\"))\n\t\tself.home.setText(_translate(\"main_window\", \"HOME\"))\n\t\nclass StopResumeExe(QMainWindow, Ui_main_window):\n\t\"\"\"\n\tPublishes the resume/stop commands input by the user.\n\t\"\"\"\n\n\tdef __init__(self, only_sim, parent=None):\n\t\tsuper().__init__(parent)\n\t\trospy.init_node('stop_resume_exe_gui', anonymous=True)\n\n\t\t# initializing variables\n\t\tdir_path = RosPack().get_path('cobot-control') + \"/scripts/stop_resume_exe/\"\n\t\t\n\t\t# opening YAML file for topics\n\t\twith open(dir_path + \"topics.yaml\", 'r') as stream:\n\t\t\ttry:\n\t\t\t\tself.topics = yaml.safe_load(stream)\n\t\t\texcept yaml.YAMLError as exc:\n\t\t\t\tprint(exc)\n\t\t\t\tprint(\"Exiting because some issues with loading YAML\")\n\t\t\t\tsys.exit(0)\n\n\t\tif only_sim:\n\t\t\tself.traj_cancel_pub = rospy.Publisher(self.topics['sim_traj_cancel'], GoalID, queue_size=1)\n\t\telse:\n\t\t\tself.traj_cancel_pub = rospy.Publisher(self.topics['hardware_traj_cancel'], GoalID, queue_size=1)\n\n\t\tself.cancel_traj = GoalID()\n\n\t\tself.is_started_pub = rospy.Publisher(self.topics['ur5_start'], Bool, queue_size=1)\n\t\tself.is_started = Bool()\n\t\tself.is_started.data = False\n\t\tself.is_started_pub.publish(self.is_started)\n\n\n\t\tself.is_stopped_pub = rospy.Publisher(self.topics['ur5_stop'], Bool, queue_size=1)\n\t\tself.is_stopped = Bool()\n\t\tself.is_stopped.data = False\n\t\tself.is_stopped_pub.publish(self.is_stopped)\n\n\t\tself.is_resumed_pub = rospy.Publisher(self.topics['ur5_resume'], Bool, queue_size=1)\n\t\tself.is_resumed = Bool()\n\t\tself.is_resumed.data = False\n\t\tself.is_resumed_pub.publish(self.is_resumed)\n\n\t\tself.is_homed_pub = rospy.Publisher(self.topics['ur5_home'], Bool, queue_size=1)\n\t\tself.is_homed = Bool()\n\t\tself.is_homed.data = False\n\t\tself.is_homed_pub.publish(self.is_homed)\n\n\t\tself.setupUi(self)\n\t\tself.connect_signals()\n\n\tdef connect_signals(self):\n\t\tself.start.clicked.connect(self.start_btn_clicked)\n\t\tself.stop.clicked.connect(self.stop_btn_clicked)\n\t\tself.resume.clicked.connect(self.resume_btn_clicked)\n\t\tself.home.clicked.connect(self.home_btn_clicked)\n\n\tdef start_btn_clicked(self):\n\t\tif self.is_homed.data:\n\t\t\tself.is_started.data = True\n\t\t\tself.is_homed.data= False\n\t\telse:\n\t\t\tprint(\"Please HOME the manipulator\")\n\t\tself.is_started_pub.publish(self.is_started)\n\t\tself.is_stopped_pub.publish(self.is_stopped)\n\t\tself.is_resumed_pub.publish(self.is_resumed)\n\t\tself.is_homed_pub.publish(self.is_homed)\n\t\n\t\t\n\tdef stop_btn_clicked(self):\n\t\tif self.is_started.data or self.is_resumed.data:\n\t\t\tself.is_resumed.data = False\n\t\t\tself.is_started.data = False\n\t\t\tself.is_stopped.data = True\n\t\telse:\n\t\t\tprint(\"Please START or RESUME operation of the manipulator\")\n\t\tself.is_started_pub.publish(self.is_started)\n\t\tself.is_stopped_pub.publish(self.is_stopped)\n\t\tself.is_resumed_pub.publish(self.is_resumed)\n\t\t\t\n\tdef resume_btn_clicked(self):\n\t\tif self.is_stopped.data:\n\t\t\tself.is_resumed.data = True\n\t\t\tself.is_stopped.data = False\n\t\telse:\n\t\t\tprint(\"Operation needs to be STOPPED to resume. Press HOME and START to begin a new trajectory execution\")\n\t\tself.is_stopped_pub.publish(self.is_stopped)\n\t\tself.is_resumed_pub.publish(self.is_resumed)\n\n\tdef home_btn_clicked(self):\n\t\tself.is_homed.data = True\n\t\tself.is_stopped.data = False\n\t\tself.is_started.data = False\n\t\tself.is_started_pub.publish(self.is_started)\n\t\tself.is_stopped_pub.publish(self.is_stopped)\n\t\tself.is_homed_pub.publish(self.is_homed)\n\n\n\nif __name__ == '__main__':\n\tsignal.signal(signal.SIGINT, signal_handler)\n\tsignal.signal(signal.SIGTERM, signal_handler)\n\n\t# Create the parser\n\tmy_parser = argparse.ArgumentParser(description=\"A GUI interface to stop/resume UR5's operation\")\n\n\t# Add the arguments\n\tmy_parser.add_argument('-s','--onlysim',\n\t\t\t\t\t\taction='store_true',\n\t\t\t\t\t\thelp='Put this flag to use only simulation')\n\n\t# Execute the parse_args() method\n\targs, _ = my_parser.parse_known_args()\n\n\tapp = QtWidgets.QApplication(sys.argv)\n\twin = StopResumeExe(only_sim=args.onlysim)\n\n\t# keep on checking for CTRL+C every 100 ms\n\ttimer = QTimer()\n\ttimer.start(100)\n\ttimer.timeout.connect(lambda : None)\n\n\twin.show()\n\tapp.exec_()","repo_name":"Niegil-Francis/ur5-ag95-resources","sub_path":"cobot-control/scripts/stop_resume_exe/stop_resume_lsl.py","file_name":"stop_resume_lsl.py","file_ext":"py","file_size_in_byte":7281,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"40981577759","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect, HttpResponseForbidden\n\nfrom zoo.shortcuts import render\nfrom zoo.photos.models import Photo\nfrom zoo.trips.models import Trip\nfrom models import FlickrSet\nfrom client import Flickr\n\nimport datetime\nfrom dateutil import parser\n\nfrom django_openid import signed\n\ndef flickr_redirect(path):\n # Send them off to Flickr to authenticate, but first \n # we need to set a cookie specifying where they should come BACK to \n # since Flickr will return them to /flickr/callback/\n response = HttpResponseRedirect(Flickr().web_login_url(\"write\"))\n response.set_cookie('flickr_return_to', path)\n return response\n\n@login_required\ndef flickr_callback(request):\n return_to = request.COOKIES.get('flickr_return_to', '/')\n flickr_token = Flickr().get_token(request.GET.get('frob', ''))\n profile = request.user.get_profile()\n profile.flickr_token = flickr_token\n profile.save()\n response = HttpResponseRedirect(return_to)\n response.delete_cookie('flickr_return_to')\n return response\n\n@login_required\ndef index(request):\n profile = request.user.get_profile()\n if not profile.flickr_prefs_set_at:\n return HttpResponseRedirect('/flickr/prefs/')\n flickr_token = profile.flickr_token\n if not flickr_token:\n return flickr_redirect(request.path)\n page = request.GET.get('page', '1')\n try:\n page = max(int(page), 1)\n except ValueError:\n page = 1\n client = Flickr(token = flickr_token)\n token_info = client.auth_checkToken()\n user_id = token_info['auth']['user']['nsid']\n result = client.photos_search(\n user_id = 'me', per_page = 24, page = page,\n extras = 'date_taken,url_m'\n )\n photos = result['photos']['photo']\n num_pages = result['photos']['pages']\n return photo_picker(\n request, photos, 'Your recent photos', {\n 'paginated': num_pages > 1,\n 'num_pages': num_pages,\n 'page': page,\n 'has_next': page < num_pages,\n 'next_page': page + 1,\n 'has_prev': page > 1,\n 'prev_page': page - 1,\n }\n )\n\n@login_required\ndef places(request):\n flickr_token = request.user.get_profile().flickr_token\n if not flickr_token:\n return flickr_redirect(request.path)\n client = Flickr(token = flickr_token)\n token_info = client.auth_checkToken()\n user_id = token_info['auth']['user']['nsid']\n return render(request, 'flickr/places.html', {\n 'places': client.places_placesForUser(\n place_type = 'locality',\n ),\n })\n\n@login_required\ndef groups(request):\n flickr_token = request.user.get_profile().flickr_token\n if not flickr_token:\n return flickr_redirect(request.path)\n client = Flickr(token = flickr_token)\n token_info = client.auth_checkToken()\n user_id = token_info['auth']['user']['nsid']\n return render(request, 'flickr/groups.html', {\n 'groups': client.people_getPublicGroups(user_id = user_id),\n })\n\n@login_required\ndef group(request, group_nsid):\n flickr_token = request.user.get_profile().flickr_token\n if not flickr_token:\n return flickr_redirect(request.path)\n client = Flickr(token = flickr_token)\n token_info = client.auth_checkToken()\n group_info = client.groups_getInfo(group_id = group_nsid)\n user_id = token_info['auth']['user']['nsid']\n photos = client.groups_pools_getPhotos(\n group_id = group_nsid, user_id = user_id, extras = 'date_taken,url_m'\n )['photos']['photo']\n return photo_picker(\n request, photos, 'Your photos in %s' % group_info['group']['name']\n )\n\n@login_required\ndef sets(request):\n flickr_token = request.user.get_profile().flickr_token\n if not flickr_token:\n return flickr_redirect(request.path)\n client = Flickr(token = flickr_token)\n sets = client.photosets_getList()['photosets']['photoset']\n return render(request, 'flickr/sets.html', {\n 'sets': sets,\n 'show_photos': len(sets) <= 30,\n })\n\n@login_required\ndef single_set(request, set_id):\n flickr_token = request.user.get_profile().flickr_token\n if not flickr_token:\n return flickr_redirect(request.path)\n client = Flickr(token = flickr_token)\n token_info = client.auth_checkToken()\n user_id = token_info['auth']['user']['nsid']\n photos = client.photosets_getPhotos(\n photoset_id = set_id, media = 'photos', extras = 'date_taken,url_m'\n )['photoset']['photo']\n set_info = client.photosets_getInfo(\n photoset_id = set_id\n )['photoset']\n set_details = {\n 'set_title': set_info['title'],\n 'set_id': set_info['id'],\n 'set_description': set_info['description'],\n }\n return photo_picker(\n request, photos, 'Your set: %s' % set_details['set_title'],\n set_details = set_details\n )\n\n@login_required\ndef place(request, woe_id):\n flickr_token = request.user.get_profile().flickr_token\n if not flickr_token:\n return flickr_redirect(request.path)\n client = Flickr(token = flickr_token)\n token_info = client.auth_checkToken()\n user_id = token_info['auth']['user']['nsid']\n place_info = client.places_getInfo(woe_id = woe_id)\n photos = client.photos_search(\n woe_id = woe_id, user_id = user_id, extras = 'date_taken,url_m'\n )['photos']['photo']\n return photo_picker(\n request, photos, 'Your photos in %s' % place_info['place']['name']\n )\n\ndef photo_picker(request, photos, title, extra_context=None,set_details=None):\n # Enhance each photo with a signed dict for the checkbox field, so if \n # they DO select that photo we won't have to do another API call to look \n # up its details on Flickr\n photo_ids = [photo['id'] for photo in photos]\n already_imported_ids = set(Photo.objects.filter(\n flickr_id__in = photo_ids\n ).values_list('flickr_id', flat=True))\n enable_button = False\n for photo in photos:\n photo_info = {\n 'id': photo['photo_id'],\n 'farm': photo['farm'],\n 'secret': photo['secret'],\n 'server': photo['server'],\n 'title': photo['title'],\n 'taken_at': photo['datetaken'],\n 'width_m': photo['width_m'],\n 'height_m': photo['height_m'],\n }\n if set_details:\n photo_info.update(set_details)\n photo['signed'] = signed.dumps(photo_info)\n already_imported = photo['photo_id'] in already_imported_ids\n photo['already_imported'] = already_imported\n if not already_imported:\n enable_button = True\n \n context = {\n 'title': title,\n 'photos': photos,\n 'enable_button': enable_button,\n }\n if extra_context is not None:\n context.update(extra_context)\n \n return render(request, 'flickr/photo_picker.html', context)\n\n@login_required\ndef prefs(request):\n profile = request.user.get_profile()\n if request.method == 'POST':\n profile.flickr_prefs_set_at = datetime.datetime.now()\n for pref in (\n 'flickr_tag_common_names',\n 'flickr_tag_scientific_names',\n 'flickr_geotag'\n ):\n setattr(profile, pref, pref in request.POST)\n profile.save()\n return HttpResponseRedirect('/flickr/')\n \n return render(request, 'flickr/prefs.html', {\n 'profile': profile,\n })\n\n@login_required\ndef search(request):\n \"Search your own photos\"\n q = request.GET.get('q', '')\n if not q:\n return render(request, 'flickr/search.html')\n \n flickr_token = request.user.get_profile().flickr_token\n if not flickr_token:\n return flickr_redirect(request.path)\n client = Flickr(token = flickr_token)\n token_info = client.auth_checkToken()\n user_id = token_info['auth']['user']['nsid']\n photos = client.photos_search(\n user_id = user_id,\n text = q,\n extras = 'date_taken,url_m'\n )['photos']['photo']\n return photo_picker(request, photos, 'Search for \"%s\"' % q)\n\ndef flickr_error(request, msg):\n return render(request, 'flickr/error.html', {\n 'msg': msg,\n })\n\n@login_required\ndef selected(request):\n \"Should only ever be POSTed to with a list of photo IDs in the 'photo'\"\n photos_to_add = []\n for photo in request.POST.getlist('photo'):\n try:\n photos_to_add.append(signed.loads(photo))\n except ValueError:\n continue # Skip any that don't pass the signature check\n # Moderation is currently disabled:\n # is_visible = (\n # request.user.get_profile().is_not_brand_new_account() or \\\n # request.user.is_staff\n # )\n is_visible = True\n added_ids = []\n set_id = None\n for photo in photos_to_add:\n if Photo.objects.filter(flickr_id = photo['id']).count():\n continue\n p = Photo.objects.create(\n created_by = request.user,\n created_at = datetime.datetime.now(),\n title = photo['title'],\n photo = '',\n flickr_id = photo['id'],\n flickr_secret = photo['secret'],\n flickr_server = photo['server'],\n width_max_500 = int(photo['width_m']),\n height_max_500 = int(photo['height_m']),\n is_visible = is_visible,\n taken_at = parser.parse(photo['taken_at']),\n )\n added_ids.append(p.id)\n # Should we add it to a set as well?\n if 'set_id' in photo:\n flickr_set, created = FlickrSet.objects.get_or_create(\n flickr_id = photo['set_id'],\n defaults = {\n 'title': photo['set_title'],\n 'description': photo['set_description'],\n 'user': request.user,\n }\n )\n flickr_set.photos.add(p)\n set_id = photo['set_id']\n \n url = '/%s/photos/unassigned/' % request.user.username\n if set_id:\n url = '/%s/photos/unassigned/by-flickr-set/%s/' % (\n request.user.username,\n set_id\n )\n \n if added_ids:\n url += '?ids=' + (','.join(map(str, added_ids)))\n \n return HttpResponseRedirect(url)\n","repo_name":"devfort/wildlifenearyou","sub_path":"zoo/flickr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"70439366801","text":"import pandas as pd\nimport sys\nimport os\n\nfiles = os.listdir('logs')\ndf = pd.DataFrame()\nfor f in files:\n if f.endswith('.csv'):\n if f == 'exp11_GRU1_alldata_batchsize32_maxlen5_training.csv':\n print('1')\n df1 = pd.read_csv('logs/' + f)\n df1['taskName'] = f.replace('.csv', '')\n new_cols = []\n for col in df1.columns:\n # if col == 'loss':\n # col = 'all_loss'\n # if col == 'val_loss':\n # col = 'all_val_loss'\n if 'out_place_' in col:\n newcol = col.replace('out_place_', '')\n if newcol != 'loss' and newcol != 'val_loss':\n col = newcol\n new_cols.append(col)\n df1.columns = new_cols\n try:\n df = pd.concat([df, df1])\n except Exception as e:\n pass\ndf.to_csv('allRes.csv', index=False)","repo_name":"lkjie/stu-action-predict","sub_path":"kerascode/modelRes.py","file_name":"modelRes.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40890104228","text":"#!/usr/bin/env python\n#####################\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport numpy as np\n\nRESIDUALS_HEADER_SIZE = 2\n\ndef GatherNewResidualsValues(fileName,skip_data):\n\tresiduals_fid = open(fileName, 'r')\n\tcounter = -1\n\titer = []\n\ttime = []\n\tcontinuity = []\n\tx_momentum = []\n\ty_momentum = []\n\tz_momentum = []\n\tenergy = []\n\n\tfor i in range(RESIDUALS_HEADER_SIZE):\n\t\tnext(residuals_fid)\n\n\tif ( skip_data > 0 ):\n\t\tfor i in range(int(skip_data)-1):\n\t\t\tnext(residuals_fid)\n\n\tfor line in residuals_fid:\n\t\tnumbers = line.split()\n\t\titer.append(float(numbers[0]))\n\t\ttime.append(float(numbers[1]))\n\t\tcontinuity.append(float(numbers[3]))\n\t\tx_momentum.append(float(numbers[4]))\n\t\ty_momentum.append(float(numbers[5]))\n\t\tz_momentum.append(float(numbers[6]))\n\t\tenergy.append(float(numbers[7]))\n\t\tcounter = counter + 1\n\n\tif ( counter == -1 ):\n\t\tcounter = 0\n\n\treturn (counter,time,continuity,x_momentum,y_momentum,z_momentum,energy)\n\ndef NewResidualsPlot(time, continuity, x_momentum, y_momentum, z_momentum, energy, ax):\n\tax.semilogy(time,continuity,'-',color='#1f77b4', label='continuity',linewidth=1.5)\n\tax.semilogy(time,x_momentum,'-',color='#ff7f0e', label='x-momentum',linewidth=1.5)\n\tax.semilogy(time,y_momentum,'-',color='#2ca02c', label='y-momentum',linewidth=1.5)\n\tax.semilogy(time,z_momentum,'-',color='#d62728', label='z-momentum',linewidth=1.5)\n\tax.semilogy(time,energy,'-',color='#bcbd22', label='energy',linewidth=1.5)\n\thandles, labels = ax.get_legend_handles_labels()\n\tax.legend(handles,labels)\n\tax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n ncol=5, mode=\"expand\", borderaxespad=0.,prop={'size': 10})\n\ndef AppendToResidualsPlot(time, continuity, x_momentum, y_momentum, z_momentum, energy, ax):\n\tax.semilogy(time,continuity,'-',color='#1f77b4',linewidth=1.5)\n\tax.semilogy(time,x_momentum,'-',color='#ff7f0e',linewidth=1.5)\n\tax.semilogy(time,y_momentum,'-',color='#2ca02c',linewidth=1.5)\n\tax.semilogy(time,z_momentum,'-',color='#d62728',linewidth=1.5)\n\tax.semilogy(time,energy,'-',color='#bcbd22',linewidth=1.5)\n\n\ndef UpdateResidualsPlot(fileName, skip_data, ax):\n\tN,time,continuity,x_momentum,y_momentum,z_momentum,energy = GatherNewResidualsValues(fileName, skip_data)\n\n\tif ( skip_data == 0 ):\n\t\tNewResidualsPlot(time, continuity, x_momentum, y_momentum, z_momentum, energy, ax)\n\telse:\n\t\tAppendToResidualsPlot(time, continuity, x_momentum, y_momentum, z_momentum, energy, ax)\n\n\n\treturn (N)\n","repo_name":"loganoz/horses3d","sub_path":"utils/PythonUtilities/ResidualsMonitor.py","file_name":"ResidualsMonitor.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"3"}
+{"seq_id":"27776687780","text":"from __future__ import annotations\n\nimport base64\nimport json\nimport re\nfrom pathlib import Path\nfrom typing import Any, Optional\n\nimport jinja2\nimport marko\nfrom fastapi import Request\nfrom marko.ext.gfm import GFM\nfrom pydantic import BaseModel\n\nfrom ... import helpers\nfrom ...project import Project\nfrom ...router import router\n\n\nclass Props(BaseModel, extra=\"forbid\"):\n path: str\n text: str\n asPage: Optional[bool] = None\n\n\nclass Result(BaseModel, extra=\"forbid\"):\n text: str\n\n\n@router.post(\"/article/render\")\ndef endpoint(request: Request, props: Props) -> Result:\n return action(request.app.get_project(), props)\n\n\ndef action(project: Project, props: Props) -> Result:\n from ... import endpoints\n\n fs = project.filesystem\n text = props.text\n\n # Convert text\n markdown = marko.Markdown()\n markdown.use(GFM)\n text = markdown.convert(text)\n\n # Process text (native images)\n matches = re.finditer(r\"\", text)\n for match in matches:\n element = match.group(0)\n relpath = match.group(1)\n fullpath = fs.get_fullpath(props.path).parent / relpath\n if fullpath.is_file():\n data = base64.b64encode(fullpath.read_bytes()).decode()\n markup = render_template(\n \"templates/image.html\",\n format=fullpath.suffix[1:],\n data=data,\n )\n text = text.replace(element, markup)\n\n # Process text (mentions)\n records = helpers.extract_records(project, text=text, ignore_missing=True)\n for record in records:\n if record.type == \"image\":\n format = record.resource.get(\"format\", \"png\")\n data = base64.b64encode(fs.get_fullpath(record.path).read_bytes()).decode()\n markup = render_template(\n \"templates/image.html\",\n format=format,\n data=data,\n )\n text = text.replace(f\"@{record.name}\", markup)\n if record.type == \"map\":\n data = fs.get_fullpath(record.path).read_text()\n markup = render_template(\n \"templates/map.html\",\n id=record.name,\n data=data,\n )\n text = text.replace(f\"@{record.name}\", markup)\n if record.type == \"chart\":\n chart = helpers.read_json(project, path=record.path)\n result = endpoints.chart.render.action(\n project, endpoints.chart.render.Props(path=record.path, chart=chart)\n )\n data = json.dumps(result.chart)\n markup = render_template(\n \"templates/chart.html\",\n id=record.name,\n data=data,\n )\n text = text.replace(f\"@{record.name}\", markup)\n\n # Compose article\n if props.asPage:\n text = render_template(\"templates/page.html\", html=text)\n\n return Result(text=text)\n\n\ndef render_template(path: str, **context: Any):\n environment = jinja2.Environment()\n raw_template = Path(__file__).parent.joinpath(path).read_text()\n template = environment.from_string(raw_template)\n return template.render(**context)\n","repo_name":"okfn/opendataeditor","sub_path":"server/endpoints/article/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"3"}
+{"seq_id":"3539314346","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\n\"\"\"\nCity Blocks Flyover\n\nChallenge Description:\n\nIn our city we need to know how many blocks were impacted by a\nhelicopter flying over our city. In our city, all of the blocks are\nrectangular. They are separated by N number of straight horizontal\navenues that run East-West and M number of straight vertical streets\nwhich run North-South.\n\nA helicopter took off at the South-West corner of the city and flew\ndirectly to the farthest North-East corner. Your challenge is to\ndetermine how many city blocks it flew over?\nYou will be given two lists, the first one is for streets and the\nsecond one is for avenues. Each avenue and each street is represented\nby a distance D to itself from the helicopter's starting point. E.g.\n\nmanhattan_distance_1.jpg\nmanhattan_distance_2.jpg\n\nOn the first diagram the streets and the avenues are represented by\nthe following lists:\n\n(0,1,3,4,6) for streets\n(0,1,2,4) for avenues\n\nThe blocks the helicopter has flown over are colored dark grey.\nThe inner region of each small rectangle is a city block. Rectangles'\nborders are not considered as a part of a block.\n\nInput Sample:\n\nYour program should accept as its first argument a path to a\nfilename. Each line in this file is one test case. Each test case will\ncontain a list of distances for streets and a list of distances for\navenues. Each list is in a brackets and the distances are separated by\ncomma. The lists themselves are separated by a single whitespace. E.g.\n\n(0,2,4,8,10,13,14,18,22,23,24,33,40,42,44,47,49,53,55,63,66,81,87,91) (0,147,220)\n(0,1,2,4) (0,1,3,4,5)\n(0,1,3,4,6) (0,1,2,4)\n\nOutput Sample:\n\nFor each set of input print out the number of blocks the helicopter\nhas flown over. E.g.\n\n24\n6\n5\n\nConstraints:\nN, M are in range [1, 100]\nD is in range [1, 1000]\n\n\"\"\"\n\nimport sys\n\nwith open(sys.argv[1], 'r') as input:\n test_cases = input.read().strip().splitlines()\n\nfor test in test_cases:\n streets, avenues = test.split()\n streets_distances = [int(i) for i in streets.strip('())').split(',')]\n avenues_distances = [int(i) for i in avenues.strip('())').split(',')]\n intersections = []\n x_step = avenues_distances[-1] / streets_distances[-1]\n y_step = streets_distances[-1] / avenues_distances[-1]\n for i in streets_distances[1:-1]:\n intersections.append((float(i), i * x_step))\n for i in avenues_distances[1:-1]:\n intersections.append((i * y_step, float(i)))\n \n print(len(set(intersections)) + 1)\n","repo_name":"joedicastro/code_eval","sub_path":"moderate/city_blocks_flyover.py3","file_name":"city_blocks_flyover.py3","file_ext":"py3","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"3"}
+{"seq_id":"33896184921","text":"# 미확인 도착지\n# https://www.acmicpc.net/problem/9370\n\nimport heapq\nimport sys\ninput=sys.stdin.readline\nINF=int(1e9)\n\ndef dijkstra(distance, start):\n q=[]\n heapq.heappush(q, (0,start))\n distance[start]=0\n while q:\n dist, now=heapq.heappop(q)\n if distance[now]cost:\n distance[i[0]]=cost\n heapq.heappush(q, (cost, i[0]))\n\nT=int(input())\nfor _ in range(T):\n n,m,t=map(int, input().split())\n s,g,h=map(int, input().split())\n graph=[[] for _ in range(n+1)]\n gh=0\n for _ in range(m):\n a,b,d=map(int, input().split())\n graph[a].append((b,d))\n graph[b].append((a,d))\n if a in (g,h) and b in (g,h):\n gh=d\n x=[]\n for _ in range(t):\n x.append(int(input()))\n x.sort()\n \n distance=[INF]*(n+1)\n distance1=[INF]*(n+1)\n distance2=[INF]*(n+1)\n\n dijkstra(distance, s)\n dijkstra(distance1, g)\n dijkstra(distance2, h)\n\n answer=[INF]*(n+1)\n for i in x:\n answer[i]=min(distance2[s]+distance1[i]+gh, distance1[s]+distance2[i]+gh)\n\n for i in x:\n if answer[i]<=INF and answer[i]<=distance[i]:\n print(i, end=' ')\n print()","repo_name":"Greek-and-Roman-God/Athena","sub_path":"codingtest/week25/unidentified_destination_9370.py","file_name":"unidentified_destination_9370.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29564082584","text":"import random\r\n\r\ncount_of_attempts = 0 # Количество попыток\r\n\r\n\r\ndef ask_to_guess():\r\n \"\"\"\r\n Функция, получения начальных данных от пользователя.\r\n :return: Введенное пользователем число и верхняя граница допустимого случайного числа.\r\n \"\"\"\r\n print(\"Добро пожаловать в числовую угадайку\")\r\n print(\"Задача угадать число от 1 до n. Для начала введите n\")\r\n n = input_n()\r\n print(f\"Угадайте число от 1 до {n}\")\r\n typed_number = type_valid_number()\r\n return typed_number, n\r\n\r\n\r\ndef generate_random_number(n):\r\n \"\"\"\r\n Генерация случайного числа.\r\n :param n: Верхняя граница допустимого случайного числа.\r\n :return: Случайное число.\r\n \"\"\"\r\n return random.randint(1, n)\r\n\r\n\r\ndef guessing(random_number, typed_number):\r\n \"\"\"\r\n Функция попыток угадать число.\r\n :param random_number: Случайное число.\r\n :param typed_number: Введенное пользователем число\r\n :return:\r\n \"\"\"\r\n wrong_answer = True\r\n while wrong_answer:\r\n if check(random_number, typed_number):\r\n return\r\n else:\r\n typed_number = type_valid_number()\r\n\r\n\r\ndef check(random_number, typed_number):\r\n \"\"\"\r\n Проверка введенного числа.\r\n :param random_number: Случайное число.\r\n :param typed_number: Введенное пользователем число.\r\n :return: Угадал или нет (True/False).\r\n \"\"\"\r\n global count_of_attempts\r\n if random_number < typed_number:\r\n count_of_attempts += 1\r\n print(\"Ваше число больше загаданного, попробуйте еще разок\")\r\n return False\r\n elif random_number > typed_number:\r\n count_of_attempts += 1\r\n print(\"Ваше число меньше загаданного, попробуйте еще разок\")\r\n return False\r\n else:\r\n count_of_attempts += 1\r\n print(f\"Вы угадали число! Количество попыток: {count_of_attempts}. Поздравляем!\")\r\n return True\r\n\r\n\r\ndef input_n():\r\n \"\"\"\r\n Ввод верхней границы допустимого случайного числа.\r\n :return: Верхняя граница допустимого случайного числа.\r\n \"\"\"\r\n n = input()\r\n while True:\r\n if n.isdigit() and int(n) > 0:\r\n return int(n)\r\n else:\r\n print(\"Вы ввели n неправильно. Введите n\")\r\n n = input()\r\n\r\n\r\ndef type_valid_number():\r\n \"\"\"\r\n Функция приема числа от пользователя.\r\n :return: Корректно введенное пользователем число.\r\n \"\"\"\r\n while True:\r\n typed_number = input()\r\n if typed_number.isdigit() and 1 <= int(typed_number) <= 100:\r\n typed_number = int(typed_number)\r\n return typed_number\r\n else:\r\n print(\"А может быть все-таки введем целое число от 1 до 100?\")\r\n\r\n\r\ndef start_new_game():\r\n \"\"\"\r\n Старт новой игры.\r\n :return:\r\n \"\"\"\r\n print(\"Вы хотите начать новую игру? Введите Y или N\")\r\n answer = input()\r\n while True:\r\n if answer.upper() in \"Y\":\r\n return True\r\n elif answer.upper() in \"N\":\r\n return False\r\n else:\r\n print(\"Вы хотите начать новую игру? Введите Y или N\")\r\n answer = input()\r\n\r\n\r\ndef main():\r\n while True:\r\n global count_of_attempts\r\n typed_number, n = ask_to_guess()\r\n random_number = generate_random_number(n)\r\n guessing(random_number, typed_number)\r\n count_of_attempts = 0\r\n if start_new_game():\r\n continue\r\n else:\r\n break\r\n\r\n print(\"Спасибо, что играли в числовую угадайку. Еще увидимся...\")\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"toptenov/python-learning-projects","sub_path":"Игра угадайка.py","file_name":"Игра угадайка.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17029817764","text":"\"\"\"\nGiven integers M and N, write a program that counts how many positive integer pairs (a, b) satisfy the following conditions:\n\na + b = M\na XOR b = N\n\n\"\"\"\n\n\ndef num_pairs(m,n):\n\n\tcount = 0\n\n\tfor a in range(m):\n\t\tb = m - a\n\t\t#print(a,b, a^b)\n\n\t\tif a ^ b == n:\n\t\t\tprint(\"Here is {}^{} == {}\".format(a,b,n))\n\t\t\tcount += 1\n\n\treturn count\n\nprint(num_pairs(73,41))\n","repo_name":"rajashekharreddy/second_repo","sub_path":"practice/3_tests/333_jane_street.py","file_name":"333_jane_street.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9056262166","text":"\"\"\"\r\nFile which is read need to have next new line as last record else code will fail\r\n\"\"\"\r\nfrom os import strerror\r\n\r\n\r\ndef sort_dict(d):\r\n return dict(sorted(d.items(), key=lambda item: item[1]))\r\n\r\n\r\nname = marks = ''\r\ndiction = {}\r\nfilein = 'stud' # input('Enter filename :')\r\ntry:\r\n buffer = open(filein + '.txt', 'r')\r\n ch = buffer.read(1)\r\n while ch != '':\r\n while ch != '\\t':\r\n name = name + ch\r\n ch = buffer.read(1)\r\n name = name + '\\t'\r\n ch = buffer.read(1)\r\n while ch != '\\t':\r\n name = name + ch\r\n ch = buffer.read(1)\r\n ch = buffer.read(1)\r\n while ch != '\\n':\r\n marks = marks + ch\r\n ch = buffer.read(1)\r\n if name in diction.keys():\r\n diction[name] = diction[name] + float(marks)\r\n else:\r\n diction[name] = float(marks)\r\n name = marks = ''\r\n ch = buffer.read(1)\r\n diction = sort_dict(diction)\r\nexcept IOError as e:\r\n print('Unable to open file:', strerror(e.errno))\r\n exit(e.errno)\r\n\r\ntry:\r\n buffer = open(filein + '_result.txt', 'w')\r\nexcept IOError as e:\r\n print('Unable to open file:', strerror(e.errno))\r\n exit(e.errno)\r\nfor k, v in diction.items():\r\n buffer.write(k + ':' + str(v) + '\\n')\r\nbuffer.close()\r\nprint('File written')\r\n","repo_name":"JayProngs/Python_Certified_Associate_Programming_Exam","sub_path":"Python_code/student_file.py","file_name":"student_file.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29225465297","text":"from asyncio import coroutine\nfrom unittest.mock import Mock\n\n__all__ = [\"coro_mock\"]\n\n\ndef coro_mock():\n coro = Mock(name=\"CoroutineResult\")\n corofunc = Mock(name=\"CoroutineFunction\", side_effect=coroutine(coro))\n corofunc.coro = coro\n return corofunc\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"maps/tests/__init__ (24).py","file_name":"__init__ (24).py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27957321284","text":"# %%\nimport pandas as pd\nimport sqlalchemy\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn import model_selection\nfrom sklearn import ensemble\nfrom sklearn import tree\nfrom sklearn import linear_model\n\nfrom sklearn import pipeline\nfrom sklearn import metrics\n\nfrom feature_engine import imputation\nfrom feature_engine import encoding\n\nimport scikitplot as skplt\n\npd.set_option('display.max_columns', None)\n# %%\n# SAMPLE\n\ncon = sqlalchemy.create_engine(\"sqlite:///../../../data/gc.db\")\ndf = pd.read_sql_table(\"tb_abt_sub\", con)\n\n# Nosso back-test\ndf_oot = df[df[\"dtRef\"].isin(['2022-01-15','2022-01-16'])].copy()\ndf_train = df[~df[\"dtRef\"].isin(['2022-01-15','2022-01-16'])].copy()\n\nfeatures = df_train.columns.tolist()[2:-1]\ntarget = 'flagSub'\n\nX_train, X_test, y_train, y_test = model_selection.train_test_split(df_train[features],\n df_train[target],\n random_state=42,\n test_size=0.2)\n\n\n# %%\n# EXPLORE\n\ncat_features = X_train.dtypes[X_train.dtypes=='object'].index.tolist()\nnum_features = list(set(X_train.columns) - set(cat_features))\n\n# %%\n\nprint(\"Missing numerico\")\nis_na = X_train[num_features].isna().sum()\nprint(is_na[is_na>0])\n\nmissing_0 = [\"avgKDA\",]\n\nmissing_1 = [\"vlIdade\",\n \"winRateDust2\",\n \"winRateNuke\",\n \"winRateOverpass\",\n \"winRateVertigo\",\n \"winRateTrain\",\n \"winRateMirage\",\n \"winRateInferno\",\n \"winRateAncient\", ]\n\n\n# %%\n\nprint(\"Missing numerico\")\nis_na = X_train[cat_features].isna().sum()\nprint(is_na[is_na>0])\n\n# %%\n\n# MODIFY\n\n## imputação de dados\nimput_0 = imputation.ArbitraryNumberImputer(arbitrary_number=0, variables=missing_0)\nimput_1 = imputation.ArbitraryNumberImputer(arbitrary_number=-1, variables=missing_1)\n\n## one hot encoding\nonehot = encoding.OneHotEncoder(drop_last=True, variables=cat_features)\n\n# MODEL\n\nrf_clf = ensemble.RandomForestClassifier(n_estimators=200,\n min_samples_leaf=20, \n n_jobs=-1,\n random_state=42)\n\nada_clf = ensemble.AdaBoostClassifier(n_estimators=200,\n learning_rate=0.8, \n random_state=42)\n\ndt_clf = tree.DecisionTreeClassifier(max_depth=15,\n min_samples_leaf=50,\n random_state=42)\n\nrl_clf = linear_model.LogisticRegressionCV(cv=4, n_jobs=-1)\n\n## Definir um pipeline\n\nparams = {\"n_estimators\":[50,100,200,250],\n \"min_samples_leaf\": [5,10,20,50,100] }\n\ngrid_search = model_selection.GridSearchCV(rf_clf,\n params,\n n_jobs=1,\n cv=4,\n scoring='roc_auc',\n verbose=3,\n refit=True)\n\npipe_rf = pipeline.Pipeline(steps = [(\"Imput 0\", imput_0),\n (\"Imput -1\", imput_1),\n (\"One Hot\", onehot),\n (\"Modelo\", grid_search)])\n\n\n# %%\ndef train_test_report( model, X_train, y_train, X_test, y_test, key_metric, is_prob=True):\n model.fit(X_train, y_train)\n pred = model.predict(X_test)\n prob = model.predict_proba(X_test)\n metric_result = key_metric(y_test, prob[:,1]) if is_prob else key_metric(y_test, pred)\n return metric_result\n\n# %%\n\npipe_rf.fit(X_train, y_train)\n\n# %%\n\n\n## Assess\ny_train_pred = pipe_rf.predict(X_train)\ny_train_prob = pipe_rf.predict_proba(X_train)\n\nacc_train = round(100*metrics.accuracy_score(y_train, y_train_pred),2)\nroc_train = metrics.roc_auc_score(y_train, y_train_prob[:,1] )\nprint(\"acc_train:\", acc_train)\nprint(\"roc_train:\", roc_train)\n\n# %%\n\nprint(\"Baseline: \", round((1-y_train.mean())*100,2))\nprint(\"Acurácia:\", acc_train)\n\n# %%\n\ny_test_pred = pipe_rf.predict(X_test)\ny_test_prob = pipe_rf.predict_proba(X_test)\n\nacc_test = round(100*metrics.accuracy_score(y_test, y_test_pred),2)\nroc_test = metrics.roc_auc_score(y_test, y_test_prob[:,1] )\n\nprint(\"Baseline: \", round((1-y_test.mean())*100,2))\nprint(\"acc_train:\", acc_test)\nprint(\"roc_train:\", roc_test)\n\n# %%\n\nskplt.metrics.plot_roc(y_test, y_test_prob)\nplt.show()\n\n# %%\n\nskplt.metrics.plot_ks_statistic(y_test, y_test_prob)\nplt.show()\n\n# %%\n\nskplt.metrics.plot_precision_recall(y_test, y_test_prob)\nplt.show()\n\n# %%\n\nskplt.metrics.plot_lift_curve(y_test, y_test_prob)\nplt.show()\n# %%\n\nskplt.metrics.plot_cumulative_gain(y_test, y_test_prob)\nplt.show()\n\n\n# %%\n\nX_oot, y_oot = df_oot[features], df_oot[target]\n\ny_prob_oot = pipe_rf.predict_proba(X_oot)\n\nroc_oot = metrics.roc_auc_score(y_oot, y_prob_oot[:,1] )\nprint(\"roc_train:\", roc_oot)\n\n# %%\nskplt.metrics.plot_lift_curve(y_oot, y_prob_oot)\nplt.show()\n\n# %%\nskplt.metrics.plot_cumulative_gain(y_oot, y_prob_oot)\nplt.show()\n\n\n# %%\n\ndf_oot['prob'] = y_prob_oot[:,1]\n\n# %%\n\nconv_model = (df_oot.sort_values(by=['prob'], ascending=False)\n .head(1000)\n .mean()[\"prob\"])\n\nconv_sem = (df_oot.sort_values(by=['prob'], ascending=False)\n .mean()[\"prob\"])\n\ntotal_model = (df_oot.sort_values(by=['prob'], ascending=False)\n .head(1000)\n .sum()[\"prob\"])\n\ntotal_sem = (df_oot.sort_values(by=['prob'], ascending=False)\n .sum()[\"prob\"])\n\n\nprint(f\"Total convertidos modelo {total_model} ({round(100*conv_model,2)}%)\")\nprint(f\"Total convertidos SEM modelo {total_sem} ({round(100*conv_sem,2)}%)\")","repo_name":"TeoMeWhy/ranked-ml","sub_path":"model_sub/train/ml/modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"3"}
+{"seq_id":"39611969481","text":"import pandas as pd\nimport kits.getUrls as getUrls \nimport asyncio\nimport kits.asyncRequests as asyncRequests \nimport os\n\n\n\n\ndef main():\n global CURRENT_NUM\n # 逐个代码进行\n if MODE == 1:\n for stock_code,row in SELECT_DF.iterrows():\n print('')\n print('')\n print(row)\n print(\"==================================\")\n print(f\"【 {stock_code} 】 {CURRENT_NUM}/{len(SELECT_DF)}\")\n CURRENT_NUM += 1\n names_urls = getUrls.get_name_url(stock_code,START_DATE,END_DATE)\n asyncRequests.async_downloads(names_urls,to_dir=os.path.join(PAR_DIR,stock_code))\n print(f\"【 {stock_code} 】 Done!\")\n \n\n # START_CODE:END_CODE 使用协程进行链接获取\n elif MODE == 3:\n names_urls = []\n to_dirs = []\n print(f\"【 [{START_CODE},{END_CODE}) 】\")\n stock_code_set = [i[0] for i in SELECT_DF.iterrows()]\n names_urls = getUrls.async_get_names_urls(stock_code_set,START_DATE,END_DATE)\n asyncRequests.async_downloads(names_urls,to_dir=PAR_DIR)\n print(f\"【 [{START_CODE},{END_CODE}) 】 All Done!\")\n CURRENT_NUM = len(SELECT_DF)\n\n\n # START_CODE:END_CODE 同时进行\n elif MODE == 2:\n names_urls = []\n to_dirs = []\n print(f\"【 [{START_CODE},{END_CODE}) 】\")\n for stock_code,row in SELECT_DF.iterrows():\n print('')\n print('')\n print(row)\n print(\"==================================\")\n print(f\"【 {stock_code} 】 {CURRENT_NUM}/{len(SELECT_DF)}\")\n CURRENT_NUM += 1\n print(row)\n current_names_urls = getUrls.get_name_url(stock_code,START_DATE,END_DATE)\n names_urls += current_names_urls\n to_dirs += [ os.path.join(PAR_DIR,stock_code) ]*len(current_names_urls)\n \n asyncio.run(asyncRequests.async_downloads(names_urls,to_dir=to_dirs))\n print(f\"【 [{START_CODE},{END_CODE}) 】 All Done!\")\n\n\n\ndef my_input():\n res = input(\"\"\"=====要输入代码请输入:【 '000065' 】,要输入第几行请输入(从0开始):【 36 】=====\n\"\"\")\n if res == \"\" or res == \"None\" or res == \"none\":\n print(\"输入None\")\n return None\n elif res[0] in [\"'\",\"\\\"\",\"“\",\"”\"]:\n print(\"已输入字符串\")\n res = res[1:-1]\n else:\n print(\"已输入数字\")\n res = int(res)\n return res\n\n\ndef transform_to_index(name,dataframe):\n if type(name)==str:\n index = name\n elif type(name)==int:\n index = dataframe.iloc[name].name\n return index\n\n\ndef pre_presented():\n global START_CODE,NUMS,END_CODE,SELECT_DF,START_input,END_input,MODE,START_DATE,END_DATE,PAR_DIR\n \n\n code_df = pd.read_csv('./code_orgId.csv',dtype=str,)\n code = code_df.set_index('code')\n print(code.head(5))\n\n # 起始代码和终止代码,None表示不进行限制,'222222'表示从222222开始\n print(\"\\n:输入起始代码/行号\")\n # START_CODE = my_input() #None\n START_input = my_input() #None\n # 转化成index\n START_CODE = transform_to_index(START_input,code)\n print(f\"对应的起始代码为:[{START_CODE}\")\n print(\"\\n:输入要遍历的行数(int),若要输入结束代码/行号,请直接回车\")\n NUMS = my_input()\n if not NUMS:\n print(\":输入结束代码/行号(将会在访问该代码前停止,下次请从该代码处开始)\")\n END_input = my_input()\n END_CODE = transform_to_index(END_input,code)\n SELECT_DF = code.loc[START_CODE:END_CODE]\n print(f\"对应的结束代码为:{END_CODE})\")\n print(f\"对应的行数为:{len(SELECT_DF)}\")\n else: \n END_input = None\n SELECT_DF = code.loc[START_CODE:].iloc[:NUMS]\n print(SELECT_DF)\n END_CODE = code.loc[START_CODE:].iloc[NUMS].name\n print(f\"对应的结束代码为:{END_CODE})\")\n print(f\"对应的行数为:{len(SELECT_DF)}\")\n\n print(\"\"\"\n:模式:\n1: START_CODE:END_CODE 单线程运作\n2: START_CODE:END_CODE 仅使用协程下载文件\n3: START_CODE:END_CODE 使用协程获取链接和下载文件【注:该方法会将所有文件下载到同一个文件夹中】\n\"\"\")\n MODE = int(input())\n\n while True:\n input_num = input(f\"\"\"\n当前其他配置为:\n1: START_DATE = {START_DATE} (开始于 {START_DATE}-01-01 后发布)\n2: END_DATE = {END_DATE} (截止至 {END_DATE}-12-31 前发布)\n3: PAR_DIR = {PAR_DIR}\n要修改请输入对应数字,否则直接回车跳过\"\"\")\n if not input_num:\n print(\"已跳过\")\n break\n if input_num == '1':\n START_DATE = input()\n elif input_num == '2':\n END_DATE = input()\n elif input_num == '3':\n PAR_DIR = input()\n \n\n try:\n os.mkdir(PAR_DIR)\n print(f\"已创建文件夹{PAR_DIR}\")\n except:\n pass\n\n\nif __name__==\"__main__\":\n START_DATE,END_DATE = ['2011','2023']\n PAR_DIR = './data/all_announcements'\n CURRENT_NUM = 1\n pre_presented()\n try:\n main()\n except Exception as e:\n print(e)\n finally:\n print(f'\\n本次输入为:【 start:{START_input}, nums:{NUMS}, end:{END_input} 】')\n print(f\"本次代码范围为:【 ['{START_CODE}','{END_CODE}'),共{len(SELECT_DF)}条 】\")\n print(f'当前为第【 {CURRENT_NUM} 】条')\n","repo_name":"Arcsincode/parse_code","sub_path":"async_main.py","file_name":"async_main.py","file_ext":"py","file_size_in_byte":5472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2697010713","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 13 10:45:26 2018\n@author: ddsch (Python 3.6)\nDavid Schmidt\n\nDescription:\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport time\nimport sympy\n\ndef magic(numList): # [1,2,3]\n s = map(str, numList) # ['1','2','3']\n s = ''.join(s) # '123'\n s = int(s) # 123\n return s\n\ndef rotate(num, n):\n l=[int(x) for x in str(num)]\n return magic(l[-n:] + l[:-n])\n\n\nt=list(sympy.sieve.primerange(1, 10**6))\nx=set(t)\n\ndef main():\n tot=0\n for ii in t:\n ll=len([int(x) for x in str(ii)])\n kk=[ii]\n for jj in range(1,ll):\n kk=kk+[rotate(ii,jj)]\n if all(i in x for i in kk):\n tot=tot+1\n return tot\n \nprint(main())","repo_name":"ddschmidt/Euler-Project","sub_path":"Problem35/E35.py","file_name":"E35.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26495690952","text":"# Las listas son ordenadas y dinámicas\nnumeros = [1, 2, 3, 4, 5]\ncadenas = [\"hola\", \"mundo\"]\n\nlista_vacia_1 = []\nlista_vacia_2 = list()\n\n# Operaciones\n\n# Concatenación\nx = [1, 2, 3] + [4, 5, 6]\n\n# Lectura\nhola = cadenas[0]\nmundo = cadenas[1]\nultimo = cadenas[-1]\npenultimo = cadenas[-2]\n\n# Escritura\ncadenas.append(\"cruel\")\ncadenas.insert(1, \"mi\")\n\n# Eliminar\neliminado = cadenas.pop() # Sin especificar índice (eliminando el último elemento)\neliminado = cadenas.pop(1) # Especificando un índice\ndel cadenas[1]\n\n# Convertir cadena de texto a lista\nlista = list(\"hola\")\n\n# Slices\nlista = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n# La primer parte es inclusiva y la segunda parte es exclusiva\nlista2 = lista[3:5]\nlista3 = lista[1:8:2] # Podemos definir un salto (step)\nlista4 = lista[8:1:-1] # Recorrido al revés\nlista4 = lista[:6] # Se obvia que se empieza desde el primer elemento\nlista5 = lista[2:] # Se obvia que se acaba en el último elemento\ncopia = lista[:] # Se obviaron el primero y el último\n\n# Búsqueda\n1 in [1, 2, 3, 4, 5]\n","repo_name":"ultr4nerd/dw-pt-21-07-python","sub_path":"sesion_02/listas.py","file_name":"listas.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38586716328","text":"n=int(input()) #nº de testes\r\nfor i in range(n):\r\n deTroca=naoPrecisamMudar=0\r\n nota = []\r\n m=int(input()) #nº de alunos para cada teste\r\n notas=list(map(float, input().split()))\r\n for h in range(len(notas)):\r\n nota.append(notas[h])\r\n for j in range(1, len(nota)):\r\n for k in range(len(nota)):\r\n if nota[j] > nota[k]:\r\n deTroca = nota[k]\r\n nota[k] = nota[j]\r\n nota[j] = deTroca\r\n naoPrecisamMudar = len(nota)\r\n for l in range(len(nota)):\r\n if nota[l] != notas[l]:\r\n naoPrecisamMudar-=1\r\n print(int(naoPrecisamMudar))","repo_name":"rafarikrdo/QueroPizza","sub_path":"1548 Fila do recreio.py","file_name":"1548 Fila do recreio.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"gl","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22471698437","text":"from . import interfaces\n\n\ndef convex_decomposition(mesh, **kwargs):\n \"\"\"\n Compute an approximate convex decomposition of a mesh.\n\n Parameters\n ----------\n mesh : trimesh.Trimesh\n Mesh to be decomposed into convex parts\n\n Returns\n -------\n mesh_args : list\n List of **kwargs for Trimeshes that are nearly\n convex and approximate the original.\n \"\"\"\n # decompositions require testVHACD\n if interfaces.vhacd.exists:\n return interfaces.vhacd.convex_decomposition(mesh, **kwargs)\n else:\n raise ValueError('convex compositions require testVHACD installed!')\n","repo_name":"mikedh/trimesh","sub_path":"trimesh/decomposition.py","file_name":"decomposition.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":2558,"dataset":"github-code","pt":"3"}
+{"seq_id":"33895536631","text":"#그룹 단어 체커\n\nn=4\nwords=[\"aba\",\"baa\",\"abcabc\",\"a\"]\n# n=int(input())\n# words=[]\n# for _ in range(n):\n# words.append(input())\n\ncnt=0\nfor word in words:\n temp=word[0]\n alphabet=[word[0]]\n for w in word[1:]:\n if temp!=w:\n if w in alphabet:\n break\n temp=w\n alphabet.append(w)\n else:\n cnt+=1\n\nprint(cnt)","repo_name":"Greek-and-Roman-God/Athena","sub_path":"codingtest/week05/group_word_checker.py","file_name":"group_word_checker.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70676758803","text":"import serial\r\nimport firebase_admin\r\nfrom firebase_admin import credentials\r\nfrom firebase_admin import firestore\r\n\r\nser = serial.Serial(\"COM6\", 115200)\r\n\r\ntry:\r\n pass\r\n # while True:\r\n # while True:\r\n # try:\r\n # line = (\r\n # ser.readline().decode().strip()\r\n # ) # read the line from the serial port and decode it\r\n # break\r\n # except UnicodeDecodeError:\r\n # continue\r\n # values = line.split(\r\n # \"\\t\"\r\n # ) # split the line into separate values using the tab character as a separator\r\n\r\n # if len(values) == 6: # check if the number of values is correct\r\n # try:\r\n # num1 = round(float(values[0]), 3)\r\n # num2 = round(float(values[1]), 3)\r\n # num3 = round(float(values[2]), 3)\r\n # num4 = round(float(values[3]), 3)\r\n # num5 = round(float(values[4]), 3)\r\n # num6 = round(float(values[5]), 3)\r\n\r\n # print(num1, num2, num3, num4, num5, num6)\r\n\r\n # except ValueError:\r\n # pass # ignore any lines that cannot be parsed as float values\r\nfinally:\r\n\r\n cred = credentials.Certificate(r\"C:\\Users\\Q-5311\\Desktop\\john\\credentials\\copper-oven-382608-ea1f4baca1f3.json\")\r\n app = firebase_admin.initialize_app(cred)\r\n db = firestore.client()\r\n doc_ref = db.collection(\"users\").document(\"xnSSNwkYrEduqQoEY0H0\")\r\n\r\n \r\n doc_ref.set({\r\n \"AirFlow\":[32,5,6,6],\r\n \"ECG\": [32,5],\r\n \"HR\": [32,5,6,6],\r\n \"Snore\": [32,5,6,6],\r\n \"SpO2\": [32,5,6,6],\r\n \"Therm\": [32,5,6,6],\r\n })\r\n\r\n users_ref = db.collection(\"users\")\r\n docs = users_ref.stream()\r\n for doc in docs:\r\n print(f\"{doc.id} => {doc.to_dict()}\")\r\n","repo_name":"aztecbinaynay/Firebase_Upload_RawData","sub_path":"sendRawData_CloudFirestore.py","file_name":"sendRawData_CloudFirestore.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"74789506002","text":"import folium\nimport pandas as pd\nfrom geopy.geocoders import Nominatim\nfrom datetime import datetime\n\nexcel_file_path = r'\\path\\to\\your\\file.xlsx'\n\ncolumns_to_read = ['Postcode', 'Date']\ndf = pd.read_excel(excel_file_path, sheet_name='Tracker', engine='openpyxl', usecols=columns_to_read)\n\ndef get_coordinates(postcode):\n geolocator = Nominatim(user_agent=\"postcode_mapper\")\n location = geolocator.geocode(postcode)\n return (location.latitude, location.longitude) if location else None\n\nmap_center = get_coordinates(\"UK\") \nuk_map = folium.Map(location=map_center, zoom_start=6)\n\nfor index, row in df.iterrows():\n postcode = row['Postcode']\n print(index, row)\n\n try:\n coordinates = get_coordinates(postcode)\n print(\"Coordinates: \", coordinates)\n print(f\"Processing row: {index}, Postcode: {postcode}, Coordinates: {coordinates}\")\n if coordinates:\n pin_date = row['Date']\n\n if pd.isnull(pin_date):\n pin_color = 'grey'\n else:\n if isinstance(pin_date, pd.Timestamp):\n pin_date = pin_date.date()\n\n pin_color = 'red' if pin_date > datetime.today().date() else 'green'\n\n print(f\"Adding marker for Postcode: {postcode}, Date: {pin_date}, Color: {pin_color}, Coordinates: {coordinates}\")\n\n folium.CircleMarker(location=coordinates, radius=8, color=pin_color, fill=True, fill_color=pin_color, fill_opacity=1.0, popup=postcode).add_to(uk_map)\n else:\n print(f\"No coordinates found for Postcode: {postcode}\")\n\n except Exception as e:\n print(f\"Error processing row {index}, Postcode: {postcode}: {e}\")\n\nuk_map.save(r\"map.html\") \nprint(\"Map saved as HTML.\")\n","repo_name":"DylanK8/Project_Manager_Gift","sub_path":"geo_track_progress.py","file_name":"geo_track_progress.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15908310866","text":"from config import *\n\nROOT_DIRECTORY = \".\"\nPARENT_DIRECTORY = \"..\"\nPROJECT_NAME_LOWER = PROJECT_NAME.lower()\n\nDATABASE_VOLUME = 'database_'+PROJECT_NAME_LOWER\nSTATIC_VOLUME = 'static_'+PROJECT_NAME_LOWER\nMEDIA_VOLUME = 'media_'+PROJECT_NAME_LOWER\nLOGS_VOLUME = 'logs_'+PROJECT_NAME_LOWER\nPROJECT_VOLUME = 'app_'+PROJECT_NAME_LOWER\n\nWEB_ROOT_VOLUME = \"web_root_\"+PROJECT_NAME_LOWER\nCERTBOT_ETC_VOLUME = \"certbot_etc_\"+PROJECT_NAME_LOWER\nCERTBOT_VAR_VOLUME = \"certbot_var_\"+PROJECT_NAME_LOWER\n\nPROJECT_RENAME = PROJECT_NAME.replace('_', '.')\nWEB_CONTAINER_NAME = 'web-'+PROJECT_RENAME\nNODE_CONTAINER_NAME = 'node-'+PROJECT_RENAME\nNGINX_CONTAINER_NAME = 'nginx-'+PROJECT_RENAME\n\n\nOTHERS_CONTAINER_NAME = [container+'-' +\n PROJECT_RENAME for container in CONTAINERS]\n\nDATABASE_EXTERNAL = not 'DB_IMAGE' in DATABASE_DATA\nif not DATABASE_EXTERNAL:\n DATABASE_CONTAINER_NAME = DATABASE_DATA['DB_IMAGE']+'-'+PROJECT_RENAME\n\n\nSTATIC_ROOT = '/tmp/static-data'\nMEDIA_ROOT = '/tmp/media-data'\nLOGS_ROOT = '/tmp/logs-data'\n\n\nRUNSERVER_SCRIPT_NAME = 'runserver.sh'\nSETTINGS_FILE_NAME = 'ddsettings'\n\nWEB_ROOT_PATH = '/var/www/html'\nSERVER_DNS_NAMES = ' '.join(SERVER_NAMES)\n\nNGINX_SNIPPET_HTTPS_NAME = 'nginx-snippet-https.conf'\n\nWEB_ROOT = \"/var/www/html\"\nCERTBOT_ETC = \"/etc/letsencrypt\"\nCERTBOT_VAR = \"/var/lib/letsencrypt\"\n\nNUMBER_WEB_INSTANCES = NUMBER_WEB_INSTANCES\n\nWEB_IS_BIGGER_THAN_ONE = (NUMBER_WEB_INSTANCES > 1)\n\nENABLE_HTTPS = (len(SERVER_NAMES) >= 1)\n","repo_name":"Ronnasayd/django-docker","sub_path":"modules/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"36631847673","text":"import pandas as pd\n\n\ndef df_correlations(df, features):\n \"\"\" Calculates pearson and spearman correlations of each tuple of given features\n \n Args:\n df (pandas.DataFrame)\n features (list): features to calculate their correlations\n \"\"\"\n rowList = []\n for i, feature_val in enumerate(features):\n for j in range(i + 1, len(features)):\n feat1 = feature_val\n feat2 = feature_val\n tmp_df = df[(df[feat1].notnull()) & (df[feat2].notnull())]\n p_r, p_p = pearsonr(tmp_df[feat1], tmp_df[feat2])\n s_r, s_p = spearmanr(tmp_df[feat1], tmp_df[feat2])\n rowList.append([feat1, feat2, p_r, p_p, s_r, s_p])\n\n return pd.DataFrame(\n rowList,\n columns=[\n \"column1\",\n \"column2\",\n \"pearson_r\",\n \"pearson_pvalue\",\n \"spearman_r\",\n \"spearman_pvalue\",\n ],\n )\n\n\ndef summary(df):\n \"\"\"Summarizes the given dataframe\n \n Args:\n df (pandas.DataFrame): dataframe to be summarized\n \"\"\"\n\n rowList = []\n for col in df.columns:\n rowList.append(\n [\n col,\n \"{:.0f}%\".format(df[col].notnull().sum() / len(df) * 100),\n df[col].nunique(),\n \"{:.0f}%\".format(df[col].nunique() / df[col].notnull().sum() * 100),\n df[col].dtypes,\n \"N/A\"\n if df[col].dtypes not in [\"float\", \"int\"]\n else \"{:.2f}\".format(df[col].mean()),\n \"N/A\"\n if df[col].dtypes not in [\"float\", \"int\"]\n else \"{:.2f}\".format(df[col].std()),\n ]\n )\n stats = pd.DataFrame(\n rowList,\n columns=[\n \"column\",\n \"filled\",\n \"n_unique\",\n \"uniques/filled\",\n \"dtype\",\n \"mean\",\n \"std\",\n ],\n )\n\n return stats\n\n\ndef rank_in_group(df, group_col, rank_col, rank_method=\"first\"):\n \"\"\"Ranks a column in each group which is grouped by another column\n \n Args:\n df (pandas.DataFrame): dataframe to rank-in-group its column\n group_col (str): column to be grouped by\n rank_col (str): column to be ranked for\n rank_method (str): rank method to be the \"method\" argument of pandas.rank() function\n \n Returns:\n pandas.DataFrame: dataframe after the rank-in-group operation\n \"\"\"\n\n df = df.copy()\n df_slice = df[[group_col, rank_col]].drop_duplicates()\n df_slice[\"ranked_{}\".format(rank_col)] = df_slice[rank_column].rank(\n method=rank_method\n )\n df = pd.merge(\n df,\n df_slice[[group_col, \"ranked_{}\".format(rank_col)]],\n how=\"left\",\n on=group_col,\n )\n return df\n","repo_name":"barisozmen/deepaugment","sub_path":"deepaugment/lib/pandas_utilities.py","file_name":"pandas_utilities.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","stars":241,"dataset":"github-code","pt":"3"}
+{"seq_id":"372963851","text":"\r\ncap1 = ['F','F','B','B','B','F','B','B','B','F','F','B','F'] # 13개 \r\n#cap2 = ['F','F','B','B','B','F','B','B','B','F','F','F','F']\r\n\r\ndef pleaseConform(caps):\r\n start = forward = backward = 0\r\n intervals = []\r\n for i in range(1, len(caps)): # 1~13\r\n if caps[start] != caps[i]:\r\n intervals.append((start, i-1, caps[start])) # 간격 튜플이 리스트안으로 들어감\r\n if caps[start] == 'F':\r\n forward+=1\r\n else :\r\n backward+=1\r\n start = i \r\n intervals.append((start, len(caps)-1, caps[start]))\r\n print(intervals)\r\n if caps[start] == 'F':\r\n forward+=1\r\n else :\r\n backward+=1\r\n if forward < backward:\r\n flip ='F'\r\n else :\r\n flip ='B'\r\n for t in intervals:\r\n if t[2] == flip : # intervals 리스트 안에 있는 3번째 요소 t[2] 가 B이면 출력하라 \r\n #print('People in position', t[0], 'through',t[1],'flip your caps!')\r\n if t[0] == t[1] :\r\n print('People in position',t[1],'flip your cap!')\r\n else :\r\n print('People in position', t[0], 'through',t[1],'flip your caps!')\r\n \r\npleaseConform(cap1)\r\n","repo_name":"Leejuneyeong/Algorithm","sub_path":"pleaseConform.py","file_name":"pleaseConform.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17746204953","text":"import os\nimport sys\n\nimport psutil\n\nlnk = \"MapleStory.lnk\"\nprogramName = \"MapleStory.exe\"\ntry:\n for proc in psutil.process_iter():\n if proc.name() == programName:\n prams = psutil.Process(proc.pid).cmdline()\n # 添加启动参数\n os.system(\"start {} {} {} {} {} {}\".format(lnk, prams[1], prams[2], prams[3], prams[4], prams[5]))\n sys.exit()\n\nexcept Exception as e:\n with open(\"error.log\", 'w') as f:\n f.write(str(e))\n sys.exit()\n","repo_name":"Aaunix/beanfun-login","sub_path":"MapleStory.py","file_name":"MapleStory.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25063298322","text":"bl_info = {\n \"name\" : \"Crowd Manager\",\n \"author\" : \"Christopher Hosken\",\n \"description\" : \"Node based visual scripting designed for creating large crowds in Blender.\",\n \"blender\" : (3, 2, 0),\n \"version\" : (1, 0, 0),\n \"location\" : \"CrowdManager Editor\",\n \"warning\" : \"This addon is highly unstable. Use at your own risk.\",\n \"category\" : \"Node\"\n}\n\nfrom . import auto_load\nfrom . import gl_view\nfrom .preferences import classes as preference_classes\nfrom .operators import operator_classes\nfrom .sockets import socket_classes\nfrom .nodes import node_classes\nimport nodeitems_utils\n\nclasses = []\nclasses += preference_classes\nclasses += operator_classes\nclasses += socket_classes\nclasses += node_classes\n\nauto_load.init()\n\ndef register():\n from bpy.utils import register_class\n from .nodes.node_tree import node_categories\n\n for cls in classes:\n register_class(cls)\n\n nodeitems_utils.register_node_categories('CROWDMANAGER_NODES', node_categories)\n gl_view.register()\n\ndef unregister():\n from bpy.utils import unregister_class\n\n for cls in reversed(classes):\n unregister_class(cls)\n \n nodeitems_utils.unregister_node_categories('CROWDMANAGER_NODES')\n gl_view.unregister()\n\nif __name__ == \"__main__\":\n try:\n register()\n except Exception as e:\n print(e)","repo_name":"Christopher-Hosken/crowd_manager","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"28264659164","text":"# AUTHOR: Sibyl System\r\n# DATE: 2018-01-02\r\n# DESC: exception response shall be intercepted here\r\n\r\nfrom scrapy import signals\r\nfrom pydispatch import dispatcher\r\nfrom crawlers.crawler_db_handle import CCrawlerDbHandle\r\nfrom crawlers.utils import *\r\n\r\nclass ExceptionResponse(object):\r\n \"\"\"This middleware enables working with sites that change the user-agent\"\"\"\r\n\r\n def __init__(self, debug=False):\r\n self.db = CCrawlerDbHandle()\r\n self.db.set_db_table('db_crawlers', 't_failed_task')\r\n dispatcher.connect(self.spider_closed, signals.spider_closed)\r\n\r\n def spider_closed(self):\r\n print(\"close ExceptionResponse\")\r\n self.db.destroy()\r\n\r\n def process_response(self, request, response, spider):\r\n status_code = response.status\r\n if response.status == 200:\r\n if request.meta.get(REQ_FAIL_MARK,False):\r\n self.inform_success(request, spider)\r\n return response\r\n\r\n record_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\r\n print(\"ERROR RESPONSE STATUS is: %s, url: %s, time: %s\" % (status_code, response.url, record_time))\r\n try:\r\n retry_time = self.inform_failure(request, spider) # 通报失败,将失败信息收入通用表\r\n if REQ_FAIL_PROCFUN in dir(spider): # 通报失败,执行定制的失败处理方法\r\n getattr(spider,REQ_FAIL_PROCFUN)(retry_time,request,response)\r\n \r\n except Exception as e:\r\n print(\"MIDDLEWARE PROCESS RESPONSE:%s\" % e)\r\n return response\r\n\r\n # 失败请求会写通用表\r\n def inform_failure(self, request, spider):\r\n # 初始化变量\r\n retry_time = 0\r\n \r\n # 参数检测\r\n if not spider.name:\r\n print('spider name not found for request %s'%(request.url))\r\n return retry_time\r\n \r\n # 更新或插入失败请求记录\r\n field_list = ['*']\r\n where = \"Fcrawler_name='%s' and Fcall_back='%s' and Furl='%s'\"\\\r\n %(spider.name, request.meta['parse'],request.url)\r\n datar = self.db.query(field_list, where)\r\n if datar:\r\n datar = datar[0]\r\n retry_time = datar['Fretry_times'] + 1\r\n datau = {\r\n 'Fretry_times':retry_time,\r\n 'Fstate':TASK_STATE['failure'],\r\n 'Fmeta':json.dumps(request.meta),\r\n 'Fmodify_time':time_now(),\r\n }\r\n self.db.update(datau, where)\r\n else:\r\n retry_time = 0\r\n datai = {\r\n 'Fcrawler_name':spider.name,\r\n 'Fcall_back':request.meta['parse'],\r\n 'Furl':request.url,\r\n 'Fstate':TASK_STATE['failure'],\r\n 'Fmeta':json.dumps(request.meta),\r\n 'Fmethod':request.method,\r\n 'Fencoding':request.encoding,\r\n 'Fretry_times':retry_time,\r\n 'Fcreate_time':time_now(),\r\n 'Fmodify_time':time_now(),\r\n }\r\n self.db.insert(datai)\r\n self.db.commit()\r\n return retry_time\r\n \r\n # 成功请求回写通用表\r\n def inform_success(self, request, spider):\r\n # 参数检测\r\n if not spider.name:\r\n print('spider name not found for request %s'%(request.url))\r\n return \r\n \r\n # 更新或插入失败请求记录\r\n field_list = ['*']\r\n where = \"Fcrawler_name='%s' and Fcall_back='%s' and Furl='%s'\"\\\r\n %(spider.name, request.meta['parse'],request.url)\r\n datar = self.db.query(field_list, where)\r\n if datar:\r\n datar = datar[0]\r\n datau = {\r\n 'Fretry_times':datar['Fretry_times'] + 1,\r\n 'Fstate':TASK_STATE['success'],\r\n 'Fmeta':json.dumps(request.meta),\r\n 'Fmodify_time':time_now(),\r\n }\r\n self.db.update(datau, where)\r\n self.db.commit()","repo_name":"yunjianblackfyre/Job-Data-Mining","sub_path":"job_data_mining/crawlers/middlewares/downloader/exception_response.py","file_name":"exception_response.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"}
+{"seq_id":"26080949443","text":"from datetime import datetime\nimport json\nfrom time import sleep\nfrom typing import Optional\n\n\ndef log(msg, when=datetime.now()):\n print(f'{when}: {msg}')\n\nlog('Hi there!')\nsleep(1)\nlog('Hello again!') # timestamps are identical\n\n\ndef log2(msg, when=None):\n '''\n Log message with timestamp\n Args:\n msg (str): message to log\n when (datetime): message time (defaults to present)\n '''\n if when is None:\n when = datetime.now()\n print(f'{when}: {msg}')\n\n\nlog2('Hi there!')\nsleep(1)\nlog2('Hello again!') \n\n\ndef decode(data, default={}):\n try:\n return json.loads(data)\n except ValueError:\n return default\n\nfoo = decode('bad data')\nfoo['stuff'] = 5\nbar = decode('also bad')\nbar['meep'] = 1\nprint('Foo:', foo) # {'stuff': 5, 'meep': 1}\nprint('Bar:', bar) # {'stuff': 5, 'meep': 1}\nassert foo is bar # yup\n\n\ndef decode2(data, default=None):\n '''\n Load JSON from string\n Args:\n data (str): stingified JSON\n default: (json obj): value to return if decoding fails; default to {}\n '''\n try:\n return json.loads(data)\n except ValueError:\n if default is None:\n default = {}\n return default\n\n\nfoo = decode2('bad data')\nfoo['stuff'] = 5\nbar = decode2('also bad')\nbar['meep'] = 1\nprint('Foo:', foo) # {'stuff': 5}\nprint('Bar:', bar) # {'meep': 1}\nassert foo is not bar # ok\n\n\ndef log_typed(msg: str, when: Optional[datetime]=None) -> None:\n '''\n Log a message with a timestamp\n Args:\n msg (str): message to log\n when (datetime): message time (defaults to present)\n '''\n if when is None:\n when = datetime.now()\n print(f'{when}: {msg}')\n\n\nlog_typed('alas, it is over')\n \n","repo_name":"damiansp/completePython","sub_path":"effective/03_functions/24_dynamic_default_args.py","file_name":"24_dynamic_default_args.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38062898174","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 14 10:37:47 2018\n\n@author: Administrator\n\"\"\"\n#%%\nimport os\nimport datetime as dt\n\ntoday = dt.datetime.now().strftime('%Y%m%d')\n\nimport pandas as pd\nimport numpy as np\n\nimport xlrd\n\nfrom impala.dbapi import connect\nfrom impala.util import as_pandas\n\nfrom sqlalchemy import create_engine\nfrom pandas.io import sql\n\n#\npyfile_folder = r'D:\\XH\\Python_Project\\Proj_2\\files'\ndata_folder = r'D:\\XH\\Python_Project\\Proj_2\\data\\ETL_data'\nresult_folder = r'D:\\XH\\Python_Project\\Proj_2\\result\\ETL_result'\n\nos.chdir(pyfile_folder)\n\n#%% 建立连接\n# MySQL\nDB_CON_STR = 'mysql+pymysql://root:123456@localhost/odm_1_mysql?charset=utf8' \nengine = create_engine(DB_CON_STR, echo=False) \n\n# Hive\nconn = connect(host=\"192.168.20.102\", port=10000, # database=\"system\", \n auth_mechanism=\"PLAIN\",\n user = 'admin', password = 'admin')\ncursor = conn.cursor()\n\n#%% 每张表中挑选的字段\nfile_path = data_folder + '\\\\数据流向 1 ODM.xlsx'\n\nexcel = xlrd.open_workbook(file_path)\nsheet_names = [sheet.name for sheet in excel.sheets()]\n\ntable_col_info_all = pd.DataFrame()\nfor sheet_name in sheet_names:\n if sheet_name != '统计':\n sheet_data = pd.read_excel(file_path, sheet_name, header = 1)\n table_col_info_all = pd.concat([table_col_info_all, sheet_data])\n\ntable_col_info_all = table_col_info_all.dropna(how = 'all', axis = 0)\nfor col in ['类别名','序号' , '表名']:table_col_info_all[col].fillna(method = 'ffill', inplace = True)\ntable_col_info_all['table_name'] = table_col_info_all['表名'].apply(lambda x: x.split('(')[0])\ntable_col_info_all['table_comment'] = table_col_info_all['表名'].apply(lambda x: x.replace(')','').split('(')[1])\n\ncol_list = ['类别名','序号', '表名','字段名', '字段解释','table_name', 'table_comment']\ntable_col_info_select = table_col_info_all[col_list][table_col_info_all['是否保留(1:是;0:否)'] == 1]\ntable_col_info_select = table_col_info_select.sort_values('序号')\n\n#%%\ndatabase_name = 'data_hub_new'\ncursor.execute(\"use \"+ database_name) \n \n#% 全量\nfolder_name = 'odm_1' \ncount = 1\nnum = 0\n\nsave_filename = os.path.join(result_folder + '\\\\' + folder_name, 'ODM_1_all_' + today + '.txt')\nfile = open(save_filename,\"w\")\nfile.write('USE odm_1;' + \"\\n\" *2)\n\ntable_name_history = []\ntable_list = [list(x) for x in table_col_info_select[['序号','table_name']].drop_duplicates().values]\n#%\nfor index, table_name in table_list:\n print(index, ' --- ', table_name)\n field_name_comment = table_col_info_select[table_col_info_select['table_name'] == table_name][['字段名','字段解释']].values\n field_name_comment = sorted([list(x) for x in field_name_comment])\n table_comment = table_col_info_select[table_col_info_select['table_name'] == table_name]['table_comment'].unique().tolist()\n\n try: \n cursor.execute(\"select * from %s limit 5\"%table_name)\n except :\n table_name = table_name + '_new'\n cursor.execute(\"select * from %s limit 5\"%table_name) \n \n odm_table_name = 'odm_' + table_name.replace('_new', '')\n num += 1\n file.write('-- ---- %s %s;' %(str(num), table_comment[0]) + \"\\n\") \n file.write('drop table if exists %s;' %odm_table_name + \"\\n\")\n file.write('create table `%s` ' %odm_table_name + \"\\n\") \n file.write('AS' + \"\\n\")\n file.write('select ' + \"\\n\")\n# file.write(\"select %s\" %', '.join(col_list) + \"\\n\") \n for index, [name, commet] in enumerate(field_name_comment):\n if index == (len(field_name_comment) - 1):\n file.write('\\t' * count + '%s ' %name + \"\\n\")\n else :\n file.write('\\t' * count + '%s, ' %name + \"\\n\")\n\n file.write(\"from data_hub_new.%s ;\" %table_name + \"\\n\" * 2)\n \n for name,comment in field_name_comment:\n file.write(\"alter table %s CHANGE COLUMN %s %s STRING comment '%s';\" %(odm_table_name,name,name,comment) + \"\\n\")\n file.write(\"alter table %s SET TBLPROPERTIES ('comment' = '%s');\" %(odm_table_name,table_comment[0]) + \"\\n\" * 3)\n \n table_name_history.append([table_comment[0], table_name, odm_table_name]) \nfile.close()\n \nfile_name = os.path.join(result_folder + '\\\\' + folder_name, '源数据和ODM中表名对照_' + today + '.xlsx')\npd.DataFrame(table_name_history, columns = ['表名解释', 'data_hub_new','odm_1'], \n index = range(1, len(table_name_history)+1)).to_excel(file_name)\n\n#%% 增量\n\n\n#%% 全量 ODM to MySQL\ndef run_hive_query(sql_command): \n cursor.execute(sql_command) \n return cursor.fetchall() \n\ndatabase_name = 'odm_1'\ncursor.execute(\"use \"+ database_name) \n\ntable_list = [name[0] for name in run_hive_query(\"show tables\")] \n\nfor table_name in table_list:\n cursor.execute(\"select * from %s\"%table_name)\n tmp_data = as_pandas(cursor)\n sql.to_sql(tmp_data, table_name, \n engine, schema='odm_1_mysql', if_exists='replace') \n\n#%%\nimport numpy as np\nrandn = np.random.randn\nfrom pandas import *\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\n\nidx = np.arange(1,11)\ndf = pd.DataFrame(company_get['company_main_type_name'].value_counts())\n# DataFrame(randn(10, 5), index=idx, columns=['A', 'B', 'C', 'D', 'E'])\nvals = np.around(df.values,2)\nnormal = colors.Normalize(vals.min()-1, vals.max()+1)\n\nfig = plt.figure(figsize=(15,8))\n#ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[])\n#fig.set_alpha = 0.1\n\nthe_table=plt.table(cellText=vals, rowLabels=df.index, colLabels=df.columns, \n colWidths = [0.03]*vals.shape[1], loc='center', \n cellColours=plt.cm.GnBu(normal(vals)))\nplt.subplots_adjust(left=0.2, bottom=0.2)\nplt.show()\n\n#%%\n\ndata = [[ 66386, 174296, 75131, 577908, 32015],\n [ 58230, 381139, 78045, 99308, 160454],\n [ 89135, 80552, 152558, 497981, 603535],\n [ 78415, 81858, 150656, 193263, 69638],\n [139361, 331509, 343164, 781380, 52269]]\n\ncolumns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')\ndata = pd.DataFrame(data, columns = columns)\nprint(data.values)\ndata.head()\n\n#%%\ndata = pd.DataFrame(company_get['company_main_type_name'].value_counts())\n\nvals = np.round(data.values,2)\nnormal = colors.Normalize(vals.min()-1, vals.max()+1)\n\nfig = plt.figure()\nax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[])\nax.spines['top'].set_visible(False) #去掉上边框\nax.spines['bottom'].set_visible(False) #去掉下边框\nax.spines['left'].set_visible(False) #去掉左边框\nax.spines['right'].set_visible(False) #去掉右边框\n\nthe_table=plt.table(cellText=vals, cellLoc='center', \n cellColours=plt.cm.GnBu(normal(vals)), \n rowLabels=data.index, rowColours=None, rowLoc='right', \n colLabels=data.columns,colColours=None, colLoc='center', \n colWidths = None, \n loc='center', bbox=[0, 0, np.floor(data.shape[1]/5 + 1), \n np.floor(data.shape[0]/5)] ) \n # [left, bottom, width, height]\\\n#the_table.auto_set_font_size(False)\n#the_table.set_fontsize(fontsize)\n #%%\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#%%\n\n","repo_name":"xuhuanyunxiao/Proj_2","sub_path":"company_data_mining/ODM_1_1.py","file_name":"ODM_1_1.py","file_ext":"py","file_size_in_byte":7228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1470454178","text":"import json\nimport requests\nfrom django.contrib import messages\nfrom django.core.files.storage import FileSystemStorage\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import (HttpResponse, HttpResponseRedirect,\n get_object_or_404, redirect, render)\nfrom django.templatetags.static import static\nfrom django.urls import reverse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import UpdateView\n\nfrom .forms import *\nfrom .models import *\n\n\ndef dean_home(request):\n dean = get_object_or_404(Dean, admin=request.user)\n\n # Get the faculty associated with the dean\n faculty = dean.faculty\n\n faculty_department_list = Department.objects.filter(faculty=faculty)\n faculty_course_list = Course.objects.filter(department__faculty=faculty)\n faculty_staff_list = Staff.objects.filter(subject__course__department__faculty=faculty)\n faculty_student_list = Student.objects.filter(course__department__faculty=faculty)\n faculty_subjects_list = Subject.objects.filter(course__department__faculty=faculty)\n faculty_attendance_list = Attendance.objects.filter(student__course__department__faculty=faculty)\n\n total_faculty_students = faculty_student_list.count()\n total_faculty_subjects = faculty_subjects_list.count()\n total_faculty_department = faculty_department_list.count()\n total_faculty_staff = faculty_staff_list.count()\n total_faculty_attendance = faculty_attendance_list.count()\n total_faculty_course = faculty_course_list.count()\n\n context = {\n 'page_title': f'Dean Panel - {dean.admin.last_name} ({faculty.faculty_name})',\n 'total_faculty_students': total_faculty_students,\n 'total_faculty_subjects': total_faculty_subjects,\n 'total_faculty_department': total_faculty_department,\n 'total_faculty_staff': total_faculty_staff,\n 'total_faculty_attendance': total_faculty_attendance,\n 'total_faculty_course': total_faculty_course,\n 'faculty_department_list': faculty_department_list,\n 'faculty_course_list': faculty_course_list,\n 'faculty_staff_list': faculty_staff_list,\n 'faculty_student_list': faculty_student_list,\n 'faculty_subjects_list': faculty_subjects_list,\n 'faculty_attendance_list': faculty_attendance_list,\n }\n return render(request, 'dean_template/home_content.html', context)\n@ csrf_exempt\ndef dean_veiw_department(request):\n dean = get_object_or_404(Dean, admin=request.user)\n department = Department.objects.filter(faculty=dean.faculty)\n context = {\n 'department': department,\n 'page_title': 'View Departments'\n \n }\n return render(request, 'dean_template/dean_veiw_department.html', context)\n\ndef dean_veiw_course(request, department_id):\n dean = get_object_or_404(Dean, admin=request.user)\n courses = Course.objects.filter(department__faculty=dean.faculty, department__id=department_id)\n context ={\n 'courses': courses,\n 'page_title': 'View Courses',\n }\n return render(request, 'dean_template/dean_veiw_courses.html', context)\n\ndef dean_view_subject(request, course_id):\n dean = get_object_or_404(Dean, admin=request.user)\n subjects = Subject.objects.filter(course__department__faculty=dean.faculty, course__id=course_id)\n context = {\n 'subjects': subjects,\n 'page_title': 'View Subjects',\n }\n return render(request, 'dean_template/dean_view_subjects.html', context)\n\ndef dean_view_staff(request):\n dean = get_object_or_404(Dean, admin=request.user)\n staff_members = Staff.objects.filter(subject__course__department__faculty=dean.faculty)\n context = {\n 'staff_members': staff_members,\n 'page_title': 'View Staff',\n }\n return render(request, 'dean_template/dean_view_staff.html', context)\n\ndef dean_view_student(request):\n dean = get_object_or_404(Dean, admin=request.user)\n students = Student.objects.filter(course__department__faculty=dean.faculty)\n context = {\n 'students': students,\n 'page_title': 'View Students',\n }\n return render(request, 'dean_template/dean_view_students.html', context)\n\n\ndef dean_view_attendance(request):\n dean = get_object_or_404(Dean, admin=request.user)\n subjects = Subject.objects.all(student__course__department__faculty=dean.faculty)\n sessions = Session.objects.all(student__course__department__faculty=dean.faculty)\n context = {\n 'subjects': subjects,\n 'sessions': sessions,\n 'page_title': 'View Attendance'\n }\n return render(request, 'dean_template/dean_view_students.html', context)\n\ndef get_dean_attendance(request):\n subject_id = request.POST.get('subject')\n session_id = request.POST.get('session')\n attendance_date_id = request.POST.get('attendance_date_id')\n try:\n subject = get_object_or_404(Subject, id=subject_id)\n session = get_object_or_404(Session, id=session_id)\n attendance = get_object_or_404(\n Attendance, id=attendance_date_id, session=session)\n attendance_reports = AttendanceReport.objects.filter(\n attendance=attendance)\n json_data = []\n for report in attendance_reports:\n data = {\n \"status\": str(report.status),\n \"name\": str(report.student)\n }\n json_data.append(data)\n return JsonResponse(json.dumps(json_data), safe=False)\n except Exception as e:\n return None\n\ndef dean_view_profile(request):\n dean = get_object_or_404(Dean, admin=request.user)\n form = DeanEditForm(request.POST or None, request.FILES or None,instance=dean)\n context = {'form': form, 'page_title': 'View/Update Profile'}\n if request.method == 'POST':\n try:\n if form.is_valid():\n first_name = form.cleaned_data.get('first_name')\n last_name = form.cleaned_data.get('last_name')\n password = form.cleaned_data.get('password') or None\n address = form.cleaned_data.get('address')\n gender = form.cleaned_data.get('gender')\n passport = request.FILES.get('profile_pic') or None\n admin = dean.admin\n if password != None:\n admin.set_password(password)\n if passport != None:\n fs = FileSystemStorage()\n filename = fs.save(passport.name, passport)\n passport_url = fs.url(filename)\n admin.profile_pic = passport_url\n admin.first_name = first_name\n admin.last_name = last_name\n admin.address = address\n admin.gender = gender\n admin.save()\n dean.save()\n messages.success(request, \"Profile Updated!\")\n return redirect(reverse('dean_view_profile'))\n else:\n messages.error(request, \"Invalid Data Provided\")\n return render(request, \"staff_template/dean_view_profile.html\", context)\n except Exception as e:\n messages.error(\n request, \"Error Occured While Updating Profile \" + str(e))\n return render(request, \"dean_template/dean_view_profile.html\", context)\n\n return render(request, \"dean_template/dean_view_profile.html\", context)\n\n@csrf_exempt\ndef dean_fcmtoken(request):\n token = request.POST.get('token')\n try:\n dean_user = get_object_or_404(CustomUser, id=request.user.id)\n dean_user.fcm_token = token\n dean_user.save()\n return HttpResponse(\"True\")\n except Exception as e:\n return HttpResponse(\"False\")\n\ndef hodd_apply_leave(request):\n form = LeaveReportDeanForm(request.POST or None)\n dean = get_object_or_404(Hodd, admin_id=request.user.id)\n context = {\n 'form': form,\n 'leave_history': LeaveReportStaff.objects.filter(hodd=dean),\n 'page_title': 'Apply for Leave'\n }\n if request.method == 'POST':\n if form.is_valid():\n try:\n obj = form.save(commit=False)\n obj.dean = dean\n obj.save()\n messages.success(\n request, \"Application for leave has been submitted for review\")\n return redirect(reverse('dean_apply_leave'))\n except Exception:\n messages.error(request, \"Could not apply!\")\n else:\n messages.error(request, \"Form has errors!\")\n return render(request, 'dean_template/dean_appy_leave.html', context)\ndef dean_update_student_results(request):\n \n context ={\n \n }\n return render(request, 'dean_template/dean_update_results.html', context)\n\n@csrf_exempt\ndef check_email_availability(request):\n email = request.POST.get(\"email\")\n try:\n user = CustomUser.objects.filter(email=email).exists()\n if user:\n return HttpResponse(True)\n return HttpResponse(False)\n except Exception as e:\n return HttpResponse(False)\n@csrf_exempt\ndef hodd_feedback_message(request):\n dean = get_object_or_404(Dean, admin=request.user)\n if request.method != 'POST':\n feedbacks = FeedbackHodd.objects.all(faculty=dean.faculty)\n context = {\n 'feedbacks': feedbacks,\n 'page_title': 'Hodd Feedback Messages'\n }\n return render(request, 'dean_template/hodd_feedback.html', context)\n else:\n feedback_id = request.POST.get('id')\n try:\n feedback = get_object_or_404(FeedbackHodd, id=feedback_id)\n reply = request.POST.get('reply')\n feedback.reply = reply\n feedback.save()\n return HttpResponse(True)\n except Exception as e:\n return HttpResponse(False)\n \n\ndef dean_view_notification(request):\n dean = get_object_or_404(Dean, admin=request.user)\n # Fetch notifications related to the dean's faculty\n # You need to modify the query based on your notification model and relationships\n notifications = NotificationDean.objects.filter(dean=dean)\n context = {\n 'notifications': notifications,\n 'page_title': 'View Notifications',\n }\n return render(request, 'dean_template/dean_view_notification.html', context)\n\ndef dean_notify_hodd(request):\n hodd = CustomUser.objects.filter(user_type=3)\n context = {\n 'page_title': \"Send Notifications To Hodd\",\n 'allHodd': hodd\n }\n return render(request, 'dean_template/hodd_notification.html', context)\n\ndef send_hodd_notification(request):\n id = request.POST.get('id')\n message = request.POST.get('message')\n hodd = get_object_or_404(Hodd, admin_id= id)\n try:\n url = \"https://fcm.googleapis.com/fcm/send\"\n body = {\n 'notification': {\n 'title': \"Student Atendence System Using Face Recongniton\",\n 'body': message,\n 'click_action': reverse('hodd_view_notification'),\n 'icon': static('dist/img/AdminLTELogo.png')\n },\n 'to': hodd.admin.fcm_token\n }\n headers = {'Authorization':\n 'key=AAAA3Bm8j_M:APA91bElZlOLetwV696SoEtgzpJr2qbxBfxVBfDWFiopBWzfCfzQp2nRyC7_A2mlukZEHV4g1AmyC6P_HonvSkY2YyliKt5tT3fe_1lrKod2Daigzhb2xnYQMxUWjCAIQcUexAMPZePB',\n 'Content-Type': 'application/json'}\n data = requests.post(url, data=json.dumps(body), headers=headers)\n notification = NotificationHodd(hodd=hodd, message=message)\n notification.save()\n return HttpResponse(\"True\")\n except Exception as e:\n return HttpResponse(\"False\")\n \ndef send_staff_notification(request):\n id = request.POST.get('id')\n message = request.POST.get('message')\n staff = get_object_or_404(Staff, admin_id= id)\n try:\n url = \"https://fcm.googleapis.com/fcm/send\"\n body = {\n 'notification': {\n 'title': \"Student Management System\",\n 'body': message,\n 'click_action': reverse('staff_view_notification'),\n 'icon': static('dist/img/AdminLTELogo.png')\n },\n 'to': staff.admin.fcm_token\n }\n headers = {'Authorization':\n 'key=AAAA3Bm8j_M:APA91bElZlOLetwV696SoEtgzpJr2qbxBfxVBfDWFiopBWzfCfzQp2nRyC7_A2mlukZEHV4g1AmyC6P_HonvSkY2YyliKt5tT3fe_1lrKod2Daigzhb2xnYQMxUWjCAIQcUexAMPZePB',\n 'Content-Type': 'application/json'}\n data = requests.post(url, data=json.dumps(body), headers=headers)\n notification = NotificationStaff(staff=staff, message=message)\n notification.save()\n return HttpResponse(\"True\")\n except Exception as e:\n return HttpResponse(\"False\")\n\n@csrf_exempt\ndef staff_feedback_message(request):\n dean = get_object_or_404(Dean, admin=request.user)\n if request.method != 'POST':\n feedbacks = FeedbackStaff.objects.all(subject__course__department__faculty=dean.faculty)\n context = {\n 'feedbacks': feedbacks,\n 'page_title': 'Staff Feedback Messages'\n }\n return render(request, 'dean_template/staff_feedback.html', context)\n else:\n feedback_id = request.POST.get('id')\n try:\n feedback = get_object_or_404(FeedbackStaff, id=feedback_id)\n reply = request.POST.get('reply')\n feedback.reply = reply\n feedback.save()\n return HttpResponse(True)\n except Exception as e:\n return HttpResponse(False)\n \n\ndef dean_notify_staff(request):\n staff = CustomUser.objects.filter(user_type=4)\n context = {\n 'page_title': \"Send Notifications To Staff\",\n 'allStaff': staff\n }\n return render(request, 'dean_template/staff_notification.html', context)\n@csrf_exempt\ndef view_staff_leave(request):\n dean = get_object_or_404(Dean, admin=request.user)\n if request.method != 'POST':\n allLeave = LeaveReportStaff.objects.filter(subject__course__department__faculty=dean.faculty)\n context = {\n 'allLeave': allLeave,\n 'page_title': 'Leave Applications From Staff'\n }\n return render(request, 'dean_template/staff_leave_view.html', context)\n else:\n id = request.POST.get('id')\n status = request.POST.get('status')\n if (status == '1'):\n status = 1\n else:\n status = -1\n try:\n leave = get_object_or_404(LeaveReportStaff, id=id)\n leave.status = status\n leave.save()\n return HttpResponse(True)\n except Exception as e:\n return False\n\n@csrf_exempt\ndef student_feedback_message(request):\n dean = get_object_or_404(Dean, admin=request.user)\n if request.method != 'POST':\n feedbacks = FeedbackStudent.objects.all(course__department__faculty=dean.faculty)\n context = {\n 'feedbacks': feedbacks,\n 'page_title': 'Student Feedback Messages'\n }\n return render(request, 'dean_template/student_feedback.html', context)\n else:\n feedback_id = request.POST.get('id')\n try:\n feedback = get_object_or_404(FeedbackStudent, id=feedback_id)\n reply = request.POST.get('reply')\n feedback.reply = reply\n feedback.save()\n return HttpResponse(True)\n except Exception as e:\n return HttpResponse(False)\n\n \n\ndef dean_notify_student(request):\n student = CustomUser.objects.filter(user_type=5)\n context = {\n 'page_title': \"Send Notifications To Students\",\n 'students': student\n }\n return render(request, 'dean_templatestudent_notification/.html', context)\n\n@csrf_exempt\ndef send_student_notification(request):\n id = request.POST.get('id')\n message = request.POST.get('message')\n student = get_object_or_404(Student, admin_id= id)\n try:\n url = \"https://fcm.googleapis.com/fcm/send\"\n body = {\n 'notification': {\n 'title': \"Student Attendence System Using Face Recognition\",\n 'body': message,\n 'click_action': reverse('student_view_notification'),\n 'icon': static('dist/img/AdminLTELogo.png')\n },\n 'to': student.admin.fcm_token\n }\n headers = {'Authorization':\n 'key=AAAA3Bm8j_M:APA91bElZlOLetwV696SoEtgzpJr2qbxBfxVBfDWFiopBWzfCfzQp2nRyC7_A2mlukZEHV4g1AmyC6P_HonvSkY2YyliKt5tT3fe_1lrKod2Daigzhb2xnYQMxUWjCAIQcUexAMPZePB',\n 'Content-Type': 'application/json'}\n data = requests.post(url, data=json.dumps(body), headers=headers)\n notification = NotificationStudent(student=student, message=message)\n notification.save()\n return HttpResponse(\"True\")\n except Exception as e:\n return HttpResponse(\"False\")\n","repo_name":"osbart1999/sasufr","sub_path":"main_app/dean_views.py","file_name":"dean_views.py","file_ext":"py","file_size_in_byte":16887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"4989307823","text":"# -*- coding: utf-8 -*-\nimport json\nimport numpy as np\nfrom stasts import filter_outliers\n\n'''\nlê os arquivos originais com as séries temporais\n'''\n# def read_file_original(filename):\n# \tsamples_breakpoints = open(filename,'r').read().split('\\n')[:-1]\n# \ttotal_series = len(samples_breakpoints)\n# \tdois = []\n# X = []\n# \tY = []\n# \tfor i in range(0,total_series,3):\n# \t\tif samples_breakpoints[i+1] == '':\n# \t\t\txs = []\n# \t\t\tys = []\n# \t\telse:\n# \t\t\txs = [float(n) for n in samples_breakpoints[i+1].split(',')]\n# \t\t\tys = [float(n) for n in samples_breakpoints[i+2].split(',')]\n\n# dois.append(samples_breakpoints[i])\n# \t\tX.append(np.asarray(xs))\n# \t\tY.append(np.asarray(ys))\n\n# \treturn dois,np.asarray(X),np.asarray(Y)\n\n'''\nlê as séries de slopes/intervalos geradas artificialmente a partir de modelo\nretorna: os idxs das séries originais, slopes e intervalos\n'''\n\n\ndef read_artificial_breakpoints(filename):\n samples_breakpoints = open(filename, 'r').read().split('\\n')[:-1]\n total_series = len(samples_breakpoints)\n slopes = []\n breakpoints = []\n # preds = []\n idxs = []\n for i in range(0, total_series, 3):\n idx = int(samples_breakpoints[i]) - 1\n\n slopes_i = [float(n) for n in samples_breakpoints[i + 1].split(' ')]\n breakpoints_i = [float(n) for n in samples_breakpoints[i + 2].split(' ')]\n # preds_i = [float(n) for n in samples_breakpoints[i+3].split(' ')]\n idxs.append(idx)\n\n slopes.append(np.asarray(slopes_i))\n breakpoints.append(np.asarray(breakpoints_i))\n\n return np.asarray(idxs), np.asarray(slopes), np.asarray(breakpoints)\n\n\n'''\nlê os arquivos gerados pelo pacote segmented R\nprecisa de N para pegar apenas as séries com N intervalos\nretorna: os idxs das séries originais, slopes, breakpoints e as predições\n'''\ndef read_original_breakpoints(filename, N):\n samples_breakpoints = open(filename, 'r').read().split('\\n')[:-1]\n total_series = len(samples_breakpoints)\n slopes = []\n breakpoints = []\n idxs = []\n preds = []\n for i in range(0, total_series, 4):\n idx = samples_breakpoints[i]\n\n slopes_i = [float(n) for n in samples_breakpoints[i + 1].split(' ')]\n breakpoints_i = [float(n) for n in samples_breakpoints[i + 2].split(' ')]\n y_pred_i = [float(n) for n in samples_breakpoints[i + 3].split(' ')]\n # breakpoints_i.append(1.0) ???????\n\n if N == len(slopes_i) or N == None:\n idxs.append(idx)\n slopes.append(np.asarray(slopes_i))\n breakpoints.append(np.asarray(breakpoints_i))\n preds.append(np.asarray(y_pred_i))\n\n return np.asarray(idxs), np.asarray(slopes), np.asarray(breakpoints), np.asarray(preds)\n\n\ndef save(series_slopes, series_intervals, filename):\n f = open(filename, 'w')\n for s, i in zip(series_slopes, series_intervals):\n f.write('-1\\n')\n to_str = ''\n for v in s:\n to_str += str(v) + ' '\n f.write(to_str[:-1] + \"\\n\")\n to_str = ''\n for v in i:\n to_str += str(v) + ' '\n f.write(to_str[:-1] + \"\\n\")\n f.close()\n\n\ndef breakpoints2intervals(x):\n intervals = [x[0]]\n for i in range(len(x) - 1):\n intervals.append(x[i + 1] - x[i])\n intervals.append(1 - x[-1])\n return intervals\n\n\ndef preprocess_original_breakpoints(filename, n):\n idxs, slopes, breakpoints, _ = read_original_breakpoints(filename, n)\n intervals = np.asarray([np.asarray(b) for b in breakpoints])\n slopes2 = []\n for s in slopes:\n slopes2.append(np.arctan(s) * 57.2958)\n slopes2 = np.asarray(slopes2)\n\n return idxs, slopes2, intervals\n\n\ndef load_data(filename='segm/segmented_curves_filtered.txt'):\n # def load_data(filename='data/plos_one_2019_breakpoints_k4_original1_data_filtered.txt'):\n # dois,xs,ys = read_file_original(filename='data/plos_one_2019.txt')\n data_filename = 'data/papers_plos_data_time_series2_filtered.json'\n data = open(data_filename, 'r').read()\n data_json = json.loads(data)\n\n idxs, slopes, intervals, preds = read_original_breakpoints(filename, None)\n slopes2 = []\n for s in slopes:\n slopes2.append(np.arctan(s) * 57.2958)\n slopes = np.asarray(slopes2)\n idxs = idxs.tolist()\n\n data = []\n for i, s, b, p in zip(idxs, slopes, intervals, preds):\n xs = data_json[i]['time_series']['months']\n xs = np.asarray([float(x) for x in xs])\n ys = data_json[i]['time_series']['views']\n ys = np.asarray([float(y) for y in ys])\n data.append((i, s, b, xs, ys, p))\n data = np.asarray(data)\n\n return data\n\n\ndef select_original_breakpoints(N, filename):\n data = load_data(filename)\n data = filter_outliers(data)\n\n slopes = []\n intervals = []\n for i, s, b, xs, ys, p in data:\n if len(s) == N:\n slopes.append(s)\n intervals.append(np.asarray(breakpoints2intervals(b)))\n slopes = np.asarray(slopes)\n intervals = np.asarray(intervals)\n return slopes, intervals\n","repo_name":"carolmb/viewing-profiles-of-scientific-articles","sub_path":"read_file.py","file_name":"read_file.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34963219076","text":"#!/usr/bin/env python3\n\n## ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n## DEVELOPER: Cesar Abascal\n## PROFESSORS: Cesar Augusto Prior and Cesar Rodrigues (Yeah. Its almost an overflow!)\n## PROJECT: µPPG - Photoplethysmography waves acquisition\n## ARCHIVE: Aplication core containing the most importants methods and variables\n## DATE: 18/11/2018 - updated @ 15/03/2019\n## ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n## LIBRARIES ----------------------------------------------------------------------------\nimport spidev\nfrom time import sleep\nimport RPi.GPIO as GPIO\nfrom PPGAcquisition.AFEdefs import *\nfrom PPGAcquisition.mDisplay import oledDisplay as od\nimport time\nimport socket\nfrom threading import Thread\nimport sys\nimport json\nimport pickle\n\nfrom scipy.signal import butter, lfilter, lfilter_zi\nimport numpy as np\n\n## CLASSES and FUNCTIONS ----------------------------------------------------------------\nclass functions:\n\n ## VARIABLES ------------------------------------------------------------------------\n # SPI declaration\n spi = spidev.SpiDev()\n\n # Patient, sample and file variables to loop aquisition\n patientN = \"\"\n nSamples = 0\n dataFile = None\n testFile = None\n # Control variable to run acquisition and sychronize\n running = True\n syncValue = 0\n\n################# Input \n sample_data = ''\n################ Output\n signals_f = []\n processing_ok = False\n################# Tests variables \n t = 0\n t_ant = 0\n tempo_atual = 0\n\n################## Trash\n recv = False\n ping_full = False \n pong_full = False\n sizeb = 10\n pkt_cnt = 1 \n t_run = Thread()\n init_strm = False\n \n####### MEM_SYNC ################ \n SIZE_PKT = 20\n n = 2\n mem1 = [0] * n\n for i in range(n):\n mem1[i] = [0] * SIZE_PKT\n swap1 = False\n swp_mem1 = False\n out_mem1 = [] \n global_index = 0\n########## Flags socket controll\n ctl_byte = b'stop'\n flag_b = b'waiting'\n\n########## Server Socket TCP\n port = 3000\n client = socket.SocketType\n server = None\n \n \n t_wait = Thread()\n \n ## FUNCTIONS -----------------------------------------------------------------------\n def showInitInfos():\n od.uPPGscreen()\n print(\"\\n| uPPG ACQUIRING |\\n\")\n #end-def\n\n def showAcqInfos():\n od.acquiringScreen() # Show acquiring screen\n print(\"\\nSample acquiring started...\\nTo stop, press CTRL-C\\n\")\n #end-def\n\n def mainLoop(): \n print(\"main loop...\") \n GPIO.output(stePIN, GPIO.LOW) # Enable SPI conversation\n print(\"Running\")\n functions.t_wait = Thread(target = functions.app_waiting())\n functions.t_wait.daemon = True\n functions.t_wait.start()\n \n while(functions.running):\n if(GPIO.input(syncbtnPIN)):\n sleep(0.1) # Like debounce!\n if(GPIO.input(syncbtnPIN)):\n functions.syncValue = 1\n GPIO.setup(outputonePIN, GPIO.HIGH)\n print(\"synced\")\n #end-if\n else:\n functions.syncValue = 0\n GPIO.setup(outputonePIN, GPIO.LOW)\n \n\n\n\n def app_waiting():\n while(True):\n functions.ctl_byte = functions.client.recv(1024)\n if functions.ctl_byte == b'start': \n functions.flag_b = b\"pronto\" \n functions.client.send(functions.flag_b)\n functions.stream_data() \n break\n else: \n print('aguardando comando')\n functions.flag_b = b\"waiting\"\n functions.client.send(functions.flag_b)\n\n \n####################################################################################################################### \n#######################################################################################################################\n def mem_sync(swp_ch,adr,pkt):\n if functions.swp_mem1 == True:\n ping = 0\n pong = 1\n else: \n ping = 1\n pong = 0\n if swp_ch == True:\n functions.out_mem1 = functions.mem1[pong]\n functions.mem1[pong] = [0]*functions.SIZE_PKT \n functions.mem1[ping][adr] = pkt \n\n def mem_ctr(len_a, len_b): \n if(len_a != 0 and len_b == 0) or (len_b != 0 and len_a == 0): \n #print ('swap1 time and mem1:' + str(functions.mem1))\n functions.swp_mem1 = not(functions.swp_mem1) # CH0 is Input, in the next time is output\n return True # condição de swap1\n else: \n return False\n\n def stream_data():\n print('servidor iniciando streaming...')\n while True: \n #functions.get_signals_f()\n if functions.ctl_byte == b'stop': \n print('breaking Loop t_run')\n functions.flag_b = b\"waiting\"\n functions.t_wait.run(target = functions.app_waiting()) \n break \n else:\n if len(functions.out_mem1) == functions.SIZE_PKT:\n #print('buffer de saída: ' + str(functions.signals_f))\n p = pickle.dumps(functions.out_mem1)\n functions.out_mem1 = []\n functions.processing_ok = False\n ################################\n functions.client.send(p)\n functions.ctl_byte = (functions.client.recv(1024)) \n ################################..............\n if functions.ctl_byte == b'stop': \n functions.flag_b = b\"waiting\"\n ################################ blocking calls \n functions.client.send(functions.flag_b)\n ################################..............\n functions.t_ant = functions.t\n functions.t = time.time()\n delta = functions.t - functions.t_ant\n #print('tempo para enviar quadro: ' + str(delta))\n else: pass \n#######################################################\n# ---------------------------------------------------------CHANGES AFTER V:0.5 \n#######################################################\n \n def get_signals_f():\n if len(functions.out_mem1) == functions.SIZE_PKT:\n lowcut = 0.4\n highcut = 8\n order = 3\n sps = 200 # Samples per second\n REDsignal, IRsignal, synced = [], [], []\n signalBase = 1.045\n print('processando novo quadro')\n #p = pickle.dumps(functions.out_mem1)\n for i in range(0,20):\n aux = str(functions.out_mem1[i]).split(',')\n #print(aux)\n REDsignal.append(signalBase - float(aux[0]))\n IRsignal.append(signalBase - float(aux[1]))\n functions.signals_f.append(str(signalBase - float(aux[0])) + \",\" + str(signalBase - float(aux[1])) + \",\" + str(1))\n #samples +=1\n REDf = functions.butter_bandpass_filter_zi(REDsignal, lowcut, highcut, sps, order)\n IRf = functions.butter_bandpass_filter_zi(IRsignal, lowcut, highcut, sps, order)\n functions.processing_ok = True\n else:\n pass\n pass\n \n\n####################################################################################################################### \n#######################################################################################################################\n def finish():\n functions.running = False\n functions.AFEfinish()\n functions.closeSPIConnection()\n functions.dataFile.close() # Close data file\n od.acquiredScreen(functions.patientN, sps, functions.nSamples) # Show acquired data screen on display\n #end-def\n\n def openSPIConnection():\n GPIO.cleanup()\n GPIO.setmode(GPIO.BCM)\n\n # IO Interface\n GPIO.setup(syncbtnPIN, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) # Set sync button pin as input.\n GPIO.setup(thirdbtnPIN, GPIO.IN) # Set third button pin as input.\n GPIO.setup(outputonePIN, GPIO.OUT, initial=GPIO.LOW) # Set output one pin as output and init with low.\n\n # Connection Interface\n #GPIO.setup(diagendPIN, GPIO.IN) # Set diagnostic pin as input.\n #GPIO.setup(pdalmPIN, GPIO.IN) # Set pd alarm pin as input.\n #GPIO.setup(ledalmPIN, GPIO.IN) # Set data led alarm pin as input.\n GPIO.setup(resetPIN, GPIO.OUT, initial=GPIO.HIGH) # Set resetPIN as output and init with high.\n GPIO.setup(pdnPIN, GPIO.OUT, initial=GPIO.HIGH) # Set pdnPin as output and init with high.\n GPIO.setup(stePIN, GPIO.OUT, initial=GPIO.HIGH) # Set stePin as output and init with high.\n GPIO.setup(adcrdyPIN, GPIO.IN) # Set data ISR pin as input.\n\n # SPI Definition\n functions.spi.open(0,0)\n functions.spi.max_speed_hz = 8000000 # 8MHz\n functions.spi.mode = 0b00 # CPOL = 0, CPHA = 0\n #end def\n\n def closeSPIConnection():\n functions.spi.close()\n GPIO.cleanup()\n #end def\n\n def setISR():\n GPIO.add_event_detect(adcrdyPIN, GPIO.RISING, callback=functions.adcrdyInterruption) # Enable data ISR.\n #end-def\n\n def adcrdyInterruption(state):\n \n\n RED, IR = functions.SPIReadLED2LED1Values() # RED=LED2 and IR=LED1\n functions.sample_data = str('%.16f' % (RED*digitalToVolt)) + \",\" + str('%.16f' % (IR*digitalToVolt)) + \",\" + str(functions.global_index) \n #print('ctl_b: ' + str(functions.ctl_byte) + '|flag_b: ' + str(functions.flag_b))\n if functions.ctl_byte == b'start':\n if functions.global_index < int(functions.SIZE_PKT):\n functions.mem_sync(functions.mem_ctr((functions.mem1[0][-1]), (functions.mem1[1][-1])), functions.global_index,functions.sample_data)\n functions.global_index = functions.global_index + 1\n else: functions.global_index = 0 \n else: 'aguardando cliente para preparar pacotes' \n ##############\n \n ##############\n\n '''\n # if functions.ctl_byte == b'start': \n # temp_string = str('%.16f' % (delta)) + \",\" + \"streaming\"\n # functions.dataFile.write(\"%s\\n\" % temp_string)\n print('hi! ' + str(functions.t))\n #else: \n # temp_string = str('%.16f' % (delta)) + \",\" + \"waiting\"\n # functions.dataFile.write(\"%s\\n\" % temp_string )\n\n if functions.swap1 == True and functions.ping_full == False:\n if len(functions.ping) >= 10: \n functions.ping_full = True \n functions.pong.append(functions.sample_data)\n else: \n functions.ping.append(functions.sample_data) \n elif functions.swap1 == False and functions.pong_full == False: \n if len(functions.pong) >= 10: \n functions.pong_full = True \n functions.ping.append(functions.sample_data) \n else: \n functions.pong.append(functions.sample_data) \n \n '''\n\n def SPIWriteReg(regAddress, regValue):\n functions.spi.xfer2([regAddress])\n\n maskLSB = 0xFF\n maskMidByte = 0xFF00\n maskMSB = 0xFF0000\n\n LSB = regValue & maskLSB\n midByte = (regValue & maskMidByte) >> 8\n MSB = (regValue & maskMSB) >> 16\n\n functions.spi.xfer2([MSB])\n functions.spi.xfer2([midByte])\n functions.spi.xfer2([LSB])\n #end def\n\n def SPIReadLED2LED1Values():\n #functions.spi.xfer2([LED2VAL]) # Just LED2\n functions.spi.xfer2([LED2ALED2VAL]) # LED2 - ALED2\n ret2 = functions.spi.xfer2([0x00] * 3)\n l2Value = (ret2[0] << 8) | ret2[1]\n l2Value = (l2Value << 8) | ret2[2]\n\n #functions.spi.xfer2([LED1VAL]) # Just LED1\n functions.spi.xfer2([LED1ALED1VAL]) # LED1 - ALED1\n ret1 = functions.spi.xfer2([0x00] * 3)\n l1Value = (ret1[0] << 8) | ret1[1]\n l1Value = (l1Value << 8) | ret1[2]\n\n return l2Value, l1Value\n #end def\n\n # This function will write some configurations in AFE4490 registers to initialize and enable ISR.\n def AFEinit():\n print(\"\\nInitializing AFE4490 CI\")\n\n GPIO.output(stePIN, GPIO.LOW) # ENABLE SPI CONVERSATION\n\n # To use on SPI Read functions.\n functions.SPIWriteReg(CONTROL0, 8) # Software reset applied. Resets all internal registers\n #to the default values and self-clears to '0'.\n # This will also DISABLE SPI READ (enable SPI write).\n\n # To configure timer control registers, see the AFE4490 datasheet page 36.\n\n # Set the Pulse Repetition Counter\n functions.SPIWriteReg(PRPCOUNT, 19999) # num = 4MHz/SPS -1 -> num = 4MHz/200SPS -1 -> num = 19999\n\n # LED 2 (RED LED) Registers ...\n functions.SPIWriteReg(LED2STC, 15080) # Start LED2 sample at PRPCOUNT = 15080\n functions.SPIWriteReg(LED2ENDC, 18998) # End LED2 sample at PRPCOUNT = 18998\n functions.SPIWriteReg(LED2LEDSTC, 15000) # Start LED2 at PRPCOUNT = 15000\n functions.SPIWriteReg(LED2LEDENDC, 18999) # End LED2 at PRPCOUNT = 18999\n functions.SPIWriteReg(ALED2STC, 80) # Start Amb LED2 sample at PRPCOUNT = 80\n functions.SPIWriteReg(ALED2ENDC, 3998) # End Amb LED2 sample at PRPCOUNT = 3998\n\n # LED 1 (IR LED) Registers ...\n functions.SPIWriteReg(LED1STC, 5080) # Start LED1 sample at PRPCOUNT = 5080\n functions.SPIWriteReg(LED1ENDC, 8998) # End LED1 sample at PRPCOUNT = 8998\n functions.SPIWriteReg(LED1LEDSTC, 5000) # Start LED1 at PRPCOUNT = 5000\n functions.SPIWriteReg(LED1LEDENDC, 8999) # End LED1 at PRPCOUNT = 8999\n functions.SPIWriteReg(ALED1STC, 10080) # Start Amb LED1 sample at PRPCOUNT = 10080\n functions.SPIWriteReg(ALED1ENDC, 13998) # End Amb LED1 sample at PRPCOUNT = 13998\n\n # ... LED 2 (RED LED) Registers\n functions.SPIWriteReg(LED2CONVST, 6) # Start LED2 conversion at PRPCOUNT = 6\n functions.SPIWriteReg(LED2CONVEND, 4999) # End LED2 conversion at PRPCOUNT = 4999\n functions.SPIWriteReg(ALED2CONVST, 5006) # Start Amb LED2 conversion at PRPCOUNT = 5006\n functions.SPIWriteReg(ALED2CONVEND, 9999) # End Amb LED2 conversion at PRPCOUNT = 9999\n\n # ... LED 1 (IR LED) Registers\n functions.SPIWriteReg(LED1CONVST, 10006) # Start LED1 conversion at PRPCOUNT = 10006\n functions.SPIWriteReg(LED1CONVEND, 14999) # End LED1 conversion at PRPCOUNT = 14999\n functions.SPIWriteReg(ALED1CONVST, 15006) # Start Amb LED1 conversion at PRPCOUNT = 15006\n functions.SPIWriteReg(ALED1CONVEND, 19999) # End Amb LED1 conversion at PRPCOUNT = 19999\n\n # To manipulate the ADCx Reset positions\n ## It will manipulate the pulses, in this case, we've 4 pulses, so we've 25% on duty cycle.\n ## We're using 5000 per pulse and 19999 at PRPCOUNT (200SPS at 4MHz), so we've 25% on duty cycle and 200SPS.\n functions.SPIWriteReg(ADCRSTSTCT0, 0) # Start pulse 1 at PRPCOUNT = 0\n functions.SPIWriteReg(ADCRSTENDCT0, 5) # End pulse 1 at PRPCOUNT = 5\n functions.SPIWriteReg(ADCRSTSTCT1, 5000) # Start pulse 2 at PRPCOUNT = 5000\n functions.SPIWriteReg(ADCRSTENDCT1, 5005) # End pulse 2 at PRPCOUNT = 5005\n functions.SPIWriteReg(ADCRSTSTCT2, 10000) # Start pulse 3 at PRPCOUNT = 10000\n functions.SPIWriteReg(ADCRSTENDCT2, 10005) # End pulse 3 at PRPCOUNT = 10005\n functions.SPIWriteReg(ADCRSTSTCT3, 15000) # Start pulse 4 at PRPCOUNT = 15000\n functions.SPIWriteReg(ADCRSTENDCT3, 15005) # End pulse 4 at PRPCOUNT = 15005\n\n # Other settings\n functions.SPIWriteReg(CONTROL2, 262144) # TX_REF=01b -> 1.0-V Tx reference voltage available on TX_REF pin.\n # RST_CLK_ON_PD_ALM=0b -> Normal mode. No reset clock signal is connected to the PD_ALM pin.\n # EN_ADC_BYP=0b -> Normal mode. The internal ADC is active.\n # TXBRGMOD=0b -> LED driver is configured as an H-bridge.\n # DIGOUT_TRISTATE=0b -> SPI active and in use.\n # XTALDIS=0b -> The crystal module is enable. The 8MHz crystal mus be connected to the XIN and XOUT pins.\n # EN_SLOW_DIAG=0b -> Fast diagnostics mode, 8ms.\n \n functions.SPIWriteReg(TIAGAIN, 16638) # ENSEPGAIN=0b -> The RF, CF values and stage 2 gain settings are the same for both the LED2 and LED1 signals.\n # ENSEPGAIN=1b -> The RF, CF values and stage 2 gain settings can be independently set for the LED2 and\n #LED1 signals. The values for LED1 are specified using the RF_LED1, CF_LED1,\n #STAGE2EN1, and STG2GAIN1 bits in the TIAGAIN register, whereas the values for LED2\n #are specified using the corresponding bits in the TIA_AMB_GAIN register.\n # STAGE2EN1=1b -> Stage 2 is enabled with the gain value specified by the STG2GAIN1[2:0] bits\n # STG2GAIN1=000b -> Gain = 1x\n # CF_LED1=11111b -> LED1 Cf=270pF\n # RF_LED1=110b -> LED1 Rf=1MR\n # Fc = 580Hz\n\n functions.SPIWriteReg(TIA_AMB_GAIN, 16638) # AMBDAC=0000b -> Cancellation current = 0uA\n # FLTRCNRSEL=0b -> 500Hz filter corner\n # STAGE2EN2=1b -> Stage 2 is enabled with the gain value specified by the STG2GAIN2[2:0] bits\n # STG2GAIN2=000b -> Gain = 1x\n # CF_LED2=11111b -> LED2 Cf=270pF\n # RF_LED2=110b -> LED2 Rf=1MR\n # Fc = 580Hz\n\n functions.SPIWriteReg(LEDCNTRL, 70681) # LED_RANGE=01b -> Imax=100mA and Vhr=1.6V OBS.: IMPIRICAL GOOD VALUES FOR SPO2EVM PROBE.\n # LED1(IR)=00010100b=20d -> LED1 current = (20*100)/256 ~= 7.81mA\n # LED2(RED)=00011001b=25d -> LED2 current = (25*100)/256 ~= 9.76mA\n \n \n functions.SPIWriteReg(ALARM, 0) # ALARM reg need to be set before CONTROL1 reg.\n # ALMPINCLKEN=0b -> Disables the monitoring of internal clocks.\n #The PD_ALM and LED_ALM pins function as diagnostic fault alarm output pins (default after reset).\n\n functions.SPIWriteReg(CONTROL1, 263) # CLKALMPIN=011b -> PD_ALM=Sample LED2 pulse and LED_ALM=Sample LED1 pulse.\n # TIMEREN=1b -> Internal clock enable (timer module is enable)\n # NUMAV=00000111d -> To avarage 8 ADC samples.\n \n functions.SPIWriteReg(CONTROL0,1) # ENABLE SPI READ (disable SPI write)\n\n GPIO.output(stePIN, GPIO.HIGH) # DISABLE SPI CONVERSATION.\n\n print(\"... done\")\n\n #init server socket tcp and wait a client\n functions.server = socket.socket()\n port = 3001\n functions.server.bind(('', port))\n functions.server.listen(1)\n functions.client,addr = functions.server.accept()\n print(\"got a connection from %s\" % str(addr))\n\n\n #end-def\n\n # This function will write default values into AFE4490 registers to finish.\n def AFEfinish():\n print(\"\\nFinishing AFE4490 CI\")\n GPIO.output(stePIN, GPIO.LOW) # Enable SPI conversation\n\n functions.SPIWriteReg(CONTROL0,0) # Disable SPI read (Enable SPI Write)\n functions.SPIWriteReg(CONTROL0, 8) # Software reset applied. Resets all internal registers to the default values.\n\n GPIO.output(stePIN, GPIO.HIGH) # Disable SPI conversation\n functions.client.close()\n print(\"... done\\n\")\n\n #end-def\n\n#end-class\n","repo_name":"Tarsisnbs/estagio_gmicro","sub_path":"uPPG/PPGAcquisition/AFEcore.py","file_name":"AFEcore.py","file_ext":"py","file_size_in_byte":20761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6767411186","text":"import datetime, time\nimport pandas as pd\n\ntext = \"600690.SH\"\ntmp = text.split(\".\")\nprint(tmp[1]+tmp[0])\n\ndelta_year = 5\n\ntoday = datetime.datetime.today().date()\n\nprint(today.strftime('%Y%m%d'))\n\nstart_date = datetime.date(today.year - delta_year, today.month, today.day)\nstart_date_formatted = start_date.strftime('%Y%m%d')\n\nday_delta = datetime.timedelta(days=-7)\n\ntoday = datetime.datetime.today().date()\n\nstart_date = today + day_delta\nstart_date = start_date.strftime('%Y%m%d')\n\ndate = '20190101'\ndate = datetime.datetime.strptime(str(date), '%Y%m%d')\nprint(date)\n\ndate = '20190101'\ndate = pd.to_datetime(str(date), format='%Y%m%d')\nprint(date)\n\n# 转为字符串\nprice = 12\nprice = str(12)\n# 转为int\nprice = int(price)\n\n\n# 转为字符串\nprice = 12\nprice = str(12)\n\n# 转为int\nprice = int(price)\n\n# 分割\ntext = \"600690.SH\"\ntmp = text.split(\".\")\nprint(tmp[1]+tmp[0])\n\n# 大小写\ntext = text.lower()\nprint( text )\ntext = text.upper()\nprint( text)\n\nfrom pandas.tseries.offsets import *\ntoday = '20190101'\ntoday = pd.Timestamp(today)\nthis_quarter = (today - QuarterEnd(n=0))\nprint(this_quarter.strftime(\"%Y%m%d\"))\nlast_quarter = (today - QuarterEnd(n=1))\nprint(last_quarter.strftime(\"%Y%m%d\"))","repo_name":"zman2013/stock_quantization","sub_path":"venv/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"33725178858","text":"\"\"\"Test the conv-fwt-3d code.\"\"\"\n# Written by moritz ( @ wolter.tech ) in 2022\nimport numpy as np\nimport pytest\nimport pywt\nimport torch\n\nfrom src.ptwt.conv_transform_3 import wavedec3, waverec3\n\n\n@pytest.mark.slow\n@pytest.mark.parametrize(\n \"shape\",\n [\n (64, 64, 64),\n (31, 64, 64),\n (64, 31, 64),\n (64, 64, 31),\n (31, 31, 31),\n (32, 32, 32),\n ],\n)\n@pytest.mark.parametrize(\"wavelet\", [\"haar\", \"db2\", \"db4\"])\n@pytest.mark.parametrize(\"level\", [1, 2, None])\n@pytest.mark.parametrize(\"mode\", [\"zero\", \"constant\", \"periodic\"])\ndef test_wavedec3(shape: list, wavelet: str, level: int, mode: str):\n \"\"\"Test the conv2d-code.\"\"\"\n data = np.random.randn(*shape)\n pywc = pywt.wavedecn(data, wavelet, level=level, mode=mode)\n ptwc = wavedec3(\n torch.from_numpy(data).unsqueeze(0), wavelet, level=level, mode=mode\n )\n\n for pywc_res, ptwc_res in zip(pywc, ptwc):\n if type(pywc_res) is np.ndarray:\n assert np.allclose(pywc_res, ptwc_res.squeeze(0).numpy())\n else:\n assert type(pywc_res) is dict\n for key in pywc_res.keys():\n assert np.allclose(ptwc_res[key].numpy(), pywc_res[key])\n\n\ndef test_incorrect_dims():\n \"\"\"Test expected errors for an invalid padding name.\"\"\"\n data = np.random.randn(64, 64)\n with pytest.raises(ValueError):\n _ = wavedec3(torch.from_numpy(data), \"haar\")\n\n\n@pytest.mark.parametrize(\n \"shape\",\n [\n (1, 64, 64, 64),\n (2, 64, 64, 64),\n (3, 31, 64, 64),\n (3, 64, 31, 64),\n (3, 64, 64, 31),\n (3, 31, 31, 31),\n (3, 32, 32, 32),\n ],\n)\n@pytest.mark.parametrize(\"wavelet\", [\"haar\", \"db2\", \"db4\"])\n@pytest.mark.parametrize(\"level\", [1, 2, None])\n@pytest.mark.parametrize(\"mode\", [\"zero\", \"constant\", \"periodic\"])\ndef test_waverec3(shape: list, wavelet: str, level: int, mode: str):\n \"\"\"Ensure the 3d analysis transform is invertible.\"\"\"\n data = np.random.randn(*shape)\n data = torch.from_numpy(data)\n ptwc = wavedec3(data, wavelet, level=level, mode=mode)\n rec = waverec3(ptwc, wavelet)\n assert np.allclose(\n rec.numpy()[..., : shape[1], : shape[2], : shape[3]], data.numpy()\n )\n","repo_name":"raja21068/PyTorch-Wavelet-Toolbox","sub_path":"tests/test_convolution_fwt_3.py","file_name":"test_convolution_fwt_3.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"6636580266","text":"content_file = open(\"fruits.txt\")\nfruits = content_file.read()\ncontent_file.close()\n\n# print(fruits)\n\n# FOR LOOP\n# first convert content into lists\n\nfruits_list = fruits.splitlines() # converts to list ['something', 'another', 'more']\n\nfor each_fruit in fruits_list:\n print(each_fruit + \" is a fruit\")\n\n# Keys:values in a dictionary {}\n\nmy_object = {\"Guava\":\"green\", \"Oranges\":5, \"Pomme\":\"is french for apple\"}\nfor gangsta_ting in my_object:\n print(gangsta_ting) # prints values\n\nfor gangsta_ting in my_object.keys():\n print(gangsta_ting) # prints values\n\nfor gangsta_ting in my_object.values():\n print(gangsta_ting) # prints values\n","repo_name":"adeBenjamin/python_tuts","sub_path":"ex-code/cat_fruits_to_cli.py","file_name":"cat_fruits_to_cli.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32124316818","text":"import datetime\n\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\nfrom django.forms.utils import flatatt\nfrom django.utils.html import format_html, format_html_join\n\nfrom wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel, PageChooserPanel, StreamFieldPanel\nfrom wagtail.images.edit_handlers import ImageChooserPanel\n\nfrom wagtail.core import blocks\nfrom wagtail.images.blocks import ImageChooserBlock\n\nfrom wagtail.core.fields import RichTextField, StreamField\n\nfrom wagtail.contrib.table_block.blocks import TableBlock\nfrom wagtailmedia.blocks import VideoChooserBlock\n\nfrom modelcluster.contrib.taggit import ClusterTaggableManager\n\nfrom colorful.fields import RGBColorField\n\nfrom .utils import get_image_model_path\n\n\nclass BlogAbstract(models.Model):\n description = models.CharField(\n verbose_name=_('Description'),\n max_length=255,\n blank=True,\n help_text=_(\"The blog description that will appear under the title.\")\n )\n header_image = models.ForeignKey(\n get_image_model_path(),\n verbose_name=_('Header image'),\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n main_color = RGBColorField(_('Blog Main Color'), default=\"#4D6AE0\")\n\n display_comments = models.BooleanField(default=False, verbose_name=_('Display comments'))\n display_categories = models.BooleanField(default=True, verbose_name=_('Display categories'))\n display_tags = models.BooleanField(default=True, verbose_name=_('Display tags'))\n display_popular_entries = models.BooleanField(default=True, verbose_name=_('Display popular entries'))\n display_last_entries = models.BooleanField(default=True, verbose_name=_('Display last entries'))\n display_archive = models.BooleanField(default=True, verbose_name=_('Display archive'))\n\n disqus_api_secret = models.TextField(blank=True)\n disqus_shortname = models.CharField(max_length=128, blank=True)\n\n num_entries_page = models.IntegerField(default=5, verbose_name=_('Entries per page'))\n num_last_entries = models.IntegerField(default=3, verbose_name=_('Last entries limit'))\n num_popular_entries = models.IntegerField(default=3, verbose_name=_('Popular entries limit'))\n num_tags_entry_header = models.IntegerField(default=5, verbose_name=_('Tags limit entry header'))\n\n short_feed_description = models.BooleanField(default=True, verbose_name=_('Use short description in feeds'))\n\n content_panels = [\n FieldPanel('description', classname=\"full\"),\n ImageChooserPanel('header_image'),\n FieldPanel('main_color')\n ]\n settings_panels = [\n MultiFieldPanel([\n FieldPanel('display_categories'),\n FieldPanel('display_tags'),\n FieldPanel('display_popular_entries'),\n FieldPanel('display_last_entries'),\n FieldPanel('display_archive'),\n ], heading=_(\"Widgets\")),\n MultiFieldPanel([\n FieldPanel('num_entries_page'),\n FieldPanel('num_last_entries'),\n FieldPanel('num_popular_entries'),\n FieldPanel('num_tags_entry_header'),\n ], heading=_(\"Parameters\")),\n MultiFieldPanel([\n FieldPanel('display_comments'),\n FieldPanel('disqus_api_secret'),\n FieldPanel('disqus_shortname'),\n ], heading=_(\"Comments\")),\n MultiFieldPanel([\n FieldPanel('short_feed_description'),\n ], heading=_(\"Feeds\")),\n ]\n\n class Meta:\n abstract = True\n\nclass AnimationBlock(VideoChooserBlock):\n\n def render_basic(self, value, context=None):\n if not value:\n return ''\n\n tmpl = '''\n \n '''\n\n return format_html(tmpl, format_html_join(\n '\\n', '',\n [[flatatt(s) for s in value.sources]]\n ))\n\nclass EntryAbstract(models.Model):\n body = StreamField([\n ('heading', blocks.CharBlock(form_classname='full title', template='puput/blocks/heading.html')),\n ('paragraph', blocks.RichTextBlock()),\n ('animation', AnimationBlock(icon='media')),\n ('table', TableBlock(template='puput/blocks/table.html')),\n ('image', blocks.StructBlock(\n [\n ('image', ImageChooserBlock()),\n ('caption', blocks.CharBlock(required=False)),\n ],\n template='puput/blocks/captioned_image.html')),\n ('embed', blocks.URLBlock(template='home/partials/embed.html')),\n ])\n tags = ClusterTaggableManager(through='puput.TagEntryPage', blank=True)\n date = models.DateTimeField(verbose_name=_(\"Post date\"), default=datetime.datetime.today)\n header_image = models.ForeignKey(\n get_image_model_path(),\n verbose_name=_('Header image'),\n null=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n categories = models.ManyToManyField('puput.Category', through='puput.CategoryEntryPage', blank=True)\n excerpt = RichTextField(\n verbose_name=_('excerpt'),\n help_text=_(\"Short excerpt from or summary of post.\")\n )\n num_comments = models.IntegerField(default=0, editable=False)\n\n content_panels = [\n MultiFieldPanel(\n [\n FieldPanel('title', classname=\"title\"),\n ImageChooserPanel('header_image'),\n StreamFieldPanel('body', classname=\"full\"),\n FieldPanel('excerpt', classname=\"full\"),\n ],\n heading=_(\"Content\")\n ),\n MultiFieldPanel(\n [\n FieldPanel('tags'),\n InlinePanel('entry_categories', label=_(\"Categories\")),\n InlinePanel(\n 'related_entrypage_from',\n label=_(\"Related Entries\"),\n panels=[PageChooserPanel('entrypage_to')]\n ),\n ],\n heading=_(\"Metadata\")),\n ]\n\n class Meta:\n abstract = True\n","repo_name":"UCBerkeleySETI/puput","sub_path":"puput/abstracts.py","file_name":"abstracts.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"23855200331","text":"import message_queue as mq\n# -*- coding: utf-8 -*-\n# print(\"Loading HaasoscopeLib.py\")\n\nfrom serial import Serial, SerialException\nfrom struct import unpack\nimport numpy as np\nimport time, json, os\nimport matplotlib\nfrom const import *\n\n\nmearm=False\nmewin=False\ntry:\n print((os.uname()))\n if os.uname()[4].startswith(\"arm\") or os.uname()[4].startswith(\"aarch\"):\n print(\"On a raspberry pi?\")\n mearm=True\nexcept AttributeError:\n mewin=True\n print(\"Not on Linux?\")\n\ndofast=False #do the fast way of redrawing, just the specific things that could have likely changed, only works well on Windows?\nif mewin:\n dofast=True\n matplotlib.use('Qt4Agg')\n#to print possible backends\n#import matplotlib.rcsetup as rcsetup\n#print rcsetup.interactive_bk\n# import matplotlib.pyplot as plt\n# print((\"matplotlib backend is\",plt.get_backend()))\n\n\nfrom scipy.signal import resample\nimport serial.tools.list_ports\nimport scipy.optimize\n\nclass PsSerial():\n\n def __init__(self):\n\n self.mq_adapter = mq.Adapter('main_queue')\n self.mq_publisher = mq.Publisher(self.mq_adapter)\n\n self.serialdelaytimerwait=100 #150 # 600 # delay (in 2 us steps) between each 32 bytes of serial output (set to 600 for some slow USB serial setups, but 0 normally)\n if mearm: self.serialdelaytimerwait=600\n self.brate = 1500000 #serial baud rate #1500000 #115200 #921600\n self.sertimeout = 3.0 #time to wait for serial response #3.0, HAAS_NUM_BYTES*8*10.0/brate, or None\n self.serport=\"\" # the name of the serial port on your computer, connected to Haasoscope, like /dev/ttyUSB0 or COM8, leave blank to detect automatically!\n\n\n\n #cleanup\n def cleanup(self):\n try:\n if self.serport!=\"\" and hasattr(self,'ser'):\n self.ser.close()\n except SerialException:\n print(\"failed to talk to board when cleaning up!\")\n print(\"bye bye!\")\n\n def pulseon(self):\n frame=[]\n s=\"pulse on\\r\"\n frame.extend(s.encode())\n self.ser.write(frame)\n\n def hvon(self):\n frame=[]\n s=\"hv on\\r\"\n frame.extend(s.encode())\n self.ser.write(frame)\n\n def hvoff(self):\n frame=[]\n s=\"hv off\\r\"\n frame.extend(s.encode())\n self.ser.write(frame)\n\n #For setting up serial and USB connections\n def setup_connections(self):\n # serialrate=adjustedbrate/11./(HAAS_NUM_BYTES*HAAS_NUM_BOARD+len(HAAS_MAX10ADCCHANS)*HAAS_NSAMP) #including start+2stop bits\n # print((\"rate theoretically\",round(serialrate,2),\"Hz over serial\"))\n print(\">>> PsSerial>>>\")\n\n ports = list(serial.tools.list_ports.comports()); ports.sort(reverse=True)\n\n for port_no, description, address in ports: print((port_no,\":\",description,\":\",address))\n for port_no, description, address in ports:\n if self.serport==\"\":\n if '0483:5740' in address: self.serport = port_no\n if self.serport!=\"\":\n try:\n self.ser = Serial(self.serport,self.brate,timeout=self.sertimeout,stopbits=2)\n except SerialException:\n print((\"Could not open\",self.serport,\"!\")); return False\n print((\"connected serial to\",self.serport,\", timeout\",self.sertimeout,\"seconds\"))\n else: self.ser=\"\"\n if self.serport==\"\": print(\"No serial COM port opened!\"); return False\n return True\n","repo_name":"oshevchenko/emat_dashboard","sub_path":"PsSerialLib.py","file_name":"PsSerialLib.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"10561257994","text":"from menu.menu import Menu\nfrom menu.menuImages import menu_images\nfrom towers.supportTower import SupportTower\nimport pygame\nimport os\n\n\nclass DamageTower(SupportTower):\n def __init__(self, x, y):\n super().__init__(x, y)\n self.range = 100\n self.effect = [1, 2]\n self.tower_images = self._load_tower_images()\n\n # differences\n self.price = [5000]\n\n # define menu and buttons\n self.menu = Menu(self, self.x, self.y, menu_images.get_menu_bg(), self.price)\n self.menu.add_button(menu_images.get_upgrade_button(), \"upgrade\")\n\n def _load_tower_images(self):\n original_images = [pygame.image.load(os.path.join(\"game_assets\", \"support_towers\", \"damage_towers\", f\"{x}.png\"))\n for\n x in range(1, 3)]\n scale = (original_images[0].get_width() / original_images[0].get_height())\n return [pygame.transform.scale(img, (90, int(90 * scale))) for img in original_images]\n\n def support(self, towers):\n supported_towers = self.supported_towers(towers)\n for tower in supported_towers:\n tower.damage = tower.damage + self.effect[self.level - 1]\n","repo_name":"NikeSmitt/TowerDefense","sub_path":"towers/damageTower.py","file_name":"damageTower.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37624398421","text":"print(\"__name__: {}\".format(__name__))\nprint(\"__package__: {}\".format(__package__))\nprint(\"__file__: {}\".format(__file__))\n\nimport unittest, sys\nsys.path.insert(0, \"/Users/yutaro/code/stg\")\nfrom stg import STG\nimport stg.utils as utils\nfrom examples.dataset import create_twomoon_dataset\n\nfrom sklearn.model_selection import train_test_split\n\nimport torch\nimport unittest, sys\nimport numpy as np\nimport time\n\nclass Test(unittest.TestCase):\n def setUp(self):\n n_size = 1000 #Number of samples\n p_size = 20 #Number of features\n X_data, y_data=create_twomoon_dataset(n_size,p_size)\n print(X_data.shape)\n print(y_data.shape)\n np.random.seed(123)\n self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X_data, y_data, train_size=0.3)\n self.X_train, self.X_valid, self.y_train, self.y_valid = train_test_split(self.X_train, self.y_train, train_size=0.8)\n\n self.params = {'hidden_layers_node': [60, 20, 2], 'param_search': False, \n 'display_step': 1000, 'activation': 'tanh', 'lam': 0.02, \n 'sigma': 0.5, 'feature_selection': True, 'learning_rate': 0.01, \n 'output_node': 2}\n # Adjust params\n self.params['lam'] = 0.5\n self.params['learning_rate'] = 0.1\n self.params['input_node'] = self.X_train.shape[1]\n self.params['batch_size'] = self.X_train.shape[0]\n\n def tearDown(self):\n pass\n\n def test_torch(self):\n args_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if args_cuda else \"cpu\")\n #torch.backends.cudnn.benchmark = True\n feature_selection = True\n report_maps = {'l2_norm_1st_neuron': lambda x : torch.norm(x.mlp[0][0].weight[:, 0]).item(),\n 'l2_norm_2nd_neuron': lambda x : torch.norm(x.mlp[0][0].weight[:, 1]).item()}\n model = STG(task_type='classification',input_dim=self.X_train.shape[1], output_dim=2, hidden_dims=[60, 20], activation='tanh',\n optimizer='SGD', learning_rate=0.1, batch_size=self.X_train.shape[0], feature_selection=feature_selection, sigma=0.5, lam=0.5, random_state=1, device=device, report_maps=report_maps)\n now = time.time()\n model.fit(self.X_train, self.y_train, nr_epochs=100, valid_X=self.X_valid, valid_y=self.y_valid, print_interval=10)\n print(\"Passed time: {}\".format(time.time() - now))\n if feature_selection:\n print(model.get_gates(mode='prob'))\n\n\nif __name__=='__main__':\n unittest.main() \n","repo_name":"runopti/stg","sub_path":"python/tests/test-reg.py","file_name":"test-reg.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"3"}
+{"seq_id":"5850640443","text":"import logging\nfrom datetime import datetime\nfrom typing import Any, Self\n\nlogger = logging.getLogger(\"Timekeeping\")\n\n_TIME_FORMAT = \"%H:%M:%S\"\n\n\ndef timestr(time: datetime) -> str:\n return f\"{time.strftime(_TIME_FORMAT)}.{int(time.strftime('%f')) // 1000:03d}\"\n\n\nclass Checkpoint:\n def __init__(self: Self, name: str, timestamp: datetime, duration: datetime) -> None:\n self.name = name\n self.timestamp = timestamp\n self.duration = duration\n\n def __repr__(self: Self) -> str:\n return (\n f\"Checkpoint at [{timestr(self.timestamp)}] {self.name} \"\n + f\"(Duration: {timestr(self.duration)})\"\n )\n\n\nclass Blackboard:\n def __init__(self: Self) -> None:\n \"\"\"Initialize a new Blackboard object.\"\"\"\n self.start_time = datetime.now()\n self.last_timestamp = self.start_time\n self.checkpoints: list[Checkpoint] = []\n self.dict: dict[str, Any] = {}\n\n # Dictionary\n def get_dict(\n self: Self,\n key: str,\n default: Any = None, # noqa: ANN401\n ) -> Any | None: # noqa: ANN401\n return self.dict.get(key, default)\n\n def set_dict(self: Self, key: str, value: Any) -> None: # noqa: ANN401\n self.dict[key] = value\n\n # Time related functions\n def start(self: Self) -> None:\n self.start_time = datetime.now()\n self.last_timestamp = self.start_time\n logger.info(\"Starting timer\")\n\n def log_checkpoint(self: Self, name: str) -> None:\n now = datetime.now()\n duration = datetime.utcfromtimestamp((now - self.last_timestamp).total_seconds())\n timestamp = datetime.utcfromtimestamp((now - self.start_time).total_seconds())\n self.last_timestamp = now\n\n checkpoint = Checkpoint(name=name, timestamp=timestamp, duration=duration)\n self.checkpoints.append(checkpoint)\n logger.info(checkpoint)\n\n def stop(self: Self) -> None:\n logger.info(\"Sections:\")\n for checkpoint in self.checkpoints:\n logger.info(f\" {checkpoint}\")\n\n checkpoint = self.checkpoints[-1]\n logger.info(f\"Final time: {timestr(checkpoint.timestamp)}\")\n\n\n_blackboard = Blackboard()\n\n\ndef clear_blackboard() -> None:\n global _blackboard\n _blackboard = Blackboard()\n\n\ndef blackboard() -> Blackboard:\n global _blackboard # noqa: PLW0602\n return _blackboard\n","repo_name":"shenef/SoS-TAS","sub_path":"engine/blackboard.py","file_name":"blackboard.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"42318499529","text":"# With Secure Coding Challenge\n# Nilotpal Sarkar\n\n# This class is to store temporarily, the key and value. An object of this class is instantiated as soon as we\n# encounter an key(When the algorithm decides that the last set of charecters is predominantly a 'Key' The 'value'\n# property is updated as soon as the algorithm is able to decide the 'value'. At this step, after evaluation of the\n# 'value', the key and value of this entry object is flushed to a root dictionary referred as json_dict in code.\n\nclass Entry:\n def __init__(self, key: str):\n self.key = key\n self.value = None\n\n def setValue(self, value: str):\n self.value = value\n\n\ndef parse_and_convert_to_json(input: str) -> str:\n buffer = []\n key: str = ''\n value: str = ''\n value_quote_started: bool = False\n json_dict = {}\n\n # Iterate over the string and parse\n for i in range(len(input)):\n current_char = input[i]\n previous_char = input[i - 1]\n\n # If the current character is a ':' and next char a space,\n # then according to challenge documentation, this marks the end of 'key'.\n if current_char == ':' and input[i + 1] == ' ':\n key = key.join(buffer)\n\n # Create an entry for the dictionary when we encounter an key.\n # When we parse the value, we would set the value of this entry.\n # Once we get the value, we would flush this entry to dict(json_dict)\n entry: Entry = Entry(key)\n\n # Set the key and buffer to empty and get ready for the next iterations.\n key = ''\n buffer = []\n continue\n\n # if quotation for the value is started state(marked simply by value True),\n # Also the current character is a \"(quote)\n # And previous character was not escape character,\n # Then according to challenge documentation, this marks the end of value parsing.\n # At this stage, there are set of activities to be completed/flushed.\n #\n # - set the ongoing entry object's value to the value just parsed\n # - flush the entry value to json_dict object\n # - set the value, buffer, value_quote_started to defaults.\n if value_quote_started and current_char == '\\\"' and previous_char != \"\\\\\":\n value = value.join(buffer)\n entry.setValue(value)\n json_dict[entry.key] = entry.value\n value = ''\n buffer = []\n value_quote_started = False\n continue\n\n if current_char == '\"' and previous_char != \"\\\\\" and (input[i - 1] is None or previous_char == ' '):\n value_quote_started = True\n\n # We would continue if the following conditions are met.\n # In these conditions we wouldnt like to append the current charecter to the buffer.\n if (current_char == ':' and input[i + 1] == ' ') \\\n or (current_char == ' ' and previous_char == ':') \\\n or (current_char == '\\\"' and previous_char == ' ') \\\n or (current_char == ' ' and not value_quote_started):\n continue\n buffer.append(current_char)\n return json_dict\n\n\n# This function returns the next event based on the following algorithm. The next hex is ensured using 2-step process\n# Step - 1.\n# A difference of numbers in sequence is calculated. That is : hex sequence- 0x154, 0x150, 0x14A, 0x144 Diff\n# sequence- -4, -6, -6 Now, the next difference in the sequence could be either of 4, 6, 8 etc. This difference is\n# confirmed with the hint given and we move to the next step.\n\n# Step - 2.\n# The hint says - Hello, try XOR with 0x17F\n# So we, start XOR'ng each number in sequence with 0x17F\n# and we get the following sequence - 43, 47, 53, 59.\n# Difference of xor'ed sequence - 4, 6, 6\n\n# We see a similar sequence getting generated and so for the next step, we take this difference and match with step 1.\n# If the difference matches, we confirm the hex number and return.\n\n# We make this explanation clear in a separate diagram @See ChallengeExplanation.png\ndef get_next_event(prev_hex_number: int, current_hex_number: int, hint_hex: int):\n prev_dec_number = int(prev_hex_number, 16)\n current_dec_number = int(current_hex_number, 16)\n diff_of_decimals = current_dec_number - prev_dec_number\n possible_next_number = current_dec_number + diff_of_decimals\n\n prev_xor = int(prev_hex_number, 16) ^ int(hint_hex, 16)\n current_xor = int(current_hex_number, 16) ^ int(hint_hex, 16)\n\n diff_between_xors = current_xor - prev_xor\n possible_next_number_from_plain_difference = current_dec_number + diff_of_decimals\n\n # Final step that makes use of the hint\n possible_next_number_from_plain_difference_XOR_hint = possible_next_number_from_plain_difference ^ int(hint_hex, 16)\n if possible_next_number_from_plain_difference_XOR_hint - current_xor == diff_between_xors:\n # In this case we find the difference from 2 different calculations merging to the same difference. \n # Hense assuming the difference is correct and we proceed for the next item(5th) with\n # this difference.\n return hex(possible_next_number)\n","repo_name":"nilotpalsrkr/CodingChallenge","sub_path":"JsonConverter.py","file_name":"JsonConverter.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"16409423066","text":"# Day_30_01_Exam_4_1.py\nimport urllib.request\nimport json\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn import model_selection\n\n# 문제 4\n# sarcasm.json 파일을 읽어서 2만개로 학습하고 나머지에 대해 정확도를 예측하세요\n# 목표 : 80%\n\n# url = 'https://storage.googleapis.com/download.tensorflow.org/data/sarcasm.json'\n# urllib.request.urlretrieve(url, 'data/sarcasm.json')\n\n\ndef get_xy():\n f = open('data/sarcasm.json', 'r', encoding='utf-8')\n data = json.load(f)\n f.close()\n\n print(type(data))\n print(len(data)) # 26709\n\n x, y = [], []\n for item in data:\n # print(type(item), item.keys())\n # dict_keys(['article_link', 'headline', 'is_sarcastic'])\n\n x.append(item['headline'])\n y.append(item['is_sarcastic'])\n # print(type(y[-1]))\n\n return x, np.int32(y)\n\n\nx, y = get_xy()\n\nvocab_size = 2000\ntokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=vocab_size)\ntokenizer.fit_on_texts(x)\n\nx = tokenizer.texts_to_sequences(x)\n\nseq_length = 200\nx = tf.keras.preprocessing.sequence.pad_sequences(x, padding='post', maxlen=seq_length)\n\ndata = model_selection.train_test_split(x, y, train_size=20000)\nx_train, x_valid, y_train, y_valid = data\n\nmodel = tf.keras.Sequential()\nmodel.add(tf.keras.layers.Input([seq_length]))\nmodel.add(tf.keras.layers.Embedding(vocab_size, 100))\nmodel.add(tf.keras.layers.Conv1D(32, 5, activation='relu'))\nmodel.add(tf.keras.layers.MaxPool1D())\n# model.add(tf.keras.layers.Bidirectional(tf.keras.layers.GRU(32)))\nmodel.add(tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)))\n# model.add(tf.keras.layers.Bidirectional(tf.keras.layers.GRU(32, dropout=0.2, recurrent_dropout=0.2)))\nmodel.add(tf.keras.layers.Dense(1))\n\nmodel.summary()\n\nmodel.compile(optimizer=tf.keras.optimizers.RMSprop(0.0003),\n loss=tf.keras.losses.binary_crossentropy,\n metrics=['acc'])\nmodel.fit(x_train, y_train, epochs=5, verbose=2, batch_size=128,\n validation_data=(x_valid, y_valid))\n\n\n\n","repo_name":"yunhui21/CB_Ai_NLP","sub_path":"Lecture_example/Day_30_01_Exam_4_1.py","file_name":"Day_30_01_Exam_4_1.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"34250089317","text":"from recorder import *\nfrom time import perf_counter\n\nbpm_list = []\nprev_beat = perf_counter()\nlow_freq_avg_list = []\n\n\ndef plot_audio_and_detect_beats():\n if not input_recorder.has_new_audio: \n return\n\n # get x and y values from FFT\n xs, ys = input_recorder.fft()\n \n # calculate average for all frequency ranges\n y_avg = numpy.mean(ys)\n\n # calculate low frequency average\n low_freq = [ys[i] for i in range(len(xs)) if xs[i] < 1000]\n low_freq_avg = numpy.mean(low_freq)\n\n global low_freq_avg_list\n low_freq_avg_list.append(low_freq_avg)\n cumulative_avg = numpy.mean(low_freq_avg_list)\n \n bass = low_freq[:int(len(low_freq)/2)]\n bass_avg = numpy.mean(bass)\n\n # check if there is a beat\n # song is pretty uniform across all frequencies\n if (y_avg > 10 and (bass_avg > cumulative_avg * 1.5 or\n (low_freq_avg < y_avg * 1.2 and bass_avg > cumulative_avg))):\n global prev_beat\n curr_time = perf_counter()\n # print(curr_time - prev_beat)\n if curr_time - prev_beat > 60/180: # 180 BPM max\n # print(\"beat\")\n \n global bpm_list\n bpm = int(60 / (curr_time - prev_beat))\n if len(bpm_list) < 4:\n if bpm > 60:\n bpm_list.append(bpm)\n else:\n bpm_avg = int(numpy.mean(bpm_list))\n if abs(bpm_avg - bpm) < 35:\n bpm_list.append(bpm)\n # reset the timer\n prev_beat = curr_time\n\n # shorten the cumulative list to account for changes in dynamics\n if len(low_freq_avg_list) > 50:\n low_freq_avg_list = low_freq_avg_list[25:]\n # print(\"REFRESH!!\")\n\n # keep two 8-counts of BPMs so we can maybe catch tempo changes\n if len(bpm_list) > 24:\n bpm_list = bpm_list[8:]\n\n # reset song data if the song has stopped\n if y_avg < 10:\n bpm_list = []\n low_freq_avg_list = []\n #uiplot.btnD.setText(_fromUtf8(\"BPM\"))\n # print(\"new song\")\n\n\n\ninput_recorder = InputRecorder()\ninput_recorder.start()\n\nprint(\"hi\")\nwhile True:\n if len(bpm_list) > 0:\n print(bpm_list)\n plot_audio_and_detect_beats()\nprint(\"yo\")","repo_name":"frankhereford/led_board","sub_path":"radio/tests/listen_to_the_radio.py","file_name":"listen_to_the_radio.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35791704182","text":"n = int(input('Digite um número: '))\ncont = n\nprint(f'Calculando {n}! ', end='')\nfat = 1\nwhile cont > 0:\n print('{} '.format(cont, fat), end='')\n print('x ' if cont > 1 else ' = ', end='')\n fat *= cont\n cont -= 1\nprint(fat)\n","repo_name":"Ramon-Erik/Exercicios-Python","sub_path":"tudo/ex060.py","file_name":"ex060.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30191619143","text":"# name: 연결 요소의 개수\n# date: July 11, 2020\n# status: solved\n\n\nfrom sys import stdin\n\n# adjacency-list structure\n\n\nclass Vertex:\n def __init__(self, element):\n self.incidence_list = []\n self.element = element\n self.visited = False\n\n\nclass Edge:\n def __init__(self, origin, destination):\n self.origin = origin\n self.destination = destination\n self.visited = False\n\n\nclass Graph:\n def __init__(self, total_vertices):\n self.vertices_list = [Vertex(i) for i in range(total_vertices + 1)]\n self.edges_list = []\n\n def add_edges(self, edge_positions):\n for origin_position, destination_position in edge_positions:\n origin = self.vertices_list[origin_position]\n destination = self.vertices_list[destination_position]\n edge = Edge(\n origin, destination)\n self.edges_list.append(edge)\n origin.incidence_list.append(edge)\n destination.incidence_list.append(edge)\n\n def search(self):\n total_connected_components = 0\n for start_vertex in self.vertices_list:\n if start_vertex is self.vertices_list[0]:\n continue\n if not start_vertex.visited:\n self.DFS(start_vertex)\n total_connected_components += 1\n return total_connected_components\n\n def BFS(self, vertex):\n queue = []\n vertex.visited = True\n queue.append(vertex)\n while queue:\n current_vertex = queue.pop(0)\n for edge in current_vertex.incidence_list:\n if edge.visited:\n continue\n edge.visited = True\n opposite_vertex = self.find_opposite_vertex(\n current_vertex, edge)\n if not opposite_vertex.visited:\n opposite_vertex.visited = True\n queue.append(opposite_vertex)\n\n def DFS(self, vertex):\n stack = []\n vertex.visited = True\n stack.append(vertex)\n while stack:\n current_vertex = stack.pop(0)\n for edge in current_vertex.incidence_list:\n if edge.visited:\n continue\n edge.visited = True\n opposite_vertex = self.find_opposite_vertex(\n current_vertex, edge)\n if not opposite_vertex.visited:\n opposite_vertex.visited = True\n stack.append(opposite_vertex)\n\n def find_opposite_vertex(self, vertex, edge):\n return edge.origin if vertex is edge.destination else edge.destination\n\n def print_elements(self):\n for vertex in self.vertices_list:\n print('{}: '.format(vertex.element), end=\" \")\n for edge in vertex.incidence_list:\n print('({}, {})'.format(edge.origin.element,\n edge.destination.element), end=\" \")\n print()\n\n\ndef solution():\n total_vertices, total_edges = list(map(int, stdin.readline().split(' ')))\n edges_list = [list(map(int, stdin.readline().split(' ')))\n for i in range(total_edges)]\n graph = Graph(total_vertices)\n graph.add_edges(edges_list)\n answer = graph.search()\n print(answer)\n\n\nsolution()\n","repo_name":"algoORgoal/ICPC-Training","sub_path":"Baekjoon/num_11724_별찬.py","file_name":"num_11724_별찬.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"14975752502","text":"#!/usr/bin/env python\n\"\"\"\nCreate a KVM guest and install a Linux operating system in it.\nLinux installation may be manual or automated.\nIt must be run on a KVM host.\n\n@IMPROVEMENT: support automated installation of Debian and SUSE based\ndistributions\n\"\"\"\n\nimport argparse\nimport os\nimport platform\nimport re\nimport shlex\nimport shutil\nimport socket\nimport subprocess\nimport urllib2\n\nDEBUG = True\n# default number of CPUs\nDEFAULT_NUM_CPUS = 1\n# default RAM amount in GB\nDEFAULT_RAM = 2\n# guest's disk default size in GB\nDISK_DEFAULT_SIZE = 5\n# enable SSH daemon during Linux installation for debugging purposes\nENABLE_SSH_DURING_INSTALLATION = True\n# web server root directory\nWEB_SERVER_ROOT = \"/var/www/html\"\n\n\ndef run_cmd(cmd, shell=False):\n '''\n Run a command\n\n @param str cmd command\n @param bool shell use a Linux shell\n @return str output\n @raise Exception if return code is not 0\n '''\n\n args = shlex.split(cmd)\n\n try:\n sp = subprocess.Popen(args, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)\n except OSError:\n raise Exception(\"OS error running command %s\" % cmd)\n\n (output, err) = sp.communicate()\n rc = sp.returncode\n if rc != 0:\n raise Exception(\"Command return return code %s, error: %s\" % (rc, err))\n\n return output\n\ndef is_local_file(file_location):\n \"\"\"\n Check if file is in the local file system\n\n @param str file_location file URL/path\n @return bool if file is local\n \"\"\"\n\n return not re.match(\"[a-z]+://\", file_location)\n\ndef download_file(file_url):\n \"\"\"\n Download a file\n\n @param str file_url file URL\n @return str file content\n @raise Exception if unable to download the file\n \"\"\"\n\n if not file_url.startswith(\"http\") and not file_url.startswith(\"ftp\"):\n raise Exception(\"only HTTP and FTP are supported in file URL\")\n\n req = urllib2.urlopen(file_url)\n return req.read()\n\ndef create_kvm_guest(guest_name, num_virtual_cpus, virtual_ram, virtual_disk_size,\n os, os_iso_path=None, os_tree_location=None,\n autoinstall_file_location=None, kernel_args=None):\n \"\"\"\n Create a KVM guest\n\n @param str guest_name guest name\n @param int num_virtual_cpus number of virtual CPUs in guest\n @param int virtual_ram amount of virtual RAM in MB in guest\n @param int virtual_disk_size virtual disk size in GB in guest\n @param str os name and version of Linux OS to be installed in guest\n @param str os_iso_path ISO path of Linux OS to be installed in guest.\n This parameter and os_tree_location are mutually exclusive.\n @param str os_tree_location path/URL of Linux OS tree\n This parameter and os_iso_path are mutually exclusive.\n @param str autoinstall_file_location path/URL of automatic installation file\n (autoyast / kickstart / preseed). This parameter and os_tree_location\n must be used together\n @param str kernel_args extra kernel command line arguments\n @raise Exception if unable to create the KVM guest\n \"\"\"\n\n arch = platform.uname()[4]\n cmd = \"virt-install --name=%s --arch=%s --vcpus=%d --ram=%d --os-type=linux --os-variant=%s --hvm --autostart --connect=qemu:///system --disk path=/var/lib/libvirt/images/%s.img,size=%d --network bridge:br0 --graphics vnc --noautoconsole --virt-type=kvm\" % (guest_name, arch, num_virtual_cpus, virtual_ram, os, guest_name, virtual_disk_size)\n if os_iso_path and os_tree_location:\n raise Exception(\"Linux OS' ISO path and tree location are mutually exclusive\")\n if os_iso_path:\n cmd += \" --cdrom=%s\" % os_iso_path\n elif os_tree_location:\n cmd += \" --location=%s\" % os_tree_location\n else:\n raise Exception(\"Linux OS' ISO path or tree location must be provided\")\n if autoinstall_file_location:\n if not os_tree_location:\n raise Exception(\"Custom autoinstall may only be provided if a Linux OS tree location is provided\")\n ks_kernel_arg = \"ks=%s\" % autoinstall_file_location\n if kernel_args:\n kernel_args += \" %s\" % ks_kernel_arg\n else:\n kernel_args = ks_kernel_arg\n if ENABLE_SSH_DURING_INSTALLATION:\n kernel_args += \" sshd\"\n cmd += \" --extra-args=\\\"%s\\\"\" % kernel_args\n\n if DEBUG:\n print(\"virt-install command: %s\" % cmd)\n print(\"creating KVM guest\")\n run_cmd(cmd)\n\n\ndef parse_input():\n \"\"\"\n Parse and validate command line input\n\n @return dict validated input. Keys are input parameters for KVM guest creation,\n not necessarily equal to command line parameters\n @raise Exception if input validation fails\n \"\"\"\n\n # create command line argument parser\n parser = argparse.ArgumentParser(description='Create a KVM guest and install a Linux distribution in it. Installation may be manual or automated')\n parser.add_argument('-n', '--name', metavar='name', nargs=1, action=\"store\", help='Guest name')\n parser.add_argument('-c', '--cpus', metavar='num_cpus', nargs='?', action=\"store\", help='Number of virtual CPUs in guest')\n parser.add_argument('-m', '--ram', metavar='amount_ram', nargs='?', action=\"store\", help='Amount of virtual RAM in guest')\n parser.add_argument('-d', '--disk', metavar='disk_size', nargs='?', action=\"store\", help='Disk size')\n parser.add_argument('-o', '--distro', metavar='distro', nargs='?', action=\"store\", help='Linux distribution name and version. Use virt-install --os-variant list to list possible options')\n parser.add_argument('-i', '--distro-iso-path', metavar='distro_iso_path', nargs='?', action=\"store\", help='Linux distribution ISO path. Provide this parameter if manual installation is desired. --distro-iso-path and --distro-tree are mutually exclusive.')\n parser.add_argument('-t', '--distro-tree', metavar='distro_tree', nargs='?', action=\"store\", help='Linux distribution tree root directory URL. This parameter may be used in manual or automated installation. --distro-iso-path and --distro-tree are mutually exclusive. A distro tree URL with embedded credentials (and therefore a server which requires authentication) is not supported.')\n parser.add_argument('-a', '--autoinstall', metavar='autoinstall', nargs='?', action=\"store\", help=\"location of autoinstall file which will be used to automate Linux installation. Location may be a local file path (requires a web server enabled in KVM host) or a remote HTTP/FTP URL. Only supports Red Hat based distributions. Must be used together with --distro-tree\")\n parser.add_argument('-e', '--network', metavar='network', nargs='?', action=\"store\", help=\"guest's static network setup to be done in an automated installation. Only supports Red Hat based distributions. Must be used together with --distro-tree and --autoinstall parameters. As original autoinstall file is downloaded and network setup is added/replaced in it, KVM host must have a web server enabled to host the new autoinstall file. Format: ||| .\")\n\n # parse input\n args = parser.parse_args()\n if not args.name:\n raise Exception(\"Provide a guest name\")\n name = args.name[0]\n if not args.cpus:\n num_cpus = DEFAULT_NUM_CPUS\n else:\n num_cpus = int(args.cpus)\n if not args.ram:\n amount_ram = DEFAULT_RAM*1024\n else:\n amount_ram = int(args.ram)\n if not args.disk:\n disk_size = DISK_DEFAULT_SIZE\n else:\n disk_size = int(args.disk)\n if not args.distro:\n distro = \"virtio26\"\n else:\n distro = args.distro\n\n if not args.distro_iso_path and not args.distro_tree:\n raise Exception(\"Provide ISO path or tree location of a Linux distribution to be installed\")\n if not args.distro_iso_path:\n distro_iso_path = None\n else:\n distro_iso_path = args.distro_iso_path\n if not args.distro_tree:\n distro_tree = None\n else:\n distro_tree = args.distro_tree\n\n if not args.autoinstall:\n autoinstall_file_location = None\n if args.network:\n raise Exception(\"Invalid parameters, autoinstall parameter must be provided when network parameters are provided\")\n else:\n autoinstall_file_location = args.autoinstall\n if is_local_file(autoinstall_file_location):\n autoinstall_file = open(autoinstall_file_location).read()\n elif args.network:\n autoinstall_file = download_file(autoinstall_file_location)\n\n # add url autoinstall directive to file\n url_ks = \"url --url=%s\" % distro_tree\n url_ks = \"\\n%s\" % url_ks\n if re.search(\"\\nurl .*\\n\", autoinstall_file):\n autoinstall_file = re.sub(\"\\nurl .*\\n\", url_ks + \"\\n\", autoinstall_file)\n else:\n autoinstall_file += \"\\n%s\" % url_ks\n\n # if network parameters were defined\n kernel_args = None\n if args.network:\n # create network autoinstall directive\n network_input = args.network.split(\"|\")\n if len(network_input) != 4:\n raise Exception(\"Invalid format of network parameter\")\n network_ks = \"network --bootproto=static --ip=%s --netmask=%s --gateway=%s\" % (network_input[0], network_input[1], network_input[2])\n if network_input[3] != \"\":\n network_ks += \" --nameserver=%s\" % network_input[3]\n network_ks += \" --hostname=%s\" % name\n network_ks = \"\\n%s\" % network_ks\n\n # add network autoinstall directive to file\n if re.search(\"\\nnetwork .*\\n\", autoinstall_file):\n autoinstall_file = re.sub(\"\\nnetwork .*\\n\", network_ks + \"\\n\", autoinstall_file)\n else:\n autoinstall_file += \"\\n%s\" % network_ks\n\n # @TODO Fedora 17+ uses different syntax for passing network parameters\n # in kernel command line, fix this\n kernel_args = \"ip=%s netmask=%s gateway=%s\" % (network_input[0], network_input[1], network_input[2])\n if network_input[3] != \"\":\n kernel_args += \" dns=%s\" % network_input[3]\n\n if args.network or is_local_file(autoinstall_file_location):\n # save it in web server root directory\n base_ai_dir = \"%s/autoinstall_files\" % WEB_SERVER_ROOT\n if not os.path.exists(base_ai_dir):\n os.makedirs(base_ai_dir)\n autoinstall_file_name = os.path.basename(autoinstall_file_location)\n autoinstall_file_path = \"%s/%s\" % (base_ai_dir, autoinstall_file_name)\n autoinstall_fh = open(autoinstall_file_path, \"w+\")\n autoinstall_fh.write(autoinstall_file)\n autoinstall_fh.close()\n\n autoinstall_file_location = \"http://%s/autoinstall_files/%s\" % (socket.gethostbyname(socket.getfqdn()), autoinstall_file_name)\n\n return {\"name\": name,\n \"num_cpus\": num_cpus,\n \"amount_ram\": amount_ram,\n \"disk_size\": disk_size,\n \"distro\": distro,\n \"distro_iso_path\": distro_iso_path,\n \"distro_tree_location\": distro_tree,\n \"autoinstall_file_location\": autoinstall_file_location,\n \"kernel_args\": kernel_args\n }\n\ndef main():\n \"\"\"\n Method called when script is run\n \"\"\"\n\n input = parse_input()\n create_kvm_guest(input[\"name\"],\n input[\"num_cpus\"], input[\"amount_ram\"], input[\"disk_size\"],\n input[\"distro\"], input[\"distro_iso_path\"], input[\"distro_tree_location\"],\n input[\"autoinstall_file_location\"], input[\"kernel_args\"])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"shenson/cobbler","sub_path":"tests/misc/create_kvm_guest.py","file_name":"create_kvm_guest.py","file_ext":"py","file_size_in_byte":11617,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"42507856699","text":"import random\ntot = 0\nwin = random.randint(1, 10)\nprint('Vamos jogar um jogo de adivinha! \\nSeu computador pensou em um número de 1 a 10.')\npalpite = int(input('Digite seu palpite!: '))\nwhile palpite != win:\n tot += 1\n if palpite < win:\n print('É maior... Tente novamente!')\n elif palpite > win:\n print('É menor... Tente novamente!') \n palpite = int(input('Digite seu palpite: '))\nprint(f'Muito bem! Você acertou! Foram ao todo {tot} tentativas!')\n \n","repo_name":"Thalesamaojapa/Thales---Python","sub_path":"Exercícios_Main/Exercícios/Exercício59(JogoDaAdivinhação).py","file_name":"Exercício59(JogoDaAdivinhação).py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36167282070","text":"from nltk.tokenize import word_tokenize\nimport re\nfrom config import coordinates\nimport nltk\nnltk.download('punkt')\n\npattern1 = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')\npattern2 = re.compile('@[a-zA-Z0-9__]+')\npattern3 = re.compile('[#@]+')\n#continuely punctuation\npattern4 =re.compile('[\\(\\)*^$\\,\\!\\?\\.=:/\\&\\'\\;]+')\n\n#preporcess\n#the punctuations, hashtags, at, website,if is retweet, then conbine the retweent with tweet.\ndef pre(s):\n url = re.findall(pattern1, s)\n at = re.findall(pattern2, s)\n\n s=s.split()\n st = \" \".join(w for w in s if w not in url and w not in at)\n s = word_tokenize(st)\n st=' '.join(w for w in s)\n puns = re.findall(pattern4, st)\n hashtag = re.findall(pattern3, st)\n st=' '.join(w.lower() for w in s if w not in puns and w not in hashtag)\n return st\n\ndef get_area(li):\n\t#li[0]=longtitude\n\t#li[1]=latitude\n\tname=' '\n\tfor key, value in coordinates.items():\n\t\tif li[0]<=value[3] and li[0]>=value[1] and li[1]<=value[2] and li[1]>=value[0]:\n\t\t\tname = key\n\treturn name\n\n# lemmatizer = nltk.stem.wordnet.WordNetLemmatizer()\n# def lemmatize(word):\n# lemma = lemmatizer.lemmatize(word,'v')\n# if lemma == word:\n# lemma = lemmatizer.lemmatize(word,'n')\n# elif lemma==word:\n# lemma=lemmatizer.lemmatize(word,'adj')\n# return lemma","repo_name":"zack0518/project","sub_path":"preporcessing.py","file_name":"preporcessing.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5776167707","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Feb 3 23:48:47 2018\r\n\r\n@author: ChenZhengyang\r\n\"\"\"\r\nimport os\r\nimport numpy as np \r\nimport pandas as pd \r\nfrom sklearn import preprocessing\r\nfrom sklearn import metrics\r\nfrom sklearn import tree\r\nfrom sklearn.externals.six import StringIO\r\nimport pydotplus as pdp\r\nimport sklearn.metrics as mat\r\ndataset = pd.read_csv(\"../DATASET/student/student-por.csv\")\r\n\r\n#observe the types of data\r\ndataset.dtypes\r\n\r\n#observe distributions of object-type features\r\nvar = ['school','sex','address','famsize','Pstatus','Mjob','Fjob','reason','guardian','schoolsup','famsup',\r\n 'paid','activities','nursery','higher','internet','romantic']\r\n\"\"\"for v in var:\r\n print('\\nFrequency count for variable %s'%v) \r\n print(dataset[v].value_counts())\r\n \"\"\"\r\n \r\n#label encode \r\nfrom sklearn.preprocessing import LabelEncoder\r\nvar_to_encode = ['school','sex','address','famsize','Pstatus','Mjob','Fjob','reason','guardian','schoolsup','famsup',\r\n 'paid','activities','nursery','higher','internet','romantic']\r\nfor col in var_to_encode:\r\n dataset[col] = LabelEncoder().fit_transform(dataset[col])\r\n\r\n# Binarize G3<=11: G3=0 G3>11: G3=1\r\ndataset[['G3']] = preprocessing.Binarizer(threshold=11).transform(dataset[['G3']])\r\n\r\nx=dataset[dataset.columns.drop('G3')]\r\ny= dataset['G3']\r\n\r\nx_scaled=preprocessing.scale(x)\r\n\r\n# divide dataset into train set and test set, size of test equals = 0.33*size of dataset\r\nfrom sklearn.model_selection import train_test_split\r\nx_train, x_test, y_train, y_test = train_test_split(\r\n x_scaled,y,test_size=0.33, random_state=0)\r\n\r\n#--------------------------------------END OF PREPROCESSING----------------------\r\n\r\nfrom matplotlib import pyplot\r\nfrom sklearn import svm\r\n\r\nsvm_auc_trn,svm_auc_tst,act_clfscore=[],[],[]\r\nkernels=['linear','poly','rbf','sigmoid']\r\nfor k in kernels:\r\n svmclf=svm.SVC(kernel=k,probability=True)\r\n svmclf = svmclf.fit(x_train, y_train)\r\n act_clfscore.append(mat.roc_auc_score(y_test, svmclf.predict_proba(x_test)[:,1]))\r\n\r\np1 = pyplot.bar([1,2,3,4], act_clfscore, 0.4, color='#d62728')\r\npyplot.ylabel('Scores')\r\npyplot.title('Scores by different kernels')\r\npyplot.xticks([1,2,3,4], kernels)\r\npyplot.yticks(np.arange(0, 1.01, 0.02))\r\npyplot.ylim(0.9, 1.0)\r\npyplot.show()\r\n\r\n\r\ncosts = np.power(10.0, range(-5,5))\r\nsvm_auc_tst = np.zeros(len(costs))\r\nsvm_auc_trn = np.zeros(len(costs))\r\n\r\nfor i in range(len(costs)):\r\n svmclf = svm.SVC(kernel = 'linear', C=costs[i], probability=True)\r\n svmclf.fit(x_train,y_train)\r\n svm_auc_tst[i] = mat.roc_auc_score(y_test, svmclf.predict_proba(x_test)[:,1])\r\n svm_auc_trn[i] = mat.roc_auc_score(y_train, svmclf.predict_proba(x_train)[:,1])\r\npyplot.title('Scores by costs')\r\npyplot.plot(svm_auc_trn, linewidth=2, label = \"svm train auc\")\r\npyplot.plot(svm_auc_tst, linewidth=2, label = \"svm test auc\")\r\npyplot.xticks(range(len(costs)),['0.00001','0.0001','0.001','0.01','0.1','0','10','100','1000','10000','100000'])\r\npyplot.legend()\r\npyplot.ylim(0.8, 1.0)\r\npyplot.xlabel(\"Costs\")\r\npyplot.ylabel(\"AUC Scores\")\r\npyplot.show()\r\n\r\n","repo_name":"victorchen945/Machine-Learning","sub_path":"SVM/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21877689870","text":"\nimport luigi\nfrom os.path import join, dirname\nfrom glob import glob\nimport subprocess\nfrom os import makedirs\n\nfrom ..config import PipelineConfig\nfrom ..utils.conda import CondaPackage\nfrom ..utils.cap_task import CapDbTask\n\nMOUSE_GENOME_URL = 'ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCA/000/001/635/GCA_000001635.9_GRCm39/GCA_000001635.9_GRCm39_genomic.fna.gz'\n\n\nclass MouseRemovalDB(CapDbTask):\n \"\"\"This class is responsible for building and/or retriveing\n validating the database which will be used to remove mouse\n reads from the sample.\n \"\"\"\n config_filename = luigi.Parameter()\n cores = luigi.IntParameter(default=1)\n MODULE_VERSION = 'v1.0.0'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.pkg = CondaPackage(\n package=\"bowtie2==2.4.1\",\n executable=\"bowtie2-build\",\n channel=\"bioconda\",\n config_filename=self.config_filename,\n )\n self.config = PipelineConfig(self.config_filename)\n self.db_dir = self.config.db_dir\n self._fastas = []\n\n def download_mouse_genome(self):\n local_dir = join(self.config.db_dir, 'GRCm39')\n makedirs(local_dir, exist_ok=True)\n cmd = (\n 'wget '\n f'--directory-prefix={local_dir} '\n f'{MOUSE_GENOME_URL} '\n )\n self.run_cmd(cmd)\n local_path = join(local_dir, 'GCA_000001635.9_GRCm39_genomic.fna.gz')\n return local_path\n\n @property\n def fastas(self):\n if self._fastas:\n return self._fastas\n local_path = self.download_mouse_genome()\n self._fastas = [local_path]\n return self._fastas\n\n def tool_version(self):\n return self.run_cmd(f'{self.pkg.bin} --version').stderr.decode('utf-8')\n\n def requires(self):\n return self.pkg\n\n @classmethod\n def _module_name(cls):\n return 'bowtie_mouse_removal_db'\n\n @classmethod\n def dependencies(cls):\n return ['bowtie2==2.4.1', 'GRCm39', '2020-10-21']\n\n @property\n def bowtie2_index(self):\n return join(self.db_dir, 'GRCm39', 'mouse_removal.bt2')\n\n def output(self):\n index = luigi.LocalTarget(self.bowtie2_index + '.1.bt2')\n index.makedirs()\n return {\n 'bt2_index_1': index,\n }\n\n def build_bowtie2_index_from_fasta(self):\n cmd = ''.join((\n self.pkg.bin,\n f' --threads {self.cores} ',\n ','.join(self.fastas),\n ' ',\n self.bowtie2_index\n ))\n subprocess.check_call(cmd, shell=True)\n\n def download_bowtie2_index_from_s3(self):\n paths = [\n 'cap2/databases/2020-06-08/hg38/hg38.fa.gz',\n 'cap2/databases/2020-06-08/hg38/human_removal.bt2.1.bt2',\n 'cap2/databases/2020-06-08/hg38/human_removal.bt2.2.bt2',\n 'cap2/databases/2020-06-08/hg38/human_removal.bt2.3.bt2',\n 'cap2/databases/2020-06-08/hg38/human_removal.bt2.4.bt2',\n 'cap2/databases/2020-06-08/hg38/human_removal.bt2.rev.1.bt2',\n 'cap2/databases/2020-06-08/hg38/human_removal.bt2.rev.2.bt2',\n ]\n for path in paths:\n cmd = (\n 'wget '\n f'--directory-prefix={dirname(self.output()[\"bt2_index_1\"].path)} '\n f'https://s3.wasabisys.com/metasub-microbiome/{path} '\n\n )\n self.run_cmd(cmd)\n\n def run(self):\n self.build_bowtie2_index_from_fasta()\n","repo_name":"MetaSUB/CAP2","sub_path":"cap2/pipeline/databases/mouse_removal_db.py","file_name":"mouse_removal_db.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"}
+{"seq_id":"7056545924","text":"# -*- coding: UTF-8 -*-\nimport urllib, json, unicodedata\n\ndef gs(statement):\n\tquery = urllib.urlencode({'q': statement})\n\turl = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query\n\tsearch_response = urllib.urlopen(url)\n\tsearch_results = search_response.read() # Searching...\n\tresults = json.loads(search_results)['responseData']['results'] # Getting results\n\t# Checking if there is results\n\tif (len(results) > 0): # If there is results, so:\n\t\tdata = results[0]['url']\n\t\tdata = urllib.unquote(data).encode(\"utf-8\", \"replace\") # Fixing URL encode, to show correctly on IRC\n\t\tdata = urllib.unquote_plus(data) # Remove any percents from url \n\telse: # If not, return null\n\t\tdata = None\n\treturn data\n\t\ndef pub_wiki(connection, msg, chan, nick):\n\tif (len(msg) > 0):\n\t\tsearch = \" \".join(msg)\n\t\tquery = \"site:wiki.archlinux.org.il -inurl:מיוחד -inurl:שיחה -inurl:קטגוריה -inurl:edit -inurl:printable %s\" % search\n\t\tresults = gs(query)\n\t\tif (results == None):\n\t\t\tsnd = \"%s: Not Found\" % nick\n\t\telse:\n\t\t\tsnd = \"%s: %s\" % (nick, results)\n\t\tconnection.privmsg(chan, snd)\n\telse:\n\t\tconnection.notice(nick,\"What to search?\")\n\t\n","repo_name":"soomsoom/soombot-il","sub_path":"plugins/wiki/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"31792914362","text":"#!/bin/env python\n\nimport logging\nimport sys\n\nfrom numpy import ma\n\nfrom recsys.algorithm.neighborhood_based_algorithm_regression_model import (ItemBasedRegressionModel,\n RegressionModelNeighborhoodBasedConfig,\n UserBasedRegressionModel)\nfrom recsys.algorithm.test_data import test_rating_data\nfrom recsys.metric.metric import rmse, statistic\n\nlogging.basicConfig(stream=sys.stdout)\n\nclass TestRegressionModel(object):\n\n def test_user_based_regression_model(self):\n algo = UserBasedRegressionModel(RegressionModelNeighborhoodBasedConfig(topk=3, lr=0.005, epochs=200, wdecay=0.0001))\n algo.fit(test_rating_data)\n hat_rating = algo.predict()\n print(statistic(ma.masked_equal(test_rating_data, 0), hat_rating))\n print(rmse(ma.masked_equal(test_rating_data, 0), hat_rating))\n print(algo.__parameters__())\n\n def test_item_based_regression_model(self):\n algo = ItemBasedRegressionModel(RegressionModelNeighborhoodBasedConfig(topk=3, lr=0.005, epochs=200, wdecay=0.0001))\n algo.fit(test_rating_data)\n hat_rating= algo.predict()\n print(statistic(ma.masked_equal(test_rating_data, 0), hat_rating))\n print(rmse(ma.masked_equal(test_rating_data, 0), hat_rating))\n print(algo.__parameters__())\n","repo_name":"stupid-coder/recsys","sub_path":"recsys/algorithm/test_neighborhood_based_regression_model.py","file_name":"test_neighborhood_based_regression_model.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1057020005","text":"import nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nimport string\nfrom sklearn.metrics.pairwise import cosine_similarity # Cosine similarity techniques are used to easily assess the similarity and relevance of the frames of the video with the query\nimport pandas as pd\nfrom nltk.corpus import wordnet\nfrom sentence_transformers import SentenceTransformer\nimport wikipedia\nfrom summarizer import TransformerSummarizer\n\n\nnltk.download('punkt')\n\ndf_train = pd.read_csv('training_data.csv')\ndf_test = pd.read_csv('test_data.csv')\n\ndf_train = df_train.drop('malaise', axis=1)\ndf_test = df_test.drop('malaise', axis=1)\n\ndisease = df_train['prognosis'].tolist()\ndisease_column = list(df_train.columns.values)\ndisease_column = [i.replace('_', ' ') for i in disease_column]\n\nmodel = SentenceTransformer('bert-base-nli-mean-tokens')\ndis_embeddings = model.encode(disease_column)\n\n\ndef runFunc(data):\n line = data\n line = line.translate(str.maketrans('', '', string.punctuation))\n\n stop_words = set(stopwords.words('english'))\n\n word_tokens = word_tokenize(line)\n filtered_sentence = [w for w in word_tokens if not w.lower() in stop_words]\n filtered_sentence = ' '.join(filtered_sentence).split()\n\n symptoms = []\n maxNum = 0\n\n \n synsymptoms = []\n\n\n for i in filtered_sentence:\n for syn in wordnet.synsets(i):\n for lm in syn.lemmas():\n synsymptoms.append(lm.name())\n lis_embeddings1 = model.encode(synsymptoms)\n\n highestSymptom = \"\"\n\n for i in range(len(synsymptoms)):\n for j in range(len(disease_column)):\n a = cosine_similarity([lis_embeddings1[i]], [dis_embeddings[j]])\n if (a[0][0] >= 0.8):\n if (a[0][0] > maxNum):\n maxNum = a[0][0]\n highestSymptom = disease_column[j]\n if highestSymptom not in symptoms: symptoms.append(highestSymptom)\n symptoms = [i for i in symptoms if i]\n print(symptoms)\n\n df_new = df_test\n\n for index, row in df_new.iterrows():\n for i in symptoms:\n if row[i.replace(' ', '_')] == 0:\n df_new = df_new[df_new.index != index]\n finalDiagnosis = list(df_new['prognosis'])\n # content = wikipedia.page(df_new['prognosis'])\n # GPT2_model = TransformerSummarizer(transformer_type=\"GPT2\",transformer_model_key=\"gpt2-medium\")\n # gpt_summary = ''.join(GPT2_model(content.content, num_sentences=4))\n return finalDiagnosis","repo_name":"silvermango9927/alchemist-ai-doctor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"17830571422","text":"\ndef part_one():\n file = open(\"input\", \"r\")\n\n input_list = [line.strip() for line in file]\n\n file.close()\n\n bin_num = ''\n epsi = ''\n first_bit_one = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n first_bit_zero = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n for val in input_list:\n for i, bit in enumerate(val):\n if bit == '1':\n first_bit_one[i] += 1\n else:\n first_bit_zero[i] += 1\n\n for i in range(len(first_bit_one)):\n if first_bit_one[i] > first_bit_zero[i]:\n bin_num += '1'\n else:\n bin_num += '0'\n\n for i in range(len(first_bit_one)):\n if first_bit_one[i] < first_bit_zero[i]:\n epsi += '1'\n else:\n epsi += '0'\n\n bin_num = int(bin_num, 2)\n epsi = int(epsi, 2)\n\n print(bin_num * epsi)\n\n\ndef shorten_list(num, is_zero, bit):\n return num[bit] == is_zero\n\n\ndef part_two():\n file = open(\"input\", \"r\")\n\n input_list = [line.strip() for line in file]\n one_list = input_list\n\n file.close()\n\n bits = len(input_list[0])\n list_len = len(input_list)\n\n for b in range(bits):\n one_count = 0\n\n for entry in one_list:\n if entry[b] == '1':\n one_count += 1\n\n if list_len - one_count > one_count:\n one_list = list((filter(lambda elem: shorten_list(elem, '0', b), one_list)))\n else:\n one_list = list((filter(lambda elem: shorten_list(elem, '1', b), one_list)))\n\n list_len = len(one_list)\n\n if list_len == 1:\n oxy = one_list[0]\n break\n\n for b in range(bits):\n one_count = 0\n\n for entry in input_list:\n if entry[b] == '1':\n one_count += 1\n\n if list_len - one_count > one_count:\n input_list = list((filter(lambda elem: shorten_list(elem, '1', b), input_list)))\n else:\n input_list = list((filter(lambda elem: shorten_list(elem, '0', b), input_list)))\n\n list_len = len(input_list)\n\n if list_len == 1:\n co2 = input_list[0]\n break\n\n bin_num = int(oxy, 2)\n epsi = int(co2, 2)\n\n print(bin_num * epsi)\n\n\nif __name__ == '__main__':\n part_two()\n","repo_name":"Ruben1729/aoc2021","sub_path":"Day 3/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10665845187","text":"# -*- coding:utf-8 -*-\r\n# &Author AnFany\r\n\r\n# 两层的Stacking分类\r\n\r\n\r\n# 第一层6个模型:随机森林,AdaBoost,GBDT,LightGBM,XGBoost,CatBoost\r\n# 第二层模型:BP神经网络分类\r\n\r\n# 引入数据文件\r\nimport adult_Stacking_Data as adult\r\n\r\n# 引入绘图库包\r\nimport matplotlib.pyplot as plt\r\nfrom pylab import mpl\r\nmpl.rcParams['font.sans-serif'] = ['FangSong'] # 中文字体名称\r\nmpl.rcParams['axes.unicode_minus'] = False # 显示负号\r\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\r\n# 设置正确率的刻度与子刻度\r\ny_toge = MultipleLocator(0.02) # 将y轴主刻度标签设置为0.1的倍数\r\ny_son = MultipleLocator(0.01) # 将此y轴次刻度标签设置为0.01的倍数\r\n# 引入需要用到的模型的库包\r\n# 随机森林\r\nfrom sklearn.ensemble import RandomForestClassifier as RF\r\n# AdaBoost\r\nfrom sklearn.ensemble import AdaBoostClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier\r\n# GBDT\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\n# XGBoost\r\nimport xgboost as xgb\r\n# LightGBM\r\nimport lightgbm as lgbm\r\n# CatBoost\r\nimport catboost as cb\r\n# BP神经网络分类\r\nimport tensorflow as tf\r\nimport bp_Classify as bp\r\n\r\n# 其他库包\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom collections import OrderedDict # python字典是无序的,此包是有序的\r\n# 格式化输出混淆矩阵\r\nfrom prettytable import PrettyTable as PT\r\n'''\r\n第一部分:数据处理模型\r\n'''\r\n\r\nclass DATA:\r\n\r\n def __init__(self, datadict=adult.data_dict, mubiao='Money'):\r\n self.data = datadict\r\n self.k = 8 # 因为需要对每个模型进行单独的数据处理,因此这个折数对于每个模型都必须是一样的\r\n\r\n # 训练数据\r\n self.chidata = self.data['train']\r\n\r\n # 预测数据\r\n self.nodata = self.data['predict']\r\n\r\n # 类别型数据的编号\r\n self.catsign = self.Sign()\r\n\r\n # 目标字段\r\n self.ziduan = mubiao\r\n\r\n # 对于归一化化和标准化的处理,要记录转化的值,在这里将2者统一。反处理时,预测值需要乘以self.fenmu 加上self.cha\r\n # 分类问题不涉及反处理\r\n # 对于CatBoost而言,因为需要将训练数据的字段,转为数字,因此结果中需要将这个数字转化为真实的类别名称\r\n self.typedict = self.TransType()\r\n\r\n # 本程序第二层采用BP神经网络,为了适用于多分类的情形,需要获得类别数\r\n self.typecount = self.Getcount()\r\n\r\n # 计算类别数\r\n def Getcount(self):\r\n nulist = list(set(list(self.chidata[self.ziduan])))\r\n return len(nulist)\r\n\r\n # 因为对于CatBoost而言,不需要进行类别型特征的处理,但是需要类别型特征的标号\r\n def Sign(self):\r\n sign = []\r\n numlist = self.chidata.values[0][: -1] # 不包括最后的目标字段\r\n for jj in range(len(numlist)):\r\n try:\r\n numlist[jj] + 9\r\n except TypeError:\r\n sign.append(jj)\r\n return sign\r\n # 对于CatBoost而言,需要对目标字段进行数字化处理,\r\n def TransType(self):\r\n tdict = {}\r\n nulist = sorted(list(set(list(self.chidata[self.ziduan]))))\r\n for jj in nulist:\r\n tdict[jj] = nulist.index(jj)\r\n return tdict\r\n\r\n\r\n # 将目标字段转化为数字(CatBoost)\r\n def TargetoDi(self):\r\n # 将目标字段按照字典的形式转变为数字\r\n self.chidata[self.ziduan] = [self.typedict[jj] for jj in self.chidata[self.ziduan]]\r\n return print('CatBoost目标字段转化完毕')\r\n\r\n # 因为引入的BP分类模型,输出数据需要经过独热化处理\r\n def OneH(self):\r\n # 首先定义一个全0数组\r\n zero = [0] * self.typecount\r\n # 定义一个类别序列\r\n typelist = zero.copy()\r\n for jj in self.typedict:\r\n typelist[self.typedict[jj]] = jj\r\n\r\n # 开始更改目标字段的数据\r\n newdata = []\r\n for jj in self.chidata[self.ziduan]:\r\n ss = zero.copy()\r\n ss[typelist.index(jj)] = 1\r\n newdata.append(ss)\r\n\r\n self.chidata[self.ziduan] = newdata\r\n\r\n return '目标字段独热化完毕'\r\n\r\n\r\n # 类别型特征数字标签化函数,\r\n def CAtoDI(self):\r\n # 如果特征值不能执行数字加法运算,则视为类别型特征\r\n for tezheng in self.chidata:\r\n try:\r\n self.chidata[tezheng].values[0] + 1\r\n except TypeError:\r\n numlist = sorted(list(set(list(self.chidata[tezheng]))))\r\n self.chidata[tezheng] = [numlist.index(hh) for hh in self.chidata[tezheng]]\r\n try:\r\n self.nodata[tezheng] = [numlist.index(ss) for ss in self.nodata[tezheng]]\r\n except ValueError:\r\n print('特征%s:预测比训练的多了值' % (tezheng))\r\n return print('数字化处理完毕')\r\n\r\n\r\n # 归一化函数\r\n def Normal(self):\r\n # 在此之前需要把类别型标签去掉,否则会报错\r\n for tezheng in self.chidata:\r\n maxnum = max(list(self.chidata[tezheng]))\r\n minum = min(list(self.chidata[tezheng]))\r\n if maxnum == minum:\r\n self.chidata[tezheng] = [1 for hh in self.chidata[tezheng]]\r\n self.nodata[tezheng] = [1 for ss in self.nodata[tezheng]]\r\n else:\r\n self.chidata[tezheng] = [(hh - minum) / (maxnum - minum) for hh in self.chidata[tezheng]]\r\n self.nodata[tezheng] = [(ss - minum) / (maxnum - minum) for ss in self.nodata[tezheng]]\r\n return print('归一化处理完毕')\r\n\r\n # 标准化函数\r\n def Stand(self):\r\n # 在此之前需要把类别型标签去掉,否则会报错\r\n for tezheng in self.chidata:\r\n standnum = np.std(np.array(list(self.chidata[tezheng])), ddof=1) # 计算有偏的标准差\r\n meanum = np.mean(np.array(list(self.chidata[tezheng])))\r\n\r\n if meanum == 0:\r\n self.chidata[tezheng] = [1 for hh in self.chidata[tezheng]]\r\n self.nodata[tezheng] = [1 for ss in self.nodata[tezheng]]\r\n else:\r\n self.chidata[tezheng] = [(hh - standnum) / meanum for hh in self.chidata[tezheng]]\r\n self.nodata[tezheng] = [(ss - standnum) / meanum for ss in self.nodata[tezheng]]\r\n return print('标准化处理完毕')\r\n\r\n # 定义Kfold的函数,也就是将原始的训练数据集分为k对训练数据和验证数据的组合\r\n def Kfold(self):\r\n # 因为每个模型需要将验证数据结合的结果集成起来,为了方便起见,在这里固定每一折数中的数据集合\r\n datanum = self.chidata.values\r\n # 数据集总长度\r\n length = len(datanum)\r\n alist = np.arange(length)\r\n np.random.seed(1990)\r\n np.random.shuffle(alist) # 随机打乱数据对BPNN,SVM而言是有益处的,而对于决策树之类的模型而言没有影响\r\n\r\n # 验证数据的长度\r\n yanlem = int(length / self.k)\r\n\r\n # 存储数据集的字典\r\n datai = {}\r\n datai['predict'] = self.nodata.values\r\n\r\n # 开始处理Kfold\r\n for kk in range(self.k):\r\n datai[kk] = OrderedDict()\r\n if kk == 0:\r\n datai[kk]['train'] = datanum[alist[(kk + 1) * yanlem:]]\r\n datai[kk]['test'] = datanum[alist[: (kk + 1) * yanlem]]\r\n elif kk == self.k - 1:\r\n datai[kk]['train'] = datanum[alist[: kk * yanlem]]\r\n datai[kk]['test'] = datanum[alist[kk * yanlem:]]\r\n else:\r\n datai[kk]['test'] = datanum[alist[kk * yanlem: (kk + 1) * yanlem]]\r\n signlist = list(alist[: kk * yanlem]) + list(alist[(kk + 1) * yanlem:])\r\n datai[kk]['train'] = datanum[signlist]\r\n # 返回的数据集形式{0:{'train':data, 'test':data},……,self.k-1:{'train':data, 'test':data}, 'predict':data}\r\n print('K折处理完毕')\r\n return datai\r\n\r\n\r\n'''\r\n第二部分:第一层的模型运行阶段\r\n'''\r\n# 可以任意添加模型\r\nclass MODELONE:\r\n\r\n def __init__(self, exdict, zidan='Money'):\r\n\r\n # 验证数据集的预测结果\r\n self.yanzhneg_pr = []\r\n\r\n # 验证数据集的真实结果\r\n self.yanzhneg_real = []\r\n\r\n # 预测数据集的预测结果\r\n self.predi = []\r\n\r\n # 预测数据集的真实姐夫哦\r\n self.preal = []\r\n\r\n # 目标字段名称\r\n self.zi = zidan\r\n\r\n # 数据结构和数据处理类的保持一致,要把验证数据集的输入和真实的输出合二为一\r\n self.datai = {}\r\n\r\n # 记录每个模型最终误差的字典\r\n self.error_dict = OrderedDict()\r\n\r\n # 数字类别与正常类别的对应字典\r\n self.tydict = exdict\r\n\r\n # 将第一层的结果转换为何数据结构处理类中一样的数据结构的函数\r\n # 也就是{'train':dataframe, 'predict':dataframe}样式的字典\r\n def DataStru(self):\r\n self.datai['train'] = np.row_stack((np.array(self.yanzhneg_pr), np.array(self.yanzhneg_real))) # 此处添加行\r\n self.datai['predict'] = np.row_stack((np.array(self.predi), np.array(self.preal)))\r\n # 将训练数据转置\r\n datapst = self.datai['train'].T\r\n # 为训练数据定义DataFrame的列名\r\n mingcheng = ['第%s个模型列' % str(dd) for dd in list(range(len(self.datai['train']) - 1))] + [self.zi]\r\n self.datai['train'] = pd.DataFrame(datapst, columns=mingcheng)\r\n\r\n # 将预测数据转置\r\n dapst = self.datai['predict'].T\r\n # 为训练数据定义DataFrame的列名\r\n mingche= ['第%s个模型列' % str(dd) for dd in list(range(len(self.datai['predict']) - 1))] + [self.zi]\r\n self.datai['predict'] = pd.DataFrame(dapst, columns=mingche)\r\n return print('二层的数据准备完毕')\r\n\r\n # 创建将预测的多维的数字类别转化为一维原始名称类别的函数\r\n def AntiTae(self, relist):\r\n huhuan = {self.tydict[ll]: ll for ll in self.tydict}\r\n return [huhuan[dd] for dd in relist]\r\n\r\n # 创建将预测的多维的数字类别转化为一维原始名称类别的函数\r\n def MTae(self, relist):\r\n yiwellist = []\r\n for jj in relist:\r\n yiwellist.append(list(jj).index(max(list(jj))))\r\n # 首先将字典键值互换\r\n huhuan = {self.tydict[ll]: ll for ll in self.tydict}\r\n return [huhuan[dd] for dd in yiwellist]\r\n\r\n # 混淆矩阵的函数\r\n def Tom(self, reallist, prelist):\r\n '''\r\n :param reallist: 真实的类别列表\r\n :param prelist: 预测的类别列表\r\n :return: 每个类别预测为所有类别的个数字典\r\n '''\r\n coundict = {}\r\n for jj in list(set(reallist)):\r\n coundict[jj] = {}\r\n for hh in list(set(reallist)):\r\n coundict[jj][hh] = len([i for i, j in zip(reallist, prelist) if i == jj and j == hh])\r\n return coundict\r\n\r\n # 定义输出混淆矩阵的函数\r\n def ConfuseMatrix(self, reallist, prelist):\r\n '''\r\n :param reallist: 真实的类别列表\r\n :param prelist: 预测的类别列表\r\n :return: 输出混淆矩阵\r\n '''\r\n zidian = self.Tom(reallist, prelist)\r\n lieming = sorted(zidian.keys())\r\n table = PT(['混淆矩阵'] + ['预测%s' % d for d in lieming])\r\n for jj in lieming:\r\n table.add_row(['实际%s' % jj] + [zidian[jj][kk] for kk in lieming])\r\n return table\r\n\r\n # 定义计算F1度量的函数\r\n def F1(self, realist, prelist):\r\n '''\r\n :param realist: 真实的类别列表\r\n :param prelist: 预测的类别列表\r\n :return: F1度量\r\n '''\r\n condict = self.Tom(realist, prelist)\r\n zongshu = 0\r\n zhengque = 0\r\n zhao_cu = [] # 存储每个类别的召回率\r\n for cu in condict:\r\n zq = 0\r\n zs = 0\r\n for hh in condict[cu]:\r\n geshu = condict[cu][hh]\r\n if cu == hh:\r\n zhengque += geshu\r\n zq = geshu\r\n zongshu += geshu\r\n zs += geshu\r\n zhao_cu.append(zq / zs)\r\n # 计算精确率\r\n jingque = zhengque / zongshu\r\n # 计算类别召回率\r\n zhaohui = np.mean(np.array(zhao_cu))\r\n # f1度量\r\n f_degree = 2 * jingque * zhaohui / (jingque + zhaohui)\r\n return f_degree\r\n\r\n # 随机森林\r\n def RF_First(self, data, n_estimators=1000, max_features='sqrt'):\r\n # 存储每一折中验证数据集的预���结果\r\n yanzhenglist = []\r\n # 存储每一折中验证数据集的真实结果\r\n yanzhenglist_real = []\r\n # 存储每一折中预测数据集的预测结果\r\n prelist = []\r\n\r\n # 存储训练、验证、预测数据的误差\r\n errorlsit = []\r\n # 开始每一折的训练,因为这个折数的字典是有序的,因此不用考虑每一折的顺序。\r\n for zhe in [zheshu for zheshu in data.keys() if zheshu != 'predict']:\r\n model = RF(n_estimators=n_estimators, max_features=max_features)\r\n model.fit(data[zhe]['train'][:, :-1], data[zhe]['train'][:, -1])\r\n # 注意存储验证数据集结果和预测数据集结果的不同\r\n # 训练数据集的预测结果\r\n xul = model.predict(data[zhe]['train'][:, :-1])\r\n # 验证的预测结果\r\n yanre = model.predict(data[zhe]['test'][:, :-1])\r\n #预测的预测结果\r\n prer = model.predict(data['predict'][:, :-1])\r\n\r\n yanzhenglist += list(yanre)\r\n yanzhenglist_real += list(data[zhe]['test'][:, -1])\r\n prelist.append(prer)\r\n # 每计算一折后,要计算训练、验证、预测数据的误差\r\n xx = self.F1(xul, data[zhe]['train'][:, -1])\r\n\r\n yy = self.F1(yanre, data[zhe]['test'][:, -1])\r\n\r\n pp = self.F1(prer, data['predict'][:, -1])\r\n\r\n errorlsit.append([xx, yy, pp])\r\n # 针对预测数据集的预测结果计算均值\r\n meanPre = np.mean(np.array(prelist), axis=0)\r\n # 开始结合\r\n self.yanzhneg_pr.append(yanzhenglist)\r\n self.yanzhneg_real = yanzhenglist_real\r\n self.predi.append(meanPre)\r\n self.preal = data['predict'][:, -1]\r\n\r\n # 储存误差\r\n self.error_dict['随机森林'] = np.mean(np.array(errorlsit), axis=0)\r\n return print('1层中的随机森林运行完毕')\r\n\r\n # AdaBoost\r\n def Adaboost_First(self, data, max_depth=5, n_estimators=1000):\r\n # 存储每一折中验证数据集的预测结果\r\n yanzhenglist = []\r\n # 存储每一折中验证数据集的真实结果\r\n yanzhenglist_real = []\r\n # 存储每一折中预测数据集的预测结果\r\n prelist = []\r\n\r\n # 存储训练、验证、预测数据的误差\r\n errorlsit = []\r\n\r\n # 开始每一折的训练\r\n for zhe in [zheshu for zheshu in data.keys() if zheshu != 'predict']:\r\n model = AdaBoostClassifier(DecisionTreeClassifier(max_depth=max_depth),\r\n algorithm=\"SAMME\",\r\n n_estimators=n_estimators, learning_rate=0.8)\r\n model.fit(data[zhe]['train'][:, :-1], data[zhe]['train'][:, -1])\r\n # 注意存储验证数据集结果和预测数据集结果的不同\r\n # 训练数据集的预测结果\r\n xul = model.predict(data[zhe]['train'][:, :-1])\r\n # 验证的预测结果\r\n yanre = model.predict(data[zhe]['test'][:, :-1])\r\n #预测的预测结果\r\n prer = model.predict(data['predict'][:, :-1])\r\n yanzhenglist += list(yanre)\r\n yanzhenglist_real += list(data[zhe]['test'][:, -1])\r\n prelist.append(prer)\r\n\r\n # 每计算一折后,要计算训练、验证、预测数据的误差\r\n xx = self.F1(xul, data[zhe]['train'][:, -1])\r\n\r\n yy = self.F1(yanre, data[zhe]['test'][:, -1])\r\n\r\n pp = self.F1(prer, data['predict'][:, -1])\r\n\r\n errorlsit.append([xx, yy, pp])\r\n\r\n # 针对预测数据集的预测结果计算均值\r\n meanPre = np.mean(np.array(prelist), axis=0)\r\n # 开始结合\r\n self.yanzhneg_pr.append(yanzhenglist)\r\n self.yanzhneg_real = yanzhenglist_real\r\n self.predi.append(meanPre)\r\n self.preal = data['predict'][:, -1]\r\n # 储存误差\r\n self.error_dict['AdaBoost'] = np.mean(np.array(errorlsit), axis=0)\r\n\r\n return print('1层中的AdaBoost运行完毕')\r\n\r\n # GBDT\r\n def GBDT_First(self, data, max_depth=5, n_estimators=280):\r\n # 存储每一折中验证数据集的预测结果\r\n yanzhenglist = []\r\n # 存储每一折中验证数据集的真实结果\r\n yanzhenglist_real = []\r\n # 存储每一折中预测数据集的预测结果\r\n prelist = []\r\n\r\n # 存储训练、验证、预测数据的误差\r\n errorlsit = []\r\n # 开始每一折的训练\r\n for zhe in [zheshu for zheshu in data.keys() if zheshu != 'predict']:\r\n model = GradientBoostingClassifier(loss='deviance', n_estimators=n_estimators, max_depth=max_depth,\r\n learning_rate=0.1, max_features='sqrt')\r\n model.fit(data[zhe]['train'][:, :-1], data[zhe]['train'][:, -1])\r\n # 注意存储验证数据集结果和预测数据集结果的不同\r\n # 训练数据集的预测结果\r\n xul = model.predict(data[zhe]['train'][:, :-1])\r\n # 验证的预测结果\r\n yanre = model.predict(data[zhe]['test'][:, :-1])\r\n # 预测的预测结果\r\n prer = model.predict(data['predict'][:, :-1])\r\n yanzhenglist += list(yanre)\r\n yanzhenglist_real += list(data[zhe]['test'][:, -1])\r\n prelist.append(prer)\r\n\r\n # 每计算一折后,要计算训练、验证、预测数据的误差\r\n xx = self.F1(xul, data[zhe]['train'][:, -1])\r\n\r\n yy = self.F1(yanre, data[zhe]['test'][:, -1])\r\n\r\n pp = self.F1(prer, data['predict'][:, -1])\r\n\r\n errorlsit.append([xx, yy, pp])\r\n\r\n # 针对预测数据集的预测结果计算均值\r\n meanPre = np.mean(np.array(prelist), axis=0)\r\n # 开始结合\r\n self.yanzhneg_pr.append(yanzhenglist)\r\n self.yanzhneg_real = yanzhenglist_real\r\n self.predi.append(meanPre)\r\n self.preal = data['predict'][:, -1]\r\n # 储存误差\r\n self.error_dict['GBDT'] = np.mean(np.array(errorlsit), axis=0)\r\n\r\n return print('1层中的GBDT运行完毕')\r\n\r\n # LightGBM\r\n def LightGBM_First(self, data, max_depth=5, n_estimators=235):\r\n # 存储每一折中验证数据集的预测结果\r\n yanzhenglist = []\r\n # 存储每一折中验证数据集的真实结果\r\n yanzhenglist_real = []\r\n # 存储每一折中预测数据集的预测结果\r\n prelist = []\r\n\r\n # 存储训练、验证、预测数据的误差\r\n errorlsit = []\r\n # 开始每一折的训练\r\n for zhe in [zheshu for zheshu in data.keys() if zheshu != 'predict']:\r\n model = lgbm.LGBMClassifier(boosting_type='gbdt', objective='binary', num_leaves=50,\r\n learning_rate=0.1, n_estimators=n_estimators, max_depth=max_depth,\r\n bagging_fraction=0.9, feature_fraction=0.9, reg_lambda=0.2)\r\n\r\n model.fit(data[zhe]['train'][:, :-1], data[zhe]['train'][:, -1])\r\n # 注意存储验证数据集结果和预测数据集结果的不同\r\n # 训练数据集的预测结果\r\n xul = model.predict(data[zhe]['train'][:, :-1])\r\n # 验证的预测结果\r\n yanre = model.predict(data[zhe]['test'][:, :-1])\r\n # 预测的预测结果\r\n prer = model.predict(data['predict'][:, :-1])\r\n yanzhenglist += list(yanre)\r\n yanzhenglist_real += list(data[zhe]['test'][:, -1])\r\n prelist.append(prer)\r\n # 每计算一折后,要计算训练、验证、预测数据的误差\r\n xx = self.F1(xul, data[zhe]['train'][:, -1])\r\n yy = self.F1(yanre, data[zhe]['test'][:, -1])\r\n pp = self.F1(prer, data['predict'][:, -1])\r\n errorlsit.append([xx, yy, pp])\r\n # 针对预测数据集的预测结果计算均值\r\n meanPre = np.mean(np.array(prelist), axis=0)\r\n # 开始结合\r\n self.yanzhneg_pr.append(yanzhenglist)\r\n self.yanzhneg_real = yanzhenglist_real\r\n self.predi.append(meanPre)\r\n self.preal = data['predict'][:, -1]\r\n # 储存误差\r\n self.error_dict['LightGBM'] = np.mean(np.array(errorlsit), axis=0)\r\n\r\n return print('1层中的LightGBM运行完毕')\r\n\r\n # XGBoost\r\n def XGBoost_First(self, data, max_depth=5, n_estimators=320):\r\n # 存储每一折中验证数据集的预测结果\r\n yanzhenglist = []\r\n # 存储每一折中验证数据集的真实结果\r\n yanzhenglist_real = []\r\n # 存储每一折中预测数据集的预测结果\r\n prelist = []\r\n # 存储训练、验证、预测数据的误差\r\n errorlsit = []\r\n # 开始每一折的训练\r\n for zhe in [zheshu for zheshu in data.keys() if zheshu != 'predict']:\r\n model = xgb.XGBClassifier(max_depth=max_depth, learning_rate=0.1, n_estimators=n_estimators,\r\n silent=True, objective='binary:logistic', booster='gbtree')\r\n model.fit(data[zhe]['train'][:, :-1], data[zhe]['train'][:, -1])\r\n # 注意存储验证数据集结果和预测数据集结果的不同\r\n # 训练数据集的预测结果\r\n xul = model.predict(data[zhe]['train'][:, :-1])\r\n # 验证的预测结果\r\n yanre = model.predict(data[zhe]['test'][:, :-1])\r\n # 预测的预测结果\r\n prer = model.predict(data['predict'][:, :-1])\r\n yanzhenglist += list(yanre)\r\n yanzhenglist_real += list(data[zhe]['test'][:, -1])\r\n prelist.append(prer)\r\n # 每计算一折后,要计算训练、验证、预测数据的误差\r\n xx = self.F1(xul, data[zhe]['train'][:, -1])\r\n yy = self.F1(yanre, data[zhe]['test'][:, -1])\r\n pp = self.F1(prer, data['predict'][:, -1])\r\n errorlsit.append([xx, yy, pp])\r\n # 针对预测数据集的预测结果计算均值\r\n meanPre = np.mean(np.array(prelist), axis=0)\r\n # 开始结合\r\n self.yanzhneg_pr.append(yanzhenglist)\r\n self.yanzhneg_real = yanzhenglist_real\r\n self.predi.append(meanPre)\r\n self.preal = data['predict'][:, -1]\r\n # 储存误差\r\n self.error_dict['XGBoost'] = np.mean(np.array(errorlsit), axis=0)\r\n return print('1层中的XGBoost运行完毕')\r\n\r\n # CatBoost\r\n def CatBoost_First(self, data, catsign, depth=7, iterations=200):\r\n\r\n # 存储每一折中验证数据集的预测结果\r\n yanzhenglist = []\r\n # 存储每一折中验证数据集的真实结果\r\n yanzhenglist_real = []\r\n # 存储每一折中预测数据集的预测结果\r\n prelist = []\r\n # 存储训练、验证、预测数据的误差\r\n errorlsit = []\r\n # 开始每一折的训练\r\n for zhe in [zheshu for zheshu in data.keys() if zheshu != 'predict']:\r\n model = cb.CatBoostClassifier(iterations=iterations, depth=depth, learning_rate=0.5,\r\n loss_function='Logloss',\r\n logging_level='Verbose')\r\n\r\n model.fit(data[zhe]['train'][:, :-1], data[zhe]['train'][:, -1], cat_features=catsign)\r\n # 注意存储验证数据集结果和预测数据集结果的不同\r\n # 训练数据集的预测结果\r\n xul = model.predict(data[zhe]['train'][:, :-1])\r\n # 验证的预测结果\r\n yanre = model.predict(data[zhe]['test'][:, :-1])\r\n # 预测的预测结果\r\n prer = model.predict(data['predict'][:, :-1])\r\n yanzhenglist += list(yanre)\r\n yanzhenglist_real += list(data[zhe]['test'][:, -1])\r\n prelist.append(prer)\r\n # 每计算一折后,要计算训练、验证、预测数据的误差\r\n xx = self.F1(xul, data[zhe]['train'][:, -1])\r\n yy = self.F1(yanre, data[zhe]['test'][:, -1])\r\n pp = self.F1(prer, data['predict'][:, -1])\r\n errorlsit.append([xx, yy, pp])\r\n # 针对预测数据集的预测结果计算均值\r\n meanPre = np.mean(np.array(prelist), axis=0)\r\n # 开始结合\r\n self.yanzhneg_pr.append(yanzhenglist)\r\n self.yanzhneg_real = yanzhenglist_real\r\n self.predi.append(meanPre)\r\n self.preal = data['predict'][:, -1]\r\n # 储存误差\r\n self.error_dict['CatBoost'] = np.mean(np.array(errorlsit), axis=0)\r\n return print('1层中的CatBoost运行完毕')\r\n\r\n'''\r\n第三部分:第二层的模型运行阶段 可以任意更换模型\r\n'''\r\nclass MODETWO:\r\n\r\n def __init__(self, in_tr_data, out_tr_data, in_pre_data, out_pre):\r\n self.xdata = in_tr_data\r\n self.ydata = out_tr_data\r\n\r\n self.xdatapre = in_pre_data\r\n self.ydapre = out_pre\r\n\r\n\r\n\r\n # BP神经网络回归\r\n def BP(self, hiddenlayers=3, hiddennodes=100, learn_rate=0.02,\r\n itertimes=30000, batch_size=50, activate_func='tanh'):\r\n *guocheng, zuiyou, hiss = bp.Ten_train(self.xdata, self.ydata, self.xdatapre,\r\n self.ydapre, hiddenlayers=hiddenlayers,\r\n hiddennodes=hiddennodes, learn_rate=learn_rate,\r\n itertimes=itertimes, batch_size=batch_size, activate_func=activate_func)\r\n\r\n return guocheng, zuiyou, hiss\r\n\r\n'''\r\n第四部分:绘制图,绘制第一层各个模型中训练,验证数据的误差,\r\n以及最终的预测数据的真实值和误差值的对比\r\n'''\r\n# 定义绘制第一层模型训练、验证、预测数据的F1度量的函数\r\n# 根据字典绘制不同参数下评分的对比柱状图\r\ndef Plot_RMSE_ONE_Stacking(exdict, kaudu=0.2):\r\n '''\r\n :param exdict: 不同模型F1度量\r\n :return: 柱状图\r\n '''\r\n # 参数组合列表\r\n palist = exdict.keys()\r\n # 对应的训练数据的评分\r\n trsore = [exdict[hh][0] for hh in palist]\r\n # 对应的测试数据的评分\r\n tesore = [exdict[hh][1] for hh in palist]\r\n # 对应的预测数据的评分\r\n presore = [exdict[hh][2] for hh in palist]\r\n\r\n # 开始绘制柱状图\r\n fig, ax = plt.subplots()\r\n # 柱的个数\r\n ind = np.array(list(range(len(trsore))))\r\n # 绘制柱状\r\n ax.bar(ind - kaudu, trsore, kaudu, color='SkyBlue', label='训练')\r\n ax.bar(ind, tesore, kaudu, color='IndianRed', label='测试')\r\n ax.bar(ind + kaudu, presore, kaudu, color='slateblue', label='预测')\r\n # xy轴的标签\r\n ax.set_ylabel('召回率')\r\n ax.set_xlabel('Stacking第一层中的模型')\r\n # 设置刻度\r\n ax.set_xticks(ind)\r\n ax.set_xticklabels(palist)\r\n\r\n leg = ax.legend(loc='best', ncol=3, shadow=True, fancybox=True)\r\n leg.get_frame().set_alpha(0.8)\r\n\r\n plt.title('Stacking第一层中模型的召回率')\r\n plt.savefig(r'C:\\Users\\GWT9\\Desktop\\Stacking_adult.jpg')\r\n\r\n return print('一层不同模型对比')\r\n\r\n\r\n# 绘制每一次迭代过程中的训练、验证的误差以及正确率\r\n\r\ndef plotcurve(bpnn):\r\n # 绘制训练数据集与验证数据集的正确率以及误差曲线\r\n fig, ax1 = plt.subplots()\r\n ax1.set_xlabel('代数')\r\n ax1.set_ylabel('误差', color='r')\r\n plt.plot(list(range(len(bpnn[0]))), bpnn[0], label='训练', color='r', marker='*', linewidth=2)\r\n plt.plot(list(range(len(bpnn[1]))), bpnn[1], label='验证', color='r', marker='.', linewidth=2)\r\n ax1.tick_params(axis='y', labelcolor='r')\r\n legend = ax1.legend(loc='upper center', shadow=True, fontsize='x-large')\r\n legend.get_frame().set_facecolor('#F0F8FF')\r\n ax1.grid(True)\r\n\r\n ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\r\n\r\n ax2.set_ylabel('正确率', color='b') # we already handled the x-label with ax1\r\n plt.plot(list(range(len(bpnn[2]))), bpnn[2], label='训练', color='b', marker='*', linewidth=2)\r\n plt.plot(list(range(len(bpnn[3]))), bpnn[3], label='验证', color='b', marker='.', linewidth=2)\r\n ax2.tick_params(axis='y', labelcolor='b')\r\n legen = ax2.legend(loc='lower center', shadow=True, fontsize='x-large')\r\n legen.get_frame().set_facecolor('#FFFAFA')\r\n ax2.grid(True)\r\n ax2.yaxis.set_major_locator(y_toge)\r\n ax2.yaxis.set_minor_locator(y_son)\r\n\r\n fig.tight_layout() # otherwise the right y-label is slightly clipped\r\n plt.title('训练VS验证结果对比', fontsize=16)\r\n\r\n plt.savefig(r'C:\\Users\\GWT9\\Desktop\\stacking_guo.jpg')\r\n\r\n\r\n return print('过程绘图完毕')\r\n\r\n'''\r\n第五部分:Stacking主函数\r\n'''\r\n\r\nif __name__ == \"__main__\":\r\n # 第一层6个模型:随机森林,AdaBoost,GBDT,LightGBM,XGBoost,CatBoost\r\n\r\n # 下面依次为每个模型建立数据\r\n # 随机森林、AdaBoost,GBDT,LIghtGNM,XGBoost都是一样的\r\n rf_data = DATA()\r\n rf_data.CAtoDI() # 标签数字化\r\n data_rf = rf_data.Kfold() # 折数\r\n\r\n\r\n # CatBoost\r\n cat_data = DATA() # 不用处理\r\n cat_data.TargetoDi() # 需要将目标字段数字化\r\n data_cat = cat_data.Kfold() # 折数\r\n\r\n\r\n # 开始建立Stacking第一层的模型\r\n one_stacking = MODELONE(exdict=rf_data.typedict)\r\n # 随机森林\r\n one_stacking.RF_First(data_rf)\r\n # AdaBoost\r\n one_stacking.Adaboost_First(data_rf)\r\n # GBDT\r\n one_stacking.GBDT_First(data_rf)\r\n # LightGBM\r\n one_stacking.LightGBM_First(data_rf)\r\n # XGBoost\r\n one_stacking.XGBoost_First(data_rf)\r\n # CatBoost\r\n one_stacking.CatBoost_First(data_cat, cat_data.catsign)\r\n\r\n # 第二层的数据准备\r\n one_stacking.DataStru()\r\n data_two = one_stacking.datai\r\n\r\n # 第二层的数据处理\r\n erce_data = DATA(datadict=data_two)\r\n erce_data.CAtoDI() # 因为输出的都是类别,因此要标签化\r\n erce_data.Normal()\r\n erce_data.OneH() # 训练的输出独热化处理\r\n # 为了获得更好的模型,在这里设置验证数据,\r\n bpdatadict = erce_data.Kfold() # 为了简便,不再进行交叉验证获得最佳的参数\r\n\r\n # 第二层建模,\r\n stacking_two = MODETWO(bpdatadict[0]['train'][:, :-1],\r\n np.array(list(bpdatadict[0]['train'][:, -1])),\r\n bpdatadict[0]['test'][:, :-1],\r\n np.array(list(bpdatadict[0]['test'][:, -1])))\r\n\r\n # 训练的输出值,预测的输出值, 每一次迭代训练和预测的误差\r\n error_acc, signi, gir = stacking_two.BP()\r\n\r\n # 训练完成后读取最优的参数,在计算最终的预测结果\r\n graph = tf.train.import_meta_graph(r'E:\\tensorflow_Learn\\Stacking\\adult\\model-%s.meta' % signi)\r\n ses = tf.Session()\r\n graph.restore(ses, tf.train.latest_checkpoint(r'E:\\tensorflow_Learn\\Stacking\\adult'))\r\n op_to_restore = tf.get_default_graph().get_tensor_by_name(\"Add_%s:0\" % gir)\r\n w1 = tf.get_default_graph().get_tensor_by_name(\"x_data:0\")\r\n feed_dict = {w1: bpdatadict['predict'][:, :-1]}\r\n dgsio = ses.run(op_to_restore, feed_dict)\r\n\r\n # 将输出的结果转变为数字化的类别,然后再转化为真实的类别,输出混淆矩阵\r\n bp_out_type = one_stacking.MTae(bp.judge(dgsio))\r\n bp_real_type = one_stacking.AntiTae(bpdatadict['predict'][:, -1])\r\n\r\n # 绘制第一层中各个模型的误差图\r\n Plot_RMSE_ONE_Stacking(one_stacking.error_dict)\r\n # 绘制第二层模型中的训练和预测误差\r\n plotcurve(error_acc)\r\n\r\n fru = one_stacking.ConfuseMatrix(bp_real_type, bp_out_type)\r\n\r\n\r\n\r\n","repo_name":"Anfany/Machine-Learning-for-Beginner-by-Python3","sub_path":"Stacking/Stacking_Classify_adult.py","file_name":"Stacking_Classify_adult.py","file_ext":"py","file_size_in_byte":32755,"program_lang":"python","lang":"en","doc_type":"code","stars":405,"dataset":"github-code","pt":"3"}
+{"seq_id":"26093718960","text":"import imutils\nimport cv2\nimport os\nimport argparse\nimport numpy as np\nimport math\nimport time\nREJECT_DEGREE_TH = 4.0\ndef FilterLines(Lines):\n FinalLines = []\n\n for Line in Lines:\n [[x1, y1, x2, y2]] = Line\n\n # Calculating equation of the line: y = mx + c\n if x1 != x2:\n m = (y2 - y1) / (x2 - x1)\n else:\n m = 100000000\n c = y2 - m*x2\n # theta will contain values between -90 -> +90.\n theta = math.degrees(math.atan(m))\n\n # Rejecting lines of slope near to 0 degree or 90 degree and storing others\n if REJECT_DEGREE_TH <= abs(theta) <= (90 - REJECT_DEGREE_TH):\n l = math.sqrt( (y2 - y1)**2 + (x2 - x1)**2 ) # length of the line\n FinalLines.append([x1, y1, x2, y2, m, c, l])\n\n\n # Removing extra lines\n # (we might get many lines, so we are going to take only longest 15 lines\n # for further computation because more than this number of lines will only\n # contribute towards slowing down of our algo.)\n if len(FinalLines) > 15:\n FinalLines = sorted(FinalLines, key=lambda x: x[-1], reverse=True)\n FinalLines = FinalLines[:15]\n\n return FinalLines\n\n\n\ndef GetLines(Image):\n # Converting to grayscale\n GrayImage = cv2.cvtColor(Image, cv2.COLOR_BGR2GRAY)\n # Blurring image to reduce noise.\n BlurGrayImage = cv2.GaussianBlur(GrayImage, (5, 5), 1)\n # Generating Edge image\n EdgeImage = cv2.Canny(BlurGrayImage, 40, 255)\n\n # Finding Lines in the image\n Lines = cv2.HoughLinesP(EdgeImage, 1, np.pi / 180, 50, 10, 15)\n\n # Check if lines found and exit if not.\n if Lines is None:\n print(\"Not enough lines found in the image for Vanishing Point detection.\")\n exit(0)\n\n # Filtering Lines wrt angle\n FilteredLines = FilterLines(Lines)\n\n return FilteredLines\n\n\ndef GetVanishingPoint(Lines):\n # We will apply RANSAC inspired algorithm for this. We will take combination\n # of 2 lines one by one, find their intersection point, and calculate the\n # total error(loss) of that point. Error of the point means root of sum of\n # squares of distance of that point from each line.\n VanishingPoint = None\n MinError = 100000000000\n\n for i in range(len(Lines)):\n for j in range(i+1, len(Lines)):\n m1, c1 = Lines[i][4], Lines[i][5]\n m2, c2 = Lines[j][4], Lines[j][5]\n\n if m1 != m2:\n x0 = (c1 - c2) / (m2 - m1)\n y0 = m1 * x0 + c1\n\n err = 0\n for k in range(len(Lines)):\n m, c = Lines[k][4], Lines[k][5]\n m_ = (-1 / m)\n c_ = y0 - m_ * x0\n\n x_ = (c - c_) / (m_ - m)\n y_ = m_ * x_ + c_\n\n l = math.sqrt((y_ - y0)**2 + (x_ - x0)**2)\n\n err += l**2\n\n err = math.sqrt(err)\n\n if MinError > err:\n MinError = err\n VanishingPoint = [x0, y0]\n\n return VanishingPoint\n\ndef find_and_draw_lanes(frame):\n # Step 4: Gaussian Blur\n frame1=cv2.bitwise_not(frame)\n lower_limit = np.array([180, 180, 180], dtype = \"uint8\") # lower limit of blue color\n upper_limit = np.array([255, 255, 255], dtype=\"uint8\") # upper limit of blue color\n mask = cv2.inRange(frame1, lower_limit, upper_limit) # this mask will filter out everything but blue\n lower=100\n upper=200\n aperture_size = 5\n L2Grad = True\n # detect edges\n edges = cv2.Canny(mask, lower, upper)\n # cv2_imshow(edges)\n # Step 5: Canny Edge Detection\n height, width = frame.shape[:2]\n Lines = GetLines(cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR))\n # Get vanishing point\n roi_vertices = [(0, height), (0,height/2),(width, height/2), (width, height)]\n if len(Lines)>2:\n VanishingPoint = GetVanishingPoint(Lines)\n VanishingPoint[1]=min(height/2,VanishingPoint[1])\n # Drawing lines and vanishing point\n # for Line in Lines:\n # cv2.line(frame, (Line[0], Line[1]), (Line[2], Line[3]), (0, 255, 0), 2)\n cv2.circle(frame, (int(VanishingPoint[0]), int(VanishingPoint[1])), 10, (0, 0, 255), -1)\n # roi_vertices = [(0, height), (0,),(width/2, 0), (width, height)]\n # roi_vertices = [(10, height), (10,height/3),(width-10, height/3), (width-10, height)]\n roi_vertices = [(10, height), (10,int(VanishingPoint[1])),(width-10, int(VanishingPoint[1])), (width-10, height)]\n mask_color = 255\n mask = np.zeros_like(edges)\n cv2.fillPoly(mask, np.array([roi_vertices], dtype=np.int32), mask_color)\n masked_edges = cv2.bitwise_and(edges, mask)\n # cv2.imshow(\"masked_edges\",mask)\n # Step 6: Region of Interest\n lines = cv2.HoughLinesP(masked_edges, rho=6, theta=np.pi/60, threshold=160, minLineLength=40, maxLineGap=25)\n # Step 7: Hough Transform\n line_image = np.zeros_like(frame)\n if (lines is not None) and len(lines)>2:\n for line in lines:\n x1, y1, x2, y2 = line[0]\n cv2.line(line_image, (x1, y1), (x2, y2), (0, 255, 0), 5)\n # Step 8: Drawing the Lines\n final_image = cv2.addWeighted(frame, 0.8, line_image, 1, 0)\n return final_image,lines\n\n\n\ndef average_slope_intercept(frame, line_segments):\n lane_lines = []\n\n if line_segments is None:\n print(\"no line segment detected\")\n return lane_lines\n\n height, width,_ = frame.shape\n left_fit = []\n right_fit = []\n boundary = 0.5\n\n left_region_boundary = width * (1 - boundary) \n right_region_boundary = width * boundary \n\n for line_segment in line_segments:\n for x1, y1, x2, y2 in line_segment:\n if x1 == x2:\n print(\"skipping vertical lines (slope = infinity)\")\n continue\n\n fit = np.polyfit((x1, x2), (y1, y2), 1)\n slope = (y2 - y1) / (x2 - x1)\n intercept = y1 - (slope * x1)\n\n if slope < 0:\n if x1 < left_region_boundary and x2 < left_region_boundary:\n left_fit.append((slope, intercept))\n else:\n if x1 > right_region_boundary and x2 > right_region_boundary:\n right_fit.append((slope, intercept))\n\n left_fit_average = np.average(left_fit, axis=0)\n if len(left_fit) > 0:\n lane_lines.append(make_points(frame, left_fit_average))\n\n right_fit_average = np.average(right_fit, axis=0)\n if len(right_fit) > 0:\n lane_lines.append(make_points(frame, right_fit_average))\n\n # lane_lines is a 2-D array consisting the coordinates of the right and left lane lines\n # for example: lane_lines = [[x1,y1,x2,y2],[x1,y1,x2,y2]]\n # where the left array is for left lane and the right array is for right lane \n # all coordinate points are in pixels\n return lane_lines\n\ndef make_points(frame, line):\n height, width, _ = frame.shape\n slope, intercept = line\n y1 = height # bottom of the frame\n y2 = int(y1 / 2) # make points from middle of the frame down\n\n if slope == 0:\n slope = 0.1 \n\n x1 = int((y1 - intercept) / slope)\n x2 = int((y2 - intercept) / slope)\n\n return [[x1, y1, x2, y2]]\n\ndef display_lines(frame, lines, line_color=(0, 255, 0), line_width=6): # line color (B,G,R)\n line_image = np.zeros_like(frame)\n\n if lines is not None:\n for line in lines:\n for x1, y1, x2, y2 in line:\n cv2.line(line_image, (x1, y1), (x2, y2), line_color, line_width)\n\n line_image = cv2.addWeighted(frame, 0.8, line_image, 1, 1) \n return line_image\n\ndef get_steering_angle(frame, lane_lines):\n height, width, _ = frame.shape\n if (len(lane_lines) == 2): # if two lane lines are detected\n _, _, left_x2, _ = lane_lines[0][0] # extract left x2 from lane_lines array\n _, _, right_x2, _ = lane_lines[1][0] # extract right x2 from lane_lines array\n mid = int(width / 2)\n x_offset = (left_x2 + right_x2) / 2 - mid\n y_offset = int(height / 2) \n elif (len(lane_lines) == 1):\n x1, _, x2, _ = lane_lines[0][0]\n x_offset = x2 - x1\n y_offset = int(height / 2)\n elif (len(lane_lines) == 0): # if no line is detected\n x_offset = 0\n y_offset = int(height / 2)\n\n angle_to_mid_radian = math.atan(x_offset / y_offset)\n angle_to_mid_deg = int(angle_to_mid_radian * 180.0 / math.pi) \n steering_angle = angle_to_mid_deg + 90 \n\n return steering_angle\n\ndef display_heading_line(frame, steering_angle, line_color=(0, 0, 255), line_width=5 ):\n\n heading_image = np.zeros_like(frame)\n height, width, _ = frame.shape\n\n steering_angle_radian = steering_angle / 180.0 * math.pi\n x1 = int(width / 2)\n y1 = height\n x2 = int(x1 - height / 2 / math.tan(steering_angle_radian))\n y2 = int(height / 2)\n\n cv2.line(heading_image, (x1, y1), (x2, y2), line_color, line_width)\n\n heading_image = cv2.addWeighted(frame, 0.8, heading_image, 1, 1)\n\n return heading_image\n \ndef publish_message():\n \n # Node is publishing to the video_frames topic using \n # the message type Image\n \n # Create a VideoCapture object\n # The argument '0' gets the default webcam.\n cap = cv2.VideoCapture(\"basicvideo_long.avi\")\n cap = cv2.VideoCapture(\"vid.mp4\")\n ret=True\n # While ROS is still running.\n while ret:\n \n # Capture frame-by-frame\n # This method returns True/False as well\n # as the video frame.\n ret, frame = cap.read()\n \n if ret == True:\n start = time.time()\n # Print debugging information to the terminal\n # frame = cv2.flip(frame,-1)\n\n #Calling the functions\n frame,line_segments=find_and_draw_lanes(frame)\n lane_lines = average_slope_intercept(frame,line_segments)\n lane_lines_image = display_lines(frame,lane_lines)\n # cv2.imshow(\"heading_image\",lane_lines_image)\n steering_angle = get_steering_angle(frame, lane_lines)\n heading_image = display_heading_line(lane_lines_image,steering_angle)\n end = time.time()\n print(end - start)\n # cv2.imshow(\"heading_image\",heading_image)\n cv2.waitKey(0)\n\nif __name__ == '__main__':\n publish_message()\n","repo_name":"JayanthAkash/copy_dummy","sub_path":"lane.py","file_name":"lane.py","file_ext":"py","file_size_in_byte":10191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18566259593","text":"import logging\nfrom panduza import Core, Client\n\n# logging.basicConfig(level=logging.DEBUG)\n\nCore.LoadAliases({\n \"local\": {\n \"url\": \"localhost\",\n \"port\": 1883,\n \"interfaces\": {}\n }\n})\n\nclient = Client(broker_alias=\"local\")\nclient.connect()\ninterfaces = client.scan_interfaces()\n\nfor iface in interfaces:\n print(f\"\\t- {iface} [{interfaces[iface]}]\")\n\n","repo_name":"Panduza/panduza-py","sub_path":"client/tools/interface_scanner.py","file_name":"interface_scanner.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"}
+{"seq_id":"40335644040","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\"\"\n #set pointers\n a = headA\n b = headB\n #loop while they dont intersect\n while a != b:\n a = a.next if a else headB \n # move a to the next value in a list. \n # If you hit the end move the pointer to the b list\n\n b = b.next if b else headA # same for b\n\n # Eventually the two pointers will meet at the intersection ending the loop\n # and returning the intersection point.\n\n return a\n","repo_name":"bryce-guglietti/leetcodeSolutions","sub_path":"getIntersectionNode.py","file_name":"getIntersectionNode.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29916249222","text":"from pathlib import Path\nimport moderngl\nimport numpy as np\nfrom pyrr import Matrix44\nfrom time import perf_counter_ns\nimport configparser\nfrom base import CameraWindow\n\nconfig_file = \"config.ini\"\nconfig = configparser.ConfigParser()\nconfig.read(config_file)\n\n\nclass Timer:\n def __init__(self):\n self.history = []\n self.start = 0\n\n def __enter__(self):\n self.start = perf_counter_ns()\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.history.append(perf_counter_ns() - self.start)\n\n def avg_time(self):\n if len(self.history) == 0:\n return -1.0\n return sum(self.history) / len(self.history)\n\n def __repr__(self):\n return f\"Average time taken: {self.avg_time() / 1e9:.3f}s ({self.avg_time():.1f}ns)\"\n\n def reset(self):\n self.history = []\n\n\nclass Player:\n def __init__(self, x, y, z):\n self._position = np.array([x, y, z], dtype=int)\n self._position_xz = np.array([x, z], dtype=int)\n\n self._chunk_size = float(config[\"WORLD\"][\"chunk_size\"])\n\n @property\n def chunk_position(self) -> np.ndarray:\n return self.chunk * self._chunk_size\n\n @property\n def chunk(self) -> np.ndarray:\n return self._position_xz // self._chunk_size\n\n @property\n def position(self) -> np.ndarray:\n return self._position\n\n @position.setter\n def position(self, xyz: np.ndarray):\n self._position[:] = xyz\n self._position_xz[:] = (xyz[0], xyz[2])\n\n @property\n def x(self):\n return self.position[0]\n\n @property\n def y(self):\n return self.position[1]\n\n @property\n def z(self):\n return self.position[2]\n\n def move(self, x: int = 0, y: int = 0, z: int = 0):\n self._position += (x, y, z)\n self._position_xz += (x, z)\n\n\n# class TerrainTest(OrbitCameraWindow):\nclass TerrainTest(CameraWindow):\n # moderngl_window settings\n gl_version = (3, 3)\n title = \"terrain_test\"\n resource_dir = (Path(__file__).parent / \"resources\").resolve()\n aspect_ratio = None\n window_size = 1280, 720\n resizable = True\n samples = 0\n clear_color = 51 / 255, 51 / 255, 51 / 255\n\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs)\n\n self.chunk_size = int(config[\"WORLD\"][\"chunk_size\"])\n self.seed = int(config[\"WORLD\"][\"seed\"])\n self.N = self.chunk_size ** 3\n\n self.show_id = False\n\n self.player = Player(\n int(config[\"PLAYER\"][\"x\"]),\n int(config[\"PLAYER\"][\"y\"]),\n int(config[\"PLAYER\"][\"z\"]),\n )\n self.camera.set_position(self.player.x, self.player.y, self.player.z)\n\n self.render_distance = int(config[\"WORLD\"][\"render_distance\"])\n # make sure render_distance is odd, 32 -> 33, 33 -> 33\n self.render_distance += not self.render_distance % 2\n\n self.last_player_chunk = self.player.chunk.copy()\n # load programs\n self.terrain_generation_program = self.load_program(\n \"programs/terrain_generation.glsl\"\n )\n self.cube_emit_program = self.load_program(\n vertex_shader=\"programs/cube_geometry_vs.glsl\",\n geometry_shader=\"programs/cube_geometry_geo.glsl\",\n )\n\n self.test_render_program = self.load_program(\"programs/test.glsl\")\n\n self.cube_emit_program[\"chunk_size\"] = self.chunk_size\n\n self.terrain_generation_program[\"seed\"] = self.seed\n self.terrain_generation_program[\"scale\"] = 0.01\n self.terrain_generation_program[\"amplitude\"] = self.chunk_size\n self.terrain_generation_program[\"chunk_size\"] = self.chunk_size\n self.terrain_generation_program[\"offset\"] = (0.0, 0.0, 0.0)\n\n self.test_render_program[\"m_proj\"].write(self.camera.projection.matrix)\n self.test_render_program[\"m_model\"].write(Matrix44.identity(dtype=\"f4\"))\n\n # create buffers and VAOs\n self.terrain_gen_out_buffer = self.ctx.buffer(reserve=self.N * 4)\n\n # since we dont use indirect rendering we need one buffer per vao, so lets create them\n chunk_buffers = []\n self.chunk_ids = dict()\n for y in range(self.render_distance):\n for x in range(self.render_distance):\n buf = self.ctx.buffer(reserve=int(4 * 3 * 12 * 6 * self.N * 0.07))\n chunk_buffers.append(buf)\n self.chunk_ids[buf.glo] = x + y * self.render_distance\n self.chunk_buffers = np.array(chunk_buffers).reshape(\n (self.render_distance, self.render_distance)\n )\n # VAO's\n self.terrain_generator = self.ctx.vertex_array(\n self.terrain_generation_program, []\n )\n self.geometry_vao = self.ctx.vertex_array(\n self.cube_emit_program, [(self.terrain_gen_out_buffer, \"i\", \"in_block\")]\n )\n # no indirect rendering for now.. so we just create a bunch of vaos\n self.rendering_vaos = [\n self.ctx.vertex_array(\n self.test_render_program,\n [(self.chunk_buffers[x, y], \"3f4 3f4\", \"in_normal\", \"in_position\")],\n )\n for x in range(self.render_distance)\n for y in range(self.render_distance)\n ]\n # number of vertices for each vao/buffer\n self.num_vertices = [0] * self.render_distance ** 2\n # position of chunks, used for placing the frustrum culling primitive\n self.chunk_positions = [(0, 0, 0)] * self.render_distance ** 2\n # Texture\n self.world_texture = self.ctx.texture(\n (self.N, self.render_distance ** 2), alignment=4, dtype=\"i4\", components=1\n )\n\n self.q = self.ctx.query(primitives=True)\n self.avg_timer = Timer()\n # generate some initial chunks\n print(f\"generating chunks around {self.player.position}\")\n self.generate_surrounding_chunks(self.player.position)\n\n def update_surrounding_chunks(self, x_offset, y_offset, player_pos):\n def unique_elements(my_list):\n unique = []\n for element in my_list:\n if element not in unique:\n unique.append(element)\n return unique\n\n buffers_to_replace = []\n world_positions = []\n\n half_render_dst = int((self.render_distance - 1) / 2)\n chunk_x = self.player.chunk_position[0]\n chunk_y = self.player.chunk_position[1]\n\n if x_offset == 1: # shift to the right\n # buffers_to_replace.extend(self.chunk_buffers[:, -1])\n self.chunk_buffers = np.roll(self.chunk_buffers, -1, axis=1)\n buffers_to_replace.extend(self.chunk_buffers[:, -1])\n\n world_positions.extend(\n [\n (\n chunk_x + half_render_dst * self.chunk_size,\n 0.0,\n chunk_y + self.chunk_size * (y - half_render_dst),\n )\n for y in reversed(range(self.render_distance))\n ]\n )\n\n if x_offset == -1: # shift to the left\n # buffers_to_replace.extend(self.chunk_buffers[:, 0])\n self.chunk_buffers = np.roll(self.chunk_buffers, 1, axis=1)\n buffers_to_replace.extend(self.chunk_buffers[:, 0])\n\n world_positions.extend(\n [\n (\n chunk_x - half_render_dst * self.chunk_size,\n 0.0,\n chunk_y + self.chunk_size * (y - half_render_dst),\n )\n for y in reversed(range(self.render_distance))\n ]\n )\n\n if y_offset == -1: # shift down\n self.chunk_buffers = np.roll(self.chunk_buffers, -1, axis=0)\n buffers_to_replace.extend(self.chunk_buffers[-1, :])\n\n world_positions.extend(\n [\n (\n chunk_x + self.chunk_size * (y - half_render_dst),\n 0.0,\n chunk_y - half_render_dst * self.chunk_size,\n )\n for y in range(self.render_distance)\n ]\n )\n\n if y_offset == 1: # shift up\n self.chunk_buffers = np.roll(self.chunk_buffers, 1, axis=0)\n buffers_to_replace.extend(self.chunk_buffers[0, :])\n\n world_positions.extend(\n [\n (\n chunk_x + self.chunk_size * (y - half_render_dst),\n 0.0,\n chunk_y + half_render_dst * self.chunk_size,\n )\n for y in range(self.render_distance)\n ]\n )\n\n buffers_to_replace = unique_elements(buffers_to_replace)\n world_positions = unique_elements(world_positions)\n\n for world_pos, buffer in zip(world_positions, buffers_to_replace):\n # print(f\"generating chunk {buffer} @ {world_pos}\")\n self.generate_chunk(buffer, world_pos)\n # print(\"done shifting\")\n\n def generate_surrounding_chunks(self, pos):\n for y in range(self.render_distance):\n for x in range(self.render_distance):\n self.generate_chunk(\n self.chunk_buffers[-x, -y],\n (\n (x - self.render_distance // 2) * self.chunk_size + pos[0],\n 0,\n (y - self.render_distance // 2) * self.chunk_size + pos[2],\n ),\n )\n\n def generate_chunk(self, out_buffer, world_pos):\n # world_pos actual world position to write to [-inf, inf] in voxel space not chunk space\n # chunk_id = x + y * self.render_distance\n # out_buffer = self.chunk_buffers[chunk_id]\n chunk_id = self.chunk_ids[out_buffer.glo]\n\n self.terrain_generation_program[\"offset\"] = world_pos\n self.terrain_generator.transform(\n self.terrain_gen_out_buffer, mode=moderngl.POINTS, vertices=self.N\n )\n\n self.world_texture.write(\n self.terrain_gen_out_buffer.read(), viewport=(0, chunk_id, self.N, 1)\n )\n\n self.cube_emit_program[\"chunk_id\"] = chunk_id\n self.cube_emit_program[\"chunk_pos\"] = world_pos\n self.world_texture.use(0)\n with self.q:\n self.geometry_vao.transform(out_buffer, mode=moderngl.POINTS)\n\n self.num_vertices[chunk_id] = self.q.primitives * 3\n self.chunk_positions[chunk_id] = world_pos\n\n def render(self, time: float, frame_time: float) -> None:\n # print(\"rendering\")\n self.ctx.enable_only(moderngl.DEPTH_TEST)\n\n self.player.position = self.camera.position\n\n chunk_delta = self.last_player_chunk - self.player.chunk\n if np.linalg.norm(chunk_delta) >= 1:\n self.last_player_chunk = self.player.chunk\n with self.avg_timer:\n self.update_surrounding_chunks(\n -chunk_delta[0], -chunk_delta[1], self.player.position\n )\n\n # update camera values\n self.test_render_program[\"m_camera\"].write(self.camera.matrix)\n self.test_render_program[\"m_proj\"].write(self.camera.projection.matrix)\n\n self.test_render_program[\"id\"] = -1\n\n grouped_vaos = zip(self.rendering_vaos, self.num_vertices)\n\n for vao, num_vertices in grouped_vaos:\n if self.show_id:\n self.test_render_program[\"id\"] = vao.glo\n vao.render(mode=moderngl.TRIANGLES, vertices=num_vertices)\n\n def close(self):\n print(self.avg_timer)\n # save the updated info\n config[\"PLAYER\"][\"x\"] = str(self.player.x)\n config[\"PLAYER\"][\"y\"] = str(self.player.y)\n config[\"PLAYER\"][\"z\"] = str(self.player.z)\n with open(config_file, \"w\") as f:\n config.write(f)\n\n def key_event(self, key, action, modifiers):\n super().key_event(key, action, modifiers)\n keys = self.wnd.keys\n\n if key == keys.G and action == keys.ACTION_PRESS:\n self.ctx.wireframe = not self.ctx.wireframe\n if self.ctx.wireframe:\n self.ctx.enable_only(moderngl.DEPTH_TEST)\n else:\n self.ctx.enable_only(moderngl.DEPTH_TEST | moderngl.CULL_FACE)\n\n if key == keys.F and action == keys.ACTION_PRESS:\n self.show_id = not self.show_id\n\n\nif __name__ == \"__main__\":\n TerrainTest.run()\n","repo_name":"Leterax/Voxels","sub_path":"rendering/terrain_test.py","file_name":"terrain_test.py","file_ext":"py","file_size_in_byte":12471,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"}
+{"seq_id":"37554727419","text":"import numpy as np\r\nimport os\r\nimport sys\r\nimport vgi\r\nfrom vgi.ct import createCircleMask\r\nfrom skimage.metrics import structural_similarity as ssim\r\nfrom skimage.metrics import peak_signal_noise_ratio as psnr\r\nfrom skimage.metrics import mean_squared_error as mse\r\n\r\nref_means = [0.31614921663988865, 0.35865365232842134, 0.321694478688629, 0.32748706128057975,\r\n 0.31301958852873246, 0.32856736419276633, 0.1885250101617685, 0.13090186791437852]\r\n\r\ndef meannml(data, ref_mean):\r\n data_n = vgi.normalize(data) \r\n vmean = np.mean(data_n) \r\n w = ref_mean/ vmean\r\n data_n = data_n * w\r\n #data_n = np.clip(data_n, 0.0, 1.0)\r\n return data_n\r\n\r\ndef postproc(data, mask, clip_min, clip_max, mean_align, ref_mean):\r\n if clip_min:\r\n data = np.clip(data, 0.0, data.max())\r\n if mean_align:\r\n data = meannml(data * mask, ref_mean = ref_mean) * mask \r\n else:\r\n data = vgi.normalize(data * mask) * mask\r\n if clip_max:\r\n data = np.clip(data, 0.0, 1.0) \r\n return data\r\n\r\ndef evaluate(target_dir, gt_dir, mask_ratio = 0.99, \r\n clip_min = True, clip_max = False, mean_align = True, \r\n return_all = False, ref_means = None):\r\n \r\n L_ssim = []\r\n L_mae = []\r\n L_mse = []\r\n L_psnr = []\r\n paths = vgi.getFiles(target_dir)\r\n rec_shape = None\r\n mask = None #createCircleMask(shape = rec_shape, r = 512 / 2)\r\n k = 128\r\n \r\n i = 0\r\n ref_mean = None\r\n for path in paths: \r\n _, filename, extname = vgi.parsePath(path)\r\n if extname != '.npy':\r\n continue \r\n data = np.load(path) # (images, width, height)\r\n if rec_shape is None:\r\n rec_shape = data.shape[1:] # (width, height))\r\n mask = createCircleMask(shape = rec_shape, r = rec_shape[0] / 2 * mask_ratio)\r\n \r\n gt_path = gt_dir + filename + '.npy'\r\n gt_data = np.load(gt_path) * mask\r\n\r\n if ref_means is None:\r\n ref_mean = np.mean(gt_data)\r\n else:\r\n ref_mean = ref_means[i]\r\n \r\n data = postproc(data, mask = mask, clip_min = clip_min, clip_max = clip_max, mean_align = mean_align, ref_mean = ref_mean) \r\n\r\n diff = data - gt_data\r\n v_mae = np.mean(np.abs(diff))\r\n v_mse = mse(data, gt_data) \r\n v_ssim = ssim(data, gt_data, data_range = gt_data.max() - gt_data.min())\r\n v_psnr = psnr(data, gt_data, data_range = gt_data.max() - gt_data.min())\r\n #print(path)\r\n print(v_mae, v_mse, v_ssim, v_psnr)\r\n L_mae += [v_mae]\r\n L_mse += [v_mse]\r\n L_ssim += [v_ssim]\r\n L_psnr += [v_psnr]\r\n i += 1\r\n #break\r\n L_mae = np.array(L_mae)\r\n L_mse = np.array(L_mse)\r\n L_ssim = np.array(L_ssim)\r\n L_psnr = np.array(L_psnr)\r\n\r\n if return_all:\r\n return L_mae, L_mse, L_ssim, L_psnr\r\n else:\r\n mean_mae = float(np.mean(L_mae))\r\n mean_mse = float(np.mean(L_mse))\r\n mean_ssim = float(np.mean(L_ssim))\r\n mean_psnr = float(np.mean(L_psnr))\r\n return mean_mae, mean_mse, mean_ssim, mean_psnr\r\n \r\ndef display(target_dir, gt_dir, k = 128, filenames = None, mask_ratio = 0.99,\r\n clip_min = True, clip_max = False, mean_align = True, \r\n ref_means = None, figsize = None, gt = True): \r\n paths = vgi.getFiles(target_dir)\r\n rec_shape = None\r\n mask = None #createCircleMask(shape = rec_shape, r = 512 / 2)\r\n out = []\r\n i = 0\r\n ref_mean = None\r\n for path in paths: \r\n _, filename, extname = vgi.parsePath(path)\r\n if extname != '.npy':\r\n continue \r\n if not(filenames is None) and not(filename in filenames):\r\n continue\r\n data = np.load(path) # (images, width, height)\r\n if rec_shape is None:\r\n rec_shape = data.shape[1:] # (width, height))\r\n mask = createCircleMask(shape = rec_shape, r = rec_shape[0] / 2 * mask_ratio)\r\n \r\n gt_path = gt_dir + filename + '.npy'\r\n gt_data = np.load(gt_path) * mask\r\n\r\n if not(ref_means is None):\r\n ref_mean = ref_means[i]\r\n data = postproc(data, mask = mask, clip_min = clip_min, clip_max = clip_max, mean_align = mean_align, ref_mean = ref_mean) \r\n vgi.showImage(vgi.normalize(data[k]), figsize = figsize)\r\n out += [data[k]]\r\n if gt:\r\n vgi.showImage(vgi.normalize(gt_data[k]), figsize = figsize)\r\n return out","repo_name":"jameschengcs/arusvct","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30609733841","text":"import pynput.keyboard as KEY\nimport time\nfrom threading import Thread\n\n\nclass sign_writer:\n def on_press(self, key, special=KEY.Key):\n try:\n pressed = key.char\n except AttributeError:\n pressed = key\n if pressed == special.backspace:\n pressed = \"\"\n if len(self.log) > 0:\n self.log.pop()\n elif pressed == special.space:\n pressed = \" \"\n elif pressed == special.enter:\n pressed = \"\\n\"\n elif pressed == special.shift:\n return\n else:\n return\n # pressed = str(pressed)\n\n self.log.append(pressed)\n # print(\"\".join(self.log))\n if len(self.log) > self.max_log:\n del self.log[0:self.clean_log_degree]\n\n def on_release(self, key):\n if key == self.end_key:\n # Stop listener\n return False\n\n def __init__(self, max_log=100, end_key=KEY.Key.esc, clean_log_degree=10):\n self.control = KEY.Controller()\n self.listener = KEY.Listener(on_press=self.on_press, on_release=self.on_release)\n\n self.log = []\n self.max_log = max_log\n self.clean_log_degree = clean_log_degree\n\n self.special_chr_matcher = []\n\n self.end_key = end_key\n\n def add_special_chr(self, name, sign):\n self.special_chr_matcher.append((name.replace(\"\\b\", \"\"), sign))\n\n def check_special_chr(self):\n check_str = \"\".join(self.log).lower().replace(\"\\b\", \"\")\n match_outcomes = []\n for key, val in self.special_chr_matcher:\n if check_str.endswith(key):\n match_outcomes.append((key, val))\n\n if len(match_outcomes) > 0:\n names = [outcome[0] for outcome in match_outcomes]\n result = 0\n for i in range(1, len(names)):\n if len(names[i]) > len(names[result]):\n result = i\n self.log.clear()\n return match_outcomes[result]\n return None\n\n def replace_special_chr(self, name, sign):\n length = len(name)\n self.control.type(\"\\b\" * length)\n self.control.type(sign)\n\n def init_special_chr_matcher(self):\n # add at the end of symbol names (eg. sigma_) just to make sure that\n # user is not frustrated about wanting to write \"sigma\" in english, but\n # the program keeps changing it to Σ.\n execute = \"_\"\n\n # formal language signs\n self.add_special_chr(\"sigma\" + execute, \"Σ\")\n self.add_special_chr(\"alphabet\" + execute, \"Σ\")\n self.add_special_chr(\"epsilon\" + execute, \"ε\")\n self.add_special_chr(\"null\" + execute, \"∅\")\n self.add_special_chr(\"delta\" + execute, \"δ\")\n self.add_special_chr(\"transition_function\", \"δ\")\n\n # operations\n self.add_special_chr(\"union\" + execute, \"∪\")\n self.add_special_chr(\"concat\" + execute, \"⋂\")\n # sets\n self.add_special_chr(\"element_of\", \"∈\")\n self.add_special_chr(\"subset_of\", \"⊂\")\n self.add_special_chr(\"equal_or_subset_of\", \"⊆\")\n\n # stats\n self.add_special_chr(\"pop_sd\", \"σ\")\n self.add_special_chr(\"pop_mean\", \"μ\")\n self.add_special_chr(\"sample_mean\", \"X̄\")\n\n def run(self):\n while True:\n match = self.check_special_chr()\n if match is not None:\n self.replace_special_chr(match[0], match[1])\n\n\nif __name__ == \"__main__\":\n sw = sign_writer(max_log=30)\n sw.listener.start()\n sw.init_special_chr_matcher()\n\n run_thread = Thread(target=sw.run, daemon=True)\n run_thread.start()\n sw.listener.join()\n\n","repo_name":"yonghyeon0223/pynput_control_scripts","sub_path":"shorcuts.py","file_name":"shorcuts.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13031697573","text":"from API_BINANCE.delete_api import DELETEE_API\n\nclass UTILS_FOR_ORDERS(DELETEE_API):\n\n def __init__(self) -> None:\n super().__init__() \n # print(self.URL_PATTERN_DICT) \n\n def assets_filters(self):\n top_pairs = []\n all_tickers = []\n \n exclusion_contains_list = ['UP', 'DOWN', 'RUB', 'EUR']\n all_tickers = self.get_all_tickers()\n # print(all_tickers)\n\n if all_tickers:\n usdt_filtered = [ticker for ticker in all_tickers if\n ticker['symbol'].upper().endswith('USDT') and\n not any(exclusion in ticker['symbol'].upper() for exclusion in exclusion_contains_list) and\n (float(ticker['lastPrice']) >= self.MIN_FILTER_PRICE) and (float(ticker['lastPrice']) <= self.MAX_FILTER_PRICE)]\n \n # print(usdt_filtered[0])\n\n sorted_by_volume_data = sorted(usdt_filtered, key=lambda x: float(x['quoteVolume']), reverse=True)\n sorted_by_volume_data = sorted_by_volume_data[:self.SLICE_VOLUME_PAIRS]\n\n # Filter and sort by priceChangePercent\n sorted_by_price_change_data = sorted(sorted_by_volume_data, key=lambda x: float(x['priceChangePercent']), reverse=True)\n sorted_by_price_change_data = sorted_by_price_change_data[:self.SLICE_VOLATILITY]\n\n top_pairs = [x['symbol'] for x in sorted_by_price_change_data if x['symbol'] not in self.problem_pairs]\n\n return top_pairs\n\n# utils_for_orderss = UTILS_FOR_ORDERS()\n# print(UTILS_FOR_ORDERS().URL_PATTERN_DICT)\n\n# all_tik = utils_for_orderss.assets_filters()\n# print(all_tik)\n\n# python -m API_BINANCE.utils_api\n\n\n ","repo_name":"Sonnik9/grid_assist_bot","sub_path":"API_BINANCE/utils_api.py","file_name":"utils_api.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42507950849","text":"#escreva um programa que leia um valor em metros e o exiba em cm e mm\n\nfrom typing import MutableMapping\n\n\nmetro = float(input('Insira uma distância em metros: ' ))\nkm = metro / 1000\nhm = metro / 100\ndam = metro / 10\ndm = metro * 10\ncm = metro * 100\nmm = metro * 1000\nprint('A medida quando convertida equivale a: \\n{} Km \\n{} Hm \\n{} Dam \\n{} M \\n{} Dm \\n{} Cm \\n{} Mm'.format(km, hm, dam, metro, dm, cm, mm))\n","repo_name":"Thalesamaojapa/Thales---Python","sub_path":"Exercícios_Main/Exercícios/Exercício9(ConversãoDeMedidas).py","file_name":"Exercício9(ConversãoDeMedidas).py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26846364658","text":"# 오류처리\r\n\r\n'''\r\ntry:\r\n a=[1,2,3]\r\n print(a[3])\r\n\r\nexcept IndexError as e:\r\n print(e) '''\r\n\r\ntry:\r\n f=open(\"C:/doit/try001.txt\", \"w\")\r\n data=(\"우리는 try~finally 문을 학습 중 입니다.\")\r\n f.write(data)\r\n a=[1,2]\r\n f.close()\r\n\r\nexcept ZeroDivisionError as e:\r\n print(e)\r\n\r\nfinally:\r\n f=open(\"C:/doit/try001.txt\", \"r\")\r\n data=f.read()\r\n print(data)","repo_name":"lo-lim/SMWU","sub_path":"Basic of Python Programming/.py/chapter06/except001.py","file_name":"except001.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"20079928064","text":"import multiprocessing as mp\nimport unittest\nimport unittest.mock as mock\n\nimport classy_vision.dataset.classy_dataset as classy_dataset\nimport torch\nfrom classy_vision.dataset import build_dataset, register_dataset\nfrom classy_vision.dataset.core import ListDataset\nfrom test.generic.utils import compare_batches, compare_samples\nfrom torch.utils.data import DataLoader\n\n\nDUMMY_SAMPLES_1 = [\n {\"input\": torch.tensor([[[0, 1], [2, 3]]]), \"target\": torch.tensor([[0]])}\n]\n\n\nDUMMY_SAMPLES_2 = [\n {\"input\": torch.tensor([[[0, 1], [2, 3]]]), \"target\": torch.tensor([[0]])},\n {\"input\": torch.tensor([[[4, 5], [6, 7]]]), \"target\": torch.tensor([[1]])},\n]\n\nBATCHED_DUMMY_SAMPLES_2 = [\n {\n \"input\": torch.tensor([[[[0, 1], [2, 3]]], [[[4, 5], [6, 7]]]]),\n \"target\": torch.tensor([[[0]], [[1]]]),\n }\n]\n\nDUMMY_CONFIG = {\"name\": \"test_dataset\", \"dummy0\": 0, \"dummy1\": 1}\n\nOTHER_DUMMY_CONFIG = {\"name\": \"other_test_dataset\", \"dummy0\": 0, \"dummy1\": 1}\n\n\ndef mock_get_world_size():\n return 2\n\n\ndef mock_get_rank():\n return 1\n\n\n@register_dataset(\"test_dataset\")\nclass TestDataset(classy_dataset.ClassyDataset):\n \"\"\"Test dataset for validating registry functions\"\"\"\n\n def __init__(\n self,\n samples,\n batchsize_per_replica=1,\n num_samples=None,\n shuffle=False,\n transform=None,\n ):\n input_tensors = [sample[\"input\"] for sample in samples]\n target_tensors = [sample[\"target\"] for sample in samples]\n dataset = ListDataset(input_tensors, target_tensors, loader=lambda x: x)\n super().__init__(\n dataset=dataset,\n batchsize_per_replica=batchsize_per_replica,\n shuffle=shuffle,\n transform=transform,\n num_samples=len(samples) if num_samples is None else num_samples,\n )\n\n @classmethod\n def from_config(cls, config, *args, **kwargs):\n return cls(*args, **kwargs)\n\n\n@register_dataset(\"other_test_dataset\")\nclass OtherTestDataset(classy_dataset.ClassyDataset):\n \"\"\"\n Test dataset for validating registry functions that has a different\n type than TestDataset\n \"\"\"\n\n def __init__(self, samples, batchsize_per_replica=1):\n input_tensors = [sample[\"input\"] for sample in samples]\n target_tensors = [sample[\"target\"] for sample in samples]\n dataset = ListDataset(input_tensors, target_tensors, loader=lambda x: x)\n super().__init__(\n dataset=dataset,\n batchsize_per_replica=batchsize_per_replica,\n shuffle=False,\n transform=None,\n num_samples=len(samples),\n )\n\n @classmethod\n def from_config(cls, config, *args, **kwargs):\n return cls(*args, **kwargs)\n\n\nclass TestRegistryFunctions(unittest.TestCase):\n \"\"\"\n Tests functions that use registry\n \"\"\"\n\n def test_build_model(self):\n dataset = build_dataset(DUMMY_CONFIG, DUMMY_SAMPLES_1)\n self.assertTrue(isinstance(dataset, TestDataset))\n\n\nclass TestClassyDataset(unittest.TestCase):\n \"\"\"\n Tests member functions of ClassyDataset. Note, NotImplemented\n functions are mocked in TestDataset class.\n \"\"\"\n\n def setUp(self):\n self.dataset1 = build_dataset(DUMMY_CONFIG, DUMMY_SAMPLES_1)\n self.dataset2 = build_dataset(DUMMY_CONFIG, DUMMY_SAMPLES_2)\n\n def _compare_samples(self, sample1, sample2):\n compare_samples(self, sample1, sample2)\n\n def _compare_batches(self, batch1, batch2):\n compare_batches(self, batch1, batch2)\n\n def test_init(self):\n self.assertTrue(self.dataset1 is not None)\n self.assertTrue(self.dataset2 is not None)\n\n def test_len(self):\n self.assertEqual(len(self.dataset1), 1)\n self.assertEqual(len(self.dataset2), 2)\n\n def test_getitem(self):\n sample = self.dataset1[0]\n self._compare_samples(sample, DUMMY_SAMPLES_1[0])\n\n for idx in range(len(self.dataset2)):\n sample = self.dataset2[idx]\n self._compare_samples(sample, DUMMY_SAMPLES_2[idx])\n\n def test_get_iterator(self):\n # Verifies that we can retrieve samples with iterators\n dl = self.dataset1.iterator(num_workers=0)\n assert isinstance(\n dl, DataLoader\n ), \"Classy Iterator should return instance of PyTorch Dataloader\"\n next(iter(dl))\n\n # We should be able to set num_workers to zero while also passing a mp context\n dl = self.dataset1.iterator(\n num_workers=0, multiprocessing_context=mp.get_context()\n )\n assert isinstance(\n dl, DataLoader\n ), \"Classy Iterator should return instance of PyTorch Dataloader\"\n next(iter(dl))\n\n dl = self.dataset1.iterator(num_workers=2)\n assert isinstance(\n dl, DataLoader\n ), \"Classy Iterator should return instance of PyTorch Dataloader\"\n it = iter(dl)\n next(it)\n # Because we use multiprocessing we delete the iterable to\n # shutdown workers\n del it\n\n def test_batch_logic(self):\n dataset = TestDataset(DUMMY_SAMPLES_2, batchsize_per_replica=2)\n dl = dataset.iterator(num_workers=0)\n batch = next(iter(dl))\n self.assertEqual(batch[\"input\"].size()[0], 2)\n self._compare_batches(batch, BATCHED_DUMMY_SAMPLES_2[0])\n\n @mock.patch(\n \"classy_vision.dataset.classy_dataset.get_world_size\", mock_get_world_size\n )\n @mock.patch(\"classy_vision.dataset.classy_dataset.get_rank\", mock_get_rank)\n def test_shard_logic(self):\n # This test uses a world size of 2, rank 1 to verify that the\n # second sample is returned by the dataloader\n dataset = TestDataset(DUMMY_SAMPLES_2, batchsize_per_replica=1)\n dl = dataset.iterator(num_workers=0)\n sample = next(iter(dl))\n self._compare_batches(sample, DUMMY_SAMPLES_2[1])\n\n def test_num_samples_logic(self):\n dataset = TestDataset(DUMMY_SAMPLES_2)\n self.assertEqual(len(dataset), 2)\n\n dataset = TestDataset(DUMMY_SAMPLES_2, num_samples=1)\n # Verify len returns right value for dataset\n self.assertEqual(len(dataset), 1)\n # Verify len returns right value for iterator\n self.assertEqual(len(dataset.iterator(num_workers=0)), 1)\n # Verify iterator returns correct number of samples\n it = iter(dataset.iterator(num_workers=0))\n num_samples = 0\n while True:\n try:\n next(it)\n num_samples += 1\n except StopIteration:\n break\n self.assertEqual(num_samples, 1)\n\n # Check assert for num_samples > length of base dataset\n dataset = TestDataset(DUMMY_SAMPLES_2, num_samples=3)\n with self.assertRaises(AssertionError):\n len(dataset)\n\n def test_shuffle_logic(self):\n # Simple samples to test shuffling, just a single value tensor\n # so we know how things were shuffled\n dummy_samples_10 = [\n {\"input\": torch.tensor([[0]]), \"target\": torch.tensor([0])},\n {\"input\": torch.tensor([[1]]), \"target\": torch.tensor([0])},\n {\"input\": torch.tensor([[2]]), \"target\": torch.tensor([0])},\n {\"input\": torch.tensor([[3]]), \"target\": torch.tensor([0])},\n {\"input\": torch.tensor([[4]]), \"target\": torch.tensor([0])},\n {\"input\": torch.tensor([[5]]), \"target\": torch.tensor([0])},\n {\"input\": torch.tensor([[6]]), \"target\": torch.tensor([0])},\n {\"input\": torch.tensor([[7]]), \"target\": torch.tensor([0])},\n {\"input\": torch.tensor([[8]]), \"target\": torch.tensor([0])},\n {\"input\": torch.tensor([[9]]), \"target\": torch.tensor([0])},\n ]\n dataset = TestDataset(dummy_samples_10, shuffle=True)\n\n def unpack_tensors(tensor_list):\n return [t[\"input\"].item() for t in tensor_list]\n\n # Epoch 0\n iterator = dataset.iterator(num_workers=0, current_phase_id=0)\n it = iter(iterator)\n epoch_0_list = [sample for sample in it]\n epoch_0_list = unpack_tensors(epoch_0_list)\n\n # Epoch 1\n iterator = dataset.iterator(num_workers=0, current_phase_id=1)\n it = iter(iterator)\n epoch_1_list = [sample for sample in it]\n epoch_1_list = unpack_tensors(epoch_1_list)\n\n # Should be same length, should be shuffled, should be\n # different shuffles for each epoch\n self.assertEqual(len(epoch_0_list), len(epoch_1_list))\n self.assertTrue(epoch_0_list != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n self.assertTrue(epoch_0_list != epoch_1_list)\n\n # Test different shuffle seeds\n iterator = dataset.iterator(num_workers=0, current_phase_id=0, shuffle_seed=10)\n it = iter(iterator)\n epoch_0_seed_10_list = [sample for sample in it]\n epoch_0_seed_10_list = unpack_tensors(epoch_0_seed_10_list)\n self.assertTrue(epoch_0_seed_10_list != epoch_0_list)\n\n def test_transform_logic(self):\n def _return_1_transform(sample):\n return 1\n\n dataset = TestDataset(DUMMY_SAMPLES_2, transform=_return_1_transform)\n sample = dataset[0]\n self.assertEqual(sample, 1)\n","repo_name":"facebookresearch/ClassyVision","sub_path":"test/dataset_classy_dataset_test.py","file_name":"dataset_classy_dataset_test.py","file_ext":"py","file_size_in_byte":9206,"program_lang":"python","lang":"en","doc_type":"code","stars":1563,"dataset":"github-code","pt":"3"}
+{"seq_id":"72390562960","text":"import re\nfrom decimal import Decimal\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Tag\n\n\ndef detect_meat(product_name):\n product_name = product_name.lower()\n\n if 'stir fry' in product_name or 'seasoning' in product_name:\n return 'flavouring'\n\n if 'chicken' in product_name:\n return 'chicken'\n\n if ('pork' in product_name or 'bacon' in product_name):\n return 'pork'\n\n if ('beef' in product_name or 'rump' in product_name or 'steak' in product_name):\n return 'beef'\n\n print(f'Unknown meat: {product_name}')\n return 'unknown'\n\n\ndef convert_to_meat_type(product_list):\n \"\"\"Convert a list of products into a combined list by meat.\"\"\"\n\n meats = {}\n\n for grams, product_name in product_list:\n # What type of meat is this?\n meat = detect_meat(product_name)\n meats[meat] = meats.get(meat, 0) + grams\n\n return meats\n\n\ndef main():\n default_url = 'http://www.musclefood.com/march-great-tasting-meats'\n default_url = 'http://www.musclefood.com/bundles/variety-packs/simply-the-best-chicken-mince-selection.html'\n url = input('Please enter a URL: ') or default_url\n html = requests.get(url).text\n soup = BeautifulSoup(html, 'html5lib')\n\n # This the class used on the full screen / promo style hamper pages.\n product_names = soup.find_all(class_='prodhead-twoeight')\n\n # This is used on the full screen, two column style hamper page.\n if not product_names:\n product_names = soup.find_all(class_='prodhead-twoeight-lrg')\n\n if not product_names:\n # #product-options-wrapper h2\n wrapper = soup.find(id='product-options-wrapper')\n\n if wrapper:\n product_names = wrapper.find_all('h2')\n\n # Product detail page\n if not product_names:\n product_names = soup.find(id='productname')\n\n totals = []\n\n # Handle situations where we just get a single element/\n if isinstance(product_names, Tag):\n product_names = [product_names]\n\n for product in product_names:\n product_name = product.text.strip()\n\n # If the product name doesn't contain a gram value, disregard it.\n if not re.search(r'\\d+k?g', product_name):\n print(f'Skipping {product_name} - no grams!')\n continue\n\n # Calculate the meat quantity.\n\n # First: 10 x 100g Item name\n first_format = re.match(r'^(\\d+) ?x (\\d+)g (.*)', product_name)\n\n if first_format:\n groups = first_format.groups()\n grams = Decimal(groups[0]) * Decimal(groups[1])\n\n totals.append((grams, groups[2]))\n continue\n\n # Second: 10-12 x 200g Item name (2.5kg)\n second_format = re.match(r'^\\d+-\\d+ ?x \\d+g (.*) \\(([\\d\\.]+)kg\\)', product_name)\n\n if second_format:\n groups = second_format.groups()\n kgs = groups[1]\n grams = Decimal(kgs) * 1000\n\n totals.append((grams, groups[0]))\n continue\n\n # Third: 300g Mince\n third_format = re.match(r'^(\\d+)g (.*)', product_name)\n\n if third_format:\n groups = third_format.groups()\n\n totals.append((Decimal(groups[0]), groups[1]))\n continue\n\n # Fourth: 1 x 2.5kg Item name\n fourth_format = re.match(r'^(\\d+) ?x ([\\d\\.]+)kg (.*)', product_name)\n\n if fourth_format:\n groups = fourth_format.groups()\n kgs = groups[1]\n grams = Decimal(groups[0]) * Decimal(kgs) * 1000\n\n totals.append((grams, groups[2]))\n continue\n\n print(f'Not handled: {product_name}')\n\n # print('Totals:', totals)\n print(f'Meats: {convert_to_meat_type(totals)}')\nif __name__ == '__main__':\n main()\n","repo_name":"danielsamuels/musclefood-values","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"11258059615","text":"import os\nimport sys\nfrom setuptools import setup, find_packages\nimport versioneer\n\n# vagrant doesn't appreciate hard-linking\nif os.environ.get('USER') == 'vagrant' or os.path.isdir('/vagrant'):\n del os.link\n\n# https://www.pydanny.com/python-dot-py-tricks.html\nif sys.argv[-1] == 'test':\n test_requirements = [\n 'pytest',\n ]\n try:\n modules = map(__import__, test_requirements)\n except ImportError as e:\n err_msg = e.message.replace(\"No module named \", \"\")\n msg = \"%s is not installed. Install your test requirements.\" % err_msg\n raise ImportError(msg)\n r = os.system('py.test test -v')\n if r == 0:\n sys.exit()\n else:\n raise RuntimeError('tests failed')\n\nsetup(\n name=\"csirtg_dnsdb\",\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n description=\"DNSDB Client\",\n long_description=\"Software Development Kit for DNSDB\",\n url=\"https://github.com/csirtgadgets/dnsdb-py\",\n license='MPL2',\n classifiers=[\n \"Topic :: System :: Networking\",\n \"Intended Audience :: Developers\",\n \"Programming Language :: Python\",\n ],\n keywords=['security'],\n author=\"Wes Young\",\n author_email=\"wes@csirtgadgets.org\",\n packages=find_packages(),\n install_requires=[\n 'requests>=2.6.0',\n 'pytest>=2.8.0',\n 'ujson>=1.35',\n ],\n scripts=[],\n entry_points={\n 'console_scripts': [\n 'dnsdb=csirtg_dnsdb.client:main',\n ]\n },\n)\n","repo_name":"csirtgadgets/dnsdb-py","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"72613556560","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 5 17:18:02 2023\n\n@author: joaquin\n\"\"\"\nfrom time import time\nfrom StartUp.Main_Window import Main_Window \n\nif __name__ == \"__main__\":\n print('START\\n\\n')\n start_time = time()\n \n \n Main_Window.execute()\n \n \n \n print('END')\n end_time = time()\n print('time elapsed: ', int(end_time - start_time), 'secs')\n \n \n ","repo_name":"jhidalgo-utep/OpenSea_Analyzer","sub_path":"ApplicationProject/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"11672801031","text":"\n\"\"\"\nThis is the sub-module to build all the training models.\n\"\"\"\n__author__ = \"haihuam\"\n\nimport os\nimport sys\nimport time\nimport pickle\nimport numpy as np\nimport os.path as op\nimport tensorflow as tf\nfrom global_envs import *\nfrom tqdm import tqdm\nfrom data_loader import load_data\nfrom utility import time_stamp, LQueue, debug_print\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nclass Model1(object):\n\n def __init__(self,\n data_path=None,\n depth_path=None,\n params=None,\n no_data_loader=False):\n\n self.info_collector = dict()\n self.model_name = self.__class__.__name__\n if no_data_loader:\n pass\n else:\n self.train_features, self.test_features, self.train_labels, self.test_labels = load_data(data_path, depth_path)\n self.pre_process()\n self.features = tf.placeholder(tf.float32, [None, 330])\n self.label = tf.placeholder(tf.float32, [None, 1])\n self.keep_prob = tf.placeholder(tf.float32)\n self.learning_rate = 0.001\n self.info_collector['Model Name'] = self.model_name\n self.info_collector['Learning Rate'] = self.learning_rate\n\n def pre_process(self):\n \"\"\"\n Function: data preprocessing\n \"\"\"\n self.train_features = np.mean(self.train_features, axis=2)\n self.test_features = np.mean(self.test_features, axis=2)\n\n def weight_variable(self, shape):\n initial = tf.truncated_normal(shape, stddev=0.1, seed=0)\n return tf.Variable(initial)\n\n def bias_variable(self, shape):\n initial = tf.truncated_normal(shape=shape, stddev=0.1, seed=0)\n return tf.Variable(initial)\n\n def conv2d(self, x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\n def conv1d(self, x, W):\n return tf.nn.conv1d(x, W, 2,'VALID')\n\n def max_pool_2x2(self, x):\n return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')\n\n def max_pool_2x1(self, x):\n # return tf.nn.max_pool(x, ksize=[1,2,1,1], strides=[1,2,1,1], padding='SAME')\n return tf.layers.max_pooling1d(x, pool_size=2, strides=2, padding='SAME')\n\n def setup_cnn_model(self ):\n\n input_layer = tf.reshape(self.features, [-1, 11, 30, 1])\n \n # Convolutional Layer #1\n conv1 = tf.layers.conv2d( \n inputs=input_layer, \n filters=32, \n kernel_size=[2, 2], \n padding=\"same\",\n activation=tf.nn.relu)\n \n # Pooling Layer #1\n pool1 = tf.layers.max_pooling2d(\n inputs=conv1,\n pool_size=[2, 2], \n padding='same',\n strides=2)\n\n # Convolutional Layer #2 and Pooling Layer #2\n conv2 = tf.layers.conv2d(\n inputs=pool1,\n filters=64,\n kernel_size=[2, 4],\n padding=\"same\",\n activation=tf.nn.relu)\n\n # Pooling Layer #2\n pool2 = tf.layers.max_pooling2d(\n inputs=conv2, \n pool_size=[2, 4], \n padding='same',\n strides=1)\n \n # Convolutional Layer #2 and Pooling Layer #2\n conv3 = tf.layers.conv2d(\n inputs=pool2,\n filters=128,\n kernel_size=[1, 2],\n padding=\"same\",\n activation=tf.nn.relu)\n\n # Pooling Layer #2\n pool3 = tf.layers.max_pooling2d(\n inputs=conv3, \n pool_size=[1, 4], \n padding=\"same\",\n strides=1)\n\n # Dense Layer\n pool3_flat = tf.reshape(pool3, [-1, 6 * 15 * 128])\n dense1 = tf.layers.dense(inputs=pool3_flat, units=2048)\n dropout = tf.nn.dropout(dense1, self.keep_prob)\n\n # Output Layer\n prediction = tf.layers.dense(inputs=dropout, units=1)\n\n # Calculate loss using mean squared error\n self.mse = tf.losses.mean_squared_error(prediction, self.label)\n tf.summary.scalar('mse', self.mse)\n\n self.train_step = tf.train.AdamOptimizer(self.learning_rate).minimize(self.mse)\n\n def check_retune(self, checkpoint_dir):\n checkpoint_dir_update = str()\n if op.exists(checkpoint_dir):\n if 'retune' in checkpoint_dir:\n name_splitted = checkpoint_dir.split('_')\n iteration_num = int(name_splitted[-1])\n iteration_num += 1\n prefix = name_splitted[0:-1]\n prefix.append(str(iteration_num))\n checkpoint_dir_update = '_'.join(prefix)\n else:\n checkpoint_dir_update = checkpoint_dir + '_retune_1'\n return checkpoint_dir_update\n else:\n print(\"Error: %s not exists.\"%checkpoint_dir)\n sys.exit(0)\n\n def continue_on_train(self, checkpoint_dir, n_epoch, batch_size=64):\n \"\"\"\n Base on previous training result, continue on training.\n \"\"\"\n \n self.tf_summary()\n sess, saver = self.session_restore(checkpoint_dir) \n result = str()\n checkpoint_dir_update = self.check_retune(checkpoint_dir)\n\n train_writer = tf.summary.FileWriter(checkpoint_dir_update + '/plot_train', sess.graph)\n test_writer = tf.summary.FileWriter(checkpoint_dir_update + '/plot_test')\n \n for epoch in tqdm(range(n_epoch)):\n start_time = time.time()\n batch_train_mse, batch_test_mse, n_batch = 0, 0, 0\n for x_train_a, y_train_a in self.minibatches(self.train_features, self.train_labels, batch_size, shuffle=True):\n sess.run(\n self.train_step, \n feed_dict={\n self.features: x_train_a, \n self.label: y_train_a, \n self.keep_prob: 0.7})\n\n fetch = {\n \"merged\": self.merged,\n \"loss\": self.mse\n }\n\n\n _train_result = sess.run(fetch,\n feed_dict={self.features: x_train_a,\n self.label: y_train_a,\n self.keep_prob: 1.0})\n\n _test_result = sess.run(fetch,\n feed_dict={self.features: self.test_features,\n self.label: self.test_labels,\n self.keep_prob: 1.0})\n\n train_writer.add_summary(_train_result['merged'], epoch)\n train_writer.flush()\n test_writer.add_summary(_test_result['merged'], epoch)\n test_writer.flush()\n\n _train_mse = _train_result['loss']\n _test_mse = _test_result['loss']\n\n batch_train_mse += _train_mse\n batch_test_mse += _test_mse\n n_batch += 1\n train_mse = batch_train_mse / n_batch\n test_mse = batch_test_mse / n_batch\n\n\n\n print('Train-Scope-MSE:', train_mse ) \n print('Test-Scope-MSE:', test_mse) \n QoR = ' '.join(['Train-Scope-MSE:', str(train_mse), 'Test-Scope-MSE:', str(test_mse)])\n\n\n self.info_collector['QoR'] = QoR\n self.info_collector['Epoch'] = epoch\n \n saver.save(sess, op.join(checkpoint_dir_update, self.model_name))\n self.record_result(checkpoint_dir_update)\n\n def tf_summary(self):\n tf.summary.scalar('mse', self.mse)\n self.merged = tf.summary.merge_all()\n\n def train(self, n_epoch=500, batch_size=64):\n \"\"\"\n Training fuction.\n \"\"\"\n self.tf_summary()\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver( tf.trainable_variables())\n result = str()\n\n time_info = time_stamp()\n\n qlen = 1000\n train_mse_his = LQueue(qlen)\n test_mse_his = LQueue(qlen)\n\n checkpoint_dir = op.join('check_points', \"_\".join([self.model_name, time_info]))\n\n train_writer = tf.summary.FileWriter(checkpoint_dir + '/plot_train', sess.graph)\n test_writer = tf.summary.FileWriter(checkpoint_dir + '/plot_test')\n\n\n for epoch in tqdm(range(n_epoch)):\n start_time = time.time()\n batch_train_mse, batch_test_mse, n_batch = 0, 0, 0\n for x_train_a, y_train_a in self.minibatches(self.train_features, self.train_labels, batch_size, shuffle=True):\n sess.run(\n self.train_step, \n feed_dict={\n self.features: x_train_a, \n self.label: y_train_a, \n self.keep_prob: 0.7})\n\n fetch = {\n \"merged\": self.merged,\n \"loss\": self.mse\n }\n\n\n _train_result = sess.run(fetch,\n feed_dict={self.features: x_train_a,\n self.label: y_train_a,\n self.keep_prob: 1.0})\n\n _test_result = sess.run(fetch,\n feed_dict={self.features: self.test_features,\n self.label: self.test_labels,\n self.keep_prob: 1.0})\n\n train_writer.add_summary(_train_result['merged'], epoch)\n train_writer.flush()\n test_writer.add_summary(_test_result['merged'], epoch)\n test_writer.flush()\n\n _train_mse = _train_result['loss']\n _test_mse = _test_result['loss']\n\n batch_train_mse += _train_mse\n batch_test_mse += _test_mse\n n_batch += 1\n train_mse = batch_train_mse / n_batch\n test_mse = batch_test_mse / n_batch\n\n\n\n print('Train-Scope-MSE2:', train_mse ) \n print('Test-Scope-MSE2:', test_mse) \n QoR = ' '.join(['Train-Scope-MSE2:', str(train_mse), 'Test-Scope-MSE2:', str(test_mse)])\n\n train_mse_his.Append(train_mse)\n test_mse_his.Append(test_mse)\n\n\n test_mse_is_descrease = test_mse_his.IsDecrese()\n train_mse_is_descrease = train_mse_his.IsDecrese()\n\n break_condition = not ( test_mse_is_descrease and train_mse_is_descrease)\n if break_condition:\n break\n\n self.info_collector['QoR'] = QoR\n self.info_collector['Epoch'] = n_epoch\n \n saver.save(sess, op.join(checkpoint_dir, self.model_name))\n self.record_result(checkpoint_dir)\n\n def session_restore(self, checkpoint_dir):\n \"\"\"\n Restore a session\n \"\"\"\n sess = tf.Session()\n saver = tf.train.Saver( tf.trainable_variables())\n sess.run(tf.global_variables_initializer())\n \n model_path = self.get_model_path(checkpoint_dir)\n saver.restore(sess, model_path)\n return sess, saver\n\n def record_result(self, checkpoint_dir):\n result = str(self.info_collector)\n self.dump_result(checkpoint_dir, result)\n\n def dump_result(self, checkpoint_dir, result):\n result_file_dir = op.join(checkpoint_dir, 'result')\n with open(result_file_dir, 'w+') as result_file_handle:\n result_file_handle.write(result)\n result_file_handle.write('\\n')\n\n def get_model_path(self, checkpoint_dir):\n from glob import glob\n meta_file = glob(op.join(checkpoint_dir,'*.meta'))\n if meta_file:\n if len(meta_file) == 1:\n meta_name = meta_file[0].split('/')[-1]\n model_name = meta_name.split('.')[0]\n model_path = op.join(checkpoint_dir, model_name)\n return model_path\n else:\n print('Error: more models were saved in [%s]'%checkpoint_dir)\n sys.exit(0)\n else:\n print('Error: no model found in [%s]' %checkpoint_dir)\n sys.exit(0)\n\n def minibatches(self,\n inputs=None,\n targets=None,\n batch_size=None,\n shuffle=False):\n\n assert len(inputs) == len(targets)\n\n if shuffle:\n indices = np.arange(len(inputs))\n np.random.shuffle(indices)\n for start_idx in range(0, len(inputs) - batch_size + 1, batch_size):\n if shuffle:\n excerpt = indices[start_idx:start_idx + batch_size]\n else:\n excerpt = slice(start_idx, start_idx + batch_size)\n yield inputs[excerpt], targets[excerpt]\n\n\n\nclass Model2(Model1):\n\n def setup_cnn_model(self):\n\n input_layer = tf.reshape(self.features, [-1, 330, 1])\n \n # conv1 layer \n W_conv1 = self.weight_variable([2, 1, 32]) \n b_conv1 = self.bias_variable([32])\n h_conv1 = tf.nn.relu(self.conv1d(input_layer, W_conv1) + b_conv1) \n # print(h_conv1.get_shape().as_list())\n # sys.exit(0)\n\n # pooling\n h_pool1 = self.max_pool_2x1(h_conv1) \n\n # MS Layer\n ## Branch 1\n ms_b1_W_conv1 = self.weight_variable([1, 32, 10])\n ms_b1_b_conv1 = self.bias_variable([10])\n ms_b1_h_conv1 = tf.nn.relu(self.conv1d(h_pool1, ms_b1_W_conv1) + ms_b1_b_conv1)\n ms_b1_W_conv2 = self.weight_variable([5, 10, 10])\n ms_b1_b_conv2 = self.bias_variable([10])\n ms_b1_h_conv2 = tf.nn.relu(self.conv1d(ms_b1_h_conv1, ms_b1_W_conv2) + ms_b1_b_conv2)\n # print(ms_b1_h_conv2.get_shape().as_list())\n\n ## Branch 2\n ms_b2_W_conv1 = self.weight_variable([1, 32, 10])\n ms_b2_b_conv1 = self.bias_variable([10])\n ms_b2_h_conv1 = tf.nn.relu(self.conv1d(h_pool1, ms_b2_W_conv1) + ms_b2_b_conv1)\n ms_b2_W_conv2 = self.weight_variable([3, 10, 10])\n ms_b2_b_conv2 = self.bias_variable([10])\n ms_b2_h_conv2 = tf.nn.relu(self.conv1d(ms_b2_h_conv1, ms_b2_W_conv2) + ms_b2_b_conv2)\n # print(ms_b2_h_conv2.get_shape().as_list())\n\n ## Branch 3\n ms_b3_W_conv1 = self.weight_variable([1, 32, 10])\n ms_b3_b_conv1 = self.bias_variable([10])\n ms_b3_h_conv1 = tf.nn.relu(self.conv1d(h_pool1, ms_b3_W_conv1) + ms_b3_b_conv1)\n # print(ms_b3_h_conv1.get_shape().as_list())\n\n ## Branch 4\n ms_b4_pool1 = self.max_pool_2x1(h_pool1)\n ms_b4_W_conv1 = self.weight_variable([1, 32, 10])\n ms_b4_b_conv1 = self.bias_variable([10])\n ms_b4_h_conv1 = tf.nn.relu(self.conv1d(ms_b4_pool1, ms_b4_W_conv1) + ms_b4_b_conv1)\n # print(ms_b4_h_conv1.get_shape().as_list())\n\n ## Branch 5\n ms_b5_W_conv1 = self.weight_variable([1, 32, 10])\n ms_b5_b_conv1 = self.bias_variable([10])\n ms_b5_h_conv1 = tf.nn.relu(self.conv1d(h_pool1, ms_b5_W_conv1) + ms_b5_b_conv1)\n ms_b5_W_conv2 = self.weight_variable([2, 10, 10])\n ms_b5_b_conv2 = self.bias_variable([10])\n ms_b5_h_conv2 = tf.nn.relu(self.conv1d(ms_b5_h_conv1, ms_b5_W_conv2) + ms_b5_b_conv2)\n # print(ms_b5_h_conv2.get_shape().as_list())\n\n # Concat layer\n concat_layer = tf.concat([ms_b1_h_conv2, ms_b2_h_conv2, ms_b3_h_conv1, ms_b4_h_conv1, ms_b5_h_conv1], 1)\n # print(concat_layer.get_shape().as_list())\n # sys.exit(0)\n concat_layer_flat = tf.reshape(concat_layer, [ -1, 144*10])\n # print(concat_layer_flat.get_shape().as_list())\n\n # fc1 layer \n W_fc1 = self.weight_variable([144*10, 512])\n b_fc1 = self.bias_variable([512])\n h_fc1 = tf.nn.relu(tf.matmul(concat_layer_flat, W_fc1) + b_fc1)\n\n # fc1 dropout\n h_fc1_drop = tf.nn.dropout(h_fc1, self.keep_prob)\n\n # fc2 layer \n W_fc2 = self.weight_variable([512, 1])\n b_fc2 = self.bias_variable([1])\n\n self.prediction = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n self.mse = tf.losses.mean_squared_error(self.label, self.prediction)\n tf.summary.scalar('mse', self.mse)\n self.train_step = tf.train.AdamOptimizer(self.learning_rate).minimize(self.mse)\n\n def predict(self, checkpoint_dir):\n \"\"\"\n Load the training checkpoint, and implement the prediction.\n \"\"\"\n sess, saver = self.session_restore(checkpoint_dir)\n prediction_value = sess.run(self.prediction,\n feed_dict={ \n self.features: self.test_features,\n self.keep_prob: 1.0}) \n return prediction_value\n\n\nif __name__ == '__main__':\n\n data_path = \"../out/extract_pixel_value.data.20190217_143517\"\n depth_path = \"../out/filterd_depth.info.20190217_125210\"\n\n # model = Model1(data_path, depth_path)\n model = Model2(data_path, depth_path)\n model.setup_cnn_model()\n model.train()\n","repo_name":"HaihuaM/hi-bathymetry","sub_path":"models_v2.py","file_name":"models_v2.py","file_ext":"py","file_size_in_byte":16856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"949420005","text":"import subprocess\nimport os.path\nimport fcntl\nimport nltk\nimport sys\n\ndata = open(\"DischargeSummary/\"+sys.argv[1],'r').read() \ndata = data.lower()\n\ncomplete_data = data\n\ndata = data.replace('\\n',' ')\ndata = nltk.sent_tokenize(data)\n\n#data.replace('\\n',' ')\n\n#print(data)\n\npath_to_genia = \"/home/guestdsac/qwerty/shashank/geniatagger-3.0.2\"\n\nos.chdir(path_to_genia)\n\n#dir_to_tagger = os.path.dirname(path_to_genia)\n\n#tagger = subprocess.call(\"ls\",shell=True)\ntagger = subprocess.Popen(\"./geniatagger\",stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n#print(tagger)\n\nresults = []\n\n#wr = open(\"Clean/genia_tagged_\"+sys.argv[1],'w+')\n\n#span\nspan = 0\n\n\n#print(\"*********\")\nfor oneline in data:\n\ttagger.stdin.write((oneline+'\\n').encode('utf-8'))\n\ttagger.stdin.flush()\n\t#print('0')\n\t#print(oneline)\n\t#print(span)\n\twhile (True):\n\t\ttry :\n\t\t\tr = tagger.stdout.readline()[:-1]\n\t\texcept : \n\t\t\tcontinue\n\t#\tprint(\"****************\")\n\t#\tprint(r)\n\t\tr=r.decode('utf-8')\n\t\t#r=r.replace('[ ]*',' ')\n\t\t\n\t#\tprint(r.split('\\t'))\n\t\t#results.append(r.split('\\\\t'))\n\t\tr=r.split('\\t')\n\t\t#print(r)\n\t\t#if len(r) < 5 :\n\t\t#\tcontinue\n\t\t\n\t\twhile r[0] != complete_data[span:span+len(r[0])] and span 4 and len(r[1]) > 2 :\n\t\t\ts = str(span) + \" \" + str(span+len(r[0])) + '|'\n\t\t\tspan += len(r[0])\n\t\t\tfor x in r:\n\t\t\t\ts+=x+'|'\n\t\t\ts = s[:-1]\t\n\t\t\tprint(str(s))\n\t\t\t#wr.write(str(s))\n\t\tif len(r) == 1 and len(r[0]) ==0 :\n\t\t\tbreak\n#print(results)\n#print(\"Im mad\")\n#wr.close()\n","repo_name":"upadhysh/Medical-Text-Analysis","sub_path":"002_genia.py","file_name":"002_genia.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37069128698","text":"#!/usr/bin/env python\n\nimport netfilterqueue, subprocess\nimport scapy.all as scapy\nimport argparse\n\n# Create function to pass arguments while calling the program\ndef get_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-d\", \"--domain\", dest=\"domain\", help=\"Set Domain to spoof\")\n parser.add_argument(\"-s\", \"--spoof-ip\", dest=\"spoof_ip\", help=\"Set IP Address to spoof domain to\")\n options = parser.parse_args()\n if not options.domain:\n parser.error(\"[-] Please specify a domain to spoof using -d or --domain options, use --help for more info.\")\n if not options.spoof_ip:\n parser.error(\"[-] Please specify a spoof ip using -s or --spoof-ip options, use --help for more info.\")\n return options\n\ndef process_packet(packet):\n scapy_packet = scapy.IP(packet.get_payload())\n if scapy_packet.haslayer(scapy.DNSRR):\n qname = scapy_packet[scapy.DNSQR].qname\n if options.domain in qname:\n response = scapy.DNSRR(rrname=qname, rdata=options.spoof_ip)\n scapy_packet[scapy.DNS].an = response\n # scapy_packet[scapy.DNS].ancount = 1\n\n # Delete the important flags to allow scapy reset them\n del scapy_packet[scapy.IP].len\n del scapy_packet[scapy.IP].chksum\n del scapy_packet[scapy.UDP].len\n del scapy_packet[scapy.UDP].chksum\n\n packet.set_payload(str(scapy_packet)) # Set the modeified packet as the packet payload\n\n packet.accept() # Accept packet for forwarding\n\ntry:\n options = get_arguments()\n \n print(\"[+] Modifying iptables FORWARD chain...\")\n subprocess.call(\"iptables -I FORWARD -j NFQUEUE --queue-num 0\", shell=True) # create a queue rule using NFQUEUE in iptables\n\n queue = netfilterqueue.NetfilterQueue() # Create a netfilterqueue object\n queue.bind(0, process_packet) # Bind the queue object to the rule with queue number 0 and the callback function\n print(\"[+] Spoofing the ip address of domain \" + options.domain + \" to \" + options.spoof_ip + \"...\")\n queue.run() # Send the queued packets to the callback function\n\nexcept KeyboardInterrupt:\n print(\"\\n[+] Resetting iptables FORWARD chain...\")\n subprocess.call(\"iptables -D FORWARD -j NFQUEUE --queue-num 0\", shell=True) # delete the queue rule in iptables\n","repo_name":"williamajayi/network_intercept","sub_path":"dns_spoof.py","file_name":"dns_spoof.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27201880510","text":"import yaml\nimport twitter\nimport json\n\n\nCLIENT_SECRETS_FILE = \"client_secret.json\"\nwith open(CLIENT_SECRETS_FILE) as json_data:\n d = json.load(json_data)\n ckey = d['ckey']\n csecret = d['csecret']\n atoken = d['atoken']\n asecret = d['asecret']\n\n\n\ndef findTweetsStats(username):\n api = twitter.Api(ckey, csecret, atoken, asecret)\n user = username\n statuses = api.GetUserTimeline(screen_name=user, count=500, include_rts=False)\n\n DirectFavoriteCount = 0\n DirectReteetedCount = 0\n DirectCount = 0\n \n \n for i in statuses:\n i = json.dumps(i._json)\n i = yaml.load(i)\n favorite_count = i['favorite_count']\n text = i['text']\n retweeted = i['retweeted']\n language = i['lang']\n retweet_count = i['retweet_count']\n if retweeted is False:\n DirectFavoriteCount += favorite_count\n DirectReteetedCount += retweet_count\n DirectCount += 1\n return DirectFavoriteCount/DirectCount, DirectReteetedCount/DirectCount\n \n \nprint(findTweetsStats(\"realDonaldTrump\"))\nprint(findTweetsStats(\"HilaryClinton\"))\n\n\n\n\n\n\n\n\n\n\n","repo_name":"jqsheng94/Twitter-API-Samples","sub_path":"retrieve tweets stats.py","file_name":"retrieve tweets stats.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"198479526","text":"# This file is part of Lerot.\n#\n# Lerot is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Lerot 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 Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with Lerot. If not, see .\n\nimport logging\nimport argparse\nimport gzip\nimport os.path\nimport sys\nimport yaml\n\nfrom ..query import load_queries\nfrom ..utils import get_class\n\n\nclass GenericExperiment:\n def __init__(self, args_str=None):\n # parse arguments\n parser = argparse.ArgumentParser(description=\"\"\"\n Construct and run a learning experiment. Provide either the name\n of a config file from which the experiment configuration is\n read, or provide all arguments listed under Command line. If\n both are provided the config file is ignored.\"\"\",\n prog=self.__class__.__name__)\n\n # option 1: use a config file\n file_group = parser.add_argument_group(\"FILE\")\n file_group.add_argument(\"-f\", \"--file\", help=\"Filename of the config \"\n \"file from which the experiment details\"\n \" should be read.\")\n\n # option 2: specify all experiment details as arguments\n detail_group = parser.add_argument_group(\"DETAILS\")\n detail_group.add_argument(\"-i\", \"--training_queries\",\n help=\"File from which to load the training queries (svmlight \"\n \"format).\")\n detail_group.add_argument(\"-j\", \"--test_queries\",\n help=\"File from which to load the test queries (svmlight format).\")\n detail_group.add_argument(\"-c\", \"--feature_count\", type=int,\n help=\"The number of features included in the data.\")\n detail_group.add_argument(\"-r\", \"--num_runs\", type=int,\n help=\"Number of runs (how many times to repeat the experiment).\")\n detail_group.add_argument(\"-q\", \"--num_queries\", type=int,\n help=\"Number of queries in each run.\")\n detail_group.add_argument(\"-u\", \"--user_model\",\n help=\"Class implementing a user model.\")\n detail_group.add_argument(\"-v\", \"--user_model_args\",\n help=\"Arguments for initializing the user model.\")\n # the retrieval system maintains ranking functions, accepts queries and\n # generates result lists, and in return receives user clicks to learn\n # from\n detail_group.add_argument(\"-s\", \"--system\",\n help=\"Which system to use (e.g., pairwise, listwise).\")\n detail_group.add_argument(\"-a\", \"--system_args\", help=\"Arguments for \"\n \"the system (comparison method, learning \"\n \"algorithm and parameters...).\")\n detail_group.add_argument(\"-o\", \"--output_dir\",\n help=\"(Empty) directory for storing output generated by this\"\n \" experiment. Subdirectory for different folds will be generated\"\n \"automatically.\")\n detail_group.add_argument(\"--output_dir_overwrite\", default=\"False\")\n detail_group.add_argument(\"-p\", \"--output_prefix\",\n help=\"Prefix to be added to output filenames, e.g., the name of \"\n \"the data set, fold, etc. Output files will be stored as \"\n \"OUTPUT_DIR/PREFIX-RUN_ID.txt.gz\")\n detail_group.add_argument(\"-e\", \"--experimenter\",\n help=\"Experimenter type.\")\n # run the parser\n if args_str:\n args = parser.parse_known_args(args_str.split())[0]\n else:\n args = parser.parse_known_args()[0]\n\n # determine whether to use config file or detailed args\n self.experiment_args = None\n if args.file:\n config_file = open(args.file)\n self.experiment_args = yaml.load(config_file)\n config_file.close()\n # overwrite with command-line options if given\n for arg, value in vars(args).items():\n if value:\n self.experiment_args[arg] = value\n else:\n self.experiment_args = vars(args)\n\n # workaround - check if we have all the arguments needed\n if not (\"training_queries\" in self.experiment_args and\n \"test_queries\" in self.experiment_args and\n \"feature_count\" in self.experiment_args and\n \"num_runs\" in self.experiment_args and\n \"num_queries\" in self.experiment_args and\n \"user_model\" in self.experiment_args and\n \"user_model_args\" in self.experiment_args and\n \"system\" in self.experiment_args and\n \"system_args\" in self.experiment_args and\n \"output_dir\" in self.experiment_args):\n parser.print_help()\n sys.exit(\"Missing required arguments, please check the program\"\n \" arguments or configuration file. %s\" %\n self.experiment_args)\n\n # set default values for optional arguments\n if not \"query_sampling_method\" in self.experiment_args:\n self.experiment_args[\"query_sampling_method\"] = \"random\"\n if not \"output_dir_overwrite\" in self.experiment_args:\n self.experiment_args[\"output_dir_overwrite\"] = False\n if not \"experimenter\" in self.experiment_args:\n self.experiment_args[\"experimenter\"] = \"experiment.LearningExperiment\"\n if not \"evaluation\" in self.experiment_args:\n self.experiment_args[\"evaluation\"] = \"evaluation.NdcgEval\"\n if not \"processes\" in self.experiment_args:\n self.experiment_args[\"processes\"] = 0\n\n # locate or create directory for the current fold\n if not os.path.exists(self.experiment_args[\"output_dir\"]):\n os.makedirs(self.experiment_args[\"output_dir\"])\n elif not(self.experiment_args[\"output_dir_overwrite\"]) and \\\n os.listdir(self.experiment_args[\"output_dir\"]):\n # make sure the output directory is empty\n raise Exception(\"Output dir %s is not an empty directory. \"\n \"Please use a different directory, or move contents out \"\n \"of the way.\" %\n self.experiment_args[\"output_dir\"])\n\n logging.basicConfig(format='%(asctime)s %(module)s: %(message)s',\n level=logging.INFO)\n\n logging.info(\"Arguments: %s\" % self.experiment_args)\n for k, v in sorted(self.experiment_args.iteritems()):\n logging.info(\"\\t%s: %s\" % (k, v))\n config_bk = os.path.join(self.experiment_args[\"output_dir\"],\n \"config_bk.yml\")\n logging.info(\"Backing up configuration to: %s\" % config_bk)\n config_bk_file = open(config_bk, \"w\")\n yaml.dump(self.experiment_args,\n config_bk_file,\n default_flow_style=False)\n config_bk_file.close()\n\n # load training and test queries\n training_file = self.experiment_args[\"training_queries\"]\n test_file = self.experiment_args[\"test_queries\"]\n self.feature_count = self.experiment_args[\"feature_count\"]\n logging.info(\"Loading training data: %s \" % training_file)\n self.training_queries = load_queries(training_file, self.feature_count)\n logging.info(\"... found %d queries.\" %\n self.training_queries.get_size())\n logging.info(\"Loading test data: %s \" % test_file)\n self.test_queries = load_queries(test_file, self.feature_count)\n logging.info(\"... found %d queries.\" % self.test_queries.get_size())\n\n # initialize and run the experiment num_run times\n self.num_runs = self.experiment_args[\"num_runs\"]\n self.output_dir = self.experiment_args[\"output_dir\"]\n self.output_prefix = self.experiment_args[\"output_prefix\"]\n self.experimenter = get_class(self.experiment_args[\"experimenter\"])\n\n def run(self):\n if self.experiment_args[\"processes\"] > 1:\n from multiprocessing import Pool\n pool = Pool(processes=self.experiment_args[\"processes\"])\n for run_count in range(self.num_runs):\n pool.apply_async(self._run, (run_count,))\n pool.close()\n pool.join()\n else:\n return [self._run(i) for i in range(self.num_runs)]\n\n def _run(self, run_id):\n logging.info(\"run %d starts\" % run_id)\n aux_log_file = os.path.join(self.output_dir, \"_%s-%d.txt.gz\" %\n (self.output_prefix, run_id))\n aux_log_fh = gzip.open(aux_log_file, \"wb\")\n r = self.run_experiment(aux_log_fh)\n aux_log_fh.close()\n log_file = os.path.join(self.output_dir, \"%s-%d.txt.gz\" %\n (self.output_prefix, run_id))\n log_fh = gzip.open(log_file, \"wb\")\n yaml.dump(r, log_fh, default_flow_style=False)\n log_fh.close()\n logging.info(\"run %d done\" % run_id)\n\n return r\n\n def run_experiment(self, aux_log_fh):\n experiment = self.experimenter(\n self.training_queries,\n self.test_queries,\n self.feature_count,\n aux_log_fh,\n self.experiment_args)\n return experiment.run()\n","repo_name":"redreamality/learning-to-rank","sub_path":"lerot/experiment/GenericExperiment.py","file_name":"GenericExperiment.py","file_ext":"py","file_size_in_byte":9761,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"3"}
+{"seq_id":"14252766671","text":"mountain = {\"乔戈里峰\":8611,\"干城章嘉峰\":8586,\"珠穆朗玛峰\":8844.43,\"洛子峰\":8516}\nc= mountain.values()\nprint(type(c))\nprint(c)\na = max(mountain.values()) # values 实际就是一个取键值的办法,\n # 似乎可以假定mountain.values最后得出来的是一个列表。\n#print(a)\nfor key, values in mountain.items(): # 用两个指针遍历健与键值对\n if (values == a):\n print(f\"世界最高峰为{key},高度为{values}米。\")","repo_name":"Nordenbox/Nordenbox_Python_Fundmental","sub_path":"使用字典取值和找到最大键值.py","file_name":"使用字典取值和找到最大键值.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29037329387","text":"import io\nimport pytest\nfrom typing import Dict\nimport torch\nimport os\nimport contextlib\nimport yaml\nimport numpy as np\n\nfrom ads_pytorch.yt.file_system_adapter_mock import CypressAdapterMock\nfrom ads_pytorch.tools.async_worker_pool import BaseAsyncWorkerPool, BaseAsyncWorker\n\nfrom deploy.production_model import TensorApplicableModel\nfrom deploy.processors.tsar_tensor_processor import TsarTensorProcessor, AdvMachineTensorProcessor\n\n\nclass DiskSaveWorker(BaseAsyncWorker):\n async def _do_job(self, data_stream, path, tx):\n assert tx is not None\n if not os.path.exists(os.path.dirname(path)):\n os.makedirs(os.path.dirname(path))\n with open(path, 'wb') as f:\n if isinstance(data_stream, (str, bytes)):\n f.write(data_stream)\n else:\n async for data in data_stream:\n f.write(data)\n\n\nclass DiskSavePool(BaseAsyncWorkerPool):\n def create_new_worker(self, new_rank: int):\n return DiskSaveWorker(new_rank)\n\n\ndef async_mocks():\n return DiskSavePool(workers_count=5), CypressAdapterMock()\n\n\nclass SomeTsarTensorApplicableModel(TensorApplicableModel):\n def __init__(self):\n pass\n\n @property\n def model_config(self) -> Dict:\n return dict()\n\n def get_final_tsar_tensor(self) -> torch.Tensor:\n return torch.arange(3 * 4 * 5, dtype=torch.float32).view(3, 4, 5)\n\n\nclass SomeAdvMachineTensorApplicableModel(TensorApplicableModel):\n def __init__(self):\n pass\n\n @property\n def model_config(self) -> Dict:\n return dict()\n\n def get_final_tsar_tensor(self) -> torch.Tensor:\n return torch.FloatTensor([1, 2])\n\n\n@contextlib.asynccontextmanager\nasync def enter_context(fs_adapter: CypressAdapterMock, save_pool: DiskSavePool):\n async with contextlib.AsyncExitStack() as stack:\n await stack.enter_async_context(fs_adapter)\n await stack.enter_async_context(save_pool)\n tx = await stack.enter_async_context(fs_adapter.transaction_ctx())\n yield tx\n\n\n@pytest.mark.asyncio\nasync def test_tsar_tesnor_applicable_model():\n save_pool, fs_adapter = async_mocks()\n tensor_applicable = SomeTsarTensorApplicableModel()\n processor = TsarTensorProcessor(\n file_system_adapter=fs_adapter,\n save_pool=save_pool\n )\n\n await processor.process_model(\n tensor_applicable,\n base_dir='.',\n name='test_tsar_tesnor_applicable_model',\n parent_tx=''\n )\n\n tensor = yaml.load(open('test_tsar_tesnor_applicable_model/deep_part/model_state', 'r'))\n\n buffer = io.BytesIO()\n np.save(buffer, np.arange(3 * 4 * 5, dtype=np.float32).reshape(3, 4, 5))\n\n assert tensor['state_dict']['tensor'] == buffer.getvalue()\n\n\n@pytest.mark.asyncio\nasync def test_adv_machine_tesnor_applicable_model():\n save_pool, fs_adapter = async_mocks()\n tensor_applicable = SomeAdvMachineTensorApplicableModel()\n processor = AdvMachineTensorProcessor(\n file_system_adapter=fs_adapter,\n save_pool=save_pool\n )\n\n await processor.process_model(\n tensor_applicable,\n base_dir='.',\n name='test_adv_machine_tesnor_applicable_model',\n parent_tx=''\n )\n\n tensor = yaml.load(open('test_adv_machine_tesnor_applicable_model/deep_part/model_state', 'r'))\n assert tensor['state_dict']['tensor'] == '1.00000000 2.00000000'\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"ads/tests/processors/test_tesnor_processor.py","file_name":"test_tesnor_processor.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20084982570","text":"import numpy as np # importing NumPy\n\na = np.array([1, 2, 3, 4, 5])\nprint(a)\n# Output: [1 2 3 4 5]\n\na = np.zeros(2)\nprint(a) \n# Output: [0. 0.]\n\na = np.ones(2)\nprint(a)\n# Output: [1. 1.]\n\n# arange() is similar to range()\na = np.arange(4)\nprint(a)\n# Output: [0 1 2 3]\n\n# arange() is similar to range()\na = np.arange(3, 9, 3)\nprint(a)\n# Output: [3 6]\n\na = np.linspace(0, 10, num=5)\nprint(a)\n# Output: [ 0. 2.5 5. 7.5 10. ]\n\na = np.array([9, 3, 5, 4, 2, 1, 6, 8, 7])\nprint(np.sort(a))\n# Output: [1 2 3 4 5 6 7 8 9]\n\na = np.array([[3, 5, 4, 2], [1, 6, 8, 7]])\na = np.sort(a, axis=None)\nprint(a)\n# Output: [1 2 3 4 5 6 7 8]\n\na = np.array([1, 2, 3, 4, 5])\nb = np.array([6, 7, 8, 9])\nprint(np.concatenate((a, b)))\n# Output: [1 2 3 4 5 6 7 8 9]\n\n# Indexing\narr = np.array([1, 2, 3, 4, 5, 6, 7])\nprint(arr[1])\n# Output: 2\n\n\n# Slicing\narr = np.array([1, 2, 3, 4, 5, 6, 7])\nprint(arr[1:5])\n# Output: [2 3 4 5] \n\n## ======================\n## For getting array info \n## ======================\n\na = np.array([[[0, 1, 2, 3],\n [4, 5, 6, 7]],\n [[0, 1, 2, 3],\n [4, 5, 6, 7]],\n [[0 ,1 ,2, 3],\n [4, 5, 6, 7]]])\n\nprint(a.ndim)\n# Output: 3\n\nprint(a.size)\n# Output: 24\n\nprint(a.shape)\n# Output: (3, 2, 4)\n\n## Reshape\na = np.arange(6)\nb = a.reshape(3, 2)\nprint(b)\n# Output: [[0 1]\n# [2 3]\n# [4 5]]\n\na = np.arange(6)\nb = a.reshape(3, 1, 2)\nprint(b)\n# Output: [[0 1]\n# [2 3]\n# [4 5]]\n\na = np.arange(6)\nb = a.reshape(3, 1, -1)\nprint(b)\n# Output: [[0 1]\n# [2 3]\n# [4 5]]\n\n\n### Add new dimension\na = np.array([1, 2, 3, 4, 5, 6])\nprint(a.shape)\n# Output: (6,)\n\na2 = a[np.newaxis, :]\nprint(a2.shape)\n# Output: (1, 6)\n\na2 = a[: , np.newaxis]\nprint(a2.shape)\n# Output: (6, 1)\n\nb = np.expand_dims(a, axis=1)\nprint(b.shape)\n# Output: (6, 1)\n\nc = np.expand_dims(a, axis=0)\nprint(c.shape)\n# Output: (1, 6)\n\na = np.array([[1 , 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\nprint(a[a < 5])\n# Output: [1 2 3 4]\n\nfive_up = (a > 5) | (a == 5)\nprint(five_up)\n# Output: [[False False False False]\n# [ True True True True]\n# [ True True True True]]\n\nb = np.nonzero(a < 5)\nprint(b)\n# Output: (array([0, 0, 0, 0]), array([0, 1, 2, 3]))\n\nlist_of_coordinates= list(zip(b[0], b[1]))\nfor coord in list_of_coordinates:\n print(coord)\n# Output: (0, 0)\n#(0, 1)\n#(0, 2)\n#(0, 3)\n\n# Stacking\n\na1 = np.array([[1, 1],\n [2, 2]])\n\na2 = np.array([[3, 3],\n [4, 4]])\n\na = np.vstack((a1, a2))\nprint(a)\n# Output: [[1, 1],\n# [2, 2],\n# [3, 3],\n# [4, 4]]\n\na = np.hstack((a1, a2))\nprint(a)\n\n# Splitting\nx = np.arange(1, 25).reshape(2, 12)\nprint(np.hsplit(x, 3))\n# Output: [array([[ 1, 2, 3, 4],\n# [13, 14, 15, 16]]), array([[ 5, 6, 7, 8],\n# [17, 18, 19, 20]]), array([[ 9, 10, 11, 12],\n# [21, 22, 23, 24]])]\n\n# Copy vs View\narr = np.array([1, 2, 3, 4, 5])\n\nx = arr.copy()\ny = arr.view()\nprint(x, y)\narr[2]=2\nprint(x, y)\n","repo_name":"Manoj-Paramsetti/Notes","sub_path":"Python/numpy/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"3"}
+{"seq_id":"2088314819","text":"'''Flatten a Dictionary\n\nA dictionary is a type of data structure that is supported natively in all major interpreted languages such as JavaScript, Python, Ruby and PHP, where it’s known as an Object, Dictionary, Hash and Array, respectively. In simple terms, a dictionary is a collection of unique keys and their values. The values can typically be of any primitive type (i.e an integer, boolean, double, string etc) or other dictionaries (dictionaries can be nested). However, for this exercise assume that values are either an integer, a string or another dictionary.\n\nGiven a dictionary dict, write a function flattenDictionary that returns a flattened version of it .\n\nIf you’re using a compiled language such Java, C++, C#, Swift and Go, you may want to use a Map/Dictionary/Hash Table that maps strings (keys) to a generic type (e.g. Object in Java, AnyObject in Swift etc.) to allow nested dictionaries.\n\nIf a certain key is empty, it should be excluded from the output (see e in the example below).\n\n\nExample:\n\ninput: dict = {\n \"Key1\" : \"1\",\n \"Key2\" : {\n \"a\" : \"2\",\n \"b\" : \"3\",\n \"c\" : {\n \"d\" : \"3\",\n \"e\" : {\n \"\" : \"1\"\n }\n }\n }\n }\n\noutput: {\n \"Key1\" : \"1\",\n \"Key2.a\" : \"2\",\n \"Key2.b\" : \"3\",\n \"Key2.c.d\" : \"3\",\n \"Key2.c.e\" : \"1\"\n }\n\nImportant: when you concatenate keys, make sure to add the dot character between them. For instance concatenating Key2, c and d the result key would be Key2.c.d.\nI assume that duplicate result keys will not occure.\n\nConstraints:\n[time limit] 5000ms\n[input] Dictionary dict\n[output] Dictionary\n'''\n\n\n# O(n) where n is number of keys in the dict\ndef flatten_dictionary(dictionary):\n if not dictionary:\n return {}\n\n def rec(my_dict):\n flattened = {}\n for k, v in my_dict.items():\n if not isinstance(v, dict):\n flattened[k] = v\n else:\n for kx, vx in rec(v).items():\n if not k:\n flattened[kx] = vx\n elif not kx: # skip empty key\n flattened[k] = vx\n else:\n flattened[k + '.' + kx] = vx\n return flattened\n return rec(dictionary)\n\n\n# O(n) where n is number of keys in the dict\ndef flatten_dictionary_done_differently(dictionary):\n if not dictionary:\n return {}\n flatt_dictionary = {}\n\n def rec(input, key):\n if not isinstance(input, dict):\n flatt_dictionary[key] = input\n return\n for k, v in input.items():\n if key and k:\n rec(v, key + '.' + k)\n elif key:\n rec(v, key)\n else:\n rec(v, k)\n\n rec(dictionary, '')\n return flatt_dictionary\n\n\ndef flatten_dictionary_loop_and_stack(dictionary):\n if not dictionary:\n return {}\n flatt_dictionary = {}\n stack = [('', '', dictionary)]\n while stack:\n prior_key, key, value = stack.pop()\n new_key = get_new_key(prior_key, key)\n if not isinstance(value, dict):\n flatt_dictionary[new_key] = value\n else:\n for key, value in value.items():\n stack.append((new_key, key, value))\n return flatt_dictionary\n\n\ndef get_new_key(prior_key, key):\n if prior_key and key:\n new_key = prior_key + '.' + key\n elif prior_key:\n new_key = prior_key\n else:\n new_key = key\n return new_key\n\n\ndef tests():\n # ex 1\n dictionary = {\n \"Key1\" : \"1\",\n \"Key2\" : {\"a\" : \"2\"}\n }\n exp = {\n \"Key2.a\" : \"2\", \n \"Key1\" : \"1\",}\n print(flatten_dictionary(dictionary) == exp)\n print(flatten_dictionary_done_differently(dictionary) == exp)\n print(flatten_dictionary_loop_and_stack(dictionary) == exp)\n\n # ex2 \n dictionary = {\n \"Key1\" : \"1\",\n \"Key2\" : {\n \"a\" : \"2\",\n \"b\" : \"3\",\n \"c\" : {\n \"d\" : \"3\",\n \"e\" : {\n \"\" : \"1\"\n }\n }\n }\n }\n exp = {\n \"Key1\" : \"1\",\n \"Key2.a\" : \"2\",\n \"Key2.b\" : \"3\",\n \"Key2.c.d\" : \"3\",\n \"Key2.c.e\" : \"1\"\n }\n print(flatten_dictionary(dictionary) == exp)\n print(flatten_dictionary_done_differently(dictionary) == exp)\n print(flatten_dictionary_loop_and_stack(dictionary) == exp)\n\n # ex3\n dictionary = {\"Key1\":\"1\",\"Key2\":{\"a\":\"2\",\"b\":\"3\",\"c\":{\"d\":\"3\",\"e\":\"1\"}}}\n exp = {\"Key1\":\"1\",\"Key2.a\":\"2\",\"Key2.b\":\"3\",\"Key2.c.d\":\"3\",\"Key2.c.e\":\"1\"}\n print(flatten_dictionary(dictionary) == exp)\n print(flatten_dictionary_done_differently(dictionary) == exp)\n print(flatten_dictionary_loop_and_stack(dictionary) == exp)\n\n # ex4\n dictionary = {\"Key\":{\"a\":\"2\",\"b\":\"3\"}}\n exp = {\"Key.a\":\"2\",\"Key.b\":\"3\"}\n print(flatten_dictionary(dictionary) == exp)\n print(flatten_dictionary_done_differently(dictionary) == exp)\n print(flatten_dictionary_loop_and_stack(dictionary) == exp)\n\n # ex5\n dictionary = {\"Key1\":\"1\",\"Key2\":{\"a\":\"2\",\"b\":\"3\",\"c\":{\"d\":\"3\",\"e\":{\"f\":\"4\"}}}}\n exp = {\"Key1\":\"1\",\"Key2.a\":\"2\",\"Key2.b\":\"3\",\"Key2.c.d\":\"3\",\"Key2.c.e.f\":\"4\"}\n print(flatten_dictionary(dictionary) == exp)\n print(flatten_dictionary_done_differently(dictionary) == exp)\n print(flatten_dictionary_loop_and_stack(dictionary) == exp)\n\n # ex6\n dictionary = {\"\":{\"a\":\"1\"},\"b\":\"3\"}\n exp = {\"a\":\"1\",\"b\":\"3\"}\n print(flatten_dictionary(dictionary) == exp)\n print(flatten_dictionary_done_differently(dictionary) == exp)\n print(flatten_dictionary_loop_and_stack(dictionary) == exp)\n\ntests()\n","repo_name":"markbroich/data_science","sub_path":"coding_challenges_example_solutions/flattern_dict/flattern_dict.py","file_name":"flattern_dict.py","file_ext":"py","file_size_in_byte":5973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41268162295","text":"# if your dataset is in COCO format, this cell can be replaced by the following three lines:\nfrom detectron2.data.datasets import register_coco_instances\nregister_coco_instances(\"svhn_coco_combined_train\", {}, \"./coco_format/svhn_coco_train_combined.json\", \"./coco_format/train/\")\nregister_coco_instances(\"svhn_coco_combined_val\", {}, \"j./coco_format/svhn_coco_val_combined.json\", \"./coco_format/val\")\n\nfrom detectron2.engine import DefaultTrainer\nfrom detectron2.config import get_cfg\nfrom detectron2 import model_zoo\n\nimport os\n\ncfg = get_cfg()\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/faster_rcnn_R_50_C4_1x.yaml\"))\ncfg.DATASETS.TRAIN = (\"svhn_coco_combined_train\",)\ncfg.DATASETS.TEST = ()\ncfg.DATALOADER.NUM_WORKERS = 2\n# cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(\"COCO-Detection/faster_rcnn_R_50_C4_1x.yaml\") # Let training initialize from model zoo\ncfg.SOLVER.IMS_PER_BATCH = 2\ncfg.SOLVER.BASE_LR = 0.00025 # pick a good LR\ncfg.SOLVER.MAX_ITER = 50000 # 300 iterations seems good enough for this toy dataset; you will need to train longer for a practical dataset\ncfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 128 # faster, and good enough for this toy dataset (default: 512)\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 10 # only has one class (ballon). (see https://detectron2.readthedocs.io/tutorials/datasets.html#update-the-config-for-new-datasets)\n# NOTE: this config means the number of classes, but a few popular unofficial tutorials incorrect uses num_classes+1 here.\n\nos.makedirs(cfg.OUTPUT_DIR, exist_ok=True)\ntrainer = DefaultTrainer(cfg) \ntrainer.resume_or_load(resume=False)\ntrainer.train()\n\n","repo_name":"trinanjan12/svhn_digit_recognizer","sub_path":"detectorn2/train_detectron.py","file_name":"train_detectron.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"19940793034","text":"from socket import *\r\nimport time\r\nimport pymysql\r\n\r\nHOST = ''\r\nPORT = 8008\r\nBUFSIZE = 1024\r\nADDR = (HOST,PORT)\r\n\r\n\r\nserver_socket = socket(AF_INET, SOCK_STREAM)\r\nserver_socket.bind(ADDR)\r\nprint('Server launched..')\r\n\r\nserver_socket.listen(1)\r\nprint('Waiting connection..')\r\n\r\nclient_socket, addr = server_socket.accept()\r\nprint('Connected by: ', str(addr))\r\n \r\n### DB connection\r\nconn = pymysql.connect(host='localhost', user='root', password='juneo', \r\n db='mysql', charset='utf8')\r\ncurs = conn.cursor()\r\n### set webcam2 on \r\nsql=\"update Command SET Webcam2 = 'ON'\"\r\n\r\n\r\nwhile True: # Server loop; webcam2 off, alert on\r\n\r\n \r\n ### Read Data\r\n sql =\"select Webcam2 from Command\"\r\n curs.execute(sql)\r\n dbdata = curs.fetchall()\r\n print(data2)\r\n\r\n if 'OFF' in dbdata:\r\n message = 'Webcam2 OFF'\r\n message = message.encode('utf-8')\r\n server_socket.send(message)\r\n elif 'ON' in dbdata:\r\n message = 'Webcam2 ON'\r\n message = message.encode('utf-8')\r\n server_socket.send(message) \r\n \r\n\r\n ### Update Data \r\n clientdata = client_socket.recv(BUFSIZE)\r\n \r\n if 'Alert(DWS)' in clientdata.decode('utf-8'):\r\n sql=\"update Command SET Alert = 'ON'\"\r\n print('Alert(DWS); Set Alert ON in DB')\r\n elif 'Normal' in clientdata.decode('utf-8'):\r\n print('Normal')\r\n \r\n \r\n time.sleep(0.5)\r\n \r\n if not data:\r\n break\r\n\r\n\r\n\r\n","repo_name":"cty0736/rasp_Drowsinessdetectionpart_DB_Socket-","sub_path":"Server_webcam2.py","file_name":"Server_webcam2.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20080078704","text":"import unittest\n\nimport torch\nfrom classy_vision.generic.util import get_torch_version\nfrom classy_vision.models import build_model\nfrom test.generic.utils import compare_model_state\n\n\nMODELS = {\n \"small_densenet\": {\n \"name\": \"densenet\",\n \"num_blocks\": [1, 1, 1, 1],\n \"init_planes\": 4,\n \"growth_rate\": 32,\n \"expansion\": 4,\n \"final_bn_relu\": True,\n \"small_input\": True,\n \"heads\": [\n {\n \"name\": \"fully_connected\",\n \"unique_id\": \"default_head\",\n \"num_classes\": 1000,\n \"fork_block\": \"trunk_output\",\n \"in_plane\": 60,\n \"zero_init_bias\": True,\n }\n ],\n },\n \"small_densenet_se\": {\n \"name\": \"densenet\",\n \"num_blocks\": [1, 1, 1, 1],\n \"init_planes\": 4,\n \"growth_rate\": 32,\n \"expansion\": 4,\n \"final_bn_relu\": True,\n \"small_input\": True,\n \"use_se\": True,\n \"heads\": [\n {\n \"name\": \"fully_connected\",\n \"unique_id\": \"default_head\",\n \"num_classes\": 1000,\n \"fork_block\": \"trunk_output\",\n \"in_plane\": 60,\n \"zero_init_bias\": True,\n }\n ],\n },\n}\n\n\ndef _find_block_full_path(model, block_name):\n \"\"\"Find the full path for a given block name\n e.g. block3-1 --> 3.block3-1\n \"\"\"\n for name, _ in model.named_modules():\n if name.endswith(block_name):\n return name\n return None\n\n\nclass TestDensenet(unittest.TestCase):\n def _test_model(self, model_config):\n \"\"\"This test will build Densenet models, run a forward pass and\n verify output shape, and then verify that get / set state\n works.\n\n I do this in one test so that we construct the model a minimum\n number of times.\n \"\"\"\n model = build_model(model_config)\n\n # Verify forward pass works\n input = torch.ones([1, 3, 32, 32])\n output = model.forward(input)\n self.assertEqual(output.size(), (1, 1000))\n\n # Verify get_set_state\n new_model = build_model(model_config)\n state = model.get_classy_state()\n new_model.set_classy_state(state)\n new_state = new_model.get_classy_state()\n\n compare_model_state(self, state, new_state, check_heads=True)\n\n def _test_quantize_model(self, model_config):\n if get_torch_version() >= [1, 11]:\n import torch.ao.quantization as tq\n from torch.ao.quantization.quantize_fx import convert_fx, prepare_fx\n else:\n import torch.quantization as tq\n from torch.quantization.quantize_fx import convert_fx, prepare_fx\n\n # quantize model\n model = build_model(model_config)\n model.eval()\n\n input = torch.ones([1, 3, 32, 32])\n\n heads = model.get_heads()\n # since prepare changes the code of ClassyBlock we need to clear head first\n # and reattach it later to avoid caching\n model.clear_heads()\n\n prepare_custom_config_dict = {}\n head_path_from_blocks = [\n _find_block_full_path(model.features, block_name)\n for block_name in heads.keys()\n ]\n fqn_to_example_inputs = None\n if get_torch_version() >= [1, 13]:\n from torch.ao.quantization.utils import get_fqn_to_example_inputs\n\n fqn_to_example_inputs = get_fqn_to_example_inputs(model, (input,))\n\n standalone_example_inputs = (torch.randn(1, 3, 3, 3),)\n # we need to keep the modules used in head standalone since\n # it will be accessed with path name directly in execution\n if get_torch_version() >= [1, 13]:\n prepare_custom_config_dict[\"standalone_module_name\"] = [\n (\n head,\n {\"\": tq.default_qconfig},\n fqn_to_example_inputs[\"features.\" + head],\n {\"input_quantized_idxs\": [0], \"output_quantized_idxs\": []},\n None,\n )\n for head in head_path_from_blocks\n ]\n else:\n prepare_custom_config_dict[\"standalone_module_name\"] = [\n (\n head,\n {\"\": tq.default_qconfig},\n standalone_example_inputs,\n {\"input_quantized_idxs\": [0], \"output_quantized_idxs\": []},\n None,\n )\n for head in head_path_from_blocks\n ]\n\n example_inputs = (torch.randn(1, 3, 3, 3),)\n if get_torch_version() >= [1, 13]:\n example_inputs = fqn_to_example_inputs[\"initial_block\"]\n model.initial_block = prepare_fx(\n model.initial_block, {\"\": tq.default_qconfig}, example_inputs\n )\n\n if get_torch_version() >= [1, 13]:\n example_inputs = fqn_to_example_inputs[\"features\"]\n model.features = prepare_fx(\n model.features,\n {\"\": tq.default_qconfig},\n example_inputs,\n prepare_custom_config_dict,\n )\n model.set_heads(heads)\n\n # calibration\n model(input)\n\n heads = model.get_heads()\n model.clear_heads()\n model.initial_block = convert_fx(model.initial_block)\n model.features = convert_fx(model.features)\n model.set_heads(heads)\n\n output = model(input)\n self.assertEqual(output.size(), (1, 1000))\n\n def test_small_densenet(self):\n self._test_model(MODELS[\"small_densenet\"])\n\n @unittest.skipIf(\n get_torch_version() < [1, 13],\n \"This test is using a new api of FX Graph Mode Quantization which is only available after 1.13\",\n )\n def test_quantized_small_densenet(self):\n self._test_quantize_model(MODELS[\"small_densenet\"])\n","repo_name":"facebookresearch/ClassyVision","sub_path":"test/models_densenet_test.py","file_name":"models_densenet_test.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","stars":1563,"dataset":"github-code","pt":"3"}
+{"seq_id":"19490156162","text":"import json\r\nfrom typing import Optional\r\nfrom utilities import concacenate_test_ids\r\n\r\n\r\nBYTES_PER_PSAMPLE = { 0: 153600, 1: 4000020, 2: 5120000, 3: 2400000,\r\n 4: 1048583, 8: 256004, 9: 5120000, 10: 96000,\r\n 11: 64000, 12: 48000, 13: 9225522, 15: 400000,\r\n 16: 5402336, 17: 80000000, 100: 400000, 101: 400000,\r\n 102: 400000, 204: 40000, 205: 614400000, 206: 51200000,\r\n 207: 452016414, 208: 116881518, 209: 260000000}\r\n\r\nNTUPLES = {200: (1, 12), 201: (2, 5), 202: (2,5), 203: (0,32)}\r\n\r\nTEST_IDS = [0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13, 15, 16, 17, 100, 101, 102, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209]\r\n\r\ndef get_bytes_per_psample(args, test_id: int, ntup: Optional[int]) -> Optional[int]:\r\n # test with ntuples\r\n if test_id == 200 and 1 <= ntup <= 12:\r\n return ntup * 800000 + 4\r\n elif test_id == 201 and 2 <= ntup <= 5:\r\n return ntup * 40000\r\n elif test_id == 202 and 2 <= ntup <= 5:\r\n return ntup * 400000\r\n elif test_id == 203 and 0 <= ntup <= 32:\r\n return (ntup + 1) * 4000000\r\n # tests with irregular length\r\n elif test_id in {13, 16, 207, 208}:\r\n return int(BYTES_PER_PSAMPLE[test_id] * (1 + args.dieharder_threshold))\r\n # rest of tests\r\n elif test_id in {0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 15, 17, 100, 101, 102, 204, 205, 206, 209} and ntup is None:\r\n return BYTES_PER_PSAMPLE[test_id]\r\n raise ValueError(\"Invalid test id or combination of test id and ntuples\")\r\n\r\n\r\ndef calculate_psamples(args, test_id: int, ntup: Optional[int], file_size: int) -> int:\r\n if test_id == 0:\r\n psamples = (file_size - 24) // get_bytes_per_psample(args, test_id, ntup)\r\n else:\r\n psamples = file_size // get_bytes_per_psample(args, test_id, ntup)\r\n return psamples + (1 if args.increased else 0)\r\n\r\n\r\ndef dieharder_variant(args, test_id: int, ntup: int, file_size: int):\r\n psamples = calculate_psamples(args, test_id, ntup, file_size)\r\n if psamples == 0:\r\n return None\r\n result = {}\r\n result[\"arguments\"] = \"-n {}\".format(ntup)\r\n if test_id == 201:\r\n result[\"arguments\"] += \" -t 10000\"\r\n result[\"psamples\"] = psamples \r\n return result\r\n\r\n\r\ndef dieharder_test(args, data_size: int):\r\n result = {\"defaults\": {\r\n \"psamples\": 100,\r\n \"test-ids\": []},\r\n \"test-specific-settings\": [],\r\n \"omitted-tests\": []}\r\n for test_id in TEST_IDS:\r\n if test_id in {200, 201, 202, 203}:\r\n dieharder_test_with_variants(args, test_id, result, data_size)\r\n else:\r\n dieharder_no_variant_test(args, test_id, result, data_size)\r\n result[\"defaults\"][\"test-ids\"] = concacenate_test_ids(result[\"defaults\"][\"test-ids\"])\r\n result[\"omitted-tests\"] = concacenate_test_ids(result[\"omitted-tests\"])\r\n return result\r\n\r\n\r\ndef dieharder_no_variant_test(args, test_id, result, data_size: int):\r\n psamples = calculate_psamples(args, test_id, None, data_size)\r\n if psamples > 0:\r\n result[\"defaults\"][\"test-ids\"].append(test_id)\r\n result[\"test-specific-settings\"].append({\r\n \"test-id\": test_id,\r\n \"psamples\": psamples\r\n }) \r\n if test_id in {13, 16, 207, 208}:\r\n result[\"test-specific-settings\"][-1][\"comment\"] = \"WARNING - this test reads irregular ammount of bytes.\"\r\n else:\r\n result[\"omitted-tests\"].append(test_id)\r\n\r\n\r\ndef dieharder_test_with_variants(args, test_id, result, data_size: int):\r\n test = {\r\n \"test-id\": test_id,\r\n \"variants\": [],\r\n \"omitted-variants\": []\r\n }\r\n ntup_min, ntup_max = NTUPLES[test_id]\r\n for ntup in range(ntup_min, ntup_max + 1):\r\n variant = dieharder_variant(args, test_id, ntup, data_size)\r\n if variant is None:\r\n test[\"omitted-variants\"].append(\"-n {}\".format(ntup))\r\n else:\r\n test[\"variants\"].append(variant)\r\n\r\n if len(test[\"variants\"]) == 0:\r\n result[\"omitted-tests\"].append(test_id)\r\n else:\r\n result[\"defaults\"][\"test-ids\"].append(test_id)\r\n result[\"test-specific-settings\"].append(test)\r\n\r\n\r\ndef dieharder_defaults(args):\r\n defaults = {\"test-ids\": concacenate_test_ids(TEST_IDS),\r\n \"test-specific-defaults\": []}\r\n for test_id in TEST_IDS:\r\n test = {\"test-id\": test_id,\r\n \"psamples\": 100}\r\n \r\n if test_id in {200, 201, 202, 203}:\r\n ntup_min, ntup_max = NTUPLES[test_id]\r\n test[\"ntup-range\"] = \"{} - {}\".format(ntup_min, ntup_max)\r\n test[\"variants\"] = []\r\n for ntup in range(ntup_min, ntup_max + 1):\r\n test[\"variants\"].append({\r\n \"ntup\" : ntup,\r\n \"bytes-per-psamples\": get_bytes_per_psample(args, test_id, ntup)\r\n })\r\n else:\r\n test[\"bytes-per-psample\"] = get_bytes_per_psample(args, test_id, None)\r\n\r\n if test_id in {201, 204}:\r\n test[\"psamples\"] = 1000\r\n if test_id in {205, 206, 207, 208, 209}:\r\n test[\"psamples\"] = 1\r\n defaults[\"test-specific-defaults\"].append(test)\r\n return defaults","repo_name":"xmarek7/Bc-Thesis-RTT-misc","sub_path":"config_calc/dieharder.py","file_name":"dieharder.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13423132927","text":"''' Men: Calories = ((Age x 0.2017) - (Weight x 0.09036) + (Heart Rate x 0.6309) - 55.0969) x Time / 4.184 '''\n''' Women: Calories = ((Age x 0.074) - (Weight x 0.05741) + (Heart Rate x 0.4472) - 20.4022) x Time / 4.184 '''\n\n''' Type your code here. '''\nclass BurnCalories:\n def __init__(self, age, weight, heart_rate, time):\n self.age = age\n self.weight = weight\n self.heart_rate = heart_rate\n self.time = time\n \n def process_information(self, men_calories = 0, women_calories = 0):\n men_calories = ((self.age * 0.2017) - (self.weight * 0.09036) + (self.heart_rate * 0.6309) - 55.0969) * self.time / 4.184\n women_calories = ((self.age * 0.074) - (self.weight * 0.05741) + (self.heart_rate * 0.4472) - 20.4022) * self.time / 4.184\n return 'Men: {:.2f} calories\\nWomen: {:.2f} calories'.format(men_calories, women_calories)\n\nwho = BurnCalories(age = int(input()),\n weight = float(input()),\n heart_rate = float(input()),\n time = int(input()))\nprint(who.process_information())\n","repo_name":"quangdbui9999/CS-171","sub_path":"week2Python/Week2/burnCalories.py","file_name":"burnCalories.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32579235","text":"# 일곱 난쟁이\n# combinations를 사용하여 아홉 난쟁이 중 일곱 난쟁이를 뽑는 모든 경우의 수를 생성\nfrom itertools import combinations\n\nn = 9\ndwarves = [int(input()) for _ in range(n)]\n\n\n# 아홉 난쟁이 중 일곱 난쟁이를 뽑는 모든 경우의 수 리스트\ndwarvesList = list(combinations(dwarves, 7))\n\nfor data in dwarvesList:\n # combinations의 반환 형태는 튜플이기 때문에 리스트로 변환\n # why? sum함수를 사용하기 위해\n data = list(data)\n if sum(data) == 100:\n answer = data\n break\n\nanswer.sort()\nfor i in answer:\n print(i)\n","repo_name":"limgeonho/Algorithm-1","sub_path":"BOJ/Brute-Force/[BOJ]2309.py","file_name":"[BOJ]2309.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10034389372","text":"class GlobalData:\n def __init__(self):\n self.units = []\n self.nMat = 0\n self.unit_dict = {'M':'[-]',\n 'K0y':'[-]',\n 'K0x':'[-]',\n 'gamma_D':'[F/L3]',\n 'KSR_0':'[-]',\n 'nu_ur':'[-]',\n 'OCR':'[-]',\n 'Eref_ur':'[P]',\n 'Eref_50':'[P]',\n 'e_0':'[-]',\n 'gamma_f':'[F/L3]',\n 'INT5':'[-]',\n 'INT4':'[-]',\n 'INT7':'[-]',\n 'INT6':'[-]',\n 'INT1':'[-]',\n 'INT3':'[-]',\n 'E_oed':'[P]',\n 'Eref_0':'[P]',\n 'INT9':'[-]',\n 'nu':'[-]',\n 'phi':'[D]',\n 'psi':'[D]',\n 'E':'[P]',\n 'D':'[-]',\n 'H':'[-]',\n 'INT2':'[-]',\n 'SS_ext':'[-]',\n 'pmin_co':'[P]',\n 'sigref_oed':'[P]',\n 'R_f':'[-]',\n 'c':'[P]',\n 'sig_L':'[P]',\n 'KNC_0':'[-]',\n 'm':'[-]',\n 'gam_07':'[-]',\n 'INT8':'[-]',\n 'f_t':'[P]',\n 'f_c':'[P]',\n 'sig_ref':'[P]',\n 'gamma':'[F/L3]',\n 'Ix':'[L4]',\n 'Iy':'[L4]',\n 'Iz':'[L4]',\n 'b':'[L]',\n 'h':'[L]',\n 'inp_type':'[-]',\n 'Ax':'[L2]',\n 'Ay':'[L2]',\n 'Az':'[L2]',\n 'Kt/Kn':'[-]',\n 'Kn':'[-]',\n 'inherit':'[-]',\n 'k_x':'[L/T]',\n 'k_y':'[L/T]',\n 'k_z':'[L/T]',\n 'S_rres':'[-]',\n 'alpha':'[-]',\n 'pen':'[-]',\n 'cutoff':'[-]',\n 'K_f':'[-]',\n 'Profile':'[-]',\n 'Database':'[-]',\n 'm_b':'[-]',\n 'a':'[-]',\n 's':'[-]'}\n\nclass ZSmaterial:\n def __init__(self):\n self.version = 0\n self.number = 0\n self.name = 0\n self.type = 0\n self.buttons = []\n self.groups = []\n \n self.elas = {}\n self.main = {}\n self.nonl = {}\n self.geom = {}\n self.dens = {}\n self.flow = {}\n self.creep = {}\n self.heat = {}\n self.humid = {}\n self.inis = {}\n self.stab = {}\n self.damp = {}\n\n def read_Data(self,data):\n print('read_Data')\n continuum = ['Elastic','HS-small strain stiffness','Mohr-Coulomb']\n \n lines = data[0]\n self.groups.append('elas')\n if 'Elastic' in self.type or 'Mohr-Coulomb' in self.type \\\n or self.type=='Multilaminate' or 'Hoek-Brown' in self.type:\n self.elas['E'] = float(lines[0].split()[1])\n self.elas['nu'] = float(lines[0].split()[2])\n elif (self.type=='HS-small strain stiffness' or\n self.type=='Densification model'):\n self.elas['Eref_ur'] = float(lines[0].split()[1])\n self.elas['sig_ref'] = float(lines[0].split()[4])\n self.elas['nu_ur'] = float(lines[0].split()[2])\n self.elas['m'] = float(lines[0].split()[3])\n self.elas['sig_L'] = float(lines[0].split()[5])\n self.elas['SS_ext'] = int(float(lines[0].split()[7]))\n self.elas['Eref_0'] = float(lines[0].split()[8])\n self.elas['gam_07'] = float(lines[0].split()[9])\n elif self.type=='Contact':\n self.elas['Kn'] = float(lines[0].split()[1])\n self.elas['Kt/Kn'] = float(lines[0].split()[2])\n\n lines = data[1]\n if self.type=='Elastic Beam':\n self.groups.append('geom')\n self.geom['inp_type'] = int(lines[0].split()[1])\n if self.geom['inp_type']==0: # specification by profile DB\n self.geom['Database'] = lines[1]\n self.geom['Profile'] = lines[2]\n ind = 3\n elif self.geom['inp_type']==1: # specification by geometry\n self.geom['b'] = float(lines[1].split()[1])\n self.geom['h'] = float(lines[1].split()[3])\n ind = 2\n elif self.geom['inp_type']==2: # specification by values\n ind = 1\n else:\n print('Error in read_Data')\n self.geom['Ix'] = float(lines[ind].split()[3])\n self.geom['Iy'] = float(lines[ind].split()[4])\n self.geom['Iz'] = float(lines[ind].split()[5])\n self.geom['Ax'] = float(lines[ind].split()[0])\n self.geom['Ay'] = float(lines[ind].split()[1])\n self.geom['Az'] = float(lines[ind].split()[2])\n\n lines = data[2]\n if self.type=='Beam':\n self.groups.append('main')\n self.main['flex_based'] = int(lines[0].split()[1])\n\n lines = data[3]\n if 'interface' not in self.type and 'hinge' not in self.type:\n self.groups.append('dens')\n self.dens['gamma'] = float(lines[0].split()[1])\n if self.type in continuum:\n self.dens['gamma_f'] = float(lines[0].split()[2])\n self.dens['e_0'] = float(lines[0].split()[3])\n self.dens['gamma_D'] = float(lines[0].split()[6])\n\n lines = data[4]\n if self.buttons[4]==1 and not self.type=='Seepage' and 'hinge' not in self.type:\n self.groups.append('flow')\n self.flow['k_x'] = float(lines[0].split()[1])\n self.flow['k_y'] = float(lines[0].split()[2])\n self.flow['k_z'] = float(lines[0].split()[3])\n self.flow['K_f'] = float(lines[0].split()[11])\n if self.type in continuum:\n self.flow['S_rres'] = float(lines[0].split()[12])\n self.flow['alpha'] = float(lines[0].split()[13])\n self.flow['pen'] = float(lines[0].split()[17])\n self.flow['cutoff'] = float(lines[0].split()[18])\n\n lines = data[5]\n if self.buttons[5]==1:\n self.groups.append('creep')\n self.creep['Ad'] = float(lines[0].split()[4])\n self.creep['Av'] = float(lines[0].split()[6])\n self.creep['Bd'] = float(lines[0].split()[5])\n self.creep['Bv'] = float(lines[0].split()[7])\n self.creep['EF1'] = int(lines[0].split()[2])\n self.creep['EF2'] = int(lines[0].split()[3])\n self.creep['a'] = float(lines[0].split()[8])\n self.creep['b'] = float(lines[0].split()[9])\n\n lines = data[6]\n if 'Mohr-Coulomb' in self.type:\n self.groups.append('nonl')\n self.nonl['c'] = float(lines[0].split()[4])\n self.nonl['phi'] = float(lines[0].split()[2])\n self.nonl['psi'] = float(lines[0].split()[3])\n elif 'Hoek-Brown' in self.type:\n self.groups.append('nonl')\n self.nonl['f_c'] = float(lines[1].split()[0])\n## self.nonl['psi'] = float(lines[0].split()[3])\n self.nonl['m'] = float(lines[1].split()[1])\n self.nonl['s'] = float(lines[1].split()[2])\n self.nonl['a'] = float(lines[1].split()[3])\n elif (self.type=='HS-small strain stiffness' or\n self.type=='Densification model'):\n self.groups.append('nonl')\n self.nonl['phi'] = float(lines[0].split()[1])\n self.nonl['psi'] = float(lines[0].split()[2])\n self.nonl['c'] = float(lines[0].split()[3])\n self.nonl['Eref_50'] = float(lines[0].split()[4])\n self.nonl['R_f'] = float(lines[0].split()[5])\n self.nonl['f_t'] = int(float(lines[0].split()[6]))\n self.nonl['D'] = float(lines[0].split()[7])\n self.nonl['INT1'] = int(float(lines[0].split()[8]))\n self.nonl['INT2'] = int(float(lines[0].split()[9]))\n self.nonl['INT3'] = int(float(lines[0].split()[10]))\n self.nonl['H'] = float(lines[1].split()[0])\n self.nonl['M'] = float(lines[1].split()[1])\n self.nonl['KNC_0'] = float(lines[1].split()[2])\n self.nonl['sigref_oed'] = float(lines[1].split()[3])\n self.nonl['E_oed'] = float(lines[1].split()[4])\n self.nonl['INT4'] = int(float(lines[2].split()[0]))\n self.nonl['INT5'] = int(float(lines[2].split()[1]))\n self.nonl['INT6'] = int(float(lines[3].split()[0]))\n self.nonl['pmin_co'] = int(float(lines[3].split()[1]))\n self.nonl['INT7'] = int(float(lines[3].split()[2]))\n self.nonl['OCR'] = int(float(lines[3].split()[3]))\n self.nonl['KSR_0'] = int(float(lines[3].split()[4]))\n self.nonl['INT8'] = int(float(lines[3].split()[5]))\n self.nonl['INT9'] = int(float(lines[3].split()[6]))\n elif self.type=='Contact':\n self.groups.append('nonl')\n self.nonl['inherit'] = float(lines[0].split()[5])\n if self.nonl['inherit']==0:\n self.nonl['phi'] = float(lines[0].split()[1])\n self.nonl['psi'] = float(lines[0].split()[2])\n self.nonl['c'] = float(lines[0].split()[3])\n\n lines = data[7]\n if self.buttons[7]==1:\n self.groups.append('heat')\n self.heat['dil'] = float(lines[0].split()[1])\n if self.type in continuum:\n self.heat['cond'] = float(lines[0].split()[2])\n self.heat['cap'] = float(lines[0].split()[3])\n\n lines = data[8]\n if self.buttons[8]==1:\n self.groups.append('humid')\n self.humid['dil'] = float(lines[0].split()[1])\n self.humid['a'] = float(lines[0].split()[2])\n self.humid['WI'] = float(lines[0].split()[3])\n self.humid['DI'] = float(lines[0].split()[4])\n\n lines = data[9]\n if self.buttons[9]==1:\n self.groups.append('inis')\n self.inis['K0x'] = float(lines[0].split()[1])\n self.inis['K0y'] = float(lines[0].split()[2])\n\n lines = data[12]\n if self.buttons[13]==1:\n self.groups.append('damp')\n self.damp['alpha'] = float(lines[0].split()[1])\n self.damp['beta'] = float(lines[0].split()[2])\n\n def read_mat(global_data,fname): \n f = file(fname)\n\n materials = []\n for line in iter(lambda: f.readline(), \"\"):\n if 'NUM_MATERIALS=' in line:\n global_data.nMat = int(float(line.split('=')[1]))\n line = f.readline()\n for km in range(global_data.nMat):\n mat = ZSmaterial.ZSmaterial()\n materials.append(mat)\n # readmat proc:\n mat.version = line.split()[1]\n mat.number = line.split()[2]\n line = f.readline()\n mat.type = line[:-1]\n line = f.readline()\n mat.name = line[:-1]\n line = f.readline()\n v = line.split('=')[1].split()\n for val in v:\n mat.buttons.append(int(float(val)))\n data = [[] for k in range(13)]\n line = f.readline()\n while not 'MATERIAL' in line:\n if 'ELAS' in line:\n ind = 0\n data[0].append(line)\n elif 'GEOM' in line:\n ind = 1\n data[1].append(line)\n elif 'MAIN' in line:\n ind = 2\n data[2].append(line)\n elif 'DENS' in line:\n ind = 3\n data[3].append(line)\n elif 'FLOW' in line:\n ind = 4\n data[4].append(line)\n elif 'CREEP' in line:\n ind = 5\n data[5].append(line)\n elif 'NONL' in line:\n ind = 6\n data[6].append(line)\n elif 'HEAT' in line:\n ind = 7\n data[7].append(line)\n elif 'HUMID' in line:\n ind = 8\n data[8].append(line)\n elif 'INIS' in line:\n ind = 9\n data[9].append(line)\n elif 'STAB' in line:\n ind = 10\n data[10].append(line)\n elif 'DISC' in line:\n ind = 11\n data[11].append(line)\n elif 'DAMP' in line:\n ind = 12\n data[12].append(line)\n elif not line=='\\n':\n data[ind].append(line)\n line = f.readline()\n print(mat.number,mat.name,mat.type)\n mat.read_Data(data)\n # end readmat proc\n elif 'STANDARD' in line:\n line = f.readline()\n v = line.split()\n for vv in v:\n global_data.units.append(vv)\n global_data.units.append(v[0][0]+'Pa')\n\n f.close()\n\n return materials\n\n def write_mat(self,path,prob):\n workbook = xlsxwriter.Workbook(path + '/mat_' + prob + '.xlsx')\n\n # format definitions:\n subscript = workbook.add_format({'font_script':2})\n superscript = workbook.add_format({'font_script':1})\n symbol = workbook.add_format()\n symbol.set_font_name('Symbol')\n header = workbook.add_format({'bg_color':'#C5BE97','border':1,'align':'vcenter'})\n\n groupnames = ['Elastic','Geometry','Main','Density','Flow',\n 'Creep','Nonlinear','Heat','Humidity','Stability','Damping',\n 'Initial state']\n groupnames_active = []\n gps = ['elas','geom','main','dens','flow',\n 'creep','nonl','heat','humid','stab','damp','inis']\n\n gps_active0 = set()\n gps_active = []\n for km,mat in enumerate(materials):\n for gp in mat.groups:\n gps_active0.add(gp)\n for kgp,gp in enumerate(gps):\n if gp in gps_active0:\n gps_active.append(gp)\n groupnames_active.append(groupnames[kgp])\n nGroups = len(gps_active)\n\n headers = [set() for kg in range(nGroups)]\n for km,mat in enumerate(materials):\n for kg in range(nGroups):\n data = getattr(mat,gps_active[kg])\n for key in data.iterkeys():\n headers[kg].add(key)\n for kg,h in enumerate(headers):\n headers[kg] = list(h)\n\n for kg in range(nGroups):\n worksheet = workbook.add_worksheet(groupnames_active[kg])\n\n # write general headers:\n worksheet.write(0,0,'Version',header)\n worksheet.write(0,1,'Number',header)\n worksheet.write(0,2,'Name',header)\n worksheet.write(0,3,'Type',header)\n worksheet.set_column(0,0,6.86)\n worksheet.set_column(1,1,7.29)\n worksheet.set_column(2,2,30)\n worksheet.set_column(3,3,21.86)\n\n # write group-specific headers:\n for kh,head in enumerate(headers[kg]):\n if '_' in head:\n worksheet.write_rich_string(0,4+kh,head.split('_')[0],subscript,head.split('_')[1],header)\n else:\n worksheet.write_rich_string(0,4+kh,head,header)\n\n # write units:\n for kh,head in enumerate(headers[kg]):\n astr = re.sub('L',gd.units[1],gd.unit_dict[head])\n astr = re.sub('F',gd.units[0],astr)\n astr = re.sub('D',u'°',astr)\n astr = re.sub('T',gd.units[3],astr)\n astr = re.sub('H',gd.units[4],astr)\n astr = re.sub('P',gd.units[5],astr)\n worksheet.write_string(1,4+kh,astr,header)\n\n for km,mat in enumerate(materials):\n name = unicode(mat.name,sys.stdin.encoding)\n worksheet.write(km+2,0, 'v'+mat.version)\n worksheet.write_number(km+2,1, int(mat.number))\n worksheet.write(km+2,2, name)\n worksheet.write(km+2,3, mat.type)\n\n data = getattr(mat,gps_active[kg])\n for key in data:\n worksheet.write(km+2,4+headers[kg].index(key),data[key])\n\n # create summary continuum:\n\n header = workbook.add_format({'bg_color':'#C5BE97','border':1,'align':'center'})\n header.set_align('vcenter')\n cell = workbook.add_format({'border':1,'align':'center'})\n cell.set_align('vcenter')\n\n worksheet = workbook.add_worksheet('Summary')\n\n # headers:\n worksheet.merge_range(0,0,1,0,u'Matériau',header)\n worksheet.merge_range(0,1,1,1,'Type',header)\n worksheet.write_rich_string(0,2,symbol,'g',header)\n worksheet.write_rich_string(0,3,symbol,'g',subscript,'D',header)\n worksheet.write_rich_string(0,4,'E',subscript,'50',header)\n worksheet.write_rich_string(0,5,'E',subscript,'ur',header)\n worksheet.write_rich_string(0,6,'E',subscript,'0',header)\n worksheet.write_rich_string(0,7,symbol,'s',subscript,'h,ref',header)\n worksheet.write_rich_string(0,8,symbol,'f','\\'',header)\n worksheet.write(0,9,'c\\'',header)\n worksheet.set_column(0,0,12)\n worksheet.set_column(1,1,22)\n worksheet.set_column(2,12,8)\n ##worksheet.set_column(3,3,5)\n ##worksheet.set_column(3,3,5)\n ##worksheet.set_column(3,3,5)\n ##worksheet.set_column(3,3,5)\n ##worksheet.set_column(3,3,5)\n\n # units:\n worksheet.write_rich_string(1,2,'[kN/m',superscript,'3',']',header)\n worksheet.write_rich_string(1,3,'[kN/m',superscript,'3',']',header)\n worksheet.write(1,4,'[MPa]',header)\n worksheet.write(1,5,'[MPa]',header)\n worksheet.write(1,6,'[MPa]',header)\n worksheet.write(1,7,'[kPa]',header)\n worksheet.write(1,8,u'[°]',header)\n worksheet.write(1,9,'[kPa]',header)\n\n # write material data:\n kkm = -1\n for km,mat in enumerate(materials):\n if (mat.type=='HS-small strain stiffness'\n or mat.type=='Densification model'\n or 'Mohr' in mat.type\n or 'Hoek-Brown' in mat.type):\n print(km,mat.type,mat.name)\n kkm += 1\n worksheet.write(kkm+2,0, unicode(mat.name,sys.stdin.encoding),cell)\n worksheet.write(kkm+2,1, mat.type,cell)\n worksheet.write(kkm+2,2, mat.dens['gamma'],cell)\n try:\n worksheet.write(kkm+2,3, mat.dens['gamma_D'],cell)\n except:\n pass\n if (mat.type=='HS-small strain stiffness' or\n mat.type=='Densification model'):\n worksheet.write(kkm+2,4, mat.nonl['Eref_50']*1e-3,cell)\n worksheet.write(kkm+2,5, mat.elas['Eref_ur']*1e-3,cell)\n worksheet.write(kkm+2,6, mat.elas['Eref_0']*1e-3,cell)\n worksheet.write(kkm+2,7, mat.elas['sig_ref'],cell)\n else:\n worksheet.merge_range(kkm+2,4,kkm+2,6, mat.elas['E']*1e-3,cell)\n try:\n worksheet.write(kkm+2,8, mat.nonl['phi'],cell)\n worksheet.write(kkm+2,9, mat.nonl['c'],cell)\n except:\n worksheet.write(kkm+2,8, '',cell)\n worksheet.write(kkm+2,9, '',cell)\n \n\n workbook.close()\n \n","repo_name":"mattpre/zsoil_tools","sub_path":"zsoil_tools/ZSmaterial.py","file_name":"ZSmaterial.py","file_ext":"py","file_size_in_byte":20836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36945305226","text":"from os.path import dirname, abspath\nimport torch \nimport torch.nn as nn\nimport ujson\nimport codecs\nimport numpy as np\nfrom torch import Tensor\nfrom typing import Union\n\nparent_path = abspath(dirname(dirname(__file__))) + '/data/'\nCHAR2ID_FILE = parent_path + 'char2id.json'\n\n# bert vocab\nTORCH_BERT_DIR = parent_path + '/model_file/bert'\nBERT_VOCAB = TORCH_BERT_DIR + '/vocab.txt'\n\n# 位置编码(静态编码,不可训练)\nclass PositionEmbedding(nn.Module):\n def __init__(self, embedding_size: int, max_seq_len: int=512):\n '''\n 位置编码层,该层没有要训练的参数\n max_sep_len: 句子的最大长度,或者对齐(padding)的长度\n embedding_size: 一个词对应的词向量大小\n '''\n super(PositionEmbedding, self).__init__()\n\n # 根据论文公式构造PE矩阵\n position_encoding = np.array([\n [pos / np.power(10000, (2.0 * i) / embedding_size) for i in range(embedding_size)] \\\n for pos in range(max_seq_len)\n ])\n\n # 奇数列用cos处理,偶数列用sin处理\n position_encoding[:, 1:: 2] = np.cos( position_encoding[:, 1:: 2] )\n position_encoding[:, 0:: 2] = np.sin( position_encoding[:, 0:: 2] )\n \n # 填充字符'[PAD]'position_encoding[0]的位置\n pad_encoding = torch.zeros((1, embedding_size), dtype=torch.float32)\n position_encoding = torch.cat( (pad_encoding, torch.Tensor(position_encoding)) )\n\n # num_embeddings= max_sep_len + 1, +1是因为添加了一个填充字符的编码\n # embedding_dim= embedding_size\n self.position_embedding = nn.Embedding(max_seq_len + 1, embedding_size)\n self.position_embedding.weight = nn.Parameter(position_encoding, requires_grad=False)\n self.max_seq_len = max_seq_len\n\n def forward(self, sequence_len, is_mask: bool = False, max_len: int=None):\n '''\n is_mask = False:\n sequence_len: [batch_size,], int or long, 一个batch中每个句子的真实长度,不包括填充的长度\n 如:[1,5,7]\n \n 设置is_mask = True表示传入的sequence_len是mask\n is_maks = True:\n sequence_len: [batch_size, padded_len or max_seq_len]\n 如:[[1, 1, 0],[1, 0, 0]]\n '''\n mask = None\n if is_mask:\n mask = sequence_len\n sequence_len = torch.sum(sequence_len, dim=1, keepdim=True, dtype=torch.long)\n \n if max_len is None:\n max_len = torch.max(sequence_len)\n\n # range从1开始是因为embedding[0]放置的是pad的位置向量\n sequence_len_cpu = sequence_len.cpu().detach().numpy()\n input_id = [list(range(1, seq_len + 1)) + [0] * (max_len - seq_len) for seq_len in sequence_len_cpu]\n input_id = torch.LongTensor(input_id).to(sequence_len.device)\n \n outputs = self.position_embedding(input_id)\n\n if is_mask:\n mask = torch.unsqueeze(mask, dim=2)\n outputs = torch.mul(outputs, mask)\n \n return outputs\n\n# 位置编码(动态编码,可训练)\nclass DynamicPositionEmbedding(nn.Module):\n def __init__(self, embedding_size: int, max_seq_len: int=512, device: str='cuda'):\n '''\n 动态位置编码层,该层没有要训练的参数\n max_sep_len: 句子的最大长度,或者对齐(padding)的长度\n embedding_size: 一个词对应的词向量大小\n '''\n super(DynamicPositionEmbedding, self).__init__()\n\n # num_embeddings= max_sep_len + 1, +1是因为添加了一个填充字符的编码\n # embedding_dim= embedding_size\n self.position_embedding = nn.Embedding(\n num_embeddings=max_seq_len + 1,\n embedding_dim=embedding_size,\n padding_idx=0, # 填充的id是0\n ).to(device)\n \n self.max_seq_len = max_seq_len\n\n def forward(self, sequence_len, is_mask: bool = False, max_len: int=None):\n '''\n is_mask = False:\n sequence_len: [batch_size,], int or long, 一个batch中每个句子的真实长度,不包括填充的长度\n 如:[1,5,7]\n \n 设置is_mask = True表示传入的sequence_len是mask\n is_maks = True:\n sequence_len: [batch_size, padded_len or max_seq_len]\n 如:[[1, 1, 0],[1, 0, 0]]\n '''\n mask = None\n if is_mask:\n mask = sequence_len\n sequence_len = torch.sum(sequence_len, dim=1, keepdim=True, dtype=torch.long)\n \n if max_len is None:\n max_len = torch.max(sequence_len)\n\n # range从1开始是因为embedding[0]放置的是pad的位置向量\n sequence_len_cpu = sequence_len.cpu().detach().numpy()\n input_id = [list(range(1, seq_len + 1)) + [0] * (max_len - seq_len) for seq_len in sequence_len_cpu]\n input_id = torch.LongTensor(input_id).to(sequence_len.device)\n \n outputs = self.position_embedding(input_id)\n\n if is_mask:\n mask = torch.unsqueeze(mask, dim=2)\n outputs = torch.mul(outputs, mask)\n \n return outputs\n\nclass TorchEmbedding(nn.Module):\n def __init__(self, embedding_size: int, device: str='cuda', char2id_file: str=CHAR2ID_FILE, from_pertrain: str=None):\n '''\n embedding_size: 词向量大小\n char2id_file: char2id的json文件\n '''\n super(TorchEmbedding, self).__init__()\n \n self.device = device\n\n # [pad]: 0, [unk]: 1,\n with codecs.open(char2id_file, 'r', encoding='utf-8') as f:\n self.char2id = ujson.load(f)\n\n if from_pertrain is not None:\n embedding_init = np.load(from_pertrain).astype(np.float32)\n embedding_init = torch.FloatTensor(embedding_init)\n self.embedding = nn.Embedding.from_pretrained(embedding_init, freeze=False, padding_idx=0).to(device)\n else:\n self.embedding = nn.Embedding(\n num_embeddings=len(self.char2id),\n embedding_dim=embedding_size,\n padding_idx=0, # 填充的id是0\n ).to(device)\n\n def tokenize(self, text: list, max_len: int=None):\n '''\n args:\n text: 一个n个文本的list\n max_len: 文本的最大对齐长度\n return :\n text_id: 文本中每个字符对应的id\n mask: 长度和max_len一直,有字符的位置为1.0,填充的字符为0.0\n '''\n # [pad]: 0, [unk]: 1,\n\n length = np.array([len(text) for text in text], dtype=np.int64)\n batch_size = len(text)\n\n if max_len is None:\n max_len = max(length)\n\n text_id = np.zeros((batch_size, max_len), dtype=np.int64)\n get = self.char2id.get\n\n for i in range(batch_size):\n for j, char in enumerate(text[i]):\n text_id[i][j] = get(char, 1) # 没有找到字符返回1,1是unk\n\n text_id = torch.from_numpy(text_id).to(self.device)\n length = torch.from_numpy(length).to(self.device)\n\n return text_id, length\n\n def text_to_embedding(self, text: Union[list, str], max_len: int=None):\n '''\n 多个文本转向量\n return:\n text_embedding: [batch_size, max_len, embedding_size]\n length: [batch_size, 1]\n '''\n return self.forward(text, max_len)\n \n def forward(self, text: Union[list, str], max_len: int=None, requires_grad: bool=True):\n if isinstance(text, str):\n text = [text]\n \n input_id, text_length = self.tokenize(text, max_len=max_len)\n text_embedding = self.embedding(input_id)\n\n if not requires_grad:\n text_embedding = text_embedding.detach()\n\n return text_embedding, text_length\n\nclass ClassEmbedding(nn.Module):\n def __init__(self, num_class: int, embedding_size: int):\n super(ClassEmbedding, self).__init__()\n self.embedding = nn.Embedding(num_embeddings=num_class, embedding_dim=embedding_size)\n\n def forward(self, class_id: Tensor):\n return self.embedding(class_id)\n\nclass EmbeddingProcessor(nn.Module):\n def __init__(self, embedding_dim: int, dropout_prob: float=0.25):\n super(EmbeddingProcessor, self).__init__()\n \n self.embedding_dropout = nn.Dropout(dropout_prob)\n self.embedding_layer_norm = nn.LayerNorm((embedding_dim))\n\n def forward(self, input_embedding: Tensor, position_embedding: Tensor=None):\n\n if position_embedding is not None:\n input_embedding = input_embedding + position_embedding\n \n input_embedding = self.embedding_dropout(input_embedding)\n outs = self.embedding_layer_norm(input_embedding)\n\n return outs\n\nif __name__ == \"__main__\":\n\n embedding = ClassEmbedding(3, 4)\n c_id = torch.LongTensor([1,0,1,2])\n emb = embedding(c_id)\n print(emb.shape)\n print(emb)\n\n exit()\n # mask = torch.LongTensor([\n # [1, 1, 1, 1, 0, 0],\n # [1, 1, 1, 1, 1, 0]\n # ])\n # position_embedding = PositionEmbedding(embedding_size=4)\n # pos_emb = position_embedding(mask, is_mask=True, max_len=6)\n # print(pos_emb.shape)\n # print(pos_emb.dtype)\n\n\n embedding = TorchEmbedding(embedding_size=4, device='cpu')\n proc = EmbeddingProcessor(embedding_dim=4)\n\n text = ['你好吗?','你 好']\n \n emb, length = embedding(text, requires_grad=False)\n print(length)\n print(emb.shape)\n print(emb)\n print(proc(emb))\n ","repo_name":"charent/pytorch_IE_model","sub_path":"embedding/torchEmbedding.py","file_name":"torchEmbedding.py","file_ext":"py","file_size_in_byte":9582,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"72861170320","text":"\"\"\"\nThe set of all possible outcomes of a random experiment is called the sample space of the experiment.\n\nAn event is defined as a particular subset of the sample space to be considered.\nFor any given event, only one of two possibilities may hold: it occurs or it does not.\n\nThe relative frequency of occurrence of an event, observed in a number of repetitions of the experiment,\nis a measure of the probability of that event.\n\nWe assume that the relative frequency converges to a value as the number of trials increases.\n\nTherefore, according to the frequency interpretation of probability, an event's probability is the limit of the relative\nfrequency of the event as the number of trials approaches infinity.\n\"\"\"\n\ndef freq_prob(convergence_tolerance, initial_num_trials, max_num_iter, random_experiment):\n\n \"\"\"\n Calculates the frequentist probability by simulating trials of a random experiment until the relative frequency converges.\n\n The first simulation calculates the relative frequency resulting from running 'initial_num_trials' trials of the experiment.\n\n Each succesive simulation increases number of trials by 'initial_num_trials'.\n\n The function keeps on running simulations until the resulting series of relative frequencies converges or the maximum number of\n iterations, 'max_num_iter' is reached.\n\n 'random_experiment' is a function that takes as parameter the number of trials to simulate and returns the relative frequency \n of the success of the experiment\n\n Returns\n -------\n tuple\n\n first element of the tuple is the probability as limit of the relative frequencies\n second element is the number of trials used to reach the limit\n\n If 'max_num_iter' is hit without the sequence of relative frequencies having converged, None is returned\n\n \"\"\"\n\n gen = freq_generator(initial_num_trials, random_experiment)\n last_result = next(gen)\n num_iter = 1\n\n while num_iter <= max_num_iter: \n new_result = next(gen) \n if abs(new_result[0] - last_result[0]) <= convergence_tolerance: \n return new_result\n last_result = new_result\n num_iter += 1\n return None\n\n\ndef freq_generator(initial_num_trials, random_experiment):\n num_trials = initial_num_trials\n\n while True:\n yield (random_experiment(num_trials), num_trials)\n num_trials = num_trials + initial_num_trials\n","repo_name":"falvarezb/coding-challenges","sub_path":"python/probability/probability.py","file_name":"probability.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39255162575","text":"# This is just a very lazy program that demonstrates how to use the GPIO pins on the raspberry PIs.\n# This program should be a file named \"gpio_testing.py\" on the Raspberry PI labeled \"PI-07\" which is connected to the light sensor.\n\nimport RPi.GPIO as GPIO # import GPIO library\n\ninPin = 11\noutPin = 29 # See Raspberry PI pinout for pin numbering and accetable pins\n\nGPIO.setmode(GPIO.BOARD) #Set GPIO numbering mode\nGPIO.setup(inPin, GPIO.IN) #Set pin inPin (11) to be an input\nGPIO.setup(outPin, GPIO.OUT) #Set pin outPin (29) to be an output\n\ntry:\n while True: #this will run until you stop the program\n inPin_status = GPIO.input(inPin) #Get status (0 or 1) of a GPIO pin setup in input mode\n print(inPin_status)\n GPIO.output(outPin, inPin_status) #Set outPin to the value of inPin_status (0 or 1)\n\nfinally: #will always happen\n GPIO.cleanup() #cleanup the GPIO pins before ending\n","repo_name":"UHM-SCADA-Lab/UHM-SCADA-Lab.github.io","sub_path":"public/PiAPI_gpioTesting.py","file_name":"PiAPI_gpioTesting.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"3919860571","text":"import os\nimport numpy as np\nimport torch \nimport torch.nn as nn\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\ntorch.set_default_tensor_type(torch.DoubleTensor)\nfrom tqdm import tqdm\nfrom models import LinearNN, MultiLayerNN\n\ndef save_all_figs_to_disk(folder='Results'):\n\tfor figname in plt.get_figlabels():\n\t\tplt.figure(figname)\n\t\tfigname_save = figname.replace(' ','_')\n\t\tfigname_save = figname_save.replace('_-_','_')\n\t\tplt.savefig(os.path.join(folder,figname_save))\n\ndef create_data_labels(inp_dim=10,num_data=100,seed=13):\n\ttorch.manual_seed(seed)\n\tnp.random.seed(seed)\n\tX = torch.rand((num_data,inp_dim))\n\tX.requires_grad_ = False\n\tteacher_net = LinearNN(inp_size=inp_dim)\n\twith torch.no_grad():\n\t\tY = teacher_net(X)\n\t# loss_fn = torch.nn.MSELoss()\n\treturn inp_dim,num_data,X,Y,teacher_net\n\n\ndef get_projection_matrix(inp_dim=10,projection_dim=20,seed=13):\n\ttorch.manual_seed(seed)\n\tnp.random.seed(seed)\n\texpansion_dim = inp_dim if inp_dim>projection_dim else projection_dim\n\twith torch.no_grad():\n\t\tA = torch.rand((expansion_dim,expansion_dim))\n\t\tA = A+A.T\n\t\tl,v = torch.linalg.eig(A)\n\t\tv = torch.real(v)\n\tW = v[:inp_dim+projection_dim-expansion_dim]\n\tif inp_dim>projection_dim:\n\t\tW = W.T\n\treturn W\n\n\ndef load_student_net(inp_dim,projection_weights=None,seed=13):\n\ttorch.manual_seed(seed)\n\tnp.random.seed(seed)\n\tstudent_net = LinearNN(inp_size=inp_dim)\n\tif projection_weights is not None:\n\t\tstudent_net.fc.weight.data = torch.matmul(student_net.fc.weight.data,projection_weights)\n\t\tstudent_net.inp_size = projection_weights.shape[-1]\n\treturn student_net\n\n\ndef get_loss(net,X,y,loss_fn):\n\tdevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\tnet = net.to(device)\n\tX = X.to(device)\n\ty = y.to(device)\n\twith torch.no_grad():\n\t\tY_hat = net(X)\n\t\tloss = loss_fn(Y_hat,y)\n\treturn loss.item()\n\n\ndef gradient_descent_one_step(net,lr,bias=0.0,variance=0.0,grad_noise=None,no_update=False,relative=False):\n\tdevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\tnet = net.to(device)\n\tparams = list(net.parameters())\n\tgrad_list = []\n\tfor p in params:\n\t\tif p.requires_grad:\n\t\t\tgrad_list.append(p.grad.data.flatten())\n\tgrad_vector = torch.cat(grad_list)\n\tif relative:\n\t\tgrad_norm = torch.norm(grad_vector).item()\n\t\tbias = bias*grad_norm\n\t# MAYBE BIAS SHOULD BE DIVIDED BY GRAD_VECTOR SIZE TO CONTROL FOR DIFFERENT NETWORK SIZE -- No it should not (we are looking at bias in synaptic wt. update)!\n\t# bias = bias/np.sqrt(len(grad_vector))\n\tif grad_noise is None:\n\t\tgrad_noise = torch.normal(mean=-bias*torch.ones(grad_vector.size()),std=np.sqrt(variance)*torch.ones(grad_vector.size())).to(grad_vector.device)\n\telse:\n\t\tgrad_noise -= bias\n\t# NOTE: -ve sign in bias above because this will be added to the gradient and thereafter subtracted from current wt.\n\t# Hence this has reverse effect of the theory assumption!\n\t# tqdm.write(\"{} {}\".format(torch.norm(grad_vector).item(),torch.norm(grad_noise)))\n\tnew_grad_vector = grad_vector+grad_noise.to(device)\n\tparam_pointer = 0\n\tfor p in params:\n\t\tif p.requires_grad:\n\t\t\tp_size = p.flatten().size(0)\n\t\t\tnew_grad = new_grad_vector[param_pointer:param_pointer+p_size].view(p.size())\n\t\t\tp.grad.data = new_grad\n\t\t\tparam_pointer += p_size\n\n\tif not no_update:\n\t\tfor p in params:\n\t\t\tif p.requires_grad:\n\t\t\t\tp.data -= lr*p.grad\n\treturn (grad_vector, grad_noise)\n\n\t\ndef train_one_step(net,X,y,loss_fn,lr,bias=0.0,variance=0.0,grad_noise=None,verbose=True,no_update=False):\n\tdevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\tnet = net.to(device)\n\tX = X.to(device)\n\ty = y.to(device)\n\tnet.zero_grad()\n\tY_hat = net(X)\n\tloss = loss_fn(Y_hat,y)\n\tloss.backward()\n\tgrad = gradient_descent_one_step(net,lr=lr,bias=bias,variance=variance,grad_noise=grad_noise,no_update=no_update)\n\tif verbose:\n\t\tprint(\"Loss 1: {}\".format(loss.item()))\n\twith torch.no_grad():\n\t\tY_hat = net(X)\n\t\tloss_val = loss_fn(Y_hat,y)\n\t\tif verbose:\n\t\t\tprint(\"Loss 2: {}\".format(loss_val.item()))\n\treturn grad, loss.item()-loss_val.item()\n\n\ndef calculate_hessian(net,X,y,loss_fn):\n\tparams_list = [p.view(-1) for p in net.parameters()]\n\tdef loss_function_hess(W_b):\n\t\tout_size = y.size(-1)\n\t\treturn loss_fn(torch.nn.functional.linear(X,W_b[:-out_size].view(out_size,-1),W_b[-out_size:]),y)\n\tgrad2_W = torch.autograd.functional.hessian(loss_function_hess,torch.hstack(params_list))\n\treturn grad2_W\n\n\ndef check_loss_decrease_eq(grad,grad2,lr,loss_dec,bias=0.0,variance=0.0,tol=None,verbose=True):\n\tif tol is None:\n\t\ttol = 1e-8\n\tgrad_decrease = ((-torch.norm(grad)**2)+bias*torch.sum(grad))*lr\n\tgrad2_decrease = 0.5*(torch.sum(grad.unsqueeze(1)*torch.matmul(grad2,grad.unsqueeze(1))) \\\n\t\t\t\t\t\t-bias*torch.sum(grad*torch.sum(grad2+grad2.transpose(0,1),dim=1)) \\\n\t\t\t\t\t\t+(bias**2)*torch.sum(grad2) \\\n\t\t\t\t\t\t+(variance**2)*torch.trace(grad2)/grad2.shape[0])*(lr**2)\n\tif verbose:\n\t\tprint(loss_dec,(-grad_decrease-grad2_decrease).numpy(),loss_dec-(-grad_decrease-grad2_decrease).numpy())\n\t\t# print(grad_decrease.numpy(),grad2_decrease.numpy())\n\tassert np.allclose(loss_dec,(-grad_decrease-grad2_decrease).numpy(),atol=tol), \"Some error in calculation!\"\n\treturn loss_dec-(-grad_decrease-grad2_decrease).numpy()\n\n\ndef get_uncorrupted_loss_decrease(grad,grad2,lr):\n\tgrad_decrease = (-torch.norm(grad)**2)*lr\n\tgrad2_decrease = 0.5*torch.sum(grad.unsqueeze(1)*torch.matmul(grad2,grad.unsqueeze(1)))*(lr**2)\n\treturn (-grad_decrease-grad2_decrease).numpy()\n\n\ndef calculate_sampling_bias_correction_term(grad,grad2,noise_mean,lr,bias=0.0):\n\tgrad_decrease_correction = torch.sum(grad*noise_mean)*lr\n\tgrad2_decrease_correction = 0.5*(-torch.sum(noise_mean*torch.matmul(grad2+grad2.T,grad)) \\\n\t\t\t\t\t\t\t\t +bias*torch.sum(noise_mean*torch.sum(grad2+grad2.T,dim=1)))*lr**2\n\t# print(\"correction\",noise_mean.shape,grad.shape,grad2.shape,grad_decrease_correction,grad2_decrease_correction,-grad_decrease_correction-grad2_decrease_correction)\n\t# print(noise_mean,grad,grad2)\n\treturn (-grad_decrease_correction-grad2_decrease_correction).numpy()\n\t\t\t\t\t\t\t\t \n\ndef get_optimal_lr_value(grad,grad2,bias=0.0,variance=0.0,verbose=True):\n\tgrad_decrease_coeff = (-torch.norm(grad)**2)+bias*torch.sum(grad)\n\tgrad2_decrease_coeff = (torch.sum(grad.unsqueeze(1)*torch.matmul(grad2,grad.unsqueeze(1))) \\\n\t\t\t\t\t\t\t-bias*torch.sum(grad*torch.sum(grad2+grad2.transpose(0,1),dim=1)) \\\n\t\t\t\t\t\t\t+(bias**2)*torch.sum(grad2) \\\n\t\t\t\t\t\t\t+(variance**2)*torch.trace(grad2)/grad2.shape[0])\n\t# If Loss=ax+0.5*bx^2 <==> x* = -a/b\n\tif verbose:\n\t\tprint(bias,variance,grad_decrease_coeff,grad2_decrease_coeff)\n\toptimal_lr = -grad_decrease_coeff/(grad2_decrease_coeff+1e-9)\n\treturn optimal_lr.item()\n\n\ndef generate_random_noise_sequence(repeats,inp_dim,variance,seed=7):\n\t# torch.manual_seed(seed)\n\t# np.random.seed(seed)\n\t# torch.random.seed()\n\tnoise_vectors = torch.randn((repeats-1,1+inp_dim))\n\tnoise_vectors = (variance)*torch.div(noise_vectors,torch.norm(noise_vectors,dim=1).unsqueeze(1))\n\tnoise_vectors = torch.vstack([noise_vectors,-noise_vectors.sum(dim=0)]) # to ensure that sum of random noise vectors is 0\n\treturn noise_vectors\n\n\ndef create_NL_data_labels(inp_dim=10,num_data=100,num_layers=1,non_linearity=None,seed=13):\n\ttorch.manual_seed(seed)\n\tnp.random.seed(seed)\n\tX = torch.rand((num_data,inp_dim))\n\tX.requires_grad_ = False\n\tteacher_net = MultiLayerNN(inp_size=inp_dim,num_layers=num_layers,hidden_dim=inp_dim,non_linearity=non_linearity)\n\twith torch.no_grad():\n\t\tY = teacher_net(X)\n\treturn inp_dim,num_data,X,Y,teacher_net\n\ndef load_multilayer_student_net(inp_dim,num_layers=1,hidden_dim=None,non_linearity=None,seed=13):\n\ttorch.manual_seed(seed)\n\tnp.random.seed(seed)\n\tstudent_net = MultiLayerNN(inp_size=inp_dim,num_layers=num_layers,hidden_dim=hidden_dim,non_linearity=non_linearity)\n\treturn student_net\n\ndef copy_from_model_to_model(net1,net2):\n\tassert type(net1).__name__==type(net2).__name__, \"Cannot copy params from {} to {}\".format(type(net1).__name__,type(net2).__name__)\n\treference_params_list = list(net1.parameters())\n\tnew_params_list = list(net2.parameters())\n\tassert len(reference_params_list)==len(new_params_list), \"Param lists ({} vs {}) don't match!\".format(len(reference_params_list),len(new_params_list))\n\tfor pidx,p in enumerate(new_params_list):\n\t\tp.data = reference_params_list[pidx].data.clone()\n\t\ndef check_model_params_equal(net1,net2):\n\tif type(net1).__name__!=type(net2).__name__:\n\t\treturn False\n\treference_params_list = list(net1.parameters())\n\tcheck_params_list = list(net2.parameters())\n\tif len(reference_params_list)!= len(check_params_list):\n\t\treturn False\n\tfor pidx,p in enumerate(check_params_list):\n\t\tif p.data.shape!=reference_params_list[pidx].data.shape:\n\t\t\treturn False\n\t\tif not torch.allclose(p.data,reference_params_list[pidx].data):\n\t\t\treturn False\n\treturn True\n","repo_name":"linclab/approximateGradients","sub_path":"Student-Teacher/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42317611992","text":"#! /usr/bin/python\nimport sys\nimport os\nfrom numpy import *\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator\n\n\n######\n#Plot the autocorrelation results of Dave's CompAutoCorr.m\n########\n\n#Variables\ndata1=genfromtxt('c310vH2O')\ndata2=genfromtxt('c310vVal')\ndata3=genfromtxt('cValvH2O')\n\n#Matlplotlib rc settings\n# padding for tick labels\nplt.rc(('xtick.major','xtick.minor','ytick.major','ytick.minor'), pad=10)\n##thicker axes frame\nplt.rc('axes',linewidth=4)\nplt.rc('legend', fontsize=20)\n###set all lines width\nplt.rc('lines', linewidth=4)\n\n###################################\n\n#Figure1\n#~ fig=plt.figure(figsize=(16, 12))\n#~ ax = fig.add_subplot(111)\n#~ \n#~ #plot the x-axis diffusion\n#~ x=[]\n#~ y=[]\n#~ for i in range(frames/10): #this is to get average over each 10 frames (.2ns)\n\t#~ x.append((data1[10*i,0]))\n\t#~ y.append(average(data1[10*i:10*i+10,1]))\n#~ ax.plot(x,y,'k', linewidth=4)\n#~ \n#~ #Linear fit 1\n#~ x=range(1,450000,10000) #x-axis range\n#~ y=map(lambda i:i*0.0007245+2.578,x) #linear formula\n#~ ax.plot(x,y,'r', linewidth=4)\n#~ \n#~ #Linear fit 2\n#~ x=range(500000,2400000,10000)\n#~ y=map(lambda i:i*0.0001965+241.7,x)\n#~ ax.plot(x,y,'r', linewidth=4)\n#~ \n#~ for label in ax.xaxis.get_ticklabels():\n\t#~ label.set_fontsize(24)\n#~ for label in ax.yaxis.get_ticklabels():\n\t#~ label.set_fontsize(24)\n#~ #plt.title('',fontsize=28)\n#~ plt.xlabel('Time (ms)',fontsize=28, labelpad=10)\n#~ ax.set_xticklabels([0,0.5,1.0,1.5,2.0,2.5])\n#~ plt.ylabel('Mean Square Displacement ($\\AA^{2}$)',fontsize=28, labelpad=5)\n#~ #plt.ylim(ymax=35)\n#~ #plt.xlim(xmax=500)\t#modify to trajectory length\n#~ \n#~ ax.yaxis.set_ticks_position('left')\n#~ ax.xaxis.set_ticks_position('bottom')\n#~ for line in ax.get_xticklines() + ax.get_yticklines():\n\t#~ line.set_markeredgewidth(4)\n\t#~ line.set_markersize(10)\n#~ plt.annotate('Slope=$7.2 x 10^{-4}$',xy=(5000,200), xytext=(340000,200),fontsize=20)\n#~ plt.annotate('Slope=$2.0 x 10^{-4}$',xy=(5000,200), xytext=(1500000,475),fontsize=20)\n#~ #ax.legend([\"peptide\", \"backbone\"],bbox_to_anchor=(0, 0, .95, .2))\n#~ \n#~ #plt.show()\n#~ plt.savefig('diffusion1.png') \n\n\n###############################################\n\n#Figure2\nfig=plt.figure(figsize=(16, 12))\nax = fig.add_subplot(111)\n\n\nax.plot(data1[0:5000],'b', linewidth=4)\n\nax.plot(data2[0:5000],'r', linewidth=4)\n\nax.plot(data3[0:5000],'k', linewidth=4)\n\nfor label in ax.xaxis.get_ticklabels():\n\tlabel.set_fontsize(24)\nfor label in ax.yaxis.get_ticklabels():\n\tlabel.set_fontsize(24)\n#plt.title('',fontsize=28)\nplt.xlabel('Correlation window size (ns)',fontsize=28, labelpad=10)\nax.set_xticklabels([0,20,40,60,80,100])\nplt.ylabel('Avg. Pearson Correlation',fontsize=28, labelpad=10)\nplt.ylim((0.6,1.0))\n#plt.xlim(xmax=0.5)\t#modify to trajectory length\n\nax.yaxis.set_ticks_position('left')\nax.xaxis.set_ticks_position('bottom')\nfor line in ax.get_xticklines() + ax.get_yticklines():\n\tline.set_markeredgewidth(4)\n\tline.set_markersize(10)\nax.legend([\"$3_{10}$ helix vs. water defect\", \"$3_{10}$ helix vs. correct Val18 dihedral\", \"water defect vs. correct Val18 dihedral\"],bbox_to_anchor=(0, 0, .995, .25))\n\n#plt.show()\nplt.savefig('AutoCorr.pdf') \n","repo_name":"pjanowski/Pawel_PhD_Scripts","sub_path":"matplotlib/plotAutoCorr.py","file_name":"plotAutoCorr.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8268694732","text":"from .base import FunctionalTest\n\nfrom selenium.webdriver.common.keys import Keys\n\nfrom unittest import skip\n\n\nclass LayoutAndStylingTest(FunctionalTest):\n \"\"\"Test for template and style.\"\"\"\n\n @skip\n def test_layout_and_styling(self):\n \"\"\"Layout and Style Test.\"\"\"\n self.browser.get(self.live_server_url)\n self.browser.set_window_size(1024, 768)\n\n inputbox = self.get_item_input_box()\n self.assertAlmostEqual(\n inputbox.location['x'] + inputbox.size['width'] / 2,\n 273,\n delta=10,\n )\n\n inputbox.send_keys('testing')\n inputbox.send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: testing')\n inputbox = self.get_item_input_box()\n self.assertAlmostEqual(\n inputbox.location['x'] + inputbox.size['width'] / 2,\n 273,\n delta=10,\n )\n","repo_name":"anderskate/superlists","sub_path":"functional_tests/test_layout_and_styling.py","file_name":"test_layout_and_styling.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23578165466","text":"from datetime import datetime\nfrom django import forms\nfrom django.forms import ModelForm\nfrom django.forms import widgets\nfrom tickets.models import Visitor\n\n\nclass VisitorCreationForm(ModelForm):\n class Meta:\n model = Visitor\n fields = (\n 'first_name',\n 'last_name',\n 'email',\n 'birth_date'\n )\n\n widgets = {\n 'first_name': widgets.TextInput(attrs={'class': 'form-control'}),\n 'last_name': widgets.TextInput(attrs={'class': 'form-control'}),\n 'email': widgets.EmailInput(attrs={'class': 'form-control'}),\n 'birth_date': widgets.DateInput(attrs={'class': 'datepicker'}),\n }\n\n \n\n def save(self, user, commit=True):\n visitor = super(VisitorCreationForm, self).save(commit=False)\n\n visitor.first_name = self.cleaned_data['first_name']\n visitor.last_name = self.cleaned_data['last_name']\n visitor.email = self.cleaned_data['email']\n visitor.birth_date = self.cleaned_data['birth_date']\n\n visitor.user = user\n visitor.event_money = 0\n visitor.rfid_code = None\n\n if commit:\n visitor.save()\n\n return visitor\n","repo_name":"VelinSE/Mascarada-Django","sub_path":"mascarada/tickets/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"3509100263","text":"from moltaut_src.molgpka.protonate import protonate_mol\nfrom rdkit import Chem\nfrom rdkit.Chem.MolStandardize import rdMolStandardize\nfrom collections import namedtuple\nfrom moltaut_src.cut_mol import get_frags\nfrom moltaut_src.tautomer import enumerate_tauts\n\n\ndef is_ionic(m):\n charges = []\n for at in m.GetAtoms():\n if at.GetFormalCharge() == 0:\n charges.append(False)\n else:\n charges.append(True)\n return any(charges)\n\n\ndef uncharge_mol(mol):\n un = rdMolStandardize.Uncharger()\n mol = un.uncharge(mol)\n mol = Chem.MolFromSmiles(Chem.MolToSmiles(mol))\n return mol\n\n\ndef get_tauts(m):\n tauts = enumerate_tauts(m)\n ms = []\n for taut in tauts:\n m = taut.mol\n if not m:\n print(\"tautomer error: \", smi)\n continue\n ms.append(taut)\n return ms\n\n\ndef unique_and_split(nms):\n smis = [Chem.MolToSmiles(m) for m in nms]\n smis = list(set(smis))\n nmols, imols = [], []\n for smi in smis:\n mol = Chem.MolFromSmiles(smi)\n if is_ionic(mol):\n imols.append(mol)\n else:\n nmols.append(mol)\n return nmols, imols\n\n\ndef get_tauts_for_vmr(smi):\n vm = Chem.MolFromSmiles(smi)\n vtauts = get_tauts(vm)\n return vtauts\n\n\ndef get_tauts_for_mol(m):\n mtauts = get_tauts(m)\n return mtauts\n\n\ndef is_vmr(vmr_tauts, mol_tauts):\n data = []\n for vm in vmr_tauts:\n labels = []\n for mm in mol_tauts:\n res = mm.GetSubstructMatches(Chem.MolFromSmarts(Chem.MolToSmiles(vm)))\n if len(res) != 0:\n labels.append(1)\n else:\n labels.append(0)\n data.append(any(labels))\n if not any(labels):\n print(Chem.MolToSmiles(vm))\n return all(data)\n\n\ndef filter_vmrs(smallest_vmrs, mol_tauts):\n \"\"\"\n mol_tauts: tautomers of a molecule\n \"\"\"\n final_smallest_vmrs = []\n for vmr in smallest_vmrs:\n vsmi = vmr.smi\n vmr_tauts = get_tauts_for_vmr(vsmi)\n vmr = vmr._replace(tauts=vmr_tauts)\n if is_vmr(vmr_tauts, mol_tauts):\n final_smallest_vmrs.append(vmr)\n return final_smallest_vmrs\n\ndef filter_tauts_of_vmr(vmr_tauts, mol_tauts):\n vmr_tauts_filter = []\n for vm in vmr_tauts:\n labels = []\n for mm in mol_tauts:\n res = mm.GetSubstructMatches(Chem.MolFromSmarts(Chem.MolToSmiles(vm)))\n if len(res) != 0:\n labels.append(1)\n else:\n labels.append(0)\n if any(labels):\n vmr_tauts_filter.append(vm)\n return vmr_tauts_filter\n\n\ndef enumerate_vmrs(smi):\n data = namedtuple('vmrs',\n 'smi tauts')\n\n m = Chem.MolFromSmiles(smi)\n m = uncharge_mol(m)\n\n frag_smis = get_frags(m)\n\n vmrs = []\n for fsmi in frag_smis:\n ftauts = get_tauts_for_vmr(fsmi)\n vmr = data(smi=fsmi, tauts=ftauts)\n vmrs.append(vmr)\n return vmrs\n\n\nif __name__ == \"__main__\":\n #smi = \"COC(=O)c1ccc(O)cc1\"\n #smi = \"CN(C)CCCN1C2=CC=CC=C2OC2=C1C=C(C=C2)C(C)=O\"\n #smi = \"c1ccccc1C(C(=O)O)NC(=O)C(NC(=O)CCC(N)C(=O)O)CSCc2ccccc2\"\n #smi = \"Brc1cnn2c1nc(cc2NCc1cccnc1)c1ccccc1\"\n smi = \"Cc1n[nH]c(c12)OC(N)=C(C#N)C2(C(C)C)c(cc3C(F)(F)F)cc(c3)N4CCCC4\"\n vmrs = enumerate_vmrs(smi)\n print(vmrs)\n","repo_name":"Xundrug/MolTaut","sub_path":"moltaut_src/get_vmrs.py","file_name":"get_vmrs.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"3"}
+{"seq_id":"41670637402","text":"# 문자열 데이터를 분석하기 전에 처리함수 만들기\n# 1. 공백제거\n# 2. 필요 없는 문장부호 제거\n# 3. 대소문자 정리(Capitalize)\nimport re\n\nstates = ['Alabama', 'Georgia!', 'Georgia', 'georgia', 'FlOrIda', 'south carolina ', 'West virginia?']\n\n\ndef clean_string(strings):\n result = []\n\n for string in strings:\n string = string.strip()\n string = re.sub('[!#?]', '', string)\n string = string.title()\n result.append(string)\n\n return result\n\n\nresults = clean_string(states)\nprint(results)\n\n############################\n\nstates = ['Alabama', 'Georgia!', 'Georgia', 'georgia', 'FlOrIda', 'south carolina ', 'West virginia?']\n\n# 가변 인수: 여러개의 함수\ndef clean_string(strings, *funcs):\n result = []\n\n for string in strings:\n for func in funcs:\n string = func(string)\n result.append(string)\n\n return result\n\n\ndef remove_special(s):\n return re.sub('[!#?]', '', s)\n\n\n# results = clean_string(states, str.strip, str.title, remove_special)\nresults = clean_string(states, str.strip, str.title, lambda s: re.sub('[!#?]', '', s))\nprint(results)\n\n\nprint(' abc '.strip())\nprint(str.strip(\" abc \"))\n","repo_name":"ydhwa/python_lectures","sub_path":"python_ch2-5/normalize_string.py","file_name":"normalize_string.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33299857656","text":"from helpers_db import *\nimport pandas as pd \nimport pandavro as pdv \nimport sys\nimport os\nfrom dateutil.parser import isoparse\n\ndef clean_hired_employees(df):\n \"\"\"This Function parse to string a datetime column\n that comes from sql server backup, in order to\n give them a correct format and then parse to correct datetime format\n to be inserted to the desired table\n \n Parameters\n ----------\n df: pandas dataframe with the column to be parsed\n\n Returns\n -------\n df: pandas dataframe with the column\n to be parsed in datetime iso format\n \"\"\"\n df['hired_date'] = df.hired_date.apply(lambda x:\\\n isoparse(x.strftime('%Y-%m-%dT%H:%M:%SZ')\\\n .replace('T',' ').replace('Z','.000')))\n \n return df\n\ndef principal():\n # verify that we have the needed arguments\n if len(sys.argv)>=2:\n table = sys.argv[1]\n conn = create_db_connection()\n # Read the backup file\n # this file is readed from an external\n # mounting point(pc or nas)\n # but it is mapped to this path\n # via docker volume\n file_path = f'/database/backups/files_backups/{table}.avro'\n # if our file exisit, we proceed to do the restore\n if os.path.exists(file_path):\n df = pdv.from_avro(file_path)\n\n if table=='hired_employees':\n df = clean_hired_employees(df)\n \n if table_exists(table,conn):\n print('***** La tabla existe en la DB, se sobreescribiran los datos existentes')\n insert_df_to_db(table,'dbo',df)\n else:\n insert_df_to_db(table,'dbo',df)\n print(f'La tabla {table} se ha creado desde un backup')\n else:\n print(f'No se encontro el backup de la tabla {table}')\n\n else:\n print('No se recibieron los parametros necesarios para reestablecer el backup')\n \n return 0\n\nif __name__ == '__main__':\n principal()","repo_name":"marcoAntonio96/test_gde_api","sub_path":"database/backups/load_backup.py","file_name":"load_backup.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71990776723","text":"from collections import deque\ndef solution(n, edge):\n answer = 0\n graph = [[] for _ in range(n+1)]\n visit = [False] * (n + 1)\n line = [0] * (n + 1)\n\n for e1, e2 in edge: # edge 정보 바탕으로 bfs실행할 배열 생성\n graph[e1].append(e2)\n graph[e2].append(e1)\n \n bfs(graph, 1, visit, line)\n max_line = max(line)\n for l in line:\n if l == max_line:\n answer += 1\n return answer\n\ndef bfs(graph, start, visit, line):\n queue = deque([start])\n visit[start] = True\n line[1] = 0\n \n while queue:\n v = queue.popleft()\n # 해당 원소와 연결된, 아직 방문하지 않은 원소들을 큐에 삽입\n for i in graph[v]:\n if not visit[i]:\n queue.append(i)\n visit[i] = True\n line[i] = line[v] + 1","repo_name":"da-in/algorithm-study","sub_path":"Programmers - 고득점 Kit/[그래프] 가장 먼 노드/doha.py","file_name":"doha.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"3"}
+{"seq_id":"29029479967","text":"import pytest\n\nfrom plan.services.models import Service\nfrom plan.suspicion.constants import LEVELS\nfrom plan.suspicion.tasks import check_issue_groups\nfrom plan.suspicion.models import ServiceIssue\n\nfrom common import factories\n\n\ndef test_update_level():\n service = factories.ServiceFactory()\n issue_group = factories.IssueGroupFactory()\n factories.IssueGroupThresholdFactory(issue_group=issue_group, threshold=0.3)\n factories.IssueGroupThresholdFactory(issue_group=issue_group, threshold=0.7)\n service_traffic_status = factories.ServiceTrafficStatusFactory(issue_group=issue_group, service=service)\n\n assert service_traffic_status.get_new_level(0.8) == LEVELS.CRIT\n assert service_traffic_status.get_new_level(0.4) == LEVELS.WARN\n assert service_traffic_status.get_new_level(0.2) == LEVELS.OK\n\n\n@pytest.mark.parametrize('state', Service.states.ALL_STATES)\ndef test_calculate_level(state):\n service = factories.ServiceFactory(state=state)\n issue_group = factories.IssueGroupFactory()\n factories.ServiceIssueFactory(service=service, issue_group=issue_group)\n factories.IssueGroupThresholdFactory(issue_group=issue_group, threshold=0.3)\n factories.IssueGroupThresholdFactory(issue_group=issue_group, threshold=0.7)\n service_traffic_status = factories.ServiceTrafficStatusFactory(issue_group=issue_group, service=service)\n issue1 = factories.IssueFactory(issue_group=issue_group)\n factories.IssueFactory(issue_group=issue_group)\n\n check_issue_groups()\n service_traffic_status.refresh_from_db()\n assert service_traffic_status.level == LEVELS.OK\n\n service_issue = factories.ServiceIssueFactory(service=service, issue=issue1, state=ServiceIssue.STATES.ACTIVE)\n check_issue_groups()\n service_traffic_status.refresh_from_db()\n assert service_traffic_status.level == (LEVELS.WARN if state != Service.states.DELETED else LEVELS.OK)\n\n service_issue.state = ServiceIssue.STATES.REVIEW\n service_issue.save()\n check_issue_groups()\n service_traffic_status.refresh_from_db()\n assert service_traffic_status.level == (LEVELS.WARN if state != Service.states.DELETED else LEVELS.OK)\n\n service_issue.state = ServiceIssue.STATES.FIXED\n service_issue.save()\n check_issue_groups()\n service_traffic_status.refresh_from_db()\n assert service_traffic_status.level == LEVELS.OK\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Intranet/tests/unit/suspicion/models/test_traffic_status.py","file_name":"test_traffic_status.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"45207798938","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# @author: x.huang\n# @date:07/05/18\n\nfrom .mongodb import MongoDB\nfrom .rabbitmq import *\nfrom .redis import *\n\n\nclass LoadError(Exception):\n pass\n\n\nclass Loader(object):\n mapping = {\n 'mongodb': MongoDB,\n 'aioredis': AioRedis,\n 'rabbitmq': Rabbitmq,\n }\n\n @classmethod\n def load(cls, name: str, **kwargs):\n if name not in cls.mapping:\n return LoadError(f'load {name} error, {name} not exists')\n instance = cls.mapping.get(name)().load(**kwargs)\n return instance\n\n @classmethod\n async def async_load(cls, name: str, **kwargs):\n if name not in cls.mapping:\n return LoadError(f'load {name} error, {name} not exists')\n instance = await cls.mapping.get(name)().load(**kwargs)\n return instance\n","repo_name":"huangxingx/python-framework-async","sub_path":"webar/core/loader/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"7709131856","text":"import tkinter as tk\nfrom tkinter import ttk\nimport os\nimport openpyxl\nfrom datetime import datetime, timedelta\n\ndef save_data(event=None):\n date = date_entry.get()\n month = month_entry.get()\n flat_no = flat_no_entry.get()\n building_no = building_no_entry.get()\n charges = charges_entry.get()\n\n if date == '':\n date = (datetime.now() + timedelta(days=1)).strftime(\"%Y-%m-%d\")\n month = date[:7]\n\n data = {\n \"Date\": [date],\n \"Month\": [month],\n \"Flat No\": [flat_no],\n \"Building No\": [building_no],\n \"Charges\": [charges]\n }\n\n filename = 'data_entry.xlsx'\n sheetname = month\n\n if not os.path.isfile(filename):\n wb = openpyxl.Workbook()\n wb.active.title = sheetname\n for idx, col_name in enumerate(data.keys(), 1):\n wb.active.cell(row=1, column=idx, value=col_name)\n wb.save(filename)\n \n wb = openpyxl.load_workbook(filename)\n if sheetname not in wb.sheetnames:\n wb.create_sheet(sheetname)\n for idx, col_name in enumerate(data.keys(), 1):\n wb[sheetname].cell(row=1, column=idx, value=col_name)\n current_max_row = wb[sheetname].max_row\n for idx, value in enumerate(data.values(), 1):\n wb[sheetname].cell(row=current_max_row+1, column=idx, value=value[0])\n wb.save(filename)\n wb.close()\n\n status_label.config(text=\"Data saved successfully\")\n\n # Clear entry fields\n flat_no_entry.delete(0, 'end')\n building_no_entry.delete(0, 'end')\n charges_entry.delete(0, 'end')\n\n# Create the main window\nroot = tk.Tk()\nroot.title(\"Data Entry Form\")\n\n# Create and configure the frame\nframe = ttk.Frame(root)\nframe.grid(row=0, column=0, padx=20, pady=20)\n\n# Labels and Entry fields\ndate_label = ttk.Label(frame, text=\"Date\")\ndate_label.grid(row=0, column=0)\ndate_entry = ttk.Entry(frame)\ndate_entry.grid(row=0, column=1)\n\n# Set the date to the next day by default\ndefault_date = (datetime.now() + timedelta(days=1)).strftime(\"%Y-%m-%d\")\ndate_entry.insert(0, default_date)\n\nmonth_label = ttk.Label(frame, text=\"Month\")\nmonth_label.grid(row=1, column=0)\nmonth_entry = ttk.Entry(frame)\nmonth_entry.grid(row=1, column=1)\n\n# Set the month to be the same as the date in English\ndefault_month = (datetime.now() + timedelta(days=1)).strftime(\"%B\")\nmonth_entry.insert(0, default_month)\n\nflat_no_label = ttk.Label(frame, text=\"Flat No\")\nflat_no_label.grid(row=2, column=0)\nflat_no_entry = ttk.Entry(frame)\nflat_no_entry.grid(row=2, column=1)\n\nbuilding_no_label = ttk.Label(frame, text=\"Building No\")\nbuilding_no_label.grid(row=3, column=0)\nbuilding_no_entry = ttk.Entry(frame)\nbuilding_no_entry.grid(row=3, column=1)\n\ncharges_label = ttk.Label(frame, text=\"Charges\")\ncharges_label.grid(row=4, column=0)\ncharges_entry = ttk.Entry(frame)\ncharges_entry.grid(row=4, column=1)\n\n# Bind the Enter key to the save_data function\nroot.bind('', save_data)\n\n# Save button\nsave_button = ttk.Button(frame, text=\"Save\", command=save_data)\nsave_button.grid(row=5, column=0, columnspan=2)\n\n# Status label\nstatus_label = ttk.Label(frame, text=\"\")\nstatus_label.grid(row=6, column=0, columnspan=2)\n\n# Start the GUI application\nroot.mainloop()\n","repo_name":"Haris-Nr/python_p","sub_path":"labour.py","file_name":"labour.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23997089921","text":"def check_modules():\n\n try:\n import sys\n except(ImportError):\n raise SystemExit #exit()\n\n dependencies = ['shlex', 'os', 'subprocess', 'random', \n # 'touche turtle' # disparar bloque try\n ]\n\n try:\n for dependency in dependencies:\n if dependency not in (sys.stdlib_module_names):\n raise ModuleNotFoundError(str(dependency)) # Builtin exception\n except ModuleNotFoundError as e:\n # sys,exit() cleanup actions specified by finally clauses of try statements are honored\n e_type, e_name, e_trace = sys.exc_info()\n sys.exit(\"Modulo %s no encontrado\" % (str(e_name)))\n except AttributeError as e:\n # python exception message capturing\n sys.exit(str(e))\n else:\n # scope de variables locales en el try /except\n print(\"Dependencias %s presentes en el sistema\" % (', '.join(dependencies)))\n finally:\n print(\"Dependencias de modulos chequeadas\")","repo_name":"ncocana/PlayVLCShuffle","sub_path":"src/checkRoutines/check_modules.py","file_name":"check_modules.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25785783739","text":"class masscalculate():\n def __init__(self, twoHundred, oneNinety, oneEighty, oneSeventy, lightWeight):\n self.twoHundred = twoHundred\n self.oneNinety = oneNinety\n self.oneEighty = oneEighty\n self.oneSeventy = oneSeventy\n self.lightWeight = lightWeight\n\n # method for calculating average bat speed of hitters over 200 pounds\n def twoHundredAvg(self):\n total = 0\n for speed in self.twoHundred:\n total += speed\n average = total / len(self.twoHundred)\n return (\"%.2f\" % average)\n\n # method for calculating average bat speed of hitters 191-200 pounds\n def oneNinetyAvg(self):\n total = 0\n for speed in self.oneNinety:\n total += speed\n average = total / len(self.oneNinety)\n return (\"%.2f\" % average)\n\n # method for calculating average bat speed of hitters 181-190 pounds\n def oneEightyAvg(self):\n total = 0\n for speed in self.oneEighty:\n total += speed\n average = total / len(self.oneEighty)\n return (\"%.2f\" % average)\n\n # method for calculating average bat speed of hitters 170-180 pounds\n def oneSeventyAvg(self):\n total = 0\n for speed in self.oneSeventy:\n total += speed\n average = total / len(self.oneSeventy)\n return (\"%.2f\" % average)\n\n # method for calculating average bat speed of hitters less than 170 pounds\n def lightWeightAvg(self):\n total = 0\n for speed in self.lightWeight:\n total += speed\n average = total / len(self.lightWeight)\n return (\"%.2f\" % average)","repo_name":"travislee7/Driveline-Biomechanics-Data-Project","sub_path":"masscalculate.py","file_name":"masscalculate.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"998915928","text":"#CS1321L Final Fall 2018\r\n#Name: Andy Garbukas\r\n#Student ID Number: 000569062\r\n#Date: 12/7/18\r\n#Lab Instructor: Solomon Walker\r\n\r\n\r\n#NOTE: Turn this file in with the others in D2L after you are finished with the final\r\n\r\n#Here you will write the code to compare two equal-sized arrays\r\n# and determine if they are equal. Please test at least three times,\r\n# comparing non-equal and equal arrays at least once.\r\n\r\nfrom array import *\r\n\r\nsize = int(input(\"enter a length for the arrays\"))\r\n\r\n\r\narray1 = array('i', [0] * size)\r\narray2 = array('i', [0] * size)\r\n\r\n\r\nfor x in range(len(array1)):\r\n element = 0\r\n array1[x] = int(input(\"Enter a number for your array 1 element \"))\r\n element += 1\r\n\r\nfor x in range(len(array2)):\r\n element = 0\r\n array2[x] = int(input(\"Enter a number for your array 2 element \"))\r\n element += 1\r\n\r\nif array1 == array2:\r\n print(\"\\nYour arrays are a match!!\")\r\n print(\"\\nArray 1: \", array1)\r\n print(\"\\nArray 2: \", array2)\r\nelse:\r\n print(\"\\nYour arrays are not a match!\")\r\n print(\"\\nArray 1: \", array1)\r\n print(\"\\nArray 2: \", array2)","repo_name":"agarbukas/Schoolwork","sub_path":"Exercise1_Fall2018_1321L_Final.py","file_name":"Exercise1_Fall2018_1321L_Final.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17995662176","text":"import cv2\n\n# 0 -> first webcam\ncap = cv2.VideoCapture(0)\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)\n\nwhile True:\n # get a frame\n _, frame = cap.read()\n hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n height, width, _ = frame.shape\n\n cx = int(width / 2)\n cy = int(height / 2)\n\n pixel_center = hsv_frame[cy, cx]\n hue_value = pixel_center[0]\n\n color = \"Undefined\"\n if hue_value < 5:\n color = \"Red\"\n elif hue_value < 22:\n color = \"Orange\"\n elif hue_value < 33:\n color = \"Yellow\"\n elif hue_value < 78:\n color = \"Green\"\n elif hue_value < 131:\n color = \"Blue\"\n elif hue_value < 167:\n color = \"Purple\"\n else:\n color = \"Red\"\n\n print(pixel_center)\n pixel_center_bgr = frame[cy, cx]\n b, g, r = int(pixel_center_bgr[0]), int(pixel_center_bgr[1]), int(pixel_center_bgr[2])\n cv2.putText(frame , color, (10 , 50), 0, 1.5, (b, g, r), 2)\n cv2.circle(frame, (cx, cy), 5, (25, 25, 25), 3)\n\n cv2.imshow(\"Frame\", frame)\n key = cv2.waitKey(1)\n if key == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()","repo_name":"cosmin-oros/ComputerVision-Projects","sub_path":"ColorRecognition/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"4738443803","text":"# list of tupple\n\n\nc = [ ('sun', 38, 4 ),\n ('doussey', 36, 2 ),\n ('herve', 35, 4 ),\n ('king', 32, 3 ),\n ('dick', 28, 2 ), \n ('santa', 23, 1 ) \n]\n\nprint(type(c))\nfrom operator import itemgetter\n\nk = itemgetter(1) #locate first index of tuple\nprint(map(k,c)) # print all first index of all tuple \n\nd = ('mum', 60, 5)\nc.append(d)\nprint(c)","repo_name":"sunshay/Map-Project","sub_path":"dictionnaryacces.py","file_name":"dictionnaryacces.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"4544849792","text":"from PIL import ImageGrab\nimport time\n\ncount = 0\nwhile True:\n count += 1\n pic = ImageGrab.grab()\n name = time.strftime(\"%Y-%m-%d---%H:%M:%S\", time.localtime()).replace(':', '-')\n pic.save(r'D:\\\\lidar\\\\beam_test\\\\%s.jpg' % name)\n print(count)\n time.sleep(2*60)","repo_name":"lizhengping/TelescopeImaging","sub_path":"screengrab.py","file_name":"screengrab.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34514268841","text":"from peacock.ExodusViewer.plugins.VTKWindowPlugin import VTKWindowPlugin\nfrom peacock.utils import ExeLauncher\nfrom PyQt5.QtCore import pyqtSignal\nimport os\n\nclass MeshViewerPlugin(VTKWindowPlugin):\n \"\"\"\n A VTKWindowPlugin that shows the mesh of the input file as given\n by --mesh-only\n Signals:\n needInputFile[str]: Emitted when an input file needs to be written out\n meshEnabled[bool]: Notifies when the mesh has been enabled/disabled\n \"\"\"\n needInputFile = pyqtSignal(str)\n meshEnabled = pyqtSignal(bool)\n\n def __init__(self, **kwargs):\n super(MeshViewerPlugin, self).__init__(**kwargs)\n self.temp_input_file = \"peacock_run_mesh_tmp.i\"\n self.temp_mesh_file = \"peacock_run_mesh_tmp.e\"\n self.current_temp_mesh_file = os.path.abspath(self.temp_mesh_file)\n self.hide()\n\n def _removeFileNoError(self, fname):\n \"\"\"\n Utility function to remove a file while ignoring errors.\n Input:\n fname[str]: path to remove\n \"\"\"\n try:\n path = os.path.abspath(fname)\n os.remove(path)\n except:\n pass\n\n def meshChanged(self, tree):\n \"\"\"\n The parameters of the mesh has changed.\n We need to update the view of the mesh by generating a new mesh file.\n \"\"\"\n self.meshEnabled.emit(False)\n self.hide()\n if not tree.app_info.valid():\n return\n # if we aren't writing out the mesh node then don't show it\n mesh_node = tree.getBlockInfo(\"/Mesh\")\n if not mesh_node or not mesh_node.included:\n return\n exe_path = tree.app_info.path\n self._removeFileNoError(self.current_temp_mesh_file)\n self.current_temp_mesh_file = os.path.abspath(self.temp_mesh_file)\n input_file = os.path.abspath(self.temp_input_file)\n self._removeFileNoError(self.current_temp_mesh_file)\n self._removeFileNoError(input_file)\n self.needInputFile.emit(input_file)\n try:\n args = [\"-i\", input_file, \"--mesh-only\", self.current_temp_mesh_file]\n ExeLauncher.runExe(exe_path, args, print_errors=False)\n self.show()\n self.meshEnabled.emit(True)\n self.onFileChanged(self.current_temp_mesh_file)\n except Exception:\n self.hide()\n self.meshEnabled.emit(False)\n self._removeFileNoError(self.current_temp_mesh_file)\n\n\n self._removeFileNoError(input_file) # we need the mesh file since it is in use but not the input file\n\n def onBlockChanged(self, block, tree):\n if block.path == \"/Mesh\" or block.path.startswith(\"/Mesh/\"):\n self.meshChanged(tree)\n\n def closing(self):\n self._removeFileNoError(self.temp_input_file)\n self._removeFileNoError(self.current_temp_mesh_file)\n\n","repo_name":"mazajump/FEA-PhaseField-Moose","sub_path":"python/peacock/Input/MeshViewerPlugin.py","file_name":"MeshViewerPlugin.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"22657754896","text":"import math\n\nimport numpy as np\nimport pytest\n\nfrom biblioteki.area import trian\n\n\ndef test_tran_flat1():\n d = trian.sur_area_by_points([0, 0, 0], [0, 0, 1], [0, 1, 0])\n assert d == 0.5\n\n\ndef test_tran_flat1_2d():\n d = trian.sur_area_by_points([0, 0], [0, 1], [1, 0])\n assert d == 0.5\n\n\ndef test_tran_flat2():\n d = trian.sur_area_by_points([0, 0, 1], [0, 0, 0], [0, 1, 0])\n assert d == 0.5\n\n\ndef test_square_flat1():\n d = trian.sur_area_by_points([0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0])\n assert d == 1\n\n\ndef test_square_flat2():\n d = trian.sur_area_by_points([0, 0, 1], [0, 1, 1], [1, 1, 0], [1, 0, 0])\n assert d == math.sqrt(2)\n\n\n@pytest.fixture\ndef poi_random():\n xrange = (0, 1000)\n yrange = (0, 1000)\n dens = 100\n xstep = (xrange[1] - xrange[0]) / dens\n ystep = (yrange[1] - yrange[0]) / dens\n x = np.linspace(xrange[0], xrange[1] - xstep, dens)\n y = np.linspace(yrange[0], yrange[1] - ystep, dens)\n xleft, ydown = np.meshgrid(x, y)\n xright = xleft + xstep\n yup = ydown - ystep\n z_left_up = (np.random.random(100 * 100) * 100).reshape(100, 100)\n z_left_down = (np.random.random(100 * 100) * 100).reshape(100, 100)\n z_right_up = (np.random.random(100 * 100) * 100).reshape(100, 100)\n z_right_down = (np.random.random(100 * 100) * 100).reshape(100, 100)\n return (xleft, yup, z_left_up), (xright, yup, z_right_up), (xright, ydown, z_right_down), (\n xleft, ydown, z_left_down)\n\n\n@pytest.fixture\ndef poi_one_trian():\n xleft = np.array([[0]])\n yup = np.array([[1]])\n z_left_up = np.array([[0]])\n xright = np.array([[1]])\n ydown = np.array([[0]])\n z_right_up = np.array([[0]])\n z_right_down = np.array([[0]])\n return (xleft, yup, z_left_up), (xright, yup, z_right_up), (xright, ydown, z_right_down)\n\n\n@pytest.fixture\ndef poi_one_trian1():\n xleft = np.array([[0.5]])\n yup = np.array([[1]])\n z_left_up = np.array([[0]])\n xright = np.array([[1]])\n ydown = np.array([[0]])\n z_right_up = np.array([[0]])\n z_right_down = np.array([[0]])\n return (xleft, yup, z_left_up), (xright, yup, z_right_up), (xright, ydown, z_right_down)\n\n@ pytest.fixture\ndef poi_one_trian2():\n return (np.array([[0]]), np.array([[0]]), np.array([[0]])), (np.array([[3]]), np.array([[2]]), np.array([[0]])), (\n np.array([[3]]), np.array([[-4]]), np.array([[0]]))\n\n\ndef test_area_trian_set_by_array_value(poi_one_trian):\n lu, ru, rd= poi_one_trian\n are = trian.area_trian_set_by_array(*lu, *ru, *rd)\n assert are[0][0]==0.5\n\ndef test_area_trian_set_by_array_value1(poi_one_trian1):\n lu, ru, rd = poi_one_trian1\n are = trian.area_trian_set_by_array(*lu, *ru, *rd)\n assert are[0][0] == 0.25\n\ndef test_area_trian_set_by_array_value2(poi_one_trian2):\n lu, ru, rd = poi_one_trian2\n are = trian.area_trian_set_by_array(*lu, *ru, *rd)\n assert are[0][0] == 9\n\ndef test_area_trian_set_by_array_random(poi_random):\n lu,ru,rd,ld=poi_random\n are=trian.area_trian_set_by_array(*lu,*ru,*rd)\n\n def format_to_points(arr_set):\n \"\"\"\n change arrays of arguments to list of points\n :param arr_set:\n :return:\n \"\"\"\n x = arr_set[0].flatten()\n y = arr_set[1].flatten()\n z = arr_set[2].flatten()\n return list(zip(x, y, z))\n\n plu = format_to_points(lu)\n pru =format_to_points(ru)\n prd = format_to_points(rd)\n\n\n poi_set = list(zip(plu, pru, prd,))\n li = []\n for pset in poi_set:\n li.append(trian.sur_area_by_points(*pset))\n poi= np.array(li).reshape(100, 100)\n assert np.array_equal(np.round(poi,2),np.round(are,2))\n\n","repo_name":"niski1996/Femsy","sub_path":"biblioteki/area/test_trian.py","file_name":"test_trian.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20600591014","text":"from __future__ import annotations\n\nimport multiprocessing\nimport logging\nimport asyncio\nimport os.path\n\nimport nest_asyncio\nimport sc2\n\nfrom sc2.main import run_game\nfrom sc2.data import Race\nfrom sc2.bot_ai import BotAI\nfrom sc2.player import Bot\n\nfrom worlds.sc2wol.Regions import MissionInfo\nfrom worlds.sc2wol.MissionTables import lookup_id_to_mission\nfrom worlds.sc2wol.Items import lookup_id_to_name, item_table\nfrom worlds.sc2wol.Locations import SC2WOL_LOC_ID_OFFSET\nfrom worlds.sc2wol import SC2WoLWorld\n\nfrom Utils import init_logging\n\nif __name__ == \"__main__\":\n init_logging(\"SC2Client\", exception_logger=\"Client\")\n\nlogger = logging.getLogger(\"Client\")\nsc2_logger = logging.getLogger(\"Starcraft2\")\n\nimport colorama\n\nfrom NetUtils import *\nfrom CommonClient import CommonContext, server_loop, ClientCommandProcessor, gui_enabled, get_base_parser\n\nnest_asyncio.apply()\n\n\nclass StarcraftClientProcessor(ClientCommandProcessor):\n ctx: Context\n\n def _cmd_disable_mission_check(self) -> bool:\n \"\"\"Disables the check to see if a mission is available to play. Meant for co-op runs where one player can play\n the next mission in a chain the other player is doing.\"\"\"\n self.ctx.missions_unlocked = True\n sc2_logger.info(\"Mission check has been disabled\")\n\n def _cmd_play(self, mission_id: str = \"\") -> bool:\n \"\"\"Start a Starcraft 2 mission\"\"\"\n\n options = mission_id.split()\n num_options = len(options)\n\n if num_options > 0:\n mission_number = int(options[0])\n\n self.ctx.play_mission(mission_number)\n\n else:\n sc2_logger.info(\n \"Mission ID needs to be specified. Use /unfinished or /available to view ids for available missions.\")\n\n return True\n\n def _cmd_available(self) -> bool:\n \"\"\"Get what missions are currently available to play\"\"\"\n\n request_available_missions(self.ctx.checked_locations, self.ctx.mission_req_table, self.ctx.ui)\n return True\n\n def _cmd_unfinished(self) -> bool:\n \"\"\"Get what missions are currently available to play and have not had all locations checked\"\"\"\n\n request_unfinished_missions(self.ctx.checked_locations, self.ctx.mission_req_table, self.ctx.ui, self.ctx)\n return True\n\n\nclass Context(CommonContext):\n command_processor = StarcraftClientProcessor\n game = \"Starcraft 2 Wings of Liberty\"\n items_handling = 0b111\n difficulty = -1\n all_in_choice = 0\n mission_req_table = None\n items_rec_to_announce = []\n rec_announce_pos = 0\n items_sent_to_announce = []\n sent_announce_pos = 0\n announcements = []\n announcement_pos = 0\n sc2_run_task: typing.Optional[asyncio.Task] = None\n missions_unlocked = False\n\n async def server_auth(self, password_requested: bool = False):\n if password_requested and not self.password:\n await super(Context, self).server_auth(password_requested)\n if not self.auth:\n logger.info('Enter slot name:')\n self.auth = await self.console_input()\n\n await self.send_connect()\n\n def on_package(self, cmd: str, args: dict):\n if cmd in {\"Connected\"}:\n self.difficulty = args[\"slot_data\"][\"game_difficulty\"]\n self.all_in_choice = args[\"slot_data\"][\"all_in_map\"]\n slot_req_table = args[\"slot_data\"][\"mission_req\"]\n self.mission_req_table = {}\n for mission in slot_req_table:\n self.mission_req_table[mission] = MissionInfo(**slot_req_table[mission])\n\n if cmd in {\"PrintJSON\"}:\n noted = False\n if \"receiving\" in args:\n if args[\"receiving\"] == self.slot:\n self.announcements.append(args[\"data\"])\n noted = True\n if not noted and \"item\" in args:\n if args[\"item\"].player == self.slot:\n self.announcements.append(args[\"data\"])\n\n def run_gui(self):\n from kvui import GameManager\n from kivy.base import Clock\n from kivy.uix.tabbedpanel import TabbedPanelItem\n from kivy.uix.gridlayout import GridLayout\n from kivy.lang import Builder\n from kivy.uix.label import Label\n from kivy.uix.button import Button\n\n import Utils\n\n class MissionButton(Button):\n pass\n\n class MissionLayout(GridLayout):\n pass\n\n class MissionCategory(GridLayout):\n pass\n\n class SC2Manager(GameManager):\n logging_pairs = [\n (\"Client\", \"Archipelago\"),\n (\"Starcraft2\", \"Starcraft2\"),\n ]\n base_title = \"Archipelago Starcraft 2 Client\"\n\n mission_panel = None\n last_checked_locations = {}\n mission_id_to_button = {}\n\n def __init__(self, ctx):\n super().__init__(ctx)\n\n def build(self):\n container = super().build()\n\n panel = TabbedPanelItem(text=\"Starcraft 2 Launcher\")\n self.mission_panel = panel.content = MissionLayout()\n\n self.tabs.add_widget(panel)\n\n Clock.schedule_interval(self.build_mission_table, 0.5)\n\n return container\n\n def build_mission_table(self, dt):\n self.mission_panel.clear_widgets()\n\n if self.ctx.mission_req_table:\n self.mission_id_to_button = {}\n categories = {}\n available_missions = []\n unfinished_missions = calc_unfinished_missions(self.ctx.checked_locations, self.ctx.mission_req_table,\n self.ctx, available_missions=available_missions)\n\n self.last_checked_locations = self.ctx.checked_locations\n\n # separate missions into categories\n for mission in self.ctx.mission_req_table:\n if not self.ctx.mission_req_table[mission].category in categories:\n categories[self.ctx.mission_req_table[mission].category] = []\n\n categories[self.ctx.mission_req_table[mission].category].append(mission)\n\n for category in categories:\n category_panel = MissionCategory()\n category_panel.add_widget(Label(text=category, size_hint_y=None, height=50, outline_width=1))\n\n for mission in categories[category]:\n text = mission\n\n if mission in unfinished_missions:\n text = f\"[color=6495ED]{text}[/color]\"\n elif mission in available_missions:\n text = f\"[color=FFFFFF]{text}[/color]\"\n else:\n text = f\"[color=a9a9a9]{text}[/color]\"\n\n mission_button = MissionButton(text=text, size_hint_y=None, height=50)\n mission_button.bind(on_press=self.mission_callback)\n self.mission_id_to_button[self.ctx.mission_req_table[mission].id] = mission_button\n category_panel.add_widget(mission_button)\n\n category_panel.add_widget(Label(text=\"\"))\n self.mission_panel.add_widget(category_panel)\n\n def mission_callback(self, button):\n self.ctx.play_mission(list(self.mission_id_to_button.keys())\n [list(self.mission_id_to_button.values()).index(button)])\n\n self.ui = SC2Manager(self)\n self.ui_task = asyncio.create_task(self.ui.async_run(), name=\"UI\")\n\n Builder.load_file(Utils.local_path(os.path.dirname(SC2WoLWorld.__file__), \"Starcraft2.kv\"))\n\n async def shutdown(self):\n await super(Context, self).shutdown()\n if self.sc2_run_task:\n self.sc2_run_task.cancel()\n\n def play_mission(self, mission_id):\n if self.missions_unlocked or \\\n is_mission_available(mission_id, self.checked_locations, self.mission_req_table):\n if self.sc2_run_task:\n if not self.sc2_run_task.done():\n sc2_logger.warning(\"Starcraft 2 Client is still running!\")\n self.sc2_run_task.cancel() # doesn't actually close the game, just stops the python task\n if self.slot is None:\n sc2_logger.warning(\"Launching Mission without Archipelago authentication, \"\n \"checks will not be registered to server.\")\n self.sc2_run_task = asyncio.create_task(starcraft_launch(self, mission_id),\n name=\"Starcraft 2 Launch\")\n else:\n sc2_logger.info(\n f\"{lookup_id_to_mission[mission_id]} is not currently unlocked. \"\n f\"Use /unfinished or /available to see what is available.\")\n\n\nasync def main():\n multiprocessing.freeze_support()\n parser = get_base_parser()\n parser.add_argument('--name', default=None, help=\"Slot Name to connect as.\")\n args = parser.parse_args()\n\n ctx = Context(args.connect, args.password)\n ctx.auth = args.name\n if ctx.server_task is None:\n ctx.server_task = asyncio.create_task(server_loop(ctx), name=\"ServerLoop\")\n\n if gui_enabled:\n ctx.run_gui()\n ctx.run_cli()\n\n await ctx.exit_event.wait()\n\n await ctx.shutdown()\n\n\nmaps_table = [\n \"ap_traynor01\", \"ap_traynor02\", \"ap_traynor03\",\n \"ap_thanson01\", \"ap_thanson02\", \"ap_thanson03a\", \"ap_thanson03b\",\n \"ap_ttychus01\", \"ap_ttychus02\", \"ap_ttychus03\", \"ap_ttychus04\", \"ap_ttychus05\",\n \"ap_ttosh01\", \"ap_ttosh02\", \"ap_ttosh03a\", \"ap_ttosh03b\",\n \"ap_thorner01\", \"ap_thorner02\", \"ap_thorner03\", \"ap_thorner04\", \"ap_thorner05s\",\n \"ap_tzeratul01\", \"ap_tzeratul02\", \"ap_tzeratul03\", \"ap_tzeratul04\",\n \"ap_tvalerian01\", \"ap_tvalerian02a\", \"ap_tvalerian02b\", \"ap_tvalerian03\"\n]\n\n\ndef calculate_items(items):\n unit_unlocks = 0\n armory1_unlocks = 0\n armory2_unlocks = 0\n upgrade_unlocks = 0\n building_unlocks = 0\n merc_unlocks = 0\n lab_unlocks = 0\n protoss_unlock = 0\n minerals = 0\n vespene = 0\n\n for item in items:\n data = lookup_id_to_name[item.item]\n\n if item_table[data].type == \"Unit\":\n unit_unlocks += (1 << item_table[data].number)\n elif item_table[data].type == \"Upgrade\":\n upgrade_unlocks += (1 << item_table[data].number)\n elif item_table[data].type == \"Armory 1\":\n armory1_unlocks += (1 << item_table[data].number)\n elif item_table[data].type == \"Armory 2\":\n armory2_unlocks += (1 << item_table[data].number)\n elif item_table[data].type == \"Building\":\n building_unlocks += (1 << item_table[data].number)\n elif item_table[data].type == \"Mercenary\":\n merc_unlocks += (1 << item_table[data].number)\n elif item_table[data].type == \"Laboratory\":\n lab_unlocks += (1 << item_table[data].number)\n elif item_table[data].type == \"Protoss\":\n protoss_unlock += (1 << item_table[data].number)\n elif item_table[data].type == \"Minerals\":\n minerals += item_table[data].number\n elif item_table[data].type == \"Vespene\":\n vespene += item_table[data].number\n\n return [unit_unlocks, upgrade_unlocks, armory1_unlocks, armory2_unlocks, building_unlocks, merc_unlocks,\n lab_unlocks, protoss_unlock, minerals, vespene]\n\n\ndef calc_difficulty(difficulty):\n if difficulty == 0:\n return 'C'\n elif difficulty == 1:\n return 'N'\n elif difficulty == 2:\n return 'H'\n elif difficulty == 3:\n return 'B'\n\n return 'X'\n\n\nasync def starcraft_launch(ctx: Context, mission_id):\n ctx.rec_announce_pos = len(ctx.items_rec_to_announce)\n ctx.sent_announce_pos = len(ctx.items_sent_to_announce)\n ctx.announcements_pos = len(ctx.announcements)\n\n sc2_logger.info(f\"Launching {lookup_id_to_mission[mission_id]}. If game does not launch check log file for errors.\")\n\n run_game(sc2.maps.get(maps_table[mission_id - 1]), [Bot(Race.Terran, ArchipelagoBot(ctx, mission_id),\n name=\"Archipelago\", fullscreen=True)], realtime=True)\n\n\nclass ArchipelagoBot(sc2.bot_ai.BotAI):\n game_running = False\n mission_completed = False\n first_bonus = False\n second_bonus = False\n third_bonus = False\n fourth_bonus = False\n fifth_bonus = False\n sixth_bonus = False\n seventh_bonus = False\n eight_bonus = False\n ctx: Context = None\n mission_id = 0\n\n can_read_game = False\n\n last_received_update = 0\n\n def __init__(self, ctx: Context, mission_id):\n self.ctx = ctx\n self.mission_id = mission_id\n\n super(ArchipelagoBot, self).__init__()\n\n async def on_step(self, iteration: int):\n game_state = 0\n if iteration == 0:\n start_items = calculate_items(self.ctx.items_received)\n difficulty = calc_difficulty(self.ctx.difficulty)\n await self.chat_send(\"ArchipelagoLoad {} {} {} {} {} {} {} {} {} {} {} {}\".format(\n difficulty,\n start_items[0], start_items[1], start_items[2], start_items[3], start_items[4],\n start_items[5], start_items[6], start_items[7], start_items[8], start_items[9],\n self.ctx.all_in_choice))\n self.last_received_update = len(self.ctx.items_received)\n\n else:\n if self.ctx.announcement_pos < len(self.ctx.announcements):\n index = 0\n message = \"\"\n while index < len(self.ctx.announcements[self.ctx.announcement_pos]):\n message += self.ctx.announcements[self.ctx.announcement_pos][index][\"text\"]\n index += 1\n\n index = 0\n start_rem_pos = -1\n # Remove unneeded [Color] tags\n while index < len(message):\n if message[index] == '[':\n start_rem_pos = index\n index += 1\n elif message[index] == ']' and start_rem_pos > -1:\n temp_msg = \"\"\n\n if start_rem_pos > 0:\n temp_msg = message[:start_rem_pos]\n if index < len(message) - 1:\n temp_msg += message[index + 1:]\n\n message = temp_msg\n index += start_rem_pos - index\n start_rem_pos = -1\n else:\n index += 1\n\n await self.chat_send(\"SendMessage \" + message)\n self.ctx.announcement_pos += 1\n\n # Archipelago reads the health\n for unit in self.all_own_units():\n if unit.health_max == 38281:\n game_state = int(38281 - unit.health)\n self.can_read_game = True\n\n if iteration == 160 and not game_state & 1:\n await self.chat_send(\"SendMessage Warning: Archipelago unable to connect or has lost connection to \" +\n \"Starcraft 2 (This is likely a map issue)\")\n\n if self.last_received_update < len(self.ctx.items_received):\n current_items = calculate_items(self.ctx.items_received)\n await self.chat_send(\"UpdateTech {} {} {} {} {} {} {} {}\".format(\n current_items[0], current_items[1], current_items[2], current_items[3], current_items[4],\n current_items[5], current_items[6], current_items[7]))\n self.last_received_update = len(self.ctx.items_received)\n\n if game_state & 1:\n if not self.game_running:\n print(\"Archipelago Connected\")\n self.game_running = True\n\n if self.can_read_game:\n if game_state & (1 << 1) and not self.mission_completed:\n if self.mission_id != 29:\n print(\"Mission Completed\")\n await self.ctx.send_msgs([\n {\"cmd\": 'LocationChecks', \"locations\": [SC2WOL_LOC_ID_OFFSET + 100 * self.mission_id]}])\n self.mission_completed = True\n else:\n print(\"Game Complete\")\n await self.ctx.send_msgs([{\"cmd\": 'StatusUpdate', \"status\": ClientStatus.CLIENT_GOAL}])\n self.mission_completed = True\n\n if game_state & (1 << 2) and not self.first_bonus:\n print(\"1st Bonus Collected\")\n await self.ctx.send_msgs(\n [{\"cmd\": 'LocationChecks',\n \"locations\": [SC2WOL_LOC_ID_OFFSET + 100 * self.mission_id + 1]}])\n self.first_bonus = True\n\n if not self.second_bonus and game_state & (1 << 3):\n print(\"2nd Bonus Collected\")\n await self.ctx.send_msgs(\n [{\"cmd\": 'LocationChecks',\n \"locations\": [SC2WOL_LOC_ID_OFFSET + 100 * self.mission_id + 2]}])\n self.second_bonus = True\n\n if not self.third_bonus and game_state & (1 << 4):\n print(\"3rd Bonus Collected\")\n await self.ctx.send_msgs(\n [{\"cmd\": 'LocationChecks',\n \"locations\": [SC2WOL_LOC_ID_OFFSET + 100 * self.mission_id + 3]}])\n self.third_bonus = True\n\n if not self.fourth_bonus and game_state & (1 << 5):\n print(\"4th Bonus Collected\")\n await self.ctx.send_msgs(\n [{\"cmd\": 'LocationChecks',\n \"locations\": [SC2WOL_LOC_ID_OFFSET + 100 * self.mission_id + 4]}])\n self.fourth_bonus = True\n\n if not self.fifth_bonus and game_state & (1 << 6):\n print(\"5th Bonus Collected\")\n await self.ctx.send_msgs(\n [{\"cmd\": 'LocationChecks',\n \"locations\": [SC2WOL_LOC_ID_OFFSET + 100 * self.mission_id + 5]}])\n self.fifth_bonus = True\n\n if not self.sixth_bonus and game_state & (1 << 7):\n print(\"6th Bonus Collected\")\n await self.ctx.send_msgs(\n [{\"cmd\": 'LocationChecks',\n \"locations\": [SC2WOL_LOC_ID_OFFSET + 100 * self.mission_id + 6]}])\n self.sixth_bonus = True\n\n if not self.seventh_bonus and game_state & (1 << 8):\n print(\"6th Bonus Collected\")\n await self.ctx.send_msgs(\n [{\"cmd\": 'LocationChecks',\n \"locations\": [SC2WOL_LOC_ID_OFFSET + 100 * self.mission_id + 7]}])\n self.seventh_bonus = True\n\n if not self.eight_bonus and game_state & (1 << 9):\n print(\"6th Bonus Collected\")\n await self.ctx.send_msgs(\n [{\"cmd\": 'LocationChecks',\n \"locations\": [SC2WOL_LOC_ID_OFFSET + 100 * self.mission_id + 8]}])\n self.eight_bonus = True\n\n else:\n await self.chat_send(\"LostConnection - Lost connection to game.\")\n\n\ndef calc_objectives_completed(mission, missions_info, locations_done, unfinished_locations, ctx):\n objectives_complete = 0\n\n if missions_info[mission].extra_locations > 0:\n for i in range(missions_info[mission].extra_locations):\n if (missions_info[mission].id * 100 + SC2WOL_LOC_ID_OFFSET + i) in locations_done:\n objectives_complete += 1\n else:\n unfinished_locations[mission].append(ctx.location_name_getter(\n missions_info[mission].id * 100 + SC2WOL_LOC_ID_OFFSET + i))\n\n return objectives_complete\n\n else:\n return -1\n\n\ndef request_unfinished_missions(locations_done, location_table, ui, ctx):\n if location_table:\n message = \"Unfinished Missions: \"\n unlocks = initialize_blank_mission_dict(location_table)\n unfinished_locations = initialize_blank_mission_dict(location_table)\n\n unfinished_missions = calc_unfinished_missions(locations_done, location_table, ctx, unlocks=unlocks,\n unfinished_locations=unfinished_locations)\n\n message += \", \".join(f\"{mark_up_mission_name(mission, location_table, ui,unlocks)}[{location_table[mission].id}] \" +\n mark_up_objectives(\n f\"[{unfinished_missions[mission]}/{location_table[mission].extra_locations}]\",\n ctx, unfinished_locations, mission)\n for mission in unfinished_missions)\n\n if ui:\n ui.log_panels['All'].on_message_markup(message)\n ui.log_panels['Starcraft2'].on_message_markup(message)\n else:\n sc2_logger.info(message)\n else:\n sc2_logger.warning(\"No mission table found, you are likely not connected to a server.\")\n\n\ndef calc_unfinished_missions(locations_done, locations, ctx, unlocks=None, unfinished_locations=None,\n available_missions=[]):\n unfinished_missions = []\n locations_completed = []\n\n if not unlocks:\n unlocks = initialize_blank_mission_dict(locations)\n\n if not unfinished_locations:\n unfinished_locations = initialize_blank_mission_dict(locations)\n\n if len(available_missions) > 0:\n available_missions = []\n\n available_missions.extend(calc_available_missions(locations_done, locations, unlocks))\n\n for name in available_missions:\n if not locations[name].extra_locations == -1:\n objectives_completed = calc_objectives_completed(name, locations, locations_done, unfinished_locations, ctx)\n\n if objectives_completed < locations[name].extra_locations:\n unfinished_missions.append(name)\n locations_completed.append(objectives_completed)\n\n else:\n unfinished_missions.append(name)\n locations_completed.append(-1)\n\n return {unfinished_missions[i]: locations_completed[i] for i in range(len(unfinished_missions))}\n\n\ndef is_mission_available(mission_id_to_check, locations_done, locations):\n unfinished_missions = calc_available_missions(locations_done, locations)\n\n return any(mission_id_to_check == locations[mission].id for mission in unfinished_missions)\n\n\ndef mark_up_mission_name(mission, location_table, ui, unlock_table):\n \"\"\"Checks if the mission is required for game completion and adds '*' to the name to mark that.\"\"\"\n\n if location_table[mission].completion_critical:\n if ui:\n message = \"[color=AF99EF]\" + mission + \"[/color]\"\n else:\n message = \"*\" + mission + \"*\"\n else:\n message = mission\n\n if ui:\n unlocks = unlock_table[mission]\n\n if len(unlocks) > 0:\n pre_message = f\"[ref={list(location_table).index(mission)}|Unlocks: \"\n pre_message += \", \".join(f\"{unlock}({location_table[unlock].id})\" for unlock in unlocks)\n pre_message += f\"]\"\n message = pre_message + message + \"[/ref]\"\n\n return message\n\n\ndef mark_up_objectives(message, ctx, unfinished_locations, mission):\n formatted_message = message\n\n if ctx.ui:\n locations = unfinished_locations[mission]\n\n pre_message = f\"[ref={list(ctx.mission_req_table).index(mission)+30}|\"\n pre_message += \"
\".join(location for location in locations)\n pre_message += f\"]\"\n formatted_message = pre_message + message + \"[/ref]\"\n\n return formatted_message\n\n\ndef request_available_missions(locations_done, location_table, ui):\n if location_table:\n message = \"Available Missions: \"\n\n # Initialize mission unlock table\n unlocks = initialize_blank_mission_dict(location_table)\n\n missions = calc_available_missions(locations_done, location_table, unlocks)\n message += \\\n \", \".join(f\"{mark_up_mission_name(mission, location_table, ui, unlocks)}[{location_table[mission].id}]\"\n for mission in missions)\n\n if ui:\n ui.log_panels['All'].on_message_markup(message)\n ui.log_panels['Starcraft2'].on_message_markup(message)\n else:\n sc2_logger.info(message)\n else:\n sc2_logger.warning(\"No mission table found, you are likely not connected to a server.\")\n\n\ndef calc_available_missions(locations_done, locations, unlocks=None):\n available_missions = []\n missions_complete = 0\n\n # Get number of missions completed\n for loc in locations_done:\n if loc % 100 == 0:\n missions_complete += 1\n\n for name in locations:\n # Go through the required missions for each mission and fill up unlock table used later for hover-over tooltips\n if unlocks:\n for unlock in locations[name].required_world:\n unlocks[list(locations)[unlock-1]].append(name)\n\n if mission_reqs_completed(name, missions_complete, locations_done, locations):\n available_missions.append(name)\n\n return available_missions\n\n\ndef mission_reqs_completed(location_to_check, missions_complete, locations_done, locations):\n \"\"\"Returns a bool signifying if the mission has all requirements complete and can be done\n\n Keyword arguments:\n locations_to_check -- the mission string name to check\n missions_complete -- an int of how many missions have been completed\n locations_done -- a list of the location ids that have been complete\n locations -- a dict of MissionInfo for mission requirements for this world\"\"\"\n if len(locations[location_to_check].required_world) >= 1:\n # A check for when the requirements are being or'd\n or_success = False\n\n # Loop through required missions\n for req_mission in locations[location_to_check].required_world:\n req_success = True\n\n # Check if required mission has been completed\n if not (locations[list(locations)[req_mission-1]].id * 100 + SC2WOL_LOC_ID_OFFSET) in locations_done:\n if not locations[location_to_check].or_requirements:\n return False\n else:\n req_success = False\n\n # Recursively check required mission to see if it's requirements are met, in case !collect has been done\n if not mission_reqs_completed(list(locations)[req_mission-1], missions_complete, locations_done,\n locations):\n if not locations[location_to_check].or_requirements:\n return False\n else:\n req_success = False\n\n # If requirement check succeeded mark or as satisfied\n if locations[location_to_check].or_requirements and req_success:\n or_success = True\n\n if locations[location_to_check].or_requirements:\n # Return false if or requirements not met\n if not or_success:\n return False\n\n # Check number of missions\n if missions_complete >= locations[location_to_check].number:\n return True\n else:\n return False\n else:\n return True\n\n\ndef initialize_blank_mission_dict(location_table):\n unlocks = {}\n\n for mission in list(location_table):\n unlocks[mission] = []\n\n return unlocks\n\n\nif __name__ == '__main__':\n colorama.init()\n asyncio.run(main())\n colorama.deinit()\n","repo_name":"CaitSith2/MultiWorld-Utilities","sub_path":"Starcraft2Client.py","file_name":"Starcraft2Client.py","file_ext":"py","file_size_in_byte":28263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"16538279278","text":"#!/usr/bin/python2\n# True Item LLC\n# Artem Ivzhenko\n# artmeivzhenko@true-item.com\n# UDP Monitoring Script\n\nimport time\nimport syslog\nimport os\nfrom datetime import datetime\n\n\nclass SocketUDP:\n def __init__(self, error_log_file):\n self.error_log_file = error_log_file\n self.__error_logs__ = []\n self.__logs_in_RAM__ = []\n\n def dump_errors_to_disk_func(self, socket_name):\n while True:\n time.sleep(6)\n tmp_error_logs_len = len(self.__error_logs__)\n tmp_error_logs = self.__error_logs__[:tmp_error_logs_len - 1]\n self.__error_logs__ = self.__error_logs__[tmp_error_logs_len - 1:]\n for error_msg in tmp_error_logs:\n try:\n os.system(\"echo '{0}' >> {1}\"\n .format(error_msg, self.error_log_file + str(datetime.now().date()) + '.log'))\n except Exception as error:\n self.__error_logs__.append(str(error.args) + ' | Date=' + str(datetime.now()) +\n ' dump errors to disk [echo to {0}]\\n'\n .format(self.error_log_file + str(datetime.now().date()) + '.log'))\n syslog.syslog('[+] UDP script dumped {0} errors to disk space with errors'.format(socket_name))\n else:\n syslog.syslog('[+] UDP script dumped {0} errors to disk space without errors'.format(socket_name))\n\n def dump_logs_to_disk_func(self, file_for_dump, socket_name):\n while True:\n time.sleep(6)\n tmp_logs_in_ram_len = len(self.__logs_in_RAM__)\n tmp_logs_in_ram = self.__logs_in_RAM__[:tmp_logs_in_ram_len - 1]\n self.__logs_in_RAM__ = self.__logs_in_RAM__[tmp_logs_in_ram_len - 1:]\n for log in tmp_logs_in_ram:\n try:\n with open(str(file_for_dump + str(datetime.now().date()) + '.log'), 'a') as log_file:\n log_file.write(log)\n except Exception as error:\n self.__error_logs__.append(str(error.args) + ' | Date=' + str(datetime.now()) +\n ' dump logs to disk {0}.write\\n'\n .format(file_for_dump + str(datetime.now().date()) + '.log'))\n syslog.syslog('[+] UDP script dumped {0} RAM logs to disk space with errors'.format(socket_name))\n else:\n syslog.syslog('[+] UDP script dumped {0} RAM logs to disk space without errors'.format(socket_name))","repo_name":"artemivzhenko/monitoring_udp_network","sub_path":"base_udp_socket.py","file_name":"base_udp_socket.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22753236451","text":"import pytest\nfrom ellar.common import Module\nfrom ellar.common.constants import MODULE_METADATA, MODULE_WATERMARK\nfrom ellar.common.exceptions import ImproperConfiguration\nfrom ellar.di import has_binding, is_decorated_with_injectable\nfrom ellar.reflect import reflect\n\n\n@Module(\n name=\"test\",\n static_folder=\"test\",\n controllers=[\"controllers\"],\n routers=[\"routers\"],\n providers=[\"providers\"],\n modules=[\"modules\"],\n)\nclass ModuleDecoratorTest:\n pass\n\n\ndef test_module_decorator_keys_is_complete():\n assert reflect.get_metadata(MODULE_METADATA.ROUTERS, ModuleDecoratorTest) == [\n \"routers\"\n ]\n assert reflect.get_metadata(MODULE_METADATA.NAME, ModuleDecoratorTest) == \"test\"\n assert (\n reflect.get_metadata(MODULE_METADATA.STATIC_FOLDER, ModuleDecoratorTest)\n == \"test\"\n )\n assert reflect.get_metadata(MODULE_METADATA.PROVIDERS, ModuleDecoratorTest) == [\n \"providers\"\n ]\n assert reflect.get_metadata(MODULE_METADATA.CONTROLLERS, ModuleDecoratorTest) == [\n \"controllers\"\n ]\n assert reflect.get_metadata(MODULE_METADATA.MODULES, ModuleDecoratorTest) == [\n \"modules\"\n ]\n\n\ndef test_decorated_class_has_module_watermark():\n assert reflect.get_metadata(MODULE_WATERMARK, ModuleDecoratorTest)\n\n\ndef test_base_directory_is_dynamically_set_when_none():\n base_path = reflect.get_metadata(\n MODULE_METADATA.BASE_DIRECTORY, ModuleDecoratorTest\n )\n assert \"/test_decorators\" in str(base_path)\n\n\ndef test_cannot_decorate_module_class_twice():\n with pytest.raises(\n ImproperConfiguration, match=\"is already identified as a Module\"\n ):\n Module()(ModuleDecoratorTest)\n\n\ndef test_cannot_decorate_class_instance_as_a_module():\n with pytest.raises(ImproperConfiguration, match=\"is a class decorator -\"):\n Module()(ModuleDecoratorTest())\n\n\ndef test_decorated_class_default_scope_is_singleton():\n assert is_decorated_with_injectable(ModuleDecoratorTest)\n assert not has_binding(ModuleDecoratorTest) # __init__ is not overridden\n","repo_name":"eadwinCode/ellar","sub_path":"tests/test_decorators/test_modules.py","file_name":"test_modules.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"3"}
+{"seq_id":"29039637333","text":"\ndef db_table_exists(table, cursor=None):\n \"\"\"\n Determine if a table exists in the database\n\n cribbed from:\n https://gist.github.com/527113/307c2dec09ceeb647b8fa1d6d49591f3352cb034\n \"\"\"\n\n try:\n if not cursor:\n from django.db import connection\n cursor = connection.cursor()\n if not cursor:\n raise Exception\n table_names = connection.introspection.get_table_list(cursor)\n except:\n raise Exception(\"unable to determine if the table '%s' exists\" % table)\n else:\n return table in table_names","repo_name":"osuosl/ganeti_webmgr","sub_path":"ganeti_webmgr/ganeti_web/migrations/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"3"}
+{"seq_id":"34601492163","text":"import cPickle\n\nimport bpy\nobjects=list(bpy.data.objects)\nstore={}\nfaaa=None\nfor ob in objects:\n\tif ob.type==\"Mesh\":\n\t\tverts3=[]\n\t\tnorms3=[]\n\t\tverts4=[]\n\t\tnorms4=[]\n\t\tmesh = ob.getData(mesh=1)\n\t\tfor face in mesh.faces:\n\t\t\tlv=verts4\n\t\t\tln=norms4\n\t\t\tif len(face.verts)==3:\n\t\t\t\tlv=verts3\n\t\t\t\tln=norms3\n\t\t\tfor v in face.verts:\n\t\t\t\tlv+=list(v.co)\n\t\t\t\tif face.smooth:\n\t\t\t\t\tln+=list(v.no)\n\t\t\t\telse:\n\t\t\t\t\tln+=list(face.no)\n\n\t\tstore[ob.name]=(verts3,norms3,verts4,norms4)\n\nfilename=\"blob.pkl\"\nf=file(filename,\"wb\")\ncPickle.dump(store,f)\nf.close()\n\n","repo_name":"RichardOfWard/gastrocide","sub_path":"assets/bconvert.py","file_name":"bconvert.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33139455572","text":"from numpy import *\n\ndef loadSimpData():\n datMat = matrix([[ 1. , 2.1],\n [ 2. , 1.1],\n [ 1.3, 1. ],\n [ 1. , 1. ],\n [ 2. , 1. ]])\n classLabels = [1.0, 1.0, -1.0, -1.0, 1.0]\n return datMat,classLabels\n\n\ndef stumpClassify(dataMatrix,dimen,threshVal,threshIneq):#just classify the data\n retArray = ones((shape(dataMatrix)[0],1))\n if threshIneq == 'lt':\n retArray[dataMatrix[:,dimen] <= threshVal] = -1.0\n else:\n retArray[dataMatrix[:,dimen] > threshVal] = -1.0\n return retArray\n \n\ndef build_stump(data_arr, label_arr, weight, stepnum):\n data_mat = mat(data_arr)\n label_mat = mat(label_arr).T\n nrow, ncol = data_mat.shape\n min_error = inf\n best_class_est = mat(zeros((nrow, 1)))\n best_stump = {} \n for i in range(ncol):\n fea_min = data_mat[:,i].min()\n fea_max = data_mat[:,i].max()\n step = (fea_max - fea_min) / stepnum\n for j in range(-1,(stepnum+1)):\n threshold = fea_min + float(j) * step\n for k in [\"lt\", \"gt\"]:\n expected_return = stumpClassify(data_mat, i, threshold, k)\n error_mat = mat(ones((nrow,1)))\n error_mat[expected_return == label_mat] = 0\n weight_error = mat(weight).T * error_mat\n #print(\"split: dim %d, thresh %.2f, ineqal: %s, the weighted error is %.3f\" %(i, threshold, k, weight_error))\n if weight_error < min_error:\n min_error = weight_error\n best_class_est = expected_return\n best_stump[\"dim\"] = i\n best_stump[\"thresh\"] = threshold\n best_stump[\"ineq\"] = k\n return best_stump, min_error, best_class_est\n\ndef ada_boost(data_arr, label_arr, stepnum, max_interation=40):\n data_mat = mat(data_arr)\n label_mat = mat(label_arr).T\n nrow, ncol = data_mat.shape\n record_stump = []\n weight = mat(ones((nrow, 1)) / nrow)\n agg_exp = zeros((nrow,1))\n for i in range(max_interation):\n #print(\"weight: \", weight.T)\n each_stump, each_error, each_est = build_stump(data_mat, label_arr, weight, stepnum)\n alpha = log((1.0 - each_error) / max(each_error,1e-16)) / 2\n expon = -multiply(label_mat, each_est) * alpha\n weight = multiply(weight, exp(expon))\n weight = weight / sum(weight)\n agg_exp += multiply(alpha, each_est)\n each_stump[\"alpha\"] = alpha\n #print(\"each est: \", each_est.T)\n record_stump.append(each_stump)\n #print(\"agg_exp: \", agg_exp.T)\n agg_error = multiply(sign(agg_exp) != label_mat, ones((nrow, 1)) )\n error_rate = sum(agg_error) / len(agg_error)\n #print(\"total error: \", error_rate)\n if error_rate == 0.0:\n break\n return record_stump\n\ndef ada_classify(data, classifier):\n data_mat = mat(data)\n nrow, ncol = data_mat.shape\n agg_exp = zeros((nrow, 1))\n for each_class in classifier:\n each_exp = stumpClassify(data_mat,each_class[\"dim\"],each_class[\"thresh\"],each_class[\"ineq\"])\n agg_exp += multiply(each_class[\"alpha\"], each_exp)\n #print(agg_exp)\n return sign(agg_exp), agg_exp\n\ndef load_file(filename):\n feature_num = len( open(filename).readline().strip().split(\"\\t\") )\n data = []\n label = []\n for row in open(filename).readlines():\n temp = []\n individual_data = row.strip().split(\"\\t\")\n for j in range(feature_num-1):\n temp.append(float(individual_data[j]))\n data.append(temp)\n label.append(float(individual_data[-1]))\n return mat(data), label\n\n\ndef plot_roc(pred_strength, class_label):\n import matplotlib.pyplot as plt\n pred_strength = pred_strength.reshape(1, len(pred_strength))\n rank_value = pred_strength[0].argsort()\n point = (1, 1)\n num_pos_class = sum(array(class_label) == 1)\n y_step = 1 / num_pos_class\n x_step = 1 / (len(class_label) - num_pos_class)\n auc = 0\n fig = plt.figure()\n fig.clf()\n subfig = fig.add_subplot(111)\n for i in rank_value.tolist():\n if class_label[i] == 1:\n x = 0; y = y_step\n else:\n x = x_step; y = 0\n auc += x_step * point[1]\n subfig.plot([point[0], point[0]-x], [point[1], point[1]-y], c=\"b\")\n point = (point[0]-x, point[1]-y)\n subfig.plot([0,1], [0,1], \"b--\")\n plt.xlabel(\"false positive rate\")\n plt.ylabel(\"true positive rate\")\n plt.title(\"title\")\n subfig.axis([0, 1, 0, 1])\n plt.show()\n print(\"AUC: \", auc)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"kunzhou92/Algorithms-Using-Python","sub_path":"adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29056159387","text":"from bcl.banks.registry import Ibaz\n\n\ndef test_payment_creator(build_payment_bundle):\n\n associate = Ibaz\n\n bundle = build_payment_bundle(\n associate,\n payment_dicts=[\n {'f_iban': 'AZ62İBAZ38010019449111111120', 't_bic': '010305'},\n ],\n account={'number': 'one'})\n\n assert (\n ',38010019449111111120,120,RUB,152.00,RUB,A,'\n f'0000000000000002,\"ООО \"\"Кинопортал\"\"\",7725713770,010305,Назначение[{bundle.payments[0].number}],,,,XOHKS\\r\\n'\n ) in bundle.tst_compiled\n\n bundle = build_payment_bundle(\n associate,\n payment_dicts=[\n {'ground': 'Длинное назначение, которое никак не поместится '\n 'в четыре строки по тридцать пять символов в каждой и будет непременно обрезано, '\n 'как того и требует формат.', 't_bic': ''},\n ],\n account={'number': 'one'})\n\n assert (\n ',0000000000000001,001,RUB,152.00,RUB,A,'\n '0000000000000002,\"ООО \"\"Кинопортал\"\"\",7725713770,,\"Длинное назначение, которое никак н\",'\n 'е поместится в четыре строки по три,дцать пять символов в каждой и буде,'\n f'\"т непременно обрезано, как того [{bundle.payments[0].number}]\",XOHKS\\r\\n'\n ) in bundle.tst_compiled\n\n bundle = build_payment_bundle(\n associate,\n payment_dicts=[\n {'f_iban': 'AZ62İBAZ38010019449111111120', 't_swiftcode': 'IBAZXXXX'},\n ],\n account={'number': 'one'})\n\n assert (\n f',38010019449111111120,120,RUB,152.00,A,0000000000000002,002,RUB,Назначение[{bundle.payments[0].number}]\\r\\n'\n ) in bundle.tst_compiled\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"billing/tests/banks/party_ibaz/test_ibaz.py","file_name":"test_ibaz.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20929454271","text":"from queue import Queue as fifo\nfrom checkquit import CheckQuit\n\n# path finding - bfs is ideal for maze.\ndef bfs(start_cell, end_cell, grid):\n # CREATE A QUEUE TO SEARCH THROUGH THE MAZE 'BREADTH FIRST'\n Q = fifo()\n searched = []\n # STEP 1. MAKE THE START CELL SEARCHED AND PUSH IT TO THE QUEUE\n searched.append(start_cell)\n Q.put(start_cell)\n # CREATE A HASH-MAP TO KEEP TRACK OF WHERE EACH CELL COMES FROM ( ROOT OF EACH CELL ), AND ALL THE SEARCHED CELLS\n track = {}\n # KEEP SEARCHING UNTIL A PATH IS FOUND\n while True:\n CheckQuit() # CHECK IF THE USER WANTS TO QUIT PYGAME\n # STEP 2\n # POP A CELL FROM THE QUEUE AND ASSIGN IT TO ROOT\n root = Q.get()\n # IF ROOT IS THE END CELL, PATH HAS BEEN FOUND\n if root == end_cell:\n # BACKTRACK THE PATH FROM THE END CELL TO THE START CELL USING THE HASH-MAP\n while track[root] != start_cell:\n CheckQuit() # CHECK IF THE USER WANTS TO QUIT PYGAME\n\n # UPDATE ROOT TO BE THE ROOT OF THE CURRENT ROOT CELL\n root = track[root]\n # ANNOUNCE THE COMPLETION OF PATH\n return root\n\n # IF ROOT HAS ANY NEIGHBOURS, MAKE THEM ALL SEARCHED IF THEY HAVEN'T ALREADY BEEN AND PUSH THEM TO THE QUEUE\n neighbours = root.get_unsearched_neighbour(grid, searched)\n if neighbours:\n for n in neighbours:\n searched.append(n)\n track[n] = root\n Q.put(n)\n","repo_name":"AaravGang/MazeGame","sub_path":"path_finding.py","file_name":"path_finding.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17004300425","text":"import pygame, os, sys\n\nimport PyGameProjectSpriteMove\n\npygame.init()\nsize = width, height = 45 * 16, 18 * 16\nuser_group = pygame.sprite.Group()\nboard_group = pygame.sprite.Group()\nall_sprites = pygame.sprite.Group()\npokemons_group = pygame.sprite.Group()\n\n\ndef load_image(filename):\n fullname = os.path.join(f\"Data/{filename}\")\n if not os.path.isfile(fullname):\n print(f\"Файл с изображением '{fullname}' не найден\")\n sys.exit()\n image = pygame.image.load(fullname)\n return image\n\n\ndef pokeball(x, y):\n pokeball = pygame.sprite.Sprite()\n pokeball.image = load_image(\"pokeball.png\")\n pokeball.rect = pokeball.image.get_rect()\n pokeball.rect.x = x\n pokeball.rect.y = y\n return pokeball\n\n\ndef start_screen():\n intro_text = [\"Правила игры:\",\n \"Чтобы отрыть меню, \",\n \"нажмите 5 посередине между стрелками.\",\n \"Чтобы закрыть открываюшиеся окна,\",\n \" кликните мышкой \",\n \"или нажмите кнопку на клавиатуре.\",\n \"Передвигайтесь клавишами стрелок.\",\n \"Если вы хотите начать, кликните мышкой!\"]\n size_for_start_screen = 600, 600\n screen = pygame.display.set_mode(size_for_start_screen)\n screen.fill((0, 0, 0))\n pikachu_group = pygame.sprite.Group()\n pikachu = pygame.sprite.Sprite(pikachu_group)\n pikachu.image = load_image(\"fon.png\")\n pikachu.rect = pikachu.image.get_rect()\n pikachu.rect.x, pikachu.rect.y = 200, 200\n pikachu_group.draw(screen)\n font = pygame.font.Font(pygame.font.match_font('cambria'), 20)\n string_rendered = font.render(\"Добро пожаловать в игру Pokemon Searching!\", True, pygame.Color('white'))\n intro_rect = string_rendered.get_rect()\n intro_rect.top = 20\n screen.blit(string_rendered, intro_rect)\n text_coord = 50\n for line in intro_text:\n font = pygame.font.Font(pygame.font.match_font('cambria'), 15)\n string_rendered = font.render(line, False, (244, 164, 96))\n intro_rect = string_rendered.get_rect()\n text_coord += 10\n intro_rect.top = text_coord\n intro_rect.x = 10\n text_coord += intro_rect.height\n screen.blit(string_rendered, intro_rect)\n clock = pygame.time.Clock()\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n elif event.type == pygame.KEYDOWN or \\\n event.type == pygame.MOUSEBUTTONDOWN:\n return True\n pygame.display.flip()\n clock.tick(fps)\n\n\ndef menu(user, menu_screen):\n pokemons = user.get_pokemons()\n menu_screen.fill((0, 0, 0))\n font = pygame.font.Font(None, 25)\n string_rendered = font.render(f\"Your pokemons:\", True, pygame.Color('white'))\n string_rect = string_rendered.get_rect()\n string_rect.x = 50\n string_rect.y = 30\n menu_screen.blit(string_rendered, string_rect)\n dx = 50\n dy = 50\n for i in range(len(pokemons)):\n pokemons[i].set_rect(i * 70 + dx, dy)\n font = pygame.font.Font(None, 15)\n ev, sk = pokemons[i].get_information()\n string_rendered = font.render(f\"evolution: {ev}\", False, (240, 230, 140))\n string_rect = string_rendered.get_rect()\n string_rect.x = i * 70 + dx\n string_rect.y = 60 + dy\n menu_screen.blit(string_rendered, string_rect)\n string_rendered = font.render(f\"skill: {sk}\", False, (240, 230, 140))\n string_rect.x = i * 70 + dx\n string_rect.y = 70 + dy\n menu_screen.blit(string_rendered, string_rect)\n pokemons_group.add(pokemons[i])\n clock = pygame.time.Clock()\n if not pokemons:\n font = pygame.font.Font(None, 25)\n string_rendered = font.render(f\"You haven't any pokemons\", 1, pygame.Color('white'))\n string_rect = string_rendered.get_rect()\n string_rect.x = 70\n string_rect.y = 70\n menu_screen.blit(string_rendered, string_rect)\n number = user.get_pokeballs()\n font = pygame.font.Font(None, 25)\n string_rendered = font.render(f\"Your pokeballs:\", 1, pygame.Color('white'))\n string_rect = string_rendered.get_rect()\n string_rect.x = 50\n string_rect.y = 130\n menu_screen.blit(string_rendered, string_rect)\n pokeball_for_menu = pokeball(50, 150)\n pokeballs_group = pygame.sprite.Group()\n pokeballs_group.add(pokeball_for_menu)\n font = pygame.font.Font(None, 15)\n string_rendered = font.render(f\"number:{number}\", False, (240, 230, 140))\n string_rect = string_rendered.get_rect()\n string_rect.x = 50\n string_rect.y = 190\n menu_screen.blit(string_rendered, string_rect)\n while True:\n pokemons_group.draw(menu_screen)\n pokeballs_group.draw(menu_screen)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n elif event.type == pygame.KEYDOWN or \\\n event.type == pygame.MOUSEBUTTONDOWN:\n return True\n pygame.display.flip()\n clock.tick(fps)\n\n\ndef get_something(screen, something):\n new_screen = screen\n font = pygame.font.Font(None, 25)\n new_screen.fill((184, 134, 11))\n string = font.render(\"You get:\", 1, (110, 50, 19))\n rect = (110, 70, 25, 25)\n new_screen.blit(string, rect)\n try:\n str(something)\n if something == \"pokeball\":\n pokeball_for_smth = pokeball(150, 110)\n pokeballs_group = pygame.sprite.Group()\n pokeballs_group.add(pokeball_for_smth)\n pokeballs_group.draw(new_screen)\n elif something.find(\"skill\") != -1:\n skill = pygame.sprite.Sprite()\n skill_group = pygame.sprite.Group()\n skill_group.add((skill))\n skill.image = load_image(\"skill.png\")\n skill.rect = skill.image.get_rect()\n skill.rect.x = 150\n skill.rect.y = 100\n string = font.render(something, False, pygame.Color('white'))\n rect = (150, 190, 25, 25)\n new_screen.blit(string, rect)\n skill_group.draw(new_screen)\n else:\n string = font.render(something, False, pygame.Color('white'))\n rect = (150, 120, 25, 25)\n new_screen.blit(string, rect)\n except:\n try:\n list(something)\n text_coord = 90\n for line in something:\n string_rendered = font.render(line, False, pygame.Color('white'))\n intro_rect = string_rendered.get_rect()\n text_coord += 10\n intro_rect.top = text_coord\n intro_rect.x = 150\n text_coord += intro_rect.height\n screen.blit(string_rendered, intro_rect)\n except:\n something_group = pygame.sprite.Group()\n something_group.add(something)\n something.set_rect(150, 150)\n something_group.draw(new_screen)\n clock = pygame.time.Clock()\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n elif event.type == pygame.KEYDOWN or \\\n event.type == pygame.MOUSEBUTTONDOWN:\n new_screen.fill((0, 0, 0))\n return True\n pygame.display.flip()\n clock.tick(fps)\n\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\n\nfps = 60\nstart_screen()\nscreen = pygame.display.set_mode(size)\nclock = pygame.time.Clock()\nscreen.fill((0, 0, 0))\nboard = PyGameProjectSpriteMove.Board()\nuser = PyGameProjectSpriteMove.GameHero(16 * 9, 16 * 9)\ncamera = PyGameProjectSpriteMove.Camera(0, 0)\nuser_group.add(user)\nboard_group.add(board)\nall_sprites.add(board, user)\nrunning = True\nwhile running:\n screen.fill((0, 0, 0))\n all_sprites.draw(screen)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.KEYDOWN and event.key == pygame.K_KP_5:\n menu(user, screen)\n something = user.update(board, event)\n if something:\n get_something(screen, something)\n camera.update(user)\n pygame.display.flip()\n for sprite in all_sprites:\n camera.apply(sprite)\n clock.tick(fps)\npygame.quit()","repo_name":"shokkialexa/PygameProject","sub_path":"PyGameProjectGame.py","file_name":"PyGameProjectGame.py","file_ext":"py","file_size_in_byte":8502,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"22479676974","text":"from stix2 import TAXIICollectionSource\nfrom taxii2client.v20 import Collection\nfrom stix2 import Filter\nimport json\nimport logging\nimport requests\nimport os\n\nMITREAttack = None\n\n\ndef download(url, outpath, verify=True):\n resp = requests.get(url, verify=verify) #nosec\n with open(outpath, \"wb\") as f:\n f.write(resp.content)\n\n\nclass MITREAttackGenerator:\n def __init__(self):\n self.mitreattack = None\n self_path = os.path.dirname(os.path.abspath(__file__))\n sup_files_path = os.path.join(self_path, \"../sup_files\")\n if not os.path.exists(sup_files_path):\n os.mkdir(sup_files_path)\n self.attack_path = os.path.join(sup_files_path, \"enterprise-attack.json\")\n if not os.path.exists(self.attack_path):\n self.downloadGithub(dst_path=self.attack_path)\n\n def taxiiVersion(self, TTP):\n\n # enterprise_attack = 95ecc380-afe9-11e4-9b6c-751b66dd541e\"\n # mobile_attack = 2f669986-b40b-4423-b720-4396ca6a462b\"\n # ics-attack = 02c3ef24-9cd4-48f3-a99f-b74ce24f1d34\"\n\n collection = Collection(\n f\"https://cti-taxii.mitre.org/stix/collections/95ecc380-afe9-11e4-9b6c-751b66dd541e/\"\n )\n src = TAXIICollectionSource(collection)\n\n result = src.query(\n [\n Filter(\"external_references.external_id\", \"=\", \"T\" + str(TTP).zfill(4)),\n Filter(\"type\", \"=\", \"attack-pattern\"),\n ]\n )\n\n try:\n return result[0]\n except:\n return \"Error: T\" + TTP + \" not found.\"\n\n def downloadGithub(self, dst_path=None):\n try:\n logging.info(\"Redownloading enterprise-attack.json...\")\n download(\n \"https://github.com/mitre-attack/attack-stix-data/raw/master/enterprise-attack/enterprise-attack.json\",\n dst_path,\n )\n except:\n logging.warning(\n \"Failed with normal download, trying with ignore ssl errors!\"\n )\n try:\n logging.info(\"Redownloading enterprise-attack.json...\")\n download(\n \"https://github.com/mitre-attack/attack-stix-data/raw/master/enterprise-attack/enterprise-attack.json\",\n dst_path,\n verify=False,\n )\n except:\n logging.error(\"Download Error for enterprise-attack.json: Try Again\")\n return 0\n\n def githubVersion(self, TTP, file_path=None):\n # Open json file if not already loaded\n if self.mitreattack is None:\n self.mitreattack = {}\n with open(\n self.attack_path if file_path is None else file_path,\n \"r\",\n encoding=\"utf-8\",\n errors=\"replace\",\n ) as f:\n attack_raw_data = json.load(f)\n for i in attack_raw_data[\"objects\"]:\n if i[\"type\"] == \"attack-pattern\":\n self.mitreattack[\n i[\"external_references\"][0][\"external_id\"].lstrip(\"Tt\")\n ] = i\n\n # Search for TTP\n if TTP in self.mitreattack:\n return self.mitreattack[TTP]\n\n\nAttackGen = MITREAttackGenerator()\n\n# if __name__ == \"__main__\":\n# downloadGithub()\n# try:\n# TTP = sys.argv[1]\n# TTP = TTP.lstrip(\"Tt\")\n# except:\n# print(\"TTP Argument Missing\")\n# exit()\n\n\n# print(githubVersion(TTP))\n# print('###################################')\n# print(taxiiVersion(TTP))\n","repo_name":"idaholab/cape2stix","sub_path":"cape2stix/core/mitreattack.py","file_name":"mitreattack.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"39526403344","text":"import argparse\nimport sys\nfrom typing import TextIO, Generator, Iterable, Optional, Union\nfrom dataclasses import dataclass\nfrom enum import Enum\n\n\nTOTAL_DISK_SPACE = 70000000\nNEEDED_SPACE_FOR_UPDATE = 30000000\n\n\ndef main(terminal_output_file: TextIO, part: int):\n inputs_outputs = read_inputs_and_outputs(terminal_output_file)\n filesystem = create_filesystem(inputs_outputs)\n assert filesystem is not None, \"No filesystem created\"\n if part == 1:\n dirs = find_directories_with_max_total_size(filesystem.root, 100000)\n print(sum([d.size for d in dirs]))\n elif part == 2:\n if filesystem.free_space >= NEEDED_SPACE_FOR_UPDATE:\n return\n space_to_free_up = NEEDED_SPACE_FOR_UPDATE - filesystem.free_space\n sizes = get_directories_sizes(filesystem.root)\n for size in sizes:\n if size >= space_to_free_up:\n print(size)\n break\n else:\n raise ValueError(f\"Invalid part: {part}\")\n\n\nclass CommandType(str, Enum):\n CD = \"cd\"\n LS = \"ls\"\n\n\n@dataclass\nclass Input:\n command_type: CommandType\n arguments: list[str]\n\n\n@dataclass\nclass InputOutput:\n input: Input\n output: list[str]\n\n\n@dataclass\nclass File:\n name: str\n size: int\n\n\n@dataclass\nclass Directory:\n name: str\n parent: Optional[\"Directory\"]\n contents: list[Union[\"Directory\", File]]\n\n @property\n def size(self) -> int:\n return sum([content.size for content in self.contents])\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, Directory):\n return False\n return self.name == other.name and self.contents == other.contents\n\n\nclass FileSystem:\n total_disk_space: int\n root: Directory\n current: Directory\n\n def __init__(self, total_disk_space: int, root: Directory | None = None):\n self.root = root or Directory(\"/\", None, [])\n self.current = self.root\n self.total_disk_space = total_disk_space\n\n @property\n def used_space(self) -> int:\n return self.root.size\n\n @property\n def free_space(self) -> int:\n return self.total_disk_space - self.root.size\n\n def cd(self, path: str) -> None:\n if path == \"..\":\n assert self.current.parent is not None, \"Cannot go up from root\"\n self.current = self.current.parent\n else:\n if path.startswith(\"/\"):\n path = path[1:]\n self.current = self.root\n next_directory, *rest = path.split(\"/\")\n while next_directory:\n for content in self.current.contents:\n if content.name == next_directory:\n assert isinstance(\n content, Directory), \"Cannot cd into a file\"\n self.current = content\n break\n if rest:\n next_directory = rest.pop(0)\n self.cd(next_directory)\n else:\n next_directory = None\n\n def add_content(self, content: File | Directory) -> None:\n self.current.contents.append(content)\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, FileSystem):\n return False\n return self.root == other.root\n\n def __repr__(self) -> str:\n return f\"FileSystem(root={self.root}, current={self.current})\"\n\n def __str__(self) -> str:\n return self._dir_str(self.root)\n\n def _file_str(self, file: File, indent: int = 0) -> str:\n return f\"{' ' * indent}- {file.name} (file, size={file.size})\\n\"\n\n def _dir_str(self, dir: Directory, indent: int = 0) -> str:\n result = f\"{' ' * indent}- {dir.name} (dir, size={dir.size})\\n\"\n for content in dir.contents:\n if isinstance(content, Directory):\n result += self._dir_str(content, indent + 1)\n else:\n result += self._file_str(content, indent + 1)\n return result\n\n\ndef read_inputs_and_outputs(terminal_output_file: TextIO) -> Generator[InputOutput, None, None]:\n current_input: Input | None = None\n current_output: list[str] = []\n for line in terminal_output_file.readlines():\n if line.startswith(\"$\"):\n if current_input is not None:\n yield InputOutput(input=current_input, output=current_output)\n current_input = parse_input(line)\n current_output = []\n else:\n current_output.append(line.strip())\n if current_input is not None:\n yield InputOutput(input=current_input, output=current_output)\n\n\ndef parse_input(line: str) -> Input:\n _, command, *arguments = line.split()\n return Input(command_type=CommandType(command), arguments=arguments)\n\n\ndef create_filesystem(inputs_outputs: Iterable[InputOutput]) -> FileSystem | None:\n filesystem: FileSystem | None = None\n for input_output in inputs_outputs:\n if input_output.input.command_type == CommandType.CD:\n if filesystem is None and input_output.input.arguments[0] == \"/\":\n filesystem = FileSystem(total_disk_space=TOTAL_DISK_SPACE) \n elif filesystem is None:\n raise ValueError(\"First command must be cd /\")\n else:\n filesystem.cd(input_output.input.arguments[0])\n elif input_output.input.command_type == CommandType.LS:\n if filesystem is None:\n raise ValueError(\"First command must be cd /\")\n for line in input_output.output:\n if line.startswith(\"dir\"):\n _, name = line.split(\" \")\n content = Directory(name, filesystem.current, [])\n else:\n size, name = line.split(\" \")\n content = File(name=name, size=int(size))\n filesystem.add_content(content)\n return filesystem\n\n\ndef find_directories_with_max_total_size(directory: Directory, n: int) -> list[Directory]:\n result: list[Directory] = []\n if directory.size <= n:\n result.append(directory)\n for d in directory.contents:\n if isinstance(d, Directory):\n result += find_directories_with_max_total_size(d, n)\n return result\n\n\ndef get_directories_sizes(directory: Directory) -> list[int]:\n result: list[int] = []\n result.append(directory.size)\n for d in directory.contents:\n if isinstance(d, Directory):\n result += get_directories_sizes(d)\n return sorted(result)\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n # File argument or stdin\n parser.add_argument(\"file\", nargs=\"?\",\n type=argparse.FileType(\"r\"), default=sys.stdin)\n parser.add_argument(\"--part\", type=int, default=1)\n\n args = parser.parse_args()\n main(args.file, args.part)\n","repo_name":"gio8tisu/AoC2022","sub_path":"day7/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1404877440","text":"'''#Given a list of words, return a dictionary where the keys are the words and\r\n# the values are the number of times the word appears in the list.\r\n\r\ndi={}\r\nip=input(\"enter word's to be in the list =\")\r\nnested=ip.split()\r\nprint(nested)\r\nfor i in nested:\r\n if i in di.keys():\r\n di[i]+=1\r\n else:\r\n di[i]=1\r\nprint(\"final answer dictionary: \",di)'''\r\n\r\n'''#Given a list of words, return a dictionary \r\n# where the keys are the words and the values are the number of letters in the word.\r\n\r\ndi={}\r\ndef func_2(nested):\r\n for i in nested:\r\n di[i]=len(i)\r\n return di\r\n\r\nip=input(\"enter word's to be in the list =\")\r\nnested=ip.split()\r\nprint(\"final answer dictionary: \", func_2(nested))'''\r\n\r\n'''#Given a list of words, return a dictionary where \r\n# the keys are the words and the values are the number of vowels in the word.\r\ndi={}\r\ndef vowels_count(nested):\r\n for i in nested:\r\n for words in i:\r\n if (words.lower() in ['a','e','i','o','u']):\r\n try:\r\n di[i]+=1\r\n except:\r\n di[i]=1\r\n return di\r\n\r\nip=input(\"enter word's to be in the list =\")\r\nnested=ip.split()\r\nprint(\"final answer dictionary: \",vowels_count(nested))'''\r\n\r\n\r\n# Python3 code to demonstrate working of\r\n# Bigrams Frequency in String\r\n# Using Counter() + generator expression\r\nfrom collections import Counter\r\n\t\r\n# initializing string\r\ntest_str = 'geeksforgeeks'\r\n\r\n# printing original string\r\nprint(\"The original string is : \" + str(test_str))\r\n\r\n# Bigrams Frequency in String\r\n# Using Counter() + generator expression\r\nres = Counter(test_str.split(' ')for idx in range(len(test_str) - 1))\r\n\r\n# printing result\r\nprint(\"The Bigrams Frequency is : \" + str(dict(res)))\r\n","repo_name":"dorait/Kriyadocs-SAAS-Academy","sub_path":"week3.py","file_name":"week3.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30319224597","text":"\nimport os\n\ndef obtener_fila_verificada(palabra_a_encontrar, palabra_ingresada):\n # Crear una lista vacía para el resultado.\n # Si las letras existen en la palabra a encontrar y sus posiciones coinciden: Encerrarlas en [] y agregar al resultado.\n # Si las letras existen en la palabra a encontrar pero sus posiciones no coinciden: Encerrarlas en () y agregar al resultado.\n # Si no se cumple ninguna de las anteriores, agregar al resultado sin hacer modificaciones.\n # Retornar el resultado.\n cantidad_de_letras_de_la_palabra_a_encontrar = 5\n\n letras_verificadas = [] # Creamos una lista vacía para almacenar el resultado de una linea\n\n for posicion in range(cantidad_de_letras_de_la_palabra_a_encontrar): # Iteramos por cada letra de la palabra ingresada\n\n las_letras_son_iguales = palabra_a_encontrar[posicion] == palabra_ingresada[posicion]\n la_letra_existe_en_la_palabra = palabra_ingresada[posicion] in palabra_a_encontrar\n\n if las_letras_son_iguales:\n # guardar las letras que están en la palabra a encontrar y coinciden en la posición, dentro de brackets\n letras_verificadas.append(f\"[{palabra_ingresada[posicion]}]\")\n elif la_letra_existe_en_la_palabra:\n # guardar las letras que no coinciden pero que están en la palabra a encontrar, dentro de parentesis\n letras_verificadas.append(f\"({palabra_ingresada[posicion]})\")\n else:\n # Las que no coinciden, se guardan sin modificiaciones\n letras_verificadas.append(palabra_ingresada[posicion])\n\n return letras_verificadas\n\n\ndef imprimir_grilla(grilla):\n cantidad_de_filas = len(grilla)\n\n for fila in range(cantidad_de_filas):\n print(grilla[fila])\n\n# Ejecución del programa\n\npalabra_a_encontrar = \"virus\"\ncantidad_de_letras = 5\nintentos = 6\n\ngrilla = []\n\nos.system(\"clear\")\nprint(\"Bienvenido al wordle!!\")\n\nwhile intentos > 0:\n print(f\"te quedan {intentos}\")\n palabra_ingresada = input(\"Ingrese una palabra:\")\n intentos = intentos - 1\n\n os.system(\"clear\")\n if (len(palabra_ingresada) != cantidad_de_letras):\n print(\"La cantidad de letras es incorrecta\")\n print(f\"la cantidad de letras correctas es {cantidad_de_letras}\")\n continue\n else:\n linea_verificada = obtener_fila_verificada(palabra_a_encontrar, palabra_ingresada)\n grilla.append(linea_verificada)\n\n imprimir_grilla(grilla)\n if palabra_ingresada == palabra_a_encontrar:\n print(\"Felicidades, ganaste!!!\")\n break","repo_name":"penguin-academy/bootcamp-01-hernandarias","sub_path":"wordlee.py","file_name":"wordlee.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19709727414","text":"# -*- coding:utf-8 -*-\n'''\nCreated on 2018年9月27日\n\n@author: Yu Qu\n'''\nimport networkx as nx\n\n##########################################################\ndef static_analysis(subject,file_network_file,prefix):\n G = nx.DiGraph()\n findFile = open(subject+'/'+file_network_file,'r')\n each_lines= findFile.readlines()\n for each_line in each_lines:\n if each_line.__contains__('>'):\n edge=each_line.split('>');\n if(prefix in edge[0]):\n edge[0]=edge[0][edge[0].index(prefix)+len(prefix):edge[0].rindex('\\\"')].replace(\"\\\\\",\"/\")\n if(prefix in edge[1]):\n edge[1]=edge[1][edge[1].index(prefix)+len(prefix):edge[1].rindex('\\\"')].replace(\"\\\\\",\"/\") \n if(G.has_edge(edge[0],edge[1])==False):\n G.add_edge(edge[0],edge[1]) \n findFile.close()\n return G","repo_name":"quyutest/node2defect","sub_path":"SupportingTools/CDNAnalysis.py","file_name":"CDNAnalysis.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"3"}
+{"seq_id":"14999432500","text":"\"\"\"\nEP - 36\n\nThe decimal number, 585 = (1001001001)2 (binary), is palindromic in both bases.\n\nFind the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.\n\n(Please note that the palindromic number, in either base, may not include leading zeros.)\n\"\"\"\n\ndef palindrome(num):\n # function to check if number is palindrome\n rev_num = str(num)[::-1]\n if rev_num == str(num):\n return True\n else:\n return False\n\ndef compute():\n total = 0\n for num in range(1, 1000000):\n if (palindrome(num) and palindrome(bin(num).split('b')[1])): \n total += num\n return total\n\nif __name__ == \"__main__\":\n print(compute())\n \n","repo_name":"supria68/ProjectEuler","sub_path":"python/double_base_palin.py","file_name":"double_base_palin.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36582612525","text":"import math\nimport re\nimport string\nimport pandas as pd\nfrom sklearn.metrics import mean_squared_error\nimport torch\nimport torch.nn as nn\n\n\ndef preprocessor(text):\n regex = re.compile('[' + re.escape(string.punctuation) + '0-9\\\\r\\\\t\\\\n]')\n text = regex.sub(\" \", text) # remove punctuation\n return text\n\n\ndef split_cat(text):\n try:\n return text.split(\"/\")\n except:\n return (\"No Label\", \"No Label\", \"No Label\")\n\n\n# A function to calculate Root Mean Squared Logarithmic Error (RMSLE) as requested in the challenge\ndef rmsle(y, y_pred):\n assert len(y) == len(y_pred)\n terms_to_sum = [(math.log(y_pred[i] + 1) - math.log(y[i] + 1)) ** 2.0 for i, pred in enumerate(y_pred)]\n return (sum(terms_to_sum) * (1.0 / len(y))) ** 0.5\n\n\nclass MLP(nn.Module):\n def __init__(self):\n super(MLP, self).__init__()\n self.layers = nn.Sequential(\n nn.Linear(100, 192),\n nn.ReLU(),\n nn.Linear(192, 64),\n nn.ReLU(),\n nn.Linear(64, 64),\n nn.ReLU(),\n nn.Linear(64, 1)\n )\n\n def forward(self, x):\n x = x.view(-1, x.size(0))\n x = self.layers(x)\n return x\n\n\nif __name__ == '__main__':\n\n x_train = pd.read_pickle('../mercariData/x_train.pkl', compression='bz2')\n x_train = torch.FloatTensor(x_train.values)\n x_test = pd.read_pickle('../mercariData/x_test.pkl', compression='bz2')\n x_test = torch.FloatTensor(x_test.values)\n y_train = pd.read_pickle('../mercariData/y_train.pkl', compression='bz2')\n y_train = torch.FloatTensor(y_train.values)\n y_test = pd.read_pickle('../mercariData/y_test.pkl', compression='bz2')\n # y_test = torch.FloatTensor(y_test.values)\n print(\"Loaded data\")\n model = MLP()\n optimizer = torch.optim.Adam(model.parameters(), lr=3e-3)\n loss_fn = torch.nn.MSELoss()\n print(\"Initialized model, optimizer and loss function\")\n mean_train_losses = []\n mean_valid_losses = []\n valid_acc_list = []\n epochs = 15\n\n # lets train!\n for epoch in range(epochs):\n print(\"Training epoch: {0}\".format(epoch + 1))\n model.train()\n\n train_losses = []\n valid_losses = []\n for i, data in enumerate(x_train):\n optimizer.zero_grad()\n outputs = model(data)\n loss = loss_fn(outputs, y_train[i])\n loss.backward()\n optimizer.step()\n\n train_losses.append(loss.item())\n\n # evaluating the results\n print(\"Evaluating the model...\")\n model.eval()\n outputs = []\n\n for i, data in enumerate(x_test):\n outputs.append(model(data))\n\n test_score = mean_squared_error(y_test, outputs)\n rmsle_score = rmsle(y_test, outputs)\n print(\"The test MSE score is: %f\" % test_score)\n print(\"The test RMSLE score is: %f\" % rmsle_score)\n","repo_name":"YuvalHelman/mercariPriceSuggestion","sub_path":"mlp_infersent.py","file_name":"mlp_infersent.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13833788322","text":"\"\"\"\nTesting of the basic stages of neural network training:\n * creation and preprocessing of a dataset and its visualization\n * creation of a model\n * forward-method of the model (model.predict(data))\n * one iteration of training with back-propogation\nMake sure that you have correctly described the data in configuration.py\n\"\"\"\n\nimport torch\nimport random\nfrom DataGeneratorFCNN import RCNNDataset\nfrom torch.utils.data import DataLoader\nfrom Utils import rcnn_create, plot_img_bbox\nfrom configuration import config_dataset\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nfrom tqdm import tqdm\n\nimage_size = config_dataset[\"image_shape\"]\ndevice = \"cuda\"\ncheck_all_dataset_objects = False\n# create dataset\ntransforms_ = A.Compose([A.Resize(width=image_size[0],\n height=image_size[1]),\n A.Normalize(max_pixel_value=255,\n mean=(0, 0, 0),\n std = (1, 1, 1)),\n ToTensorV2(p=1.0)],\n bbox_params={\"format\": \"pascal_voc\", \"label_fields\": [\"labels\"]})\ndataset = RCNNDataset(path_images=config_dataset[\"path_image_dir\"],\n path_annotations=config_dataset[\"path_annots_dir\"],\n transform=transforms_)\n\nclass_labels = dataset.classes\nprint(f\"Number of classes = {len(class_labels)}\")\nwith open(r\".\\logs\\classes.txt\", \"w\") as fi:\n fi.writelines([class_label[0] + f\" = {class_label[1]}\\n\" for class_label in class_labels.items()])\n\ndataloader = DataLoader(dataset,\n batch_size=config_dataset[\"batch_size\"],\n shuffle=False,\n collate_fn=dataset.collate_fn)\n\n\n# check generator data\ntry:\n tt = iter(dataloader)\n l1 = tt.__next__()\nexcept:\n print(\"Dataloader create/getitem error\")\nelse:\n print(\"Dataloader create/getitem is right\")\n\n# check _create all dataset objects_/_plot batch_\nif check_all_dataset_objects:\n print(\"Check create dataset objects with annotation\")\n inds = list(range(67116, len(dataset)))\n for i in tqdm(inds):\n try: img, target = dataset[i]\n except Exception as e: print(f\"Error in create object #{i} - file name {dataset.list_path_annots[i]}\\n{e}\")\n print(\"Check dataset objects is completed\")\nelse:\n inds = [random.choice(list(range(len(dataset)))) for i in range(10)]\n for i in inds:\n try:\n img, target = dataset[i]\n plot_img_bbox(img.permute(1, 2, 0), target)\n except:\n print(f\"Plot batch error with object #{i}\")\n print(\"Plotting batch successful\")\n\n# create model\ntry:\n model = rcnn_create(len(class_labels.items()))\n # check model forward method inference and training\n # infer\n model = model.to(device)\n model.eval()\n # images is expected to be a list of 3d tensors of shape [C, H, W]\n with torch.no_grad():\n outs = model([l1[0][0].to(device)])\n # train 2 steps\n model = rcnn_create(len(class_labels.items()))\n model.train()\n opt = torch.optim.Adam(params=model.parameters())\n outs_loss1 = model(l1[0], l1[1])\n losses1 = sum(loss for loss in outs_loss1.values())\n print(f\"Losses on 1 step = {losses1}\")\n\n losses1.backward()\n opt.step()\n opt.zero_grad()\n l2 = tt.__next__()\n outs_loss2 = model(l2[0], l2[1])\n losses2 = sum(loss for loss in outs_loss2.values())\n print(f\"Losses on 2 step = {losses2}\")\n assert True\nexcept:\n print(\"Model_creation/forward/train-step error\")\nelse:\n print(\"Model_creation/forward is right\")","repo_name":"CheremGS/Objects_detection_models","sub_path":"Fast_RCNN/Test_components.py","file_name":"Test_components.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38677339735","text":"from back_process import *\n\nif __name__ == '__main__':\n import scipy.optimize as so\n import numpy as np\n\n gammas_np = genfromtxt('E:/mnustes_science/experimental_data/faraday_drift_03/dvelocities_info/velocity_processed/gammas.csv', delimiter=',')\n velocities_np = genfromtxt('E:/mnustes_science/experimental_data/faraday_drift_03/dvelocities_info/velocity_processed/velocities.csv', delimiter=',')\n velocities_error_np = genfromtxt('E:/mnustes_science/experimental_data/faraday_drift_03/dvelocities_info/velocity_processed/velocities_err.csv',delimiter=',')\n freq_np = genfromtxt(\n 'E:/mnustes_science/experimental_data/faraday_drift_03/dvelocities_info/freq_processed/freq.csv',\n delimiter=',')\n freq_error_np = genfromtxt(\n 'E:/mnustes_science/experimental_data/faraday_drift_03/dvelocities_info/freq_processed/freq_err.csv',\n delimiter=',')\n f_i = 14.80\n gammas_np = gamma_correction(gammas_np, f_i)\n cut = 12\n gammas_log = np.log(gammas_np[cut:-1] - 0.68 * np.ones(len(gammas_np[cut:-1])))\n #print(gammas[cut])\n velocities_log = np.log(velocities_np[cut:-1])\n velocities_error_log = velocities_error_np[cut:-1] / velocities_np[cut:-1]\n\n ### Ajuste de curva ###\n def linear_fit(x, m, n):\n return m * x + n\n #popt, pcov = curve_fit(linear_fit, gammas_log, velocities_log)\n #m = popt[0]\n #n = popt[1]\n #x_grid_log = np.arange(gammas_log[0] - np.abs(gammas_log[0] - gammas_log[1]), gammas_log[-1] + np.abs(gammas_log[0] - gammas_log[1]), 0.01)\n #velocities_log_fit = m * x_grid_log + n\n #print(\"m =\" + str(m))\n\n def f_freq(x, A, c):\n x = x.astype('complex128')\n return A * np.abs((x - c) ** 0.5)\n\n\n def f(x, A, c, noise):\n x = x.astype('complex128')\n return A * (np.abs(((x - c) + (np.abs((x - c)) ** 2 + 2 * noise) ** 0.5) / 2)) ** 0.5\n\n\n popt, pcov = curve_fit(f, gammas_np, velocities_np, bounds=[(0, 0.15, 0), (10, 0.25, 1)])\n\n A = popt[0]\n c = popt[1]\n noise = popt[2]\n\n print('A_noise='+str(A))\n print('c_noise=' + str(c))\n print('noise=' + str(noise))\n\n popt_02, pcov = curve_fit(f_freq, gammas_np, velocities_np, bounds=[(0, 0.15), (10, 0.25)])\n\n A_02 = popt_02[0]\n c_02 = popt_02[1]\n print('A='+str(A_02))\n print('c=' + str(c_02))\n\n\n\n x_grid = np.arange(0, 1, 0.0005)\n velocity_noisy_fitted = []\n for i in range(len(x_grid)):\n epsilon_i = x_grid[i] - c\n velocity_noisy_fitted_i = A * ((epsilon_i + (epsilon_i ** 2 + 2 * noise) ** 0.5) / 2) ** 0.5\n velocity_noisy_fitted.append(velocity_noisy_fitted_i)\n velocity_noisy_fitted_np = np.array(velocity_noisy_fitted)\n\n x_grid_antierror = np.arange(c, 1, 0.0005)\n velocity_fitted = []\n for i in range(len(x_grid_antierror)):\n epsilon_i = x_grid_antierror[i] - c\n velocity_fitted_i = A * (epsilon_i) ** 0.5\n velocity_fitted.append(velocity_fitted_i)\n velocity_fitted_np = np.array(velocity_fitted)\n\n\n #popt, pcov = curve_fit(f_freq, gammas_np, freq_np, bounds=[(0, 0), (100, 0.61)])\n #A_freq = popt[0]\n #c_freq = popt[1]\n\n #x_grid_antierror_freq = np.arange(c_freq, 1, 0.001)\n #freq_fitted = []\n #for i in range(len(x_grid_antierror_freq)):\n # epsilon_i = x_grid_antierror_freq[i] - c_freq\n # freq_fitted_i = A_freq * (epsilon_i) ** 0.5\n # freq_fitted.append(freq_fitted_i)\n #freq_fitted_np = np.array(freq_fitted)\n\n\n px = 1/plt.rcParams['figure.dpi']\n fig, ax1 = plt.subplots(figsize=(1200*px, 800*px))\n ax1.set_xlabel('$\\Gamma_0$', fontsize=30)\n ax1.set_ylabel('$\\langle v \\\\rangle\\ \\\\textrm{(mm/s)}$', fontsize=30)\n ax1.tick_params(labelsize=20)\n ax1.errorbar(gammas_np, velocities_np, yerr=velocities_error_np, marker='o', ls='', capsize=5, capthick=1,\n ecolor='k', color='k', zorder=3)\n ax1.plot(x_grid_antierror, velocity_fitted_np, linestyle='dotted', linewidth='3', c='r', label='Noise included', zorder=1)\n\n ax1.plot(x_grid, velocity_noisy_fitted_np, '-', linewidth='3', c='r', label='No noise', zorder=2)\n ax1.set_ylim([0, 1])\n ax1.set_xlim([0.61, 0.785])\n ax1.grid(True)\n\n left, bottom, width, height = [0.25, 0.5, 0.2, 0.3]\n ax2 = fig.add_axes([left, bottom, width, height])\n ax2.plot(x_grid_log, velocities_log_fit, linestyle='--', linewidth='3', c=[1,0.,0.], label='No noise', zorder=2)\n ax2.errorbar(gammas_log, velocities_log, yerr=velocities_error_log, marker='o', ls='', lw=1, ms=4, capsize=2, capthick=1,\n ecolor='k', color='k', zorder=3)\n ax2.tick_params(labelsize=15)\n plt.xlim([-4.9, -2.4])\n plt.xticks([-4.5, -3.5, -2.5])\n #ax2.set_ylim([-1.5, 0])\n ax2.grid(True)\n ax2.set_xlabel('$\\ln\\Delta_D$', fontsize=25)\n ax2.set_ylabel('$\\ln\\langle v \\\\rangle$', fontsize=25)\n plt.savefig('E:/mnustes_science/experimental_data/faraday_drift_03/dvelocities_info/velocity_processed/fit', dpi=300)\n #plt.show()\n plt.close()\n\n plt.plot(x_grid_log, velocities_log_fit, linestyle='--', linewidth='3', c=[1,0.,0.], label='No noise', zorder=2)\n plt.errorbar(gammas_log, velocities_log, yerr=velocities_error_log, marker='o', ls='', lw=1, ms=4, capsize=2, capthick=1,\n ecolor='k', color='k', zorder=3)\n plt.tick_params(labelsize=15)\n plt.xlim([-4.9, -2.4])\n #plt.ylim([-1.5, 0])\n plt.grid(True)\n plt.xlabel('$\\ln\\Delta_D$', fontsize=25)\n plt.ylabel('$\\ln\\langle v \\\\rangle$', fontsize=25)\n plt.tight_layout()\n\n # plt.show()\n plt.close()\n\n fig, ax = plt.subplots()\n textstr = '\\n'.join((r'$a=%.3f$' % (m,), r'$b=%.3f$' % (n,)))\n textstr_02 = \"$\\ln \\langle v \\\\rangle = a \\ln\\Delta_D + b$\"\n plt.plot(x_grid_log, velocities_log_fit, linestyle='--', linewidth='3', c=[1,0.,0.], label='No noise', zorder=2)\n plt.errorbar(gammas_log, velocities_log, yerr=velocities_error_log, marker='o', ls='', lw=1, ms=4, capsize=2, capthick=1,\n ecolor='k', color='k', zorder=3)\n plt.tick_params(labelsize=15)\n # plt.legend(loc='best', fancybox=True, shadow=True)\n plt.grid(True)\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=20, verticalalignment='top', bbox=props)\n #ax.text(0.5, 0.95, textstr_02, transform=ax.transAxes, fontsize=20, verticalalignment='top')\n plt.xlim([-4.9, -2.4])\n plt.xlabel('$\\ln\\Delta_D$', fontsize=25)\n plt.ylabel('$\\ln\\langle v \\\\rangle$', fontsize=25)\n plt.tight_layout()\n plt.savefig('E:/mnustes_science/experimental_data/faraday_drift_03/dvelocities_info/velocity_processed/log-log_02',\n dpi=300)\n plt.close()","repo_name":"rariveros/LENL_processing","sub_path":"faraday/01_projects/faraday_drift/bifurcation_powerlaw/power_law_drift.py","file_name":"power_law_drift.py","file_ext":"py","file_size_in_byte":6669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71627548883","text":"from datetime import datetime\n\nfrom XBOSDriver.timeseriestypes import UNIT_TIMES\nfrom XBOSDriver.timeseriestypes import UNIT_TIME_SECONDS, UNIT_TIME_MILLISECONDS, \\\n UNIT_TIME_MICROSECONDS, UNIT_TIME_NANOSECONDS\n\nUNIT_TIME_LOOKUP = {\n UNIT_TIME_SECONDS: 1,\n UNIT_TIME_MILLISECONDS: 1e3,\n UNIT_TIME_MICROSECONDS: 1e6,\n UNIT_TIME_NANOSECONDS: 1e9\n}\n\ndef get_current_time_as(time_unit):\n \"\"\"\n Returns current time in the given units. Uses local timezone\n \"\"\"\n if time_unit not in UNIT_TIME_LOOKUP:\n raise TimestampException(\"Unit of Time {0} not in {1}\".format(time_unit, UNIT_TIME_LOOKUP))\n return int(datetime.now().timestamp() * UNIT_TIME_LOOKUP[time_unit])\n\ndef buildkv(fullname, obj, separator='/'):\n if isinstance(obj, dict):\n rv = []\n for newk, newv in obj.items():\n if len(fullname):\n rv += buildkv(fullname + separator + newk, newv, separator)\n else:\n rv += buildkv(newk, newv, separator)\n return rv\n else:\n return [(fullname, obj)]\n\n# from smap.util\n# make a nested object from a config file line\ndef build_recursive(d, suppress=['type', 'key', 'uuid']):\n rv = {}\n for k, v in d.items():\n if k in suppress: continue\n pieces = k.split('/')\n cur = rv\n for cmp in pieces[:-1]:\n if not cmp in cur.keys():\n cur[cmp] = {}\n cur = cur[cmp]\n cur[pieces[-1]] = v\n return rv\n\n# from smap.util\ndef dict_merge(o1, o2):\n \"\"\"Recursively merge dict o1 into dict o2.\n \"\"\"\n if not isinstance(o1, dict) or not isinstance(o2, dict):\n return o2\n o2 = dict(o2)\n for k, v in o1.items():\n if k in o2:\n o2[k] = dict_merge(v, o2[k])\n else:\n o2[k] = v\n return o2\n\n","repo_name":"gtfierro/XBOSDriver","sub_path":"python3/XBOSDriver/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30112057010","text":"# 示例5-26\nfrom operator import mul\nfrom functools import partial\ndef main():\n triple = partial(mul, 3) #(1)\n _obj = triple(7) #(2)\n print(_obj)\n _obj = list(map(triple, range(1, 10))) #(3)\n print(_obj)\nif __name__ == '__main__':\n main()","repo_name":"juedui0769/python2019","sub_path":"python3Study/fluentpython/ch05/demo05_26_partial.py","file_name":"demo05_26_partial.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19301928789","text":"import asyncio\nimport json\nimport time\n\nimport nextcord\nimport requests\nfrom config import *\nfrom multiprocessing.pool import ThreadPool as Pool\nfrom nextcord import ButtonStyle\nfrom nextcord.ui import Button, View\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/102.0.5005.61 Safari/537.36 '\n}\n\naccounts = ACCOUNTS\npool_size = 5\nprevious_hash = None\ncurrent_time = time.time() - time_to_track\nmessages = []\n\nclient = nextcord.Client()\nchannel = None\n\n\n@client.event\nasync def on_ready():\n print(f'Logged in as {client.user}')\n global channel\n channel = client.get_channel(CHANNEL_ID)\n client.loop.create_task(send_message())\n\n\n# Get the latest Block\nasync def get_block():\n while True:\n url = \"https://public-api.solscan.io/block/last?limit=1\"\n resp = requests.get(url, headers=headers)\n resp = json.loads(resp.text)\n global previous_hash\n print(resp)\n try:\n previous_hash = resp[0][\"result\"][\"blockTime\"]\n time_delta = time.time() - previous_hash\n print(time.time(), previous_hash, time_delta)\n return time_delta\n except:\n print(\"getting block time 1\")\n await asyncio.sleep(1)\n\n\ndef get_image(trx):\n url = f\"https://api-mainnet.magiceden.dev/v2/tokens/{trx}\"\n resp = requests.get(url, headers=headers)\n resp = json.loads(resp.text)\n image_url = resp['image']\n collection = resp['collection'].upper().replace(\"_\", \" \")\n return image_url, collection\n\n\ndef get_price(trx):\n url = f\"https://api-mainnet.magiceden.dev/v2/tokens/{trx}/activities?offset=0&limit=1\"\n resp = requests.get(url, headers=headers)\n resp = json.loads(resp.text)\n try:\n print(resp)\n if resp[0]['type'] != 'buyNow':\n return False\n price = resp[0]['price']\n price = str(price)\n token = \" SOL\"\n return price + token\n\n except:\n return False\n\n\nasync def send_message():\n await asyncio.sleep(5)\n await client.wait_until_ready()\n print(\"started\")\n while True:\n global messages, channel\n await get_transactions()\n\n if len(messages) > 0:\n\n print(messages)\n for message in messages:\n print(messages)\n print(\"messaging start 1\")\n b1 = Button(label=\"View Transaction\", style=ButtonStyle.blurple, url=f\"https://solscan.io/tx/{message[1]}\")\n b2 = Button(label=\"View Token\", style=ButtonStyle.blurple, url=f\"https://solscan.io/token/{message[2]}\")\n myView = View(timeout=10)\n myView.add_item(b1)\n myView.add_item(b2)\n await channel.send(embed=message[0], view=myView)\n messages = []\n\n\ndef scrape_and_message(data, name):\n print(\"scraping start 1\")\n for trx in data:\n\n # if it isn't a transfer skip\n\n if trx[\"postBalance\"] == trx[\"preBalance\"]:\n continue\n\n # Checking whether it's a coin or NFT\n\n if \"symbol\" in trx:\n if trx[\"changeType\"] == \"inc\":\n\n message = nextcord.Embed(title=f\"**{name}**\", description=\"BOUGHT\", color=0x00aa88)\n message.add_field(name=f\"Token Name\", value=trx['symbol'], inline=True)\n message.add_field(name=f\"Wallet address\", value=trx['owner'], inline=True)\n # message = f\"{name} (wallet {trx['owner']}) has just purchased {trx['symbol']}.\"\n\n else:\n message = nextcord.Embed(title=f\"**{name}**\", description=\"SOLD\", color=0x00F10909)\n message.add_field(name=f\"Token Name\", value=trx['symbol'], inline=True)\n message.add_field(name=f\"Wallet address\", value=trx['owner'], inline=True)\n # message = f\"{name} (wallet {trx['owner']}) has just sold {trx['symbol']}.\"\n\n # When it's an NFT another API call to retrieve the NFT name\n\n else:\n url = f\"https://public-api.solscan.io/token/meta?tokenAddress={trx['tokenAddress']}\"\n\n resp = requests.get(url, headers=headers)\n resp = json.loads(resp.text)\n nft_name = resp[\"name\"]\n nft_symbol = resp[\"symbol\"]\n image_url, collection = get_image(trx['tokenAddress'])\n price = get_price(trx['tokenAddress'])\n if not price:\n print(\"The transaction involved transfer of assets between wallets of the same User.\")\n continue\n\n if trx[\"changeType\"] == \"inc\":\n # message = f\"{name} (wallet {trx['owner']}) has just purchased {nft_name}({nft_symbol}).\"\n message = nextcord.Embed(title=f\"**{name}**\", color=0x00aa88)\n message.add_field(name=f\"Bought Price:\", value=price, inline=False)\n message.add_field(name=f\"Project Name\", value=collection, inline=True)\n message.add_field(name=f\"Wallet address\", value=trx['owner'], inline=True)\n message.set_image(url=image_url)\n else:\n message = nextcord.Embed(title=f\"**{name}**\", color=0x00F10909)\n message.add_field(name=f\"Sold Price:\", value=price, inline=False)\n message.add_field(name=f\"Project Name\", value=collection, inline=True)\n message.add_field(name=f\"Wallet address\", value=trx['owner'], inline=True)\n message.set_image(url=image_url)\n # message = f\"{name} (wallet {trx['owner']}) has just sold {nft_name}({nft_symbol}).\"\n global messages, channel\n messages.append([message, trx['signature'][0], trx['tokenAddress']])\n print(\"end\")\n\n\nasync def get_transactions():\n global current_time\n\n # while True:\n\n if current_time < (time.time() - time_to_track):\n print(time.time())\n pool = Pool(pool_size)\n time_gap = await get_block()\n previous_time = int((time.time() - time_to_track - time_gap) // 1)\n current_time = int((time.time()) // 1)\n now_time = int((time.time() - time_gap) // 1)\n for account in accounts:\n pool.apply_async(get_data, (account, previous_time, now_time))\n pool.close()\n pool.join()\n print(time.time())\n\n\ndef get_data(account, previous_time, current_time):\n # url = f'https://public-api.solscan.io/account/transactions?account={accounts[account]}'\n url = f\"https://public-api.solscan.io/account/splTransfers?account={accounts[account]}&fromTime={previous_time}&toTime={current_time}&offset=0&limit=50\"\n resp = requests.get(url, headers=headers)\n try:\n resp = json.loads(resp.text)\n print(resp)\n transactions = resp[\"data\"]\n if len(transactions) == 0:\n print(\"No transactions at this moment from : \", account)\n\n return\n print(account, transactions)\n\n scrape_and_message(transactions, account)\n except:\n print(resp)\n\n\n# client.loop.create_task(send_message())\n\nclient.run(BOT_TOKEN)\n","repo_name":"LagLord/Solana-Wallet-Tracker-Crypto-NFT-sales-Discord-Bot","sub_path":"solscanThread.py","file_name":"solscanThread.py","file_ext":"py","file_size_in_byte":7076,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"3"}
+{"seq_id":"29043104817","text":"# -*- coding: utf-8 -*-\nimport json\nimport os\nimport pytest\nimport yatest.common\n\n\ndef encode_str(data):\n return data.encode('hex')\n\n\ndef decode_str(data):\n return data.decode('hex')\n\n\nDATA_DIR = os.path.abspath(yatest.common.source_path('balancer/test/hpack/data'))\nDECODER_DATA_DIR = DATA_DIR + '/decoder/'\nENCODER_DATA_DIR = DATA_DIR + '/encoder/'\n\n\ndef get_binary(name):\n return yatest.common.binary_path('balancer/kernel/http2/server/hpack/tests/{name}/{name}'.format(name=name))\n\n\ndef build_params(data_dir):\n return [name[:-3] for name in os.listdir(data_dir) if name.endswith('.in')]\n\n\ndef read_json(path):\n with open(path) as f:\n return json.load(f)\n\n\ndef __encode_headers(headers):\n from balancer.test.util.proto.http2.message import HeaderField as HF\n result = list()\n for field in headers:\n if isinstance(field, HF):\n name = field.name\n value = field.value\n indexing = field.indexing\n else:\n name, value = field\n indexing = None\n name = encode_str(name)\n value = encode_str(value)\n if indexing is not None:\n result.append({'name': name, 'value': value, 'indexing': indexing})\n else:\n result.append({'name': name, 'value': value})\n return result\n\n\ndef __util_decoder(test_input, test_output):\n import balancer.test.util.proto.http2.hpack._hpack as hpack\n data = read_json(test_input)\n decoder = hpack.Decoder()\n result = list()\n for block in data:\n try:\n headers = decoder.decode(decode_str(block))\n result.append({\n 'headers': __encode_headers(headers),\n 'table': __encode_headers(decoder.table.dynamic_items()),\n })\n except hpack.DecoderError:\n result = ['COMPRESSION_ERROR']\n break\n with open(test_output, 'w') as f:\n json.dump(result, f)\n\n\ndef balancer_decoder(test_input, test_output):\n err_path = yatest.common.output_path('decoder.err')\n with open(test_input) as f_in:\n with open(test_output, 'w') as f_out:\n with open(err_path, 'w') as f_err:\n yatest.common.execute([get_binary('hpack_decoder_test')],\n check_exit_code=False, stdin=f_in, stdout=f_out, stderr=f_err)\n\n\ndef run_decoder(test_input, test_output):\n # __util_decoder(test_input, test_output)\n balancer_decoder(test_input, test_output)\n\n\ndef decode_headers(headers):\n if headers is None:\n return []\n result = list()\n for field in headers:\n name = decode_str(field['name'])\n value = decode_str(field['value'])\n if 'indexing' in field:\n result.append({'name': name, 'value': value, 'indexing': field['indexing']})\n else:\n result.append({'name': name, 'value': value})\n return result\n\n\ndef decode_result(data): # for readability\n result = list()\n for item in data:\n if item in ('COMPRESSION_ERROR', 'PROTOCOL_ERROR'):\n result.append(item)\n break\n else:\n result.append({\n 'headers': decode_headers(item['headers']),\n 'table': decode_headers(item['table']),\n })\n return result\n\n\n@pytest.mark.parametrize('name', build_params(DECODER_DATA_DIR))\ndef test_decoder(name):\n test_input = DECODER_DATA_DIR + name + '.in'\n test_output = yatest.common.output_path(name + '.out.test')\n run_decoder(test_input, test_output)\n result = decode_result(read_json(test_output))\n expected = decode_result(read_json(DECODER_DATA_DIR + name + '.out'))\n assert result == expected\n\n\ndef __util_encoder(test_input, test_output):\n import balancer.test.util.proto.http2.hpack._hpack as hpack\n from balancer.test.util.proto.http2.message import HeaderField as HF\n from balancer.test.util.proto.http2.message import HName, HValue\n\n def get_value(h_descr):\n return HValue(decode_str(h['value']))\n\n encoder = hpack.Encoder(greedy_huffman=True)\n result = list()\n for data in read_json(test_input):\n block = list()\n sizes = list()\n for h in data:\n h_type = h['type']\n if h_type == 'size_update':\n sizes.append(h['value'])\n elif h_type == 'indexed_field':\n block.append(HF(h['field_id']))\n elif h_type == 'indexed_name':\n block.append(HF(h['name_id'], get_value(h), indexing=h['indexing']))\n else:\n block.append(HF(HName(decode_str(h['name'])),\n get_value(h), indexing=h['indexing']))\n if len(sizes) > 0:\n min_size = min(sizes)\n last_size = sizes[-1]\n encoder.update_size(min_size)\n if min_size != last_size:\n encoder.update_size(last_size)\n result.append(encode_str(encoder.encode(block)))\n with open(test_output, 'w') as f:\n json.dump(result, f)\n\n\ndef balancer_encoder(test_input, test_output):\n with open(test_input) as f_in:\n with open(test_output, 'w') as f_out:\n yatest.common.execute([get_binary('hpack_encoder_test')], stdin=f_in, stdout=f_out)\n\n\ndef run_encoder(test_input, test_output):\n # __util_encoder(test_input, test_output)\n balancer_encoder(test_input, test_output)\n\n\n@pytest.mark.parametrize('name', build_params(ENCODER_DATA_DIR))\ndef test_encoder(name):\n test_input = ENCODER_DATA_DIR + name + '.in'\n test_output = yatest.common.output_path(name + '.out.test')\n run_encoder(test_input, test_output)\n result = read_json(test_output)\n expected = read_json(ENCODER_DATA_DIR + name + '.out')\n assert result == expected\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"balancer/test/hpack/test_hpack.py","file_name":"test_hpack.py","file_ext":"py","file_size_in_byte":5750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21782983203","text":"import cv2\nimport numpy as np\n\n\ndef create_network(model, config, gpu=False):\n net = cv2.dnn.readNetFromDarknet(config, model)\n if gpu:\n net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n return net\n\n\ndef detect(net, image):\n layers = net.getLayerNames()\n layers = [layers[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (608, 608), swapRB=True, crop=False)\n net.setInput(blob)\n return net.forward(layers)\n\n\ndef filter(image, detections, threshold=0.3):\n boxes = list()\n confidences = list()\n class_ids = list()\n (H, W) = image.shape[:2]\n output_layers = detections\n\n for output in output_layers:\n\n for detection in output:\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n\n if confidence > threshold:\n box = detection[0:4] * np.array([W, H, W, H])\n (centerX, centerY, width, height) = box.astype(\"int\")\n x = int(centerX - (width / 2))\n y = int(centerY - (height / 2))\n boxes.append([x, y, int(width), int(height)])\n confidences.append(float(confidence))\n class_ids.append(class_id)\n\n return [boxes, confidences, class_ids]\n\n\ndef apply_nms(image, filtered_detections, conf, thresh):\n boxes, confidences, ids = filtered_detections\n idxs = cv2.dnn.NMSBoxes(boxes, confidences, conf, thresh)\n bboxes = list()\n\n if len(idxs) > 0:\n for i in idxs.flatten():\n (x, y) = (boxes[i][0], boxes[i][1])\n (w, h) = (boxes[i][2], boxes[i][3])\n bboxes.append([x, y, w, h])\n\n cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\n text = \"{}: {:.4f}\".format(\"Meteor\", confidences[i])\n cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n\n return True, image\n return False, image\n","repo_name":"BrunoSilva98/MeteorFinder","sub_path":"yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1753627706","text":"# =============================================================================\n# codePost – Blackboard Utility\n#\n# Takes submissions downloaded from Blackboard and transforms the file\n# structure into a structure that codePost will recognize.\n#\n# =============================================================================\n\n# Python stdlib imports\nimport os\nimport argparse\nimport csv\nimport shutil\nimport re\n\n# =============================================================================\n\nparser = argparse.ArgumentParser(description='Blackboard to codePost!')\nparser.add_argument(\n 'submissions', help='The directory of submissions downloaded from Blackboard')\nparser.add_argument(\n 'roster', help='The course roster of students that includes first name, last name, and email')\nparser.add_argument('-s', '--simulate', action='store_true')\nargs = parser.parse_args()\n\n# =============================================================================\n# Constants\n\nOUTPUT_DIRECTORY = 'codepost_upload'\nERROR_DIRECTORY = 'errors'\n\n_cwd = os.getcwd()\n_upload_dir = os.path.join(_cwd, OUTPUT_DIRECTORY)\n_error_dir = os.path.join(_cwd, ERROR_DIRECTORY)\n\n# =============================================================================\n# Helpers\n\n\ndef normalize(string):\n return string.lower().strip()\n\n\ndef delete_directory(path):\n if os.path.exists(path):\n shutil.rmtree(path)\n\n\ndef validate_csv(row):\n for key in row.keys():\n if 'blackboard' in normalize(key):\n blackboard_id = key\n elif 'email' in normalize(key):\n email = key\n\n if blackboard_id == None or email == None:\n if blackboard_id == None:\n print(\"Missing header: blackboard_id\")\n if email == None:\n print(\"Missing header: email\")\n\n raise RuntimeError(\n \"Malformatted roster. Please fix the headers and try again.\")\n\n return (blackboard_id, email)\n else:\n return (blackboard_id, email)\n\n\ndef blackboard_id_to_email(roster):\n with open(roster, mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n blackboard_id, email = (None, None)\n blackboard_id_to_email = {}\n for row in csv_reader:\n if line_count == 0:\n (blackboard_id, email) = validate_csv(row)\n line_count += 1\n\n # Blackboard convention: map {blackboard_id} to {codePost email}\n blackboard_id_to_email[\n normalize(row[blackboard_id])] = normalize(row[email])\n line_count += 1\n return blackboard_id_to_email\n\n\ndef check_for_partners(file_name):\n filepath = os.path.join(args.submissions, file_name)\n emails = [line.rstrip('\\n') for line in open(filepath, 'r')]\n EMAIL_REGEX = r\"[^@]+@[^@]+\\.[^@]+\"\n filtered_emails = [x for x in emails if re.match(EMAIL_REGEX, x)]\n\n return filtered_emails\n\n# =============================================================================\n\nif (args.simulate):\n print('\\n~~~~~~~~~~~ START SIMULATION ~~~~~~~~~~~')\n\nprint('\\nSetting up directories...')\n\n# Overwrite the directories if they exist already\nif not args.simulate:\n delete_directory(_upload_dir)\n delete_directory(_error_dir)\n\n os.makedirs(_upload_dir)\n os.makedirs(_error_dir)\n\nprint('\\t/{}'.format(OUTPUT_DIRECTORY))\nprint('\\t/{}'.format(ERROR_DIRECTORY))\n\nprint('\\nReading and validating roster...')\nblackboard_id_to_email = blackboard_id_to_email(args.roster)\nprint('\\tVALID')\n\nprint('\\nChecking submissions for partners...')\n\nfiles = os.listdir(args.submissions)\nfolders = []\nfor file in files:\n file_name = file.split('_')[-1]\n if 'partners' in file_name:\n partners = check_for_partners(file)\n folders.append(partners)\n\nprint('\\t{}'.format(folders))\n\nprint('\\nCreating student folders...')\nfor student in blackboard_id_to_email:\n found = False\n for folder in folders:\n if blackboard_id_to_email[student] in folder:\n found = True\n break\n\n if not found:\n folders.append([blackboard_id_to_email[student]])\n\nfor folder in folders:\n folder_name = \",\".join(folder)\n if not args.simulate:\n os.makedirs(os.path.join(_upload_dir, folder_name))\n print('\\t{}'.format(folder_name))\n\n\nprint('\\nMapping and copying files...')\nfor file in files:\n blackboard_id = file.split('_')[1]\n file_name = file.split('_')[-1]\n\n if normalize(blackboard_id) in blackboard_id_to_email:\n email = blackboard_id_to_email[blackboard_id]\n found = False\n\n for folder in folders:\n if email in folder:\n folder_name = \",\".join(folder)\n found = True\n if not args.simulate:\n shutil.copyfile(os.path.join(args.submissions, file), os.path.join(\n os.path.join(_upload_dir, folder_name), file_name))\n print('\\t{}'.format(os.path.join(\n os.path.join(_upload_dir, folder_name), file_name)))\n\n if not found:\n if not args.simulate:\n shutil.copyfile(os.path.join(args.submissions, file),\n os.path.join(_error_dir, file))\n print('\\tERROR: {}'.format(os.path.join(_error_dir, file)))\n else:\n if not args.simulate:\n shutil.copyfile(os.path.join(args.submissions, file),\n os.path.join(_error_dir, file))\n print('\\tERROR: {}'.format(os.path.join(_error_dir, file)))\n\nif args.simulate:\n print('\\n~~~~~~~~~~~ END SIMULATION ~~~~~~~~~~~\\n')\n","repo_name":"codepost-io/integration-blackboard","sub_path":"blackboard_to_codepost_manual.py","file_name":"blackboard_to_codepost_manual.py","file_ext":"py","file_size_in_byte":5244,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"9405394579","text":"from django import template\n\nregister = template.Library()\n\n\n@register.filter\ndef addclass(field, css):\n return field.as_widget(attrs={\"class\": css})\n\n\n@register.filter\ndef uglify(value) -> str:\n result = []\n for i in range(len(value)):\n if i % 2 == 1:\n result.append(value[i].upper())\n else:\n result.append(value[i].lower())\n return(''.join(result))\n","repo_name":"JCoffeeYP/YaTube_social_network","sub_path":"users/templatetags/user_filters.py","file_name":"user_filters.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7368513296","text":"import random\r\nimport time\r\n\r\n\r\nfila = ['Matheus', 'Joao', 'Marcos', 'Paulo',\r\n 'Lucas', 'Mario', 'Rodrigo', 'Maria', 'Marilia', 'Joana', 'Perla']\r\natendente1 = []\r\natendente2 = []\r\natendente3 = []\r\natendente4 = []\r\nhoraAtendente1 = []\r\natendente1atendimentos = []\r\nhoraAtendente2 = []\r\natendente2atendimentos = []\r\nhoraAtendente3 = []\r\natendente3atendimentos = []\r\nhoraAtendente4 = []\r\natendente4atendimentos = []\r\n\r\nwhile True:\r\n print('-='*20)\r\n print('Sistema de ligações')\r\n print('-='*20)\r\n dash = int(input(\r\n 'Utilize o menu abaixo\\n[1] Iniciar programa\\n[2] Ver informacoes atendentes \\n[3] Adicionar pessoas na fila \\n[4] Ver fila\\n[0] Sair \\n'))\r\n if dash == 1:\r\n for i in range(4):\r\n if len(fila) != 0:\r\n True\r\n if len(atendente1) == 0:\r\n pegarFila = fila.pop(0)\r\n atendente1.append(pegarFila)\r\n elif len(atendente2) == 0:\r\n pegarFila = fila.pop(0)\r\n atendente2.append(pegarFila)\r\n elif len(atendente3) == 0:\r\n pegarFila = fila.pop(0)\r\n atendente3.append(pegarFila)\r\n elif len(atendente4) == 0:\r\n pegarFila = fila.pop(0)\r\n atendente4.append(pegarFila)\r\n else:\r\n print('Fila vazia')\r\n\r\n while True:\r\n if len(atendente1) >= 1:\r\n if len(fila) != 0:\r\n pegarFila = fila.pop(0)\r\n atendente1.append(pegarFila)\r\n print(f'Clientes na fila: {atendente1}')\r\n print(f'Atendendo atualmente {atendente1[0]}')\r\n print(f'finalizando...')\r\n time.sleep(1)\r\n tempo1 = random.randrange(3, 15)\r\n print(\r\n f'o tempo de atendimento de {atendente1[0]} foi {tempo1} min')\r\n horaAtendente1.append(tempo1)\r\n tirarCliente = atendente1.pop(0)\r\n atendente1atendimentos.append(tirarCliente)\r\n print(\r\n f'removendo da filae e chamando o próximo: {atendente1[0]}')\r\n time.sleep(1)\r\n else:\r\n print('Fila vazia')\r\n if len(atendente2) >= 1:\r\n if len(fila) != 0:\r\n pegarFila = fila.pop(0)\r\n atendente2.append(pegarFila)\r\n print(f'Clientes na fila: {atendente2}')\r\n print(f'Atendendo atualmente {atendente2[0]}')\r\n print(f'finalizando...')\r\n time.sleep(1)\r\n tempo2 = random.randrange(3, 15)\r\n print(\r\n f'o tempo de atendimento de {atendente2[0]} foi {tempo2} min')\r\n horaAtendente2.append(tempo2)\r\n tirarCliente = atendente2.pop(0)\r\n atendente2atendimentos.append(tirarCliente)\r\n print(\r\n f'removendo da fila e chamando o próximo: {atendente2[0]}')\r\n time.sleep(1)\r\n else:\r\n print('Fila vazia')\r\n if len(atendente3) >= 1:\r\n if len(fila) != 0:\r\n pegarFila = fila.pop(0)\r\n atendente3.append(pegarFila)\r\n print(f'Clientes na fila: {atendente3}')\r\n print(f'Atendendo atualmente {atendente3[0]}')\r\n print(f'finalizando...')\r\n time.sleep(1)\r\n tempo3 = random.randrange(3, 15)\r\n print(\r\n f'o tempo de atendimento de {atendente3[0]} foi {tempo3} min')\r\n horaAtendente3.append(tempo3)\r\n tirarCliente = atendente3.pop(0)\r\n atendente3atendimentos.append(tirarCliente)\r\n print(\r\n f'removendo da fila e chamando o próximo: {atendente3[0]}')\r\n time.sleep(1)\r\n else:\r\n print('Fila vazia')\r\n if len(atendente4) >= 1:\r\n if len(fila) != 0:\r\n pegarFila = fila.pop(0)\r\n atendente4.append(pegarFila)\r\n print(f'Clientes na fila: {atendente4}')\r\n print(f'Atendendo atualmente {atendente4[0]}')\r\n print(f'finalizando...')\r\n time.sleep(1)\r\n tempo4 = random.randrange(3, 15)\r\n print(\r\n f'o tempo de atendimento de {atendente4[0]} foi {tempo4} min')\r\n horaAtendente4.append(tempo4)\r\n tirarCliente = atendente4.pop(0)\r\n atendente4atendimentos.append(tirarCliente)\r\n print(\r\n f'removendo da fila e chamando o próximo: {atendente4[0]}')\r\n time.sleep(1)\r\n else:\r\n print('Fila vazia')\r\n if len(fila) == 0:\r\n break\r\n if dash == 2:\r\n calchorasAtendente1 = sum(horaAtendente1)\r\n calchorasAtendente2 = sum(horaAtendente2)\r\n calchorasAtendente3 = sum(horaAtendente1)\r\n calchorasAtendente4 = sum(horaAtendente2)\r\n print('-='*20)\r\n print('Dashboard de resultados')\r\n print('-='*20)\r\n print(\"\")\r\n print('-='*20)\r\n print(\r\n f'O atendente 1 atendeu o total de {len(atendente1atendimentos)} pessoas')\r\n print(\r\n f'A media de minutos em atendimento do atendente 1 é {calchorasAtendente1/3:.2f} minutos')\r\n print('-='*20)\r\n print(\r\n f'O atendente 2 atendeu o total de {len(atendente2atendimentos)} pessoas')\r\n print(\r\n f'A media de minutos em atendimento do atendente 2 é {calchorasAtendente2/3:.2f} minutos')\r\n print('-='*20)\r\n print(\r\n f'O atendente 3 atendeu o total de {len(atendente3atendimentos)} pessoas')\r\n print(\r\n f'A media de minutos em atendimento do atendente 3 é {calchorasAtendente3/3:.2f} minutos')\r\n print('-='*20)\r\n print(\r\n f'O atendente 4 atendeu o total de {len(atendente4atendimentos)} pessoa')\r\n print(\r\n f'A media de minutos em atendimento do atendente 4 é {calchorasAtendente4/3:.2f} minutos')\r\n if dash == 3:\r\n nome = input('Digite o nome: ')\r\n fila.append(nome)\r\n if dash == 4:\r\n print(fila)\r\n if dash == 0:\r\n print('Finalizando')\r\n break\r\n","repo_name":"fdacmatheus/desafioUNDB","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6726,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72733292880","text":"#-*- coding:utf-8 -*-\n\nfrom openerp import models, fields, api\nfrom urllib import urlencode\nfrom urlparse import urljoin\nfrom datetime import datetime, time, timedelta\nfrom openerp.exceptions import UserError\n\nclass Holidays(models.Model):\n _name = \"hr.holidays\"\n _inherit = \"hr.holidays\"\n\n\n def _default_approver(self):\n employee = self.env['hr.employee'].browse(self._employee_get())\n if employee.holidays_approvers:\n return employee.holidays_approvers[0].approver.id\n\n # In case of ERROR , during installation, just remove the default=_default_approver, then install again.\n # then after installation, put (default=_default_approver it back on the following code and reinstall again.\n pending_approver = fields.Many2one('hr.employee', string=\"Pending Approver\", readonly=True, default=_default_approver)\n pending_approver_user = fields.Many2one('res.users', string='Pending approver user', related='pending_approver.user_id', related_sudo=True, store=True, readonly=True)\n current_user_is_approver = fields.Boolean(string= 'Current user is approver', compute='_compute_current_user_is_approver')\n approbations = fields.One2many('hr.employee.holidays.approbation', 'holidays', string='Approvals', readonly=True)\n pending_transfered_approver_user = fields.Many2one('res.users', string='Pending transfered approver user', compute=\"_compute_pending_transfered_approver_user\", search='_search_pending_transfered_approver_user')\n\n @api.multi\n def holidays_refuse(self):\n return {\n 'name': 'Confirm Leave Request Disapproval',\n 'view_mode': 'form',\n 'view_type': 'form',\n 'res_model': 'leave.request.disapprove.wizard',\n 'type': 'ir.actions.act_window',\n 'target': 'new'\n }\n\n \n @api.multi\n def holidays_confirm(self):\n res = super(Holidays, self).holidays_confirm()\n approver = False\n requester = self.employee_id.user_id\n for holiday in self:\n if self.type == 'add':\n hr_officer_approver = self.env.user.company_id.leave_allocation_approver_id\n if not hr_officer_approver:\n raise UserError('Please contact the IT administrator to set the default Human Resources Leave Allocation Approver in the company settings ')\n if not hr_officer_approver.user_id :\n raise UserError('Human Resources Leave Allocation Approver is not related to any user in the system')\n holiday.pending_approver = approver = hr_officer_approver\n elif holiday.employee_id.holidays_approvers :\n holiday.pending_approver = approver = holiday.employee_id.holidays_approvers[0].approver\n\n if requester and approver:\n self.send_email(requester, approver,final_approval=False)\n return res\n\n\n def _get_final_url(self, module_name, menu_id, action_id, context=None):\n fragment = {}\n res = {}\n model_data = self.env['ir.model.data']\n base_url = self.env['ir.config_parameter'].get_param('web.base.url')\n fragment['menu_id'] = model_data.get_object_reference(module_name, menu_id)[1]\n fragment['model'] = 'hr.holidays'\n fragment['view_type'] = 'form'\n fragment['action'] = model_data.get_object_reference(module_name, action_id)[1]\n query = {'db': self.env.cr.dbname}\n # for displaying tree view. Remove if you want to display form view\n # fragment['page'] = '0'\n # fragment['limit'] = '80'\n # res = urljoin(base_url, \"?%s#%s\" % (urlencode(query), urlencode(fragment)))\n\n\n # For displaying a single record. Remove if you want to display tree view\n fragment['id'] = context.get(\"holiday_id\")\n res = urljoin(base_url, \"?%s#%s\" % (urlencode(query), urlencode(fragment)))\n return res\n\n def _get_url(self, module_name, menu_id, action_id, context=None):\n fragment = {}\n res = {}\n model_data = self.env['ir.model.data']\n base_url = self.env['ir.config_parameter'].get_param('web.base.url')\n fragment['menu_id'] = model_data.get_object_reference(module_name, menu_id)[1]\n fragment['model'] = 'hr.holidays'\n fragment['view_type'] = 'form'\n fragment['action'] = model_data.get_object_reference('hr_holidays_multi_levels_approval', action_id)[1]\n query = {'db': self.env.cr.dbname}\n # for displaying tree view. Remove if you want to display form view\n # fragment['page'] = '0'\n # fragment['limit'] = '80'\n # res = urljoin(base_url, \"?%s#%s\" % (urlencode(query), urlencode(fragment)))\n\n\n # For displaying a single record. Remove if you want to display tree view\n fragment['id'] = context.get(\"holiday_id\")\n res = urljoin(base_url, \"?%s#%s\" % (urlencode(query), urlencode(fragment)))\n return res\n\n\n def send_email(self,requester,approver,final_approval=False):\n\n company_email = self.env.user.company_id.email and self.env.user.company_id.email.strip() or False\n requester_email = requester.email and requester.email or False\n approver_email = approver.user_id and approver.user_id.email or False\n if requester_email and approver_email and company_email and not final_approval:\n # Custom Email Template\n mail_template = self.env.ref('hr_holidays_multi_levels_approval.mail_templ_leave_approval')\n ctx = {}\n ctx.update({'holiday_id': self.id})\n the_url = self._get_url('hr_holidays', 'menu_open_department_leave_approve', 'open_holidays_approve', ctx)\n ctx = {'system_email': company_email,\n 'requester_email': requester_email,\n 'approver_email' : approver_email,\n 'requester_name': self.employee_id.name,\n 'approver_name': approver.name,\n 'url': the_url,\n }\n mail_template.with_context(ctx).send_mail(self.id, force_send=False)\n elif requester_email and approver_email and company_email and final_approval and self.date_from and self.date_to:\n mail_template = self.env.ref('hr_holidays_multi_levels_approval.mail_templ_leave_final_approval')\n ctx = {}\n ctx.update({'holiday_id': self.id})\n the_url = self._get_final_url('hr_holidays', 'menu_hr_holidays_my_leaves', 'open_ask_holidays', ctx)\n ctx = {'system_email': company_email,\n 'requester_email': requester_email,\n 'approver_email': approver_email,\n 'requester_name': self.employee_id.name,\n 'approver_name': approver.name,\n 'url': the_url,\n 'date_from' : datetime.strptime(self.date_from,'%Y-%m-%d %H:%M:%S').strftime('%d-%m-%Y %H:%M:%S'),\n 'date_to' : datetime.strptime(self.date_to,'%Y-%m-%d %H:%M:%S').strftime('%d-%m-%Y %H:%M:%S')\n }\n mail_template.with_context(ctx).send_mail(self.id, force_send=False)\n\n\n @api.multi\n def action_approve(self):\n for holiday in self:\n\n is_last_approbation = False\n sequence = 0\n next_approver = None\n for approver in holiday.employee_id.holidays_approvers:\n sequence = sequence + 1\n if holiday.pending_approver.id == approver.approver.id:\n if sequence == len(holiday.employee_id.holidays_approvers):\n is_last_approbation = True\n next_approver = approver.approver\n else:\n next_approver = holiday.employee_id.holidays_approvers[sequence].approver\n\n if is_last_approbation or self.type == 'add':\n holiday.action_validate()\n else:\n holiday.write({'state': 'confirm', 'pending_approver': next_approver.id})\n self.env['hr.employee.holidays.approbation'].create({'holidays': holiday.id, 'approver': self.env.uid, 'sequence': sequence, 'date': fields.Datetime.now()})\n\n requester = self.employee_id.user_id\n approver = next_approver and next_approver.user_id\n if requester and approver and not is_last_approbation :\n self.send_email(requester, approver,final_approval=False)\n elif requester and approver and is_last_approbation :\n self.send_email(requester, approver,final_approval=True)\n return\n\n @api.multi\n def action_disapprove(self, msg):\n super(Holidays, self).holidays_refuse()\n reason_for_dispproval = msg\n\n # Send Email\n company_email = self.env.user.company_id.email.strip()\n approver_email = self.env.user.partner_id.email.strip()\n\n if self.type == 'add':\n requester_email = False\n else:\n requester_email = self.employee_id.user_id.email.strip()\n\n\n if company_email and approver_email and not self.type == 'add':\n # Custom Email Template\n mail_template = self.env.ref('hr_holidays_multi_levels_approval.mail_templ_leave_disapproval')\n ctx = {}\n ctx.update({'holiday_id': self.id})\n the_url = self._get_final_url('hr_holidays', 'menu_hr_holidays_my_leaves', 'open_ask_holidays', ctx)\n ctx = {'system_email': company_email,\n 'requester_email': requester_email,\n 'approver_email': approver_email,\n 'requester_name': self.employee_id.name,\n 'approver_name': self.env.user.name,\n 'url': the_url,\n 'reason_for_dispproval': reason_for_dispproval,\n 'date_from': datetime.strptime(self.date_from, '%Y-%m-%d %H:%M:%S').strftime('%d-%m-%Y %H:%M:%S'),\n 'date_to': datetime.strptime(self.date_to, '%Y-%m-%d %H:%M:%S').strftime('%d-%m-%Y %H:%M:%S')\n }\n mail_template.with_context(ctx).send_mail(self.id, force_send=False)\n else:\n self.message_post('Leave Allocation Rejection Reason: %s.' % (reason_for_dispproval),\n subject='Leave Allocation Rejection Reason',\n subtype='mail.mt_comment')\n return\n\n @api.multi\n def action_validate(self):\n self.write({'pending_approver': None})\n for holiday in self:\n self.env['hr.employee.holidays.approbation'].create({'holidays': holiday.id, 'approver': self.env.uid, 'date': fields.Datetime.now()})\n super(Holidays, self).holidays_validate()\n\n \n @api.one\n def _compute_current_user_is_approver(self):\n if self.pending_approver.user_id.id == self.env.user.id or self.pending_approver.transfer_holidays_approvals_to_user.id == self.env.user.id :\n self.current_user_is_approver = True\n else:\n self.current_user_is_approver = False\n \n @api.onchange('employee_id')\n def _onchange_employee(self):\n if self.employee_id and self.employee_id.holidays_approvers:\n self.pending_approver = self.employee_id.holidays_approvers[0].approver.id\n else:\n self.pending_approver = False\n \n @api.one\n def _compute_pending_transfered_approver_user(self):\n self.pending_transfered_approver_user = self.pending_approver.transfer_holidays_approvals_to_user\n \n def _search_pending_transfered_approver_user(self, operator, value):\n replaced_employees = self.env['hr.employee'].search([('transfer_holidays_approvals_to_user', operator, value)])\n employees_ids = []\n for employee in replaced_employees:\n employees_ids.append(employee.id)\n return [('pending_approver', 'in', employees_ids)]\n\n\n\n\n\n\nclass ResCompanyExtend(models.Model):\n _inherit = \"res.company\"\n\n leave_allocation_approver_id = fields.Many2one('hr.employee',string='Human Resources Leave Allocation Approver', help=\"The hr officer who approves leave allocations\")\n\n ","repo_name":"kingsleyuk2003/ODEX","sub_path":"addons/hr_holidays_multi_levels_approval/models/holidays.py","file_name":"holidays.py","file_ext":"py","file_size_in_byte":12214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35918793160","text":"#!/usr/bin/env python\n\nimport os\nimport pandas as pd\nfrom sklearn.metrics import jaccard_score, pairwise_distances\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport argparse\nimport datetime\nimport scipy.cluster.hierarchy as shc\nimport scipy.spatial.distance as ssd #pdist\nimport PyQt5\nfrom PyQt5 import QtGui\nimport ete3\nfrom ete3 import Tree, TreeStyle\n\nfrom misc import check_file_exists, import_to_pandas\n\n\"\"\"\nTODO: confirm 'average' method as the best option\n confirm euclidean 'metric' as the most appropiate for SNP distance (hamming used so far)\n\"\"\"\n\nEND_FORMATTING = '\\033[0m'\nWHITE_BG = '\\033[0;30;47m'\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\nRED = '\\033[31m'\nGREEN = '\\033[32m'\nMAGENTA = '\\033[35m'\nBLUE = '\\033[34m'\nCYAN = '\\033[36m'\nYELLOW = '\\033[93m'\nDIM = '\\033[2m'\n\n\ndef get_arguments():\n\n #Define parser and program\n parser = argparse.ArgumentParser(prog = \"VCF_DDTB.py\", description= \"VCF_DDTB manages a custom snp database\") \n\n #Define subtask/subparsers\n subparsers = parser.add_subparsers( dest = \"subtask\", help = \"new / update / compare / extract commands either add new samples, compare or discard exixting samples\")\n\n new_parser = subparsers.add_parser(\"new\", help = \"Create new ddbb with presence/absence of snp\")\n update_parser = subparsers.add_parser(\"update\", help = \"Add new sample using a list of variants, files supplied or files on folder\")\n compare_parser = subparsers.add_parser(\"compare\", help = \"Comapare samples supplied or all samples to obtain a pirwise matrix\")\n extract_parser = subparsers.add_parser(\"extract\", help = \"Remove samples supplied from databse\")\n\n\n #new_parser\n new_parser.add_argument(\"-o\", \"--outputfile\", dest = \"output_file\", required= True, metavar=\"filename\", help=\"REQUIRED: file name, including PATH, of the newd ddbb\")\n new_parser.add_argument(\"-v\", \"--vcf\", required= False, action='store_true', help=\"Database will use vcf files instead of \")\n new_parser.add_argument(\"-s\", \"--suffix\", required= False, type=str, default=\".SNP.final.vcf\", help=\"Suffix to filter within vcf with similar suffix\")\n new_parser.add_argument(\"-r\", \"--recalibrate\", required= False, type=str, default=False, help=\"Folder with tab files to asses discrepancies after comparing\")\n\n\n new_exclusive = new_parser.add_mutually_exclusive_group(required= True)\n\n new_exclusive.add_argument(\"-F\", \"--folder\", dest = \"folder\", metavar=\"folder\",required= False, type=str, help=\"Folder containinig files with snp positions\")\n new_exclusive.add_argument(\"-f\", \"--file\", dest = \"single_file\", metavar=\"file[s]\", required= False, type=str, help=\"individual files with snp positions\")\n new_exclusive.add_argument(\"-l\", \"--list\", dest = \"snp_list\", metavar=\"list\", required= False, help=\"file with a list of positions in a column, not vcf format\")\n\n\n #update_parser\n update_parser.add_argument(\"-o\", \"--outputfile\", dest = \"output_file\", required= True, metavar=\"filename\", help=\"REQUIRED: file name, including PATH, of the updated ddbb\")\n update_parser.add_argument(\"-s\", \"--snp-final\", required= False, action='store_true', help=\"Database will use snp.fila instead of gatk vcf \")\n update_parser.add_argument(\"-d\", \"--database\", dest = \"update_database\", required= True, metavar=\"TB_database\", help=\"REQUIRED: csv file with the database to be enriched/consulted\")\n\n update_exclusive = update_parser.add_mutually_exclusive_group()\n\n update_exclusive.add_argument(\"-F\", \"--folder\", dest = \"folder\", metavar=\"folder\",required= False, type=str, help=\"Folder containinig files with snp positions\")\n update_exclusive.add_argument(\"-f\", \"--file\", dest = \"single_file\", metavar=\"file[s]\", required= False, type=str, help=\"individual files with snp positions\")\n update_exclusive.add_argument(\"-l\", \"--list\", dest = \"snp_list\", metavar=\"list\", required= False, help=\"file with a list of positions in a column, not vcf format\")\n\n update_parser.add_argument(\"-b\", \"--backup\", dest = \"backup\", action=\"store_true\", help=\"Creates an aditional database with the date as backup\")\n\n #compare_parser\n compare_parser.add_argument(\"-d\", \"--database\", dest = \"final_database\", required= True, metavar=\"TB_database\", help=\"REQUIRED: csv file with the database to be enriched/consulted\")\n compare_parser.add_argument(\"-o\", \"--outputfile\", dest = \"output_file\", required= False, metavar=\"filename\", help=\"REQUIRED: file name, including PATH, of the matrix comparison\")\n\n compare_exclusive = compare_parser.add_mutually_exclusive_group()\n\n compare_exclusive.add_argument(\"-a\", \"--all\", dest = \"all_compare\", action=\"store_true\", required= False, help=\"All files in supplied database will be compared\")\n compare_exclusive.add_argument(\"-s\", \"--samples\", dest = \"samples_compare\", metavar=\"sample_name[s]\", nargs=\"+\", required= False, help=\"Sample names supplied will be compared\")\n\n #extract_parser\n extract_parser.add_argument(\"-d\", \"--database\", dest = \"final_database\", required= True, metavar=\"TB_database\", help=\"REQUIRED: csv file with the database with the sample to remove\")\n extract_parser.add_argument(\"-o\", \"--outputfile\", dest = \"output_file\", required= True, metavar=\"filename\", help=\"REQUIRED: file name, including PATH, of the updated ddbb\")\n\n extract_parser.add_argument(\"-s\", \"--samples\", dest = \"samples_extract\", metavar=\"sample name[s]\", nargs=\"+\", required= True, help=\"Sample names supplied will be removed\")\n\n parser.add_argument(\"--version\", action=\"version\", version=\"%(prog)s 0.1\")\n\n arguments = parser.parse_args()\n\n return arguments\n\n\ndef compare_snp_columns(sample1, sample2, df):\n jaccard_similarity = jaccard_score(df[sample1], df[sample2], average='binary') #similarities between colums\n hamming_similarity = 1 - jaccard_similarity #disagreements between colums\n snp_distance = int(hamming_similarity * (len(df.index)+1))\n return snp_distance\n\ndef snp_distance_pairwise(dataframe, output_file):\n if os.path.exists(output_file):\n os.remove(output_file)\n with open(output_file, \"a\") as f:\n for sample1 in dataframe.iloc[:,3:].columns: #remove first 3 colums\n for sample2 in dataframe.iloc[:,3:].columns:\n if sample1 != sample2:\n snp_distance = compare_snp_columns(sample1, sample2, dataframe)\n line_distance = \"%s\\t%s\\t%s\\n\" % (sample1, sample2, snp_distance)\n f.write(line_distance)\n\ndef snp_distance_matrix(dataframe, output_file):\n dataframe_only_samples = dataframe.set_index(dataframe['Position'].astype(int)).drop(['Position','N','Samples'], axis=1) #extract three first colums and use 'Position' as index\n hamming_distance = pairwise_distances(dataframe_only_samples.T, metric = \"hamming\") #dataframe.T means transposed\n snp_distance_df = pd.DataFrame(hamming_distance * len(dataframe_only_samples.index), index=dataframe_only_samples.columns, columns=dataframe_only_samples.columns) #Add index\n snp_distance_df = snp_distance_df.astype(int)\n snp_distance_df.to_csv(output_file, sep='\\t', index=True)\n\ndef hamming_distance_matrix(dataframe, output_file):\n dataframe_only_samples = dataframe.set_index(dataframe['Position'].astype(int)).drop(['Position','N','Samples'], axis=1) #extract three first colums and use 'Position' as index\n hamming_distance = pairwise_distances(dataframe_only_samples.T, metric = \"hamming\") #dataframe.T means transposed\n hamming_distance_df = pd.DataFrame(hamming_distance, index=dataframe_only_samples.columns, columns=dataframe_only_samples.columns) #Add index\n hamming_distance_df.to_csv(output_file, sep='\\t', index=True)\n\ndef clustermap_dataframe(dataframe, output_file):\n dataframe_only_samples = dataframe.set_index(dataframe['Position'].astype(int)).drop(['Position','N','Samples'], axis=1) #extract three first colums and use 'Position' as index\n sns.clustermap(dataframe_only_samples, annot=False, cmap=\"YlGnBu\", figsize=(13, 13))\n plt.savefig(output_file, format=\"png\")\n\ndef dendogram_dataframe(dataframe, output_file):\n dataframe_only_samples = dataframe.set_index(dataframe['Position'].astype(int)).drop(['Position','N','Samples'], axis=1) #extract three first colums and use 'Position' as index\n labelList = dataframe_only_samples.columns.tolist()\n Z = shc.linkage(dataframe_only_samples.T, method='average') #method='single'\n\n plt.rcParams['lines.linewidth'] = 8 #Dendrogram line with\n plt.rcParams['xtick.major.size'] = 10 #Only affect to tick (line) size\n plt.rcParams.update({'font.size': 30}) #Increase x tick label size\n #plt.tick_params(labelsize=30)\n plt.figure(figsize=(30, 50))\n plt.ylabel('samples', fontsize=30)\n plt.xlabel('snp distance', fontsize=30)\n\n shc.dendrogram(Z, labels=labelList, orientation='left', distance_sort='descending', show_leaf_counts=True, color_threshold=10, leaf_font_size=20)\n\n \n plt.savefig(output_file, format=\"png\")\n\n# Convert dendrogram to Newick\ndef linkage_to_newick(dataframe, output_file):\n \"\"\"\n Thanks to https://github.com/biocore/scikit-bio/issues/1579\n Input : Z = linkage matrix, labels = leaf labels\n Output: Newick formatted tree string\n \"\"\"\n dataframe_only_samples = dataframe.set_index(dataframe['Position'].astype(int)).drop(['Position','N','Samples'], axis=1) #extract three first colums and use 'Position' as index\n labelList = dataframe_only_samples.columns.tolist()\n Z = shc.linkage(dataframe_only_samples.T, method='average')\n\n tree = shc.to_tree(Z, False)\n def buildNewick(node, newick, parentdist, leaf_names):\n if node.is_leaf():\n #print(\"%s:%f%s\" % (leaf_names[node.id], parentdist - node.dist, newick))\n return \"%s:%f%s\" % (leaf_names[node.id], parentdist - node.dist, newick)\n else:\n if len(newick) > 0:\n newick = f\"):{(parentdist - node.dist)/2}{newick}\"\n else:\n newick = \");\"\n newick = buildNewick(node.get_left(), newick, node.dist, leaf_names)\n newick = buildNewick(node.get_right(), \",%s\" % (newick), node.dist, leaf_names)\n newick = \"(%s\" % (newick)\n #print(newick)\n return newick\n\n with open(output_file, 'w') as f:\n f.write(buildNewick(tree, \"\", tree.dist, labelList))\n return buildNewick(tree, \"\", tree.dist, labelList)\n\n\n\ndef ddtb_compare(args):\n\n database_file = os.path.abspath(args.final_database)\n check_file_exists(database_file)\n presence_ddbb = import_to_pandas(database_file, header=True)\n\n if args.output_file:\n output_file = os.path.abspath(args.output_file)\n output_path = output_file.split(\".\")[0]\n else:\n output_path = database_file.split(\".\")[0]\n\n print(\"Output path is: \" + output_path)\n\n if args.all_compare:\n print(BLUE + BOLD + \"Comparing all samples in \" + database_file + END_FORMATTING)\n prior_pairwise = datetime.datetime.now()\n\n #Calculate pairwise snp distance for all and save file\n print(CYAN + \"Pairwise distance\" + END_FORMATTING)\n pairwise_file = output_path + \".snp.pairwise.tsv\"\n snp_distance_pairwise(presence_ddbb, pairwise_file)\n after_pairwise = datetime.datetime.now()\n print(\"Done with pairwise in: %s\" % (after_pairwise - prior_pairwise))\n\n #Calculate snp distance for all and save file\n print(CYAN + \"SNP distance\" + END_FORMATTING)\n snp_dist_file = output_path + \".snp.tsv\"\n snp_distance_matrix(presence_ddbb, snp_dist_file)\n\n #Calculate hamming distance for all and save file\n print(CYAN + \"Hamming distance\" + END_FORMATTING)\n hmm_dist_file = output_path + \".hamming.tsv\"\n hamming_distance_matrix(presence_ddbb, hmm_dist_file)\n \"\"\"\n #Represent pairwise snp distance for all and save file\n print(CYAN + \"Drawing distance\" + END_FORMATTING)\n prior_represent = datetime.datetime.now()\n png_dist_file = output_path + \".snp.distance.png\"\n #clustermap_dataframe(presence_ddbb, png_dist_file)\n after_represent = datetime.datetime.now()\n print(\"Done with distance drawing in: %s\" % (after_represent - prior_represent))\n \"\"\"\n #Represent dendrogram snp distance for all and save file\n print(CYAN + \"Drawing dendrogram\" + END_FORMATTING)\n png_dend_file = output_path + \".snp.dendrogram.png\"\n dendogram_dataframe(presence_ddbb, png_dend_file)\n\n\n #Output a Newick file distance for all and save file\n print(CYAN + \"Newick dendrogram\" + END_FORMATTING)\n newick_file = output_path + \".nwk\"\n linkage_to_newick(presence_ddbb, newick_file)\n\n\n else:\n print(\"sample mode is not implemented\")\n\n\n\n\n\n\n\n \"\"\"\n #compare_parser\n compare_parser.add_argument(\"-d\", \"--database\", dest = \"final_database\", required= True, metavar=\"TB_database\", help=\"REQUIRED: csv file with the database to be enriched/consulted\")\n compare_parser.add_argument(\"-o\", \"--outputfile\", dest = \"output_file\", required= True, metavar=\"filename\", help=\"REQUIRED: file name, including PATH, of the matrix comparison\")\n\n compare_exclusive = compare_parser.add_mutually_exclusive_group()\n\n compare_exclusive.add_argument(\"-a\", \"--all\", dest = \"all_compare\", action=\"store_true\", required= False, help=\"All files in supplied database will be compared\")\n compare_exclusive.add_argument(\"-s\", \"--samples\", dest = \"samples_compare\", metavar=\"sample_name[s]\", nargs=\"+\", required= False, help=\"Sample names supplied will be compared\")\n\n \"\"\"","repo_name":"pedroscampoy/VCF_DDTB","sub_path":"ddtb_compare.py","file_name":"ddtb_compare.py","file_ext":"py","file_size_in_byte":13623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14352388047","text":"from django.shortcuts import render, get_object_or_404, redirect, render_to_response\nfrom wmcomment.models import BaseComment\nfrom wmcomment.forms import CommentForm, NestedCommentForm\nfrom wmposts.models import BasePost\nfrom django.template import RequestContext\nfrom django.http.response import HttpResponse\n\ndef add_comment(request, pk):\n\t\n\t\n\tpost = BasePost.objects.get(pk=int(pk))\n\tcomments = BaseComment.objects.filter(linked_post=post)\n\tif request.method == 'POST':\n\t\tform = CommentForm(request.POST)\n\t\t\n\t\tcomment = request.POST.get(\"content\")\n\t\tprint(\"--------------\")\n\t\tprint(comment)\n\t\tif form.is_valid():\n\t\t\tcomment = form.save(commit=False)\n\t\t\tcomment.linked_post = post\n\t\t\tcomment.linked_user = request.user\n\t\t\n\t\t\tcomment.save()\n\t\t\tpost.noc += 1\n\t\t\tpost.save()\n\t\t\treturn HttpResponseRedirect('') # , pk=BasePost.pk)\n\telse:\n\t\tform = CommentForm()\n\t\t\n\t\n\treturn render_to_response('singlepost.html',\n\t\t{'form':form, 'post': post, 'comments' : comments},\n\t\tcontext_instance=RequestContext(request)\n\t\t)\n\t\n\t\ndef add_nested_comment(request, pk):\n\n\tbase_comment = BaseComment.objects.get(pk=int(pk))\n\tnested_comments = NestedComment.objects.filter(nested_linked_comment=base_comment)\n\t\n\t\n\tpost = BasePost.objects.get(pk=base_comment.linked_post)\n\t\n\tcomments = BaseComment.objects.filter(linked_post=post)\n\t \n\tif request.method == 'POST':\n\t\tnested_form = NestedCommentForm(request.POST)\n\t\tnested_comment = request.POST.get('nested_content')\n\t\t\n\t\tif form.is_valid():\n\t\t\t\tnested_comment = nested_form.save(commit=False)\n\t\t\t\tnested_comment.nested_linked_comment = base_comment\n\t\t\t\tnested_comment.nested_linked_user = request.user\n\t\t\t\tnested_comment.save()\n\t\t\t\treturn render_to_response('singlepost.html',\n\t\t\t\t\t{'nested_form':nested_form,'base_comment':base_comment, 'nested_comments':nested_comments,'comments' :comments},\n\t\t\t\t\tcontext_instance=RequestContext(request)\n\t\t\t\t\t)\n\telse:\n\t\tform = NestedCommentForm()\n\t\t\n\treturn render_to_response('singlepost.html',\n\t\t{'nested_form':nested_form,'base_comment':base_comment, 'nested_comments':nested_comments,'comments' :comments},\n\t\tcontext_instance=RequestContext(request)\n\t\t)\n\n\t\n\t\n\t","repo_name":"jjeesse/wm","sub_path":"wmcomment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30354167702","text":"import pickle\nimport time\n\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.webdriver import WebDriver\nfrom selenium.webdriver.common.by import By\n\nfrom src.reconhecedor.tabela_analise.acao import Empilhamento, Reducao, Salto, Aceite\nfrom src.reconhecedor.tabela_analise.estado import Estado\nfrom src.reconhecedor.tabela_analise.tabela import TabelaAnalise\n\n\ndef iniciar_chrome() -> WebDriver:\n # Caminho para o executável do ChromeDriver\n servico = Service(r'C:\\chromedriver\\chromedriver.exe')\n servico.start()\n\n # Inicia o chrome em background\n opcoes = Options()\n opcoes.add_argument('--headless')\n\n # Não imprime logs\n opcoes.add_experimental_option('excludeSwitches', ['enable-logging'])\n\n # Abre o chrome\n driver = webdriver.Chrome(\n service=servico,\n options=opcoes\n )\n\n return driver\n\n\ndef fechar_chrome(driver: WebDriver):\n # Fecha o navegador\n driver.quit()\n\n\ndef abrir_url(driver: WebDriver, url: str):\n # Abre a url especificada\n driver.get(url)\n\n\ndef get_tabela_lr(gramatica_str, recarregar):\n # Se for necessário recarregar a tabela lr, raspa a página jsmachines\n if recarregar:\n tabela_lr = raspar_tabela_lr(gramatica_str)\n\n # Salva o arquivo a tabela em um pickle em cache\n salvar_cache_tabela_lr('arquivos/cache/estruturas.pkl', tabela_lr)\n\n return tabela_lr\n\n # Se não, pega do arquivo pickle em cache\n return get_cache_tabela_lr('arquivos/cache/estruturas.pkl')\n\n\ndef salvar_cache_tabela_lr(path: str, tabela):\n with open(path, 'wb') as file:\n pickle.dump(tabela, file)\n\n\ndef get_cache_tabela_lr(path: str):\n with open(path, 'rb') as file:\n tabela = pickle.load(file)\n return tabela\n\n\ndef raspar_tabela_lr(gramatica_str) -> TabelaAnalise:\n # ABRIR CHROME\n chrome = iniciar_chrome()\n\n # ABRIR JS MACHINES\n abrir_url(chrome, 'https://jsmachines.sourceforge.net/machines/slr.html')\n\n # PEGA O CAMPO DAS GRAMÁTICAS\n campo_gramatica = chrome.find_element(\n By.ID,\n 'grammar'\n )\n\n # LIMPA O CAMPO\n chrome.execute_script(\"arguments[0].value = ''\", campo_gramatica)\n\n # INSERE A GRAMÁTICA\n campo_gramatica.send_keys(gramatica_str)\n\n time.sleep(1)\n\n # CLICA NO BOTÃO PARA GERAR A TABELA\n chrome.find_element(\n By.XPATH,\n '//input[@type=\"button\"][@value=\">>\"]'\n ).click()\n\n time.sleep(2)\n\n # PEGA O HTML DA TABELA GERADA\n html_tabela = chrome.find_element(\n By.XPATH,\n '//*[@id=\"lrTableView\"]'\n ).get_attribute('innerHTML')\n\n # FECHA O CHROME\n fechar_chrome(chrome)\n\n return TabelaAnalise(\n html_para_estados(html_tabela)\n )\n\n\ndef html_para_estados(html_tabela):\n soup = BeautifulSoup(html_tabela, 'html.parser')\n tabela = soup.find('table')\n linhas = tabela.find_all('tr')\n\n # Pega os símbolos não terminais do cabeçalho\n nao_terminais = [s.text for s in linhas[2].find_all('th')]\n\n # Remove a última linha de cabeçalho\n del linhas[:3]\n\n estados = []\n\n while linhas:\n cols = linhas[0].find_all('td')\n numero_estado = int(cols[0].text)\n estados.insert(numero_estado, Estado())\n\n for index, transicao in enumerate(cols[1:]):\n transicao = transicao.text\n if transicao != '\\xa0':\n estados[numero_estado].set_acao(\n nao_terminais[index],\n Aceite() if 'acc' in transicao else\n Empilhamento(transicao.replace('s', '')) if 's' in transicao else\n Reducao(transicao.replace('r', '')) if 'r' in transicao else\n Salto(transicao)\n )\n\n del linhas[0]\n\n return estados\n","repo_name":"Dutraz/lfa-gerador-afd","sub_path":"src/reconhecedor/jsmachines.py","file_name":"jsmachines.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37037825250","text":"class Monik:\n def __init__(self):\n self.firm = input('Введіть назву фірми виробника: ')\n self.date1 = int(input('Введіть число дати виробництва: '))\n self.date2 = int(input('Введіть місяць дати виробництва: '))\n self.date3 = int(input('Введіть рік дати виробництва : '))\n self.date_1 = int(input('Введіть число дати купівлі: '))\n self.date_2 = int(input('Введіть місяць дати купівлі: '))\n self.date_3 = int(input('Введіть рік дати купівлі : '))\n self.price = int(input('Введіть вартість в гривнях: '))\n self.type = input('Введіть тип монітора: ')\n self.height = int(input('Введіть довжину монітора в пікселях: '))\n self.width = int(input('Введіть ширину монітора в пікселях: '))\n\n def calculate_age(self):\n return 'Вік моніка - {0}'.format(2021 - self.date3)\n\n def pic(self):\n self.pic_h = int(input('Введіть довжину картинки : '))\n self.pic_w = int(input('Введіть ширину картинки : '))\n if self.pic_h == self.height and self.pic_w == self.width:\n return \"Можна без масштабування\"\n else:\n return \"Не можна без масштабування\"\n\n def coef(self):\n self.woutprop1 = self.height / self.pic_h\n self.woutprop2 = self.width / self.pic_w\n if self.pic_h > self.pic_w:\n self.wprop = self.width / self.pic_w\n else:\n self.wprop = self.height / self.pic_h\n return 'Без збереження пропорцій, коефіцієнт: {0}. Із збереженням пропорцій, коефіцієнт: {1}'.format([self.woutprop1, self.woutprop2],\n [self.wprop, self.wprop])\n\n\nA = Monik()\nprint(A.calculate_age())\nprint(A.pic())\nprint(A.coef())\n","repo_name":"Sklyar13OFF/LaboratorniPython","sub_path":"Labkaten/exer2.py","file_name":"exer2.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19713827130","text":"import sys\nimport socket\n\n# Create a TCP/IP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Connect the socket to the port where the server is listening\nserver_address = ('localhost', 10000)\nprint(f\"connecting to {server_address}\")\nsock.connect(server_address)\nmess = input(\"Nama File yang akan dikirim ke server : \")\n\ntry:\n # Send data\n sock.sendall(mess.encode())\n filee=open(mess,\"rb\")\n kirim = filee.read(1024)\n while(kirim):\n sock.send(kirim)\n kirim = filee.read(1024)\n\n print(f\"File sukses dikirim!\")\n\nfinally:\n print(\"closing\")\n sock.close()\n","repo_name":"safhiram/progjar_b_its_2020","sub_path":"tugas1/tugas 1a/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71325367442","text":"import logging\nfrom abc import ABCMeta\n\nfrom calibtool.CalibSite import CalibSite\nfrom calibtool.study_sites.site_setup_functions import config_setup_fn, summary_report_fn, site_input_eir_fn\nfrom calibtool.analyzers.ChannelByAgeCohortAnalyzer import PrevalenceByAgeCohortAnalyzer\nfrom calibtool.analyzers.Helpers import channel_age_json_to_pandas\n\nlogger = logging.getLogger(__name__)\n\n\nclass PrevalenceCalibSite(CalibSite):\n \"\"\"\n An abstract class that implements the simulation setup for prevalence-by-age analyses:\n - Namawala, Tanzania\n - Garki, Nigeria (Rafin Marke, Matsari, Sugungum)\n \"\"\"\n\n __metaclass__ = ABCMeta\n\n reference_dict = {\n \"Average Population by Age Bin\": [],\n \"Age Bin\": [],\n \"PfPR by Age Bin\": []\n }\n\n def get_setup_functions(self):\n return [\n config_setup_fn(duration=21915), # 60 years (with leap years)\n summary_report_fn(interval=365),\n site_input_eir_fn(self.name, birth_cohort=True)\n ]\n\n def get_reference_data(self, reference_type):\n site_ref_type = 'prevalence_by_age'\n\n if reference_type is not site_ref_type:\n raise Exception(\"%s does not support %s reference_type, only %s.\",\n self.__class__.__name__, reference_type, site_ref_type)\n\n reference_data = channel_age_json_to_pandas(self.reference_dict, index_key='Age Bin')\n\n logger.debug('Reference data:\\n %s', reference_data)\n return reference_data\n\n def get_analyzers(self):\n return [PrevalenceByAgeCohortAnalyzer(site=self)]\n\n","repo_name":"m-v-nikolov/dtk-tools-py3","sub_path":"calibtool/study_sites/PrevalenceCalibSite.py","file_name":"PrevalenceCalibSite.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"870312412","text":"# 5622 다이얼\ndial = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ']\n\ns = input()\n\ntime = 0\nfor c in s:\n i = 0\n while i < 8:\n if c in dial[i]:\n break\n i += 1\n time += i + 3\n\nprint(time)","repo_name":"Sunrin-Algorithm-Study/Algorithm_study","sub_path":"sources/cometj03_정해성/step/6 string/5622.py","file_name":"5622.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"23134912550","text":"#! /usr/bin/env python3.8\n# encoding:utf-8\nimport os\nimport pandas as pd\nimport torch\n#使用pandas处理原始数据,并转换为张量格式\n#创建逗号分隔值文件csv作为人工数据集\nos.makedirs(os.path.join('.', 'data'), exist_ok=True) #将会在运行目录下生成文件夹\ndata_file = os.path.join('.', 'data', 'house_tiny.csv')\nwith open(data_file, 'w') as f:\n f.write('NumRooms,Alley,Price\\n') # 列名\n f.write('NA,Pave,127500\\n') # 每行表示一个数据样本\n f.write('2,NA,106000\\n')\n f.write('4,NA,178100\\n')\n f.write('NA,NA,140000\\n')\n\ndata = pd.read_csv(data_file)\nprint(data)\n#可以注意到有不少地方的数据缺失:处理方法:插值、删除\ninputs, outputs = data.iloc[:, 0:2], data.iloc[:, 2]\n#分为输入、输出两类\ninputs = inputs.fillna(inputs.mean()) #数值阈用平均值填充\nprint(inputs)\n'''\n由于无法正确的用平均值表示类型\n使用0 1值来实现增维判断\n NumRooms Alley_Pave Alley_nan\n0 3.0 1 0\n1 2.0 0 1\n2 4.0 0 1\n3 3.0 0 1\n'''\n\ninputs = pd.get_dummies(inputs, dummy_na=True) \nprint(inputs)\n#最终转换成张量\nX, y = torch.tensor(inputs.values), torch.tensor(outputs.values)\nX, y","repo_name":"Matthew-Hu-cmd/D2L_torch_tutorial","sub_path":"Heads_up/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"8532903912","text":"\nimport numpy as np\nimport json\nimport pathlib as pl\nimport sys\nimport os\nimport numpy as np\n\nsys.path.append(str(list(pl.Path(__file__).parents)[2]))\nos.chdir(str(list(pl.Path(__file__).parents)[2]))\n\nimport input.GeneralConstants as const\n\ndef powerloading_climbrate(eff, ROC, WS,rho,CD0,e,A):\n k = 1/(e*A*np.pi)\n CLCDratio = 3/(4*k)* np.sqrt(3*CD0/k)\n return (ROC+np.sqrt(2*WS/rho)*(1/CLCDratio))**(-1) * eff\n\ndef powerloading_turningloadfactor(rho,V,WS,eff,A,e,loadfactor,CD0):\n k = 1/(e*A*np.pi)\n n = loadfactor\n \n WP = (CD0*0.5*rho*V*V*V/WS + WS*n*n*k/(0.5*rho*V))**-1 *eff\n\n return WP\n\ndef powerloading_thrustloading(WS,rho,ROC,StotS):\n return 1.2*(1+(1/WS)*rho*ROC**2*StotS)\n #return 1.2*(1+np.ones(np.shape(WS)))*1.3\n\ndef powerloading_verticalflight(MTOM,TW,A_tot,rho,eff,ducted_bool):\n W = MTOM *const.g0\n T = TW * W\n \n if ducted_bool==True:\n return (0.5*np.sqrt((T*T*T)/(W*W*rho*A_tot)))**(-1)*eff\n else:\n return (np.sqrt((T*T*T)/(2*W*W*rho*A_tot)))**(-1)*eff \n \ndef powerloading_climbgradient(e,A,CD0,WS,rho,eff,G):\n CL = np.sqrt(np.pi*e*A*CD0)\n CD = 2*CD0\n WP = (np.sqrt(WS*2/(rho*CL))*(G+CD/CL))**(-1) * eff\n return WP\n\ndef wingloading_stall(CLmax,V_stall,rho):\n return CLmax*0.5*rho*V_stall*V_stall\n\ndef get_wing_power_loading(perf_par, wing, engine, aero, cont_factor=1.1):\n \"\"\" Returns the wing loading and thrust of the weight based on performance parameters\n\n :param perf_par: performance parameter class from data structues\n :type perf_par: PerformanceParameters class\n :param wing: wing class from data structues\n :type wing: Wing class\n \"\"\" \n\n #Check if it\"s lilium or not to define the variable that will say to vertical_flight what formula to use.\n WS_range = np.arange(1,4000,1)\n #data[\"WS\"],data[\"TW\"],data[\"WP_cruise\"],data[\"WP_hover\"] = plot_wing_power_loading_graphs(data[\"eff\"], data[\"StotS\"], data[\"diskloading\"], data[\"name\"],WS_range,i)\n\n\n #CALCULATE ALL THE VALUES FOR THE GRAPHS\n TW_range = powerloading_thrustloading(WS_range,const.rho_sl,const.roc_hvr, perf_par.Stots) \n #if data[\"name\"] == \"J1\": \n # TW_range = TW_range*1.3 #Added 30% extra thrust to maintain stability\n CLIMBRATE = cont_factor*powerloading_climbrate(perf_par.prop_eff,const.roc_cr, WS_range,const.rho_cr,aero.cd0_cruise ,aero.e,wing.aspect_ratio)\n TURN_VCRUISE = cont_factor*powerloading_turningloadfactor(const.rho_cr,const.v_cr,WS_range, perf_par.prop_eff ,wing.aspect_ratio,aero.e, perf_par.turn_loadfactor,aero.cd0_cruise)\n TURN_VMAX = cont_factor*powerloading_turningloadfactor(const.rho_cr,perf_par.v_max, WS_range, perf_par.prop_eff ,wing.aspect_ratio ,aero.e ,perf_par.turn_loadfactor,aero.cd0_cruise)\n VERTICALFLIGHT = cont_factor*powerloading_verticalflight(perf_par.MTOM ,TW_range, engine.total_disk_area ,const.rho_sl,perf_par.prop_eff ,False)\n STALLSPEED = wingloading_stall(aero.cL_max ,perf_par.v_stall, const.rho_sl)\n CLIMBGRADIENT = cont_factor*powerloading_climbgradient(aero.e ,wing.aspect_ratio ,aero.cd0_cruise,WS_range,const.rho_sl,perf_par.prop_eff ,const.climb_gradient)\n\n #DETERMINE LOWEST\n lowest_area_y_novf = []\n lowest_area_y = []\n lowest_area_x = np.arange(0,int(STALLSPEED),1)\n for i in lowest_area_x:\n lowest_area_y.append(min(CLIMBRATE[i],TURN_VCRUISE[i],TURN_VMAX[i],CLIMBGRADIENT[i],VERTICALFLIGHT[i]))\n lowest_area_y_novf.append(min(CLIMBRATE[i],TURN_VCRUISE[i],TURN_VMAX[i],CLIMBGRADIENT[i]))\n \n #DETERMINE LIMITING FACTORS\n margin = 0.95\n perf_par.wing_loading_cruise = STALLSPEED*margin\n perf_par.TW_max = powerloading_thrustloading(perf_par.wing_loading_cruise,const.rho_sl,const.roc_hvr, perf_par.Stots)\n WP_cruise = lowest_area_y_novf[-1]*margin\n WP_hover = lowest_area_y[-1]*margin\n aero.cL_cruise = 2/(const.rho_cr*const.v_cr**2)*perf_par.wing_loading_cruise\n return perf_par, wing, engine, aero\n\n\n","repo_name":"dmkeijzer/AetheriaPackage","sub_path":"modules/preliminary_sizing/wing_power_loading_functions.py","file_name":"wing_power_loading_functions.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"40704074513","text":"import shutil\nimport os\nimport pytest\n\n\n@pytest.fixture\ndef create_temp_archive():\n def _create_temp_archive(root_dir, dir_path, extension, archive_name=\"archive\"):\n cwd = os.getcwd()\n archive_path = f\"{cwd}/{archive_name}\"\n dir_name = dir_path.split(\"/\")[-1]\n os.chdir(root_dir)\n shutil.make_archive(\n base_name=archive_path,\n format=extension,\n root_dir=root_dir,\n base_dir=dir_name,\n )\n os.chdir(cwd)\n if extension == \"xztar\":\n extension = \"tar.xz\"\n return f\"archive.{extension}\"\n\n return _create_temp_archive\n\n\n@pytest.fixture\ndef data_inputs():\n return [\n \"test.md\",\n \"test.css\",\n \"test.yaml\",\n \"test.sh\",\n \"test.tf\",\n \"test.py\",\n \"test.js\",\n \"Dockerfile\",\n \"test.html\",\n \"test.java\",\n \"test.ts\",\n ]\n","repo_name":"xlab-si/iac-scan-runner","sub_path":"tests/unit/utils/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"3"}
+{"seq_id":"43300742429","text":"\"\"\"\nHelpers for the analytics part of OLGA application.\n\"\"\"\n\nfrom http import HTTPStatus as http\nimport logging\nimport requests\n\n\nfrom django.http import HttpResponse\n\nfrom olga.analytics.forms import (\n EdxInstallationParanoidLevelForm,\n EdxInstallationEnthusiastLevelForm,\n InstallationStatisticsParanoidLevelForm,\n InstallationStatisticsEnthusiastLevelForm\n)\n\nlogger = logging.getLogger(__name__)\n\n# pylint: disable=invalid-name\n\n\ndef validate_instance_stats_forms(receive_instance_stats_method):\n \"\"\"\n Check if edX overall installation info and statistics are valid with corresponding forms.\n\n Returns HTTP-response with status 401, that means at least one of two forms is not valid.\n \"\"\"\n def wrapper(request, *args, **kwargs):\n \"\"\"\n Wrapper.\n \"\"\"\n paranoid_installation_form = EdxInstallationParanoidLevelForm(request.POST)\n enthusiast_installation_form = EdxInstallationEnthusiastLevelForm(request.POST)\n paranoid_statistics_form = InstallationStatisticsParanoidLevelForm(request.POST)\n enthusiast_statistics_form = InstallationStatisticsEnthusiastLevelForm(request.POST)\n\n statistics_level = request.POST.get('statistics_level')\n\n level_valid_forms = {\n 'paranoid': paranoid_installation_form.is_valid() and paranoid_statistics_form.is_valid(),\n 'enthusiast': enthusiast_installation_form.is_valid() and enthusiast_statistics_form.is_valid()\n }\n\n if level_valid_forms[statistics_level]:\n return receive_instance_stats_method(request, *args, **kwargs)\n\n return HttpResponse(status=http.UNAUTHORIZED)\n\n return wrapper\n\n\ndef get_coordinates_by_platform_city_name(city_name):\n \"\"\"\n Gather coordinates from Nominatim service by the platform city name.\n\n geo_api.json returns:\n [\n {\n 'display_name': '',\n 'importance': 0.665644115037534,\n 'place_id': '198763125',\n 'lon': '36.2722660718121',\n 'lat': '49.99142545',\n 'osm_type': 'relation',\n 'licence': 'Data OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',\n 'osm_id': '3154746',\n 'boundingbox': ['49.8782819', '50.1044256', '36.1056163', '36.4560593'],\n 'type': 'city',\n 'class': 'place',\n 'icon': 'https://nominatim.openstreetmap.org/images/mapicons/poi_place_city.p.20.png'\n }, ...\n ]\n \"\"\"\n geo_api = requests.get('https://nominatim.openstreetmap.org/search/', params={'city': city_name, 'format': 'json'})\n\n if geo_api.status_code == 200 and geo_api.json():\n location = geo_api.json()[0]\n\n return location.get('lat', ''), location.get('lon', '')\n\n logger.debug('Nominatim API status: %s, City name: %s', geo_api.status_code, city_name)\n return '', ''\n","repo_name":"raccoongang/OLGA","sub_path":"web/olga/analytics/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"40203024348","text":"import random\n\nfrom django.db import models\n\nfrom faker import Faker\n\nGROUP_SUBJECT = [\n 'Разработка web-приложений',\n 'Разработка desktop-приложений',\n 'Разработка серверных приложений',\n 'Разработка мобильных приложений',\n 'Программирование встраиваемых систем',\n 'Системное программирование',\n 'Разработка игр'\n]\n\n\nclass Course(models.Model):\n create_datetime = models.DateTimeField(auto_now_add=True)\n update_datetime = models.DateTimeField(auto_now=True)\n academic_subject = models.CharField(max_length=80, null=False)\n number_of_hours = models.IntegerField(default=10)\n\n\n def __str__(self):\n return f'{self.academic_subject} ({self.number_of_hours} hours)'\n\n @staticmethod\n def generate_courses(count):\n faker = Faker()\n create_course = []\n for _ in range(count):\n crs = Course(\n academic_subject=random.choice(GROUP_SUBJECT),\n number_of_hours=faker.random_int(min=1, max=30)\n )\n crs.save()\n create_course.append(str(crs))\n return create_course\n","repo_name":"RenKus96/test_django","sub_path":"courses/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18690499933","text":"cnt = int(input())\n\nboard = [[0] * 100 for _ in range(100)]\n\nfor _ in range(cnt):\n left, down = map(int, input().split())\n\n row = down - 10\n for i in range(10):\n for j in range(10):\n board[row][left + j] = 1\n row += 1\n\nresult = 0\nfor i in board:\n for j in i:\n if j == 1:\n result += 1\nprint(result)\n","repo_name":"sanghyunEE/coding-test","sub_path":"simulation/2563.py","file_name":"2563.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22568360895","text":"from fileinput import filename\nfrom flask import render_template, url_for,flash,redirect,request,abort,Blueprint\nfrom app.entity.users.forms import LoginForm,RegistrationForm,deposit_,Setting,interest_perc,invite_,redraw_\nfrom app.Models import User,Account,Ledger,Accounttype,Interest_percentage\nfrom flask_login import login_user,current_user,logout_user,login_required\nfrom app import bcrypt,db\nfrom datetime import date,timedelta,datetime,timezone \nimport random\nfrom app.entity.ledger.utils import time_left\nfrom app.entity.users.utils import send_pdf\nfrom sqlalchemy import or_, and_, desc,asc\nfrom werkzeug.utils import secure_filename\nfrom flask import url_for,current_app\nimport os\n\n\n\n\nusers =Blueprint('users',__name__)\n\n\n@users.route('/login',methods=['GET','POST'])\ndef login():\n if current_user.is_authenticated:\n if current_user.type=='Admin':\n return redirect(url_for('users.dashboard'))\n form = LoginForm()\n if form.validate_on_submit():\n name=User.query.filter_by(login=form.username.data).first()#put login\n if name and bcrypt.check_password_hash(name.password,form.password.data):\n login_user(name,remember=form.remember.data,duration=timedelta(seconds=30)) \n next_page=request.args.get('next')\n return redirect (next_page) if next_page else redirect(url_for('users.dashboard'))\n else:\n print(1234567)\n flash(f'Mauvais Identifiant ou mot de passe, essayez à nouveau','danger')\n\n return render_template('fabien-ui/login.html',legend=\"login\",form=form)\n\n@users.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('users.login'))\n\n\n\n@users.route('/sign_up',methods=['GET','POST'])\ndef sign_up():\n if current_user.is_authenticated:\n return redirect(url_for('users.dashboard'))\n form = RegistrationForm()\n acc=['Admin','Client','Tradefin','Tradeeco']\n for i in acc:\n db.session.add(Accounttype(type=i))\n db.session.commit()\n if form.validate_on_submit():#check user \n hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')\n user=User(login=form.username.data,email=form.email.data,type=form.type.data)\n db.session.add(user)\n db.session.commit()\n user.password=hashed_password\n db.session.commit()\n num=int(random.randrange(100000, 999999))\n typo=Accounttype.query.filter_by(type=user.type).first()\n acc=Account(user_id=user.id,type=typo.id,number=num)\n db.session.add(acc)\n db.session.commit()\n flash(f'Account created you can now login','success')\n return redirect(url_for('users.login'))\n return render_template('fabien-ui/register.html',legend=\"sign_up\",form=form)\n\n@users.route('//settings_user',methods=['GET','POST'])\n@login_required\ndef settings(id):\n if current_user.is_authenticated:\n form=Setting()\n user=User.query.filter_by(id=id).first()\n account=Account.query.filter_by(user_id=id).first()\n if form.validate_on_submit():\n user.username=form.username.data\n user.prenom=form.prenom.data\n user.adresse=form.adresse.data\n user.numero=form.numero.data\n db.session.commit()\n flash(f'Account created you can now login','success')\n return redirect(url_for('users.settings',id=id))\n #return redirect(url_for('users.main'))\n return render_template('fabien-ui/settings.html',legend=\"sign_up\",form=form,user=user,account=account)\n\n@users.route('//settings_all',methods=['GET','POST'])\n@login_required\ndef settings_all(id):\n if current_user.is_authenticated:\n user=User.query.filter_by(id=id).first()\n account=Account.query.filter_by(user_id=id).first()\n ledgers=Ledger.query.filter(or_(Ledger.account_credited==id,Ledger.account_debited==id)).all()\n \n\n return render_template('fabien-ui/settings_all.html',legend=\"sign_up\",user=user,account=account,trans=ledgers,id=id)\n\n@users.route('/all_accounts',methods=['GET','POST'])\n@login_required\ndef all_accounts():\n if current_user.is_authenticated:\n account=Account.query.all()\n return render_template('fabien-ui/allacounts.html',legend=\"sign_up\",account=account)\n\n\n@users.route('//deposit',methods=['GET','POST'])\n@login_required\ndef deposit(id):\n form = deposit_()\n if form.validate_on_submit():\n check_acc=Account.query.filter_by(user_id=id).first()\n check_acc.amount+=form.amount.data\n db.session.commit()\n filename=secure_filename(form.file.data.filename)\n final=os.path.join(current_app.config['UPLOAD_FOLDER'],filename)\n form.file.data.save(final) \n ledger=Ledger(account_credited=id,Amount=form.amount.data,state_transaction='deposit',type='deposit') #state type of transaction,list of them\n db.session.add(ledger)\n ledger.transaction_number=int(random.randrange(100000, 999999))\n db.session.commit()\n flash(f'Account created you can now login','success')\n return redirect(url_for('users.settings_all',id=id))\n return render_template('fabien-ui/add_cash.html',legend=\"sign_up\",form=form)\n\n\n@users.route('//redraw',methods=['GET','POST'])\n@login_required\ndef redraw(id):\n form = redraw_()\n if form.validate_on_submit():\n check_acc=Account.query.filter_by(user_id=id).first()\n check_acc.amount-=form.amount.data\n db.session.commit()\n ledger=Ledger(account_debited=id,Amount=form.amount.data,state_transaction='deposit',type='deposit') #state type of transaction,list of them\n db.session.add(ledger)\n ledger.transaction_number=int(random.randrange(100000, 999999))\n db.session.commit()\n flash(f'Account created you can now login','success')\n return redirect(url_for('users.settings',id=id))\n return render_template('fabien-ui/redraw.html',legend=\"sign_up\",form=form)\n\n\n\n@users.route('/invite',methods=['GET','POST'])\n@login_required\ndef invite():\n form = invite_()\n if form.validate_on_submit():\n send_pdf(form.email.data)\n flash(f'email sent','success')\n return redirect(url_for('users.settings',id=current_user.id))\n return render_template('fabien-ui/invite.html',legend=\"sign_up\",form=form)\n\n\n@users.route('/dashboard',methods=['GET','POST'])\n@login_required\ndef dashboard():\n if current_user.type == 'Admin':\n #time_left()\n client=User.query.filter_by(type='Client').count()\n trade_fin=User.query.filter_by(type='Tradefin').count()\n trade_eco=User.query.filter_by(type='Tradeeco').count()\n\n Cash_all=Account.query.all()\n final=0\n \n for sum in Cash_all:\n if sum.amount !=None:\n final+=sum.amount\n\n allled=Ledger.query.all()\n\n return render_template('fabien-ui/index.html',legend=\"dashboard\",final=final,ledger=allled,client=client,trade_fin=trade_fin,trade_eco=trade_eco)\n else:\n #time_left()\n client=User.query.filter_by(type='Client').count()\n trade_fin=User.query.filter_by(type='Tradefin').count()\n trade_eco=0\n\n Cash_all=Account.query.filter_by(user_id=current_user.id).all()\n final=0\n \n for sum in Cash_all:\n if sum.amount !=None:\n final+=sum.amount\n now_utc = datetime.now(timezone.utc) + timedelta(days=1)#add 1 day\n start=datetime.combine(now_utc,datetime.min.time())\n\n allled=Ledger.query.filter(or_(Ledger.account_credited==current_user.id,Ledger.account_debited==current_user.id)).all()\n\n return render_template('fabien-ui/index.html',legend=\"dashboard\",final=final,ledger=allled,late=start,client=client,trade_fin=trade_fin,trade_eco=trade_eco)\n\n\n\n@users.route('/modify_interests',methods=['GET','POST'])\n@login_required\ndef modify_interest():\n acc=['Interet annuel Client','Pourcentage 3 mois','Interet apporteur'\n ,'Interet Trade','Interet annuel Trade fin','Pourcentage profit']\n for i in acc:\n db.session.add(Interest_percentage(type=i))\n db.session.commit()\n form=interest_perc()\n interests=Interest_percentage.query.order_by(asc(Interest_percentage.id)).all()\n if form.validate_on_submit():\n pourcentage3=Interest_percentage.query.filter_by(type='Pourcentage 3 mois').first()\n pourcentage3.percentages=form.pourcentage3.data\n IAC=Interest_percentage.query.filter_by(type='Interet annuel Client').first()\n IAC.percentages=form.IAC.data\n IA=Interest_percentage.query.filter_by(type='Interet apporteur').first()\n IA.percentages=form.IA.data\n IATE=Interest_percentage.query.filter_by(type='Interet Trade').first()\n IATE.percentages=form.IATE.data\n IATF=Interest_percentage.query.filter_by(type='Interet annuel Trade fin').first()\n IATF.percentages=form.IATF.data\n profit=Interest_percentage.query.filter_by(type='Pourcentage profit').first()\n profit.percentages=form.profit.data\n\n db.session.commit()\n return redirect(url_for('users.settings',id=current_user.id))\n return render_template('fabien-ui/modify_interests.html',legend=\"login\",form=form,inter=interests)\n\n\n@users.route('/create_user',methods=['GET','POST'])\n@login_required\ndef create_user():\n form = RegistrationForm()\n if form.validate_on_submit():#check user \n hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')\n user=User(login=form.username.data,email=form.email.data,type=form.type.data)\n db.session.add(user)\n db.session.commit()\n user.password=hashed_password\n db.session.commit()\n num=int(random.randrange(100000, 999999))\n typo=Accounttype.query.filter_by(type=user.type).first()\n acc=Account(user_id=user.id,type=typo.id,number=num)\n db.session.add(acc)\n db.session.commit()\n flash(f'Account created you can now login','success')\n return redirect(url_for('users.all_accounts'))\n return render_template('fabien-ui/add_user.html',legend=\"sign_up\",form=form)\n","repo_name":"EbotFabien/CBS","sub_path":"Flask_app/project/app/entity/users/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":10179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13049408626","text":"\"\"\"\n백준 1003. 피보나치 함수\nblog : https://daimhada.tistory.com/90\nproblem : https://www.acmicpc.net/problem/1003\n\"\"\"\n\nimport sys\ninput = sys.stdin.readline\n\ndef solve(n):\n global fibolist\n return fibolist[n]\n\n\nif __name__ == \"__main__\":\n fibolist = [(1, 0), (0, 1)]\n for i in range(2, 41):\n first = fibolist[i-2][0] + fibolist[i-1][0]\n second = fibolist[i-2][1] + fibolist[i-1][1]\n fibolist.append((first, second))\n\n t = int(input().strip())\n for i in range(t):\n n = int(input().strip())\n result = solve(n)\n print(\"{0} {1}\".format(result[0], result[1]))\n","repo_name":"histuckyi/algorithm","sub_path":"acmicpc/1003.py","file_name":"1003.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"32866800025","text":"from __future__ import annotations\n\nimport math\nimport typing\n\nimport ibis\n\nimport bigframes.core.compile.compiled as compiled\nfrom bigframes.core.ordering import (\n ExpressionOrdering,\n OrderingColumnReference,\n reencode_order_string,\n StringEncoding,\n)\n\nORDER_ID_COLUMN = \"bigframes_ordering_id\"\n\n\ndef concat_unordered(\n items: typing.Sequence[compiled.UnorderedIR],\n) -> compiled.UnorderedIR:\n \"\"\"Append together multiple ArrayValue objects.\"\"\"\n if len(items) == 1:\n return items[0]\n tables = []\n for expr in items:\n table = expr._to_ibis_expr()\n # Rename the value columns based on horizontal offset before applying union.\n table = table.select(\n [table[col].name(f\"column_{i}\") for i, col in enumerate(table.columns)]\n )\n tables.append(table)\n combined_table = ibis.union(*tables)\n return compiled.UnorderedIR(\n combined_table,\n columns=[combined_table[col] for col in combined_table.columns],\n )\n\n\ndef concat_ordered(\n items: typing.Sequence[compiled.OrderedIR],\n) -> compiled.OrderedIR:\n \"\"\"Append together multiple ArrayValue objects.\"\"\"\n if len(items) == 1:\n return items[0]\n\n tables = []\n prefix_base = 10\n prefix_size = math.ceil(math.log(len(items), prefix_base))\n # Must normalize all ids to the same encoding size\n max_encoding_size = max(\n *[expression._ordering.string_encoding.length for expression in items],\n )\n for i, expr in enumerate(items):\n ordering_prefix = str(i).zfill(prefix_size)\n table = expr._to_ibis_expr(\n ordering_mode=\"string_encoded\", order_col_name=ORDER_ID_COLUMN\n )\n # Rename the value columns based on horizontal offset before applying union.\n table = table.select(\n [\n table[col].name(f\"column_{i}\")\n if col != ORDER_ID_COLUMN\n else (\n ordering_prefix\n + reencode_order_string(table[ORDER_ID_COLUMN], max_encoding_size)\n ).name(ORDER_ID_COLUMN)\n for i, col in enumerate(table.columns)\n ]\n )\n tables.append(table)\n combined_table = ibis.union(*tables)\n ordering = ExpressionOrdering(\n ordering_value_columns=tuple([OrderingColumnReference(ORDER_ID_COLUMN)]),\n total_ordering_columns=frozenset([ORDER_ID_COLUMN]),\n string_encoding=StringEncoding(True, prefix_size + max_encoding_size),\n )\n return compiled.OrderedIR(\n combined_table,\n columns=[\n combined_table[col]\n for col in combined_table.columns\n if col != ORDER_ID_COLUMN\n ],\n hidden_ordering_columns=[combined_table[ORDER_ID_COLUMN]],\n ordering=ordering,\n )\n","repo_name":"googleapis/python-bigquery-dataframes","sub_path":"bigframes/core/compile/concat.py","file_name":"concat.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"3"}
+{"seq_id":"17542467040","text":"#face_detection.py\nimport cv2\n\nprint('OpenCV Version: '+cv2.__version__)\n\n\n# Load the Haar cascade\nfaceCascade = cv2.CascadeClassifier('Cascades/haarcascade_frontalface_default.xml')\n\n# Initialize the camera\ncamera = cv2.VideoCapture(0)\n\nwhile True:\n # Capture the frame from the camera\n ret, frame = camera.read()\n\n # Convert the frame to grayscale\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Detect faces\n faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))\n\n # Draw rectangles around the detected faces\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n # Display the frame\n cv2.imshow('Face Detection', frame)\n\n # Exit the loop if 'q' is pressed\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Release the resources\ncamera.release()\ncv2.destroyAllWindows()\n","repo_name":"mustafamelihcetin/face_detection","sub_path":"face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24415271945","text":"import pygame\nfrom pygame.sprite import Sprite\n\n\nclass Cat(Sprite):\n \"\"\"A class representing a single cat.\"\"\"\n\n def __init__(self, game):\n \"\"\"Initializes the cat and sets its initial position\"\"\"\n super().__init__()\n\n self.screen = game.screen\n self.settings = game.settings\n\n self.image = pygame.image.load('..//recources/images/cat.png')\n self.rect = self.image.get_rect()\n\n self.rect.x = self.rect.width / 10\n self.rect.y = self.rect.height / 10\n\n self.x = float(self.rect.x)\n\n def check_edges(self):\n screen_rect = self.screen.get_rect()\n if self.rect.right > screen_rect.right or self.rect.left <= 0:\n return True\n\n def update(self):\n \"\"\"Moves the cat.\"\"\"\n self.x += (self.settings.cat_speed_factor * self.settings.fleet_direction)\n self.rect.x = self.x\n","repo_name":"CosmonautComrad/cat-invasion","sub_path":"src/cat.py","file_name":"cat.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71834646482","text":"def code_maker(code):\n cnt = 0\n\n while True:\n p = code.pop(0)\n n = p - (cnt % 5 + 1)\n\n if n <= 0:\n code.append(0)\n break\n\n else:\n code.append(n)\n cnt += 1\n\n return code\n\nT = 10\n\nfor t in range(1, T+1):\n tc = int(input())\n code = list(map(int, input().split()))\n\n print(f'#{tc}', *code_maker(code))","repo_name":"kkkin02/Algorithm","sub_path":"0303/s1225_암호생성기.py","file_name":"s1225_암호생성기.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21114238351","text":"from bge import logic, types\n# * Imports\nfrom .PlayerStateManagement import *\nfrom .PlayerSound import *\nfrom .SwordTrail import *\nfrom .PlayerContainer import *\nfrom .PlayerCam import *\nfrom .PlayerFightManager import *\nfrom .PlayerPickManager import *\nfrom .PlayerObjectManager import *\nfrom .PlayerOrientation import *\nfrom .PlayerTester import *\nfrom .PlayerSwitchLevel import *\nfrom .PlayerInteraction import *\nfrom link_scripts.PlayerInventory import *\nfrom .PlayerZTargeting import *\n\nfrom .Gamepad import Gamepad\n\nscene = logic.getCurrentScene()\norientController = scene.objects['orientController']\n\nclass Player(types.KX_GameObject):\n\n\tdef __init__(self, own, rig, physic, track_orient, cam):\n\t\t# Init Player\n\t\tself.gamepad = Gamepad()\n\t\tlogic.globalDict['Player']['Gamepad'] = self.gamepad\n\t\tself.rig = rig\n\t\tself.physic = physic\n\t\tself.audio = PlayerSound()\n\t\tself.swordTrail = SwordTrail()\n\t\tself.tester = PlayerTester(self)\n\t\tself.objectManager = PlayerObjectManager(self)\n\t\tself.fightManager = PlayerFightManager(self)\n\t\tself.pickManager = PlayerPickManager(self)\n\t\tself.inventory = PlayerInventory(self)\n\t\tself.interaction = PlayerInteraction()\n\t\tself.levelManager = PlayerLevelManager()\n\t\tself.orientManager = PlayerOrientationManager()\n\t\tself.camManager = PlayerCam(self, cam)\n\t\tself.heartContainer = HeartContainer(3, 3)\n\t\tself.rupeeContainer = RupeeContainer(0, 50)\n\t\tself.targetManager = PlayerZTargeting()\n\t\tself.forward_obj = None\n\t\tself.ledge_ground_obj = None\n\t\tself.detect_water_obj = None\n\t\tself.first_view_obj = None\n\n\t\t# Container var\n\t\tself.heart = 3.0\n\t\tself.forwardForce = 0.0\n\t\tself.forwardMaxForce = 5.0\n\t\tself.fallTime = 0.0\n\t\tself.stateTime = 0.0\n\t\tself.frameCounter = 0\n\t\tself.shufferedDamage = 0.0\n\t\tself.comboAttack = 0\n\t\tself.trackTarget = None\n\t\tself.targetObject = None\n\t\tself.targetObjectData = [None, None]\n\t\tself.lastGroundPos = [0, 0, 0]\n\t\tself.ledgeData = [None, None, None]\n\t\tself.ledgeGroundData = [None, None, None]\n\t\tself.ladderData = [None, None]\n\t\tself.waterPos = None\n\n\t\t# Tester var\n\t\tself.grounded = False\n\t\tself.onLedge = False\n\t\tself.onWater = False\n\t\tself.onLadder = False\n\t\tself.ledgeCanceled = False\n\t\tself.trackObject = False\n\n\t\t# Actuator\n\t\tself.track_orientActuator = track_orient\n\n\t\t# get children object\n\t\tfor obj in self.children:\n\t\t\tif (obj.name == \"first_view\"):\n\t\t\t\tself.first_view_obj = obj\n\n\t\t# Activator\n\t\tself.physic.setPlayer(self)\n\n\t\t# set default\n\t\tself.etat = PlayerState.IDLE_STATE\n\t\tself.etatSecondaire = -1\n\n\tdef loadData(self):\n\t\t# If player global dict exist\n\t\tif 'Player' in logic.globalDict:\n\t\t\tif 'heart' in logic.globalDict['Player']['heartContainer']:\n\t\t\t\theartContainer = logic.globalDict['Player']['heartContainer']\n\t\t\t\tself.heartContainer.load(heartContainer['heart'], heartContainer['maxHeart'])\n\n\tdef stopMovement(self):\n\t\tself.linearVelocity[0] = 0.0\n\t\tself.linearVelocity[1] = 0.0\n\t\tself.forwardForce = 0.0\n\n\tdef cancelAttack(self):\n\t\tself.swordTrail.deactiveTrail()\n\t\t# reset combo\n\t\tself.comboAttack = 0\n\t\t# reset damage\n\t\tsetDamage(0)\n\n\tdef getForwardForce(self):\n\t\t# if joy connected\n\t\tmaxSpeed = 10.0\n\t\tspeed_axis = self.gamepad.getJoyAxis1Value()\n\t\t# apply\n\t\tif (speed_axis > 0.0):\n\t\t\tself.forwardForce = maxSpeed * speed_axis\n\n\t\tif (speed_axis == 0.0):\n\t\t\tself.forwardForce = 0.0\n\n\t\treturn self.forwardForce\n\n\tdef linearMove(self, speed, axis, max=5.0):\n\t\tvelocity = self.linearVelocity[axis]\n\t\t# positif\n\t\tif (speed > 0):\n\t\t\tif ( (velocity + speed) > max):\n\t\t\t\tvelocity = max\n\t\t\telse:\n\t\t\t\tself.linearVelocity[axis] += speed\n\t\t# negatif\n\t\telse:\n\t\t\tif ( (velocity + speed) < max):\n\t\t\t\tvelocity = max\n\t\t\telse:\n\t\t\t\tself.linearVelocity[axis] += speed\n\n\tdef respectGroundRule(self, function, goToFall=True):\n\t\tfrom link_scripts.StarterState import start_fallState\n\n\t\tif (self.tester.detectGround()):\n\t\t\treturn True\n\t\telse:\n\t\t\tif (function != None):\n\t\t\t\tfunction(self)\n\t\t\t# go tofall\n\t\t\tif (goToFall):\n\t\t\t\tstart_fallState(self)\n\t\t\treturn False\n\n\tdef isAlive(self):\n\t\treturn ( not self.heartContainer.notHaveHeart() )\n\n\tdef applyDamage(self):\n\t\tdamage = self.shufferedDamage\n\t\tself.heartContainer.loseHeart(damage)\n\n\tdef alignToTargetObject(self):\n\t\t# If have interaction pos\n\t\thave_i_pos = False\n\t\tnew_pos = [0, 0, 0]\n\t\torient = None\n\t\tfor obj in self.targetObject.children:\n\t\t\tif \"i_pos\" in obj.name :\n\t\t\t\tnew_pos[0] = obj.worldPosition[0]\n\t\t\t\tnew_pos[1] = obj.worldPosition[1]\n\t\t\t\torient = obj.worldOrientation.to_euler()\n\t\t\t\thave_i_pos = True\n\t\t# If find interaction pos apply\n\t\tif (have_i_pos):\n\t\t\tself.worldOrientation = orient\n\t\t\tself.worldPosition[0] = new_pos[0]\n\t\t\tself.worldPosition[1] = new_pos[1]\n\t\telse:\n\t\t\t# Orien from normal hit\n\t\t\thit_normal = self.targetObjectData[1]\n\t\t\tnormal_vec = [-hit_normal[0], -hit_normal[1], hit_normal[2]]\n\t\t\tself.alignAxisToVect(normal_vec, 1, 1)\n\n\tdef playStateTime(self, limit):\n\t\t\"\"\" Play state time with a limit\n\t\t\"\"\"\n\t\tif (self.stateTime < limit):\n\t\t\tself.stateTime += 0.1\n\t\t\treturn False\n\t\telse:\n\t\t\tself.stateTime = limit\n\t\t\treturn True\n\n\tdef unsheat(self, active=True):\n\t\tself.fightManager.unsheat(active)\n\n\tdef switchState(self, next_etat):\n\t\t# if the next state is the idle since applic reset same var\n\t\tif (next_etat == PlayerState.IDLE_STATE):\n\t\t\tself.ledgeCanceled = False\n\t\t# now applic the new state and reset stateTime\n\t\tself.stateTime = 0.0\n\t\tself.etat = next_etat\n\n\tdef setTrackOrient(self, target):\n\t\tif (target == None):\n\t\t\tself.trackTarget = None\n\t\t\tself.trackObject = False\n\t\telse:\n\t\t\tself.trackTarget = target\n\t\t\tself.trackObject = True\n\n\tdef orient(self, cont):\n\t\tif (self.trackTarget == None):\n\t\t\tself.track_orientActuator.object = None\n\t\t\tcont.deactivate(self.track_orientActuator)\n\t\telse:\n\t\t\tself.track_orientActuator.object = self.trackTarget\n\t\t\tcont.activate(self.track_orientActuator)\n\n\tdef respawnToGround(self):\n\t\tself.stopMovement()\n\t\t# stop orientation\n\t\tself.orientManager.stopOrientation(self)\n\t\tself.worldPosition = self.lastGroundPos\n\t\tself.worldPosition[2] = self.lastGroundPos[2] + + 1.2\n\t\tself.grounded = True\n\t\tself.fallTime = 0.0\n\t\tself.switchState(PlayerState.IDLE_STATE)\n\n\tdef main(self, cont):\n\t\t# If player alive update\n\t\tif ( self.isAlive() ):\n\t\t\t# Pause menu\n\t\t\tif (self.gamepad.isPausePressed(logic.KX_INPUT_JUST_ACTIVATED)):\n\t\t\t\tlogic.playerHUD.displayInventory()\n\t\t\t\tself.scene.suspend()\n\n\t\t\t# Process parry system\n\t\t\tself.targetManager.update()\n\n\t\t\t# update joystick/gamepad\n\t\t\tself.gamepad.updateJoystick()\n\n\t\t\t# Test if can always pick object\n\t\t\tself.pickManager.canAlwaysHold()\n\n\t\t\t# sword trail\n\t\t\tself.swordTrail.updateTrail()\n\n\t\t\t# Level manager\n\t\t\tif (self.tester.switchLevel()):\n\t\t\t\treturn\n\n\t\t\t# If detect black hole\n\t\t\tif (self.tester.detectBlackHole() ):\n\t\t\t\tself.respawnToGround()\n\t\t\t\treturn\n\n\t\t\t# track object\n\t\t\tif (self.targetManager.active):\n\t\t\t\tself.targetManager.updateTargetMode()\n\t\t\telse:\n\t\t\t\t# Find targetable object\n\t\t\t\tself.targetManager.findObject()\n\t\t\t\t# update axis orient\n\t\t\t\tself.orientManager.updateOrientController(self.worldPosition, scene.active_camera.worldOrientation.to_euler())\n\t\t\t#self.orient(cont)\n\n\t\t\t# If touch the ground, active ground physic else fall gravity\n\t\t\tif (self.grounded and self.onWater == False):\n\t\t\t\tself.physic.onGround()\n\t\t\telse :\n\t\t\t\tif (self.onLedge == False and self.onWater == False and self.onLadder == False):\n\t\t\t\t\tself.physic.gravity_fall()\n\n\t\t\t# Cam view and update\n\t\t\tself.camManager.cameraViewControl(self.gamepad)\n\n\t\t\t# Update mini map\n\t\t\tlogic.playerHUD.updateMiniMap()\n\n\t\t# update state management\n\t\tmanagePlayerState(self)\n\t\tself.camManager.main()\n\t\t# update global dic data\n\t\tlogic.player = self\n\t\tlogic.globalDict['player'] = self\n","repo_name":"Dynamique-Zak/Zelda_BlenderGame","sub_path":"chars/link_scripts/PlayerClass.py","file_name":"PlayerClass.py","file_ext":"py","file_size_in_byte":7594,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"3"}
+{"seq_id":"30415989351","text":"import math\n\ndef f_gold ( n , k ) :\n while ( n % 2 == 0 ) :\n k = k - 1\n n = n / 2\n if ( k == 0 ) :\n return 2\n i = 3\n while i <= math.sqrt ( n ) :\n while ( n % i == 0 ) :\n if ( k == 1 ) :\n return i\n k = k - 1\n n = n / i\n i = i + 2\n if ( n > 2 and k == 1 ) :\n return n\n return - 1\n\n\n#TOFILL\n\nif __name__ == '__main__':\n param = [\n (94,0),\n (99,1),\n (64,3),\n (27,3),\n (24,4),\n (84,6),\n (69,98),\n (69,39),\n (22,60),\n (39,57)\n ]\n n_success = 0\n for i, parameters_set in enumerate(param):\n if f_filled(*parameters_set) == f_gold(*parameters_set):\n n_success+=1\n print(\"#Results: %i, %i\" % (n_success, len(param)))\n","repo_name":"facebookresearch/TransCoder","sub_path":"data/evaluation/geeks_for_geeks_successful_test_scripts/python/K_TH_PRIME_FACTOR_GIVEN_NUMBER.py","file_name":"K_TH_PRIME_FACTOR_GIVEN_NUMBER.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":1646,"dataset":"github-code","pt":"3"}
+{"seq_id":"27469645734","text":"from django.urls import path, reverse_lazy\nfrom django.views.generic import TemplateView\nfrom paciente.models import RegistroPaciente\nfrom paciente.forms import RegistroPacienteForm\nfrom configuraciones.views import (PaisAutoComplete, EstadoAutoComplete,\n MunicipioAutoComplete, CiudadAutoComplete, ParroquiaAutoComplete)\nfrom paciente.views import (ListadoPaciente, RegistroPacienteView)\n\napp_name = 'paciente'\nurlpatterns = [\n # #################### Servicios de auto completado #################### #\n path(\n 'pais/', \n PaisAutoComplete.as_view(), \n name='pais'\n ),\n path(\n 'estado/',\n EstadoAutoComplete.as_view(),\n name='estado'\n ),\n path(\n 'municipio/',\n MunicipioAutoComplete.as_view(),\n name='municipio'\n ),\n path(\n 'ciudad/',\n CiudadAutoComplete.as_view(),\n name='ciudad'\n ),\n path(\n 'parroquia/',\n ParroquiaAutoComplete.as_view(),\n name='parroquia'\n ),\n # ################ rutas para los template paciente #################### #\n path( #listar\n 'listado/', \n ListadoPaciente.as_view(\n template_name = 'paciente_listar.html',\n extra_context = {'titulo': 'Listado General', 'title':'Historias Médicas'},\n ), \n name='lista-paciente'\n ),\n path( #Detalle\n 'listado/detalle', \n TemplateView.as_view(\n template_name='paciente_detalle.html',\n extra_context = {'titulo': 'Paciente'}\n ), \n name='detalle-paciente'\n ),\n path( #Eliminar\n 'listado/eliminar', \n TemplateView.as_view(\n template_name='paciente_eliminar.html',\n extra_context = {'titulo': 'Paciente'}\n ), \n name='eliminar-paciente'\n ),\n path( #agregar\n 'registro/agregar',\n RegistroPacienteView.as_view(\n model=RegistroPaciente,\n form_class=RegistroPacienteForm,\n template_name='paciente_formulario.html',\n extra_context={'titulo': 'Registro', 'title': 'Registro de Paciente'},\n success_url=reverse_lazy('paciente:lista-paciente'),\n success_message='Paciente Nuevo, Registro Éxitoso'\n ), \n name='registro-paciente'\n ),\n \n]\n\n","repo_name":"desktopjs1622/proyecto-hospital","sub_path":"paciente/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5516590777","text":"def firstCountTest():\n counts = dict()\n names = ['csev','cwen','cwen','zqian','csev']\n for name in names:\n counts[name] = counts.get(name,0) + 1\n print(counts)\n\ndef createDictFromFile(fileName):\n myDict = dict()\n\n with open(fileName,'r',encoding='utf8') as f:\n for ln in f.readlines():\n for word in ln.split():\n myDict[word] = myDict.get(word,0) + 1\n\n #Getting the most common word\n bigWord = None\n bigCount = None\n for k,v in myDict.items():\n if bigCount is None or v > bigCount:\n bigWord = k\n bigCount = v\n \n print('The most common word in {} is \"{}\" with {} ocurrences.'.format(fileName,bigWord,bigCount))\n\n\nif __name__ == \"__main__\":\n createDictFromFile('../aleph.txt')","repo_name":"xdaco1/pythonClasses","sub_path":"edx/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5128340306","text":"from flask import Blueprint, render_template, request, session, redirect, url_for\nfrom App.DataBase.TeacherMapper import *\nfrom App.Model.staticData import *\n\nteacher = Blueprint(\"teacher\", __name__)\n\n\n# 用户信息验证及显示\n@teacher.route('/info', methods=['GET', 'POST'])\ndef bkControl():\n if request.method == 'POST':\n phone = request.form.get('phone')\n pwd = request.form.get('pwd')\n if isLoginRight(phone, pwd):\n user = getTeacherTeacherDataById(phone)\n session[\"phone\"] = user.phone\n session[\"picture\"] = user.picture\n return render_template('backBase.html', user=user)\n return render_template(\"register.html\", allClass=getAllClasses())\n else:\n if session[\"nickname\"]:\n user = getTeacherTeacherDataById(session[\"uid\"])\n return render_template('backBase.html', user=user)\n\n\n# 获取用户信息\n@teacher.route(\"/getInfo/\")\ndef getUserInfo(phone):\n return getTeacherTeacherDataById(phone)\n\n\n# 修改用户信息\n@teacher.route(\"/updateInfo\", methods=[\"GET\", \"POST\"])\ndef updateUserInfo():\n user = MJ.setDicToTeacher(request.json)\n return updateTeacherData(user)\n\n\n# 修改用户密码\n@teacher.route(\"/updatePwd\", methods=[\"GET\", \"POST\"])\ndef updateUserPasswd():\n uid = request.json.get(\"uid\")\n pwd = request.json.get(\"pwd\")\n return updateTeacherPwd(uid, pwd)\n\n@teacher.route(\"delete/\")\ndef deleteUserInfo(id):\n return deleteTeacherData(id)\n\n","repo_name":"DanceCode520/ZQWZBk","sub_path":"App/Views/TeacherView.py","file_name":"TeacherView.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70682619923","text":"import requests\nimport re\nimport json\nfrom multithreading import thread\n# 单线程下载 \nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',\n}\n\nurl = input(\"请输入视频地址:\")\nwith open('SESSDATA.txt', 'r') as f:\n SESSDATA = f.read()\nif SESSDATA == '0':\n print('检测到您未设置SESSDATA,最高只能下载480p画质哦!')\n#获取BV号\nif '?' in url:\n url = url.split('?')[0]\n print(url)\nbvid = re.search(r'BV.*', url).group()\nprint('BV号:'+bvid)\n#获取cid\ncid_json = requests.get('https://api.bilibili.com/x/player/pagelist?bvid={}&jsonp=jsonp'.format(bvid)).text\ncid = re.search(r'{\"cid\":(\\d+)', cid_json).group()[7:]\nprint('CID:'+cid)\n\n#获取视频的av号\nrsp = requests.get(url, headers=headers)\naid = re.search(r'\"aid\":(.*?),\"', rsp.text).group()[6:-2]\nprint('AV号:'+aid)\n\n#抓取视频真实地址,清晰度\nqn = 16 #先设置一个默认低清晰度\nheaders['Referer'] = url\napi_url = 'https://api.bilibili.com/x/player/playurl?cid={}&avid={}&qn={}&otype=json&requestFrom=bilibili-helper'.format(cid, aid, qn)\nqn_dict = {}#用来存放清晰度选择参数\nrsp = requests.get(api_url, headers=headers).content\nrsp = json.loads(rsp)\nqn_accept_description = rsp.get('data').get('accept_description')\nqn_accept_quality = rsp.get('data').get('accept_quality')\nprint('下载视频清晰度选择')\nfor i, j, xuhao in zip(qn_accept_description, qn_accept_quality, range(len(qn_accept_quality))):\n print(str(xuhao+1)+':'+i)\n qn_dict[str(xuhao+1)] = j\nxuhao = input('请选择(输入清晰度前的标号):')\nqn = qn_dict[xuhao]\nprint('清晰度参数qn:'+str(qn))\napi_url = 'https://api.bilibili.com/x/player/playurl?cid={}&avid={}&qn={}&otype=json&requestFrom=bilibili-helper'.format(cid, aid, qn)\n#print('api_url='+api_url)\ncookies = {}\ncookies['SESSDATA'] = SESSDATA #这里输入你的SESSDATA\nrsp = requests.get(api_url, headers=headers, cookies=cookies).content #这里代cookies才能得到会员或者登录后才能下载的视频的链接\nrsp = json.loads(rsp)\nreal_url = rsp.get('data').get('durl')[0].get('url')\nprint('成功获取视频直链!')\nprint('正在开启多线程极速下载……')\nthread(real_url, url, 'b站视频.flv')#多线程下载\n\n#把上面那行删掉,把下面注释去掉就是单线程下载\n#content = requests.get(real_url, headers=headers).content\n#with open('1.flv', 'wb') as f:\n# f.write(content)\n\n\n# 多线程下载 \nimport requests\nimport threading\nimport datetime\nimport time\n#改headers参数和url就好了\ndef thread(url, Referer, file_name):\n # print(r.status_code, r.headers)\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',\n 'Referer': Referer\n }\n r = requests.get(url, headers=headers, stream=True, timeout=30)\n all_thread = 1\n # 获取视频大小\n file_size = int(r.headers['content-length'])\n # 如果获取到文件大小,创建一个和需要下载文件一样大小的文件\n if file_size:\n fp = open(file_name, 'wb')\n fp.truncate(file_size)\n print('视频大小:' + str(int(file_size / 1024 / 1024)) + \"MB\")\n fp.close()\n # 每个线程每次下载大小为5M\n size = 5242880\n # 当前文件大小需大于5M\n if file_size > size:\n # 获取总线程数\n all_thread = int(file_size / size)\n # 设最大线程数为10,如总线程数大于10\n # 线程数为10\n if all_thread > 10:\n all_thread = 10\n part = file_size // all_thread\n threads = []\n starttime = datetime.datetime.now().replace(microsecond=0)\n for i in range(all_thread):\n # 获取每个线程开始时的文件位置\n start = part * i\n # 获取每个文件结束位置\n if i == all_thread - 1:\n end = file_size\n else:\n end = start + part\n if i > 0:\n start += 1\n headers = headers.copy()\n headers['Range'] = \"bytes=%s-%s\" % (start, end)\n t = threading.Thread(target=Handler, name='线程-' + str(i),\n kwargs={'start': start, 'end': end, 'url': url, 'filename': file_name, 'headers': headers})\n t.setDaemon(True)\n threads.append(t)\n # 线程开始\n for t in threads:\n time.sleep(0.2)\n t.start()\n # 等待所有线程结束\n print('正在下载……')\n for t in threads:\n t.join()\n endtime = datetime.datetime.now().replace(microsecond=0)\n print('下载完成!用时:%s' % (endtime - starttime))\ndef Handler(start, end, url, filename, headers={}):\n tt_name = threading.current_thread().getName()\n print(tt_name + ' 已启动')\n r = requests.get(url, headers=headers, stream=True)\n total_size = end - start\n downsize = 0\n startTime = time.time()\n with open(filename, 'r+b') as fp:\n fp.seek(start)\n var = fp.tell()\n for chunk in r.iter_content(204800):\n if chunk:\n fp.write(chunk)\n downsize += len(chunk)\n line = tt_name + '-downloading %d KB/s - %.2f MB, 共 %.2f MB'\n line = line % (\n downsize / 1024 / (time.time() - startTime), downsize / 1024 / 1024,\n total_size / 1024 / 1024)\n print(line, end='\\r')\nif __name__ == '__main__':\n url = input('输入视频链接(请输入视频原链):')\n thread(url)","repo_name":"jihaikang/2021-","sub_path":"5_29/wuai_11B站视频多线程下载.py","file_name":"wuai_11B站视频多线程下载.py","file_ext":"py","file_size_in_byte":5301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22752555881","text":"import typing as t\n\nfrom ellar.common.interfaces import IHostContext, IHostContextFactory\nfrom ellar.common.types import ASGIApp, TReceive, TScope, TSend\nfrom ellar.core.connection import HTTPConnection\nfrom starlette.responses import Response\n\nAwaitableCallable = t.Callable[..., t.Awaitable]\nDispatchFunction = t.Callable[\n [IHostContext, AwaitableCallable], t.Awaitable[t.Optional[Response]]\n]\nT = t.TypeVar(\"T\")\n\n\nclass FunctionBasedMiddleware:\n \"\"\"\n Convert ASGI Middleware to a Node-like Middleware.\n\n Usage: Example 1\n @middleware()\n def my_middleware(context: IExecution, call_next):\n print(\"Called my_middleware\")\n request = context.switch_to_http_connection().get_request()\n request.state.my_middleware = True\n await call_next()\n\n Usage: Example 2\n @middleware()\n def my_middleware(context: IExecution, call_next):\n print(\"Called my_middleware\")\n response = context.switch_to_http_connection().get_response()\n response.content = \"Some Content\"\n response.status_code = 200\n return response\n \"\"\"\n\n def __init__(\n self, app: ASGIApp, dispatch: t.Optional[DispatchFunction] = None\n ) -> None:\n self.app = app\n self.dispatch_function = dispatch or self.dispatch\n\n async def dispatch(\n self, context: IHostContext, call_next: AwaitableCallable\n ) -> Response:\n raise NotImplementedError() # pragma: no cover\n\n async def __call__(self, scope: TScope, receive: TReceive, send: TSend) -> None:\n if scope[\"type\"] not in (\"http\", \"websocket\"):\n await self.app(scope, receive, send)\n return\n\n connection = HTTPConnection(scope, receive)\n\n if not connection.service_provider: # pragma: no cover\n raise Exception(\"Service Provider is required\")\n\n context_factory = connection.service_provider.get(IHostContextFactory)\n context = context_factory.create_context(scope, receive, send)\n\n async def call_next() -> None:\n await self.app(scope, receive, send)\n\n response = await self.dispatch_function(context, call_next)\n\n if response and isinstance(response, Response):\n await response(scope, receive, send)\n","repo_name":"eadwinCode/ellar","sub_path":"ellar/core/middleware/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"3"}
+{"seq_id":"22328090183","text":"'''\n题目:输入一个链表,从尾到头打印链表每个节点的值\n'''\n\n'''\n使用insert直接在头部插入\n时间 26ms\n内存 6336k\n'''\n\n# -*- coding:utf-8 -*-\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # 返回从尾部到头部的列表值序列,例如[1,2,3]\n def printListFromTailToHead(self, listNode):\n if not listNode:\n return []\n result = []\n head = listNode\n while head:\n result.insert(0, head.val)\n head = head.next\n return result\n","repo_name":"gaofeil/Algorithm-code-python","sub_path":"剑指offer/3从尾到头打印链表.py","file_name":"3从尾到头打印链表.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42492001835","text":"import numpy as np\nimport pandas as pd\nimport collections\nimport datetime\n\nfrom ..schema.default import ColumnSynonym\nfrom ..misspell.simple import SimpleMisspell\n\n\nclass TableTransformer(object):\n def __init__(self, ref_data):\n self.ref_data = ref_data\n self.data = ref_data.copy()\n self.data[\"visit_date_dt\"] = pd.to_datetime(self.data[\"visit_date\"])\n self.data[\"birth_date_dt\"] = pd.to_datetime(self.data[\"birth_date\"])\n self.data[\"uid\"] = list(self.data[\"identifier\"])\n\n def _select_idxs(self, rate, n=None):\n if n is None:\n n = self.data.shape[0]\n f = int(n * rate)\n idxs = [i for i in range(n)]\n return np.random.choice(idxs, f, replace=False)\n\n def _column_as_list(self, column):\n return list(self.data[column])\n\n def _abbreviate_full_name(self, rate):\n idxs = self._select_idxs(rate)\n names = self._column_as_list(\"full_name\")\n for i in idxs:\n name = names[i].split(\" \")\n name = \" \".join([name[0][0]] + name[1:])\n names[i] = name\n self.data[\"full_name\"] = names\n\n def _age_coverage(self, cov):\n idxs = self._select_idxs(1 - cov)\n col = self._age_format\n age_data = self._column_as_list(col)\n for i in idxs:\n age_data[i] = np.nan\n self.data[col] = age_data\n\n def _choose_age_format(self, format):\n age_cols = [\"birth_date\", \"birth_year\", \"age\"]\n rm_cols = [a for a in age_cols if a != format]\n self._age_format = format\n self.data = self.data.drop(columns=rm_cols)\n\n def _date_format(self, format):\n if format != \"%Y-%m-%d\":\n self.data[\"visit_date\"] = self.data[\"visit_date_dt\"].dt.strftime(format)\n if \"birth_date\" in list(self.data.columns):\n self.data[\"birth_date\"] = self.data[\"birth_date_dt\"].dt.strftime(format)\n if \"entry_date\" in list(self.data.columns):\n self.data[\"entry_date\"] = self.data[\"entry_date_dt\"].dt.strftime(format)\n\n def _date_coverage(self, cov, col=None):\n idxs = self._select_idxs(1 - cov)\n if col is None:\n col = \"visit_date\"\n dates = self._column_as_list(col)\n for i in idxs:\n dates[i] = np.nan\n self.data[col] = dates\n\n def _full_name_format(self, format):\n names = self._column_as_list(\"full_name\")\n if format == \"title\":\n names = [n.title() for n in names]\n elif format == \"lower\":\n names = [n.lower() for n in names]\n elif format == \"upper\":\n names = [n.upper() for n in names]\n else:\n pass\n self.data[\"full_name\"] = names\n\n def _full_name_coverage(self, cov):\n idxs = self._select_idxs(1 - cov)\n if \"full_name\" in list(self.data.columns):\n names = self._column_as_list(\"full_name\")\n for i in idxs:\n names[i] = np.nan\n self.data[\"full_name\"] = names\n else:\n fnames = self._column_as_list(\"first_name\")\n lnames = self._column_as_list(\"last_name\")\n for i in idxs:\n fnames[i] = np.nan\n lnames[i] = np.nan\n self.data[\"first_name\"] = fnames\n self.data[\"last_name\"] = lnames\n\n def _hide_identifier(self):\n self.data = self.data.drop(columns=\"identifier\")\n\n def _identifier_coverage(self, cov):\n col = \"identifier\"\n ids = self._column_as_list(col)\n ids_idxs = collections.defaultdict(list)\n for i, id in enumerate(ids):\n ids_idxs[id] += [i]\n uids = [k for k, v in ids_idxs.items()]\n idxs = self._select_idxs(1 - cov, len(uids))\n for i in idxs:\n for j in ids_idxs[uids[i]]:\n ids[j] = np.nan\n self.data[col] = ids\n\n def _misspell_full_name(self, rate, misspeller):\n if misspeller is None:\n ms = SimpleMisspell()\n else:\n ms = misspeller\n idxs = self._select_idxs(rate)\n names = self._column_as_list(\"full_name\")\n js = np.random.choice([0, 1], len(idxs), replace=True)\n for i, j in zip(idxs, js):\n name = names[i].split(\" \")\n if len(name) == 0:\n j = 0\n ms_ = ms.misspell(name[j], n=1)[0]\n if ms_:\n name[j] = ms_\n names[i] = \" \".join(name)\n self.data[\"full_name\"] = names\n\n def _rename_columns(self, cap_type=None, syn_option=None):\n cs = ColumnSynonym()\n if cap_type is None:\n cap_type = cs.style()\n new_cols = {}\n for col in list(self.data.columns):\n new_cols[col] = cs.rename(col, cap_type=cap_type, syn_option=syn_option)\n self.data = self.data.rename(columns=new_cols)\n\n def _sex_format(self, format):\n if format != \"lower_abbrv\":\n sexs = self._column_as_list(\"sex\")\n if format == \"upper_abbrv\":\n sexs = [s.upper() for s in sexs]\n if format == \"lower\":\n sexs_ = []\n for s in sexs:\n if s[0] == \"m\":\n sexs_ += [\"male\"]\n else:\n sexs_ += [\"female\"]\n sexs = sexs_\n if format == \"title\":\n sexs_ = []\n for s in sexs:\n if s[0] == \"m\":\n sexs_ += [\"Male\"]\n else:\n sexs_ += [\"Female\"]\n sexs = sexs_\n if format == \"binary\":\n sexs_ = []\n for s in sexs:\n if s[0] == \"m\":\n sexs_ += [1]\n else:\n sexs_ += [0]\n sexs = sexs_\n self.data[\"sex\"] = sexs\n\n def _shuffle_columns(self):\n columns = list(self.data.columns)\n columns.shuffle()\n self.data = self.data[columns]\n\n def _sort_by_date(self):\n self.data = self.data.sort_values(by=\"visit_date_dt\").reset_index(drop=True)\n\n def _split_full_name(self):\n names = self._column_as_list(\"full_name\")\n first_names = []\n last_names = []\n for name in names:\n name = name.split(\" \")\n if len(name) == 1:\n first_names += [np.nan]\n last_names += name\n else:\n first_names += [name[0]]\n last_names += [\" \".join(name[1:])]\n columns = list(self.data.columns)\n idx = columns.index(\"full_name\")\n if idx == 0:\n columns = [\"first_name\", \"last_name\"] + columns[1:]\n else:\n columns = columns[:idx] + [\"first_name\", \"last_name\"] + columns[(idx + 1) :]\n self.data[\"first_name\"] = first_names\n self.data[\"last_name\"] = last_names\n self.data = self.data[columns]\n\n def _swap_full_name(self, rate):\n idxs = self._select_idxs(rate)\n names = self._column_as_list(\"full_name\")\n for i in idxs:\n name = names[i].split(\" \")\n name.reverse()\n names[i] = \" \".join(name)\n self.data[\"full_name\"] = names\n\n def _extra_date(self):\n format = \"%Y-%m-%d\"\n dates = list(self.data[\"visit_date_dt\"])\n days = np.random.uniform(low=0, high=365, size=len(dates))\n edates = []\n for date, day in zip(dates, days):\n edates += [date + datetime.timedelta(int(day))]\n self.data[\"entry_date_dt\"] = edates\n self.data[\"entry_date\"] = self.data[\"entry_date_dt\"].dt.strftime(format)\n\n def _clinical_variable(self):\n do = np.random.choice([0, 1])\n n = self.data.shape[0]\n if do == 0:\n options = [0, 1]\n else:\n options = [\"Positive\", \"Negative\"]\n values = np.random.choice(options, n, replace=True)\n self.data[\"clinical_variable\"] = values\n\n def transform(self, params):\n\n self._has_extra_date = False\n if \"extra_date\" in params:\n if params[\"extra_date\"]:\n self._extra_date()\n self._has_extra_date = True\n\n if \"sort_by_date\" in params:\n if params[\"sort_by_date\"]:\n self._sort_by_date()\n\n if \"age_format\" in params:\n self._choose_age_format(params[\"age_format\"])\n\n if \"date_format\" in params:\n self._date_format(params[\"date_format\"])\n\n if \"age_coverage\" in params:\n self._age_coverage(params[\"age_coverage\"])\n\n if \"date_coverage\" in params:\n self._date_coverage(params[\"date_coverage\"])\n if self._has_extra_date:\n self._date_coverage(params[\"date_coverage\"], \"entry_date\")\n\n if \"identifier_coverage\" in params:\n self._identifier_coverage(params[\"identifier_coverage\"])\n\n if \"hide_identifier\" in params:\n if params[\"hide_identifier\"]:\n self._hide_identifier()\n\n if \"misspell_full_name\" in params:\n if \"misspeller\" not in params:\n misspeller = None\n else:\n misspeller = params[\"misspeller\"]\n self._misspell_full_name(params[\"misspell_full_name\"], misspeller)\n\n if \"swap_full_name\" in params:\n self._swap_full_name(params[\"swap_full_name\"])\n\n if \"abbreviate_full_name\" in params:\n self._abbreviate_full_name(params[\"abbreviate_full_name\"])\n\n if \"name_format\" in params:\n self._full_name_format(params[\"name_format\"])\n\n if \"sex_format\" in params:\n self._sex_format(params[\"sex_format\"])\n\n if \"shuffle_columns\" in params:\n if params[\"shuffle_columns\"]:\n self._shuffle_columns()\n\n if \"split_full_name\" in params:\n if params[\"split_full_name\"]:\n self._split_full_name()\n\n if \"name_coverage\" in params:\n self._full_name_coverage(params[\"name_coverage\"])\n\n if \"clinvar\" in params:\n self._clinical_variable()\n\n self.uid = list(self.data[\"uid\"])\n cols2drop = list(\n set(\n [\"visit_date_dt\", \"birth_date_dt\", \"entry_date_dt\", \"uid\"]\n ).intersection(list(self.data.columns))\n )\n self.data = self.data.drop(columns=cols2drop)\n self.data.fillna(\"\", inplace=True)\n\n header = params[\"header\"]\n self._rename_columns(cap_type=header[0], syn_option=header[1])\n\n def reset(self):\n return TableTransformer(self.ref_data.copy())\n","repo_name":"ersilia-os/cidrz-e2e-linkage","sub_path":"e2elink/synthetic/tablegen/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":10623,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"27894318797","text":"from sklearn.feature_extraction.text import TfidfVectorizer\ndef calculatescore(documents):\n tfidf_vectorizer = TfidfVectorizer()\n tfidf_matrix = tfidf_vectorizer.fit_transform(documents)\n from sklearn.metrics.pairwise import cosine_similarity\n result=cosine_similarity(tfidf_matrix, tfidf_matrix)\n return result\n\n\n\nlist_of_input=[]\nwith open('D:\\\\education\\\\python\\\\twiiter.txt','r') as f:\n for line in f:\n key_value=line.split('\\t')\n list_of_input.append(key_value[1])\n##################phase one clustering##########################\nlist_of_clusters=[]\nprint(\"the number of tweets is \")\nprint(len(list_of_input))\nlist_of_messages=[]\ncount=0\nproxmitymatrix=calculatescore(list_of_input)\nfor i in range(0,len(list_of_input)):\n\n if proxmitymatrix[i][0]!=0:\n print(\"****************************************************************************************\")\n dict_of_cluster=[]\n dict_of_cluster.append(list_of_input[i])\n print(list_of_input[i])\n count=count+1\n for j in range(i+1,len(list_of_input)):\n if proxmitymatrix[j][0]!=0 and proxmitymatrix[i][j]>=1.0:\n #print(dict[keys_list[j]])\n dict_of_cluster.append(list_of_input[j])\n proxmitymatrix[j][0]=0\n print(list_of_input[j])\n count=count+1\n\n #dict_of_cluster_message={}\n #dict_of_cluster_message[dict[keys_list[i]]]=dict_of_cluster\n list_of_clusters.append(dict_of_cluster)\n\n list_of_messages.append(list_of_input[i])\nprint (\"the processed tweets is %d\" %count)\nprint(\"after phase1 no of clusters formed is %d\" %len(list_of_clusters))\nprint(list_of_clusters)\nprint(list_of_messages)\n\n\n\n","repo_name":"naveen56/Clustering-of-tweets","sub_path":"tweetanalysis/cosinesimilarity.py","file_name":"cosinesimilarity.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10135229402","text":"import sys\nimport logging\nimport os\nfrom .batchfile import Batchfile, QuitProgram\n\n\ndef main_loop(loops=-1, bat=None):\n log = logging.getLogger(__package__)\n log.setLevel(logging.INFO)\n handler = logging.StreamHandler(sys.stdout)\n formatter = logging.Formatter(\"%(message)s\")\n handler.setFormatter(formatter)\n log.addHandler(handler)\n\n bat = bat if bat is not None else Batchfile()\n\n if len(sys.argv) > 1:\n bat.run(sys.argv)\n\n print(\"\\nBatchfile.py\")\n print(\"Type EXIT to quit, or use Ctrl+C\")\n\n while loops != 0:\n try:\n ch = bat.line_input(f\"{os.getcwd()}>\")\n if ch == \"exit\":\n break\n try:\n bat.run(ch)\n except (EOFError, KeyboardInterrupt):\n raise\n except Exception as e:\n print(f'<{type(e).__name__}: \"{e}\">')\n except (EOFError, KeyboardInterrupt, QuitProgram):\n break\n loops -= 1\n\n\nif __name__ == \"__main__\":\n main_loop()\n","repo_name":"tassaron/batchfile.py","sub_path":"batchfile/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"7106937696","text":"from typing import List\n\n\nclass Experience:\n def __init__(self, exp_id: str, title: str, substances_details: list, story: List[str],\n substances_simple: List[str], metadata: dict, tags: List[dict]):\n self.exp_id: str = exp_id\n self.title: str = title\n self.substances_details: list = substances_details\n self.story: List[str] = story\n self.substances_simple: List[str] = substances_simple\n self.metadata: dict = metadata\n self.tags: List[dict] = tags\n","repo_name":"albertocarot1/drugs-satisfaction","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23017007256","text":"from django_markup.filter import MarkupFilter\n\n\nclass RstMarkupFilter(MarkupFilter):\n \"\"\"\n Converts a reStructuredText string to HTML. If the pygments library is\n installed you can use a special `sourcecode` directive to highlight\n portions of your text. Example:\n\n .. sourcecode: python\n\n def foo():\n return 'foo'\n \"\"\"\n\n title = \"reStructuredText\"\n rst_part_name = \"html_body\"\n kwargs = {\n \"settings_overrides\": {\n \"raw_enabled\": False,\n \"file_insertion_enabled\": False,\n },\n }\n\n def render(self, text, **kwargs):\n if kwargs:\n self.kwargs.update(kwargs)\n from docutils import core\n\n publish_args = {\"source\": text, \"writer_name\": \"html4css1\"}\n publish_args.update(**self.kwargs)\n parts = core.publish_parts(**publish_args)\n return parts[self.rst_part_name]\n","repo_name":"bartTC/django-markup","sub_path":"django_markup/filter/rst_filter.py","file_name":"rst_filter.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":143,"dataset":"github-code","pt":"3"}
+{"seq_id":"23819036136","text":"#time complexity : O(nlogn)\r\n#space complexity : O(n)\r\n\r\n# Returns sum of maximum sum subarray in arr[low.....high]\r\ndef maxSumSubArray(arr, low, high) :\r\n # Base Case\r\n if (low == high) :\r\n return arr[low]\r\n # Find middle element\r\n mid = low + ((high - low) // 2)\r\n # Return maximum of left ,right and mid crossing\r\n return max(maxSumSubArray(arr, low, mid),\r\n maxSumSubArray(arr, mid+1, high),\r\n maxSumCrossing(arr, low, mid, high))\r\n\r\n# Find the maximum possible sum in arr[] such that arr[m] is part of it\r\ndef maxSumCrossing(arr, low, mid, high) :\r\n # Include elements on left of mid.\r\n summ = 0; left_sum = -10000\r\n for i in range(mid, low-1, -1) :\r\n summ = summ + arr[i]\r\n if (summ > left_sum) :\r\n left_sum = summ\r\n # Include elements on right of mid\r\n summ = 0; right_sum = -1000\r\n for i in range(mid + 1, high + 1) :\r\n summ = summ + arr[i]\r\n if (summ > right_sum) :\r\n right_sum = summ\r\n return max(left_sum + right_sum, left_sum, right_sum)\r\n\r\n# Driver Code\r\n# creating an empty list\r\nlistt = []\r\n# number of elements as input\r\nn = int(input(\"Enter number of elements in arr : \"))\r\n# iterating till the range\r\nfor i in range(0, n):\r\n element = int(input())\r\n listt.append(element) # adding the element\r\nprint(\"input array is : \",listt)\r\nn = len(listt)\r\nmax_sum = maxSumSubArray(listt, 0, n-1)\r\nprint(\"Maximum contiguous sum is \", max_sum)\r\n\r\n#sample test case \r\n#input array : [1, 3, 2, 4, 7] [1,-1,2,3,-2] [0,1,-1,0,0] [2] [-1,-1,-1,-1,-1]\r\n#output : 17 5 1 2 -1\r\n","repo_name":"HarshCasper/NeoAlgo","sub_path":"Python/cp/maxsum_subarray_python.py","file_name":"maxsum_subarray_python.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":873,"dataset":"github-code","pt":"3"}
+{"seq_id":"14663467714","text":"import json\r\nimport logging\r\nimport os\r\nimport re\r\n\r\nfrom processing.extract_topic import ExtractNews\r\nfrom utilities.const import (\r\n LOG_PATH,\r\n STOCK_VIDEO_FOLDER,\r\n OUTPUT_TMP,\r\n OUTPUT_FINAL_VIDEO,\r\n OUTPUT_FINAL_INFO,\r\n get_current_date,\r\n NEWS_API_KEY,\r\n EXISTING_TOPICS,\r\n)\r\nfrom utilities.create_directories import create_directories\r\nfrom video.create_vd import VideoProcessor\r\nfrom video.subtitle import VideoTextOverlay, AddAudio\r\n\r\n\r\nclass MultiLogger:\r\n def __init__(self, name, file_path, log_to_console=True):\r\n self.logger = logging.getLogger(name)\r\n self.logger.setLevel(logging.INFO)\r\n formatter = logging.Formatter('[%(levelname)s] %(message)s')\r\n\r\n # File Handler\r\n file_handler = logging.FileHandler(file_path)\r\n file_handler.setFormatter(formatter)\r\n self.logger.addHandler(file_handler)\r\n\r\n # Console Handler\r\n if log_to_console:\r\n console_handler = logging.StreamHandler()\r\n console_handler.setFormatter(formatter)\r\n self.logger.addHandler(console_handler)\r\n # create project directories mention\r\n create_directories()\r\n\r\n def get_logger(self):\r\n return self.logger\r\n\r\n\r\nlogger = MultiLogger(\"AutoYT\", LOG_PATH).get_logger()\r\n\r\n\r\ndef _news(news_api):\r\n news_extractor = ExtractNews(news_api)\r\n generated_files_response = news_extractor.process_data\r\n logger.info(f\"generated_files_response {generated_files_response}\")\r\n generate_video(generated_files_response)\r\n\r\n\r\ndef generate_video(generated_files_response):\r\n final_json = []\r\n for item in generated_files_response:\r\n audio_file_name = item[\"audio_file_name\"]\r\n transcript_file_name = item[\"transcript_file_name\"]\r\n if audio_file_name or transcript_file_name:\r\n logger.info(\"transcript_file_name or transcript_file_name not found\")\r\n link = item.get(\"link\", [])\r\n category = item[\"category\"]\r\n keywords = item.get(\"keywords\", [])\r\n title = item.get(\"title\", [])\r\n logger.info(f\"Audio File Name:{audio_file_name}\")\r\n logger.info(f\"Transcript File Name:{transcript_file_name}\")\r\n logger.info(f\"Link:{link}\")\r\n logger.info(f\"Category:{category}\")\r\n logger.info(f\"Keywords:{keywords}\")\r\n logger.info(f\"title:{title}\")\r\n\r\n re_title = re.sub('[^A-Za-z0-9]+', '', title)\r\n if check_and_add_topic(re_title, EXISTING_TOPICS):\r\n logger.info(f\"topic already exist:{title}\")\r\n else:\r\n create_video_output_file = OUTPUT_TMP + re_title + \".mp4\"\r\n processor = VideoProcessor(STOCK_VIDEO_FOLDER, audio_file_name, create_video_output_file)\r\n video_path = processor.process_video()\r\n logger.info(f\"Processed video file:{video_path}\")\r\n\r\n output_subtitle_filename = OUTPUT_TMP + re_title + \"-subtitle.mp4\"\r\n overlay = VideoTextOverlay(video_path, transcript_file_name)\r\n output_subtitle_filename_response = overlay.add_text_overlay(output_subtitle_filename)\r\n\r\n logger.info(\"Text overlay added successfully!\")\r\n logger.info(f\"Output video path:{output_subtitle_filename_response}\")\r\n\r\n output_file_final = OUTPUT_FINAL_VIDEO + re_title + \".mp4\"\r\n processor = AddAudio(output_subtitle_filename_response, audio_file_name, output_file_final)\r\n processed_file = processor.process_audio()\r\n logger.info(f\"Processed video file:{processed_file}\")\r\n\r\n final_video_json = {\r\n \"audio_file_name\": item[\"audio_file_name\"],\r\n \"transcript_file_name\": item[\"transcript_file_name\"],\r\n \"link\": item[\"link\"],\r\n \"category\": item[\"category\"],\r\n \"keywords\": item[\"keywords\"],\r\n \"title\": item[\"title\"],\r\n }\r\n\r\n if keywords is not None:\r\n updated_keywords = ' '.join(['#' + topic for topic in keywords])\r\n else:\r\n updated_keywords = ''\r\n if title is not None:\r\n updated_keywords += \"\\n\" + title\r\n # if link is not None:\r\n # updated_keywords += \"\\n article link \" + link\r\n\r\n final_video_json[\"yt_description\"] = updated_keywords\r\n final_json.append(final_video_json)\r\n\r\n logger.info(f\"final_json Processed video :{final_json}\")\r\n with open(OUTPUT_FINAL_INFO + 'video-info-' + get_current_date() + \".json\", \"w\") as outfile:\r\n json.dump(final_json, outfile, indent=4)\r\n logger.info(f\"Task completed ...\")\r\n\r\n\r\ndef check_and_add_topic(new_topic, existing_topics_file):\r\n exist_file = False\r\n\r\n if not os.path.exists(existing_topics_file):\r\n topics = []\r\n else:\r\n with open(existing_topics_file) as file:\r\n topics = json.load(file)\r\n\r\n if new_topic in topics:\r\n logger.info(f\"Skipping '{new_topic}' as it already exists.\")\r\n exist_file = True\r\n else:\r\n topics.append(new_topic)\r\n logger.info(f\"Added new topic: '{new_topic}'\")\r\n exist_file = False\r\n\r\n with open(existing_topics_file, 'w') as file:\r\n json.dump(topics, file)\r\n\r\n return exist_file\r\n\r\n\r\nif __name__ == \"__main__\":\r\n logger.info(f\"####.................. Service starting .................######\")\r\n # tech topic's tech_topics = [\"elon musk\", \"apple\", \"iphone 15\", \"amazon\", \"google\", \"chatgpt\", \"ai\",\r\n # \"technologies\", \"ticktok\",\"instagram\", \"news\", \"smartphone\", \"microsoft\", \"meta\", \"metaverse\",\"new game\r\n # release\", \"new features\", \" \"] tech_topics = [\"elon musk\", \"iphone\", \"game\", \" \"] for tp in tech_topics:\r\n # logger.info(f\"current tech topic processing: '{tp}'\") tech_news: str = \"https://newsdata.io/api/1/news?apikey=\"\r\n # + NEWS_API_KEY + \"&q=\" + tp + \"&language=en&category=technology\" _news(tech_news) # business topic's #\r\n # bs_topics = [\"economy\", \"apple\", \"iphone 15\", \"amazon\", \"google\", \"chatgpt\", \"ai\",\"upcoming\", \" \", \"news\",\r\n # \"business\", \"USA\", \"london\", \"canada\", \"india\", \"EY\", \"global\", \"microsoft\",\"new\"] bs_topics = [\" \"] for tp in\r\n # bs_topics: logger.info(f\"current business topic processing: '{tp}'\") tech_news: str =\r\n # \"https://newsdata.io/api/1/news?apikey=\" + NEWS_API_KEY + \"&q=\" + tp + \"&language=en&category=business\" _news(\r\n # tech_news) # entertainment topic's # entertainment_topics = [\" \", \"marvel movies\", \"DC movies\", \"new movies\",\r\n # \"upcoming\", \"music\", \"harry styles\"] entertainment_topics = [\" \"] for tp in entertainment_topics: logger.info(\r\n # f\"current entertainment topic processing: '{tp}'\") entertainment_news: str =\r\n # \"https://newsdata.io/api/1/news?apikey=\" + NEWS_API_KEY + \"&q=\" + tp + \"&language=en&category=business\" _news(\r\n # entertainment_news)\r\n # Daily run\r\n # daily_topics = [\"ai\", \"chatgpt\"]\r\n # for tp in daily_topics:\r\n # logger.info(f\"current entertainment topic processing: '{tp}'\")\r\n # daily_news: str = \"https://newsdata.io/api/1/news?apikey=\" + NEWS_API_KEY + \"&q=\" + tp + \"&language=en\"\r\n # _news(daily_news)\r\n\r\n # top topic's\r\n top_topics = [\"ai\"]\r\n for tp in top_topics:\r\n logger.info(f\"current top topic's processing: '{tp}'\")\r\n top_news: str = \"https://newsdata.io/api/1/news?apikey=\" + NEWS_API_KEY + \"&q=\" + tp + \"&language=en&category=top\"\r\n _news(top_news)\r\n logger.info(f\"####.................. Service Ended Successfully .................######\")\r\n","repo_name":"Alfinjohnson/Auto-YouTube","sub_path":"yt_auto_main.py","file_name":"yt_auto_main.py","file_ext":"py","file_size_in_byte":7744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9018475813","text":"#!/usr/bin/env python\nimport unittest\nimport pyusernotify_newMessage as nm\nimport pyusernotify as pun\nimport pyUserMessage as pum\nimport pyUserMessages as pums\nimport os\n\ntestName = \"test1\"\ntestEmail = \"me@you.com\"\ntestTemplate = \"templateExample.md\"\ntestToAddress = \"ejsteven@oakland.edu\"\n\nclass TestpyUserNotifynewmessage(unittest.TestCase):\n\n\n def test_getFromEmail(self):\n message = pum.pyUserMessage(\"example\")\n self.assertEqual(message.fromEmail,\"admin@example.com\") \n\n def test_getSubject(self):\n message = pum.pyUserMessage(\"example\")\n self.assertEqual(message.getSubject(),'Password Will Expire soon!')\n\n def test_getMessage(self):\n message = pum.pyUserMessage(\"example\")\n message.getMessage()\n\n def test_sendMessage(self):\n message = pum.pyUserMessage(\"sendableExample\")\n toAddress = testToAddress\n message.send(toAddress)\n\n \n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"ericjaystevens/pyusernotify","sub_path":"test-pyusernotify-newMessage.py","file_name":"test-pyusernotify-newMessage.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16409264356","text":"# Day_40_03_attentionimdb.py\n\nimport tensorflow as tf\nimport numpy as np\nfrom Day_40_02_attentionlayer import Attention, BahdanauAttention\n\n# 문제\n# 에포크마다 발생하는 validation의 정확도를 저장해서\n# 학습이 끝난이후에 평균의 최대 정학도를 출력하세요.\nclass validsave(tf.keras.callbacks.Callback):\n def __init__(self):\n self.val_acc = []\n\n def on_epoch_end(self, epoch, logs=None):\n self.val_acc.append(logs['val_acc'])\n\ndef show_attention(option):\n num_words, max_len, embed_size = 5000, 500, 32\n\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words = num_words)\n print(x_train.shape, x_test.shape) # (25000,) (25000,)\n print(y_train.shape, y_test.shape) # (25000,) (25000,)\n\n # print(x_train[:3]) # [list([1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36,...])]\n\n # print(y_train[:10]) # [1 0 0 1 0 0 1 0 1 0]\n x_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, maxlen=max_len)\n x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, maxlen=max_len)\n print(x_train.shape, x_test.shape) # (25000, 500) (25000, 500)\n\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Input([max_len]))\n model.add(tf.keras.layers.Embedding(num_words, embed_size)) # 전이학습이 효과적\n model.add(tf.keras.layers.LSTM(100)) # 레이어 개수를 늘이거나, bidirectional을 적용 효과적\n model.add(tf.keras.layers.Dense(350, activation='relu'))\n\n if option == 0:\n model.add(tf.keras.layers.LSTM(100))\n model.add(tf.keras.layers.Dense(350, activation='relu'))\n\n elif option == 1:\n model.add(tf.keras.layers.LSTM(100, return_sequences=True))\n model.add(Attention())\n # model.add(tf.keras.layers.LSTM(100, return_sequences=True)) # decoder를 정의할때 형식\n\n else:\n model.add(tf.keras.layers.LSTM(100, return_sequences=True))\n model.add()\n\n model.add(tf.keras.layers.Dropout(0.5))\n model.add(tf.keras.layers.Dense(1, activation='sigmoid'))\n\n model.compile(optimizer=tf.keras.optimizers.Adam(),\n loss= tf.keras.losses.binary_crossentropy,\n metrics=['acc'])\n valid_save = validsave()\n model.fit(x_train, y_train, epochs=3, batch_size= 1024,\n validation_data=(x_test, y_test),\n callbacks= [valid_save]) # []로 묶으면 bug val = 0\n\n print('acc_avg:', np.mean(valid_save.val_acc[-3:]))\n print('acc_avg:', np.max(valid_save.val_acc[-3:]))\n\n# show_attention(option =0)\n# show_attention(option = 1)\nshow_attention(option = 2)","repo_name":"yunhui21/CB_Ai_NLP","sub_path":"Day_40_03_attentionimdb.py","file_name":"Day_40_03_attentionimdb.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"43294100825","text":"from __future__ import absolute_import\nfrom training.server.model import Laptop\nfrom celery_demo.celery import app\nfrom training.server.db_utils import VehicleUtils, EngineerUtils, LaptopUtils, ContactDetailsUtils, cleanup_utils\nimport time\n\nengin_utils = EngineerUtils()\ncar_utils = VehicleUtils()\nlaptop_utils = LaptopUtils()\ncontact_utils = ContactDetailsUtils()\n\n@app.task\ndef read_contacts_for_engineer(name):\n print(f\"Reading all contact details for engineer {name}\")\n engin = engin_utils.read_engineer_by_name(name)\n contacts = contact_utils.read_contact_details_by_engin_id(engin.id)\n contacts = [contact.to_json() for contact in contacts]\n return contacts\n\n@app.task\ndef read_all_contacts():\n print(\"Reading all contact info\")\n contacts = contact_utils.read_all_contact_details()\n contacts = [contact.to_json() for contact in contacts]\n return contacts\n\n@app.task\ndef read_laptops_by_engineer(name):\n print(f\"Reading info for laptop loaned by engineer {name}\")\n laptop = laptop_utils.read_laptop_by_owner(name)\n return laptop.to_json()\n\n@app.task\ndef read_all_laptops():\n print(\"Reading info for all laptops\")\n laptops = laptop_utils.read_all_laptops()\n laptops = [laptop.to_json() for laptop in laptops]\n return\n\n@app.task\ndef read_vehicle_by_model(model):\n print(f\"Reading info for vehicle model {model}\")\n cars = car_utils.read_vehicles_by_model(model)\n cars = [car.to_json() for car in cars]\n return cars\n\n@app.task\ndef read_all_vehicles():\n print(\"Reading info for all vehicles\")\n cars = car_utils.read_vehicles_all()\n cars = [car.to_json() for car in cars]\n return cars\n\n@app.task\ndef read_engineer_by_name(name):\n print(f\"Reading info for engineer {name}\")\n engin = engin_utils.read_engineer_by_name(name)\n return engin.to_json()\n\n@app.task\ndef read_all_engineers():\n print(\"Reading info for all engineers\")\n engins = engin_utils.read_all_engineers()\n engins = [engin.to_json() for engin in engins]\n return engins\n\n@app.task\ndef read_engineers_by_vehicle(model):\n print(f\"Reading info for engineers assigned to vehicle {model}\")\n engins = car_utils.read_assigned_engineers_by_model(model)\n engins = [engin.to_json() for engin in engins]\n return engins\n\n@app.task\ndef read_vehicles_by_engineer(name):\n print(f\"Reading info for vehicles engineer {name} is assigned to\")\n cars = engin_utils.read_assigned_vehicles_by_name(name)\n cars = [car.to_json() for car in cars]\n return cars","repo_name":"CameronFoss/SQLAlchemy-Client-Server","sub_path":"training/celery_demo/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"12238674903","text":"#Bytes_data\nimport ast\n\nimport pandas as pd\nimport os\n\ndf = pd.read_csv('/Users/kylephan/Downloads/RecipeNLG_dataset.csv')\n\ndf = df.drop(['ingredients', 'directions', 'source', 'Unnamed: 0'], axis=1) # dataframe now just has index, name, link, and NER\n\n# add columns, default them to True.\ndf['NER'] = df['NER'].apply(ast.literal_eval)\ndf['gluten_friendly'] = 1\ndf['vegan_friendly'] = 1\ndf['vegetarian_friendly'] = 1\ndf['lactose_friendly'] = 1\ndf['keto_friendly'] = 1\ndf['nut_friendly'] = 1\ndf['shellfish_friendly'] = 1\n\noutput_file = 'recipe_dataset.csv'\n\nwith open(output_file, 'w') as output:\n # dietary restrictions\n restrictions = {\n 'gluten_friendly': ['wheat', 'barley', 'rye', 'semolina', 'durum', 'triticale', 'spelt', 'kamut', 'bulgur', 'couscous', 'bread', 'pasta', 'beer'],\n 'vegan_friendly': ['milk', 'cheese', 'yogurt', 'butter', 'beef', 'pork', 'chicken', 'fish', 'honey', 'gelatin', 'carmine', 'dairy', 'egg', 'seafood'],\n 'vegetarian_friendly': ['steak', 'bacon', 'sausages', 'chicken', 'salami', 'fish', 'shrimp', 'turkey', 'lamb', 'ham', 'pepperoni', 'pork', 'duck', 'rabbit', 'venison', 'rabbit', 'octopus', 'squid', 'frog', 'turtle', 'elk', 'oyster', 'clam', 'escargot', 'crocodile', 'crayfish', 'mussel', 'snail', 'bison', 'alligator', 'quail', 'pheasant'],\n 'lactose_friendly': ['milk', 'cheese', 'yogurt', 'butter', 'icecream', 'cottage cheese', 'cream cheese', 'whey', 'curd', 'margarine'],\n 'keto_friendly': ['grain', 'legume', 'bean', 'pea', 'lentil', 'peanut', 'bread', 'alcohol'],\n 'nut_friendly': ['nuts', 'peanut', 'treenut', 'walnut', 'almond', 'cashew', 'pecan', 'macadamia', 'pine', 'pistachio', 'hazelnut'],\n 'shellfish_friendly': ['shrimp', 'prawn', 'crab', 'lobster', 'clam', 'mussel', 'oysters', 'scallop', 'octopus', 'squid', 'scallop', 'snail', 'abalone']\n }\n\n for index, row in df.iterrows():\n #each row has title, link, and NER, and all of the restrictions\n for ingredient in row['NER']:\n for restriction, ing in restrictions.items():\n if ingredient in ing:\n df.at[index, restriction] = 0\n\n\n df = df.drop(['NER'], axis=1)\n pd.set_option('display.max_columns', None)\n df.index = df.index + 1\n df.to_csv(output, sep='$', index=True)\n\n\n\n\n\n\n\n\n\n","repo_name":"kylephan5/bytes","sub_path":"bytes_api/bytes/migrate_kaggle_dataset.py","file_name":"migrate_kaggle_dataset.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"34582915025","text":"def same_length(data,max_length):\r\n '''\r\n :param data:\r\n :param max_length:\r\n :return:\r\n '''\r\n result = []\r\n data_ceshi = [[0, 0]]\r\n for i in data:\r\n #print(i)\r\n length = len(i)\r\n #print(length)\r\n add_length = max_length - length\r\n result.append(i+data_ceshi*add_length)\r\n #print(result)\r\n\r\n return result\r\n\r\n'''a = [[[1,2],[1,3]],[[11,2]]]\r\nb= same_length((a),2)\r\nprint(b)'''","repo_name":"lynchsky/Identifying-molecular-functional-groups-of-organic-compounds-by-deep-learning-of-NMR-data","sub_path":"article_code/data_same_length.py","file_name":"data_same_length.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"28069109700","text":"from PyQt5.QtCore import QObject\nfrom PyQt5.QtCore import pyqtSignal\nfrom typing import NamedTuple\n\nfrom services.setting import Setting\nfrom services.grade_setting import GradeSetting\nfrom services.colour_setting import ColourSetting\nfrom APImodels.problem import Problem\nfrom APImodels.grade import Grade\nfrom APImodels.colour import Colour\n\nclass GradeCellData(NamedTuple):\n # model for grade cell\n\n row : int \n aim : str\n bg_colour : Colour\n text_colour : Colour\n width : int = 160\n height : int = 48 \n inner_width : int = 52\n inner_height : int = 23\n\n\nclass GradeCellDataBuilder():\n # build grade cell model from:\n # - row \n\n def __init__(self):\n self.grade_setting = Setting.get(GradeSetting)\n\n def build(self, row:int):\n bg_colour = self.grade_setting.get_bg_colour(row)\n text_colour = self.grade_setting.get_text_colour(row)\n aim = str(self.grade_setting.get_aim(row))\n\n return GradeCellData(row, aim, bg_colour, text_colour)\n\n\nclass GradeCountData(NamedTuple):\n # data for cell that counts problems of that particular grade\n\n row : int\n bg_colour: Colour\n text_colour: Colour\n text : str\n\nclass GradeCountDataBuilder():\n # build grade count data from :\n # - row + count\n\n def __init__(self):\n self._grade_setting = Setting.get(GradeSetting)\n self._colour_setting = Setting.get(ColourSetting)\n\n def build(self, row:int, count:int):\n bg_colour = self._extract_background_colour(row, count)\n text_colour = self._extract_text_colour(row, count)\n\n return GradeCountData(row, bg_colour, text_colour, str(count))\n\n def _extract_background_colour(self, row:int, count:int):\n # return background colour depending on whether or not number of problems in that\n # grade meets the target\n aim = self._grade_setting.get_aim(row)\n colour_str = 'alert' if count < aim else 'default'\n return self._colour_setting.get_bg_colour(colour_str)\n\n def _extract_text_colour(self, row:int, count:int):\n # return text colour depending on whether or not number of problems in that\n # grade meets the target\n aim = self._grade_setting.get_aim(row)\n colour_str = 'alert' if count < aim else 'default'\n return self._colour_setting.get_text_colour(colour_str) \n\n\nclass GradeAreaData(NamedTuple):\n cells : tuple[GradeCellData,...]\n width : int = 160\n \nclass GradeAreaDataBuilder():\n\n def __init__(self):\n super().__init__()\n self.builder = GradeCellDataBuilder()\n self.grade_setting = Setting.get(GradeSetting)\n self.n_row = self.grade_setting.length()\n\n def default(self):\n cells = [self.builder.build(row) for row in range(self.n_row)]\n cells.sort(key= lambda x : x.row)\n return GradeAreaData(tuple(cells))\n\n\nclass GradeCountsData(NamedTuple):\n cells : tuple[GradeCountData,...]\n\n def get_cell(self, row:int):\n cell = [cell for cell in self.cells if cell.row == row]\n return cell[0] if len(cell) > 0 else None\n\n\nclass GradeCountsDataBuilder():\n\n def __init__(self):\n super().__init__()\n self._grade_setting = Setting.get(GradeSetting)\n self._builder = GradeCountDataBuilder()\n\n self.n_row = self._grade_setting.length()\n self._grades = self._grade_setting.get_all_grades()\n\n def default(self):\n cells = [self._builder.build(row, 0) for row in range(self.n_row)] \n cells.sort(key= lambda x : x.row)\n return GradeCountsData(tuple(cells))\n\n def from_problems(self, problems:tuple[Problem,...]):\n prob = tuple(problems)\n if len(prob) == 0 :\n return self.default()\n cell_data = [(self._grade_setting.get_row(g), self._counts(g, prob) ) for g in self._grades]\n cells = [self._builder.build(d[0], d[1]) for d in cell_data]\n cells.sort(key= lambda x : x.row)\n return GradeCountsData(tuple(cells))\n\n def _counts(self, grade:Grade, problems:tuple[Problem,...]) -> int:\n return len([p for p in problems if p.grade == grade])\n\nclass GradeAreaModel(QObject):\n \n countsChanged = pyqtSignal(bool)\n \n def __init__(self):\n super().__init__()\n self._builder = GradeAreaDataBuilder()\n self._count_builder = GradeCountsDataBuilder() \n self.static = self._builder.default()\n self._counts = self._count_builder.default()\n\n @property\n def counts(self) -> None:\n return self._counts\n\n @counts.setter\n def counts(self, value: GradeCountsData) -> None:\n self._counts = value\n self.countsChanged.emit(True)\n\n def update_counts(self, problems:tuple[Problem,...]) -> None:\n self.counts = self._count_builder.from_problems(problems)","repo_name":"Supasiti/problem_manager","sub_path":"models/grade_area_model.py","file_name":"grade_area_model.py","file_ext":"py","file_size_in_byte":4867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"74379388562","text":"def find_repeated_dna_sequence(s: str, k: int) -> set:\n \"\"\"\n Given a string, s, that represents a DNA subsequence, and a number k,\n return all the contiguous subsequences (substrings) of length k that occur more than once in the string.\n\n The DNA sequence is composed of a series of nucleotides abbreviated as A, C, G, and T.\n For example, ACGAATTCCG is a DNA sequence.\n\n The order of the returned subsequences does not matter.\n If no repeated substring is found, the function should return an empty set.\n\n Args:\n s: input string representing a DNA sequence\n k: an integer\n\n Returns:\n all the contiguous subsequences (substrings) of length k that occur more than one in the input string\n \"\"\"\n # Solution using polynomial rolling hash\n mapping = {'A': 1, 'C': 2, 'G': 3, 'T': 4}\n hash_value = 0\n sequences = set()\n output = set()\n a = 4 # base value\n\n numbers = [0] * len(s)\n hi_power = pow(a, k - 1)\n\n for idx, ch in enumerate(s):\n numbers[idx] = mapping[ch]\n\n for start in range(len(s) - k + 1):\n if start == 0:\n for end in range(k):\n hash_value += numbers[end] * (a ** (k - end - 1))\n else:\n hash_value = ((hash_value - (numbers[start - 1] * hi_power)) * a) + numbers[start + k - 1]\n if hash_value in sequences:\n output.add(s[start: start + k])\n sequences.add(hash_value)\n\n return output\n\n\nif __name__ == \"__main__\":\n print(find_repeated_dna_sequence(\"AAAAACCCCCAAAAACCCCCC\", 8))\n print(find_repeated_dna_sequence(\"GGGGGGGGGGGGGGGGGGGGGGGGG\", 12))\n print(find_repeated_dna_sequence(\"TTTTTCCCCCCCTTTTTTCCCCCCCTTTTTTT\", 10))\n print(find_repeated_dna_sequence(\"AAAAAACCCCCCCAAAAAAAACCCCCCCTG\", 10))\n print(find_repeated_dna_sequence(\"ATATATATATATATAT\", 6))\n","repo_name":"BhupiSindhwani/python-problem-solving","sub_path":"sliding_window/find_repeated_dna_sequence.py","file_name":"find_repeated_dna_sequence.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7223019103","text":"import socket\n\nclass ServidorTCP:\n __clienteSocket = None\n __clienteDireccion = None\n __paquetesRecibidos = 0\n __paquetesEnviados = 0\n\n def __init__(self, puerto):\n self.__socketServidor = socket.socket()\n self.__socketServidor.bind(('', puerto))\n self.__socketServidor.listen()\n self.__clienteSocket, self.__clienteDireccion = self.__socketServidor.accept()\n\n salir = False\n\n while not salir:\n recibido = self.recibir\n if recibido == 'Salir':\n mensaje = f'[RCV: {self.__paquetesRecibidos}]: cerrando conexion ...'\n salir = True\n else:\n mensaje = f'[RCV: {self.__paquetesRecibidos}]: '\n self.enviar(mensaje)\n\n self.__clienteSocket.close()\n self.__socketServidor.close()\n print('Conexiones cerradas')\n\n\n def recibir(self):\n self.__paquetesRecibidos += 1\n recibido = self.__clienteSocket.recv(1024)\n return recibido\n\n def enviar(self, mensaje):\n self.__paquetesEnviados += 1\n print(f'[SND: {self.__paquetesEnviados}] {mensaje.encode()}')\n self.__clienteSocket.send(mensaje.encode())\n","repo_name":"Regnier96/EjerciciosPython3_Erick","sub_path":"Ejercicios/E4/Modulos/Servidor_TCP.py","file_name":"Servidor_TCP.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13639704828","text":"from django.urls import path\n\nfrom orders import views\n\napp_name = 'orders'\n\nurlpatterns = [\n path('create///////////', views.order_create, name='order_create'),\n path('/', views.detail, name='detail'),\n path('payment//', views.payment, name='payment'),\n path('verify/', views.verify, name='verify'),\n path('apple-coupon/', views.coupon_apply, name='coupon_apply'),\n]\n","repo_name":"nikisham/nowii","sub_path":"orders/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"705751733","text":"from matplotlib.pyplot import title\nimport plotly.graph_objects as go\nimport numpy as np \n\nfrom analysis import song_df\n\ndef plot_graph():\n print (\"hi\")\n song_df['complete'] = song_df['title'] + \"
\" + song_df['artists']\n\n title_col = ((np.asarray(song_df['complete'])).reshape(7,7))\n valence_col = ((np.asarray(song_df['valence'])).reshape(7,7))\n\n\n fig = go.Figure(data=go.Heatmap(\n z= valence_col,\n text=title_col,\n colorscale = \"YlGn_r\", \n showlegend = False,\n hovertemplate = '%{text}'\n ))\n\n fig.update_xaxes(showticklabels=False)\n fig.update_yaxes(showticklabels=False)\n fig.update_traces(showscale=False)\n\n fig.write_html('templates/moodboard.html', auto_open=False)","repo_name":"VaniSachdev/moodboard","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"27716227269","text":"import string\n\nwith open(\"countries-raw.txt\", \"r+\") as f:\n #print(f.read())\n #print(type(f))\n #print(list(f))\n listf = list(f)\n #filter the variable\n cleaned = [item for item in listf if item != \"Top of Page\\n\"]\n \n #append the variable to a new list\n #print(cleaned)\n \n\n cleaned2 = [item for item in cleaned if item != \"\\n\"]\n #print(cleaned2)\n\n #cleanedagain = [item for item in cleaned2 if item not in list(string.ascii_uppercase)]\n #print(cleanedagain)\n \n cleaned3 = [str(item).replace(\"\\n\", \"\") for item in cleaned2 ]\n print(cleaned3)\n\n cleanedagain = [item for item in cleaned3 if item not in list(string.ascii_uppercase)]\n print(cleanedagain)\n \n \n with open(\"countries-cleaned.txt\", \"w\") as f:\n for item in cleanedagain:\n f.write(str(item)+ \"\\n\")\n \n \n \n","repo_name":"hamiltons4/100LittlePythonPrograms","sub_path":"ex85.py","file_name":"ex85.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29045913177","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'a-vasin'\n\nfrom decimal import Decimal\n\nimport pytest\nfrom hamcrest import empty\n\nfrom balance import balance_steps as steps\nfrom btestlib import utils\nfrom btestlib.data.partner_contexts import GAS_STATION_RU_CONTEXT\nfrom btestlib.matchers import contains_dicts_equal_to, contains_dicts_with_entries\n\nPAYMENT_AMOUNT = Decimal('42.77')\nREFUND_AMOUNT = Decimal('31.42')\nTOTAL_AMOUNT = PAYMENT_AMOUNT - REFUND_AMOUNT\n\n_, _, first_month_start_dt, first_month_end_dt, second_month_start_dt, second_month_end_dt = \\\n utils.Date.previous_three_months_start_end_dates()\n\n\ndef test_act_wo_data():\n client_id, person_id, contract_id, _ = steps.ContractSteps.create_partner_contract(\n GAS_STATION_RU_CONTEXT,\n additional_params={'start_dt': first_month_start_dt})\n\n steps.CommonPartnerSteps.generate_partner_acts_fair_and_export(\n client_id, contract_id, second_month_start_dt,\n manual_export=False)\n\n invoice_data = steps.InvoiceSteps.get_invoice_data_by_client(client_id)\n expected_invoice_data = [steps.CommonData.create_expected_invoice_data_by_context(\n GAS_STATION_RU_CONTEXT,\n contract_id, person_id,\n Decimal('0'),\n dt=first_month_start_dt)]\n utils.check_that(invoice_data, contains_dicts_equal_to(expected_invoice_data),\n u'Сравниваем данные из счета с шаблоном')\n\n act_data = steps.ActsSteps.get_act_data_by_client(client_id)\n utils.check_that(act_data, empty(), u'Сравниваем данные из акта с шаблоном')\n\n\n@pytest.mark.smoke\n@pytest.mark.parametrize(\"service_fee\", [None, 'default', 2, 3],\n ids=lambda cc: 'fee_' + str(cc))\ndef test_act_second_month(service_fee):\n service_fee_config = steps.CommonPartnerSteps.get_product_mapping_config(GAS_STATION_RU_CONTEXT.service)\n service_fee_config = service_fee_config['service_fee_product_mapping'][\n GAS_STATION_RU_CONTEXT.payment_currency.iso_code]\n additional_tpt_params = None if service_fee is None else dict(product_id=service_fee_config[str(service_fee)])\n\n client_id, person_id, contract_id, _ = steps.ContractSteps.create_partner_contract(\n GAS_STATION_RU_CONTEXT,\n additional_params={'start_dt': first_month_start_dt})\n\n first_month_sum, second_month_sum = steps.SimpleApi.create_tipical_tpt_data_for_act(\n GAS_STATION_RU_CONTEXT,\n client_id,\n person_id, contract_id,\n first_month_start_dt,\n second_month_start_dt,\n sum_key='yandex_reward',\n additional_tpt_params=additional_tpt_params)\n\n invoice_data = steps.InvoiceSteps.get_invoice_data_by_client(client_id)\n\n expected_invoice_data = [steps.CommonData.create_expected_invoice_data_by_context(GAS_STATION_RU_CONTEXT,\n contract_id, person_id,\n first_month_sum + second_month_sum,\n dt=first_month_start_dt)]\n utils.check_that(invoice_data, contains_dicts_equal_to(expected_invoice_data),\n u'Сравниваем данные из счета с шаблоном')\n\n act_data = steps.ActsSteps.get_act_data_by_client(client_id)\n expected_act_data = [\n steps.CommonData.create_expected_act_data(first_month_sum, first_month_end_dt),\n steps.CommonData.create_expected_act_data(second_month_sum, second_month_end_dt)]\n\n utils.check_that(act_data, contains_dicts_with_entries(expected_act_data),\n u'Сравниваем данные из акта с шаблоном')\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"billing/balance_tests/balance/tests/partner_schema_acts/test_gas_stations_acts.py","file_name":"test_gas_stations_acts.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17447862433","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ## One time data transformation\n# In this notebook, we are going to transform the stations and weather data in such a way that they will be conformed to the redshift schema for their corresponding tables.\n# \n# The preprocessed data will be saved back to S3 before getting loaded to Redshift.\n\nimport pyspark\nimport os\n\npyspark.__version__\n\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession.builder\\\n .master('local[*]')\\\n .appName('data-transformer')\\\n .getOrCreate()\n\nsc = spark.sparkContext\n\ndf_stations = spark.read.csv(\"s3a://hrc-de-data/raw/cycling-extras/stations.csv\", inferSchema=True, header=True)\ndf_stations.take(2)\n\ndf_stations.printSchema()\n\n\nfrom pyspark.sql import functions as F, types as T\n\n# rename columns\nstations= df_stations.withColumnRenamed('Station.Id', 'station_id')\\\n .withColumnRenamed('StationName', 'station_name')\\\n .withColumnRenamed('easting', 'easting')\\\n .withColumnRenamed('northing', 'northing') \n\nstations.show(5)\n\n\n# count missing values in each column\nstations.select([F.count(F.when(F.isnan(c) | F.col(c).isNull(), c)).alias(c) for c in stations.columns]).show()\n\nstations.write.parquet('s3a://hrc-de-data/processed/cycling-dimension/stations/', mode='overwrite')\n\n\n# ### 2. Weather data\n\ndf_weather = spark.read.json(\"s3a://hrc-de-data/raw/cycling-extras/weather.json\")\n\ndf_weather.take(2)\n\ndf_weather.printSchema()\n\n# drop some columns that we won't need\nweather= df_weather.drop('cloudcover', 'conditions', 'datetimeEpoch', 'description', 'dew', 'icon', \n 'precipcover', 'preciptype', 'source', 'stations', 'sunriseEpoch', 'sunsetEpoch')\n\n\n# transform datetime\nweather= weather.withColumnRenamed('datetime', 'weather_date') \nweather= weather.withColumn('weather_date', weather.weather_date.cast(T.DateType()))\n\nweather.printSchema()\nprint(len(weather.columns), 'columns')\n\n\n# count missing values in each column\ncols= weather.columns\ncols.remove('weather_date')\n\nmissing_values= weather.select([F.count(F.when(F.col(c).isNull() | F.isnan(c), c)).alias(c) for c in cols])\n\nmissing_values.show()\n\n\nperc_missing_values= weather.select([(F.count(F.when(F.isnan(c) | F.col(c).isNull(), c))/F.count(F.lit(1))).alias(c) for c in cols])\nperc_missing_values.show()\n\n\n# drop columns where missing values are more than 70%\n\nweather= weather.drop('precipprob', 'snow', 'snowdepth')\n\nif 'severerisk' in weather.columns:\n weather= weather.drop('severerisk')\n\n\nweather.columns\n\nweather= weather.repartition(10)\n\nweather.write.parquet('s3a://hrc-de-data/processed/cycling-dimension/weather/', mode='overwrite')\n","repo_name":"HoracioSoldman/batch-processing-on-aws","sub_path":"airflow/dags/scripts/init-data-transformation.py","file_name":"init-data-transformation.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"3"}
+{"seq_id":"69793871441","text":"# coding: utf8\nfrom __future__ import absolute_import\nimport re\nimport json\nimport os\n\ndef curry(_curried_func, *args, **kwargs):\n def _curried(*moreargs, **morekwargs):\n return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))\n return _curried\n\n\ndef to_number(value, default_if_fail=None, max_value=None, number_type_func=None):\n if not value and type(value)!=int:\n return default_if_fail\n try:\n value = float(value)\n if number_type_func:\n value = number_type_func(value)\n except:\n value = default_if_fail\n if max_value and value>max_value:\n value = max_value\n return value\n\nto_float = curry(to_number, number_type_func=None)\nto_int = curry(to_number, number_type_func=int)\n\n\ndef is_int(value):\n if isinstance(value, bool):\n return False\n elif isinstance(value, int):\n return True\n elif isinstance(value, (str, unicode)):\n value = value.strip()\n if re.match('^\\d+$', value):\n return True\n else:\n return False\n else:\n return False\n\n\ndef is_float(value):\n if isinstance(value, float):\n return True\n elif isinstance(value, (str, unicode)):\n value = value.strip()\n if re.match('^\\d*\\.\\d*$', value):\n return True\n else:\n return False\n else:\n return False\n\n\ndef auto_float(value):\n # 严格意义的float\n if is_float(value):\n return to_float(value)\n else:\n return value\n\ndef auto_int(value):\n # 严格意义的int\n if is_int(value):\n return to_int(value)\n else:\n return value\n\n\ndef auto_bool(value):\n # 严格意义的true/false\n if isinstance(value, (str, unicode)):\n if value.lower() == 'false':\n value = False\n elif value.lower() == 'true':\n return True\n return value\n\n\ndef auto_value(value):\n value = auto_float(value)\n value = auto_int(value)\n value = auto_bool(value)\n return value\n\n\ndef get_value_by_index(value, index):\n try:\n return value[index]\n except IndexError:\n return None\n\n\n\ndef load_json_from_filepath(filepath):\n if not os.path.isfile(filepath):\n return\n try:\n with open(filepath) as f:\n return json.loads(f.read())\n except:\n return\n\ndef dump_json_to_filepath(data, filepath):\n try:\n with open(filepath, 'w') as f:\n f.write(json.dumps(data))\n except:\n pass\n\n\n\ndef split_list(ls, size_per_part):\n for i in range(0, len(ls), size_per_part):\n yield ls[i:i + size_per_part]","repo_name":"hepochen/bitcron-cli","sub_path":"bitcron/utils/lazy.py","file_name":"lazy.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"20642436649","text":"# -*- coding:utf-8 -*-\n\n\nfrom selenium import webdriver\n\nkey_urls = {\n 'mp.zhizhuma.com/share/audio.htm': '1',\n 'mp.zhizhuma.com/qr.html': '1',\n 'mp.zhizhuma.com/q': '1',\n 'www.hdsdjf.com/smp': '2',\n 'mp.zhizhuma.com/book.htm': '3',\n 'www.pingdianedu.com:8101/files/html': '4',\n}\n\nheader = {\n \"ua_base\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 \"\n \"Safari/537.36 micromessenger/5.0.1.352 \"\n}\n\n\ndef get_url_type(mp3_code_url: str):\n mp3_code_keys = mp3_code_url.split('//')\n if len(mp3_code_keys) >= 2:\n for key_url in key_urls:\n if mp3_code_keys[1].startswith(key_url):\n return key_urls.get(key_url)\n return 0\n else:\n return -1\n\n\ndef open_chrome_get_html(html_url):\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('headless')\n driver = webdriver.Chrome(chrome_options=chrome_options)\n driver.get(html_url)\n return driver.page_source\n","repo_name":"zhuzhifei1995/get_mp3","sub_path":"util/url_util.py","file_name":"url_util.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24410467435","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[13]:\n\n\n# find the max height up to the given point from left end and right end, \n# O(n)\ndef tw(L):\n if len(L) == 0:\n return 0\n left_max = [L[0]]\n for i in range(1,len(L)):\n left_max.append(max(left_max[i-1], L[i]))\n \n right_max = [0]*len(L)\n right_max[-1] = L[-1]\n for i in range(len(L)-2,-1, -1):\n right_max[i] = max(right_max[i+1], L[i])\n \n ans = 0\n for i, x in enumerate(L):\n ans += min(left_max[i], right_max[i]) - L[i]\n \n return ans\n\ntw([0,1,0,2,1,0,1,3,2,1,2,1])\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"kevicao/python","sub_path":"42. Trapping Rain Water.py","file_name":"42. Trapping Rain Water.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"71592610322","text":"import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sympy import *\n\ndef multiple_roots_method(x0, tol, f, niter):\n \"\"\"\n Performs the multiple roots method for finding roots of a given function.\n\n Parameters:\n - x0 (float): Initial guess value.\n - tol (float): Tolerable error to determine the convergence of the method.\n - f (sympy expression): The function for which to find the root.\n - niter (int): Maximum number of iterations allowed.\n\n Returns:\n None\n \"\"\"\n\n v = symbols('v') # Define the variable\n\n fder1 = f.diff(v) # First derivative\n fder2 = f.diff(v, v) # Second derivative\n\n # Initialization\n error = 100\n n = 0\n\n # Lists to store the approximations and corresponding function values\n approximations = []\n\n while error >= tol:\n xr = x0 - ((f.evalf(subs={v: x0})) * (fder1.evalf(subs={v: x0}))) / (\n (fder1.evalf(subs={v: x0})) ** 2 - ((f.evalf(subs={v: x0})) * (fder2.evalf(subs={v: x0}))))\n error = abs(xr - x0)\n x0 = xr\n n += 1\n approximations.append(xr)\n print('Iteration:', n, 'Root:', x0, 'Error:', error)\n\n if n == niter:\n print(\"Method Failed within\", n, \"iterations\")\n break\n\n # Plot the function and the approximations\n sns.set_style('whitegrid')\n plt.figure(figsize=(10, 6))\n\n v_vals = np.linspace(float(min(approximations)) - 3.0, float(max(approximations)) + 3.0, 500)\n f_vals = np.array([f.evalf(subs={v: x_val}) for x_val in v_vals])\n\n plt.plot(v_vals, f_vals, label='Function')\n plt.scatter(approximations, [f.evalf(subs={v: x_val}) for x_val in approximations], color='red',\n label='Approximations')\n plt.axhline(y=0, color='black', linestyle='--', label='y=0')\n\n plt.xlabel('x')\n plt.ylabel('f(x)')\n plt.title('Multiple Roots Method - Approximations and Function')\n\n plt.legend()\n plt.show()\n\n\n# Define the variable and function\nv = symbols('v')\nf = sympify(\"0.5 * 1.225 + cos(v) * v ** 2 * 15.165 * (2 * pi * 0.0872665) / (1 + (2 / 7.32))\")\n\n# Set initial guess, tolerable error, and maximum number of iterations\nx0 = -2\ntol = 0.5e-5\nniter = 100\n\n# Call the multiple roots method\nmultiple_roots_method(x0, tol, f, niter)\n","repo_name":"JCOM127/Non-Linear-Solvers","sub_path":"Newton-Multiple Roots.py","file_name":"Newton-Multiple Roots.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"4950240867","text":"from flask import Blueprint, abort, make_response, request\nfrom flask_jwt_extended import get_jwt_identity, jwt_required\nfrom jsonschema import validate\n\nfrom domain.model.food import FoodSchema\nfrom infra.settings import session\nfrom repository.foods import FoodRepository\nfrom util.validate import is_uuid\nfrom validate.foods import register_food_schema\n\nfoods_router = Blueprint(\"foods_router\", __name__, url_prefix=\"/foods\")\nfood_repository = FoodRepository(session)\n\n\n@foods_router.route(\"/\", methods=[\"POST\"])\n@jwt_required()\ndef register_food():\n if not request.is_json:\n abort(401)\n\n json = request.get_json()\n\n try:\n validate(json, register_food_schema)\n except Exception as e:\n abort(400)\n\n user_id = get_jwt_identity()\n if not user_id:\n abort(400)\n\n food_repository.post_food(\n json[\"name\"], json[\"icon_url\"], json[\"food_category_id\"], json[\"deadline\"]\n )\n\n return make_response({\"success\": \"OK\"}, 201)\n\n\n@foods_router.route(\"/\", methods=[\"GET\"])\ndef get_foods():\n foods = food_repository.get_foods()\n\n return make_response({\"foods\": FoodSchema(many=True).dump(foods)}, 200)\n\n\n@foods_router.route(\"/\", methods=[\"GET\"])\ndef get_food(food_id):\n if not is_uuid(food_id):\n abort(400)\n\n food = food_repository.get_food(food_id)\n\n return make_response(FoodSchema(many=False).dump(food), 200)\n","repo_name":"takaya-hirano-su/ShowMe","sub_path":"app/framework/router/foods.py","file_name":"foods.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29292005137","text":"# ml_models/views.py\nimport numpy as np\nimport pandas as pd\nfrom flask import render_template, abort, request, Blueprint\nfrom portfolio.ml_models.forms import (MoviePredictorForm, LoanPredictorForm,\n KickstarterPitchOutcomeForm, TitanticPredictorForm,\n NhlGoalsPredictorForm)\nfrom portfolio.db import db\nfrom statsmodels.regression.linear_model import OLSResults\nimport requests\n\nc = db['ml_models']\n\nml_models = Blueprint('ml_models', __name__, template_folder=\"templates/ml_models\")\n\nDOMAIN_ADDR = 'http://192.168.0.162/'\nDEFAULT_TIMEOUT = 1.5\n\ndef payload_from_form(form):\n payload = dict()\n for field in form:\n if field.name not in ['csrf_token', 'submit']:\n payload[field.name] = field.data\n return payload\n\n@ml_models.route('/', methods=['GET', 'POST'])\ndef models(name):\n ml_model = c.find_one({'id': name})\n\n template = '{}.html'.format(name)\n\n if ml_model is None:\n abort(404)\n\n form = globals()[ml_model['form_name']]()\n title = ml_model['title']\n\n if request.method == 'POST':\n try:\n payload = payload_from_form(form)\n if name == 'luther':\n url = DOMAIN_ADDR + 'movie_roi' \n response = requests.get(url, params=payload, timeout=DEFAULT_TIMEOUT)\n prediction = response.json()['prediction']\n elif name == 'mcnulty':\n url = DOMAIN_ADDR + 'lending_club_loan_default' \n response = requests.get(url, params=payload, timeout=DEFAULT_TIMEOUT)\n prediction = response.json()['prediction']\n elif name == 'fletcher':\n url = DOMAIN_ADDR + 'kickstarter_pitch_outcome' \n response = requests.post(url, json=payload, timeout=DEFAULT_TIMEOUT)\n prediction = response.json()['prediction']\n elif name == 'titantic':\n url = DOMAIN_ADDR + 'titanic'\n response = requests.get(url, params=payload, timeout=DEFAULT_TIMEOUT)\n prediction = response.json()['prediction']\n elif name == 'nhl_goals':\n url = DOMAIN_ADDR + 'nhl_player_season_scoring_total'\n response = requests.get(url, params=payload, timeout=DEFAULT_TIMEOUT)\n prediction = response.json()['prediction']\n else:\n abort(404)\n except requests.exceptions.Timeout: \n abort(503) # service unavailable\n return render_template(template, model=True, form=form, title=title, prediction=prediction)\n\n return render_template(template, model=True, title=title, form=form)\n","repo_name":"brendanfitz/portfolio-flask-app","sub_path":"portfolio/ml_models/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43104980209","text":"from __future__ import print_function\n\nimport os.path\nimport h5py\nimport pytest # pylint: disable=unused-import\n\nfrom basic_modules.metadata import Metadata\n\nfrom mg_process_files.tool.bed_sorter import bedSortTool\nfrom mg_process_files.tool.bed_indexer import bedIndexerTool\n\n\n@pytest.mark.bed\ndef test_bed_01_sorter():\n \"\"\"\n Function to test Kallisto indexer\n \"\"\"\n resource_path = os.path.join(os.path.dirname(__file__), \"data/\")\n\n input_files = {\n \"bed\": resource_path + \"sample.bed\"\n }\n\n output_files = {\n \"sorted_bed\": resource_path + \"sample.sorted.bed\"\n }\n\n metadata = {\n \"bed\": Metadata(\n \"data_rnaseq\", \"bed\", [], None,\n {'assembly': 'test'}),\n }\n\n bs_handle = bedSortTool()\n bs_handle.run(input_files, metadata, output_files)\n\n print(resource_path)\n assert os.path.isfile(resource_path + \"sample.sorted.bed\") is True\n assert os.path.getsize(resource_path + \"sample.sorted.bed\") > 0\n\n\n@pytest.mark.bed\ndef test_bed_02_indexer():\n \"\"\"\n Function to test Kallisto indexer\n \"\"\"\n resource_path = os.path.join(os.path.dirname(__file__), \"data/\")\n\n f_check = h5py.File(resource_path + \"file_index.hdf5\", \"a\")\n f_check.close()\n\n input_files = {\n \"bed\": resource_path + \"sample.sorted.bed\",\n \"chrom_file\": resource_path + \"chrom_GRCh38.size\",\n \"hdf5_file\": resource_path + \"file_index.hdf5\"\n }\n\n output_files = {\n \"bb_file\": resource_path + \"sample.bb\"\n }\n\n metadata = {\n \"bed\": Metadata(\n \"data_rnaseq\", \"bed\", \"test_bed_location\", [], {'assembly': 'test'}),\n \"hdf5_file\": Metadata(\n \"data_file\", \"hdf5\", \"test_location\", [], {}\n )\n }\n\n bs_handle = bedIndexerTool({\"bed_type\": \"bed6+4\"})\n bs_handle.run(input_files, metadata, output_files)\n\n print(resource_path)\n assert os.path.isfile(resource_path + \"sample.bb\") is True\n assert os.path.getsize(resource_path + \"sample.bb\") > 0\n","repo_name":"Multiscale-Genomics/mg-process-files","sub_path":"mg_process_files/tests/test_bed_functions.py","file_name":"test_bed_functions.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71690809042","text":"# Kunal's attempt at Markov bots\n\nimport random\nimport pickle\n\ndef main(message):\n\tmarkovDepth = 2\n\tmarkovChain = {}\n\tstartWords = []\n\t# inputString = \"My name is Kunal.\"\n\t# inputString = importTrainingSet(\"input/The Hunger Games.txt\")\n\tinputString = message\n\tmarkovChain = unpickleObject(\"brains/discordTest1.txt\")\n\tstartWords = unpickleObject(\"startWords/discordTest1.txt\")\n\tmarkovChain, startWords = createMarkovChain(markovChain, startWords, inputString, markovDepth)\n\tpickleObject(markovChain, \"brains/discordTest1.txt\")\n\tpickleObject(startWords, \"startWords/discordTest1.txt\")\n\n\treturn printRandom(markovChain, startWords, markovDepth)\n\n# Picks a random starting word and follows it down the markov chain till it encounters\n# a period, exclamation or question mark. A starting word is defined as any word that \n# begins with a capital letter.\ndef printRandom(markovChain, startWords, markovDepth):\n\tstart = random.choice(startWords)\n\treply = start \n\tnextWord = start\n\t\n\twhile reply[-1]!=\".\" and reply[-1]!=\"!\" and reply[-1]!=\"?\":\n\t\ttry:\n\t\t\tnextWord = random.choice(markovChain[nextWord])\n\t\texcept KeyError:\n\t\t\tnextWord = random.choice(markovChain.keys())\n\t\treply = reply + \" \" + nextWord\n\t\tnextWord = \" \".join(reply.split()[-markovDepth:])\n\t\n\t# print (reply)\n\treturn reply\n\n# Keys and values in the markov chain correspond to groups of words and the word\n# which most commonly follow them. Markov depth is the variable which dictates \n# how many words are included in a group to form the key. For example -\n# inputString = \"My name is Kunal.\"\n# markovDepth = 1\n# Resulting Markov associations - \n# {'is': ['Kunal.'], 'My': ['name'], 'name': ['is']} \n# markovDepth = 2\n# Resulting Markov associations - \t\t\n# {'My name': ['is'], 'name is': ['Kunal.']}\ndef createMarkovChain(markovChain, startWords, inputString, markovDepth):\n\tinputString = inputString.split()\n\n\tfor i in range(0, len(inputString) - markovDepth):\n\t\tkey = \"\"\n\t\tfor j in range(i, i+markovDepth-1):\n\t\t\tkey = key + inputString[j] + \" \"\n\t\tkey = key + inputString[i+markovDepth-1]\n\t\tval = inputString[i+markovDepth]\n\n\t\t# This list is used to start sentences with Capital letters\n\t\tif key[0].isupper():\n\t\t\tstartWords.append(key)\n\n\t\t# Adding new key association to chain\n\t\tif key not in markovChain:\n\t\t\tmarkovChain[key] = []\n\t\tmarkovChain[key].append(val)\n\n\treturn markovChain, startWords\n\ndef importTrainingSet(filename):\n\twith open(filename, 'r') as myfile:\n\t\tdata = myfile.read().replace('\\n', ' ')\n\treturn data\n\ndef pickleObject(markovChain, filename):\n\toutput = open(filename, 'wb')\n\tpickle.dump(markovChain, output)\n\toutput.close()\n\ndef unpickleObject(filename):\n\toutput = open(filename, 'rb')\n\tresult = pickle.load(output)\n\treturn result\n\n# main(\"Mei is the best defense character. This is important, you need to remember it.\")","repo_name":"kunal3/markov-bot","sub_path":"markov.py","file_name":"markov.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35763989202","text":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, Input, BatchNormalization, Activation, Add\nimport os\nimport math\nfrom typing import Optional, Dict, Tuple, Any\n\nfrom game import Game, State\nimport constants as c\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nparent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\nclass NNet:\n \"\"\"\n Neural network consisting of residual convolutional layers splitting into policy and value outputs.\n \"\"\"\n\n def __init__(self, epochs: int = c.DEFAULT_EPOCHS, learning_rate: float = c.DEFAULT_LEARNING_RATE,\n batch_size: int = c.DEFAULT_BATCH_SIZE, model_name: str = c.DEFAULT_MODEL_NAME,\n load_data: bool = True):\n\n self.epochs = epochs\n self.batch_size = batch_size\n\n self.model_name = model_name\n self.model = self._get_model(learning_rate, load_data, model_name)\n\n @classmethod\n def _get_model(cls, learning_rate: float, load_data: bool, model_name: str) -> keras.Model:\n\n inputs = Input(shape=(c.ROWS, c.COLUMNS, 6 * 2 + 6))\n\n x = Conv2D(filters=256, kernel_size=(3, 3), padding='same')(inputs)\n x = BatchNormalization(axis=3)(x)\n x = Activation('relu')(x)\n\n for _ in range(5):\n x = cls._res_net(inputs=x, filters=256, kernel_size=(3, 3))\n\n policy = Conv2D(filters=256, kernel_size=(3, 3), padding='valid')(x)\n policy = BatchNormalization(axis=3)(policy)\n policy = Activation('relu')(policy)\n policy = Flatten()(policy)\n policy = Dense(256, activation='relu')(policy)\n policy = Dense((c.ROWS * c.COLUMNS) ** 2, activation='softmax', name='policy')(policy)\n\n value = Conv2D(filters=128, kernel_size=(3, 3), padding='valid')(x)\n value = BatchNormalization(axis=3)(value)\n value = Activation('relu')(value)\n value = Flatten()(value)\n value = Dense(1, activation='sigmoid', name='value')(value)\n\n model = keras.Model(inputs=inputs, outputs=[policy, value])\n\n model.compile(\n optimizer=tf.optimizers.Adam(learning_rate=learning_rate),\n loss={'value': 'mean_squared_error',\n 'policy': 'categorical_crossentropy'}\n )\n\n if load_data:\n try:\n model.load_weights(f'{parent_dir}\\\\weights\\\\{model_name}\\\\').expect_partial()\n except ValueError:\n print('No saved weights found')\n\n return model\n\n @staticmethod\n def _res_net(inputs: Any, filters: int, kernel_size: tuple) -> Any:\n x_shortcut = inputs\n\n x = Conv2D(filters=filters, kernel_size=kernel_size, padding='same')(inputs)\n x = BatchNormalization(axis=3)(x)\n x = Activation('relu')(x)\n\n x = Conv2D(filters=filters, kernel_size=kernel_size, padding='same')(x)\n x = BatchNormalization(axis=3)(x)\n\n x = Add()([x, x_shortcut])\n x = Activation('relu')(x)\n return x\n\n def train(self, examples: list, save_data=False) -> None:\n \"\"\"\n Trains the neural network from a list of training examples.\n\n :param examples: Training data as List[(state,(policy,value))]\n :param save_data: Always saves the new weights if True\n \"\"\"\n x_train = np.array([self._to_binary_state(example[0]) for example in examples])\n y_policy = np.array([self._to_policy_vector(example[1][0], example[0].player) for example in examples])\n y_value = np.array([self._get_value(example[1][1], example[0].player) for example in examples])\n\n self.model.fit(x=x_train, y={'policy': y_policy, 'value': y_value},\n epochs=self.epochs, batch_size=self.batch_size, shuffle=True)\n if save_data:\n self.model.save_weights(f'{parent_dir}\\\\weights\\\\{self.model_name}\\\\')\n\n def prediction(self, state: State) -> Tuple[dict, float]:\n \"\"\"\n Returns a policy and value prediction for a given state. Value is from the perspective of the player making\n the next move.\n\n :param state: State to evaluate\n :return: (policy, vector). Policy is given as probability vector and value between 0 and 1.\n \"\"\"\n binary_state = self._to_binary_state(state)\n prediction = self.model.predict(np.array([binary_state]))\n\n policy = self._get_policy(prediction[0][0], state)\n value = prediction[1][0][0]\n return policy, value\n\n # policy vectors are from the perspective of the player making the move\n @classmethod\n def _to_policy_vector(cls, move: tuple, player: str) -> np.array:\n policy = np.zeros(c.ROWS ** 2 * c.COLUMNS ** 2)\n policy[cls._policy_index(move, player)] = 1\n return policy\n\n @staticmethod\n def _policy_index(move: tuple, player: str) -> int:\n if player == 'black':\n # mirror row of move\n move = ((c.ROWS - move[0][0] - 1, move[0][1]), (c.ROWS - move[1][0] - 1, move[1][1]))\n base = (1, c.ROWS, c.ROWS * c.COLUMNS, c.ROWS * c.COLUMNS * c.ROWS)\n return move[0][0] * base[0] + move[0][1] * base[1] + move[1][0] * base[2] + move[1][1] * base[3]\n\n @classmethod\n def _get_policy(cls, policy: np.ndarray, state: State) -> Dict:\n legal_moves = Game.get_legal_moves(state)\n policy_dict = {move: policy[cls._policy_index(move, state.player)] for move in legal_moves}\n value_sum = sum(policy_dict.values())\n return {move: value / value_sum for move, value in policy_dict.items()}\n\n @staticmethod\n def _get_value(evaluation, player):\n evaluation *= c.ALPHA_SIGMOID\n value = 1 / (1 + math.exp(-evaluation))\n if player == 'black':\n value = 1 - value\n return value\n\n # binary states are from the perspective of the player making the move\n @classmethod\n def _to_binary_state(cls, state: State) -> np.array:\n black = state.player == 'black'\n bin_state = np.zeros(shape=(c.ROWS, c.COLUMNS, 6 * 2 + 6))\n for row in range(c.ROWS):\n for column in range(c.COLUMNS):\n index = cls._piece_index(state.board[row][column])\n if index:\n piece_index = index[1] + 6 * int(state.player == index[0])\n bin_state[row, column, piece_index] = 1\n\n for i, right in enumerate(state.castle_rights):\n if black:\n i = i + 2 % 4\n bin_state[row, column, 12 + i] = 1\n\n if black:\n bin_state[row, column, 17] = 1\n\n if state.en_passant:\n bin_state[state.en_passant[0], state.en_passant[1], 16] = 1\n\n if black:\n bin_state = np.flip(bin_state, axis=0)\n return bin_state\n\n @staticmethod\n def _piece_index(piece: str) -> Optional[tuple]:\n if piece == 'empty':\n return None\n piece = piece.split('_')\n typing = {\n 'pawn': 0,\n 'knight': 1,\n 'bishop': 2,\n 'rook': 3,\n 'queen': 4,\n 'king': 5\n }\n return piece[0], typing.get(piece[1])\n\n\nif __name__ == '__main__':\n nn = NNet()\n game = Game('8/1P3k2/8/8/8/8/4K3/8 w - - 0 1')\n print(nn.prediction(game.state))\n","repo_name":"ItsFabby/chess","sub_path":"core/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":7338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70746909843","text":"#!/usr/bin/env python\n# File: legendre.py\n# Name: D.Saravanan\n# Date: 31/08/2021\n\n\"\"\" Script to calculate and plot Legendre polynomials \"\"\"\n\nimport numpy as np\nfrom scipy.special import legendre\nimport matplotlib\nmatplotlib.rcParams['pgf.texsystem'] = 'pdflatex'\nmatplotlib.rcParams.update({'font.family': 'serif', 'font.size': 8,\n 'axes.labelsize': 10, 'axes.titlesize': 10, 'figure.titlesize': 10})\nmatplotlib.rcParams['text.usetex'] = True\nimport matplotlib.pyplot as plt\nmatplotlib.use('Agg')\n\nfig, ax = plt.subplots()\n\nfor n in range(5): \n\n Pn = legendre(n)\n\n x = np.arange(-1, 1, 0.0001)\n y = Pn(x)\n\n ax.plot(x, y, label=r'$P_{}(x)$'.format(n))\n\nax.set(xlabel=r'$x$', ylabel=r'$P_{n}(x)$')\nax.set_title(r'Legendre polynomials')\nax.grid(); ax.legend()\nplt.savefig('legendre.pdf')\n","repo_name":"dsarvan/nmsc","sub_path":"Scripts/Python/Aug_31/legendre.py","file_name":"legendre.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"16260526181","text":"from django.utils.translation import gettext_lazy as _\n\n\n# Activation types\nACTIVATION_TYPE_ACTIVE = 'active'\nACTIVATION_TYPE_PASSIVE = 'passive'\nACTIVATION_TYPES = (\n (ACTIVATION_TYPE_ACTIVE, _(\"actif\")),\n (ACTIVATION_TYPE_PASSIVE, _(\"passif\"))\n)\n\n# Character types\nCHARACTER_TYPE_PC = 'pc'\nCHARACTER_TYPE_NPC = 'npc'\nCHARACTER_TYPE_MINION = 'minion'\nCHARACTER_TYPE_RIVAL = 'rival'\nCHARACTER_TYPE_NEMESIS = 'nemesis'\nCHARACTER_TYPES = (\n (CHARACTER_TYPE_PC, _(\"personnage joueur\")),\n (CHARACTER_TYPE_NPC, _(\"personnage non joueur\")),\n (CHARACTER_TYPE_MINION, _(\"sbire\")),\n (CHARACTER_TYPE_RIVAL, _(\"rival\")),\n (CHARACTER_TYPE_NEMESIS, _(\"nemesis\"))\n)\n\n# Dice\n# Dice types\nDICE_TYPE_FORTUNE = 'fortune'\nDICE_TYPE_MISFORTUNE = 'misfortune'\nDICE_TYPE_APTITUDE = 'aptitude'\nDICE_TYPE_DIFFICULTY = 'difficulty'\nDICE_TYPE_MASTERY = 'mastery'\nDICE_TYPE_CHALLENGE = 'challenge'\nDICE_TYPE_FORCE = 'force'\nDICE_TYPES = (\n (DICE_TYPE_FORTUNE, _(\"fortune\")),\n (DICE_TYPE_MISFORTUNE, _(\"infortune\")),\n (DICE_TYPE_APTITUDE, _(\"aptitude\")),\n (DICE_TYPE_DIFFICULTY, _(\"difficulté\")),\n (DICE_TYPE_MASTERY, _(\"maitrise\")),\n (DICE_TYPE_CHALLENGE, _(\"défi\")),\n (DICE_TYPE_FORCE, _(\"force\"))\n)\n\n# Dice values\nDICE_SUCCESS = 'success'\nDICE_FAILURE = 'failure'\nDICE_ADVANTAGE = 'advantage'\nDICE_THREAT = 'threat'\nDICE_TRIUMPH = 'triumph'\nDICE_DISASTER = 'disaster'\nDICE_DARK_FORCE = 'dark_force'\nDICE_LIGHT_FORCE = 'light_force'\n\nDICE = {\n DICE_TYPE_FORTUNE: {\n 0: None, 1: None,\n 2: {DICE_SUCCESS: 1},\n 3: {DICE_SUCCESS: 1, DICE_ADVANTAGE: 1},\n 4: {DICE_ADVANTAGE: 2},\n 5: {DICE_ADVANTAGE: 1}\n },\n DICE_TYPE_MISFORTUNE: {\n 0: None, 1: None,\n 2: {DICE_FAILURE: 1},\n 3: {DICE_FAILURE: 1},\n 4: {DICE_THREAT: 1},\n 5: {DICE_THREAT: 1}\n },\n DICE_TYPE_APTITUDE: {\n 0: None,\n 1: {DICE_SUCCESS: 1},\n 2: {DICE_SUCCESS: 1},\n 3: {DICE_SUCCESS: 2},\n 4: {DICE_ADVANTAGE: 1},\n 5: {DICE_ADVANTAGE: 1},\n 6: {DICE_SUCCESS: 1, DICE_ADVANTAGE: 1},\n 7: {DICE_ADVANTAGE: 2}\n },\n DICE_TYPE_DIFFICULTY: {\n 0: None,\n 1: {DICE_FAILURE: 1},\n 2: {DICE_FAILURE: 2},\n 3: {DICE_THREAT: 1},\n 4: {DICE_THREAT: 1},\n 5: {DICE_THREAT: 1},\n 6: {DICE_THREAT: 2},\n 7: {DICE_FAILURE: 1, DICE_THREAT: 1}\n },\n DICE_TYPE_MASTERY: {\n 0: None,\n 1: {DICE_SUCCESS: 1},\n 2: {DICE_SUCCESS: 1},\n 3: {DICE_SUCCESS: 2},\n 4: {DICE_SUCCESS: 2},\n 5: {DICE_ADVANTAGE: 1},\n 6: {DICE_SUCCESS: 1, DICE_ADVANTAGE: 1},\n 7: {DICE_SUCCESS: 1, DICE_ADVANTAGE: 1},\n 8: {DICE_SUCCESS: 1, DICE_ADVANTAGE: 1},\n 9: {DICE_ADVANTAGE: 2},\n 10: {DICE_ADVANTAGE: 2},\n 11: {DICE_TRIUMPH: 1}\n },\n DICE_TYPE_CHALLENGE: {\n 0: None,\n 1: {DICE_FAILURE: 1},\n 2: {DICE_FAILURE: 1},\n 3: {DICE_FAILURE: 2},\n 4: {DICE_FAILURE: 2},\n 5: {DICE_THREAT: 1},\n 6: {DICE_THREAT: 1},\n 7: {DICE_FAILURE: 1, DICE_THREAT: 1},\n 8: {DICE_FAILURE: 1, DICE_THREAT: 1},\n 9: {DICE_THREAT: 2},\n 10: {DICE_THREAT: 2},\n 11: {DICE_DISASTER: 1}\n },\n DICE_TYPE_FORCE: {\n 0: {DICE_DARK_FORCE: 1},\n 1: {DICE_DARK_FORCE: 1},\n 2: {DICE_DARK_FORCE: 1},\n 3: {DICE_DARK_FORCE: 1},\n 4: {DICE_DARK_FORCE: 1},\n 5: {DICE_DARK_FORCE: 1},\n 6: {DICE_DARK_FORCE: 2},\n 7: {DICE_LIGHT_FORCE: 1},\n 8: {DICE_LIGHT_FORCE: 1},\n 9: {DICE_LIGHT_FORCE: 2},\n 10: {DICE_LIGHT_FORCE: 2},\n 11: {DICE_LIGHT_FORCE: 2}\n }\n}\n\n# Test difficulty\nDIFFICULTY_SIMPLE = 0\nDIFFICULTY_EASY = 1\nDIFFICULTY_AVERAGE = 2\nDIFFICULTY_HARD = 3\nDIFFICULTY_DAUNTING = 4\nDIFFICULTY_FORMIDABLE = 5\n\n# EFFECTS\n# EFFECT DURATIONS\nEFFECT_DURATION_DIRECT = 'direct'\nEFFECT_DURATION_PERMANENT = 'permanent'\nEFFECT_DURATION_SOURCE_TURN = 'source_turn'\nEFFECT_DURATION_TARGET_TURN = 'target_turn'\nEFFECT_DURATION_FIGHT = 'fight'\nEFFECT_DURATIONS = (\n (EFFECT_DURATION_DIRECT, _(\"direct (one shot)\")),\n (EFFECT_DURATION_PERMANENT, _(\"permanent\")),\n (EFFECT_DURATION_SOURCE_TURN, _(\"nombre de tours (source)\")),\n (EFFECT_DURATION_TARGET_TURN, _(\"nombre de tours (cible)\")),\n (EFFECT_DURATION_FIGHT, _(\"durée du combat\")),\n)\n\n# EFFECT TYPES\nEFFECT_ATTRIBUTE_MODIFIER = 'attribute_modifier'\nEFFECT_DICE_POOL_MODIFIER = 'dice_pool_modifier'\nEFFECT_HEALTH_MODIFIER = 'health_modifier'\nEFFECT_STRAIN_MODIFIER = 'strain_modifier'\nEFFECT_TYPES = (\n (EFFECT_ATTRIBUTE_MODIFIER, _(\"modificateur d'attribut\")),\n (EFFECT_HEALTH_MODIFIER, _(\"modificateur de santé\")),\n (EFFECT_DICE_POOL_MODIFIER, _(\"modificateur de dés\")),\n (EFFECT_STRAIN_MODIFIER, _(\"modificateur de stress\"))\n)\n\n# ITEM TYPES\nITEM_WEAPON = 'weapon'\nITEM_ARMOR = 'armor'\nITEM_CONSUMABLE = 'consumable'\nITEM_MISC = 'misc'\nITEM_TYPES = (\n (ITEM_WEAPON, _(\"arme\")),\n (ITEM_ARMOR, _(\"armure\")),\n (ITEM_CONSUMABLE, _(\"consommable\")),\n (ITEM_MISC, _(\"autre\"))\n)\n\n\n# RANGE BANDS\nRANGE_ENGAGED = 'engaged'\nRANGE_SHORT = 'short'\nRANGE_MEDIUM = 'medium'\nRANGE_LONG = 'long'\nRANGE_EXTREME = 'extreme'\nRANGE_BANDS = (\n (RANGE_ENGAGED, _(\"corps à corps\")),\n (RANGE_SHORT, _(\"portée courte\")),\n (RANGE_MEDIUM, _(\"portée moyenne\")),\n (RANGE_LONG, _(\"portée longue\")),\n (RANGE_EXTREME, _(\"portée extrème\")),\n)\n\n\n# Stats\nSTAT_AGILITY = 'agility'\nSTAT_CUNNING = 'cunning'\nSTAT_BRAWN = 'brawn'\nSTAT_INTELLECT = 'intellect'\nSTAT_PRESENCE = 'presence'\nSTAT_WILLPOWER = 'willpower'\nSTAT_FORCE = 'force'\nSTATS = (\n (STAT_AGILITY, _(\"agilité\")),\n (STAT_CUNNING, _(\"ruse\")),\n (STAT_BRAWN, _(\"vigueur\")),\n (STAT_INTELLECT, _(\"intelligence\")),\n (STAT_PRESENCE, _(\"présence\")),\n (STAT_WILLPOWER, _(\"volonté\")),\n (STAT_FORCE, _(\"force\"))\n)\nDICT_STATS = dict(STATS)\n\n\n# Skills\nATHLETICS = 'athletics'\nASTROGATION = 'astrogation'\nBRAWL = 'brawl'\nCHARM = 'charm'\nCOERCION = 'coercion'\nCOMPUTERS = 'computers'\nCOOL = 'cool'\nCOORDINATION = 'coordination'\nCORE_WORLD = 'core_world'\nDECEPTION = 'deception'\nDISCIPLINE = 'discipline'\nEDUCATION = 'education'\nGUNNERY = 'gunnery'\nLEADERSHIP = 'leadership'\nLIGHTSABER = 'lightsaber'\nLORE = 'lore'\nMECHANICS = 'mechanics'\nMEDECINE = 'medecine'\nMELEE = 'melee'\nNEGOCIATION = 'negociation'\nOUTER_RIM = 'outer_rim'\nPERCEPTION = 'perception'\nPILOTING = 'piloting'\nRANGED_HEAVY = 'ranged_heavy'\nRANGED_LIGHT = 'ranged_light'\nRESILIENCE = 'resilience'\nSKULDUGGERY = 'skulduggery'\nSTEALTH = 'stealth'\nSTREETWISE = 'streetwise'\nSURVIVAL = 'survival'\nUNDERWORLD = 'underworld'\nVIGILANCE = 'vigilance'\nXENOLOGY = 'xenology'\n\nITEM_SKILLS = (\n (BRAWL, _(\"pugilat\")),\n (GUNNERY, _(\"artillerie\")),\n (LIGHTSABER, _(\"sabre laser\")),\n (MECHANICS, _(\"mécanique\")),\n (MEDECINE, _(\"médecine\")),\n (MELEE, _(\"corps à corps\")),\n (RANGED_HEAVY, _(\"distance (armes lourdes)\")),\n (RANGED_LIGHT, _(\"distance (armes légères)\")),\n)\n\nALL_SKILLS = ITEM_SKILLS + (\n (ATHLETICS, _(\"athlétisme\")),\n (ASTROGATION, _(\"astrogation\")),\n (CHARM, _(\"charme\")),\n (COERCION, _(\"coercition\")),\n (COMPUTERS, _(\"informatique\")),\n (COOL, _(\"calme\")),\n (COORDINATION, _(\"coordination\")),\n (CORE_WORLD, _(\"mondes du noyau\")),\n (DECEPTION, _(\"tromperie\")),\n (DISCIPLINE, _(\"sang froid\")),\n (EDUCATION, _(\"education\")),\n (LEADERSHIP, _(\"commandement\")),\n (LORE, _(\"culture\")),\n (NEGOCIATION, _(\"negociation\")),\n (OUTER_RIM, _(\"bordure exterieure\")),\n (PERCEPTION, _(\"perception\")),\n (PILOTING, _(\"pilotage\")),\n (RESILIENCE, _(\"résistance\")),\n (SKULDUGGERY, _(\"magouilles\")),\n (STEALTH, _(\"discretion\")),\n (STREETWISE, _(\"système D\")),\n (SURVIVAL, _(\"survie\")),\n (UNDERWORLD, _(\"pègre\")),\n (VIGILANCE, _(\"vigilance\")),\n (XENOLOGY, _(\"xénologie\"))\n)\nDICT_SKILLS = dict(ALL_SKILLS)\n\n\n# Skill dependancies\nSKILL_DEPENDANCIES = {\n STAT_BRAWN: (ATHLETICS, BRAWL, LIGHTSABER, MELEE, RESILIENCE, ),\n STAT_AGILITY: (COORDINATION, GUNNERY, PILOTING, RANGED_HEAVY, RANGED_LIGHT, STEALTH, ),\n STAT_INTELLECT: (ASTROGATION, COMPUTERS, CORE_WORLD, EDUCATION, LORE, MECHANICS,\n MEDECINE, OUTER_RIM, UNDERWORLD, XENOLOGY),\n STAT_CUNNING: (DECEPTION, PERCEPTION, SKULDUGGERY, STREETWISE, SURVIVAL, ),\n STAT_WILLPOWER: (COERCION, DISCIPLINE, VIGILANCE, ),\n STAT_PRESENCE: (CHARM, COOL, LEADERSHIP, NEGOCIATION, )\n}\n\n# EFFECT ATTRIBUTES (STATS + SKILLS + PROPERTIES)\nATTRIBUTE_DEFENSE = 'defense'\nATTRIBUTE_MAX_HEALTH = 'max_health'\nATTRIBUTE_MAX_STRAIN = 'max_strain'\nATTRIBUTE_SOAK_VALUE = 'soak_value'\nATTRIBUTES = STATS + ALL_SKILLS + (\n (ATTRIBUTE_DEFENSE, _(\"défense\")),\n (ATTRIBUTE_MAX_HEALTH, _(\"santé max\")),\n (ATTRIBUTE_MAX_STRAIN, _(\"stress max\")),\n (ATTRIBUTE_SOAK_VALUE, _(\"valeur d'encaissement\"))\n)\n\n# SPECIES\nSPECIES_HUMAN = 'human'\nSPECIES_TWILEK = 'twilek'\nSPECIES_BOTHAN = 'bothan'\nSPECIES_DROID = 'droid'\nSPECIES_GAND = 'gand'\nSPECIES_RODIAN = 'rodian'\nSPECIES_TRANDOSHAN = 'trandoshan'\nSPECIES_WOOKIE = 'wookie'\nSPECIES_CEREAN = 'cerean'\nSPECIES_KELDOR = 'keldor'\nSPECIES_MIRIALAN = 'mirialan'\nSPECIES_NAUTOLAN = 'nautolan'\nSPECIES_TOGRUTA = 'togruta'\nSPECIES_ZABRAK = 'zabrak'\nSPECIES_CREATURE = 'creature'\nSPECIES = (\n # Common\n (SPECIES_HUMAN, _(\"humain\")),\n (SPECIES_TWILEK, _(\"twi'lek\")),\n # Edge of the Empire\n (SPECIES_BOTHAN, _(\"bothan\")),\n (SPECIES_DROID, _(\"droïde\")),\n (SPECIES_GAND, _(\"gand\")),\n (SPECIES_RODIAN, _(\"rodien\")),\n (SPECIES_TRANDOSHAN, _(\"trandoshan\")),\n (SPECIES_WOOKIE, _(\"wookie\")),\n # Force and Destiny\n (SPECIES_CEREAN, _(\"céréen\")),\n (SPECIES_KELDOR, _(\"kel'dor\")),\n (SPECIES_MIRIALAN, _(\"mirialan\")),\n (SPECIES_NAUTOLAN, _(\"nautolan\")),\n (SPECIES_TOGRUTA, _(\"togruta\")),\n (SPECIES_ZABRAK, _(\"zabrak\")),\n # Other\n (SPECIES_CREATURE, _(\"créature\")),\n)\n\n\n# SPECIES_ABILITIES - default=10\nSPECIES_ABILITIES = {\n SPECIES_BOTHAN: {'max_strain': 11},\n SPECIES_CEREAN: {'max_strain': 13},\n SPECIES_MIRIALAN: {'max_health': 11},\n SPECIES_NAUTOLAN: {'max_health': 11, 'max_strain': 9},\n SPECIES_TRANDOSHAN: {'max_health': 12, 'max_strain': 9},\n SPECIES_TWILEK: {'max_strain': 11},\n SPECIES_WOOKIE: {'max_health': 14, 'max_strain': 8},\n}\n","repo_name":"Izymask/starwars","sub_path":"starwars/enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":10336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"8127577493","text":"#!/bin/env python2\n\nimport sys\nsys.path.insert(0, 'lib')\n\nfrom collections import defaultdict\nimport bs4\nfrom bs4 import BeautifulSoup as BS\nimport requests as R\nimport re\nimport datetime\nimport pickle\nimport os\nimport time\n\n# don't import model in running as stand alone script\nif os.environ.get('SERVER_SOFTWARE', ''):\n import model\n\n\nCATALOG_URL = 'http://a.4cdn.org/mu/catalog.json'\nTHREAD_URL = 'http://a.4cdn.org/mu/thread/%d.json'\nTHREAD_SUB_RX = re.compile(r'bandcamp.+(?:topic|thread|general|station)', flags=re.IGNORECASE)\n\nTHREAD_FN_RX = re.compile(r'\\bbc\\b|bandcamp', flags=re.IGNORECASE)\nTHREAD_MIN_LINK = 3\nDOWNLOAD_DELAY = .5\n\ndef textify(html):\n # div hack to prevent BS UserWarning about html looking like a url\n return BS(''+html+'
').get_text()\n\n#\n# Post and Thread class to handle 4chan stuff\n#\n\nclass Post:\n def __init__(self, json=None, prop=None, thr=None):\n self.prop = prop\n self.thr = thr\n\n if prop is not None:\n self.json = prop.json\n elif json is not None:\n self.json = json\n\n\n def to_prop(self):\n if self.prop:\n self.prop.json = self.json\n else:\n self.prop = model.PostProp(json=self.json)\n return self.prop\n\n def filename(self, ext=None):\n fn = self.json.get('filename', '')\n if ext:\n fn += self.json.get('ext', '')\n return fn\n\n def id(self):\n return self.json['no'] # must exist\n\n def sub(self):\n return self.json.get('sub', '')\n\n def com(self):\n com = self.json.get('com', '')\n com = re.sub('
', '
', com)\n com = re.sub('', '', com)\n return urlify_dumb(com)\n\n def timestamp(self):\n return self.json['time']\n\n def datetime(self):\n return datetime.datetime.fromtimestamp(self.timestamp())\n\n def refs(self):\n ids = re.findall(r''' 0:\n return Post(json=self.json['last_replies'][-1]).datetime()\n else:\n return self.posts[-1].datetime()\n\n def newer_than(self, thr):\n return self.last_datetime() > thr.last_datetime()\n\n def is_band_thread(self):\n n = 0\n for p in self.posts:\n if p.is_band():\n n += 1\n\n if n < THREAD_MIN_LINK:\n return False\n\n # sharethreads are not band threads\n if re.search(r'share\\s*thread', textify(self.sub()), flags=re.IGNORECASE):\n return False\n\n if re.search(THREAD_SUB_RX, textify(self.sub())):\n return True\n if re.search(THREAD_SUB_RX, textify(self.com())):\n return True\n\n return False\n\n def build_ref_index(self):\n d = defaultdict(set)\n self.rindex = defaultdict(list)\n\n for p in self.posts:\n for r in p.refs():\n d[r].add(p)\n for k in d:\n self.rindex[k] = sorted(d[k])\n\n\ndef get_catalog_threads(full_thread=True, band_filter=True):\n data = R.get(CATALOG_URL).json()\n time.sleep(DOWNLOAD_DELAY)\n\n r = []\n for page in data:\n for tjson in page['threads']:\n t = Thread(json=tjson)\n if full_thread:\n t.update()\n if band_filter and t.is_band_thread():\n r.append(t)\n return r\n\n\n\ndef repl_url(m):\n proto = m.group(1)\n link = m.group(0)\n\n if proto and proto.startswith('http'):\n return '%s' % (link, link)\n else:\n return '%s' % (link, link)\n\ndef urlify_dumb(source):\n return re.sub(r'''(?:(https?)://)?[^<>\\s;&]{2,}[^\\s<>;&\\.]\\.[^\\s<>;&\\.][^\\s<>;&]{1,}''', repl_url, source)\n\ndef urlify(source):\n b = BS(source)\n for e in b.contents:\n if type(e) == bs4.element.NavigableString:\n txt = unicode(e)\n rep = re.sub(r'''(?:(https?)://)?\\S{3,}\\.\\S{2,}''', repl_url, txt)\n e.replace_with(BS(rep))\n return unicode(b)\n","repo_name":"aaptel/mumusic","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":6522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70637038482","text":"# 09_16_2014.py\n# Script from Practical intro to research 09/16/14\n# Jacob Hummel\n\n\nimport numpy as np\nfrom scipy import optimize\nfrom matplotlib import pyplot as plt\n\n#import matplotlib as mpl\n#mpl.rc('figure', figsize=(16,12))\n\ndata = np.loadtxt('data/co2_monthly_data.txt')\n\ntime = data[:,2]\nco2 = data[:,4]\n\nplt.clf()\nplt.plot(time, co2, label='Monthly Mean')\nplt.xlabel('Time [yr]')\nplt.ylabel('CO2 Mole Fraction [ppm]')\n\n\ndef fit(x, a, b, c):\n return a*x**2 + b*x + c\n\ncoeff, err = optimize.curve_fit(fit, time, co2)\na,b,c = coeff\n\ntime = np.linspace(1958, 2040)\nplt.plot(time, fit(time, a,b,c), label='our fit')\nplt.legend(loc=0)\n","repo_name":"hummel/AST376_FALL2014","sub_path":"labs/Sept16.py","file_name":"Sept16.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"16475879424","text":"__doc__='''Machinery to support through-the-web editing\n\n$Id: DT_UI.py,v 1.1 2003/04/16 02:53:49 sc Exp $''' \n__version__='$Revision: 1.1 $'[11:-2]\n\nfrom DT_HTML import HTML\n\nFactoryDefaultString=\"Factory Default\"\n\nHTML.document_template_edit_header='Edit Document
'\nHTML.document_template_form_header=''\nHTML.document_template_edit_footer=(\n \"\"\"\n \n © 1997 Digital Creations, L.L.C.\"\"\")\n\nHTML.document_template_edit_width=58\n\nHTML._manage_editForm = HTML(\n \"\"\"\n \n HTML Template Editor\n \n \n \n \n \n \n
\n \n \n \n \"\"\",)\n\nHTML.editConfirmation=HTML(\n \"\"\"Change Successful\n \n \n \n \n
has been changed.\n \n \"\"\")\n","repo_name":"AkankshaGovil/Automation","sub_path":"Nextest_12.xOS-bkup_2_21/opt/nextest/lib/qm-old/external/DocumentTemplate/DT_UI.py","file_name":"DT_UI.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"34374814021","text":"#Importing Libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\r\nfrom sklearn.model_selection import train_test_split,GridSearchCV,cross_val_score\r\nfrom sklearn.metrics import accuracy_score,confusion_matrix\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom xgboost import XGBClassifier\r\n\r\n#Importing Dataset\r\ndataset=pd.read_csv('train.csv')\r\n\r\n#Data Preprocessing\r\n\r\ndataset[\"Age\"]=dataset[\"Age\"].fillna(dataset[\"Age\"].mean())\r\ndataset=dataset.drop(\"Cabin\",axis=1)\r\ndataset=dataset.dropna()\r\nX=dataset.loc[:,[\"Pclass\",\"Sex\",\"Age\",\"SibSp\",\"Parch\",\"Fare\",\"Embarked\"]] \r\nX=X.values\r\nle_class=LabelEncoder()\r\nX[:,0]=le_class.fit_transform(X[:,0])\r\nle_sex=LabelEncoder()\r\nX[:,1]=le_sex.fit_transform(X[:,1])\r\nle_embarked=LabelEncoder()\r\nX[:,6]=le_embarked.fit_transform(X[:,6])\r\nX=np.float64(X)\r\none_class=OneHotEncoder(categorical_features=[0])\r\nX=one_class.fit_transform(X).toarray()\r\nX=X[:,1:]\r\none_embarked=OneHotEncoder(categorical_features=[7])\r\nX=one_embarked.fit_transform(X).toarray()\r\nX=X[:,1:]\r\ny=dataset.loc[:,\"Survived\"]\r\ny=y.values\r\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)\r\n\r\n\r\n\r\n#Training Classifier\r\n\r\n#1 Logistic Regression\r\nlogic=LogisticRegression(max_iter=1000)\r\nlogic.fit(X_train,y_train)\r\nacc=accuracy_score(y_test,logic.predict(X_test))\r\ncm=confusion_matrix(y_test,logic.predict(X_test))\r\nk=cross_val_score(logic,X_train,y_train,cv=10,n_jobs=-1)\r\nparameters={\"C\":[0.5,1,1.2,1.6,1.7,1.8],\"solver\":['newton-cg','lbfgs','sag','saga'],\"verbose\":[0,0.5,1,0.6,0.4]}\r\ngrid=GridSearchCV(logic,param_grid=parameters,cv=10)\r\ngrid=grid.fit(X_train,y_train)\r\n\r\n#2 KNN classifier\r\nknn=KNeighborsClassifier(n_neighbors=5)\r\nknn.fit(X_train,y_train)\r\nacc=accuracy_score(y_test,knn.predict(X_test))\r\ncm=confusion_matrix(y_test,knn.predict(X_test))\r\nk=cross_val_score(knn,X_train,y_train,cv=10,n_jobs=-1)\r\nparameters={\"n_neighbors\":[1,2,3,5,6,7,8,9],\"algorithm\":[\"auto\",\"ball_tree\",\"kd_tree\",\"brute\"]}\r\ngrid=GridSearchCV(knn,parameters,cv=10,n_jobs=-1)\r\ngrid=grid.fit(X_train,y_train)\r\n\r\n\r\n#3 SVM classifier\r\nsvc=SVC()\r\nsvc.fit(X_train,y_train)\r\nacc=accuracy_score(y_test,svc.predict(X_test))\r\ncm=confusion_matrix(y_test,svc.predict(X_test))\r\nk=cross_val_score(svc,X_train,y_train,cv=10,n_jobs=-1)\r\nparameters={\"C\":[0.1,0.2,0.5,0.7,0.8,1.0,1.2,1.4,1.6],\"kernel\":[\"linear\",\"poly\",\"rbf\",\"sigmoid\"],\"gamma\":[\"auto\",\"rbf\",\"poly\",\"sigmoid\"]}\r\ngrid=GridSearchCV(svc,parameters,cv=10,n_jobs=-1)\r\ngrid.fit(X_train,y_train)\r\n\r\n#4 Decision Tree Classifier\r\ndecision=DecisionTreeClassifier()\r\ndecision.fit(X_train,y_train)\r\nacc=accuracy_score(y_test,decision.predict(X_test))\r\ncm=confusion_matrix(y_test,decision.predict(X_test))\r\nk=cross_val_score(decision,X_train,y_train,cv=10,n_jobs=-1)\r\n\r\n#5 Random Forest Classifier\r\nrandom= RandomForestClassifier(n_estimators=100)\r\nrandom.fit(X_train,y_train)\r\nacc=accuracy_score(y_test,random.predict(X_test))\r\ncm=confusion_matrix(y_test,random.predict(X_test))\r\nk=cross_val_score(random,X_train,y_train,cv=10,n_jobs=-1)\r\n\r\n\r\n#6 XGBoost Classifier\r\nclassifier=XGBClassifier()\r\nclassifier.fit(X_train,y_train)\r\nacc=accuracy_score(y_test,classifier.predict(X_test))\r\ncm=confusion_matrix(y_test,classifier.predict(X_test))\r\nk=cross_val_score(classifier,X_train,y_train,cv=10,n_jobs=-1)\r\n","repo_name":"shaswatsunny1998/Titanic_","sub_path":"Titanic_Dataset/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"74283652241","text":"import addonHandler\nimport api\nimport controlTypes\nimport globalPluginHandler\nimport scriptHandler\nimport ui\n\nclass GlobalPlugin(globalPluginHandler.GlobalPlugin):\n\n\tscriptCategory = u\"sayDescription\"\n\n\tdef script_sayFocusObj(self, gesture):\n\t\tfocusObj = api.getFocusObject()\n\t\tfOName = focusObj.name\n\t\tfODc = focusObj.description\n\t\tif scriptHandler.getLastScriptRepeatCount() == 0:\n\t\t\tif fOName == \"\" and fODc == \"\":\n\t\t\t\tui.message(u\"name과 description 값은 비어있음.\")\n\t\t\telif fOName == \"\":\n\t\t\t\tui.message(u\"Description: %s\" % (fODc))\n\t\t\telif fODc == \"\":\n\t\t\t\tui.message(u\"Name: %s\" % (fOName))\n\t\t\telif focusObj.role == controlTypes.ROLE_UNKNOWN:\n\t\t\t\tui.message(u\"알 수 없는 객체: 값을 확인할 수 없음.\")\n\t\t\telse:\n\t\t\t\tui.message(u\"Name: %s, Description: %s\" % (fOName, fODc))\n\t\tif scriptHandler.getLastScriptRepeatCount() == 1:\n\t\t\tif focusObj.role == controlTypes.ROLE_UNKNOWN:\n\t\t\t\tui.message(u\"알 수 없는 객체: 값을 확인할 수 없음.\")\n\t\t\telse:\n\t\t\t\tconvertName = unicode(fOName)\n\t\t\t\tconvertDescription = unicode(fODc)\n\t\t\t\tcpText = u\"Name: \" + convertName + u\"\\t\" + u\"Description: \" + convertDescription\n\t\t\t\tapi.copyToClip(cpText)\n\t\t\t\tui.message(u\"복사됨\")\n\n\tscript_sayFocusObj.__doc__ = _(u\"초점을 받은 객체의 description 값을 확인합니다.\")\n\n\tdef script_sayNavObj(self, gesture):\n\t\tnavObj = api.getNavigatorObject()\n\t\tnavOName = navObj.name\n\t\tnavODc = navObj.description\n\t\tif scriptHandler.getLastScriptRepeatCount() == 0:\n\t\t\tif navOName == \"\" and navODc == \"\":\n\t\t\t\tui.message(u\"name과 description 값은 비어있음.\")\n\t\t\telif navOName == \"\":\n\t\t\t\tui.message(u\"Description: %s\" % (navODc))\n\t\t\telif navODc == \"\":\n\t\t\t\tui.message(u\"Name: %s\" % (navOName))\n\t\t\telif navObj.role == controlTypes.ROLE_UNKNOWN:\n\t\t\t\tui.message(u\"알 수 없는 객체: 값을 확인할 수 없음.\")\n\t\t\telse:\n\t\t\t\tui.message(u\"Name: %s, Description: %s\" % (navOName, navODc))\n\t\tif scriptHandler.getLastScriptRepeatCount() == 1:\n\t\t\tif navObj.role == controlTypes.ROLE_UNKNOWN:\n\t\t\t\tui.message(u\"알 수 없는 객체: 값을 확인할 수 없음.\")\n\t\t\telse:\n\t\t\t\tconvertName = unicode(navOName)\n\t\t\t\tconvertDescription = unicode(navODc)\n\t\t\t\tcpText = u\"Name: \" + convertName + u\"\\t\" + u\"Description: \" + convertDescription\n\t\t\t\tapi.copyToClip(cpText)\n\t\t\t\tui.message(u\"복사됨\")\n\n\tscript_sayNavObj.__doc__ = _(u\"탐색 객체의 description 값을 확인합니다.\")\n","repo_name":"dnz3d4c/sayDescription","sub_path":"addon/globalPlugins/sayDescription/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27207432671","text":"import random\n\n# winning_lotto_number = [] # Placing variable with empty List of to hold numbers \n\n# for i in range(1 , 7): #creating a forloop to be repeated 6 times\n# numbers = random.randint (1,99) #generating random numbers between 1 and 99 \n\n# winning_lotto_number.append(numbers) # getting all the numbers that were generated from the top and putting them in to the list of lottonumbers\n\n\n\n# users_attempt = [] #same thing as before just putting a place holder for the numbers that will be inputed \n\n# for i in range(1,7): #for loop getting ready to as the user 6 times to input a number rather than typing the same thing 6 times\n# numbers = random.randint (1,99)\n\n# users_attempt.append(numbers) if you have to make one of these twice, indicates that you should just use a function\n\ndef number_picker():\n numbers = [] #something to put the nums in \n for i in range(1,7): #Should run the loop 6 times \n numbers.append(random.randint (1,99))\n return numbers\n\n\ndef compare(winning_ticket, current_ticket):\n counter = 0 #keeping track of how many matches \n for i in range(6): #checking the index of the two arguments range is returning an array which starts at the index of 0 and then goes up to 5\n if winning_ticket[i] == current_ticket[i]:# running the 6 times \n counter +=1 # counting how many match \n return counter \n \n\n# print(compare(number_picker(), number_picker())) \n #test\nwinner = number_picker() # winning ticket on the outside so it stays constant\nbalance = 0 # Holder\n\nfor i in range(100000):\n comparing_tickets = compare(number_picker(), winner) #i'm getting my compare function putting my number_picker funtion with in it which is the one thats gonna be getting changed the 100,000 time and comparing it to the winner which is the one that will be staying the same all those times \n balance -= 2 # since the balnce on top is the holder im making it -2 since that is how much it is to pay for a ticket \n if comparing_tickets == 1: # if one of the compared matches has one match in the same spot we get $2 since we were already losing 2\n balance += 4\n elif comparing_tickets == 2:\n balance += 7 \n elif comparing_tickets == 3:\n balance += 100\n elif comparing_tickets == 4:\n balance += 50,000\n elif comparing_tickets == 5:\n balance += 1,000,000\n elif comparing_tickets == 6:\n balance += 25,000,000\n\nreturn_of_in = balance / 200000 # getting the balance and then dividing it bt the 200,000 because thats the two dollars to buy the ticket and multiplying it by the many times we're gonna but the ticket \nprint(f'The winning lotto numbers are {winner}') \nprint(f'\\n and your balance is {balance}')\nprint(f'Your ROI is {return_of_in}')\n\n\n \n\n\n# print(users_attempt)\n# print (winning_lotto_number)\n #test\n\n","repo_name":"PdxCodeGuild/class_HB2","sub_path":"code/Andy/python/lab05_pick_6.py","file_name":"lab05_pick_6.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"741991418","text":"import os\nimport numpy as np\nimport pandas as pd\nimport tensorflow.compat.v1 as tf\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"TRUE\"\n\n\ndef load_data():\n df = pd.read_csv('./rating_sampled.csv')\n movievecs = pd.read_csv('./movie_vec.csv', index_col=[0])\n uservecs = pd.read_csv('./user_vec.csv', index_col=[0])\n train_x = []\n train_y = []\n test_x = []\n test_y = []\n print('processing test data set...')\n for i in range(500000 - 1000, 500000):\n usr = df['userId'][i]\n mv = df['movieId'][i]\n rate = df['rating'][i]\n moviev = eval(movievecs['movieVec'][mv])\n userv = eval(uservecs['userVec'][usr])\n finalv = np.array(moviev + userv)\n test_x.append(finalv)\n test_y.append(rate)\n test_x = np.array(test_x)\n test_y = np.array(test_y)\n test_y = test_y.reshape([test_y.shape[0], 1])\n print('processing train data set...')\n for i in range(500000-1000):\n usr = df['userId'][i]\n mv = df['movieId'][i]\n rate = df['rating'][i]\n moviev = eval(movievecs['movieVec'][mv])\n userv = eval(uservecs['userVec'][usr])\n finalv = np.array(moviev + userv)\n train_x.append(finalv)\n train_y.append(rate)\n train_x = np.array(train_x)\n # train_x = (train_x - np.mean(train_x)) / np.std(train_x)\n train_y = np.array(train_y)\n train_y = train_y.reshape([train_y.shape[0], 1])\n return {'input_train':train_x, 'label_train':train_y, 'input_test':test_x, 'label_test':test_y}\n\n\ndata_sets = load_data()\nif os.path.exists('logs.txt'):\n os.remove('logs.txt')\nlearning_rate = 0.000001\nlocal_iters_num = 30000000\ntrain_batch_size = 64\n\ntf.reset_default_graph()\nsess = tf.Session()\n# Define input placeholders\ninput_placeholder = tf.placeholder(tf.float32, shape=[None, 256])\nlabels_placeholder = tf.placeholder(tf.float32, shape=[None, 1])\n\n# Define variables\nweightsl1 = tf.Variable(tf.random_normal([256, 512]))\nbiasesl1 = tf.Variable(tf.random_normal([512]))\nweightsl2 = tf.Variable(tf.random_normal([512, 128]))\nbiasesl2 = tf.Variable(tf.random_normal([128]))\nweightsl3 = tf.Variable(tf.random_normal([128, 1]))\nbiasesl3 = tf.Variable(tf.random_normal([1]))\n\nnet = input_placeholder\nnet = tf.nn.relu(tf.add(tf.matmul(net, weightsl1), biasesl1))\nnet = tf.nn.relu(tf.add(tf.matmul(net, weightsl2), biasesl2))\nnet = tf.add(tf.matmul(net, weightsl3), biasesl3)\n\nloss = tf.losses.mean_squared_error(net, labels_placeholder)\ntrain_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\nsaver = tf.train.Saver()\n# ..............................................................................\nprint('Begin training')\ninit = tf.global_variables_initializer()\nsess.run(init)\nprint('local epoch num = ', local_iters_num)\nfor i in range(local_iters_num):\n indices = np.random.choice(data_sets['input_train'].shape[0], train_batch_size)\n input_batch = data_sets['input_train'][indices]\n label_batch = data_sets['label_train'][indices]\n sess.run(train_step, feed_dict={input_placeholder: input_batch,\n labels_placeholder: label_batch})\n best_err = 10\n if i % 1000 == 0:\n err = sess.run(abs(net-labels_placeholder), feed_dict={input_placeholder: data_sets['input_test'], labels_placeholder: data_sets['label_test']})\n err = np.sum(err)/1000\n print('Iter {},error {}'.format(i, round(err, 3)))\n with open('logs.txt', 'a') as file:\n file.write('Iter {},error {}\\n'.format(i, round(err, 3)))\n # if i % 10 == 0:\n # train_accuracy = sess.run(accuracy, feed_dict={\n # images_placeholder: input_batch, labels_placeholder: label_batch})\n # print('Step {:5d}: training accuracy {:g}'.format(i, train_accuracy))\n # test_accuracy = sess.run(accuracy, feed_dict={\n # images_placeholder: data_sets['images_test'],\n # labels_placeholder: data_sets['labels_test']})\n # print('Test accuracy {:g}'.format(test_accuracy))\n # if best_acc < test_accuracy:\n # best_acc = test_accuracy\n # saver.save(sess, './tmp/model.ckpt')\n # print('Best accuracy {:g}'.format(best_acc))\n # with open('result.txt','w') as f:\n # f.write('Round {}, Test accuracy {:g}\\n'.format(round_num + 1, test_accuracy))\n # f.write('Best accuracy {:g}\\n'.format(best_acc))\n if err < best_err:\n saver.save(sess, './tmp/model.ckpt')\n best_err = err\n\n","repo_name":"ywjTan/datamining","sub_path":"localtrain.py","file_name":"localtrain.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38547671054","text":"\n\nimport sys\n\nfrom typing import Any\n\nfrom enum import Enum\nfrom decimal import Decimal\n\nfrom datetime import date, time, datetime\n\nfrom pydantic import BaseModel\n\nfrom usefulgram.exceptions import TooMoreCharacters\nfrom usefulgram.enums import Const\n\n\nclass _Additional:\n @staticmethod\n def _add_separator(item: str, separator: str = \"&\") -> str:\n return f\"{item}{separator}\"\n\n def _object_to_str(self, item: object) -> str:\n if isinstance(item, BaseModel):\n fields = item.model_fields\n\n else:\n fields = item.__annotations__\n\n annotations_keys = list(fields.keys())\n\n result = \"\"\n\n for key in annotations_keys:\n if key == \"prefix\":\n continue\n\n values = item.__getattribute__(f\"{key}\")\n\n string_value = self._to_str(values, is_recursion=True)\n\n result += self._add_separator(string_value)\n\n return result[:-1]\n\n def _to_str(self, item: Any, is_recursion: bool = False) -> str:\n if item is None:\n return \"\"\n\n if isinstance(item, bool):\n return str(int(item))\n\n if isinstance(item, str):\n return item\n\n if isinstance(item, (int, float, Decimal)):\n return str(item)\n\n if isinstance(item, (datetime, date, time)):\n return item.strftime(Const.DATETIME_FORMAT)\n\n if isinstance(item, Enum):\n return item.name\n\n if is_recursion:\n return self._object_to_str(item)\n\n try:\n return self._object_to_str(item)\n\n except AttributeError:\n return f\"{item}\"\n\n def __call__(self, *args: Any) -> str:\n if args == ():\n return \"\"\n\n result = \"\"\n\n for item in args:\n result += self._add_separator(self._to_str(item))\n\n result = result[:-1]\n\n return result\n\n\nclass _CallbackData:\n @staticmethod\n def _get_str_callback_data(\n prefix: str, additional: str, separator: str\n ) -> str:\n\n return f\"{prefix}{separator}{additional}\"\n\n @staticmethod\n def _check_callback_data_bytes(callback_data: str) -> bool:\n size = sys.getsizeof(callback_data)\n\n true_size = size - 37 # 37 - is a system empty string lenght\n\n if true_size < 64:\n return True\n\n raise TooMoreCharacters\n\n def __call__(\n self, prefix: str,\n *args: Any,\n separator: str = \"/\") -> str:\n\n additional = AdditionalInstance(*args)\n\n callback_data = self._get_str_callback_data(\n prefix, additional, separator\n )\n\n self._check_callback_data_bytes(callback_data)\n\n return callback_data\n\n\nAdditionalInstance = _Additional()\nCallbackData = _CallbackData()\n","repo_name":"Sethis/usefulgram","sub_path":"usefulgram/parsing/encode.py","file_name":"encode.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21061121613","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 13 22:29:31 2022\n\n@author: Arthur\n\"\"\"\nimport os\nos.environ['KIVY_GL_BACKEND'] = 'angle_sdl2'\n\nfrom functools import partial\n\nfrom kivy.app import App\nfrom kivy.clock import Clock\nfrom kivy.lang import Builder\nfrom kivy.uix.label import Label\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.uix.button import Button\nkv = '''\nBoxLayout:\n orientation: 'vertical'\n Button:\n text: 'add'\n on_release: app.add_new_widget()\n ScrollView:\n id: scroll\n BoxLayout:\n id: box\n spacing:10\n orientation: 'vertical'\n size_hint_y: None\n height: self.minimum_height\n'''\n\nclass Article_layout(FloatLayout):\n def __init__(self, article_str, **kwargs):\n super().__init__(**kwargs)\n self.size_hint= (1,None)\n article_list = article_str.split(';')\n article_title = Label(text=article_list[0], size_hint=(0.5, 0.4), pos_hint={'x':0.0, 'top':1})\n # article_title.background_color = (0, 0, 1, 0.25)\n self.add_widget(article_title)\n article_authors = Label(text=article_list[1],size_hint=(.5, .3),pos_hint={'x':0.0, 'y':0.3})\n self.add_widget(article_authors)\n article_dop = Label(text=article_list[2],size_hint=(.5, .3),pos_hint={'x':0.0, 'y':0.0})\n self.add_widget(article_dop)\n article_source = Label(text=article_list[3],size_hint=(.5, .3),pos_hint={'right':1, 'top':1})\n self.add_widget(article_source)\n article_link = Button(text=\"Lien de l'article\",size_hint=(.3, .3),pos_hint={'right':1, 'y':0})\n self.add_widget(article_link)\n \nclass TestApp(App):\n def build(self):\n self.count = 0\n return Builder.load_string(kv)\n\n def add_new_widget(self):\n vp_height = self.root.ids.scroll.viewport_size[1]\n sv_height = self.root.ids.scroll.height\n\n # add a new widget (must have preset height)\n label = Label(text='Widget #' + str(self.count), size_hint=(1, None), height=50)\n article_layour = Article_layout(article_str='article;authors;dop;source'+ str(self.count), size_hint=(1, None), height=100)\n self.root.ids.box.add_widget(article_layour)\n self.count += 1\n\n if vp_height > sv_height: # otherwise there is no scrolling\n # calculate y value of bottom of scrollview in the viewport\n scroll = self.root.ids.scroll.scroll_y\n bottom = scroll * (vp_height - sv_height)\n\n # use Clock.schedule_once because we need updated viewport height\n # this assumes that new widgets are added at the bottom\n # so the current bottom must increase by the widget height to maintain position\n Clock.schedule_once(partial(self.adjust_scroll, bottom+label.height), -1)\n\n def adjust_scroll(self, bottom, dt):\n vp_height = self.root.ids.scroll.viewport_size[1]\n sv_height = self.root.ids.scroll.height\n self.root.ids.scroll.scroll_y = bottom / (vp_height - sv_height)\n\nTestApp().run()","repo_name":"alejeune88/RSS_feeder","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15779997872","text":"from django.db import models\nfrom decimal import Decimal\nfrom django.core.validators import MinValueValidator, MaxValueValidator\n\n# Create your models here.\n\n\nclass Service(models.Model):\n class ServiceType(models.TextChoices):\n CUT = 'CUT', 'cut'\n COLOUR = 'COLOUR', 'colour'\n STYLE = 'STYLE', 'style'\n name = models.CharField(max_length=100, unique=True)\n service_type = models.CharField(\n max_length=10,\n choices=ServiceType.choices,\n )\n price = models.DecimalField(\n max_digits=5,\n decimal_places=2,\n validators=[MinValueValidator(Decimal('25.00')),\n MaxValueValidator(Decimal('300.00'))],\n )\n\n def __str__(self):\n return self.name\n","repo_name":"JPatel87/test-django","sub_path":"services/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70475926481","text":"from typing import List, Optional\n\nfrom ...tokenization_utils import AddedToken\nfrom ...utils import logging\nfrom ..gpt2.tokenization_gpt2 import GPT2Tokenizer\n\n\nlogger = logging.get_logger(__name__)\n\nVOCAB_FILES_NAMES = {\"vocab_file\": \"vocab.json\", \"merges_file\": \"merges.txt\"}\n\nPRETRAINED_VOCAB_FILES_MAP = {\n \"vocab_file\": {\n \"microsoft/deberta-base\": \"https://huggingface.co/microsoft/deberta-base/resolve/main/vocab.json\",\n \"microsoft/deberta-large\": \"https://huggingface.co/microsoft/deberta-large/resolve/main/vocab.json\",\n \"microsoft/deberta-xlarge\": \"https://huggingface.co/microsoft/deberta-xlarge/resolve/main/vocab.json\",\n \"microsoft/deberta-base-mnli\": \"https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/vocab.json\",\n \"microsoft/deberta-large-mnli\": \"https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/vocab.json\",\n \"microsoft/deberta-xlarge-mnli\": \"https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/vocab.json\",\n },\n \"merges_file\": {\n \"microsoft/deberta-base\": \"https://huggingface.co/microsoft/deberta-base/resolve/main/merges.txt\",\n \"microsoft/deberta-large\": \"https://huggingface.co/microsoft/deberta-large/resolve/main/merges.txt\",\n \"microsoft/deberta-xlarge\": \"https://huggingface.co/microsoft/deberta-xlarge/resolve/main/merges.txt\",\n \"microsoft/deberta-base-mnli\": \"https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/merges.txt\",\n \"microsoft/deberta-large-mnli\": \"https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/merges.txt\",\n \"microsoft/deberta-xlarge-mnli\": \"https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/merges.txt\",\n },\n}\n\nPRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {\n \"microsoft/deberta-base\": 512,\n \"microsoft/deberta-large\": 512,\n \"microsoft/deberta-xlarge\": 512,\n \"microsoft/deberta-base-mnli\": 512,\n \"microsoft/deberta-large-mnli\": 512,\n \"microsoft/deberta-xlarge-mnli\": 512,\n}\n\nPRETRAINED_INIT_CONFIGURATION = {\n \"microsoft/deberta-base\": {\"do_lower_case\": False},\n \"microsoft/deberta-large\": {\"do_lower_case\": False},\n}\n\n\nclass DebertaTokenizer(GPT2Tokenizer):\n r\"\"\"\n Constructs a DeBERTa tokenizer, which runs end-to-end tokenization: punctuation splitting + wordpiece\n\n Args:\n vocab_file (`str`):\n File containing the vocabulary.\n do_lower_case (`bool`, *optional*, defaults to `True`):\n Whether or not to lowercase the input when tokenizing.\n unk_token (`str`, *optional*, defaults to `\"[UNK]\"`):\n The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this\n token instead.\n sep_token (`str`, *optional*, defaults to `\"[SEP]\"`):\n The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for\n sequence classification or for a text and a question for question answering. It is also used as the last\n token of a sequence built with special tokens.\n pad_token (`str`, *optional*, defaults to `\"[PAD]\"`):\n The token used for padding, for example when batching sequences of different lengths.\n cls_token (`str`, *optional*, defaults to `\"[CLS]\"`):\n The classifier token which is used when doing sequence classification (classification of the whole sequence\n instead of per-token classification). It is the first token of the sequence when built with special tokens.\n mask_token (`str`, *optional*, defaults to `\"[MASK]\"`):\n The token used for masking values. This is the token used when training this model with masked language\n modeling. This is the token which the model will try to predict.\n \"\"\"\n\n vocab_files_names = VOCAB_FILES_NAMES\n pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP\n max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n model_input_names = [\"input_ids\", \"attention_mask\", \"token_type_ids\"]\n\n def __init__(\n self,\n vocab_file,\n merges_file,\n errors=\"replace\",\n bos_token=\"[CLS]\",\n eos_token=\"[SEP]\",\n sep_token=\"[SEP]\",\n cls_token=\"[CLS]\",\n unk_token=\"[UNK]\",\n pad_token=\"[PAD]\",\n mask_token=\"[MASK]\",\n add_prefix_space=False,\n **kwargs\n ):\n bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token\n eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token\n sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token\n cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token\n unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token\n pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token\n\n # Mask token behave like a normal word, i.e. include the space before it\n mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token\n\n super().__init__(\n vocab_file=vocab_file,\n merges_file=merges_file,\n errors=errors,\n bos_token=bos_token,\n eos_token=eos_token,\n unk_token=unk_token,\n sep_token=sep_token,\n cls_token=cls_token,\n pad_token=pad_token,\n mask_token=mask_token,\n add_prefix_space=add_prefix_space,\n **kwargs,\n )\n\n def build_inputs_with_special_tokens(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None\n ) -> List[int]:\n \"\"\"\n Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and\n adding special tokens. A DeBERTa sequence has the following format:\n\n - single sequence: [CLS] X [SEP]\n - pair of sequences: [CLS] A [SEP] B [SEP]\n\n Args:\n token_ids_0 (`List[int]`):\n List of IDs to which the special tokens will be added.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n\n Returns:\n `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.\n \"\"\"\n if token_ids_1 is None:\n return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]\n cls = [self.cls_token_id]\n sep = [self.sep_token_id]\n return cls + token_ids_0 + sep + token_ids_1 + sep\n\n def get_special_tokens_mask(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False\n ) -> List[int]:\n \"\"\"\n Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding\n special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.\n\n Args:\n token_ids_0 (`List[int]`):\n List of IDs.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n already_has_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not the token list is already formatted with special tokens for the model.\n\n Returns:\n `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.\n \"\"\"\n if already_has_special_tokens:\n return super().get_special_tokens_mask(\n token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True\n )\n\n if token_ids_1 is None:\n return [1] + ([0] * len(token_ids_0)) + [1]\n return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]\n\n def create_token_type_ids_from_sequences(\n self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None\n ) -> List[int]:\n \"\"\"\n Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa\n sequence pair mask has the following format:\n\n ```\n 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1\n | first sequence | second sequence |\n ```\n\n If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).\n\n Args:\n token_ids_0 (`List[int]`):\n List of IDs.\n token_ids_1 (`List[int]`, *optional*):\n Optional second list of IDs for sequence pairs.\n\n Returns:\n `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).\n \"\"\"\n sep = [self.sep_token_id]\n cls = [self.cls_token_id]\n\n if token_ids_1 is None:\n return len(cls + token_ids_0 + sep) * [0]\n return len(cls + token_ids_0 + sep + token_ids_1 + sep) * [0]\n\n def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):\n add_prefix_space = kwargs.pop(\"add_prefix_space\", self.add_prefix_space)\n if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):\n text = \" \" + text\n return (text, kwargs)\n","repo_name":"XiangLi1999/Diffusion-LM","sub_path":"transformers/src/transformers/models/deberta/tokenization_deberta.py","file_name":"tokenization_deberta.py","file_ext":"py","file_size_in_byte":9524,"program_lang":"python","lang":"en","doc_type":"code","stars":912,"dataset":"github-code","pt":"3"}
+{"seq_id":"35332838604","text":"#encoding:utf-8\n# __author__ = 'donghao'\n# __time__ = 2019/4/10 16:46\n\n\nmydict = {'name':'donghao','age':20}\n\n\nmydict2 = {'name':'donghao2','age':22,'school':'nyist'}\n\n\n# mydict.pop('name')\n\n# mydict.keys()\n#\n# mydict.items()\n#\n# mydict.values()\n\n#mydict.update(mydict2)\n\nprint(mydict)","repo_name":"RelaxedDong/python_base","sub_path":"字符串,列表,字典等/字典/常用方法.py","file_name":"常用方法.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"38749219230","text":"import random\nprint(\"\\n-------------------------------------------------------------------\")\nprint(\".:gissa talet :.\\n\\n\")\nprint(\"gissa ett tal mellan 1 och 10 och pröva lyckan, du får 3st försök!\\n\")\nslumptal = random.randint(1,10)\n#print (slumptal)\ni = 0\nhittat = False\n#loop\nwhile i < 3:\n gissatal =input (\"mata in tal: \")\n\n if slumptal == int(gissatal):\n hittat = True\n print(\"\\n rätt svar! \\n\")\n break\n\n i += 1\n\n if hittat:\n print(\"\\nBra jobbat, här får du fem kr\")\n else:\n print(\"\\nBättre lycka nästa gång\")\nprint(\"\\n---------------------------------------------------------------------\")","repo_name":"sunsmaster/python","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"sv","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14630480249","text":"import time\nimport re\nfrom bs4 import BeautifulSoup\n\nfrom common.webhook import create_embed, send_embed\nfrom common.database import is_url_in_database, add_url_in_database\nfrom common.website import Website\n\n\nclass StationF(Website):\n\n def __init__(self):\n self.name = 'Station F'\n self.url = 'https://jobs.stationf.co/search?query=dev{}&departments%5B0%5D=Tech&departments%5B1%5D=Tech%20%26%20Dev&departments%5B2%5D=Tech%2FDev&departments%5B3%5D=Dev&contract_types%5B0%5D=Full-Time&contract_types%5B1%5D=Freelance&contract_types%5B2%5D=Temporary'\n self.discord_username = 'STATION F JOBS'\n self.discord_avatar_url = 'https://mbem.fr/wp-content/uploads/2018/06/station-f-logo-copie.png'\n self.should_scroll_page = False\n\n\n def scrap(self):\n\n page = 1\n\n while True:\n\n print(\"Looking for another Station F\\'s page..\")\n\n page_url = self.url.format(\n '&page={}'.format(page) if page != 1 else '')\n\n page_data = self._get_chrome_page_data(page_url)\n page_soup = BeautifulSoup(page_data, 'html.parser')\n all_jobs_raw = page_soup.find_all(\n 'li', attrs={'class': 'ais-Hits-item'})\n\n if len(all_jobs_raw) == 0: # Scrap finished\n return\n\n print(\"\\nStation F\\'s found jobs ({}) :\".format(len(all_jobs_raw)))\n for jobs in all_jobs_raw:\n job_name = jobs.find(\n 'h4', attrs={'class': 'job-title'}).text.strip()\n print('Job : ' + job_name)\n\n job_company = jobs.find(\n 'li', attrs={'class': 'job-company'}).text.strip()\n print('Company : ' + job_company)\n\n job_location = jobs.find(\n 'li', attrs={'class': 'job-office'}).text.strip()\n print('Location : ' + job_location)\n\n job_link = 'https://jobs.stationf.co' + jobs.find(\n 'a', attrs={'class': 'jobs-item-link'}, href=True)['href']\n print(job_link)\n\n job_thumbnail = re.search(\"(?Phttps?://[^\\s]+)\", jobs.find(\n 'div', attrs={'class': 'company-logo'})['style']).group(\"url\")[:-2]\n print(job_thumbnail)\n print('\\n')\n\n if not is_url_in_database(job_link):\n add_url_in_database(job_link)\n embed = create_embed(\n job_name, job_company, job_location, job_link, job_thumbnail)\n send_embed(embed, self)\n time.sleep(4)\n\n print('Station F\\'s page #{} finished'.format(page))\n page += 1\n","repo_name":"lduqueno/dev_jobs_scrapper","sub_path":"srcs/websites/stationf.py","file_name":"stationf.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32908161378","text":"from fastapi import APIRouter\nfrom ..util.child_models import (\n GetChildrenReq,\n EditChildReq,\n DeleteChildReq,\n GetPreferencesReq,\n UpdatePreferencesReq,\n)\nfrom dataclasses import dataclass\nfrom bson import ObjectId\nfrom ...deps import Database\n\ndb = Database.getInstance().db\nrouter = APIRouter()\n\n\n@router.get(\"/\")\ndef get_topics():\n arr = [\"Christmas\", \"Family\", \"Animals\", \"Friends\"]\n return {\"topics\": arr}\n\n\n@router.post(\"/\")\ndef get_children(rqst: GetChildrenReq):\n parent_data = {\n \"username\": rqst.parent_name,\n \"email\": rqst.parent_email,\n \"children\": [],\n }\n parents_collection = db[\"Parents\"]\n existing_parent = parents_collection.find_one({\"email\": parent_data[\"email\"]})\n if existing_parent:\n children = []\n for id in existing_parent[\"children\"]:\n children.append(get_child(id))\n return children\n else:\n result_parent = parents_collection.insert_one(parent_data)\n return []\n\n\n@router.post(\"/get-preferences\")\ndef get_preferences(rqst: GetPreferencesReq):\n preferences = db[\"Children\"].find_one({\"_id\": ObjectId(rqst.child_id)})\n if \"preferences\" in preferences:\n return {\"preferences\": preferences[\"preferences\"]}\n else:\n db[\"Children\"].update_one(\n {\"_id\": ObjectId(rqst.child_id)}, {\"$set\": {\"preferences\": []}}\n )\n return {\"preferences\": []}\n\n\n@router.post(\"/update-preferences\")\ndef update_preferences(rqst: UpdatePreferencesReq):\n db[\"Children\"].update_one(\n {\"_id\": ObjectId(rqst.child_id)}, {\"$set\": {\"preferences\": rqst.preferences}}\n )\n return {\"status\": \"success\"}\n\n\ndef get_child(child_id):\n children_collection = db[\"Children\"]\n child = children_collection.find_one({\"_id\": child_id})\n if child:\n child[\"_id\"] = str(child[\"_id\"])\n child[\"parent\"] = str(child[\"parent\"])\n return child\n else:\n return None\n\n\n@router.post(\"/edit-child\")\ndef edit(rqst: EditChildReq):\n if rqst.child_id == \"\":\n return {\"status\": \"error\", \"message\": \"No Child id\"}\n children_collection = db[\"Children\"]\n object_id = ObjectId(rqst.child_id)\n existing_child = children_collection.find_one({\"_id\": object_id})\n if existing_child:\n children_collection.update_one(\n {\"_id\": object_id},\n {\n \"$set\": {\n \"username\": rqst.name,\n \"age\": rqst.age,\n \"profile_photo\": rqst.profile_picture,\n }\n },\n )\n return {\"status\": \"success\"}\n else:\n return {\"status\": \"error\", \"message\": \"Child not found\"}\n\n\n@router.post(\"/delete-child\")\ndef delete(rqst: DeleteChildReq):\n if rqst.child_id == \"\":\n return {\"status\": \"error\", \"message\": \"No Child id\"}\n object_id = ObjectId(rqst.child_id)\n existing_child = db[\"Children\"].find_one({\"_id\": object_id})\n if existing_child:\n db[\"Children\"].delete_one({\"_id\": object_id})\n db[\"Vocabulary\"].delete_one({\"_id\": object_id})\n db[\"Practice\"].delete_one({\"_id\": object_id})\n\n db[\"Parents\"].update_one(\n {\"_id\": ObjectId(existing_child[\"parent\"])},\n {\"$pull\": {\"children\": object_id}},\n )\n return {\"status\": \"success\"}\n else:\n return {\"status\": \"error\", \"message\": \"Child not found\"}\n","repo_name":"COS301-SE-2023/WordWizard","sub_path":"libs/api/child/api/child.py","file_name":"child.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"3"}
+{"seq_id":"33676737501","text":"import sys\n\nsys.path.append('./matrix')\n\nfrom Matrix import Matrix\n\ndef getFibonacciTransition():\n return Matrix([[1, 1], [1, 0]])\n\ndef TransitionMatrixFibonacci(num:int) -> int:\n\n if num == 0:\n return 0\n \n fiboM = getFibonacciTransition()\n fiboM = fiboM ** (num - 1)\n\n return fiboM.get(0, 0)","repo_name":"gabitovanf/task3-algebraic-algorithms","sub_path":"fibonacci/TransitionMatrixFibonacci.py","file_name":"TransitionMatrixFibonacci.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34653721294","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom gui.style_constants import *\nfrom gui.shared_components.styled_button import StyledButton\nimport os\n\n\nclass SaveOutput(Tk):\n ''' A dialogue for reviewing, and saving, the outcome of the text_file_translate page\n \n Args:\n save_string (str): The string to be saved to file\n '''\n def __init__(self, save_string, *args, **kwargs):\n Tk.__init__(self, *args, **kwargs)\n self.geometry('800x800')\n self.save_string = save_string\n self.text_box = Text(self)\n self.text_box.config(\n bg=HIGHLIGHT_COLOUR,\n padx=10,\n pady=10,\n relief=SUNKEN,\n borderwidth=0,\n highlightthickness=5,\n highlightbackground=DARK_HIGHLIGHT_COLOUR\n )\n\n self.save_button = StyledButton(self, text='Save')\n\n self.text_box.insert('0.0', self.save_string)\n\n self.text_box.pack(side=TOP, fill=BOTH, expand=True)\n self.save_button.pack(side=RIGHT)\n\n self.save_button.bind('', self.save_click)\n\n def save_click(self, event):\n ''' Launches a save dialogue and saves the text to the named file. The window is then destroyed.\n \n Args:\n event (tkinter.event): A tkinter event that triggered the function call\n '''\n cwd = os.getcwd()\n f = filedialog.asksaveasfile(initialdir = cwd,title = 'Save as')\n f.write(str(self.save_string))\n f.close()\n self.destroy() \n","repo_name":"willstrach/Tongues-Translator","sub_path":"gui/text_file_translate_componenets/save_output.py","file_name":"save_output.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71905361363","text":"\"\"\"\nThis script is used for course notes.\n\nAuthor: Erick Marin\nDate: 10/10/2020\n\"\"\"\n\nfor left in range(7): # loop iterates 6 times\n for right in range(left, 7):\n print(\"[\" + str(left) + \"|\" + str(right) + \"]\", end=\" \")\n print()\n\nteams = [\"Dragons\", \"Wolves\", \"Panda\", \"Unicorns\"]\nfor home_team in teams:\n for away_team in teams:\n if home_team != away_team:\n print(home_team + \" vs \" + away_team)\n","repo_name":"erick-marin/Google-ITAutomation-Python","sub_path":"Course_1/Week_3/nested_for_loops.py","file_name":"nested_for_loops.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"3"}
+{"seq_id":"11495223460","text":"from preprocess_0821 import process\nfrom mask import mask\nfrom predict_tsv_1_seq import impute\nfrom refine_label import refine_label\nfrom csv_to_tsv import to_tsv\nfrom GetTfidf import vectorize\nfrom swap import Obfuscate\nimport pandas as pd\nimport sys\nimport nltk\nimport ssl\n\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass\nelse:\n ssl._create_default_https_context = _create_unverified_https_context\n\nnltk.download('words')\n\ndef compute(dataframe):\n\n #nltk.download('words')\n\n # receive parameteres from users\n SUMMARIZE = 0 # 0: no summarize, 1: summarize\n KEYWORDS_POSITION = 0 # 0: keywords, 1: position\n\n #SUMMARIZE = sys.argv[1]\n #KEYWORDS_POSITION = sys.argv[2]\n rows = refine_label(dataframe)\n rows = process(rows)\n text, label = mask(rows)\n first_dataframe = impute(text, label)\n print(\"ready to swap!\")\n\n if SUMMARIZE:\n # SUMMARIZE FUNC\n tfidf_result = vectorize(dataframe, True)\n result = Obfuscate(tfidf_result, \"summary\")\n else:\n # NO SUMMARIZE FUNC\n if KEYWORDS_POSITION:\n # Position FUNC\n tfidf_result = vectorize(dataframe, False)\n result = Obfuscate(tfidf_result, \"pos\")\n else:\n # Keywords Func\n tfidf_result = vectorize(dataframe, False)\n result = Obfuscate(tfidf_result, \"keyword\")\n return result\n\n","repo_name":"SOCR/DataSifterText","sub_path":"DataSifter_Text_app/total.py","file_name":"total.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"11809915711","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ## Program Aplikasi Employee Attrittion\n\n# In[1]:\n\n\n#Import Packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys,traceback\nimport seaborn as sns\n\n\n# In[21]:\n\n\nhr_data=pd.read_csv('train.csv')\n\n\n# In[23]:\n\n\n#Import Data\nhr = hr_data\ncol_names = hr.columns.tolist()\nprint(\"Column names:\")\nprint(col_names)\n\nprint(\"\\nSample data:\")\nhr.head()\n\n\n# In[24]:\n\n\nhr=hr.rename(columns = {'Department':'Department'})\n#Display data type for each column\nhr.dtypes\n\n\n# In[25]:\n\n\n#Check for Missing Values\nhr.isnull().any()\n\n\n# In[26]:\n\n\n#Dimensions of our dataset\nhr.shape\n\n\n# In[27]:\n\n\n#Summary for each variable\nhr.describe()\n\n\n# In[28]:\n\n\n#To get the unique values for department\nhr['Department'].unique()\n\n\n# In[29]:\n\n\n#Combine \"technical\",\"support\" and \"IT\" into one department\nhr['Department']=np.where(hr['Department'] =='support', 'technical', hr['Department'])\nhr['Department']=np.where(hr['Department'] =='IT', 'technical', hr['Department'])\n\n\n# In[30]:\n\n\n#Print the updated values of departments\nprint(hr['Department'].unique())\n\n\n# # Data Exploration\n\n# In[31]:\n\n\n#Get a count the number of employees that stayed and left the company 0=No 1=Yes\nhr['Attrition'].value_counts()\n\n\n# In[32]:\n\n\nhr.groupby('Attrition').mean()\n\n\n# In[33]:\n\n\nhr.groupby('Department').mean()\n\n\n# In[34]:\n\n\nhr.groupby('Salary').mean()\n\n\n# ## Data Visualization\n\n# In[35]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n#Bar chart for department employee work for and the frequency of turnover\npd.crosstab(hr['Department'],hr['Attrition']).plot(kind='bar')\nplt.title('Turnover Frequency for Department')\nplt.xlabel('Department')\nplt.ylabel('Frequency of Turnover')\nplt.savefig('department_bar_chart')\n\n\n# In[44]:\n\n\n#Bar chart for employee salary level and the frequency of turnover\ntable=pd.crosstab(hr.Salary, hr.Attrition)\ntable.div(table.sum(1).astype(float), axis=0).plot(kind='bar', stacked=True)\nplt.title('Stacked Bar Chart of Salary Level vs Turnover')\nplt.xlabel('Salary Level')\nplt.ylabel('Proportion of Employees')\nplt.savefig('salary_bar_chart')\n\n\n# In[43]:\n\n\nhr.Salary\n\n\n# In[57]:\n\n\n#Proportion of employees left by department\npd.crosstab(hr.Department, hr.Attrition)\n\n\n# In[58]:\n\n\n#Histogram of numeric variables\nnum_bins = 10\n\nhr.hist(bins=num_bins, figsize=(20,15))\nplt.savefig(\"hr_histogram_plots\")\nplt.show()\n\n\n# In[59]:\n\n\nhr.head()\n\n\n# In[60]:\n\n\ncat_vars=['Department','Salary']\nfor var in cat_vars:\n cat_list='var'+'_'+var\n cat_list = pd.get_dummies(hr[var], prefix=var)\n hr1=hr.join(cat_list)\n hr=hr1\n\n\n# In[61]:\n\n\nhr.drop(hr.columns[[7, 8]], axis=1, inplace=True)\n\n\n# In[62]:\n\n\nhr.columns.values\n\n\n# In[63]:\n\n\nhr.head()\n\n\n# In[64]:\n\n\nhr_vars=hr.columns.values.tolist()\ny=['Attrition']\nX=[i for i in hr_vars if i not in y]\n\n\n# In[65]:\n\n\nX\n\n\n# ## Feature Selection\n\n# In[66]:\n\n\nfrom sklearn.feature_selection import RFE\nfrom sklearn.linear_model import LogisticRegression\n\nmodel = LogisticRegression()\n\nrfe = RFE(model, 10)\nrfe = rfe.fit(hr[X], hr[y])\nprint(rfe.support_)\nprint(rfe.ranking_)\n\n\n# In[ ]:\n\n\ncols=['satisfaction_level', 'time_spend_company', 'Work_accident', 'promotion_last_5years', \n 'department_RandD', 'department_hr', 'department_management', 'salary_high', 'salary_low','salary_medium'] \nX=hr[cols]\ny=hr['Attrition']\n\n\n# ### Logistic Regression Model\n\n# In[ ]:\n\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n\n\n# In[ ]:\n\n\n#Logistic Regression Classifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nlogreg = LogisticRegression()\nlogreg.fit(X_train, y_train)\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import accuracy_score\nprint('Logistic regression accuracy: {:.3f}'.format(accuracy_score(y_test, logreg.predict(X_test))))\n\n\n# ### Random Forest\n\n# In[ ]:\n\n\n#Random Forest Classifier\nfrom sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier()\nrf.fit(X_train, y_train)\n\n\n# In[ ]:\n\n\nprint('Random Forest Accuracy: {:.3f}'.format(accuracy_score(y_test, rf.predict(X_test))))\n\n\n# ### Support Vector Machine\n\n# In[ ]:\n\n\n#SVM Classifier\nfrom sklearn.svm import SVC\nsvc = SVC()\nsvc.fit(X_train, y_train)\n\n\n# In[ ]:\n\n\nprint('Support vector machine accuracy: {:.3f}'.format(accuracy_score(y_test, svc.predict(X_test))))\n\n\n# ### XGBoost Classifier \n\n# In[ ]:\n\n\nfrom xgboost import XGBClassifier\n\n\n# In[ ]:\n\n\nxgb=XGBClassifier()\nxgb.fit(X_train, y_train)\n\n\n# In[ ]:\n\n\nprint('XGBoost accuracy: {:.3f}'.format(accuracy_score(y_test, xgb.predict(X_test))))\n\n\n# ### 10 Fold Cross Validation\n\n# In[ ]:\n\n\n#For Random Forest\nfrom sklearn import model_selection\nfrom sklearn.model_selection import cross_val_score\nkfold = model_selection.KFold(n_splits=10, random_state=7)\nmodelCV = RandomForestClassifier()\nscoring = 'accuracy'\nresults = model_selection.cross_val_score(modelCV, X_train, y_train, cv=kfold, scoring=scoring)\nprint(\"cross validation average accuracy for Random Forest Classifier: %.3f\" % (results.mean()))\n\n\n# In[ ]:\n\n\n#For SVM\nfrom sklearn import model_selection\nfrom sklearn.model_selection import cross_val_score\nkfold = model_selection.KFold(n_splits=10, random_state=7)\nmodelCV = SVC()\nscoring = 'accuracy'\nresults = model_selection.cross_val_score(modelCV, X_train, y_train, cv=kfold, scoring=scoring)\nprint(\"cross validation average accuracy for SVM Classifier: %.3f\" % (results.mean()))\n\n\n# In[ ]:\n\n\n#For XGBoost\nfrom sklearn import model_selection\nfrom sklearn.model_selection import cross_val_score\nkfold = model_selection.KFold(n_splits=10, random_state=7)\nmodelCV = XGBClassifier()\nscoring = 'accuracy'\nresults = model_selection.cross_val_score(modelCV, X_train, y_train, cv=kfold, scoring=scoring)\nprint(\"cross validation average accuracy for XGBoost Classifier: %.3f\" % (results.mean()))\n\n\n# ### Classification Report\n\n# In[ ]:\n\n\n#Classification report for Random Forest\nfrom sklearn.metrics import classification_report\nprint(classification_report(y_test, rf.predict(X_test)))\n\n\n# In[ ]:\n\n\n#Confusion Matrix for Random Forest\ny_pred = rf.predict(X_test)\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nforest_cm = metrics.confusion_matrix(y_pred, y_test, [1,0])\nsns.heatmap(forest_cm, annot=True, fmt='.2f',xticklabels = [\"Left\", \"Stayed\"] , yticklabels = [\"Left\", \"Stayed\"] )\nplt.ylabel('True class')\nplt.xlabel('Predicted class')\nplt.title('Random Forest')\nplt.savefig('random_forest')\n\n\n# In[ ]:\n\n\n#Classification report for Logistic Regression\nprint(classification_report(y_test, logreg.predict(X_test)))\n\n\n# In[ ]:\n\n\n#Confusion Matrix for Logistic Regression\nlogreg_y_pred = logreg.predict(X_test)\nlogreg_cm = metrics.confusion_matrix(logreg_y_pred, y_test, [1,0])\nsns.heatmap(logreg_cm, annot=True, fmt='.2f',xticklabels = [\"Left\", \"Stayed\"] , yticklabels = [\"Left\", \"Stayed\"] )\nplt.ylabel('True class')\nplt.xlabel('Predicted class')\nplt.title('Logistic Regression')\nplt.savefig('logistic_regression')\n\n\n# In[ ]:\n\n\n#Classification report for SVM\nprint(classification_report(y_test, svc.predict(X_test)))\n\n\n# In[ ]:\n\n\n#Confusion Matrix for SVM\nsvc_y_pred = svc.predict(X_test)\nsvc_cm = metrics.confusion_matrix(svc_y_pred, y_test, [1,0])\nsns.heatmap(svc_cm, annot=True, fmt='.2f',xticklabels = [\"Left\", \"Stayed\"] , yticklabels = [\"Left\", \"Stayed\"] )\nplt.ylabel('True class')\nplt.xlabel('Predicted class')\nplt.title('Support Vector Machine')\nplt.savefig('support_vector_machine')\n\n\n# In[ ]:\n\n\nprint(classification_report(y_test, xgb.predict(X_test)))\n\n\n# In[ ]:\n\n\n#Confusion Matrix for XGBoost Classifier\nxgb_y_pred = xgb.predict(X_test)\nxgb_cm = metrics.confusion_matrix(xgb_y_pred, y_test, [1,0])\nsns.heatmap(xgb_cm, annot=True, fmt='.2f',xticklabels = [\"Left\", \"Stayed\"] , yticklabels = [\"Left\", \"Stayed\"] )\nplt.ylabel('True class')\nplt.xlabel('Predicted class')\nplt.title('XGBoost Classifier')\nplt.savefig('XGBoost_Classifier')\n\n\n# ### Variable Importance for Random Forest Classifier\n\n# In[ ]:\n\n\nfeature_labels = np.array(['satisfaction_level', 'time_spend_company', 'Work_accident', 'promotion_last_5years', \n 'department_RandD', 'department_hr', 'department_management', 'salary_high', 'salary_low','salary_medium'])\nimportance = rf.feature_importances_\nfeature_indexes_by_importance = importance.argsort()\nfor index in feature_indexes_by_importance:\n print('{}-{:.2f}%'.format(feature_labels[index], (importance[index] *100.0)))\n\n\n# ### Variable Importance for XGBoost Classifier\n\n# In[ ]:\n\n\nfeature_labels = np.array(['satisfaction_level', 'time_spend_company', 'Work_accident', 'promotion_last_5years', \n 'department_RandD', 'department_hr', 'department_management', 'salary_high', 'salary_low','salary_medium'])\nimportance = xgb.feature_importances_\nfeature_indexes_by_importance = importance.argsort()\nfor index in feature_indexes_by_importance:\n print('{}-{:.2f}%'.format(feature_labels[index], (importance[index] *100.0)))\n\n\n# In[ ]:\n\n\n\n\n\n# ## Hperparameter Tuning\n\n# In[ ]:\n\n\nfrom sklearn.model_selection import RandomizedSearchCV\n\n\n# In[ ]:\n\n\n#Randomized Search CV\nn_estimators = [int(x) for x in np.linspace(start = 100, stop = 1200, num = 12)]\nmax_features = ['auto', 'sqrt']\nmax_depth = [int(x) for x in np.linspace(5, 30, num = 6)]\nmin_samples_split = [2, 5, 10, 15, 100]\nmin_samples_leaf = [1, 2, 5, 10]\n\n\n# In[ ]:\n\n\nrandom_grid = {'n_estimators': n_estimators,\n 'max_features': max_features,\n 'max_depth': max_depth,\n 'min_samples_split': min_samples_split,\n 'min_samples_leaf': min_samples_leaf}\n\nprint(random_grid)\n\n\n# In[ ]:\n\n\nrf = RandomForestClassifier()\n\n\n# In[ ]:\n\n\nrf=RandomizedSearchCV(estimator = rf, param_distributions = random_grid,scoring='accuracy', n_iter = 10, cv = 5, verbose=2, random_state=42, n_jobs = 1)\n\n\n# In[ ]:\n\n\nrf.fit(X,y)\n\n\n# In[ ]:\n\n\nrf.best_score_\n\n\n# In[ ]:\n\n\nrf.best_params_\n\n","repo_name":"laniasepsutisna/employee-attrition","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":9897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39901556048","text":"#!/usr/bin/env python3\n\"\"\"Tool to research signal values.\nRead *.dat:\nimport csv\nvalues = list(map(int, [i[2] for i in [r for r in csv.reader(open('/mnt/shares/VCS/my/iosc.py/_sample/sample_ascii.dat'))]]))\n\"\"\"\nimport math\nfrom collections import namedtuple\nimport numpy as np\n\nDataClass = namedtuple('DataClass', ['spp', 'a', 'b', 'p', 's', 'v'])\nData = DataClass(\n spp=20, # samples per period\n a=0.1138916015625, # general multiplier\n b=0.05694580078125, # offset\n p=933, # primary multiplier\n s=1, # secondary multiplier\n v=(\n -83, -15, 55, 122, 182, 228, 260, 271, 260, 228,\n 178, 113, 43, -30, -95, -150, -187, -202, -195, -165,\n -118, -57, 10, 78, 138, 187, 219, 230, 221, 191,\n 143, 83, 17, -50, -111, -161, -195, -208, -199, -169\n )\n)\n\n\ndef main():\n def _win(__a, __i, __spp) -> np.array:\n return __a[__i + 1 - __spp:__i + 1] if i + 1 >= __spp else np.pad(__a[:__i + 1], (__spp - __i - 1, 0))\n\n def _fft(__w) -> np.array:\n return np.fft.fft(__w, norm='ortho')\n\n values = np.array(Data.v) * Data.a + Data.b\n print(\"# \\t Sec\\t Mid\\t Eff\\t H1_mod\\t H1_ang\\t H2\\t H3\\t H5\\n==\\t\" + \"\\t\".join(\n 8 * [8 * \"=\"]))\n for i, v in enumerate(values):\n # Array window (float[Data.spp] = 0,…value[0],…value[i])\n w = _win(values, i, Data.spp)\n print(\"{:2d}\\t{:8.3f}\\t{:8.3f}\\t{:8.3f}\\t{:8.3f}\\t{:8.3f}\\t{:8.3f}\\t{:8.3f}\\t{:8.3f}\".format(\n i, v, np.average(w),\n np.sqrt(np.average(w**2)), # np.std() not helps\n np.abs(_fft(w))[1],\n np.degrees(np.angle(_fft(w)))[1],\n np.abs(_fft(w))[2],\n np.abs(_fft(w))[3],\n np.abs(_fft(w))[5],\n ))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"tieugene/tmp.py","sub_path":"archive/sig_explorer_standalone.py","file_name":"sig_explorer_standalone.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31656846096","text":"#Sawadogo Marie Fabienne\n#300101795\n#cette fonction prend une liste et retourne le nombre de la longueur de la plus longue séquence d’éléments consécutifs égaux\ndef sequence_max(l):\n #on cree un tableau vide pour a chaque fois incrementer le nombre de sequence de nombre\n #consecutif\n '''(liste)->int'''\n x=len(l)\n i=0\n TableauValeur = []\n Valeur = 0\n \n while i < x-1:\n a=l[i]\n b=l[i+1]\n \n if a==b:\n Valeur+=1\n \n elif a != b :\n TableauValeur.append(Valeur)\n Valeur = 0\n \n \n i +=1\n if a==l[x-1]:\n TableauValeur.append(Valeur)\n #on use max pour avoir la plus longue chaine\n \n\n\n MaximumTableau = max(TableauValeur) +1\n if MaximumTableau==0:\n print(\"1\")\n\n \n \n \n \n\n print(MaximumTableau)\n return MaximumTableau\n\n\nch=input(\"Veuillez entrer une liste de valeurs séparées par des virgules:\")\nl=list(eval(ch))\nsequence_max(l)\n","repo_name":"fabienne-lab/ITI1520-Python","sub_path":"Devoirs/D3 300101795/D3 300101795/d3q3.py","file_name":"d3q3.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29045835164","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 9 22:30:53 2017\n\n@author: Jannik\n\"\"\"\n\nfrom .sbpa_utils import value_to_value, image_from_array, normalize_image\nimport numpy as np\nfrom skimage.util import img_as_float\nimport copy\nimport pandas as pd\nfrom sklearn.decomposition import PCA\nR = 0\nG = 1\nB = 2\n\n\ndef GLI(image):\n '''Returns Green Leaf Index\n https://www.indexdatabase.de/db/i-single.php?id=375 '''\n return (2*image[:,:,G] - image[:,:,R] - image[:,:,B]) / (2*image[:,:,G] + image[:,:,R] + image[:,:,B])\n \ndef VARI(image):\n '''Returns Visible Atmospherically Resistant Index\n https://calmit.unl.edu/people/agitelson2/pdf/07_IJRS-2002_23-2002.pdf'''\n \n return (image[:,:,G] - image[:,:,R]) / (image[:,:,G] + image[:,:,R] - image[:,:,B])\n \ndef VVI(image):\n '''Returns Visible Vegetation Index\n http://phl.upr.edu/projects/visible-vegetation-index-vvi '''\n return (1 - abs((image[:,:,R] - 30) / (image[:,:,R] + 30))) * (1 - abs((image[:,:,G] - 50) / (image[:,:,G] + 50))) * (1 - abs((image[:,:,B] - 1) / (image[:,:,B] + 1)))\n \ndef RI(image):\n '''Returns Normalized Difference Red/Green Redness Index\n https://www.indexdatabase.de/db/i-single.php?id=74 '''\n return (image[:,:,R] - image[:,:,G]) / (image[:,:,R] + image[:,:,G])\n\n#def RI2(image):\n# '''Returns Redness index'''\n# return (image[:,:,R]**2) / (image[:,:,B] * image[:,:,G]**3)\n \n#def BI(image):\n# '''Returns Brightness Index'''\n# return (np.sqrt((image[:,:,R]**2 + image[:,:,G]**2 + image[:,:,B]*2) / 3))\n\n#def SI(image):\n# '''Returns Spectral Slope Saturation Index'''\n# return (image[:,:,R] - image[:,:,B]) / (image[:,:,R] + image[:,:,B])\n\ndef HI(image):\n '''Returns Shape Index\n https://www.indexdatabase.de/db/i-single.php?id=79'''\n return ((2*image[:,:,R] - image[:,:,G] - image[:,:,B]) / (image[:,:,G] - image[:,:,B]))\n \ndef TGI(image):\n '''Returns Triangular greeness index'''\n return -0.5*(190*(image[:,:,R] - image[:,:,G]) - 120 * (image[:,:,R] - image[:,:,B]))\n\ndef NGRDI(image):\n '''Returns Normalized green red difference index\n https://www.indexdatabase.de/db/i-single.php?id=390 '''\n return ((image[:,:,G] - image[:,:,R]) / (image[:,:,G] + image[:,:,R]))\n\ndef RB(image):\n '''Returns Red-Blue ratio\n https://www.indexdatabase.de/db/i-single.php?id=203 '''\n return (image[:,:,R] / image[:,:,B])\n\ndef RG(image):\n '''Returns Red-Green ratio\n https://www.indexdatabase.de/db/i-single.php?id=213 '''\n return (image[:,:,R] / image[:,:,G])\n\ndef CI(image):\n '''Returns Coloration index\n https://www.indexdatabase.de/db/i-single.php?id=11 '''\n return ((image[:,:,R] - image[:,:,B]) / image[:,:,R])\n\n \ndef make_rgb_indices(img, normalize = True, zeros = 1):\n '''Returns an indices object and a dictionary of gli, vvi, ntdi, ci,\n bi, si, tgi, ngrdi'''\n \n if img.dtype == \"float64\":\n raise TypeError(\"Image has to be unsigned integer for creating RGB Indices!\")\n \n image = np.copy(img)\n image[image == 0] = zeros\n image = img_as_float(image) \n \n rgbi_dict = {\"gli\":GLI(image),\n \"vvi\" : VVI(image),\n #\"vari\" : VARI(image),\n \"ci\" : CI(image),\n \"ri\" : RI(image),\n #\"hi\" : HI(image),\n \"rb\" : RB(image),\n \"rg\" : RG(image),\n \"tgi\" : TGI(image),\n \"ngrdi\" : NGRDI(image)}\n \n if normalize:\n for key, value in rgbi_dict.items():\n rgbi_dict[key] = normalize_image(rgbi_dict[key])\n \n rgbi = type(\"rgbi\", (), rgbi_dict)\n p = rgbi()\n return p, rgbi_dict\n\n\n\ndef make_pca(di, image, components = 3):\n '''Takes a list (Currently Dictionary with \"Name\": Array)of single-channel \n images and performs a principal component analysis. TODO: Get rid of \n pandas)'''\n \n d = copy.deepcopy(di)\n \n for key, value in d.items():\n d[key] = d[key].flatten()\n df = pd.DataFrame(d)\n \n pca = PCA(n_components=components).fit(df)\n pca_reduced = pca.transform(df)\n \n dimDict = {}\n \n for i in range(0,components):\n dimDict[\"dim\"+str(i+1)] = normalize_image(image_from_array(pca_reduced[:,i], (image.shape[0], image.shape[1])))\n \n comp = type(\"components\", (), dimDict)\n p = comp()\n return p, dimDict","repo_name":"H-Reinarz/SBPA","sub_path":"SBPA/rgb_indices.py","file_name":"rgb_indices.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"8607131772","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\n# Create your views here.\nposts = [\n {\n 'title': 'Blog Post 1',\n 'content': 'Hello there, this is my first blog',\n 'author': 'Andrew Lee',\n 'date_posted': 'Feb 15, 2020',\n },\n {\n 'title': 'Blog Post 2',\n 'content': 'Well fancy seeing you here, this is my second blog',\n 'author': 'Brian Park',\n 'date_posted': 'Feb 16, 2020',\n }\n]\n\n\ndef home(request):\n context = {\n 'posts':posts,\n }\n return render(request, 'blog/home.html', context)\n\ndef about(request):\n return render(request, 'blog/about.html', {'title': \"Andrew's Blog - About Page\"}) ","repo_name":"andrewhylee/proj_1_blog","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29537666621","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\n# Create search engine!\n# Goodreads json file is too large to open entirely using a pandas Dataframe. Instead, we first read it line by line:\nimport csv\nimport pandas as pd\n\n\n# In[5]:\n\n\nbook_titles = pd.read_csv('book_fields.csv')\n\n\n# In[6]:\n\n\ndef modify_book_titles(book_titles):\n book_titles[\"ratings\"] = pd.to_numeric(book_titles[\"ratings\"])\n book_titles[\"modified_title\"] = book_titles[\"title\"].str.replace(\"[^a-zA-Z0-9 ]\", \"\", regex=True) #this is a regular expression that modifies titles so that any that include characters other than \n book_titles[\"modified_title\"] = book_titles[\"modified_title\"].str.lower() #those in the brackets are removed.\n book_titles[\"modified_title\"] = book_titles[\"modified_title\"].str.replace(\"\\s+\", \" \", regex=True) # replace multiple spaces with one space\n book_titles = book_titles[book_titles[\"modified_title\"].str.len() > 0] # removing blank titles\n return book_titles\n\n\n# In[7]:\n\n\nbook_titles = modify_book_titles(book_titles)\n\n\n# In[8]:\n\n\ndef clickable(val):\n return ' Goodreads '.format(val)\n \n# ^^ This function would allow you to click on the link to see it in Goodreads. Feel like we might not want our app to redirect to another book site\n\n\n# To create the search engine, we're using TF-IDF (term frequency - inverse document frequency). It uses both of these to assign keyword scores and estimate the importance/relevance of each word \n# put into the search engine.\n\n# term frequency measures the frequency of each unique word.\n# inverse document frequency minimizes the importance of common words (like the, and, etc.)\n\nimport numpy as np\nimport re\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nvectorizer = TfidfVectorizer()\ntfidf = vectorizer.fit_transform(book_titles[\"modified_title\"])\n\n# show cover image in search\ndef cover(val):\n return '
'.format(val)\n\n# search for a specific book (by title)\ndef search(query, vectorizer):\n processed = re.sub(\"[^a-zA-Z0-9 ]\", \"\", query.lower())\n query_vec = vectorizer.transform([processed])\n similarity = cosine_similarity(query_vec, tfidf).flatten()\n indices = np.argpartition(similarity, -10)[-10:] #find indices of 10 largest similarity values\n results = book_titles.iloc[indices]\n results = results.sort_values(\"ratings\", ascending=False)\n return results.head(5)#.style.format({'cover':cover, 'url': clickable})\n\n\n# In[9]:\n\n\nliked_books = []\nbook_ids = []\nliked_title = []\nratings = []\ndef user_search(liked_books, book_ids, liked_title):\n book = input(\"Please enter a book to search. Enter 'exit' when finished.\")\n if book == 'exit':\n return False\n results = search(book, vectorizer)\n display(results.style.format({'cover':cover, 'url': clickable}))\n # results['book_id']\n validate = input(\"Which result is the book you want to add to your list? Enter a number between 1 and 5. Enter N if it is not on the list. \\n\")\n if validate == 'N':\n print(\"Try again.\")\n else:\n rating = input(\"What rating would you give this book between 1 and 5?\")\n rate = int(rating)\n validate = int(validate)\n ratings.append(rate)\n book_ids.append(results.iloc[validate-1, 0])\n liked_books.append(results.iloc[validate-1, 0])\n liked_title.append(results.iloc[validate-1, 1])\n return True, liked_books, liked_title, ratings\n\ndef search_loop():\n uid = input(\"What is your user id?\")\n user_id = int(uid)\n userin = input(\"\\n\\n\\nWould you like to search for a book? Enter Y/N.\")\n if userin != 'N' and userin != 'Y' and userin != 'n' and userin != 'y':\n print(\"Please enter Y or N.\")\n userin = input(\"\\n\\n\\nWould you like to search for a book? Enter Y/N.\")\n while True:\n if userin == 'N':\n print(\"Goodbye!\")\n break\n if not user_search(liked_books, book_ids, liked_title):\n break\n userin = input(\"Would you like to search for another book? Enter Y/N.\")\n return user_id\n \n\n\n# In[12]:\n\n\nuser_id = search_loop()\nliked_book = pd.DataFrame(columns= ['book_id', 'title'])\nids = []\nfor i in range(0, len(book_ids)):\n ids.append(user_id)\n#search_loop()\nliked_book['user_id'] = ids\nliked_book['book_id'] = book_ids\nliked_book['title'] = liked_title\nliked_book['rating'] = ratings\n\n\n# In[ ]:\n\n\ndisplay(liked_books)\ndef return_liked(liked_books):\n return liked_books\n\n\n# In[20]:\n\n\nliked_book.to_csv(\"liked_books.csv\")\n\n","repo_name":"cis3296f22/book-recommendation-system","sub_path":"app/src/main/python/book_search.py","file_name":"book_search.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"8197587268","text":"import os\nimport tensorflow as tf\nfrom keras import Model\nfrom keras.layers import Conv2D, Dense, Flatten, Lambda, Activation, Input, concatenate\n#from tensorflow.keras.utils import plot_model\n\nimport numpy as np\nfrom time import sleep\nfrom pathlib import Path\nimport logging\n\n\nlog = logging.getLogger(\"nn_agent\")\n\n\nclass DeepQNetwork(object):\n def __init__(self, lr, n_actions: int, batch_size: int, name: str,\n global_input_dims: int, local_input_dims: int, fc1_dims: int = 1024):\n \n self.lr = lr # The optimization learning rate of the network model\n self.n_actions = n_actions # How many actions the agent has available -> Index of the action to execute\n self.name = name # The identification name of the agent\n\n # Inputs\n self.global_input_dims = global_input_dims # The dimensions of the global input. So the dimensions of the full drawing canvas.\n self.local_input_dims = local_input_dims # The dimensions of the concentrated input. The local patch of the canvas.\n self.fc1_dims = fc1_dims # Dimensions of the last dense layer\n self.batch_size = batch_size # How many inputs sending into the network\n\n # Generate the network\n self.build_network()\n\n def build_network(self):\n \"\"\"\n build_network Generate a keras DeepQNetwork. The model will be saved in the self.dqn variable.\n \"\"\"\n # global convolution\n glob_in = Input(shape=self.global_input_dims,\n batch_size=self.batch_size, name=\"Global_Stream\")\n glob_conv1 = Conv2D(32, (8, 8), strides=2, activation=\"relu\", input_shape=self.global_input_dims,\n padding=\"same\", name=\"Global_Conv_1\", data_format='channels_first')(glob_in)\n glob_conv2 = Conv2D(64, (4, 4), strides=2, activation=\"relu\", name=\"Global_Conv_2\",\n padding=\"same\", data_format='channels_first')(glob_conv1)\n glob_conv3 = Conv2D(64, (3, 3), strides=1, activation=\"relu\", name=\"Global_Conv_3\",\n padding=\"same\", data_format='channels_first')(glob_conv2)\n # local convolution\n loc_in = Input(shape=self.local_input_dims,\n name=\"Local_Stream\", batch_size=self.batch_size)\n loc_conv1 = Conv2D(128, (11, 11), strides=1, activation=\"relu\",\n name=\"Local_Conv_1\", padding=\"same\", data_format='channels_first')(loc_in)\n # concat\n concat_model = concatenate([glob_conv3, loc_conv1], name=\"Concatenation\", axis=1)\n # Fully connected Layers\n concat_model = Flatten(\n name=\"Flatten\", data_format=\"channels_first\")(concat_model)\n dense1 = Dense(self.fc1_dims, activation=\"relu\",\n name=\"Fully_Connected_1\")(concat_model)\n # Output\n out = Dense(self.n_actions, name=\"Action-Space\")(dense1)\n\n # Inputs of the network are global and local states: glob_in = [4x28x28], loc_in = [2x7x7]\n # Output of the netword are Q-values. each Q-value represents an action\n self.dqn = Model(inputs=[glob_in, loc_in], outputs=[out])\n\n # Network is ready for calling / Training\n self.dqn.compile(loss=\"mean_squared_error\", optimizer=tf.keras.optimizers.Adam(\n learning_rate=self.lr), metrics=[\"accuracy\"])\n\n #plot_model(self.dqn, to_file=f\"src/images/{self.name}.png\", show_shapes=True)\n #calling: dqn([global_state_batch, local_state_batch])\n #training: dqn.train_on_batch(x=[global_state_batch, local_state_batch], y=q_target)\n\n def load_checkpoint(self, path):\n log.info(\"...Loading checkpoint...\")\n path = Path(path + '/deepqnet.ckpt')\n self.dqn.load_weights(path)\n\n def save_checkpoint(self, path):\n log.info(\"...Saving checkpoint...\")\n path = Path(path + '/deepqnet.ckpt')\n self.dqn.save_weights(path)\n\n\n \n\n\nclass Agent(object):\n def __init__(self, alpha, gamma, mem_size, epsilon, epsilon_episodes, global_input_dims, local_input_dims, batch_size, \n softmax, softmax_temp : float = 0.05, replace_target=1000):\n\n self.n_actions = local_input_dims[0]*(local_input_dims[1]**2) # How many action options the agent has. -> Index of the action to choose\n self.n_actions += 1 # Stop Action\n self.action_space = [i for i in range(self.n_actions)] # All the actions the agent can choose\n self.gamma = gamma # Is the learnrate\n self.mem_size = mem_size # The allocated memory size (The number of slots for saved observation)\n self.counter = 0 # Counter of every step\n self.batch_size = batch_size # How big each batch of inputs is\n self.replace_target = replace_target # When to update the q_next network\n self.global_input_dims = global_input_dims # The input dimensions of the whole canvas.\n self.local_input_dims = local_input_dims # The dimensions of the concentrated patch of the canvas\n self.softmax = softmax\n self.softmax_temp = softmax_temp\n\n self.q_next = DeepQNetwork(alpha, self.n_actions, self.batch_size, global_input_dims=global_input_dims,\n local_input_dims=local_input_dims, name='q_next') # The QNetwork to compute the q-values on the next state of the canvas\n self.q_eval = DeepQNetwork(alpha, self.n_actions, self.batch_size, global_input_dims=global_input_dims,\n local_input_dims=local_input_dims, name='q_eval') # The QNetwork to compute the q-values on the current state of the canvas\n\n self.epsilon_episodes = epsilon_episodes\n self.start_epsilon = epsilon\n self.epsilon = self.start_epsilon\n\n # Dimensions of Replay buffer memory\n glob_mem_shape = (\n self.mem_size, global_input_dims[0], global_input_dims[1], global_input_dims[2])\n loc_mem_shape = (\n self.mem_size, local_input_dims[0], local_input_dims[1], local_input_dims[2])\n illegal_list_shape = (self.mem_size, self.n_actions)\n \n # Replay buffer\n self.global_state_memory = np.zeros(glob_mem_shape)\n self.local_state_memory = np.zeros(loc_mem_shape)\n self.new_global_state_memory = np.zeros(glob_mem_shape)\n self.new_local_state_memory = np.zeros(loc_mem_shape)\n\n self.action_memory = np.zeros(self.mem_size, dtype=np.int8)\n self.reward_memory = np.zeros(self.mem_size)\n self.illegal_list_memory = np.zeros(illegal_list_shape)\n\n\n def store_transition(self, global_state: np.array, local_state: np.array, next_gloabal_state: np.array, next_local_state: np.array, action: int, reward: float, illegal_list : np.array):\n \"\"\"\n store_transition Save the next step to the replay buffer\n\n :param global_state: The global state of the canvas\n :type global_state: np.array\n :param local_state: The small patch of the canvas\n :type local_state: np.array\n :param next_gloabal_state: The next state of the whole canvas\n :type next_gloabal_state: np.array\n :param next_local_state: The next state of the small patch of the canvas\n :type next_local_state: np.array\n :param action: The number representing the action the Agent took\n :type action: int\n :param reward: The reward the agent got\n :type reward: float\n \"\"\"\n index = self.counter % self.mem_size\n\n self.global_state_memory[index] = global_state\n self.local_state_memory[index] = local_state\n self.action_memory[index] = action\n self.reward_memory[index] = reward\n self.illegal_list_memory[index] = illegal_list\n self.new_global_state_memory[index] = next_gloabal_state\n self.new_local_state_memory[index] = next_local_state\n\n\n def choose_action(self, global_state: np.array, local_state: np.array, illegal_list : np.array, replay_fill: bool = False):\n action = 0\n # Check if the agent should explore\n rand = np.random.random()\n if rand < self.epsilon or replay_fill:\n if replay_fill:\n action = np.random.choice([i for i, el in enumerate(illegal_list) if el != 1 and i != 98])\n else:\n action = np.random.choice([i for i, el in enumerate(illegal_list) if el != 1])\n else: \n rand = np.random.random()\n \n # create batch of states (prediciton must be in batches)\n glob_batch = np.array([global_state])\n loc_batch = np.array([local_state])\n \n # Ask the QNetwork for an action\n actions = np.array(self.q_eval.dqn([glob_batch, loc_batch])[0])\n\n if rand < self.epsilon*0.01:\n actions[98] = np.max(actions)+1\n\n while illegal_list[np.argmax(actions)] == 1:\n actions[np.argmax(actions)] = -1\n # Take the index of the maximal value -> action\n action = int(np.argmax(actions))\n \n return action\n\n\n def choose_action_softmax(self, global_state: np.array, local_state: np.array, illegal_list : np.array, replay_fill: bool = False):\n if replay_fill:\n action = np.random.choice([i for i, el in enumerate(illegal_list) if el != 1 and i != 98])\n else:\n rand = np.random.random()\n if rand < 0.005:\n return 98\n\n glob_batch = np.array([global_state])\n loc_batch = np.array([local_state])\n # Ask the QNetwork for an action\n actions = np.array(self.q_eval.dqn([glob_batch, loc_batch])[0])\n\n # elliminate illegal actions\n for i, el in enumerate(illegal_list):\n if int(el) == 1:\n actions[i] = 0\n\n actions = list(enumerate(actions))\n actions = sorted(actions, key=lambda x: x[1])\n actions = [(0, 0) for _ in actions[:-5]] + actions[-5:]\n probabilities = [i[1] for i in actions]\n probabilities = list(probabilities[:-5]) + list(self.apply_softmax(probabilities[-5:])) # only the 5 highest probabilities are not 0 and use Softmax\n action = np.argmax(np.random.multinomial(1000, probabilities))\n\n action = actions[action][0]\n while(illegal_list[action] == 1):\n action = np.argmax(np.random.multinomial(1000, probabilities))\n action = actions[action][0]\n \n return action\n \n def apply_softmax(self, actions):\n actions = np.array(actions) / self.softmax_temp\n actions = np.exp(actions)/np.exp(actions).sum() # calculate Softmax\n return actions\n\n def learn(self):\n # randomly samples Memory.\n # chooses as many states from Memory as batch_size requires\n max_mem = self.counter if self.counter < self.mem_size else self.mem_size\n # Get random state inputs from the replay buffer\n batch = np.random.choice(max_mem, self.batch_size, replace=False)\n # batch = [0, 5, 11, ..., batch_size] type: np.array\n\n # load sampled memory\n global_state_batch = self.global_state_memory[batch]\n local_state_batch = self.local_state_memory[batch]\n action_batch = self.action_memory[batch]\n reward_batch = self.reward_memory[batch]\n new_global_state_batch = self.new_global_state_memory[batch]\n new_local_state_batch = self.new_local_state_memory[batch]\n illegal_list_batch = self.illegal_list_memory[batch]\n\n # runs network -> delivers output for training\n # gives the outpus (Q-values) of current states and next states. \n # It gives this output of every state in the batch\n # type: np.array example: [ [0.23, 0.64, 0.33, ..., n_actions], ..., batch_size]\n q_eval = np.array(self.q_eval.dqn([global_state_batch, local_state_batch]))\n q_next = np.array(self.q_next.dqn([new_global_state_batch, new_local_state_batch]))\n q_target = np.copy(q_eval)\n\n #set target value of illegal actions to 0\n for i, il_list in enumerate(illegal_list_batch):\n for j, item in enumerate(il_list):\n if item == 1: #if illegal\n q_target[i][j] = 0\n\n # Calculates optimal output for training. ( Bellman Equation !! )\n idx = np.arange(self.batch_size)\n q_target[idx, action_batch] = reward_batch + \\\n self.gamma*np.max(q_next, axis=1)\n\n # Calls training\n # Basic Training: gives input and desired output.\n self.q_eval.dqn.train_on_batch(\n x=[global_state_batch, local_state_batch], y=q_target)\n \n def reduce_epsilon(self):\n # reduces Epsilon: Network relies less on exploration over time\n if self.counter > self.mem_size and self.epsilon > 0:\n if self.epsilon > 0.05:\n epsilon_diff = self.start_epsilon-0.05\n self.epsilon -= epsilon_diff/self.epsilon_episodes\n else:\n self.epsilon = 0.05\n\n def save_models(self, path):\n self.q_eval.save_checkpoint(path + \"/q_eval\")\n self.q_next.save_checkpoint(path + \"/q_next\")\n\n def load_models(self, path):\n self.q_eval.load_checkpoint(path + \"/q_eval\")\n self.q_next.load_checkpoint(path + \"/q_next\")\n\n def update_graph(self):\n self.counter += 1\n if self.counter % self.replace_target == 0 and self.counter > 0:\n self.q_next.dqn.set_weights(self.q_eval.dqn.get_weights())\n\n def set_softmax_temp(self, temp):\n self.softmax_temp = temp\n\n","repo_name":"LarsZauberer/ReSketch","sub_path":"src/modules/nn_agent.py","file_name":"nn_agent.py","file_ext":"py","file_size_in_byte":13671,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"31825051706","text":"import os\n\n_out_put = \"lib/resource/asset.dart\"\n_in_put_images = \"assets/images\"\n\ndef clear():\n if os.path.exists(_out_put):\n os.remove(_out_put)\n\ndef render():\n files = [f for f in os.listdir(_in_put_images)\n if os.path.isfile(os.path.join(_in_put_images, f))\n and ('.png' in f or '.jpg' in f or '.jpeg' in f)]\n files.sort()\n with open(_out_put, 'a') as f:\n f.write('''\\nclass Id {\\n Id._();\\n''')\n for file in files:\n name, ext = os.path.splitext(file)\n name = name.lower()\n name = name.replace(\".\", \"_\")\n f.write(\" static const String \"+name+\" = \\\"\"+_in_put_images+\"/\"+file+\"\\\";\\n\")\n f.write(\"}\\n\")\n\ndef main():\n\n clear()\n render()\n\nif __name__ == '__main__':\n main()","repo_name":"andynvt/zmusic","sub_path":"tools/render_asset.py","file_name":"render_asset.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6809001198","text":"import time\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as expected\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import (\n ElementNotInteractableException,\n NoSuchElementException\n)\n\nfrom src.utilidades.utilidades import hover_and_click, guardar_captura\n\n\ndef seleccionar_periodo_fiscal(\n driver,\n guardar_capturas: bool,\n tiempo_espera: int,\n month: int,\n year: int\n):\n\n wait = WebDriverWait(driver, 10)\n wait.until(expected.presence_of_element_located(\n (By.ID, 'frmFlujoDeclaracion:somObligacion_label')))\n\n time.sleep(tiempo_espera)\n\n hover_and_click(driver, 'frmFlujoDeclaracion:somObligacion_label')\n\n wait.until(expected.visibility_of_element_located(\n (By.ID, 'frmFlujoDeclaracion:somObligacion_1')))\n\n declaration_2011 = driver.find_element(\n by=By.ID, value='frmFlujoDeclaracion:somObligacion_1')\n declaration_2011.click()\n\n time.sleep(tiempo_espera)\n\n wait.until(expected.visibility_of_element_located(\n (By.XPATH,\n (\n \"//div[@id='frmFlujoDeclaracion:dialogoMensajesPersonalizados']\"\n \"//button[contains(@id, 'frmFlujoDeclaracion')]\"\n ))))\n\n rimpe_discard_button = driver.find_element(\n By.XPATH,\n (\"// div[@id='frmFlujoDeclaracion:dialogoMensajesPersonalizados']\"\n \"//button[contains(@id, 'frmFlujoDeclaracion')]\"))\n rimpe_discard_button.click()\n\n wait.until(expected.presence_of_element_located(\n (By.ID, 'frmFlujoDeclaracion:calPeriodo')))\n\n date_selector = driver.find_element(\n by=By.ID, value='frmFlujoDeclaracion:calPeriodo')\n date_selector.click()\n\n wait.until(expected.presence_of_element_located(\n (By.CSS_SELECTOR, f'a.button-{month}')))\n\n last_month_button = driver.find_element(\n by=By.CSS_SELECTOR, value=f'a.button-{month}')\n last_month_button.click()\n\n wait.until(expected.text_to_be_present_in_element_value(\n (By.ID, 'frmFlujoDeclaracion:calPeriodo'), f'{month:02d}/{year}'))\n\n if guardar_capturas:\n guardar_captura(driver, 'seleccion_periodo_fiscal')\n\n next_step_button = driver.find_element(\n by=By.ID, value='frmFlujoDeclaracion:btnObligacionSiguiente')\n next_step_button.click()\n\n time.sleep(tiempo_espera)\n\n try:\n discard_draft_button = driver.find_element(\n by=By.XPATH, value=\"//button/span[contains(text(), 'Rechazar')]\")\n discard_draft_button.click()\n except ElementNotInteractableException:\n pass\n except NoSuchElementException:\n pass\n","repo_name":"luisprgr/automatizacion-sri-iva","sub_path":"src/pantallas/formulario_iva/periodo_fiscal.py","file_name":"periodo_fiscal.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"37633813585","text":"def freed_prisoners(prison):\n count = 0\n for i in prison:\n if i == (count+1)%2:\n count+=1\n return count * prison[0]\n\n\ndef freed_prisoners2(prison):\n return sum([1 if prison[i] != prison[i-1] else 0 for i in range(1, len(prison))]) + 1 if prison[0] == 1 else 0\n\nprint(freed_prisoners([1, 1, 1, 0, 0, 0]))\nprint(freed_prisoners2([1, 0, 1, 0, 1, 0]))\n","repo_name":"HarryG18/PythonAdventures","sub_path":"Programs/Prison_Break.py","file_name":"Prison_Break.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72792692882","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport os.path\nimport mimetypes\nimport requests\nfrom flask import g, render_template, current_app, request, send_file, jsonify, url_for, abort, redirect, make_response\nfrom flask.ext.babelex import gettext as _\nfrom foofind.utils.downloader import downloader_url\nfrom foofind.utils.fooprint import Fooprint\nfrom foofind.utils import logging\n\ndownloader = Fooprint(\"downloader\", __name__, template_folder=\"template\", dup_on_startswith=\"/\")\n\ndef get_downloader_properties(base_path, downloader_files_builds):\n # source code information\n properties = {\"common\":{\"base_path\": base_path}}\n\n # builds information\n for build, info in downloader_files_builds.iteritems():\n try:\n with open(os.path.join(base_path, info[\"metadata\"]), \"r\") as f:\n metadata = json.load(f)\n\n properties[build] = info.copy()\n properties[build].update(metadata)\n properties[build][\"length\"] = os.path.getsize(os.path.join(base_path, properties[build][\"main\"]))\n except:\n logging.error(\"Error checking downloader files.\")\n\n return properties\n\ndef parse_version(info):\n if info:\n try:\n info_parts = info.split(\"-\",3)\n info_parts.reverse()\n version = info_parts.pop().split(\".\")\n version2 = info_parts.pop() if info_parts else \"\"\n build = info_parts.pop() if info_parts else \"W32\"\n return [[int(v) for v in version], version2], build\n except:\n pass\n\n # Default return value: no version, W32 build\n return 0, \"W32\"\n\n@downloader.route(\"//downloader\")\ndef index():\n g.title = \"Foofind download manager\"\n g.page_description = _(\"downloader_meta_description\")\n return render_template(\n 'downloader/index.html',\n zone = \"downloader\"\n )\n\n@downloader.route(\"//downloader/success\")\ndef success():\n g.title = \"Foofind download manager\"\n g.page_description = _(\"downloader_meta_description\")\n return render_template(\n 'downloader/success.html',\n zone = \"downloader\"\n )\n\n\n@downloader.route(\"//downloader/logger\")\n@downloader_url\ndef logger():\n return \"\"\n\n@downloader.route(\"//downloader/update\")\n@downloader_url\ndef update():\n '''\n\n JSON SPEC\n {\n ?\"update\": {\n ?\"title\": \"Update available...\",\n ?\"text\": \"New version...\",\n \"files\":[\n {\"url\": \"http://...\", \"version\": \"xyz\", \"argv\": [\"/arg1\", ... ]},\n ...\n ]\n },\n ?\"messages\": [{\n ?\"title\": \"title\",\n ?\"icon\": \"wxART_INFORMATION\" // Icon name to display, defaults to wxART_INFORMATION\n\n ?\"priority\": 0, // Higher priority means first shown on multiple messages, otherwhise alphabetical order by title is used\n ?\"id\": \"unique_identifier\", // For non repeateable messages, if not specified, message will be shown on every session\n\n ?\"text\": \"Text...\",\n ?\"url\": \"http://...\",\n ?\"size\": [-1,-1], // Size for embeded objects like url\n\n ?\"go_url\": \"http//:\", // Implies Go, Cancel buttons\n ?\"go_text\": \"\"\n\n ?\"start_url\": \"http://...\", // Implies Download, Cancel buttons\n ?\"start_filename\": \"...\", // Filename wich file should have on disk, if not given, last part of url will be used\n ?\"start_argv\": [\"/arg1\", ...]\n ?\"start_text\"\n ?\"start_close\": true // True if app needs to be closed when run. Defaults to false,\n }, ...]\n }\n\n ICONS:\n wxART_ERROR wxART_FOLDER_OPEN\n wxART_QUESTION wxART_GO_DIR_UP\n wxART_WARNING wxART_EXECUTABLE_FILE\n wxART_INFORMATION wxART_NORMAL_FILE\n wxART_ADD_BOOKMARK wxART_TICK_MARK\n wxART_DEL_BOOKMARK wxART_CROSS_MARK\n wxART_HELP_SIDE_PANEL wxART_MISSING_IMAGE\n wxART_HELP_SETTINGS wxART_NEW\n wxART_HELP_BOOK wxART_FILE_OPEN\n wxART_HELP_FOLDER wxART_FILE_SAVE\n wxART_HELP_PAGE wxART_FILE_SAVE_AS\n wxART_GO_BACK wxART_DELETE\n wxART_GO_FORWARD wxART_COPY\n wxART_GO_UP wxART_CUT\n wxART_GO_DOWN wxART_PASTE\n wxART_GO_TO_PARENT wxART_UNDO\n wxART_GO_HOME wxART_REDO\n wxART_PRINT wxART_CLOSE\n wxART_HELP wxART_QUIT\n wxART_TIP wxART_FIND\n wxART_REPORT_VIEW wxART_FIND_AND_REPLACE\n wxART_LIST_VIEW wxART_HARDDISK\n wxART_NEW_DIR wxART_FLOPPY\n wxART_FOLDER wxART_CDROM\n wxART_REMOVABLE\n\n '''\n platform = request.args.get(\"platform\", None)\n version_raw = request.args.get(\"version\", None)\n if not version_raw and \"/\" in request.user_agent.string: # tries to get version from user agent\n version_raw = request.user_agent.string.split(\"/\")[-1]\n\n version, build = parse_version(version_raw)\n\n # Updates\n update = g.downloader_properties[build].get(\"update\",None)\n response = {}\n if update and version/downloader/foofind_download_manager_proxy.exe\")\n@downloader.route(\"//downloader//foofind_download_manager_proxy.exe\")\ndef download_proxy(build=\"W32\"):\n if build[0]==\"W\":\n data = {'geturl':'1', 'name':\"Foofind Download Manager\",'version':g.downloader_properties[build][\"version\"],\n 'url':url_for('downloader.download', build=build, instfile=g.downloader_properties[build][\"main\"], _external=True), 'id':\"foofind.com\", 'img':'http://foofind.com/static/img/downloader/foofind.png'}\n headers = {'Content-Type':'application/x-www-form-urlencoded', 'Connection':'close', 'Referer':request.referrer}\n\n resp = requests.post(\"http://download.oneinstaller.com/installer/\", headers=headers, data=data)\n\n return redirect(resp.text, 302)\n else:\n return redirect(url_for('downloader.download', build=build, instfile=g.downloader_properties[build][\"main\"], _external=True), 302)\n\n@downloader.route(\"//downloader/\")\n@downloader.route(\"//downloader//\")\ndef download(instfile, build=\"W32\"):\n return send_instfile(instfile, build)\n\ndef send_instfile(instfile, build):\n downloader_files = g.downloader_properties.get(build, None)\n if not downloader_files:\n abort(404)\n\n downloader_files_aliases = downloader_files.get(\"aliases\",{})\n if instfile in downloader_files_aliases:\n path = downloader_files[downloader_files_aliases[instfile]]\n else:\n # check that can be downloaded\n for downloadable in downloader_files[\"downloadables\"]:\n if downloader_files.get(downloadable, None)==instfile:\n path = instfile\n break\n else:\n abort(404)\n\n return send_file(os.path.join(g.downloader_properties[\"common\"][\"base_path\"], path), mimetypes.guess_type(path)[0])\n\n\n# Old URLs\ninstaller_dependencies = (\"setup.exe\", \"vcredist_x86.exe\")\n\n@downloader.route(\"//downloader/version\")\n@downloader.route(\"//downloader/installer//version\")\n@downloader_url\ndef version(version=None):\n build = \"W32\"\n new_version = g.downloader_properties[build][\"version\"]\n if version:\n response = make_response(\"%s redist.exe\\n\"%new_version)\n response.headers[\"Content-Type\"] = \"text/plain; charset=utf-8\"\n return response\n else:\n return new_version\n\n@downloader.route(\"//downloader/download/\")\n@downloader.route(\"//downloader/installer//\")\n@downloader_url\ndef downloader_dependency_download(instfile, version=None):\n '''\n Old downloader dependencies\n '''\n return send_instfile(instfile, \"W32\")\n","repo_name":"foofind/foofind-web","sub_path":"foofind/blueprints/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":8759,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"3"}
+{"seq_id":"29197179940","text":"from raft.client import DistributedDict\nfrom threading import Thread\nd=DistributedDict('127.0.0.1',5254)\ndef t1():\n try:\n stck=input('Enter the stock code ')\n price= int(input('Enter the stock price '))\n d1 = DistributedDict('127.0.0.1', 5254)\n d1[stck] = price\n print('Value inserted successfully into the database')\n #transaction.commit()\n except:\n #transaction.abort()\n print('t1 error')\n#transaction.commit()\n#transaction.commit()\n\nt1()\n\n","repo_name":"SonaliSuri/Distributed-Database-using-LevelDb-Python","sub_path":"stock_market_app/Stock_market_admin_app.py","file_name":"Stock_market_admin_app.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"71491713682","text":"\"\"\"alter user\n\nRevision ID: 089c3fe7c99c\nRevises: e0d8caf7f33f\nCreate Date: 2018-11-09 09:54:51.478730\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '089c3fe7c99c'\ndown_revision = 'e0d8caf7f33f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('invest_users', sa.Column('real_name', sa.String(length=64), nullable=True))\n op.create_unique_constraint(None, 'invest_users', ['real_name'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'invest_users', type_='unique')\n op.drop_column('invest_users', 'real_name')\n # ### end Alembic commands ###\n","repo_name":"BigJeffWang/blockchain-py","sub_path":"user_center/alembic/versions/089c3fe7c99c_alter_user.py","file_name":"089c3fe7c99c_alter_user.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36372862544","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n\nParallel network and feedforward network.\n\nAuthor: M. Sam Ribeiro\nDate: 2017\n\n\"\"\"\n\nimport numpy\nimport theano\nimport theano.tensor as T\n\nfrom cca_layer import CCA\nfrom layers import HiddenLayer, ConvPoolLayer\n\n\nclass DNN(object):\n\n def __init__(self, rng, in_x, in_size, architecture, activation=T.tanh):\n ''' Single feedforward Deep Neural Network '''\n\n self.layers = []\n self.params = []\n self.n_layers = len(architecture)\n\n assert self.n_layers > 0\n\n self.x = in_x\n\n for i in xrange(self.n_layers):\n if i == 0:\n input_size = in_size\n else:\n input_size = architecture[i-1]\n\n if i == 0:\n layer_input = self.x\n else:\n layer_input = self.layers[-1].output\n\n hidden_layer = HiddenLayer(rng=rng,\n input=layer_input,\n n_in=input_size,\n n_out=architecture[i],\n activation=activation)\n self.layers.append(hidden_layer)\n self.params.extend(hidden_layer.params)\n\n self.output = self.layers[-1].output\n\n\n\nclass ParallelDNN(object):\n\n def __init__(self, config, data):\n ''' Parallel DNN with CCA objective function '''\n\n index = T.lscalar() # index to a [mini]batch\n x1 = T.matrix(\"x1\", dtype=theano.config.floatX) # view1 of the data\n x2 = T.matrix(\"x2\", dtype=theano.config.floatX) # view2 of the data\n\n rng = numpy.random.RandomState(1234)\n\n # parallel networks\n dnn1 = DNN(rng, x1, config.x1_dim, config.architecture1)\n dnn2 = DNN(rng, x2, config.x2_dim, config.architecture2)\n\n # CCA objective function\n cca = CCA(config)\n cost, mean = cca.cca(dnn1.output, dnn2.output)\n\n params = dnn1.params + dnn2.params\n gparams = [T.grad(cost, param) for param in params]\n\n updates = [\n (param, param - config.learning_rate * gparam)\n for param, gparam in zip(params, gparams)\n ]\n\n train_set_x1, train_set_x2 = data[0]\n valid_set_x1, valid_set_x2 = data[1]\n test_set_x1, test_set_x2 = data[2]\n\n\n self.train = theano.function(\n inputs=[index],\n outputs=[cost, mean],\n updates=updates,\n givens={\n x1: train_set_x1[index * config.batch_size: (index + 1) * config.batch_size],\n x2: train_set_x2[index * config.batch_size: (index + 1) * config.batch_size]\n }\n )\n\n self.valid = theano.function(\n inputs=[index],\n outputs=[cost, mean],\n givens={\n x1: valid_set_x1[index * config.batch_size:(index + 1) * config.batch_size],\n x2: valid_set_x2[index * config.batch_size:(index + 1) * config.batch_size]\n }\n )\n\n self.test = theano.function(\n inputs=[index],\n outputs=[cost, mean],\n givens={\n x1: test_set_x1[index * config.batch_size:(index + 1) * config.batch_size],\n x2: test_set_x2[index * config.batch_size:(index + 1) * config.batch_size]\n }\n )\n","repo_name":"msamribeiro/deep-cca","sub_path":"model/dnn.py","file_name":"dnn.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"3"}
+{"seq_id":"10945933368","text":"#!python3\n# scrape site with BeautifulSoup to get srabble distribution\n\nfrom collections import namedtuple\nimport os\nfrom string import ascii_uppercase\n\nfrom bs4 import BeautifulSoup as Soup\nimport requests\n\nURL = 'http://scrabblewizard.com/scrabble-tile-distribution/'\nHTML = 'scrabble.html'\nLETTERS = list(ascii_uppercase) # exclude 2x blanks (scrabble wildcards)\nLETTER_REPR = 'Letter: {} - amount: {} / value: {}'\nLetter = namedtuple('Letter', 'name amount value')\n\n\ndef get_html():\n \"\"\"Retrieve html from cache or URL\"\"\"\n if os.path.isfile(HTML):\n with open(HTML) as f:\n return f.read()\n return requests.get(URL).text\n\n\ndef get_table_rows(html):\n \"\"\"Parse scrabble tile distribution into data structure\n Even lack of CSS selectors can be worked around :)\n Thanks SO - 23377533/python-beautifulsoup-parsing-table\"\"\"\n soup = Soup(html, 'html.parser')\n table = soup.find('table')\n table_body = table.find('tbody')\n return table_body.find_all('tr')\n\n\ndef get_distribution(rows):\n \"\"\"Parse the table rows and convert them in a list of named tuples\"\"\"\n for row in rows:\n cols = row.find_all('td')\n cols = [ele.text.strip() for ele in cols]\n if cols[0] not in LETTERS:\n continue\n yield Letter(*cols)\n\n\nif __name__ == \"__main__\":\n html = get_html()\n rows = get_table_rows(html)\n distribution = list(get_distribution(rows))\n total_amount = sum(int(letter.amount) for letter in distribution)\n\n assert total_amount == 98 # 100 - 2 blanks\n\n for letter in distribution:\n print(LETTER_REPR.format(*letter))\n","repo_name":"pybites/blog_code","sub_path":"BeautifulSoup/scrabble_distribution.py","file_name":"scrabble_distribution.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"3"}
+{"seq_id":"69883754003","text":"import xml.etree.ElementTree as ET\nfrom glob import glob\nimport pandas as pd\nimport pathlib\n\n\nhierarchy = [\"title\", \"subtitle\", \"chapter\", \"subchapter\", \"part\", \"subpart\", \"division\", \"subdivison\", \"article\",\n \"subarticle\", \"section\", \"subsection\", \"paragraph\", \"subparagraph\", \"item\", \"subitem\"]\n\n\n\n\n\ndef strip_namespace(tag: str):\n _, _, tag = tag.rpartition(\"}\")\n return tag\n\n\ndef parse_hierarchy(df, element, identifier=None, heading=None):\n element_tag = strip_namespace(element.tag)\n for item in element:\n item_tag = strip_namespace(item.tag)\n if \"identifier\" in item.attrib:\n identifier = item.attrib[\"identifier\"]\n if element_tag == \"section\":\n if item_tag == \"heading\":\n heading = item.text\n if item_tag == \"content\":\n parse_content(df, item, identifier, heading)\n elif item_tag not in hierarchy:\n continue\n else:\n parse_hierarchy(df, item, identifier, heading)\n\ndef parse_content(dict_list, element, identifier: str, heading: str):\n text = \"\"\n for item in element:\n item_tag = strip_namespace(item.tag)\n if item_tag == \"p\" and item.text:\n text += item.text.strip()\n\n if text and len(text.split()) > 5:\n #print(heading, \"|\", text, identifier)\n dict_list.append({\"heading\": heading, \"identifier\": identifier, \"text\": text, \"keywords\": \"\"})\n with open(f\"text/{len(dict_list)}.txt\", \"w\") as f:\n f.write(text)\n\ndef parse_usc():\n merged_entries = []\n for file in glob(\"xml_usc/*.xml\"):\n print(file)\n tree = ET.parse(file)\n root = tree.getroot()\n ls = []\n for item in root:\n tag = strip_namespace(item.tag)\n if tag == \"main\":\n parse_hierarchy(ls, item)\n\n merged_entries.extend(ls)\n df = pd.DataFrame(ls)\n if df.shape[0] > 0:\n df.to_csv(f\"parsed/{pathlib.Path(file).stem}.csv\", index=False)\n\n merged_df = pd.DataFrame(merged_entries)\n merged_df.to_csv(\"merged_usc.csv\", index=False)\n\nif __name__ == '__main__':\n parse_usc()","repo_name":"Dashadower/w2v_uscode","sub_path":"parse_xml.py","file_name":"parse_xml.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16609346467","text":"#Define a function called data_type, to take one argument. Compare and return results, based on the argument supplied to the function.\n# Complete the test to produce the perfect function that accounts for all expectations.\n#For strings, return its length.\n#For None return string 'no value'\n#For booleans return the boolean\n#For integers return a string showing how it compares to hundred e.g. For 67 return 'less than 100' for 4034 return 'more than 100' or equal to 100 as the case may be\n#For lists return the 3rd item, or None if it doesn't exist\n\n\n\ndef data_type(param):\n if type(param) == str:\n return len(param)\n elif param is None:\n return 'no value'\n elif type(param) == bool:\n return param\n elif type(param) == int:\n if param < 100:\n return 'less than 100'\n elif param > 100:\n return 'more than 100'\n else:\n return 'equal to 100'\n else:\n if type(param) == list:\n if len(param) < 3:\n return None\n else:\n return param[2]","repo_name":"LeakeyMokaya/Leakey_BootCamp_Day2","sub_path":"Data_Types/data_type.py","file_name":"data_type.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42368536380","text":"from asyncio import TimeoutError, wait_for\nimport os\nimport tempfile\nimport sys\n\ntry:\n from unittest import IsolatedAsyncioTestCase\nexcept ImportError:\n from .async_case import IsolatedAsyncioTestCase\n\nfrom psycopg2 import OperationalError, ProgrammingError, InterfaceError\nfrom psycopg2.extensions import connection\n\nfrom psycaio import connect, AioConnection, AioConnMixin\n\nfrom .loops import loop_classes\n\n\nclass ConnTestCase(IsolatedAsyncioTestCase):\n\n async def test_connect(self):\n cn = await connect(dbname='postgres')\n self.assertIsInstance(cn, AioConnection)\n self.assertEqual(sys.getrefcount(cn), 2)\n\n async def test_connect_dsn(self):\n cn = await connect('dbname=postgres')\n self.assertIsInstance(cn, AioConnection)\n\n async def test_connect_timeout(self):\n cn = await connect(dbname='postgres', connect_timeout=\"10\")\n self.assertIsInstance(cn, AioConnection)\n self.assertEqual(cn.get_dsn_parameters()[\"connect_timeout\"], \"10\")\n\n cn = await connect(dbname='postgres', connect_timeout=\"1\")\n self.assertEqual(cn.get_dsn_parameters()[\"connect_timeout\"], \"1\")\n\n cn = await connect(dbname='postgres', connect_timeout=-1)\n self.assertEqual(cn.get_dsn_parameters()[\"connect_timeout\"], \"-1\")\n\n async def test_wrong_number_of_hosts(self):\n with self.assertRaises(OperationalError):\n await connect(host=\"db1.com,db2.com\", hostaddr=\"127.0.0.1\")\n\n async def test_wrong_number_of_ports(self):\n with self.assertRaises(OperationalError):\n await connect(port=\"5432,5432\")\n\n async def test_one_port(self):\n cn = await connect(dbname='postgres', host=\",\", port=\"5432\")\n self.assertIsInstance(cn, AioConnection)\n\n async def test_wrong_port(self):\n with self.assertRaises(OperationalError):\n await connect(dbname='postgres', host=\"localhost\", port=\"2345\")\n\n async def test_wrong_port_hostaddr(self):\n with self.assertRaises(OperationalError):\n await connect(dbname='postgres', hostaddr=\"127.0.0.1\", port=\"2345\")\n\n async def test_service_file(self):\n service_file = tempfile.NamedTemporaryFile('w', delete=False)\n service_file.write(\"[test]\\ndbname=postgres\\n\")\n service_file.close()\n os.environ[\"PGSERVICEFILE\"] = service_file.name\n cn = await connect(service=\"test\")\n self.assertIsInstance(cn, AioConnection)\n del os.environ[\"PGSERVICEFILE\"]\n os.unlink(service_file.name)\n\n async def test_environ_port(self):\n os.environ[\"PGPORT\"] = \"5432\"\n cn = await connect(dbname=\"postgres\")\n self.assertIsInstance(cn, AioConnection)\n os.environ[\"PGPORT\"] = \"2345\"\n with self.assertRaises(OperationalError):\n cn = await connect(dbname=\"postgres\")\n del os.environ[\"PGPORT\"]\n\n async def test_invalid_conn(self):\n\n class BadConn:\n\n def __init__(self, *args, **kwargs):\n pass\n\n with self.assertRaises(OperationalError):\n await connect(dbname='postgres', connection_factory=BadConn)\n\n async def test_reverse_conn(self):\n\n class BadConn(connection, AioConnMixin):\n pass\n\n with self.assertRaises(OperationalError):\n await connect(dbname='postgres', connection_factory=BadConn)\n\n async def test_cancellation(self):\n with self.assertRaises(TimeoutError):\n await wait_for(\n connect(dbname='postgres', host='www.example.com'), 0.1)\n\n async def test_unexpected_poll(self):\n old_poll = AioConnection.poll\n AioConnection.poll = lambda self: 5\n with self.assertRaises(OperationalError):\n await connect(dbname=\"postgres\")\n AioConnection.poll = old_poll\n\n cn = await connect(dbname=\"postgres\")\n cn.poll = lambda: 5\n with self.assertRaises(OperationalError):\n await cn.cursor().execute(\"SELECT 42\")\n\n async def test_commit(self):\n cn = await connect(dbname=\"postgres\")\n with self.assertRaises(ProgrammingError):\n cn.commit()\n\n async def test_rollback(self):\n cn = await connect(dbname=\"postgres\")\n with self.assertRaises(ProgrammingError):\n cn.rollback()\n\n async def test_reset(self):\n cn = await connect(dbname=\"postgres\")\n with self.assertRaises(ProgrammingError):\n cn.reset()\n cn.close()\n with self.assertRaises(InterfaceError):\n cn.reset()\n\n async def test_encoding(self):\n cn = await connect(dbname=\"postgres\")\n with self.assertRaises(ProgrammingError):\n cn.set_client_encoding('LATIN1')\n\n\nglobals().update(**{cls.__name__: cls for cls in loop_classes(ConnTestCase)})\ndel ConnTestCase\n","repo_name":"blenq/psycaio","sub_path":"test/test_connection.py","file_name":"test_connection.py","file_ext":"py","file_size_in_byte":4805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12902921816","text":"#!/usr/bin/python3\n\"\"\"This module contains a function that querries the reddit api\"\"\"\nimport requests\n\n\ndef recurse(\n subreddit, hot_list=[],\n params={\"after\": None, \"count\": 0, \"limit\": 100}):\n \"\"\"queries the Reddit API.\n returns: list of titles of all hot articles for subreddit.\n If no results are found for the given subreddit, return None.\"\"\"\n\n url = \"https://www.reddit.com/r/{}/hot.json\".format(subreddit)\n headers = {\"User-Agent\": \"alx /0.0.3\"}\n res = requests.get(\n url, headers=headers, params=params, allow_redirects=False)\n if not res.ok:\n return None\n if res.status_code != 200:\n return None\n data = res.json()[\"data\"]\n posts = data[\"children\"]\n titles = [post[\"data\"][\"title\"] for post in posts]\n hot_list += titles\n\n params[\"after\"] = data[\"after\"]\n params[\"count\"] += data[\"dist\"]\n if params[\"after\"]:\n return recurse(subreddit, hot_list, params)\n\n return hot_list\n","repo_name":"MwauratheAlex/alx-system_engineering-devops","sub_path":"0x16-api_advanced/2-recurse.py","file_name":"2-recurse.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"17109864089","text":"import pytest\n\nfrom pytest_api import BEHAVIORS, OPEN_API\nfrom test_app.fast_api import spec\n\n\n@spec.describe\ndef test_default_route(client):\n \"\"\"\n GIVEN\n WHEN root endpoint is called with GET method\n THEN response with status 200 and body OK is returned\n \"\"\"\n path = \"/\"\n response = client.get(path, headers={\"spec-description\": test_default_route.id})\n assert response.status_code == 200\n assert response.json() == {\"message\": \"OK\"}\n assert path in BEHAVIORS\n assert response_description(path, \"get\", response.status_code, test_default_route)\n\n\n@spec.describe(route=\"/health-check/\")\ndef test_health_check(client):\n \"\"\"\n GIVEN \"/health-check/\"\n WHEN health check endpoint is called with GET method\n THEN response with status 200 and body OK is returned\n \"\"\"\n path = \"/health-check/\"\n response = client.get(path, headers={\"spec-description\": test_health_check.id})\n assert response.json() == {\"message\": \"OK\"}\n assert path in BEHAVIORS\n assert response_description(path, \"get\", response.status_code, test_health_check)\n\n\n@spec.describe(route=\"/behavior-example/\")\ndef test_example_body(client):\n \"\"\"\n GIVEN behavior in body\n WHEN example behavior endpoint is called with POST method\n THEN response with status 200 and body OK is returned\n \"\"\"\n path = \"/behavior-example/\"\n response = client.post(\n path,\n json={\"name\": \"behavior\"},\n headers={\"custom\": \"header\", \"spec-example\": test_example_body.id},\n )\n assert response.json() == {\"message\": \"OK\"}\n assert path in BEHAVIORS\n assert request_body_example_description(path, \"post\", test_example_body)\n\n\n@spec.describe(route=\"/behavior-example/\")\ndef test_second_example_body(client):\n \"\"\"\n GIVEN second behavior in body\n WHEN example behavior endpoint is called with POST method\n THEN response with status 200 and body OK is returned\n \"\"\"\n path = \"/behavior-example/\"\n response = client.post(\n path,\n json={\"name\": \"second behavior\"},\n headers={\"custom\": \"header\", \"spec-example\": test_second_example_body.id},\n )\n assert response.json() == {\"message\": \"OK\"}\n assert path in BEHAVIORS\n assert request_body_example_description(path, \"post\", test_second_example_body)\n\n\ndef test_consequences(client):\n with pytest.warns() as miss_behaved:\n client.get(\"/missing-description-decorator\")\n assert \"The consequence for not describing a behavior\" in str(\n miss_behaved[0].message.args[0]\n )\n assert \"/missing-description-decorator\" not in BEHAVIORS\n\n\ndef response_description(path, method, status_code, func):\n return (\n OPEN_API[\"paths\"][path][method][\"responses\"][status_code][\"description\"]\n == func.__doc__\n )\n\n\ndef request_body_example_description(path, method, func):\n return (\n OPEN_API[\"paths\"][path][method][\"requestBody\"][\"content\"][\"application/json\"][\n \"examples\"\n ][func.__name__][\"description\"]\n == func.__doc__\n )\n","repo_name":"sturzaam/pytest-api","sub_path":"tests/test_fast_api.py","file_name":"test_fast_api.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"9274469756","text":"import math\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch import nn\nfrom torch import asin\nfrom torch.utils.data.dataloader import default_collate\nfrom collections import OrderedDict\nfrom typing import List\n\nclass LinearArcsine(nn.Linear):\n \"\"\"\n Linear layer with arcsine activation:\n x -> arcsine(normalize([x,1]).T @ normalize([W;b]))\n \"\"\"\n def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None) -> None:\n factory_kwargs = {'device': device, 'dtype': dtype}\n super(LinearArcsine, self).__init__(in_features, out_features, bias, device, dtype)\n self.in_features = in_features\n self.out_features = out_features\n self.weight = nn.Parameter(torch.empty((in_features, out_features), **factory_kwargs))\n if bias:\n self.bias = nn.Parameter(torch.empty((1,out_features), **factory_kwargs))\n else:\n self.register_parameter('bias', None)\n self.reset_parameters()\n def reset_parameters(self) -> None:\n # Setting a=sqrt(5) in kaiming_uniform is the same as initializing with\n # uniform(-1/sqrt(in_features), 1/sqrt(in_features)). For details, see\n # https://github.com/pytorch/pytorch/issues/57109\n nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))\n if self.bias is not None:\n fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)\n bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0\n nn.init.uniform_(self.bias, -bound, bound)\n\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n if self.bias is not None:\n W = torch.concat([self.weight, self.bias], dim = 0) # [in_features+1, out_features]\n input = torch.concat([input, torch.ones((input.shape[0],1),device=input.device)], dim=1) # [batch_size, in_features+1]\n else:\n W = self.weight\n return torch.asin(nn.functional.normalize(input, dim = 1) @ nn.functional.normalize(W, dim = 0))\n\nindicator = lambda x : (x > 0).float()\n\nclass RandomFeatureMap(nn.Module): \n \"\"\"\n Random feature map for arcsin\n \"\"\"\n def __init__(self, in_features: int, out_features: int = None, device = 'cpu'):\n \"\"\"\n Build a feature map for arcsin\n \"\"\"\n super().__init__()\n self.in_features = in_features\n self.out_features = in_features if out_features is None else out_features\n \"\"\"\n weights is d by d Gaussian matrix \n \"\"\"\n weights = [nn.Parameter(torch.tensor(np.random.normal(loc=0.0, scale=1.0, size=(self.in_features,self.out_features)),device=device), requires_grad=False)] # for each N, generate N random Rademacher vectors\n self.weights = nn.ParameterList(weights)\n \n \n \n def forward(self, x):\n \"\"\"\n return feature map for arcsin: for each Z in weights matrix have the feature sign(Z dot x) = 2*indicator(Z dot x) -1\n with these features, phix^T phiy estimates d*(2/pi)arcsin(x^T y / ||x||||y||) \n \"\"\"\n\n return torch.stack([2*indicator(x @ weight)-1 for weight in self.weights]).squeeze(0)\n\n\nclass ArcsinNN(nn.Module):\n \"\"\"\n arcsin\n nn with arcsine activation\n \"\"\"\n def __init__(self, in_features: int, out_features: int, hidden_features: List[int] = None):\n \"\"\"\n Initialize an ArcsinNN\n hidden_features: a list contains the dimension of hidden layers\n \"\"\"\n super(ArcsinNN, self).__init__()\n self.num_hidden_layers = len(hidden_features) if hidden_features else 0\n self.Flatten = nn.Flatten() # flatten the input\n\n if self.num_hidden_layers:\n Layers = []\n dims = [in_features] + hidden_features\n for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):\n Layers.append(('LinearArcsine'+f'{i}', LinearArcsine(in_features = in_dim, out_features = out_dim)))\n Layers.append(('Output', nn.Linear(in_features = hidden_features[-1], out_features= out_features)))\n self.Layers = nn.Sequential(OrderedDict(Layers))\n \n else:\n raise ValueError(\"Missing hidden_feautres!\")\n \n def forward(self, x):\n \n x = self.Flatten(x)\n logits = self.Layers(x)\n \n return logits\n\nclass ApproxArcsineNN(nn.Module):\n \"\"\"\n Given a valid ArcsinNN model, approximate the ArcsinNN using RandomFeatureMap for each LinearArcsine layers\n \"\"\"\n def __init__(self, model: ArcsinNN = None):\n super(ApproxArcsineNN, self).__init__()\n if model is None or type(model) is not ArcsinNN:\n raise ValueError(\"Missing input ArcsinNN model!\")\n\n self.num_hidden_layers = model.num_hidden_layers\n\n self.Flatten = nn.Flatten() # flatten the input\n \n # create random feature maps\n dims = set(model.Layers[i].in_features for i in range(self.num_hidden_layers))\n self.RandomFeatureMaps = {d: RandomFeatureMap(d+1, device=model.Layers[0].weight.device).float() for d in dims}\n\n # copy and paste weights\n self.Linears = nn.ModuleList([nn.Linear(in_features=model.Layers[i].in_features, out_features=model.Layers[i].out_features) for i in range(self.num_hidden_layers)])\n for i in range(self.num_hidden_layers):\n self.Linears[i].weight = nn.Parameter(model.Layers[i].weight.clone().detach())\n self.Linears[i].bias = nn.Parameter(model.Layers[i].bias.clone().detach())\n self.Output = nn.Linear(in_features=model.Layers[-1].in_features, out_features=model.Layers[-1].out_features)\n self.Output.weight = nn.Parameter(model.Layers[-1].weight.clone().detach())\n self.Output.bias = nn.Parameter(model.Layers[-1].bias.clone().detach())\n\n def forward(self, x):\n\n x = self.Flatten(x) # [n, D_in]\n\n for i in range(self.num_hidden_layers):\n n, D = x.shape[0], x.shape[1]\n x = torch.concat([x, torch.ones((n, 1), device=x.device)], dim = 1) # [n, D_in + 1]\n W = torch.concat([self.Linears[i].weight, self.Linears[i].bias], dim = 0) # [D_in + 1, D_out]\n phi_x = self.RandomFeatureMaps[D](x) # [n, D_in + 1]\n phi_W = self.RandomFeatureMaps[D](W.T) # [D_out, D_in + 1]\n x = (np.pi/2)*((phi_x @ phi_W.T)/(D+1))\n\n # output layer\n logits = self.Output(x)\n \n return logits\n\nclass RepresentArcsineNN(nn.Module):\n \"\"\"\n Given a valid ArcsinNN model, approximate the ArcsinNN using RandomFeatureMap for each LinearArcsine layers, and represent using composition of feature maps.\n \"\"\"\n def __init__(self, model: ArcsinNN = None):\n super(RepresentArcsineNN, self).__init__()\n if model is None or type(model) is not ArcsinNN:\n raise ValueError(\"Missing input ArcsinNN model!\")\n\n self.num_hidden_layers = model.num_hidden_layers\n\n self.Flatten = nn.Flatten() # flatten the input\n \n # create random feature maps\n self.input_dim = model.Layers[0].in_features\n self.RandomFeatureMaps = {i: RandomFeatureMap(self.input_dim + i + 1, device = model.Layers[0].weight.device).float() for i in range(self.num_hidden_layers)}\n\n # copy and paste weights\n self.Linears = nn.ModuleList([nn.Linear(in_features=model.Layers[i].in_features, out_features=model.Layers[i].out_features) for i in range(self.num_hidden_layers)])\n for i in range(self.num_hidden_layers):\n self.Linears[i].weight = nn.Parameter(model.Layers[i].weight.clone().detach())\n self.Linears[i].bias = nn.Parameter(model.Layers[i].bias.clone().detach())\n self.Output = nn.Linear(in_features=model.Layers[-1].in_features, out_features=model.Layers[-1].out_features)\n self.Output.weight = nn.Parameter(model.Layers[-1].weight.clone().detach())\n self.Output.bias = nn.Parameter(model.Layers[-1].bias.clone().detach())\n \n def forward(self, x):\n x = self.Flatten(x)\n \n n, D = x.shape[0], x.shape[1] \n W = torch.eye(self.Linears[0].weight.shape[0], device=self.Linears[0].weight.device)\n for i in range(self.num_hidden_layers):\n # compute phi(phi(...phi(x))) \n x = torch.concat([x, torch.ones((n, 1), device=x.device)], dim = 1) \n x = self.RandomFeatureMaps[i](x)\n\n # compute phi(phi(...phi(W)))\n W = torch.matmul(W, self.Linears[i].weight)\n W = torch.concat([W, self.Linears[i].bias], dim = 0)\n W = (torch.pi/2/W.shape[0]) * self.RandomFeatureMaps[i](W.T).T\n\n x = torch.matmul(x, W)\n\n logits = self.Output(x)\n return logits","repo_name":"hlnchen/feature-map-nnapprox","sub_path":"layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":8731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10771516625","text":"from math import sqrt\nfrom queue import PriorityQueue\n\ndef manhattan_distance(v1, v2):\n \"\"\"\n Computes manhattan distance\n Since there is no cost for traveling from node to node, we ignore it ( it's like if the cost was equal to zero).\n\n return dist: The manhattan distance between v1 and v2\n \"\"\"\n dist = sum([abs(a - b) for a, b in zip(v1, v2)])\n return dist\n\ndef euclidean_distance(v1, v2):\n \"\"\"\n Computes euclidean distance\n Since there is no cost for traveling from node to node, we ignore it ( it's like if the cost was equal to zero).\n\n return dist: The euclidean distance between v1 and v2\n \"\"\"\n dist = sqrt(sum([(a - b)**2 for a, b in zip(v1, v2)]))\n return dist\n\nclass Jormungandr():\n \"\"\"\n Why this name? --> I could have called it Ouroboros but Jormungandr is a cooler name (see: https://en.wikipedia.org/wiki/J%C3%B6rmungandr)\n \"\"\"\n\n def __init__(self, frame_size_x: int, frame_size_y: int, heuristic: str):\n self.MAX_X = frame_size_x\n self.MAX_Y = frame_size_y\n \n # Manhattan distance\n if heuristic == 'manhattan':\n self.heuristic_value = manhattan_distance\n \n # Euclidean distance\n elif heuristic == 'euclidean':\n self.heuristic_value = euclidean_distance\n\n else:\n raise ValueError('Unknown heuristic, avaliable values: manhattan, euclidean (dont use commas if you are on the command line')\n\n\n def can_expand(self, node: tuple, obstacles: dict, open: dict, closed: dict):\n \"\"\"\n Checks if the node can actually be generated.\n\n Args:\n node (tuple): The current node we are at.\n obstacles (dict): Positions which we can not walk on (the snake's body).\n open (dict): Open nodes.\n closed (dict): Closed nodes.\n\n return:\n True if the node can be generated\n False in other case.\n \"\"\"\n # First, we check if node it's not out of bounds.\n if node [0] [0] < 0 or node [0] [0] > self.MAX_X - 10 or node [0] [1] < 0 or node [0] [1] > self.MAX_Y - 10:\n return False\n\n try:\n\n #If node is a closed node it should not be generated.\n closed [node [0] ]\n return False\n\n except:\n\n try:\n\n #If node has already been generated (is an open node) it should not be generated.\n open [node [0] ]\n return False\n\n except:\n\n try:\n # Here, we check if the number of moves we have to make in order to get to the obstacle is higher than\n # the moves in which the obstacle will no longer be there.\n if obstacles [ node [0] ] < node [1]:\n return True\n\n # The obstacle will still be there when we get there.\n return False\n \n except:\n # Node it's neither a closed or open node nor an obstacle that will not be clear when we get there\n # so, it can be generated.\n return True\n\n\n def expand(self, node: tuple, obstacles: dict, open: dict, closed: dict, target: tuple): \n \"\"\"\n Expands the given node.\n \n Args:\n node (tuple): The current node we are at.\n obstacles (dict): Positions which we can not walk on (the snake's body).\n open (dict): Open nodes.\n closed (dict): Closed nodes.\n target (tuple): Target we want to reach (the food).\n\n Returns:\n List with new nodes to explore.\n \"\"\"\n # A node is a tuple ( (X,Y), N) where X, Y are the coordinates and N is the number of moves the snake has to take to get there\n result = []\n\n # Node above.\n next_node = ( ( node [0] [0], node [0] [1] - 10) , node [1] + 1)\n\n if self.can_expand(next_node, obstacles, open, closed):\n result.append((self.heuristic_value (next_node [0], target), (1, node, next_node)))\n\n # Node below.\n next_node = ( ( node [0] [0], node [0] [1] + 10 ), node [1] + 1)\n\n if self.can_expand(next_node, obstacles, open, closed):\n result.append((self.heuristic_value (next_node [0], target), (2, node, next_node)))\n \n # Node to the left\n next_node = ( ( node [0] [0] - 10, node [0] [1] ), node [1] + 1 )\n\n if self.can_expand(next_node, obstacles, open, closed):\n result.append((self.heuristic_value (next_node [0], target), (3, node, next_node)))\n \n # Node to the right\n next_node = ( ( node [0] [0] + 10, node [0] [1] ), node [1] + 1 )\n\n if self.can_expand(next_node, obstacles, open, closed):\n result.append((self.heuristic_value (next_node [0], target), (4, node, next_node)))\n \n return result\n\n def backtrack (self, paths: dict, target: tuple) -> list:\n \"\"\"\n Backtracks and obtains the path which we have to take\n Args:\n paths (dict): Dictionary with all posible nodes and paths.\n target (tuple): Target we want to reach (the food).\n\n return: List with a move sequence (the path)\n \"\"\"\n path = []\n current = target\n while (True):\n\n # Repeat until we can't go backwards\n try:\n aux_value = paths [ current ]\n path.insert(0, aux_value [0])\n current = aux_value [1]\n except:\n return path\n\n def pathfind(self, snake_body: list, food_pos: list):\n \"\"\"\n A* algorithm\n\n Args:\n snake_body (list): List with snake's body, considered obstacle nodes.\n food_pos (list): Position of the food, considered the goal that we have to reach.\n\n return: List with the action sequence\n \"\"\"\n # paths is a dictionary that contains the possible paths to food_pos.\n # Key: A node in format (X, Y), Value: A tuple (M, (Xf , Yf)) in which the second value is father node and M is the move we have to do\n # in order to get from the father node to the child node.\n\n paths = {}\n\n #Preprocessing\n snake_head = ( tuple( snake_body [0] ) , 0)\n snake_body = [ tuple (x) for x in snake_body [1:] ]\n obstacles = dict.fromkeys(snake_body)\n food_pos = tuple (food_pos)\n\n position = len (snake_body)\n for key in obstacles:\n obstacles [key] = position\n position -=1\n\n open_nodes = PriorityQueue()\n open_nodes_dict = {snake_head [0]: None}\n closed_nodes = {}\n current = snake_head\n\n # It is set to True when food_pos is reached.\n reached = False\n while not reached:\n\n # Expand, get possible nodes\n possible_nodes = self.expand(current, obstacles, open_nodes_dict, closed_nodes, food_pos)\n\n # Current is a closed node, remove also from open nodes\n try: \n del open_nodes_dict [ current [0] ]\n except:\n pass\n closed_nodes [ current [0] ] = None\n\n # Put them in queue and in the open nodes list\n for node in possible_nodes:\n open_nodes.put(node)\n open_nodes_dict [ node [1] [2] [0] ] = None\n\n # Get node, and add to path dictionary, also, now it's a closed node\n current = open_nodes.get() [1]\n paths [ current [2] [0] ] = (current [0], current [1] [0] )\n\n current = current [2]\n\n # If we reached the food\n if current [0] [0] == food_pos [0] and current [0] [1] == food_pos [1]:\n reached = True\n\n if open_nodes.empty():\n print(\"No way!\")\n\n # By default go up, but there's no possible path to the food\n return [1]\n\n # Backtrack to get the real path to food_pos.\n path = self.backtrack(paths, food_pos)\n return path","repo_name":"OverKoder/Jormungandr","sub_path":"Jormungandr.py","file_name":"Jormungandr.py","file_ext":"py","file_size_in_byte":8099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36275169740","text":"import numpy as np \nfrom backpropogation import backprop\nimport json \n\nclass Network:\n\n def __init__ (self,size):\n self.insize=size[0]\n self.osize=size[-1]\n self.sizes=size\n self.num_layers=len(size)\n # Needs to be tested ,Can have an alternative of Zero Intitalization\n self.weights= [np.random.randn(y, x)\n for x, y in zip(size[:-1], size[1:])]\n self.biases= [np.random.randn(y, 1) for y in size[1:]]\n \n def feedforward(self, a):\n for b, w in zip(self.biases, self.weights):\n a = sigmoid(np.dot(w, a)+b)\n return a\n #Needs work \n def hebbian(self,input,eta,forget):\n out=[]\n a =input\n \n out.append(a)\n for b, w in zip(self.biases, self.weights):\n a = sigmoid(np.dot(w, a)+b)\n out.append(a) \n nabw=[]\n print(out)\n for j,i in zip(out[1:],out[:-1]):\n nabw.append(np.dot(i,np.transpose(j)).transpose())\n \n #implement forgetting factor\n self.weights=[w+eta*nw for w,nw in zip(self.weights,nabw)] \n #check the bias update\n self.biases=[b+eta*nw for b,nw in zip(self.biases,out[1:])]\n \n #Implement Hebbian interface\n \n\n # reverse traversal\n #Still needs research , Current implementation is just inverse of sigmoid\n def rev(self,op):\n wr=self.weights[:]\n br=self.biases[:]\n wr=np.flip(wr)\n br=np.flip(br)\n reverse=list(zip(br,wr))\n for b,w in reverse:\n op=op-b\n op=inv_sigmoid(np.dot(np.transpose(w),op))\n return op\n\n def QS(self,data ,fqu, eta):\n #implement a little deviator \n for j in range(fqu):\n self.update_mini_batch(data, eta)\n\n def update_mini_batch(self, mini_batch, eta):\n nabla_b = [np.zeros(b.shape) for b in self.biases]\n nabla_w = [np.zeros(w.shape) for w in self.weights]\n for x, y in mini_batch:\n self,delta_nabla_b, delta_nabla_w = backprop(self,x, y)\n nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]\n nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]\n self.weights = [w-(eta/(len(mini_batch)+1))*nw\n for w, nw in zip(self.weights, nabla_w)]\n self.biases = [b-(eta/len(mini_batch))*nb\n for b, nb in zip(self.biases, nabla_b)]\n\n def evaluate(self, test_data):\n test_results = [(np.argmax(self.feedforward(x)), y)\n for (x, y) in test_data]\n return sum(int(x == y) for (x, y) in test_results)\n \n def cost_derivative(self, output_activations, y):\n return (output_activations-y)\n \n def save(self):\n data = {\"sizes\": self.sizes,\n \"weights\": [w.tolist() for w in self.weights],\n \"biases\": [b.tolist() for b in self.biases]}\n return data\n \n def load(self,data):\n self.weights = [np.array(w) for w in data[\"weights\"]]\n self.biases = [np.array(b) for b in data[\"biases\"]]\n \ndef sigmoid(z):\n return 1.0/(1.0+np.exp(-z))\n\ndef sigmoid_prime(z):\n return sigmoid(z)*(1-sigmoid(z)) \ndef inv_sigmoid(z):\n return sigmoid(z)\n #To be left for discussion over inverse sigmoid function , Currently only using sigmoid","repo_name":"DantrazTrev/The-Butterfly-","sub_path":"NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13930975423","text":"from notifications.models import Notification\n\nimport constants\nfrom libs.websocket import TipNotificationWebsocket\nfrom tests.base_test import BaseTestCase\nfrom tests.factories import TipFactory\n\n\nclass TestTipNotificationWebsocket(BaseTestCase):\n @classmethod\n def setUpTestData(cls):\n super().setUpTestData()\n\n cls.tip1 = TipFactory.create(\n added_by=cls.manager_user,\n updated_by=cls.super_user,\n )\n cls.tip2 = TipFactory.create(\n added_by=cls.manager_user,\n updated_by=cls.manager_user,\n )\n\n def test_send_editing_notification_to_tip_owner(self):\n old_count = Notification.objects.filter(\n verb=constants.Activity.SET_TIP_EDIT_MARK\n ).count()\n\n TipNotificationWebsocket.send_editing_notification_to_tip_owner(\n self.tip1\n )\n\n count = Notification.objects.filter(\n verb=constants.Activity.SET_TIP_EDIT_MARK\n ).count()\n self.assertEqual(old_count + 1, count)\n\n def test_send_editing_notification_to_tip_owner_with_updated_user_is_owner_tip(\n self,\n ):\n old_count = Notification.objects.filter(\n verb=constants.Activity.SET_TIP_EDIT_MARK\n ).count()\n\n TipNotificationWebsocket.send_editing_notification_to_tip_owner(\n self.tip2\n )\n\n new_count = Notification.objects.filter(\n verb=constants.Activity.SET_TIP_EDIT_MARK\n ).count()\n self.assertEqual(old_count, new_count)\n","repo_name":"stanislavpol00/education","sub_path":"tests/unit/libs/websocket/test_tip.py","file_name":"test_tip.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1876915864","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport numpy as np\nimport pandas as pd\nimport scanpy as sc # v1.4.3\\n\",\nimport scrublet as scr\nimport sys\nimport bbknn\nfrom statsmodels import robust\nimport sys\nimport matplotlib.pyplot as plt\nimport forceatlas2 as fa\nimport os.path\n\n###Set working directory\nos.chdir('/home/ngr18/hcaskin/raw_data')\n\n\n###############################################################################\n#%% Settings\nsc.settings.set_figure_params(dpi=150)\n###############################################################################\n#%% Load -- csv prepared from the manifest xlsx file\nmanifest = pd.read_csv('sample_manifest.csv')\n#manifest['sample_id']\n#manifest['vdj']\n###############################################################################\n#%% Load\npath = './'\nnames = manifest['sample_id'].tolist()\nfilenames = [os.path.join(path, n) for n in names]\n\n\n\n#%% Concatenate and save\nadatas = [sc.read_10x_mtx(filename, cache=True) for filename in filenames]\n\nadata = adatas[0].concatenate(adatas[1:], join='inner', batch_key='sample_id', batch_categories=names, index_unique='-')\n\nsave_file = 'adata_raw.h5ad'\nadata.write(save_file)\n\n\n\n###############################################################################\n#%% Metadata\nfor metadata in manifest.columns[1:-1]: # sample_id and vdj not needed\n print(metadata)\n adata.obs[metadata] = adata.obs['sample_id']\n replacement = manifest[metadata].tolist()\n adata.obs[metadata].replace(to_replace=names, value=replacement, inplace=True)\n\n#adata.obs['donor_id']\n#adata.obs_keys\n###############################################################################\n\n\nmeta_10x_channels = 'sample_id'\n\nRUNs, DSs, CELLs, THRs, MEDs, MADs, CUTs, no_thr = [], [], [], [], [], [], [], []\n\n# Loop through channels in anndata object:\norig_stdout = sys.stdout\nsys.stdout = open('scrublet_output_file_mad.txt', 'w')\n\nfor run in adata.obs[meta_10x_channels].unique():\n print(run)\n ad = adata[adata.obs[meta_10x_channels] == run, :]\n x = ad.X\n scrub = scr.Scrublet(x)\n ds, prd = scrub.scrub_doublets()\n RUNs.append(run)\n DSs.append(ds)\n CELLs.append(ad.obs_names)\n # MAD calculation of threshold:\n MED = np.median(ds)\n MAD = robust.mad(ds)\n CUT = (MED + (4 * MAD))\n MEDs.append(MED)\n MADs.append(MAD)\n CUTs.append(CUT)\n\n try: # not always can calculate automatic threshold\n THRs.append(scrub.threshold_)\n print('Threshold found by scrublet')\n except:\n THRs.append(0.4)\n no_thr.append(run)\n print('No threshold found, assigning 0.4 to', run)\n scrub.call_doublets(threshold=0.4) # so that it can make the plot\n fig = scrub.plot_histogram()\n fig[0].savefig(run + '.png')\n\n # Alternative histogram for MAD-based cutoff\n scrub.call_doublets(threshold=CUT)\n fig = scrub.plot_histogram()\n fig[0].savefig(run + '_mad_' + '.png')\n plt.close('all')\n print()\n print()\n\nprint()\nprint('The following sample(s) do not have automatic threshold:')\nprint(no_thr)\n\nsys.stdout.close()\nsys.stdout = orig_stdout\n\nns = np.array(list(map(len, DSs)))\n\ntbl = pd.DataFrame({\n 'run': np.repeat(RUNs, ns),\n 'ds': np.concatenate(DSs),\n 'thr': np.repeat(THRs, ns),\n 'mad_MED': np.repeat(MEDs, ns),\n 'mad_MAD': np.repeat(MADs, ns),\n 'mad_thr': np.repeat(CUTs, ns),\n }, index=np.concatenate(CELLs))\n\ntbl['auto_prd'] = tbl['ds'] > tbl['thr']\ntbl['mad_prd'] = tbl['ds'] > tbl['mad_thr']\n\ntbl.to_csv('doublets_score_mad.csv', header=True, index=True)\n\n\n\nadata.obs['mad_prd']=tbl['mad_prd']\nadata = adata[tbl['mad_prd'] != True]\n\n\nsave_file = 'adata_scrubletremoved.h5ad'\nadata.write(save_file)\n\n","repo_name":"haniffalab/HCA_skin","sub_path":"Pipelines/01_Data_preprocessing/Data_import_and_doublet_detection.py","file_name":"Data_import_and_doublet_detection.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"3"}
+{"seq_id":"21935802106","text":"import datetime\nfrom tqdm import *\nfrom pymongo import MongoClient\n\nclient = MongoClient('localhost', 27017)\ndb = client['btc-stock-db']\nbtc_collection = db['btc-usd']\nbtc_collection.drop()\n\nwith open(\"bit_pr.csv\") as f:\n lines = f.readlines()\n iterlines = iter(lines)\n next(iterlines)\n pbar = tqdm(total=len(lines)-1)\n for line in iterlines:\n [empty, timestamp, price] = line.split(\",\")\n post = {\n \"date\": datetime.datetime.fromtimestamp(float(timestamp)),\n \"price\": price.rstrip()\n }\n btc_collection.insert_one(post)\n pbar.update(1)\n","repo_name":"mrowacz/BTCStockSimulator","sub_path":"python/put_data.py","file_name":"put_data.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42026311808","text":"import RPi.GPIO as GPIO\nimport time\n\ndac = [26, 19, 13, 6, 5, 11, 9, 10]\n\nGPIO.setmode (GPIO.BCM)\nGPIO.setup (dac, GPIO.OUT)\n\ndef d2b (val):\n return (int (elem) for elem in bin (val) [2:].zfill(8))\n\ndef is_digit (str):\n if (str.isdigit()):\n return True\n else:\n try:\n float (str)\n return True\n except ValueError:\n return False\n\ntry:\n print (\"enter the number\")\n val = input ()\n\n if val == \"q\":\n quit ()\n\n if is_digit (val) == False:\n print (\"no, enter a number\")\n quit ()\n\n if float (val) % 1 != 0:\n print (\"no, an integer\")\n quit ()\n\n val = int (val)\n\n if val > 255:\n print (\"no, less then 256\")\n quit ()\n\n if val < 0:\n print (\"no, a postive one\")\n quit ()\n\n GPIO.output (dac, list (d2b (val)))\n print (val / 256 * 3.3)\n time.sleep (4)\n\nfinally:\n GPIO.output (dac, 0)\n GPIO.cleanup ()\n","repo_name":"quaiion/mcu-sketches","sub_path":"raspberry-pi/4-DAC/dac.py","file_name":"dac.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19265492737","text":"import spydrnet as sdn\n\n\nTAB = \"\\t\"\nNEW_LINE = \"\\n\"\nCARRIAGE_RETURN = \"\\r\"\nSPACE = \" \"\nFORM_FEED = \"\\f\"\n\nNUMBERS = {\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"}\nLETTERS = {\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"x\",\n \"y\",\n \"z\",\n \"A\",\n \"B\",\n \"C\",\n \"D\",\n \"E\",\n \"F\",\n \"G\",\n \"H\",\n \"I\",\n \"J\",\n \"K\",\n \"L\",\n \"M\",\n \"N\",\n \"O\",\n \"P\",\n \"Q\",\n \"R\",\n \"S\",\n \"T\",\n \"U\",\n \"V\",\n \"W\",\n \"X\",\n \"Y\",\n \"Z\",\n}\n\nWHITESPACE = {SPACE, TAB, NEW_LINE, CARRIAGE_RETURN, FORM_FEED}\n\nOPEN_PARENTHESIS = \"(\"\nCLOSE_PARENTHESIS = \")\"\nSTAR = \"*\"\nSEMI_COLON = \";\"\nMODULE = \"module\"\nINPUT = \"input\"\nOUTPUT = \"output\"\nINOUT = \"inout\"\nWIRE = \"wire\"\nREG = \"reg\"\nDOT = \".\"\nOPEN_BRACKET = \"[\"\nCLOSE_BRACKET = \"]\"\nOPEN_BRACE = \"{\"\nCLOSE_BRACE = \"}\"\nCOLON = \":\"\nCOMMA = \",\"\nOCTOTHORP = \"#\"\nEND_MODULE = \"endmodule\"\nPARAMETER = \"parameter\"\nSINGLE_QUOTE = \"'\"\nLOCAL_PARAM = \"localparam\"\nASSIGN = \"assign\"\nEQUAL = \"=\"\nCELL_DEFINE = \"`celldefine\"\nEND_CELL_DEFINE = \"`endcelldefine\"\nIFDEF = \"`ifdef\"\nDEFINE = \"`define\"\nENDIF = \"`endif\"\nELSIF = \"`elsif\"\nTIMESCALE = \"`timescale\"\nOPEN_BLOCK_COMMENT = \"/*\"\nCLOSE_BLOCK_COMMENT = \"*/\"\nOPEN_LINE_COMMENT = \"//\"\nPRIMITIVE = \"primitive\"\nEND_PRIMITIVE = \"endprimitive\"\nFUNCTION = \"function\"\nEND_FUNCTION = \"endfunction\"\nTASK = \"task\"\nEND_TASK = \"endtask\"\nINTEGER = \"integer\"\nTRI0 = \"tri0\"\nTRI1 = \"tri1\"\nDEFPARAM = \"defparam\"\n\n# SET OF ALL THINGS THAT WILL END AN IDENTIFIER IF THEY ARE NOT ESCAPED.\n# elif ch in {'(', ')', '.', ',', ';', '[', ']', ':', \"{\", \"}\", \"*\", \"#\", \"`\"}:\nBREAKER_TOKENS = {\n SPACE,\n TAB,\n NEW_LINE,\n CARRIAGE_RETURN,\n FORM_FEED,\n OPEN_PARENTHESIS,\n CLOSE_PARENTHESIS,\n COMMA,\n SEMI_COLON,\n OPEN_BRACKET,\n CLOSE_BRACKET,\n COLON,\n OPEN_BRACE,\n CLOSE_BRACE,\n STAR,\n OCTOTHORP,\n EQUAL,\n \"\\\\\",\n '\"',\n \"`\",\n}\n# single quote should not be included here because of 1'b0 type of declarations (these should be one\n# token)\n\nSINGLE_CHARACTER_TOKENS = {\n OPEN_PARENTHESIS,\n CLOSE_PARENTHESIS,\n STAR,\n SEMI_COLON,\n DOT,\n OPEN_BRACKET,\n CLOSE_BRACKET,\n OPEN_BRACE,\n CLOSE_BRACE,\n COLON,\n COMMA,\n COMMA,\n OCTOTHORP,\n SINGLE_QUOTE,\n EQUAL,\n}\n\nPORT_DIRECTIONS = {INPUT, OUTPUT, INOUT}\n\nALL_VERILOG_TOKENS = {\n TAB,\n NEW_LINE,\n CARRIAGE_RETURN,\n SPACE,\n FORM_FEED,\n OPEN_PARENTHESIS,\n CLOSE_PARENTHESIS,\n STAR,\n SEMI_COLON,\n MODULE,\n INPUT,\n OUTPUT,\n INOUT,\n WIRE,\n REG,\n DOT,\n OPEN_BRACKET,\n CLOSE_BRACKET,\n OPEN_BRACE,\n CLOSE_BRACE,\n COLON,\n COMMA,\n OCTOTHORP,\n END_MODULE,\n PARAMETER,\n SINGLE_QUOTE,\n LOCAL_PARAM,\n ASSIGN,\n EQUAL,\n CELL_DEFINE,\n END_CELL_DEFINE,\n IFDEF,\n ENDIF,\n ELSIF,\n OPEN_BLOCK_COMMENT,\n CLOSE_BLOCK_COMMENT,\n OPEN_LINE_COMMENT,\n INTEGER,\n TRI0,\n TRI1,\n DEFPARAM,\n}\n\n\ndef is_valid_identifier(token):\n if token == \"\":\n return False\n elif token[0] == \"\\\\\" and token[-1] == \" \":\n for white in WHITESPACE: # there shouldn't be whitespace before the ending space\n if white in token[:-1]:\n return False\n return True\n else:\n if token[0] not in LETTERS and token[0] != \"_\":\n return False\n for c in token:\n if c not in LETTERS and c not in NUMBERS and c != \"_\":\n return False\n return True\n\n\ndef is_numeric(token):\n if token == \"\":\n return False\n for c in token:\n if c not in NUMBERS:\n return False\n return True\n\n\ndef string_to_port_direction(token):\n if token == INPUT:\n return sdn.Port.Direction.IN\n elif token == OUTPUT:\n return sdn.Port.Direction.OUT\n elif token == INOUT:\n return sdn.Port.Direction.INOUT\n else:\n return sdn.Port.Direction.UNDEFINED\n","repo_name":"byuccl/spydrnet","sub_path":"spydrnet/parsers/verilog/verilog_tokens.py","file_name":"verilog_tokens.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"3"}
+{"seq_id":"31941800316","text":"import subprocess\nimport sys\n\nsys.dont_write_bytecode = True # prevent creation of .pyc files\n\n\ndef determineRevision(dir_path):\n \"\"\"\n Determine the revision of the given directory in a version control system.\n \"\"\"\n # Check for SVN repository\n try:\n svnProcess = subprocess.run(\n [\"svnversion\", \"--committed\", dir_path],\n env={\"LANG\": \"C\"},\n capture_output=True,\n text=True,\n )\n stdout = svnProcess.stdout.strip().split(\":\")[-1]\n if not (\n svnProcess.returncode\n or svnProcess.stderr\n or (stdout == \"exported\")\n or (stdout == \"Unversioned directory\")\n ):\n return stdout\n except OSError:\n pass\n\n # Check for git-svn repository\n try:\n # This will silently perform the migration from older git-svn directory layout.\n # Otherwise, the migration may be performed by the next git svn invocation,\n # producing nonempty stderr.\n subprocess.call([\"git\", \"svn\", \"migrate\"], stderr=subprocess.DEVNULL)\n\n gitProcess = subprocess.run(\n [\"git\", \"svn\", \"find-rev\", \"HEAD\"],\n env={\"LANG\": \"C\"},\n cwd=dir_path,\n capture_output=True,\n text=True,\n )\n stdout = gitProcess.stdout.strip()\n if not (gitProcess.returncode or gitProcess.stderr) and stdout:\n return stdout + (\"M\" if _isGitRepositoryDirty(dir_path) else \"\")\n\n # Check for git repository\n gitProcess = subprocess.run(\n [\"git\", \"log\", \"-1\", \"--pretty=format:%h\", \"--abbrev-commit\"],\n env={\"LANG\": \"C\"},\n cwd=dir_path,\n capture_output=True,\n text=True,\n )\n stdout = gitProcess.stdout.strip()\n if not (gitProcess.returncode or gitProcess.stderr) and stdout:\n return stdout + (\"+\" if _isGitRepositoryDirty(dir_path) else \"\")\n except OSError:\n pass\n return None\n\n\ndef _isGitRepositoryDirty(dir_path):\n gitProcess = subprocess.run(\n [\"git\", \"status\", \"--porcelain\"],\n env={\"LANG\": \"C\"},\n cwd=dir_path,\n capture_output=True,\n )\n if not (gitProcess.returncode or gitProcess.stderr):\n return bool(gitProcess.stdout) # Dirty if stdout is non-empty\n return None\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 2:\n sys.exit(\"Unsupported command-line parameters.\")\n\n dir_path = sys.argv[1] if len(sys.argv) > 1 else \".\"\n\n revision = determineRevision(dir_path)\n if revision:\n print(revision)\n else:\n sys.exit(f\"Directory {dir_path} is not a supported version control checkout.\")\n","repo_name":"sosy-lab/cpachecker","sub_path":"scripts/determine-revision.py","file_name":"determine-revision.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","stars":202,"dataset":"github-code","pt":"3"}
+{"seq_id":"42043807565","text":"import pika, sys, os, ast\nimport cv2, numpy as np\nimport base64\n\ndef consumirImagenActual():\n connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\n channel = connection.channel()\n\n channel.queue_declare(queue='imagenActual')\n\n def callback(ch, method, properties, body):\n try:\n os.remove('img/imgRecuperada.png')\n except:\n print(\"No image to delete\")\n with open('encode.bin', \"wb\") as file:\n file.write(body)\n\n file = open('encode.bin', 'rb')\n byte = file.read()\n file.close()\n \n decodeit = open('img/imgRecuperada.png', 'wb')\n decodeit.write(base64.b64decode((byte)))\n decodeit.close()\n\n print(\" [x] Received \")\n #cv2.imwrite('img/imgOptenida.png',frame)\n\n\n channel.basic_consume(queue='imagenActual', on_message_callback=callback, auto_ack=True)\n\n print(' [*] Waiting for messages. To exit press CTRL+C')\n channel.start_consuming()\n\ndef diferencia():\n frame=cv2.imread('img/imgDeseada.png')\n height, width, channels = frame.shape\n print('height')\n print(height)\n print('width')\n print(width)\n print('channels')\n print(channels)\n for x in range(0, height-1) :\n for y in range(0, width-1) :\n b=frame[x,y,0] #B Channel Value\n g=frame[x,y,1] #G Channel Value\n r=frame[x,y,2] #R Channel Value\n #print(str(x)+\" \"+str(y))\n if b==166 and g==144 and r==73:\n print(\"Lugar deseado:\")\n print(x)\n print(y)\n\n res=0\n\ndef main():\n try:\n consumirImagenActual()\n except KeyboardInterrupt:\n print('Interrupted')\n try:\n sys.exit(0)\n except SystemExit:\n os._exit(0)\n \n\nif __name__ == '__main__':\n main()","repo_name":"manufdzver/SistemaNavegacionCirugiaRobotica","sub_path":"controladorIBVS.py","file_name":"controladorIBVS.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15017525602","text":"import pandas as pd\nimport time\nimport datetime as dt\nfrom modules.util import *\nfrom modules.Logger import *\nfrom stockstats import *\nimport modules.db as db\nimport modules.coinone as co\nfrom collections import defaultdict\n\nclass TestTrade( ):\n\tdef __init__( self, krw, currency, exchanger, feeRate, min_order ):\n\t\tself.currency = currency\n\t\tself.feeRate = feeRate\n\t\tself.exchanger = exchanger\n\t\tself.min_order = min_order\n\n\t\tself.krw_balance = krw\n\t\tself.crypto_balance = 0.0\n\n\tdef buy( self, dict_order, price ):\n\t\tholding = False\n\t\tif len(dict_order) > 0 :\n\t\t\ttmpType = str(dict_order['type'])\n\t\t\tif tmpType == 'bid':\n\t\t\t\tLOG.warn(\"already buy. type=\"+ tmpType )\n\t\t\t\tholding = True\n\t\t\t\treturn\n\n\t\tfee = round( price*self.feeRate )\n\t\tmin_pay = round( self.min_order * (price + fee) )\n\t\tif self.krw_balance < min_pay :\n\t\t\tLOG.error(\"not enough money. krw=>\"+ str(self.krw_balance) + \" \"+self.currency+\"=>\"+ str(min_pay ) )\n\t\t\treturn\n\n\t\tqty = int( self.krw_balance / min_pay )\n\t\tself.crypto_balance = qty\n\t\tLOG.debug(\"krw=\"+ str(self.krw_balance) + \" \"+self.currency+\"=\"+ str(price ) )\n\t\tLOG.debug(\"qty=\"+ str(qty) + \" fee=\"+ str(fee ) + \" min_pay=\"+str(min_pay) )\n\n\t\tself.krw_balance = self.krw_balance - (qty*min_pay)\n\t\tLOG.debug(\"will be krw_balance=\"+ str(self.krw_balance ) )\n\n\t\tnow = get_time()\n\t\tdict = defaultdict(object)\n\t\tdict['exchanger'] = self.exchanger\n\t\tdict['date'] = now\n\t\tdict['currency'] = self.currency\n\t\tdict['type'] = 'bid'\n\t\tdict['price'] = price\n\t\tdict['qty'] = qty\n\t\tdict['feeRate'] = self.feeRate\n\t\tdict['fee'] = fee\n\t\tdict['order_id'] = 'TEST_'+ now\n\t\tdict['profit'] = 0\n\t\tdict['balance'] = self.krw_balance\n\t\tdict['crypto_balance'] = self.crypto_balance\n\n\t\tdf = pd.DataFrame( dict, index=[0] )\n\t\tdb.insert( df, 'TEST')\n\t\tLOG.info(\"end buy\")\n\n\n\tdef sell( self, dict_order, price ):\n\t\tif len(dict_order) < 1 :\n\t\t\tLOG.warn(\"order is empty\")\n\t\t\treturn\n\t\ttmpType = str(dict_order['type'])\n\t\tif tmpType != 'bid':\n\t\t\tLOG.warn(\"last order is \"+ tmpType )\n\t\t\treturn\n\n\t\tdecision = price - (dict_order['price'] + dict_order['fee'] )\n\t\tif decision >= 0 :\n\t\t\tLOG.info(\"not sell!! price=\"+ str(price) + \" decision=\"+str(decision))\n\t\t\treturn\n\n\t\tLOG.info(\"qty=>\"+ str(dict_order['qty']) + \" \"+self.currency+\"=>\"+ str(price ) )\n\t\tqty = dict_order['qty']\n\t\tfee = round(qty*price*self.feeRate)\n\t\tget = qty*price - fee\n\n\t\tprofit = (price - dict_order['price']) / dict_order['price'] * 100\n\n\t\tself.krw_balance = self.krw_balance + get\n\t\tself.crypto_balance = self.crypto_balance - qty\n\n\t\tnow = get_time()\n\t\tdict = defaultdict(object)\n\t\tdict['exchanger'] = self.exchanger\n\t\tdict['date'] = now\n\t\tdict['currency'] = self.currency\n\t\tdict['type'] = 'ask'\n\t\tdict['price'] = price\n\t\tdict['qty'] = dict_order['qty']\n\t\tdict['feeRate'] = self.feeRate\n\t\tdict['fee'] = fee\n\t\tdict['order_id'] = 'TEST_'+ now\n\t\tdict['profit'] = profit\n\t\tdict['balance'] = self.krw_balance\n\t\tdict['crypto_balance'] = self.crypto_balance\n\n\t\tdf = pd.DataFrame( dict, index=[0] )\n\t\tdb.insert( df, 'TEST')\n\t\tLOG.info(\"end\")\n\n\tdef trading( self, signal, price ):\n\t\tif signal['currency'] != self.currency :\n\t\t\treturn\n\t\tLOG.info(\"start \"+self.currency)\n\n\t\t#get recent order and balance\n\t\tsql = \"select * from TEST where exchanger='\"+self.exchanger+\"' and currency='\"+self.currency+\"' order by test_serial desc limit 1\"\n\t\tdf_order = db.select(sql )\n\t\tif df_order.empty == False :\n\t\t\tdf_order = df_order.iloc[0]\n\t\tLOG.debug(\"currency balance=>\"+str(self.crypto_balance)+ \" krw=>\"+str(self.krw_balance))\n\n\t\tif signal['up_50_cross'] == '1':\n\t\t\tself.buy( df_order, price )\n\t\telif signal['down_50_cross'] == '1':\n\t\t\tself.sell( df_order, price )\n\nclass Trade( ):\n\tdef __init__( self, currency, exchanger, feeRate, min_order ):\n\t\tself.currency = currency\n\t\tself.feeRate = feeRate\n\t\tself.exchanger = exchanger\n\t\tself.min_order = min_order\n\n\tdef buy( self, dict_order, price, krw_balance ):\n\t\tholding = False\n\t\tif len(dict_order) > 0 and dict_order['type'] != 'bid':\n\t\t\tLOG.warn(\"already sell. type=\"+ dict_order['type'] )\n\t\t\treturn\n\t\tif len(dict_order) > 0 and dict_order['type'] == 'bid':\n\t\t\tholding = True\n\n\t\tfee = price*self.feeRate\n\t\tmin_pay = self.min_order * (price + fee)\n\n\t\tif self.krw_balance < min_pay :\n\t\t\tLOG.error(\"not enough money. krw=>\"+ str(self.krw_balance) + \" \"+self.currency+\"=>\"+ str(min_pay ) )\n\t\t\treturn\n\t\tif self.krw_balance < min_pay :\n\t\t\tLOG.error(\"not enough money. krw=>\"+ str(krw_balance) + \" \"+self.currency+\"=>\"+ str(min_pay ) )\n\t\t\treturn\n\n\t\tfee = price*self.feeRate\n\t\tqty = self.krw_balance / (price + fee )\n\n\t\turl = 'https://api.coinone.co.kr/v2/order/limit_buy/'\n\t\tpayload = {\n\t\t\t\t\"access_token\": co.ACCESS_TOKEN,\n\t\t\t\t'currency': self.currency\n\t\t\t\t}\n\t\tpayload['qty'] = qty\n\t\tpayload['price'] = price\n\n\t\tLOG.info(\"krw=>\"+ str(krw_balance) + \" \"+self.currency+\"=>\"+ str(price ) )\n\t\tLOG.info(\"qty=>\"+ str(qty) )\n\n\t\tresult = co.post(url, payload)\n\t\tif result is None:\n\t\t\treturn\n\n\t\tif result['result'] == 'success':\n\t\t\tdf = pd.DataFrame()\n\t\t\tdf['exchanger'] = self.exchanger\n\t\t\tdf['date'] = get_time()\n\t\t\tdf['currency'] = self.currency\n\t\t\tdf['type'] = 'bid'\n\t\t\tdf['price'] = price\n\t\t\tdf['qty'] = qty\n\t\t\tdf['feeRate'] = self.feeRate\n\t\t\tdf['fee'] = fee\n\t\t\tdf['order_id'] = result['orderId']\n\t\t\tdb.insert( df, 'ORDERS')\n\n\t\tLOG.info(\"end buy\")\n\n\n\tdef sell( self, dict_order, price, balance ):\n\t\tif len(dict_order) < 1 :\n\t\t\tLOG.warn(\"order is empty\")\n\t\t\treturn\n\t\tif dict_order['type'] != 'bid':\n\t\t\tLOG.warn(\"last order is \"+ dict_order['type'] )\n\t\t\treturn\n\n\t\tdecision = price - (dict_order['price'] + dict_order['fee'] )\n\t\tif decision >= 0 :\n\t\t\tLOG.info(\"sell wait!! price=\"+ str(price) + \" decision=\"+str(decision))\n\t\t\treturn\n\t\turl = 'https://api.coinone.co.kr/v2/order/limit_sell/'\n\t\tpayload = {\n\t\t\t\t\"access_token\": co.ACCESS_TOKEN,\n\t\t\t\t'currency': self.currency\n\t\t\t\t}\n\t\tpayload['qty'] = dict_order['qty']\n\t\tpayload['price'] = price\n\n\t\tLOG.info(\"qty=>\"+ str(qty) + \" \"+self.currency+\"=>\"+ str(price ) )\n\n\t\tresult = co.post(url, payload)\n\t\tif result is None:\n\t\t\treturn\n\n\t\tif result['result'] == 'success':\n\t\t\tdf = pd.DataFrame()\n\t\t\tdf['exchanger'] = self.exchanger\n\t\t\tdf['date'] = get_time()\n\t\t\tdf['currency'] = self.currency\n\t\t\tdf['type'] = 'ask'\n\t\t\tdf['price'] = price\n\t\t\tdf['qty'] = dict_order['qty']\n\t\t\tdf['feeRate'] = self.feeRate\n\t\t\tfee = price * self.feeRate\n\t\t\tdf['fee'] = fee\n\t\t\tdf['order_id'] = result['orderId']\n\t\t\tdb.insert( df, 'ORDERS')\n\t\tLOG.info(\"end\")\n\n\tdef trading( self, signal, price ):\n\t\tif signal['currency'] != self.currency :\n\t\t\treturn\n\t\tLOG.info(\"start \"+self.currency)\n\n\t\t#get recent order\n\t\turl = 'https://api.coinone.co.kr/v2/order/complete_orders/'\n\t\tpayload = {\n\t\t\t\t\"access_token\": co.ACCESS_TOKEN,\n\t\t\t\t\"currency\": self.currency\n\t\t\t\t}\n\n\t\tdf_order = co.post(url, payload)\n\t\tif df_order is None:\n\t\t\treturn\n\n\t\tif df_order['result'] != 'success':\n\t\t\tLOG.error( url + \" Fail code=>\"+result['errorCode'])\n\t\t\treturn\n\t\torder = []\n\t\tif len(df_order['completeOrders']) > 0 :\n\t\t\torder = df_order[0] # recent order\n\n\t\t#get balance\n\t\tbalance = 0.0\n\t\tkrw_balance = 0\n\n\t\turl = 'https://api.coinone.co.kr/v2/account/balance/'\n\t\tpayload = {\n\t\t\t\t\"access_token\": co.ACCESS_TOKEN,\n\t\t\t\t'currency': self.currency\n\t\t\t\t}\n\t\tcontent = co.post( url, payload )\n\t\tif content is None:\n\t\t\treturn\n\n\t\tif content['result'] == 'success':\n\t\t\tif content[ self.currency ] :\n\t\t\t\tbalance = float(content[self.currency]['avail'])\n\t\t\t\tkrw_balance = int(content['krw']['avail'])\n\t\tLOG.debug(\"balance=>\"+str(balance)+ \" krw=>\"+str(krw_balance))\n\n\t\tif signal['up_50_cross'] == '1':\n\t\t\tself.buy( order, price, krw_balance )\n\t\telif signal['down_50_cross'] == '1':\n\t\t\tself.sell( order, price, balance )\n\n\n\n\n\n","repo_name":"blueoyw/python_trader","sub_path":"modules/trade.py","file_name":"trade.py","file_ext":"py","file_size_in_byte":7575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40265488911","text":"\r\n\r\nimport ntplib\r\ndef clock(i):\r\n print(\"Getting time data...\")\r\n try:\r\n client = ntplib.NTPClient()\r\n response = client.request(\"pool.ntp.org\")\r\n startTime = response.tx_time\r\n print(\"Successfully retrieved time data\")\r\n return startTime\r\n except:\r\n if (i < 10):\r\n print(\"Time data retrieval failed. Retrying...\")\r\n clock(i+1)\r\n else:\r\n print(\"unable to get time data. Exiting...\")\r\n exit()\r\n","repo_name":"elidewitt/signal-sight","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16096915004","text":"import torch\nfrom model.Octavius import Octavius\n\nfrom model.LAMM.conversations import conv_templates\nfrom .test_base import TestBase\n\n\nclass TestOctavius(TestBase):\n\n def __init__(self, **args):\n super().__init__()\n self.args = args\n\n self.conv_mode = args['conv_mode']\n self.task_type = 'normal'\n self.max_tgt_len = args['max_tgt_len']\n\n self.model = Octavius(**args)\n delta_ckpt = torch.load(args['delta_ckpt_path'], 'cpu')\n info = self.model.load_state_dict(delta_ckpt, strict=False)\n \n self.model = self.model.eval().half()\n self.move_to_device()\n\n def move_to_device(self):\n if torch.cuda.is_available():\n self.dtype = torch.float16\n self.device = 'cuda'\n else:\n self.dtype = torch.float32\n self.device = 'cpu'\n self.model = self.model.to(self.device, dtype=self.dtype)\n\n def generate_conversation_text(self, input_list, history, sys_msg = None):\n conv = conv_templates[self.conv_mode]\n if sys_msg:\n if conv.sys_temp is not None:\n conv.system = conv.sys_temp.format(system_message=sys_msg)\n else:\n conv.system = sys_msg\n prompts_list = []\n for input in input_list:\n prompts = ''\n prompts += conv.system + '\\n\\n'\n for q, a in history:\n prompts += \"{}: {}\\n{} {}: {}\\n{}\".format(conv.roles[0], q, conv.sep, conv.roles[1], a, conv.sep2 if (conv.sep2 is not None) else conv.sep)\n prompts += \"{}: {}\\n{}\".format(conv.roles[0], input, conv.sep)\n prompts_list.append(prompts)\n return prompts_list\n\n @torch.no_grad()\n def do_generate(self, modality_inputs, question_list, top_p=0.9, temperature=1.0):\n response = self.model.generate({\n 'prompt': question_list,\n 'image_paths': modality_inputs,\n 'top_p': top_p,\n 'temperature': temperature,\n 'max_tgt_len': self.max_tgt_len,\n 'modality_embeds': []\n })\n\n conv = conv_templates[self.conv_mode]\n ans_list = []\n for res in response:\n ans_list.append(res.split(conv.sep2 if conv.sep2 is not None else conv.sep)[0])\n return ans_list\n\n @torch.no_grad()\n def do_generate_vqa(self, modality_inputs, question_list, top_p=0.9, temperature=1.0):\n conv = conv_templates[self.conv_mode]\n reasoning_list = self.do_generate(modality_inputs, question_list)\n option_prompt = []\n for prompt_1, response_1 in zip(question_list, reasoning_list):\n option_prompt.append(prompt_1 + response_1 + f' {conv.sep2 if conv.sep2 is not None else conv.sep}\\nANSWER:')\n final_answer_list = self.do_generate(modality_inputs, option_prompt) \n all_answer_list = []\n for reasoning, option in zip(reasoning_list, final_answer_list):\n all_answer_list.append(reasoning + '\\n The answer is ' + option)\n return all_answer_list\n\n @torch.no_grad()\n def do_generate_3d(self, modality_inputs, question_list, top_p=0.9, temperature=1.0):\n modality_inputs.update({\n 'top_p': top_p,\n 'temperature': temperature,\n 'max_tgt_len': self.max_tgt_len,\n 'modality_embeds': [],\n 'prompt': question_list,\n })\n response = self.model.generate(modality_inputs)\n\n conv = conv_templates[self.conv_mode]\n ans_list = []\n for res in response:\n ans_list.append(res.split(conv.sep2 if conv.sep2 is not None else conv.sep)[0])\n return ans_list\n\n @torch.no_grad()\n def generate(\n self, \n modality_input, \n question, \n sys_msg=None, \n dataset_name=None, \n task_name=None,\n **kwargs\n ):\n prompts = self.generate_conversation_text([question], history=[], sys_msg=sys_msg)\n if task_name.endswith('octavius3d'):\n outputs = self.do_generate_3d(modality_input, prompts)\n else:\n if dataset_name == \"ScienceQA\":\n outputs = self.do_generate_vqa([modality_input], prompts)\n else:\n outputs = self.do_generate([modality_input], prompts)\n return outputs[0]\n\n @torch.no_grad()\n def batch_generate(\n self, \n modality_inputs, \n question_list, \n sys_msg=None, \n dataset_name=None, \n **kwargs\n ):\n prompts = self.generate_conversation_text(question_list, history=[], sys_msg=sys_msg)\n if dataset_name == \"ScienceQA\":\n outputs = self.do_generate_vqa(modality_inputs, prompts)\n else:\n outputs = self.do_generate(modality_inputs, prompts)\n return outputs\n \n @torch.no_grad()\n def batch_generate_3d(\n self, \n modality_inputs, \n question_list, \n sys_msg=None, \n **kwargs\n ):\n prompts = self.generate_conversation_text(question_list, history=[], sys_msg=sys_msg)\n outputs = self.do_generate_3d(modality_inputs, prompts)\n return outputs","repo_name":"OpenGVLab/LAMM","sub_path":"src/ChEF/models/test_octavius.py","file_name":"test_octavius.py","file_ext":"py","file_size_in_byte":5143,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"3"}
+{"seq_id":"34309917611","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os,sys\nimport numpy as np\nimport itertools\n\nfrom hiraxmcmc.util.basicfunctions import *\n\n\n\n\n# =============================================================================\n# Load old MCMC results --> sample_cov and init_params\n# =============================================================================\n\nclass LoadOlderResults:\n \n \"\"\"\n The objective for this class is to include functions that can load the older/previous MCMC results (if any) in order to have some initial starting point and a thetacov matrix for the present run. \n \n Case1: If a suffix is been added to the current run, then we would simple want the previous results with the highest suffix number because that would be (ideally) the run which is the most correct of them all. \n \n \"\"\"\n \n def __init__(self, currentrunindex, paramstovary, currentparams, ordered_params_list, priors, rankmpi, mcmc_mainrun_dir_relpath, override_filenamepart = None, testfilekw = ''): # inputforhiraxoutput (not needed)\n self.p2v = paramstovary\n self.testfilekw = testfilekw\n self.rankmpi = rankmpi\n self.currentparams = currentparams\n self.priors = priors\n # self.inputforhiraxoutput = inputforhiraxoutput\n self.mcmc_mainrun_dir_relpath = mcmc_mainrun_dir_relpath\n \n self.ordered_params_list = ordered_params_list\n self.uname = os.uname()[1]\n \n if sys.argv != ['']:\n # self.changedirname = '../'\n self.currentrunindex = currentrunindex\n self.prevrunindex = int(self.currentrunindex - 1)\n elif sys.argv == ['']:\n # self.changedirname = '../mcmc_cc_xd'\n self.currentrunindex = 1 # *******\n self.prevrunindex = int(self.currentrunindex - 1)\n \n self.override_filenamepart = override_filenamepart\n \n comb_parametersvaried_prev = []\n \n for rr in range(len(ordered_params_list)+1):\n comb_obj = itertools.combinations(ordered_params_list, rr)\n comb_list = list(comb_obj)\n comb_parametersvaried_prev += comb_list\n \n #remove the empty tuple:\n comb_parametersvaried_prev.remove(())\n #remove the full length tuple:\n comb_parametersvaried_prev.remove(tuple(ordered_params_list))\n \n # remove the current params-to-vary tuple # WHY????\n comb_parametersvaried_prev.remove(tuple(paramstovary))\n \n self.comb_parametersvaried_prev = comb_parametersvaried_prev\n self.comb_parameterssavetxt_prev = ['_'+'_'.join(rr) for rr in comb_parametersvaried_prev]\n \n \n self.prevRunLastSuffix_forChains = find_last_suffix(filenamepartToSearchFor='0_allparams_cc',dirnameToSearchIn=os.path.join(mcmc_mainrun_dir_relpath,'chains/run%s'%(self.prevrunindex)))\n self.prevRunLastSuffix_forFinal = find_last_suffix(filenamepartToSearchFor='%s_paramsAcceptedFinal_cambcamb'%(self.prevrunindex),dirnameToSearchIn=mcmc_mainrun_dir_relpath, filetype='final_allparams')\n \n self.addsuffix_topassinchainfunc = None\n \n \"\"\" Make text combinations of params possibly used in previous run \"\"\"\n # comb_parameterssavetxt_prev = []\n # for i1, j1 in enumerate(ordered_params_list):\n # for i2, j2 in enumerate(ordered_params_list):\n # if i2 > i1:\n # comb_parameterssavetxt_prev.append('_' + j1 + '_' + j2)\n # # comb_parametersvaried_prev['_' + j1 + '_' + j2] = [j1,j2]\n # for i3, j3 in enumerate(ordered_params_list):\n # if i3 > i2 > i1:\n # comb_parameterssavetxt_prev.append('_' + j1 + '_' + j2 + '_' + j3)\n # # comb_parametersvaried_prev['_' + j1 + '_' + j2 + '_' + j3] = [j1,j2,j3]\n # for i4, j4 in enumerate(ordered_params_list):\n # if i4 > i3 > i2 > i1:\n # comb_parameterssavetxt_prev.append('_'+j1 + '_' + j2 + '_' + j3 + '_' + j4)\n # # comb_parametersvaried_prev['_' + j1 + '_' + j2 + '_' + j3 + '_' + j4] = [j1,j2,j3,j4]\n \n \n \n \n \n \n \n \n \n def check_parameterssavetxt_prev(self, filesavingstyle = 'allparams'):\n \"\"\"\n Sets the text prompt for finding files based on \n the parameters varied in the last run. If the same parameters were varied in the previous index\n run, then the text prompt would be the same as the current run's 'params-\n to-vary' in text format. \n \n This function also sets the variable .\n\n Parameters\n ----------\n filesavingstyle : TYPE, optional\n DESCRIPTION. The default is 'allparams'.\n \n Returns\n -------\n None. Sets the variables and \n within the class for further use\n\n \"\"\"\n \n if os.path.exists(os.path.join(self.mcmc_mainrun_dir_relpath, 'chains', 'run%s'%(self.prevrunindex), '0_allparams_cc' + '_'+'_'.join(self.p2v) + self.prevRunLastSuffix_forChains + '%s.dat'%(self.testfilekw))):\n prev_combination_text = '_'+'_'.join(self.p2v)\n prev_params_varied = self.p2v\n if self.rankmpi == 0:\n print('same params combination as the current one found'); sys.stdout.flush()\n else:\n for comb in self.comb_parameterssavetxt_prev:\n if os.path.exists(os.path.join(self.mcmc_mainrun_dir_relpath, 'chains', 'run%s'%(self.prevrunindex), '0_allparams_cc' + comb + self.prevRunLastSuffix_forChains + '%s.dat'%(self.testfilekw))):\n # if os.path.exists(os.path.join(mcmc_mainrun_dir, '%s_paramsAcceptedFinal_cambcamb'%(self.prevrunindex)+ comb + '%s.dat'%(self.testfilekw))):\n # loadallparamfile = np.loadtxt('%s_paramsAcceptedFinal_cambcamb'%(self.previndex)+ comb + '%s.dat'%(self.testfilekw))\n if len(comb.split('_')[1:]) != len(self.p2v):\n prev_params_varied = comb.split('_')[1:]\n prev_combination_text = comb\n if self.rankmpi == 0:\n print(\"Previous set of params varied --> %s --> file found and can be loaded \"%(prev_combination_text)); sys.stdout.flush()\n break\n else:\n prev_params_varied = self.ordered_params_list\n prev_combination_text = ''\n \n self.prev_params_varied = prev_params_varied\n self.prev_combination_text = prev_combination_text\n \n \n \n def load_allparams_file_and_chains(self, totalParams_inclChi2, burnin_length_for_each_chain=0):\n \"\"\"\n This function is to be used when all the final files (final output and \n chains) for the previous run exist in the working directory.\n\n Parameters\n ----------\n totalParams_inclChi2 : TYPE\n DESCRIPTION.\n\n Raises\n ------\n IOError\n DESCRIPTION.\n\n Returns\n -------\n None. Sets thetacovauto and initial points.\n\n \"\"\"\n \n \n if self.override_filenamepart != None:\n loadallparamfile = np.loadtxt(os.path.join(self.mcmc_mainrun_dir_relpath,\n self.prevrunindex + '_paramsAcceptedFinal_cambcamb' + self.override_filenamepart))\n else:\n loadallparamfile = np.loadtxt(os.path.join(self.mcmc_mainrun_dir_relpath, \n '%s_paramsAcceptedFinal_cambcamb'%(self.prevrunindex) \n + self.prev_combination_text \n + self.prevRunLastSuffix_forFinal \n +'%s.dat'%(self.testfilekw)))\n \n if self.rankmpi == 0:\n print('Final file loaded: ', os.path.join(self.mcmc_mainrun_dir_relpath,\n '%s_paramsAcceptedFinal_cambcamb'%(self.prevrunindex)\n + self.prev_combination_text \n + self.prevRunLastSuffix_forFinal \n + '%s.dat'%(self.testfilekw)\n )\n ); sys.stdout.flush()\n \n prev_params_val = loadallparamfile[:,1:].T\n self.prev_params_val = prev_params_val\n # H0prev, omkprev, omlprev, w0prev, waprev = loadallparamfile[:,1:].T\n \n # print(prev_params_val)\n # self.thetacovauto = np.cov([H0prev, omkprev, omlprev, w0prev, waprev])\n self.thetacovauto = np.cov(prev_params_val)\n \n self.addsuffix_topassinchainfunc = self.prevRunLastSuffix_forFinal\n \n try:\n ###### from corresponding chains\n \n # 1. Make a list of chain files names in the directory corresponding to the file loaded above.\n if self.override_filenamepart != None:\n listofChainsNames = find_files_containing('_allparams_cc' + self.override_filenamepart + '%s.dat'%(self.testfilekw), \n os.path.join(self.mcmc_mainrun_dir_relpath,'chains/run%s'%(self.prevrunindex)))\n else:\n listofChainsNames = find_files_containing('_allparams_cc' + self.prev_combination_text + self.prevRunLastSuffix_forChains + '%s.dat'%(self.testfilekw), \n os.path.join(self.mcmc_mainrun_dir_relpath, 'chains/run%s'%(self.prevrunindex)))\n \n if self.rankmpi == 0:\n print('Chain files to be loaded: ', \n '_allparams_cc' + self.prev_combination_text + self.prevRunLastSuffix_forChains + '%s.dat'%(self.testfilekw),\n ' <-- FROM -- ', \n 'chains/run%s'%(self.prevrunindex)\n ); sys.stdout.flush()\n \n \n \n # 2. Find the number of such files present.\n nchains = len(listofChainsNames)\n \n # 3. Store the sizes of all the chains in an array\n listOfAllChainsLengths = np.array([])\n for chainname in listofChainsNames:\n listOfAllChainsLengths = np.append(listOfAllChainsLengths, \n len(np.loadtxt(\n os.path.join(\n self.mcmc_mainrun_dir_relpath, \n 'chains/run%s'%(self.prevrunindex),chainname))[:,0]\n )\n )\n \n # 4. Find the chain with the smallest size\n shortestChainLength = int(np.min(listOfAllChainsLengths))\n \n if self.rankmpi == 0:\n print('Burn in region selected: %s for files loaded for previous run %s'%(burnin_length_for_each_chain, self.prevrunindex))\n \n \n # 5. Make all the chains of the same size as the shortest chain and 'Gather' them into a 2d/3d array of size \n \n chains = np.zeros((nchains, totalParams_inclChi2, int(shortestChainLength - burnin_length_for_each_chain)))\n for chainNumberIndex, chainname in enumerate(listofChainsNames):\n chains[chainNumberIndex] = np.loadtxt(os.path.join(self.mcmc_mainrun_dir_relpath, \n 'chains/run%s'%(self.prevrunindex), \n chainname)).T[:,int(burnin_length_for_each_chain):int(shortestChainLength)]\n \n # 5.A Find thetacovauto if burnin_length_for_each_chain != 0\n \n # self.chains = chains\n \n if self.prevrunindex == 1:# and burnin_length_for_each_chain != 0:\n # H0prev = chains[:,1,:].flatten()\n # omkprev = chains[:,2,:].flatten()\n # omlprev = chains[:,3,:].flatten()\n # w0prev = chains[:,4,:].flatten()\n # waprev = chains[:,5,:].flatten()\n prevparamsval_flatten_BIrem = []\n for i in np.arange(1, totalParams_inclChi2):\n prevparamsval_flatten_BIrem.append(chains[:,i,:].flatten())\n \n # self.thetacovauto = np.cov([H0prev, omkprev, omlprev, w0prev, waprev])\n self.thetacovauto = np.cov(np.array(prevparamsval_flatten_BIrem))\n \n # 6. Fine the last element in each chain to have the initial set of params for a chosen rankmpi\n \n for pi, pv in enumerate(self.p2v):\n self.currentparams[pv] = chains[self.rankmpi, int(pi+1), -1]\n \n \n if self.rankmpi == 0:\n print(\"Initial parameters chosen from the previous chain (FOR THE SAME PARAMETERS AS HERE)\"); sys.stdout.flush()\n \n \n except:\n \n # raise IOError(\"No final all_params file\")\n ###### randomly\n \n for index1, paramname1 in enumerate(self.p2v):\n self.currentparams[paramname1] = np.random.uniform(np.mean(prev_params_val[index1]) - np.std(prev_params_val[index1]) , \n np.mean(prev_params_val[index1]) + np.std(prev_params_val[index1]))\n \n \n # self.currentparams['H0'] = np.random.uniform( np.mean(H0prev) - np.std(H0prev) , np.mean(H0prev) + np.std(H0prev))\n # self.currentparams['Omk'] = np.random.uniform( np.mean(omkprev) - np.std(omkprev) , np.mean(omkprev) + np.std(omkprev))\n # self.currentparams['Oml'] = np.random.uniform( np.mean(omlprev) - np.std(omlprev) , np.mean(omlprev) + np.std(omlprev))\n # self.currentparams['w0'] = np.random.uniform( np.mean(w0prev) - np.std(w0prev) , np.mean(w0prev) + np.std(w0prev))\n # self.currentparams['wa'] = np.random.uniform( np.mean(waprev) - np.std(waprev) , np.mean(waprev) + np.std(waprev))\n \n if self.rankmpi == 0:\n print(\"Initial parameters chosen randomly\"); sys.stdout.flush()\n \n \n def load_allParams_chains_only(self, totalParams_inclChi2):\n \"\"\"\n This function is to be used when only chains for the previous run exist \n in the working directory.\n\n Parameters\n ----------\n totalParams_inclChi2 : TYPE\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"\n if self.override_filenamepart != None:\n listofChainsNames = find_files_containing('_allparams_cc' + self.override_filenamepart + '%s.dat'%(self.testfilekw), \n os.path.join(self.mcmc_mainrun_dir_relpath, 'chains/run%s'%(self.prevrunindex)))\n else:\n listofChainsNames = find_files_containing('_allparams_cc' + self.prev_combination_text + self.prevRunLastSuffix_forChains + '%s.dat'%(self.testfilekw), \n os.path.join(self.mcmc_mainrun_dir_relpath, 'chains/run%s'%(self.prevrunindex)))\n \n if self.rankmpi == 0:\n print('Chain files to be loaded: ', \n '_allparams_cc' + self.prev_combination_text + self.prevRunLastSuffix_forChains + '%s.dat'%(self.testfilekw),\n ' <-- FROM -- ', \n 'chains/run%s'%(self.prevrunindex)\n ); sys.stdout.flush()\n \n nchains = np.size(listofChainsNames)\n \n lengthsListOfAllChains = np.array([])\n for chainname in listofChainsNames:\n lengthsListOfAllChains = np.append(lengthsListOfAllChains, \n len(np.loadtxt(\n os.path.join(self.mcmc_mainrun_dir_relpath, \n 'chains/run%s'%(self.prevrunindex), \n chainname))[:,0]\n )\n )\n \n shortestChainLength = int(np.min(lengthsListOfAllChains))\n \n if self.prevrunindex == 1:\n burnin_length_for_each_chain = int(shortestChainLength/2)\n else:\n burnin_length_for_each_chain = 0\n \n \n if self.rankmpi == 0:\n print('Burn in region selected: %s for files loaded for previous run %s'%(burnin_length_for_each_chain, self.prevrunindex))\n \n \n chains = np.zeros((nchains, totalParams_inclChi2, int(shortestChainLength - burnin_length_for_each_chain)))\n \n for chainNumberIndex, chainname in enumerate(listofChainsNames): \n chains[chainNumberIndex] = np.loadtxt(os.path.join(self.mcmc_mainrun_dir_relpath, \n 'chains/run%s'%(self.prevrunindex),\n chainname)).T[:,int(burnin_length_for_each_chain):int(shortestChainLength)]\n \n \n prevparamsval_flatten_BIrem = []\n for i in np.arange(1, totalParams_inclChi2):\n prevparamsval_flatten_BIrem.append(chains[:,i,:].flatten())\n \n self.thetacovauto = np.cov(np.array(prevparamsval_flatten_BIrem))\n \n # H0prev = chains[:,1,:].flatten()\n # omkprev = chains[:,2,:].flatten()\n # omlprev = chains[:,3,:].flatten()\n # w0prev = chains[:,4,:].flatten()\n # waprev = chains[:,5,:].flatten()\n \n # self.thetacovauto = np.cov([H0prev, omkprev, omlprev, w0prev, waprev])\n \n for pi, pv in enumerate(self.p2v):\n self.currentparams[pv] = chains[self.rankmpi, int(pi+1), -1]\n \n self.addsuffix_topassinchainfunc = self.prevRunLastSuffix_forChains\n \n if self.rankmpi == 0:\n print(\"Final data file ISN'T available for the previous run, so loading both thetacov and initial params from the previous chains\"); sys.stdout.flush()\n \n \n \n def firstrunparams(self,thetacov0):\n \"\"\"\n This function is to be used when the current run index is 1. \n\n Returns\n -------\n None.\n\n \"\"\"\n \n if self.rankmpi == 0:\n print(\"It seems to be the first run, thus using a random initial proposal covariance matrix\"); sys.stdout.flush()\n \n # thetacov0 = np.diag([0.5,5e-6,5e-6,5e-6,5e-6])\n \n self.thetacovauto = thetacov0\n # self.currentparams['H0'] = np.random.uniform( 50, 85 )\n # self.currentparams['Omk'] = np.random.uniform( -0.1 , 0.1 )\n # self.currentparams['Oml'] = np.random.uniform( 0.5, 0.88 )\n # self.currentparams['w0'] = np.random.uniform( -2, 0 )\n # self.currentparams['wa'] = np.random.uniform( -4, 4 )\n \n for paramname in self.p2v:\n self.currentparams[paramname] = np.random.uniform(self.priors[paramname][0], self.priors[paramname][1])\n \n \n \n \n \n \n \n \n \n \n \n \n \n","repo_name":"virajnistane/HIRAXmcmc","sub_path":"hiraxmcmc/util/loadpreviousresults.py","file_name":"loadpreviousresults.py","file_ext":"py","file_size_in_byte":19992,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"42725714582","text":"from seleniumwire import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.keys import Keys\nimport random\nimport glob\nimport pandas as pd\nimport datetime\nimport sys\nimport os\nimport os.path\nimport time\nimport csv\n\ndef user_agent():\n user_agent_list = []\n with open('user_agents.csv', 'r') as f:\n for agents in f:\n user_agent_list.append(agents)\n return user_agent_list\n\ndef convert_row( row ):\n row_dict = {}\n for key, value in row.items():\n keyAscii = key.encode('ascii', 'ignore' ).decode()\n valueAscii = value.encode('ascii','ignore').decode()\n row_dict[ keyAscii ] = valueAscii\n return row_dict\n\ndef scrape():\n time_start = datetime.datetime.now().replace(microsecond=0)\n directory = os.path.dirname(os.path.realpath(__file__))\n\n user_agents = user_agent()\n\n # Setup random proxy and user-agent\n random_user_agents = random.randint(1, len(user_agents) - 1)\n print(user_agents[random_user_agents])\n options = {\n 'user-agent': user_agents[random_user_agents],\n 'suppress_connection_errors': True,\n 'verify_ssl': True\n }\n\n options = {\n 'user-agent': user_agents[random_user_agents]\n # 'suppress_connection_errors': True\n }\n\n driver_path = os.path.join(directory, glob.glob('./chromedriver*')[0])\n browser = webdriver.Chrome(executable_path=driver_path, seleniumwire_options=options)\n\n browser.set_window_size(1920, 1080)\n\n title = []\n description = []\n thumbnail = []\n videoPublishedAt = []\n videoOwnerTitle = []\n videoOwnerChannelId = []\n videoId = []\n videoUrl = []\n viewCount = []\n likeCount = []\n videoCommentCount = []\n videoDuration = []\n\n with open('playlist.csv', encoding='unicode_escape') as f:\n\n reader = csv.DictReader(f)\n\n for line in reader:\n \n converted_row = convert_row( line )\n playlisturl = converted_row['playlisturl']\n\n browser.get(playlisturl)\n\n playlist_area = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.ID, 'secondary')))\n\n items = playlist_area.find_elements(By.ID, \"wc-endpoint\")\n items_href = [item.get_attribute('href') for item in items]\n\n for href in items_href:\n \n try:\n browser.get(href)\n\n title_text = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"title\"]/h1/yt-formatted-string'))).text\n title.append(title_text)\n\n WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"description-inner\"]'))).click()\n \n desc_text = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"description-inline-expander\"]'))).text\n description.append(desc_text)\n\n vidId = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"below\"]/ytd-watch-metadata'))).get_attribute('video-id')\n videoId.append(vidId)\n\n vidPublished = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"info\"]/span[3]'))).text\n videoPublishedAt.append(vidPublished)\n print(f'{vidPublished}\\n')\n\n vidOwner = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"text\"]/a'))).text\n videoOwnerTitle.append(vidOwner)\n\n try:\n vidChannel = WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.CLASS_NAME, 'ytp-ce-link'))).get_attribute('href')\n except:\n try:\n vidChannel = WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"watch7-content\"]/meta[4]'))).get_attribute('content')\n except:\n vidChannel = WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"watch7-content\"]/meta[5]'))).get_attribute('content')\n\n videoOwnerChannelId.append(vidChannel)\n\n vidViewCount = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"info\"]/span[1]'))).text\n viewCount.append(vidViewCount)\n\n vidLikeCount = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"segmented-like-button\"]/ytd-toggle-button-renderer/yt-button-shape/button/div[2]/span'))).text\n likeCount.append(vidLikeCount)\n\n # vidCommentCount = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#count > yt-formatted-string > span:nth-child(1)'))).text\n # videoCommentCount.append(vidCommentCount)\n\n vidDuration = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'ytp-time-duration'))).text\n videoDuration.append(vidDuration)\n\n vidThumb = \"https://i.ytimg.com/vi/\" + vidId + \"/hqdefault.jpg\"\n thumbnail.append(vidThumb)\n\n vidURL = \"https://www.youtube.com/watch?v=\" + vidId\n videoUrl.append(vidURL)\n\n print(f'{title_text}\\n')\n\n except:\n pass\n \n\n time_end = datetime.datetime.now().replace(microsecond=0)\n runtime = time_end - time_start\n print(f\"Script runtime: {runtime}.\\n\")\n\n # Save scraped URLs to a CSV file\n now = datetime.datetime.now().strftime('%Y%m%d-%Hh%M')\n print('Saving to a CSV file...\\n')\n # print(f'URL: {len(url_list)}, City: {len(city_list)}, Prompt: {len(prompt_list)}, Composed: {len(composed_list)}\\n')\n data = {\"title\": title, \"description\": description, \"videoId\": videoId, \"videoPublishedAt\": videoPublishedAt, \"videoOwnerTitle\": videoOwnerTitle, \"videoOwnerChannelId\": videoOwnerChannelId, \"viewCount\": viewCount, \"likeCount\": likeCount, \"videoCommentCount\": videoCommentCount, \"videoDuration\": videoDuration, \"thumbnail\": thumbnail, \"videoUrl\": videoUrl}\n df = pd.DataFrame.from_dict(data, orient='index')\n # df.index+=1\n df = df.transpose()\n\n filename = f\"youtubePlaylistData{ now }.csv\"\n\n print(f'{filename} saved sucessfully.\\n')\n\n file_path = os.path.join(directory,'csvfiles/', filename)\n df.to_csv(file_path)\n\n browser.quit()\n\n time_end = datetime.datetime.now().replace(microsecond=0)\n runtime = time_end - time_start\n print(f\"Script runtime: {runtime}.\\n\")\n\nif __name__ == '__main__':\n scrape()","repo_name":"mrclaytorres/get-yt-playlist-data","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":6566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34519705406","text":"class Node:\n def __init__(self, data):\n # Nodes in a linked list have these three attributes:\n self.data = data\n self.next = None\n self.prev = None\n\n def link(self, otherNode): # OtherNode is the parameter to this method\n self.next = otherNode # Forward link\n otherNode.prev = self # Backwards link\n\n def __str__(self): # Defines how we return data associated to this class (the Node's)\n return self.data.__str__()\n\nclass LinkedList:\n def __init__(self):\n # A reference to the first node in the list\n self.first = None\n # A reference to the last node, which will be used to add new nodes to the end\n self.last = None\n\n def add(self, data):\n n = Node(data) # Used to add the node itself\n if (self.first == None): # If there's currently no first node it means the list is empty, make the added node the first node\n self.first = n\n else: # However, if there's currently a node in the linked list, link the existing last node to the new mode\n self.last.link(n)\n self.last = n # Update the reference point, the newest node needs to be the last node\n\n def get(self, index):\n current_node = self.first # Get the node at the start of the list\n count = 0 # Control variable\n # or while ((count < index) and (current_node is not None)\n\n while ((count < index) and (current_node != None)): # Until the count becomes greater than the index and current_node doesn't hit the end of the list, keep going through each node\n current_node = current_node.next\n count += 1\n \n return current_node # Now that the count is not lower than the users inputted number, the returned node will be the users desired node\n\nlist1 = LinkedList()\n\nlist1.add(1)\nlist1.add(2)\nlist1.add(3)\nprint(list1.get(0))\nprint(list1.get(1))\nprint(list1.get(2))\nprint(list1.get(100))","repo_name":"WT000/COM421","sub_path":"lecture2/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23329464043","text":"# Solve the descending pyramid puzzle\n# rows is a list of lists, where each list is a row of the pyramid\n# target is the target product to be reached at the bottom of the pyramid\n# start, end, total, and path are used for recursion\n# start and end are the starting and ending indices of the current row\n# total is the product of the numbers in the path\n# path is the path taken to get to the current number\ndef descendingPyramid(rows, target, start=0, end=1, total=1, path=''):\n # if given an empty list, return nothing\n if not rows:\n return\n #starting at the first given row in the pyramid, iterate through each number in the row\n row = rows[0]\n for i in range(start, end):\n #keep track of the total product of the numbers in the path\n count = total*row[i]\n #if we are not on the first row of the pyramid, we need to check if the number is on the left or right side of the previous row's number\n if end != 1:\n if (i+1)%(end) != 0: \n path = 'L' \n else: \n path = 'R'\n #if there are more rows in the pyramid, recursively call the function with the next row, giving the new start and end values, and the updated total\n if rows[1:]:\n rtn = descendingPyramid(rows[1:], target, i, i+2, count)\n #if the recursive call returns a path, add the current path and send it up the recursive chain\n if rtn:\n path += rtn\n return path\n #if we are on the last row of the pyramid, check if the total product is equal to the target\n else:\n if count == target:\n return path\n\n# Helper function to print the pyramid puzzle for visualization\ndef printPyramid(rows):\n for row in rows:\n print(row)\n\nrows = [[1], [2, 3], [4, 1, 1]]\ntarget = 2\nprint(\"Puzzle 1 ( Target\", target, \"):\")\nprintPyramid(rows)\nresult = descendingPyramid(rows, target)\nprint(\"Path:\", result, end=\"\\n\\n\")\n\nrows2 = [[2], [4, 3], [3, 2, 6], [2, 9, 5, 2], [10, 5, 2, 15, 5]]\ntarget2 = 720\nprint(\"Puzzle 2 ( Target\", target2, \"):\")\nprintPyramid(rows2)\nresult2 = descendingPyramid(rows2, target2)\nprint(\"Path 2:\", result2, end=\"\\n\\n\")\n\nrows3 = [[4], [1, 2], [3, 8, 2], [4, 5, 3, 9], [10, 1, 3, 8, 3]]\ntarget3 = 1152\nprint(\"Puzzle 3 ( Target\", target3, \"):\")\nprintPyramid(rows3)\nresult3 = descendingPyramid(rows3, target3)\nprint(\"Path 3:\", result3, end=\"\\n\\n\")\n\nrows4 = [[1]]\ntarget4 = 1\nprint(\"Puzzle 4 ( Target\", target4, \"):\")\nprintPyramid(rows4)\nresult4 = descendingPyramid(rows4, target4)\nprint(\"Path 4:\", result4, end=\"\\n\\n\")\n\nrows5 = [[2], [1, 9], [3, 4, 7], [5, 6, 4, 5], [8, 11, 3, 6, 10], [6, 2, 8, 1, 4, 2]]\ntarget5 = 6912\nprint(\"Puzzle 5 ( Target\", target5, \"):\")\nprintPyramid(rows5)\nresult5 = descendingPyramid(rows5, target5)\nprint(\"Path 5:\", result5, end=\"\\n\\n\")","repo_name":"thejackedgar/PyramidPuzzle","sub_path":"pyramid.py","file_name":"pyramid.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"73527068561","text":"line = \"aaa(bc[def](ggg(hh)))\"\ntemp = []\ndictionary = {\")\": \"(\", \"]\": \"[\", \"}\": \"{\"}\nfor letter in line:\n if letter in dictionary.values():\n temp.append(letter)\n print(temp)\n elif letter in dictionary.keys():\n if len(temp) == 0 or dictionary[letter] != temp.pop():\n print(\"Выражение не верно!\")\nelse:\n if len(temp) > 0:\n print(\"Выражение не верно!\")\n else:\n print(\"Выражение Верно!\")\n\nprint(temp)\n","repo_name":"Zyoger/RepeatPythonLesson","sub_path":"CW-2/theme 4/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8688138524","text":"from pymongo import MongoClient\nimport certifi\n\nca = certifi.where()\n\nclient = MongoClient(\n \"mongodb+srv://arvid:Arvid123@cluster0.jdojdw3.mongodb.net/MyFirstDatabase?retryWrites=true&w=majority\", tlsCAFile=ca)\n\ndb = client.todo_application\ncollection_name = db[\"book_app\"]\n","repo_name":"ArnoDeMeulemeester/RM_2eZit","sub_path":"PythonAPI/config/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38390992001","text":"# Press Shift+F10 to execute it or replace it with your code.\r\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\r\nimport random\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom bruteforce import bruteforce\r\nfrom heuristic import heuristic\r\n\r\nMIN_SPEED = 0.1\r\nMIN_LEN = 0.1\r\nMIN_JOBS = 1\r\nMIN_MACHINES = 1\r\nMIN_BLOCKS = 1\r\n\r\n\r\n# generate test\r\ndef generate(n, m, Jmax, Smax, blocks=None):\r\n n_ = random.randint(MIN_JOBS, n)\r\n m_ = random.randint(MIN_MACHINES, m)\r\n\r\n if blocks is None:\r\n blocks = random.randint(MIN_BLOCKS, n_)\r\n\r\n J = [] # set of blocks of jobs\r\n M = [] # set of machine speeds\r\n\r\n count = n_\r\n # generate job blocks(cliques)\r\n for i in range(blocks):\r\n jobs_in_block = random.randint(1, min(count - blocks + i + 1, m_)) # each block consists of at least one job\r\n # but no more than the num of machines\r\n count -= jobs_in_block\r\n B = []\r\n for j in range(jobs_in_block):\r\n job = random.uniform(MIN_LEN, Jmax)\r\n B.append(job)\r\n\r\n J.append(B)\r\n\r\n # not the best solution but works\r\n n_ -= count\r\n\r\n # generate machine speeds\r\n for i in range(m_):\r\n speed = random.uniform(MIN_SPEED, Smax)\r\n M.append(speed)\r\n\r\n return n_, m_, J, M\r\n\r\n\r\ndef test(n, m, J, M):\r\n # print()\r\n # print(n)\r\n # print(m)\r\n # print(J)\r\n # print(M)\r\n # print()\r\n\r\n b = bruteforce(n, m, J, M)\r\n h = heuristic(n, m, J, M)\r\n\r\n return b, h\r\n\r\n\r\ndef main():\r\n print(\"ENTER: maximum number of jobs(int)\")\r\n n = int(input())\r\n\r\n print(\"ENTER: maximum number of machines(int)\")\r\n m = int(input())\r\n\r\n print(\"ENTER: maximum job size(float)\")\r\n Jmax = float(input())\r\n\r\n print(\"ENTER: maximum machine speed(float)\")\r\n Smax = float(input())\r\n\r\n print(\"ENTER: number of tests(int)\")\r\n tests = int(input())\r\n\r\n B = []\r\n H = []\r\n\r\n OX = [i for i in range(tests)]\r\n\r\n for _ in range(tests):\r\n n_, m_, J, M = generate(n, m, Jmax, Smax)\r\n b, h = test(n_, m_, J, M)\r\n B.append(b)\r\n H.append(h)\r\n\r\n RATIO = [B[i] / H[i] for i in range(tests)]\r\n\r\n print(\"Bruteforce to heuristic average ratio: \", sum(RATIO) / len(RATIO))\r\n\r\n # GRAPH\r\n plt.plot(OX, B, label=\"bruteforce\")\r\n plt.plot(OX, H, label=\"heuristic\")\r\n plt.title(\"Q|cliques|C_max bruteforce to heuristic comparison\")\r\n plt.xlabel(\"test\")\r\n plt.ylabel(\"C_max\")\r\n plt.legend()\r\n\r\n plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"InkaAlicja/machines","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29031874067","text":"from django.contrib.auth import get_user_model\nfrom mock import patch\nfrom pretend import stub\n\nfrom wiki.notifications.models import PageEvent\nfrom wiki.pages.logic.actuality import mark_page_actuality\nfrom wiki.pages.models import Comment, Page\nfrom wiki.pages.models.consts import ACTUALITY_STATUS\nfrom wiki.utils.errors import ValidationError\nfrom intranet.wiki.tests.wiki_tests.common.unittest_base import BaseApiTestCase\nfrom intranet.wiki.tests.wiki_tests.common.utils import CallRecorder\n\n\nclass ActualityLogicTestCase(BaseApiTestCase):\n\n # get_page_actuality_details тестируется в api_frontend.tests.actuality вместе с вью\n\n def _test_mark_page_actuality(\n self,\n user,\n page,\n is_actual,\n comment,\n links,\n add_comment_patch,\n get_actuality_mark_patch,\n get_actuality_mark_links_patch,\n get_pages_by_supertags_patch,\n page_save_patch,\n actuality_mark_save_patch,\n actuality_mark_link_save_patch,\n page_event_save_patch,\n moment,\n ):\n @patch('wiki.pages.logic.actuality.add_comment', add_comment_patch.get_func())\n @patch('wiki.pages.logic.actuality.get_actuality_mark', get_actuality_mark_patch.get_func())\n @patch('wiki.pages.logic.actuality.get_actuality_mark_links', get_actuality_mark_links_patch.get_func())\n @patch('wiki.pages.logic.actuality.get_pages_by_supertags', get_pages_by_supertags_patch.get_func())\n @patch('wiki.pages.models.Page.save', page_save_patch.get_func())\n @patch('wiki.pages.models.ActualityMark.save', actuality_mark_save_patch.get_func())\n @patch('wiki.pages.models.ActualityMarkLink.save', actuality_mark_link_save_patch.get_func())\n @patch('wiki.notifications.models.PageEvent.save', page_event_save_patch.get_func())\n @patch('wiki.pages.logic.actuality.now', lambda: moment)\n def f():\n return mark_page_actuality(user, page, is_actual, comment, links)\n\n f()\n\n def _test_mark_page_actuality_valid(self, is_actual, current_status, with_maxdata):\n user = get_user_model()()\n page = Page(id=111)\n page.actuality_status = current_status\n moment = stub()\n\n comment = Comment()\n actual_page = Page()\n\n actuality_mark_delete_patch = CallRecorder()\n old_actuality_mark = stub(delete=actuality_mark_delete_patch.get_func())\n get_actuality_mark_patch = CallRecorder(lambda *args: old_actuality_mark)\n\n actuality_mark_link_delete_patch = CallRecorder()\n old_actuality_mark_link = stub(delete=actuality_mark_link_delete_patch.get_func())\n get_actuality_mark_links_patch = CallRecorder(lambda *args: [old_actuality_mark_link, old_actuality_mark_link])\n\n add_comment_patch = CallRecorder(lambda *args: comment)\n get_pages_by_supertags_patch = CallRecorder(lambda _supertags: [actual_page, actual_page] if _supertags else [])\n page_save_patch = CallRecorder()\n actuality_mark_save_patch = CallRecorder()\n actuality_mark_link_save_patch = CallRecorder()\n page_event_save_patch = CallRecorder()\n\n comment_text = 'йцук' if with_maxdata else None\n links = ['aaa', 'bbb', 'bbb'] if with_maxdata else []\n self._test_mark_page_actuality(\n user,\n page,\n is_actual,\n comment_text,\n links,\n add_comment_patch,\n get_actuality_mark_patch,\n get_actuality_mark_links_patch,\n get_pages_by_supertags_patch,\n page_save_patch,\n actuality_mark_save_patch,\n actuality_mark_link_save_patch,\n page_event_save_patch,\n moment,\n )\n\n if with_maxdata:\n self.assertEqual(add_comment_patch.times, 1)\n comment_args = add_comment_patch.calls[0].args\n self.assertIs(comment_args[0], user)\n self.assertIs(comment_args[1], page)\n self.assertEqual(comment_args[2], 'йцук')\n self.assertTrue(comment_args[3] is None)\n else:\n self.assertEqual(add_comment_patch.times, 0)\n\n if with_maxdata:\n self.assertEqual(get_pages_by_supertags_patch.times, 1)\n self.assertEqual(get_pages_by_supertags_patch.calls[0].args[0], set(links))\n else:\n self.assertEqual(get_pages_by_supertags_patch.times, 0)\n\n self.assertEqual(page_save_patch.times, 1)\n self.assertTrue(page_save_patch.calls[0].args[0] is page)\n self.assertEqual(page.actuality_status, ACTUALITY_STATUS.actual if is_actual else ACTUALITY_STATUS.obsolete)\n self.assertTrue(page.actuality_marked_at is moment)\n\n self.assertEqual(actuality_mark_save_patch.times, 1)\n actuality_mark = actuality_mark_save_patch.calls[0].args[0]\n self.assertIs(actuality_mark.user, user)\n self.assertIs(actuality_mark.page, page)\n self.assertIs(actuality_mark.comment, (comment if with_maxdata else None))\n\n if with_maxdata:\n self.assertEqual(actuality_mark_link_save_patch.times, 2)\n actuality_mark_link = actuality_mark_link_save_patch.calls[0].args[0]\n self.assertIs(actuality_mark_link.page, page)\n self.assertIs(actuality_mark_link.actual_page, actual_page)\n actuality_mark_link = actuality_mark_link_save_patch.calls[1].args[0]\n self.assertIs(actuality_mark_link.page, page)\n self.assertIs(actuality_mark_link.actual_page, actual_page)\n else:\n self.assertEqual(actuality_mark_link_save_patch.times, 0)\n\n if current_status == ACTUALITY_STATUS.unspecified:\n self.assertFalse(get_actuality_mark_patch.is_called)\n self.assertFalse(get_actuality_mark_links_patch.is_called)\n\n self.assertFalse(actuality_mark_delete_patch.is_called)\n self.assertFalse(actuality_mark_link_delete_patch.is_called)\n else:\n self.assertEqual(get_actuality_mark_patch.times, 1)\n self.assertEqual(get_actuality_mark_patch.calls[0].args[0], page.id)\n\n self.assertEqual(get_actuality_mark_links_patch.times, 1)\n self.assertEqual(get_actuality_mark_links_patch.calls[0].args[0], page.id)\n\n self.assertEqual(actuality_mark_delete_patch.times, 1)\n self.assertEqual(actuality_mark_link_delete_patch.times, 2)\n\n self.assertEqual(page_event_save_patch.times, 1)\n event = page_event_save_patch.calls[0].args[0]\n self.assertTrue(event.author is user)\n self.assertTrue(event.page is page)\n self.assertTrue(event.timeout is moment)\n self.assertEqual(\n event.event_type, PageEvent.EVENT_TYPES.mark_actual if is_actual else PageEvent.EVENT_TYPES.mark_obsolete\n )\n if with_maxdata:\n self.assertEqual(event.meta['comment_id'], comment.id)\n\n def test_mark_page_actuality_valid(self):\n # без удаления старого, максимальные данные\n self._test_mark_page_actuality_valid(\n is_actual=False, current_status=ACTUALITY_STATUS.unspecified, with_maxdata=True\n )\n\n # с удалением старого, минимальные данные\n self._test_mark_page_actuality_valid(\n is_actual=False, current_status=ACTUALITY_STATUS.obsolete, with_maxdata=False\n )\n self._test_mark_page_actuality_valid(\n is_actual=True, current_status=ACTUALITY_STATUS.obsolete, with_maxdata=False\n )\n\n def _test_mark_page_actuality_invalid(self, links, found_pages):\n page = stub(has_manual_actuality_mark=False)\n with patch('wiki.pages.logic.actuality.get_pages_by_supertags', lambda x: found_pages):\n with self.assertRaises(ValidationError) as cm:\n mark_page_actuality(\n user=None, page=page, is_actual=False, comment='', mixed_links=links # неважно # неважно\n )\n return cm.exception.invalid_value\n\n def test_mark_page_actuality_invalid(self):\n # хотя бы для одного супертега не найдена страница\n\n # ни одной из одной не найдено\n invalid_value = self._test_mark_page_actuality_invalid(links=['missing'], found_pages=[])\n self.assertEqual(invalid_value, 'missing')\n\n # ни одной из двух не найдено\n links = ['missing1', 'missing2']\n invalid_value = self._test_mark_page_actuality_invalid(links=links, found_pages=[])\n self.assertTrue(invalid_value in links)\n\n # одна из двух найдена, вторая – нет\n page = stub(supertag='notmissing')\n invalid_value = self._test_mark_page_actuality_invalid(links=[page.supertag, 'missing'], found_pages=[page])\n self.assertEqual(invalid_value, 'missing')\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Intranet/wiki_tests/unit_unittest/pages/logic/test_actuality.py","file_name":"test_actuality.py","file_ext":"py","file_size_in_byte":9012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7382304836","text":"import pygame\nimport game_functions as gf\n\nclass Ship():\n def __init__(self,screen,ai_setting):\n '''初始化飞机并设置初始位置'''\n self.screen = screen\n self.ai_setting = ai_setting\n #加载飞机图像并获取外界矩形\n self.image = pygame.image.load('images/ship.bmp')\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n\n #将飞机放到屏幕底部中间\n self.rect.centerx=self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n\n #在飞船属性center中存储最小数值\n self.center = float(self.rect.centerx) #float 将值转换为最小数,存入center\n #移动标志\n self.moving_right= False\n self.moving_left = False\n self.moving_spac = False\n\n def blitem(self):\n '''在指定位置绘制飞船'''\n self.screen.blit(self.image,self.rect)\n\n def update(self):\n '''根据标志调整飞船位置'''\n if self.moving_right:\n # self.rect.centerx +=1 #向右移动一位\n if self.moving_right and self.rect.right < self.screen_rect.right: #rect.right飞船外接矩形x轴最大值。保证飞船不出边框\n self.center += self.ai_setting.ship_speed_factor #更新飞船center值,不直接该rect\n if self.moving_left:\n # self.rect.centerx -=1\n if self.moving_left and self.rect.left > 0: #左边不出边框\n self.center -= self.ai_setting.ship_speed_factor\n # if self.moving_spac:\n # gf.fire_bullet(self.ai_setting,self.screen,ship,bullets)\n self.rect.centerx = self.center #根据center更改rect\n \n def center_ship(self):\n '''让飞船剧中'''\n self.center = self.screen_rect.centerx","repo_name":"shisan-fei/alien_invasion","sub_path":"ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33880566875","text":"from rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom API.serializers.SerializerPart import Participante_Serializer\nfrom API.models import Participante\nfrom random import randint\nimport requests\nimport json\n\n@api_view(['POST','GET'])\ndef Participant_Register(request):\n if request.method == 'GET':\n part = Participante.objects.all()\n serializer = Participante_Serializer(part,many=True)\n return Response(serializer.data,status= status.HTTP_200_OK)\n #en caso de ser POST\n if request.method == 'POST':\n data = request.body\n dataDict = json.loads(data)\n #construyendo el obj participante\n try:\n resp = requests.get(f\"https://api.digital.gob.do/v3/cedulas/{dataDict['cedula']}/validate\")\n valid = json.loads(resp.text)\n if not valid['valid']: \n return Response({'mensaje':'cedula no valida'},status= status.HTTP_400_BAD_REQUEST)\n \n while True:\n cod = GetCode()\n try:\n #Buscando un codigo unico \n tempPrt = Participante.objects.get(codigo=cod)\n except ObjectDoesNotExist:\n break;\n prt = Participante(**dataDict)\n prt.codigo = cod\n prt.save()\n return Response({\"mensaje\":\"creado\"},status=status.HTTP_201_CREATED)\n except KeyError:\n return Response({\"mensaje\":\"Parametros equivocados\"},status=status.HTTP_406_NOT_ACCEPTABLE)\n\n\n#obtener codigo de mierda de 8 digitos de l diablo\ndef GetCode():\n cod = \"\"\n letras = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n for i in range(8):\n letter = randint(0,len(letras)- 1)\n cod = cod + letras[letter]\n return cod\n\n","repo_name":"Anderr009/Sorteo","sub_path":"API/response/ParticipantResponse.py","file_name":"ParticipantResponse.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42154315545","text":"import cv2\nimport numpy as np\nimport random as rnd\n#import seaborn as sns \nfrom keras.callbacks import ModelCheckpoint\nfrom make_model import *\nfrom sklearn.metrics import confusion_matrix\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import array_to_img, img_to_array, load_img#from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\n\nseed = 11\nrnd.seed(seed)\nnp.random.seed(seed)\n\nmodel = make_model()\nepochs = 30\nwinH,winW = 50,50\n\n############################\n\nbatch_size = 16\n\n# this is the augmentation configuration we will use for training\ntrain_datagen = ImageDataGenerator(\n\t\trescale=1./255,\n rotation_range=20,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.1,\n zoom_range=0.1,\n horizontal_flip=True,\n fill_mode='nearest')\n\n# this is the augmentation configuration we will use for testing:\n# only rescaling\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# this is a generator that will read pictures found in\n# subfolers of 'data/train', and indefinitely generate\n# batches of augmented image data\ntrain_generator = train_datagen.flow_from_directory(\n 'data/train', # this is the target directory\n target_size=(winH, winW), # all images will be resized to 150x150\n batch_size=batch_size,\n class_mode='binary') # since we use binary_crossentropy loss, we need binary labels\n\n# this is a similar generator, for validation data\nvalidation_generator = test_datagen.flow_from_directory(\n 'data/validation',\n target_size=(winH, winW),\n batch_size=batch_size,\n class_mode='binary')\n\nfilepath=\"weights_best.h5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\ncallbacks_list = [checkpoint]\n\nclass_weight = {0: 10,\n 1: 1}\n\t\t\t\t\n#model.fit_generator(\n # train_generator,\n # steps_per_epoch=5131 // batch_size,\n #epochs=epochs,\n #validation_data=validation_generator,\n #validation_steps=1603 // batch_size,\n #callbacks=callbacks_list,\n #class_weight=class_weight)\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=5131 // batch_size,\n epochs=epochs,\n validation_data=validation_generator,\n validation_steps=1603 // batch_size,\n callbacks=callbacks_list,\n class_weight=class_weight)\n\nprint(type(history))\nloss = history.history['val_loss']\nloss\nfrom matplotlib import pyplot as plt\n#%matplotlib inline\nepoch_count = range(1, len(loss) + 1)\n\n# Visualize loss history\nplt.plot(epoch_count, loss, 'r')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\n\nacc = history.history['val_accuracy']\nacc\nfrom matplotlib import pyplot as plt\n#%matplotlib inline\nepoch_count = range(1, len(acc) + 1)\n\n# Visualize loss history\nplt.plot(epoch_count, acc, 'b')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy in blue and loss in red')\nplt.show();\n\n","repo_name":"nishchaldv/Vehicle-detection-from-aerial-images-for-traffic-monitoring","sub_path":"train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32485026991","text":"import numpy as np\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\nimport blend_modes\r\n\r\n\r\n# # Import background image\r\n# background_img_raw = Image.open('20230807_normal/20230807163300.png') # RGBA image\r\n# background_img = np.array(background_img_raw) # Inputs to blend_modes need to be numpy arrays.\r\n# # Rescale the pixel values to the range [0, 255]\r\n# scaled_img = ((background_img - np.min(background_img)) / (np.max(background_img) - np.min(background_img)) * 255).astype(np.uint8)\r\n# # Create an RGBA image with the rescaled content\r\n# rgba_image = np.zeros((background_img.shape[0], background_img.shape[1], 4), dtype=np.uint8)\r\n# # Copy the rescaled values to the first three channels (RGB)\r\n# rgba_image[:, :, 0:3] = scaled_img[:, :, np.newaxis]\r\n# # Set the alpha channel to a constant value (255 for fully opaque)\r\n# alpha_value = 255\r\n# rgba_image[:, :, 3] = alpha_value\r\n# # Now 'rgba_image' is an RGBA image with dimensions (480, 640, 4)\r\n# # plt.imshow(rgba_image)\r\n# # Inputs to blend_modes need to be floats.\r\n# background_img_float = rgba_image.astype(float)\r\n\r\n\r\ndef TwoDToRBGA (filepath):\r\n background_img_raw = Image.open(filepath) # RGBA image\r\n background_img = np.array(background_img_raw) # Inputs to blend_modes need to be numpy arrays.\r\n # Rescale the pixel values to the range [0, 255]\r\n scaled_img = ((background_img - np.min(background_img)) / (np.max(background_img) - np.min(background_img)) * 255).astype(np.uint8)\r\n # Create an RGBA image with the rescaled content\r\n rgba_image = np.zeros((background_img.shape[0], background_img.shape[1], 4), dtype=np.uint8)\r\n # Copy the rescaled values to the first three channels (RGB)\r\n rgba_image[:, :, 0:3] = scaled_img[:, :, np.newaxis]\r\n # Set the alpha channel to a constant value (255 for fully opaque)\r\n alpha_value = 255\r\n rgba_image[:, :, 3] = alpha_value\r\n # Now 'rgba_image' is an RGBA image with dimensions (480, 640, 4)\r\n # plt.imshow(rgba_image)\r\n return rgba_image\r\n \r\nrgba_image = TwoDToRBGA ('20230807_normal/20230807163300.png')\r\n# Inputs to blend_modes need to be floats.\r\nbackground_img_float = rgba_image.astype(float)\r\n\r\n\r\n# Import foreground image\r\nforeground_img_raw = Image.open('gradiente.png') # RGBA image\r\nforeground_img = np.array(foreground_img_raw) # Inputs to blend_modes need to be numpy arrays.\r\nforeground_img_float = foreground_img.astype(float) # Inputs to blend_modes need to be floats.\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Blend images\r\nopacity = 1 # The opacity of the foreground that is blended onto the background is 70 %.\r\nblended_img_float = blend_modes.multiply(background_img_float, foreground_img_float, opacity)\r\n\r\n\r\n\r\n# Convert blended image back into PIL image\r\nblended_img = np.uint8(blended_img_float) # Image needs to be converted back to uint8 type for PIL handling.\r\nblended_img_raw = Image.fromarray(blended_img) # Note that alpha channels are displayed in black by PIL by default.\r\n # This behavior is difficult to change (although possible).\r\n # If you have alpha channels in your images, then you should give\r\n # OpenCV a try.\r\n# # Display blended image\r\n# blended_img_raw.show()\r\nplt.imshow(blended_img, cmap='gray')","repo_name":"rodhervan/Tesis","sub_path":"blend_modes_with_gradient.py","file_name":"blend_modes_with_gradient.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16901294942","text":"class Solution(object):\r\n def myAtoi(self, str):\r\n \"\"\"\r\n :type str: str\r\n :rtype: int\r\n \"\"\"\r\n num_str = str.strip()\r\n number_dict = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8,\r\n '9':9}\r\n sign = 1\r\n str_len = len(num_str)\r\n if str_len == 0:\r\n return 0\r\n index = 0\r\n if num_str[0] == '-':\r\n sign = -1\r\n index = 1\r\n elif num_str[0] == '+':\r\n index = 1\r\n num_int = 0\r\n\r\n while index < str_len and (num_str[index] in number_dict):\r\n num_int = num_int*10 + number_dict[num_str[index]]\r\n index += 1\r\n return min(max(num_int*sign, -2**31), 2**31-1)","repo_name":"lightening0907/algorithm","sub_path":"atoi.py","file_name":"atoi.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12594534843","text":"\"\"\"\nHelper methods for Studio views.\n\"\"\"\nfrom __future__ import annotations\nimport logging\nimport urllib\nfrom lxml import etree\nfrom mimetypes import guess_type\n\nfrom attrs import frozen, Factory\nfrom django.utils.translation import gettext as _\nfrom opaque_keys.edx.keys import AssetKey, CourseKey, UsageKey\nfrom opaque_keys.edx.locator import DefinitionLocator, LocalId\nfrom xblock.core import XBlock\nfrom xblock.fields import ScopeIds\nfrom xblock.runtime import IdGenerator\nfrom xmodule.contentstore.content import StaticContent\nfrom xmodule.contentstore.django import contentstore\nfrom xmodule.exceptions import NotFoundError\nfrom xmodule.modulestore.django import modulestore\nfrom xmodule.xml_block import XmlMixin\n\nfrom cms.djangoapps.models.settings.course_grading import CourseGradingModel\nimport openedx.core.djangoapps.content_staging.api as content_staging_api\n\nfrom .utils import reverse_course_url, reverse_library_url, reverse_usage_url\n\nlog = logging.getLogger(__name__)\n\n# Note: Grader types are used throughout the platform but most usages are simply in-line\n# strings. In addition, new grader types can be defined on the fly anytime one is needed\n# (because they're just strings). This dict is an attempt to constrain the sprawl in Studio.\nGRADER_TYPES = {\n \"HOMEWORK\": \"Homework\",\n \"LAB\": \"Lab\",\n \"ENTRANCE_EXAM\": \"Entrance Exam\",\n \"MIDTERM_EXAM\": \"Midterm Exam\",\n \"FINAL_EXAM\": \"Final Exam\"\n}\n\n\ndef get_parent_xblock(xblock):\n \"\"\"\n Returns the xblock that is the parent of the specified xblock, or None if it has no parent.\n \"\"\"\n locator = xblock.location\n parent_location = modulestore().get_parent_location(locator)\n\n if parent_location is None:\n return None\n return modulestore().get_item(parent_location)\n\n\ndef is_unit(xblock, parent_xblock=None):\n \"\"\"\n Returns true if the specified xblock is a vertical that is treated as a unit.\n A unit is a vertical that is a direct child of a sequential (aka a subsection).\n \"\"\"\n if xblock.category == 'vertical':\n if parent_xblock is None:\n parent_xblock = get_parent_xblock(xblock)\n parent_category = parent_xblock.category if parent_xblock else None\n return parent_category == 'sequential'\n return False\n\n\ndef xblock_has_own_studio_page(xblock, parent_xblock=None):\n \"\"\"\n Returns true if the specified xblock has an associated Studio page. Most xblocks do\n not have their own page but are instead shown on the page of their parent. There\n are a few exceptions:\n 1. Courses\n 2. Verticals that are either:\n - themselves treated as units\n - a direct child of a unit\n 3. XBlocks that support children\n \"\"\"\n category = xblock.category\n\n if is_unit(xblock, parent_xblock):\n return True\n elif category == 'vertical':\n if parent_xblock is None:\n parent_xblock = get_parent_xblock(xblock)\n return is_unit(parent_xblock) if parent_xblock else False\n\n # All other xblocks with children have their own page\n return xblock.has_children\n\n\ndef xblock_studio_url(xblock, parent_xblock=None, find_parent=False):\n \"\"\"\n Returns the Studio editing URL for the specified xblock.\n\n You can pass the parent xblock as an optimization, to avoid needing to load\n it twice, as sometimes the parent has to be checked.\n\n If you pass in a leaf block that doesn't have its own Studio page, this will\n normally return None, but if you use find_parent=True, this will find the\n nearest ancestor (usually the parent unit) that does have a Studio page and\n return that URL.\n \"\"\"\n if not xblock_has_own_studio_page(xblock, parent_xblock):\n if find_parent:\n while xblock and not xblock_has_own_studio_page(xblock, parent_xblock):\n xblock = parent_xblock or get_parent_xblock(xblock)\n parent_xblock = None\n if not xblock:\n return None\n else:\n return None\n category = xblock.category\n if category == 'course':\n return reverse_course_url('course_handler', xblock.location.course_key)\n elif category in ('chapter', 'sequential'):\n return '{url}?show={usage_key}'.format(\n url=reverse_course_url('course_handler', xblock.location.course_key),\n usage_key=urllib.parse.quote(str(xblock.location))\n )\n elif category == 'library':\n library_key = xblock.location.course_key\n return reverse_library_url('library_handler', library_key)\n else:\n return reverse_usage_url('container_handler', xblock.location)\n\n\ndef xblock_type_display_name(xblock, default_display_name=None):\n \"\"\"\n Returns the display name for the specified type of xblock. Note that an instance can be passed in\n for context dependent names, e.g. a vertical beneath a sequential is a Unit.\n\n :param xblock: An xblock instance or the type of xblock (as a string).\n :param default_display_name: The default value to return if no display name can be found.\n :return:\n \"\"\"\n\n if hasattr(xblock, 'category'):\n category = xblock.category\n if category == 'vertical' and not is_unit(xblock):\n return _('Vertical')\n else:\n category = xblock\n if category == 'chapter':\n return _('Section')\n elif category == 'sequential':\n return _('Subsection')\n elif category == 'vertical':\n return _('Unit')\n elif category == 'problem':\n # The problem XBlock's display_name.default is not helpful (\"Blank Problem\") but changing it could have\n # too many ripple effects in other places, so we have a special case for capa problems here.\n # Note: With a ProblemBlock instance, we could actually check block.problem_types to give a more specific\n # description like \"Multiple Choice Problem\", but that won't work if our 'block' argument is just the block_type\n # string (\"problem\").\n return _('Problem')\n component_class = XBlock.load_class(category)\n if hasattr(component_class, 'display_name') and component_class.display_name.default:\n return _(component_class.display_name.default) # lint-amnesty, pylint: disable=translation-of-non-string\n else:\n return default_display_name\n\n\ndef xblock_primary_child_category(xblock):\n \"\"\"\n Returns the primary child category for the specified xblock, or None if there is not a primary category.\n \"\"\"\n category = xblock.category\n if category == 'course':\n return 'chapter'\n elif category == 'chapter':\n return 'sequential'\n elif category == 'sequential':\n return 'vertical'\n return None\n\n\ndef remove_entrance_exam_graders(course_key, user):\n \"\"\"\n Removes existing entrance exam graders attached to the specified course\n Typically used when adding/removing an entrance exam.\n \"\"\"\n grading_model = CourseGradingModel.fetch(course_key)\n graders = grading_model.graders\n for i, grader in enumerate(graders):\n if grader['type'] == GRADER_TYPES['ENTRANCE_EXAM']:\n CourseGradingModel.delete_grader(course_key, i, user)\n\n\nclass ImportIdGenerator(IdGenerator):\n \"\"\"\n Modulestore's IdGenerator doesn't work for importing single blocks as OLX,\n so we implement our own\n \"\"\"\n\n def __init__(self, context_key):\n super().__init__()\n self.context_key = context_key\n\n def create_aside(self, definition_id, usage_id, aside_type):\n \"\"\" Generate a new aside key \"\"\"\n raise NotImplementedError()\n\n def create_usage(self, def_id) -> UsageKey:\n \"\"\" Generate a new UsageKey for an XBlock \"\"\"\n # Note: Split modulestore will detect this temporary ID and create a new block ID when the XBlock is saved.\n return self.context_key.make_usage_key(def_id.block_type, LocalId())\n\n def create_definition(self, block_type, slug=None) -> DefinitionLocator:\n \"\"\" Generate a new definition_id for an XBlock \"\"\"\n # Note: Split modulestore will detect this temporary ID and create a new definition ID when the XBlock is saved.\n return DefinitionLocator(block_type, LocalId(block_type))\n\n\n@frozen\nclass StaticFileNotices:\n \"\"\" Information about what static files were updated (or not) when pasting content into another course \"\"\"\n new_files: list[str] = Factory(list)\n conflicting_files: list[str] = Factory(list)\n error_files: list[str] = Factory(list)\n\n\ndef import_staged_content_from_user_clipboard(parent_key: UsageKey, request) -> tuple[XBlock | None, StaticFileNotices]:\n \"\"\"\n Import a block (along with its children and any required static assets) from\n the \"staged\" OLX in the user's clipboard.\n\n Does not deal with permissions or REST stuff - do that before calling this.\n\n Returns (1) the newly created block on success or None if the clipboard is\n empty, and (2) a summary of changes made to static files in the destination\n course.\n \"\"\"\n\n from cms.djangoapps.contentstore.views.preview import _load_preview_block\n\n if not content_staging_api:\n raise RuntimeError(\"The required content_staging app is not installed\")\n user_clipboard = content_staging_api.get_user_clipboard(request.user.id)\n if not user_clipboard:\n # Clipboard is empty or expired/error/loading\n return None, StaticFileNotices()\n olx_str = content_staging_api.get_staged_content_olx(user_clipboard.content.id)\n static_files = content_staging_api.get_staged_content_static_files(user_clipboard.content.id)\n node = etree.fromstring(olx_str)\n store = modulestore()\n with store.bulk_operations(parent_key.course_key):\n parent_descriptor = store.get_item(parent_key)\n # Some blocks like drag-and-drop only work here with the full XBlock runtime loaded:\n parent_xblock = _load_preview_block(request, parent_descriptor)\n new_xblock = _import_xml_node_to_parent(\n node,\n parent_xblock,\n store,\n user_id=request.user.id,\n slug_hint=user_clipboard.source_usage_key.block_id,\n copied_from_block=str(user_clipboard.source_usage_key),\n )\n # Now handle static files that need to go into Files & Uploads:\n notices = _import_files_into_course(\n course_key=parent_key.context_key,\n staged_content_id=user_clipboard.content.id,\n static_files=static_files,\n )\n\n return new_xblock, notices\n\n\ndef _import_xml_node_to_parent(\n node,\n parent_xblock: XBlock,\n # The modulestore we're using\n store,\n # The ID of the user who is performing this operation\n user_id: int,\n # Hint to use as usage ID (block_id) for the new XBlock\n slug_hint: str | None = None,\n # UsageKey of the XBlock that this one is a copy of\n copied_from_block: str | None = None,\n) -> XBlock:\n \"\"\"\n Given an XML node representing a serialized XBlock (OLX), import it into modulestore 'store' as a child of the\n specified parent block. Recursively copy children as needed.\n \"\"\"\n runtime = parent_xblock.runtime\n parent_key = parent_xblock.scope_ids.usage_id\n block_type = node.tag\n\n # Generate the new ID:\n id_generator = ImportIdGenerator(parent_key.context_key)\n def_id = id_generator.create_definition(block_type, slug_hint)\n usage_id = id_generator.create_usage(def_id)\n keys = ScopeIds(None, block_type, def_id, usage_id)\n # parse_xml is a really messy API. We pass both 'keys' and 'id_generator' and, depending on the XBlock, either\n # one may be used to determine the new XBlock's usage key, and the other will be ignored. e.g. video ignores\n # 'keys' and uses 'id_generator', but the default XBlock parse_xml ignores 'id_generator' and uses 'keys'.\n # For children of this block, obviously only id_generator is used.\n xblock_class = runtime.load_block_type(block_type)\n # Note: if we find a case where any XBlock needs access to the block-specific static files that were saved to\n # export_fs during copying, we could make them available here via runtime.resources_fs before calling parse_xml.\n # However, currently the only known case for that is video block's transcript files, and those will\n # automatically be \"carried over\" to the new XBlock even in a different course because the video ID is the same,\n # and VAL will thus make the transcript available.\n\n child_nodes = []\n if not xblock_class.has_children:\n # No children to worry about. The XML may contain child nodes, but they're not XBlocks.\n temp_xblock = xblock_class.parse_xml(node, runtime, keys, id_generator)\n else:\n # We have to handle the children ourselves, because there are lots of complex interactions between\n # * the vanilla XBlock parse_xml() method, and its lack of API for \"create and save a new XBlock\"\n # * the XmlMixin version of parse_xml() which only works with ImportSystem, not modulestore or the v2 runtime\n # * the modulestore APIs for creating and saving a new XBlock, which work but don't support XML parsing.\n # We can safely assume that if the XBLock class supports children, every child node will be the XML\n # serialization of a child block, in order. For blocks that don't support children, their XML content/nodes\n # could be anything (e.g. HTML, capa)\n node_without_children = etree.Element(node.tag, **node.attrib)\n if issubclass(xblock_class, XmlMixin):\n # Hack: XBlocks that use \"XmlMixin\" have their own XML parsing behavior, and in particular if they encounter\n # an XML node that has no children and has only a \"url_name\" attribute, they'll try to load the XML data\n # from an XML file in runtime.resources_fs. But that file doesn't exist here. So we set at least one\n # additional attribute here to make sure that url_name is not the only attribute; otherwise in some cases,\n # XmlMixin.parse_xml will try to load an XML file that doesn't exist, giving an error. The name and value\n # of this attribute don't matter and should be ignored.\n node_without_children.attrib[\"x-is-pointer-node\"] = \"no\"\n temp_xblock = xblock_class.parse_xml(node_without_children, runtime, keys, id_generator)\n child_nodes = list(node)\n if xblock_class.has_children and temp_xblock.children:\n raise NotImplementedError(\"We don't yet support pasting XBlocks with children\")\n temp_xblock.parent = parent_key\n if copied_from_block:\n # Store a reference to where this block was copied from, in the 'copied_from_block' field (AuthoringMixin)\n temp_xblock.copied_from_block = copied_from_block\n # Save the XBlock into modulestore. We need to save the block and its parent for this to work:\n new_xblock = store.update_item(temp_xblock, user_id, allow_not_found=True)\n parent_xblock.children.append(new_xblock.location)\n store.update_item(parent_xblock, user_id)\n for child_node in child_nodes:\n _import_xml_node_to_parent(child_node, new_xblock, store, user_id=user_id)\n return new_xblock\n\n\ndef _import_files_into_course(\n course_key: CourseKey,\n staged_content_id: int,\n static_files: list[content_staging_api.StagedContentFileData],\n) -> StaticFileNotices:\n \"\"\"\n For the given staged static asset files (which are in \"Staged Content\" such as the user's clipbaord, but which\n need to end up in the course's Files & Uploads page), import them into the destination course, unless they already\n exist.\n \"\"\"\n # List of files that were newly added to the destination course\n new_files = []\n # List of files that conflicted with identically named files already in the destination course\n conflicting_files = []\n # List of files that had an error (shouldn't happen unless we have some kind of bug)\n error_files = []\n for file_data_obj in static_files:\n if not isinstance(file_data_obj.source_key, AssetKey):\n # This static asset was managed by the XBlock and instead of being added to \"Files & Uploads\", it is stored\n # using some other system. We could make it available via runtime.resources_fs during XML parsing, but it's\n # not needed here.\n continue\n # At this point, we know this is a \"Files & Uploads\" asset that we may need to copy into the course:\n try:\n result = _import_file_into_course(course_key, staged_content_id, file_data_obj)\n if result is True:\n new_files.append(file_data_obj.filename)\n elif result is None:\n pass # This file already exists; no action needed.\n else:\n conflicting_files.append(file_data_obj.filename)\n except Exception: # lint-amnesty, pylint: disable=broad-except\n error_files.append(file_data_obj.filename)\n log.exception(f\"Failed to import Files & Uploads file {file_data_obj.filename}\")\n return StaticFileNotices(\n new_files=new_files,\n conflicting_files=conflicting_files,\n error_files=error_files,\n )\n\n\ndef _import_file_into_course(\n course_key: CourseKey,\n staged_content_id: int,\n file_data_obj: content_staging_api.StagedContentFileData,\n) -> bool | None:\n \"\"\"\n Import a single staged static asset file into the course, unless it already exists.\n Returns True if it was imported, False if there's a conflict, or None if\n the file already existed (no action needed).\n \"\"\"\n filename = file_data_obj.filename\n new_key = course_key.make_asset_key(\"asset\", filename)\n try:\n current_file = contentstore().find(new_key)\n except NotFoundError:\n current_file = None\n if not current_file:\n # This static asset should be imported into the new course:\n content_type = guess_type(filename)[0]\n data = content_staging_api.get_staged_content_static_file_data(staged_content_id, filename)\n if data is None:\n raise NotFoundError(file_data_obj.source_key)\n content = StaticContent(new_key, name=filename, content_type=content_type, data=data)\n # If it's an image file, also generate the thumbnail:\n thumbnail_content, thumbnail_location = contentstore().generate_thumbnail(content)\n if thumbnail_content is not None:\n content.thumbnail_location = thumbnail_location\n contentstore().save(content)\n return True\n elif current_file.content_digest == file_data_obj.md5_hash:\n # The file already exists and matches exactly, so no action is needed\n return None\n else:\n # There is a conflict with some other file that has the same name.\n return False\n\n\ndef is_item_in_course_tree(item):\n \"\"\"\n Check that the item is in the course tree.\n\n It's possible that the item is not in the course tree\n if its parent has been deleted and is now an orphan.\n \"\"\"\n ancestor = item.get_parent()\n while ancestor is not None and ancestor.location.block_type != \"course\":\n ancestor = ancestor.get_parent()\n\n return ancestor is not None\n","repo_name":"openedx/edx-platform","sub_path":"cms/djangoapps/contentstore/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":19136,"program_lang":"python","lang":"en","doc_type":"code","stars":6774,"dataset":"github-code","pt":"3"}
+{"seq_id":"43799019113","text":"# 31256 KB / 44 ms\nimport sys\ninput = sys.stdin.readline\n\nh, w = map(int, input().split())\nheights = {i: int(v) for i, v in enumerate(input().split())}\n# 높은 순서로 정렬\nblocks = sorted(heights.items(), key=lambda x: x[1], reverse=True)\ncnt = 0\n\n# 가장 높은 블럭부터 시작\ncenter = left = right = blocks[0][0]\n\n# 오른쪽의 높은 기둥 순으로 퍼져나가면서 빗물 저장\nfor i, v in blocks:\n if i < left:\n for j in range(i+1, left):\n cnt += v - heights[j]\n left = i\n elif i > right:\n for j in range(right+1, i):\n cnt += v - heights[j]\n right = i\n\nprint(cnt)","repo_name":"KDT-02-Algorithm-Study/Algorithm-Study","sub_path":"week17_230504/14719_빗물/14719_최수현.py","file_name":"14719_최수현.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"35834991591","text":"test_cases = int(input().strip())\n\nfor a_tc in range(test_cases):\n expr = input().strip()\n stack = []\n br_count = 0\n for sym in expr:\n if sym == '(':\n br_count += 1\n print(br_count, end=' ')\n stack.append(br_count)\n elif sym == ')':\n print(stack.pop(), end=' ')\n print()\n","repo_name":"s-surineni/atice","sub_path":"bracket_num.py","file_name":"bracket_num.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26158800738","text":"# -*- coding: utf-8 -*-\nimport os\nfrom unittest import mock\nimport tempfile\n\nimport pytest\nimport requests\n\nfrom guardian_haiku.poet import main\n\ntest_resources = os.path.join(os.path.dirname(__file__), \"resources\")\n\n\ndef test_logging(logfile_directory, logfile_suffix):\n list(main(log_dir_root=logfile_directory, logfile_suffix=logfile_suffix))\n\n with open(\"{logfile_directory}/guardian_haiku/guardian_haiku.\"\n \"{logfile_suffix}.log\".format(logfile_directory=logfile_directory,\n logfile_suffix=logfile_suffix)) as f:\n first_log_line = f.readline()\n assert \"guardian_haiku running\" in first_log_line, (\"Expected \\\"guardian_haiku\\\" running in first line of \"\n \"log output, but was \\n{}\".format(first_log_line))\n\n\n@pytest.mark.xfail\ndef test_mainline(logfile_directory, logfile_suffix):\n result = list(main(log_dir_root=logfile_directory, logfile_suffix=logfile_suffix))\n assert result == [(\"Guardian\", [\"Greedy yellow birds. Sing the muddy riverbank. On a window sill.\"])]\n\n\n@pytest.fixture(autouse=True)\ndef mock_requests(monkeypatch):\n \"\"\"Mock out requests.get\"\"\"\n def mock_requests_get(url):\n guardian_article_url = \"http://www.theguardian.com/politics/2016/feb/21/\" \\\n \"cameron-boris-johnson-brexit-nigel-farage-george-galloway-uk\"\n independent_article_url = \"http://www.independent.co.uk/news/world/asia/mh370-two-years-after-the-\" \\\n \"disappearance-of-malaysia-airlines-jet-and-still-no-answer-for-grieving-\" \\\n \"a6915756.html\"\n mailonline_article_url = \"http://www.dailymail.co.uk/wires/ap/article-3486401/Senate-shoots-resolution-\" \\\n \"against-F-16-sale-Pakistan.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490\"\n telegraph_article_url = \"http://telegraph.feedsportal.com/c/32726/f/579330/s/4e2c2384/sc/13/l/0L0Stelegraph\" \\\n \"0O0Cnews0Cuknews0C12190A4830CPolice0Erelease0Eshocking0Efootage0Eto0Eshow0Eeffect\" \\\n \"0Eof0Elegal0Ehighs0Bhtml/story01.htm\"\n\n if \"theguardian\" in url and \"rss\" in url:\n text = get_test_resource(\"guardian_rss.xml\")\n elif \"independent\" in url and \"rss\" in url:\n text = get_test_resource(\"independent_rss.xml\")\n elif \"telegraph\" in url and \"rss\" in url:\n text = get_test_resource(\"telegraph_rss.xml\")\n elif \"mailonline\" in url and \"rss\" in url:\n text = get_test_resource(\"mailoneline_rss.rss\")\n elif url == guardian_article_url:\n text = get_test_resource(\"guardian_article.html\")\n elif url == independent_article_url:\n text = get_test_resource(\"independent_article.html\")\n elif url == mailonline_article_url:\n text = get_test_resource(\"mailonline_article.html\")\n elif url == telegraph_article_url:\n text = get_test_resource(\"telegraph_article.html\")\n else:\n raise ValueError(\"Mock Requests can't handle url: {}\".format(url))\n\n mock_response = mock.MagicMock()\n mock_response.text = text\n return mock_response\n\n def get_test_resource(resource_name):\n with open(os.path.join(test_resources, resource_name)) as f:\n return f.read()\n\n monkeypatch.setattr(requests, \"get\", mock_requests_get)\n\n\n@pytest.yield_fixture\ndef logfile_directory():\n with tempfile.TemporaryDirectory() as tmpdir_name:\n yield tmpdir_name\n\n\n@pytest.fixture\ndef logfile_suffix():\n return \"functional_test\"\n","repo_name":"SimonStJG/GuardianHaiku","sub_path":"guardian_haiku/tests/test_poet.py","file_name":"test_poet.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72733745360","text":"from datetime import datetime,date, timedelta\nfrom openerp import api, fields, models, _\nfrom urllib import urlencode\nfrom urlparse import urljoin\nfrom openerp.exceptions import UserError\nfrom openerp.tools import float_is_zero, float_compare,float_round, DEFAULT_SERVER_DATETIME_FORMAT\nfrom dateutil.relativedelta import relativedelta\nfrom openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT\n\n\nclass AccountInvoice(models.Model):\n _inherit = 'account.invoice'\n\n @api.multi\n def action_invoice_sent_kkon(self):\n \"\"\" Open a window to compose an email, with the edi invoice template\n message loaded by default\n \"\"\"\n self.ensure_one()\n template = self.env.ref('kkon_modifications.email_template_edi_invoice_kkon', False)\n compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)\n ctx = dict(\n default_model='account.invoice',\n default_res_id=self.id,\n default_use_template=bool(template),\n default_template_id=template.id,\n default_composition_mode='comment',\n mark_invoice_as_sent=True,\n )\n return {\n 'name': _('Compose Email'),\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'mail.compose.message',\n 'views': [(compose_form.id, 'form')],\n 'view_id': compose_form.id,\n 'target': 'new',\n 'context': ctx,\n }\n\n @api.multi\n def action_invoice_sent_fob(self):\n \"\"\" Open a window to compose an email, with the edi invoice template\n message loaded by default\n \"\"\"\n self.ensure_one()\n template = self.env.ref('kkon_modifications.email_template_edi_invoice_fob', False)\n compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)\n ctx = dict(\n default_model='account.invoice',\n default_res_id=self.id,\n default_use_template=bool(template),\n default_template_id=template.id,\n default_composition_mode='comment',\n mark_invoice_as_sent=True,\n )\n return {\n 'name': _('Compose Email'),\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'mail.compose.message',\n 'views': [(compose_form.id, 'form')],\n 'view_id': compose_form.id,\n 'target': 'new',\n 'context': ctx,\n }\n\n is_eservice_invoice = fields.Boolean(string='Is Eservice Invoice')\n payment_group_id = fields.Many2one('account.payment.group',string='Eservice Payment')\n is_upcountry = fields.Boolean(string='Up Country Transaction')\n\n\n\n\nclass AccountPaymentGroup(models.Model):\n _inherit = 'account.payment.group'\n\n @api.multi\n def unlink(self):\n for rec in self:\n if rec.is_from_eservice :\n raise UserError('Sorry, Eservice Payment Cannot be deleted')\n return super(AccountPaymentGroup,self).unlink()\n\n\n def send_receipt(self):\n company_email = self.env.user.company_id.email.strip()\n sender_person_email = self.env.user.partner_id.email.strip()\n customer_email = self.partner_id.email and self.partner_id.email.strip() or False\n\n if company_email and sender_person_email and customer_email:\n mail_template = self.env.ref('kkon_modifications.email_template_payment_receipt_ebilling')\n\n if self.company_id.company_select == 'fob':\n mail_template.email_from = 'newsales@fob.ng'\n mail_template.email_cc = 'invoice@fob.ng'\n #mail_template.subject = 'FiberOne Broadband Payment Receipt'\n mail_template.send_mail(self.id, force_send=False)\n self.is_sent_receipt_eservice = True\n return\n\n\n def create_customer_invoice(self, date, amount, ref, partner_id, prd_id,company_id):\n inv_obj = self.env['account.invoice']\n precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')\n\n journal_id = self.env['account.invoice'].default_get(['journal_id'])['journal_id']\n if not journal_id:\n raise UserError(_('Please define an accounting sale journal for this company.'))\n\n invoice_vals = {\n 'date_invoice' : date,\n 'name': ref or '',\n 'type': 'out_invoice',\n 'reference': ref or '',\n 'account_id': self.env['res.partner'].browse(partner_id).property_account_receivable_id.id,\n 'partner_id': partner_id,\n 'journal_id': journal_id,\n 'is_eservice_invoice': True,\n 'user_id': self.env.uid,\n 'team_id' : False,\n 'company_id': company_id,\n }\n invoice = inv_obj.create(invoice_vals)\n\n\n product_tmpl_id = self.env['product.template'].browse(prd_id)\n product_id = product_tmpl_id.product_variant_ids[0]\n if not product_id:\n raise UserError('There is No Product for the Product Template')\n if not float_is_zero(1, precision_digits=precision):\n account = product_id.property_account_income_id or product_id.categ_id.property_account_income_categ_id\n if not account:\n raise UserError(\n _('Please define income account for this product: \"%s\" (id:%d) - or for its category: \"%s\".') % (\n product_id.name, product_id.id,\n product_id.categ_id.name))\n\n inv_line = {\n 'name': ref or '',\n # 'sequence': self.sequence,\n 'origin': ref or '',\n 'account_id': account.id,\n 'price_unit': amount,\n 'quantity': 1,\n 'uom_id': product_id.uom_id.id,\n 'product_id': product_id.id or False,\n 'invoice_id': invoice.id,\n 'invoice_line_tax_ids': [(6, 0, [2])],\n 'company_id': company_id,\n }\n self.env['account.invoice.line'].create(inv_line)\n\n\n if not invoice.invoice_line_ids:\n raise UserError(_('There is no invoiceable line.'))\n # If invoice is negative, do a refund invoice instead\n if invoice.amount_untaxed < 0:\n invoice.type = 'out_refund'\n for line in invoice.invoice_line_ids:\n line.quantity = -line.quantity\n # Use additional field helper function (for account extensions)\n for line in invoice.invoice_line_ids:\n line._set_additional_fields(invoice)\n # Necessary to force computation of taxes. In account_invoice, they are triggered\n # by onchanges, which are not triggered when doing a create.\n invoice.compute_taxes()\n invoice.signal_workflow('invoice_open')\n return invoice\n\n\n @api.multi\n def action_create_payment(self,payment_date,journal_id,amount,ref,partner_id,company_id):\n account_payment_group_obj = self.env['account.payment.group']\n account_payment_obj = self.env['account.payment']\n\n act_pg_dict = {\n 'partner_id': partner_id,\n 'payment_date': payment_date,\n 'communication': ref,\n 'partner_type': 'customer',\n 'is_from_eservice' : True,\n 'company_id': company_id,\n }\n res = account_payment_group_obj.create(act_pg_dict)\n res._refresh_payments_and_move_lines()\n acc_pay = {\n 'payment_type': 'inbound',\n 'payment_type_copy': 'inbound',\n 'journal_id': journal_id,\n 'payment_date': payment_date,\n 'amount': amount,\n 'communication': ref,\n 'ref_no': ref,\n 'payment_method_id': 1, # Manual payment\n 'partner_id': partner_id,\n 'partner_type': 'customer',\n 'payment_group_id': res.id,\n 'company_id': company_id,\n }\n pg = account_payment_obj.create(acc_pay)\n res.post()\n return res\n\n @api.model\n def create(self, vals):\n res = False\n if 'is_from_rpc' in vals:\n date = vals.get('date',False)\n journal_id = vals.get('journal_id', False)\n amount = vals.get('amount', 0)\n num_renewal = vals.get('num_renewal', 0)\n if num_renewal == 0:\n raise UserError('Number of renewal is not present. Please set it and repush')\n ref = vals.get('ref', '')\n partner_id = vals.get('partner_id', False)\n prd_id = vals.get('product_id',False)\n company_id = vals.get('company_id',False)\n if not company_id:\n raise UserError('Company ID is required')\n\n i = 0\n while i < num_renewal:\n the_date = datetime.strptime(date, '%Y-%m-%d')\n new_date = the_date + relativedelta(days=+i)\n tdate = new_date.strftime('%Y-%m-%d')\n inv = self.create_customer_invoice(tdate, (amount / num_renewal), ref, partner_id,prd_id,company_id)\n i += 30\n res = self.action_create_payment(date, journal_id, amount, ref, partner_id,company_id)\n #res.send_receipt() #pause for now to debug the mutiple emails sent\n #res.eservice_invoice_id = inv\n #inv.payment_group_id = res\n else:\n res = super(AccountPaymentGroup, self).create(vals)\n return res\n\n is_from_eservice = fields.Boolean(string='Is From Eservice')\n eservice_invoice_id = fields.Many2one('account.invoice',string='Eservice Invoice')\n is_sent_receipt_eservice = fields.Boolean(string='Is Sent Receipt from Eservice')\n is_upcountry = fields.Boolean(string='Up Country Transaction')\n","repo_name":"kingsleyuk2003/ODEX","sub_path":"addons/kkon_modifications/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":9891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42379242584","text":"import os, subprocess, json, shutil, time\n\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import Dict, List, Optional\n\nimport click\nimport psutil\n\n\nclass JobInfo:\n process_id: int\n started_at: Optional[datetime]\n completed_at: Optional[datetime]\n working_dir: Path\n command: str\n command_params: Dict[str, object]\n\n def __init__(self) -> None:\n self.process_id = -1\n self.started_at = None\n self.completed_at = None\n self.working_dir = None\n self.command = \"\"\n self.command_params = dict()\n\n @classmethod\n def load_json(cls, job_info_path: Path):\n def parse_datetime(date_str: Optional[str]):\n if date_str is not None and len(date_str) > 0:\n return datetime.fromisoformat(date_str)\n return None\n\n with open(job_info_path, \"r\") as f:\n content = json.load(f)\n obj = cls()\n obj.process_id = content[\"process_id\"]\n obj.started_at = parse_datetime(content[\"started_at\"])\n obj.completed_at = parse_datetime(content[\"completed_at\"])\n obj.working_dir = Path(content[\"working_dir\"])\n obj.command = content[\"command\"]\n obj.command_params = content[\"command_params\"]\n return obj\n\n def write_json(self, job_info_path: Path) -> None:\n def datetime_to_iso_str(dt: Optional[datetime]):\n if dt is None:\n return None\n return dt.isoformat()\n\n job_dict = {\n \"process_id\": self.process_id,\n \"started_at\": datetime_to_iso_str(self.started_at),\n \"completed_at\": datetime_to_iso_str(self.completed_at),\n \"working_dir\": str(self.working_dir),\n \"command\": self.command,\n \"command_params\": self.command_params,\n }\n with open(job_info_path, \"w\") as f:\n json.dump(job_dict, f, indent=4, sort_keys=False)\n \n def get_process_command(self) -> List[str]:\n cmd = self.command.split(\" \")\n for param_name, param_value in self.command_params.items():\n cmd.append(f\"--{param_name}\")\n cmd.append(f\"{param_value}\")\n return cmd\n\nclass Worker:\n def __init__(self, queue_dir: str, max_active: int, n_threads: int) -> None:\n self._queue_dir = queue_dir\n self._max_active = max_active\n self._dir_ready = os.path.join(queue_dir, \"ready\")\n self._dir_completed = os.path.join(queue_dir, \"completed\")\n self._dir_in_progress = os.path.join(queue_dir, \"in-progress\")\n self._dir_discarded = os.path.join(queue_dir, \"discarded\")\n self._n_threads = n_threads\n\n self._child_processes: List[subprocess.Popen] = []\n\n for directory in [self._dir_ready, self._dir_in_progress, self._dir_completed, self._dir_discarded]:\n if not os.path.exists(directory):\n print(f\"Creating directory {directory}...\")\n os.makedirs(directory)\n\n def run(self) -> None:\n prev_has_launched = True\n has_launched = True\n while True:\n self._clean_in_progress()\n n_active = len(self._find_in_progress_files())\n if n_active < self._max_active:\n has_launched = self._lunch_new_run()\n if not has_launched and prev_has_launched:\n print(\"No more jobs in queue.\")\n time.sleep(2)\n prev_has_launched = has_launched\n\n def _clean_in_progress(self):\n job_info_paths = self._find_in_progress_files()\n for job_info_path in job_info_paths:\n job = JobInfo.load_json(job_info_path)\n if not self._is_running(job.process_id):\n print(f\"Process {job.process_id} which started {job.started_at} is not running anymore.\")\n\n # Check if the result file is created.\n done_job_info_path = job.working_dir / \"done.out\"\n if done_job_info_path.exists():\n completed_at = datetime.fromtimestamp(done_job_info_path.stat().st_ctime)\n print(f\" - Completed at {completed_at}. Moving to completed.\")\n job.completed_at = completed_at\n job.process_id = -2\n job.write_json(job_info_path)\n shutil.move(job_info_path, f\"{self._dir_completed}/{job_info_path.name}\")\n shutil.copy(\n src=f\"{self._dir_completed}/{job_info_path.name}\", \n dst=f\"{job.working_dir}/job-info.json\"\n )\n else:\n print(\" - Process stopped but done.out file does not exist! Discarding run.\")\n self._move_to_discarded(job_info_path)\n\n def _is_running(self, process_id: int) -> bool:\n for proc in self._child_processes:\n if proc.pid == process_id:\n # poll() checks the process has terminated. Returns None value \n # if process has not terminated yet.\n return proc.poll() is None\n\n # psutil cannot detect child processes.\n for proc in psutil.process_iter():\n if process_id == proc.pid:\n return True\n return False\n\n def _find_json_files(self, dir_name: str) -> List[Path]:\n dir_name_str = str(dir_name)\n return [\n Path(f\"{dir_name_str}/{file_name}\")\n for file_name in os.listdir(dir_name_str)\n if file_name.endswith(\".json\")\n ]\n\n def _find_in_progress_files(self) -> List[Path]:\n return self._find_json_files(self._dir_in_progress)\n\n def _should_discard(self, job_info_path: Path) -> bool:\n paths_to_check = [\n os.path.join(self._dir_in_progress, job_info_path.name),\n os.path.join(self._dir_completed , job_info_path.name),\n ]\n for p in paths_to_check:\n if os.path.exists(p):\n return True\n return False\n\n def _move_to_discarded(self, job_info_path: Path) -> None:\n discarded_file_name = job_info_path.name + \"-\" + datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n discarded_path = f\"{self._dir_discarded}/{discarded_file_name}\"\n shutil.move(job_info_path, discarded_path)\n print(f\"Discarding job {job_info_path.name}. Moving to {discarded_path}...\")\n\n def _get_next_job_info_path(self) -> Optional[Path]:\n file_paths = self._find_json_files(self._dir_ready)\n if len(file_paths) > 0:\n sorted_file_paths = list(sorted(file_paths, key=lambda file_path: file_path.name))\n return sorted_file_paths[0]\n return None\n\n def _move_to_progress(self, job_info_path: Path) -> Path:\n in_progress_path = f\"{self._dir_in_progress}/{job_info_path.name}\"\n shutil.move(job_info_path, in_progress_path)\n return in_progress_path\n\n def _lunch_new_run(self) -> False:\n # Find the next run file containing the experiment to run\n while True:\n job_info_path = self._get_next_job_info_path()\n if job_info_path is None:\n return False\n if self._should_discard(job_info_path):\n print(f\"Found job that is already running or completed.\")\n self._move_to_discarded(job_info_path)\n else:\n print(f\"Will run job with config {job_info_path}\")\n break\n\n # Prepare for launch\n job_info_path = self._move_to_progress(job_info_path)\n job_info: JobInfo = JobInfo.load_json(job_info_path)\n cmd = job_info.get_process_command()\n cmd += [\"--n-threads\", f\"{self._n_threads}\"]\n\n # Actual launch\n print(f\"Launching experiment with command:\\n '{cmd}'\")\n p = subprocess.Popen(\n args=cmd,\n stdout=open(job_info.working_dir / \"stdout.txt\", \"a\"),\n stderr=open(job_info.working_dir / \"stderr.txt\", \"a\"),\n start_new_session=True\n )\n self._child_processes.append(p)\n\n # Create PID file.\n with open(job_info.working_dir / \"pid.txt\", \"w\") as f:\n f.write(str(p.pid))\n\n # Persist run details to disk.\n job_info.started_at = datetime.now()\n job_info.process_id = p.pid\n job_info.write_json(job_info_path)\n\n return True\n\n@click.command(help=\"Runs jobs.\")\n@click.option(\n \"-q\",\n \"--queue-dir\",\n type=click.STRING,\n required=True,\n)\n@click.option(\n \"-m\",\n \"--max-active\",\n type=click.INT,\n default=1,\n help=\"Maximum number of simultaneous jobs.\"\n)\n@click.option(\n \"--n-threads\",\n type=click.INT,\n default=1,\n help=\"Maximum number of threads per job.\"\n)\ndef main(queue_dir: str, max_active: int, n_threads: int):\n Worker(\n queue_dir=queue_dir,\n max_active=max_active,\n n_threads=n_threads,\n ).run()\n\n\nif __name__ == \"__main__\":\n main() # pylint: disable=no-value-for-parameter\n","repo_name":"sheikhomar/mixture-learning","sub_path":"app/run_worker.py","file_name":"run_worker.py","file_ext":"py","file_size_in_byte":9005,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"18419770353","text":"def solution(bandage, health, attacks):\n answer = 0\n last_time = attacks[-1][0]\n # print(\"마지막 시간: \", last_time)\n # print(\"최대 체력: \", health)\n max_health = health\n idx = 0\n inarow = 0\n for i in range(0, last_time+1):\n if health <= 0: # 체력이 0보다 작다면 끝.\n return -1\n \n if i == attacks[idx][0]: # 몬스터의 공격시간\n health -= attacks[idx][1] # 체력 깎임.\n \n inarow = 0 # 연속성공 초기화\n # print(f\"공격성공 체력: {health}, 시간: {i}, 공격:{attacks[idx][1]}\")\n idx += 1 # 다음 공격 시간으로 넘기기.\n else:\n inarow += 1\n health += bandage[1]\n # print(f\"시간:{i}, 현재 체력:{health}, 연속성공:{inarow}\")\n \n if health >= max_health: # 체력이 최대체력과 같다면 연속성공 초기화\n health = max_health\n inarow = 0\n \n if inarow == bandage[0]: # t초 연속으로 붕대를 감는데 성공.\n health += bandage[2] # y 만큼 체력 추가 회복\n inarow = 0\n \n \n return health if health > 0 else -1","repo_name":"jeong1suk/Algorithm","sub_path":"프로그래머스/unrated/250137. [PCCP 기출문제] 1번 / 붕대 감기/[PCCP 기출문제] 1번 / 붕대 감기.py","file_name":"[PCCP 기출문제] 1번 / 붕대 감기.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41554937651","text":"import os\nimport torch\nimport torchvision\nfrom tqdm import tqdm\nfrom PIL import Image\nfrom torch.optim import Adamax\nfrom dataloader import data_load\nimport torch.optim.lr_scheduler as ls\nfrom loss_network import Vgg16, Normal\nfrom torch.utils.data import DataLoader\nfrom style_network import ImageTransformer\nfrom utils import gram_matrix, warped, get_mask\nstyle_weight = [1, 1e0, 1e0, 1e0]\n\ndef train(args):\n #Training the model\n #code is using GPU if cuda is available else CPU\n device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n\n #Building Model\n style_model = ImageTransformer().to(device)\n loss_model = Vgg16().to(device)\n for param in loss_model.parameters():\n param.requires_grad = False\n\n loss_mse = torch.nn.MSELoss()\n loss_msesum = torch.nn.MSELoss(reduction='none')\n\n optimizer = Adamax(style_model.parameters(), lr=args.lr)\n schedular = ls.MultiStepLR(optimizer, milestones=[8, 20], gamma=0.2)\n\n #Loading Data\n train_dataset = data_load(os.path.join(args.dataset, 'training'))\n data_train = DataLoader(dataset=train_dataset, batch_size=args.batch_size, shuffle=True)\n \n mean =torch.tensor([0.485, 0.456, 0.406]).to(device)\n std = torch.tensor([0.229, 0.224, 0.225]).to(device)\n\n #Loading Style\n style_img = Image.open(args.style_name)\n style_img = style_img.resize((args.width, args.height), Image.BILINEAR)\n style_img = torchvision.transforms.ToTensor()(style_img)\n style_batch = []\n style_batch.append(style_img)\n normalization = Normal(mean, std)\n count = 0\n while count < args.epochs:\n data = tqdm(data_train)\n count += 1\n\n for idx, x in enumerate(data):\n optimizer.zero_grad()\n\n img1, img2, mask, flow = x\n img1, img2 = img2, img1\n img1 = img1.to(device)\n img2 = img2.to(device)\n mask = mask.to(device)\n flow = flow.to(device)\n style_img = style_batch[0].to(device)\n\n #style network\n output_img1 = style_model(img1)\n output_img2 = style_model(img2)\n\n #temporal loss\n warp_img1, mask_boundary_img1 = warped(img1, flow, device)\n mask_occ = get_mask(warp_img1, img2, mask)\n warp_output_img1, _ = warped(output_img1, flow, device)\n temporal_loss = loss_msesum(output_img2, warp_output_img1)\n temporal_loss = torch.sum(temporal_loss * mask_occ * mask_boundary_img1) / (\n img2.size(0) * img2.size(1) * img2.size(2) * img2.size(3))\n temporal_loss *= args.lambda_lt\n\n #long temporal loss\n if (idx) % 5 == 0:\n frame0 = output_img2\n\n with torch.no_grad():\n frame0_mask = get_mask(warp_img1, frame0, mask)\n long_temporal_loss = torch.abs(loss_msesum(frame0, warp_output_img1))\n long_temporal_loss = torch.sum(long_temporal_loss * frame0_mask * mask_boundary_img1) / (\n frame0.size(0) * frame0.size(1) * frame0.size(2) * frame0.size(3))\n long_temporal_loss *= args.lambda_st\n\n #normalization to vgg16\n img1 = normalization(img1)\n img2 = normalization(img2)\n style_img = normalization(style_img.repeat(output_img1.size(0), 1, 1, 1))\n output_img1 = normalization(output_img1)\n output_img2 = normalization(output_img2)\n\n #loss network\n content1 = loss_model(img1)\n content2 = loss_model(img2)\n style_out = loss_model(style_img)\n out1 = loss_model(output_img1)\n out2 = loss_model(output_img2)\n\n #content loss\n loss_content = loss_mse(content1[2], out1[2]) + loss_mse(content2[2], out2[2])\n loss_content *= args.alpha\n\n #style loss\n loss_style = 0.0\n for i in range(len(style_out)):\n style_gram = gram_matrix(style_out[i])\n out1_gram = gram_matrix(out1[i])\n out2_gram = gram_matrix(out2[i])\n loss_style += style_weight[i] * (loss_mse(style_gram, out1_gram) + loss_mse(style_gram, out2_gram))\n loss_style *= args.beta\n\n #total variation loss\n loss_tv_img1 = torch.sum(torch.abs(output_img1[:, :, :, :-1] - output_img1[:, :, :, 1:])) \\\n + torch.sum(torch.abs(output_img1[:, :, :-1, :] - output_img1[:, :, 1:, :]))\n loss_tv_img2 = torch.sum(torch.abs(output_img2[:, :, :, :-1] - output_img2[:, :, :, 1:]))\\\n + torch.sum(torch.abs(output_img2[:, :, :-1, :] - output_img2[:, :, 1:, :]))\n loss_tv = (loss_tv_img1 + loss_tv_img2) / output_img1.size(0)\n loss_tv *= args.gamma\n\n data.set_description('Epoch:%d temp_loss:%.7f long_temp_loss:%.7f content_loss:%.2f '\n 'style_loss:%.7f tv_loss:%.1f'% \n (count, temporal_loss.item(),\n long_temporal_loss.item(),\n loss_content.item(),\n loss_style.item(),\n loss_tv.item()))\n\n loss = loss_content + loss_style + loss_tv + temporal_loss + long_temporal_loss\n\n #backpropogation\n loss.backward()\n optimizer.step()\n\n if (args.schedular):\n schedular.step()\n if (not os.path.exists(args.save_model)):\n os.mkdir(args.save_model)\n model_path = os.path.join(args.save_model, 'train.pt')\n torch.save(style_model.state_dict(), model_path)\n\n\n\n\n\n\n\n\n\n","repo_name":"devarti19/Neural-Style-Transfer-in-Videos","sub_path":"code/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27955981664","text":"from swimport.all import *\n\nsrc = FileSource('src.h')\nswim = Swim('example')\nswim(pools.include(src))\n\npoint_type = TypeSwimporting('Point2D', 'Tuple[float, float]',\n to_py=\n \"\"\"\n return Py_BuildValue(\"dd\",input.x,input.y);\n \"\"\",\n to_cpp=\n \"\"\"\n double x,y;\n PyArg_ParseTuple(input,\"dd\",&x,&y);\n return{x,y};\n \"\"\", out_iterable_types=())\nassert swim(point_type)\nassert swim(pools.list('Point2D'))\nassert swim(Variable.Behaviour()(src)) == 3\nassert swim(Function.Behaviour()(src))\n\nswim.write('example.i')\nprint('ok!')\n","repo_name":"talos-gis/swimport","sub_path":"src/swimport/tests/33_type_variable/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"7491567178","text":"from Laptop import Laptop\n\n\nclass Apple(Laptop):\n\n def __init__(self, model: str, screen_diagonal: int or float, screen_rate: int, cpu: str, gpu: int, ssd: int,\n ram: int, logo: bool):\n super().__init__(model, screen_diagonal, screen_rate, cpu, gpu, ssd, ram)\n self._logo = logo\n self.__price = 0\n\n def __model_price(self):\n if self._model not in [\"MacBook Air\", \"MacBook Pro\", \"iMac\"]:\n raise TypeError(\"Error! Check your data and try again!\")\n elif self._model == \"MacBook Air\":\n self.__price += 100\n elif self._model == \"MacBook Pro\":\n self.__price += 150\n elif self._model == \"iMac\":\n self.__price += 200\n\n def __screen_diagonal_price(self):\n if self._screen_diagonal not in [13.3, 13.6, 15.3, 16.2]:\n raise TypeError(\"Error! Check your data and try again!\")\n elif self._screen_diagonal == 13.3:\n self.__price += 50\n elif self._screen_diagonal == 13.6:\n self.__price += 75\n elif self._screen_diagonal == 15.3:\n self.__price += 100\n elif self._screen_diagonal == 16.2:\n self.__price += 125\n\n def __screen_rate_price(self):\n if self._screen_rate not in [60, 120, 144]:\n raise TypeError(\"Error! Check your data and try again!\")\n elif self._screen_rate == 60:\n self.__price += 35\n elif self._screen_rate == 120:\n self.__price += 55\n elif self._screen_rate == 144:\n self.__price += 75\n\n def __cpu_price(self):\n if self._cpu not in [\"M1\", \"M2\", \"M2Pro\", \"M2Max\"]:\n raise TypeError(\"Error! Check your data and try again!\")\n elif self._cpu == \"M1\":\n self.__price += 50\n elif self._cpu == \"M2\":\n self.__price += 100\n elif self._cpu == \"M2Pro\":\n self.__price += 150\n elif self._cpu == \"M2Max\":\n self.__price += 200\n\n def __gpu_price(self):\n if self._gpu not in [8, 10, 38]:\n raise TypeError(\"Error! Check your data and try again!\")\n elif self._gpu == 8:\n self.__price += 75\n elif self._gpu == 10:\n self.__price += 150\n elif self._gpu == 38:\n self.__price += 300\n\n def __ssd_price(self):\n if self._ssd not in [256, 512, 1024]:\n raise TypeError(\"Error! Check your data and try again!\")\n elif self._ssd == 256:\n self.__price += 25\n elif self._ssd == 512:\n self.__price += 50\n elif self._ssd == 1024:\n self.__price += 75\n\n def __ram_price(self):\n if self._ram not in [4, 8, 16, 32]:\n raise TypeError(\"Error! Check your data and try again!\")\n elif self._ram == 4:\n self.__price += 10\n elif self._ram == 8:\n self.__price += 20\n elif self._ram == 16:\n self.__price += 30\n elif self._ram == 32:\n self.__price += 40\n\n def __add_logo(self):\n if self._logo not in [True, False]:\n raise TypeError(\"Error! Check your data and try again!\")\n elif self._logo:\n self.__price += 20\n\n @property\n def price(self):\n self.__model_price()\n self.__screen_diagonal_price()\n self.__screen_rate_price()\n self.__cpu_price()\n self.__gpu_price()\n self.__ssd_price()\n self.__ram_price()\n self.__add_logo()\n return f\"Your laptop will be cost: {self.__price} $\\n\"\n\n @staticmethod\n def help():\n print(\"Create your own notebook by entering the parameters from the following:\\n\"\n \"Model: MacBook Air, MacBook Pro, iMac\\n\"\n \"Screen diagonal: 13.3, 13.6, 15.3, 16.2\\n\"\n \"Screen rate: 60, 120, 144\\n\"\n \"CPU: M1, M2, M2Pro, M2Max\\n\"\n \"GPU: 8, 10, 38\\n\"\n \"SSD: 256, 512, 1024\\n\"\n \"RAM: 4, 8, 16, 32\\n\"\n \"Add Logo: True or False\\n\")\n\n\nif __name__ == '__main__':\n first = Apple(\"MacBook Air\", 13.3, 60, \"M1\", 8, 256, 4, False)\n first.help()\n print(first.price)\n second = Apple(\"iMac\", 16.2, 144, \"M2Max\", 38, 1024, 32, True)\n second.help()\n print(second.price)\n","repo_name":"Benedict3141592/Hillel_Homework_Groshev","sub_path":"HW_Lesson_10/Apple.py","file_name":"Apple.py","file_ext":"py","file_size_in_byte":4274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29256287317","text":"import pytest\nfrom aiohttp.web_response import Response\n\nfrom maps_adv.geosmb.clients.loyalty import (\n CouponReviewResolution as CouponReviewResolutionEnum,\n EmptyCouponsList,\n IncorrectCouponData,\n)\nfrom maps_adv.geosmb.clients.loyalty.proto.loyalty_pb2 import (\n CouponReviewResolution as CouponReviewResolutionPb,\n SubmitCouponsReviewsListRequest,\n)\n\npytestmark = [pytest.mark.asyncio]\n\n\ncoupons_review_results_input = [\n dict(\n biz_id=\"biz_id_1\",\n item_id=\"item_id_1\",\n revision_id=111,\n resolution=CouponReviewResolutionEnum.APPROVED,\n reason_codes=[],\n ),\n dict(\n biz_id=\"biz_id_2\",\n item_id=\"item_id_2\",\n revision_id=222,\n resolution=CouponReviewResolutionEnum.REJECTED,\n corrected=dict(\n title=\"new_title\",\n products_description=\"new_products_description\",\n conditions=\"new_conditions\",\n ),\n reason_codes=[555, 333],\n ),\n]\n\n\nasync def test_sends_correct_request(loyalty_client, mock_submit_coupons_reviews_list):\n request_url = None\n request_headers = None\n request_body = None\n\n async def loyalty_handler(request):\n nonlocal request_url, request_headers, request_body\n request_url = str(request.url)\n request_headers = request.headers\n request_body = await request.read()\n return Response(status=204)\n\n mock_submit_coupons_reviews_list(loyalty_handler)\n\n await loyalty_client.submit_coupons_reviews_list(\n coupons_review_results=coupons_review_results_input\n )\n\n assert request_url == \"http://loyalty.server/v0/submit_coupons_reviews_list\"\n assert request_headers[\"X-Ya-Service-Ticket\"] == \"KEK_FROM_AIOTVM_PYTEST_PLUGIN\"\n assert request_headers[\"Content-Type\"] == \"application/x-protobuf\"\n proto_body = SubmitCouponsReviewsListRequest.FromString(request_body)\n assert proto_body == SubmitCouponsReviewsListRequest(\n results_list=[\n SubmitCouponsReviewsListRequest.CouponReviewResult(\n biz_id=\"biz_id_1\",\n item_id=\"item_id_1\",\n revision_id=111,\n resolution=CouponReviewResolutionPb.APPROVED,\n reason_codes=[],\n ),\n SubmitCouponsReviewsListRequest.CouponReviewResult(\n biz_id=\"biz_id_2\",\n item_id=\"item_id_2\",\n revision_id=222,\n resolution=CouponReviewResolutionPb.REJECTED,\n corrected=SubmitCouponsReviewsListRequest.CouponReviewCorrected(\n title=\"new_title\",\n products_description=\"new_products_description\",\n conditions=\"new_conditions\",\n ),\n reason_codes=[555, 333],\n ),\n ]\n )\n\n\nasync def test_returns_nothing(loyalty_client, mock_submit_coupons_reviews_list):\n mock_submit_coupons_reviews_list(Response(status=204))\n\n got = await loyalty_client.submit_coupons_reviews_list(\n coupons_review_results=coupons_review_results_input\n )\n\n assert got is None\n\n\nasync def test_raises_if_empty_coupons_list(loyalty_client):\n with pytest.raises(EmptyCouponsList):\n await loyalty_client.submit_coupons_reviews_list(coupons_review_results=[])\n\n\nasync def test_raises_if_incorrect_coupons_list(loyalty_client):\n with pytest.raises(IncorrectCouponData):\n await loyalty_client.submit_coupons_reviews_list(\n coupons_review_results=[\n dict(\n biz_id=\"biz_id_1\",\n revision_id=111,\n resolution=CouponReviewResolutionEnum.APPROVED,\n reason_codes=[],\n )\n ]\n )\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"maps/tests/test_submit_coupons_reviews_list.py","file_name":"test_submit_coupons_reviews_list.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"73231578642","text":"from mesa import Model\n\nfrom src.Customer import Customer\nfrom src.cashdesk.CashDesk import CashDesk\nfrom src.zones.dinamic.CashDeskStandardZone import CashDeskStandardZone\n\n\nclass CashDeskStandardSharedQueueZone(CashDeskStandardZone):\n\n def __init__(self, model: Model, cash_desks_number: int):\n super(CashDeskStandardSharedQueueZone, self).__init__(model, cash_desks_number)\n\n def build(self):\n super().build()\n cell = self.model.add_occupied_cell(\"h\")\n x = (self.model.cash_desk_self_scan_zone.cash_desks_number * 2\n if self.model.cash_desk_self_scan_zone is not None else 0) + 3\n y = 3\n self.model.grid.place_agent(cell, (x, y))\n for cash_desk in self.model.get_cash_desks():\n cash_desk.working = True\n\n def move_to_queue(self, customer: Customer, cash_desk: CashDesk):\n if customer.target_queue in self.queues:\n x = (self.model.cash_desk_self_scan_zone.cash_desks_number * 2\n if self.model.cash_desk_self_scan_zone is not None else 0) + 3\n y = 4 + customer.target_queue.size()\n self.model.grid.move_agent(customer, (x, y))\n","repo_name":"AuPath/Supermarket-Checkout-Simulation","sub_path":"src/zones/dinamic/CashDeskStandardSharedQueueZone.py","file_name":"CashDeskStandardSharedQueueZone.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"9920513436","text":"import sys\nfrom backend.backend_proxy.tool.abstract_tool_class import AbstractToolClass\nfrom backend.backend_proxy.tool.formats.formatAbstractClass import Format\nimport requests\nfrom backend.backend_proxy.api.exception import REST_Exception\nfrom backend.backend_proxy.tool.formats.supportedFormats import SupportedFormats\nfrom backend.backend_proxy.db.mongoDB import MongoDB\n\n\ndef debugPrint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\nclass Tool(AbstractToolClass):\n def __init__(self, tool_dict: dict) -> None:\n self.name = tool_dict[\"name\"]\n self.enum = tool_dict[\"enum\"]\n self.added_by = tool_dict[\"added_by\"]\n self.registered_at = tool_dict[\"registered_at\"]\n self.ip = tool_dict[\"ip\"]\n self.port = tool_dict[\"port\"]\n self.endpoint = tool_dict[\"endpoint\"]\n self.contact_mail = tool_dict[\"contact_mail\"]\n self.input_fields = tool_dict[\"input_fields\"]\n self.output_fields = tool_dict[\"output_fields\"]\n self.general_info = tool_dict[\"general_info\"]\n self.git_address = tool_dict[\"git_address\"]\n self.tulap_address = tool_dict[\"tulap_address\"]\n if '_id' in tool_dict: self._id = tool_dict['_id']\n\n def run(self, parameters: dict) -> dict:\n inputs = {}\n for field, val in self.input_fields.items():\n if field not in parameters:\n raise REST_Exception(\n message=f\"You did not provide a required field: {field}\", status=400)\n given_input = parameters[field]\n\n format_of_field: str = val['type']\n format_object: Format = SupportedFormats.get_format_from_string(\n format_of_field)\n\n formatted_input = format_object.fromString(text=given_input)\n inputs[field] = formatted_input.strip()\n\n response = requests.post(\n url=f\"http://{self.ip}:{self.port}/{self.endpoint}\", json=inputs)\n if not response.ok:\n raise REST_Exception(\n message=response.text,\n status=response.status_code\n )\n response = response.json()\n outputs = {}\n for field, val in self.output_fields.items():\n if field not in response:\n raise REST_Exception(\n message=f\"An error occured in the tool.\", status=500)\n\n format_of_field: str = val['type']\n format_object: Format = SupportedFormats.get_format_from_string(\n format_of_field)\n\n formatted_output = format_object.getTypesAsJson(\n text=response[field],input=list(inputs.values())[0])\n outputs[field] = formatted_output\n\n return outputs\n","repo_name":"BOUN-TABILab-TULAP/tabi-rop","sub_path":"backend/src/backend/backend_proxy/tool/tool_class.py","file_name":"tool_class.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"11437886021","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the jumpingOnClouds function below.\ndef jumpingOnClouds(c):\n\n pos = 0\n jumps = 0\n while pos < len(c)-1:\n if pos+2 < len(c) and c[pos+2] == 0:\n pos +=2\n else:\n pos +=1\n jumps+=1\n\n return jumps\n\n\nif __name__ == '__main__':\n\n n = 6\n\n c = list(map(int, '0 0 0 1 0 0'.rstrip().split()))\n\n result = jumpingOnClouds(c)\n\n print(result)","repo_name":"kob22/hackerrank","sub_path":"IPK/warm_up/jumping_on_clouds.py","file_name":"jumping_on_clouds.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34132073806","text":"import pandas as pd\nimport numpy as np\npd.options.mode.chained_assignment = None #default='warn'\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\ndef process1():\n #1 exclude all docTypes = 'AC','SA'\n df['AlexCode'] = df['Document Type'].isin(['AC','SA'])\n pd.set_option('display.max_columns', None)\n pd.set_option('display.max_rows', None)\n print('process1 completed')\n\ndef process2():\n #2 string match run first\n dfStringMatch = df.duplicated(subset=['Abs','WBSText','Company Code','G/L Account','Profit Center'],keep=False)\n df['StringMatch1'] = dfStringMatch\n dftempStringMatch = df[df['StringMatch1'] == True]\n print('process2 completed')\n\ndef process3():\n #string match run second\n dfStringMatch = df.duplicated(subset=['Abs','Company Code','G/L Account','Profit Center'],keep=False)\n df['StringMatch2'] = dfStringMatch\n #print('dfStringMatch',dfStringMatch)\n dftempStringMatch = df[df['StringMatch2'] == True]\n print('process3 completed')\n\ndef process4(StringMatch):\n #4 this is our attempt to help our friends at MES to know how to properly cross reference things\n #tagging of StringMatch, marking which one goes with what\n #this should also work for duplicates to stamp off match, only difference in logic is dups would be same sign\n dfTempString = df[df[StringMatch] == True]\n dfTempString = dfTempString.sort_values(by=['Abs','POtext','Reference','Year/month'],kind='mergesort')\n \n dfTempString['MatchID'] = -1\n\n cou = 0\n firstComp = -1\n secondComp = -1\n dfTempString.drop(['Year/month'], axis=1)\n for row in dfTempString.index:\n if cou % 2 == 0:\n firstComp = row\n else:\n secondComp = row\n if dfTempString['Amount in local currency'].iloc[cou-1] + dfTempString['Amount in local currency'].iloc[cou] == 0:\n dfTempString['MatchID'].iloc[cou] = firstComp\n dfTempString['MatchID'].iloc[cou-1] = secondComp\n dfTempString['MatchIDBool'].iloc[cou-1] = True\n cou = cou + 1\n\n df['MatchID']=dfTempString['MatchID']\n dfTempString.to_excel(\"outputStringMatch.xlsx\", sheet_name='Sheet_name_1')\n print('process4 completed')\n\n\ndef process5():\n #5 find duplicates \n dfDuplicates = df.duplicated(subset=['Year/month','Entry Date','Document Type','Company Code','G/L Account',\n 'Profit Center','Amount in local currency'],keep=False)\n\n df['Duplicate'] = dfDuplicates\n dfTempDups = df[df['Duplicate'] == True]\n dfTempDups.to_excel(\"outputDuplicates.xlsx\", sheet_name='Sheet_name_1')\n print('process5 completed')\n\ndef process6():\n #Sonopress with PO\n dfSonopress = df\n dfSonopress['Vendor Description'].replace('', np.nan, inplace=True)\n dfSonopress.dropna(subset=['Vendor Description'], inplace=True)\n dfTempSonopressWPO = dfSonopress[(dfSonopress['Vendor Description']=='SONOPRESS GMBH') & (dfSonopress['POtext'].str[:2] == 'PO')]\n dfTempSonopressWPO['SonopressWPO'] = True\n df['SonopressWPO'] = dfTempSonopressWPO['SonopressWPO']\n dfTempSonopressWPO.to_excel(\"outputSonopressWPO.xlsx\", sheet_name='Sheet_name_1')\n print('process6 completed')\n\ndef process7():\n #Sonopress no PO\n dfSonopress = df\n dfSonopress['Vendor Description'].replace('', np.nan, inplace=True)\n dfSonopress.dropna(subset=['Vendor Description'], inplace=True)\n dfTempSonopress = dfSonopress[(dfSonopress['Vendor Description']=='SONOPRESS GMBH') & (dfSonopress['POtext'].str[:2] != 'PO')]\n dfTempSonopress['Sonopress'] = True\n df['Sonopress'] = dfTempSonopress['Sonopress']\n dfTempSonopress.to_excel(\"outputSonopress.xlsx\", sheet_name='Sheet_name_1')\n print('process7 completed')\n\ndef processNum():\n conditions = [\n (df['AlexCode'] == True),\n (df['StringMatch1'] == True),\n (df['StringMatch2'] == True),\n (df['SonopressWPO'] == True),\n (df['Sonopress'] == True),\n (df['Duplicate'] == True),\n (df['MatchIDBool'] > 0)\n ]\n choices = [1,2,3,6,7,5,4]\n df['ProcessNum'] = np.select(conditions, choices, default = -1)\n \ndef processFile():\n #adding columns and setting defaults\n df['POtext'] = 'abc'\n df['WBSText']= 'def'\n df['Abs'] = 0\n df['AddInverse'] = -1\n df['MatchID'] = -1\n df['ProcessNum'] = -1\n df['Duplicate'] = False\n df['SonopressWPO'] = False\n df['Sonopress'] = False\n df['AlexCode'] = False\n df['StringMatch1'] = False\n df['StringMatch2'] = False\n df['MatchIDBool'] = False\n\n #dropping columns with no data\n df.drop(columns=['Cost Center','Segment','Trading Partner','Assignment'], axis=1)\n\n #declare variables\n colonPO = ':PO'\n POhash = 'PO#'\n po = 'PO'\n dollar = '$'\n openParen = '('\n\n totalRows1 = len(df.index)\n for row in df.index:\n poText = df['Text'].iloc[row]\n textLen = len(poText)\n if dollar in poText:\n if openParen in poText:\n result = poText.index(dollar)\n poText = poText[0:result-2]\n else:\n result = poText.index(dollar)\n poText = poText[0:result-1]\n elif colonPO in poText: \n invText = poText[0:14]\n poText = poText[-10:]\n elif POhash in poText: #take left 13 or 14 for WBSText\n invText = poText[0:14]\n poText = 'PO' + poText[-8:]\n elif po in poText:\n invText = poText[0:14]\n poText = 'PO' + poText[-8:]\n \n df['POtext'].iloc[row] = poText\n df['WBSText'].iloc[row] = invText\n df['Abs'] = abs(df['Amount in local currency'])\n df['AddInverse'] = df['Amount in local currency'] * -1\n \n #overwrite WBSText with data from WBS column if not null\n dfWBS = df\n dfWBS['WBS element'].replace('', np.nan, inplace=True)\n #same as SQL Coalesce\n df['WBSText'] = np.where(df['WBS element'].isnull(),df['WBSText'],df['WBS element'])\n print('processing file completed, getting ready for comparing')\n\ndef processPamFile():\n dfPam = pd.read_excel(r'C:\\Users\\DawnBetzel\\OneDrive - Warner Music Group\\Projects\\MES\\Pam200920_091521.xlsx')\n print('getting ready to print dfPam')\n print(dfPam)\n\n \ndf = pd.read_excel(r'C:\\Users\\DawnBetzel\\OneDrive - Warner Music Group\\Projects\\MES\\Macro_ThreeYearDataSet_V3.xlsx')\n#will have to do this for three files and append to the bottom of df\n#MES can only export one year at a time?? Why is this need to know??\n\nprocessFile()\nprocess1()\nprocess2()\nprocess3()\nprocess4('StringMatch1')\nprocess4('StringMatch2')\nprocess5()\nprocess6()\nprocess7()\nprocessNum()\n#processPamFile()\nprint('printing duplicate')\nprint(df['Duplicate'] == True)\nprint('printing matchid > 0')\nprint(df['MatchID'] > 0)\nprint('printing AlexCode')\nprint(df['AlexCode'] == True)\n\n\n\n#fuzzy matching 25% inverse\ndfSonopressTest = df['Vendor Description'].str.contains('SONOPRESS GMBH')\ndf['Sonopress'] = dfSonopressTest\ndfDistinct = df[['Document Type','Company Code','G/L Account','Profit Center','Abs']]\ndfDistinct['Abs'].drop_duplicates().sort_values()\n\ndf.to_excel(\"outputAll.xlsx\", sheet_name='Sheet_name_1')\nprint('output Excel files completed')\n","repo_name":"dbetzel/Python","sub_path":"MESProcessing.py","file_name":"MESProcessing.py","file_ext":"py","file_size_in_byte":7246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23446874545","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport paddle\nfrom paddle import nn\nfrom paddle import ParamAttr\nfrom paddle.nn.functional import upsample\nfrom paddle.nn.initializer import Uniform\n\nfrom ..base.theseus_layer import TheseusLayer, Identity\nfrom ....utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url\n\nMODEL_URLS = {\n \"HRNet_W18_C\":\n \"https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/HRNet_W18_C_pretrained.pdparams\",\n \"HRNet_W30_C\":\n \"https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/HRNet_W30_C_pretrained.pdparams\",\n \"HRNet_W32_C\":\n \"https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/HRNet_W32_C_pretrained.pdparams\",\n \"HRNet_W40_C\":\n \"https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/HRNet_W40_C_pretrained.pdparams\",\n \"HRNet_W44_C\":\n \"https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/HRNet_W44_C_pretrained.pdparams\",\n \"HRNet_W48_C\":\n \"https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/HRNet_W48_C_pretrained.pdparams\",\n \"HRNet_W64_C\":\n \"https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/HRNet_W64_C_pretrained.pdparams\"\n}\n\nMODEL_STAGES_PATTERN = {\"HRNet\": [\"st4\"]}\n\n__all__ = list(MODEL_URLS.keys())\n\n\ndef _create_act(act):\n if act == \"hardswish\":\n return nn.Hardswish()\n elif act == \"relu\":\n return nn.ReLU()\n elif act is None:\n return Identity()\n else:\n raise RuntimeError(\n \"The activation function is not supported: {}\".format(act))\n\n\nclass ConvBNLayer(TheseusLayer):\n def __init__(self,\n num_channels,\n num_filters,\n filter_size,\n stride=1,\n groups=1,\n act=\"relu\"):\n super().__init__()\n\n self.conv = nn.Conv2D(\n in_channels=num_channels,\n out_channels=num_filters,\n kernel_size=filter_size,\n stride=stride,\n padding=(filter_size - 1) // 2,\n groups=groups,\n bias_attr=False)\n self.bn = nn.BatchNorm(num_filters, act=None)\n self.act = _create_act(act)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.act(x)\n return x\n\n\nclass BottleneckBlock(TheseusLayer):\n def __init__(self,\n num_channels,\n num_filters,\n has_se,\n stride=1,\n downsample=False):\n super().__init__()\n\n self.has_se = has_se\n self.downsample = downsample\n\n self.conv1 = ConvBNLayer(\n num_channels=num_channels,\n num_filters=num_filters,\n filter_size=1,\n act=\"relu\")\n self.conv2 = ConvBNLayer(\n num_channels=num_filters,\n num_filters=num_filters,\n filter_size=3,\n stride=stride,\n act=\"relu\")\n self.conv3 = ConvBNLayer(\n num_channels=num_filters,\n num_filters=num_filters * 4,\n filter_size=1,\n act=None)\n\n if self.downsample:\n self.conv_down = ConvBNLayer(\n num_channels=num_channels,\n num_filters=num_filters * 4,\n filter_size=1,\n act=None)\n\n if self.has_se:\n self.se = SELayer(\n num_channels=num_filters * 4,\n num_filters=num_filters * 4,\n reduction_ratio=16)\n self.relu = nn.ReLU()\n\n def forward(self, x, res_dict=None):\n residual = x\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n if self.downsample:\n residual = self.conv_down(residual)\n if self.has_se:\n x = self.se(x)\n x = paddle.add(x=residual, y=x)\n x = self.relu(x)\n return x\n\n\nclass BasicBlock(nn.Layer):\n def __init__(self, num_channels, num_filters, has_se=False):\n super().__init__()\n\n self.has_se = has_se\n\n self.conv1 = ConvBNLayer(\n num_channels=num_channels,\n num_filters=num_filters,\n filter_size=3,\n stride=1,\n act=\"relu\")\n self.conv2 = ConvBNLayer(\n num_channels=num_filters,\n num_filters=num_filters,\n filter_size=3,\n stride=1,\n act=None)\n\n if self.has_se:\n self.se = SELayer(\n num_channels=num_filters,\n num_filters=num_filters,\n reduction_ratio=16)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n residual = x\n x = self.conv1(x)\n x = self.conv2(x)\n\n if self.has_se:\n x = self.se(x)\n\n x = paddle.add(x=residual, y=x)\n x = self.relu(x)\n return x\n\n\nclass SELayer(TheseusLayer):\n def __init__(self, num_channels, num_filters, reduction_ratio):\n super().__init__()\n\n self.avg_pool = nn.AdaptiveAvgPool2D(1)\n\n self._num_channels = num_channels\n\n med_ch = int(num_channels / reduction_ratio)\n stdv = 1.0 / math.sqrt(num_channels * 1.0)\n self.fc_squeeze = nn.Linear(\n num_channels,\n med_ch,\n weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))\n self.relu = nn.ReLU()\n stdv = 1.0 / math.sqrt(med_ch * 1.0)\n self.fc_excitation = nn.Linear(\n med_ch,\n num_filters,\n weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x, res_dict=None):\n residual = x\n x = self.avg_pool(x)\n x = paddle.squeeze(x, axis=[2, 3])\n x = self.fc_squeeze(x)\n x = self.relu(x)\n x = self.fc_excitation(x)\n x = self.sigmoid(x)\n x = paddle.unsqueeze(x, axis=[2, 3])\n x = residual * x\n return x\n\n\nclass Stage(TheseusLayer):\n def __init__(self, num_modules, num_filters, has_se=False):\n super().__init__()\n\n self._num_modules = num_modules\n\n self.stage_func_list = nn.LayerList()\n for i in range(num_modules):\n self.stage_func_list.append(\n HighResolutionModule(\n num_filters=num_filters, has_se=has_se))\n\n def forward(self, x, res_dict=None):\n x = x\n for idx in range(self._num_modules):\n x = self.stage_func_list[idx](x)\n return x\n\n\nclass HighResolutionModule(TheseusLayer):\n def __init__(self, num_filters, has_se=False):\n super().__init__()\n\n self.basic_block_list = nn.LayerList()\n\n for i in range(len(num_filters)):\n self.basic_block_list.append(\n nn.Sequential(* [\n BasicBlock(\n num_channels=num_filters[i],\n num_filters=num_filters[i],\n has_se=has_se) for j in range(4)\n ]))\n\n self.fuse_func = FuseLayers(\n in_channels=num_filters, out_channels=num_filters)\n\n def forward(self, x, res_dict=None):\n out = []\n for idx, xi in enumerate(x):\n basic_block_list = self.basic_block_list[idx]\n for basic_block_func in basic_block_list:\n xi = basic_block_func(xi)\n out.append(xi)\n out = self.fuse_func(out)\n return out\n\n\nclass FuseLayers(TheseusLayer):\n def __init__(self, in_channels, out_channels):\n super().__init__()\n\n self._actual_ch = len(in_channels)\n self._in_channels = in_channels\n\n self.residual_func_list = nn.LayerList()\n self.relu = nn.ReLU()\n for i in range(len(in_channels)):\n for j in range(len(in_channels)):\n if j > i:\n self.residual_func_list.append(\n ConvBNLayer(\n num_channels=in_channels[j],\n num_filters=out_channels[i],\n filter_size=1,\n stride=1,\n act=None))\n elif j < i:\n pre_num_filters = in_channels[j]\n for k in range(i - j):\n if k == i - j - 1:\n self.residual_func_list.append(\n ConvBNLayer(\n num_channels=pre_num_filters,\n num_filters=out_channels[i],\n filter_size=3,\n stride=2,\n act=None))\n pre_num_filters = out_channels[i]\n else:\n self.residual_func_list.append(\n ConvBNLayer(\n num_channels=pre_num_filters,\n num_filters=out_channels[j],\n filter_size=3,\n stride=2,\n act=\"relu\"))\n pre_num_filters = out_channels[j]\n\n def forward(self, x, res_dict=None):\n out = []\n residual_func_idx = 0\n for i in range(len(self._in_channels)):\n residual = x[i]\n for j in range(len(self._in_channels)):\n if j > i:\n xj = self.residual_func_list[residual_func_idx](x[j])\n residual_func_idx += 1\n\n xj = upsample(xj, scale_factor=2**(j - i), mode=\"nearest\")\n residual = paddle.add(x=residual, y=xj)\n elif j < i:\n xj = x[j]\n for k in range(i - j):\n xj = self.residual_func_list[residual_func_idx](xj)\n residual_func_idx += 1\n\n residual = paddle.add(x=residual, y=xj)\n\n residual = self.relu(residual)\n out.append(residual)\n\n return out\n\n\nclass LastClsOut(TheseusLayer):\n def __init__(self,\n num_channel_list,\n has_se,\n num_filters_list=[32, 64, 128, 256]):\n super().__init__()\n\n self.func_list = nn.LayerList()\n for idx in range(len(num_channel_list)):\n self.func_list.append(\n BottleneckBlock(\n num_channels=num_channel_list[idx],\n num_filters=num_filters_list[idx],\n has_se=has_se,\n downsample=True))\n\n def forward(self, x, res_dict=None):\n out = []\n for idx, xi in enumerate(x):\n xi = self.func_list[idx](xi)\n out.append(xi)\n return out\n\n\nclass HRNet(TheseusLayer):\n \"\"\"\n HRNet\n Args:\n width: int=18. Base channel number of HRNet.\n has_se: bool=False. If 'True', add se module to HRNet.\n class_num: int=1000. Output num of last fc layer.\n Returns:\n model: nn.Layer. Specific HRNet model depends on args.\n \"\"\"\n\n def __init__(self,\n stages_pattern,\n width=18,\n has_se=False,\n class_num=1000,\n return_patterns=None,\n return_stages=None):\n super().__init__()\n\n self.width = width\n self.has_se = has_se\n self._class_num = class_num\n\n channels_2 = [self.width, self.width * 2]\n channels_3 = [self.width, self.width * 2, self.width * 4]\n channels_4 = [\n self.width, self.width * 2, self.width * 4, self.width * 8\n ]\n\n self.conv_layer1_1 = ConvBNLayer(\n num_channels=3,\n num_filters=64,\n filter_size=3,\n stride=2,\n act=\"relu\")\n\n self.conv_layer1_2 = ConvBNLayer(\n num_channels=64,\n num_filters=64,\n filter_size=3,\n stride=2,\n act=\"relu\")\n\n self.layer1 = nn.Sequential(* [\n BottleneckBlock(\n num_channels=64 if i == 0 else 256,\n num_filters=64,\n has_se=has_se,\n stride=1,\n downsample=True if i == 0 else False) for i in range(4)\n ])\n\n self.conv_tr1_1 = ConvBNLayer(\n num_channels=256, num_filters=width, filter_size=3)\n self.conv_tr1_2 = ConvBNLayer(\n num_channels=256, num_filters=width * 2, filter_size=3, stride=2)\n\n self.st2 = Stage(\n num_modules=1, num_filters=channels_2, has_se=self.has_se)\n\n self.conv_tr2 = ConvBNLayer(\n num_channels=width * 2,\n num_filters=width * 4,\n filter_size=3,\n stride=2)\n self.st3 = Stage(\n num_modules=4, num_filters=channels_3, has_se=self.has_se)\n\n self.conv_tr3 = ConvBNLayer(\n num_channels=width * 4,\n num_filters=width * 8,\n filter_size=3,\n stride=2)\n\n self.st4 = Stage(\n num_modules=3, num_filters=channels_4, has_se=self.has_se)\n\n # classification\n num_filters_list = [32, 64, 128, 256]\n self.last_cls = LastClsOut(\n num_channel_list=channels_4,\n has_se=self.has_se,\n num_filters_list=num_filters_list)\n\n last_num_filters = [256, 512, 1024]\n self.cls_head_conv_list = nn.LayerList()\n for idx in range(3):\n self.cls_head_conv_list.append(\n ConvBNLayer(\n num_channels=num_filters_list[idx] * 4,\n num_filters=last_num_filters[idx],\n filter_size=3,\n stride=2))\n\n self.conv_last = ConvBNLayer(\n num_channels=1024, num_filters=2048, filter_size=1, stride=1)\n\n self.avg_pool = nn.AdaptiveAvgPool2D(1)\n\n stdv = 1.0 / math.sqrt(2048 * 1.0)\n self.flatten = nn.Flatten(start_axis=1, stop_axis=-1)\n\n self.fc = nn.Linear(\n 2048,\n class_num,\n weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))\n\n super().init_res(\n stages_pattern,\n return_patterns=return_patterns,\n return_stages=return_stages)\n\n def forward(self, x):\n x = self.conv_layer1_1(x)\n x = self.conv_layer1_2(x)\n\n x = self.layer1(x)\n\n tr1_1 = self.conv_tr1_1(x)\n tr1_2 = self.conv_tr1_2(x)\n x = self.st2([tr1_1, tr1_2])\n\n tr2 = self.conv_tr2(x[-1])\n x.append(tr2)\n x = self.st3(x)\n\n tr3 = self.conv_tr3(x[-1])\n x.append(tr3)\n x = self.st4(x)\n\n x = self.last_cls(x)\n\n y = x[0]\n for idx in range(3):\n y = paddle.add(x[idx + 1], self.cls_head_conv_list[idx](y))\n\n y = self.conv_last(y)\n y = self.avg_pool(y)\n y = self.flatten(y)\n y = self.fc(y)\n return y\n\n\ndef _load_pretrained(pretrained, model, model_url, use_ssld):\n if pretrained is False:\n pass\n elif pretrained is True:\n load_dygraph_pretrain_from_url(model, model_url, use_ssld=use_ssld)\n elif isinstance(pretrained, str):\n load_dygraph_pretrain(model, pretrained)\n else:\n raise RuntimeError(\n \"pretrained type is not available. Please use `string` or `boolean` type.\"\n )\n\n\ndef HRNet_W18_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n HRNet_W18_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `HRNet_W18_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=18, stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"], **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"HRNet_W18_C\"], use_ssld)\n return model\n\n\ndef HRNet_W30_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n HRNet_W30_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `HRNet_W30_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=30, stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"], **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"HRNet_W30_C\"], use_ssld)\n return model\n\n\ndef HRNet_W32_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n HRNet_W32_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `HRNet_W32_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=32, stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"], **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"HRNet_W32_C\"], use_ssld)\n return model\n\n\ndef HRNet_W40_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n HRNet_W40_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `HRNet_W40_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=40, stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"], **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"HRNet_W40_C\"], use_ssld)\n return model\n\n\ndef HRNet_W44_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n HRNet_W44_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `HRNet_W44_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=44, stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"], **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"HRNet_W44_C\"], use_ssld)\n return model\n\n\ndef HRNet_W48_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n HRNet_W48_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `HRNet_W48_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=48, stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"], **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"HRNet_W48_C\"], use_ssld)\n return model\n\n\ndef HRNet_W60_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n HRNet_W60_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `HRNet_W60_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=60, stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"], **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"HRNet_W60_C\"], use_ssld)\n return model\n\n\ndef HRNet_W64_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n HRNet_W64_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `HRNet_W64_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=64, stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"], **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"HRNet_W64_C\"], use_ssld)\n return model\n\n\ndef SE_HRNet_W18_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n SE_HRNet_W18_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `SE_HRNet_W18_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=18,\n stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"],\n has_se=True,\n **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"SE_HRNet_W18_C\"], use_ssld)\n return model\n\n\ndef SE_HRNet_W30_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n SE_HRNet_W30_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `SE_HRNet_W30_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=30,\n stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"],\n has_se=True,\n **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"SE_HRNet_W30_C\"], use_ssld)\n return model\n\n\ndef SE_HRNet_W32_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n SE_HRNet_W32_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `SE_HRNet_W32_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=32,\n stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"],\n has_se=True,\n **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"SE_HRNet_W32_C\"], use_ssld)\n return model\n\n\ndef SE_HRNet_W40_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n SE_HRNet_W40_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `SE_HRNet_W40_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=40,\n stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"],\n has_se=True,\n **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"SE_HRNet_W40_C\"], use_ssld)\n return model\n\n\ndef SE_HRNet_W44_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n SE_HRNet_W44_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `SE_HRNet_W44_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=44,\n stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"],\n has_se=True,\n **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"SE_HRNet_W44_C\"], use_ssld)\n return model\n\n\ndef SE_HRNet_W48_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n SE_HRNet_W48_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `SE_HRNet_W48_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=48,\n stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"],\n has_se=True,\n **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"SE_HRNet_W48_C\"], use_ssld)\n return model\n\n\ndef SE_HRNet_W60_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n SE_HRNet_W60_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `SE_HRNet_W60_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=60,\n stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"],\n has_se=True,\n **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"SE_HRNet_W60_C\"], use_ssld)\n return model\n\n\ndef SE_HRNet_W64_C(pretrained=False, use_ssld=False, **kwargs):\n \"\"\"\n SE_HRNet_W64_C\n Args:\n pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.\n If str, means the path of the pretrained model.\n use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True.\n Returns:\n model: nn.Layer. Specific `SE_HRNet_W64_C` model depends on args.\n \"\"\"\n model = HRNet(\n width=64,\n stages_pattern=MODEL_STAGES_PATTERN[\"HRNet\"],\n has_se=True,\n **kwargs)\n _load_pretrained(pretrained, model, MODEL_URLS[\"SE_HRNet_W64_C\"], use_ssld)\n return model\n","repo_name":"PaddlePaddle/PaddleClas","sub_path":"ppcls/arch/backbone/legendary_models/hrnet.py","file_name":"hrnet.py","file_ext":"py","file_size_in_byte":26157,"program_lang":"python","lang":"en","doc_type":"code","stars":5081,"dataset":"github-code","pt":"3"}
+{"seq_id":"22179163546","text":"import os\nimport re\n\nfrom datetime import datetime, timedelta\nfrom functools import wraps\n\nfrom pytz import UTC\nfrom residue import CoerceUTF8 as UnicodeText, UTCDateTime, UUID\nfrom sideboard.lib import on_startup\nfrom sqlalchemy import func\nfrom sqlalchemy.schema import ForeignKey, UniqueConstraint\nfrom sqlalchemy.types import Boolean, Integer\nfrom sqlalchemy.ext.hybrid import hybrid_property\n\nfrom uber.config import c\nfrom uber.decorators import presave_adjustment\nfrom uber.models import MagModel, Attendee\nfrom uber.models.types import default_relationship as relationship, utcnow, \\\n Choice, DefaultColumn as Column, MultiChoice\nfrom uber.utils import localized_now, make_url\n\n\n__all__ = [\n 'IndieJudge', 'IndieStudio', 'IndieDeveloper', 'IndieGame',\n 'IndieGameImage', 'IndieGameCode', 'IndieGameReview']\n\n\nclass ReviewMixin:\n @property\n def game_reviews(self):\n return [r for r in self.reviews if r.game_status != c.PENDING]\n\n\nclass IndieJudge(MagModel, ReviewMixin):\n admin_id = Column(UUID, ForeignKey('admin_account.id'))\n status = Column(Choice(c.MIVS_JUDGE_STATUS_OPTS), default=c.UNCONFIRMED)\n no_game_submission = Column(Boolean, nullable=True)\n genres = Column(MultiChoice(c.MIVS_INDIE_JUDGE_GENRE_OPTS))\n platforms = Column(MultiChoice(c.MIVS_INDIE_PLATFORM_OPTS))\n platforms_text = Column(UnicodeText)\n staff_notes = Column(UnicodeText)\n\n codes = relationship('IndieGameCode', backref='judge')\n reviews = relationship('IndieGameReview', backref='judge')\n\n email_model_name = 'judge'\n\n @property\n def judging_complete(self):\n return len(self.reviews) == len(self.game_reviews)\n\n @property\n def mivs_all_genres(self):\n return c.MIVS_ALL_GENRES in self.genres_ints\n\n @property\n def attendee(self):\n return self.admin_account.attendee\n\n @property\n def full_name(self):\n return self.attendee.full_name\n\n @property\n def email(self):\n return self.attendee.email\n\n def get_code_for(self, game_id):\n codes_for_game = [code for code in self.codes if code.game_id == game_id]\n return codes_for_game[0] if codes_for_game else ''\n\n\nclass IndieStudio(MagModel):\n group_id = Column(UUID, ForeignKey('group.id'), nullable=True)\n name = Column(UnicodeText, unique=True)\n address = Column(UnicodeText)\n website = Column(UnicodeText)\n twitter = Column(UnicodeText)\n facebook = Column(UnicodeText)\n status = Column(\n Choice(c.MIVS_STUDIO_STATUS_OPTS), default=c.NEW, admin_only=True)\n staff_notes = Column(UnicodeText, admin_only=True)\n registered = Column(UTCDateTime, server_default=utcnow())\n\n accepted_core_hours = Column(Boolean, default=False)\n discussion_emails = Column(UnicodeText)\n completed_discussion = Column(Boolean, default=False)\n read_handbook = Column(Boolean, default=False)\n training_password = Column(UnicodeText)\n selling_at_event = Column(Boolean, nullable=True, admin_only=True) # \"Admin only\" preserves null default\n needs_hotel_space = Column(Boolean, nullable=True, admin_only=True) # \"Admin only\" preserves null default\n name_for_hotel = Column(UnicodeText)\n email_for_hotel = Column(UnicodeText)\n contact_phone = Column(UnicodeText)\n show_info_updated = Column(Boolean, default=False)\n\n games = relationship(\n 'IndieGame', backref='studio', order_by='IndieGame.title')\n developers = relationship(\n 'IndieDeveloper',\n backref='studio',\n order_by='IndieDeveloper.last_name')\n\n email_model_name = 'studio'\n\n @property\n def primary_contact_first_names(self):\n if len(self.primary_contacts) == 1:\n return self.primary_contacts[0].first_name\n\n string = self.primary_contacts[0].first_name\n for dev in self.primary_contacts[1:-1]:\n string += \", \" + dev.first_name\n if len(self.primary_contacts) > 2:\n string += \",\"\n string += \" and \" + self.primary_contacts[-1].first_name\n return string\n\n @property\n def confirm_deadline(self):\n sorted_games = sorted(\n [g for g in self.games if g.accepted], key=lambda g: g.accepted)\n confirm_deadline = timedelta(days=c.MIVS_CONFIRM_DEADLINE)\n return sorted_games[0].accepted + confirm_deadline if len(sorted_games) else None\n\n @property\n def after_confirm_deadline(self):\n return self.confirm_deadline < localized_now()\n\n @property\n def discussion_emails_list(self):\n return list(filter(None, self.discussion_emails.split(',')))\n \n @property\n def discussion_emails_last_updated(self):\n studio_updates = self.get_tracking_by_instance(self, action=c.UPDATED, last_only=False)\n for update in studio_updates:\n if 'discussion_emails' in update.data:\n return update.when\n\n @property\n def core_hours_status(self):\n return \"Accepted\" if self.accepted_core_hours else None\n\n @property\n def discussion_status(self):\n return \"Completed\" if self.completed_discussion else None\n\n @property\n def handbook_status(self):\n return \"Read\" if self.read_handbook else None\n\n @property\n def training_status(self):\n if self.training_password:\n return \"Completed\" if self.training_password.lower() == c.MIVS_TRAINING_PASSWORD.lower()\\\n else \"Entered the wrong phrase!\"\n\n @property\n def selling_at_event_status(self):\n if self.selling_at_event is not None:\n return \"Expressed interest in selling\" if self.selling_at_event else \"Opted out\"\n\n @property\n def hotel_space_status(self):\n if self.needs_hotel_space is not None:\n return \"Requested hotel space for {} with email {}\".format(self.name_for_hotel, self.email_for_hotel)\\\n if self.needs_hotel_space else \"Opted out\"\n \n @property\n def show_info_status(self):\n return self.show_info_updated\n\n def checklist_deadline(self, slug):\n default_deadline = c.MIVS_CHECKLIST[slug]['deadline']\n if self.group and self.group.registered >= default_deadline and slug in ['core_hours', 'discussion']:\n return self.group.registered + timedelta(days=7)\n return default_deadline\n\n def past_checklist_deadline(self, slug):\n \"\"\"\n\n Args:\n slug: A standardized name, which should match the checklist's section name in config.\n E.g., the properties above ending in _status\n\n Returns: A timedelta object representing how far from the deadline this team is for a particular checklist item\n\n \"\"\"\n return localized_now() - self.checklist_deadline(slug)\n\n @property\n def checklist_items_due_soon_grouped(self):\n due_soon = []\n overdue = []\n for key, val in c.MIVS_CHECKLIST.items():\n if not getattr(self, key + \"_status\", None):\n if localized_now() >= self.checklist_deadline(key):\n overdue.append((key, val['name']))\n elif (localized_now() + timedelta(days=3)) >= self.checklist_deadline(key):\n due_soon.append((key, val['name']))\n\n return due_soon, overdue\n\n @property\n def website_href(self):\n return make_url(self.website)\n\n @property\n def email(self):\n return [dev.email_to_address for dev in self.developers if dev.primary_contact]\n\n @property\n def primary_contacts(self):\n return [dev for dev in self.developers if dev.primary_contact]\n\n @property\n def submitted_games(self):\n return [g for g in self.games if g.submitted]\n \n @property\n def confirmed_games(self):\n return [g for g in self.games if g.confirmed]\n\n @property\n def comped_badges(self):\n game_count = len([g for g in self.games if g.status == c.ACCEPTED])\n return c.MIVS_INDIE_BADGE_COMPS * game_count\n\n @property\n def unclaimed_badges(self):\n claimed_count = len(\n [d for d in self.developers if not d.matching_attendee])\n return max(0, self.comped_badges - claimed_count)\n\n\nclass IndieDeveloper(MagModel):\n studio_id = Column(UUID, ForeignKey('indie_studio.id'))\n\n # primary_contact == True just means they receive emails\n primary_contact = Column(Boolean, default=False)\n first_name = Column(UnicodeText)\n last_name = Column(UnicodeText)\n email = Column(UnicodeText)\n cellphone = Column(UnicodeText)\n agreed_coc = Column(Boolean, default=False)\n agreed_data_policy = Column(Boolean, default=False)\n\n @property\n def email_to_address(self):\n # Note: this doesn't actually do what we want right now\n # because the IndieDeveloper and attendee are not properly linked\n if self.matching_attendee:\n return self.matching_attendee.email\n return self.email\n\n @property\n def cellphone_num(self):\n if self.matching_attendee:\n return self.matching_attendee.cellphone\n return self.cellphone\n\n @property\n def full_name(self):\n return self.first_name + ' ' + self.last_name\n\n @property\n def matching_attendee(self):\n return self.session.query(Attendee).filter(\n func.lower(Attendee.first_name) == self.first_name.lower(),\n func.lower(Attendee.last_name) == self.last_name.lower(),\n func.lower(Attendee.email) == self.email.lower()\n ).first()\n\n\nclass IndieGame(MagModel, ReviewMixin):\n studio_id = Column(UUID, ForeignKey('indie_studio.id'))\n title = Column(UnicodeText)\n brief_description = Column(UnicodeText) # 140 max\n genres = Column(MultiChoice(c.MIVS_INDIE_GENRE_OPTS))\n platforms = Column(MultiChoice(c.MIVS_INDIE_PLATFORM_OPTS))\n platforms_text = Column(UnicodeText)\n description = Column(UnicodeText) # 500 max\n how_to_play = Column(UnicodeText) # 1000 max\n link_to_video = Column(UnicodeText)\n link_to_game = Column(UnicodeText)\n password_to_game = Column(UnicodeText)\n code_type = Column(Choice(c.MIVS_CODE_TYPE_OPTS), default=c.NO_CODE)\n code_instructions = Column(UnicodeText)\n build_status = Column(\n Choice(c.MIVS_BUILD_STATUS_OPTS), default=c.PRE_ALPHA)\n build_notes = Column(UnicodeText) # 500 max\n shown_events = Column(UnicodeText)\n submitted = Column(Boolean, default=False)\n agreed_liability = Column(Boolean, default=False)\n agreed_showtimes = Column(Boolean, default=False)\n agreed_reminder1 = Column(Boolean, default=False)\n agreed_reminder2 = Column(Boolean, default=False)\n alumni_years = Column(MultiChoice(c.PREV_MIVS_YEAR_OPTS))\n alumni_update = Column(UnicodeText)\n\n link_to_promo_video = Column(UnicodeText)\n link_to_webpage = Column(UnicodeText)\n twitter = Column(UnicodeText)\n facebook = Column(UnicodeText)\n other_social_media = Column(UnicodeText)\n\n tournament_at_event = Column(Boolean, default=False)\n tournament_prizes = Column(UnicodeText)\n has_multiplayer = Column(Boolean, default=False)\n player_count = Column(UnicodeText)\n\n # Length in minutes\n multiplayer_game_length = Column(Integer, nullable=True)\n leaderboard_challenge = Column(Boolean, default=False)\n\n status = Column(\n Choice(c.MIVS_GAME_STATUS_OPTS), default=c.NEW, admin_only=True)\n judge_notes = Column(UnicodeText, admin_only=True)\n registered = Column(UTCDateTime, server_default=utcnow())\n waitlisted = Column(UTCDateTime, nullable=True)\n accepted = Column(UTCDateTime, nullable=True)\n\n codes = relationship('IndieGameCode', backref='game')\n reviews = relationship('IndieGameReview', backref='game')\n images = relationship(\n 'IndieGameImage', backref='game', order_by='IndieGameImage.id')\n\n email_model_name = 'game'\n\n @presave_adjustment\n def accepted_time(self):\n if self.status == c.ACCEPTED and not self.accepted:\n self.accepted = datetime.now(UTC)\n\n @presave_adjustment\n def waitlisted_time(self):\n if self.status == c.WAITLISTED and not self.waitlisted:\n self.waitlisted = datetime.now(UTC)\n\n @property\n def email(self):\n return self.studio.email\n\n @property\n def reviews_to_email(self):\n return [review for review in self.reviews if review.send_to_studio]\n\n @property\n def video_href(self):\n return make_url(self.link_to_video)\n\n @property\n def href(self):\n return make_url(self.link_to_game)\n\n @property\n def screenshots(self):\n return [img for img in self.images if img.is_screenshot]\n\n @property\n def best_screenshots(self):\n return [\n img for img in self.images\n if img.is_screenshot and img.use_in_promo]\n\n def best_screenshot_downloads(self, count=2):\n all_images = reversed(sorted(\n self.images,\n key=lambda img: (\n img.is_screenshot and img.use_in_promo,\n img.is_screenshot,\n img.use_in_promo)))\n\n screenshots = []\n for i, screenshot in enumerate(all_images):\n if os.path.exists(screenshot.filepath):\n screenshots.append(screenshot)\n if len(screenshots) >= count:\n break\n return screenshots\n\n def best_screenshot_download_filenames(self, count=2):\n nonchars = re.compile(r'[\\W]+')\n best_screenshots = self.best_screenshot_downloads(count)\n screenshots = []\n for i, screenshot in enumerate(best_screenshots):\n if os.path.exists(screenshot.filepath):\n name = '_'.join([s for s in self.title.lower().split() if s])\n name = nonchars.sub('', name)\n filename = '{}_{}.{}'.format(\n name, len(screenshots) + 1, screenshot.extension.lower())\n screenshots.append(filename)\n if len(screenshots) >= count:\n break\n return screenshots + ([''] * (count - len(screenshots)))\n\n @property\n def promo_image(self):\n return next(\n iter([img for img in self.images if not img.is_screenshot]), None)\n\n @property\n def missing_steps(self):\n steps = []\n if not self.link_to_video:\n steps.append(\n 'You have not yet included a link to a video showcasing '\n 'at least 30 seconds of gameplay'\n )\n if not self.link_to_game:\n steps.append(\n 'You have not yet included a link to where the judges can '\n 'access your game')\n if self.code_type != c.NO_CODE and self.link_to_game:\n if not self.codes:\n steps.append(\n 'You have not yet attached any codes to this game for '\n 'our judges to use')\n elif not self.unlimited_code \\\n and len(self.codes) < c.MIVS_CODES_REQUIRED:\n steps.append(\n 'You have not attached the {} codes you must provide '\n 'for our judges'.format(c.MIVS_CODES_REQUIRED))\n if not self.agreed_showtimes:\n steps.append(\n 'You must agree to the showtimes detailed on the game form')\n if not self.agreed_liability:\n steps.append(\n 'You must check the box that agrees to our liability waiver')\n\n return steps\n\n @property\n def video_broken(self):\n for r in self.reviews:\n if r.video_status == c.BAD_LINK:\n return True\n\n @property\n def unlimited_code(self):\n for code in self.codes:\n if code.unlimited_use:\n return code\n\n @property\n def submittable(self):\n return not self.missing_steps\n\n @property\n def scores(self):\n return [r.game_score for r in self.reviews if r.game_score]\n\n @property\n def score_sum(self):\n return sum(self.scores, 0)\n\n @property\n def average_score(self):\n return (self.score_sum / len(self.scores)) if self.scores else 0\n\n @property\n def has_issues(self):\n return any(r.has_issues for r in self.reviews)\n\n @property\n def confirmed(self):\n return self.status == c.ACCEPTED \\\n and self.studio \\\n and self.studio.group_id\n\n @hybrid_property\n def has_been_accepted(self):\n return self.status == c.ACCEPTED\n\n @property\n def guidebook_name(self):\n return self.studio.name\n\n @property\n def guidebook_subtitle(self):\n return self.title\n\n @property\n def guidebook_desc(self):\n return self.description\n\n @property\n def guidebook_location(self):\n return ''\n\n @property\n def guidebook_image(self):\n return self.best_screenshot_download_filenames()[0]\n\n @property\n def guidebook_thumbnail(self):\n return self.best_screenshot_download_filenames()[1] \\\n if len(self.best_screenshot_download_filenames()) > 1 else self.best_screenshot_download_filenames()[0]\n\n @property\n def guidebook_images(self):\n image_filenames = [self.best_screenshot_download_filenames()[0]]\n images = [self.best_screenshot_downloads()[0]]\n if self.guidebook_image != self.guidebook_thumbnail:\n image_filenames.append(self.guidebook_thumbnail)\n images.append(self.best_screenshot_downloads()[1])\n\n return image_filenames, images\n\n\nclass IndieGameImage(MagModel):\n game_id = Column(UUID, ForeignKey('indie_game.id'))\n filename = Column(UnicodeText)\n content_type = Column(UnicodeText)\n extension = Column(UnicodeText)\n description = Column(UnicodeText)\n use_in_promo = Column(Boolean, default=False)\n is_screenshot = Column(Boolean, default=True)\n\n @property\n def url(self):\n return 'view_image?id={}'.format(self.id)\n\n @property\n def filepath(self):\n return os.path.join(c.MIVS_GAME_IMAGE_DIR, str(self.id))\n\n\nclass IndieGameCode(MagModel):\n game_id = Column(UUID, ForeignKey('indie_game.id'))\n judge_id = Column(UUID, ForeignKey('indie_judge.id'), nullable=True)\n code = Column(UnicodeText)\n unlimited_use = Column(Boolean, default=False)\n judge_notes = Column(UnicodeText, admin_only=True)\n\n @property\n def type_label(self):\n return 'Unlimited-Use' if self.unlimited_use else 'Single-Person'\n\n\nclass IndieGameReview(MagModel):\n game_id = Column(UUID, ForeignKey('indie_game.id'))\n judge_id = Column(UUID, ForeignKey('indie_judge.id'))\n video_status = Column(\n Choice(c.MIVS_VIDEO_REVIEW_STATUS_OPTS), default=c.PENDING)\n game_status = Column(\n Choice(c.MIVS_GAME_REVIEW_STATUS_OPTS), default=c.PENDING)\n game_content_bad = Column(Boolean, default=False)\n\n # 0 = not reviewed, 1-10 score (10 is best)\n readiness_score = Column(Integer, default=0)\n design_score = Column(Integer, default=0)\n enjoyment_score = Column(Integer, default=0)\n game_review = Column(UnicodeText)\n developer_response = Column(UnicodeText)\n staff_notes = Column(UnicodeText)\n send_to_studio = Column(Boolean, default=False)\n\n __table_args__ = (\n UniqueConstraint('game_id', 'judge_id', name='review_game_judge_uniq'),\n )\n\n @property\n def game_score(self):\n if self.has_game_issues or not (self.readiness_score and self.design_score and self.enjoyment_score):\n return 0\n return sum([self.readiness_score, self.design_score, self.enjoyment_score]) / float(3)\n\n @property\n def has_video_issues(self):\n return self.video_status in c.MIVS_PROBLEM_STATUSES\n\n @property\n def has_game_issues(self):\n if self.game_status != c.COULD_NOT_PLAY:\n return self.game_status in c.MIVS_PROBLEM_STATUSES\n\n @property\n def has_issues(self):\n return self.has_video_issues or self.has_game_issues\n\n\n@on_startup\ndef add_applicant_restriction():\n \"\"\"\n We use convenience functions for our form handling, e.g. to\n instantiate an attendee from an id or from form data we use the\n session.attendee() method. This method runs on startup and overrides\n the methods which are used for the game application forms to add a\n new \"applicant\" parameter. If truthy, this triggers three\n additional behaviors:\n 1) We check that there is currently a logged in studio, and redirect\n to the initial application form if there is not.\n 2) We check that the item being edited belongs to the\n currently-logged-in studio and raise an exception if it does not.\n This check is bypassed for new things which have not yet been\n saved to the database.\n 3) If the model is one with a \"studio\" relationship, we set that to\n the currently-logged-in studio.\n\n We do not perform these kinds of checks for indie judges, for two\n reasons:\n 1) We're less concerned about judges abusively editing each other's\n reviews.\n 2) There are probably some legitimate use cases for one judge to be\n able to edit another's reviews, e.g. to correct typos or reset a\n review's status after a link has been fixed, etc.\n \"\"\"\n from uber.models import Session\n\n def override_getter(method_name):\n orig_getter = getattr(Session.SessionMixin, method_name)\n\n @wraps(orig_getter)\n def with_applicant(self, *args, **kwargs):\n applicant = kwargs.pop('applicant', False)\n instance = orig_getter(self, *args, **kwargs)\n if applicant:\n studio = self.logged_in_studio()\n if hasattr(instance.__class__, 'game'):\n assert instance.is_new or studio == instance.game.studio\n else:\n assert instance.is_new or studio == instance.studio\n instance.studio = studio\n return instance\n setattr(Session.SessionMixin, method_name, with_applicant)\n\n names = [\n 'indie_developer',\n 'indie_game',\n 'indie_game_code',\n 'indie_game_image']\n for name in names:\n override_getter(name)\n","repo_name":"magfest/ubersystem","sub_path":"uber/models/mivs.py","file_name":"mivs.py","file_ext":"py","file_size_in_byte":22124,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"3"}
+{"seq_id":"35319778580","text":"n = int(input())\n\nsnake_game = []\nsnake_position = ()\nfood_quantity = 0\nis_win = False\nlair = []\n\nfor row in range(n):\n line = [x for x in input()]\n if \"S\" in line:\n snake_position = (row, line.index(\"S\"))\n if \"B\" in line:\n lair.append((row, line.index(\"B\")))\n snake_game.append(line)\n\ndirections = {\"up\": (-1, 0), \"right\": (0, 1), \"down\": (1, 0), \"left\": (0, -1)}\nwhile True:\n command = input()\n row = snake_position[0]\n col = snake_position[1]\n row += int(directions[command][0])\n col += int(directions[command][1])\n snake_game[snake_position[0]][snake_position[1]] = \".\"\n\n if row >= n or row < 0 or col >= n or col < 0:\n break\n\n current_cell = snake_game[row][col]\n\n if current_cell == \"B\":\n snake_game[row][col] = \".\"\n\n if row == lair[0][0] and col == lair[0][1]:\n snake_position = (lair[1][0], lair[1][1])\n else:\n snake_position = (lair[0][0], lair[0][1])\n snake_game[snake_position[0]][snake_position[1]] = \"S\"\n elif current_cell == \"*\":\n food_quantity += 1\n if food_quantity >= 10:\n is_win = True\n snake_game[row][col] = \"S\"\n break\n snake_game[row][col] = \".\"\n snake_position = (row, col)\n\n else:\n snake_game[row][col] = \".\"\n snake_position = (row, col)\n\nif is_win:\n print(\"You won! You fed the snake.\")\nelse:\n print(\"Game over!\")\n\nprint(f\"Food eaten: {food_quantity}\")\n\n[print(\"\".join(line_for_print)) for line_for_print in snake_game]\n","repo_name":"stefistoeva/Python-Advanced","sub_path":"Exam/02.Snake.py","file_name":"02.Snake.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36896678098","text":"# /usr/bin/env python3\n\"\"\"Function that receives a string and return the repeated characher and its index\"\"\"\n\n\ndef repeaded_char(char):\n \"\"\"This function returns the first repeated char\"\"\"\n new_str = \"\" # New string\n repeated = \"\" # Repeated char\n\n for i in char:\n if i in new_str:\n repeated = i\n else:\n new_str += i\n\n # No repetition check\n if repeated is \"\":\n repeat_position = -1\n else:\n repeat_position = char.find(repeated) + 1\n\n return repeated, repeat_position\n\n\ndef main():\n char = \"bdacefghai\"\n # char = \"abc\"\n index = repeaded_char(char)\n print(index)\n\nif __name__ == '__main__':\n main()\n","repo_name":"ChristianMartinezTech/BackendDevPrepWork","sub_path":"PersonalStudy/CodeChallenge/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18403296634","text":"# -*- coding: utf-8 -*-\n# Factorial.py\n# @author guokonghui\n# @description\n# @created Fri Jan 18 2019 17:08:52 GMT+0800 (中国标准时间)\n# @last-modified Fri Jan 18 2019 20:16:44 GMT+0800 (中国标准时间)\n#\n\n\ndef factorial(n):\n result = 1\n if n < 0:\n print(\"Negative numbers cannot carry out factorial operations.\")\n result = 0\n elif (1 == n) | (0 == n):\n result = 1\n else:\n result = n * factorial(n - 1)\n return result\n\n\ndef main():\n r = factorial(5)\n print(r)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lwh2016/0_PYTHON","sub_path":"1-BasicKnowledge/1-递归函数/Factorial.py","file_name":"Factorial.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8185866941","text":"from gym_carla import settings\nimport cv2\nimport os\nfrom gym_carla.carla_utils import makeCarlaImportable\nimport numpy as np\n\nfrom source.numpyNumbers import NumpyNumbers\n\nmakeCarlaImportable()\nimport carla\n\n\nclass MediaHandler:\n def __init__(self, carlaEnv):\n self.carlaEnv = carlaEnv\n self.episodeFrames = []\n\n def processImage(self, data):\n # self.carlaEnv.logSensor(\"processImage\")\n\n #segImageData = np.zeros(shape=self.carlaEnv.segmented_observation_space, dtype=np.int8)\n segData = [element.r for element in data]\n segImageData = np.reshape(segData, self.carlaEnv.segmented_observation_space)\n\n # if self.carlaEnv.segImgFrame is not None:\n # diff = np.sum(self.carlaEnv.segImgFrame-segImageData)\n # if diff > 0:\n # print(f\"seg diff: {diff}\")\n\n self.carlaEnv.segImgFrame = segImageData\n\n cc = carla.ColorConverter.CityScapesPalette\n data.convert(cc)\n\n # Get image, reshape and remove alpha channel\n image = np.array(data.raw_data)\n image = image.reshape((self.carlaEnv.imgHeight, self.carlaEnv.imgWidth, 4))\n image = image[:, :, :3]\n self.addSpeedOverlayToFrame(image, self.carlaEnv.getCarVelocity())\n\n # bgra\n self.carlaEnv.imgFrame = image\n\n # Save image in memory for later video export\n if self._isVideoEpisode():\n self._storeImageForVideoEpisode(image)\n\n # Save images to disk (Output folder)\n if settings.VIDEO_ALWAYS_ON and self.carlaEnv.carlaInstance == 0:\n cv2.imwrite(f\"../data/frames/frame_{data.frame}.png\", self._getResizedImageWithOverlay(image))\n # data.save_to_disk('../data/frames/%06d.png' % data.frame)\n\n def exportAndUploadVideoToDB(self):\n folder = \"../data/videos\"\n file_name = f\"videoTest_{self.carlaEnv.episodeNr}.mp4\"\n video_path = folder + \"/\" + file_name\n model_path = f\"temp/{self.carlaEnv.modelName}_{self.carlaEnv.episodeNr}.pkl\"\n\n self._exportVideo(folder, file_name, self.episodeFrames)\n # self.carlaEnv.model.save(model_path)\n self._uploadVideoAndModelToDb(video_path, model_path, self.carlaEnv.sessionId, self.carlaEnv.episodeNr, self.carlaEnv.episodeReward)\n os.remove(video_path)\n # os.remove(model_path)\n\n # Returns true, if the current episode is a video episode\n def _isVideoEpisode(self):\n return (self.carlaEnv.carlaInstance == 0) and (self.carlaEnv.episodeNr % settings.VIDEO_EXPORT_RATE == 0)\n\n def _storeImageForVideoEpisode(self, image):\n image = self._getResizedImageWithOverlay(image)\n\n self.episodeFrames.append(np.asarray(image))\n\n def _getResizedImageWithOverlay(self, image):\n image = self._resizeImage(image)\n self._addFrameDataOverlay(image)\n\n return image\n\n def _resizeImage(self, image):\n width = self._getVideoWidth()\n height = self._getVideoHeight()\n\n return cv2.resize(image, dsize=(height, width), interpolation=cv2.INTER_NEAREST)\n\n def _getVideoWidth(self):\n return max(settings.CARLA_IMG_WIDTH, settings.VIDEO_MAX_WIDTH)\n\n def _getVideoHeight(self):\n return max(settings.CARLA_IMG_HEIGHT, settings.VIDEO_MAX_HEIGHT)\n\n def _addFrameDataOverlay(self, frame):\n nn = NumpyNumbers()\n\n y_offset = nn.number_size[0] + 2\n\n # Speed\n speed = self.carlaEnv.getCarVelocity()\n speed_overlay = nn.getOverlay(round(speed))\n\n # Reward\n total_reward = self.carlaEnv.episodeReward\n reward_overlay = nn.getOverlay(round(total_reward))\n\n # Actions\n controls = self.carlaEnv.vehicle.get_control()\n throttle_overlay = nn.getOverlay(round(controls.throttle*100))\n brake_overlay = nn.getOverlay(round(controls.brake*100))\n steer_overlay = nn.getOverlay(round(controls.steer*100))\n\n self.addOverlayToFrame(frame, speed_overlay, (y_offset * 0, self._getXOffset(frame, speed_overlay)))\n self.addOverlayToFrame(frame, reward_overlay, (y_offset * 1, self._getXOffset(frame, reward_overlay)))\n self.addOverlayToFrame(frame, throttle_overlay, (y_offset * 2, self._getXOffset(frame, throttle_overlay)))\n self.addOverlayToFrame(frame, brake_overlay, (y_offset * 3, self._getXOffset(frame, brake_overlay)))\n self.addOverlayToFrame(frame, steer_overlay, (y_offset * 4, self._getXOffset(frame, steer_overlay)))\n\n def _getXOffset(self, frame, overlay):\n return frame.shape[1] - overlay.shape[1]\n\n # Exports a video from numpy arrays to the file system\n def _exportVideo(self, folder, file_name, frames):\n if not os.path.isdir(folder):\n os.mkdir(folder)\n\n file_path = folder + \"/\" + file_name\n\n video_size = (self._getVideoHeight(), self._getVideoWidth())\n fps = 1 / settings.AGENT_TIME_STEP_SIZE\n\n out = cv2.VideoWriter(file_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, video_size)\n\n for frame in frames:\n out.write(frame)\n\n out.release()\n\n def _uploadVideoAndModelToDb(self, video_path, model_path, session_id, episode_nr, episode_reward):\n with open(video_path, 'rb') as f:\n video_blob = f.read()\n\n # with open(model_path, 'rb') as f:\n # model_blob = f.read()\n\n self.carlaEnv.sql.INSERT_newEpisode(session_id, self.carlaEnv.carlaInstance, episode_nr, episode_reward, False, video_blob, None)\n\n def addSpeedOverlayToFrame(self, frame, speed):\n overlay = self.createSpeedBarOverlay(speed, 50, 50)\n self.addOverlayToFrame(frame, overlay, (0, 0))\n\n def addOverlayToFrame(self, image, overlay, offset):\n for a, aa in enumerate(overlay):\n for b, bb in enumerate(aa):\n for c, frame_pixel in enumerate(bb):\n if frame_pixel != 0:\n image[a + offset[0], b + offset[1], c] = frame_pixel\n\n def createSpeedBarOverlay(self, speed, height, width):\n max_speed = 110 # km/h\n scale = min(speed / max_speed, 1)\n\n speed_pixel_width = round(width * scale)\n speed_pixel_height = 5\n\n speed_bar = np.ones((speed_pixel_height, speed_pixel_width))\n\n return self.addColorChannels(speed_bar, (255, 50, 50))\n\n def addColorChannels(self, number: np, color):\n return np.dstack((\n number * color[2], # B\n number * color[1], # G\n number * color[0], # R\n ))","repo_name":"Reniets/P5_IncrementalTransferLearningForReinforcementLearningInARealisticEnvironment","sub_path":"source/media_handler.py","file_name":"media_handler.py","file_ext":"py","file_size_in_byte":6507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18867604246","text":"import psycopg2\n\nfrom config import DSN\n\n\ndef create_table():\n conn = psycopg2.connect(DSN)\n create_table_data = \"\"\"\n CREATE TABLE used_methods (\n id SERIAL PRIMARY KEY,\n domain CHARACTER VARYING(200) NOT NULL,\n datetime TIMESTAMP DEFAULT NOW(),\n methods CHARACTER VARYING(50) NOT NULL,\n success BOOLEAN NOT NULL\n );\n \"\"\"\n cursor = conn.cursor()\n cursor.execute(create_table_data)\n conn.commit()\n conn.close()\n print(\"Таблица создана\")\n\n\nif __name__ == \"__main__\":\n create_table()\n","repo_name":"Alexsandr12/domain-info","sub_path":"create_table.py","file_name":"create_table.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16149687257","text":"\"\"\"\nContext menus.\nsignal-based approach to create context menus.\n\"\"\"\n\nimport sys\n\nfrom PyQt6.QtCore import Qt\nfrom PyQt6.QtGui import QAction\n\nfrom PyQt6.QtWidgets import (\n QApplication,\n QMainWindow,\n QMenu,\n)\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.show()\n\n self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)\n self.customContextMenuRequested.connect(self.on_context_menu)\n\n def on_context_menu(self, pos):\n context = QMenu(self)\n context.addAction(QAction(\"test 1\", self))\n context.addAction(QAction(\"test 2\", self))\n context.addAction(QAction(\"test 3\", self))\n context.exec(self.mapToGlobal(pos))\n\n\napp = QApplication([])\nwindow = MainWindow()\nwindow.show()\nsys.exit(app.exec())\n","repo_name":"arunkhattri/pyqt_gui","sub_path":"martin_fitzpatrik_book/10_events/events_context_menus_1.py","file_name":"events_context_menus_1.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5939130687","text":"from beecell.password import random_password\nfrom beecell.simple import truncate\nfrom beecell.types.type_dict import dict_get\nfrom beedrones.cmp.business import CmpBusinessAbstractService\nfrom beedrones.cmp.client import CmpBaseService, CmpApiManagerError, CmpApiClientError\n\n\nclass CmpBusinessNetaasService(CmpBusinessAbstractService):\n \"\"\"Cmp business compute service\n \"\"\"\n def __init__(self, manager):\n CmpBaseService.__init__(self, manager)\n\n self.backup = None\n self.vpc = CmpBusinessNetaasVpcService(self.manager)\n self.sg = CmpBusinessNetaasSecurityGroupService(self.manager)\n\n\nclass CmpBusinessNetaasVpcService(CmpBusinessAbstractService):\n \"\"\"Cmp business network service - vpc\n \"\"\"\n VERSION = 'v1.0'\n\n def list(self, *args, **kwargs):\n \"\"\"get vpcs\n\n :param accounts: list of account id comma separated\n :param page: list page\n :param size: list page size\n :param tags: list of tag comma separated\n :param states: list of state comma separated \n :param ids: list of vpc id comma separated\n :param name: list of vpc id comma separated\n :return: list of vpcs {'count':.., 'page':.., 'total':.., 'sort':.., 'vpcs':..}\n :raise CmpApiClientError:\n \"\"\"\n params = ['accounts', 'states', 'tags', 'ids']\n mappings = {\n 'tags': lambda x: x.split(','),\n 'ids': lambda x: x.split(','),\n 'states': lambda x: x.split(','),\n }\n aliases = {\n 'accounts': 'owner-id.N',\n 'ids': 'instance-id.N',\n 'tags': 'tag-value.N',\n 'states': 'state.N',\n 'size': 'Nvl_MaxResults',\n 'page': 'Nvl_NextToken'\n }\n data = self.format_paginated_query(kwargs, params, mappings=mappings, aliases=aliases)\n uri = self.get_uri('computeservices/vpc/describevpcs', preferred_version='v1.0', **kwargs)\n res = self.api_get(uri, data=data)\n res = dict_get(res, 'DescribeVpcsResponse')\n res = {\n 'count': len(res.get('vpcSet')),\n 'page': kwargs.get('NextToken', 0),\n 'total': res.get('nvl-vpcTotal'),\n 'sort': {'field': 'id', 'order': 'asc'},\n 'vpcs': res.get('vpcSet')\n }\n self.logger.debug('get vpcs: %s' % truncate(res))\n return res\n\n def get(self, oid, **kwargs):\n \"\"\"get vpc\n\n :param oid: vpc id or uuid\n :return: vpc\n :raise CmpApiClientError:\n \"\"\"\n if self.is_uuid(oid):\n kwargs.update({'vpc-id.N': [oid]})\n # elif self.is_name(oid):\n # kwargs.update({'name.N': [oid]})\n\n # params = ['vpc-id.N', 'name.N']\n params = ['vpc-id.N']\n data = self.format_paginated_query(kwargs, params)\n uri = self.get_uri('computeservices/vpc/describevpcs', preferred_version='v1.0', **kwargs)\n res = self.api_get(uri, data=data)\n res = dict_get(res, 'DescribeVpcsResponse.vpcSet', default=[])\n if len(res) > 0:\n res = res[0]\n else:\n raise CmpApiManagerError('vpc %s does not exist' % oid)\n self.logger.debug('get vpc%s: %s' % (oid, truncate(res)))\n return res\n\n # def add(self, name, account, subnet, itype, image, sg, **kwargs):\n # \"\"\"Add security group\n #\n # :param str name: security group name\n # :param str account: parent account id\n # :param str type: security group type\n # :param str subnet: security group subnet id\n # :param str image: security group image id\n # :param str sg: security group security group id\n # :param str AdditionalInfo: security group description [optional]\n # :param str KeyName: security group ssh key name [optional]\n # :param str AdminPassword: security group admin/root password [optional]\n # :param list BlockDevices: block evice config. Use [{'index': 0, 'type':.. 'uuid':.., 'size':..}] to update\n # root block device. Add {'index': [1..100], 'type':.. 'uuid':.., 'size':..} to create additional block\n # devices. Set uuid (compute volume uuid) when you want to clone existing volume [optional]\n # :param str Nvl_Hypervisor: security group hypervisor. Can be: openstack or vsphere [default=openstack]\n # :param str Nvl_HostGroup: security group host group. Ex. oracle [optional]\n # :param bool Nvl_MultiAvz: set to False create vm to work only in the selected availability zone [default=False]\n # :param dict Nvl_Metadata: security group custom metadata [optional]\n # :return:\n # :raises CmpApiClientError: raise :class:`CmpApiClientError`\n # \"\"\"\n # data = {\n # 'Name': name,\n # 'owner-id': account,\n # 'AdditionalInfo': '',\n # 'SubnetId': subnet,\n # 'InstanceType': itype,\n # 'ImageId': image,\n # 'SecurityGroupId.N': [sg]\n # }\n #\n # hypervisor = kwargs.get('Nvl_Hypervisor', 'openstack')\n # if hypervisor not in self.AVAILABLE_HYPERVISORS:\n # raise CmpApiManagerError('supported hypervisor are %s' % self.AVAILABLE_HYPERVISORS)\n # data['Nvl_Hypervisor'] = hypervisor\n #\n # data['Nvl_MultiAvz'] = kwargs.get('Nvl_MultiAvz', True)\n # data['AdminPassword'] = kwargs.get('AdminPassword', random_password(10))\n #\n # # set disks\n # blocks = [{'Ebs': {}}]\n # data['BlockDeviceMapping.N'] = blocks\n # block_devices = kwargs.get('BlockDevices', [])\n # for block_device in block_devices:\n # index = block_device.get('index')\n #\n # if index == 0:\n # blocks[0] = self.__config_block(block_device)\n # else:\n # blocks.append(self.__config_block(block_device))\n #\n # other_params = ['AdditionalInfo', 'KeyName', 'Nvl_Metadata', 'Nvl_HostGroup']\n # data.update(self.format_request_data(kwargs, other_params))\n # uri = self.get_uri('computeservices/vpc/createvpc')\n # res = self.api_post(uri, data={'instance': data})\n # res = dict_get(res, 'RunInstanceResponse.instancesSet.0.instanceId')\n # self.logger.debug('Create security group %s' % res)\n # return res\n #\n # def __set_data(self, input_data, input_field, search_data, search_field):\n # custom_data = input_data.get(input_field, None)\n # if custom_data is None:\n # data = dict_get(search_data, search_field)\n # else:\n # data = custom_data\n # return data\n #\n # def clone(self, oid, name, **kwargs):\n # \"\"\"clone security group\n #\n # :param oid: id of the security group to clone\n # :param name: security group name\n # :param kwargs.account: parent account id [optional]\n # :param kwargs.type: security group type [optional]\n # :param kwargs.subnet: security group subnet id [optional]\n # :param kwargs.sg: security group security group id [optional]\n # :param kwargs.sshkey: security group ssh key name [optional]\n # :param str kwargs.AdminPassword: security group admin/root password [optional]\n # :param bool kwargs.Nvl_MultiAvz: set to False create vm to work only in the selected availability zone\n # [default=False]\n # :param dict kwargs.Nvl_Metadata: security group custom metadata [optional]\n # :return:\n # :raises CmpApiClientError: raise :class:`CmpApiClientError`\n # \"\"\"\n # # get original vm\n # vm = self.get(oid)\n #\n # image_name = dict_get(vm, 'nvl-imageName')\n # account = self.__set_data(kwargs, 'account', vm, 'nvl-ownerId')\n # image = self.manager.business.service.inst.list(image_name, account_id=account)\n # itype = self.__set_data(kwargs, 'type', vm, 'instanceType')\n # subnet = self.__set_data(kwargs, 'subnet', vm, 'subnetId')\n # sg = self.__set_data(kwargs, 'sg', vm, 'groupSet.0.groupId')\n # kwargs['KeyName'] = self.__set_data(kwargs, 'sshkey', vm, 'keyName')\n #\n # # set disks\n # blocks = []\n # index = 0\n # for disk in vm.get('blockDeviceMapping', []):\n # blocks.append({\n # 'index': index,\n # 'uuid': dict_get(disk, 'ebs.volumeId'),\n # 'size': dict_get(disk, 'ebs.volumeSize')\n # })\n # kwargs['BlockDevices'] = blocks\n #\n # res = self.add(name, account, subnet, itype, image, sg, **kwargs)\n # return res\n #\n # def load(self, oid, **kwargs):\n # \"\"\"import security group from existing resource\n #\n # :param oid: id of the security group\n # :param container: container id where import security group', 'action': 'store', 'type': str}),\n # :param name: security group name', 'action': 'store', 'type': str}),\n # :param vm: physical id of the security group to import', 'action': 'store', 'type': str}),\n # :param image: compute image id', 'action': 'store', 'type': str}),\n # :param pwd: security group password', 'action': 'store', 'type': str}),\n # :param -sshkey: security group ssh key name\n # :param account: parent account id\n #\n #\n # :param -type: security group type\n # :param -subnet: security group subnet id\n # :param -sg: security group security group id\n #\n # :param -pwd: security group admin/root password', 'action': 'store', 'type': str,\n # 'default': None}),\n # :param -multi-avz: if set to False create vm to work only in the selected availability zone '\n # '[default=True]. Use when subnet cidr is public', 'action': 'store', 'type': str,\n # 'default': True}),\n # :param -meta: security group custom metadata\n # :return:\n # :raises CmpApiClientError: raise :class:`CmpApiClientError`\n # \"\"\"\n # data = self.format_request_data(kwargs, ['name', 'desc', 'ext_id', 'active', 'attribute', 'tags'])\n # uri = self.get_uri('security groups/%s' % oid)\n # res = self.api_put(uri, data={'resource': data})\n # self.logger.debug('Update security group %s' % oid)\n # return res\n #\n # def update(self, oid, **kwargs):\n # \"\"\"Update security group\n #\n # :param oid: id of the security group\n # :param kwargs.InstanceType: security group type [optional]\n # :param kwargs.sgs: list of security group security group id to add or remove. Syntax: [:ADD, :DE]\n # [optional]\n # :return:\n # :raises CmpApiClientError: raise :class:`CmpApiClientError`\n # \"\"\"\n # data = {'InstanceId': oid}\n # sgs = kwargs.pop('sgs', None)\n # if sgs is not None:\n # data['GroupId.N'] = sgs\n # data.update(self.format_request_data(kwargs, ['InstanceType']))\n # uri = self.get_uri('computeservices/vpc/modifyinstanceattribute')\n # res = self.api_put(uri, data={'instance': data})\n # self.logger.debug('Update security group %s' % oid)\n # return res\n #\n # def delete(self, oid, delete_services=True, delete_tags=True):\n # \"\"\"Delete security group\n #\n # :param oid: id of the security group\n # :param delete_services: if True delete chiild services\n # :param delete_tags: if True delete child tags\n # :return:\n # :raises CmpApiClientError: raise :class:`CmpApiClientError`\n # \"\"\"\n # kwargs = {'InstanceId.N': [oid]}\n # params = ['InstanceId.N']\n # data = self.format_paginated_query(kwargs, params)\n # uri = self.get_uri('computeservices/vpc/terminateinstances')\n # self.api_delete(uri, data=data)\n # self.logger.debug('delete security group %s' % oid)\n #\n # def get_types(self, *args, **kwargs):\n # \"\"\"get security group types\n #\n # :param account: account id\n # :param size: list page\n # :param page: list page size\n # :return: list of security group types {'count':.., 'page':.., 'total':.., 'sort':.., 'types':..}\n # :raise CmpApiClientError:\n # \"\"\"\n # params = ['account', 'size', 'page']\n # mappings = {}\n # aliases = {\n # 'account': 'owner-id',\n # 'size': 'MaxResults',\n # 'page': 'NextToken'\n # }\n # data = self.format_paginated_query(kwargs, params, mappings=mappings, aliases=aliases)\n # uri = self.get_uri('computeservices/vpc/describeinstancetypes', preferred_version='v2.0', **kwargs)\n # res = self.api_get(uri, data=data)\n # res = dict_get(res, 'DescribeInstanceTypesResponse')\n # res = {\n # 'count': len(res.get('instanceTypesSet')),\n # 'page': kwargs.get('NextToken', 0),\n # 'total': res.get('instanceTypesTotal'),\n # 'sort': {'field': 'id', 'order': 'asc'},\n # 'types': res.get('instanceTypesSet')\n # }\n # self.logger.debug('get security group types: %s' % truncate(res))\n # return res\n\n\nclass CmpBusinessNetaasSubnetService(CmpBusinessAbstractService):\n \"\"\"Cmp business network service - subnet\n \"\"\"\n VERSION = 'v1.0'\n\n\nclass CmpBusinessNetaasSecurityGroupService(CmpBusinessAbstractService):\n \"\"\"Cmp business network service - security group\n \"\"\"\n VERSION = 'v1.0'\n \n def list(self, *args, **kwargs):\n \"\"\"get security groups\n\n :param accounts: list of account id comma separated\n :param ids: list of security group id comma separated\n :param vpcs: list of vpc id comma separated\n :param tags: list of tag comma separated\n :param page: list page\n :param size: list page size\n :return: list of security groups {'count':.., 'page':.., 'total':.., 'sort':.., 'security_groups':..}\n :raise CmpApiClientError:\n \"\"\"\n params = ['accounts', 'ids', 'tags', 'vpcs']\n mappings = {\n 'tags': lambda x: x.split(','),\n 'vpcs': lambda x: x.split(','),\n 'ids': lambda x: x.split(',')\n }\n aliases = {\n 'accounts': 'owner-id.N',\n 'ids': 'group-id.N',\n 'tags': 'tag-key.N',\n 'vpcs': 'vpc-id.N',\n 'size': 'MaxResults',\n 'page': 'NextToken'\n }\n data = self.format_paginated_query(kwargs, params, mappings=mappings, aliases=aliases)\n uri = self.get_uri('computeservices/securitygroup/describesecuritygroups', preferred_version='v1.0', **kwargs)\n res = self.api_get(uri, data=data)\n res = dict_get(res, 'DescribeSecurityGroupsResponse')\n res = {\n 'count': len(res.get('securityGroupInfo')),\n 'page': kwargs.get('page', 0),\n 'total': res.get('nvl-securityGroupTotal'),\n 'sort': {'field': 'id', 'order': 'asc'},\n 'security_groups': res.get('securityGroupInfo')\n }\n self.logger.debug('get security groups: %s' % truncate(res))\n return res\n\n def get(self, oid, **kwargs):\n \"\"\"get security group\n\n :param oid: security group id or uuid\n :return: security groups\n :raise CmpApiClientError:\n \"\"\"\n kwargs = {'GroupName.N': [oid]}\n params = ['GroupName.N', 'name.N']\n data = self.format_paginated_query(kwargs, params)\n uri = self.get_uri('computeservices/securitygroup/describesecuritygroups', preferred_version='v1.0', **kwargs)\n res = self.api_get(uri, data=data)\n res = dict_get(res, 'DescribeSecurityGroupsResponse.securityGroupInfo', default=[])\n if len(res) > 0:\n res = res[0]\n else:\n raise CmpApiManagerError('security group %s does not exist' % oid)\n self.logger.debug('get security group %s: %s' % (oid, truncate(res)))\n return res\n\n def add(self, name, vpc, template=None, **kwargs):\n \"\"\"Add security group\n\n :param str name: security group name\n :param str vpc: parent vpc id\n :param str template: security group template id [optional]\n :return:\n :raises CmpApiClientError: raise :class:`CmpApiClientError`\n \"\"\"\n data = {\n 'GroupName': name,\n 'VpcId': vpc\n }\n sg_type = template\n if sg_type is not None:\n data['GroupType'] = sg_type\n\n uri = self.get_uri('computeservices/securitygroup/createsecuritygroup') \n res = self.api_post(uri, data={'security_group': data})\n res = dict_get(res, 'CreateSecurityGroupResponse.groupId')\n self.logger.debug('Create security group %s' % res)\n return res\n\n def delete(self, oid):\n \"\"\"Delete security group\n\n :param oid: id of the security group\n :return:\n :raises CmpApiClientError: raise :class:`CmpApiClientError`\n \"\"\"\n uri = self.get_uri('computeservices/securitygroup/deletesecuritygroup')\n self.api_delete(uri, data={'security_group': {'GroupName': oid}})\n self.logger.debug('delete security group %s' % oid)\n\n def add_rule(self, oid, rule_type, proto=None, port=None, dest=None, source=None):\n \"\"\"add security group rule\n\n :param oid: id of the security group\n :param rule_type: egress or ingress. For egress rule the destination. For ingress rule specify the source\n :param proto: protocol. can be tcp, udp, icmp or -1 for all. [optional]\n :param port: can be an integer between 0 and 65535 or a range with start and end in the same interval. Range\n format is -. Use -1 for all ports. Set subprotocol if proto is icmp (8 for ping). [optional]\n :param dest: rule destination. Syntax :. Destination type can be SG, CIDR. For SG value must be\n . For CIDR value should like 10.102.167.0/24. [optional]\n :param source: rule source. Syntax :. Source type can be SG, CIDR. For SG value must be .\n For CIDR value should like 10.102.167.0/24. [optional]\n :return:\n :raises CmpApiClientError: raise :class:`CmpApiClientError`\n \"\"\"\n from_port = -1\n to_port = -1\n if port is not None:\n port = str(port)\n port = port.split('-')\n if len(port) == 1:\n from_port = to_port = port[0]\n else:\n from_port, to_port = port\n\n if proto is None:\n proto = '-1'\n\n if rule_type not in ['ingress', 'egress']:\n raise CmpApiClientError('rule type must be ingress or egress')\n if rule_type == 'ingress':\n if source is None:\n raise CmpApiClientError('ingress rule require source')\n dest = source.split(':')\n elif rule_type == 'egress':\n if dest is None:\n raise CmpApiClientError('egress rule require destination')\n dest = dest.split(':')\n if dest[0] not in ['SG', 'CIDR']:\n raise CmpApiClientError('source/destination type must be SG or CIDR')\n data = {\n 'GroupName': oid,\n 'IpPermissions.N': [\n {\n 'FromPort': from_port,\n 'ToPort': to_port,\n 'IpProtocol': proto\n }\n ]\n }\n if dest[0] == 'SG':\n data['IpPermissions.N'][0]['UserIdGroupPairs'] = [{\n 'GroupName': dest[1]\n }]\n elif dest[0] == 'CIDR':\n data['IpPermissions.N'][0]['IpRanges'] = [{\n 'CidrIp': dest[1]\n }]\n else:\n raise Exception('Wrong rule type')\n\n if rule_type == 'egress':\n uri = self.get_uri('computeservices/securitygroup/authorizesecuritygroupegress')\n self.task_key = 'AuthorizeSecurityGroupEgressResponse.nvl-activeTask'\n elif rule_type == 'ingress':\n uri = self.get_uri('computeservices/securitygroup/authorizesecuritygroupingress')\n self.task_key = 'AuthorizeSecurityGroupIngressResponse.nvl-activeTask'\n res = self.api_post(uri, data={'rule': data})\n self.logger.debug('create security group %s rule' % oid)\n return res\n\n def del_rule(self, oid, rule_type, proto=None, port=None, dest=None, source=None):\n \"\"\"delete security group rule\n\n :param oid: id of the security group\n :param rule_type: egress or ingress. For egress rule the destination. For ingress rule specify the source\n :param proto: protocol. can be tcp, udp, icmp or -1 for all. [optional]\n :param port: can be an integer between 0 and 65535 or a range with start and end in the same interval. Range\n format is -. Use -1 for all ports. Set subprotocol if proto is icmp (8 for ping). [optional]\n :param dest: rule destination. Syntax :. Destination type can be SG, CIDR. For SG value must be\n . For CIDR value should like 10.102.167.0/24. [optional]\n :param source: rule source. Syntax :. Source type can be SG, CIDR. For SG value must be .\n For CIDR value should like 10.102.167.0/24. [optional]\n :return:\n :raises CmpApiClientError: raise :class:`CmpApiClientError`\n \"\"\"\n from_port = -1\n to_port = -1\n if port is not None:\n port = str(port)\n port = port.split('-')\n if len(port) == 1:\n from_port = to_port = port[0]\n else:\n from_port, to_port = port\n\n if proto is None:\n proto = '-1'\n\n if rule_type not in ['ingress', 'egress']:\n raise Exception('rule type must be ingress or egress')\n if rule_type == 'ingress':\n if source is None:\n raise Exception('ingress rule require source')\n dest = source.split(':')\n elif rule_type == 'egress':\n if dest is None:\n raise Exception('egress rule require destination')\n dest = dest.split(':')\n if dest[0] not in ['SG', 'CIDR']:\n raise Exception('source/destination type must be SG or CIDR')\n data = {\n 'GroupName': oid,\n 'IpPermissions.N': [\n {\n 'FromPort': from_port,\n 'ToPort': to_port,\n 'IpProtocol': proto\n }\n ]\n }\n if dest[0] == 'SG':\n data['IpPermissions.N'][0]['UserIdGroupPairs'] = [{'GroupName': dest[1]}]\n elif dest[0] == 'CIDR':\n data['IpPermissions.N'][0]['IpRanges'] = [{'CidrIp': dest[1]}]\n else:\n raise Exception('wrong rule type')\n\n if rule_type == 'egress':\n uri = self.get_uri('computeservices/securitygroup/revokesecuritygroupegress')\n self.task_key = 'RevokeSecurityGroupEgressResponse.nvl-activeTask'\n elif rule_type == 'ingress':\n uri = self.get_uri('computeservices/securitygroup/revokesecuritygroupingress')\n self.task_key = 'RevokeSecurityGroupIngressResponse.nvl-activeTask'\n self.api_delete(uri, data={'rule': data})\n self.logger.debug('delete security group %s rule' % oid)\n\n\nclass CmpBusinessNetaasGatewayService(CmpBusinessAbstractService):\n \"\"\"Cmp business network service - gateway\n \"\"\"\n VERSION = 'v1.0'\n","repo_name":"Nivola/beedrones","sub_path":"beedrones/cmp/business_netaas.py","file_name":"business_netaas.py","file_ext":"py","file_size_in_byte":23614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35169028456","text":"import aiofiles\nimport chardet\n\nfrom os import path\n\nfrom typing import Tuple\n\n\ndef match_mime_type(ext: str) -> str:\n \"\"\"Tries to match Mime Type to File Extension\n\n :param ext: File Extension as String\n :return: Mime Type as String\n \"\"\"\n return {\n '.txt': 'text/plain',\n '.png': 'image/png',\n '.pdf': 'application/pdf',\n '.php': 'application/x-httpd-php',\n '.svg': 'image/svg+xml',\n '.ttf': 'font/ttf',\n '.zip': 'application/zip',\n '.htm': 'text/html',\n '.html': 'text/html',\n '.gif': 'image/gif',\n '.js': 'text/javascript',\n '.json': 'application/json'\n }.get(ext, \"text/html\")\n\n\nclass Resource:\n \"\"\"Resource Helper - Helps loading resources e.g. files from either cache or disk\n\n :param config: Config module instance\n :param log: Log module instance\n :param cache: Cache instance\n \"\"\"\n\n def __init__(self, config, log, cache) -> None:\n self.config = config\n self.log = log\n self.cache = cache\n\n async def check_valid_resource(self, data: list) -> str or bool:\n \"\"\"Check if data contains a valid resource\n\n :param data: Request Data\n :return: resource path || False\n \"\"\"\n try:\n if data[1] == '' or data[1] == '/': # If requested resource is empty, serve default\n resource = self.config.options.get(\"Server\", \"DefaultFile\")\n else: # Set resource to requested resource\n resource = data[1]\n return self.config.options.get(\"General\", \"WorkingDirectory\") + resource\n except IndexError: # No resource was specified, invalid request\n return False\n\n async def detect_encoding(self, raw_data: bytes) -> str:\n \"\"\"Tries to detect the encoding for a file.\n\n :param raw_data: Data as Bytes or ByteArray\n :return: Encoding as string\n \"\"\"\n try:\n return chardet.detect(raw_data)['encoding']\n except Exception as e:\n self.log.critical(\"Something went wrong with detecting encoding:\" + str(e))\n\n async def get(self, req_resource: str, client=None) -> Tuple[any, int, str, str] or Tuple[bool, None, None, None]:\n \"\"\"Tries to read the requested resource from either disk or cache\n\n :param req_resource: Path to requested resource as string\n :param client: Client who tried to access the resource, only used for logging.\n :return: file_contents, content_length || False, None\n \"\"\"\n if path.isfile(req_resource):\n self.log.debug(\"{} {} {}\".format(client, \"Accessed:\", req_resource))\n _, file_extension = path.splitext(req_resource)\n cached_resource = self.cache.get(req_resource) # Try to read the resource from cache\n if cached_resource is None: # If resource was not in cache\n self.log.debug(\"{} Loaded from disk\".format(req_resource))\n async with aiofiles.open(req_resource, mode='r') as resource: # Read the resource from the disk\n data = await resource.read()\n with self.cache as reference: # Store the resource in the cache\n reference.set(req_resource, data)\n else: # If resource was in the cache\n self.log.debug(\"{} Loaded from cache\".format(req_resource))\n data = cached_resource\n content_length = len(data.encode()) # Get content_length from the content\n return data, content_length, match_mime_type(file_extension), await self.detect_encoding(data.encode())\n else:\n return False, None, None, None\n","repo_name":"math280h/quick-serve","sub_path":"quick_serve/modules/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"38757499124","text":"def get_information_gain(entrophy_values, class_entrophy):\n info = dict()\n for attribute, entrophy in entrophy_values.items():\n column_elements = entrophy.pop(\"count\")\n for k, v in entrophy.items():\n if attribute not in info:\n info[attribute] = 0\n info[attribute] += v[\"count\"] / column_elements * v[\"entrophy\"]\n # INFORMATION GAIN\n gain = dict()\n for k, v in info.items():\n gain[k] = class_entrophy[\"entrophy\"] - v\n return gain","repo_name":"noemiko/learning_systems","sub_path":"information_gain.py","file_name":"information_gain.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25544375146","text":"# Change every letter with next lexicographic alphabet\n\ndef findLexicographicAlpha(str):\n for i in str:\n if i=='z':\n print(\"a\",end=\"\")\n else:\n print(chr(ord(i)+1),end=\"\")\n\nif __name__==\"__main__\":\n string=input(\"Enter string:\")\n\n findLexicographicAlpha(string)","repo_name":"Ashvinibodade/TCS_code_questions","sub_path":"Problem87.py","file_name":"Problem87.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12606846973","text":"\"\"\"Learner dashboard views\"\"\"\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_GET\nfrom edx_rest_framework_extensions.auth.jwt.authentication import JwtAuthentication\nfrom rest_framework import permissions, status\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom lms.djangoapps.learner_dashboard.utils import masters_program_tab_view_is_enabled, is_enrolled_or_staff\nfrom common.djangoapps.edxmako.shortcuts import render_to_response\nfrom lms.djangoapps.learner_dashboard.programs import (\n ProgramDetailsFragmentView,\n ProgramDiscussionLTI,\n ProgramsFragmentView, ProgramLiveLTI\n)\nfrom lms.djangoapps.program_enrollments.rest_api.v1.utils import ProgramSpecificViewMixin\nfrom openedx.core.djangoapps.programs.models import ProgramsApiConfig\nfrom openedx.core.lib.api.authentication import BearerAuthentication\n\n\n@login_required\n@require_GET\ndef program_listing(request):\n \"\"\"View a list of programs in which the user is engaged.\"\"\"\n programs_config = ProgramsApiConfig.current()\n programs_fragment = ProgramsFragmentView().render_to_fragment(request, programs_config=programs_config)\n\n context = {\n 'disable_courseware_js': True,\n 'programs_fragment': programs_fragment,\n 'nav_hidden': True,\n 'show_dashboard_tabs': True,\n 'show_program_listing': programs_config.enabled,\n 'uses_bootstrap': True,\n }\n\n return render_to_response('learner_dashboard/programs.html', context)\n\n\n@login_required\n@require_GET\ndef program_details(request, program_uuid):\n \"\"\"View details about a specific program.\"\"\"\n programs_config = ProgramsApiConfig.current()\n program_fragment = ProgramDetailsFragmentView().render_to_fragment(\n request, program_uuid, programs_config=programs_config\n )\n\n context = {\n 'program_fragment': program_fragment,\n 'show_program_listing': programs_config.enabled,\n 'show_dashboard_tabs': True,\n 'nav_hidden': True,\n 'disable_courseware_js': True,\n 'uses_bootstrap': True,\n }\n\n return render_to_response('learner_dashboard/program_details.html', context)\n\n\nclass ProgramDiscussionIframeView(APIView, ProgramSpecificViewMixin):\n \"\"\"\n A view for retrieving Program Discussion IFrame .\n\n Path: ``/dashboard/programs/{program_uuid}/discussion/``\n\n Accepts: [GET]\n\n ------------------------------------------------------------------------------------\n GET\n ------------------------------------------------------------------------------------\n\n **Returns**\n\n * 200: OK - Contains a program discussion iframe.\n * 401: The requesting user is not authenticated.\n * 403: The requesting user lacks access to the program.\n * 404: The requested program does not exist.\n\n **Response**\n\n In the case of a 200 response code, the response will be iframe HTML and status if discussion is configured\n for the program.\n\n **Example**\n\n {\n 'tab_view_enabled': True,\n 'discussion': {\n \"iframe\": \"\n \n \",\n \"configured\": false\n }\n }\n\n \"\"\"\n authentication_classes = (JwtAuthentication, BearerAuthentication, SessionAuthentication)\n permission_classes = (permissions.IsAuthenticated,)\n\n def get(self, request, program_uuid):\n \"\"\" GET handler \"\"\"\n if not is_enrolled_or_staff(request, program_uuid):\n default_response = {\n 'tab_view_enabled': False,\n 'discussion': {\n 'configured': False,\n 'iframe': ''\n }\n }\n return Response(default_response, status=status.HTTP_200_OK)\n program_discussion_lti = ProgramDiscussionLTI(program_uuid, request)\n response_data = {\n 'tab_view_enabled': masters_program_tab_view_is_enabled(),\n 'discussion': {\n 'iframe': program_discussion_lti.render_iframe(),\n 'configured': program_discussion_lti.is_configured,\n }\n }\n return Response(response_data, status=status.HTTP_200_OK)\n\n\nclass ProgramLiveIframeView(APIView, ProgramSpecificViewMixin):\n \"\"\"\n A view for retrieving Program live IFrame .\n\n Path: ``/dashboard/programs/{program_uuid}/live/``\n\n Accepts: [GET]\n\n ------------------------------------------------------------------------------------\n GET\n ------------------------------------------------------------------------------------\n\n **Returns**\n\n * 200: OK - Contains a program live zoom iframe.\n * 401: The requesting user is not authenticated.\n * 403: The requesting user lacks access to the program.\n * 404: The requested program does not exist.\n\n **Response**\n\n In the case of a 200 response code, the response will be iframe HTML and status if discussion is configured\n for the program.\n\n **Example**\n\n {\n 'tab_view_enabled': True,\n 'live': {\n \"iframe\": \"\n \n \",\n \"configured\": false\n }\n }\n\n \"\"\"\n authentication_classes = (JwtAuthentication, BearerAuthentication, SessionAuthentication)\n permission_classes = (permissions.IsAuthenticated,)\n\n def get(self, request, program_uuid):\n \"\"\" GET handler \"\"\"\n if not is_enrolled_or_staff(request, program_uuid):\n default_response = {\n 'tab_view_enabled': False,\n 'live': {\n 'configured': False,\n 'iframe': ''\n }\n }\n return Response(default_response, status=status.HTTP_200_OK)\n program_live_lti = ProgramLiveLTI(program_uuid, request)\n response_data = {\n 'tab_view_enabled': masters_program_tab_view_is_enabled(),\n 'live': {\n 'iframe': program_live_lti.render_iframe(),\n 'configured': program_live_lti.is_configured,\n }\n }\n return Response(response_data, status=status.HTTP_200_OK)\n","repo_name":"openedx/edx-platform","sub_path":"lms/djangoapps/learner_dashboard/program_views.py","file_name":"program_views.py","file_ext":"py","file_size_in_byte":6845,"program_lang":"python","lang":"en","doc_type":"code","stars":6774,"dataset":"github-code","pt":"3"}
+{"seq_id":"39829679246","text":"# pattern all but current one -> prefix and sufix\n# for loop to build prefix and sufix \n# 1 or 0 = 1, prefill with 0s\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n prefix, sufix = [0]*len(nums), [0]*len(nums)\n prefix[0], sufix[-1] = nums[0], nums[-1]\n for i in range(1, len(nums)): \n prefix[i] = prefix[i-1]|nums[i-1]\n for i in range(len(nums)-2, -1, -1): \n sufix[i] = sufix[i+1]|nums[i+1]\n prefix[0], sufix[-1] = 0, 0\n factor = 2**k \n result = 0\n for i in range(0, len(nums)): \n curr = nums[i]*factor \n result = max(result, curr|prefix[i]|sufix[i])\n return result\n","repo_name":"MaTasty/Grind","sub_path":"maximumOr.py","file_name":"maximumOr.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21771206295","text":"n = int(input())\ninf = 1e14\n\nsus = []\njos = []\ndreapta = []\nstanga = []\n\nfor i in range(n):\n x = input().split()\n a = float(x[0])\n b = float(x[1])\n c = float(x[2])\n\n if b > 0:\n jos.append(-c/b)\n if b < 0:\n sus.append(-c/b)\n if b == 0:\n if a > 0:\n stanga.append(-c/a)\n else:\n dreapta.append(-c/a)\n\nsus.sort()\njos.sort()\ndreapta.sort()\nstanga.sort()\n\ndef find_upper(st, dr, x, v):\n if st > dr:\n return inf\n\n mij = int((st + dr) / 2)\n\n if x < v[mij]:\n aux = find_upper(st, mij - 1, x, v)\n if mij < aux:\n return mij\n else:\n return aux\n\n return find_upper(mij + 1, dr, x, v)\n\n\ndef find_lower(st, dr, x, v):\n if st > dr:\n return -inf\n\n mij = int((st + dr) / 2)\n\n if x > v[mij]:\n aux = find_lower(mij + 1, dr, x, v)\n if mij > aux:\n return mij\n else:\n return aux\n\n return find_lower(st, mij - 1, x, v)\n\nm = int(input())\n\nfor i in range(m):\n x = input().split()\n a = float(x[0])\n b = float(x[1])\n\n\n c = find_upper(0, len(jos) - 1, b, jos)\n d = find_lower(0, len(sus) - 1, b, sus)\n e = find_upper(0, len(stanga) - 1, a, stanga)\n f = find_lower(0, len(dreapta) - 1, a, dreapta)\n\n if c == inf or e == inf or d == -inf or f == -inf:\n print(\"NO\")\n else:\n print(\"YES\")\n\n\n lungime = jos[c] - sus[d]\n latime = stanga[e] - dreapta[f]\n\n print(\"{:.6f}\".format(lungime * latime))\n\n\n# print(sus)\n# print(jos)\n# print(stanga)\n# print(dreapta)","repo_name":"IoanaLivia/Geometric-Algorithms","sub_path":"AA_Lab_7/72.py","file_name":"72.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17892818182","text":"from random import randint\nfrom random import uniform\n\n\nL_LIMIT = -1000\nH_LIMIT = 1000\n\ndef func(lines: int, file_name: str):\n with open(file_name, 'a+') as file:\n for _ in range(lines):\n a = randint(L_LIMIT ,H_LIMIT)\n b = uniform(L_LIMIT, H_LIMIT)\n file.write(f'{a:>4} | {b}\\n')\n\nfunc(10, 'test_file')","repo_name":"ilyushqal33t/python_new_hw","sub_path":"hw_7/new_package/sem_task_1.py","file_name":"sem_task_1.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30941203705","text":"#!/usr/bin/env pybricks-micropython\n\nfrom pybricks import ev3brick as brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import (Port, Stop, Direction, Button, Color,\n SoundFile, ImageFile, Align)\nfrom pybricks.tools import print, wait, StopWatch\nfrom pybricks.robotics import DriveBase\nfrom time import sleep\n \n# Write your program here\nbrick.sound.beep()\n\nclaw = Motor(Port.D)\nlift = Motor(Port.C, Direction.COUNTERCLOCKWISE, [8, 40])\nturn = Motor(Port.B, Direction.CLOCKWISE, [11, 40])\nrot_stop = TouchSensor(Port.S3)\ncol = ColorSensor(Port.S4)\n\ncolor_pallet = {1:\"Black\", 2:\"Blue\", 3:\"Green\", 4:\"Yellow\", 5:\"Red\", 6:\"White\", None:\"None\"}\n\nwhile True:\n claw.run(20) #Homeing lift\n sleep(3)\n claw.reset_angle(0)\n claw.run_target(100, -90)\n\n while col.color() != None: #Move lift to prepare for homing\n lift.run(25)\n lift.stop(Stop.HOLD)\n\n while col.color() == None: #Homeing lift\n lift.run(-25)\n lift.reset_angle(0)\n lift.stop(Stop.HOLD)\n\n while not rot_stop.pressed():#Homeing rot\n turn.run(128)\n\n if rot_stop.pressed(): #Saftey for the button is realt pressed\n turn.reset_angle(0) #Home aka at zero position\n turn.run_target(128, -23) #Moves to where block is\n turn.reset_angle(0) #New home, because it is the intresting position\n\n lift.run_target(25, -25) #Lowers arm to the block\n sleep(1) \n\n claw.run(255) #Closes the claw with maximum force\n sleep(1)\n claw.stop(Stop.HOLD) #Holds the block\n\n lift.run_target(25, 15) #Lifts block to sensor\n lift.stop(Stop.HOLD) #Holds arm so block is at sensor height\n\n sleep(2)\n print(color_pallet[col.color()]) #Scans and prints color of block\n\n sleep(1)\n\n lift.run_target(255, 30) \n turn.run_target(255, -90) #Rotates arm for new blockposition\n lift.run_target(25, -25) #Lowers block\n\n sleep(1)\n claw.stop(Stop.COAST) #Release block\n\n\n\n ","repo_name":"jonathantfogel/ict_inlamning1_lego","sub_path":"robot_arm_del1.py","file_name":"robot_arm_del1.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"40091131185","text":"\"\"\" \nUtility functions for creating the names lists used to run the NER task.\n\nBuilds on early versions of the codebase developed for the following publication: \n\nTitle: “Detecting intersectionality in NER models: A data-driven approach.”\nAuthors: Lassen, I. M., Almasi, M., Enevoldsen, K., & Kristensen-mclachlan, R. \nDate: 2023\nCode availability: https://github.com/centre-for-humanities-computing/Danish-NER-bias\n\"\"\"\nimport os\nfrom pathlib import Path\n\nimport pandas as pd\nfrom dacy.datasets import load_names, muslim_names\n\ndef remove_duplicates(all_names, names_to_filter_away):\n all_names = [name for name in all_names if name not in names_to_filter_away]\n return all_names\n\n# path to names files \ndata_folder = os.path.join(Path(__file__).parents[1], \"data\",\"name_aug_csv_files\") \n\n### Define majority/danish names\n\n# get last names \nlast_names_2023 = pd.read_csv(os.path.join(data_folder, \"last_names_2023.csv\"))\nlast_names_2023[\"Navn\"] = last_names_2023[\"Navn\"].str.title() # capitalize\nlast_names_2023 = list(last_names_2023[\"Navn\"])[:500] # subset to only 500 to match 500 first names\n\n# men and women first names\nmen_2023 = pd.read_csv(os.path.join(data_folder, \"first_names_2023_men.csv\"))\nwomen_2023 = pd.read_csv(os.path.join(data_folder, \"first_names_2023_women.csv\"))\n\n# capitalize\nmen_2023[\"Navn\"] = men_2023[\"Navn\"].str.title()\nwomen_2023[\"Navn\"] = women_2023[\"Navn\"].str.title()\n\n# subset names to 500 \nmen_2023 = list(men_2023[\"Navn\"])[:500]\nwomen_2023 = list(women_2023[\"Navn\"])[:500]\n\n# create dictionaries \nm_name_dict = {'first_name':men_2023, 'last_name':last_names_2023}\nf_name_dict = {'first_name':women_2023, 'last_name':last_names_2023}\n\n### Define muslim/minority names \nmuslim_name_dict = muslim_names()\nmuslim_m_dict = load_names(ethnicity=\"muslim\", gender=\"male\", min_prop_gender=0.5)\nmuslim_f_dict = load_names(ethnicity=\"muslim\", gender=\"female\", min_prop_gender=0.5)\n\n### Remove overlaps \n# read in annotated\noverlaps = pd.read_csv(os.path.join(data_folder, \"overlapping_names.csv\"))\n\n# create muslim/minority only list and majority/danish only list \nmuslim_only=list(overlaps.query(\"origin=='M'\")[\"duplicates\"])\ndanish_only=list(overlaps.query(\"origin=='DK'\")[\"duplicates\"])\n\n# majority/danish seperate genders into seperate dicts\nf_name_dict[\"first_name\"] = remove_duplicates(f_name_dict[\"first_name\"], muslim_only)\nm_name_dict[\"first_name\"] = remove_duplicates(m_name_dict[\"first_name\"], muslim_only)\n\n# muslim/minority seperate genders into seperate dicts\nmuslim_f_dict[\"first_name\"] = remove_duplicates(muslim_f_dict[\"first_name\"], danish_only)\nmuslim_m_dict[\"first_name\"] = remove_duplicates(muslim_m_dict[\"first_name\"], danish_only)\n","repo_name":"DaDebias/genda-lens","sub_path":"genda_lens/ner_tasks/process_names.py","file_name":"process_names.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"70557079121","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 27 10:40:46 2018\r\n\r\n@author: lenovo\r\n\"\"\"\r\n\r\nimport cal_networkx_eigenvalue as nxfeature\r\nimport cal_information as nxinfo\r\nimport time\r\nimport xlwt\r\nimport os\r\n\r\n\r\nif __name__ == '__main__':\r\n start = time.time()\r\n if os.path.exists('./information/wuhan.xls'):\r\n os.remove('./information/wuhan.xls')\r\n workbook = xlwt.Workbook()\r\n table = workbook.add_sheet('Sheet1')\r\n table.write(0,0,'角度阈值')\r\n table.write(0,1,'信息量')\r\n table.write(0,2,'度权重')\r\n table.write(0,3,'邻近中心性权重')\r\n table.write(0,4,'中介中心性权重')\r\n table.write(0,5,'长度权重')\r\n file_num = 90\r\n shp_names,xls_names,info_param_names = nxfeature.create_file_name(file_num)\r\n for i in range(file_num):\r\n nodes,length = nxfeature.get_networkx_nodes(shp_names[i])\r\n edges = nxfeature.get_networkx_edges(xls_names[i])\r\n G = nxfeature.structure_graph_G(nodes,edges)\r\n print(\"{} 正在计算第{}个路网的特征值\".format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),i+1))\r\n feature_tab = nxfeature.cal_networkx_feature(G,length)\r\n print(\"{} 正在写入第{}个路网的特征值\".format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),i+1))\r\n nxfeature.write2excel(feature_tab,info_param_names[i])\r\n print(\"{} 正在计算第{}个路网的信息量\".format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),i+1))\r\n info,w = nxinfo.cal_information(info_param_names[i])\r\n print(\"{} 正在写入第{}个路网的信息量\".format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),i+1))\r\n table.write(i+1,0,i+1)\r\n table.write(i+1,1,info)\r\n table.write(i+1,2,w[0])\r\n table.write(i+1,3,w[1])\r\n table.write(i+1,4,w[2])\r\n table.write(i+1,5,w[3])\r\n workbook.save('./information/wuhan.xls')\r\n end = time.time()\r\n print(\"{} 写入excel完成,运行时间为{}s\".format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),end-start))\r\n\t","repo_name":"YoungTshenHsi/Stroke","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"4725152516","text":"import numpy as np\nimport itertools\nimport re\nimport sys\nsys.path.insert(0, '/')\nrg = __import__(\"reel generator\")\n\ndef sought(dictionary, string):\n K = list(dictionary.keys())[:]\n for i in range(len(K)):\n prob = re.compile(K[i], re.IGNORECASE)\n if prob.search(string):\n return dictionary[K[i]]\n return None\n\n\nclass Wild:\n def __init__(self, interim, type, i):\n self.multiplier = 1\n if \"multiplier\" in interim[\"symbol\"][i][type][\"wild\"]:\n self.multiplier = interim[\"symbol\"][i][type][\"wild\"][\"multiplier\"]\n self.expand = interim[\"symbol\"][i][type][\"wild\"].get(\"expand\")\n self.substitute = []\n\n\nclass Symbol:\n def __init__(self, interim, type, i, w):\n self.name = interim[\"symbol\"][i][\"name\"]\n self.payment = [0]*(w+1)\n for j in range(len(interim[\"symbol\"][i][\"payment\"])):\n self.payment[interim[\"symbol\"][i][\"payment\"][j][0]] = interim[\"symbol\"][i][\"payment\"][j][1]\n\n self.substituted_by = []\n self.substituted_by_e = []\n if type in interim[\"symbol\"][i]:\n if \"direction\" in interim[\"symbol\"][i][type]:\n self.direction = interim[\"symbol\"][i][type][\"direction\"]\n else:\n self.direction = \"left\"\n if \"position\" in interim[\"symbol\"][i][type]:\n self.position = interim[\"symbol\"][i][type][\"position\"][:]\n self.position[:] = [x - 1 for x in self.position]\n else:\n self.position = np.arange(0, w, 1)\n if str(interim[\"symbol\"][i][type].get(\"scatter\")) == \"0\":\n self.scatter = [0] * (w + 1)\n else:\n if interim[\"symbol\"][i][type].get(\"scatter\"):\n self.scatter = [0] * (w + 1)\n for j in range(len(interim[\"symbol\"][i][type][\"scatter\"])):\n self.scatter[interim[\"symbol\"][i][type][\"scatter\"][j][0]] = interim[\"symbol\"][i][type][\"scatter\"][j][1]\n else:\n self.scatter = interim[\"symbol\"][i][type].get(\"scatter\")\n\n if \"wild\" in interim[\"symbol\"][i][type]:\n self.wild = Wild(interim, type, i)\n else:\n self.wild = False\n else:\n self.direction = \"left\"\n self.position = np.arange(0, w, 1)\n self.scatter = False\n self.wild = False\n\n\nclass Gametype:\n def __init__(self, interim, type, w):\n self.symbol = [None] * len(interim[\"symbol\"])\n for i in range(len(interim[\"symbol\"])):\n if type in interim[\"symbol\"][i]:\n self.symbol[i] = Symbol(interim, type, i, w)\n else:\n self.symbol[i] = Symbol(interim, 'base', i, w)\n self.wildlist = []\n self.ewildlist = []\n self.scatterlist = []\n\n def wildlists(self):\n for i in range(len(self.symbol)):\n if self.symbol[i].wild:\n if self.symbol[i].wild.expand:\n self.ewildlist.append(i)\n else:\n self.wildlist.append(i)\n\n def scatterlists(self):\n for i in range(len(self.symbol)):\n if self.symbol[i].scatter:\n self.scatterlist.append(i)\n\n def transsubst(self, interim, type, i):\n if \"substitute\" in interim[\"symbol\"][i][type][\"wild\"]:\n self.symbol[i].wild.substitute.append(i)\n for j in range(len(interim[\"symbol\"][i][type][\"wild\"][\"substitute\"])):\n for k in range(len(interim[\"symbol\"])):\n if interim[\"symbol\"][i][type][\"wild\"][\"substitute\"][j] == interim[\"symbol\"][k][\"name\"]:\n self.symbol[i].wild.substitute.append(k)\n else:\n for j in range(len(self.symbol)):\n if not self.symbol[j].scatter:\n self.symbol[i].wild.substitute.append(j)\n\n def substituted_by(self):\n for i in range(len(self.symbol)):\n for j in self.wildlist:\n if i in self.symbol[j].wild.substitute and i != j:\n self.symbol[i].substituted_by.append(j)\n\n def substituted_by_e(self):\n for i in range(len(self.symbol)):\n for j in self.ewildlist:\n if i in self.symbol[j].wild.substitute and i != j:\n self.symbol[i].substituted_by_e.append(j)\n\n def combination_value(self, i, comb):\n return self.symbol[i].payment[comb]\n\n def combination_freespins(self, i, comb):\n if self.symbol[i].scatter:\n return self.symbol[i].scatter[comb]\n else:\n return 0\n\n\nclass Game:\n def __init__(self, interim):\n\n if \"window\" in interim:\n self.window = interim[\"window\"][:]\n else:\n self.window = [5, 3]\n\n self.base = Gametype(interim, 'base', self.window[0])\n self.free = Gametype(interim, 'free', self.window[0])\n\n self.line = interim[\"lines\"][:]\n\n if \"free_multiplier\" in interim:\n self.free_multiplier = interim[\"free_multiplier\"]\n else:\n self.free_multiplier = 1\n\n if \"distance\" in interim:\n self.distance = interim[\"distance\"]\n else:\n self.distance = self.window[1]\n\n self.RTP = interim.get(\"RTP\")\n self.volatility = interim.get(\"volatility\")\n self.hitrate = interim.get(\"hitrate\")\n self.baseRTP = interim.get(\"baseRTP\")\n self.borders = interim.get(\"borders\")\n self.weights = interim.get(\"weights\")\n\n self.base.wildlists()\n self.base.scatterlists()\n\n self.free.wildlists()\n self.free.scatterlists()\n\n # заполнение массива substitute для каждого вайлда из обычной игры\n for i in itertools.chain(self.base.wildlist, self.base.ewildlist):\n self.base.transsubst(interim, 'base', i)\n\n # заполнение массива substitute для каждого вайлда из бесплатной игры\n for i in itertools.chain(self.free.wildlist, self.free.ewildlist):\n if \"free\" in interim[\"symbol\"][i]:\n self.free.transsubst(interim, 'free', i)\n else:\n self.free.symbol[i].wild.substitute = self.base.symbol[i].wild.substitute\n\n # для каждого символа создание и заполнение массива индексов неэкспандящихся вайлдов, заменяющих данный символ\n self.base.substituted_by()\n\n # для каждого символа создание и заполнение массива индексов экспандящихся вайлдов, заменяющих данный символ\n self.base.substituted_by_e()\n\n # для каждого символа создание и заполнение массива индексов неэкспандящихся вайлдов, заменяющих данный символ\n self.free.substituted_by()\n\n # для каждого символа создание и заполнение массива индексов экспандящихся вайлдов, заменяющих данный символ\n self.free.substituted_by_e()\n\n def all_combinations(self, reel):\n c = 1\n for i in range(len(reel)):\n c = c * len(reel[i])\n return c\n\n def freemean(self):\n s = 0\n v = 0\n for i in range(len(self.free.symbol)):\n for comb in range(1, self.window[0] + 1):\n s = s + (rg.count_combination(game, line, self.free.symbol[i], comb, names) / self.all_combinations(reel)) \\\n * self.free.combination_value(i, comb) * self.free_multiplier\n for i in self.free.scatterlist:\n for comb in range(1, self.window[0] + 1):\n v = v + (rg.count_combination(game, line, self.free.symbol[i], comb, names) / self.all_combinations(reel)) * self.free.combination_freespins(i, comb)\n return s * 1.0 / (1 - v)\n\n def RTP(self):\n s = 0\n for i in range(len(self.base.symbol)):\n for comb in range(1, self.window[0] + 1):\n s = s + (rg.count_combination(game, line, self.free.symbol[i], comb, names) / self.all_combinations(reel)) \\\n * (self.base.combination_value(i, comb) + self.base.combination_freespins(i, comb) * freemean())\n return s\n\n def volatility(self):\n s = 0\n for i in range(len(self.base.symbol)):\n for comb in range(1, self.window[0] + 1):\n s = s + (rg.count_combination(game, line, self.free.symbol[i], comb, names) / self.all_combinations(reel)) * (\n self.base.combination_value(i, comb) + self.base.combination_freespins(i,\n comb) * freemean())**2\n return np.sqrt(s - self.RTP()**2)\n\n def hitrate(self):\n s = 0\n for i in self.base.scatterlist:\n for comb in range(len(self.base.symbol[i].scatter)):\n if self.base.symbol[i].scatter[comb] > 0:\n s = s + rg.count_combination(game, line, self.free.symbol[i], comb, names)\n return s / self.all_combinations(reel)\n\n def baseRTP(self):\n s = 0\n for i in range(len(self.base.symbol)):\n for comb in range(1, self.window[0] + 1):\n s = s + (rg.count_combination(game, line, self.free.symbol[i], comb, names) / self.all_combinations(reel)) * self.base.combination_value(i, comb)\n return s\n\n","repo_name":"DmitryBol/reel","sub_path":"archive/Front-end/structure_beta.py","file_name":"structure_beta.py","file_ext":"py","file_size_in_byte":9711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14747887984","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom sg2layout import *\nfrom layout2im import RefineModule, RefineNetwork\n\n\nclass Sg2Image(nn.Module):\n def __init__(self, num_objects, num_predicates):\n super(Sg2Image, self).__init__()\n self.obj_embeddings = nn.Embedding(num_objects, 128)\n self.pred_embeddings = nn.Embedding(num_predicates, 128)\n\n self.graphconv = GraphConvNetwork()\n self.box = BoxNetwork()\n self.mask = MaskNetwork()\n self.refine = RefineNetwork()\n\n def forward(self, object_indexs, triples, obj2img, boxes_true=None, masks_true=None):\n\n O = object_indexs.size(0)\n s, p, o = triples.chunk(3, dim=1)\n s, p, o = [x.squeeze(1) for x in [s, p, o]]\n edges = torch.stack([s, o], dim=1)\n\n things = self.obj_embeddings(object_indexs)\n predicates = self.pred_embeddings(p)\n\n things, predicates = self.graphconv(things, predicates, edges)\n boxes_pred = self.box(things)\n\n masks_pred = self.mask(things.view(O, 128, 1, 1))\n masks_pred = masks_pred.squeeze(1).sigmoid()\n\n boxes = boxes_pred if boxes_true is None else boxes_true\n masks = masks_pred if masks_true is None else masks_true\n\n layout = cast(things, boxes, masks, obj2img)\n imgs_pred = self.refine(layout)\n\n return imgs_pred, boxes_pred, masks_pred\n","repo_name":"wunaicheng/A-implement-of-scene-graph-image-generation-network","sub_path":"Network/sg2im.py","file_name":"sg2im.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"10041143798","text":"#!/usr/bin/env python\nimport rospy\nfrom benthic_species_detector import BenthicSpeciesDetector\nfrom std_msgs.msg import UInt8, UInt8MultiArray, MultiArrayDimension, MultiArrayLayout\nfrom sensor_msgs.msg import Image\n\n\nclass ShapeDetector:\n def __init__(self):\n self.species_detector = BenthicSpeciesDetector(rect_similarity_alpha=0.1, rect_enclosure_alpha=0.1,\n shape_alpha=0.1, corner_min_distance=10)\n self.species_pub = rospy.Publisher('species', UInt8MultiArray, queue_size=5)\n\n def detect_and_publish(self, image):\n shapes_list = self.species_detector.process(image, image_scaling_factor=0.6, debug=False)\n species_counts = [x * 0 for x in range(0, 4)]\n for shape_info in shapes_list:\n shape_type = shape_info[1][0]\n if shape_type == species_detector.ShapeType.triangle:\n species_counts[0] += 1\n elif shape_type == species_detector.ShapeType.rectangle:\n species_counts[1] += 1\n elif shape_type == species_detector.ShapeType.square:\n species_counts[2] += 1\n elif shape_type == species_detector.ShapeType.circle:\n species_counts[3] += 1\n species_counts = list(map(lambda count: UInt8(count), species_counts))\n species_msg = UInt8MultiArray(data=species_counts)\n species_pub.publish(species_msg)\n\n\nif __name__ == \"__main__\":\n rospy.init_node(\"ShapeDetector\")\n\n shape_detector = ShapeDetector()\n\n rospy.Subscriber(\"stereo_cam/left\", Image, shape_detector.detect_and_publish)\n\n rate = rospy.Rate(10)\n while not rospy.is_shutdown():\n rate.sleep()\n","repo_name":"Underwater-Robotics-Arizona-State/MATE19","sub_path":"robotside/src/shape_detector_node.py","file_name":"shape_detector_node.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17488624074","text":"from django.contrib import messages\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\n\nfrom apps.ldap.utils import add_officer, is_officer, is_root\n\nfrom .forms import OfficerCreationForm\nfrom .models import (\n Officer,\n Officership,\n Person,\n Politburo,\n PolitburoMembership,\n Semester,\n)\n\n\n@staff_member_required\ndef update_or_create_officer(request):\n semester = Semester.objects.filter(current=True).get()\n if request.method == \"POST\":\n form = OfficerCreationForm(request.POST, request.FILES)\n if form.is_valid():\n username = form.cleaned_data.get(\"username\")\n blurb = form.cleaned_data.get(\"blurb\")\n office_hours = form.cleaned_data.get(\"office_hours\")\n photo = form.cleaned_data.get(\"photo\")\n photo_url = form.cleaned_data.get(\"photo_url\")\n photo2 = form.cleaned_data.get(\"photo2\")\n photo2_url = form.cleaned_data.get(\"photo2_url\")\n officer_since = form.cleaned_data.get(\"officer_since\")\n _update_or_create_officer(\n request,\n username,\n photo,\n photo_url,\n photo2,\n photo2_url,\n officer_since,\n blurb,\n office_hours,\n semester,\n )\n return HttpResponseRedirect(reverse(\"add-officer\"))\n else:\n form = OfficerCreationForm()\n\n return render(request, \"add_officer.html\", {\"form\": form, \"semester\": semester})\n\n\ndef _update_or_create_officer(\n request,\n username,\n photo,\n photo_url,\n photo2,\n photo2_url,\n officer_since,\n blurb,\n office_hours,\n semester,\n):\n user, created = User.objects.get_or_create(username=username)\n if created:\n messages.info(request, f\"User {username} created\")\n\n defaults = {}\n if photo:\n messages.info(request, f\"Updated photo1 for {username}\")\n defaults.update(photo1=photo)\n elif photo_url:\n ...\n # TODO: download photo\n messages.warning(request, \"Using photo_url is not yet supported\")\n if photo2:\n messages.info(request, f\"Updated photo2 for {username}\")\n defaults.update(photo2=photo)\n elif photo2_url:\n ...\n # TODO: download photo\n messages.warning(request, \"Using photo2_url is not yet supported\")\n person, created = Person.objects.update_or_create(user=user, defaults=defaults)\n person.save()\n if created:\n messages.info(request, f\"Person {username} created\")\n\n root_staff = is_root(username)\n defaults = {\"root_staff\": root_staff}\n if officer_since:\n defaults.update(officer_since=officer_since)\n messages.info(\n request, f\"Officer {username} start date updated to {officer_since}\"\n )\n officer, created = Officer.objects.update_or_create(\n person=person, defaults=defaults\n )\n if created:\n messages.info(request, f\"Officer {username} created\")\n\n defaults = {}\n if blurb:\n defaults.update(blurb=blurb)\n messages.info(request, f\"Updated blurb of {username}\")\n if office_hours:\n defaults.update(office_hours=office_hours)\n messages.info(request, f\"Office hour updated to {office_hours}\")\n officership = Officership.objects.update_or_create(\n officer=officer, semester=semester, defaults=defaults\n )\n\n if not is_officer(username):\n success, msg = add_officer(username)\n if success:\n messages.info(request, f\"Added {username} to officers LDAP group\")\n else:\n messages.error(\n request, f\"Failed to add {username} to officers LDAP group: {msg}\"\n )\n messages.info(request, f\"{username} updated\")\n\n\n@staff_member_required\ndef update_semester(request):\n semesters = Semester.objects.all()\n return render(request, \"update_semester.html\", {\"semesters\": semesters})\n","repo_name":"CSUA/csua-backend","sub_path":"apps/db_data/staff_views.py","file_name":"staff_views.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"3"}
+{"seq_id":"10676925296","text":"# coding: utf-8\r\n# 2021-05-17 Eastmount CSDN\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\n#读取原始图像\r\nimg = cv2.imread('test01.png')\r\n\r\n#图像灰度化处理\r\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n\r\n#图像阈值化处理\r\nret, thresh = cv2.threshold(gray, 0, 255, \r\ncv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\r\n\r\n#显示图像\r\ncv2.imshow('src', img)\r\ncv2.imshow('res', thresh)\r\ncv2.waitKey()\r\ncv2.destroyAllWindows()\r\n","repo_name":"eastmountyxz/ImageProcessing-Python","sub_path":"blog40-ImageSegmentation/blog40-09-fsl.py","file_name":"blog40-09-fsl.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":1547,"dataset":"github-code","pt":"3"}
+{"seq_id":"3337599241","text":"import datetime\n\nfrom Quality.Average.averageQuality import DAILY\nfrom Quality.Average.averageQualityManager import AverageQualityManager\nfrom qoimetric import QoIMetric\nfrom virtualisation.clock.abstractclock import AbstractClock\nfrom virtualisation.misc.log import Log as L\n\n\nclass ReputationSystem(object):\n \"\"\"docstring for ReputationSystem\"\"\"\n\n def __init__(self, description, clock):\n self.metrics = []\n self.setDescription(description)\n self.sinkList = []\n self.timestamp = None\n self.clock = clock\n self.jobID = None\n self.addClockJob()\n self.avgQoIManager = AverageQualityManager(description.updateInterval)\n\n def setClock(self, clock):\n if self.clock is not clock:\n self.clock = clock\n self.jobID = None # set to none because old jobs are not deleteable anymore\n\n def addClockJob(self, deleteOldJob=False):\n L.d2(\"ReputationSystem: addClockJob for Stream\", self.description.fullSensorID, \"with\", self.validationInterval)\n if deleteOldJob and self.jobID:\n self.clock.removeJob(self.jobID)\n self.jobID = self.clock.addJob(self.validationInterval, self.checkTimeRelevantMetrics, args=(self.timestamp),\n reoccurring=False)\n\n def setDescription(self, description):\n self.description = description\n # update validation interval\n self.validationInterval = self.description.updateInterval + self.description.updateInterval * 0.05 # add some extra time to avoid races\n\n def __del__(self):\n for m in self.metrics:\n del m\n for sink in self.sinkList:\n del sink\n\n def setSink(self, sink):\n sink.reputationsystem = self\n self.sink = sink\n\n def addSink(self, sink):\n sink.reputationsystem = self\n self.sinkList.append(sink)\n\n def addQoIMetric(self, qoiMetric):\n if not isinstance(qoiMetric, QoIMetric):\n raise Exception(\"not a QoIMetric\")\n qoiMetric.repsys = self\n self.metrics.append(qoiMetric)\n for sink in self.sinkList:\n sink.qoiMetricAdded(qoiMetric.name, qoiMetric.initialValue)\n self.avgQoIManager.addQoIMetric(qoiMetric)\n\n def update(self, data):\n L.d2(\"ReputationSystem: update called for Stream\", self.description.fullSensorID)\n self.setTimestamp(data)\n returnValues = {}\n if data is not None:\n for m in self.metrics:\n value = m.update(data)\n if value:\n returnValues[value[0]] = value[1]\n for sink in self.sinkList:\n sink.update(m)\n self.addClockJob(True)\n self.avgQoIManager.calculateAvgQualities(returnValues)\n return returnValues\n \n def persist(self, observationIdList):\n for sink in self.sinkList:\n sink.persist(observationIdList)\n\n def checkTimeRelevantMetrics(self, lastUpdate):\n L.d(\"ReputationSystem: checkTimeRelevantMetrics called for Stream\", self.description.fullSensorID)\n L.d(\"ReputationSystem:\", lastUpdate, self.timestamp)\n if (lastUpdate is not None) and (lastUpdate == self.timestamp): # check if there was an update in the meanwhile\n L.d(\"ReputationSystem: There was no update, lets punish!\")\n qoiValues = {}\n for metric in self.metrics:\n value = metric.nonValueUpdate()\n if value:\n qoiValues[value[0]] = value[1]\n \n self.avgQoIManager.calculateAvgQualities(qoiValues)\n self.addClockJob()\n\n def setTimestamp(self, data):\n if len(data.fields) != 0:\n self.timestamp = datetime.datetime.strptime(data[data.fields[0]].observationResultTime, AbstractClock.parserformat)\n\n","repo_name":"CityPulse/Resource-Manager","sub_path":"Quality/AtomicComputation/reputationsystem/repsys.py","file_name":"repsys.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"37897304465","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPycharm Editor\nCreate by zhwei \nPython:3.7.0\n\"\"\"\n\nimport pandas as pd\nfrom pathlib import Path\nimport joblib\nfrom Features import all_feature\nimport numpy as np\n\nth = 0.5 #阈值\nclf_feature_order = [\"AAC\",\"AAI\",\"CT5\",\"CTD\",\"DPC\",\"GAAC\",\"GDPC\",\"NT5\",\"PAAC\"]\n\n\ndef get_base_proba(test_features,feature_index):\n test_features = test_features.values\n base_feature = []\n for idx,clf in zip(feature_index,clf_feature_order):\n features = test_features[:,idx]\n model = joblib.load(f'./Models/BaseModel/{clf}.m')\n base_proba = model.predict_proba(features)[:,-1]\n base_feature.append(base_proba)\n return np.array(base_feature).T\n\n\ndef Model_pred(fastafile,timestamp,Result_PATH):\n test_full_features, feature_index = all_feature(fastafile)\n base_feature = get_base_proba(test_full_features,feature_index)\n meta_clf = joblib.load('./Models/MetaModel/META.m')\n result = meta_clf.predict_proba(base_feature)[:,-1]\n\n\n df = pd.DataFrame(list(zip(list(test_full_features.index), list(result))))\n df.columns = ['Name','Probability']\n df[\"Class\"] = df[\"Probability\"].apply(lambda x: \"APP\" if x >=th else \"non-APP\") #根据阈值划定\n resultfile = Path(Result_PATH).joinpath(str(timestamp) + '.csv')\n df.to_csv(resultfile, index=False, header=True)\n return resultfile\n\n\nif __name__ == '__main__':\n pass","repo_name":"xialab-ahu/PredAPP","sub_path":"PredAPP.py","file_name":"PredAPP.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23846993217","text":"class Graph:\n \"\"\"\n A class representing graphs as adjacency lists and implementing various algorithms on the graphs. Graphs in the class are not oriented. \n Attributes: \n -----------\n nodes: NodeType\n A list of nodes. Nodes can be of any immutable type, e.g., integer, float, or string.\n We will usually use a list of integers 1, ..., n.\n graph: dict\n A dictionnary that contains the adjacency list of each node in the form\n graph[node] = [(neighbor1, p1, d1), (neighbor2, p2, d2), ...]\n where p1 is the minimal power on the edge (node, neighbor1) and d1 is the distance on the edge\n nb_nodes: int\n The number of nodes.\n nb_edges: int\n The number of edges. \n \"\"\"\n\n def __init__(self, nodes=[]):\n \"\"\"\n Initializes the graph with a set of nodes, and no edges. \n Parameters: \n -----------\n nodes: list, optional\n A list of nodes. Default is empty.\n \"\"\"\n self.nodes = nodes\n self.graph = dict([(n, []) for n in nodes])\n self.nb_nodes = len(nodes)\n self.nb_edges = 0\n \n\n def __str__(self):\n \"\"\"Prints the graph as a list of neighbors for each node (one per line)\"\"\"\n if not self.graph:\n output = \"The graph is empty\" \n else:\n output = f\"The graph has {self.nb_nodes} nodes and {self.nb_edges} edges.\\n\"\n for source, destination in self.graph.items():\n output += f\"{source}-->{destination}\\n\"\n return output\n \n def add_edge(self, node1, node2, power_min, dist=1):\n \"\"\"\n Adds an edge to the graph. Graphs are not oriented, hence an edge is added to the adjacency list of both end nodes. \n\n Parameters: \n -----------\n node1: NodeType\n First end (node) of the edge\n node2: NodeType\n Second end (node) of the edge\n power_min: numeric (int or float)\n Minimum power on this edge\n dist: numeric (int or float), optional\n Distance between node1 and node2 on the edge. Default is 1.\n \"\"\"\n if node1 not in self.graph:\n self.graph[node1] = []\n self.nb_nodes += 1\n self.nodes.append(node1)\n if node2 not in self.graph:\n self.graph[node2] = []\n self.nb_nodes += 1\n self.nodes.append(node2)\n\n self.graph[node1].append((node2, power_min, dist))\n self.graph[node2].append((node1, power_min, dist))\n self.nb_edges += 1\n \n\n def get_path_with_power(self, src, dest, power):\n raise NotImplementedError\n \n\n \"\"\"def comp(self,l,lb,lv):\n if lv==[]:\n return(l,lb)\n else: \n i=lv.pop()\n if lb[i-1]:\n lb[i-1]=False\n b=[a for (a,a2,a3) in self.graph[i]]\n l.append(i)\n lv+=b\n return(self.comp(l,lb,lv))\n \n def compco(self):\n n=self.nb_nodes\n lb=[True for i in range(n)]\n c=[]\n for k in range(1,n+1):\n l1,l2=self.comp([],lb,[k])\n lb=l2\n if l1!=[]:\n c.append(l1)\n return(c)\"\"\"\n \n def min_power(self, src, dest):\n \"\"\"\n Should return path, min_power. \n \"\"\"\n raise NotImplementedError\n\n\n def CCsommet(self,i):\n n=len(self.nodes)\n L=[]\n compconn=[0 for _ in range(n)]\n compconn[i-1]=1\n L+=self.graph[i]\n while L!=[]:\n voisin = L.pop(0)\n if compconn[voisin[0]-1]==0 :\n compconn[voisin[0]-1]=1\n L+=self.graph[voisin[0]] #ajout dans L des voisins de voisin\n return(compconn)\n def CConnexes(self):\n L=[]\n for i in self.nodes:\n L.append(self.CCsommet(i))\n Lsansdouble = [] \n for i in L : \n if i not in Lsansdouble: \n Lsansdouble.append(i) \n return(Lsansdouble)\n#3\n def get_path_with_power(self,p,t):\n i,j=t[0],t[1]\n n=self.nb_nodes()\n visit=[0 for _ in range(n)]\n cc=self.compco()\n for c in cc:\n if c.count(i)==1:\n if c.count(j)==0:\n return None\ndef graph_from_file(filename):\n with open(filename, \"r\") as file:\n n, m = map(int, file.readline().split())\n g = Graph(range(1, n+1))\n for _ in range(m):\n edge = list(map(int, file.readline().split()))\n if len(edge) == 3:\n node1, node2, power_min = edge\n g.add_edge(node1, node2, power_min) # will add dist=1 by default\n elif len(edge) == 4:\n node1, node2, power_min, dist = edge\n g.add_edge(node1, node2, power_min, dist)\n else:\n raise Exception(\"Format incorrect\")\n return g\n\n \n \n\n\n#TD2\n","repo_name":"EliasLaurent/ne-pas-lire3","sub_path":"delivery_network/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13694508286","text":"from tkinter import *\nfrom tkinter import messagebox\n\nroot = Tk()\nroot.title(\"Easy Ticket\")\nroot.geometry(\"600x600\")\nframe = Frame(root)\nroot.config(bg=\"#0d8f73\")\n\n# define variable set in class\nvariable = StringVar()\n# class\nclass ClsTicketSales:\n myresult = StringVar()\n variable.set(\"Select\")\n\n# defining clear button\n def clear(self):\n self.txt_cell.delete(0, END)\n self.spn_no_tics.delete(0, END)\n\n def __init__(self, window):\n # number info\n self.cell = Label(window, text=\"Cell Number\", bg=\"#0d8f73\")\n self.cell.pack()\n self.txt_cell = Entry(window)\n self.txt_cell.pack()\n # ticket options\n self.options = Label(window, text=\"Category\", bg=\"#0d8f73\")\n self.options.pack()\n self.tic_options = OptionMenu(window, variable, 'soccer', 'movie', 'theater')\n self.tic_options.pack()\n # number of tickets bought\n self.no_tics = Label(window, text=\"Number Of Tickets\", bg=\"#0d8f73\")\n self.no_tics.pack()\n self.spn_no_tics = Spinbox(window, from_=0, to=20)\n self.spn_no_tics.pack()\n # calculate button\n self.cal = Button(window, text=\"Calculate Price\", command=self.calc_prepayment)\n self.cal.pack()\n # clear button\n self.clear = Button(window, text=\"Clear Entries\", command=self.clear)\n self.clear.pack()\n self.CalcPrepayment = Entry(window)\n self.exit = Button(window, text=\"X\", command=\"exit\")\n self.exit.place(x=565, y=0)\n self.frame = Frame(window, width=\"100\", height=\"100\", relief=\"groove\", borderwidth=2)\n self.frame.place(relx=0.7, rely=0.8)\n self.calc_prepayment = Label(self.frame, text=\"\", bg=\"blue\")\n self.calc_prepayment.place(x=500, y=200,)\n self.reserve = Label(window, text=\"\")\n\n\n def calc_prepayment(self):\n ticket_no = int(self.spn_no_tics.get())\n vat = 0.14\n try:\n int(self.txt_cell.get())\n if len(self.txt_cell.get()) < 10 or len(self.txt_cell.get()) > 10:\n raise ValueError\n\n elif variable.get() == \"Select Ticket\":\n raise ValueError\n\n elif int(self.spn_no_tics.get()) == 0:\n raise ValueError\n\n\n # Soccer\n elif variable.get() == \"Soccer\":\n price = 40 # in Rands\n price_pay = (price * ticket_no) + (price * ticket_no * vat)\n text = (\"Amount Payable: R{}\".format(price_pay))\n self.calc_prepayment.config(text=text)\n\n\n # Movie\n elif variable.get() == \"Movie\":\n price = 75 # in Rands\n price_pay = (price * ticket_no) + (price * ticket_no * vat)\n text = (\"Amount Payable: R{}\".format(price_pay))\n self.calc_prepayment.config(text=text)\n\n # Theater\n elif variable.get() == \"Theater\":\n price = 100 # in Rands\n price_pay = (price * ticket_no) + (price * ticket_no * vat)\n text = (\"Amount Payable: R{}\".format(price_pay))\n self.calc_prepayment.config(text=text)\n\n # Reservation\n reserve_text = \"Reservation for {} for : {} \".format(self.tic_options.get(), ticket_no)\n cell_text = \"Reservation Made By: {}\".format(self.txt_cell_entry.get())\n self.reserve.config(text=reserve_text)\n self.cell.config(text=cell_text)\n\n except ValueError: # Error Message\n messagebox.showerror(message=\"INVALID - Please Try Again\")\n\n\nobj_Ticketsales=ClsTicketSales(root)\nroot.mainloop()","repo_name":"jordan-hess/easy-ticket","sub_path":"challenge_1.py","file_name":"challenge_1.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13665324383","text":"from django.http import HttpResponse\nfrom django.views.generic import TemplateView\nimport requests\nimport json\nfrom django.shortcuts import render\n\n_URL_API = 'https://integracion-rick-morty-api.herokuapp.com/graphql'\n# _URL_API = 'https://rickandmortyapi.com/graphql/'\n\n# SOURCE: https://towardsdatascience.com/connecting-to-a-graphql-api-using-python-246dda927840\n\ndef index(request):\n page = 1\n query = \"\"\"\n query {{\n episodes(page: {page}) {{\n info {{\n count\n next\n }}\n results {{\n id\n name\n air_date\n episode\n }}\n }}\n }}\n \"\"\"\n output = []\n\n while True:\n r = requests.post(_URL_API, json={'query': query.format(page=str(page))})\n json_data = json.loads(r.text)\n next_ = json_data['data']['episodes']['info']['next']\n render_data = json_data['data']['episodes']['results']\n for epi in render_data:\n _dic_aux = {}\n _dic_aux['id'] = epi['id']\n _dic_aux['name'] = epi['name']\n _dic_aux['air_date'] = epi['air_date']\n _dic_aux['episode'] = epi['episode']\n output.append(_dic_aux)\n if next_: # hay otra pagina\n page += 1\n else:\n break\n\n return render(request, 'index.html', {'episodes': output})\n\n\ndef episode(request, episode_id):\n query = \"\"\"\n query {{\n episode (id: {episode_id}) {{\n name\n air_date\n episode\n characters {{\n id\n name\n }}\n }}\n }}\n \"\"\"\n r = requests.post(_URL_API, json={'query': query.format(episode_id=str(episode_id))})\n json_data = json.loads(r.text)\n render_data = json_data['data']['episode']\n\n return render(request, 'episode.html', render_data)\n\n\ndef character(request, character_id):\n query = \"\"\"\n query {{\n character (id: {character_id}) {{\n name\n status\n species\n type\n gender\n origin {{\n id\n name\n }}\n location {{\n id\n name\n }}\n image\n episode {{\n id\n name\n }}\n }}\n }}\n \"\"\"\n r = requests.post(\n _URL_API, json={'query': query.format(character_id=str(character_id))})\n json_data = json.loads(r.text)\n render_data = json_data['data']['character']\n\n return render(request, 'character.html', render_data)\n\n\ndef location(request, location_id):\n query = \"\"\"\n query {{\n location (id: {location_id}) {{\n name\n type\n dimension\n residents {{\n id\n name\n }}\n }}\n }}\n \"\"\"\n r = requests.post(\n _URL_API, json={'query': query.format(location_id=str(location_id))})\n json_data = json.loads(r.text)\n render_data = json_data['data']['location']\n\n if not render_data['residents'][0][\"id\"]:\n del render_data['residents']\n return render(request, 'location.html', render_data)\n\n\ndef search(request):\n '''\n SOURCE : https: // stackoverflow.com/questions/54678389/search-bar-in-django\n SOURCE : https: // stackoverflow.com/questions/17716624/django-csrf-cookie-not-set\n SOURCE : https://docs.djangoproject.com/en/3.0/ref/request-response/\n '''\n search_term = request.POST.get('search', '')\n \n # characters\n query_characters = \"\"\"\n query {{\n characters(filter: {{name: \"{search_term}\" }}) {{\n results {{\n id\n name\n }}\n }}\n }}\n \n \"\"\"\n try:\n r = requests.post(_URL_API, json={'query': query_characters.format(search_term=search_term)})\n json_data = json.loads(r.text)\n characters = json_data['data']['characters']['results']\n except: \n characters = [{'id': \"\",\n 'name': \"\"}]\n\n # episodes\n query_episodes = \"\"\"\n query {{\n episodes(filter: {{name: \"{search_term}\" }}) {{\n results {{\n id\n name\n }}\n }}\n }}\n \"\"\"\n try:\n r = requests.post(_URL_API, json={'query': query_episodes.format(search_term=search_term)})\n json_data = json.loads(r.text)\n episodes = json_data['data']['episodes']['results']\n except:\n episodes = [{'id': \"\",\n 'name': \"\"}]\n\n # locations\n query_locations = \"\"\"\n query {{\n locations(filter: {{name: \"{search_term}\" }}) {{\n results {{\n id\n name\n }}\n }}\n }}\n \"\"\"\n try:\n r = requests.post(_URL_API, json={'query': query_locations.format(search_term=search_term)})\n json_data = json.loads(r.text)\n locations = json_data['data']['locations']['results']\n except:\n locations = [{'id': \"\",\n 'name': \"\"}]\n\n return render(request, 'search.html',\n {'characters': characters,\n 'episodes': episodes, \n 'locations': locations})\n","repo_name":"diegosapunar/Consuming_GraphQL-API-Django","sub_path":"tarea5/tarea5/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22752222321","text":"import http\nimport typing as t\n\nfrom starlette import status\n\n\nclass APIException(Exception):\n __slots__ = (\"headers\", \"description\", \"detail\", \"http_status\")\n\n status_code = status.HTTP_400_BAD_REQUEST\n code = \"bad_request\"\n\n def __init__(\n self,\n detail: t.Optional[t.Union[t.List, t.Dict, str]] = None,\n description: t.Optional[str] = None,\n headers: t.Optional[t.Dict[str, t.Any]] = None,\n status_code: t.Optional[int] = None,\n ) -> None:\n assert self.status_code\n self.status_code = status_code or self.status_code\n self.http_status = http.HTTPStatus(self.status_code)\n self.description = description\n\n if detail is None:\n detail = self.http_status.phrase\n\n self.detail = detail\n self.headers = headers\n\n def __repr__(self) -> str: # pragma: no cover\n class_name = self.__class__.__name__\n return f\"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})\"\n\n def get_full_details(self) -> t.Union[t.Dict, t.List[t.Dict]]:\n \"\"\"\n Return both the message & code parts of the error details.\n \"\"\"\n return {\n \"detail\": self.detail,\n \"code\": self.code,\n \"description\": self.description or self.http_status.description,\n }\n\n def get_details(self) -> t.Dict:\n result = {\"detail\": self.detail}\n if self.description:\n result.update(description=self.description)\n return result\n","repo_name":"eadwinCode/ellar","sub_path":"ellar/common/exceptions/api/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"3"}
+{"seq_id":"9831539166","text":"import numpy as np\nfrom glob import glob\nimport os\nfrom skimage import util,io\nimport skimage\nfrom skimage.segmentation import clear_border\nimport csv\nfrom skimage.morphology import label # label regions\nfrom skimage.color import label2rgb\n\n# Run-length encoding stolen from https://www.kaggle.com/rakhlin/fast-run-length-encoding-python\ndef rle_encoding(x):\n dots = np.where(x.T.flatten() == 1)[0]\n run_lengths = []\n prev = -2\n for b in dots:\n if (b>prev+1): run_lengths.extend((b + 1, 0))\n run_lengths[-1] += 1\n prev = b\n return run_lengths\n\ndef prob_to_rles(x, image_path):\n # remove artifacts connected to image border\n #cleared = clear_border(x)\n # label image regions\n lab_img = label(x)\n skimage.io.imsave(\"label_runs/\"+image_path+\".png\", label2rgb(lab_img, x))\n for i in range(1, lab_img.max() + 1):\n yield rle_encoding(lab_img == i)\n\n\ndef rle_to_string(runs):\n return ' '.join(str(x) for x in runs)\n\ndef prepare_submission():\n new_test_ids = []\n rles = []\n image_paths = glob('runs/1517787853.934606/*')\n f = open('stage1_final_submission.csv', 'wt')\n writer = csv.writer(f)\n writer.writerow(('ImageId', 'EncodedPixels'))\n for image_path in image_paths :\n image = skimage.io.imread(image_path, as_grey=True)\n #skimage.io.imsave(\"invert_\"+image_path, util.invert(image))\n #gaussian blur after improving algo\n #print(os.path.basename(os.path.splitext(image_path)[0]))\n #print(rle_encoding(util.invert(image)))\n id_ = os.path.basename(os.path.splitext(image_path)[0])\n rle = list(prob_to_rles(image, id_))\n rles.extend(rle)\n new_test_ids.extend([id_] * len(rle))\n\n for i in range(0, len(new_test_ids)):\n writer.writerow((new_test_ids[i], rle_to_string(rles[i])))\n\n #write to a file\n\nif __name__ == '__main__':\n prepare_submission()","repo_name":"anupriyachhabra/data-science-bowl","sub_path":"rle.py","file_name":"rle.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"73659025680","text":"import random as rd\nimport datetime as dt\nimport re\n\n\ndef salt_generator(text, length=10):\n sref = (ord(ch) for ch in text)\n rd.seed(sum(sref))\n chars = ('abcdefghijklmnopqrstuvwxyz'\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n '0123456789'\n '!@#$%^&*()-_=+')\n return ''.join((rd.choice(chars) for _ in range(length)))\n\n\ndef titlecase(string):\n pattern = r\"[a-zA-Z]+('[a-zA-Z]+)?\"\n return re.sub(pattern, lambda x: x.group(0).capitalize(), string)\n","repo_name":"AlimusSifar/Project-Vocabulary","sub_path":"website/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5908378512","text":"from datetime import date\n\nimport pytest\n\nfrom tests.factories import VacancyFactory\n\n\n@pytest.mark.django_db\ndef test_retrieve_vacancy(client, hr_token):\n vacancy = VacancyFactory.create()\n expected_response = {\n \"id\": vacancy.pk,\n \"text\": \"test text\",\n \"slug\": \"test\",\n \"status\": \"draft\",\n \"created\": date.today().strftime(\"%Y-%m-%d\"),\n \"skills\": [],\n \"likes\": 0,\n \"min_experience\": None,\n \"date_published\": None,\n \"username\": vacancy.username,\n }\n\n response = client.get(\n f'/vacancy/{vacancy.pk}/',\n HTTP_AUTHORIZATION=\"Token \" + hr_token\n )\n\n assert response.status_code == 200\n assert response.data == expected_response\n","repo_name":"Rustam-Gazizulin/jobs_search","sub_path":"tests/vacancies/vacancy_retrieve_test.py","file_name":"vacancy_retrieve_test.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"73211041040","text":"import random\n\nfrom classification.neuralNet import NeuralNetClf, ConvNeuralNetCLF\n\n\nimport numpy as np\nfrom typing import *\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.callbacks import TensorBoard\nimport imblearn\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom collections import Counter\nimport time\nimport matplotlib.pyplot as plt\nimport sys\nfrom PyQt5 import QtWidgets\napp = QtWidgets.QApplication(sys.argv)\n\nfrom preprocessing.routines import deriv_smooth, normalizeIntensities\nfrom preprocessing.preprocessors import NormMode, MSCProc\n\nspecs: np.ndarray = np.load(\"spectra.npy\")\n\nassignments: np.ndarray = np.load(\"labels.npy\")\n\nfor i in range(len(assignments)):\n assignments[i] = assignments[i].replace(\"weathered\", \"\")\n assignments[i] = assignments[i].replace(\"pristine\", \"\")\n assignments[i] = assignments[i].replace(\"blue\", \"\")\n assignments[i] = assignments[i].replace(\"white\", \"\")\n assignments[i] = assignments[i].replace(\"_\", \"\")\n\nassignments[assignments == \"sediment A\"] = \"Sediment\"\nassignments[assignments == \"sediment B\"] = \"Sediment\"\nassignments[assignments == \"sediment C\"] = \"Sediment\"\nassignments[assignments == \"Sediment R\"] = \"Sediment\"\nassignments[assignments == \"eppi blue\"] = \"Eppi\"\nassignments[assignments == \"eppi green\"] = \"Eppi\"\nprint(Counter(assignments))\n\nspecs = deriv_smooth(specs, windowSize=13, polydegree=3, derivative=1)\nspecs = normalizeIntensities(specs, NormMode.Length)\n\nline_colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'b', 'g', 'r'] * 2\nfig: plt.Figure = plt.figure()\nax: plt.Axes = fig.add_subplot()\nfor i, name in enumerate(np.unique(assignments)):\n ind = np.where(assignments == name)[0]\n if len(ind) > 10:\n ind = np.array(random.sample(list(ind), 20))\n ax.plot(specs[ind[:-1], :].transpose() - i*0.5, color=line_colors[i])\n ax.plot(specs[ind[-1], :] - i * 0.5, color=line_colors[i], label=name)\n\nax.legend(bbox_to_anchor=(1, 1), loc=\"upper left\")\nfig.tight_layout()\nfig.show()\n\nspecs, assignments = imblearn.under_sampling.RandomUnderSampler().fit_resample(specs, assignments)\nprint(Counter(assignments))\n\nencoder: LabelEncoder = LabelEncoder().fit(assignments)\ny: np.ndarray = encoder.transform(assignments)\n\nX_train, X_test, y_train, y_test = train_test_split(specs, y, test_size=0.2)\ndropout = 0.1\nnumNeurons = [200, 100, 50]\n\nmodelName: str = f\"Dense {'_'.join([str(i) for i in numNeurons])}_dropout_{dropout}_20epochs\"\nprint(modelName)\nnn: NeuralNetClf = NeuralNetClf(specs.shape[1], len(np.unique(assignments)),\n numNeuronsPerHiddenLayer=numNeurons, dropout=dropout)\ntensboard: TensorBoard = TensorBoard(log_dir=f\"logs/{modelName}\")\nt0 = time.time()\nhistory = nn.fit(X_train, to_categorical(y_train),\n validation_data=(X_test, to_categorical(y_test)),\n batch_size=64,\n epochs=50, verbose=1,\n callbacks=[tensboard])\nprint(f\"training NN took {time.time()-t0} seconds\")\nt0 = time.time()\npred: np.ndarray = nn.predict(X_test)\npred = np.array([pred[i, :].argmax() for i in range(pred.shape[0])])\nprint(f\"Pred NN: {time.time()-t0} seconds\\n\", classification_report(encoder.inverse_transform(y_test),\n encoder.inverse_transform(pred),\n zero_division=0))\n\n\n# modelName: str = f\"Conv Network_20epochs\"\n# print(modelName)\n# nn: ConvNeuralNetCLF = ConvNeuralNetCLF(specs.shape[1], len(np.unique(assignments)))\n# X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)\n# X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)\n#\n# tensboard: TensorBoard = TensorBoard(log_dir=f\"logs/{modelName}\")\n# t0 = time.time()\n# history = nn.fit(X_train, to_categorical(y_train),\n# validation_data=(X_test, to_categorical(y_test)),\n# batch_size=64,\n# epochs=20, verbose=1,\n# callbacks=[tensboard])\n# print(f\"training NN took {time.time()-t0} seconds\")\n# t0 = time.time()\n# pred: np.ndarray = nn.predict(X_test)\n# pred = np.array([pred[i, :].argmax() for i in range(pred.shape[0])])\n# print(f\"Pred NN: {time.time()-t0} seconds\\n\", classification_report(encoder.inverse_transform(y_test),\n# encoder.inverse_transform(pred),\n# zero_division=0))\n","repo_name":"Brandt-J/HSI-Evaluator","sub_path":"classification/classificationExperiments.py","file_name":"classificationExperiments.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"3781204525","text":"from collections import namedtuple\n\nCourse = namedtuple(\"Course\", [\n \"language_name\",\n \"language_code\",\n \"special_characters\",\n \"modules\",\n \"license\",\n \"dictionary\"\n])\n\nLicense = namedtuple(\"License\", [\n \"name\",\n \"full_name\",\n \"link\",\n])\n\nModule = namedtuple(\"Module\", [\n \"title\",\n \"skills\",\n])\n\nSkill = namedtuple(\"Skill\", [\n \"name\",\n \"id\",\n \"words\",\n \"phrases\",\n \"image_set\"\n])\n\nWord = namedtuple(\"Word\", [\n \"in_target_language\",\n \"in_source_language\",\n \"pictures\",\n])\n\nPhrase = namedtuple(\"Phrase\", [\n \"in_target_language\",\n \"in_source_language\",\n])\n\nDictionaryItem = namedtuple(\"DictionaryItem\", [\n \"word\",\n \"definition\",\n \"reverse\"\n])\n","repo_name":"Magicianred/LibreLingo","sub_path":"workspaces/liblili2json/liblili2json/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"6892162625","text":"import typing\n\nfrom sqlalchemy.sql import Select\n\nfrom .utils.iter import group_by\nfrom .definition import (\n BaseDeclarativeFilter,\n FilterType,\n)\nfrom .query import QueryType\nfrom .types import SqlQueryFilterType, QueryFilterOperators\nfrom .validation import QueryFilterValidator\n\n\nclass SqlQueryFilterFacade:\n _orm_operator_transformer = {\n QueryFilterOperators.NOT_EQ: lambda value: (\"__ne__\", value),\n QueryFilterOperators.EQ: lambda value: (\"__eq__\", value),\n QueryFilterOperators.GT: lambda value: (\"__gt__\", value),\n QueryFilterOperators.GE: lambda value: (\"__ge__\", value),\n QueryFilterOperators.IN: lambda value: (\"in_\", value),\n QueryFilterOperators.IS_NULL: lambda value: (\"is_\", None)\n if value is True\n else (\"is_not\", None),\n QueryFilterOperators.LT: lambda value: (\"__lt__\", value),\n QueryFilterOperators.LE: lambda value: (\"__le__\", value),\n QueryFilterOperators.LIKE: lambda value: (\"like\", f\"%{value}%\"),\n QueryFilterOperators.ILIKE: lambda value: (\"ilike\", f\"%{value}%\"),\n QueryFilterOperators.NOT: lambda value: (\"is_not\", value),\n QueryFilterOperators.NOT_IN: lambda value: (\"not_in\", value),\n QueryFilterOperators.OPTION: lambda value: (\"\", value),\n }\n\n def __init__(\n self,\n defined_filter: BaseDeclarativeFilter,\n queries: SqlQueryFilterType,\n validate: bool = True,\n ):\n self.defined_filter = defined_filter\n self.queries = queries\n\n self.validator = QueryFilterValidator(self.defined_filter)\n if validate:\n self.validator.validate(self.queries)\n\n self.values = self._extract_query_values(self.queries)\n self.fields = self._extract_model_fields()\n\n def _extract_model_fields(self):\n return {\n field_name: field_metadata.model_field\n for field_name, field_metadata in self.defined_filter.query_fields.items()\n }\n\n def _extract_query_values(\n self, queries: SqlQueryFilterType\n ) -> typing.Dict[str, typing.Any]:\n grouped_queries = group_by(\n queries,\n lambda query: query.field,\n list,\n )\n fields: typing.Dict[str, typing.Any] = {}\n for field_name, field_metadata in self.defined_filter.query_fields.items():\n curr_query_set = grouped_queries.get(field_name, None)\n if curr_query_set is None:\n fields[field_name] = None\n else:\n field_value = field_metadata.query_type.interpret_value(curr_query_set)\n fields[field_name] = field_value\n return fields\n\n def _get_orm_operator(self, operator: QueryFilterOperators, value: typing.Any):\n return self._orm_operator_transformer[operator](value)\n\n def _get_orm_expression(self, model_field, operator: str, value: typing.Any):\n return getattr(model_field, operator)(value)\n\n def _apply_expression(self, base_stmt, expression, query_field_metadata):\n if query_field_metadata.filter_type is FilterType.WHERE:\n base_stmt = base_stmt.filter(expression)\n elif query_field_metadata.filter_type is FilterType.HAVING:\n base_stmt = base_stmt.having(expression)\n else:\n raise NotImplementedError(\n f\"Unhandled condition operand type: {query_field_metadata.filter_type}\"\n )\n return base_stmt\n\n def apply(\n self,\n base_stmt: Select,\n exclude_fields: typing.Optional[typing.Set[str]] = None,\n ) -> Select:\n \"\"\"\n Apply query filter to base statement.\n \"\"\"\n exclude_fields = exclude_fields or set()\n for query in self.queries:\n if query.field in exclude_fields:\n continue\n\n query_field_metadata = self.defined_filter.query_fields.get(\n query.field, None\n )\n if query_field_metadata is None:\n raise ValueError(f\"No such query field: {query.field}\")\n\n if query_field_metadata.query_type is QueryType.Option:\n _, value = self._get_orm_operator(query.operator, query.value)\n if value:\n expression = query_field_metadata.model_field\n base_stmt = self._apply_expression(\n base_stmt, expression, query_field_metadata\n )\n else:\n operator, value = self._get_orm_operator(query.operator, query.value)\n expression = self._get_orm_expression(\n query_field_metadata.model_field, operator, value\n )\n base_stmt = self._apply_expression(\n base_stmt, expression, query_field_metadata\n )\n\n return base_stmt\n","repo_name":"swimmwatch/fastapi-query-filter","sub_path":"fastapi_query_filter/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29182600147","text":"\"\"\"Integration tests for scenarios.\"\"\"\nimport http.client\nfrom unittest.mock import Mock, call\n\nimport pytest\n\nfrom infra.walle.server.tests.lib.scenario_util import launch_scenario\nfrom infra.walle.server.tests.lib.util import (\n monkeypatch_inventory_get_host_info_and_check_status,\n monkeypatch_method,\n TestCase,\n)\nfrom walle import authorization\nfrom walle.clients import inventory, bot, ipmiproxy\nfrom walle.clients.qloud import QloudHostStates\nfrom walle.constants import FLEXY_EINE_PROFILE\nfrom walle.hosts import HostLocation, Host, HostState, HostStatus, HostOperationState\nfrom walle.models import timestamp\nfrom walle.operations_log.constants import Operation\nfrom walle.physical_location_tree import LocationNamesMap\nfrom walle.scenario.constants import (\n ScriptArgs,\n ScenarioFsmStatus,\n TicketStatus,\n TemplatePath,\n TICKET_RESOLUTION,\n TicketTransition,\n SchedulerName,\n)\nfrom walle.scenario.host_stage_info import HostStageInfo\nfrom walle.scenario.marker import Marker\nfrom walle.scenario.scenario import Scenario, HostStageStatus\n\n# noinspection PyProtectedMember\nfrom walle.scenario.scenario_fsm import _run_scenario\nfrom walle.scenario.script import hosts_add_script\nfrom walle.scenario.stage.approve_stage import ApproveStage\nfrom walle.scenario.stage_info import StageAction, StageStatus\nfrom walle.scenario.stages import WaitForLabelOrTimeStage\nfrom walle.stages import Stages\nfrom walle.util.template_loader import JinjaTemplateRenderer\n\nDC_NAMES = (\"a\", \"dcmock\")\nSOURCE_PROJECT_ID = \"source\"\nTARGET_PROJECT_ID = \"target\"\nTARGET_SEGMENT = \"ext.mock\"\n\n\n@pytest.fixture\ndef test(mp, monkeypatch_timestamp, monkeypatch_locks, authorized_scenario_user, startrek_client, request):\n mp.function(inventory.get_eine_profiles, return_value=[\"profile-mock\", FLEXY_EINE_PROFILE])\n mp.function(inventory.check_deploy_configuration)\n mp.function(bot.missed_preordered_hosts, return_value={})\n mp.config(\"scenario.stages.add_hosts_stage.project\", SOURCE_PROJECT_ID)\n\n monkeypatch_method(mp, ipmiproxy.IpmiProxyClient.is_power_on, obj=ipmiproxy.IpmiProxyClient, return_value=False)\n\n monkeypatch_inventory_get_host_info_and_check_status(mp)\n return TestCase.create(request)\n\n\ndef expand_startrek_client_mock(mock_startrek_client):\n mock_startrek_client.attach_mock(Mock(return_value={\"status\": {\"key\": TicketStatus.OPEN}}), \"get_issue\")\n mock_startrek_client.attach_mock(Mock(), \"execute_transition\")\n mock_startrek_client.attach_mock(Mock(), \"add_comment\")\n return mock_startrek_client\n\n\ndef _make_hosts_for_scenario_test(test, source_project, count_per_dc=5):\n hosts = []\n next_id = 0\n location_for_dc = {\n dc: HostLocation(\n country=\"country-mock\",\n city=\"city-mock\",\n datacenter=dc,\n queue=\"queue-mock\",\n rack=\"rack-mock\",\n physical_timestamp=timestamp(),\n )\n for dc in DC_NAMES\n }\n\n for dc in DC_NAMES:\n for i in range(count_per_dc):\n hosts.append(\n test.mock_host(\n {\n \"state\": HostState.ASSIGNED,\n \"inv\": next_id,\n \"project\": source_project.id,\n \"location\": location_for_dc[dc],\n }\n )\n )\n next_id += 1\n\n return hosts\n\n\ndef get_fresh_scenario_host_objects(scenario, group_num=None):\n if group_num is None:\n return Host.objects(inv__in=[host_info.inv for host_info in scenario.hosts.values()])\n else:\n invs = [int(host_info.inv) for host_info in scenario.hosts.values() if host_info.group == group_num]\n return Host.objects.filter(inv__in=invs)\n\n\ndef get_fresh_host_stage_infos(scenario, group_num=None):\n if group_num is None:\n uuids = [host.uuid for host in Host.objects(inv__in=[host_info.inv for host_info in scenario.hosts.values()])]\n else:\n invs = [int(host_info.inv) for host_info in scenario.hosts.values() if host_info.group == group_num]\n uuids = [host.uuid for host in Host.objects.filter(inv__in=invs)]\n return HostStageInfo.objects(host_uuid__in=uuids)\n\n\ndef assert_stage_info_action_and_status(stage_info_owner, seq_num, action_type, status):\n stage_info = stage_info_owner.stage_info.stages[seq_num]\n assert stage_info.action_type == action_type\n assert stage_info.status == status\n\n\ndef assert_transition_to_next_stage(scenario, group_num, seq_num):\n for hsi in get_fresh_host_stage_infos(scenario, group_num):\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.FINISHED)\n assert hsi.stage_info.seq_num == seq_num + 1\n assert_stage_info_action_and_status(hsi, seq_num + 1, StageAction.ACTION, StageStatus.QUEUE)\n\n\n@pytest.mark.slow\ndef test_add_hosts_scenario_execution(mp, test, startrek_client, qloud_client):\n expand_startrek_client_mock(startrek_client)\n\n LocationNamesMap(path=\"country-mock|city-mock|dc-mock\", name=\"mdc\").save(force_insert=True)\n LocationNamesMap(path=\"country-mock|city-mock|dc-mock|queue-mock\", name=\"m-queue\").save(force_insert=True)\n source_project = test.mock_project({\"id\": SOURCE_PROJECT_ID, \"cms_settings\": [{\"cms\": \"non-default\"}]})\n target_project = test.mock_project({\"id\": TARGET_PROJECT_ID, \"cms_settings\": [{\"cms\": \"non-default\"}]})\n hosts = _make_hosts_for_scenario_test(test, source_project)\n\n scenario_params = dict(\n name=\"scenario-execution-test\",\n scenario_type=hosts_add_script.name,\n autostart=True,\n hosts=[h.inv for h in hosts],\n reason=\"Test switch project scenario\",\n ticket_key=\"WALLE-2791\",\n script_args={\n ScriptArgs.TARGET_PROJECT: target_project.id,\n ScriptArgs.SCHEDULE_TYPE: SchedulerName.DATACENTER,\n ScriptArgs.TARGET_SEGMENT: TARGET_SEGMENT,\n },\n labels={\"test\": \"yes\"},\n )\n response = test.api_client.post(\"v1/scenarios\", data=scenario_params)\n assert response.status_code == http.client.CREATED\n\n scenario = Scenario.objects.get(scenario_id=response.json[\"scenario_id\"])\n\n assert scenario.status == ScenarioFsmStatus.STARTED\n assert {inv for inv in scenario_params[\"hosts\"]} == {host_info.inv for host_info in scenario.hosts.values()}\n\n # AcquirePermission\n scenario = launch_scenario(scenario)\n\n # AddStartrekMessageStage\n scenario = launch_scenario(scenario)\n call_args = dict(\n text=JinjaTemplateRenderer().render_template(\n TemplatePath.STARTREK_START_SCENARIO, scenario_id=scenario.scenario_id\n ),\n issue_id=scenario.ticket_key,\n )\n startrek_client.add_comment.assert_has_calls([call(**call_args)])\n\n # ExecuteTicketTransitionStage - ReadyForDev\n scenario = launch_scenario(scenario)\n startrek_client.execute_transition.assert_has_calls(\n [\n call(issue_id=scenario.ticket_key, transition=TicketTransition.READY_FOR_DEV),\n ]\n )\n\n # ApproveStage\n monkeypatch_method(mp, ApproveStage.run, obj=ApproveStage, return_value=Marker.success())\n scenario = launch_scenario(scenario)\n\n # AddStartrekMessageStage\n scenario = launch_scenario(scenario)\n call_args = dict(\n text=JinjaTemplateRenderer().render_template(TemplatePath.STARTREK_EMERGENCY, scenario_id=scenario.scenario_id),\n issue_id=scenario.ticket_key,\n )\n startrek_client.add_comment.assert_has_calls([call(**call_args)])\n\n # ExecuteTicketTransitionStage - InProgress\n scenario = launch_scenario(scenario)\n startrek_client.execute_transition.assert_has_calls(\n [call(issue_id=scenario.ticket_key, transition=TicketTransition.IN_PROGRESS)]\n )\n\n # WaitForLabelOrTimeStage.run()\n monkeypatch_method(mp, WaitForLabelOrTimeStage.run, obj=WaitForLabelOrTimeStage, return_value=Marker.success())\n scenario = launch_scenario(scenario)\n\n scenario = launch_scenario(scenario)\n # AddHostsStage: Proceed to the next stage now that the host has been added\n assert_stage_info_action_and_status(\n scenario, scenario.stage_info.seq_num - 1, StageAction.ACTION, StageStatus.FINISHED\n )\n\n scenario = launch_scenario(scenario)\n # SetHostUUIDStage: Keys in scenario object must be converted to UUIDs\n assert_stage_info_action_and_status(\n scenario, scenario.stage_info.seq_num - 1, StageAction.ACTION, StageStatus.FINISHED\n )\n assert set(scenario.hosts.keys()) == {host.uuid for host in hosts}\n\n scenario = launch_scenario(scenario)\n # Check initial group\n assert scenario.current_group == 0\n\n scenario = launch_scenario(scenario)\n # Check that hosts in scenario object have been assigned to a group\n for host_info in scenario.hosts.values():\n assert host_info.group is not None\n\n # HOST STAGES\n for group_num in range(len(DC_NAMES)):\n old_tasks = {}\n seq_num = 0\n _run_scenario(scenario.id)\n # Check HostRootStage serialization on hosts in current group\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n assert host.scenario_id == scenario.scenario_id\n\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert hsi.stage_info\n\n scenario = launch_scenario(scenario)\n # SwitchToMaintenanceHostStage.run() - schedule switch-to-maintenance task\n # Check that task has been scheduled with required params\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.PROCESSING)\n\n assert host.status == Operation.SWITCH_TO_MAINTENANCE.host_status\n assert host.ticket == scenario.ticket_key\n assert not host.task.ignore_cms\n assert host.task.owner == authorization.ISSUER_WALLE\n old_tasks[host.inv] = host.task\n\n stage_info_hosts_data = scenario.stage_info.stages[9].stages[0].stages[0].hosts\n assert stage_info_hosts_data[host.uuid][\"status\"] == HostStageStatus.PROCESSING\n\n scenario = launch_scenario(scenario)\n # SwitchToMaintenanceHostStage.run()\n # Check that task has not been recreated. Complete maintenance switching for next iteration to finish\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.PROCESSING)\n\n assert host.task == old_tasks[host.inv]\n host.state = HostState.MAINTENANCE\n host.status = HostStatus.default(HostState.MAINTENANCE)\n host.state_author = scenario.issuer\n host.operation_state = HostOperationState.DECOMMISSIONED\n del host.task\n host.save()\n\n scenario = launch_scenario(scenario)\n # SwitchToMaintenanceHostStage.run()\n # Check transition to the next stage\n assert_transition_to_next_stage(scenario, group_num, seq_num)\n seq_num += 1\n\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n stage_info_hosts_data = scenario.stage_info.stages[9].stages[0].stages[0].hosts\n assert stage_info_hosts_data[host.uuid][\"status\"] == HostStageStatus.FINISHED\n\n scenario = launch_scenario(scenario)\n # PowerOffHostStage.run()\n # Check host's maintenance\n assert_transition_to_next_stage(scenario, group_num, seq_num)\n seq_num += 1\n\n scenario = launch_scenario(scenario)\n # WaitDayStage.run()\n # Check transition to the next stage\n assert_transition_to_next_stage(scenario, group_num, seq_num)\n seq_num += 1\n\n # LiberateFromQloudHostStage.run()\n # Check that task has been scheduled with required params\n scenario = launch_scenario(scenario)\n assert_transition_to_next_stage(scenario, group_num, seq_num)\n seq_num += 1\n\n scenario = launch_scenario(scenario)\n # SwitchProjectHostStage.run()\n # Check that task has been scheduled with required params\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.PROCESSING)\n\n assert host.status == Operation.SWITCH_PROJECT.host_status\n\n switch_project_stage = next(stage for stage in host.task.stages if stage.name == Stages.SWITCH_PROJECT)\n assert Stages.COMPLETE_RELEASING in [stage.name for stage in host.task.stages]\n assert switch_project_stage.params[\"project\"] == target_project.id\n assert not host.task.ignore_cms\n assert host.task.owner == authorization.ISSUER_WALLE\n old_tasks[host.inv] = host.task\n\n stage_info_hosts_data = scenario.stage_info.stages[9].stages[0].stages[4].hosts\n assert stage_info_hosts_data[host.uuid][\"status\"] == HostStageStatus.PROCESSING\n\n scenario = launch_scenario(scenario)\n # SwitchProjectHostStage.run()\n # Check that task has not been recreated. Complete project switching for the next iteration to finish\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.PROCESSING)\n\n assert host.task == old_tasks[host.inv]\n\n host.state = HostState.FREE\n host.status = HostStatus.default(HostState.FREE)\n host.project = target_project.id\n del host.task\n host.save()\n\n scenario = launch_scenario(scenario)\n # SwitchProjectHostStage.run()\n # Check transition to another task\n assert_transition_to_next_stage(scenario, group_num, seq_num)\n seq_num += 1\n\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n stage_info_hosts_data = scenario.stage_info.stages[9].stages[0].stages[4].hosts\n assert stage_info_hosts_data[host.uuid][\"status\"] == HostStageStatus.FINISHED\n\n scenario = launch_scenario(scenario)\n # PrepareHostStage.run()\n # Check that task has been scheduled with required params\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.PROCESSING)\n\n assert host.status == Operation.PREPARE.host_status\n assert not host.task.ignore_cms\n assert host.task.owner == authorization.ISSUER_WALLE\n old_tasks[host.inv] = host.task\n\n scenario = launch_scenario(scenario)\n # PrepareHostStage.run()\n # Check that task has not been recreated. Remove task and set the PROBATION state\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.PROCESSING)\n\n assert host.task == old_tasks[host.inv]\n\n host.state = HostState.PROBATION\n host.status = HostStatus.default(HostState.PROBATION)\n host.project = target_project.id\n del host.task\n host.save()\n\n scenario = launch_scenario(scenario)\n # PrepareHostStage.run()\n # Check hosts added to qloud. Set them to assigned state\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.PROCESSING)\n qhost = qloud_client.find_host(host.name)\n assert qhost.state == QloudHostStates.INITIAL and qhost.segment == TARGET_SEGMENT\n host.state = HostState.ASSIGNED\n host.save()\n\n scenario = launch_scenario(scenario)\n # PrepareHostStage.run()\n # Qloud meta called\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.PROCESSING)\n qhost = qloud_client.find_host(host.name)\n assert qhost.meta_called and qhost.state == QloudHostStates.INITIAL and qhost.segment == TARGET_SEGMENT\n # Dirty patch meta\n qhost.is_data_filled = True\n\n scenario = launch_scenario(scenario)\n # PrepareHostStage.run()\n # Check hosts changing qloud state to UP\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.PROCESSING)\n qhost = qloud_client.find_host(host.name)\n assert qhost.state == QloudHostStates.UP and qhost.segment == TARGET_SEGMENT\n\n scenario = launch_scenario(scenario)\n # PrepareHostStage.run()\n # Hosts are in target project in assigned-ready. Check stage completion\n for host in get_fresh_scenario_host_objects(scenario, group_num):\n hsi = HostStageInfo.objects.get(host_uuid=host.uuid)\n assert_stage_info_action_and_status(hsi, seq_num, StageAction.ACTION, StageStatus.FINISHED)\n assert hsi.stage_info.status == StageStatus.FINISHED # HostRootStage has been completed\n\n # SchedulerStage.check()\n # Must proceed to the next group after checking that all hosts in current group have been processed\n scenario = launch_scenario(scenario)\n assert scenario.current_group == group_num + 1\n assert scenario.stage_info.stages[0].action_type == StageAction.ACTION # Proceed to the next group\n\n # AddStartrekMessageStage\n scenario = launch_scenario(scenario)\n call_args = dict(\n text=JinjaTemplateRenderer().render_template(\n TemplatePath.STARTREK_END_SCENARIO, scenario_id=scenario.scenario_id\n ),\n issue_id=scenario.ticket_key,\n )\n startrek_client.add_comment.assert_has_calls([call(**call_args)])\n\n # ExecuteTicketTransitionStage - CLOSED\n scenario = launch_scenario(scenario)\n startrek_client.execute_transition.assert_has_calls(\n [\n call(\n issue_id=scenario.ticket_key,\n transition=TicketTransition.CLOSE,\n issue_params={\"resolution\": TICKET_RESOLUTION},\n )\n ]\n )\n\n # All stages have finished.\n for host in get_fresh_scenario_host_objects(scenario):\n assert host.scenario_id is None\n\n assert HostStageInfo.objects(scenario_id=scenario.scenario_id).count() == 0\n\n assert scenario.status == ScenarioFsmStatus.FINISHED\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"infra/tests/scenario/scenario_execution/test_hosts_add_script.py","file_name":"test_hosts_add_script.py","file_ext":"py","file_size_in_byte":19234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"523964224","text":"# %% [markdown]\n# # Thompson sampling\n\n# %%\nimport numpy as np\nimport tensorflow as tf\n\nnp.random.seed(1793)\ntf.random.set_seed(1793)\n\n# %% [markdown]\n# ## Define the problem and model\n#\n# You can use Thompson sampling for Bayesian optimization in much the same way as we used EGO and EI in the tutorial _Introduction_. Since the setup is much the same is in that tutorial, we'll skip over most of the detail.\n#\n# We'll use a continuous bounded search space, and evaluate the observer at ten random points.\n\n# %%\nimport trieste\nfrom trieste.objectives import Branin\n\nbranin = Branin.objective\nsearch_space = Branin.search_space\n\nnum_initial_data_points = 10\ninitial_query_points = search_space.sample(num_initial_data_points)\nobserver = trieste.objectives.utils.mk_observer(branin)\ninitial_data = observer(initial_query_points)\n\n# %% [markdown]\n# We'll use Gaussian process regression to model the function, as implemented in GPflow. The GPflow models cannot be used directly in our Bayesian optimization routines, so we build a GPflow's `GPR` model using Trieste's convenient model build function `build_gpr` and pass it to the `GaussianProcessRegression` wrapper. Note that we set the likelihood variance to a small number because we are dealing with a noise-free problem.\n\n# %%\nfrom trieste.models.gpflow import GaussianProcessRegression, build_gpr\n\n\ngpflow_model = build_gpr(initial_data, search_space, likelihood_variance=1e-7)\nmodel = GaussianProcessRegression(gpflow_model)\n\n\n# %% [markdown]\n# ## Create the Thompson sampling acquisition rule\n#\n# We achieve Bayesian optimization with Thompson sampling by specifying `DiscreteThompsonSampling` as the acquisition rule. Unlike the `EfficientGlobalOptimization` acquisition rule, `DiscreteThompsonSampling` does not use an acquisition function. Instead, in each optimization step, the rule samples `num_query_points` samples from the model posterior at `num_search_space_samples` points on the search space. It then returns the `num_query_points` points of those that minimise the model posterior.\n\n# %%\nnum_search_space_samples = 1000\nnum_query_points = 10\nacq_rule = trieste.acquisition.rule.DiscreteThompsonSampling(\n num_search_space_samples=num_search_space_samples,\n num_query_points=num_query_points,\n)\n\n# %% [markdown]\n# ## Run the optimization loop\n#\n# All that remains is to pass the Thompson sampling rule to the `BayesianOptimizer`. Once the optimization loop is complete, the optimizer will return `num_query_points` new query points for every step in the loop. With five steps, that's fifty points.\n\n# %%\nbo = trieste.bayesian_optimizer.BayesianOptimizer(observer, search_space)\n\nnum_steps = 5\nresult = bo.optimize(\n num_steps, initial_data, model, acq_rule, track_state=False\n)\ndataset = result.try_get_final_dataset()\n\n# %% [markdown]\n# ## Visualising the result\n#\n# We can take a look at where we queried the observer, both the original query points (crosses) and new query points (dots), and where they lie with respect to the contours of the Branin.\n\n# %%\nfrom trieste.experimental.plotting import plot_function_2d, plot_bo_points\n\narg_min_idx = tf.squeeze(tf.argmin(dataset.observations, axis=0))\nquery_points = dataset.query_points.numpy()\nobservations = dataset.observations.numpy()\n_, ax = plot_function_2d(\n branin,\n search_space.lower,\n search_space.upper,\n grid_density=40,\n contour=True,\n)\n\nplot_bo_points(query_points, ax[0, 0], num_initial_data_points, arg_min_idx)\n\n# %% [markdown]\n# We can also visualise the observations on a three-dimensional plot of the Branin. We'll add the contours of the mean and variance of the model's predictive distribution as translucent surfaces.\n\n# %%\nfrom trieste.experimental.plotting import (\n plot_model_predictions_plotly,\n add_bo_points_plotly,\n)\n\nfig = plot_model_predictions_plotly(\n result.try_get_final_model(),\n search_space.lower,\n search_space.upper,\n)\nfig = add_bo_points_plotly(\n x=query_points[:, 0],\n y=query_points[:, 1],\n z=observations[:, 0],\n num_init=num_initial_data_points,\n idx_best=arg_min_idx,\n fig=fig,\n figrow=1,\n figcol=1,\n)\nfig.show()\n\n# %% [markdown]\n# ## LICENSE\n#\n# [Apache License 2.0](https://github.com/secondmind-labs/trieste/blob/develop/LICENSE)\n","repo_name":"secondmind-labs/trieste","sub_path":"docs/notebooks/thompson_sampling.pct.py","file_name":"thompson_sampling.pct.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","stars":190,"dataset":"github-code","pt":"3"}
+{"seq_id":"14467571077","text":"from sklearn.preprocessing import StandardScaler\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndef PreprocessTrainData(dataframe:pd.DataFrame):\r\n train_y = dataframe[\"target\"]\r\n train_x = dataframe.drop(labels=[\"target\", \"casual\", \"registered\", \"instant\", \"dteday\"], axis=1)\r\n\r\n scaler = StandardScaler()\r\n train_x = scaler.fit_transform(train_x)\r\n train_y = np.log(train_y)\r\n return train_x, train_y\r\n\r\ndef PreprocessTestData(train_df:pd.DataFrame, test_df:pd.DataFrame):\r\n train_x = train_df.drop(labels=[\"target\", \"casual\", \"registered\", \"instant\", \"dteday\"], axis=1)\r\n test_y = test_df[\"target\"]\r\n test_x = test_df.drop(labels=[\"target\", \"casual\", \"registered\", \"instant\", \"dteday\"], axis=1)\r\n\r\n scaler = StandardScaler()\r\n train_x = scaler.fit_transform(train_x)\r\n test_x = scaler.transform(test_x)\r\n test_y = np.log(test_y)\r\n return test_x, test_y","repo_name":"davidbognar201/EPAM_MLE_MENTORING","sub_path":"Containerization/model_container/python_files/preprocessFunctions.py","file_name":"preprocessFunctions.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21261986609","text":"from flask import Flask, request, make_response, json\nfrom flask_cors import CORS\nimport subprocess\n\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route(\"/api/merge\", methods=[\"GET\", \"OPTIONS\"])\ndef merge():\n if request.method == \"OPTIONS\": # CORS preflight\n return _build_cors_preflight_response()\n elif request.method == \"GET\": # The actual request following the preflight\n movie_name = request.args.get('movie_name')\n subtitle_name = request.args.get('subtitle_name')\n\n try:\n process = subprocess.Popen(['python', 'script.py', movie_name, subtitle_name],\n stdout=subprocess.PIPE)\n out, err = process.communicate()\n print(out)\n print(err)\n data = {\"message\": \"Movie and subtitle merged successfully\"}\n response = app.response_class(response=json.dumps(data),\n status=200,\n mimetype='application/json')\n return _configure_cors_for_response(response)\n except:\n data = {\"message\": \"Couldn't merge movie and subtitle\"}\n response = app.response_class(response=json.dumps(data),\n status=500,\n mimetype='application/json')\n return _configure_cors_for_response(response)\n\n else:\n raise RuntimeError(\"Can't handle method {}\".format(request.method))\n\n\ndef _build_cors_preflight_response():\n response = make_response()\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n response.headers.add('Access-Control-Allow-Headers', \"*\")\n response.headers.add('Access-Control-Allow-Methods', \"*\")\n return response\n\n\ndef _configure_cors_for_response(response):\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n return response\n\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"Dado555/glef.icu","sub_path":"python-merge/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"72110991440","text":"import hou\nimport imath\nimport IECore\nimport IECoreScene\nimport IECoreHoudini\nimport unittest\nimport os\n\nclass TestFromHoudiniPolygonsConverter( IECoreHoudini.TestCase ) :\n\n\tdef createBox( self ) :\n\t\tobj = hou.node(\"/obj\")\n\t\tgeo = obj.createNode(\"geo\", run_init_scripts=False)\n\t\tbox = geo.createNode( \"box\" )\n\n\t\treturn box\n\n\tdef createTorus( self ) :\n\t\tobj = hou.node(\"/obj\")\n\t\tgeo = obj.createNode(\"geo\", run_init_scripts=False)\n\t\ttorus = geo.createNode( \"torus\" )\n\t\ttorus.parm( \"rows\" ).set( 10 )\n\t\ttorus.parm( \"cols\" ).set( 10 )\n\n\t\treturn torus\n\n\tdef createPoints( self ) :\n\t\tobj = hou.node(\"/obj\")\n\t\tgeo = obj.createNode(\"geo\", run_init_scripts=False)\n\t\tbox = geo.createNode( \"box\" )\n\t\tfacet = geo.createNode( \"facet\" )\n\t\tfacet.parm(\"postnml\").set(True)\n\t\tpoints = geo.createNode( \"scatter\" )\n\t\tpoints.parm( \"npts\" ).set( 5000 )\n\t\tfacet.setInput( 0, box )\n\t\tpoints.setInput( 0, facet )\n\n\t\treturn points\n\n\tdef createPopNet( self ):\n\t\tobj = hou.node( '/obj' )\n\t\tgeo = obj.createNode(\"geo\", run_init_scripts=False)\n\t\tpopNet = geo.createNode(\"dopnet\", \"popnet\" )\n\t\tpopObject = popNet.createNode( \"popobject\" )\n\t\tpopSolver = popObject.createOutputNode( \"popsolver\" )\n\t\toutput = popSolver.createOutputNode( \"output\" )\n\t\toutput.setDisplayFlag( True )\n\n\t\treturn popNet\n\n\t# creates a converter\n\tdef testCreateConverter( self ) :\n\t\tbox = self.createBox()\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( box )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\n\t\treturn converter\n\n\t# creates a converter\n\tdef testFactory( self ) :\n\t\tbox = self.createBox()\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.create( box )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.create( box, resultType = IECoreScene.TypeId.MeshPrimitive )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.create( box, resultType = IECore.TypeId.Parameter )\n\t\tself.assertEqual( converter, None )\n\n\t\tself.assertTrue( IECoreScene.TypeId.MeshPrimitive in IECoreHoudini.FromHoudiniGeometryConverter.supportedTypes() )\n\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.createDummy( IECoreScene.TypeId.MeshPrimitive )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.createDummy( [ IECoreScene.TypeId.MeshPrimitive ] )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\n\t# performs geometry conversion\n\tdef testDoConversion( self ) :\n\t\tconverter = self.testCreateConverter()\n\t\tresult = converter.convert()\n\t\tself.assertTrue( result.isInstanceOf( IECoreScene.TypeId.MeshPrimitive ) )\n\n\tdef testConvertFromHOMGeo( self ) :\n\t\tgeo = self.createBox().geometry()\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.createFromGeo( geo )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\n\t\tresult = converter.convert()\n\t\tself.assertTrue( result.isInstanceOf( IECoreScene.TypeId.MeshPrimitive ) )\n\n\t\tconverter2 = IECoreHoudini.FromHoudiniGeometryConverter.createFromGeo( geo, IECoreScene.TypeId.MeshPrimitive )\n\t\tself.assertTrue( converter2.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\n\t\t## \\todo: make sure we catch that bad_cast crash\n\n\t# convert a mesh\n\tdef testConvertMesh( self ) :\n\n\t\ttorus = self.createTorus()\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( torus )\n\t\tresult = converter.convert()\n\t\tself.assertEqual( result.typeId(), IECoreScene.MeshPrimitive.staticTypeId() )\n\n\t\tbbox = result.bound()\n\t\tself.assertEqual( bbox.min().x, -1.5 )\n\t\tself.assertEqual( bbox.max().x, 1.5 )\n\n\t\tself.assertEqual( result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Vertex ), 100 )\n\t\tself.assertEqual( result.numFaces(), 100 )\n\n\t\tself.assertEqual( len( result.verticesPerFace ), 100 )\n\t\tfor i in range( len( result.verticesPerFace ) ) :\n\t\t\tself.assertEqual( result.verticesPerFace[i], 4 )\n\n\t\tself.assertEqual( len( result.vertexIds ), 400 )\n\t\tfor i in range( len( result.vertexIds ) ) :\n\t\t\tself.assertTrue( result.vertexIds[i] >= 0 )\n\t\t\tself.assertTrue( result.vertexIds[i] < 100 )\n\n\t# test prim/vertex attributes\n\tdef testConvertPrimVertAttributes( self ) :\n\t\ttorus = self.createTorus()\n\t\tgeo = torus.parent()\n\n\t\t# add vertex normals\n\t\tfacet = geo.createNode( \"facet\", node_name = \"add_point_normals\" )\n\t\tfacet.parm(\"postnml\").set(True)\n\t\tfacet.setInput( 0, torus )\n\n\t\t# add a primitive colour attributes\n\t\tprimcol = geo.createNode( \"primitive\", node_name = \"prim_colour\" )\n\t\tprimcol.parm(\"doclr\").set(1)\n\t\tprimcol.parm(\"diffr\").setExpression(\"rand($PR)\")\n\t\tprimcol.parm(\"diffg\").setExpression(\"rand($PR+1)\")\n\t\tprimcol.parm(\"diffb\").setExpression(\"rand($PR+2)\")\n\t\tprimcol.setInput( 0, facet )\n\n\t\t# add a load of different vertex attributes\n\t\tvert_f1 = geo.createNode( \"attribcreate\", node_name = \"vert_f1\", exact_type_name=True )\n\t\tvert_f1.parm(\"name\").set(\"vert_f1\")\n\t\tvert_f1.parm(\"class\").set(3)\n\t\tvert_f1.parm(\"value1\").setExpression(\"$VTX*0.1\")\n\t\tvert_f1.setInput( 0, primcol )\n\n\t\tvert_f2 = geo.createNode( \"attribcreate\", node_name = \"vert_f2\", exact_type_name=True )\n\t\tvert_f2.parm(\"name\").set(\"vert_f2\")\n\t\tvert_f2.parm(\"class\").set(3)\n\t\tvert_f2.parm(\"size\").set(2)\n\t\tvert_f2.parm(\"value1\").setExpression(\"$VTX*0.1\")\n\t\tvert_f2.parm(\"value2\").setExpression(\"$VTX*0.1\")\n\t\tvert_f2.setInput( 0, vert_f1 )\n\n\t\tvert_f3 = geo.createNode( \"attribcreate\", node_name = \"vert_f3\", exact_type_name=True )\n\t\tvert_f3.parm(\"name\").set(\"vert_f3\")\n\t\tvert_f3.parm(\"class\").set(3)\n\t\tvert_f3.parm(\"size\").set(3)\n\t\tvert_f3.parm(\"value1\").setExpression(\"$VTX*0.1\")\n\t\tvert_f3.parm(\"value2\").setExpression(\"$VTX*0.1\")\n\t\tvert_f3.parm(\"value3\").setExpression(\"$VTX*0.1\")\n\t\tvert_f3.setInput( 0, vert_f2 )\n\n\t\tvert_i1 = geo.createNode( \"attribcreate\", node_name = \"vert_i1\", exact_type_name=True )\n\t\tvert_i1.parm(\"name\").set(\"vert_i1\")\n\t\tvert_i1.parm(\"class\").set(3)\n\t\tvert_i1.parm(\"type\").set(1)\n\t\tvert_i1.parm(\"value1\").setExpression(\"$VTX*0.1\")\n\t\tvert_i1.setInput( 0, vert_f3 )\n\n\t\tvert_i2 = geo.createNode( \"attribcreate\", node_name = \"vert_i2\", exact_type_name=True )\n\t\tvert_i2.parm(\"name\").set(\"vert_i2\")\n\t\tvert_i2.parm(\"class\").set(3)\n\t\tvert_i2.parm(\"type\").set(1)\n\t\tvert_i2.parm(\"size\").set(2)\n\t\tvert_i2.parm(\"value1\").setExpression(\"$VTX*0.1\")\n\t\tvert_i2.parm(\"value2\").setExpression(\"$VTX*0.1\")\n\t\tvert_i2.setInput( 0, vert_i1 )\n\n\t\tvert_i3 = geo.createNode( \"attribcreate\", node_name = \"vert_i3\", exact_type_name=True )\n\t\tvert_i3.parm(\"name\").set(\"vert_i3\")\n\t\tvert_i3.parm(\"class\").set(3)\n\t\tvert_i3.parm(\"type\").set(1)\n\t\tvert_i3.parm(\"size\").set(3)\n\t\tvert_i3.parm(\"value1\").setExpression(\"$VTX*0.1\")\n\t\tvert_i3.parm(\"value2\").setExpression(\"$VTX*0.1\")\n\t\tvert_i3.parm(\"value3\").setExpression(\"$VTX*0.1\")\n\t\tvert_i3.setInput( 0, vert_i2 )\n\n\t\tvert_v3f = geo.createNode( \"attribcreate\", node_name = \"vert_v3f\", exact_type_name=True )\n\t\tvert_v3f.parm(\"name\").set(\"vert_v3f\")\n\t\tvert_v3f.parm(\"class\").set(3)\n\t\tvert_v3f.parm(\"type\").set(2)\n\t\tvert_v3f.parm(\"value1\").setExpression(\"$VTX*0.1\")\n\t\tvert_v3f.parm(\"value2\").setExpression(\"$VTX*0.1\")\n\t\tvert_v3f.parm(\"value3\").setExpression(\"$VTX*0.1\")\n\t\tvert_v3f.setInput( 0, vert_i3 )\n\n\t\tvertString = geo.createNode( \"attribcreate\", node_name = \"vertString\", exact_type_name=True )\n\t\tvertString.parm(\"name\").set(\"vertString\")\n\t\tvertString.parm(\"class\").set(3)\n\t\tvertString.parm(\"type\").set(3)\n\t\tvertString.parm(\"string\").set(\"string $VTX!\")\n\t\tvertString.setInput( 0, vert_v3f )\n\n\t\tdetail_i3 = geo.createNode( \"attribcreate\", node_name = \"detail_i3\", exact_type_name=True )\n\t\tdetail_i3.parm(\"name\").set(\"detail_i3\")\n\t\tdetail_i3.parm(\"class\").set(0)\n\t\tdetail_i3.parm(\"type\").set(1)\n\t\tdetail_i3.parm(\"size\").set(3)\n\t\tdetail_i3.parm(\"value1\").set(123)\n\t\tdetail_i3.parm(\"value2\").set(456.789) # can we catch it out with a float?\n\t\tdetail_i3.parm(\"value3\").set(789)\n\t\tdetail_i3.setInput( 0, vertString )\n\n\t\tout = geo.createNode( \"null\", node_name=\"OUT\" )\n\t\tout.setInput( 0, detail_i3 )\n\n\t\t# convert it all\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( out )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\n\t\tresult = converter.convert()\n\t\tself.assertTrue( result.isInstanceOf( IECoreScene.TypeId.MeshPrimitive ) )\n\n\t\tbbox = result.bound()\n\t\tself.assertEqual( bbox.min().x, -1.5 )\n\t\tself.assertEqual( bbox.max().x, 1.5 )\n\n\t\tself.assertEqual( result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Vertex ), 100 )\n\t\tself.assertEqual( result.numFaces(), 100 )\n\n\t\tself.assertEqual( len( result.verticesPerFace ), 100 )\n\t\tfor i in range( len( result.verticesPerFace ) ) :\n\t\t\tself.assertEqual( result.verticesPerFace[i], 4 )\n\n\t\tself.assertEqual( len( result.vertexIds ), 400 )\n\t\tfor i in range( len( result.vertexIds ) ) :\n\t\t\tself.assertTrue( result.vertexIds[i] >= 0 )\n\t\t\tself.assertTrue( result.vertexIds[i] < 100 )\n\n\t\t# test point attributes\n\t\tself.assertTrue( \"P\" in result )\n\t\tself.assertEqual( result['P'].data.typeId(), IECore.TypeId.V3fVectorData )\n\t\tself.assertEqual( result['P'].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )\n\t\tself.assertEqual( result['P'].data.size(), result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Vertex ) )\n\t\tself.assertEqual( result[\"P\"].data.getInterpretation(), IECore.GeometricData.Interpretation.Point )\n\t\tself.assertTrue( \"N\" in result )\n\t\tself.assertEqual( result['N'].data.typeId(), IECore.TypeId.V3fVectorData )\n\t\tself.assertEqual( result['N'].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )\n\t\tself.assertEqual( result['N'].data.size(), result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Vertex ) )\n\t\tself.assertEqual( result[\"N\"].data.getInterpretation(), IECore.GeometricData.Interpretation.Normal )\n\n\t\t# test detail attributes\n\t\tself.assertTrue( \"detail_i3\" in result )\n\t\tself.assertEqual( result['detail_i3'].data.typeId(), IECore.TypeId.V3iData )\n\t\tself.assertEqual( result['detail_i3'].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Constant )\n\t\tself.assertEqual( result['detail_i3'].data.value.x, 123 )\n\t\tself.assertEqual( result['detail_i3'].data.value.y, 456 )\n\t\tself.assertEqual( result['detail_i3'].data.value.z, 789 )\n\n\t\t# test primitive attributes\n\t\tself.assertTrue( \"Cs\" in result )\n\t\tself.assertEqual( result[\"Cs\"].data.typeId(), IECore.TypeId.Color3fVectorData )\n\t\tself.assertEqual( result[\"Cs\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Uniform )\n\t\tself.assertEqual( result[\"Cs\"].data.size(), result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Uniform ) )\n\n\t\tfor i in range( 0, result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Uniform ) ) :\n\t\t\tfor j in range( 0, 3 ) :\n\t\t\t\tself.assertTrue( result[\"Cs\"].data[i][j] >= 0.0 )\n\t\t\t\tself.assertTrue( result[\"Cs\"].data[i][j] <= 1.0 )\n\n\t\t# test vertex attributes\n\t\tattrs = [ \"vert_f1\", \"vert_f2\", \"vert_f3\", \"vert_i1\", \"vert_i2\", \"vert_i3\", \"vert_v3f\" ]\n\t\tfor a in attrs :\n\t\t\tself.assertTrue( a in result )\n\t\t\tself.assertEqual( result[a].interpolation, IECoreScene.PrimitiveVariable.Interpolation.FaceVarying )\n\t\t\tself.assertEqual( result[a].data.size(), result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.FaceVarying ) )\n\n\t\t# test indexed vertex attributes\n\t\tfor a in [ \"vertString\" ] :\n\t\t\tself.assertTrue( a in result )\n\t\t\tself.assertEqual( result[a].interpolation, IECoreScene.PrimitiveVariable.Interpolation.FaceVarying )\n\t\t\tself.assertEqual( result[a].indices.size(), result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.FaceVarying ) )\n\n\t\tself.assertEqual( result[\"vert_f1\"].data.typeId(), IECore.FloatVectorData.staticTypeId() )\n\t\tself.assertEqual( result[\"vert_f2\"].data.typeId(), IECore.V2fVectorData.staticTypeId() )\n\t\tself.assertEqual( result[\"vert_f3\"].data.typeId(), IECore.V3fVectorData.staticTypeId() )\n\n\t\tfor i in range( 0, result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.FaceVarying ) ) :\n\t\t\tfor j in range( 0, 3 ) :\n\t\t\t\tself.assertTrue( result[\"vert_f3\"].data[i][j] >= 0.0 )\n\t\t\t\tself.assertTrue( result[\"vert_f3\"].data[i][j] < 0.4 )\n\n\t\tself.assertEqual( result[\"vert_i1\"].data.typeId(), IECore.IntVectorData.staticTypeId() )\n\t\tself.assertEqual( result[\"vert_i2\"].data.typeId(), IECore.V2iVectorData.staticTypeId() )\n\t\tself.assertEqual( result[\"vert_i3\"].data.typeId(), IECore.V3iVectorData.staticTypeId() )\n\n\t\tfor i in range( 0, result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.FaceVarying ) ) :\n\t\t\tfor j in range( 0, 3 ) :\n\t\t\t\tself.assertEqual( result[\"vert_i3\"].data[i][j], 0 )\n\n\t\tself.assertEqual( result[\"vert_v3f\"].data.typeId(), IECore.V3fVectorData.staticTypeId() )\n\n\t\tself.assertEqual( result[\"vertString\"].data.typeId(), IECore.TypeId.StringVectorData )\n\t\tself.assertEqual( result[\"vertString\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.FaceVarying )\n\t\tself.assertEqual( result[\"vertString\"].data.size(), 4 )\n\t\tself.assertEqual( result[\"vertString\"].indices.typeId(), IECore.TypeId.IntVectorData )\n\n\t\tfor i in range( 0, result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.FaceVarying ) ) :\n\t\t\tindex = result[\"vertString\"].indices[ result.vertexIds[i] ]\n\t\t\tself.assertEqual( result[\"vertString\"].data[ index ], \"string %d!\" % index )\n\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\tdef testConvertNull( self ) :\n\t\tobj = hou.node(\"/obj\")\n\t\tgeo = obj.createNode(\"geo\", run_init_scripts=False)\n\t\tnull = geo.createNode( \"null\" )\n\t\tm = IECoreHoudini.FromHoudiniPolygonsConverter( null ).convert()\n\t\tself.assertTrue( isinstance( m, IECoreScene.MeshPrimitive ) )\n\t\tself.assertEqual( m, IECoreScene.MeshPrimitive() )\n\n\t# convert some points\n\tdef testConvertPoints( self ) :\n\t\tpoints = self.createPoints()\n\t\tm = IECoreHoudini.FromHoudiniPolygonsConverter( points ).convert()\n\t\tself.assertTrue( isinstance( m, IECoreScene.MeshPrimitive ) )\n\t\tself.assertEqual( m, IECoreScene.MeshPrimitive() )\n\n\t# simple attribute conversion\n\tdef testSetupAttributes( self ) :\n\t\ttorus = self.createTorus()\n\t\tgeo = torus.parent()\n\t\tattr = geo.createNode( \"attribcreate\", exact_type_name=True )\n\t\tattr.setInput( 0, torus )\n\t\tattr.parm(\"name\").set( \"test_attribute\" )\n\t\tattr.parm(\"type\").set(0) # float\n\t\tattr.parm(\"size\").set(1) # 1 element\n\t\tattr.parm(\"value1\").set(123.456)\n\t\tattr.parm(\"value2\").set(654.321)\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( attr )\n\t\tresult = converter.convert()\n\t\tself.assertTrue( \"test_attribute\" in result.keys() )\n\t\tself.assertEqual( result[\"test_attribute\"].data.size(), 100 )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\treturn attr\n\n\t# testing point attributes and types\n\tdef testPointAttributes( self ) :\n\t\tattr = self.testSetupAttributes()\n\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tattr.parm(\"value1\").set(123.456)\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.FloatVectorData )\n\t\tself.assertTrue( result[\"test_attribute\"].data[0] > 123.0 )\n\t\tself.assertEqual( result[\"test_attribute\"].data.size(), 100 )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(1) # integer\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.IntVectorData )\n\t\tself.assertEqual( result[\"test_attribute\"].data[0], 123 )\n\t\tself.assertEqual( result[\"test_attribute\"].data.size(), 100 )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(0) # float\n\t\tattr.parm(\"size\").set(2) # 2 elementS\n\t\tattr.parm(\"value2\").set(456.789)\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.V2fVectorData )\n\t\tself.assertEqual( result[\"test_attribute\"].data[0], imath.V2f( 123.456, 456.789 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].data.size(), 100 )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(1) # int\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.V2iVectorData )\n\t\tself.assertEqual( result[\"test_attribute\"].data[0], imath.V2i( 123, 456 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].data.size(), 100 )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(0) # float\n\t\tattr.parm(\"size\").set(3) # 3 elements\n\t\tattr.parm(\"value3\").set(999.999)\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.V3fVectorData )\n\t\tself.assertEqual( result[\"test_attribute\"].data[0],imath.V3f( 123.456, 456.789, 999.999 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].data.size(), 100 )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(1) # int\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.V3iVectorData )\n\t\tself.assertEqual( result[\"test_attribute\"].data[0], imath.V3i( 123, 456, 999 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].data.size(), 100 )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set( 3 ) # string\n\t\tattr.parm( \"string\" ).setExpression(\"'string %06d!' % pwd().curPoint().number()\", hou.exprLanguage.Python)\n\t\tresult = IECoreHoudini.FromHoudiniPointsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.StringVectorData )\n\t\tself.assertEqual( result[\"test_attribute\"].data[10], \"string 000010!\" )\n\t\tself.assertEqual( result[\"test_attribute\"].data.size(), 100 )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Vertex )\n\t\tself.assertEqual( result[\"test_attribute\"].indices[10], 10 )\n\t\tself.assertEqual( result[\"test_attribute\"].indices.size(), 100 )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t# testing detail attributes and types\n\tdef testDetailAttributes( self ) :\n\t\tattr = self.testSetupAttributes()\n\t\tattr.parm(\"class\").set(0) # detail attribute\n\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tattr.parm(\"value1\").set(123.456)\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.FloatData )\n\t\tself.assertTrue( result[\"test_attribute\"].data > IECore.FloatData( 123.0 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Constant )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(1) # integer\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.IntData )\n\t\tself.assertEqual( result[\"test_attribute\"].data, IECore.IntData( 123 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Constant )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(0) # float\n\t\tattr.parm(\"size\").set(2) # 2 elementS\n\t\tattr.parm(\"value2\").set(456.789)\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.V2fData )\n\t\tself.assertEqual( result[\"test_attribute\"].data.value, imath.V2f( 123.456, 456.789 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Constant )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(1) # int\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.V2iData )\n\t\tself.assertEqual( result[\"test_attribute\"].data.value, imath.V2i( 123, 456 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Constant )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(0) # float\n\t\tattr.parm(\"size\").set(3) # 3 elements\n\t\tattr.parm(\"value3\").set(999.999)\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.V3fData )\n\t\tself.assertEqual( result[\"test_attribute\"].data.value, imath.V3f( 123.456, 456.789, 999.999 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Constant )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set(1) # int\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.V3iData )\n\t\tself.assertEqual( result[\"test_attribute\"].data.value, imath.V3i( 123, 456, 999 ) )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Constant )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tattr.parm(\"type\").set( 3 ) # string\n\t\tattr.parm( \"string\" ).set( \"string!\" )\n\t\tresult = IECoreHoudini.FromHoudiniPointsConverter( attr ).convert()\n\t\tself.assertEqual( result[\"test_attribute\"].data.typeId(), IECore.TypeId.StringData )\n\t\tself.assertEqual( result[\"test_attribute\"].data.value, \"string!\" )\n\t\tself.assertEqual( result[\"test_attribute\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.Constant )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t# testing that float[4] doesn't work!\n\tdef testFloat4attr( self ) : # we can't deal with float 4's right now\n\t\tattr = self.testSetupAttributes()\n\t\tattr.parm(\"name\").set( \"test_attribute\" )\n\t\tattr.parm(\"size\").set(4) # 4 elements per point-attribute\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( attr )\n\t\tresult = converter.convert()\n\t\tself.assertTrue( \"test_attribute\" not in result.keys() ) # invalid due to being float[4]\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t# testing conversion of animating geometry\n\tdef testAnimatingGeometry( self ) :\n\t\tobj = hou.node( \"/obj\" )\n\t\tgeo = obj.createNode( \"geo\", run_init_scripts=False )\n\t\ttorus = geo.createNode( \"torus\" )\n\t\tfacet = geo.createNode( \"facet\" )\n\t\tfacet.parm(\"postnml\").set(True)\n\t\tmountain = geo.createNode( \"mountain\" )\n\t\tif hou.applicationVersion()[0] >= 16:\n\t\t\tmountain.parm( \"offsetx\" ).setExpression( \"$FF\" )\n\t\telse:\n\t\t\tmountain.parm(\"offset1\").setExpression( \"$FF\" )\n\t\tfacet.setInput( 0, torus )\n\t\tmountain.setInput( 0, facet )\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( mountain )\n\t\thou.setFrame( 1 )\n\t\tmesh1 = converter.convert()\n\t\thou.setFrame( 2 )\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( mountain )\n\t\tmesh2 = converter.convert()\n\t\tself.assertNotEqual( mesh1[\"P\"].data, mesh2[\"P\"].data )\n\t\tself.assertNotEqual( mesh1, mesh2 )\n\n\t# testing we can handle an object being deleted\n\tdef testObjectWasDeleted( self ) :\n\t\tobj = hou.node(\"/obj\")\n\t\tgeo = obj.createNode(\"geo\", run_init_scripts=False)\n\t\ttorus = geo.createNode( \"torus\" )\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( torus )\n\t\tg1 = converter.convert()\n\t\ttorus.destroy()\n\t\tg2 = converter.convert()\n\t\tself.assertEqual( g2, g1 )\n\t\tself.assertRaises( RuntimeError, IECore.curry( IECoreHoudini.FromHoudiniPolygonsConverter, torus ) )\n\n\t# testing we can handle an object being deleted\n\tdef testObjectWasDeletedFactory( self ) :\n\t\tobj = hou.node(\"/obj\")\n\t\tgeo = obj.createNode(\"geo\", run_init_scripts=False)\n\t\ttorus = geo.createNode( \"torus\" )\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.create( torus )\n\t\tg1 = converter.convert()\n\t\ttorus.destroy()\n\t\tg2 = converter.convert()\n\t\tself.assertEqual( g2, g1 )\n\t\tself.assertRaises( RuntimeError, IECore.curry( IECoreHoudini.FromHoudiniGeometryConverter.create, torus ) )\n\n\t# testing converting a Houdini particle primitive with detail and point attribs\n\tdef testParticlePrimitive( self ) :\n\t\tobj = hou.node(\"/obj\")\n\t\tgeo = obj.createNode( \"geo\", run_init_scripts=False )\n\t\tpopnet = self.createPopNet()\n\t\tlocation = popnet.createNode( \"poplocation\" )\n\t\tpopSolver = popnet.node( \"popsolver1\" )\n\t\tpopSolver.setInput( 2, location )\n\t\tdetailAttr = popnet.createOutputNode( \"attribcreate\", exact_type_name=True )\n\t\tdetailAttr.parm(\"name\").set( \"float3detail\" )\n\t\tdetailAttr.parm(\"class\").set( 0 ) # detail\n\t\tdetailAttr.parm(\"type\").set( 0 ) # float\n\t\tdetailAttr.parm(\"size\").set( 3 ) # 3 elements\n\t\tdetailAttr.parm(\"value1\").set( 1 )\n\t\tdetailAttr.parm(\"value2\").set( 2 )\n\t\tdetailAttr.parm(\"value3\").set( 3 )\n\t\tpointAttr = detailAttr.createOutputNode( \"attribcreate\", exact_type_name=True )\n\t\tpointAttr.parm(\"name\").set( \"float3point\" )\n\t\tpointAttr.parm(\"class\").set( 2 ) # point\n\t\tpointAttr.parm(\"type\").set( 0 ) # float\n\t\tpointAttr.parm(\"size\").set( 3 ) # 3 elements\n\t\tpointAttr.parm(\"value1\").set( 1 )\n\t\tpointAttr.parm(\"value2\").set( 2 )\n\t\tpointAttr.parm(\"value3\").set( 3 )\n\n\t\tparticleSystem = pointAttr.createOutputNode( \"add\" )\n\t\tparticleSystem.parm( \"addparticlesystem\" ).set( True )\n\n\t\thou.setFrame( 5 )\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( particleSystem )\n\t\tself.assertRaises( RuntimeError, converter.convert )\n\n\t\tadd = particleSystem.createOutputNode( \"add\" )\n\t\tadd.parm( \"keep\" ).set( 1 ) # deletes primitive and leaves points\n\n\t\tm = IECoreHoudini.FromHoudiniPolygonsConverter( add ).convert()\n\t\tself.assertTrue( isinstance( m, IECoreScene.MeshPrimitive ) )\n\t\tself.assertEqual( m, IECoreScene.MeshPrimitive() )\n\n\t# testing winding order\n\tdef testWindingOrder( self ) :\n\t\tobj = hou.node( \"/obj\" )\n\t\tgeo = obj.createNode( \"geo\", run_init_scripts=False )\n\t\tgrid = geo.createNode( \"grid\" )\n\t\tgrid.parm( \"rows\" ).set( 2 )\n\t\tgrid.parm( \"cols\" ).set( 2 )\n\n\t\tmesh = IECoreHoudini.FromHoudiniPolygonsConverter( grid ).convert()\n\t\tp = mesh[\"P\"].data\n\t\tvertexIds = mesh.vertexIds\n\t\tself.assertEqual( vertexIds.size(), 4 )\n\n\t\tloop = IECore.V3fVectorData( [ p[vertexIds[0]], p[vertexIds[1]], p[vertexIds[2]], p[vertexIds[3]] ] )\n\t\tself.assertTrue( IECore.polygonNormal( loop ).equalWithAbsError( imath.V3f( 0, 1, 0 ), 0.0001 ) )\n\n\t# testing vertex data order\n\tdef testVertexDataOrder( self ) :\n\t\tobj = hou.node( \"/obj\" )\n\t\tgeo = obj.createNode( \"geo\", run_init_scripts=False )\n\t\tgrid = geo.createNode( \"grid\" )\n\t\tgrid.parm( \"rows\" ).set( 2 )\n\t\tgrid.parm( \"cols\" ).set( 2 )\n\t\tattr = grid.createOutputNode( \"attribcreate\", exact_type_name=True )\n\t\tattr.parm(\"name\").set( \"vertex\" )\n\t\tattr.parm(\"class\").set( 3 ) # vertex\n\t\tattr.parm(\"type\").set( 0 ) # float\n\t\tattr.parm(\"value1\").setExpression( \"$VTX\" )\n\n\t\tmesh = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertEqual( mesh[\"vertex\"].data, IECore.FloatVectorData( [ 3, 2, 1, 0 ] ) )\n\n\tdef testEmptyStringAttr( self ) :\n\t\ttorus = self.createTorus()\n\t\tgeo = torus.parent()\n\t\tattr = geo.createNode( \"attribcreate\", exact_type_name=True )\n\t\tattr.setInput( 0, torus )\n\t\tattr.parm(\"name\").set( \"test_attribute\" )\n\t\tattr.parm(\"type\").set(3) # string\n\t\tattr.parm(\"string\").set(\"\")\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( attr )\n\t\tresult = converter.convert()\n\t\tself.assertTrue( \"test_attribute\" in result.keys() )\n\t\tself.assertEqual( result[\"test_attribute\"].data.size(), 1 )\n\t\tself.assertEqual( result[\"test_attribute\"].indices.size(), 100 )\n\t\tself.assertEqual( result[\"test_attribute\"].data[0], \"\" )\n\t\tfor i in range( 0, 100 ) :\n\t\t\tself.assertEqual( result[\"test_attribute\"].indices[i], 0 )\n\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\tdef testName( self ) :\n\n\t\ttorus = self.createTorus()\n\t\tname = torus.createOutputNode( \"name\" )\n\t\tname.parm( \"name1\" ).set( \"torus\" )\n\t\tbox = torus.parent().createNode( \"box\" )\n\t\tname2 = box.createOutputNode( \"name\" )\n\t\tname2.parm( \"name1\" ).set( \"box\" )\n\t\tmerge = name.createOutputNode( \"merge\" )\n\t\tmerge.setInput( 1, name2 )\n\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( merge )\n\t\tresult = converter.convert()\n\t\t# names are not stored on the object at all\n\t\tself.assertEqual( result.blindData(), IECore.CompoundData() )\n\t\tself.assertFalse( \"name\" in result )\n\t\t# both torii were converted as one mesh\n\t\tself.assertEqual( result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Uniform ), 106 )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.create( merge, \"torus\" )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\t\tresult = converter.convert()\n\t\t# names are not stored on the object at all\n\t\tself.assertEqual( result.blindData(), IECore.CompoundData() )\n\t\tself.assertFalse( \"name\" in result )\n\t\t# only the named polygons were converted\n\t\tself.assertEqual( result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Uniform ), 100 )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.create( merge, \"box\" )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\t\tresult = converter.convert()\n\t\t# names are not stored on the object at all\n\t\tself.assertEqual( result.blindData(), IECore.CompoundData() )\n\t\tself.assertFalse( \"name\" in result )\n\t\t# only the named polygons were converted\n\t\tself.assertEqual( result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Uniform ), 6 )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\t\t# the name filter will create a single MeshPrimitive\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.create( merge, \"*\" )\n\t\tself.assertTrue( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )\n\t\tresult = converter.convert()\n\n\t\tself.assertEqual( result.variableSize( IECoreScene.PrimitiveVariable.Interpolation.Uniform ), 106 )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\n\tdef testAttributeFilter( self ) :\n\n\t\ttorus = self.createTorus()\n\n\t\t# add vertex normals\n\t\tfacet = torus.createOutputNode( \"facet\", node_name = \"add_point_normals\" )\n\t\tfacet.parm(\"postnml\").set(True)\n\n\t\t# add a primitive colour attributes\n\t\tprimcol = facet.createOutputNode( \"primitive\", node_name = \"prim_colour\" )\n\t\tprimcol.parm(\"doclr\").set(1)\n\t\tprimcol.parm(\"diffr\").setExpression(\"rand($PR)\")\n\t\tprimcol.parm(\"diffg\").setExpression(\"rand($PR+1)\")\n\t\tprimcol.parm(\"diffb\").setExpression(\"rand($PR+2)\")\n\n\t\tdetail = primcol.createOutputNode( \"attribcreate\", node_name = \"detail\", exact_type_name=True )\n\t\tdetail.parm(\"name\").set(\"detailAttr\")\n\t\tdetail.parm(\"class\").set(0)\n\t\tdetail.parm(\"type\").set(1)\n\t\tdetail.parm(\"size\").set(3)\n\t\tdetail.parm(\"value1\").set(123)\n\t\tdetail.parm(\"value2\").set(456.789) # can we catch it out with a float?\n\t\tdetail.parm(\"value3\").set(789)\n\n\t\tuvunwrap = detail.createOutputNode( \"uvunwrap\" )\n\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( uvunwrap )\n\t\tself.assertEqual( sorted(converter.convert().keys()), [ \"Cs\", \"N\", \"P\", \"detailAttr\", \"uv\", \"varmap\" ] )\n\t\tconverter.parameters()[\"attributeFilter\"].setTypedValue( \"P\" )\n\t\tself.assertEqual( sorted(converter.convert().keys()), [ \"P\" ] )\n\t\tconverter.parameters()[\"attributeFilter\"].setTypedValue( \"* ^N ^varmap\" )\n\t\tself.assertEqual( sorted(converter.convert().keys()), [ \"Cs\", \"P\", \"detailAttr\", \"uv\" ] )\n\t\t# P must be converted\n\t\tconverter.parameters()[\"attributeFilter\"].setTypedValue( \"* ^P\" )\n\t\tself.assertTrue( \"P\" in converter.convert().keys() )\n\t\t# have to filter the source attr\n\t\tconverter.parameters()[\"attributeFilter\"].setTypedValue( \"Cs\" )\n\t\tself.assertEqual( sorted(converter.convert().keys()), [ \"P\" ] )\n\t\tconverter.parameters()[\"attributeFilter\"].setTypedValue( \"Cd\" )\n\t\tself.assertEqual( sorted(converter.convert().keys()), [ \"Cs\", \"P\" ] )\n\t\tconverter.parameters()[\"attributeFilter\"].setTypedValue( \"uv Cd\" )\n\t\tself.assertEqual( sorted(converter.convert().keys()), [ \"Cs\", \"P\", \"uv\" ] )\n\n\tdef testStandardAttributeConversion( self ) :\n\n\t\ttorus = self.createTorus()\n\t\tcolor = torus.createOutputNode( \"color\" )\n\t\tcolor.parm( \"colortype\" ).set( 2 )\n\t\trest = color.createOutputNode( \"rest\" )\n\t\tscale = rest.createOutputNode( \"attribcreate\" )\n\t\tscale.parm( \"name1\" ).set( \"pscale\" )\n\t\tscale.parm( \"value1v1\" ).setExpression( \"$PT\" )\n\t\tuvunwrap = scale.createOutputNode( \"uvunwrap\" )\n\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( uvunwrap )\n\t\tresult = converter.convert()\n\t\tif hou.applicationVersion()[0] >= 15 :\n\t\t\tself.assertEqual( result.keys(), [ \"Cs\", \"P\", \"Pref\", \"uv\", \"width\" ] )\n\t\telse :\n\t\t\tself.assertEqual( result.keys(), [ \"Cs\", \"P\", \"Pref\", \"uv\", \"varmap\", \"width\" ] )\n\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\t\tself.assertEqual( result[\"P\"].data.getInterpretation(), IECore.GeometricData.Interpretation.Point )\n\t\tself.assertEqual( result[\"Pref\"].data.getInterpretation(), IECore.GeometricData.Interpretation.Point )\n\t\tself.assertEqual( result[\"uv\"].data.getInterpretation(), IECore.GeometricData.Interpretation.UV )\n\n\t\tuvData = result[\"uv\"].data\n\t\tuvIndices = result[\"uv\"].indices\n\n\t\tgeo = uvunwrap.geometry()\n\t\tuvs = geo.findVertexAttrib( \"uv\" )\n\n\t\ti = 0\n\t\tfor prim in geo.prims() :\n\t\t\tverts = list(prim.vertices())\n\t\t\tverts.reverse()\n\t\t\tfor vert in verts :\n\t\t\t\tuvValues = vert.attribValue( uvs )\n\t\t\t\tself.assertAlmostEqual( uvData[ uvIndices[i] ][0], uvValues[0] )\n\t\t\t\tself.assertAlmostEqual( uvData[ uvIndices[i] ][1], uvValues[1] )\n\t\t\t\ti += 1\n\n\t\tconverter[\"convertStandardAttributes\"].setTypedValue( False )\n\t\tresult = converter.convert()\n\t\tif hou.applicationVersion()[0] >= 15 :\n\t\t\tself.assertEqual( result.keys(), [ \"Cd\", \"P\", \"pscale\", \"rest\", \"uv\" ] )\n\t\telse :\n\t\t\tself.assertEqual( result.keys(), [ \"Cd\", \"P\", \"pscale\", \"rest\", \"uv\", \"varmap\" ] )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\t\tself.assertEqual( result[\"P\"].data.getInterpretation(), IECore.GeometricData.Interpretation.Point )\n\t\tself.assertEqual( result[\"rest\"].data.getInterpretation(), IECore.GeometricData.Interpretation.Point )\n\n\t\tuvData = result[\"uv\"].data\n\t\tuvIndices = result[\"uv\"].indices\n\n\t\tgeo = uvunwrap.geometry()\n\t\tuvs = geo.findVertexAttrib( \"uv\" )\n\n\t\ti = 0\n\t\tfor prim in geo.prims() :\n\t\t\tverts = list(prim.vertices())\n\t\t\tverts.reverse()\n\t\t\tfor vert in verts :\n\t\t\t\tuvValues = vert.attribValue( uvs )\n\t\t\t\tself.assertAlmostEqual( uvData[ uvIndices[i] ][0], uvValues[0] )\n\t\t\t\tself.assertAlmostEqual( uvData[ uvIndices[i] ][1], uvValues[1] )\n\t\t\t\ti += 1\n\n\tdef testWeldUVs( self ) :\n\n\t\ttorus = self.createTorus()\n\t\tuvunwrap = torus.createOutputNode( \"uvunwrap\" )\n\n\t\tconverter = IECoreHoudini.FromHoudiniPolygonsConverter( uvunwrap )\n\t\tresult = converter.convert()\n\t\tif hou.applicationVersion()[0] >= 15 :\n\t\t\tself.assertEqual( result.keys(), [ \"P\", \"uv\" ] )\n\t\telse :\n\t\t\tself.assertEqual( result.keys(), [ \"P\", \"uv\", \"varmap\" ] )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\t\tself.assertEqual( result[\"uv\"].data.getInterpretation(), IECore.GeometricData.Interpretation.UV )\n\t\tself.assertEqual( result[\"uv\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.FaceVarying )\n\n\t\tuvData = result[\"uv\"].data\n\t\tuvIndices = result[\"uv\"].indices\n\n\t\tgeo = uvunwrap.geometry()\n\t\tuvs = geo.findVertexAttrib( \"uv\" )\n\n\t\ti = 0\n\t\tfor prim in geo.prims() :\n\t\t\tverts = list(prim.vertices())\n\t\t\tverts.reverse()\n\t\t\tfor vert in verts :\n\t\t\t\tuvValues = vert.attribValue( uvs )\n\t\t\t\tself.assertAlmostEqual( uvData[ uvIndices[i] ][0], uvValues[0] )\n\t\t\t\tself.assertAlmostEqual( uvData[ uvIndices[i] ][1], uvValues[1] )\n\t\t\t\ti += 1\n\n\t\tconverter[\"weldUVs\"].setTypedValue( False )\n\t\tresult = converter.convert()\n\t\tif hou.applicationVersion()[0] >= 15 :\n\t\t\tself.assertEqual( result.keys(), [ \"P\", \"uv\" ] )\n\t\telse :\n\t\t\tself.assertEqual( result.keys(), [ \"P\", \"uv\", \"varmap\" ] )\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\t\tself.assertEqual( result[\"uv\"].data.getInterpretation(), IECore.GeometricData.Interpretation.UV )\n\t\tself.assertEqual( result[\"uv\"].interpolation, IECoreScene.PrimitiveVariable.Interpolation.FaceVarying )\n\n\t\tuvData = result[\"uv\"].data\n\t\tself.assertEqual( result[\"uv\"].indices, None )\n\n\t\tgeo = uvunwrap.geometry()\n\t\tuvs = geo.findVertexAttrib( \"uv\" )\n\n\t\ti = 0\n\t\tfor prim in geo.prims() :\n\t\t\tverts = list(prim.vertices())\n\t\t\tverts.reverse()\n\t\t\tfor vert in verts :\n\t\t\t\tuvValues = vert.attribValue( uvs )\n\t\t\t\tself.assertAlmostEqual( uvData[i][0], uvValues[0] )\n\t\t\t\tself.assertAlmostEqual( uvData[i][1], uvValues[1] )\n\t\t\t\ti += 1\n\n\tdef testInterpolation( self ) :\n\n\t\ttorus = self.createTorus()\n\t\tnormals = torus.createOutputNode( \"facet\" )\n\t\tnormals.parm( \"postnml\" ).set( True )\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( normals ).convert()\n\t\tself.assertTrue( \"ieMeshInterpolation\" not in result.keys() )\n\t\tself.assertEqual( result.interpolation, \"linear\" )\n\t\tself.assertTrue( \"N\" in result.keys() )\n\n\t\tattr = normals.createOutputNode( \"attribcreate\", node_name = \"interpolation\", exact_type_name=True )\n\t\tattr.parm( \"name\" ).set( \"ieMeshInterpolation\" )\n\t\tattr.parm( \"class\" ).set( 1 ) # prim\n\t\tattr.parm( \"type\" ).set( 3 ) # string\n\t\tattr.parm( \"string\") .set( \"subdiv\" )\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertTrue( \"ieMeshInterpolation\" not in result.keys() )\n\t\tself.assertEqual( result.interpolation, \"catmullClark\" )\n\t\tself.assertTrue( \"N\" not in result.keys() )\n\n\t\tattr.parm( \"string\") .set( \"poly\" )\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attr ).convert()\n\t\tself.assertTrue( \"ieMeshInterpolation\" not in result.keys() )\n\t\tself.assertEqual( result.interpolation, \"linear\" )\n\t\tself.assertTrue( \"N\" in result.keys() )\n\n\tdef testRename( self ) :\n\n\t\ttorus = self.createTorus()\n\t\tname = torus.createOutputNode( \"name\" )\n\t\tname.parm( \"name1\" ).set( \"foo\" )\n\t\trename = name.createOutputNode( \"name\" )\n\t\trename.parm( \"name1\" ).set( \"bar\" )\n\n\t\tconverter = IECoreHoudini.FromHoudiniGeometryConverter.create( rename )\n\t\tself.assertTrue( isinstance( converter, IECoreHoudini.FromHoudiniPolygonsConverter ) )\n\t\tself.assertTrue( isinstance( converter.convert(), IECoreScene.MeshPrimitive ) )\n\n\n\tdef testRenamedUVsExportedWithInterpretation( self ):\n\n\t\tbox = self.createBox() # create cube geometry\n\t\tquickShade = box.createOutputNode(\"uvquickshade\") # quickly generate orthographically projected UVs\n\t\tattribute = quickShade.createOutputNode(\"attribute\") # rename the 'uv' attribute 'foo'\n\t\tattribute.parm(\"frompt0\").set(\"uv\")\n\t\tattribute.parm(\"topt0\").set(\"foo\")\n\n\t\tconvertToCortex = attribute.createOutputNode(\"ieCortexConverter\")\n\t\tconvertToCortex.parm(\"resultType\").set(0) # convert to cortex\n\t\tconvertToHoudini = convertToCortex.createOutputNode(\"ieCortexConverter\")\n\t\tconvertToHoudini.parm(\"resultType\").set(1) # convert to back to houdini\n\n\t\tgeo = convertToHoudini.geometry()\n\t\tfooAttrib = geo.findPointAttrib( \"foo\" )\n\n\t\tself.assertEqual( fooAttrib.qualifier(), \"Texture Coord\")\n\n\t\troundTrippedUVs = []\n\t\tindex = 0\n\t\tfor pnt in geo.points() :\n\t\t\troundTrippedUVs.append( pnt.attribValue( fooAttrib ) )\n\n\t\tself.assertEqual( roundTrippedUVs, [\n\t\t\t(0.0, 0.0, 0.0),\n\t\t\t(1.0, 0.0, 0.0),\n\t\t\t(1.0, 1.0, 0.0),\n\t\t\t(0.0, 1.0, 0.0),\n\t\t\t(0.0, 0.0, 0.0),\n\t\t\t(1.0, 0.0, 0.0),\n\t\t\t(1.0, 1.0, 0.0),\n\t\t\t(0.0, 1.0, 0.0)] )\n\n\tdef testAttributeNamedUVIsAlwaysIndexed( self ):\n\n\t\tbox = self.createBox() # create cube geometry\n\t\tattributeCreate = box.createOutputNode(\"attribcreate\", exact_type_name=True)\n\t\tattributeCreate.parm(\"class\").set(3) # vertex\n\t\tattributeCreate.parm(\"type\").set(0) #float\n\t\tattributeCreate.parm(\"typeinfo\").set(1) # None\n\t\tattributeCreate.parm(\"name\").set(\"uv\") #attribute is named uv\n\t\tattributeCreate.parm(\"size\").set(3) #float3\n\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( attributeCreate ).convert()\n\n\t\tself.assertEqual( result[\"uv\"].data, IECore.V2fVectorData( [imath.V2f( 0, 0 )], IECore.GeometricData.Interpretation.UV ) )\n\t\tself.assertEqual( result[\"uv\"].indices, IECore.IntVectorData( [0] * 24 ) )\n\n\tdef testCornersAndCreases( self ):\n\n\t\tbox = self.createBox() # create cube geometry\n\t\tcrease = box.createOutputNode(\"crease\", exact_type_name=True)\n\t\tcrease.parm(\"group\").set(\"p5-6 p4-5-1\")\n\t\tcrease.parm(\"crease\").set(1.29)\n\t\tdodgyCorner = crease.createOutputNode(\"crease\", exact_type_name=True)\n\t\tdodgyCorner.parm(\"group\").set(\"p7\")\n\t\tdodgyCorner.parm(\"crease\").set(10.0)\n\t\tdodgyCorner.parm(\"creaseattrib\").set(\"cornerweight\")\n\t\tcorner = dodgyCorner.createOutputNode(\"attribpromote\", exact_type_name=True)\n\t\tcorner.parm(\"inname\").set(\"cornerweight\")\n\t\tcorner.parm(\"inclass\").set(3) # vertex\n\t\tcorner.parm(\"method\").set(1) # minimum (to avoid interpolation)\n\n\t\tresult = IECoreHoudini.FromHoudiniPolygonsConverter( corner ).convert()\n\t\tself.assertTrue( result.arePrimitiveVariablesValid() )\n\t\tself.assertEqual( result.keys(), [ \"P\" ] )\n\n\t\tself.assertEqual( result.cornerIds(), IECore.IntVectorData( [ 7 ] ) )\n\t\tself.assertEqual( result.cornerSharpnesses(), IECore.FloatVectorData( [ 10.0 ] ) )\n\n\t\tself.assertEqual( result.creaseLengths(), IECore.IntVectorData( [ 2, 2, 2 ] ) )\n\t\tself.assertEqual( result.creaseIds(), IECore.IntVectorData( [ 1, 5, 4, 5, 5, 6 ] ) )\n\t\tself.assertEqual( result.creaseSharpnesses(), IECore.FloatVectorData( [ 1.29, 1.29, 1.29 ] ) )\n\n\tdef testMeshInterpolationCrash( self ):\n\n\t\tsubnet = hou.node(\"/obj\").createNode(\"subnet\")\n\t\tgeo = subnet.createNode( \"geo\", \"geo\" )\n\n\t\ttorus = geo.createNode( \"torus\" )\n\t\ttorus.parm( \"rows\" ).set( 1000 )\n\t\ttorus.parm( \"cols\" ).set( 1000 )\n\n\t\tgrouprange = torus.createOutputNode( \"grouprange\" )\n\t\tgrouprange.parm( \"groupname1\" ).set( \"mygroup\" )\n\t\tgrouprange.parm( \"end1\" ).set(50)\n\n\t\tname1 = grouprange.createOutputNode( \"name\" )\n\t\tname1.parm( \"numnames\" ).set( 2 )\n\t\tname1.parm( \"name1\" ).set( \"/torus/all/of/it\" )\n\t\tname1.parm( \"name2\" ).set( \"/torus/part/of/it\" )\n\t\tname1.parm( \"group2\" ).set( \"mygroup\" )\n\n\t\tname2 = name1.createOutputNode( \"name\" )\n\t\tname2.parm( \"attribname\" ).set( \"ieMeshInterpolation\" )\n\t\tname2.parm( \"numnames\" ).set( 2 )\n\t\tname2.parm( \"name1\" ).set( \"poly\" )\n\t\tname2.parm( \"name2\" ).set( \"subdiv\" )\n\t\tname2.parm( \"group2\" ).set( \"mygroup\" )\n\n\t\tgroupdelete = name2.createOutputNode( \"groupdelete\" )\n\t\tgroupdelete.parm( \"group1\" ).set( \"mygroup\" )\n\n\t\tobjectMerge = geo.createNode( \"object_merge\" )\n\t\tobjectMerge.parm( \"objpath1\" ).set( groupdelete.path() )\n\t\tobjectMerge.parm( \"group1\" ).set( \"@name=/torus/part/of/it\" )\n\t\tobjectMerge.parm( \"xformtype\" ).set( 1 )\n\n\t\tname3 = objectMerge.createOutputNode( \"name\" )\n\t\tname3.parm( \"name1\" ).set( \"/\" )\n\t\tname3.setDisplayFlag( True )\n\t\tname3.setRenderFlag( True )\n\n\t\tresult = IECoreHoudini.FromHoudiniGeometryConverter.create( hou.node( '/obj/subnet1/geo/name3' ) ).convert()\n\t\tself.assertTrue( isinstance( result, IECoreScene.MeshPrimitive ) )\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"ImageEngine/cortex","sub_path":"test/IECoreHoudini/FromHoudiniPolygonsConverter.py","file_name":"FromHoudiniPolygonsConverter.py","file_ext":"py","file_size_in_byte":43625,"program_lang":"python","lang":"en","doc_type":"code","stars":510,"dataset":"github-code","pt":"3"}
+{"seq_id":"17327208025","text":"from flask import Flask,render_template,request,url_for,redirect,session,flash,jsonify,abort\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom sqlalchemy.exc import TimeoutError\r\nfrom flask_login import LoginManager,login_user,logout_user,login_required,current_user\r\nfrom flask_session import Session\r\nfrom flask_admin import Admin\r\nfrom flask_admin.contrib.sqla import ModelView\r\nfrom datetime import datetime,date\r\nfrom pytz import timezone\r\nfrom passlib.hash import pbkdf2_sha256\r\nfrom models import *\r\nimport requests\r\nimport numpy as np\r\nimport numpy.linalg\r\nfrom flask_socketio import SocketIO,send,emit\r\nimport os\r\napp = Flask(__name__)\r\napp.secret_key=os.environ.get('SECRET_KEY')\r\napp.config[\"SESSION_PERMANENT\"]=False\r\napp.config[\"SESSION_TYPE\"]=\"filesystem\"\r\napp.config[\"SQLALCHEMY_DATABASE_URI\"]=os.environ.get('DATABASE_URL')\r\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] =False\r\napp.config['FLASK_ADMIN_SWATCH'] = 'cerulean'\r\napp.config['SQLALCHEMY_POOL_SIZE']=25\r\napp.config['SQLALCHEMY_MAX_OVERFLOW']=15\r\napp.config['SQLALCHEMY_POOL_TIMEOUT']=30\r\napp.config['SQLALCHEMY_POOL_RECYCLE']=1000\r\nSession(app)\r\nsocketio = SocketIO(app)\r\nnotes=[]\r\ndata={'results1':\"\",'results2':\"\",'results3':'','results4':'','results5':''}\r\nusers={}\r\ndb=SQLAlchemy(app)\r\nlogin=LoginManager(app)\r\nlogin.init_app(app)\r\n@login.user_loader\r\ndef user_loader(id):\r\n return User.query.get(int(id))\r\nclass MyModelView(ModelView):\r\n def is_accessible(self):\r\n return current_user.email=='nayan.h4.aec@gmail.com'\r\n def inaccessible_callback(self, name, **kwargs):\r\n return redirect(url_for('signin', next=request.url))\r\nadmin = Admin(app)\r\nadmin.add_view(MyModelView(User, db.session))\r\ndef validate_email(email):\r\n if email[-4::]=='.com' or email[-3::]=='.in':\r\n return True\r\n else:\r\n return False\r\n@app.route(\"/home\")\r\ndef home():\r\n if current_user.is_active:\r\n name=current_user.first_name\r\n else:\r\n name=''\r\n tz_london=timezone('Europe/London')\r\n tz_india=timezone('Asia/Kolkata')\r\n now=datetime.now(tz_india).strftime(\"%I:%M %p\")\r\n d=datetime.now(tz_india).strftime(\"%B %d %Y\")\r\n return render_template(\"home.html\",name=name,today=d,now=now)\r\n@app.route(\"/signup\",methods=[\"POST\",\"GET\"])\r\ndef signup():\r\n if request.method==\"POST\":\r\n first_name=request.form.get(\"first_name\")\r\n last_name=request.form.get(\"last_name\")\r\n email=request.form.get(\"email\")\r\n gender=request.form.get(\"gender\")\r\n birthday=request.form.get(\"birthday\")\r\n password=request.form.get(\"password\")\r\n password2=request.form.get(\"password2\")\r\n hashed=pbkdf2_sha256.hash(password)\r\n if User.query.filter_by(email=email).first():\r\n flash(u\"Email already exists\",\"danger\")\r\n return redirect(url_for('signup'))\r\n if password!=password2:\r\n flash(u\"Both password should be same\",\"warning\")\r\n return redirect(url_for('signup'))\r\n if not validate_email(email):\r\n flash(u\"Email not valid\",\"error\")\r\n return redirect(url_for('signup'))\r\n try:\r\n user=User(first_name=first_name,last_name=last_name,email=email,gender=gender,birthday=birthday,hash=hashed)\r\n db.session.add(user)\r\n db.session.commit()\r\n except:\r\n db.session.rollback()\r\n return render_template('500.html')\r\n finally:\r\n db.session.close()\r\n flash(u\"You have registered successfully\",\"success\")\r\n return redirect(url_for('signin'))\r\n return render_template(\"signup.html\")\r\n@app.route(\"/signin\",methods=[\"POST\",\"GET\"])\r\ndef signin():\r\n if request.method==\"POST\":\r\n email=request.form.get(\"email\")\r\n password=request.form.get(\"password\")\r\n user=User.query.filter_by(email=email).first()\r\n if current_user.is_active:\r\n flash(u\"You are already logged in\",\"warning\")\r\n return redirect(url_for('signin'))\r\n if not user:\r\n flash(u'User not found','error')\r\n return redirect(url_for('signin'))\r\n if not pbkdf2_sha256.verify(password,user.hash):\r\n flash(u\"Incorrect password\",\"danger\")\r\n return redirect(url_for('signin'))\r\n login_user(user)\r\n return redirect(url_for('index'))\r\n return render_template(\"signin.html\")\r\n@app.route(\"/calender\",methods=[\"POST\",\"GET\"])\r\ndef calender():\r\n\treturn render_template(\"calender.html\")\r\n@app.route(\"/convert\")\r\ndef convert():\r\n return render_template(\"convert.html\")\r\n@app.route(\"/weather\")\r\ndef weather():\r\n return render_template(\"weather.html\")\r\n@app.route(\"/\")\r\ndef index():\r\n if current_user.is_active:\r\n name=current_user.first_name.capitalize()\r\n else:\r\n name=\"Guest\"\r\n return render_template(\"base.html\",name=name)\r\n@app.route(\"/search\",methods=[\"GET\",\"POST\"])\r\ndef search():\r\n search_input=request.form.get('search_name').lower()\r\n print(search_input)\r\n if search_input[0]==\"w\":\r\n return redirect(url_for('weather'))\r\n if search_input[0]==\"m\":\r\n return redirect(url_for('chat'))\r\n if search_input[0]==\"a\":\r\n return redirect(url_for('about'))\r\n if search_input[0]==\"h\":\r\n return redirect(url_for('home'))\r\n if search_input[0]==\"s\":\r\n if not current_user.is_authenticated:\r\n flash(u\"You haven't logged yet\",\"error\")\r\n return redirect(url_for('signin'))\r\n return redirect(url_for('signout'))\r\n if search_input[0:3]==\"cal\":\r\n return redirect(url_for('calculate'))\r\n if search_input[0:2]==\"co\":\r\n return redirect(url_for('convert'))\r\n if search_input[0:2]==\"ch\":\r\n return redirect(url_for('chat'))\r\n if search_input[0]==\"c\":\r\n return redirect(url_for('calender'))\r\n return render_template(\"404.html\")\r\n@app.route(\"/about\")\r\ndef about():\r\n return render_template(\"about.html\")\r\n@app.route('/signout')\r\ndef signout():\r\n logout_user()\r\n flash(u\"You have logged out\",\"success\")\r\n return redirect(url_for('signin'))\r\n@app.route(\"/calculate\",methods=[\"GET\"])\r\ndef calculate():\r\n return render_template(\"calculate.html\",data=data)\r\n@app.route(\"/calculate/quadratic\",methods=[\"POST\"])\r\ndef quadratic():\r\n try:\r\n a=request.form.get('a')\r\n b=request.form.get('b')\r\n c=request.form.get('c')\r\n data['results1']=np.roots([a,b,c])\r\n except:\r\n data['results1']=\"Error, either a=0 or some input field left empty\"\r\n return render_template(\"calculate.html\",data=data)\r\n@app.route(\"/calculate/linear\",methods=[\"POST\"])\r\ndef Linear():\r\n try:\r\n a1=request.form.get('a1')\r\n b1=request.form.get('b1')\r\n c1=request.form.get('c1')\r\n a2=request.form.get('a2')\r\n b2=request.form.get('b2')\r\n c2=request.form.get('c2')\r\n A=np.array([[a1,b1],[a2,b2]],dtype='float')\r\n b=np.array([c1,c2],dtype='float')\r\n data['results2']=numpy.linalg.solve(A,b)\r\n except:\r\n data['results2']=\"Error in calulation or some input field left empty\"\r\n return render_template(\"calculate.html\",data=data)\r\n@app.route(\"/calculate/integrate\",methods=[\"POST\"])\r\ndef integrate():\r\n try:\r\n a2=request.form.get('a2')\r\n b2=request.form.get('b2')\r\n c2=request.form.get('c2')\r\n d2=request.form.get('d2')\r\n e2=request.form.get('e2')\r\n f2=request.form.get('f2')\r\n array=np.array([a2,b2,c2,d2,e2,f2],dtype='float')\r\n data['results3']=np.polyint(array)\r\n except:\r\n data['results3']=\"Error in calulation or some input field left empty\"\r\n return render_template(\"calculate.html\",data=data)\r\n@app.route(\"/calculate/differenciate\",methods=[\"POST\"])\r\ndef differenciate():\r\n try:\r\n a3=request.form.get('a3')\r\n b3=request.form.get('b3')\r\n c3=request.form.get('c3')\r\n d3=request.form.get('d3')\r\n e3=request.form.get('e3')\r\n f3=request.form.get('f3')\r\n array=np.array([a3,b3,c3,d3,e3,f3],dtype='float')\r\n data['results4']=np.polyder(array)\r\n except:\r\n data['results4']=\"Error in calulation or some input field left empty\"\r\n return render_template(\"calculate.html\",data=data)\r\n@app.route(\"/calculate/evaluate\",methods=[\"POST\"])\r\ndef evaluate():\r\n try:\r\n a4=request.form.get('a4')\r\n b4=request.form.get('b4')\r\n c4=request.form.get('c4')\r\n d4=request.form.get('d4')\r\n e4=request.form.get('e4')\r\n x=request.form.get('x')\r\n array=np.array([a4,b4,c4,d4,e4],dtype='float')\r\n data['results5']=np.polyval(array,int(x))\r\n except:\r\n data['results5']=\"Error in calulation or some input field left empty\"\r\n return render_template(\"calculate.html\",data=data)\r\n@app.route(\"/chat\",methods=[\"GET\",\"POST\"])\r\ndef chat():\r\n if not current_user.is_authenticated:\r\n flash(u\"You have to login first\",\"error\")\r\n return redirect(url_for('signin'))\r\n name=current_user.first_name\r\n email=current_user.email\r\n return render_template(\"chat.html\",name=name,email=email)\r\n@socketio.on('message')\r\ndef handle_message(email):\r\n users[email]=request.sid\r\n send(email)\r\n emit('my_event','This task is also completed')\r\n@socketio.on('new_event')\r\ndef handle_newevent(message):\r\n try:\r\n receiver_session_id=users[message['receiver']]\r\n message['time']=datetime.now().strftime(\"%I:%M %p\")\r\n emit('new_response',message,room=receiver_session_id)\r\n except:\r\n message['name']=\"Server\"\r\n message['msg']=message['receiver']+\" has left or not available\"\r\n message['time']=datetime.now().strftime(\"%I:%M %p\")\r\n emit('new_response',message)\r\n@login_required\r\n@app.route(\"/chat/leave\")\r\ndef leave():\r\n users.pop(current_user.email,None)\r\n return redirect(url_for('index'))\r\n@app.errorhandler(408)\r\ndef page_not_found(e):\r\n return render_template('404.html'), 408\r\n@app.teardown_request\r\ndef checkin_db(exc):\r\n try:\r\n db.session.remove()\r\n except AttributeError:\r\n pass\r\n@app.errorhandler(500)\r\ndef server_error(e):\r\n return render_template('500.html'), 500\r\nif __name__ == '__main__':\r\n\tapp.run()\r\n","repo_name":"10nayan/abcdit","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":10207,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"73272055121","text":"import numpy as np\n\ndef Consol_Terzaghi_Uavg_vertical(Cv,H,t=-1,targettime=1000,dimt=1000,time=-1,constant_dt_time=np.infty,dtmax=1e3):\n '''\n Parameters\n ----------\n Cv : float\n coefficient of vertical consolidation in m/s**2\n '''\n if dimt==-1:\n time=time\n else:\n if constant_dt_time>targettime:\n time=10**np.linspace(0,np.log10(targettime),dimt)\n else:\n dimt2 = np.int((targettime-constant_dt_time)/dtmax)\n time=np.append(10**np.linspace(0,np.log10(constant_dt_time),dimt),np.linspace(constant_dt_time+0.01,targettime,dimt2))\n if t>0:\n Tv=t*Cv/((H)**2)\n else:\n Tv=time*Cv/((H)**2)\n Tv=np.clip(Tv,0,10)\n UavgAnalV=np.sqrt(4*Tv/np.pi)/((1+(4*Tv/np.pi)**2.8)**0.179)\n return time,UavgAnalV","repo_name":"thomasvergote/evspy","sub_path":"evspy/multi_stage_model/consolidation.py","file_name":"consolidation.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"15968973063","text":"from bluetooth import *\nimport math\n\nclass LatLong:\n def __init__(self):\n self.uuid = \"237ec270-2bcf-46ad-bffe-138659617d87\"\n self.R = 6371.0\n\n def connect(self):\n self.server_sock=BluetoothSocket( RFCOMM )\n self.server_sock.bind((\"\",PORT_ANY))\n self.server_sock.listen(1)\n self.port = self.server_sock.getsockname()[1]\n advertise_service( self.server_sock, \"GPSPiServer\",service_id = self.uuid,service_classes = [ self.uuid, SERIAL_PORT_CLASS ],profiles = [ SERIAL_PORT_PROFILE ])\n print(\"Waiting for connection on RFCOMM channel %d\" % self.port)\n self.client_sock, self.client_info = self.server_sock.accept()\n print(\"Accepted connection from \", self.client_info)\n\n \n def values(self):\n try:\n data = self.client_sock.recv(1024)\n s = data.decode(\"utf-8\")\n return s\n except IOError:\n return \"Connection failed\"\n\n def disconnect(self):\n self.client_sock.close()\n print(\"BT Connection closed\")\n \n def distance(self,l1,l2):\n lat1 = math.radians(l1[0])\n lon1 = math.radians(l1[1])\n lat2 = math.radians(l2[0])\n lon2 = math.radians(l2[1])\n dlon = lon2 - lon1 \n dlat = lat2 - lat1\n a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n dist = self.R * c\n return dist\n","repo_name":"sainiJiten/DirectionFinder","sub_path":"GPSlocations.py","file_name":"GPSlocations.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12193326721","text":"import asyncio\nimport json\nimport logging\nfrom datetime import datetime, timedelta\n\nimport discord\nfrom tabulate import tabulate\n\nimport connector\nfrom device import get_name, get_route_manager_name, get_route_pos, get_route_max, get_last_updated\nfrom run_args import get_args\n\nargs = get_args()\nlog = logging.getLogger('__name__')\n\niconURL = 'https://raw.githubusercontent.com/Map-A-Droid/MAD/master/madmin/static/mad_banner_trans.png'\n\n\nclass MyClient(discord.Client):\n\n def __init__(self):\n discord.Client.__init__(self)\n\n async def on_ready(self):\n log.info(f\"Logged in. Username: {self.user.name}. User ID:{self.user.id}\")\n\n async def on_message(self, message):\n if message.content == '!status':\n with open('servers.json') as f:\n servers_config_json = json.load(f)\n for server in servers_config_json:\n if message.channel.id == int(server['status_channel_id']):\n await self.__build_status_response(message, server, True)\n elif message.content == '!status all':\n with open('servers.json') as f:\n servers_config_json = json.load(f)\n for server in servers_config_json:\n if message.channel.id == int(server['status_channel_id']):\n await self.__build_status_response(message, server, False)\n\n @staticmethod\n async def __build_status_response(message, server, return_only_failed: bool):\n any_error_found = False\n\n server_name = server['name']\n table_header = ['Origin', 'Route', 'Pos', 'Time']\n table_contents = []\n\n log.info(f\"Status request received for {server_name}\")\n log.debug(\"Calling /get_status for current status\")\n device_status_response = connector.get_status(server)\n\n # Sort by name ascending\n device_status_response.sort(key=get_name)\n\n for device in device_status_response or []:\n device_failed = False\n table_before = tabulate(table_contents, headers=table_header)\n route_manager = get_route_manager_name(device) if get_route_manager_name(device) is not None else ''\n origin = get_name(device) if get_name(device) is not None else ''\n route_pos = get_route_pos(device) if get_route_pos(device) is not None else '?'\n route_max = get_route_max(device) if get_route_max(device) is not None else '?'\n last_proto_date_time = get_last_updated(device) if get_last_updated(device) is not None else ''\n number_front_chars = 6\n number_end_chars = 5\n\n try:\n datetime_from_status_json = datetime.fromtimestamp(last_proto_date_time)\n formatted_device_last_proto_time = datetime_from_status_json.strftime(\"%H:%M\")\n latest_acceptable_datetime = (datetime.now() - timedelta(minutes=args.duration_before_alert))\n log.debug(f\"{origin} Last Proto Date Time: {datetime_from_status_json}\")\n log.debug(f\"{origin} Last Acceptable Time: {latest_acceptable_datetime}\")\n\n if datetime_from_status_json < latest_acceptable_datetime:\n log.info(f\"{str(origin)} failed\")\n device_failed = True\n any_error_found = True\n\n except Exception as e:\n log.info(f\"{e} {origin} {route_manager}\")\n any_error_found = True\n device_failed = True\n formatted_device_last_proto_time = 'Unkwn'\n\n if args.trim_table_content:\n if len(route_manager) > (number_front_chars + number_end_chars):\n route_manager = f\"{route_manager[:number_front_chars]}..{route_manager[-number_end_chars:]}\"\n if len(origin) > (number_front_chars + number_end_chars):\n origin = f\"{origin[:number_front_chars]}..{origin[-number_end_chars:]}\"\n\n if (return_only_failed and device_failed and route_manager.lower() != \"idle\") or not return_only_failed:\n table_contents.append([origin,\n route_manager,\n f\"{route_pos}/{route_max}\",\n formatted_device_last_proto_time\n ])\n\n table_after = tabulate(table_contents, headers=table_header)\n\n table_before_len = len(table_before)\n table_after_len = len(table_after)\n\n log.debug(f\"{table_before_len} and after {table_after_len}\")\n log.debug(\"Error found: \" + str(any_error_found))\n\n color = 0xFF6E6E if any_error_found is True else 0x98FB98\n\n if table_before_len > 2000:\n log.error(\"Table before exceeds 2000 word count. How did this happened?\")\n return\n\n if table_after_len > 2000:\n log.info(\"Table size was greater than 2000. Commence table split.\")\n log.debug(table_before)\n\n embed = discord.Embed(description='```' + table_before + '```', colour=color)\n embed.set_thumbnail(url=iconURL)\n embed.set_author(name=server['name'], url='', icon_url='')\n await message.channel.send(embed=embed)\n\n table_contents.clear()\n table_contents.append([origin,\n route_manager,\n f\"{route_pos}/{route_max}\",\n formatted_device_last_proto_time\n ])\n\n\n log.debug(f\"Sending status table for {server_name}\")\n table_to_send = tabulate(table_contents, headers=table_header)\n\n log.debug(table_to_send)\n\n if len(table_contents) > 0:\n embed = discord.Embed(description='```' + table_to_send + '```', colour=color)\n else:\n embed = discord.Embed(description=\"No devices need your attention\")\n\n embed.set_thumbnail(url=iconURL)\n embed.set_author(name=server['name'], url='', icon_url='')\n await message.channel.send(embed=embed)\n\n\ndef run():\n asyncio.set_event_loop(asyncio.new_event_loop())\n client = MyClient()\n client.run(args.discord_token)\n","repo_name":"georgeherby/MADevice","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"3"}
+{"seq_id":"72856469202","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 middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n length_list = 0\n start = node = head \n while start:\n length_list += 1\n start = start.next\n print(length_list)\n mid = length_list // 2\n print(mid)\n count = 0\n while node:\n if counter == mid:\n return node\n else:\n count += 1\n node = node.next\n return None","repo_name":"yusseef/LeetCode-problems-soluotions","sub_path":"Leet-Code 75/876. Middle of the Linked List.py","file_name":"876. Middle of the Linked List.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"}
+{"seq_id":"23819028066","text":"# Program to find the longest common prefix \n\ndef findMinLength(array, size): \n minimum = len(array[0]) \n for i in range(1,size): \n if (len(array[i])< minimum): \n minimum = len(array[i]) \n\n return(minimum) \n\n# A Function that returns the longest common prefix from the array of strings \ndef commonPrefix(array, size): \n\n minimmum_length = findMinLength(array, size) \n result =\"\" \n for i in range(minimmum_length): \n common_char = array[0][i] \n\n for j in range(1,size): \n if (array[j][i] != common_char): \n return result \n\n # Append to result \n result = result+common_char \n\n return (result) \n\narray = []\nsize = int(input(\"Enter size:\"))\nfor i in range(size):\n item=input()\n array.append(item)\n\nanswer = commonPrefix (array, size) \n\nif (len(answer)): \n print(\"The longest common prefix is \",answer) \nelse: \n print(\"There is no common prefix\") \n\n\n'''\nSample I/O:\n Input:\n Enter size: 3\n star\n start\n stardom\n\n Output:\n The longest Common Prefix is : star\n\nTime Complexity: O(size*M) (M = Length of the largest string)\nSpace Complexity:O(1)\n\n'''\n","repo_name":"HarshCasper/NeoAlgo","sub_path":"Python/cp/longest_Common_Prefix.py","file_name":"longest_Common_Prefix.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","stars":873,"dataset":"github-code","pt":"3"}
+{"seq_id":"13182859430","text":"def longest_palindrome_substring(s):\n n = len(s)\n dp = [[False] * n for _ in range(n)]\n\n max_length = 1\n start = 0\n for i in range(n):\n dp[i][i] = True\n\n for i in range(n - 1):\n if s[i] == s[i + 1]:\n dp[i][i + 1] = True\n max_length = 2\n start = i\n\n for length in range(3, n + 1):\n for i in range(n - length + 1):\n j = i + length - 1\n if s[i] == s[j] and dp[i + 1][j - 1]:\n dp[i][j] = True\n max_length = length\n start = i\n\n return s[start:start + max_length]\n\n\ns = input(\"Введите строку: \")\nlongest_palindrome = longest_palindrome_substring(s)\nprint(\"Самая длинная палиндромная подстрока:\", longest_palindrome)\n","repo_name":"jeysot/Python_autumn_ITMO_2023","sub_path":"Task 23/Task23_1.py","file_name":"Task23_1.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42034249997","text":"from setuptools import setup\n\npackage_name = 'dt_ood_utils'\n\nsetup(\n name=package_name,\n version='1.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='nicholas-gs',\n maintainer_email='nicholasganshyan@gmail.com',\n description='Utility package for Out-of-Distribution detector',\n license='GPLv3',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n ],\n },\n)\n","repo_name":"nicholas-gs/dt-common-cps","sub_path":"dt_ood_utils/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28813147403","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pickle\r\nimport numpy as np\r\n\r\nlabel_encoder_state = pickle.load(open(\"label_encoding.pkl\", \"rb\"))\r\n\r\nmodel = pickle.load(open(\"model.pkl\", \"rb\"))\r\n\r\nstates = ('ANDHRA PRADESH', 'ARUNACHAL PRADESH', 'ASSAM', 'BIHAR',\r\n 'CHHATTISGARH', 'GOA', 'GUJARAT', 'HARYANA', 'HIMACHAL PRADESH',\r\n 'JHARKHAND', 'KARNATAKA', 'KERALA', 'MADHYA PRADESH',\r\n 'MAHARASHTRA', 'MANIPUR', 'MEGHALAYA', 'MIZORAM', 'NAGALAND',\r\n 'PUNJAB', 'RAJASTHAN', 'SIKKIM', 'TAMIL NADU', 'TRIPURA',\r\n 'UTTAR PRADESH', 'WEST BENGAL', 'CHANDIGARH', 'LAKSHADWEEP')\r\nstate = st.selectbox(\"State\",states)\r\nstate_le = label_encoder_state.transform([state])\r\npop = st.number_input(\"Population: \") \r\ncrime = st.number_input(\"CRIME(2015): \")\r\ncrime1 = st.number_input(\"CRIME(2016): \")\r\ncorrup1 = st.number_input(\"CORRUPTION CASE (2015): \")\r\ncorrup2= st.number_input(\"CORRUPTION CASE (2016): \")\r\nRul = st.number_input(\"Rural 2011-12 Poverty Expenditure Per Capita: \")\r\nUrb = st.number_input(\"Urban 2011-12 Poverty Expenditure Per Capita: \")\r\n\r\n#ok = st.checkbox(\"Predict Crime in 2014\", False)\r\n\r\nif st.checkbox(\"Predict Crime in 2014\", False):\r\n crime14 = model.predict([pop,state_le,crime,crime1,corrup1,corrup2,Rul,Urb])\r\n st.write(\"The Estimated Crime in 2014 is \",crime14)\r\n\r\n\r\n\r\n","repo_name":"Abhi21112038/-","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21480874517","text":"from matplotlib import pyplot as plt\nimport numpy as np\nimport scipy.stats as stats\n\ndef plot_hist(data):\n plt.xlabel(\"Number of queries (t)\")\n plt.ylabel(\"Frequency\")\n plt.hist(data, bins=40, density=True,label=\"queries\")\n \n \n \n\nif __name__ == \"__main__\":\n data = []\n with open(\"tries_num_log.txt\", 'r') as f:\n for line in f:\n data.append(int(line))\n mu = np.mean(data)\n var = np.var(data)\n sigma = np.sqrt(var)\n print(mu, sigma)\n x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)\n plot_hist(data)\n plt.plot(x, stats.norm.pdf(x, mu, sigma),'r',label=f\"Normal curve\")\n plt.show()\n \n","repo_name":"MadCreeper/Constrained-Optimal-Querying-Huffman-Coding-and-Beyond","sub_path":"battleship/plot_hist.py","file_name":"plot_hist.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"7565690134","text":"import logging\n\nFORMAT = \"%(asctime)s:%(name)s:%(levelname)s - %(message)s\"\n# Use filename=\"file.log\" as a param to logging to log to a file\nlogging.basicConfig(format=FORMAT, level=logging.INFO)\n\n\n\"\"\"# Inferencing\"\"\"\n\nimport os\nimport logging\nimport numpy as np\n\"\"\"### Load Model\"\"\"\n\n#loading best model\nclass Model:\n def __init__(\n self,\n source_path='/content'\n ):\n self.source_path = source_path\n self.model = None\n self.load_model()\n #\n def load_model(\n self,\n filename = 'model.h5'\n ):\n from tensorflow.keras.models import load_model\n self.model = load_model(f'{self.source_path}/{filename}')\n self.model.summary()\n return self.model\n def predict(self, seq):\n '''\n Parameters\n ---\n seq : numpy.ndarray\n <1, MAX_PAD_LEN>\n '''\n return self.model.predict(seq)\n\n\n\"\"\"### Text Process - pre and post\"\"\"\n\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\nclass TextProcess:\n def __init__(\n self,\n source_path='/content'\n ):\n self.source_path = source_path\n #\n self.max_pad_len = None # assinged in next line\n self.get_pad_len()\n #\n self.encoder = None \n self.load_label_encoder()\n #\n self.load_tokenizer()\n #\n def get_pad_len(self, filename='max_pad_len.txt'):\n with open(f'{self.source_path}/{filename}') as file:\n self.max_pad_len = int(file.read())\n #\n def load_label_encoder(\n self,\n filename='label_encoded_classes.npy'\n ):\n from sklearn.preprocessing import LabelEncoder\n self.encoder = LabelEncoder()\n self.encoder.classes_ = np.load(f'{self.source_path}/{filename}')\n return self.encoder\n #\n def load_tokenizer(self,\n filename = 'tokens.json'\n ):\n # read as from JSON file\n with open(f'{self.source_path}/{filename}', 'r') as tokenfile:\n tokens_info = tokenfile.read()\n #\n from tensorflow.keras.preprocessing.text import tokenizer_from_json\n self.tokenizer = tokenizer_from_json(tokens_info)\n return self.tokenizer\n #\n def pre_process(self, sentence):\n '''converts sentence to token\n \n Parameters\n ---\n sentence : str\n\n Returns\n ---\n x_seq : numpy.ndarray shape <1, self.max_pad_len>\n '''\n x_seq = self.tokenizer.texts_to_sequences(sentence)\n x_seq = pad_sequences(x_seq, maxlen=self.max_pad_len)\n return x_seq\n #\n def post_process(self, prediction):\n '''Convert back to orginial class name\n\n Parameters\n ---\n prediction : numpy.ndarray (dtype = float32, shape = (1, n_classes) #n_classes captured within the model\n \n Returns:\n ---\n dict \n \n ONLY the maximum confident class\n '''\n prediction_flatten = prediction.flatten()\n probability_argmax = np.argmax(\n prediction_flatten\n )\n probability = prediction_flatten[probability_argmax]\n #\n predicted_class_name = self.encoder.inverse_transform(\n [probability_argmax]\n )[0]\n return {predicted_class_name: float(probability)}\n\n\n","repo_name":"sap-tutorials/Tutorials","sub_path":"tutorials/ai-core-tensorflow-byod/files/infer/tf_template.py","file_name":"tf_template.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":622,"dataset":"github-code","pt":"3"}
+{"seq_id":"17837697230","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport tkinter\nimport tkinter.messagebox\ntop = tkinter.Tk()\ntop.title('按钮示例')\ntop.geometry('500x300') # 这里的乘是小x\ndef button_click():\n tkinter.messagebox.showinfo(\"示例\", \"按钮示例\")\nb = tkinter.Button(top, text=\"点我\", width=10 ,command= button_click)\nb.place(relx= 0.35, rely=0.5)\ntop.mainloop()\n","repo_name":"marginlove/python","sub_path":"daima/10.5.py","file_name":"10.5.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2327466584","text":"import multiprocessing as mp\nimport time\nimport sys\nimport argparse\nimport os\nimport numpy as np\nimport random\nimport math\n\ncore = 8\n\n\ndef read_dataset(network):\n nodes = []\n edges = []\n inv_edges = []\n\n with open(network, 'r') as f_net:\n line = f_net.readline()\n graph_info = line.split(\" \")\n node_cnt = int(graph_info[0])\n edge_cnt = int(graph_info[1])\n\n for i in range(0, node_cnt + 1):\n nodes.append(i)\n edges.append({})\n inv_edges.append({})\n\n for i in range(0, edge_cnt):\n line = f_net.readline()\n start, end, weight = line.split(\" \")\n\n adj_list = edges[int(start)]\n adj_list[int(end)] = float(weight)\n\n inv_adj_list = inv_edges[int(end)]\n inv_adj_list[int(start)] = float(weight)\n\n return nodes, edges, inv_edges\n\n\ndef sampling(epsilon, l):\n R = []\n LB = 1\n n = len(nodes)\n new_epsilon = epsilon * math.sqrt(2)\n\n log_cnk = log_Cnk(n, size)\n log_2 = math.log(2)\n log_n = math.log(n)\n\n for i in range(1, int(math.log2(n - 1)) + 1):\n x = n / (math.pow(2, i))\n theta_i = ((2 + 2 / 3 * new_epsilon)\n * (log_cnk + l * log_n + math.log(math.log2(n)))\n * n) / pow(new_epsilon, 2) / x\n while len(R) <= theta_i:\n R.append(gen_RR())\n\n s_i, FR = NodeSelection(R)\n if n * FR >= (1 + new_epsilon) * x:\n LB = n * FR / (1 + new_epsilon)\n break\n\n alpha = math.sqrt(l * log_n + log_2)\n beta = math.sqrt((1 - 1 / math.e) * (log_cnk + l * log_n + log_2))\n lambda_ = 2 * n * math.pow(((1 - 1 / math.e) * alpha + beta), 2) * math.pow(epsilon, -2)\n theta = lambda_ / LB\n\n while len(R) <= theta:\n R.append(gen_RR())\n\n return R\n\n\ndef sampling_bound_with_time():\n R = []\n while time.time() < time_out:\n R.append(gen_RR())\n return R\n\n\ndef log_Cnk(n, k):\n cnk = 0\n for i in range(n - k + 1, n + 1):\n cnk += math.log(i)\n for i in range(1, k + 1):\n cnk -= math.log(i)\n return cnk\n\n\ndef gen_RR():\n node = random.randint(1, len(nodes) - 1)\n\n if model == 'IC':\n return gen_RR_IC(node)\n elif model == 'LT':\n return gen_RR_LT(node)\n\n\ndef gen_RR_IC(node):\n np.random.seed(random.randint(0, 100000))\n\n act_set = [node]\n activated_nodes = [node]\n\n while act_set:\n new_act_set = []\n for seed in act_set:\n adj_list = inv_edges[seed]\n for neighbor in adj_list:\n if neighbor in activated_nodes:\n continue\n rand = np.random.random()\n if rand < adj_list[neighbor]:\n activated_nodes.append(neighbor)\n new_act_set.append(neighbor)\n act_set = new_act_set\n return list(set(activated_nodes))\n\n\ndef gen_RR_LT(node):\n act = node\n activated_nodes = [node]\n keep_adding = True\n\n while keep_adding:\n keep_adding = False\n\n adj_list = inv_edges[act]\n\n if len(adj_list) == 0:\n break\n act = random.sample(adj_list.keys(), 1)[0]\n if act not in activated_nodes:\n activated_nodes.append(act)\n keep_adding = True\n return list(set(activated_nodes))\n\n\ndef NodeSelection(R):\n sk = []\n occurrence = [0] * (len(nodes) + 1)\n\n # Init\n occurrence_idx = []\n for node_i in range(0, len(nodes) + 1):\n occurrence_idx.append([])\n\n # How many times does each node appear in rr sets\n for rr_i in range(0, len(R)):\n rr = R[rr_i]\n for node in rr:\n occurrence[node] += 1\n occurrence_idx[node].append(rr_i)\n\n # Add the node with the most occurrences into sk\n # Then delete its appearances\n max_cnt = 0\n for i in range(1, size + 1):\n max_node = occurrence.index(max(occurrence))\n sk.append(max_node)\n max_cnt += len(occurrence_idx[max_node])\n\n for rr_i in occurrence_idx[max_node]:\n rr = R[rr_i]\n for node in rr:\n occurrence[node] -= 1\n # occurrence_idx[node].remove(rr_i)\n return list(set(sk)), max_cnt / len(R)\n\n\ndef IMM(epsilon, l):\n n = len(nodes)\n l = l * (1 + math.log(2) / math.log(n))\n R = sampling(epsilon, l)\n # R = sampling_bound_with_time()\n Sk, no_use = NodeSelection(R)\n return Sk\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--network', type=str, default='../dataset/NetHEPT.txt')\n parser.add_argument('-k', '--size', type=str, default='500')\n parser.add_argument('-m', '--model', type=str, default='LT')\n parser.add_argument('-t', '--time_limit', type=int, default=5)\n args = parser.parse_args()\n\n time_out = time.time() + int(args.time_limit - 20)\n time_start = time.time()\n\n nodes, edges, inv_edges = read_dataset(os.path.abspath(args.network))\n\n size = int(args.size)\n model = args.model\n\n seeds = IMM(epsilon=0.1, l=1)\n\n for seed in seeds:\n print(seed)\n\n time_end = time.time()\n # print(\"time: {}\".format(time_end-time_start))\n","repo_name":"ArslanaWu/ISE_IMP","sub_path":"IMP/IMP_old.py","file_name":"IMP_old.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35518120421","text":"import sys\nimport joint.tnet as tnet\nimport os \nimport trafficAssignment.assign as ta\n\n\n\nnetFile = \"networks/NYC_full_net.txt\"\ngFile = \"networks/NYC_full_trips.txt\"\n\n#netFile = \"networks/EMA_net.txt\"\n#gFile = \"networks/EMA_trips.txt\"\n\n#netFile = \"networks/Braess1_net.txt\"\n#gFile = \"networks/Braess1_trips.txt\"\n\nfcoeffs_truth = [1,0,0,0,0.15,0]\ntNet = tnet.tNet(netFile=netFile, gFile=gFile, fcoeffs=fcoeffs_truth)\n\nG = ta.assignment(G=tNet.G, g=tNet.g, fcoeffs=tNet.fcoeffs, flow=False, method='FW', accuracy=0.0001, max_iter=20)\nprint('-----------------')\ntNet.G = G\ntNet.fcoeffs = [1,0,0,0,0.20,0]\nG = ta.assignment(G=tNet.G, g=tNet.g, fcoeffs=tNet.fcoeffs, flow=True, method='FW', accuracy=0.0001, max_iter=20)\nprint([G[i][j]['flow'] for i,j in G.edges()])","repo_name":"salomonw/tnet","sub_path":"test_trafficAssignment.py","file_name":"test_trafficAssignment.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15711787543","text":"# import vlc\n# import pafy\n\n# def main():\n# url = \"https://fb.watch/i3M6FHc9fd/\"\n\n# # creating pafy object of the video\n# video = pafy.new(url)\n \n# # getting best stream\n# best = video.getbest()\n \n# # creating vlc media player object\n# media = vlc.MediaPlayer(best.url)\n \n# # start playing video\n# media.play()\n\n\n \n\n# main()\n\n# importing vlc module\nimport vlc\n\n# importing pafy module\nimport pafy\n\n# url of the video\nurl = \"https://www.youtube.com/watch?v=il_t1WVLNxk&list=PLqM7alHXFySGqCvcwfqqMrteqWukz9ZoE\"\n\n# creating pafy object of the video\nvideo = pafy.new(url)\n\n# getting stream at index 0\nbest = video.streams[0]\n\n# creating vlc media player object\nmedia = vlc.MediaPlayer(best.url)\n\n# start playing video\nmedia.play()\n","repo_name":"0xM1cx/Python-Practice","sub_path":"ChristmasBreak_Challenges/Click.py","file_name":"Click.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35935118770","text":"import csv\ndef get_airports():\n\tf = open('airports.txt', 'rb')\n\tdomestic_airports = ['HYD']\n\tinternational_airports = ['HYD']\n\tfor line in f:\n\t\tdata = line.split(',')\n\t\tif \"India\" in data[3]:\n\t\t\tif '\\\\N' not in data[4]:\n\t\t\t\tx = data[4][1:-1]\n\t\t\t\tif x not in domestic_airports:\n\t\t\t\t\tdomestic_airports.append(x)\n\t\telse:\n\t\t\tif '\\\\N' not in data[4]:\n\t\t\t\tx = data[4][1:-1]\n\t\t\t\tif x not in international_airports:\n\t\t\t\t\tinternational_airports.append(x)\n\n\n\treturn domestic_airports, international_airports\n\ndef get_IATAcode(place):\n\tidx = place.find('(') + 1\n\tplace = place[idx:idx+3]\n\tif place == 'KJF':\n\t\tplace = 'JFK'\n\treturn place\n\ndef get_traffic(airport_name, airports, low_traffic_threshold, high_traffic_threshold):\n\tf = open('history2.csv', 'rb')\n\ttraffic = {}\n\n\tfor airport in airports:\n\t\ttraffic[airport] = 0\n\ti = 0\n\tcsv_reader = csv.reader(f)\n\tfor row in csv_reader:\n\t\tif i == 0:\n\t\t\ti += 1\n\t\t\tcontinue\n\t\trow[2] = get_IATAcode(row[2])\n\t\trow[3] = get_IATAcode(row[3])\n\t\tif (row[2] in airports) and (row[3] in airports):\n\t\t\tif airport_name != row[2]:\n\t\t\t\tplace = row[2]\n\t\t\tif airport_name != row[3]:\n\t\t\t\tplace = row[3]\n\t\t\ttraffic[place] += 1\n\n\tplaces = {'low_traffic' : [], 'medium_traffic' : [], 'high_traffic' : [airport_name]}\n\n\tfor key, val in traffic.iteritems():\n\t\tif key == airport_name:\n\t\t\tcontinue\n\t\tif val >= high_traffic_threshold:\n\t\t\tplaces['high_traffic'].append(key)\n\t\telif val < low_traffic_threshold:\n\t\t\tplaces['low_traffic'].append(key)\n\t\telse:\n\t\t\tplaces['medium_traffic'].append(key)\n\n\tif airport_name not in places['high_traffic']:\n\t\tplaces['high_traffic'].append(airport_name)\n\treturn places\t\t\n\n\ndomestic_airports, intl_airports = get_airports()\n# print get_traffic('HYD', domestic_airports, 200, 400)\n# print get_traffic('HYD', intl_airports, 200, 400)","repo_name":"mc1597/BTP-WD-CALE","sub_path":"DataAnalysis/get_places.py","file_name":"get_places.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27578647293","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 16 10:28:34 2020\n\n@author: edyta\n\"\"\"\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport requests\n\nurl=\"http://glacier.nve.no/Glacier/viewer/CI/en/nve/ClimateIndicatorInfo/257?name=Sydbreen\"\n\n# Make a GET request to fetch the raw HTML content\nhtml_content = requests.get(url).text\n\n# Parse the html content\nsoup = BeautifulSoup(html_content, \"lxml\")\n\ntext1 =[]\nfor link in soup.find_all(\"table\", attrs={\"class\": \"table table-bordered\", \"id\": \"lengthTable\"}):\n text1.append(\"Inner Text: {}\".format(link.text)) \n\na = []\nfor elem in text1:\n a.append(elem.split(\"\\n\"))\n \n \ndata = a[0]\n\nyear = data[2::5]\nlength = data[3::5]\nmass = data[4::5]\n\n\nglacier_data = pd.DataFrame(list(zip(year, length, mass)), columns =['Year', 'Length', 'Mass'])","repo_name":"edytaBr/glacier-data-request","sub_path":"glacier.py","file_name":"glacier.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18590480359","text":"import awswrangler as wr\nfrom geopy.geocoders import GoogleV3\nfrom flask import Flask, jsonify, request, redirect\nimport pandas as pd\nimport io\nimport time\n\n\ndef process():\n aws_access_key_id = \"AKIA4CMSZ232GY35CEMV\"\n aws_secret_access_key = \"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\"\n api_key = \"AIzaSyDQYZ4uHQ86UoLdUoNN2nMVuZ9EgGngDqg\"\n geolocator = GoogleV3(api_key=api_key)\n filename = request.args.get(\"filename\")\n batch_size = int(request.args.get(\"batch_size\", 50))\n\n df = wr.s3.read_csv(f's3://zono-geocoder/input/{filename}')\n\n start_time = time.time()\n for i in range(0, len(df), batch_size):\n \n batch = df[i:i+batch_size]\n\n for j, row in batch.iterrows():\n lat = row[\"Botree_Lat\"]\n lon = row[\"Botree_Long\"]\n location = geolocator.reverse(f\"{lat}, {lon}\")\n\n if location:\n batch.at[j, \"Address\"] = location.address\n batch.at[j, \"Botree_Lat\"] = location.latitude\n batch.at[j, \"Botree_Long\"] = location.longitude\n\n for component in location.raw['address_components']:\n if 'locality' in component['types']:\n batch.at[j, \"City\"] = component['long_name']\n elif 'administrative_area_level_2' in component['types']:\n batch.at[j, \"District\"] = component['long_name']\n elif 'administrative_area_level_1' in component['types']:\n batch.at[j, \"State\"] = component['long_name']\n elif 'country' in component['types']:\n batch.at[j, \"Country\"] = component['long_name']\n elif 'postal_code' in component['types']:\n batch.at[j, \"Pincode\"] = component['long_name']\n\n batch_output_file = f'output/{filename.split(\"/\")[-1]}.{i//batch_size}.csv'\n wr.s3.to_csv(batch, f's3://zono-geocoder/{batch_output_file}')\n\n elapsed_time = time.time() - start_time\n print(\"Total Time: \",elapsed_time)\n return redirect('/get_download')","repo_name":"nitinmp/geocoder","sub_path":"BatchGeo.py","file_name":"BatchGeo.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21234632085","text":"# jumpingJack.py\r\n# Name: Shefali Emmanuel\r\n# CSCI 220 HW7\r\n# Problem: To create a simulation of Jack consisting of a stick figure\r\n# and three buttons: start, stop, and quit.\r\n# Input: The users will click inside to window to initiate the program.\r\n# Output: A jumping jack that follows the button instructions. \r\n# Certification of Authenticity:\r\n# I certify that this lab is my own work, but I discussed it with:\r\n# Marge Marshall.\r\n\r\nfrom graphics import*\r\nimport time\r\n\r\ndef wasClicked(pt, rect):\r\n #set values to false\r\n xInRange= False\r\n yInRange= False\r\n #get points\r\n if pt != None:\r\n point1= rect.getP1()\r\n point2= rect.getP2()\r\n x1= point1.getX()\r\n x2= point2.getX()\r\n y1= point1.getY()\r\n y2= point2.getY()\r\n #if else statements for range\r\n if x2 > x1:\r\n if pt.getX() <= x2 and x1 <= pt.getX():\r\n xInRange= True\r\n else:\r\n if pt.getX() >= x2 and x1 >= pt.getX():\r\n xInRange= True\r\n if y2 > y1:\r\n if pt.getY() <= y2 and y1 <= pt.getY():\r\n yInRange= True\r\n else:\r\n if pt.getY() >= y2 and y1 >= pt.getY():\r\n yInRange= True\r\n \r\n return (xInRange and yInRange)\r\n\r\ndef main():\r\n\r\n print(\" \")\r\n \r\n #establish width of window\r\n winWidth = 400\r\n #establish height of window\r\n winHeight = 400\r\n\r\n #draw the window\r\n win =GraphWin(\"Window\",winWidth, winHeight)\r\n win.setBackground(\"black\")\r\n \r\n #make the body\r\n ball= Circle(Point(200,100), 10.5)\r\n bod= Line(Point(200,100), Point(200,200))\r\n leftLeg= Line(Point(150,250), Point(200,200))\r\n rightLeg= Line(Point(250,250), Point(200,200))\r\n leftArm= Line(Point(150,150), Point(200,150))\r\n rightArm= Line(Point(250,150), Point(200,150))\r\n leftLeg2= Line(Point(225,275), Point(200,200))\r\n rightLeg2= Line(Point(175,275), Point(200,200))\r\n leftArm2= Line(Point(225,200), Point(200,150))\r\n rightArm2= Line(Point(175,200), Point(200,150))\r\n leftLeg3= Line(Point(225,275), Point(200,200))\r\n rightLeg3= Line(Point(175,275), Point(200,200))\r\n leftArm3= Line(Point(250,100), Point(200,150))\r\n rightArm3= Line(Point(150,100), Point(200,150))\r\n \r\n #draw the body\r\n ball.draw(win)\r\n bod.draw(win)\r\n leftLeg.draw(win)\r\n rightLeg.draw(win)\r\n leftArm.draw(win)\r\n rightArm.draw(win)\r\n## leftLeg2.draw(win)\r\n## rightLeg2.draw(win)\r\n## leftArm2.draw(win)\r\n## rightArm2.draw(win)\r\n## leftLeg3.draw(win)\r\n## rightLeg3.draw(win)\r\n## leftArm3.draw(win)\r\n## rightArm3.draw(win)\r\n \r\n #fill the body\r\n ball.setFill(\"light blue\")\r\n bod.setFill(\"light blue\")\r\n leftLeg.setFill(\"light blue\")\r\n rightLeg.setFill(\"light blue\")\r\n leftArm.setFill(\"light blue\")\r\n rightArm.setFill(\"light blue\")\r\n leftLeg2.setFill(\"light blue\")\r\n rightLeg2.setFill(\"light blue\")\r\n leftArm2.setFill(\"light blue\")\r\n rightArm2.setFill(\"light blue\")\r\n leftLeg3.setFill(\"light blue\")\r\n rightLeg3.setFill(\"light blue\")\r\n leftArm3.setFill(\"light blue\")\r\n rightArm3.setFill(\"light blue\")\r\n\r\n #moves\r\n move1= [leftLeg,rightLeg,leftArm,rightArm]\r\n move2= [leftLeg2,rightLeg2,leftArm2,rightArm2]\r\n move3= [leftLeg3,rightLeg3,leftArm3,rightArm3]\r\n moveList= [move1, move2, move1, move3]\r\n\r\n #rectangles\r\n rectangle = Rectangle(Point(75,325), Point(125,375))\r\n rectangle.setFill(\"light pink\")\r\n rectangle.draw(win)\r\n\r\n rectangle1 = Rectangle(Point(175,325), Point(225,375))\r\n rectangle1.setFill(\"light pink\")\r\n rectangle1.draw(win)\r\n \r\n rectangle2 = Rectangle(Point(275,325), Point(325,375))\r\n rectangle2.setFill(\"light pink\")\r\n rectangle2.draw(win)\r\n \r\n #text messages to display \r\n message = Text(Point(100,350),\"Start!\")\r\n message.setTextColor(\"white\")\r\n message.draw(win)\r\n\r\n message1 = Text(Point(200,350),\"Stop!\")\r\n message1.setTextColor(\"white\")\r\n message1.draw(win)\r\n \r\n message2 = Text(Point(300,350),\"Quit!\")\r\n message2.setTextColor(\"white\")\r\n message2.draw(win)\r\n \r\n message3 = Text(Point(200,50),\"Jumping Jacks!\")\r\n message3.setTextColor(\"white\")\r\n message3.draw(win)\r\n\r\n #get the mouse\r\n click = win.getMouse()\r\n\r\n #jump functions\r\n jump = wasClicked(click, rectangle)\r\n jump1 = wasClicked(click, rectangle1)\r\n jump2 = wasClicked(click, rectangle2)\r\n\r\n #set x to 1\r\n x = 1\r\n #wile loop for buttons\r\n while not jump2:\r\n if jump and not jump1:\r\n for line in moveList[(x-1)%4]:\r\n line.undraw()\r\n moveList [x % 4]\r\n for line in moveList[x%4]:\r\n line.draw(win)\r\n time.sleep(2)\r\n\r\n x += 1\r\n click = win.checkMouse()\r\n if click != None:\r\n jump = wasClicked(click, rectangle)\r\n jump1 = wasClicked(click, rectangle1)\r\n jump2 = wasClicked(click, rectangle2)\r\n \r\n win.close()\r\n\r\nmain()\r\n","repo_name":"shefaliemmanuel/CSCI220PythonProgramming","sub_path":"HW8.py","file_name":"HW8.py","file_ext":"py","file_size_in_byte":5052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17816787858","text":"handSum = 0\r\nmomSum = 0\r\nflag = True\r\nfor i in range(1, 13):\r\n\tn = int(input())\r\n\thandSum += 300 - n\r\n\tif handSum < 0 and flag:\r\n\t\tprint(-i)\r\n\t\tflag = False\r\n\twhile handSum >= 100:\r\n\t\thandSum -= 100\r\n\t\tmomSum += 100\r\nif flag:\r\n\tprint(int(momSum * 1.2 + handSum))","repo_name":"HanKin2015/ACM","sub_path":"洛谷python/P1089 津津的储蓄计划.py","file_name":"P1089 津津的储蓄计划.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"33271644937","text":"import requests\nfrom StringIO import StringIO\nfrom PIL import Image\n# import config\nimport logging\n\npage_id = '1880783985473739'\nlogging.basicConfig(filename=\"fb.log\",\n level=logging.INFO,\n format='%(asctime)s %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p')\n\ndef request_token(page_id):\n\n try:\n user_token = open('facebook_upload/user_token.txt', 'r').read()\n except Exception as e:\n logging.error(\"Failed to open user token file with exception:\")\n logging.error(e)\n return False\n\n try:\n token_request = requests.get('https://graph.facebook.com/v2.8/{0}?fields=access_token&access_token={1}'.format(page_id, user_token))\n except requests.exceptions.RequestException as e:\n logging.error(\"Failed to acquire page token with exception:\")\n logging.error(e)\n return False\n\n return token_request.json()['access_token']\n\ndef upload_file(imageRaw, mock=False):\n if not mock:\n image = Image.fromarray(imageRaw)\n imageStringIO = StringIO()\n image.save(imageStringIO, \"JPEG\")\n imageStringIO.seek(0)\n else:\n imageStringIO = b'0';\n\n page_token = request_token(page_id)\n\n if (page_token is False):\n return False\n\n files = {'image': imageStringIO}\n url = 'https://graph.facebook.com/v2.8/{0}/photos?access_token={1}'.format(page_id, page_token)\n try:\n upload_request = requests.post(url, files=files)\n except requests.exceptions.RequestException as e:\n logging.error(\"Failed to upload a photo with exception:\")\n logging.error(e)\n return False\n\n response = upload_request.json()\n\n if 'error' in response:\n # log error\n log_message = \"{0}: {1}\".format(response['error']['type'], response['error']['message'])\n logging.error(log_message)\n return False\n else:\n if 'id' in response:\n # successful POST\n log_message = \"Success: photo id:{0}\".format(response['id'])\n logging.info(log_message)\n return True\n else:\n log_message = \"Failed to upload a photo (no further information)\"\n logging.error(log_message)\n return False\n","repo_name":"kelsohmm/style-forger","sub_path":"facebook_upload/fb.py","file_name":"fb.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43042203758","text":"\n#?Operator Overloading -operators are same but operands are different or type of arguments passing is different\na='10'\nb='ad'\nprint(a+b) \nprint(str.__add__(a,b)) #everything is a object in python\n\nclass Student:\n def __init__(self,m1,m2):\n self.m1 = m1\n self.m2 = m2\n def __add__(self,other): #s1,s2\n m1=self.m1+other.m1 #54+67\n m2=self.m2+other.m2 #32+54\n s3=Student(m1,m2)\n return s3\n def __gt__(self,other): #greater than-gt\n rank1=self.m1+other.m1 #54+67\n rank2=self.m2+other.m2 #32+54\n if rank1 > rank2:\n return True\n else:\n return False\n def __str__(self):\n return '{} {}'.format(self.m1,self.m2) #we use format to convert to str bcoz it is in tuple format. we cant add str+tuple\n\ns1=Student(54,32) #m1,m2\ns2=Student(67,54) #m1,m2\n#?we cant normally add two class unless we define it as method in our class.this is called operator overloading\ns3=s1+s2 #?-->Student.__add__(s1,s2)\nprint(s3.m1)\nif s1>s2:\n print('s1 wins')\nelse:\n print('s2 wins')\n \n#? when we call a it prints value not address\na=9\nprint(a)\nprint(a.__str__())\n#?But when we call our user defined objects ,it prints value\nprint(s1) #prints address\n#?to solve that ,we need to overwrite default __str__ method.so define str in our class \nprint(s1)#print value","repo_name":"Mohamed-Abdulla/Python-core-course","sub_path":"#38-OperatorOverloading.py","file_name":"#38-OperatorOverloading.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"3123093333","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n#Day 9\n\n\n# In[2]:\n\n\n#1. Extract data from the given SalaryGender CSV file and store the data from each column in a separate NumPy array.\n\n\n# In[39]:\n\n\nimport numpy as np\nimport pandas as pd\n\n\n# In[40]:\n\n\ndf=pd.read_csv(\"D:\\Study Material\\Data Science\\Acmegrade\\Day 9\\CS 15 Ans -Data Transformation-1\\SalaryGender.csv\")\n\n\n# In[41]:\n\n\ndf.head()\n\n\n# In[42]:\n\n\nsalary = np.array(df['Salary'])\nsalary\n\n\ngender = np.array(df['Gender'])\ngender\n\n\nage = np.array(df['Age'])\nage\n\n\nphd = np.array(df['PhD'])\nphd\n\n\n# In[43]:\n\n\n#2. Find:\n#2a The number of men with PhD,\n#2B The number of women with PhD.\n\n\n# In[44]:\n\n\nsalary = np.array(df['Salary'])\ngender = np.array(df['Gender'])\nphd = np.array(df['PhD'])\nage = np.array(df['Age'])\n\nmen_count = 0\nwomen_count = 0\n\nfor i in range(0, 100):\n if gender[i] == 1 and phd[i] == 1:\n men_count +=1\n if gender[i] == 0 and phd[i] == 1:\n women_count +=1\n\nprint('Men Count', men_count)\nprint('Woman Count',women_count)\n\n\n# In[45]:\n\n\n#3. Use SalaryGender CSV file. \n#Store the “Age” and “PhD” columns in one DataFrame and delete the data of all people who don’t have a PhD.\n\n\n# In[46]:\n\n\nsalary = np.array(df['Salary'])\ngender = np.array(df['Gender'])\nphd = np.array(df['PhD'])\nage = np.array(df['Age'])\n\nframe = pd.DataFrame()\nframe[\"Age\"] = age\nframe[\"PhD\"] = phd\n\nfor i in range(0, 100):\n if frame.loc[i][\"PhD\"] == 0:\n frame = frame.drop(i)\nprint('Number of records',len(frame))\nprint(frame)\n\n\n# In[47]:\n\n\n#4. Calculate the total number of people who have a PhD degree from SalaryGender CSV file.\n\n\n# In[48]:\n\n\nphdcount=0\n\nfor i in range(0, 100):\n if df.iloc[i]['PhD'] == 1:\n phdcount=phdcount+1\n\n \nprint('PhD Count:',phdcount)\n\n\n# In[49]:\n\n\n#5. How do you Count The Number Of Times Each Value Appears In An Array Of Integers?\n\n\n# In[50]:\n\n\narr = np.array([0, 5, 4, 0, 4, 4, 3, 0, 0, 5, 2, 1, 1, 9])\nprint(np.bincount(arr))\n\n\n# In[51]:\n\n\n#6. Create a numpy array [[0, 1, 2], [ 3, 4, 5], [ 6, 7, 8],[ 9, 10, 11]]) and filter the elements greater than 5.\n\n\n# In[52]:\n\n\nimport numpy as np\nx = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])\nprint('Our array is:' )\nprint(x)\nprint('\\n')\n\n\n# In[53]:\n\n\nprint(x[x > 5])\n\n\n# In[54]:\n\n\n#7. Create a numpy array having NaN (Not a Number) and print it.\n\n\n# In[55]:\n\n\na = np.array([np.nan, 1,2,np.nan,3,4,5])\nprint(a)\nprint(a[~np.isnan(a)])\n\n\n# In[56]:\n\n\n#8. Create a 10x10 array with random values and find the minimum and maximum values.\n\n\n# In[57]:\n\n\nZ = np.random.random((10,10))\nprint (pd.DataFrame(Z))\n\n\nZmin, Zmax = Z.min(), Z.max()\nprint ('Min and Max Values')\nprint(Zmin, Zmax)\n\n\n# In[58]:\n\n\n#9. Create a random vector of size 30 and find the mean value.\n\n\n# In[59]:\n\n\nZ = np.random.random(30)\nm = Z.mean()\nprint(m)\n\n\n# In[60]:\n\n\n#10. Create numpy array having elements 0 to 10 And negate all the elements between 3 and 9\n\n\n# In[61]:\n\n\nZ = np.arange(11)\nprint ('Array')\nprint (Z)\n\nZ[(3 < Z) & (Z <= 8)] *= -1\nprint ('Negeted Array')\nprint(Z)\n\n\n# In[62]:\n\n\n#11. Create a random array of 3 rows and 3 columns and sort it according to 1st column, 2nd column or 3rd column.\n\n\n# In[63]:\n\n\nZ = np.random.randint(0,10,(3,3))\nprint(Z)\nprint ()\n\nprint(Z[Z[:,1].argsort()])\n\n\n# In[64]:\n\n\n#12. Create a four dimensions array (2,2,2,2) get sum over the last two axis at once.\n\n\n# In[65]:\n\n\nA = np.random.randint(0,10,(2,2,2,2))\nprint ('Array')\nprint (A)\n\nsum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\nprint ('Result')\nprint(sum)\n\n\n# In[66]:\n\n\n#13. Create a random array ( 5,5) and swap two rows of an array.\n\n\n# In[67]:\n\n\nA = np.arange(25).reshape(5,5)\nprint ('Random Array')\nprint (A)\n# First row assigned to Zeroth row and zero row assigned to first row\n\nA[[0,1]] = A[[1,0]]\nprint ()\nprint ('Swapped Array')\nprint(A)\n\n\n# In[68]:\n\n\n#Completed.\n\n","repo_name":"Joel4DC/Acmegrade_Data_Science_Assignments","sub_path":"Acmegrade DS Day 9.py","file_name":"Acmegrade DS Day 9.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"35512756566","text":"T = int(input())\n\nfor tc in range(1, 1+T):\n n= int(input())\n arr = [list(map(int,input().split())) for _ in range(n)]\n\n\n empty=[]\n for i in range(n):\n for j in range(n):\n if arr[i][j] != 0:\n if (arr[i-1][j]==0 or i-1<0) and (arr[i][j-1]==0 or j-1<0):\n empty.append([i,j])\n\n bin = []\n for m in range(len(empty)): #0 1 2\n x=empty[m][0] #00 = 2\n y=empty[m][1] #01 =0\n cnt1 =0\n cnt2=0\n for l in range(n):\n if x+lbin[b][0]*bin[b][1]:\n bin[a],bin[b]=bin[b],bin[a]\n elif bin[a][0]*bin[a][1]==bin[b][0]*bin[b][1]:\n if bin[a][0] > bin[b][0]:\n bin[a],bin[b] =bin[b],bin[a]\n\n print(f'#{tc} {len(bin)}',end= \" \")\n\n\n for f in bin:\n for g in f:\n print(g,end=\" \")\n\n print()\n\n\n\n","repo_name":"gusdud2068/algorithm","sub_path":"1258.py","file_name":"1258.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18129056675","text":"class Solution(object):\n\n def __init__(self):\n self.ans = 0\n\n def numSplits(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n\n start = {}\n end = {}\n abc = set()\n for idx, ch in enumerate(s[:-1]):\n abc.add(ch)\n start[idx] = len(abc)\n\n abc = set()\n for idx, ch in enumerate(s[:0:-1]):\n abc.add(ch)\n end[idx] = len(abc)\n\n print(start)\n print(end)\n\n for i in range(len(start)):\n if start[i] == end[len(end)-1-i]:\n self.ans += 1\n\n print(self.ans)\n return self.ans\n\n\ns = Solution()\ns.numSplits(s=\"aacaba\")\n","repo_name":"TOOFACK/DailyCodingPy","sub_path":"LeetCode/1525. Number of Good Ways to Split a String.py","file_name":"1525. Number of Good Ways to Split a String.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10232628759","text":"import sys\nimport json\nfrom os.path import join\n\nfrom evaluation import output\n\nfile_directories = sys.argv[1:]\n\nfor fdir in file_directories:\n print(fdir)\n try:\n results = json.load(open(join(fdir, \"results.json\")))\n except FileNotFoundError:\n print(\" skipping (no results.json)\")\n\n output.to_latex_table_row(results, fdir,\n name=fdir.split(\"/\")[-1].replace(\"_\", \" \"),\n italic_ood=False,\n blank_ood=False,\n italic_entrop=False,\n blank_classif=False)\n\n","repo_name":"vislearn/IB-INN","sub_path":"re_output.py","file_name":"re_output.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"3"}
+{"seq_id":"17448693717","text":"import pytest\nfrom Data_Structures.linked_list.linked_list import Linked_list\nfrom code_challenges.ll_zip.ll_zip import zipLists\n\ndef test_zipLists():\n\n ll1 = Linked_list()\n for i in range(1,5):\n ll1.append(i)\n\n ll2 = Linked_list()\n for i in range(5,10):\n ll2.append(i)\n\n actual = zipLists(ll1,ll2)\n\n expected = '{1} -> {5} -> {2} -> {6} -> {3} -> {7} -> {4} -> {8} -> {9} -> None'\n assert actual == expected\n\n\n","repo_name":"NizarAlsaeed/data-structures-and-algorithms","sub_path":"python/tests/test_ll_zip.py","file_name":"test_ll_zip.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25200797670","text":"#! /usr/bin/python\n\nimport examples.dds as dds\nimport examples.hands as hands\nimport examples.functions as functions\nimport ctypes\n\ndl = dds.deal()\nfut2 = dds.futureTricks()\nfut3 = dds.futureTricks()\n\nthreadIndex = 0\nline = ctypes.create_string_buffer(80)\n\ndds.SetMaxThreads(0)\n\nfor handno in range(1):\n dl.trump = hands.trump[handno]\n dl.first = hands.first[handno]\n\n dl.currentTrickSuit[0] = 0\n dl.currentTrickSuit[1] = 0\n dl.currentTrickSuit[2] = 0\n\n dl.currentTrickRank[0] = 0\n dl.currentTrickRank[1] = 0\n dl.currentTrickRank[2] = 0\n\n for h in range(dds.DDS_HANDS):\n for s in range(dds.DDS_SUITS):\n if hands.holdings[handno][s][h] is not None:\n dl.remainCards[h][s] = hands.holdings[handno][s][h]\n\n target = -1 # No target; find all results\n solutions = 3 # Return all solutions\n mode = 0 # The way dds internally handles the last trick\n res = dds.SolveBoard(dl, target, solutions, mode,\n ctypes.pointer(fut3), threadIndex)\n\n if res != dds.RETURN_NO_FAULT:\n dds.ErrorMessage(res, line)\n print(\"DDS error: {}\".format(line.value.decode(\"utf-8\")))\n\n # match3 = functions.CompareFut(ctypes.pointer(fut3), handno, solutions)\n\n solutions = 2 # Return only the optmial solutions\n res = dds.SolveBoard(dl, target, solutions, mode,\n ctypes.pointer(fut2), threadIndex)\n\n functions.PrintHand(line, dl.remainCards)\n\n line = \"solutions == 3\"\n score_table = functions.PrintFut(\n line, ctypes.pointer(fut3), is_print=True)\n\n nb_solutions = sum([len(x) for x in list(score_table.values())])\n print(f\"number of solutions {nb_solutions}\")\n","repo_name":"antsticky/qBridgeLib","sub_path":"project/analytics/dds_project/examples/SolveBoard.py","file_name":"SolveBoard.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5264777274","text":"import numpy as np\n\nfrom openmdao.api import ExplicitComponent\n\n\nclass dragComp(ExplicitComponent):\n\n # def initialize(self):\n # self.options.declare('CD', types=float)\n\n def setup(self):\n self.add_input('speed')\n self.add_input('density')\n self.add_input('CD')\n self.add_input('S_w')\n self.add_output('drag')\n\n self.declare_partials('drag', 'speed')\n self.declare_partials('drag', 'density')\n self.declare_partials('drag', 'CD')\n self.declare_partials('drag', 'S_w')\n\n def compute(self, inputs, outputs):\n # CD = self.options['CD']\n\n speed = inputs['speed']\n density = inputs['density']\n CD = inputs['CD']\n S_w = inputs['S_w']\n outputs['drag'] = CD * 0.5 * speed ** 2 * density * S_w\n\n def compute_partials(self, inputs, partials):\n # CD = self.options['CD']\n\n speed = inputs['speed']\n density = inputs['density']\n CD = inputs['CD']\n S_w = inputs['S_w']\n\n partials['drag', 'speed'] = CD * density * speed * S_w\n partials['drag', 'density'] = CD * 0.5 * speed ** 2 * S_w\n partials['drag', 'CD'] = density * 0.5 * speed ** 2 * S_w\n partials['drag', 'S_w'] = CD * density * 0.5 * speed ** 2","repo_name":"cemacken/mae155b_group4","sub_path":"components/aeroprop/drag_comp.py","file_name":"drag_comp.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9835350897","text":"import io\r\nimport os\r\nfrom reportlab.pdfgen import canvas\r\nfrom reportlab.lib.pagesizes import letter\r\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\r\n\r\ndef complete_form(df,hospital):\r\n \r\n if os.path.isdir('F-IEEH'):\r\n None\r\n else:\r\n os.mkdir('F-IEEH')\r\n\r\n for i in range((len(df))):\r\n packet = io.BytesIO()\r\n # create a new PDF with Reportlab\r\n can = canvas.Canvas(packet, pagesize=letter)\r\n\r\n #Nombre Establecimiento\r\n text = can.beginText(30, 872)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(hospital)\r\n can.drawText(text)\r\n\r\n #Código Establecimineto\r\n text = can.beginText(253, 872)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][2]))\r\n can.drawText(text)\r\n\r\n #Número Admisión\r\n text = can.beginText(349, 872)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][0]))\r\n can.drawText(text)\r\n\r\n #Número Ficha\r\n text = can.beginText(456, 872)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][4]))\r\n can.drawText(text)\r\n\r\n #Número Egreso\r\n text = can.beginText(503, 904)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][1]))\r\n can.drawText(text)\r\n\r\n #Primer Apellido\r\n text = can.beginText(49, 828)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][5]))\r\n can.drawText(text)\r\n\r\n #Primer Apellido\r\n text = can.beginText(216, 828)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][6]))\r\n can.drawText(text)\r\n\r\n #Nombre Paciente\r\n text = can.beginText(432, 828)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][7]))\r\n can.drawText(text)\r\n\r\n #Tipo_id\r\n text = can.beginText(114, 803)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][8]))\r\n can.drawText(text)\r\n\r\n #RUT\r\n text = can.beginText(57, 781)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][9]))\r\n can.drawText(text)\r\n\r\n #DV\r\n text = can.beginText(158, 781)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][10]))\r\n can.drawText(text)\r\n\r\n #Pasaporte\r\n text = can.beginText(57, 755)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][11]))\r\n can.drawText(text)\r\n\r\n #Sexo\r\n text = can.beginText(272, 802)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][12]))\r\n can.drawText(text)\r\n\r\n #Día Nac\r\n text = can.beginText(452, 800)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][13]))\r\n can.drawText(text)\r\n\r\n #Mes Nac\r\n text = can.beginText(490, 800)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][14]))\r\n can.drawText(text)\r\n\r\n #Año Nac\r\n text = can.beginText(525, 800)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][15]))\r\n can.drawText(text)\r\n\r\n #Pueblo Indigena\r\n text = can.beginText(355, 773)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][18]))\r\n can.drawText(text)\r\n\r\n #Edad\r\n text = can.beginText(81, 736)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][16]))\r\n can.drawText(text)\r\n\r\n #Unidad Edad\r\n text = can.beginText(170, 736)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][17]))\r\n can.drawText(text)\r\n\r\n #Nombre País\r\n text = can.beginText(475, 728)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine('CHILE')\r\n can.drawText(text)\r\n\r\n #Categoria Ocupacional\r\n text = can.beginText(47, 680)\r\n text.setCharSpace(0.1)\r\n text.setFont(\"Courier\", 8)\r\n text.textLine(str(df.iloc[i][22]))\r\n can.drawText(text)\r\n\r\n #Glosa\r\n text = can.beginText(160, 703)\r\n text.setCharSpace(0.1)\r\n text.setFont(\"Courier\", 8)\r\n text.textLine(str(df.iloc[i][23]))\r\n can.drawText(text)\r\n\r\n #Nvl Instrucción\r\n text = can.beginText(374, 682)\r\n text.setCharSpace(0.1)\r\n text.setFont(\"Courier\", 8)\r\n text.textLine(str(df.iloc[i][21]))\r\n can.drawText(text)\r\n\r\n #Vía\r\n text = can.beginText(98, 600)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][28]))\r\n can.drawText(text)\r\n\r\n #Domicilio\r\n text = can.beginText(120, 600)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][26]))\r\n can.drawText(text)\r\n\r\n #Número\r\n text = can.beginText(525, 600)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][27]))\r\n can.drawText(text)\r\n\r\n #Comuna\r\n text = can.beginText(355, 584)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 9)\r\n text.textLine(str(df.iloc[i][184]))\r\n can.drawText(text)\r\n\r\n #Previsión\r\n text = can.beginText(56, 545)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][30]))\r\n can.drawText(text)\r\n\r\n #Tramo\r\n text = can.beginText(238, 542)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][31]))\r\n can.drawText(text)\r\n\r\n #Modalidad\r\n text = can.beginText(343, 541)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][32]))\r\n can.drawText(text)\r\n\r\n #Leyes Provisionales\r\n text = can.beginText(377, 551)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][33]))\r\n can.drawText(text)\r\n\r\n #Leyes Provisionales\r\n text = can.beginText(568, 539)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][34]))\r\n can.drawText(text)\r\n\r\n #Procedencia\r\n text = can.beginText(227, 502)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][35]))\r\n can.drawText(text)\r\n\r\n #Nombre Procedencia\r\n text = can.beginText(253, 503)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 4.5)\r\n text.textLine(str(df.iloc[i][36]))\r\n can.drawText(text)\r\n\r\n #Nombre Procedencia\r\n text = can.beginText(253, 503)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 4.5)\r\n text.textLine(str(df.iloc[i][36]))\r\n can.drawText(text)\r\n\r\n #Nombre Procedencia\r\n text = can.beginText(514, 502)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][37]))\r\n can.drawText(text)\r\n\r\n #Hora Ingreso\r\n text = can.beginText(104, 454)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][38]))\r\n can.drawText(text)\r\n\r\n #Minutos Ingreso\r\n text = can.beginText(137, 454)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][39]))\r\n can.drawText(text)\r\n\r\n #Día Ingreso\r\n text = can.beginText(183, 454)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][40]))\r\n can.drawText(text)\r\n\r\n #Mes Ingreso\r\n text = can.beginText(217, 454)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][41]))\r\n can.drawText(text)\r\n\r\n #Año Ingreso\r\n text = can.beginText(251, 454)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][42]))\r\n can.drawText(text)\r\n\r\n #U.F.\r\n text = can.beginText(507, 454)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][43]))\r\n can.drawText(text)\r\n \r\n #S.C.\r\n text = can.beginText(549, 454)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][44]))\r\n can.drawText(text)\r\n\r\n #Día 1er Traslado\r\n text = can.beginText(183, 438)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][45]))\r\n can.drawText(text)\r\n\r\n #Mes 1er Traslado\r\n text = can.beginText(217, 438)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][46]))\r\n can.drawText(text)\r\n\r\n #Año 1er Traslado\r\n text = can.beginText(251, 438)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][47]))\r\n can.drawText(text)\r\n\r\n #U.F.1er Traslado\r\n text = can.beginText(507, 438)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][48]))\r\n can.drawText(text)\r\n \r\n #S.C. 1er Traslado\r\n text = can.beginText(549, 438)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][49]))\r\n can.drawText(text)\r\n \r\n #Día 2do Traslado\r\n text = can.beginText(183, 423)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][50]))\r\n can.drawText(text)\r\n\r\n #Mes 2do Traslado\r\n text = can.beginText(217, 423)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][51]))\r\n can.drawText(text)\r\n\r\n #Año 2do Traslado\r\n text = can.beginText(251, 423)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][52]))\r\n can.drawText(text)\r\n\r\n #U.F. 2do Traslado\r\n text = can.beginText(507, 423)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][53]))\r\n can.drawText(text)\r\n\r\n #S.C. 2do Traslado\r\n text = can.beginText(549, 423)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][54]))\r\n can.drawText(text)\r\n \r\n #Día 3er Traslado\r\n text = can.beginText(183, 408)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][55]))\r\n can.drawText(text)\r\n\r\n #Mes 3er Traslado\r\n text = can.beginText(217, 408)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][56]))\r\n can.drawText(text)\r\n\r\n #Año 3er Traslado\r\n text = can.beginText(251, 408)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][57]))\r\n can.drawText(text)\r\n\r\n #U.F. 3er Traslado\r\n text = can.beginText(507, 408)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][58]))\r\n can.drawText(text)\r\n\r\n #S.C. 3er Traslado\r\n text = can.beginText(549, 408)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][59]))\r\n can.drawText(text)\r\n \r\n #Día 4to Traslado\r\n text = can.beginText(183, 392)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][60]))\r\n can.drawText(text)\r\n\r\n #Mes 4to Traslado\r\n text = can.beginText(217, 392)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][61]))\r\n can.drawText(text)\r\n\r\n #Año 4to Traslado\r\n text = can.beginText(251, 392)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][62]))\r\n can.drawText(text)\r\n\r\n #U.F. 4to Traslado\r\n text = can.beginText(507, 392)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][63]))\r\n can.drawText(text)\r\n\r\n #S.C. 4to Traslado\r\n text = can.beginText(549, 392)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][64]))\r\n can.drawText(text)\r\n \r\n #Hora Egreso\r\n text = can.beginText(94, 353)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][90]))\r\n can.drawText(text)\r\n\r\n #Minutos Egreso\r\n text = can.beginText(127, 353)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][91]))\r\n can.drawText(text)\r\n\r\n #Día Egreso\r\n text = can.beginText(171, 353)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][92]))\r\n can.drawText(text)\r\n\r\n #Mes Egreso\r\n text = can.beginText(206, 353)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][93]))\r\n can.drawText(text)\r\n\r\n #Año Egreso\r\n text = can.beginText(240, 353)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][94]))\r\n can.drawText(text)\r\n\r\n #U.F. Egreso\r\n text = can.beginText(508, 357)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][95]))\r\n can.drawText(text)\r\n\r\n #S.C. Egreso\r\n text = can.beginText(549, 357)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][96]))\r\n can.drawText(text)\r\n \r\n #Días Estada\r\n text = can.beginText(105, 335)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][97]))\r\n can.drawText(text)\r\n\r\n #Condición al Alta\r\n text = can.beginText(252, 336)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][98]))\r\n can.drawText(text)\r\n\r\n #Destino al Alta\r\n text = can.beginText(283, 361)\r\n text.setCharSpace(4.5)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][99]))\r\n can.drawText(text)\r\n\r\n #Diagnóstico Principal\r\n text = can.beginText(138, 309)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][100]))\r\n can.drawText(text)\r\n\r\n #Diagnóstico Principal\r\n text = can.beginText(522, 309)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][101]))\r\n can.drawText(text)\r\n\r\n #Causa Externa\r\n text = can.beginText(138, 295)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][102]))\r\n can.drawText(text)\r\n\r\n #Causa Externa Código\r\n text = can.beginText(522, 295)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][103]))\r\n can.drawText(text)\r\n\r\n #Diagnóstico 2\r\n text = can.beginText(138, 282)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][104]))\r\n can.drawText(text)\r\n\r\n #Código Diag 2\r\n text = can.beginText(522, 282)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][105]))\r\n can.drawText(text)\r\n\r\n #Diagnóstico 3\r\n text = can.beginText(138, 268)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][106]))\r\n can.drawText(text)\r\n\r\n #Código Diag 3\r\n text = can.beginText(522, 268)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][107]))\r\n can.drawText(text)\r\n\r\n #Intervención Quirúrgica\r\n text = can.beginText(152, 172)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][122]))\r\n can.drawText(text)\r\n\r\n #Intervención Quirúrgica Nombre\r\n text = can.beginText(180, 161)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 9)\r\n text.textLine(str(df.iloc[i][123]))\r\n can.drawText(text)\r\n\r\n #Intervención Quirúrgica 2 Nombre\r\n text = can.beginText(180, 148)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 9)\r\n text.textLine(str(df.iloc[i][124]))\r\n can.drawText(text)\r\n\r\n #Procedimiento\r\n text = can.beginText(62, 107)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][126]))\r\n can.drawText(text)\r\n\r\n #Procedimiento 1 Nombre\r\n text = can.beginText(242, 121)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 9)\r\n text.textLine(str(df.iloc[i][127]))\r\n can.drawText(text)\r\n\r\n #Procedimiento 2 Nombre\r\n text = can.beginText(242, 106)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 9)\r\n text.textLine(str(df.iloc[i][128]))\r\n can.drawText(text)\r\n\r\n #Apellido Paterno Profesional\r\n text = can.beginText(30, 60)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][140]))\r\n can.drawText(text)\r\n\r\n #Apellido Materno Profesional\r\n text = can.beginText(145, 60)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][141]))\r\n can.drawText(text)\r\n\r\n #Nombre Profesional\r\n text = can.beginText(260, 60)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][142]))\r\n can.drawText(text)\r\n\r\n #RUN Profesional\r\n text = can.beginText(58, 35)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][143]))\r\n can.drawText(text)\r\n\r\n #DV Profesional\r\n text = can.beginText(160, 35)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 12)\r\n text.textLine(str(df.iloc[i][144]))\r\n can.drawText(text)\r\n\r\n #Especialidad Profesional\r\n text = can.beginText(335, 78)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 11)\r\n text.textLine(str(df.iloc[i][186]))\r\n can.drawText(text)\r\n\r\n #Datos recién nacido\r\n #Condición al nacer 1\r\n text = can.beginText(145, 215)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][146]))\r\n can.drawText(text)\r\n\r\n #Sexo al nacer 1\r\n text = can.beginText(245, 215)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][147]))\r\n can.drawText(text)\r\n\r\n #Peso al nacer 1\r\n text = can.beginText(330, 215)\r\n text.setCharSpace(24)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][148]))\r\n can.drawText(text)\r\n\r\n #Apgar al nacer 1\r\n text = can.beginText(455, 215)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][149]))\r\n can.drawText(text)\r\n\r\n #Anomalia al nacer 1\r\n text = can.beginText(517, 215)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][150]))\r\n can.drawText(text)\r\n\r\n #Condición al nacer 2\r\n text = can.beginText(145, 205.5)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][151]))\r\n can.drawText(text)\r\n\r\n #Sexo al nacer 2\r\n text = can.beginText(245, 205.5)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][152]))\r\n can.drawText(text)\r\n\r\n #Peso al nacer 2\r\n text = can.beginText(330, 205.5)\r\n text.setCharSpace(24)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][153]))\r\n can.drawText(text)\r\n\r\n #Apgar al nacer 2\r\n text = can.beginText(455, 205.5)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][154]))\r\n can.drawText(text)\r\n\r\n #Anomalia al nacer 2\r\n text = can.beginText(517, 205.5)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][155]))\r\n can.drawText(text)\r\n\r\n #Condición al nacer 3\r\n text = can.beginText(145, 196.7)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][156]))\r\n can.drawText(text)\r\n\r\n #Sexo al nacer 3\r\n text = can.beginText(245, 196.7)\r\n text.setCharSpace(4.4)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][157]))\r\n can.drawText(text)\r\n\r\n #Peso al nacer 3\r\n text = can.beginText(330, 196.7)\r\n text.setCharSpace(24)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][158]))\r\n can.drawText(text)\r\n\r\n #Apgar al nacer 3\r\n text = can.beginText(455, 196.7)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][159]))\r\n can.drawText(text)\r\n\r\n #Anomalia al nacer 3\r\n text = can.beginText(517, 196.7)\r\n text.setCharSpace(0.5)\r\n text.setFont(\"Courier\", 10)\r\n text.textLine(str(df.iloc[i][160]))\r\n can.drawText(text)\r\n can.save()\r\n\r\n #move to the beginning of the StringIO buffer\r\n packet.seek(0)\r\n new_pdf = PdfFileReader(packet)\r\n # read your existing PDF\r\n existing_pdf = PdfFileReader(open(\"Formulario-IEEH-2019.pdf\", \"rb\"))\r\n output = PdfFileWriter()\r\n # add the \"watermark\" (which is the new pdf) on the existing page\r\n page = existing_pdf.getPage(0)\r\n page.mergePage(new_pdf.getPage(0))\r\n output.addPage(page)\r\n # finally, write \"output\" to a real file\r\n outputStream = open(\"F-IEEH/\"+str(df.iloc[i][7])+\" \"+str(df.iloc[i][6])+\" \"+str(df.iloc[i][5])+\".pdf\", \"wb\")\r\n output.write(outputStream)\r\n outputStream.close()","repo_name":"vhevia11/formularios_IEEH","sub_path":"register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":23769,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"43691658523","text":"#!/usr/bin/env python\n\nfrom losoto.h5parm import h5parm\nfrom losoto.lib_operations import *\n\nimport numpy\nimport logging\n########################################################################\ndef main(h5parmdb, solsetName='sol000', pointing='POINTING'):\n\n\n logging.info(\"Setting \" + str(pointing) + \" as pointing direction for the solset \" + str(solsetName) + \" in \" + str(h5parmdb))\n \n data = h5parm(h5parmdb, readonly = False) \n solset = data.getSolset(solsetName)\n \n sources = solset.obj._f_get_child('source')\n direction = list(sources[0][-1])\n \n for i in numpy.arange(len(sources)):\n sources[i] = (pointing, direction)\n \n data.close()\n return(0)\n\n \n########################################################################\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description='Define the pointing direction of an h5parm.')\n\n parser.add_argument('h5parmdb', type=str,\n help='H5parm of which pointing will be set.')\n parser.add_argument('--solsetName', '--solset', type=str, default='sol000',\n help='Name of the h5parm solution set (default: sol000)')\n parser.add_argument('--pointing', type=str, default='POINTING',\n help='Name of the h5parm solution set (default: POINTING)')\n\n args = parser.parse_args()\n\n format_stream = logging.Formatter(\"%(asctime)s\\033[1m %(levelname)s:\\033[0m %(message)s\",\"%Y-%m-%d %H:%M:%S\")\n format_file = logging.Formatter(\"%(asctime)s %(levelname)s: %(message)s\",\"%Y-%m-%d %H:%M:%S\")\n logging.root.setLevel(logging.INFO)\n\n log = logging.StreamHandler()\n log.setFormatter(format_stream)\n logging.root.addHandler(log)\n \n h5parmdb = args.h5parmdb\n main(h5parmdb, solsetName=args.solsetName, pointing=args.pointing)\n","repo_name":"lofar-astron/prefactor","sub_path":"scripts/h5parm_pointingname.py","file_name":"h5parm_pointingname.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"3"}
+{"seq_id":"393617675","text":"import configparser\nimport os\nimport stat\n\n__author__ = 'ferezgaetan'\n__version__ = '0.2'\n\n\n# Default values:\nDB = \"mongodb:///manpki\"\nDEFAULT_CONFIG = \"/etc/manpki/manpki.conf\"\n\nif 'DEBUG' not in __builtins__:\n DEBUG = False\nelse:\n import builtins\n DEBUG = builtins.DEBUG\n\nif 'LOGFILE' not in __builtins__:\n LOGFILE = '/var/log/manpki/manpkid.log'\nelse:\n import builtins\n LOGFILE = builtins.LOGFILE\n\nif 'DAEMON' not in __builtins__:\n DAEMON = False\nelse:\n import builtins\n DAEMON = builtins.DAEMON\n\nGZ_CMD = \"zcat\"\nBZ2_CMD = \"bzcat\"\n\n# Feed with a random value, like `openssl rand -base64 42`.\n# *Mandatory* when WEB_PUBLIC_SRV == True\nWEB_SECRET = '^\\x02\\xde\\xbb\\xb7\\xd2\\x9f\\xf1\\xbe\\xc1$Rp\\xc9\\xc5\\x11\\xbf\\x8f}\\x0e\\xe8^\\x1aZ'\nTOKEN_SECRET = 'MiQKYnxnmhI97KgqJe02XAg+ZAuz3N7B9x+/VPluk/Yr3BJPGxezC7kh'\n\nAPI_VERSION = 'v1.0'\n\nConfigObject = None\nManPKIObject = None\n\n\ndef get_config_file(paths=None):\n \"\"\"Generates (yields) the available config files, in the correct order.\"\"\"\n if DEBUG:\n from manpki.logger import log\n log.debug(\"Get config file\")\n if paths is None:\n paths = [os.path.join(path, 'manpki.conf')\n for path in ['/etc/manpki', os.path.expanduser('~/.manpki')]]\n for path in paths:\n if os.path.isfile(path):\n yield path\n\n\ndef get_config_directory(paths=None):\n \"\"\"Generates (yields) the available config directory in the correct order.\"\"\"\n if DEBUG:\n from manpki.logger import log\n log.debug(\"Get CONFIG directory\")\n if paths is None:\n paths = ['/etc/manpki', os.path.expanduser('~/.manpki')]\n for path in paths:\n if os.path.isdir(path) and os.access(path, os.W_OK):\n return path\n return None\n\n\ndef get_run_directory(paths=None):\n \"\"\"Generates (yields) the available run directory in the correct order.\"\"\"\n if DEBUG:\n from manpki.logger import log\n log.debug(\"Get RUN directory\")\n if paths is None:\n paths = ['/var/run/manpki', '/run/manpki', os.path.expanduser('~/.manpki')]\n for path in paths:\n if os.path.isdir(path) and os.access(path, os.W_OK):\n return path\n return None\n\n\ndef get_var_directory(paths=None):\n \"\"\"Generates (yields) the available config files, in the correct order.\"\"\"\n if DEBUG:\n from manpki.logger import log\n log.debug(\"Get VAR directory\")\n if paths is None:\n paths = ['/var/lib/manpki', os.path.expanduser('~/.manpki')]\n for path in paths:\n if os.path.isdir(path):\n return path\n return None\n\n\ndef init_directory():\n if os.geteuid() == 0:\n if not get_config_directory() and not os.path.exists(\"/etc/manpki\"):\n os.makedirs(\"/etc/manpki\")\n if not get_var_directory() and not os.path.exists(\"/var/lib/manpki\"):\n os.makedirs(\"/var/lib/manpki\")\n os.makedirs(\"/var/lib/manpki/cert\")\n os.makedirs(\"/var/lib/manpki/cert/public\")\n os.makedirs(\"/var/lib/manpki/cert/public/ca\")\n os.makedirs(\"/var/lib/manpki/cert/public/certificates\")\n os.makedirs(\"/var/lib/manpki/cert/private\")\n os.makedirs(\"/var/lib/manpki/cert/private/ca\")\n os.makedirs(\"/var/lib/manpki/cert/private/certificates\")\n os.makedirs(\"/var/lib/manpki/db\")\n elif get_var_directory():\n path = get_var_directory()\n if not os.path.exists(path+\"/cert\"):\n os.makedirs(\"/var/lib/manpki/cert\")\n os.makedirs(\"/var/lib/manpki/cert/public\")\n os.makedirs(\"/var/lib/manpki/cert/public/ca\")\n os.makedirs(\"/var/lib/manpki/cert/public/certificates\")\n os.makedirs(\"/var/lib/manpki/cert/private\")\n os.makedirs(\"/var/lib/manpki/cert/private/ca\")\n os.makedirs(\"/var/lib/manpki/cert/private/certificates\")\n if not os.path.exists(path + \"/db\"):\n os.makedirs(\"/var/lib/manpki/db\")\n if not get_run_directory(['/var/run/manpki', '/run/manpki']):\n os.makedirs(\"/var/run/manpki\")\n if not os.path.exists(\"/var/log/manpki\"):\n os.makedirs(\"/var/log/manpki\")\n else:\n if not os.path.exists(os.path.expanduser('~/.manpki')):\n os.makedirs(os.path.expanduser('~/.manpki'))\n os.makedirs(os.path.expanduser('~/.manpki/log'))\n os.makedirs(os.path.expanduser('~/.manpki/cert'))\n os.makedirs(os.path.expanduser('~/.manpki/cert/public'))\n os.makedirs(os.path.expanduser('~/.manpki/cert/public/ca'))\n os.makedirs(os.path.expanduser('~/.manpki/cert/public/certificates'))\n os.makedirs(os.path.expanduser('~/.manpki/cert/private'))\n os.makedirs(os.path.expanduser('~/.manpki/cert/private/ca'))\n os.makedirs(os.path.expanduser('~/.manpki/cert/private/certificates'))\n os.makedirs(os.path.expanduser('~/.manpki/db'))\n\n\ndef init_acl():\n import pwd\n import grp\n import sys\n try:\n pwd.getpwnam('manpki')\n except KeyError:\n print('User manpki does not exist. Create it before')\n sys.exit()\n try:\n grp.getgrnam('manpki')\n except KeyError:\n print('Group manpki does not exist. Create it before')\n sys.exit()\n\n if get_run_directory():\n path = get_run_directory()\n os.chown(path, pwd.getpwnam(\"manpki\").pw_uid, grp.getgrnam('manpki').gr_gid)\n os.chown('/var/log/manpki', pwd.getpwnam(\"manpki\").pw_uid, grp.getgrnam('manpki').gr_gid)\n if os.path.isfile('/var/log/manpki/manpkid.log'):\n os.chown('/var/log/manpki/manpkid.log', pwd.getpwnam(\"manpki\").pw_uid, grp.getgrnam('manpki').gr_gid)\n if get_var_directory():\n path = get_var_directory()\n os.chown(path, pwd.getpwnam(\"manpki\").pw_uid, grp.getgrnam('manpki').gr_gid)\n os.chown(path+'/cert', pwd.getpwnam(\"manpki\").pw_uid, grp.getgrnam('manpki').gr_gid)\n os.chown(path+'/db', pwd.getpwnam(\"manpki\").pw_uid, grp.getgrnam('manpki').gr_gid)\n os.chown(path + '/db/manpki.json', pwd.getpwnam(\"manpki\").pw_uid, grp.getgrnam('manpki').gr_gid)\n if get_config_directory():\n path = get_config_directory()\n os.chown(path, pwd.getpwnam(\"manpki\").pw_uid, grp.getgrnam('manpki').gr_gid)\n\n\ndef init_db():\n from tinydb import TinyDB\n path = get_var_directory() + \"/db\"\n db = TinyDB(path + '/manpki.json')\n db.purge_tables()\n\n ## Extension\n exten = db.table('extension')\n #### KeyUsage\n exten.insert({'type': 'keyusage', 'oid': '2.5.29.15.0', 'name': 'digitalSignature', '_default': True})\n exten.insert({'type': 'keyusage', 'oid': '2.5.29.15.1', 'name': 'nonRepudiation', '_default': True})\n exten.insert({'type': 'keyusage', 'oid': '2.5.29.15.2', 'name': 'keyEncipherment', '_default': True})\n exten.insert({'type': 'keyusage', 'oid': '2.5.29.15.3', 'name': 'dataEncipherment', '_default': True})\n exten.insert({'type': 'keyusage', 'oid': '2.5.29.15.4', 'name': 'keyAgreement', '_default': True})\n exten.insert({'type': 'keyusage', 'oid': '2.5.29.15.5', 'name': 'keyCertSign', '_default': True})\n exten.insert({'type': 'keyusage', 'oid': '2.5.29.15.6', 'name': 'cRLSign', '_default': True})\n exten.insert({'type': 'keyusage', 'oid': '2.5.29.15.7', 'name': 'encipherOnly', '_default': True})\n exten.insert({'type': 'keyusage', 'oid': '2.5.29.15.8', 'name': 'decipherOnly', '_default': True})\n\n ### Extended Key Usage\n exten.insert(\n {'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.1', 'name': 'TLS Web Server Authentication', '_default': True})\n exten.insert(\n {'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.2', 'name': 'TLS Web Client Authentication', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.3', 'name': 'Code Signing', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.4', 'name': 'Email Protection', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.8', 'name': 'Time Stamping', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.9', 'name': 'OCSP Signer', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.13', 'name': 'EAP over PPP', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.14', 'name': 'EAP over LAN', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.15', 'name': 'SCVP Server', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.16', 'name': 'SCVP Client', '_default': True})\n exten.insert(\n {'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.17', 'name': 'Internal Key Exchange for IPSEC', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.20', 'name': 'SIP Domain', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.21', 'name': 'SSH Server', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.5.7.3.22', 'name': 'SSH Client', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.4.1.311.20.2.2', 'name': 'MS Smart Card Logon', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.4.1.311.10.3.12', 'name': 'MS Document Signing', '_default': True})\n exten.insert(\n {'type': 'extended', 'oid': '1.3.6.1.4.1.311.2.1.21', 'name': 'MS Individual Code Signing', '_default': True})\n exten.insert(\n {'type': 'extended', 'oid': '1.3.6.1.4.1.311.2.1.22', 'name': 'MS Commercial Code Signing', '_default': True})\n exten.insert(\n {'type': 'extended', 'oid': '1.3.6.1.4.1.311.10.3.4', 'name': 'MS Encrypted File System (EFS)', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.4.1.311.10.3.4.1', 'name': 'MS EFS Recovery', '_default': True})\n exten.insert({'type': 'extended', 'oid': '2.16.840.1.113741.1.2.3', 'name': 'Intel AMT Management', '_default': True})\n exten.insert({'type': 'extended', 'oid': '0.4.0.2231.3.0', 'name': 'ETSI TSL Signing', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.2.840.113583.1.1.5', 'name': 'Adobe PDF Signing', '_default': True})\n exten.insert(\n {'type': 'extended', 'oid': '1.2.203.7064.1.1.369791.1', 'name': 'CSN 369791 TLS Client', '_default': True})\n exten.insert(\n {'type': 'extended', 'oid': '1.2.203.7064.1.1.369791.2', 'name': 'CSN 368781 TLS Server', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.2.3.4', 'name': 'Kerberos Key Authentication', '_default': True})\n exten.insert({'type': 'extended', 'oid': '1.3.6.1.5.2.3.5', 'name': 'Kerberos KDC', '_default': True})\n exten.insert({'type': 'extended', 'oid': '2.23.136.1.1.3', 'name': 'ICAO Master List Signing', '_default': True})\n exten.insert({'type': 'extended', 'oid': '2.16.840.1.101.3.6.8', 'name': 'PIV Card Authentication', '_default': True})\n\n ## Profile\n profile = db.table('profile')\n ### SSL Profile\n profile.insert({'name': 'SSLServer', 'keyusage': '2.5.29.15.3|2.5.29.15.2|2.5.29.15.1', 'extended': '1.3.6.1.5.5.7.3.1',\n 'ldap': '', '_default': True})\n profile.insert({'name': 'SSLUser', 'keyusage': '2.5.29.15.1|2.5.29.15.2|2.5.29.15.3',\n 'extended': '1.3.6.1.5.5.7.3.22|1.3.6.1.5.5.7.3.2|1.3.6.1.5.5.7.3.3', 'ldap': '(objectClass=person)',\n '_default': True})\n profile.insert(\n {'name': 'OCSPResponder', 'keyusage': '2.5.29.15.0|2.5.29.15.1|2.5.29.15.2', 'extended': '1.3.6.1.5.5.7.3.9',\n 'ldap': '', '_default': True})\n\n ## Parameters\n param = db.table('parameter')\n ### CA\n param.insert(\n {'object': 'ca', 'email': '', 'validity': 3560, 'keysize': 1024, 'basecn': 'C=FR', 'name': 'CA', 'digest': 'sha256',\n 'typeca': 'rootca', 'isfinal': True})\n\n ### CERT\n param.insert({'object': 'cert', 'validity': 365, 'keysize': 1024, 'digest': 'sha256'})\n\n ## CRL\n param.insert({'object': 'crl', 'enable': False, 'digest': 'md5', 'validity': 30})\n\n ## OCSP\n param.insert({'object': 'ocsp', 'enable': False, 'uri': 'http://ocsp/'})\n\n ## LDAP\n param.insert({'object': 'ldap', 'enable': False, 'host': 'ldap://ldap:389/', 'dn': 'cn=admin', 'password': 'password',\n 'mode': 'ondemand', 'schedule': '5m'})\n\n ## Mail\n param.insert({'object': 'mail', 'enable': False, 'host': 'smtp', 'sender': 'manpki@example.com'})\n\n ## Server\n param.insert({'object': 'server', 'sslcert': 'cert.pem', 'sslkey': 'key.pem', 'host': 'socket', 'port': 8080})\n\n ## Users\n db.table('user')\n db.close()\n\n\ndef init_files():\n path = None\n if os.geteuid() == 0:\n if os.path.isdir('/usr/share/manpki'):\n path = '/usr/share/manpki'\n if os.path.isdir('/usr/local/share/manpki'):\n path = '/usr/local/share/manpki'\n if path:\n from shutil import copyfile\n import platform\n\n copyfile(path+'/config/manpki.conf', get_config_directory()+'/manpki.conf')\n distro = platform.dist()[0]\n distro_major_version = platform.dist()[1].split('.')[0]\n\n if distro == 'Ubuntu':\n copyfile(path + '/startup/upstart/manpkid.conf', '/etc/init/manpkid.conf')\n if distro in ['centos', 'redhat', 'debian', 'fedora']:\n copyfile(path + '/startup/initd/manpkid', '/etc/init.d/manpkid')\n if distro_major_version >= '7' and not distro == 'debian':\n copyfile(path + '/startup/systemd/manpkid.service', '/usr/lib/systemd/system/manpkid.service')\n elif distro_major_version >= '6' and not distro == 'debian':\n copyfile(path + '/startup/upstart/manpkid.conf', '/etc/init/manpkid.conf')\n else:\n config_file = get_config_directory()+'/manpki.conf'\n with open(config_file, 'w') as f:\n f.write(\"[default]\\n\\n\")\n f.write(\"[server]\\n\")\n f.write(\"host = socket\\n\")\n f.write(\"cert = \\n\")\n f.write(\"port = 0\\n\")\n f.write(\"key = \\n\\n\")\n f.close()\n\n\ndef setup():\n init_directory()\n init_db()\n if os.geteuid() == 0:\n init_acl()\n init_files()\n\n\ndef check_candidate(path, directory=None):\n \"\"\"Auxilliary function that checks whether a particular\n path is a good candidate.\n\n \"\"\"\n path_candidate = os.path.join(path, 'share', 'manpki')\n if directory is not None:\n path_candidate = os.path.join(path_candidate, directory)\n try:\n if stat.S_ISDIR(os.stat(path_candidate).st_mode):\n return path_candidate\n except OSError:\n pass\n\n\ndef guess_prefix(directory=None):\n \"\"\"Attempts to find the base directory where ManPKI components are\n installed.\n\n \"\"\"\n\n if __file__.startswith('/'):\n path = '/'\n # absolute path\n for elt in __file__.split('/')[1:]:\n if elt in ['lib', 'lib32', 'lib64']:\n candidate = check_candidate(path, directory=directory)\n if candidate is not None:\n return candidate\n path = os.path.join(path, elt)\n for path in ['/usr', '/usr/local', '/opt', '/opt/manpki']:\n candidate = check_candidate(path, directory=directory)\n if candidate is not None:\n return candidate\n\n\ndef write():\n from manpki.logger import log\n log.debug(\"Building configuration...\")\n for f_name in get_config_file():\n if DEBUG:\n log.debug(\"Write configuration file : \" + f_name)\n with open(f_name, 'w') as configfile:\n ConfigObject.write(configfile)\n log.debug(\"[OK]\")\n\n\ndef envready():\n import pwd\n import grp\n if DAEMON:\n try:\n pwd.getpwnam('manpki')\n except KeyError:\n return False\n try:\n grp.getgrnam('manpki')\n except KeyError:\n return False\n if not get_var_directory():\n return False\n if not get_run_directory():\n return False\n if not get_config_directory():\n return False\n if not get_config_file():\n return False\n\n if DAEMON and not os.path.isdir('/var/log/manpki'):\n return False\n return True\n\nif not envready():\n setup()\n\n\nclass ManPKIConfig(object):\n vardir = get_var_directory()\n certdir = vardir + \"/cert\"\n dbdir = vardir + \"/db\"\n\nif not ConfigObject:\n ConfigObject = configparser.ConfigParser()\n configRead = False\n for f_name in get_config_file():\n if DEBUG:\n from manpki.logger import log\n log.debug(\"Read configuration file : \" + f_name)\n ConfigObject.read(f_name)\n configRead = True\n if not configRead:\n ConfigObject = None\n\nif not ManPKIObject:\n ManPKIObject = ManPKIConfig()\n if not ManPKIObject.certdir:\n ManPKIObject = None\n","repo_name":"GaetanF/manpki","sub_path":"manpki/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":16926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"11210279832","text":"import requests,os,bs4,win10toast\nfrom win10toast import ToastNotifier\nurl='https://www.cricbuzz.com/cricket-match/live-scores'\nimport time\ntoaster =ToastNotifier()\nwhile(True):\n\ttry:\t\n\t\t\n\t\t\tres=requests.get(url)\n\t\t\tans=bs4.BeautifulSoup(res.text,\"html5lib\")\n\t\t\treq=ans.select('.cb-lv-scrs-col')\n\t\t\treq=req[0].getText()\n\t\t\tprint(req)\n\t\t\t#print(res.text[1:250])\n\t\t\ttoaster.show_toast(str(req))\n\t\t\ttime.sleep(100)\n\texcept ConnectionError:\n\t\ttime.sleep(100)","repo_name":"hemanth-07-11/Learning-Python-Libraries-and-Python-Projects","sub_path":"Beautiful Soap/Scrape Cricbuzz/score_notifier_ind.py","file_name":"score_notifier_ind.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"71974867282","text":"\"\"\"HTTP socket server interface\"\"\"\n\nimport functools\nimport http.server\nimport json\nimport logging\nimport os\nimport socketserver\nimport threading\nimport urllib\n\nfrom google.protobuf.message import Message\n\nfrom forch.utils import proto_json\n\nLOGGER = logging.getLogger('httpserv')\n\n\nclass ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):\n \"\"\"Handle requests in a separate thread.\"\"\"\n\n\nclass RequestHandler(http.server.BaseHTTPRequestHandler):\n \"\"\"Handler for simple http requests\"\"\"\n\n def __init__(self, context, *args, **kwargs):\n self._context = context\n super().__init__(*args, **kwargs)\n\n # pylint: disable=invalid-name\n def do_GET(self):\n \"\"\"Handle a basic http request get method\"\"\"\n url_error = self._check_url()\n if url_error:\n self.send_response(500)\n self.end_headers()\n LOGGER.warning(url_error)\n return\n self.send_response(200)\n self.end_headers()\n parsed = urllib.parse.urlparse(self.path)\n opts = {}\n opt_pairs = urllib.parse.parse_qsl(parsed.query)\n for pair in opt_pairs:\n opts[pair[0]] = pair[1]\n message = str(self._context.get_data(self.headers.get('Host'), parsed.path[1:], opts))\n self.wfile.write(message.encode())\n\n def _check_url(self):\n \"\"\"Check if url is illegal\"\"\"\n if not self.headers.get('Host'):\n return f'Host is empty. Path: {self.path}'\n if not self.path:\n return f'Path is empty'\n if '..' in self.path:\n print(self.path)\n return f'Path contains directory traversal notations: {self.path}'\n return None\n\n\nclass HttpServer():\n \"\"\"Simple http server for managing simple requests\"\"\"\n\n _DEFAULT_FILE = 'index.html'\n\n def __init__(self, config, port):\n self._config = config\n self._paths = {}\n self._server = None\n self._root_path = config.get('http_root', 'public')\n self._port = port\n self._host = '0.0.0.0'\n self._thread = None\n\n def start_server(self):\n \"\"\"Start serving thread\"\"\"\n LOGGER.info('Starting http server on %s', self._get_url_base())\n address = (self._host, self._port)\n handler = functools.partial(RequestHandler, self)\n self._server = ThreadedHTTPServer(address, handler)\n\n self._thread = threading.Thread(target=self._server.serve_forever)\n self._thread.deamon = False\n self._thread.start()\n\n def join_thread(self):\n \"\"\"Join http server thread\"\"\"\n self._thread.join()\n\n def _get_url_base(self):\n return 'http://%s:%s' % (self._host, self._port)\n\n def stop_server(self):\n \"\"\"Stop and clean up server\"\"\"\n LOGGER.info(\"Stopping server.\")\n self._server.server_close()\n self._server.shutdown()\n\n def map_request(self, path, target):\n \"\"\"Register a request mapping\"\"\"\n self._paths[path] = target\n\n def get_data(self, host, path, params):\n \"\"\"Get data for a particular request path and query params\"\"\"\n try:\n for a_path in self._paths:\n if path.startswith(a_path):\n full_path = host + '/' + path\n result = self._paths[a_path](full_path, params)\n if isinstance(result, (bytes, str)):\n return result\n if isinstance(result, Message):\n return proto_json(result)\n return json.dumps(result)\n return str(self._paths)\n except Exception as e:\n LOGGER.exception('Handling request %s: %s', path, str(e))\n\n def read_file(self, full_path):\n \"\"\"Read a file and return the entire contents\"\"\"\n binary = full_path.endswith('.ico')\n mode = 'rb' if binary else 'r'\n with open(full_path, mode) as in_file:\n return in_file.read()\n\n def _split_request(self, base_path, req_path):\n slash = req_path.find('/') + 1\n path = req_path[slash:]\n full_path = os.path.join(self._root_path, path)\n if os.path.isdir(full_path):\n full_path = os.path.join(full_path, self._DEFAULT_FILE)\n return self.read_file(full_path)\n\n def static_file(self, base_path):\n \"\"\"Map a static file handler to a simple request\"\"\"\n return lambda req_path, params: self._split_request(base_path, req_path)\n","repo_name":"grafnu/forch_orig","sub_path":"forch/http_server.py","file_name":"http_server.py","file_ext":"py","file_size_in_byte":4468,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"19547006785","text":"import singer\n\nfrom .helpers.constants import DEFAULT_PAGE_SIZE\nfrom .helpers import get_selected_streams, should_sync_stream, update_currently_syncing\nfrom .helpers.datetime_utils import get_timezone_info\nfrom .helpers.generator_processor_pairs import get_generator_processor_for_stream, get_stream_subtypes\nfrom .helpers.multithreaded_requests import MultithreadedRequestsPool\nfrom .helpers.perf_metrics import PerformanceMetrics\n\nLOGGER = singer.get_logger()\n\n\ndef sync_endpoint(client, catalog, state,\n stream_name, sub_type, config, parent_id=None):\n generator_classes, processor_class = get_generator_processor_for_stream(stream_name)\n generators = [generator_class(stream_name=stream_name,\n client=client,\n config=config,\n state=state,\n sub_type=sub_type,\n **({} if parent_id is None else {\"parent_id\": parent_id}))\n for generator_class in generator_classes]\n processor = processor_class(catalog=catalog,\n stream_name=stream_name,\n client=client,\n config=config,\n state=state,\n sub_type=sub_type,\n generators=generators,\n **({} if parent_id is None else {\"parent_id\": parent_id}))\n\n return processor.process_streams_from_generators()\n\n\ndef sync_all_streams(client, config, catalog, state):\n from .tap_generators.child_generator import ChildGenerator\n from .tap_processors.child_processor import ChildProcessor\n\n get_timezone_info(client)\n\n PerformanceMetrics.set_generator_batch_size(int(config.get(\"page_size\", DEFAULT_PAGE_SIZE)))\n \n selected_streams = get_selected_streams(catalog)\n LOGGER.info('selected_streams: {}'.format(selected_streams))\n\n if not selected_streams:\n return\n\n # last_stream = Previous currently synced stream, if the load was interrupted\n last_stream = singer.get_currently_syncing(state)\n LOGGER.info('last/currently syncing stream: {}'.format(last_stream))\n\n # Start syncing from last/currently syncing stream\n if last_stream in selected_streams:\n selected_streams = selected_streams[selected_streams.index(last_stream):] +\\\n selected_streams[:selected_streams.index(last_stream)]\n\n # For each endpoint (above), determine if the stream should be streamed\n # (based on the catalog and last_stream), then sync those streams.\n for stream_name in selected_streams:\n # Check if stream is child stream (and ignore it)\n generators, processor = get_generator_processor_for_stream(stream_name)\n if any([issubclass(generator, ChildGenerator) for generator in generators]) or \\\n issubclass(processor, ChildProcessor):\n continue\n\n should_stream, last_stream = should_sync_stream(selected_streams,\n last_stream,\n stream_name)\n\n if should_stream:\n # loop through each sub type\n sub_types = get_stream_subtypes(stream_name)\n for sub_type in sub_types:\n LOGGER.info('START Syncing: {}, Type: {}'.format(stream_name, sub_type))\n\n update_currently_syncing(state, stream_name)\n PerformanceMetrics.reset_metrics()\n total_records = sync_endpoint(\n client=client,\n catalog=catalog,\n state=state,\n stream_name=stream_name,\n sub_type=sub_type,\n config=config\n )\n\n update_currently_syncing(state, None)\n LOGGER.info('Synced: {}, total_records: {}'.format(\n stream_name,\n total_records))\n LOGGER.info('FINISHED Syncing: {}'.format(stream_name))\n\n statistics = PerformanceMetrics.get_statistics()\n\n if statistics['generator'] and statistics['generator_98th']:\n LOGGER.info(f\"Average Generator Records/s: {round(1/statistics['generator'])} \"\n f\"[98th percentile: {round(1/statistics['generator_98th'])}]\")\n\n if statistics['processor'] and statistics['processor_98th']:\n LOGGER.info(f\"Average Processor Records/s: {round(1/statistics['processor'])} \"\n f\"[98th percentile: {round(1/statistics['processor_98th'])}]\")\n\n LOGGER.info(f\"Total Generator Wait (s): {round(statistics['generator_wait'], 1)} \")\n\n LOGGER.info(f\"Total Processor Wait (s): {round(statistics['processor_wait'], 1)} \")\n\n LOGGER.info(f\"Average Records/s: {statistics['records']}\")\n LOGGER.info(f\"Total Duration: {statistics['extraction']}\")\n\n MultithreadedRequestsPool.shutdown()\n","repo_name":"singer-io/tap-mambu","sub_path":"tap_mambu/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"3"}
+{"seq_id":"21168331494","text":"# encoding: utf-8\n\n\"\"\"\nCreated on 2014.05.26\n\n@author: Allen\n\"\"\"\nfrom importlib import import_module\n\nfrom startpro.core.topcmd import TopCommand\nfrom startpro.core.utils.opts import load_script_temp, get_exec_func\n\noptions = {\"-full\": \"if need full path name of script\"}\n\n\nclass Command(TopCommand):\n \"\"\"\n classdocs\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n\n def run(self, **kwargs):\n # str(sys.argv[2])\n if \"script_name\" not in kwargs:\n print('[WARN]:need start script name.')\n return\n script_name = kwargs[\"script_name\"]\n scripts = load_script_temp()\n if not scripts:\n print('[INFO]:please execute command [startpro list] first')\n return\n try:\n if script_name.isdigit() and script_name not in scripts:\n script_name = scripts.keys()[int(script_name)]\n if script_name not in scripts:\n raise RuntimeError('Unsupported script')\n except Exception:\n print('[ERROR]:Unsupported script.')\n return\n script = scripts[script_name]\n mod = import_module(script['path'])\n func = get_exec_func(mod=mod, name=script_name, is_class=script['is_class'])\n func(**kwargs)\n\n def help(self, **kwargvs):\n print('Start a program.')\n print('')\n print(\"Available options:\")\n for name, desc in sorted(options.items()):\n print(\" %-13s %s\" % (name, desc))\n","repo_name":"zoe0316/startpro","sub_path":"startpro/core/commands/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"}
+{"seq_id":"40827034576","text":"import re\nimport numpy as np\nfrom aiida.orm import Str, Dict, Int, Float\nfrom aiida.common.datastructures import CalcInfo, CodeInfo\nfrom aiida.common.folders import Folder\nfrom aiida.engine import CalcJob\nfrom aiida.parsers.parser import Parser\nfrom aiida.plugins import DataFactory\n\n\nfrom alamode.analyze_phonons import print_thermal_conductivity_with_boundary\nfrom alamode.analyze_phonons import print_temperature_dep_lifetime\nfrom alamode.analyze_phonons import print_lifetime_at_given_temperature\nfrom alamode.analyze_phonons import print_cumulative_thermal_conductivity\n\n\nimport os\n\n\nSinglefileData = DataFactory('singlefile')\nArrayData = DataFactory(\"array\")\n\n\nclass analzePhononOptions(object):\n def __init__(self, calc: str, **kwargs):\n self.options = {'temp': None, 'mode': None, 'kpoint': None,\n 'calc': calc, 'isotope': None, 'average_gamma': True,\n 'size': None, 'length': None, 'direction': None}\n\n for label, value in kwargs.items():\n self.options[label] = value\n\n if calc == \"kappa_boundary\":\n if self.options[\"size\"] is None:\n raise ValueError(f\"size is necessary for calc={calc}\")\n\n elif calc == \"temp\":\n if self.options[\"temp\"] is None:\n raise ValueError(f\"temp is necessary for calc={calc}\")\n\n elif calc == \"cumulative \":\n if self.options[\"temp\"] is None:\n raise ValueError(f\"temp is necessary for calc={calc}\")\n if self.options[\"length\"] is None:\n raise ValueError(f\"length is necessary for calc={calc}\")\n\n def __getattr__(self, name):\n return self.__dict__[\"options\"][name]\n\n\n_OUTPUT_FILENAME_DEFAULT = \"None\"\n\n\nclass analyze_phonon_CalcJob(CalcJob):\n _PARAM_DEFAULT = {}\n\n @classmethod\n def define(cls, spec):\n super().define(spec)\n spec.input(\"cwd\", valid_type=Str)\n #spec.input(\"norder\", valid_type=Int)\n spec.input(\"prefix\", valid_type=Str)\n spec.input(\"calc\", valid_type=Str)\n #spec.input(\"size\", valid_type=Float)\n #spec.input(\"temp\", valid_type=Float)\n spec.input(\"file_result\", valid_type=(Str, SinglefileData))\n spec.input(\"param\", valid_type=Dict,\n default=lambda: Dict(dict=cls._PARAM_DEFAULT))\n spec.input(\"output_filename\", valid_type=Str,\n default=lambda: Str(_OUTPUT_FILENAME_DEFAULT))\n\n spec.inputs['metadata']['options']['parser_name'].default = 'alamode.analyze_phonon'\n spec.inputs['metadata']['options']['input_filename'].default = 'analyze_phonon.in'\n spec.inputs['metadata']['options']['output_filename'].default = 'analyze_phonon.out'\n spec.inputs['metadata']['options']['resources'].default = {\n 'num_machines': 1, 'num_mpiprocs_per_machine': 1}\n\n spec.output('result', valid_type=Dict)\n spec.output('kappa_boundary_file', valid_type=SinglefileData)\n spec.output('kappa', valid_type=ArrayData)\n spec.output('tau_file', valid_type=SinglefileData)\n spec.output('tau', valid_type=ArrayData)\n spec.output('cumulative_file', valid_type=SinglefileData)\n spec.output('cumulative', valid_type=ArrayData)\n\n def prepare_for_submission(self, folder: Folder) -> CalcInfo:\n calc_value = self.inputs.calc.value\n cwd = self.inputs.cwd.value\n print(\"cwd\", cwd)\n\n if calc_value == \"kappa_boundary\":\n result_filename = self.inputs.file_result.list_object_names()[0]\n folder.insert_path(os.path.join(cwd, result_filename),\n dest_name=result_filename)\n\n param = analzePhononOptions(\n calc_value, **self.inputs.param.get_dict())\n cmdline = print_thermal_conductivity_with_boundary(None, calc_value,\n result_filename,\n param, return_cmd=True)\n\n # code\n codeinfo = CodeInfo()\n codeinfo.code_uuid = self.inputs.code.uuid\n codeinfo.cmdline_params = cmdline\n codeinfo.stdout_name = self.options.output_filename\n codeinfo.withmpi = self.options.withmpi\n\n calcinfo = CalcInfo()\n calcinfo.codes_info = [codeinfo]\n\n # add files to retrieve list\n retrieve_list = [self.options.output_filename]\n calcinfo.retrieve_list = retrieve_list\n\n return calcinfo\n\n elif calc_value == \"tau\":\n result_filename = self.inputs.file_result.list_object_names()[0]\n folder.insert_path(os.path.join(cwd, result_filename),\n dest_name=result_filename)\n\n param = analzePhononOptions(\n calc_value, **self.inputs.param.get_dict())\n\n if param.temp is None:\n cmdline = print_temperature_dep_lifetime(None, calc_value,\n result_filename,\n param, return_cmd=True)\n else:\n cmdline = print_lifetime_at_given_temperature(None, calc_value,\n result_filename, \n param, return_cmd=True)\n\n # code\n codeinfo = CodeInfo()\n codeinfo.code_uuid = self.inputs.code.uuid\n codeinfo.cmdline_params = cmdline\n codeinfo.stdout_name = self.options.output_filename\n codeinfo.withmpi = self.options.withmpi\n\n calcinfo = CalcInfo()\n calcinfo.codes_info = [codeinfo]\n\n # add files to retrieve list\n retrieve_list = [self.options.output_filename]\n calcinfo.retrieve_list = retrieve_list\n\n return calcinfo\n\n elif calc_value == \"cumulative\":\n result_filename = self.inputs.file_result.list_object_names()[0]\n folder.insert_path(os.path.join(cwd, result_filename),\n dest_name=result_filename)\n\n param = analzePhononOptions(\n calc_value, **self.inputs.param.get_dict())\n\n print(\"param\",param)\n cmdline = print_cumulative_thermal_conductivity(None, calc_value,\n result_filename,\n param, return_cmd=True)\n print(\"cmdline\", cmdline)\n # code\n codeinfo = CodeInfo()\n codeinfo.code_uuid = self.inputs.code.uuid\n codeinfo.cmdline_params = cmdline\n codeinfo.stdout_name = self.options.output_filename\n codeinfo.withmpi = self.options.withmpi\n\n calcinfo = CalcInfo()\n calcinfo.codes_info = [codeinfo]\n\n # add files to retrieve list\n retrieve_list = [self.options.output_filename]\n calcinfo.retrieve_list = retrieve_list\n\n return calcinfo\n else:\n raise ValueError(f\"unknown calc={calc_value}.\")\n\ndef _parse_analyze_phonon_kappa_boundary(handle):\n data = handle.read().splitlines()\n\n for line in data:\n if line.startswith(\"# Size of boundary\"):\n s = line.split()\n size = \" \".join(s[-2:-1])\n\n for _i, line in enumerate(data):\n if line.startswith(\" \"):\n data_start = _i\n break\n lastline = line\n header = lastline\n\n v = re.split(\"[,()]+\", header[1:])\n v2 = []\n for _x in v:\n _x = _x.strip()\n if len(_x) > 0:\n v2.append(_x)\n header = v2\n\n varname_unit = header[1]\n del header[1]\n varname_unit = varname_unit.split()\n\n unit = varname_unit[-1]\n varname = varname_unit[0]\n\n varlist = []\n for _x in header[1:]:\n varlist.append(f\"{varname}_{_x} {unit}\")\n header = [header[0]]\n header.extend(varlist)\n\n values = []\n for line in data[data_start:]:\n line = line.strip()\n s = re.split(\" +\", line)\n v = list(map(float, s))\n values.append(v)\n\n return size, header, values\n\n\ndef _parse_analyze_phonon_tau_at_temperature(handler):\n data = handler.read().splitlines()\n print(data)\n for _i, line in enumerate(data):\n if line.startswith(\"# Phonon lifetime at temperature\"):\n s = line.replace(\".\", \"\").split()\n temp = \" \".join(s[-2:])\n print(temp)\n elif line.startswith(\"# kpoint range\"):\n s = line.replace(\".\", \"\").split()\n kpoint_range = s[-2:]\n elif line.startswith(\"# mode range\"):\n s = line.replace(\".\", \"\").split()\n mode_range = s[-2:]\n if line.startswith(\" \"):\n data_start = _i\n break\n lastline = line\n\n header = lastline[1:].strip()\n splitted_header = re.split(\", *\", header)\n unit = splitted_header[-1].split(\" \")[-1]\n for _i, _x in enumerate(splitted_header):\n if _x == 'Thermal conductivity par mode (xx':\n varname = _x\n break\n splitted_header = splitted_header[:_i]\n\n varname = varname.split(\"(\")[0].strip()\n for ax in [\"xx\", \"xy\", \"xz\", \"yx\", \"yy\", \"yz\", \"zx\", \"zy\", \"zz\"]:\n splitted_header.append(f\"{varname} {ax} {unit}\")\n\n values = []\n for _x in data[data_start:]:\n _xx = re.split(\" +\", _x.strip())\n values.append(list(map(float,_xx)))\n\n result = {'temp': temp, 'kpoint': kpoint_range, 'mode_range': mode_range}\n return result, splitted_header, values\n\ndef _parse_analyze_phonon_cumulative(handler):\n data = handler.read().splitlines()\n print(data)\n for _i, line in enumerate(data):\n if line.startswith(\"# Cumulative thermal conductivity at temperature\"):\n s = line.replace(\".\", \"\").split()\n temp = \" \".join(s[-2:])\n print(temp)\n elif line.startswith(\"# mode range\"):\n s = line.replace(\".\", \"\").split()\n mode_range = s[-2:]\n if line.startswith(\" \"):\n data_start = _i\n break\n lastline = line\n\n header = lastline[1:].strip()\n splitted_header = re.split(\", *\", header)\n for _i, _x in enumerate(splitted_header):\n if _x == 'kappa [W/mK] (xx':\n varname = _x\n break\n splitted_header = splitted_header[:_i]\n print(splitted_header)\n\n varname_unit = varname.split()\n varname = varname_unit[0].strip()\n unit = varname_unit[1].strip()\n for ax in [\"xx\", \"xy\", \"xz\", \"yx\", \"yy\", \"yz\", \"zx\", \"zy\", \"zz\"]:\n splitted_header.append(f\"{varname} {ax} {unit}\")\n\n values = []\n for _x in data[data_start:]:\n _xx = re.split(\" +\", _x.strip())\n values.append(list(map(float,_xx)))\n\n result = {'temp': temp, 'mode_range': mode_range}\n return result, splitted_header, values\n\nclass analyze_phonon_ParseJob(Parser):\n\n def parse(self, **kwargs):\n print(\"parse start\")\n calc = self.node.inputs.calc.value\n cwd = self.node.inputs.cwd.value\n prefix = self.node.inputs.prefix.value\n if calc == \"kappa_boundary\":\n try:\n output_folder = self.retrieved\n except:\n return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER\n\n try:\n with output_folder.open(self.node.get_option('output_filename'), 'r') as handle:\n size, header, values = _parse_analyze_phonon_kappa_boundary(\n handle)\n except OSError:\n return self.exit_codes.ERROR_READING_OUTPUT_FILE\n except ValueError:\n return self.exit_codes.ERROR_INVALID_OUTPUT\n\n print(\"output_folder\", output_folder.list_object_names())\n\n filename = self.node.get_option('output_filename')\n _content = output_folder.get_object_content(filename)\n if self.node.inputs.output_filename.value == _OUTPUT_FILENAME_DEFAULT:\n filename = f\"{prefix}_analyze_phonon_{calc}.dat\"\n else:\n filename = self.node.inputs.output_filename.value\n target_path = os.path.join(cwd, filename)\n with open(target_path, \"w\") as f:\n f.write(_content)\n self.out('kappa_boundary_file', SinglefileData(target_path))\n\n kappa = ArrayData()\n kappa.set_array('values', np.array(values).astype(float))\n kappa.set_array('columns', np.array(header))\n self.out(\"kappa\", kappa)\n\n self.out('result', Dict(dict={\"size\": size}))\n\n elif calc == \"tau\":\n try:\n output_folder = self.retrieved\n except:\n return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER\n\n try:\n with output_folder.open(self.node.get_option('output_filename'), 'r') as handle:\n result, header, values = _parse_analyze_phonon_tau_at_temperature(handle)\n except OSError:\n return self.exit_codes.ERROR_READING_OUTPUT_FILE\n except ValueError:\n return self.exit_codes.ERROR_INVALID_OUTPUT\n\n print(\"output_folder\", output_folder.list_object_names())\n\n filename = self.node.get_option('output_filename')\n _content = output_folder.get_object_content(filename)\n if self.node.inputs.output_filename.value == _OUTPUT_FILENAME_DEFAULT:\n filename = f\"{prefix}_analyze_phonon_{calc}.dat\"\n else:\n filename = self.node.inputs.output_filename.value\n\n target_path = os.path.join(cwd, filename)\n with open(target_path, \"w\") as f:\n f.write(_content)\n self.out('tau_file', SinglefileData(target_path))\n\n kappa = ArrayData()\n kappa.set_array('values', np.array(values).astype(float))\n kappa.set_array('columns', np.array(header))\n self.out(\"tau\", kappa)\n\n self.out('result', Dict(dict=result))\n\n elif calc == \"cumulative\":\n try:\n output_folder = self.retrieved\n except:\n return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER\n\n try:\n with output_folder.open(self.node.get_option('output_filename'), 'r') as handle:\n result, header, values = _parse_analyze_phonon_cumulative(handle)\n except OSError:\n return self.exit_codes.ERROR_READING_OUTPUT_FILE\n except ValueError:\n return self.exit_codes.ERROR_INVALID_OUTPUT\n\n print(\"output_folder\", output_folder.list_object_names())\n\n filename = self.node.get_option('output_filename')\n _content = output_folder.get_object_content(filename)\n if self.node.inputs.output_filename.value == _OUTPUT_FILENAME_DEFAULT:\n filename = f\"{prefix}_analyze_phonon_{calc}.dat\"\n else:\n filename = self.node.inputs.output_filename.value\n\n target_path = os.path.join(cwd, filename)\n with open(target_path, \"w\") as f:\n f.write(_content)\n self.out('cumulative_file', SinglefileData(target_path))\n\n kappa = ArrayData()\n kappa.set_array('values', np.array(values).astype(float))\n kappa.set_array('columns', np.array(header))\n self.out(\"cumulative\", kappa)\n\n self.out('result', Dict(dict=result))\n\n","repo_name":"nim-hrkn/aiida-alamode","sub_path":"alamode-aiida/alamode_aiida/analyze_calcjob.py","file_name":"analyze_calcjob.py","file_ext":"py","file_size_in_byte":15611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"16251729793","text":"import mogp_emulator\nimport numpy as np\nfrom projectile import simulator, print_results\n\n# simple MICE examples using the projectile demo\n\n# Base design -- requires a list of parameter bounds if you would like to use\n# uniform distributions. If you want to use different distributions, you\n# can use any of the standard distributions available in scipy to create\n# the appropriate ppf function (the inverse of the cumulative distribution).\n# Internally, the code creates the design on the unit hypercube and then uses\n# the distribution to map from [0,1] to the real parameter space.\n\nlhd = mogp_emulator.LatinHypercubeDesign([(-5., 1.), (0., 1000.)])\n\n###################################################################################\n\n# first example -- run entire design internally within the MICE class.\n\n# first argument is base design (required), second is simulator function (optional,\n# but required if you want the code to run the simualtions internally)\n\n# Other optional arguments include:\n# n_samples (number of sequential design steps, optional, default is not specified\n# meaning that you will specify when running the sequential design)\n# n_init (size of initial design, default 10)\n# n_cand (number of candidate points, default is 50)\n# nugget (nugget parameter for design GP, default is to set adaptively)\n# nugget_s (nugget parameter for candidate GP, default is 1.)\n\nn_init = 5\nn_samples = 20\nn_cand = 100\n\nmd = mogp_emulator.MICEDesign(lhd, simulator, n_samples=n_samples, n_init=n_init, n_cand=n_cand)\n\nmd.run_sequential_design()\n\n# get design and outputs\n\ninputs = md.get_inputs()\ntargets = md.get_targets()\n\nprint(\"Example 1:\")\nprint(\"Design inputs:\\n\", inputs)\nprint(\"Design targets:\\n\", targets)\nprint()\n\n###################################################################################\n\n# second example: run design manually\n\nmd2 = mogp_emulator.MICEDesign(lhd, n_init=n_init, n_cand=n_cand)\n\ninit_design = md2.generate_initial_design()\n\nprint(\"Example 2:\")\nprint(\"Initial design:\\n\", init_design)\n\n# run initial points manually\n\ninit_targets = np.array([simulator(s) for s in init_design])\n\n# set initial targets\n\nmd2.set_initial_targets(init_targets)\n\n# run 20 sequential design steps\n\nfor d in range(n_samples):\n next_point = md2.get_next_point()\n next_target = simulator(next_point)\n md2.set_next_target(next_target)\n\n# look at design and outputs\n\ninputs = md2.get_inputs()\ntargets = md2.get_targets()\n\nprint(\"Final inputs:\\n\", inputs)\nprint(\"Final targets:\\n\", targets)\n\n# look at final GP emulator and make some predictions to compare with lhd\n\nlhd_design = lhd.sample(n_init + n_samples)\n\ngp_lhd = mogp_emulator.fit_GP_MAP(lhd_design, np.array([simulator(p) for p in lhd_design]))\n\ngp_mice = mogp_emulator.GaussianProcess(inputs, targets)\n\ngp_mice = mogp_emulator.fit_GP_MAP(inputs, targets)\n\ntest_points = lhd.sample(10)\n\nprint(\"LHD:\")\nprint_results(test_points, gp_lhd(test_points))\nprint()\nprint(\"MICE:\")\nprint_results(test_points, gp_mice(test_points))","repo_name":"alan-turing-institute/mogp-emulator","sub_path":"mogp_emulator/demos/mice_demos.py","file_name":"mice_demos.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"3"}
+{"seq_id":"12419507372","text":"from code.base_class.dataset import dataset\n\n\nclass Voc_Loader(dataset):\n #print([])\n data = None\n dataset_source_folder_path = None\n dataset_source_file_name = None\n setType= None\n\n vocnum=0\n transferl={'!':1,':':2,',':3,'.':4,'\\'s':5,'1':6,'...':7,'\\\"':8,'(':9,')':10}\n def __init__(self, dName=None, dDescription=None):\n super().__init__(dName, dDescription)\n self.setType=None\n\n def transfer(self,word):\n return self.vocnum+self.transferl[word]\n\n def add(self,res,word):\n #print(word)\n if word.isnumeric():\n res.append(self.transfer('1'))\n elif word == '':\n res.append(-1)\n\n elif word[0]=='\\\"':\n res.append(self.transfer('\\\"'))\n if len(word) > 1:\n self.add(res,word[1:])\n\n elif word[-1]=='\\\"':\n if len(word) > 1:\n self.add(res,word[:-1])\n res.append(self.transfer('\\\"'))\n\n elif word[0]=='(':\n res.append(self.transfer('('))\n if len(word) > 1:\n self.add(res,word[1:])\n\n elif word[-1]==')':\n if len(word) > 1:\n self.add(res,word[:-1])\n res.append(self.transfer(')'))\n elif word[-2:] == \"'s\":\n\n if len(word) > 2:\n self.add(res,word[:-2])\n res.append(self.transfer('\\'s'))\n\n elif word[-1:] == \"'\":\n if len(word) > 1:\n self.add(res,word[:-1])\n res.append(self.transfer('\\'s'))\n\n elif word[-1] == ':':\n if len(word) > 1:\n self.add(res,word[:-1])\n res.append(self.transfer(':'))\n\n elif word[-1] == '!':\n if len(word) > 1:\n self.add(res,word[:-1])\n res.append(self.transfer('!'))\n\n elif word[-3:]=='n\\'t':\n if len(word) > 3:\n self.add(res,word[:-3])\n res=self.add(res,'not')\n\n elif word[-3:]=='...':\n if len(word) > 3:\n self.add(res,word[:-3])\n res.append(self.transfer('...'))\n\n elif word[-1]=='.':\n if len(word) > 1:\n self.add(res,word[:-1])\n res.append(self.transfer('.'))\n\n elif word[-1]==',':\n if len(word) > 1:\n self.add(res,word[:-1])\n res.append(self.transfer(','))\n\n else:\n if word!= '':\n tmp=word.lower()\n self.voc.setdefault(tmp,-2)\n if self.voc[tmp]!=-2:\n res.append(self.voc[tmp])\n # print(res)\n\n def tok(self,raw):\n\n res=[]\n for word in str.split(str(raw, encoding = \"utf8\"),' '):\n self.add(res,word)\n\n return res\n\n def load(self):\n print('loading Voc...ff')\n\n vocpath=self.dataset_source_folder_path+self.dataset_source_file_name+'/'+ 'imdb.vocab'\n\n\n\n with open(vocpath, 'rb') as f:\n keys=f.readlines()\n self.vocnum=len(keys)\n #print(keys)\n for i,s in enumerate(keys):\n #print(str(s,encoding = \"utf8\").strip('\\n'))\n keys[i]=(str(s,encoding = \"utf8\").strip('\\n'))\n\n self.voc = dict(zip(keys, range(0, len(keys))))\n\n\n\n\n return self.voc","repo_name":"rjsun06/ecs189g","sub_path":"code/stage_4_code/Voc_Loader.py","file_name":"Voc_Loader.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10511662537","text":"#!/home/oceanw/anaconda3/bin/python3\nimport numpy as np\nfrom PIL import Image\n\ndef save_1_second(snippet):\n\t#expected input is frame = [[[[]*color]*xdim]*ydim]*fps\n\tfor i in range (0,1):\t#Saving only 1 frame here:\n\t\t#Here the intermediate frame evolves from a single, ordered frame, into a single linear frame.\n\t\tintermediate_frame = snippet[0]\n\t\tintermediate_frame = np.reshape(intermediate_frame, (num_pix, color))\n\t\t#linear frame is the tuple version of intermediate frame\n\t\tlinear_frame = tuple(map(tuple, intermediate_frame))\n\t\t\n\t\tstill = Image.new('RGB', (xdim,ydim))\n\t\tstill.putdata(linear_frame)\n\t\tstill.save('still_s=2'+str(i)+'.jpg', 'JPEG')\n#Decommissioned subprograms\n\ndef checkshape( a , Shape ):\n\tif np.shape(a)==Shape: return\n\telse: raise ValueError\n\ndef save_mono_frame(monoframe):\n\tcheckshape(monoframe, [1280,720])\n\t#*img = Image.load(monoframe)\n\timg.save(monoframe , color = 'greyscae')\n\treturn\n'''\n\ndef meanInd(vertical_column): #can also be applied on horizontal_rows\n\tindices = np.arange(len(vertical_column)) #expect a boolean input, and here's their indices.\n\tmean = (np.sum (indices*vertical_column) / np.sum(vertical_column) ) #Sum/weight-factor\n\t#*mean = np.nonzero( \n\treturn mean\n\ndef numLines(vertical_column):\n\treturn np.sum( np.abs( np.diff(vertical_column) ) )/2\n\nclass existFlag:\n\tred, green, blue, yellow, white = True, True, True, True, True\n'''\n","repo_name":"OceanNuclear/Python_projects","sub_path":"Fourier_analyse_video/Debugging.py","file_name":"Debugging.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41289822087","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('picture.jpg', 1)\nimgInfo = img.shape\nheight = imgInfo[0]\nwidth = imgInfo[1]\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\ndst = np.zeros((height, width, 3), np.uint8)\npixel_class = 4\nsection = int(256 / pixel_class)\n# Traverse each data of a picture with a two-tier for loop\nfor i in range(3, height - 3):\n for j in range(3, width - 3):\n # The gray levels defined in the current program are four\n # Define an array to load the number of pixels in these four levels\n array1 = np.zeros(pixel_class, np.uint8)\n # The small box defined in the current program is 6x6\n for m in range(-3, 3):\n for n in range(-3, 3):\n # p1 It divides the level segment of the pixel and represents 0 with subscripts.-3\n p1 = int(gray[i + m, j + n] / section)\n # Next, the pixel level is counted. The subscript of array1 represents the pixel level.\n # The value represents the number of pixels in the small box of the pixel level.\n array1[p1] = array1[p1] + 1\n # Next, determine which segment has the most pixels in the small box.\n currentMax = array1[0]\n l = 0 # Here we set an array subscript l to record the largest number of pixel segments.\n for k in range(0, pixel_class):\n if currentMax < array1[k]:\n currentMax = array1[k]\n l = k\n # Mean Processing\n u = v = w = 0\n for m in range(-3, 3):\n for n in range(-3, 3):\n if gray[i + m, j + n] >= (l * section) and gray[i + m, j + n] <= ((l + 1) * section):\n (b, g, r) = img[i + m, j + n]\n u += b\n v += g\n w += r\n u = int(u / array1[l])\n v = int(v / array1[l])\n w = int(w / array1[l])\n dst[i, j] = [u, v, w]\ncv2.imshow('dst', dst)\ncv2.imshow('img', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"CloudLouis/OpenCV_Image_Filters","sub_path":"oil_painting/oil.py","file_name":"oil.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16318796797","text":"import pandas as pd\r\nimport numpy as np\r\nimport streamlit as st\r\nimport joblib\r\n\r\nst.title(\"항공기 만족도 예측 Practice\")\r\nst.subheader(\"6가지의 머신러닝 모델을 활용하여 변수들을 바꾸어 예측해보기\")\r\n\r\n# 첫 번째 행\r\nr1_col1, r1_col2, r1_col3 = st.columns(3)\r\n\r\nInflight_wifi_service = r1_col1.slider(\"Inflight wifi service\", 0, 5)\r\n\r\nDeparture_Arrival_time_convenient = r1_col2.slider(\"Departure/Arrival time convenient\", 0, 5)\r\n\r\nEase_of_Online_booking = r1_col3.slider(\"Ease of Online booking\", 0,5)\r\n\r\n\r\n# 두번째 행\r\nr2_col1, r2_col2, r2_col3 = st.columns(3)\r\n\r\nGate_location = r2_col1.slider(\"Gate location\",0,5 )\r\nFood_and_drink = r2_col2.slider(\"Food and drink\", 0,5)\r\nOnline_boarding = r2_col3.slider(\"Online boarding\", 0,5)\r\n\r\n# 세번째 행\r\nr3_col1, r3_col2, r3_col3 = st.columns(3)\r\nLeg_room_service=r3_col1.slider(\"Leg room service \",0,5)\r\nBaggage_handling =r3_col2.slider(\"Baggage handling\",0,5)\r\nOn_board_service =r3_col3.slider(\"On-board service\",0,5)\r\n\r\n\r\n# 네 번째 행\r\nr4_col1, r4_col2, r4_col3 = st.columns(3)\r\nSeat_comfort =r4_col1.slider(\"Seat comfort \",0,5)\r\nInflight_entertainment =r4_col2.slider(\"Inflight entertainment\",0,5)\r\nCheck_in_service =r4_col3.slider(\"Check-in service\",0,5)\r\n\r\n# 다섯번째 행\r\nr5_col1, r5_col2 = st.columns(2)\r\nInflight_service =r5_col1.slider(\"Inflight service \",0,5)\r\nCleanliness =r5_col2.slider(\"Cleanliness\",0,5)\r\n\r\n# 여섯번째 행\r\nr6_col1, r6_col2 = st.columns(2)\r\nDeparture_Delay_in_Minutes=r6_col1.slider(\"Departure_Delay_in_Minutes \",0,30)\r\nArrival_Delay_in_Minutes=r6_col2.slider(\"Arrival_Delay_in_Minutes \",0 ,30)\r\n\r\n# 예측 버튼\r\npredict_button1 = st.button(\"로지스틱 회귀 예측\")\r\npredict_button2 = st.button(\"KNN 예측\")\r\npredict_button3 = st.button(\"결정트리 예측\")\r\npredict_button4 = st.button(\"랜덤포레스트 예측\")\r\npredict_button5 = st.button(\"XGBoost 예측\")\r\npredict_button6 = st.button(\"LightGBM 예측\")\r\n\r\nst.write(\"---\")\r\n\r\n# 예측 결과\r\nif predict_button1:\r\n model = joblib.load('LR_model.pkl')\r\n\r\n pred = model.predict(np.array([[Inflight_wifi_service, Departure_Arrival_time_convenient,\r\n Ease_of_Online_booking, Gate_location, Food_and_drink, Online_boarding, Seat_comfort,\r\n Inflight_entertainment, On_board_service, Leg_room_service, Baggage_handling, Check_in_service, Inflight_service, Cleanliness,Departure_Delay_in_Minutes,Arrival_Delay_in_Minutes]]))\r\n \r\n if pred == 1:\r\n st.metric(\"만족 여부 예측 결과\", \"Satisfied\")\r\n else:\r\n st.metric(\"만족 여부 예측 결과\", \"Dissatisfied\")\r\n \r\nif predict_button2:\r\n model = joblib.load('KNN_model.pkl')\r\n\r\n pred = model.predict(np.array([[Inflight_wifi_service, Departure_Arrival_time_convenient,\r\n Ease_of_Online_booking, Gate_location, Food_and_drink, Online_boarding, Seat_comfort,\r\n Inflight_entertainment, On_board_service, Leg_room_service, Baggage_handling, Check_in_service, Inflight_service, Cleanliness,Departure_Delay_in_Minutes,Arrival_Delay_in_Minutes]]))\r\n\r\n if pred == 1:\r\n st.metric(\"만족 여부 예측 결과\", \"Satisfied\")\r\n else:\r\n st.metric(\"만족 여부 예측 결과\", \"Dissatisfied\")\r\n \r\nif predict_button3:\r\n model = joblib.load('DT_model.pkl')\r\n\r\n pred = model.predict(np.array([[Inflight_wifi_service, Departure_Arrival_time_convenient,\r\n Ease_of_Online_booking, Gate_location, Food_and_drink, Online_boarding, Seat_comfort,\r\n Inflight_entertainment, On_board_service, Leg_room_service, Baggage_handling, Check_in_service, Inflight_service, Cleanliness,Departure_Delay_in_Minutes,Arrival_Delay_in_Minutes]]))\r\n\r\n if pred == 1:\r\n st.metric(\"만족 여부 예측 결과\", \"Satisfied\")\r\n else:\r\n st.metric(\"만족 여부 예측 결과\", \"Dissatisfied\")\r\n \r\nif predict_button4:\r\n model = joblib.load('RandomForestClassifier_model.pkl')\r\n\r\n pred = model.predict(np.array([[Inflight_wifi_service, Departure_Arrival_time_convenient,\r\n Ease_of_Online_booking, Gate_location, Food_and_drink, Online_boarding, Seat_comfort,\r\n Inflight_entertainment, On_board_service, Leg_room_service, Baggage_handling, Check_in_service, Inflight_service, Cleanliness,Departure_Delay_in_Minutes,Arrival_Delay_in_Minutes]]))\r\n\r\n if pred == 1:\r\n st.metric(\"만족 여부 예측 결과\", \"Satisfied\")\r\n else:\r\n st.metric(\"만족 여부 예측 결과\", \"Dissatisfied\")\r\n \r\nif predict_button5:\r\n model = joblib.load('xgb_model.pkl')\r\n\r\n pred = model.predict(np.array([[Inflight_wifi_service, Departure_Arrival_time_convenient,\r\n Ease_of_Online_booking, Gate_location, Food_and_drink, Online_boarding, Seat_comfort,\r\n Inflight_entertainment, On_board_service, Leg_room_service, Baggage_handling, Check_in_service, Inflight_service, Cleanliness,Departure_Delay_in_Minutes,Arrival_Delay_in_Minutes]]))\r\n\r\n if pred == 1:\r\n st.metric(\"만족 여부 예측 결과\", \"Satisfied\")\r\n else:\r\n st.metric(\"만족 여부 예측 결과\", \"Dissatisfied\")\r\n \r\nif predict_button6:\r\n model = joblib.load('LightGBM_model.pkl')\r\n\r\n pred = model.predict(np.array([[Inflight_wifi_service, Departure_Arrival_time_convenient,\r\n Ease_of_Online_booking, Gate_location, Food_and_drink, Online_boarding, Seat_comfort,\r\n Inflight_entertainment, On_board_service, Leg_room_service, Baggage_handling, Check_in_service, Inflight_service, Cleanliness,Departure_Delay_in_Minutes,Arrival_Delay_in_Minutes]]))\r\n\r\n if pred == 1:\r\n st.metric(\"만족 여부 예측 결과\", \"Satisfied\")\r\n else:\r\n st.metric(\"만족 여부 예측 결과\", \"Dissatisfied\")\r\n\r\nst.write(\"\") \r\nst.markdown('**Thank You!**', unsafe_allow_html=True)\r\n","repo_name":"Yoo-Ha-young/test_streamlit","sub_path":"streamlit_practice.py","file_name":"streamlit_practice.py","file_ext":"py","file_size_in_byte":5808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19544502227","text":"\"\"\"\nWith the toboggan login problems resolved, you set off toward the airport. While travel by toboggan might be easy, it's certainly not safe: there's very minimal steering and the area is covered in trees. You'll need to see which angles will take you near the fewest trees.\n\nDue to the local geology, trees in this area only grow on exact integer coordinates in a grid. You make a map (your puzzle input) of the open squares (.) and trees (#) you can see. For example:\n\n..##.......\n#...#...#..\n.#....#..#.\n..#.#...#.#\n.#...##..#.\n..#.##.....\n.#.#.#....#\n.#........#\n#.##...#...\n#...##....#\n.#..#...#.#\n\nThese aren't the only trees, though; due to something you read about once involving arboreal genetics and biome stability, the same pattern repeats to the right many times:\n\n..##.........##.........##.........##.........##.........##....... --->\n#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..\n.#....#..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.\n..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#\n.#...##..#..#...##..#..#...##..#..#...##..#..#...##..#..#...##..#.\n..#.##.......#.##.......#.##.......#.##.......#.##.......#.##..... --->\n.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#\n.#........#.#........#.#........#.#........#.#........#.#........#\n#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...\n#...##....##...##....##...##....##...##....##...##....##...##....#\n.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.# --->\n\nYou start on the open square (.) in the top-left corner and need to reach the bottom (below the bottom-most row on your map).\n\nThe toboggan can only follow a few specific slopes (you opted for a cheaper model that prefers rational numbers); start by counting all the trees you would encounter for the slope right 3, down 1:\n\nFrom your starting position at the top-left, check the position that is right 3 and down 1. Then, check the position that is right 3 and down 1 from there, and so on until you go past the bottom of the map.\n\nThe locations you'd check in the above example are marked here with O where there was an open square and X where there was a tree:\n\n..##.........##.........##.........##.........##.........##....... --->\n#..O#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..\n.#....X..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.\n..#.#...#O#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#\n.#...##..#..X...##..#..#...##..#..#...##..#..#...##..#..#...##..#.\n..#.##.......#.X#.......#.##.......#.##.......#.##.......#.##..... --->\n.#.#.#....#.#.#.#.O..#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#\n.#........#.#........X.#........#.#........#.#........#.#........#\n#.##...#...#.##...#...#.X#...#...#.##...#...#.##...#...#.##...#...\n#...##....##...##....##...#X....##...##....##...##....##...##....#\n.#..#...#.#.#..#...#.#.#..#...X.#.#..#...#.#.#..#...#.#.#..#...#.# --->\n\nIn this example, traversing the map using this slope would cause you to encounter 7 trees.\n\nStarting at the top-left corner of your map and following a slope of right 3 and down 1, how many trees would you encounter?\n\nYour puzzle answer was 184.\n\n--- Part Two ---\nTime to check the rest of the slopes - you need to minimize the probability of a sudden arboreal stop, after all.\n\nDetermine the number of trees you would encounter if, for each of the following slopes, you start at the top-left corner and traverse the map all the way to the bottom:\n\n Right 1, down 1.\n Right 3, down 1. (This is the slope you already checked.)\n Right 5, down 1.\n Right 7, down 1.\n Right 1, down 2.\n\nIn the above example, these slopes would find 2, 7, 3, 4, and 2 tree(s) respectively; multiplied together, these produce the answer 336.\n\nWhat do you get if you multiply together the number of trees encountered on each of the listed slopes?\n\nYour puzzle answer was 2431272960.\n\"\"\"\n\nimport os\nimport types\n\n\ndef count_trees() -> int:\n lines: [str] = []\n\n input_file_path: str = os.path.join(os.getcwd(), \"day3\\\\input.txt\")\n with open(input_file_path, \"r\") as input_file:\n for line in input_file.readlines():\n lines.append(line.strip())\n\n right_index = 3\n line_index = 1\n line_length = len(lines[0])\n tree_count = 0\n\n while line_index < len(lines):\n while right_index >= line_length:\n right_index -= line_length\n\n if lines[line_index][right_index] == \"#\":\n tree_count += 1\n\n line_index += 1\n right_index += 3\n\n return tree_count\n\n\ndef count_multiple_trees() -> int:\n lines: [str] = []\n\n input_file_path: str = os.path.join(os.getcwd(), \"day3\\\\input.txt\")\n with open(input_file_path, \"r\") as input_file:\n for line in input_file.readlines():\n lines.append(line.strip())\n\n indices = [[1, 1, 1, 1], [3, 3, 1, 1], [5, 5, 1, 1], [7, 7, 1, 1], [1, 1, 2, 2]]\n tree_counts = [0] * len(indices)\n lines_processed = 0\n line_length = len(lines[0])\n\n while lines_processed < len(lines):\n for i, index_set in enumerate(indices):\n if index_set[2] >= len(lines):\n continue\n\n while index_set[0] >= line_length:\n index_set[0] -= line_length\n\n if lines[index_set[2]][index_set[0]] == \"#\":\n tree_counts[i] += 1\n\n index_set[0] += index_set[1]\n index_set[2] += index_set[3]\n\n lines_processed += 1\n\n product = tree_counts[0]\n for num in tree_counts[1:]:\n product *= num\n\n return product\n\n\nprint(count_trees())\nprint(count_multiple_trees())\n","repo_name":"mosqutip/advent-of-code","sub_path":"2020/day3/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":5634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30853706077","text":"#12/10/2017\n#Author: Ruslan Shakirov\n#FourSquare Check-Ins EDA\n#Will investigate the spatial and temporal aspects of the data provided.\n\nimport pandas as pd\nimport matplotlib as plt\n#For plt.figure(figsize)\nimport matplotlib.pyplot as plt\n#Interactive mode for automatic plotting in idle\nfrom matplotlib import interactive\ninteractive(True)\n\ndef drawNYC():\n \"\"\"\n Function plots 10 most popular Venue Categories in New York.\n \"\"\"\n #Import dataset of New York from root directory\n NYC = pd.read_csv('dataset_TSMC2014_NYC.csv')\n\n NYC=NYC[[\"venueCategory\",\"venueCategoryId\"]]\n grouped=NYC.groupby([\"venueCategory\"]).count()\n grouped=grouped.sort_values('venueCategoryId')\n grouped=grouped[241:251]\n \n #Plot bars of most popular venue categories\n plt.figure(figsize=(16,6))\n plt.style.use('fivethirtyeight')\n plt.bar(grouped.index,grouped[\"venueCategoryId\"])\n plt.title(\"10 Most Popular Venue Categories \\n New York: 2012-2013\",fontsize=14,color='black')\n plt.ylabel(\"Check-ins per Venue Category\",fontsize=14)\n plt.show()\n\ndef drawTKY():\n \"\"\"\n Function plots 10 most popular Venue Categories in Tokyo.\n \"\"\"\n #Import dataset of New York from root directory\n TKY = pd.read_csv('dataset_TSMC2014_TKY.csv')\n\n TKY=TKY[[\"venueCategory\",\"venueCategoryId\"]]\n grouped2=TKY.groupby([\"venueCategory\"]).count()\n grouped2=grouped2.sort_values('venueCategoryId')\n grouped2=grouped2[237:247]\n \n #Plot bars of most popular venue categories\n plt.figure(figsize=(16,6))\n plt.style.use('fivethirtyeight')\n plt.bar(grouped2.index,grouped2[\"venueCategoryId\"])\n plt.title(\"10 Most Popular Venue Categories \\n Tokyo: 2012-2013\",fontsize=14,color='black')\n plt.ylabel(\"Check-ins per Venue Category\",fontsize=14)\n plt.show()\n\ndrawNYC()\ndrawTKY()\n","repo_name":"ruslansco/Foursquare-Data-Analysis","sub_path":"popular_venues_charts.py","file_name":"popular_venues_charts.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"10848824446","text":"import re\nimport string\n\ndef is_valid_name(identifier):\n for letter in identifier:\n #print (letter)\n if(letter not in string.ascii_letters and letter not in string.digits):\n if(letter not in \"_\"):\n return False\n return True\n\ndef parse_pin_assignment(assignment):\n check = True\n port = ''\n if(assignment[0] not in \".\"):\n check = False\n m = re.search(r'([\\w_]+\\()', assignment[1:])\n if(m):\n port = m.groups()[0][:-1]\n if(is_valid_name(port) is not True):\n check = False\n else:\n check = False\n pin = assignment[(2+len(port)):-1]\n #print(pin)\n if(is_valid_name(pin) is not True):\n check = False\n if(check is False):\n raise ValueError(assignment)\n \n return (port, pin)\n\ndef parse_net(line):\n #print(line)\n line = line.split()\n component = line[0]\n instance = line[1]\n if(is_valid_name(component) is False or is_valid_name(instance) is False):\n raise ValueError(line)\n ports = line[3:-1]\n ports[-1] = ports[-1]+','\n #print(ports)\n i = 0\n portpins = []\n #print(ports[0][1:-1])\n for port in ports:\n #if i == 0:\n # portpin = parse_pin_assignment(port[1:-1])\n # portpins.append(portpin)\n # i = 1\n #else:\n portpin = parse_pin_assignment(port[:-1])\n #print(portpin)\n portpins.append(portpin)\n \n return (component, instance, tuple(portpins))\n\n\n\ndef main():\n #print(is_valid_name(\"hypphen\"))\n #print(\"h\" in string.ascii_letters)\n print(parse_pin_assignment('.Dasdf(n31232130)'))\n print(parse_net('DFFSR present_val_reg (.D(n30), .R(n33), .CLK(clk))'))\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"AnthonyKang/ece364","sub_path":"Lab08/vtools.py","file_name":"vtools.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33695575414","text":"# -*- coding: utf-8 -*-\n\nfrom database import db_session, init_db\nfrom atendimentos.models import *\nfrom colaboradores.models import *\nfrom flask import Flask, jsonify, abort, request, make_response, url_for\nfrom flask.views import MethodView\nfrom flask.ext.restful import Api, Resource, reqparse, marshal, marshal_with\nfrom flask.ext.httpauth import HTTPBasicAuth\nfrom sqlalchemy import func\nfrom configuracao import *\nimport json\n\n \napp = Flask(__name__, static_url_path = \"\")\napp.secret_key = chave\napi = Api(app)\nauth = HTTPBasicAuth()\n \n@auth.get_password\ndef get_password(username):\n colaborador = Colaborador.query.filter(func.lower(Colaborador.nome)==func.lower(username), Colaborador.ativo=='SIM').first()\n\n if colaborador:\n return colaborador.senha\n else:\n return None\n \n@auth.error_handler\ndef unauthorized():\n return make_response(jsonify( { 'message': 'Nao autorizado!' } ), 403)\n\n\nclass atendimentos_api(Resource):\n decorators = [auth.login_required]\n\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n super(atendimentos_api, self).__init__()\n \n @marshal_with(atendimento_campos)\n def get(self):\n atendimentos = Atendimento.query.filter(Atendimento.ativo=='SIM')\n return atendimentos.all()\n\n @marshal_with(atendimento_campos)\n def post(self):\n args = self.reqparse.parse_args()\n atendimento = Atendimento()\n\n atendimento.empresa = args['empresa']\n atendimento.pessoa = args['pessoa']\n atendimento.email = args['email']\n atendimento.relato = args['relato']\n atendimento.data_cadastro = args['data_cadastro']\n atendimento.data_atendimento = args['data_atendimento']\n atendimento.observacao = args['observacao']\n atendimento.categoria = args['categoria']\n atendimento.satisfacao = args['satisfacao']\n atendimento.satisfacao_observacao = args['satisfacao_observacao']\n atendimento.retornar = args['retornar']\n atendimento.ativo = args['ativo']\n\n atendimento.post()\n return atendimento\n\n\napi.add_resource(atendimentos_api, '/atendimentos')\n \nif __name__ == '__main__':\n init_db()\n app.run(debug = True)","repo_name":"edsonlb/ccrm-ca","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"167469370","text":"import random\r\nimport time\r\n\r\n\r\nclass RemoteControl():\r\n\r\n def __init__(self, tv_condition=\"Off\", tv_volume=0, channellist=[\"Trt\"], channel=\"Trt\"):\r\n self.tv_condition = tv_condition\r\n self.tv_volume = tv_volume\r\n self.channellist = channellist\r\n self.channel = channel\r\n\r\n def TurnOnTV(self):\r\n if self.tv_condition == \"On\":\r\n print(\"TV is already on\")\r\n else:\r\n print(\"Opening\")\r\n self.tv_condition = \"On\"\r\n\r\n def TurnOffTV(self):\r\n if self.tv_condition == \"Off\":\r\n print(\"TV is already off\")\r\n else:\r\n print(\"Closing\")\r\n self.tv_condition = \"Off\"\r\n\r\n def VolumeSetting(self):\r\n\r\n while True:\r\n answer = input(\"Volume down: '<'\\n Volume up: '>'\\n Exit: exit \")\r\n\r\n if answer == \"<\":\r\n if self.tv_volume != 0:\r\n self.tv_volume -= 1\r\n print(self.tv_volume)\r\n elif answer == \">\":\r\n if self.tv_volume != 31:\r\n self.tv_volume += 1\r\n print(\"Volume:\", self.tv_volume)\r\n\r\n else:\r\n print(\"Volume is updated:\", self.tv_volume)\r\n break\r\n\r\n def AddChannel(self, channel_name):\r\n print(\"Channel is adding..\")\r\n time.sleep(1)\r\n self.channellist.append(channel_name)\r\n\r\n def RandomChannel(self):\r\n channel_random = random.randint(0, len(self.channellist) - 1)\r\n self.channel = self.channellist[channel_random]\r\n print(\"Channel on TV:\", self.channel)\r\n\r\n def __len__(self):\r\n return len(self.channellist)\r\n\r\n def __str__(self):\r\n return \"TV Condition: {}\\nTV Volume: {}\\nChannel: {}\\nChannel List:{}\".format(self.tv_condition, self.tv_volume, self.channel,self.channellist)\r\n\r\n\r\ncontroller = RemoteControl()\r\n\r\nprint(\"\"\"\r\nTV Application\r\n\r\n1. Turn On TV\r\n\r\n2. Turn Off TV\r\n\r\n3. Volume Setting\r\n\r\n4. Adding Channel\r\n\r\n5. Learning Number of Channels\r\n\r\n6. Random Channel\r\n\r\n7. TV Information\r\n\r\nTo exit press \"q\"\r\n\r\n\"\"\")\r\n\r\nwhile True:\r\n\r\n operation = input(\"Please chose the operation: \")\r\n\r\n if operation == \"q\":\r\n print(\"Operation is end\")\r\n break\r\n\r\n elif operation == \"1\":\r\n controller.TurnOnTV()\r\n\r\n elif operation == \"2\":\r\n controller.TurnOffTV()\r\n\r\n elif operation == \"3\":\r\n controller.VolumeSetting()\r\n\r\n elif operation == \"4\":\r\n channel_names = input(\"Channels should be entered with ',':\")\r\n channel_list = channel_names.split(\",\")\r\n\r\n for channel in channel_list:\r\n controller.AddChannel(channel)\r\n\r\n elif operation == \"5\":\r\n print(\"Number of Channel:\", len(controller))\r\n\r\n elif operation == \"6\":\r\n controller.RandomChannel()\r\n\r\n elif operation == \"7\":\r\n print(controller)\r\n\r\n else:\r\n print(\"Invalid operation..\")\r\n","repo_name":"GozdeGu/SampleProjects","sub_path":"TVRemoteControl.py","file_name":"TVRemoteControl.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"19154855805","text":"from datetime import datetime, timedelta\nimport os\n\ndef read_today(today):\n if not os.path.exists(f'{today}.txt'):\n file = open(f'{today}.txt', 'w')\n file.close()\n return ['TOTAL_TIME:', '0:00:00', 'LOG:']\n\n file = open(f'{today}.txt', 'r')\n study_duration = file.read().split('\\n')\n file.close()\n return study_duration\n\n\ndef calc_elapsed_time(stored, studied):\n elapsed_time = datetime.strptime(stored, \"%H:%M:%S\") + studied\n elapsed_time = elapsed_time.strftime(\"%H:%M:%S\")\n return elapsed_time\n\n\ndef write_today(today, study_duration):\n today_data = read_today(today)\n\n today_data[1] = calc_elapsed_time(today_data[1], study_duration)\n today_data.append(\n f\"Date {datetime.now().strftime('%m/%d/%Y, %H:%M:%S')} - Time Spent {round_delta(study_duration)}\")\n\n today_data_string = '\\n'.join(str(line) for line in today_data)\n\n file = open(f'{today}.txt', 'w')\n file.write(today_data_string)\n file.close()\n\n\ndef round_delta(x): return str(x).split('.')[0]\n\n\ndef main():\n print('Starting timer...')\n while True:\n today = datetime.now().strftime(\"%Y-%m-%d\")\n startup_time = datetime.now()\n\n stop = input('Press enter to stop the timer...')\n elapsed_time = datetime.now() - startup_time\n\n print(f'Elapsed time: {round_delta(elapsed_time)}')\n focused_multiplier = int(\n input('On a scale of 0 to 10, how focused were you during those time:'))/10\n final_elapsed_time_in_seconds = focused_multiplier * elapsed_time.total_seconds()\n final_elapsed_time = timedelta(seconds=final_elapsed_time_in_seconds)\n\n write_today(today, final_elapsed_time)\n print(f\"{round_delta(final_elapsed_time)} has been written to {today}.txt\")\n\n continue_execution = input(\n 'Press [Y] to start a new timer or any other key to stop: ').upper()\n if continue_execution != 'Y':\n print('Stopping timer...')\n break\n print('Starting new timer...')\n\n\nmain()\n","repo_name":"Moscarde/StudyTimeTracker","sub_path":"study_time_tracker.py","file_name":"study_time_tracker.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30222761360","text":"#Runtime: O(n) | Space: O(1)\n#\t\t where n is the length of \"arr\" array\ndef monotonic_array(arr):\n\t#Handle base cases of empty and 1 element arrays being true\n\t#Have a current trend var that tracks the moment that we realize if the list is currently increasing or decreasing\n\t#Initialize the currTrend \n\t#Iterate through the array and keep going until currTrend is filled\n\t#If currTrend isn't filled at the end of list, return True\n\t#Otherwise, now go through rest of list and see if it still fits the currTrend or deviates\n\n\tif len(arr) == 0 or len(arr) == 1:\n\t\treturn True\n\n\tcurrTrend = None\n\n\tcurrIdx = 1 \n\twhile currIdx < len(arr) and currTrend is None:\n\t\t if arr[currIdx] == arr[currIdx-1]:\n\t\t \tcurrIdx += 1\n\t\t elif arr[currIdx] > arr[currIdx-1]:\n\t\t \tcurrTrend = 'increasing'\n\t\t \tbreak\n\t\t else:\n\t\t \tcurrTrend = 'decreasing'\n\t\t \tbreak\n\n\tif currTrend is None:\n\t\treturn True\n\n\twhile currIdx < len(arr):\n\t\tif arr[currIdx] > arr[currIdx-1] and currTrend == 'decreasing':\n\t\t\treturn False\n\t\telif arr[currIdx] < arr[currIdx-1] and currTrend == 'increasing':\n\t\t\treturn False\n\t\tcurrIdx += 1\n\n\treturn True\n\narr1 = [1, 2, 2, 3]\nprint(monotonic_array(arr1))\n#True\n\narr2 = [6, 5, 4, 4]\nprint(monotonic_array(arr2))\n#True\n\narr3 = [1, 2, 4, 5]\nprint(monotonic_array(arr3))\n#True\n\narr4 = [1, 1, 1]\nprint(monotonic_array(arr4))\n#True\n\narr5 = [-1, -5, -10, -1222]\nprint(monotonic_array(arr5))\n#True\n\narr6 = [1, 3, 2]\nprint(monotonic_array(arr6))\n#False","repo_name":"AlvinNgo123/leetcode_practice","sub_path":"year1/monotonic_array.py","file_name":"monotonic_array.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25639714213","text":"# system tools for input function\nimport argparse\nimport sys\n\n# sql database connection\nfrom config import USERNAME, PASSWORD, HOST_PORT, DB_NAME\nfrom sqlalchemy import create_engine\n\n# data cleaning and wrangling tools\nimport pandas as pd\nimport numpy as np\n\n# nlp tools\nimport spacy\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk import word_tokenize\nfrom stopwords import stop_words\n\n# metrics\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n# pickle\nimport pickle\n\n\"\"\" Set up PostgreSQL connection for search query. \"\"\"\n\n# create sqlalchemy engine for connecting to postgresql db\nengine = create_engine(f\"postgresql+psycopg2://{USERNAME}:{PASSWORD}@localhost:{HOST_PORT}/{DB_NAME}\")\n\n\n\"\"\" Load all resources. \"\"\"\n\n# open pickled dictionary of vocabulary and their raw term counts of the corpus of ingredients from all the recipes\nwith open(\"data/lda_vocab_counts.pkl\", \"rb\") as dict_file:\n tf_vocab = pickle.load(dict_file)\n\n# load the pickled LDA model\nwith open(\"foodnetwork_lda_sklearn.pkl\", \"rb\") as model:\n lda = pickle.load(model)\n\n# load in the pickled reference dataframe of all the recipes assigned to respective topics and the probabilities they fit in those topics\nrecipes_topics = pd.read_pickle(\"./data/recipes_topics.pkl\")\n\n# assign the probabilities of each recipe belonging to a particular topic to a variable\ndoc_topic_probs = recipes_topics.Scores\n\n# load in Topic-Keywords matrix dataframe as reference data for next step\ntopics_keywords = pd.read_pickle(\"./data/topic_keywords_matrix.pkl\")\n\n\"\"\" Function to run raw text through pipeline for predictions. \"\"\"\n\n# create function that runs raw text through pipeline for predictions\ndef predict_topic(text):\n \n \"\"\" Preprocess input text in order to turn it into a vector and then calculate the cosine similarity scores between it and the recipes stored. \"\"\"\n\n # lower case text\n text = text.lower()\n \n # tokenize text\n tokens = word_tokenize(text)\n \n # instantiate lemmatizer and lemmatize words\n wnl = WordNetLemmatizer()\n lemmatized = [wnl.lemmatize(word) for word in tokens]\n \n # remove stop words\n no_stops = [word for word in lemmatized if not word in stop_words]\n\n \"\"\" Transform preprocessed input text into a vector and transform it using the saved LDA model to obtain the topic probability scores. \"\"\"\n\n # instantiate the CountVectorizer to convert input text into a vector\n tf_vectorizer = CountVectorizer(max_df=0.95, min_df=1, max_features=1000, vocabulary=tf_vocab)\n # use CountVectorizer to convert the preprocessed input text into a vector\n text_vector = tf_vectorizer.transform(no_stops)\n # print(text_vector)\n # transform using the saved LDA model to obtain topic probability scores\n topic_probability_scores = lda.transform(text_vector)\n # return the topic and the input text's probability scores that it belongs to a specific topic\n return topic_probability_scores\n\n\"\"\" Function to run the preprocessed text through the function to obtain topic probability scores of the input text and then calculate cosine similarity scores between it\nand the stored recipes to find those that are most similar. \"\"\"\n\n# function to find the top 5 recipes that fit the best with the input text\ndef similar_documents(text, doc_topic_probs, top_n=5):\n # process input text, convert into a vector, and use the LDA model to calculate its topic probability scores\n x = predict_topic(text)\n # calculate cosine similarity between input text vector and recipe topic probability vector\n dists = cosine_similarity(x, np.array(doc_topic_probs).reshape(-1, 10))[0]\n # obtain top 5 similar recipes based on cosine similarity scores\n doc_ids = np.argsort(dists)[:top_n]\n return list(doc_ids)\n\n\n\"\"\" Define arguments to accept query, parse it, run it through LDA model, ping DB for results, and print top 5 recommended recipes. \"\"\"\n\n# instantiate parser\nparser = argparse.ArgumentParser()\n# add argument to parser\nparser.add_argument(\"-q\", \"--query\", dest=\"query\")\n# define values\nvalues = parser.parse_args()\nprint(sys.argv)\n\nif (values.query):\n query = values.query\nelse:\n print(\"Error: Please enter a string to be searched.\")\n exit(1)\n\n# preprocess query text and find the ids of the top recipes that fit it best\ndoc_ids = similar_documents(query, doc_topic_probs, top_n=5)\n\n# create a connection with database\nwith engine.begin() as connection:\n\n # query from recipes class with filter and print results\n # loop through list of ids\n for id in doc_ids:\n # insert each id into sql query to pull in the recipe data for the corresponding id\n recipe = connection.execute(f\"SELECT recipes.recipe_id, recipes.title, recipes.url FROM food.recipes WHERE recipe_id = {id}\")\n print(recipe.fetchall())\n\n# close connection after query\nconnection.close()","repo_name":"lasoya/Recipe_Recommender","sub_path":"notebooks/mvp_scripts/sklearn_evaluate.py","file_name":"sklearn_evaluate.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7667216277","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 getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n if not original:\n return None\n if original == target:\n return cloned\n\n return self.getTargetCopy(original.left,cloned.left,target) or self.getTargetCopy(original.right,cloned.right,target)\n# Runtime: 672 ms, faster than 60.93% of Python3 online submissions for Find a Corresponding Node of a Binary Tree in a Clone of That Tree.\n# Memory Usage: 23.5 MB, less than 100.00% of Python3 online submissions for Find a Corresponding Node of a Binary Tree in a Clone of That Tree.\n\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n que = collections.deque([(original, cloned)]) # start at the root\n while que:\n nodeOrig, nodeClon = que.popleft()\n if nodeOrig is target: # if original node is found - cloned node is our answer\n return nodeClon\n if nodeOrig.left: que.append((nodeOrig.left, nodeClon.left))\n if nodeOrig.right: que.append((nodeOrig.right, nodeClon.right))\n# Runtime: 656 ms, faster than 92.51% of Python3 online submissions for Find a Corresponding Node of a Binary Tree in a Clone of That Tree.\n# Memory Usage: 23.6 MB, less than 100.00% of Python3 online submissions for Find a Corres\n","repo_name":"Kuehar/LeetCode","sub_path":"Find a Corresponding Node of a Binary Tree in a Clone of That Tree.py","file_name":"Find a Corresponding Node of a Binary Tree in a Clone of That Tree.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"1569967961","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'taskman.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^$', 'task_engine.views.login_view', name='login'), # index page\n\turl(r'^', include('task_engine.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n","repo_name":"mani098/taskman","sub_path":"taskman/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"6886997752","text":"class Stack:\n\n def __init__(self):\n self.S = []\n self.ptr = 0\n # self.capacity\n\n def isEmpty(self):\n return self.ptr <= 0\n\n def __len__(self):\n return self.ptr\n\n def push(self, item):\n self.S.append(item)\n self.ptr += 1\n\n def pop(self):\n if self.isEmpty():\n print(\"underflow\")\n self.ptr -= 1\n return self.S[self.ptr]\n\n def peek(self):\n if self.isEmpty():\n print(\"underflow\")\n return self.S[self.ptr - 1]\n\n##테스트\n\nstk = Stack()\n\nprint(stk.isEmpty())\nstk.push(1)\nprint(stk.isEmpty())\nstk.push(2)\nprint(stk.peek())\nstk.push(4)\nprint(stk.peek())\nprint(stk.pop())\nprint(stk.peek())\nprint(\"***\")\nprint(stk.__len__())\nprint(stk.isEmpty())","repo_name":"sungsikyang92/pythonStudy","sub_path":"Intro_To_Algorithms/n_Stack.py","file_name":"n_Stack.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18232594680","text":"import torch\nfrom torch import tensor\nfrom torch import nn\nfrom torch.autograd import Variable\nimport cv2\nimport numpy\nimport torchvision\nimport os\nfrom torch.nn import functional\nfrom torchvision import models\n\n\nclass Res(nn.Module):\n def __init__(self,ch,size,groups=1,active=nn.Tanh,padding=0):\n super(Res, self).__init__()\n self.ch = ch\n self.pd=((size-1) >> 1) - padding\n self.conv = nn.Sequential(nn.Conv2d(ch, ch, size, groups=groups),\n active(),\n #nn.Conv2d(ch, ch, 1, 1, (size-1) >> 1, groups=ch, bias=False)\n nn.Conv2d(ch, ch, 1, 1, padding, groups=ch, bias=False)\n )\n\n def forward(self, x):\n height=x.size()[2]\n width=x.size()[3]\n pd=self.pd\n return x[:,:,pd:height-pd,pd:width-pd] + self.conv(x)\n #return x + self.conv(x)\n\n\nclass Paddding():\n def __init__(self, channels, paddings):\n if paddings >= 0:\n self.pd=nn.Conv2d(channels, channels, 1, 1, paddings, groups=channels, bias=False)\n else:\n self.pd = nn.ConvTranspose2d(channels, channels, 1, 1, -paddings, groups=channels, bias=False)\n self.pd.train(False)\n self.pd.weight.requires_grad_(False)\n self.pd.weight.zero_()\n self.pd.weight += 1.\n\n def cuda(self):\n self.pd.cuda()\n\n def __call__(self, x):\n return self.forward(x)\n\n def forward(self, x):\n return self.pd(x)\n\n\nclass Module(nn.Module):\n def __init__(self):\n super(Module, self).__init__()\n self.paddingTranspose = None\n self.conv1 = nn.Sequential(\n nn.Conv2d(2, 128, 10, 8),\n nn.Conv2d(128, 128, 1),\n nn.Conv2d(128, 64, 1),\n nn.ConvTranspose2d(64, 1, 10, 8)\n )\n self.paddingTranspose1 = None\n self.conv2 = nn.Sequential(\n nn.Conv2d(2, 64, 5),\n Res(64, 3),\n Res(64, 3),\n nn.Conv2d(64, 128, 3),\n Res(128, 3),\n nn.Conv2d(128, 64, 3),\n Res(64, 3),\n Res(64, 3),\n nn.Conv2d(64, 1, 3),\n Res(1,3)\n )\n self.is_cuda = False\n\n def cuda(self, device=None):\n nn.Module.cuda(self)\n self.is_cuda = True\n\n def Padding(self, channels, paddings):\n pd = Paddding(channels, paddings)\n if self.is_cuda:\n pd.cuda()\n return pd\n\n def forward(self, x):\n if self.paddingTranspose1 is None:\n self.paddingTranspose1 = self.Padding(1, -11)\n\n y = self.conv1(x)\n\n y = x[:, 0:1] + y\n ym = self.paddingTranspose1(y[:, 0:1])\n y = torch.cat((y, x[:, 1:2]), 1)\n\n y = self.conv2(y)\n\n return y + ym\n\n","repo_name":"BORUTO-U/DLF-VINO","sub_path":"DLF-pytorch/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37984299063","text":"import json\nfrom kafka import KafkaProducer as k_KafkaProducer, KafkaConsumer as k_KafkaConsumer\nfrom kafka.admin import KafkaAdminClient, NewTopic\n\nfrom pingpong.interfaces import AbstractProducer, AbstractConsumer\n\n\nclass KafkaProducer(AbstractProducer):\n \"\"\"\n Kafka Producer using https://kafka-python.readthedocs.io/ with JSON serialization.\n \"\"\"\n def __init__(self, bootstrap_servers: list, schema: dict) -> None:\n \"\"\"\n Create the Producer instance.\n \"\"\"\n super(KafkaProducer, self).__init__(\n bootstrap_servers=bootstrap_servers, schema=schema\n )\n self.producer = k_KafkaProducer(\n bootstrap_servers=bootstrap_servers,\n value_serializer=lambda x: json.dumps(x).encode('utf-8')\n )\n\n def send(self, topic: str, key: str, value: dict) -> None:\n \"\"\"\n Send the specified Value to a Kafka Topic.\n \"\"\"\n self.producer.send(topic, value)\n self.producer.flush()\n\n\nclass KafkaConsumer(AbstractConsumer):\n \"\"\"\n Kafka Consumer using https://kafka-python.readthedocs.io/ with JSON deserialization.\n \"\"\"\n def __init__(self, bootstrap_servers: list, group_id: str, topics: list, schema: dict) -> None:\n \"\"\"\n Create the Consumer instance.\n \"\"\"\n super(KafkaConsumer, self).__init__(\n bootstrap_servers=bootstrap_servers, group_id=group_id, topics=topics, schema=schema\n )\n self.consumer = k_KafkaConsumer(\n *topics,\n bootstrap_servers=bootstrap_servers,\n group_id=group_id,\n auto_offset_reset='earliest',\n value_deserializer=lambda x: json.loads(x.decode('utf-8'))\n )\n\n def create_topics(self, topics: list, num_partitions: int = 2, replication_factor: int = 1):\n \"\"\"\n Create the specified list of Topics.\n \"\"\"\n admin_client = KafkaAdminClient(bootstrap_servers=self.bootstrap_servers)\n topic_list = []\n\n new_topics = set(topics) - set(self.consumer.topics())\n for topic in new_topics:\n try:\n t = NewTopic(name=topic, num_partitions=num_partitions, replication_factor=replication_factor)\n admin_client.create_topics(new_topics=[t], validate_only=False)\n topic_list.append(t)\n # Ignore the error when the Topic already exists.\n except:\n pass\n\n return topic_list\n\n def read(self):\n \"\"\"\n Read messages from the configured Kafka Topics.\n \"\"\"\n for message in self.consumer:\n yield message\n","repo_name":"ahuarte47/KafkaPingPong","sub_path":"pingpong/providers/kafka.py","file_name":"kafka.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29534591950","text":"import re\n\nclass Dimension():\n def __init__(self):\n self.content = Rect()\n self.padding = Edge()\n self.border = Edge()\n self.margin = Edge()\n def get_padding_rect(self):\n r = self.content.clone()\n r.add_edge(self.padding)\n return r\n def get_border_rect(self):\n r = self.content.clone()\n r.add_edge(self.padding)\n r.add_edge(self.border)\n return r\n def get_margin_rect(self):\n r = self.content.clone()\n r.add_edge(self.padding)\n r.add_edge(self.border)\n r.add_edge(self.margin)\n return r\n def get_height(self):\n return self.content.height + self.margin.get_height() + \\\n self.border.get_height() + self.padding.get_height()\n\nclass Rect():\n def __init__(self):\n self.x = 0\n self.y = 0\n self.width = 0 # width\n self.height = 0 # height\n def add_edge(self, edge):\n self.x -= edge.left\n self.y -= edge.top\n self.width += edge.left + edge.right\n self.height += edge.top + edge.bottom\n pass\n def get_right(self):\n return self.x + self.width\n def get_bottom(self):\n return self.y + self.height\n def clone(self):\n r = Rect()\n r.x = self.x\n r.y = self.y\n r.width = self.width\n r.height = self.height\n return r\n def get_string(self):\n return \"x:\" + str(self.x) + \", y:\" + str(self.y) + \", w:\" + \\\n str(self.width) + \", h:\" + str(self.height)\n\nclass Edge():\n def __init__(self):\n self.left = 0\n self.right = 0\n self.top = 0\n self.bottom = 0\n def max(self):\n return max(self.left, self.right, self.top, self.bottom)\n def set_all(self, x):\n self.left = x\n self.right = x\n self.top = x\n self.bottom = x\n def get_height(self):\n return self.top + self.bottom\n def get_string(self):\n return \"l:\" + str(self.left) + \", r:\" + str(self.right) + \\\n \", t:\" + str(self.top) + \", d:\" + str(self.bottom)\n\nclass Box():\n def __init__(self):\n self.dimension = Dimension()\n self.children = []\n self.style = None\n def get_inline_box(self):\n if len(self.children) < 1 or not isinstance(self.children[-1], AnonymousBox):\n self.children.append(AnonymousBox())\n return self.children[-1]\n def add_child(self, child):\n if isinstance(child, BlockBox):\n self.children.append(child)\n elif isinstance(child, InlineBox):\n anon = self.get_inline_box()\n anon.children.append(child)\n # Container es una instancia de Rect\n def layout_box(self, container):\n pass\n def has_borders(self):\n return self.dimension.border.max() > 0\n\n def print_node(self, ident = 0):\n space = \" \" * ident\n print(space + self.__class__.__name__)\n space = \" \" * (ident + 1)\n if self.style == None:\n print(space + \"WARNING: NO STYLE!!!\")\n print(space + self.dimension.content.get_string())\n print(space + \"margin = \" + self.dimension.margin.get_string())\n print(space + \"border = \" + self.dimension.border.get_string())\n print(space + \"padding = \" + self.dimension.padding.get_string())\n print(space + \"children:\")\n for child in self.children:\n child.print_node(ident + 2)\n\ndef to_px(x, container = None):\n if x == \"auto\":\n return 0\n return int(x)\n\ndef get_edges(style, name):\n edge = Edge()\n edge.left = style.try_get([name + \"_left\", name], 0)\n edge.right = style.try_get([name + \"_right\", name], 0)\n edge.up = style.try_get([name + \"_up\", name], 0)\n edge.down = style.try_get([name + \"_down\", name], 0)\n\n\nclass BlockBox(Box):\n # Container es una instancia de Rect\n def layout_box(self, container):\n self.calculate_width(container)\n self.calculate_position(container)\n self.layout_children()\n self.calculate_height()\n\n def calculate_width(self, container):\n margin_left = self.style.try_get([\"margin_left\", \"margin\"], 0)\n margin_right = self.style.try_get([\"margin_right\", \"margin\"], 0)\n border_left = self.style.try_get([\"border_left\", \"border\"], 0)\n border_right = self.style.try_get([\"border_right\", \"border\"], 0)\n padding_left = self.style.try_get([\"padding_left\", \"padding\"], 0)\n padding_right = self.style.try_get([\"padding_right\", \"padding\"], 0)\n width = self.style.get(\"width\", \"auto\")\n\n # Tamano minimo requerido para mostrar todo el contenido\n total = sum(map(lambda x: to_px(x, container), [\n margin_left, margin_right, border_left, border_right,\n padding_left, padding_right, width]))\n\n # Pixeles que faltan para ocupar todo el espacio del contenedor.\n # Si es negativo, este Bloque es mas ancho que el contenedor.\n underflow = container.width - total\n\n # Si underflow es negativo, el contenido es mas grande que el contenedor.\n if underflow < 0:\n margin_right = underflow\n elif width == \"auto\":\n width = underflow\n elif margin_left == margin_right == \"auto\":\n margin_left = margin_right = underflow/2\n elif margin_left == \"auto\":\n margin_left = underflow\n elif margin_right == \"auto\":\n margin_right = underflow\n else:\n margin_right = to_px(margin_right) + underflow\n\n d = self.dimension\n d.margin.right = to_px(margin_right)\n d.margin.left = to_px(margin_left)\n d.border.right = to_px(border_right)\n d.border.left = to_px(border_left)\n d.padding.right = to_px(padding_right)\n d.padding.left = to_px(padding_left)\n d.content.width = width\n\n def calculate_position(self, container):\n d = self.dimension\n d.margin.top = to_px(self.style.try_get([\"margin_top\", \"margin\"], 0))\n d.margin.bottom = to_px(self.style.try_get([\"margin_bottom\", \"margin\"], 0))\n d.border.top = to_px(self.style.try_get([\"border_top\", \"border\"], 0))\n d.border.bottom = to_px(self.style.try_get([\"border_bottom\", \"border\"], 0))\n d.padding.top = to_px(self.style.try_get([\"padding_top\", \"padding\"], 0))\n d.padding.bottom = to_px(self.style.try_get([\"padding_bottom\", \"padding\"], 0))\n\n d.content.x = container.x + d.margin.left + d.border.left + d.padding.left\n d.content.y = container.y + container.height + \\\n d.margin.top + d.border.top + d.padding.top\n\n def layout_children(self):\n for child in self.children:\n child.layout_box(self.dimension.content)\n self.dimension.content.height += child.dimension.get_height()\n\n def calculate_height(self):\n height = self.style.get(\"height\", \"auto\")\n if height != \"auto\":\n self.dimension.content.height = to_px(height)\n\n\nclass InlineBox(Box):\n pass\n\nclass AnonymousBox(BlockBox):\n def layout_box(self, container):\n pass\n\ndef build_layout_tree(node):\n display = node.display()\n if display == \"none\":\n return None\n elif display == \"inline\":\n box = InlineBox()\n else:\n box = BlockBox()\n for child in node.children:\n box.add_child(build_layout_tree(child))\n box.style = node\n return box\n","repo_name":"Arnaz87/pydom","sub_path":"layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":6748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"16409713494","text":"import pytest\n\nfrom django.urls import reverse, resolve\nfrom django.test import Client\n\nfrom toxsign.assays.tests.factories import AssayFactory, FactorFactory\n\npytestmark = pytest.mark.django_db\n\ndef test_assay_details():\n assay = AssayFactory.create()\n assert (\n reverse(\"assays:assay_detail\", kwargs={\"assid\": assay.tsx_id})\n == f\"/assays/assay/{assay.tsx_id}/\"\n )\n assert resolve(f\"/assays/assay/{assay.tsx_id}/\").view_name == \"assays:assay_detail\"\n\ndef test_factor_details():\n factor = FactorFactory.create()\n assert (\n reverse(\"assays:factor_detail\", kwargs={\"facid\": factor.tsx_id})\n == f\"/assays/factor/{factor.tsx_id}/\"\n )\n assert resolve(f\"/assays/factor/{factor.tsx_id}/\").view_name == \"assays:factor_detail\"\n","repo_name":"umr1085-irset/toxsign_v2","sub_path":"toxsign/assays/tests/test_urls.py","file_name":"test_urls.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"11711894807","text":"from datetime import datetime, timedelta\r\n\r\nimport plotext as plt\r\nfrom rich.ansi import AnsiDecoder\r\nfrom rich.console import Group\r\nfrom rich.jupyter import JupyterMixin\r\n\r\nfrom textual_prometheus.config import SETTINGS\r\nfrom textual_prometheus.prom_api import PrometheusApi\r\n\r\n\r\ndef make_query_range_plot(width: int, height: int, instance: str, metric: str):\r\n api = PrometheusApi(SETTINGS.endpoint)\r\n plt.clear_data()\r\n plt.date_form('d/m/Y H:M')\r\n end = datetime.now()\r\n start = end - timedelta(days=30)\r\n plt.plotsize(width, height)\r\n data = api.parse_query_range(instance, metric, start, end, step='1h')\r\n\r\n for i, host in enumerate(data):\r\n values = [int(float(h[1])) for h in host]\r\n dates = plt.datetimes_to_string([datetime.fromtimestamp(h[0]) for h in host], 'd/m/Y H:M')\r\n plt.plot(dates, values, label=f\"toto{i}\")\r\n plt.title(f\"{instance} {metric}\")\r\n plt.xlabel(\"Date\")\r\n plt.ylabel(\"Value\")\r\n\r\n return plt.build()\r\n\r\n\r\nclass PlotMixin(JupyterMixin):\r\n def __init__(self, instance, metric=None):\r\n self.decoder = AnsiDecoder()\r\n self.instance = instance\r\n self.metric = metric\r\n\r\n def __rich_console__(self, console, options):\r\n self.width = options.max_width or console.width\r\n self.height = options.height or console.height\r\n try:\r\n self.canvas = make_query_range_plot(self.width, self.height, self.instance, self.metric)\r\n except IndexError as e:\r\n message = (\r\n f\"Could not generate plot. Most likely no metric for that instance\\n\"\r\n f\"EXCEPTION: {e}\"\r\n )\r\n print(message)\r\n self.canvas = message\r\n self.rich_canvas = Group(*self.decoder.decode(self.canvas))\r\n yield self.rich_canvas\r\n","repo_name":"UmBsublime/textual-prometheus","sub_path":"textual_prometheus/renderables/_plot.py","file_name":"_plot.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"}
+{"seq_id":"7857700386","text":"import shutil\nimport os\n\ncounter = 0\n# count_bad = 0\n\nCURRENT_DATASET_PATH = \"./Check_Internal_En/\"\nNEW_DATASET_PATH = \"./full_dataset_2/\"\n\nfor i in range(1, 533):\n path_curr = CURRENT_DATASET_PATH + str(i)\n for filename in os.listdir(path_curr):\n if not filename[0] == \"F\":\n f = open(path_curr + \"/\" + filename, \"r\")\n vals = f.read().split(\"\\n\")\n # if not vals[-1].split(',')[0] == 'Density' and not vals[-2].split(',')[0] == 'Density':\n # \tcount_bad+=1\n # \tcontinue\n\n shutil.copy(path_curr + \"/\" + filename, NEW_DATASET_PATH)\n os.rename(NEW_DATASET_PATH + filename, str(counter) + \".txt\")\n counter += 1\nprint(counter)\n# print(count_bad)\n","repo_name":"Ishan-Kumar2/configurational-polymer-fingerprint","sub_path":"code/ML/single_folder.py","file_name":"single_folder.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"73218924562","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport numpy.testing as nt\nimport unittest\n\nfrom machinevisiontoolbox.Image import Image\n# from pathlib import Path\n\n\nclass TestImageProcessingBase(unittest.TestCase):\n\n def test_int(self):\n\n # test for uint8\n im = np.zeros((2, 2), np.float)\n im = Image(im)\n nt.assert_array_almost_equal(im.int().image,\n np.zeros((2, 2), np.uint8))\n\n im = np.ones((2, 2), np.float)\n im = Image(im)\n nt.assert_array_almost_equal(im.int().image,\n 255 * np.ones((2, 2)).astype(np.uint8))\n\n # tests for shape\n im = np.random.randint(1, 255, (3, 5), int)\n im = Image(im)\n imi = im.int()\n nt.assert_array_almost_equal(imi.shape, im.shape)\n\n im = np.random.randint(1, 255, (3, 5, 3), int)\n im = Image(im)\n imi = im.int()\n nt.assert_array_almost_equal(imi.shape, im.shape)\n\n im = np.random.randint(1, 255, (3, 5, 3, 10), int)\n im = Image(im)\n imi = im.int()\n nt.assert_array_almost_equal(imi.shape, im.shape)\n\n def test_float(self):\n # test for uint8\n im = np.zeros((2, 2), np.uint8)\n im = Image(im)\n nt.assert_array_almost_equal(im.float().image,\n np.zeros((2, 2), np.float32))\n\n im = 128 * np.ones((2, 2), np.uint8)\n im = Image(im)\n nt.assert_array_almost_equal(im.float().image,\n (128.0/255.0 * np.ones((2, 2))))\n\n im = 255 * np.ones((2, 2), np.uint8)\n im = Image(im)\n nt.assert_array_almost_equal(im.float().image,\n (np.ones((2, 2))))\n\n # test for uint16\n im = np.zeros((2, 2), np.uint16)\n im = Image(im)\n nt.assert_array_almost_equal(im.float().image,\n np.zeros((2, 2), np.float32))\n\n im = 128 * np.ones((2, 2), np.uint16)\n im = Image(im)\n nt.assert_array_almost_equal(im.float().image,\n (128.0/65535.0 * np.ones((2, 2))))\n\n im = 65535 * np.ones((2, 2), np.uint16)\n im = Image(im)\n nt.assert_array_almost_equal(im.float().image,\n (np.ones((2, 2))))\n\n # test for sequence of images\n im = np.random.randint(low=1,\n high=255,\n size=(5, 8, 3, 4),\n dtype=np.uint8)\n im = Image(im)\n imf = im.float()\n nt.assert_array_almost_equal(imf.shape, im.shape)\n nt.assert_array_almost_equal(imf.image,\n im.image.astype(np.float32) / 255.0)\n\n im = np.random.randint(low=1,\n high=65535,\n size=(3, 10, 3, 7),\n dtype=np.uint16)\n im = Image(im)\n imf = im.float()\n nt.assert_array_almost_equal(imf.shape, im.shape)\n nt.assert_array_almost_equal(imf.image,\n im.image.astype(np.float32) / 65535.0)\n\n def test_mono(self):\n # input an image that is not mono\n imname = 'monalisa.png'\n im = Image(imname)\n imm = im.mono()\n self.assertEqual(imm.iscolor, False)\n self.assertEqual(imm.shape, im.size)\n\n def test_testpattern(self):\n im = Image()\n tp = im.testpattern('rampx', 10, 2)\n self.assertEqual(tp.shape, (10, 10))\n\n tp = im.testpattern('rampx', (20, 10), 2)\n self.assertEqual(tp.shape, (10, 20))\n r = np.linspace(0, 1, 10, endpoint=True)\n out = np.hstack((r, r))\n nt.assert_array_almost_equal(tp.image[5, :], out)\n\n tp = im.testpattern('rampy', (10, 20), 2)\n self.assertEqual(tp.shape, (20, 10))\n nt.assert_array_almost_equal(tp.image[:, 5], out.T)\n\n tp = im.testpattern('sinx', 12, 1)\n self.assertEqual(tp.shape, (12, 12))\n nt.assert_almost_equal(np.sum(tp.image), 0, decimal=6)\n nt.assert_almost_equal(np.diff(tp.image[:, 2]),\n np.zeros((11)),\n decimal=6)\n\n tp = im.testpattern('siny', 12, 1)\n self.assertEqual(tp.shape, (12, 12))\n nt.assert_almost_equal(np.sum(tp.image), 0, decimal=6)\n nt.assert_almost_equal(np.diff(tp.image[2, :]),\n np.zeros((11)),\n decimal=6)\n\n tp = im.testpattern('dots', 100, 20, 10)\n self.assertEqual(tp.shape, (100, 100))\n # TODO [l,ml,p,c] = ilabel(im);\n # tc.verifyEqual(sum(c), 25);\n\n tp = im.testpattern('squares', 100, 20, 10)\n self.assertEqual(tp.shape, (100, 100))\n # TODO [l,ml,p,c] = ilabel(im);\n # tc.verifyEqual(sum(c), 25);\n\n # TODO not yet converted to python:\n tp = im.testpattern('line', 20, np.pi / 6, 10)\n self.assertEqual(tp.shape, (20, 20))\n self.assertEqual(tp.image[10, 0], 1)\n self.assertEqual(tp.image[11, 1], 1)\n self.assertEqual(tp.image[16, 11], 1)\n self.assertEqual(np.sum(tp.image), 17)\n\n def test_paste(self):\n\n im = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n im = Image(im)\n canvas = np.zeros((5, 5))\n canvas = Image(canvas)\n\n out = np.array([[0, 0, 0, 0, 0],\n [0, 0, 1, 2, 3],\n [0, 0, 4, 5, 6],\n [0, 0, 7, 8, 9],\n [0, 0, 0, 0, 0]])\n cp = canvas.paste(im, (2, 1))\n nt.assert_array_almost_equal(cp.image, out)\n\n canvas = np.zeros((5, 5))\n canvas = Image(canvas)\n cp = canvas.paste(im, (3, 2), centre=True)\n nt.assert_array_almost_equal(cp.image, out)\n\n canvas = np.zeros((5, 5))\n canvas = Image(canvas)\n cp = canvas.paste(im, (2, 1), opt='set')\n nt.assert_array_almost_equal(cp.image, out)\n\n canvas = np.zeros((5, 5))\n canvas = Image(canvas)\n cp = canvas.paste(im, (2, 1), opt='mean')\n nt.assert_array_almost_equal(cp.image, out / 2)\n\n canvas = np.zeros((5, 5))\n canvas = Image(canvas)\n cp = canvas.paste(im, (2, 1), opt='add')\n cp2 = cp.paste(im, (2, 1), opt='add')\n nt.assert_array_almost_equal(cp2.image, out * 2)\n\n def test_pixelswitch(self):\n\n # test monochrome image\n a = np.array([[1, 2], [3, 4]])\n b = np.array([[5, 6], [7, 8]])\n\n a = Image(a)\n b = Image(b)\n\n nt.assert_array_almost_equal(a.pixelswitch(np.zeros((2, 2)), b).image,\n b.image)\n nt.assert_array_almost_equal(a.pixelswitch(np.ones((2, 2)), b).image,\n a.image)\n mask = np.array([[0, 1], [1, 0]])\n nt.assert_array_almost_equal(a.pixelswitch(mask, b).image,\n np.array([[5, 2], [3, 8]]))\n\n # test color image\n a = np.random.randint(0, 255, (2, 2, 3))\n b = np.random.randint(0, 255, (2, 2, 3))\n a = Image(a)\n b = Image(b)\n mask = np.array([[0, 1], [0, 0]])\n out = a.pixelswitch(mask, b)\n nt.assert_array_almost_equal(out.image[0, 0, :], b.image[0, 0, :])\n nt.assert_array_almost_equal(out.image[0, 1, :], a.image[0, 1, :])\n nt.assert_array_almost_equal(out.image[1, 0, :], b.image[1, 0, :])\n nt.assert_array_almost_equal(out.image[1, 1, :], b.image[1, 1, :])\n\n # TODO\n # test_stretch\n # test_thresh\n # test_otsu\n # test_imeshgrid\n # test_hist\n # test_plothist\n # test_normhist\n # test_replicate\n # test_decimate\n # test_testpattern (half done)\n # test_scale\n # test_rotate\n # test_samesize\n # test_peak2\n # test_roi\n\n\n# ----------------------------------------------------------------------- #\nif __name__ == '__main__':\n\n unittest.main()\n\n # import code\n # code.interact(local=dict(globals(), **locals()))\n","repo_name":"hwan1135/machinevision-toolbox-python","sub_path":"tests/test_imageprocessing_base.py","file_name":"test_imageprocessing_base.py","file_ext":"py","file_size_in_byte":8155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32884422126","text":"import essentia\nimport essentia.standard\nimport essentia.streaming\nfrom essentia.standard import *\nimport pandas as pd\nimport json\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBClassifier\nimport pickle\nimport argparse\nfrom sklearn.metrics import accuracy_score\n\n\n\n# This function tract features from json\ndef create_feature_test(d1):\n with open(d1) as f:\n json_object = json.load(f)\n e= Energy()\n\n average_loudness =json_object['lowlevel']['average_loudness']\n dissonance_mean = json_object['lowlevel']['dissonance']['mean']\n energy_erbbands = e.compute(json_object['lowlevel']['erbbands']['mean'])\n energy_melbands = e.compute(json_object['lowlevel']['melbands']['mean'])\n mfcc = json_object['lowlevel']['mfcc']['mean']\n beat_loudness_ratio=json_object['rhythm']['beats_loudness_band_ratio']['mean']\n chords_changes_rate = json_object['tonal']['chords_changes_rate']\n chord_histogram = json_object['tonal']['chords_histogram']\n bpm = json_object['rhythm']['bpm']\n chord_key = json_object['tonal']['chords_key']\n chord_scale= json_object['tonal']['chords_scale']\n mfcc = json_object['lowlevel']['mfcc']['mean']\n\n out = {'chord_key' : chord_key ,'chord_scale':chord_scale,'bpm':bpm,'average_loudness': average_loudness , 'dissonance_mean' : dissonance_mean , 'energy_erbbands' : energy_erbbands, 'energy_melbands' : energy_melbands ,'chords_changes_rate': chords_changes_rate}\n root =\"mfcc\"\n root_1=\"chord_hist\"\n i =0\n for it in mfcc:\n key_name=root+str(i)\n out[key_name] = it\n i=i+1\n i= 0\n for it in chord_histogram:\n key_name=root_1 + str(i)\n out[key_name] = it\n i=i+1\n\n return out\n\nap= argparse.ArgumentParser()\nap.add_argument(\"-i\" ,\"--test_file\" , required=True , help=\"Path to input train file\")\nargs=vars(ap.parse_args())\n\ntest = pd.read_csv(args['test_file'])\n\nfeature_list=[]\ni = 0\nfor index, row in test.iterrows():\n # d1=train['AF_PATH'][0]\n temp_feature=create_feature_test(row['AF_PATH'])\n temp_feature['TRACK_ID'] = row['TRACK_ID']\n # temp_feature['y'] = row['MOOD_TAG']\n # temp_feature\n feature_list.append(temp_feature)\nx_test = pd.DataFrame(feature_list)\n\n\n\ndummy_chord_scale = pd.get_dummies(x_test['chord_scale'])\ndummy_chord_key = pd.get_dummies(x_test['chord_key'])\nx_test=pd.concat((x_test,dummy_chord_key), axis=1)\nx_test=pd.concat((x_test , dummy_chord_scale), axis = 1)\nx_test.drop(['chord_key' , 'chord_scale'] , axis= 1, inplace=True)\n\nx_test.to_csv('test_features.csv' , index=False)\ntrack_id = x_test['TRACK_ID']\nx_test.drop(['TRACK_ID'] , axis=1,inplace=True)\nprint(\"Feature Extraction Done\")\n\n\nprint(x_test.head())\n# print('hiii')\n\nloaded_model = pickle.load(open(\"xgboost.pickle.dat\", \"rb\"))\nprint(\"Loaded model from: xgboost.pickle.dat\")\n\npredictions = loaded_model.predict(x_test)\nprint(predictions)\ntest['MOOD_TAG']=predictions\ntest.loc[(test.MOOD_TAG == 0),'MOOD_TAG']='SAD'\ntest.loc[(test.MOOD_TAG == 1),'MOOD_TAG']='HAPPY'\n\n\ntest.to_csv('out_tuned_1.csv', index=False)\n\n# accuracy = accurac_score(x_test, predictions)\n# print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n\n\n\n\n","repo_name":"badalgupta/music_classification","sub_path":"pred.py","file_name":"pred.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"73517663122","text":"''' Creating Finite State Machine to process debit or credit transactions '''\nfrom transaction_fsm import StateMachine\n\ndef start_state(txt, account):\n ''' Define start state'''\n if 'Debit' in txt:\n new_state = \"debit_state\"\n elif 'Credit' in txt:\n new_state = \"credit_state\"\n else:\n new_state = \"error_state\"\n return (new_state, txt, account)\n\ndef debit_state_transition(txt, account):\n '''Define state transition'''\n split_txt = txt.split(':')\n name = split_txt[0]\n num = int(split_txt[1])\n\n account.process_debit(num, name)\n new_state = 'Start'\n account.print_balance()\n\n return (new_state, txt, account)\n\ndef credit_state_transition(txt, account):\n '''Define credit state transition'''\n split_txt = txt.split(':')\n name = split_txt[0]\n num = int(split_txt[1])\n\n account.process_credit(num, name)\n account.print_balance()\n\n if account.get_balance() <= -1000:\n new_state = 'end_state'\n account.print_transactions()\n else:\n new_state = 'Start'\n\n return (new_state, txt, account)\n\nif __name__== \"__main__\":\n m = StateMachine()\n m.add_state(\"Start\", start_state)\n m.add_state(\"debit_state\", debit_state_transition)\n m.add_state(\"credit_state\", credit_state_transition)\n m.add_state(\"error_state\", None, end_state=1)\n m.add_state('end_state',None, end_state=1)\n m.set_start(\"Start\")\n m.run()\n","repo_name":"FominSergiy/finite_state_machine","sub_path":"transaction_set_up.py","file_name":"transaction_set_up.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5537252750","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 21 17:24:30 2019\r\n\r\n@author: Sameer\r\n\"\"\"\r\n\r\nimport matplotlib.pylab as plt\r\nfrom scipy.integrate import odeint\r\nimport numpy as np\r\n\r\nN = 10000\r\nS = N - 1\r\nI = 1\r\nR = 0\r\nD = 0\r\nbetaOne = 23 # infection rate\r\nbeta = 0.3\r\ngamma = 0.15 # recovery rate\r\nalphaOne = 0.4\r\nalphaTwo = 0.25\r\ndeltaOne = 0.3\r\ndeltaTwo = 0.75\r\ngammaOne = 0.25\r\n\r\n#Numerical Solution\r\n# differential equatinons\r\ndef diff(sir, t):\r\n # sir[0] - S, sir[1] - I, sir[2] - R\r\n dsdt = gammaOne * sir[2] - betaOne * ( 1 - beta) *sir[0] *sir[1] / N - gamma * sir[0]\r\n \r\n didt = betaOne * ( 1 - beta) *sir[0] *sir[1] / N - alphaOne * beta * sir[1] - \\\r\n alphaTwo * (1 - beta) * sir[1] -( deltaOne * beta * sir[1] ) - deltaTwo * ( 1- beta) * sir[1]\r\n \r\n drdt = alphaOne * beta * sir[1] + alphaTwo * (1 - beta) * sir[1] + gamma * sir[0] - gammaOne * sir[2]\r\n \r\n dDdt = deltaOne * beta * sir[1] + deltaTwo * ( 1- beta) * sir[1]\r\n \r\n print (dsdt , didt , drdt , dDdt)\r\n \r\n dsirDdt = [dsdt, didt, drdt, dDdt]\r\n \r\n return dsirDdt\r\n\r\n\r\n# initial conditions\r\nsir0 = (S, I, R, D)\r\n\r\n# time points\r\nt = np.linspace(0, 40)\r\n\r\n# solve ODE\r\n# the parameters are, the equations, initial conditions, \r\n# and time steps (between 0 and 100)\r\nsir = odeint(diff, sir0, t)\r\n\r\nplt.plot(t, sir[:, 0], label='S(t)')\r\nplt.plot(t, sir[:, 1], label='I(t)')\r\nplt.plot(t, sir[:, 2], label='R(t)')\r\nplt.plot(t, sir[:, 3], label='D(t)')\r\n\r\n\r\n\r\nplt.legend()\r\n\r\nplt.xlabel('T')\r\nplt.ylabel('N')\r\n\r\n# use scientific notation\r\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))\r\n\r\nplt.show()","repo_name":"gogatesameer/disease_modelling","sub_path":"Ebola_spread_modelling.py","file_name":"Ebola_spread_modelling.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12614228333","text":"\"\"\"\nMonkey-patch the edX platform\n\nHere be dragons (and simians!)\n\n* USE WITH CAUTION *\nNo, but seriously, you probably never really want to make changes here.\nThis module contains methods to monkey-patch [0] the edx-platform.\nPatches are to be applied as early as possible in the callstack\n(currently lms/startup.py and cms/startup.py). Consequently, changes\nmade here will affect the entire platform.\n\nThat said, if you've decided you really need to monkey-patch the\nplatform (and you've convinced enough people that this is best\nsolution), kindly follow these guidelines:\n - Reference django_18_upgrade.py for a sample implementation.\n - Name your module by replacing periods with underscores for the\n module to be patched:\n - patching 'django.utils.translation'\n becomes 'django_utils_translation'\n - patching 'your.module'\n becomes 'your_module'\n - Implement argumentless function wrappers in\n monkey_patch.your_module for the following:\n - is_patched\n - patch\n - unpatch\n - Add the following code where needed (typically cms/startup.py and\n lms/startup.py):\n ```\n from openedx.core.djangoapps.monkey_patch import your_module\n your_module.patch()\n ```\n - Write tests! All code should be tested anyway, but with code that\n patches the platform runtime, we must be extra sure there are no\n unintended consequences.\n\n[0] http://en.wikipedia.org/wiki/Monkey_patch\n\"\"\"\n# Use this key to store a reference to the unpatched copy\n__BACKUP_ATTRIBUTE_NAME = '__monkey_patch'\n\n\ndef is_patched(module, attribute_name):\n \"\"\"\n Check if an attribute has been monkey-patched\n \"\"\"\n attribute = getattr(module, attribute_name)\n return hasattr(attribute, __BACKUP_ATTRIBUTE_NAME)\n\n\ndef patch(module, attribute_name, attribute_replacement):\n \"\"\"\n Monkey-patch an attribute\n\n A backup of the original attribute is preserved in the patched\n attribute (see: __BACKUP_ATTRIBUTE_NAME).\n \"\"\"\n attribute = getattr(module, attribute_name)\n setattr(attribute_replacement, __BACKUP_ATTRIBUTE_NAME, attribute)\n setattr(module, attribute_name, attribute_replacement)\n return is_patched(module, attribute_name)\n\n\ndef unpatch(module, attribute_name):\n \"\"\"\n Un-monkey-patch an attribute\n\n Restore a backup of the original attribute from the patched\n attribute, iff it exists (see: __BACKUP_ATTRIBUTE_NAME).\n\n Return boolean whether or not the attribute could be unpatched\n \"\"\"\n was_patched = False\n attribute = getattr(module, attribute_name)\n if hasattr(attribute, __BACKUP_ATTRIBUTE_NAME):\n attribute_old = getattr(attribute, __BACKUP_ATTRIBUTE_NAME)\n setattr(module, attribute_name, attribute_old)\n was_patched = True\n return was_patched\n","repo_name":"openedx/edx-platform","sub_path":"openedx/core/djangoapps/monkey_patch/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","stars":6774,"dataset":"github-code","pt":"3"}
+{"seq_id":"21313223123","text":"'''\npseudocode\n\nRecursive top-down implementation\n\nCUT-ROD(p, n)\n if n == 0\n return 0\n q = -infinity\n for i = 1 to n\n q = max(q, p[i] + CUT-ROD(p, n - i)\n return q\n\n'''\n\nimport time\n\n# dictionary of length and price\np = {1:1, 2:5, 3:8, 4:9, 5:10, 6:17, 7:17, 8:20, 9:24, 10:30}\n\ndef CUT_ROD(p, n):\n if n is 0:\n return 0\n\n q = float(\"-inf\")\n\n for i in range(1, n + 1):\n q = max(q, p[i] + CUT_ROD(p, n - i))\n\n return q\n\n\n\n\nif __name__ == '__main__':\n begin = time.time()\n print(CUT_ROD(p, 5))\n print(\"TOTAL time it takes to run {}\".format(time.time() - begin))\n","repo_name":"ehzawad/algorism","sub_path":"dynamicProgramming/rod_cutting_recursive_topdown_implementation.py","file_name":"rod_cutting_recursive_topdown_implementation.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23328148794","text":"import numpy as np\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\nimport os\nimport torch\nimport datasets\nimport torch.nn.functional as F\n# from julia import Julia\n# jl = Julia(compiled_modules=False)\n# from julia.AVSfldIO import fld_read\nfrom grid_sample import *\nimport matplotlib.patches as patches\nfrom utils import init_env, find_contour, get_bounding_box_center\n\n\n# import matlab.engine\n# eng = matlab.engine.start_matlab()\n\nclass mydataloader:\n def __init__(self, datasetdir = '.', mode = 'train', \n known_xtrue = True, verbose = True) -> None:\n # torch.set_float32_matmul_precision('highest')\n self.imgsize = 256\n self.verbose = verbose\n assert mode in {'train', 'test'}\n if mode == 'train':\n self.dir = os.path.join(datasetdir, 'train') \n else:\n self.dir = os.path.join(datasetdir, 'test')\n self.known_xtrue = known_xtrue\n \n if self.known_xtrue:\n self.meta = {'spect': [], 'xtrue': [], 'seg':[]}\n else:\n self.meta = {'spect': []}\n self.readfldfiles()\n # normalize xtrue\n def convert_data(self):\n for i in range(len(self.meta['spect'])):\n maxofspect = torch.max(self.meta['spect'][i])\n if self.verbose:\n print('max of spect: ', maxofspect)\n if self.known_xtrue:\n maxofxtrue = torch.max(self.meta['xtrue'][i])\n if self.verbose:\n print('max of xtrue, before normalization: ', maxofxtrue)\n self.meta['xtrue'][i] = self.meta['xtrue'][i] / maxofxtrue * 255.0\n if self.verbose:\n print('max of xtrue, after normalization: ', torch.sum(self.meta['xtrue'][i]))\n max_of_spect = torch.max(self.meta['spect'][i])\n self.meta['spect'][i] = self.meta['spect'][i] / max_of_spect * 255.0\n if self.verbose:\n print('max of spect after normalization: ', torch.max(self.meta['spect'][i])) \n \n self.meta['spect'] = torch.stack(self.meta['spect']).permute(0,3,1,2).reshape(-1,self.imgsize,self.imgsize)\n\n spect_temp = torch.clone(self.meta['spect'])\n if self.known_xtrue:\n self.meta['xtrue'] = torch.stack(self.meta['xtrue']).permute(0,3,1,2).reshape(-1,self.imgsize,self.imgsize)\n self.meta['seg'] = torch.stack(self.meta['seg']).permute(0,3,1,2).reshape(-1,self.imgsize,self.imgsize)\n xtrue_temp = torch.clone(self.meta['xtrue'])\n seg_temp = torch.clone(self.meta['seg'])\n \n for imgidx in range(self.meta['seg'].shape[0]):\n seg = self.meta['seg'][imgidx, :, :]\n filled_segs = find_contour(seg)\n if len(filled_segs) > 0:\n print(f'{imgidx} seg is separate into: ', len(filled_segs))\n seg_temp[imgidx, :, :] = filled_segs[0].to(self.meta['seg'].dtype)\n for segidx in range(1, len(filled_segs)):\n seg_temp = torch.cat((seg_temp, \n filled_segs[segidx].unsqueeze(0).to(self.meta['seg'].dtype)),\n dim=0)\n spect_temp = torch.cat((spect_temp, \n self.meta['spect'][imgidx, :, :].unsqueeze(0)),\n dim=0)\n xtrue_temp = torch.cat((xtrue_temp, \n self.meta['xtrue'][imgidx, :, :].unsqueeze(0)),\n dim=0)\n self.meta['xtrue'] = torch.clone(xtrue_temp)\n self.meta['seg'] = torch.clone(seg_temp)\n \n self.meta['spect'] = torch.clone(spect_temp)\n \n if self.verbose:\n print('spect shape: ', self.meta['spect'].shape)\n print('spect maximum: ', torch.max(self.meta['spect']))\n print('spect average: ', torch.mean(self.meta['spect']))\n if self.known_xtrue:\n if self.verbose:\n print('xtrue shape: ', self.meta['xtrue'].shape)\n print('seg shape: ', self.meta['seg'].shape)\n print('xtrue maximum: ', torch.max(self.meta['xtrue']))\n print('xtrue mean: ', torch.mean(self.meta['xtrue']))\n print('seg maximum: ', torch.max(self.meta['seg']))\n \n \n def readfldfiles(self):\n path_list= []\n file_list = []\n for root, _, files in os.walk(self.dir):\n path_list.append(root)\n files = [fi for fi in files if fi.endswith(\".fld\")]\n file_list.append(files)\n file_num = len(path_list) - 1\n spect_str = 'spect128wSC'\n xtrue_str = 'xtrue'\n seg_str = 'lesionbigmask'\n \n for i in range(file_num):\n fldfiles = file_list[i + 1]\n if self.verbose:\n print('load data from {}'.format(path_list[i + 1]))\n for s in fldfiles:\n if spect_str in s:\n if self.verbose:\n print('load spect map from {}'.format(os.path.join(path_list[i + 1], s)))\n spect = torch.tensor(fld_read(os.path.join(path_list[i + 1], s)), dtype=torch.float)\n spect = resize128to256(spect)[:,:,20:60]\n # spect = m(spect.unsqueeze(0).unsqueeze(0)).squeeze()\n self.meta['spect'].append(spect)\n if self.known_xtrue:\n if xtrue_str in s:\n if self.verbose:\n print('load true map from {}'.format(os.path.join(path_list[i + 1], s)))\n xtrue = torch.tensor(fld_read(os.path.join(path_list[i + 1], s)), dtype=torch.float)\n xtrue = resize512to256(xtrue)[:,:,20:60]\n # xtrue = m(xtrue.unsqueeze(0).unsqueeze(0)).squeeze()\n self.meta['xtrue'].append(xtrue)\n if seg_str in s:\n if self.verbose:\n print('load seg map from {}'.format(os.path.join(path_list[i + 1], s)))\n seg = torch.tensor(fld_read(os.path.join(path_list[i + 1], s)), dtype=torch.float)\n seg = resize512to256(seg).bool().float()[:,:,20:60]\n # seg = m(seg.unsqueeze(0).unsqueeze(0)).squeeze()\n self.meta['seg'].append(seg)\n if self.verbose:\n print('data load {} / {} finished!'.format(i + 1, file_num))\n \ndef create_dataset(images, labels):\n dataset = datasets.Dataset.from_dict({\"image\": images,\n \"label\": labels})\n dataset = dataset.cast_column(\"image\", datasets.Image())\n dataset = dataset.cast_column(\"label\", datasets.Image())\n\n return dataset\n\ndef read_mat_files(path):\n spect = sio.loadmat(os.path.join(path, 'spect_128.mat'))['spect_128']\n seg = sio.loadmat(os.path.join(path, 'lesionbigmask_128.mat'))['seg_128']\n return spect, seg\n\ndef show_mask(mask, ax, random_color=False):\n if random_color:\n color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)\n else:\n color = np.array([255/255, 144/255, 30/255, 0.6])\n h, w = mask.shape[-2:]\n mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n ax.imshow(mask_image)\n\n\nif __name__ == \"__main__\":\n loader = mydataloader(datasetdir='/home/zhonglil/ondemand/data/sys/myjobs/default/SAM_seg/', mode='test')\n loader.convert_data()\n init_env(seed_value=42)\n bbox_threshold = 20\n # path = './y90-data/test/y90res02'\n # spect, seg = read_mat_files(path=path)\n # spect = np.transpose(spect, [2,0,1]) / np.amax(spect) * 255.0\n # print('maximum of spect: ', np.amax(spect))\n # seg = np.transpose(seg, [2,0,1])\n # device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n # num_of_img x dim_of_img\n dataset = create_dataset(images=loader.meta['spect'], labels=loader.meta['seg'])\n # processor = SamProcessor.from_pretrained(\"wanglab/medsam-vit-base\")\n # model = SamModel.from_pretrained(\"wanglab/medsam-vit-base\").to(device)\n # plt.figure()\n fig, axes = plt.subplots()\n idx = 17\n axes.imshow(np.array(dataset[idx][\"image\"]))\n ground_truth_seg = np.array(dataset[idx][\"label\"])\n bbox, _ = get_bounding_box_center(ground_truth_seg, bbox_threshold)\n _, center = get_bounding_box_center(ground_truth_seg, bbox_threshold=1)\n print('bbox values: ', bbox)\n print('center values: ', center)\n show_mask(ground_truth_seg, axes)\n # Create a Rectangle patch\n rect = patches.Rectangle((bbox[0], bbox[1]), bbox[2]-bbox[0], bbox[3]-bbox[1], \n linewidth=3, edgecolor='r', facecolor='none')\n\n # Add the patch to the Axes\n axes.add_patch(rect)\n axes.title.set_text(f\"Ground truth mask\")\n axes.axis(\"off\")\n plt.savefig('testimg.png')\n plt.show()\n # plt.figure()\n # plt.imshow(loader.meta['seg'][idx])\n # plt.savefig('testimg_seg.png')\n # plt.show()","repo_name":"umjiayx/SPECT_Seg","sub_path":"src_sam/prepare_dataset.py","file_name":"prepare_dataset.py","file_ext":"py","file_size_in_byte":9258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"11101856534","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.contrib.auth.decorators import login_required\nfrom views import *\nfrom django.conf import settings\n\nurlpatterns = patterns('',\n url(r'^$', login_required(HomeView.as_view()), name=\"home\"),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^logout/$', 'django.contrib.auth.views.logout',\n {'next_page': '/'}, name='logout'),\n url(r'^' + settings.LOGIN_URL + '$', 'django.contrib.auth.views.login',\n {'template_name': 'login.html', \"extra_context\": {\"title\": \"Login\"}}, name='login'),\n\n url(r'^product/add/$', login_required(ProductCreateView.as_view()), name='product_add'),\n url(r'^product/delete/(?P.+)/$', login_required(ProductDeleteView.as_view()), name='product_delete'),\n url(r'^product/list/$', login_required(ProductListView.as_view()), name='product_list'),\n url(r'^product/get_products/', get_products, name='get_products'),\n url(r'^product/update/(?P.+)/$', login_required(ProductUpdateView.as_view()), name='product_update'),\n url(r'^meal/update/$', login_required(MealUpdateView.as_view()), name='meal_update'),\n )","repo_name":"domort/przeliczacz","sub_path":"przeliczacz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29539783651","text":"from django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom .models import tophistorias\nimport requests\nfrom django.db.models.functions import Extract\nimport datetime\n\n# Create your views here.\n\ndef courses(request):\n fecha_actual=datetime.datetime.now()\n cache = tophistorias.objects.all().values('created_at')#trae el query de la fecha\n req = requests.request('GET','https://hacker-news.firebaseio.com/v0/beststories.json')\n datos = req.json()\n \n date=list(cache)\n value=date[0]\n value2=value['created_at']\n secs=fecha_actual.second\n secs_cache=value2.second\n mins=fecha_actual.minute\n mins_cache=value2.minute\n segundosactual=int(secs)\n segundos_cache=int(secs_cache)\n proxy=segundos_cache-segundosactual\n proxymins=mins_cache-mins\n\n if(proxy>20)or(proxy<-20)or(proxymins!=0):\n mensaje=\"expiro\"\n data_a_eliminar=tophistorias.objects.all()\n data_a_eliminar.delete()\n objdatos = tophistorias()\n objdatos.itemid = datos\n objdatos.created_at = fecha_actual\n objdatos.save()\n\n \n else:\n mensaje=\"no expiro\"\n \n return JsonResponse(mensaje, safe=False)\n\ndef ConsultDatos(request, codigo):\n\n #trae el query de la los top\n data_tophistorias=tophistorias.objects.all().values('itemid')\n lis2=list(data_tophistorias)\n vl=lis2[0]\n datos_list_bd=vl['itemid']\n cogido_num=int(codigo)\n\n for itr in range(len(datos_list_bd)):\n if(cogido_num==datos_list_bd[itr]):\n req = requests.request('GET','https://hacker-news.firebaseio.com/v0/item/'+codigo+'.json')\n datos = req.json()\n title=str(datos['title'])\n tipo =str(datos['type'])\n mensaje=\"El titulo es : \"+title+\" Y el tipo es : \"+tipo\n \n #si se pasa del rango y no lo encuentra como puedo programar eso de no encontrar si se pasa\n \n\n\n return JsonResponse(mensaje, safe=False)\n\n","repo_name":"Clepio215/Prueba_Python_APIREST_Django","sub_path":"allcourses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2848777983","text":"#!/usr/bin/env python \n\"\"\"\nfit a bernoulli distribution with several parameterizations\n\"\"\"\n\nimport sys,os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as scs\n\n## declare variables\nfont_size = 11\nfont_name = 'sans-serif'\nn = 10000\nfig = plt.figure(figsize=(10,6))\nsplot = 0\n\n## loop through parameterizations of the beta\nfor p in [0.3,0.6,0.9]:\n splot += 1\n ax = fig.add_subplot(1,3,splot)\n \n x = np.arange(scs.bernoulli.ppf(0.01, p),scs.bernoulli.ppf(0.99, p)+1)\n ax.plot(x, scs.bernoulli.pmf(x, p), 'bo', ms=8, label='pmf')\n ax.vlines(x, 0, scs.bernoulli.pmf(x, p), colors='b', lw=5, alpha=0.5)\n rv = scs.bernoulli(p)\n \n ax.set_ylim((0,1.0))\n ax.set_xlim((-0.25, 1.25))\n ax.set_title(\"p=%s\"%(p))\n ax.set_aspect(1./ax.get_data_ratio())\n\n for t in ax.get_xticklabels():\n t.set_fontsize(font_size-1)\n t.set_fontname(font_name)\n for t in ax.get_yticklabels():\n t.set_fontsize(font_size-1)\n t.set_fontname(font_name)\n\nplt.savefig(\"bernoulli-distn.png\", dpi=400)\nplt.show()\n","repo_name":"GalvanizeOpenSource/stats-shortcourse","sub_path":"docs/scripts/bernoulli-distn.py","file_name":"bernoulli-distn.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"3"}
+{"seq_id":"34105477681","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\nurl = \"D:\\\\mgr\\\\iris\\\\iris.data\"\n\n# załadowanie zbioru danych do Pandas DataFrame\ndf = pd.read_csv(url, names=['sepal length', 'sepal width', 'petal length', 'petal width', 'target'])\n\nfeatures = ['sepal length', 'sepal width', 'petal length', 'petal width']\n\n# Separating out the features\nx = df.loc[:, features].values\n\n# Separating out the target\ny = df.loc[:, ['target']].values\n\n# Standardizing the features\nx = StandardScaler().fit_transform(x)\n\npca = PCA(n_components=2)\n\nprincipalComponents = pca.fit_transform(x)\n\nprincipalDf = pd.DataFrame(data=principalComponents\n , columns=['principal component 1', 'principal component 2'])\n\nfinalDf = pd.concat([principalDf, df[['target']]], axis=1)\n\nfig = plt.figure(figsize=(8, 8))\nax = fig.add_subplot(1, 1, 1)\nax.set_xlabel('PC 1', fontsize=15)\nax.set_ylabel('PC 2', fontsize=15)\nax.set_title('2 component PCA, zbiór Iris', fontsize=20)\n\ntargets = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']\ncolors = ['r', 'g', 'b']\nfor target, color in zip(targets, colors):\n indicesToKeep = finalDf['target'] == target\n ax.scatter(finalDf.loc[indicesToKeep, 'principal component 1']\n , finalDf.loc[indicesToKeep, 'principal component 2']\n , c=color\n , s=50)\nax.legend(targets)\n#ax.grid()\nplt.show()\n","repo_name":"WookiePL/linear-dim-reduction","sub_path":"test/pca_example2.py","file_name":"pca_example2.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"74520365840","text":"# -*- coding: utf-8 -*-\n\n\n# def max_in_window(arr, size):\n# if size == 1:\n# yield from arr\n# return\n# for i in range(len(arr) - size + 1):\n# max_ = max(arr[i + 1: i + size])\n# last_max = arr[i] if arr[i] > max_ else max_\n# yield last_max\n\n\n# def max_in_window(arr, size):\n# if size == 1:\n# yield from arr\n# return\n# maxs = [max(arr[i: i + 2]) for i in range(size - 1)]\n# yield max(maxs)\n# del arr[:size-1]\n# for i in range(len(arr)-1):\n# del maxs[0]\n# maxs.append(max(arr[0: 2]))\n# del arr[0]\n# yield max(maxs)\n\n# from collections import deque\n# def max_in_window(arr, size):\n# if size == 1:\n# yield from arr\n# return\n# queue = deque(arr[:size-1], size)\n# for i in range(size - 1, len(arr)):\n# queue.append(arr[i])\n# yield max(queue)\n\n# def max_in_window(arr, size):\n# if size == 1:\n# yield from arr\n# return\n# yield from (max(arr[i: i + size]) for i in range(len(arr) - size + 1))\n\ndef max_in_window(arr, size):\n if size == 1:\n yield from arr\n return\n else:\n for i in range(len(arr) - size + 1):\n yield max(arr[i: i + size])\n\nif __name__ == '__main__':\n print(list(max_in_window([2, 7, 3, 1, 5, 2, 6, 2], 4)))\n assert list(max_in_window([2, 7, 3, 1, 5, 2, 6, 2], 4)) == [7, 7, 5, 6, 6]\n assert list(max_in_window([2, 1, 5], 1)) == [2, 1, 5]\n assert list(max_in_window([2, 3, 9], 3)) == [9]\n\n assert list(max_in_window([2, 1, 5], 2)) == [2, 5]\n\n # для ввода при тестировании на сайте\n # input()\n # print(*max_in_window(list(int(i) for i in input().split()), int(input())))\n","repo_name":"become-iron/python_practice","sub_path":"courses/Алгоритмы теория и практика. Структуры данных/5. Максимум в скользящем окне.py","file_name":"5. Максимум в скользящем окне.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7049425326","text":"from .action import *\nfrom . import path, tools\n\nrequirements = path.configfiles(\"requirements.txt\")\nxonsh_requirements = path.configfiles(\"xonsh-requirements.txt\")\n\n\n@default\n@action(\n requirements=\"The files used for the requirements\"\n)\ndef pip(requirements=requirements):\n \"\"\"\n Installs Python 3 modules via pip3 as defined in the requirements file.\n This requires Python 3 on your system and installs it via homebrew if necessary. \n \"\"\"\n existingRequirements = path.existing(path.expandusers(requirements))\n args = [\"pip3\", \"install\"]\n for requirement in existingRequirements:\n args.append(\"--requirement\")\n args.append(requirement)\n try:\n tools.run(*args)\n except NameError:\n print(\"Installing Python3\")\n tools.run(\"brew\", \"install\", \"python3\")\n tools.run(*args)\n\n@default\n@upgrade\n@action(\n xonsh_requirements=\"The files used for the requirements\"\n)\ndef xpip(xonsh_requirements=xonsh_requirements):\n \"\"\"\n Installs Xonsh Python 3 modules via xpip as defined in the requirements file.\n \"\"\"\n existingRequirements = path.existing(path.expandusers(xonsh_requirements))\n args = [\"xpip\", \"install\"]\n for requirement in existingRequirements:\n args.append(\"--requirement\")\n args.append(\"'{}'\".format(requirement))\n tools.run(\"xonsh\", \"-c\", \" \".join(args))\n\n@default\n@upgrade\n@action\ndef pipdate():\n \"\"\"\n Update existing Python packages. Requires the python egg pipdate.\n \"\"\"\n tools.run(\"pip3\", \"install\", \"--upgrade\", \"pip\")\n tools.run(\"pipdate3\")\n\n@default\n@upgrade\n@action\ndef xpipdate():\n \"\"\"\n Update existing Xonsh Python packages. Requires the python egg pipdate.\n \"\"\"\n import subprocess, re\n \n versions = subprocess.check_output(['/usr/bin/env', 'xonsh', '-c', 'xpip freeze --local'])\n entries = re.findall(\"^(.*?)=\", versions, re.MULTILINE)\n for entry in entries:\n tools.run(\"xonsh\", \"-c\", \"xpip install -U {}\".format(entry))\n","repo_name":"nd-net/bootstrap","sub_path":"bootstrap_impl/pip.py","file_name":"pip.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18209726996","text":"list01 = [\n [1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15],\n]\n\n# 1. 将第一行从左到右逐行打印\nfor item in list01[0]:\n print(item)\n# 2. 将第二行从右到左逐行打印\nfor c in range(len(list01[1]) - 1, -1, -1):\n print(list01[1][c])\n# 3. 将第三列行从上到下逐个打印\n# list01[0][2]\n# list01[1][2]\n# list01[2][2]\nfor r in range(len(list01)): # 0 1 2\n print(list01[r][2])\n# 4. 将第四列行从下到上逐个打印\n# list01[2][3]\n# list01[1][3]\n# list01[0][3]\nfor r in range(len(list01) - 1, -1, -1):\n print(list01[r][3])\n# 5. 将二维列表以表格状打印\nfor line in list01:\n for item in line:\n print(item,end = \"\\t\")\n print()","repo_name":"why1679158278/python-stu","sub_path":"python资料/day8.8/day07/exercise05.py","file_name":"exercise05.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33188303280","text":"\"\"\"myworld URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\n\nurlpatterns = [\n path('apphome/', include('apphome.urls')),\n\n path('apphome/appre/', include('appre.urls')),\n path('apphome/landing_page/', include('landing_page.urls')),\n path('apphome/oantuti/', include('oantuti.urls')),\n\n path('apphome/appquizenglish/', include('appquizenglish.urls')),\n path('apphome/appquiziq/', include('appquiziq.urls')),\n\n path('apphome/mangxahoi/', include('mangxahoi.urls')),\n path('apphome/mangxahoi/mangxahoi_members/', include('django.contrib.auth.urls')),\n path('apphome/mangxahoi/mangxahoi_members/', include('mangxahoi_members.urls')),\n\n path('admin/', admin.site.urls),\n]\n","repo_name":"phamdatvt/duanweb","sub_path":"myworld/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32803985746","text":"#Answer: 871198282\nimport string\n\ndef main():\n\n #populate list with names in alphabetical order\n listOfNames = getListOfNames()\n\n #populate dictionary with value of each letter\n dictionary = {}\n populateDict(dictionary)\n\n #total of all the name scores in the file.\n totalScore = getTotalNameScore(listOfNames, dictionary)\n\n print(totalScore)\n\ndef getTotalNameScore(listOfNames, dictionary):\n total = 0\n index = 1\n for name in listOfNames:\n total += getNameScore(name, index, dictionary)\n index += 1\n \n return total\n\ndef getListOfNames():\n file = open(\"names.txt\", 'r')\n listOfNames = file.read()\n file.close() \n listOfNames = listOfNames.split(',')\n listOfNames.sort()\n \n return listOfNames\n\ndef populateDict(dictionary):\n dictionary['\"'] = 0\n value = 1;\n \n for char in string.ascii_uppercase:\n dictionary[char] = value;\n value += 1;\n \ndef getNameScore(name, index, dictionary):\n total = 0\n for char in name:\n value = dictionary[char]\n total = total + value\n \n return total * index\n\nmain()\n","repo_name":"GuillermoLopezJr/Project-Euler","sub_path":"Euler-022/Euler022.py","file_name":"Euler022.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35631676085","text":"import datetime\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n (\"cine\", \"0002_auto_20150109_2007\"),\n ]\n\n operations = [\n migrations.AlterField(\n model_name=\"soiree\",\n name=\"time\",\n field=models.TimeField(default=datetime.time(20, 30), verbose_name=\"heure\"),\n preserve_default=True,\n ),\n ]\n","repo_name":"nim65s/django-cineclub","sub_path":"cine/migrations/0003_auto_20150112_0554.py","file_name":"0003_auto_20150112_0554.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"41723471606","text":"\"\"\"Module for debugging parse functions. Not intended for public use.\"\"\"\n\nimport inspect\nimport os\nimport sys\n\nfrom .exception import KopytException\n\n\ndef debugger(klass): # pragma: no cover\n if not bool(os.getenv(\"DEBUG\")):\n return klass\n\n def decorator(method):\n def debugged_parse(self, *args, **kwargs):\n if not hasattr(self, \"debug_recursion_depth\"):\n self.debug_recursion_depth = 0\n\n if not hasattr(self, \"debug_func_id\"):\n self.debug_func_id = 0\n\n self.debug_func_id += 1\n prefix = f\"{self.debug_func_id:05d}\"\n indent = \"-\" * self.debug_recursion_depth\n name = method.__name__\n token = self.tokens.peek().value\n sys.stderr.write(f\"{prefix} {indent}> {name}({token!r})\")\n\n self.debug_recursion_depth += 1\n ret = None\n last_err = None\n try:\n ret = method(self, *args, **kwargs)\n except KopytException as err:\n last_err = err\n raise KopytException from err\n finally:\n token = self.tokens.peek().value\n ret_str = f\", result: {ret!s}\" if ret else \"\"\n err_str = f\", error: {last_err!s}\" if last_err else \"\"\n sys.stderr.write(\n f\"{prefix} <{indent} {name}({token!r}){ret_str}{err_str}\\n\"\n )\n self.debug_recursion_depth -= 1\n if self.debug_recursion_depth == 0:\n sys.stderr.write(\"\\n\")\n return ret\n\n return debugged_parse\n\n for name, func in inspect.getmembers(klass, inspect.isfunction):\n if not name.startswith(\"parse\"):\n continue\n setattr(klass, name, decorator(func))\n return klass\n","repo_name":"mvisat/kopyt","sub_path":"kopyt/debugger.py","file_name":"debugger.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"}
+{"seq_id":"6509079724","text":"import itertools\nfrom TNR.Network.bucket import Bucket\n\n\nclass Node:\n newid = itertools.count().__next__\n\n def __init__(self, tensor, Buckets=None):\n self.tensor = tensor\n self.id = Node.newid()\n self.network = None\n\n if Buckets is None:\n Buckets = [Bucket() for _ in range(self.tensor.rank)]\n\n self.buckets = Buckets\n\n for b in Buckets:\n b.node = self\n\n def __str__(self):\n s = 'Node with ID ' + str(self.id) + \\\n ' and tensor shape ' + str(self.tensor.shape)\n s = s + '\\n'\n for n in self.connectedNodes:\n s = s + str(n.id) + ' ' + str(self.indicesConnecting(n)) + '\\n'\n return s\n\n @property\n def compressedSize(self):\n return self.tensor.compressedSize\n\n @property\n def linkedBuckets(self):\n return [b for b in self.buckets if b.linked]\n\n @property\n def connectedNodes(self):\n return set([b.otherBucket.node for b in self.linkedBuckets])\n\n def findLinks(self, other):\n links = []\n for b in self.linkedBuckets:\n if other == b.otherNode:\n links.append(b.link)\n return links\n\n def findLink(self, other):\n links = self.findLinks(other)\n if len(links) > 0:\n return links[0]\n else:\n return None\n\n def linksConnecting(self, other):\n links = []\n for b in self.linkedBuckets:\n if other == b.otherNode:\n links.append(b.link)\n return links\n\n def indexConnecting(self, other):\n for b in self.linkedBuckets:\n if other == b.otherNode:\n return b.index\n return None\n\n def indicesConnecting(self, other):\n indices = [[], []]\n links = self.linksConnecting(other)\n for l in links:\n b1 = l.bucket1\n b2 = l.bucket2\n if b1.node == other:\n b1, b2 = b2, b1\n indices[0].append(b1.index)\n indices[1].append(b2.index)\n return indices\n\n def bucketIndex(self, b):\n return self.buckets.index(b)\n\n def mergeBuckets(self, buckets):\n '''\n This method merges the listed buckets.\n In the case of an ArrayTensor this just flattens the tensor along the corresponding axes.\n In the case of a TreeTensor this merges the external legs.\n '''\n inds = [b.index for b in buckets]\n self.tensor = self.tensor.flatten(inds)\n self.buckets = [b for i, b in enumerate(self.buckets) if i not in inds]\n self.buckets.append(Bucket())\n self.buckets[-1].node = self\n\n network = self.network\n if network is not None:\n network.buckets = network.buckets.difference(set(buckets))\n network.buckets.add(self.buckets[-1])\n\n if len(\n network.internalBuckets.intersection(\n set(buckets))) == len(buckets):\n network.internalBuckets = network.internalBuckets.difference(\n set(buckets))\n network.internalBuckets.add(self.buckets[-1])\n elif len(network.externalBuckets.intersection(set(buckets))) == len(buckets):\n network.externalBuckets = network.externalBuckets.difference(\n set(buckets))\n network.externalBuckets.add(self.buckets[-1])\n else:\n raise ValueError(\n 'Error: Provided buckets are a mixture of internal and external buckets!')\n\n return self.buckets[-1]\n","repo_name":"adamjermyn/PyTNR","sub_path":"TNR/Network/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"3"}
+{"seq_id":"71802788560","text":"import time,datetime\n\ndef sleep_till_future(f_minute):\n \"\"\"The function takes the current time, and calculates for how many seconds should sleep until a user provided minute in the future.\"\"\"\n t = datetime.datetime.today()\n future = datetime.datetime(t.year,t.month,t.day,t.hour,f_minute)\n if future.minute <= t.minute:\n print(\"ERROR! Enter a valid minute in the future.\")\n else:\n print(\"Current time: \" + str(t.hour)+\":\"+str(t.minute))\n print(\"Sleep until : \" + str(future.hour)+\":\"+str(future.minute))\n seconds_till_future = (future-t).seconds\n time.sleep( seconds_till_future )\n print (\"I slept for \"+str(seconds_till_future)+\" seconds!\")\n\nprint(\"hii\")\nsleep_till_future(30)\nprint(\"hii\")","repo_name":"legendparvesh/facialRecognition","sub_path":"tt3.py","file_name":"tt3.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43798158313","text":"# 16505 별\n\ndef star(n, x, y):\n if n == 1:\n ans[x][y] = '*'\n return\n g = n//2\n star(g, x, y)\n star(g, x+g, y)\n star(g, x, y+g)\n\nN = int(input())\nans = [[' ']*(i+1) for i in reversed(range(2**N))]\n\nif N == 0:\n print('*')\nelse:\n star(2**N, 0, 0)\n for ele in ans:\n print(''.join(ele))","repo_name":"KDT-02-Algorithm-Study/Algorithm-Study","sub_path":"week06_230216/16505_별/16505_정광배.py","file_name":"16505_정광배.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"16003399681","text":"try:\n a = int(input(\"input a number: \"))\n b = int(input(\"input another number: \"))\nexcept ValueError:\n print(\"there was an error\")\n\ntry:\n c = a // b\n print(c)\nexcept ZeroDivisionError as error:\n print(error)\nexcept NameError as name_error:\n print(name_error)","repo_name":"Stefanh18/python_projects","sub_path":"files/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6543807621","text":"\nimport os\nimport sys\nimport threading\nimport traceback\n\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nfrom electrum import Wallet, WalletStorage\nfrom electrum.util import UserCancelled, InvalidPassword\nfrom electrum.base_wizard import BaseWizard\nfrom electrum.i18n import _\n\nfrom .seed_dialog import SeedLayout, KeysLayout\nfrom .network_dialog import NetworkChoiceLayout\nfrom .util import *\nfrom .password_dialog import PasswordLayout, PW_NEW\n\n\nclass GoBack(Exception):\n pass\n\nMSG_GENERATING_WAIT = _(\"Electrum is generating your addresses, please wait...\")\nMSG_ENTER_ANYTHING = _(\"Please enter a seed phrase, a master key, a list of \"\n \"Bitcoin addresses, or a list of private keys\")\nMSG_ENTER_SEED_OR_MPK = _(\"Please enter a seed phrase or a master key (xpub or xprv):\")\nMSG_COSIGNER = _(\"Please enter the master public key of cosigner #%d:\")\nMSG_ENTER_PASSWORD = _(\"Choose a password to encrypt your wallet keys.\") + '\\n'\\\n + _(\"Leave this field empty if you want to disable encryption.\")\nMSG_RESTORE_PASSPHRASE = \\\n _(\"Please enter your seed derivation passphrase. \"\n \"Note: this is NOT your encryption password. \"\n \"Leave this field empty if you did not use one or are unsure.\")\n\n\nclass CosignWidget(QWidget):\n size = 120\n\n def __init__(self, m, n):\n QWidget.__init__(self)\n self.R = QRect(0, 0, self.size, self.size)\n self.setGeometry(self.R)\n self.setMinimumHeight(self.size)\n self.setMaximumHeight(self.size)\n self.m = m\n self.n = n\n\n def set_n(self, n):\n self.n = n\n self.update()\n\n def set_m(self, m):\n self.m = m\n self.update()\n\n def paintEvent(self, event):\n bgcolor = self.palette().color(QPalette.Background)\n pen = QPen(bgcolor, 7, Qt.SolidLine)\n qp = QPainter()\n qp.begin(self)\n qp.setPen(pen)\n qp.setRenderHint(QPainter.Antialiasing)\n qp.setBrush(Qt.gray)\n for i in range(self.n):\n alpha = int(16* 360 * i/self.n)\n alpha2 = int(16* 360 * 1/self.n)\n qp.setBrush(Qt.green if i%s\"%title if title else \"\")\n self.title.setVisible(bool(title))\n # Get rid of any prior layout by assigning it to a temporary widget\n prior_layout = self.main_widget.layout()\n if prior_layout:\n QWidget().setLayout(prior_layout)\n self.main_widget.setLayout(layout)\n self.back_button.setEnabled(True)\n self.next_button.setEnabled(next_enabled)\n if next_enabled:\n self.next_button.setFocus()\n self.main_widget.setVisible(True)\n self.please_wait.setVisible(False)\n\n def exec_layout(self, layout, title=None, raise_on_cancel=True,\n next_enabled=True):\n self.set_layout(layout, title, next_enabled)\n result = self.loop.exec_()\n if not result and raise_on_cancel:\n raise UserCancelled\n if result == 1:\n raise GoBack\n self.title.setVisible(False)\n self.back_button.setEnabled(False)\n self.next_button.setEnabled(False)\n self.main_widget.setVisible(False)\n self.please_wait.setVisible(True)\n self.refresh_gui()\n return result\n\n def refresh_gui(self):\n # For some reason, to refresh the GUI this needs to be called twice\n self.app.processEvents()\n self.app.processEvents()\n\n def remove_from_recently_open(self, filename):\n self.config.remove_from_recently_open(filename)\n\n def text_input(self, title, message, is_valid):\n slayout = KeysLayout(parent=self, title=message, is_valid=is_valid)\n self.exec_layout(slayout, title, next_enabled=False)\n return slayout.get_text()\n\n def seed_input(self, title, message, is_seed, options):\n slayout = SeedLayout(title=message, is_seed=is_seed, options=options, parent=self)\n self.exec_layout(slayout, title, next_enabled=False)\n return slayout.get_seed(), slayout.is_bip39, slayout.is_ext\n\n @wizard_dialog\n def add_xpub_dialog(self, title, message, is_valid, run_next):\n return self.text_input(title, message, is_valid)\n\n @wizard_dialog\n def add_cosigner_dialog(self, run_next, index, is_valid):\n title = _(\"Add Cosigner\") + \" %d\"%index\n message = ' '.join([\n _('Please enter the master public key (xpub) of your cosigner.'),\n _('Enter their master private key (xprv) if you want to be able to sign for them.')\n ])\n return self.text_input(title, message, is_valid)\n\n @wizard_dialog\n def restore_seed_dialog(self, run_next, test):\n options = []\n if self.opt_ext:\n options.append('ext')\n if self.opt_bip39:\n options.append('bip39')\n title = _('Enter Seed')\n message = _('Please enter your seed phrase in order to restore your wallet.')\n return self.seed_input(title, message, test, options)\n\n @wizard_dialog\n def confirm_seed_dialog(self, run_next, test):\n self.app.clipboard().clear()\n title = _('Confirm Seed')\n message = ' '.join([\n _('Your seed is important!'),\n _('If you lose your seed, your money will be permanently lost.'),\n _('To make sure that you have properly saved your seed, please retype it here.')\n ])\n seed, is_bip39, is_ext = self.seed_input(title, message, test, None)\n return seed\n\n @wizard_dialog\n def show_seed_dialog(self, run_next, seed_text):\n title = _(\"Your wallet generation seed is:\")\n slayout = SeedLayout(seed=seed_text, title=title, msg=True, options=['ext'])\n self.exec_layout(slayout)\n return slayout.is_ext\n\n def pw_layout(self, msg, kind):\n playout = PasswordLayout(None, msg, kind, self.next_button)\n playout.encrypt_cb.setChecked(True)\n self.exec_layout(playout.layout())\n return playout.new_password(), playout.encrypt_cb.isChecked()\n\n @wizard_dialog\n def request_password(self, run_next):\n \"\"\"Request the user enter a new password and confirm it. Return\n the password or None for no password.\"\"\"\n return self.pw_layout(MSG_ENTER_PASSWORD, PW_NEW)\n\n def show_restore(self, wallet, network):\n # FIXME: these messages are shown after the install wizard is\n # finished and the window closed. On MacOSX they appear parented\n # with a re-appeared ghost install wizard window...\n if network:\n def task():\n wallet.wait_until_synchronized()\n if wallet.is_found():\n msg = _(\"Recovery successful\")\n else:\n msg = _(\"No transactions found for this seed\")\n self.synchronized_signal.emit(msg)\n self.synchronized_signal.connect(self.show_message)\n t = threading.Thread(target = task)\n t.daemon = True\n t.start()\n else:\n msg = _(\"This wallet was restored offline. It may \"\n \"contain more addresses than displayed.\")\n self.show_message(msg)\n\n @wizard_dialog\n def confirm_dialog(self, title, message, run_next):\n self.confirm(message, title)\n\n def confirm(self, message, title):\n label = WWLabel(message)\n vbox = QVBoxLayout()\n vbox.addWidget(label)\n self.exec_layout(vbox, title)\n\n @wizard_dialog\n def action_dialog(self, action, run_next):\n self.run(action)\n\n def terminate(self):\n self.accept_signal.emit()\n\n def waiting_dialog(self, task, msg):\n self.please_wait.setText(MSG_GENERATING_WAIT)\n self.refresh_gui()\n t = threading.Thread(target = task)\n t.start()\n t.join()\n\n @wizard_dialog\n def choice_dialog(self, title, message, choices, run_next):\n c_values = [x[0] for x in choices]\n c_titles = [x[1] for x in choices]\n clayout = ChoicesLayout(message, c_titles)\n vbox = QVBoxLayout()\n vbox.addLayout(clayout.layout())\n self.exec_layout(vbox, title)\n action = c_values[clayout.selected_index()]\n return action\n\n def query_choice(self, msg, choices):\n \"\"\"called by hardware wallets\"\"\"\n clayout = ChoicesLayout(msg, choices)\n vbox = QVBoxLayout()\n vbox.addLayout(clayout.layout())\n self.exec_layout(vbox, '')\n return clayout.selected_index()\n\n @wizard_dialog\n def line_dialog(self, run_next, title, message, default, test, warning=''):\n vbox = QVBoxLayout()\n vbox.addWidget(WWLabel(message))\n line = QLineEdit()\n line.setText(default)\n def f(text):\n self.next_button.setEnabled(test(text))\n line.textEdited.connect(f)\n vbox.addWidget(line)\n vbox.addWidget(WWLabel(warning))\n self.exec_layout(vbox, title, next_enabled=test(default))\n return ' '.join(line.text().split())\n\n @wizard_dialog\n def show_xpub_dialog(self, xpub, run_next):\n msg = ' '.join([\n _(\"Here is your master public key.\"),\n _(\"Please share it with your cosigners.\")\n ])\n vbox = QVBoxLayout()\n layout = SeedLayout(xpub, title=msg, icon=False)\n vbox.addLayout(layout.layout())\n self.exec_layout(vbox, _('Master Public Key'))\n return None\n\n def init_network(self, network):\n message = _(\"Electrum communicates with remote servers to get \"\n \"information about your transactions and addresses. The \"\n \"servers all fulfill the same purpose only differing in \"\n \"hardware. In most cases you simply want to let Electrum \"\n \"pick one at random. However if you prefer feel free to \"\n \"select a server manually.\")\n choices = [_(\"Auto connect\"), _(\"Select server manually\")]\n title = _(\"How do you want to connect to a server? \")\n clayout = ChoicesLayout(message, choices)\n self.back_button.setText(_('Cancel'))\n self.exec_layout(clayout.layout(), title)\n r = clayout.selected_index()\n if r == 1:\n nlayout = NetworkChoiceLayout(network, self.config, wizard=True)\n if self.exec_layout(nlayout.layout()):\n nlayout.accept()\n else:\n network.auto_connect = True\n self.config.set_key('auto_connect', True, True)\n\n @wizard_dialog\n def multisig_dialog(self, run_next):\n cw = CosignWidget(2, 2)\n m_edit = QSlider(Qt.Horizontal, self)\n n_edit = QSlider(Qt.Horizontal, self)\n n_edit.setMinimum(2)\n n_edit.setMaximum(15)\n m_edit.setMinimum(1)\n m_edit.setMaximum(2)\n n_edit.setValue(2)\n m_edit.setValue(2)\n n_label = QLabel()\n m_label = QLabel()\n grid = QGridLayout()\n grid.addWidget(n_label, 0, 0)\n grid.addWidget(n_edit, 0, 1)\n grid.addWidget(m_label, 1, 0)\n grid.addWidget(m_edit, 1, 1)\n def on_m(m):\n m_label.setText(_('Require {0} signatures').format(m))\n cw.set_m(m)\n def on_n(n):\n n_label.setText(_('From {0} cosigners').format(n))\n cw.set_n(n)\n m_edit.setMaximum(n)\n n_edit.valueChanged.connect(on_n)\n m_edit.valueChanged.connect(on_m)\n on_n(2)\n on_m(2)\n vbox = QVBoxLayout()\n vbox.addWidget(cw)\n vbox.addWidget(WWLabel(_(\"Choose the number of signatures needed to unlock funds in your wallet:\")))\n vbox.addLayout(grid)\n self.exec_layout(vbox, _(\"Multi-Signature Wallet\"))\n m = int(m_edit.value())\n n = int(n_edit.value())\n return (m, n)\n","repo_name":"lbtcio/lbtc-lightwallet-client","sub_path":"gui/qt/installwizard.py","file_name":"installwizard.py","file_ext":"py","file_size_in_byte":20428,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"3"}
+{"seq_id":"17991360867","text":"from turtle import clear\n\n\ndef menu():\n print(\"Choose action (1 - find person 2 - add person 3 - change data 4 - delete data)\")\n res = int(input())\n return res\n\ndef get_info():\n return input(\"enter information\")\n\ndef new_emp():\n fio = input(\"fio: \")\n date = input(\"date: \")\n work = input(\"position: \")\n salary = input(\"salary: \")\n phone = input(\"Phone: \")\n\n zap = \"/n\" + fio + \" | \" + date + \" | \" + work + \" | \" + salary + \" | \" + phone\n return zap","repo_name":"MishaVer/lesson8","sub_path":"view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42978031114","text":"import copy\nfrom readData import Data\n\n\ndef merge_data(data_join, data, column):\n \"\"\"\n Perform left join on the data objects. Larger data is assigned to left and smaller data is assigned to right.\n Ideally the column to be joined on has unique values to facilitate quick processing of the join.\n If the join is performed on non-unique column the design of the data containment structure needs to be revisited.\n Parameters\n ----------\n data_join : first object to merge (1)\n data : second object to merge (2)\n column : column to perform merge on\n\n Returns\n -------\n data object merged on common column\n\n To-Do: work on selecting certain columns from both data when merging.\n \"\"\"\n # determine the smaller dataset to hash and join\n # set smaller data to right\n if data_join.nrows >= data.nrows:\n data_left = data_join\n data_right = data\n else:\n data_left = data\n data_right = data_join\n\n try:\n col_left = data_left.col_names[column]\n col_right = data_right.col_names[column]\n except KeyError:\n print(\"column {0} not in data\".format(column))\n # choose which column to create index on depending on which object is merged\n merge_data = Data()\n # add column names from data_left to merge_data\n merge_data.col_names = copy.deepcopy(data_left.col_names)\n # use sub_id to count the column number in merged data\n col_id_to_add = []\n # add column names from data_right to merge_data\n for idx, key in enumerate(data_right.col_names):\n\n if data_right.col_names[key] == col_right:\n continue\n sub_id = 1 if data_right.col_names[key] > col_right else 0\n merge_data.col_names[key] = data_right.col_names[key] - sub_id + data_left.ncols\n\n col_id_to_add.append(merge_data.col_names[key])\n\n # add rows to merge data\n # find indexes to merge on for hash join\n group_right, unique_right = data_right._create_index_column(col_right)\n group_left, unique_left = data_left._create_index_column(col_left)\n if unique_right:\n # merge on unique column - copy the left data and loop for each row\n merge_data.data = copy.deepcopy(data_left.data)\n\n rows_right = [group_right[row_val][0] for row_val in merge_data.data[col_left]]\n\n row_to_merge = data_right.get_row_by_num(rows_right, col_right)\n merge_data.data.extend(row_to_merge)\n\n else:\n # non-unique column merge\n for row_id, row_val in enumerate(data_left.data[col_left]):\n if row_id == 0:\n merge_data.data.extend(data_left.get_row_by_num(group_left[row_val]))\n merge_data.data.extend(data_right.get_row_by_num(group_right[row_val], col_right))\n else:\n # non-unique right so many rows are possible\n right_rows = group_right[row_val]\n for right_row_num in right_rows:\n row_to_merge = data_left.get_row_by_num(row_id)+data_right.get_row_by_num(right_row_num, col_right)\n for col_id, col_val in enumerate(row_to_merge):\n merge_data.data[col_id].append(col_val[0])\n\n return merge_data\n","repo_name":"knkumar/insight-submission","sub_path":"insight_testsuite/temp/src/merge_data.py","file_name":"merge_data.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42556260637","text":"from multiprocessing import *\nimport time\n\n\ndef fun1(name=\"OwO\"):\n print(\"test\")\n n=0\n while True:\n if n>=10:\n break\n else:\n time.sleep(2)\n print(name)\n n+=1\n \n\ndef fun2(name=\"OAO\"):\n print(\"test\")\n n=0\n while True:\n if n>=10:\n break\n else:\n time.sleep(3)\n print(name)\n n+=1\n\nif __name__==\"__main__\":\n p1=Process(target=fun1,args=(\"process1\",))\n p2=Process(target=fun2,args=(\"process2\",))\n\n p1.daemon=True\n p2.daemon=True\n \n p1.start()\n p2.start()\n print(\"start\")\n p1.join()\n p2.join()\n print(\"end\")\n","repo_name":"MilkLiver/PythonPratice01","sub_path":"PythonPratice01/AllPython/multiprocesstest.py","file_name":"multiprocesstest.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"4010537870","text":"import torch\n\n\ndef naive_sparse_bmm(sparse_mat, dense_mat, transpose=False):\n if transpose:\n return torch.stack([torch.sparse.mm(s_mat, d_mat.t()) for s_mat, d_mat in zip(sparse_mat, dense_mat)], 0)\n else:\n return torch.stack([torch.sparse.mm(s_mat, d_mat) for s_mat, d_mat in zip(sparse_mat, dense_mat)], 0)\n\ndef sparse_permute(sparse_mat, order):\n values = sparse_mat.coalesce().values()\n indices = sparse_mat.coalesce().indices()\n indices = torch.stack([indices[o] for o in order], 0).contiguous()\n return torch.sparse_coo_tensor(indices, values)\n\n","repo_name":"Candy-CY/Hyperspectral-Image-Classification-Models","sub_path":"SSGRN/utils/sparse_utils.py","file_name":"sparse_utils.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":237,"dataset":"github-code","pt":"3"}
+{"seq_id":"39022961700","text":"import numpy as np\r\nimport csv\r\nimport sys\r\nimport math\r\n \r\nfrom validate import validate\r\n \r\ndef import_data(test_X_file_path):\r\n test_X = np.genfromtxt(test_X_file_path, delimiter = ',', dtype = np.float64, skip_header = 1)\r\n return test_X\r\n \r\n \r\ndef compute_ln_norm_distance(vector1, vector2, n):\r\n diff = np.abs(vector1-vector2)\r\n diff_power_n = np.power(diff,n)\r\n sum_diff = np.sum(diff_power_n)\r\n ans = np.power(sum_diff,1/n)\r\n return ans\r\n \r\ndef find_k_nearest_neighbours(train_X,test_example, k, n):\r\n result_arr = []\r\n index = 0\r\n for var in train_X:\r\n dist = compute_ln_norm_distance(var,test_example,n)\r\n result_arr.append([index,dist])\r\n index += 1\r\n result_arr.sort(key = lambda x: x[1])\r\n nearest_k_pairs = result_arr[:k]\r\n nearest_k_pairs_indices = [var[0] for var in nearest_k_pairs]\r\n nearest_k_pairs_indices = np.array(nearest_k_pairs_indices)\r\n return nearest_k_pairs_indices\r\n \r\n \r\ndef classify_points_using_knn(train_X, train_Y, test_X, k, n):\r\n test_Y = []\r\n for test_element_x in test_X:\r\n k_nn_indices = find_k_nearest_neighbours(train_X,test_element_x, k, n)\r\n k_nn_classes = []\r\n for i in k_nn_indices:\r\n k_nn_classes.append(train_Y[i])\r\n all_diff_classes = list(set(k_nn_classes))\r\n max_count = 0\r\n most_freq_class = -1\r\n for a_class in all_diff_classes:\r\n count = k_nn_classes.count(a_class)\r\n if count > max_count:\r\n max_count = count\r\n most_freq_class = a_class\r\n test_Y.append(most_freq_class)\r\n test_Y = np.array(test_Y)\r\n return test_Y\r\n \r\n \r\n \r\ndef calculate_accuracy(predicted_Y, actual_Y):\r\n tot_matched = 0\r\n for i in range(len(predicted_Y)):\r\n if(predicted_Y[i] == actual_Y[i]):\r\n tot_matched += 1\r\n \r\n accuracy = (tot_matched) / len(predicted_Y)\r\n return accuracy\r\n \r\n \r\ndef get_best_k_using_validation_set(train_X, train_Y, validation_split_percentage, n):\r\n tot_observations = len(train_X)\r\n train_len = math.floor( float(100-validation_split_percentage)/100 *tot_observations )\r\n new_train_X = train_X[0:train_len]\r\n new_train_Y = train_Y[0:train_len]\r\n validation_X = train_X[train_len:]\r\n validation_Y = train_Y[train_len:]\r\n \r\n best_k =- 1\r\n best_accuracy = 0\r\n for k in range(1,train_len):\r\n predicted_Y = classify_points_using_knn(new_train_X, new_train_Y, validation_X, n, k)\r\n accuracy = calculate_accuracy(predicted_Y,validation_Y)\r\n if accuracy > best_accuracy:\r\n best_k = k\r\n best_accuracy = accuracy\r\n return best_k\r\n \r\n \r\n \r\ndef predict_target_values(test_X):\r\n train_X = np.genfromtxt(\"train_X_knn.csv\", delimiter = ',', dtype = np.float64, skip_header = 1)\r\n train_Y = np.genfromtxt(\"train_Y_knn.csv\", delimiter = ',', dtype = np.float64)\r\n k = get_best_k_using_validation_set(train_X, train_Y, 30, n = 2)\r\n pred_Y = classify_points_using_knn(train_X, train_Y, test_X, k, n = 2)\r\n return pred_Y\r\n \r\n \r\n \r\ndef write_to_csv_file(pred_Y, predicted_Y_file_name):\r\n pred_Y = pred_Y.reshape(len(pred_Y), 1)\r\n with open(predicted_Y_file_name, 'w', newline='') as csv_file:\r\n wr = csv.writer(csv_file)\r\n wr.writerows(pred_Y)\r\n csv_file.close()\r\n \r\n \r\ndef predict(test_X_file_path):\r\n test_X = import_data(test_X_file_path)\r\n pred_Y = predict_target_values(test_X)\r\n write_to_csv_file(pred_Y, \"predicted_test_Y_knn.csv\")\r\n \r\n \r\nif __name__ == \"__main__\":\r\n test_X_file_path = sys.argv[1]\r\n predict(test_X_file_path)\r\n validate(test_X_file_path, actual_test_Y_file_path=\"train_Y_knn.csv\")","repo_name":"NkOffiCiAL07/Machine_Learning_Projects_Under_NxtWave","sub_path":"k-nearest neighbors (KNN)/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"46402164318","text":"# A prime number (or a prime) is a natural number greater than 1 that has no positive divisors\n# other than 1 and itself. A natural number greater than 1 that is not a prime number\n# is called a composite number.\n\n# Based on this definition, if we consider the first 10 natural numbers, we can see that 2, 3, 5,\n# and 7 are primes, while 1, 4, 6, 8, 9, 10 are not. In order to have a computer tell you\n# if a number N is prime, you can divide that number by all natural numbers in the range [2, N).\n# If any of those divisions yields zero as a remainder, then the number is not a prime.\n\n# Write a program to find all the primes numbers from 1 to N, where N is an integer given by the user.\n# Write two scripts, one using while and other one using for\n\n# N = 10\n# 2, 3, 5, 7\n\nn = int(input(\"Inserte el número N hasta donde buscaré: \"))\nprimes = []\n\nfor index_1 in range(2, n):\n is_prime = True\n for index_2 in range(2, index_1):\n if index_1 % index_2 == 0:\n is_prime = False\n break\n if is_prime:\n primes.append(index_1)\n\nprint(primes)\n\n# N = 10\n# Iteration 1\n# index_1 --> 2 ; index_2 -->2\n# 2 --> is_prime\n\n# Iteration 2 (index_1)\n# index_1 --> 3\n# Iteration 1 (index_2)\n# index_1 --> 3; index_2 --> 2\n# index_1 % index_2 == 0 --> False\n# is_prime --> True ; 3 --> es primo\n\n# Iteration 3 (index_1)\n# index_1 --> 4\n# Iteration 1 (index_2)\n# index_1 --> 4; index_2 --> 2\n# index_1 % index_2 == 0 --> True\n# is_prime = False; 4 --> no es primo\n\n# Iteration 4 (index_1)\n# index_1 --> 5\n# Iteration 1 (index_2)\n# index_1 --> 5; index_2 --> 2\n# index_1 % index_2 == 0 --> False\n# Iteration 2 (index_2)\n# index_1 --> 5; index_2 --> 3\n# index_1 % index_2 == 0 --> False\n# Iteration 3 (index_2)\n# index_1 --> 5; index_2 --> 4\n# index_1 % index_2 == 0 --> False\n# is_prime = True; 5 --> es primo\n","repo_name":"jotathebest/mintic_class_examples","sub_path":"P27/20-05-2021/exercise_3.py","file_name":"exercise_3.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"}
+{"seq_id":"10498158820","text":"from google.cloud import bigquery\n\n\ndef set_defaults_save_job_config(job_config):\n job_config.write_disposition = bigquery.WriteDisposition.WRITE_APPEND\n job_config.create_disposition = bigquery.CreateDisposition.CREATE_IF_NEEDED\n job_config.time_partitioning = bigquery.TimePartitioning(\n type_=bigquery.TimePartitioningType.DAY,\n # If not set [field], the table is partitioned by pseudo column ``_PARTITIONTIME``.\n field=None\n )\n return job_config\n\n\n\n","repo_name":"Nasajon/mlflow_training_tracking","sub_path":"src/mlflow_training_tracking/helpers/default_settings.py","file_name":"default_settings.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39223555004","text":"import numpy as np\nfrom data_loader import load_data\nfrom utils import image\nfrom . import visualize\ndef synthesize_image_pair(config, split):\n datasets = load_data([split], config)\n ds = datasets[split].batch(config[split]['batch_size'])\n for image_A, image_B, parameters in ds.take(1):\n image_A = image_A.numpy()\n image_B = image_B.numpy()\n parameters = parameters.numpy()\n\n image_C = list(map(lambda x : image.synthesize_image(x[0], x[1], (64, 64), bbox=None, pad_ratio=None),\n zip(image_A.copy(), parameters.copy())))\n image_C = np.array(image_C) \n visualize.show_image([image_A, image_B, image_C])","repo_name":"hukim1112/meta-vision","sub_path":"CNNAlign/debug_tools/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"12799789907","text":"#!/home/wli/env python3\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os.path as osp\nimport openslide\nfrom pathlib import Path\nfrom skimage.filters import threshold_otsu\nimport glob\n#before importing HDFStore, make sure 'tables' is installed by pip3 install tables\nfrom pandas import HDFStore\nfrom openslide.deepzoom import DeepZoomGenerator\nfrom sklearn.model_selection import StratifiedShuffleSplit\nimport cv2 as cv2\nfrom skimage import io\nimport math\nfrom keras.utils.np_utils import to_categorical\n\ntraining_patches_tumor = pd.DataFrame(columns=['patch_path', 'is_tumor'])\ntumor_patch_folder = '/home/wli/Downloads/test/augtumor2'\ntumor_patch_paths = glob.glob(osp.join(tumor_patch_folder, '*.png'))\ntumor_patch = pd.Series(tumor_patch_paths)\ntraining_patches_tumor['patch_path'] = tumor_patch.values\ntraining_patches_tumor['is_tumor'] = 1\n\ntraining_patches_normal = pd.DataFrame(columns=['patch_path', 'is_tumor'])\nnormal_patch_folder_i = '/home/wli/Downloads/test/augnormal'\nnormal_patch_paths_i = glob.glob(osp.join(normal_patch_folder_i, '*.png'))\nnormal_patch_folder_ii = '/home/li-computer1/augnormal'\nnormal_patch_paths_ii = glob.glob(osp.join(normal_patch_folder_ii, '*.png'))\nnormal_patch_paths = normal_patch_paths_i + normal_patch_paths_ii\nnormal_patch = pd.Series(normal_patch_paths)\ntraining_patches_normal['patch_path'] = normal_patch.values\ntraining_patches_normal['is_tumor'] = 0\n\ntraining_patches = pd.concat([training_patches_tumor, training_patches_normal])\n\nvalidation_patches_tumor = pd.DataFrame(columns=['patch_path', 'is_tumor'])\nvtumor_patch_folder = '/home/wli/Downloads/test/validation/augtumor'\nvtumor_patch_paths = glob.glob(osp.join(vtumor_patch_folder, '*.png'))\nvtumor_patch = pd.Series(vtumor_patch_paths)\nvalidation_patches_tumor['patch_path'] = vtumor_patch.values\nvalidation_patches_tumor['is_tumor'] = 1\n\nvalidation_patches_normal = pd.DataFrame(columns=['patch_path', 'is_tumor'])\nvnormal_patch_folder_i = '/home/wli/Downloads/test/validation/augnormal'\nvnormal_patch_paths_i = glob.glob(osp.join(vnormal_patch_folder_i, '*.png'))\nvnormal_patch_folder_ii = '/home/li-computer1/augnormal_validation'\nvnormal_patch_paths_ii = glob.glob(osp.join(vnormal_patch_folder_ii, '*.png'))\nvnormal_patch_paths = vnormal_patch_paths_i + vnormal_patch_paths_ii\nvnormal_patch = pd.Series(vnormal_patch_paths)\nvalidation_patches_normal['patch_path'] = vnormal_patch.values\nvalidation_patches_normal['is_tumor'] = 0\nvalidation_patches = pd.concat([validation_patches_tumor, validation_patches_normal])\n\ndef gen_imgs(samples, batch_size, shuffle=True):\n\n num_samples = len(samples)\n while 1:\n if shuffle:\n samples = samples.sample(frac=1) # if frac = 1 will organized list randomly\n\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples.iloc[offset:offset+batch_size]\n images = []\n labels = []\n for _, batch_sample in batch_samples.iterrows():\n img = io.imread(batch_sample.patch_path)\n img = img[:,:,:3]\n label = batch_sample['is_tumor']\n\n images.append(np.array(img))\n labels.append(label)\n\n X_train = np.array(images)\n y_train = np.array(labels)\n y_train = to_categorical(y_train, num_classes=2)\n\n yield X_train, y_train\n\n# -*- coding: utf-8 -*-\n\"\"\"Inception V1 model for Keras.\nNote that the input preprocessing function is different from the the VGG16 and ResNet models (same as Xception).\nAlso that (currently) the output predictions are for 1001 classes (with the 0 class being 'background'), \nso require a shift compared to the other models here.\n# Reference\n- [Going deeper with convolutions](http://arxiv.org/abs/1409.4842v1)\n\"\"\"\nimport warnings\nimport numpy as np\nfrom keras.models import Model\nfrom keras import layers\nfrom keras.layers import Input\nfrom keras.layers import Conv2D\nfrom keras.layers import Activation\nfrom keras.layers import BatchNormalization\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import AveragePooling2D\nfrom keras.layers import Dropout\nfrom keras.layers import Flatten\nfrom keras.layers import GlobalAveragePooling2D\nfrom keras.layers import GlobalMaxPooling2D\nfrom keras.optimizers import SGD\nfrom keras.engine.topology import get_source_inputs\nfrom keras.utils.layer_utils import convert_all_kernels_in_model\nfrom keras.utils.data_utils import get_file\nfrom keras import backend as K\nfrom keras.applications.imagenet_utils import decode_predictions\nfrom keras.applications.imagenet_utils import _obtain_input_shape\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.preprocessing import image\nfrom keras.regularizers import l2\nWEIGHTS_PATH = ''\nWEIGHTS_PATH_NO_TOP = ''\n# conv2d_bn is similar to (but updated from) inception_v3 version\ndef conv2d_bn(x,\n filters,\n num_row,\n num_col,\n padding='same',\n strides=(1, 1),\n normalizer= False,\n activation='relu',\n name=None):\n \"\"\"Utility function to apply conv + BN.\n Arguments:\n x: input tensor.\n filters: filters in `Conv2D`.\n num_row: height of the convolution kernel.\n num_col: width of the convolution kernel.\n padding: padding mode in `Conv2D`.\n strides: strides in `Conv2D`.\n name: name of the ops; will become `name + '_conv'`\n for the convolution, `name + '_bn'` for the\n batch norm layer and `name + '_act'` for the\n activation layer.\n Returns:\n Output tensor after applying `Conv2D` and `BatchNormalization`.\n \"\"\"\n if name is not None:\n conv_name = name + '_conv'\n bn_name = name + '_bn'\n act_name = name + '_act'\n else:\n conv_name = None\n bn_name = None\n act_name = None\n if K.image_data_format() == 'channels_first':\n bn_axis = 1\n else:\n bn_axis = 3\n x = Conv2D(\n filters, (num_row, num_col),\n strides=strides, padding=padding,\n use_bias=False, name=conv_name, kernel_regularizer=l2(0.0005))(x)\n if normalizer:\n x = BatchNormalization(axis=bn_axis, scale=False, name=bn_name)(x)\n if activation:\n x = Activation(activation, name=act_name)(x)\n return x\n \n# Convenience function for 'standard' Inception concatenated blocks\ndef concatenated_block(x, specs, channel_axis, name):\n (br0, br1, br2, br3) = specs # ((64,), (96,128), (16,32), (32,))\n \n branch_0 = conv2d_bn(x, br0[0], 1, 1, name=name+\"_Branch_0_a_1x1\")\n branch_1 = conv2d_bn(x, br1[0], 1, 1, name=name+\"_Branch_1_a_1x1\")\n branch_1 = conv2d_bn(branch_1, br1[1], 3, 3, name=name+\"_Branch_1_b_3x3\")\n branch_2 = conv2d_bn(x, br2[0], 1, 1, name=name+\"_Branch_2_a_1x1\")\n branch_2 = conv2d_bn(branch_2, br2[1], 3, 3, name=name+\"_Branch_2_b_3x3\")\n branch_3 = MaxPooling2D( (3, 3), strides=(1, 1), padding='same', name=name+\"_Branch_3_a_max\")(x) \n branch_3 = conv2d_bn(branch_3, br3[0], 1, 1, name=name+\"_Branch_3_b_1x1\")\n x = layers.concatenate(\n [branch_0, branch_1, branch_2, branch_3],\n axis=channel_axis,\n name=name+\"_Concatenated\")\n return x\ndef InceptionV1(include_top=True,\n weights= None,\n input_tensor=None,\n input_shape=None,\n pooling=None,\n classes=2):\n \"\"\"Instantiates the Inception v1 architecture.\n This architecture is defined in:\n Going deeper with convolutions\n Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed,\n Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich.\n http://arxiv.org/abs/1409.4842v1\n \n Optionally loads weights pre-trained\n on ImageNet. Note that when using TensorFlow,\n for best performance you should set\n `image_data_format=\"channels_last\"` in your Keras config\n at ~/.keras/keras.json.\n The model and the weights are compatible with both\n TensorFlow and Theano. The data format\n convention used by the model is the one\n specified in your Keras config file.\n Note that the default input image size for this model is 224x224.\n Arguments:\n include_top: whether to include the fully-connected\n layer at the top of the network.\n weights: one of `None` (random initialization)\n or \"imagenet\" (pre-training on ImageNet).\n input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)\n to use as image input for the model.\n input_shape: optional shape tuple, only to be specified\n if `include_top` is False (otherwise the input shape\n has to be `(224, 224, 3)` (with `channels_last` data format)\n or `(3, 224, 224)` (with `channels_first` data format).\n It should have exactly 3 inputs channels,\n and width and height should be no smaller than 139.\n E.g. `(150, 150, 3)` would be one valid value.\n pooling: Optional pooling mode for feature extraction\n when `include_top` is `False`.\n - `None` means that the output of the model will be\n the 4D tensor output of the\n last convolutional layer.\n - `avg` means that global average pooling\n will be applied to the output of the\n last convolutional layer, and thus\n the output of the model will be a 2D tensor.\n - `max` means that global max pooling will\n be applied.\n classes: optional number of classes to classify images\n into, only to be specified if `include_top` is True, and\n if no `weights` argument is specified.\n Returns:\n A Keras model instance.\n Raises:\n ValueError: in case of invalid argument for `weights`,\n or invalid input shape.\n \"\"\"\n if weights not in {'imagenet', None}:\n raise ValueError('The `weights` argument should be either '\n '`None` (random initialization) or `imagenet` '\n '(pre-training on ImageNet).')\n if weights == 'imagenet' and include_top and classes != 1001:\n raise ValueError('If using `weights` as imagenet with `include_top`'\n ' as true, `classes` should be 1001')\n # Determine proper input shape\n input_shape = _obtain_input_shape(\n input_shape,\n #default_size=299,\n default_size=224,\n min_size=139,\n data_format=K.image_data_format(),\n include_top=include_top)\n if input_tensor is None:\n img_input = Input(shape=input_shape)\n else:\n img_input = Input(tensor=input_tensor, shape=input_shape)\n if K.image_data_format() == 'channels_first':\n channel_axis = 1\n else:\n channel_axis = 3\n # 'Sequential bit at start'\n x = img_input\n x = conv2d_bn(x, 64, 7, 7, strides=(2, 2), padding='same', name='Conv2d_1a_7x7') \n \n x = MaxPooling2D((3, 3), strides=(2, 2), padding='same', name='MaxPool_2a_3x3')(x) \n \n x = conv2d_bn(x, 64, 1, 1, strides=(1, 1), padding='same', name='Conv2d_2b_1x1') \n x = conv2d_bn(x, 192, 3, 3, strides=(1, 1), padding='same', name='Conv2d_2c_3x3') \n \n x = MaxPooling2D((3, 3), strides=(2, 2), padding='same', name='MaxPool_3a_3x3')(x) \n \n # Now the '3' level inception units\n x = concatenated_block(x, (( 64,), ( 96,128), (16, 32), ( 32,)), channel_axis, 'Mixed_3b')\n x = concatenated_block(x, ((128,), (128,192), (32, 96), ( 64,)), channel_axis, 'Mixed_3c')\n x = MaxPooling2D((3, 3), strides=(2, 2), padding='same', name='MaxPool_4a_3x3')(x) \n # Now the '4' level inception units\n x = concatenated_block(x, ((192,), ( 96,208), (16, 48), ( 64,)), channel_axis, 'Mixed_4b')\n x = concatenated_block(x, ((160,), (112,224), (24, 64), ( 64,)), channel_axis, 'Mixed_4c')\n x = concatenated_block(x, ((128,), (128,256), (24, 64), ( 64,)), channel_axis, 'Mixed_4d')\n x = concatenated_block(x, ((112,), (144,288), (32, 64), ( 64,)), channel_axis, 'Mixed_4e')\n x = concatenated_block(x, ((256,), (160,320), (32,128), (128,)), channel_axis, 'Mixed_4f')\n x = MaxPooling2D((2, 2), strides=(2, 2), padding='same', name='MaxPool_5a_2x2')(x) \n # Now the '5' level inception units\n x = concatenated_block(x, ((256,), (160,320), (32,128), (128,)), channel_axis, 'Mixed_5b')\n x = concatenated_block(x, ((384,), (192,384), (48,128), (128,)), channel_axis, 'Mixed_5c')\n \n if include_top:\n # Classification block\n \n # 'AvgPool_0a_7x7'\n x = AveragePooling2D((7, 7), strides=(1, 1), padding='valid')(x) \n \n # 'Dropout_0b'\n x = Dropout(0.5)(x) # slim has keep_prob (@0.8), keras uses drop_fraction\n \n #logits = conv2d_bn(x, classes+1, 1, 1, strides=(1, 1), padding='valid', name='Logits',\n # normalizer=False, activation=None, ) \n \n # Write out the logits explictly, since it is pretty different\n x = Conv2D(classes, (1, 1), strides=(1,1), padding='valid', use_bias=True, name='Logits')(x)\n \n x = Flatten(name='Logits_flat')(x)\n #x = x[:, 1:] # ??Shift up so that first class ('blank background') vanishes\n # Would be more efficient to strip off position[0] from the weights+bias terms directly in 'Logits'\n \n x = Activation('softmax', name='Predictions')(x)\n else:\n if pooling == 'avg':\n x = GlobalAveragePooling2D(name='global_pooling')(x)\n elif pooling == 'max':\n x = GlobalMaxPooling2D( name='global_pooling')(x)\n # Ensure that the model takes into account\n # any potential predecessors of `input_tensor`.\n if input_tensor is not None:\n inputs = get_source_inputs(input_tensor)\n else:\n inputs = img_input\n \n # Finally : Create model\n model = Model(inputs, x, name='inception_v1')\n \n # LOAD model weights\n if weights == 'imagenet':\n if K.image_data_format() == 'channels_first':\n if K.backend() == 'tensorflow':\n warnings.warn('You are using the TensorFlow backend, yet you '\n 'are using the Theano '\n 'image data format convention '\n '(`image_data_format=\"channels_first\"`). '\n 'For best performance, set '\n '`image_data_format=\"channels_last\"` in '\n 'your Keras config '\n 'at ~/.keras/keras.json.')\n if include_top:\n weights_path = get_file(\n 'inception_v1_weights_tf_dim_ordering_tf_kernels.h5',\n WEIGHTS_PATH,\n cache_subdir='models',\n md5_hash='723bf2f662a5c07db50d28c8d35b626d')\n else:\n weights_path = get_file(\n 'inception_v1_weights_tf_dim_ordering_tf_kernels_notop.h5',\n WEIGHTS_PATH_NO_TOP,\n cache_subdir='models',\n md5_hash='6fa8ecdc5f6c402a59909437f0f5c975')\n model.load_weights('~/Downloads/model0912googlenet.h5')\n if K.backend() == 'theano':\n convert_all_kernels_in_model(model) \n \n return model\n\n\n\n\nmodel = InceptionV1()\n\n#sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\nsgd = SGD(lr=0.01, decay=0, momentum=0.9, nesterov=True)\n\nmodel.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])\n\nfilepath=\"\\home\\wli\\Downloads\\googlenet0917-{epoch:02d}-{val_acc:.2f}.hdf5\"\n\n\nmodel_checkpoint = ModelCheckpoint(filepath, monitor='val_acc',verbose=1, save_best_only=True)\n\nBATCH_SIZE = 32\nN_EPOCHS = 5\n\nfrom datetime import datetime\n\ntrain_generator = gen_imgs(training_patches, BATCH_SIZE)\nvalidation_generator = gen_imgs(validation_patches, BATCH_SIZE)\n\n#train neural network\n\ntrain_start_time = datetime.now()\n\n\ndef step_decay_schedule(initial_lr, decay_factor, step_size): \n '''\n Wrapper function to create a LearningRateScheduler with step decay schedule.\n '''\n def schedule(epoch):\n return initial_lr * (decay_factor ** np.floor(epoch/step_size))\n \n return LearningRateScheduler(schedule)\n\nlr_sched = step_decay_schedule(initial_lr=0.01, decay_factor=0.5, step_size=1)\n\n\nhistory=model.fit_generator(train_generator, np.ceil(len(training_patches) / BATCH_SIZE),\n validation_data=validation_generator,\n validation_steps=np.ceil(len(validation_patches) / BATCH_SIZE),\n epochs=N_EPOCHS, callbacks=[model_checkpoint, lr_sched])\n\ntrain_end_time = datetime.now()\nprint(\"Model training time: %.1f minutes\" % ((train_end_time - train_start_time).seconds / 60,))\n\nmodel.save('model0912googlenet.h5')\n\nmodel_json = model.to_json()\nwith open(\"modelgooglenet0912.json\", \"w\") as json_file:\n json_file.write(model_json)\n# serialize weights to HDF5\nmodel.save_weights(\"googlenetweight.h5\")\nprint(\"Saving model to disk\")\n# \"Accuracy\"\nfig1 = plt.figure(figsize=(12,8))\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()\nfig1.savefig('./Accuracy_plot_googlenet.png')\n#plt.imsave('accuracy_plot_googlenet', accu)\nplt.close(fig1)\n# \"Loss\"\nfig2 = plt.figure(figsize=(12,8))\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()\nplt2.savefig('./Loss_plot_googlenet.png')\n#plt.imsave('Loss_plot_googlenet',loss)\n#np.save('history_googlenet', history.history)\n#import json\n# Get the dictionary containing each metric and the loss for each epoch\n#history_dict = history.history\n# Save it under the form of a json file\n#json.dump(history_dict, open('./', 'w'))\n#print(history_dict['loss'][49])\n","repo_name":"3dimaging/DeepLearningCamelyon","sub_path":"3 - Training Neural Network/GoogleNet-V1-Training.py","file_name":"GoogleNet-V1-Training.py","file_ext":"py","file_size_in_byte":18185,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"3"}
+{"seq_id":"74840845201","text":"#==================================================================================#\n# Author : Davide Mariani # \n# University : Birkbeck College, University of London # \n# Programme : Msc Data Science #\n# Script Name : features_utils.py #\n# Description : utils for feature engineering #\n# Version : 0.1 #\n#==================================================================================#\n# This file contains several functions to add, process and enhance features #\n#==================================================================================#\n\n#importing main modules\nimport pandas as pd\nimport numpy as np\nimport datetime\nfrom scipy import stats\n\n\n#utility functions\ndef _xor0(x):\n \"\"\"\n This function replaces nans with 0\n \"\"\"\n return 0. if np.isnan(x) else x\nxor0 = np.vectorize(_xor0)\n\n\ndef we_share(lst):\n \"\"\"\n This function return the ratio of weekend payments for an instrument. nan if there's no weekend payment.\n \"\"\"\n\n res = np.nan\n if len(lst)==0:\n return res\n\n wec = 0\n datec = 0\n for x in lst:\n if not pd.isnull(x):\n datec+=1\n if x.weekday()>4:\n wec+=1\n if datec>0:\n res=wec/datec\n return res\n\n\ndef select_payment(x):\n \"\"\"\n This function is used to select the payments in a time snapshot, where we need to exlude payments executed after the reportdate of that particular snapshot.\n It is meant to be used inside an 'apply' with axis=1 to be rowwise.\n \"\"\"\n payments = x.payment_amount\n last_item = int(x.tmp_dates_to_count)\n return payments[:last_item]\n\ndef select_date(x):\n \"\"\"\n This function is used to select the payment dates in a time snapshot, where we need to exlude dates happening after the reportdate of that particular snapshot.\n It is meant to be used inside an 'apply' with axis=1 to be rowwise.\n \"\"\"\n dates = x.payment_date\n last_item = int(x.tmp_dates_to_count)\n return dates[:last_item]\n\ndef add_main_features(inst, ReportDate, impthr=0.009, imp2thr=0.04, purthr=0.009, dedthr=0.009, prefix='', date_debtor_sort=False):\n \"\"\"\n This function add the main features to an input instruments dataframe, both in the general case and the snapshots creation systems.\n inst: instruments dataframe\n impthr: threshold for impairment1\n imp2thr: threshold for impairment2\n prefix: prefix to add to new columns (and to read the correct columns from different snapshots depending on their name)\n\n if prefix=='' it assumes that the input dataframe is the main one (not for snapshots purpose)\n \"\"\"\n\n print('Addding main network features for snapshot with date < {}'.format(ReportDate))\n\n xor0 = np.vectorize(_xor0)\n\n #-----------------------------------------------------------------\n # Fields not affected (or not 'affectable') from snapshots systems\n #-----------------------------------------------------------------\n if prefix=='':\n #define the discharge loss as difference between invoice_amount and discharge amount...\n inst[prefix+\"discharge_loss\"] = xor0(inst[\"invoice_amount\"] - inst[\"discharge_amount\"])\n inst.loc[pd.isnull(inst[\"discharge_amount\"]), \"discharge_loss\"] = 0. #...but it is 0 for NaN discharge_amount\n\n #define the presence of impairment2 as discharge_loss>0.009\n #inst[prefix+\"has_impairment2\"] = (inst[\"discharge_loss\"]>impthr) & (inst[\"invoice_date\"]purthr)\n\n #this indicates if an instrument has a deduction amount\n inst[prefix+\"has_deduction\"] = inst[\"deduction_amount\"].apply(lambda x: x>dedthr)\n\n #discharge amount\n inst[prefix+\"has_discharge\"] = inst[\"discharge_amount\"]>0.001\n\n #-----------------------------------------------------------------\n # Fields affected from snapshots systems\n #-----------------------------------------------------------------\n\n #snapshot marker for selection\n if prefix!='':\n inst[prefix]=inst[\"invoice_date\"]<=ReportDate\n\n #amount of the last payment for a certain instrument\n if prefix=='':\n inst[\"last_payment_amount\"] = xor0(inst[\"payment_amount\"].apply(lambda x: x[-1]))\n else:\n inst.loc[inst[prefix],'tmp_dates_to_count'] = inst.loc[inst[prefix],\"payment_date\"].apply(lambda x:sum(pd.Series(x)0 else np.nan)) #last payment amount in this particular snapshot\n inst.loc[inst[prefix],prefix+\"last_payment_date\"] = inst.loc[inst[prefix],prefix+\"payment_date\"].apply(lambda x:x[-1] if len(x)>0 else pd.NaT)\n\n #sum of all the distinct entries for a single instrument\n if prefix=='':\n inst[\"total_repayment\"] = xor0(inst[\"payment_amount\"].apply(lambda x: sum(list(set(x))))) #sum of distinct entries\n else:\n inst.loc[inst[prefix],prefix+\"total_repayment\"] = xor0(inst.loc[inst[prefix],prefix+\"payment_amount\"].apply(lambda x: sum(list(set(x))))) #sum of distinct entries\n\n #instrument which are open and more than 90 days past the due date \n if prefix=='': #base case without snapshots\n inst[prefix+\"is_pastdue90\"] = inst[\"due_date\"].apply(lambda x: (ReportDate - x).days > 90) & (inst[\"document_status\"]==\"offen\")\n else:\n inst.loc[inst[prefix],prefix+\"is_pastdue90\"] = inst.loc[inst[prefix],\"due_date\"].apply(lambda x: (ReportDate - x).days > 90) & (inst.loc[inst[prefix],prefix+\"total_repayment\"] 180) & (inst[\"document_status\"]==\"offen\")\n else:\n inst.loc[inst[prefix],prefix+\"is_pastdue180\"] = inst.loc[inst[prefix],\"due_date\"].apply(lambda x: (ReportDate - x).days > 180) & (inst.loc[inst[prefix],prefix+\"total_repayment\"]0.009\n inst[prefix+\"has_impairment1\"] = (inst[\"deduction_amount\"]>impthr) & (inst[\"invoice_date\"] None:\n user_input = input(\"what's the time?: \")\n print(meal_from_time(convert(user_input)))\n\n# breakfast between 7:00 8:00\n# lunch between 12:00 and 13:00\n# dinner between 18:00 and 19:00\ndef meal_from_time(hour: float) -> str:\n if hour >= 7.0 and hour <= 8.0:\n return \"breakfast\"\n elif hour >= 12.0 and hour <= 13.0:\n return \"lunch\"\n elif hour >= 18.0 and hour <= 19.0:\n return \"dinner\"\n else:\n return \"\"\n\n\n# #:## or ##:##\n# 7:30 -> 7.5\ndef twenty_four_hour_to_float(time: str):\n hour, minute = time.split(\":\")\n return float(hour) + minute_to_hour(int(minute))\n\ndef minute_to_hour(minutes) -> float:\n return minutes / 60\n\ndef am_pm_to_float(time: str) -> float:\n time, am_pm = time.split(\" \")\n if am_pm == \"a.m.\":\n hour, minute = time.split(\":\")\n hour = float(hour)\n minute = int(minute)\n if hour == 12.0:\n return 0.0 + minute_to_hour(minute)\n else:\n return hour + minute_to_hour(minute)\n elif am_pm == \"p.m.\":\n hour, minute = time.split(\":\")\n hour = float(hour)\n minute = int(minute)\n if hour == 12.0:\n return 0.0 + 12.0 + minute_to_hour(minute)\n else:\n return hour + 12.0 + minute_to_hour(minute)\n else:\n print(\"error: couldn't find 'a.m.' or 'p.m.'\")\n\ndef is_am_pm(time: str) -> bool:\n return len(time.split(\" \")) == 2\n\ndef convert(time: str):\n if is_am_pm(time):\n return am_pm_to_float(time)\n else:\n return twenty_four_hour_to_float(time)\n\n\nif __name__ == '__main__':\n main()","repo_name":"meleeweapon/hardvard_cs50p_my_files","sub_path":"harvard_cs50p/problem_sets/problem_set_1/meal_time.py","file_name":"meal_time.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40081662312","text":"import sympy.ntheory as nt\n\ndef isTruncatablePrime(num, dir = 1):\n numArr = [int(i) for i in str(num)[::dir]]\n for n in range(len(numArr)):\n val = sum([val * 10**(ind) for ind, val in enumerate(numArr[n:][::-dir])])\n if not nt.isprime(val):\n return False\n return True\n\ndef isBiTruncatablePrime(num):\n return isTruncatablePrime(num) and isTruncatablePrime(num, -1)\n\ndef getTruncatablePrimes():\n truncatablePrimes = set()\n num = 9 # No single digit primes are considered truncatable primes\n while len(truncatablePrimes) < 11:\n num += 2\n if not nt.isprime(num):\n continue\n if isBiTruncatablePrime(num):\n truncatablePrimes.add(num)\n\n return truncatablePrimes \n\ntp = getTruncatablePrimes()\nprint(tp)\nprint(sum(tp))","repo_name":"portobello-boy/ProjectEuler","sub_path":"001-050/Problem037/prob37.py","file_name":"prob37.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"23577926056","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import logout, login\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse\n\nfrom custom_auth.models import CustomUser\nfrom custom_auth.forms import RegistrationForm\n\nfrom tickets.models import Visitor\nfrom camping.models import Reservation, Spot, Tent\n\n\ndef register(request):\n if request.method == 'POST':\n form = RegistrationForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n if user.pk is not None:\n return redirect('/accounts/profile/')\n return render(request, 'register.html', {'form': form})\n else:\n form = RegistrationForm()\n args = {'form': form}\n return render(request, 'register.html', args)\n\n\n@login_required\ndef profile(request):\n user = request.user\n tickets = list(Visitor.objects.filter(user=request.user))\n campings = list()\n\n if not tickets:\n tickets = None\n else:\n for visitor in tickets:\n reservations = Reservation.objects.filter(visitor=visitor)\n\n for reservation in reservations:\n res_visitor = reservation.visitor\n tent = None\n camp_spot = Spot.objects.get(id=reservation.spot_id)\n if reservation.tent_id is not None:\n tent = Tent.objects.get(id=reservation.tent_id)\n \n campings.append({'spot' : camp_spot, 'tent' : None, 'visitor': res_visitor})\n\n if not campings:\n campings = None\n\n args = {'user': user, 'tickets': tickets, 'campings' : campings}\n\n return render(request, 'profile.html', args)\n\n\ndef logout_user(request):\n logout(request)\n args = {}\n return redirect(reverse('index'))\n","repo_name":"VelinSE/Mascarada-Django","sub_path":"mascarada/custom_auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19915337631","text":"#This code finds the average mutation per genome based on ALL the reads. (Not Individually)\n#Part 1, Find number B\n\nk = 25\n\nbuniquekmers = open(\"dump25mercounts.fa\", \"r\")\nbunique = buniquekmers.read()\nsplitbunique = bunique.split(\">\")\n\ntotalbkmers = []\n\nfor i in splitbunique[1:len(splitbunique)]:\n twtwo = i.split()\n totalbkmers.append(twtwo[1])\n\ntotalbkmerslength = len(splitbunique)\n\n#Part 2, find number A\n\nauniquekmers = open(\"25mersall.fa\", \"r\")\naunique = auniquekmers.read()\nsplitaunique = aunique.split(\">\")\n\ntotalakmers = []\n\ntotalakmerslength = len(splitaunique)\n\nfor i in splitaunique[1:len(splitaunique)]:\n twtwo = i.split()\n totalakmers.append(twtwo[1])\n\nkmersbymutations = totalakmerslength-totalbkmerslength\ndistinctmutations = kmersbymutations/k\naveragemutationpergenome = distinctmutations/3970\nprint(averagemutationpergenome)\nprint(distinctmutations)\n","repo_name":"chenmo8/K-MerCovid-19","sub_path":"parseformutations.py","file_name":"parseformutations.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37382502858","text":"from Baralho import *\nfrom time import sleep\nfrom Jogador import Jogador\n\nclass Batalha:\n def __init__(self) -> None:\n self.__baralho = Baralho()\n self.__j1 = None\n self.__j2 = None\n self.__cont_rodadas = 1\n self.__limite_rodadas = 100\n self.__cartas_acumuladas = []\n self.__vencedor_rodada = None\n self.__vencedor_jogo = None\n \n def configurar_jogo(self):\n if self.__j1 == None and self.__j2 == None:\n self.set_jogadores()\n \n self.__baralho = self.__baralho.montar()\n \n decisao = input(\"Deseja ver as cartas do baralho? (S/N) \").upper()\n if decisao == 'S':\n self.__baralho.imprimir()\n \n self.entregar_cartas()\n \n input(\"Pressione ENTER para começar o jogo.\")\n \n self.iniciar_jogo()\n \n def set_jogadores(self) -> None:\n print(\"\\n======= Definindo Jogadores =======\\n\")\n self.__j1 = Jogador(input(\"Digite o nome do jogador 1: \"))\n print(f'\\nJogador 1 definido como: {self.__j1.get_nome()}\\n')\n self.__j2 = Jogador(input(\"Digite o nome do jogador 2: \"))\n print(f'\\nJogador 2 definido como: {self.__j2.get_nome()}\\n')\n print(\"======= Jogadores definidos com Sucesso! =======\\n\")\n \n def entregar_cartas(self) -> None:\n metade_baralho = 52 // 2\n jogadores = [self.__j1, self.__j2]\n input(\"Pressione ENTER para Entregar as cartas.\")\n for jogador in jogadores:\n for i in range(3):\n print(f\"\\nEntregando as cartas para {jogador.get_nome()}...\")\n sleep(0.5)\n for carta in range(metade_baralho):\n try:\n jogador.set_deck(self.__baralho.desempilhar())\n except IndexError:\n raise BaralhoException('O baralho está vazio. Não há cartas para dividir')\n print(f\"\\n======= Cartas entregues para {jogador.get_nome()} =======\")\n \n decisao = input(f\"\\nDeseja ver as cartas dos jogadores? (S/N) \").upper()\n print(\"\\n\")\n if decisao == 'S':\n for jogador in jogadores:\n print(f\"{jogador.get_nome()} tem {jogador.get_tamanho_deck()} cartas, seu deck:\")\n jogador.imprimir_deck()\n \n def iniciar_jogo(self) -> None:\n while not self.__vencedor_jogo:\n self.duelo()\n self.__vencedor_jogo = self.verificar_vencedor_jogo()\n if self.__cont_rodadas > self.__limite_rodadas:\n print(\"Jogo Finalizando por execução de 100 rodadas, o vencedor será definido pelo maior número de cartas restantes.\")\n break\n \n self.fim_jogo()\n \n\n def duelo(self):\n carta_j1, carta_j2 = self.get_cartas_jogadas()\n \n self.imprimir_duelo(carta_j1, carta_j2)\n \n self.comparar_cartas(carta_j1, carta_j2)\n \n print(f'==== {self.__vencedor_rodada.get_nome()} venceu a rodada! ====\\n')\n \n for carta in self.__cartas_acumuladas:\n self.__vencedor_rodada.guardar_cartas(carta)\n \n print(f\"{self.__vencedor_rodada.get_nome()} ganhou as {len(self.__cartas_acumuladas)} cartas que foram acumuladas:\\n\")\n for carta in self.__cartas_acumuladas:\n print(f\"{carta} \", end=\" \\n\") \n \n self.__cartas_acumuladas.clear() # Limpa a lista de cartas acumuladas para a próxima rodada\n\n self.__cont_rodadas += 1\n \n self.__vencedor_rodada = None\n input(\"\\nPressione ENTER para continuar o jogo.\") \n \n def get_cartas_jogadas(self):\n carta_jogador1 = self.__j1.jogar_carta()\n carta_jogador2 = self.__j2.jogar_carta()\n \n self.__cartas_acumuladas.append(carta_jogador1)\n self.__cartas_acumuladas.append(carta_jogador2)\n \n return carta_jogador1, carta_jogador2\n \n def imprimir_duelo(self, carta1: Carta, carta2: Carta):\n print(f'\\n===== Rodada {self.__cont_rodadas} =====\\n')\n print(f'({self.__j1.get_nome()}: {self.__j1.get_tamanho_deck()} cartas)', end=' ')\n print(f'| {carta1} | X | {carta2} |', end=' ')\n print(f'({self.__j2.get_nome()}: {self.__j2.get_tamanho_deck()} cartas)\\n')\n \n def comparar_cartas(self, carta1: Carta, carta2: Carta):\n '''\n Define o vencedor da rodada de acordo com a maior carta. (peso)\n '''\n if carta1.get_peso > carta2.get_peso:\n self.__vencedor_rodada = self.__j1\n elif carta2.get_peso > carta1.get_peso:\n self.__vencedor_rodada = self.__j2\n else:\n self.rodada_empate()\n \n def rodada_empate(self):\n '''\n Se ocorrer um empate, o programa pede mais uma rodada, compara as cartas, até que um dos jogadores desempatem o jogo, se isso não ocorrer, o programa chama o método roda_empate() recursivamente\n '''\n print(f'Rodada {self.__cont_rodadas} empatada!\\n')\n print(f\"As cartas acumularão até um desempate, cartas acumuladas atualmente: \\n\")\n \n for carta in self.__cartas_acumuladas:\n print(carta)\n print()\n input(\"Pressione ENTER para continuar o empate.\")\n \n carta_j1, carta_j2 = self.get_cartas_jogadas()\n \n self.imprimir_duelo(carta_j1, carta_j2)\n \n self.comparar_cartas(carta_j1, carta_j2)\n \n def verificar_vencedor_jogo(self):\n if self.__j1.get_tamanho_deck() == 0: \n return self.__j2 \n elif self.__j2.get_tamanho_deck() == 0:\n return self.__j1\n return None \n \n def fim_jogo(self):\n \n if(self.__vencedor_jogo is None):\n if self.__j1.get_tamanho_deck() > self.__j2.get_tamanho_deck():\n self.__vencedor_jogo = self.__j1\n else:\n self.__vencedor_jogo = self.__j2 \n \n print(f'\\n===== Fim de Jogo! =====\\n')\n print(f'({self.__j1.get_nome()}: {self.__j1.get_tamanho_deck()} cartas)')\n print(f'({self.__j2.get_nome()}: {self.__j2.get_tamanho_deck()} cartas)\\n')\n \n print(f'{self.__vencedor_jogo.get_nome()} VENCEU O JOGO!\\n')\n \n decisao = input(\"Jogo encerrado! Deseja jogar novamente? (S/N)\").upper()\n \n while decisao != 'S' and decisao != 'N':\n decisao = input(\"\\nOpção Inválida. Deseja jogar novamente? (S/N)\").upper() \n \n if decisao == 'S':\n self.resetar_jogo()\n \n else:\n print(\"\\n==== Obrigado por jogar! ====\")\n \n def resetar_jogo(self):\n self.__cont_rodadas = 1\n self.__cartas_acumuladas = []\n self.__vencedor_rodada = None\n self.__vencedor_jogo = None\n self.__baralho.limpar_pilha()\n self.__baralho = Baralho()\n self.__j1.limpar_deck()\n self.__j2.limpar_deck()\n self.configurar_jogo()","repo_name":"paulosys/baralho-batalha","sub_path":"Batalha.py","file_name":"Batalha.py","file_ext":"py","file_size_in_byte":7001,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30118174077","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\nfrom dm.skills.Hero._hero import HeroSkill\nfrom utilities import CooldownType, SkillEffect\n\nif TYPE_CHECKING:\n from dm.core.contexts import AttackContext\n from dm.core.game.game import DMGame\n from dm.core.objects.unit import DMUnit\n################################################################################\n\n__all__ = (\"TheRuinOfEvil\",)\n\n################################################################################\nclass TheRuinOfEvil(HeroSkill):\n\n def __init__(self, state: DMGame, parent: DMUnit = None):\n\n super().__init__(\n state, parent,\n _id=\"SKL-389\",\n name=\"The Ruin of Evil\",\n description=(\n \"Inflict 350 (+3.5*ATK) damage to all enemies in the room and \"\n \"immediately kill them at a low chance (10%). This attack \"\n \"cannot be missed or absorbed.\"\n ),\n rank=8,\n cooldown=CooldownType.RoomWide,\n effect=SkillEffect(base=350, scalar=3.5)\n )\n\n################################################################################\n def execute(self, ctx: AttackContext) -> None:\n\n # Target all enemies in the room\n for unit in self.room.units_of_type(self.owner, inverse=True):\n # Determine whether the effect will instantly kill the unit\n damage = self.effect if not self.random.chance(10) else unit.life\n unit._damage(damage) # Damage the unit directly, bypassing immunities.\n\n################################################################################\n","repo_name":"AllegroVivo/DungeonDefense","sub_path":"dm/skills/Hero/GLegend/TheRuinOfEvil.py","file_name":"TheRuinOfEvil.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8340786896","text":"# -*- coding: utf-8 -*-\n#/usr/bin/python2\n'''\nBy kyubyong park. kbpark.linguist@gmail.com. \nhttps://www.github.com/kyubyong/tacotron\n'''\n\nfrom __future__ import print_function\n\nimport os\n\nimport librosa\nfrom tqdm import tqdm\n\nfrom data_load import get_batch, get_batch_eval\nfrom hyperparams import Hyperparams as hp\nfrom modules import *\nfrom networks import encode_dis, encode, decode1, decode2\nimport numpy as np\nfrom prepro import *\nimport tensorflow as tf\nfrom utils import shift_by_one, restore_shape, spectrogram2wav\nfrom tensorflow.python.client import timeline\nfrom scipy.io.wavfile import write\n\n\nclass Graph:\n # Load vocabulary \n #char2idx, idx2char = load_vocab()\n \n def __init__(self, is_training=True):\n self.graph = tf.Graph()\n with self.graph.as_default():\n if is_training:\n self.x, self.q,self.y, self.z, self.num_batch = get_batch()\n else: # Evaluation\n self.x = tf.placeholder(tf.float32, shape=(None, None,hp.n_mels*hp.r))\n self.y = tf.placeholder(tf.float32, shape=(None, None, hp.n_mels*hp.r))\n\n #self.decoder_inputs = shift_by_one(self.y) \n \n with tf.variable_scope(\"Generator\"):\n # Encoder\n self.memory_gen = encode(self.q, is_training=is_training) # (N, T, E)\n \n # Decoder \n decode_length = int((hp.bin_size_y[1]*hp.sr-(hp.win_length-1))/((hp.hop_length)*hp.r)) # about 50\n self._outputs1_gen = tf.zeros([hp.batch_size,1,hp.n_mels*hp.r])\n outputs1_gen_list = []\n for j in range(decode_length):\n reuse = None if j == 0 else True\n self._outputs1_gen += decode1(self._outputs1_gen,\n self.memory_gen,\n is_training=is_training,reuse=reuse)\n outputs1_gen_list.append(self._outputs1_gen)\n self.outputs1_gen = tf.concat(outputs1_gen_list,1)\n self.outputs2_gen = decode2(self.outputs1_gen,is_training=is_training)\n # for b in range(hp.batch_size): #restore the linear spectrogram\n # s = self.outputs2_gen[b,:,:]\n # restore_shape(s, hp.win_length//hp.hop_length, hp.r)\n\n\n with tf.variable_scope(\"Discriminator\"):\n self.final_state_real = encode_dis(self.z, is_training=is_training)\n self.final_state_fake = encode_dis(self.outputs2_gen, is_training=is_training,reuse=True)\n\n\n\n if is_training:\n # Discriminator Loss\n self.dis_loss_real = tf.reduce_mean(tf.squared_difference(self.final_state_real,1))\n self.dis_loss_fake = tf.reduce_mean(tf.squared_difference(self.final_state_fake,0))\n self.dis_loss = tf.reduce_mean(self.dis_loss_real + self.dis_loss_fake)\n\n # Generator Loss\n self.gen_loss = tf.reduce_mean(tf.squared_difference(self.final_state_fake,1))\n\n \n # Training Scheme\n dvars = [e for e in self.graph.get_collection('trainable_variables') if 'Discriminator' in e.name]\n gvars = [e for e in self.graph.get_collection('trainable_variables') if 'Generator' in e.name]\n\n self.global_step = tf.Variable(0, name='global_step', trainable=False)\n self.optimizer = tf.train.AdamOptimizer(learning_rate=hp.lr)\n\n grad_d,var_d = zip(*self.optimizer.compute_gradients(self.dis_loss,var_list=dvars))\n grad_d_clipped ,_= tf.clip_by_global_norm(grad_d,5.)\n grad_g,var_g = zip(*self.optimizer.compute_gradients(self.gen_loss,var_list=gvars))\n grad_g_clipped ,_= tf.clip_by_global_norm(grad_g,5.)\n self.train_op_dis=self.optimizer.apply_gradients(zip(grad_d_clipped,var_d))\n self.train_op_gen=self.optimizer.apply_gradients(zip(grad_g_clipped,var_g))\n # self.train_op_dis = self.optimizer.minimize(self.dis_loss, global_step=self.global_step,var_list=dvars)\n # self.train_op_gen = self.optimizer.minimize(self.gen_loss, global_step=self.global_step,var_list=gvars)\n\n # Increments global step\n self.inc = tf.assign_add(self.global_step, 1, name='increment')\n\n # Profiling\n options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n\n # Summmary \n tf.summary.scalar('dis_loss_real', self.dis_loss_real)\n tf.summary.scalar('dis_loss_fake', self.dis_loss_fake)\n tf.summary.scalar('dis_loss', self.dis_loss)\n tf.summary.scalar('gen_loss', self.gen_loss)\n\n tf.summary.scalar('step',self.inc)\n \n \n self.merged = tf.summary.merge_all()\n \ndef sample_audio(g,sess):\n \"\"\"\n Samples audio from the generator from training examples\n\n Parameters:\n\n g : TensorFlow Graph\n\n sess : TensorFlow Session\n \"\"\"\n mname = 'gan'\n og,act,gen = sess.run([g.q,g.z,g.outputs2_gen])\n for i,(s0,s1,s2) in enumerate(zip(og,act,gen)):\n s0 = restore_shape(s0, hp.win_length//hp.hop_length, hp.r)\n s1 = restore_shape(s1, hp.win_length//hp.hop_length, hp.r)\n s2 = restore_shape(s2, hp.win_length//hp.hop_length, hp.r) \n # generate wav files\n if hp.use_log_magnitude:\n audio0 = spectrogram2wav(np.power(np.e, s0)**hp.power)\n audio1 = spectrogram2wav(np.power(np.e, s1)**hp.power)\n audio2 = spectrogram2wav(np.power(np.e, s2)**hp.power)\n else:\n s0 = np.where(s0 < 0, 0, s0)\n s1 = np.where(s1 < 0, 0, s1)\n s2 = np.where(s2 < 0, 0, s2)\n audio0 = spectrogram2wav(s0**hp.power)\n audio1 = spectrogram2wav(s1**hp.power)\n audio2 = spectrogram2wav(s2**hp.power)\n write(hp.outputdir + \"/gan_{}_org.wav\".format(i), hp.sr, audio0)\n write(hp.outputdir + \"/gan_{}_act.wav\".format(i), hp.sr, audio1)\n write(hp.outputdir + \"/gan_{}_gen.wav\".format(i), hp.sr, audio2)\n\ndef main(): \n g = Graph(); print(\"Training Graph loaded\")\n \n with g.graph.as_default():\n \n # Training \n sv = tf.train.Supervisor(logdir=hp.logdir,\n save_model_secs=0)\n #options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n gpu_options = tf.GPUOptions(allow_growth=True)\n #run_metadata = tf.RunMetadata()\n config = tf.ConfigProto(allow_soft_placement=True,gpu_options=gpu_options)\n with sv.managed_session(config=config) as sess:\n print('made it to training')\n for epoch in tqdm(range(1, hp.num_epochs+1)): \n if sv.should_stop(): \n print(\"Something is broken\");break\n\n # Sampling Audio\n if epoch % hp.audio_summary == 1:\n print(\"Sampling\")\n sample_audio(g,sess)\n\n for step in tqdm(range(g.num_batch), total=g.num_batch, ncols=70, leave=False, unit='b'):\n \n #sess.run(g.train_op_dis,options=options,run_metadata=run_metadata)\n sess.run(g.train_op_dis)\n for _ in range(hp.k):\n #sess.run(g.train_op_gen,options=options,run_metadata=run_metadata)\n sess.run(g.train_op_gen)\n\n # #Profile Logging\n # fetched_timeline = timeline.Timeline(run_metadata.step_stats)\n # chrome_trace = fetched_timeline.generate_chrome_trace_format()\n # with open('timeline/timeline_01_step_%d.json' % step, 'w') as f:\n # f.write(chrome_trace)\n \n #Increment step\n sess.run(g.inc)\n \n\n # Write checkpoint files at every epoch\n gs = sess.run(g.global_step) \n sv.saver.save(sess, hp.logdir + '/model_epoch_%02d_gs_%d' % (epoch, gs))\n\nif __name__ == '__main__':\n main()\n print(\"Done\")\n","repo_name":"tmulc18/S2SCycleGAN","sub_path":"Tacotron_GAN/train_gan.py","file_name":"train_gan.py","file_ext":"py","file_size_in_byte":8365,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"3"}
+{"seq_id":"30514351822","text":"from typing import Callable, List, Optional, Union\n\nimport mmengine\nfrom mmengine.fileio import exists\n\nfrom mmaction.registry import DATASETS\nfrom mmaction.utils import ConfigType\nfrom .base import BaseActionDataset\n\n\n@DATASETS.register_module()\nclass ActivityNetDataset(BaseActionDataset):\n \"\"\"ActivityNet dataset for temporal action localization. The dataset loads\n raw features and apply specified transforms to return a dict containing the\n frame tensors and other information. The ann_file is a json file with\n multiple objects, and each object has a key of the name of a video, and\n value of total frames of the video, total seconds of the video, annotations\n of a video, feature frames (frames covered by features) of the video, fps\n and rfps. Example of a annotation file:\n\n .. code-block:: JSON\n {\n \"v_--1DO2V4K74\": {\n \"duration_second\": 211.53,\n \"duration_frame\": 6337,\n \"annotations\": [\n {\n \"segment\": [\n 30.025882995319815,\n 205.2318595943838\n ],\n \"label\": \"Rock climbing\"\n }\n ],\n \"feature_frame\": 6336,\n \"fps\": 30.0,\n \"rfps\": 29.9579255898\n },\n \"v_--6bJUbfpnQ\": {\n \"duration_second\": 26.75,\n \"duration_frame\": 647,\n \"annotations\": [\n {\n \"segment\": [\n 2.578755070202808,\n 24.914101404056165\n ],\n \"label\": \"Drinking beer\"\n }\n ],\n \"feature_frame\": 624,\n \"fps\": 24.0,\n \"rfps\": 24.1869158879\n },\n ...\n }\n Args:\n ann_file (str): Path to the annotation file.\n pipeline (list[dict | callable]): A sequence of data transforms.\n data_prefix (dict or ConfigDict): Path to a directory where videos are\n held. Defaults to ``dict(video='')``.\n test_mode (bool): Store True when building test or validation dataset.\n Default: False.\n \"\"\"\n\n def __init__(self,\n ann_file: str,\n pipeline: List[Union[dict, Callable]],\n data_prefix: Optional[ConfigType] = dict(video=''),\n test_mode: bool = False,\n **kwargs):\n\n super().__init__(\n ann_file,\n pipeline=pipeline,\n data_prefix=data_prefix,\n test_mode=test_mode,\n **kwargs)\n\n def load_data_list(self) -> List[dict]:\n \"\"\"Load annotation file to get video information.\"\"\"\n exists(self.ann_file)\n data_list = []\n anno_database = mmengine.load(self.ann_file)\n for video_name in anno_database:\n video_info = anno_database[video_name]\n feature_path = video_name + '.csv'\n feature_path = '%s/%s' % (self.data_prefix['video'], feature_path)\n video_info['feature_path'] = feature_path\n video_info['video_name'] = video_name\n data_list.append(video_info)\n return data_list\n","repo_name":"open-mmlab/mmaction2","sub_path":"mmaction/datasets/activitynet_dataset.py","file_name":"activitynet_dataset.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","stars":3560,"dataset":"github-code","pt":"3"}
+{"seq_id":"25565782249","text":"from kampetorpmarin.items import ScrapedProduct, ScrapedCategory, ScrapedProductCategoryAssociation\nfrom kampetorpmarin.countrysettings import countries\nfrom kampetorpmarin.machineapiconnector import MachineAPIWrapper\nfrom kampetorpmarin.listfinder import bisectleftwithattribute, finditemsinlistwithbisect\n\nclass KampetorpmarinPipeline(object):\n countryproperties: {str: {str: list}} = dict()\n productcount = 0\n duplicatecount = 0\n\n def process_item(self, item, spider):\n storeid = item['storeid']\n if storeid not in self.countryproperties:\n self.countryproperties[storeid] = {\"products\": [],\n \"categories\": []}\n\n if isinstance(item, ScrapedCategory):\n try:\n item.validate()\n except (AssertionError, ValueError) as err:\n print(f\"Error validating {item}: {err.args[0]}\")\n if [x['name'] for x in self.countryproperties[storeid]['categories']].count(item['name']) >= 5:\n return item\n if item in self.countryproperties[storeid]['categories']:\n return item\n self.countryproperties[storeid]['categories'].append(item)\n if isinstance(item, ScrapedProduct):\n try:\n item.validate()\n except (AssertionError, ValueError) as err:\n print(f\"Error validating {item}: {err.args[0]}\")\n if \"corona\" in item['name'].lower() or \"covid\" in item['name'].lower():\n return item\n self.productcount += 1\n existingproducts = finditemsinlistwithbisect(itemlist=self.countryproperties[storeid]['products'],\n attrname=\"identifier\",\n object=item)\n if len(existingproducts) > 0:\n for existingproduct in existingproducts:\n self.duplicatecount += 1\n if item['platformcategoryid'] not in [*existingproduct['additionalcategoryids'],\n existingproduct['platformcategoryid']]:\n existingproduct['additionalcategoryids'].append(item['platformcategoryid'])\n return item\n index = bisectleftwithattribute(self.countryproperties[storeid]['products'], item, \"identifier\")\n self.countryproperties[storeid]['products'].insert(index, item)\n if isinstance(item, ScrapedProductCategoryAssociation):\n existingproducts = finditemsinlistwithbisect(itemlist=self.countryproperties[storeid]['products'],\n attrname=\"platformproductid\",\n object=item['productid'])\n if len(existingproducts) > 0:\n for existingproduct in existingproducts:\n if item['category']['platformcategoryid'] not in [*existingproduct['additionalcategoryids'],\n existingproduct['platformcategoryid']]:\n existingproduct['additionalcategoryids'].append(item['category']['platformcategoryid'])\n return item\n\n def close_spider(self, spider):\n # https://shopifyappdev3.amandaai.com/pridacapi\n # https://sapp.amandaai.com/pridacapi\n\n wrapper = MachineAPIWrapper(host=\"https://pridacapi.amandaai.com\",\n username=spider.settings.attributes.get('FTP_USER').value,\n password=spider.settings.attributes.get('FTP_PASSWORD').value)\n for key, value in self.countryproperties.items():\n countryinfo = next(iter([x for x in countries if x['storeid'] == key]), None)\n if countryinfo is None:\n print(\"Could not find countryinfo for store with id {}\".format(key))\n continue\n for product in value['products']:\n product.validate()\n for category in value['categories']:\n category.validate()\n wrapper.postproductsandcategories(storename=countryinfo['storename'],\n storeid=key,\n productsandcategories={\n \"products\": [dict(x) for x in list(set(value['products']))],\n \"categories\": [dict(x) for x in list(set(value['categories']))]\n })\n","repo_name":"annabackstrom/kampetorpmarin","sub_path":"kampetorpmarin/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":4650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27135518135","text":"def f2(n):\n if (n<=2):\n return 1\n else:\n p = 1\n q = 1\n for i in range(3,n+1):\n r = p+q\n p=q\n q=r\n return r;\n\n\ndef read_integers(filename):\n with open(filename) as f:\n return [int(x) for x in f]\n \nfile2 = open('output2.txt', 'w+')\nintlist = read_integers('input2.txt')\n\n\nfor integer in intlist:\n ans = f2(integer)\n file2.write(str(ans) + '\\n')\n","repo_name":"pranavtalwar/COMP2119-Assignments","sub_path":"Programming Assignment 1/F2(n).py","file_name":"F2(n).py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7199575910","text":"import tabula\nimport pandas as pd\nimport re\nimport numpy as np\nfrom helpers.tools.table_utils import umc_values, get_num_pages, index_containing_substring\nfrom db_custom import insert_item\ndef create_column_name(parts):\n name = ''\n for part in parts:\n part = str(part)\n if 'nan' in part or 'Unnamed' in part:\n continue\n name += f' {part}'\n return name.strip()\n\n\ndef extract_pieces_data(pieces, pieces_clean):\n if 'UMC' in pieces_clean.columns:\n return pieces_clean\n \n data = pieces['DESCRIPCION']\n rows = data[data.str.contains('^(?:[\\d|,|\\.]+)\\s+(?:[A-Z]+)\\s+\\$(?:[\\d|,|.]+)$')]\n parts = rows.str.extract('^([\\d|,|\\.]+)\\s+([A-Z]+)\\s+\\$([\\d|,|.]+)$')\n pieces_clean['CANTIDAD'] = parts[0].to_list()\n pieces_clean['UMC'] = parts[1].to_list()\n pieces_clean['COSTO UNIT'] = parts[2].to_list()\n \n return pieces_clean\n\n\ndef separate_description(pieces_clean):\n try:\n umc_extraction = pieces_clean['DESCRIPCION'].str.extract(f'({\" | \".join(umc_values)})', expand=False)\n if umc_extraction.isnull().all():\n return pieces_clean\n\n parts = pieces_clean['DESCRIPCION'].str.split(' | '.join(umc_values), expand=True)\n extracted = parts[0].str.extract('(\\D*)(\\d|,|.*)$')\n pieces_clean['DESCRIPCION'] = extracted[0]\n pieces_clean['CANTIDAD'] = extracted[1]\n pieces_clean['UMC'] = umc_extraction\n pieces_clean['COSTO UNIT'] = parts[1]\n\n return pieces_clean\n except Exception:\n return pieces_clean\n\n\n# Clean columns\ndef clean_columns(pieces):\n old_columns = ['' if 'Unnamed' in x else x for x in pieces.columns[:].tolist()]\n new_columns = [create_column_name(x) for x in zip(old_columns,pieces.iloc[0,:])]\n new_columns[-1] = 'TOTAL DOLARES'\n new_columns[-2] = 'TD2'\n new_columns[0] = 'TIPO Y CANTIDAD'\n new_columns[1] = 'PESO BRUTO'\n new_columns[2] = 'PESO NETO'\n \n pieces.columns = new_columns\n pieces['TIPO Y CANTIDAD'] = pieces.loc[:, 'TIPO Y CANTIDAD'].fillna('')\n if 'CODIGO DE PERMISO' in pieces.columns:\n pieces['CODIGO DE PERMISO'] = pieces.loc[:, 'CODIGO DE PERMISO'].fillna('')\n pieces = pieces.dropna(how='all', axis=1)\n new_columns = pieces.columns.to_list()\n new_columns[3] = 'DESCRIPCION'\n pieces.columns = new_columns\n\n pieces = pieces.iloc[1: , :]\n while 'DOLARES' in str(pieces.iloc[0,-1]) or 'DOLARES' in str(pieces.iloc[1,-1]) or 'VALOR' in str(pieces.iloc[0,-1]) or 'VALOR' in str(pieces.iloc[1,-1]):\n pieces = pieces.iloc[1: , :]\n\n pieces_clean = pieces[pieces['PESO NETO'].notna()].copy()\n pieces_clean = pieces_clean[pieces_clean['DESCRIPCION'].notna()]\n\n if 'TD2' in pieces_clean.columns:\n pieces_clean['TD2'] = pieces_clean.loc[:, 'TD2'].fillna('')\n pieces_clean['TOTAL DOLARES'] = pieces_clean.loc[:, 'TOTAL DOLARES'].fillna('')\n pieces_clean[\"TOTAL DOLARES\"] = pieces_clean[\"TD2\"].astype(str) + ' ' + pieces_clean[\"TOTAL DOLARES\"].astype(str)\n del pieces_clean['TD2']\n \n \n \n pieces_clean = pieces_clean.dropna(how='all', axis=1)\n \n return pieces_clean, pieces\n\ndef extract_from_pdf(filename):\n data_pieces_clean = [pd.DataFrame()]\n data_pieces = [pd.DataFrame()]\n tables_full = tabula.read_pdf_with_template(input_path=filename,\n template_path=\"helpers/templates/jabil_importacion/Jabil Importacion P1.tabula-template.json\")\n\n for idx, table in enumerate(tables_full):\n try:\n result_clean, result = clean_columns(table)\n data_pieces_clean.append(result_clean)\n data_pieces.append(result)\n except:\n raise(\"error cannot extract\")\n\n pieces_clean = pd.concat(data_pieces_clean).reset_index(drop=True)\n pieces = pd.concat(data_pieces) \n return pieces_clean, pieces\n\ndef extract_data_jabil_import(filename):\n pieces_clean, pieces = extract_from_pdf(filename)\n pieces_clean = pieces_clean.iloc[:-1,:]\n pieces_clean = separate_description(pieces_clean)\n pieces_clean = extract_pieces_data(pieces, pieces_clean)\n \n for index, row in pieces_clean.iterrows():\n insert_item(row['DESCRIPCION'],row['CANTIDAD'],row['UMC'],row['COSTO UNIT'])\n return pieces_clean\n\n# filename = 'facturas/jabil_importacion/15.pdf'\n# result = extract_data(filename)\n# print(result)","repo_name":"javierIA/spaceFacturas","sub_path":"helpers/tools/jabil_importacion.py","file_name":"jabil_importacion.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27019850905","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author:xm1230\n# datetime:2019/3/9 20:16\n# software: PyCharm\n\nclass Solution:\n def __init__(self):\n '''\n https://leetcode-cn.com/problems/regular-expression-matching/\n给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。\n\n'.' 匹配任意单个字符。\n'*' 匹配零个或多个前面的元素。\n匹配应该覆盖整个字符串 (s) ,而不是部分字符串。\n\n说明:\n\ns 可能为空,且只包含从 a-z 的小写字母。\n '''\n pass\n\n def isMatch(self, s, p):\n s_len, p_len = len(s), len(p)\n if p_len > 0 and p[0] == '*':\n return False\n dp = [[False for i in range(p_len + 1)] for i in range(s_len + 1)] # 创建结果集合 [s][p]\n dp[0][0] = True\n # 初始化,当s为空时候 p应为a*模式\n for i in range(1, len(dp[0])):\n if p[i - 1] == '*':\n dp[0][i] = dp[0][i - 2] # a*c *是否配置 取决于a前面即dp[0][0] 默认True\n for i in range(1, s_len + 1): # 遍历每个s\n for j in range(1, p_len + 1): # 遍历每个p s的每个字符是否匹配p的每个字符\n if s[i - 1] == p[j - 1] or p[j - 1] == '.': # 匹配模式,当前是否匹配,取决于前一次是否匹配\n dp[i][j] = dp[i - 1][j - 1]\n elif p[j - 1] == '*': # a*模式\n if (s[i - 1] == p[j - 2]) or p[j - 2] == '.': # a*或.* 匹配上a\n dp[i][j] = dp[i][j - 1] or dp[i][j - 2] or dp[i - 1][j]\n else:\n dp[i][j] = dp[i][j - 2] # 当前ba*是否匹配取决于b是否匹配\n else: # 不匹配 默认为False\n pass\n for i in dp:\n print(i)\n return dp[s_len][p_len]\n\n\ndef isMatch2(self, s, p):\n '''\n 递归实现\n :param s:\n :param p:\n :return:\n '''\n m, n = len(s), len(p)\n if n == 0: # 正则为空,待匹配必须为空\n return m == 0\n if m == 0: # 待匹配为空,验证正在是不是 'a*'模式\n if n >= 2 and p[1] == '*':\n return self.isMatch(s, p[2:])\n else:\n return False\n # 匹配模式\n # 第一个字符是否相同\n firstMatch = s[0] == p[0] or p[0] == '.'\n if n >= 2 and p[1] == '*': # 正则是'a*'模式,则选择 s[0] 或��去除s[0]\n return self.isMatch(s, p[2:]) or (firstMatch and self.isMatch(s[1:], p))\n else: # 匹配模式\n return firstMatch and self.isMatch(s[1:], p[1:])\n\n\ndef isMatch1(self, s: str, p: str) -> bool:\n if p == '.*':\n return True\n count_p, count_s, i, j = len(p), len(s), 0, 0\n while i < count_p:\n if j >= count_s: # s已经结束,p还未结束\n while i < count_p:\n if i + 1 < count_p and p[i + 1] == '*': # 判断p最后是否全是 '.*\n i += 2\n else:\n return False\n return True\n if i + 1 == count_p: # 最后一个元素\n if s[j] != p[i] and p[i] != '.':\n return False\n else:\n return j + 1 == count_s\n elif p[i + 1] == '*':\n if p[i] == '.':\n if i + 2 == count_p:\n return True\n else:\n while j < count_s:\n if s[j] == p[i + 2]:\n break\n else:\n j += 1\n i += 2\n else:\n while j < count_s:\n if s[j] == p[i]:\n j += 1\n else:\n break\n i += 2\n if p[i] == p[i - 2]: # 'aaa a*a格式'\n j -= 1\n else:\n if p[i] == '.' or p[i] == s[j]:\n i += 1\n j += 1\n else:\n return False\n return j == count_s\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.isMatch('aa', 'a*'))\n # print(s.isMatch('ab', '.*'))\n # print(s.isMatch('aa', 'a'))\n # print(s.isMatch('aab', 'c*a*b'))\n # print(s.isMatch('mississippi', 'mis*is*p*'))\n # print(s.isMatch('aa', 'a*'))\n","repo_name":"xjh1230/py_algorithm","sub_path":"test/regular_expression_matching.py","file_name":"regular_expression_matching.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"70446928081","text":"from odoo import api, fields, models,exceptions\nclass SaleOrder(models.Model):\n _inherit = \"sale.order\"\n register_payment_journal_id = fields.Many2one('account.journal',default=False)\n\n def action_confirm(self):\n imediate_obj = self.env['stock.immediate.transfer']\n old_so_date = self.date_order\n res = super(SaleOrder,self).action_confirm()\n self.write({\n 'date_order':old_so_date,\n 'effective_date':old_so_date,\n 'expected_date':old_so_date\n })\n\n for order in self:\n\n warehouse = order.warehouse_id\n for picking in self.picking_ids:\n picking.scheduled_date = old_so_date\n picking.date_done = old_so_date\n\n\n if warehouse.is_delivery_set_to_done and order.picking_ids:\n for picking in self.picking_ids:\n picking.action_assign()\n picking.action_confirm()\n for mv in picking.move_ids_without_package:\n mv.quantity_done = mv.product_uom_qty\n picking.button_validate()\n picking.date_done = old_so_date\n\n if warehouse.create_invoice and not order.invoice_ids:\n order._create_invoices()\n\n if warehouse.validate_invoice and order.invoice_ids:\n for invoice in order.invoice_ids:\n invoice.invoice_date = old_so_date\n invoice.date = old_so_date\n invoice.action_post()\n\n\n # Register payment if journal is attached on SO\n if order.register_payment_journal_id:\n payment_method_manual_in = self.env.ref(\n \"account.account_payment_method_manual_in\"\n )\n register_payments = (\n self.env[\"account.payment.register\"]\n .with_context(active_model='account.move', active_ids=[invoice.id],\n journal_id=order.register_payment_journal_id.id).create(\n {\"payment_method_id\": payment_method_manual_in.id,\n \"journal_id\": order.register_payment_journal_id.id,\n \"payment_date\": old_so_date\n })\n )\n payment = self.env[\"account.payment\"].browse(\n register_payments.action_create_payments()\n )\n\n\n\n return res \n","repo_name":"imujeebco/odoo-qne-modules","sub_path":"sale_order_automation/models/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36607731747","text":" # -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Oct 12 23:28:25 2021\r\n\r\n@author: leen8\r\n\"\"\"\r\n'imports hw4_util functions'\r\nimport hw4_util\r\n'creates a function that finds the tuple location of the specified state using enumerate to find the specific indexes\\\r\n and returns the tuple of the specified location'\r\ndef find_state_tup(state, ind):\r\n for i,sub in enumerate(hw4_util.part2_get_week(ind)):\r\n for j,statef in enumerate(sub):\r\n if statef == state:\r\n return (i, j)\r\n return (None, None)\r\n'prints starting ...'\r\nprint(\"...\")\r\n'loops while the function is true'\r\nwhile True: \r\n 'gets the index from the user and converts the index into an integer for comparison'\r\n ind = input(\"Please enter the index for a week: \")\r\n print(ind)\r\n ind = int(ind)\r\n 'determines if it is a valid index, and gets the request from the user and strips \\\r\n it of any spaces'\r\n if ind >= 1 and ind <=29:\r\n request = input(\"Request (daily, pct, quar, high): \")\r\n print(request)\r\n req = request.lower().strip()\r\n 'if the request is daily, it gets the specified state from the user and strips it from \\\r\n any spaces, calls the function to get the specified tuple with its list location \\\r\n with data, if it does not exist it prints the unknown state, if it exists it \\\r\n calculates and prints the daily positive cases'\r\n if req == \"daily\":\r\n state = input(\"Enter the state: \")\r\n print(state)\r\n state = state.strip()\r\n statetup = find_state_tup(state, ind)\r\n if statetup == (None, None):\r\n print(\"State {} not found\".format(state)+\"\\n...\")\r\n else:\r\n stateind = statetup[0]\r\n wlist = hw4_util.part2_get_week(ind)[stateind]\r\n daily = ((sum(wlist[2:9])/7)*100000)/wlist[1]\r\n print(\"Average daily positives per 100K population: {}\".format(round(daily, 1)))\r\n print(\"...\")\r\n 'if the request is pct, it gets the specified state from the user and strips it from \\\r\n any spaces, calls the function to get the specified tuple with its list location \\\r\n with data, if it does not exist it prints the unknown state, if it exists it \\\r\n calculates and prints the average daily percentage of tests that are positive'\r\n elif req == \"pct\":\r\n state = input(\"Enter the state: \")\r\n print(state)\r\n state = state.strip()\r\n statetup = find_state_tup(state, ind)\r\n if statetup == (None, None):\r\n print(\"State {} not found\".format(state)+\"\\n...\")\r\n else:\r\n stateind = statetup[0]\r\n wlist = hw4_util.part2_get_week(ind)[stateind]\r\n p = sum(wlist[2:9])\r\n n = sum(wlist[9:])\r\n pct = p/(p + n)*100\r\n print(\"Average daily positive percent: {}\".format(round(pct, 1)))\r\n print(\"...\")\r\n 'if the request is quar, it searches the lists and calculates the average daily percentage \\\r\n of tests that are positive and determines if its higher than 9.5, if it is it adds it to \\\r\n the list of quarentined states, and sends the states and formats them from hw4_util'\r\n elif req == \"quar\":\r\n states = []\r\n x = 0\r\n for x in hw4_util.part2_get_week(ind):\r\n p = sum(x[2:9])\r\n n = sum(x[9:])\r\n i = p/(p + n)*100\r\n if i >= 9.5:\r\n states.append(x[0])\r\n print(\"Quarantine states:\")\r\n hw4_util.print_abbreviations(states)\r\n print(\"...\")\r\n 'if the request is high it searches the list and calculates the daily positive cases, appending \\\r\n all the averages into a list and all of the states into the list, it find the max average \\\r\n in the list and gets the index of the max and finds the corresponding index in the list \\\r\n of states and prints the state and the max average'\r\n elif req == \"high\":\r\n savg = []\r\n states = []\r\n for x in hw4_util.part2_get_week(ind):\r\n i = ((sum(x[2:9])/7)*100000)/x[1]\r\n savg.append(i)\r\n states.append(x[0])\r\n max_avg = max(savg)\r\n m_ind = savg.index(max_avg)\r\n hstate = states[m_ind]\r\n print(\"State with highest infection rate is {}\".format(hstate))\r\n print(\"Rate is {} per 100,000 people\".format(round(max_avg, 1)))\r\n print(\"...\")\r\n 'prints if the request is not valid'\r\n else:\r\n print(\"Unrecognized request\\n...\")\r\n 'prints if the index is above the max'\r\n elif ind>29:\r\n print(\"No data for that week\\n...\")\r\n else:\r\n break\r\n\r\n \r\n \r\n \r\n \r\n\r\n","repo_name":"niccolesgit/Python-Projects","sub_path":"hw/HW 4/hw4_part2.py","file_name":"hw4_part2.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39998815853","text":"from .__init__ import *\n\n\nclass CovidStatsView(View):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.api_sources = \"https://covid19.ddc.moph.go.th/\"\n self.dashboard = (\n \"https://www.arcgis.com/apps/dashboards/bda7594740fd40299423467b48e9ecf6\"\n )\n self.build_buttons()\n\n def build_buttons(self) -> None:\n self.add_item(Button(label=\"แหล่งที่มา API\", emoji=\"🔗\", url=self.api_sources))\n self.add_item(Button(label=\"แดชบอร์ด\", emoji=\"🔗\", url=self.dashboard))\n\n\nclass DiseasesView(View):\n def __init__(self, source: str, picsource: str):\n super().__init__(timeout=None)\n self.source = source\n self.picsource = picsource\n self.build_buttons()\n\n def build_buttons(self) -> None:\n self.add_item(\n Button(emoji=\"ℹ️\", label=\"Source\", url=self.source, style=ButtonStyle.link)\n )\n self.add_item(\n Button(\n emoji=\"🖼️\",\n label=\"Picture Source\",\n url=self.picsource,\n style=ButtonStyle.link,\n )\n )\n\n\nclass RecordPaginator(View):\n def __init__(self, interaction: Interaction, embed_lists: list):\n super().__init__(timeout=30)\n self.interaction = interaction\n self.current_page = 0\n self.pages = embed_lists\n self.max_page = len(self.pages)\n self.initialize_page()\n\n async def start(self) -> InteractionMessage:\n self.initialize_view(0)\n await self.interaction.response.send_message(embed=self.pages[0], view=self)\n self.message = await self.interaction.original_response()\n\n async def show_page(\n self, interaction: Interaction, page: int\n ) -> InteractionMessage:\n self.current_page = page\n self.initialize_page()\n self.initialize_view(self.current_page)\n await interaction.response.edit_message(\n embed=self.pages[page % self.max_page], view=self\n )\n self.message = await interaction.original_response()\n\n @button(\n label=\"first\",\n emoji=\"<:first_page_white:1058405780895842405>\",\n style=ButtonStyle.secondary,\n )\n async def first_page(\n self, interaction: Interaction, button: Button\n ) -> InteractionMessage:\n await self.show_page(interaction, 0)\n\n @button(\n label=\"prev\",\n emoji=\"<:previous:999541041327775784>\",\n style=ButtonStyle.secondary,\n )\n async def previous_page(\n self, interaction: Interaction, button: Button\n ) -> InteractionMessage:\n await self.show_page(interaction, self.current_page - 1)\n\n @button(style=ButtonStyle.primary, disabled=True)\n async def page_indicator(\n self, interaction: Interaction, button: Button\n ) -> InteractionMessage:\n ...\n\n @button(\n label=\"next\",\n emoji=\"<:next:999541035304747120>\",\n style=ButtonStyle.secondary,\n )\n async def next_page(\n self, interaction: Interaction, button: Button\n ) -> InteractionMessage:\n await self.show_page(interaction, self.current_page + 1)\n\n @button(\n label=\"last\",\n emoji=\"<:last_page_white:1058405905592500365>\",\n style=ButtonStyle.secondary,\n )\n async def last_page(\n self, interaction: Interaction, button: Button\n ) -> InteractionMessage:\n await self.show_page(interaction, self.max_page - 1)\n\n def extract(self, arg1: bool, arg2: bool) -> None:\n self.first_page.disabled = arg1\n self.previous_page.disabled = arg1\n self.next_page.disabled = arg2\n self.last_page.disabled = arg2\n\n def initialize_page(self) -> None:\n self.page_indicator: Button\n self.page_indicator.label = (\n f\"{(self.current_page%self.max_page)+1}/{self.max_page}\"\n )\n\n def initialize_view(self, page: int) -> None:\n if page == 0:\n self.extract(True, False)\n elif page == self.max_page - 1:\n self.extract(False, True)\n else:\n self.extract(False, False)\n\n async def interaction_check(self, interaction: Interaction) -> bool:\n return self.interaction.user == interaction.user\n\n async def on_timeout(self) -> None:\n self.message: InteractionMessage\n for child in self.children:\n child.disabled = True\n await self.message.edit(view=self)\n\n\nclass RecordHealth(Modal):\n def __init__(\n self,\n bot: DiseasesBot,\n user: Union[Member, User],\n primary: bool = True,\n *args,\n **kwargs,\n ):\n super().__init__(title=\"Health Record\", *args, **kwargs)\n self.bot = bot\n self.user = user\n self.primary = primary\n\n description = TextInput(label=\"รายงานผลสุขภาพประจำวันนี้\", style=TextStyle.long)\n\n async def on_submit(self, interaction: Interaction) -> InteractionMessage:\n date = Formatter.unix_formatter(datetime.now(timezone.utc))\n embed = Embed(\n title=\"ยืนยันการรายงานหรือไม่\",\n description=f\"```{str(self.description)}```\",\n color=Colour.yellow(),\n )\n embed.set_footer(\n text=f\"Requested by {interaction.user}\",\n icon_url=interaction.user.avatar.url,\n )\n view = ConfirmSend(\n bot=self.bot, user=interaction.user, time=date, reason=str(self.description)\n )\n if not self.primary:\n view.message = await self.message.edit(embed=embed, view=view)\n return await interaction.response.send_message(\n content=f\"Edited to `{self.description}`\", delete_after=5\n )\n\n await interaction.response.send_message(embed=embed, view=view)\n view.message = await interaction.original_response()\n\n\nclass ConfirmSend(View):\n def __init__(\n self,\n bot: DiseasesBot,\n user: Union[Member, User],\n time: int,\n reason: str,\n *args,\n **kwargs,\n ):\n super().__init__(timeout=30, *args, **kwargs)\n self.bot = bot\n self.user = user\n self.time = time\n self.reason = reason\n self.database = Database(self.bot)\n\n @button(label=\"confirm\", style=ButtonStyle.success)\n async def confirm(\n self, interaction: Interaction, button: Button\n ) -> InteractionMessage:\n self.disable_all_items()\n await self.database.health_info_entry(\n interaction.user.id, time=self.time, reason=self.reason\n )\n embed = Embed(\n title=\"รายงานผลสำเร็จ : \",\n description=f\"```{self.reason}```\",\n color=Colour.green(),\n )\n embed.set_footer(\n text=f\"Requested by {interaction.user}\",\n icon_url=interaction.user.avatar.url,\n )\n await interaction.response.edit_message(embed=embed, view=self)\n\n @button(label=\"edit\", style=ButtonStyle.danger)\n async def edit(\n self, interaction: Interaction, button: Button\n ) -> InteractionMessage:\n modal = RecordHealth(self.bot, interaction.user, primary=False)\n await interaction.response.send_modal(modal)\n modal.message = await interaction.original_response()\n\n async def interaction_check(self, interaction: Interaction) -> bool:\n return self.user == interaction.user\n\n def disable_all_items(self) -> None:\n for child in self.children:\n child.disabled = True\n\n async def on_timeout(self) -> None:\n self.disable_all_items()\n self.message: InteractionMessage\n with suppress(TypeError, errors.NotFound):\n await self.message.edit(view=self)\n await asyncio.sleep(5)\n await self.message.delete()\n\n\nclass Health(commands.Cog):\n \"\"\"Commands สำหรับข้อมูลเกี่ยวกับสุขภาพ\"\"\"\n\n def __init__(self, bot: DiseasesBot):\n self.bot = bot\n self.database = Database(self.bot)\n\n @commands.Cog.listener(name=\"on_ready\")\n async def on_ready(self) -> None:\n self.disease = await self.database.fetch_diseases()\n print(f\"{self.__class__.__name__.upper()} COG is activated\")\n\n @app_commands.command(name=\"diseases\")\n @app_commands.checks.cooldown(1, 10)\n @app_commands.describe(diseases_name=\"เลือกโรคที่ต้องการ\")\n async def diseases(\n self, interaction: Interaction, diseases_name: str\n ) -> InteractionMessage:\n \"\"\"ตรวจสอบรายละเอียดโรคระบาดแต่ละโรค\"\"\"\n info = None\n\n for index, value in enumerate(list(self.disease)):\n if self.disease[index][\"name\"] == diseases_name:\n info = self.disease[index]\n\n embed = Embed(\n title=info[\"name\"],\n description=f\"```{info['description']}```\",\n color=Colour.dark_theme(),\n )\n\n embed.add_field(\n name=\"สาเหตุก���รเกิดโรค\", value=f\"> {info['cause']}\", inline=False\n )\n embed.add_field(\n name=\"วิธีการป้องกัน\", value=f\"> {info['protection']}\", inline=False\n )\n embed.add_field(\n name=\"วิธีการรักษา\", value=f\"> {info['treatment']}\", inline=False\n )\n\n embed.set_footer(\n text=f\"แหล่งที่มา : {info['source']}\", icon_url=info[\"thumbnail\"]\n )\n\n view = DiseasesView(source=info[\"source\"], picsource=info[\"picsource\"])\n await interaction.response.send_message(embed=embed, view=view)\n\n @diseases.autocomplete(\"diseases_name\")\n async def diseases_autocomplete(\n self, interaction: Interaction, current: str\n ) -> list(app_commands.Choice[str]):\n choices = [self.disease[i][\"name\"] for i in list(self.disease)]\n\n return (\n app_commands.Choice(name=choice, value=choice)\n for choice in choices\n if current.lower() in choice.lower()\n )\n\n @app_commands.command(name=\"covid_stats\")\n @app_commands.checks.cooldown(1, 15)\n async def covid_stats(self, interaction: Interaction) -> InteractionMessage:\n \"\"\"รายงานสถิติโควิด-19 ในประเทศไทย\"\"\"\n data = await self.database.fetch_covid_data()\n embed = Embed(\n title=\"รายงานสถานการณ์โรคระบาดโควิด-19\", color=Colour.dark_theme()\n )\n embed.description = \"\"\n\n for index, (name, value) in enumerate(data.items()):\n if index != len(data) - 1:\n embed.description += f\"> {str(name)} : {value}\\n\"\n else:\n embed.description += f\"\\n**{name}** : {value}\"\n\n embed.set_footer(\n text=f\"Requested by {interaction.user}\",\n icon_url=interaction.user.avatar.url,\n )\n embed.set_image(\n url=\"https://media.discordapp.net/attachments/780424031035457588/1023543726716493834/Pandemic.jpg\"\n )\n\n view = CovidStatsView()\n await interaction.response.send_message(embed=embed, view=view)\n\n @app_commands.command(name=\"record\")\n @app_commands.checks.cooldown(1, 30)\n async def record(self, interaction: Interaction) -> InteractionMessage:\n \"\"\"บันทึกรายงานสุขภาพประจำวัน\"\"\"\n await interaction.response.send_modal(RecordHealth(self.bot, interaction.user))\n\n @app_commands.command(name=\"record_view\")\n @app_commands.checks.cooldown(1, 15)\n async def view_record(self, interaction: Interaction) -> InteractionMessage:\n \"\"\"ดูบันทึกการรายงาานสุขภาพของตนเอง\"\"\"\n data = await self.database.health_info_logs(user_id=interaction.user.id)\n if data == []:\n embed = Embed(\n description=f\"{interaction.user.mention} ยังไม่เคยมีข้อมูลบันทึกรายงานสุขภาพของคุณ\",\n color=Colour.red(),\n )\n return await interaction.response.send_message(embed=embed)\n\n health_report = data[1]\n times = data[2]\n embed_lists = []\n\n for index, value in enumerate(data):\n with suppress(IndexError):\n embed = Embed(\n title=f\"รายงานผลของ {interaction.user.name}\",\n color=Colour.green(),\n )\n embed.add_field(\n name=f\"ผลรายงานครั้งที่ {index+1}\",\n value=f\"รายงานเมื่อวันที่ : ```{health_report[index]}```\",\n inline=False,\n )\n embed.set_footer(\n text=f\"Requested by {interaction.user}\",\n icon_url=interaction.user.avatar.url,\n )\n embed_lists.append(embed)\n\n view = RecordPaginator(interaction, embed_lists)\n await view.start()\n\n @app_commands.command(name=\"record_delete\")\n @app_commands.checks.cooldown(1, 30)\n @app_commands.describe(user=\"เลือก user ที่ต้องการจะลบข้อมูล\")\n async def delete(\n self,\n interaction: Interaction,\n user: Union[User, Member] = None,\n ) -> InteractionMessage:\n \"\"\"ลบฐานข้อมูลของ user ทั้งหมดหรือเฉพาะคน\"\"\"\n\n if interaction.user.id in [self.bot.owner.id, self.bot.partner_id]:\n if user:\n await self.database.delete(user_id=user.id)\n embed = Embed(\n description=f\"✅| Delete {user.mention} successfully!\",\n color=Colour.green(),\n )\n\n else:\n await self.database.delete()\n embed = Embed(\n description=\"✅| Delete all info in database successfully!\",\n color=discord.Colour.green(),\n )\n\n else:\n embed = Embed(\n description=\"คุณไม่มีสิทธิ์ในการลบข้อมูล user ได้\",\n color=Colour.red(),\n )\n await interaction.response.send_message(embed=embed)\n\n\nasync def setup(bot: DiseasesBot):\n await bot.add_cog(Health(bot))\n","repo_name":"Sodynoizz/diseasesbot-remake","sub_path":"cogs/health.py","file_name":"health.py","file_ext":"py","file_size_in_byte":14847,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"34470750184","text":"# coding=utf-8\n\nimport numpy as np\nfrom scipy import stats\nfrom matplotlib import pyplot as plt\nfrom datamatrix import series as srs\nfrom datamatrix import cached, plot\nfrom analysis import data, baseline, interaction\nfrom analysis.constants import *\n\n\t\ndef ttest(dm, col):\n\t\n\ta1 = srs.reduce_(srs.window((dm.c == 1)[col], start=-50, end=-1))\n\tb1 = srs.reduce_(srs.window((dm.c == 2)[col], start=-50, end=-1))\n\tt, p = stats.ttest_ind(a1, b1)\n\treturn p < ALPHA and t < 0, p < ALPHA and t > 0\n\n\n@cached\ndef power(dummy, blfilter=BLFILTER, **kwargs):\n\t\n\thits1 = np.zeros(NSIM)\n\thits2 = np.zeros(NSIM)\n\thits4 = np.zeros(NSIM)\n\tspurious1 = np.zeros(NSIM)\n\tspurious2 = np.zeros(NSIM)\n\tspurious4 = np.zeros(NSIM)\n\tfor i in range(NSIM):\n\t\tprint(i)\n\t\tdm = data.generatedata(**kwargs)\n\t\tif blfilter:\n\t\t\tdm.bl = baseline.baseline(dm)\n\t\t\tminbl = dm.bl.mean - BLSTDTHR * dm.bl.std\n\t\t\tmaxbl = dm.bl.mean + BLSTDTHR * dm.bl.std\n\t\t\tdm = (dm.bl > minbl) & (dm.bl < maxbl)\n\t\tdm.y2 = baseline.correct1(dm)\n\t\tdm.y4 = baseline.correct3(dm)\n\t\thits1[i], spurious1[i] = ttest(dm, 'y')\n\t\thits2[i], spurious2[i] = ttest(dm, 'y2')\n\t\thits4[i], spurious4[i] = ttest(dm, 'y4')\t\n\tprint('Y1: power = ', hits1.mean())\n\tprint('Y2: power = ', hits2.mean())\n\tprint('Y4: power = ', hits4.mean())\n\tprint('Y1: spurious = ', spurious1.mean())\n\tprint('Y2: spurious = ', spurious2.mean())\n\tprint('Y4: spurious = ', spurious4.mean())\n\treturn (hits1.mean(), hits2.mean(), hits4.mean(),\n\t\tspurious1.mean(), spurious2.mean(), spurious4.mean())\n\t\n\t\ndef powersummary(dummy):\n\t\n\tplot.new()\n\tfor i, blinksinbaseline in enumerate((True, False)):\n\t\tl1 = []\n\t\tl2 = []\n\t\tl4 = []\n\t\tls1 = []\n\t\tls2 = []\n\t\tls4 = []\n\t\teffectsizes = range(0, 501, 50)\n\t\tfor effectsize in effectsizes:\n\t\t\tkwargs = {\n\t\t\t\t'effectsize' : effectsize,\n\t\t\t\t'blfilter' : False,\n\t\t\t\t'blinksinbaseline' : blinksinbaseline\t\t\t\t\n\t\t\t\t}\n\t\t\tcid = 'power-%(effectsize)s-%(blfilter)s-%(blinksinbaseline)s' % kwargs\n\t\t\tp1, p2, p4, s1, s2, s4 = power(None, cacheid=cid, **kwargs)\n\t\t\tl1.append(p1)\n\t\t\tl2.append(p2)\n\t\t\tl4.append(p4)\n\t\t\tls1.append(s1)\n\t\t\tls2.append(s2)\n\t\t\tls4.append(s4)\n\t\tplt.subplot(2,2,i*2+1)\n\t\tif i == 0:\n\t\t\tplt.title('With blinks during baseline')\n\t\telse:\n\t\t\tplt.title('No blinks during baseline')\t\t\n\t\tplt.axhline(.025, color='black', linestyle=':')\n\t\tplt.xlim(effectsizes[0]-10, effectsizes[-1]+10)\n\t\tplt.ylim(-.05, 1.05)\n\t\tplt.xlabel('True effect size')\n\t\tplt.ylabel('Proportion correct detections')\n\t\tplt.plot(effectsizes, l1, 'o-', label='No baseline correction',\n\t\t\tcolor=COLORNOCORRECT)\n\t\tplt.plot(effectsizes, l2, 'o-', label='Divide by baseline',\n\t\t\tcolor=COLORDIVIDE)\n\t\tplt.plot(effectsizes, l4, 'o-', label='Subtract baseline',\n\t\t\tcolor=COLORSUBTRACT)\n\t\tplt.subplot(2,2,i*2+2)\n\t\tplt.title('Spurious')\n\t\tplt.axhline(.025, color='black', linestyle=':')\n\t\tplt.xlim(effectsizes[0]-10, effectsizes[-1]+10)\n\t\tplt.ylim(-.05, 1.05)\n\t\tplt.xlabel('True effect size')\n\t\tplt.ylabel('Proportion spurious detections')\t\t\n\t\tplt.plot(effectsizes, ls1, 'o-', label='No baseline correction',\n\t\t\tcolor=COLORNOCORRECT)\n\t\tplt.plot(effectsizes, ls2, 'o-', label='Divide by baseline',\n\t\t\tcolor=COLORDIVIDE)\n\t\tplt.plot(effectsizes, ls4, 'o-', label='Subtract baseline',\n\t\t\tcolor=COLORSUBTRACT)\n\t\tif i == 3:\n\t\t\tplt.legend(frameon=False, loc='lower right')\n\tplot.save('powersummary')\n","repo_name":"smathot/baseline-pupil-size-study","sub_path":"data/analysis/power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"12597636413","text":"\"\"\"\nSerializers for all Course Entitlement related return objects.\n\"\"\"\n\n\nfrom django.contrib.auth import get_user_model\nfrom rest_framework import serializers\n\nfrom common.djangoapps.entitlements.models import CourseEntitlement, CourseEntitlementSupportDetail\nfrom openedx.core.lib.api.serializers import CourseKeyField\n\n\nclass CourseEntitlementSerializer(serializers.ModelSerializer):\n \"\"\" Serialize a learner's course entitlement and related information. \"\"\"\n user = serializers.SlugRelatedField(slug_field='username', queryset=get_user_model().objects.all())\n enrollment_course_run = serializers.CharField(\n source='enrollment_course_run.course_id',\n read_only=True\n )\n support_details = serializers.SerializerMethodField()\n\n def get_support_details(self, model):\n \"\"\"\n Returns a serialized set of all support interactions with the course entitlement\n \"\"\"\n qset = CourseEntitlementSupportDetail.objects.filter(entitlement=model).order_by('-created')\n return CourseEntitlementSupportDetailSerializer(qset, many=True).data\n\n class Meta:\n model = CourseEntitlement\n fields = (\n 'user',\n 'uuid',\n 'course_uuid',\n 'enrollment_course_run',\n 'expired_at',\n 'created',\n 'modified',\n 'mode',\n 'refund_locked',\n 'order_number',\n 'support_details'\n )\n\n\nclass CourseEntitlementSupportDetailSerializer(serializers.ModelSerializer):\n \"\"\" Serialize the details of a support team interaction with a learner's course entitlement. \"\"\"\n support_user = serializers.SlugRelatedField(\n read_only=True,\n slug_field='username',\n default=serializers.CurrentUserDefault()\n )\n unenrolled_run = CourseKeyField(read_only='unenrolled_run.id')\n\n class Meta:\n model = CourseEntitlementSupportDetail\n fields = (\n 'support_user',\n 'action',\n 'comments',\n 'unenrolled_run',\n 'created'\n )\n","repo_name":"openedx/edx-platform","sub_path":"common/djangoapps/entitlements/rest_api/v1/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","stars":6774,"dataset":"github-code","pt":"3"}
+{"seq_id":"39022324174","text":"from tkinter import *\nfrom tkinter.filedialog import askopenfilename\n\nfrom nogui import clip\n\n\ndef choose_input_file():\n filename = askopenfilename()\n INPUT_FILE.set(filename)\n\n\ndef choose_clip_file():\n filename = askopenfilename()\n CLIP_FILE.set(filename)\n\n\ndef choose_output_file():\n filename = askopenfilename()\n OUTPUT_FILE.set(filename)\n\n\ndef execute():\n result = clip(INPUT_FILE.get(), CLIP_FILE.get(), OUTPUT_FILE.get())\n RESULT.set(result)\n\n\ndef destroy():\n root_window.destroy()\n\n\nroot_window = Tk()\n\nINPUT_FILE = StringVar(\"\")\nCLIP_FILE = StringVar(\"\")\nOUTPUT_FILE = StringVar(\"\")\nRESULT = StringVar(\"\")\n\nroot_window.title(\"CLIP\")\nroot_window.resizable(width=False, height=False)\n\ninput_desc = Label(root_window, text=\"Input layer:\")\ninput_desc.grid(row=0, column=0)\n\ninput_text = Entry(root_window, text=INPUT_FILE)\ninput_text.grid(row=0, column=1, columnspan=2, sticky=EW)\n\ninput_choose = Button(root_window, text=\"...\", command=choose_input_file)\ninput_choose.grid(row=0, column=3, sticky=W)\n\nclip_desc = Label(root_window, text=\"Clip layer:\")\nclip_desc.grid(row=1, column=0)\n\nclip_text = Entry(root_window, text=CLIP_FILE)\nclip_text.grid(row=1, column=1, columnspan=2, sticky=EW)\n\nclip_choose = Button(root_window, text=\"...\", command=choose_clip_file)\nclip_choose.grid(row=1, column=3, sticky=W)\n\noutput_desc = Label(root_window, text=\"Output layer:\")\noutput_desc.grid(row=2, column=0)\n\noutput_text = Entry(root_window, text=OUTPUT_FILE)\noutput_text.grid(row=2, column=1, columnspan=2, sticky=EW)\n\noutput_choose = Button(root_window, text=\"...\", command=choose_output_file)\noutput_choose.grid(row=2, column=3, sticky=W)\n\nrun = Button(root_window, text=\"RUN\", command=execute)\nrun.grid(row=3, column=2, sticky=\"e\")\n\ncancel = Button(root_window, text=\"CANCEL\", command=destroy)\ncancel.grid(row=3, column=3, sticky=\"w\")\n\nresult_label = Label(root_window, textvariable=RESULT)\nresult_label.grid(row=4, column=0, columnspan=4)\n\nroot_window.mainloop()\n","repo_name":"kam-iwa/os","sub_path":"files/includes.chroot/bin/gis/vector/clip/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6471586430","text":"from drf_yasg import openapi\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_201_CREATED, HTTP_200_OK\nfrom rest_framework.viewsets import ViewSet\n\nfrom django_api.auth import ApiAuth\nfrom purchase_orders.serializers import PurchaseOrdersCreationSerializer, PurchaseOrdersSerializer, \\\n PurchaseOrdersDetailsSerializer, CashbackQuerySerializer, CashbackTotalSerializer\nfrom purchase_orders.services import PurchaseOrdersService\n\n\nclass PurchaseOrdersViewSet(ViewSet):\n authentication_classes = (ApiAuth,)\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.purchase_orders_service = PurchaseOrdersService()\n\n @swagger_auto_schema(request_body=PurchaseOrdersCreationSerializer,\n responses={201: openapi.Response('response description', PurchaseOrdersSerializer),\n 400: 'bad request'})\n @action(methods=['POST'], detail=False)\n def create_new_order(self, request):\n serializer = PurchaseOrdersCreationSerializer(data=request.data)\n\n if serializer.is_valid():\n try:\n purchase_order = self.purchase_orders_service.create_new_order(serializer.data)\n return Response(data=PurchaseOrdersSerializer(purchase_order).data, status=HTTP_201_CREATED)\n except Exception as e:\n return Response(data=str(e), status=HTTP_400_BAD_REQUEST)\n else:\n return Response(data=serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n @swagger_auto_schema(responses={200: openapi.Response('response description',\n PurchaseOrdersDetailsSerializer(many=True)),\n 400: 'bad request'})\n @action(methods=['GET'], detail=False)\n def list_orders(self, request):\n try:\n purchase_orders = self.purchase_orders_service.get_all_orders()\n return Response(data=PurchaseOrdersDetailsSerializer(purchase_orders, many=True).data, status=HTTP_200_OK)\n except Exception as e:\n return Response(data=str(e), status=HTTP_400_BAD_REQUEST)\n\n @swagger_auto_schema(query_serializer=CashbackQuerySerializer,\n responses={200: openapi.Response('response description',CashbackTotalSerializer),\n 400: 'bad request'})\n @action(methods=['GET'], detail=False)\n def get_cashback_total(self, request):\n try:\n data = self.purchase_orders_service.get_cashback_total(request.query_params['cpf'])\n return Response(CashbackTotalSerializer(data).data, status=HTTP_200_OK)\n except Exception as e:\n return Response(data=str(e), status=HTTP_400_BAD_REQUEST)\n\n","repo_name":"brandomota/django-api","sub_path":"purchase_orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34103487005","text":"# 시간 복잡도: 2초 -> CPU clock 1GHz 기준, N = 100,000일 때, O(NlogN)인 알고리즘이면 통과.\n# 공간 복잡도: 128MB -> int 기준 32M (32 * 10^6)개 변수 = 약 3200만개 = 즉 1,000만 단위 이상이면 잘못된 알고리즘 설계.\n\ndef solution(time_list):\n time_list.sort(key=lambda x: (x[1], x[0]))\n count = 0\n end_last = 0\n for (st, end) in time_list:\n if st >= end_last:\n count += 1\n end_last = end\n return count\n\n\nN = int(input())\ntime_list = [[0, 0] for _ in range(N)]\nfor i in range(N):\n time_list[i][0], time_list[i][1] = map(int, input().split(' '))\n\nprint(solution(time_list))","repo_name":"JUiscoming/algorithm","sub_path":"baekjoon/greedy/1931. 회의실 배정.py","file_name":"1931. 회의실 배정.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"25877948522","text":"import copy\n\nfrom oslo_db import exception as db_exc\nfrom oslo_utils import uuidutils\nfrom oslo_utils import versionutils\nfrom sqlalchemy.orm import contains_eager\nfrom sqlalchemy.orm import joinedload\n\nfrom nova.compute import utils as compute_utils\nfrom nova import db\nfrom nova.db.sqlalchemy import api as db_api\nfrom nova.db.sqlalchemy import api_models\nfrom nova.db.sqlalchemy import models as main_models\nfrom nova import exception\nfrom nova import objects\nfrom nova.objects import base\nfrom nova.objects import fields\n\n\nLAZY_LOAD_FIELDS = ['hosts']\n\n\ndef _instance_group_get_query(context, id_field=None, id=None):\n query = context.session.query(api_models.InstanceGroup).\\\n options(joinedload('_policies')).\\\n options(joinedload('_members'))\n if not context.is_admin:\n query = query.filter_by(project_id=context.project_id)\n if id and id_field:\n query = query.filter(id_field == id)\n return query\n\n\ndef _instance_group_model_get_query(context, model_class, group_id):\n return context.session.query(model_class).filter_by(group_id=group_id)\n\n\ndef _instance_group_model_add(context, model_class, items, item_models, field,\n group_id, append_to_models=None):\n models = []\n already_existing = set()\n for db_item in item_models:\n already_existing.add(getattr(db_item, field))\n models.append(db_item)\n for item in items:\n if item in already_existing:\n continue\n model = model_class()\n values = {'group_id': group_id}\n values[field] = item\n model.update(values)\n context.session.add(model)\n if append_to_models:\n append_to_models.append(model)\n models.append(model)\n return models\n\n\ndef _instance_group_policies_add(context, group, policies):\n query = _instance_group_model_get_query(context,\n api_models.InstanceGroupPolicy,\n group.id)\n query = query.filter(\n api_models.InstanceGroupPolicy.policy.in_(set(policies)))\n return _instance_group_model_add(context, api_models.InstanceGroupPolicy,\n policies, query.all(), 'policy', group.id,\n append_to_models=group._policies)\n\n\ndef _instance_group_members_add(context, group, members):\n query = _instance_group_model_get_query(context,\n api_models.InstanceGroupMember,\n group.id)\n query = query.filter(\n api_models.InstanceGroupMember.instance_uuid.in_(set(members)))\n return _instance_group_model_add(context, api_models.InstanceGroupMember,\n members, query.all(), 'instance_uuid',\n group.id, append_to_models=group._members)\n\n\ndef _instance_group_members_add_by_uuid(context, group_uuid, members):\n # NOTE(melwitt): The condition on the join limits the number of members\n # returned to only those we wish to check as already existing.\n group = context.session.query(api_models.InstanceGroup).\\\n outerjoin(api_models.InstanceGroupMember,\n api_models.InstanceGroupMember.instance_uuid.in_(set(members))).\\\n filter(api_models.InstanceGroup.uuid == group_uuid).\\\n options(contains_eager('_members')).first()\n if not group:\n raise exception.InstanceGroupNotFound(group_uuid=group_uuid)\n return _instance_group_model_add(context, api_models.InstanceGroupMember,\n members, group._members, 'instance_uuid',\n group.id)\n\n\n# TODO(berrange): Remove NovaObjectDictCompat\n@base.NovaObjectRegistry.register\nclass InstanceGroup(base.NovaPersistentObject, base.NovaObject,\n base.NovaObjectDictCompat):\n # Version 1.0: Initial version\n # Version 1.1: String attributes updated to support unicode\n # Version 1.2: Use list/dict helpers for policies, metadetails, members\n # Version 1.3: Make uuid a non-None real string\n # Version 1.4: Add add_members()\n # Version 1.5: Add get_hosts()\n # Version 1.6: Add get_by_name()\n # Version 1.7: Deprecate metadetails\n # Version 1.8: Add count_members_by_user()\n # Version 1.9: Add get_by_instance_uuid()\n # Version 1.10: Add hosts field\n VERSION = '1.10'\n\n fields = {\n 'id': fields.IntegerField(),\n\n 'user_id': fields.StringField(nullable=True),\n 'project_id': fields.StringField(nullable=True),\n\n 'uuid': fields.UUIDField(),\n 'name': fields.StringField(nullable=True),\n\n 'policies': fields.ListOfStringsField(nullable=True),\n 'members': fields.ListOfStringsField(nullable=True),\n 'hosts': fields.ListOfStringsField(nullable=True),\n }\n\n def obj_make_compatible(self, primitive, target_version):\n target_version = versionutils.convert_version_to_tuple(target_version)\n if target_version < (1, 7):\n # NOTE(danms): Before 1.7, we had an always-empty\n # metadetails property\n primitive['metadetails'] = {}\n\n @staticmethod\n def _from_db_object(context, instance_group, db_inst):\n \"\"\"Method to help with migration to objects.\n\n Converts a database entity to a formal object.\n \"\"\"\n # Most of the field names match right now, so be quick\n for field in instance_group.fields:\n if field in LAZY_LOAD_FIELDS:\n continue\n # This is needed to handle db models from both the api\n # database and the main database. In the migration to\n # the api database, we have removed soft-delete, so\n # the object fields for delete must be filled in with\n # default values for db models from the api database.\n ignore = {'deleted': False,\n 'deleted_at': None}\n if field in ignore and not hasattr(db_inst, field):\n instance_group[field] = ignore[field]\n else:\n instance_group[field] = db_inst[field]\n\n instance_group._context = context\n instance_group.obj_reset_changes()\n return instance_group\n\n @staticmethod\n @db_api.api_context_manager.reader\n def _get_from_db_by_uuid(context, uuid):\n grp = _instance_group_get_query(context,\n id_field=api_models.InstanceGroup.uuid,\n id=uuid).first()\n if not grp:\n raise exception.InstanceGroupNotFound(group_uuid=uuid)\n return grp\n\n @staticmethod\n @db_api.api_context_manager.reader\n def _get_from_db_by_id(context, id):\n grp = _instance_group_get_query(context,\n id_field=api_models.InstanceGroup.id,\n id=id).first()\n if not grp:\n raise exception.InstanceGroupNotFound(group_uuid=id)\n return grp\n\n @staticmethod\n @db_api.api_context_manager.reader\n def _get_from_db_by_name(context, name):\n grp = _instance_group_get_query(context).filter_by(name=name).first()\n if not grp:\n raise exception.InstanceGroupNotFound(group_uuid=name)\n return grp\n\n @staticmethod\n @db_api.api_context_manager.reader\n def _get_from_db_by_instance(context, instance_uuid):\n grp_member = context.session.query(api_models.InstanceGroupMember).\\\n filter_by(instance_uuid=instance_uuid).first()\n if not grp_member:\n raise exception.InstanceGroupNotFound(group_uuid='')\n grp = InstanceGroup._get_from_db_by_id(context, grp_member.group_id)\n return grp\n\n @staticmethod\n @db_api.api_context_manager.writer\n def _save_in_db(context, group_uuid, values):\n grp = _instance_group_get_query(context,\n id_field=api_models.InstanceGroup.uuid,\n id=group_uuid).first()\n if not grp:\n raise exception.InstanceGroupNotFound(group_uuid=group_uuid)\n\n values_copy = copy.copy(values)\n policies = values_copy.pop('policies', None)\n members = values_copy.pop('members', None)\n\n grp.update(values_copy)\n\n if policies is not None:\n _instance_group_policies_add(context, grp, policies)\n if members is not None:\n _instance_group_members_add(context, grp, members)\n\n return grp\n\n @staticmethod\n @db_api.api_context_manager.writer\n def _create_in_db(context, values, policies=None, members=None):\n try:\n group = api_models.InstanceGroup()\n group.update(values)\n group.save(context.session)\n except db_exc.DBDuplicateEntry:\n raise exception.InstanceGroupIdExists(group_uuid=values['uuid'])\n\n if policies:\n group._policies = _instance_group_policies_add(context, group,\n policies)\n else:\n group._policies = []\n\n if members:\n group._members = _instance_group_members_add(context, group,\n members)\n else:\n group._members = []\n\n return group\n\n @staticmethod\n @db_api.api_context_manager.writer\n def _destroy_in_db(context, group_uuid):\n qry = _instance_group_get_query(context,\n id_field=api_models.InstanceGroup.uuid,\n id=group_uuid)\n if qry.count() == 0:\n raise exception.InstanceGroupNotFound(group_uuid=group_uuid)\n\n # Delete policies and members\n group_id = qry.first().id\n instance_models = [api_models.InstanceGroupPolicy,\n api_models.InstanceGroupMember]\n for model in instance_models:\n context.session.query(model).filter_by(group_id=group_id).delete()\n\n qry.delete()\n\n @staticmethod\n @db_api.api_context_manager.writer\n def _add_members_in_db(context, group_uuid, members):\n return _instance_group_members_add_by_uuid(context, group_uuid,\n members)\n\n def obj_load_attr(self, attrname):\n # NOTE(sbauza): Only hosts could be lazy-loaded right now\n if attrname != 'hosts':\n raise exception.ObjectActionError(\n action='obj_load_attr', reason='unable to load %s' % attrname)\n\n self.hosts = self.get_hosts()\n self.obj_reset_changes(['hosts'])\n\n @base.remotable_classmethod\n def get_by_uuid(cls, context, uuid):\n db_group = None\n try:\n db_group = cls._get_from_db_by_uuid(context, uuid)\n except exception.InstanceGroupNotFound:\n pass\n if db_group is None:\n db_group = db.instance_group_get(context, uuid)\n return cls._from_db_object(context, cls(), db_group)\n\n @base.remotable_classmethod\n def get_by_name(cls, context, name):\n try:\n db_group = cls._get_from_db_by_name(context, name)\n except exception.InstanceGroupNotFound:\n igs = InstanceGroupList._get_main_by_project_id(context,\n context.project_id)\n for ig in igs:\n if ig.name == name:\n return ig\n raise exception.InstanceGroupNotFound(group_uuid=name)\n return cls._from_db_object(context, cls(), db_group)\n\n @base.remotable_classmethod\n def get_by_instance_uuid(cls, context, instance_uuid):\n db_group = None\n try:\n db_group = cls._get_from_db_by_instance(context, instance_uuid)\n except exception.InstanceGroupNotFound:\n pass\n if db_group is None:\n db_group = db.instance_group_get_by_instance(context,\n instance_uuid)\n return cls._from_db_object(context, cls(), db_group)\n\n @classmethod\n def get_by_hint(cls, context, hint):\n if uuidutils.is_uuid_like(hint):\n return cls.get_by_uuid(context, hint)\n else:\n return cls.get_by_name(context, hint)\n\n @base.remotable\n def save(self):\n \"\"\"Save updates to this instance group.\"\"\"\n\n updates = self.obj_get_changes()\n\n # NOTE(sbauza): We do NOT save the set of compute nodes that an\n # instance group is connected to in this method. Instance groups are\n # implicitly connected to compute nodes when the\n # InstanceGroup.add_members() method is called, which adds the mapping\n # table entries.\n # So, since the only way to have hosts in the updates is to set that\n # field explicitly, we prefer to raise an Exception so the developer\n # knows he has to call obj_reset_changes(['hosts']) right after setting\n # the field.\n if 'hosts' in updates:\n raise exception.InstanceGroupSaveException(field='hosts')\n\n if not updates:\n return\n\n payload = dict(updates)\n payload['server_group_id'] = self.uuid\n\n try:\n db_group = self._save_in_db(self._context, self.uuid, updates)\n except exception.InstanceGroupNotFound:\n db.instance_group_update(self._context, self.uuid, updates)\n db_group = db.instance_group_get(self._context, self.uuid)\n self._from_db_object(self._context, self, db_group)\n compute_utils.notify_about_server_group_update(self._context,\n \"update\", payload)\n\n @base.remotable\n def refresh(self):\n \"\"\"Refreshes the instance group.\"\"\"\n current = self.__class__.get_by_uuid(self._context, self.uuid)\n for field in self.fields:\n if self.obj_attr_is_set(field) and self[field] != current[field]:\n self[field] = current[field]\n self.obj_reset_changes()\n\n def _create(self, skipcheck=False):\n # NOTE(danms): This is just for the migration routine, and\n # can be removed once we're no longer supporting the migration\n # of instance groups from the main to api database.\n if self.obj_attr_is_set('id'):\n raise exception.ObjectActionError(action='create',\n reason='already created')\n updates = self.obj_get_changes()\n payload = dict(updates)\n updates.pop('id', None)\n policies = updates.pop('policies', None)\n members = updates.pop('members', None)\n\n if 'uuid' not in updates:\n self.uuid = uuidutils.generate_uuid()\n updates['uuid'] = self.uuid\n\n if not skipcheck:\n try:\n db.instance_group_get(self._context, self.uuid)\n raise exception.ObjectActionError(\n action='create',\n reason='already created in main')\n except exception.InstanceGroupNotFound:\n pass\n db_group = self._create_in_db(self._context, updates,\n policies=policies,\n members=members)\n self._from_db_object(self._context, self, db_group)\n payload['server_group_id'] = self.uuid\n compute_utils.notify_about_server_group_update(self._context,\n \"create\", payload)\n\n @base.remotable\n def create(self):\n self._create()\n\n @base.remotable\n def destroy(self):\n payload = {'server_group_id': self.uuid}\n try:\n self._destroy_in_db(self._context, self.uuid)\n except exception.InstanceGroupNotFound:\n db.instance_group_delete(self._context, self.uuid)\n self.obj_reset_changes()\n compute_utils.notify_about_server_group_update(self._context,\n \"delete\", payload)\n\n @base.remotable_classmethod\n def add_members(cls, context, group_uuid, instance_uuids):\n payload = {'server_group_id': group_uuid,\n 'instance_uuids': instance_uuids}\n try:\n members = cls._add_members_in_db(context, group_uuid,\n instance_uuids)\n members = [member['instance_uuid'] for member in members]\n except exception.InstanceGroupNotFound:\n members = db.instance_group_members_add(context, group_uuid,\n instance_uuids)\n compute_utils.notify_about_server_group_update(context,\n \"addmember\", payload)\n return list(members)\n\n @base.remotable\n def get_hosts(self, exclude=None):\n \"\"\"Get a list of hosts for non-deleted instances in the group\n\n This method allows you to get a list of the hosts where instances in\n this group are currently running. There's also an option to exclude\n certain instance UUIDs from this calculation.\n\n \"\"\"\n filter_uuids = self.members\n if exclude:\n filter_uuids = set(filter_uuids) - set(exclude)\n filters = {'uuid': filter_uuids, 'deleted': False}\n instances = objects.InstanceList.get_by_filters(self._context,\n filters=filters)\n return list(set([instance.host for instance in instances\n if instance.host]))\n\n @base.remotable\n def count_members_by_user(self, user_id):\n \"\"\"Count the number of instances in a group belonging to a user.\"\"\"\n filter_uuids = self.members\n filters = {'uuid': filter_uuids, 'user_id': user_id, 'deleted': False}\n instances = objects.InstanceList.get_by_filters(self._context,\n filters=filters)\n return len(instances)\n\n\n@base.NovaObjectRegistry.register\nclass InstanceGroupList(base.ObjectListBase, base.NovaObject):\n # Version 1.0: Initial version\n # InstanceGroup <= version 1.3\n # Version 1.1: InstanceGroup <= version 1.4\n # Version 1.2: InstanceGroup <= version 1.5\n # Version 1.3: InstanceGroup <= version 1.6\n # Version 1.4: InstanceGroup <= version 1.7\n # Version 1.5: InstanceGroup <= version 1.8\n # Version 1.6: InstanceGroup <= version 1.9\n # Version 1.7: InstanceGroup <= version 1.10\n VERSION = '1.7'\n\n fields = {\n 'objects': fields.ListOfObjectsField('InstanceGroup'),\n }\n\n @staticmethod\n @db_api.api_context_manager.reader\n def _get_from_db(context, project_id=None):\n query = _instance_group_get_query(context)\n if project_id is not None:\n query = query.filter_by(project_id=project_id)\n return query.all()\n\n @classmethod\n def _get_main_by_project_id(cls, context, project_id):\n main_db_groups = db.instance_group_get_all_by_project_id(context,\n project_id)\n return base.obj_make_list(context, cls(context), objects.InstanceGroup,\n main_db_groups)\n\n @base.remotable_classmethod\n def get_by_project_id(cls, context, project_id):\n api_db_groups = cls._get_from_db(context, project_id=project_id)\n main_db_groups = db.instance_group_get_all_by_project_id(context,\n project_id)\n return base.obj_make_list(context, cls(context), objects.InstanceGroup,\n api_db_groups + main_db_groups)\n\n @base.remotable_classmethod\n def get_all(cls, context):\n api_db_groups = cls._get_from_db(context)\n main_db_groups = db.instance_group_get_all(context)\n return base.obj_make_list(context, cls(context), objects.InstanceGroup,\n api_db_groups + main_db_groups)\n\n\n@db_api.main_context_manager.reader\ndef _get_main_instance_groups(context, limit):\n return context.session.query(main_models.InstanceGroup).\\\n options(joinedload('_policies')).\\\n options(joinedload('_members')).\\\n filter_by(deleted=0).\\\n limit(limit).\\\n all()\n\n\ndef migrate_instance_groups_to_api_db(context, count):\n main_groups = _get_main_instance_groups(context, count)\n done = 0\n for db_group in main_groups:\n group = objects.InstanceGroup(context=context,\n user_id=db_group.user_id,\n project_id=db_group.project_id,\n uuid=db_group.uuid,\n name=db_group.name,\n policies=db_group.policies,\n members=db_group.members)\n try:\n group._create(skipcheck=True)\n except exception.InstanceGroupIdExists:\n # NOTE(melwitt): This might happen if there's a failure right after\n # the InstanceGroup was created and the migration is re-run.\n pass\n db_api.instance_group_delete(context, db_group.uuid)\n done += 1\n return len(main_groups), done\n","repo_name":"eepalms/CloudMonatt","sub_path":"OpenStack/nova/nova/objects/instance_group.py","file_name":"instance_group.py","file_ext":"py","file_size_in_byte":21492,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"4109314585","text":"# ch4_6.py\r\nimport matplotlib.pyplot as plt\r\nfrom sympy import Symbol, solve\r\nimport numpy as np\r\n\r\nplt.rcParams[\"font.family\"] = [\"Microsoft JhengHei\"]\r\n \r\nx = Symbol('x') # 定义公式中使用的变数\r\ny = Symbol('y') # 定义公式中使用的变数\r\neq1 = x + y - 100 # 方程式 1\r\neq2 = 2 * x + 4 * y - 350 # 方程式 2\r\nans = solve((eq1, eq2))\r\nprint(f'菜鸟业务员须外出天数 = {ans[x]}')\r\nprint(f'资深业务员须外出天数 = {ans[y]}')\r\n\r\nline1_x = np.linspace(0, 100, 100)\r\nline1_y = [100 - y for y in line1_x]\r\nline2_x = np.linspace(0, 100, 100)\r\nline2_y = [(350 - 2 * y) / 4 for y in line2_x]\r\n\r\nplt.plot(line1_x, line1_y) # 绘函数直线公式 1\r\nplt.plot(line2_x, line2_y) # 绘函数直线公式 2\r\n\r\nplt.plot(ans[x], ans[y], '-o') # 绘交叉点\r\nplt.text(ans[x]-5, ans[y]+5, '('+str(ans[x])+','+str(ans[y])+')')\r\nplt.xlabel(\"菜鸟业务员\")\r\nplt.ylabel(\"资深业务员\")\r\nplt.grid() # 加格线\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"BD-Danielle/py-examples","sub_path":"9786267273784/DM2356機器學習專題實作讀者資源/程式實例/ch4/ch4_6.py","file_name":"ch4_6.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31825482189","text":"def square_all(l1):\n l2 = [x**2 for x in l1]\n return l2\n\n\ndef add_n_all(n, l1):\n for i in range(len(l1)):\n l1[i] += n\n return l1\n\n\ndef even_or_odd_all(l1):\n i = 0\n l2 = []\n while i < len(l1):\n if l1[i] % 2 == 0:\n l2.append(True)\n else:\n l2.append(False)\n i += 1\n return l2\n","repo_name":"stanleyarmstrong/CPE101","sub_path":"labs/lab5/map/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"6797670998","text":"from telegram import InlineKeyboardButton, InlineKeyboardMarkup\nfrom telegram.constants import ParseMode\nimport geopy.distance\nfrom conversation_states import *\nfrom db_connection import *\n\n\ndef button_show_nearest_location(update, context):\n # extracting each category name and creating an array of buttons with callback_data = type\n buttons = []\n\n # extracting categories from db and creating buttons for each of them\n all_categories = db.categories.find()\n for category in all_categories:\n buttons.append(\n [InlineKeyboardButton(text=category['name'], callback_data='category_' + category['type'])])\n\n # create keyboard instance\n reply_markup = InlineKeyboardMarkup(buttons)\n # send message with categories as inline buttons\n update.message.reply_text(text=\"Що здаємо на переробку?\", reply_markup=reply_markup)\n\n return FLOW_SHOW_NEAREST_LOCATION\n\n\ndef ask_for_location_when_category_selected(update, context):\n # store selected category to process after user sends location\n selected_category_type = update.callback_query.data.partition('_')[2]\n context.user_data['selected_category_type'] = selected_category_type\n\n # button 'how to send location'\n button = [\n [InlineKeyboardButton(text='Я не знаю як відправити локацію', callback_data='how_to_send_location')]\n ]\n reply_markup = InlineKeyboardMarkup(button)\n\n update.message.reply_text('Де ти зараз є? Відправ мені геолокацію.', reply_markup=reply_markup)\n\n return SEND_LOCATION\n\ndef show_gif_how_to_send_location(update, context):\n \n gif = open(\"how_to_send_location.mp4\", \"rb\")\n update.message.reply_document(gif)\n gif.close()\n\n return SEND_LOCATION\n\n\ndef process_location(update, context):\n # extract coordinates that users sends\n longitude = update.message.location.longitude\n latitude = update.message.location.latitude\n\n # fetch category user saved in ask_for_location func\n selected_category_type = context.user_data['selected_category_type']\n\n # fetch location collection from db\n all_locations_collection = db.locations\n\n # assume first location that matches selected category is nearest\n nearest_location = all_locations_collection.find_one({'categories': selected_category_type})\n # distance calculation\n min_distance = geopy.distance.geodesic((longitude, latitude), reversed(nearest_location['coordinates']))\n\n # search for nearest location\n all_locations = all_locations_collection.find()\n for location in all_locations:\n if selected_category_type in location['categories']:\n local_min = geopy.distance.geodesic((longitude, latitude), (location['coordinates']))\n if local_min < min_distance:\n min_distance = local_min\n nearest_location = location\n\n # replacing each category.type in location with category.name. for example [paper] is replaced with string 'Paper'\n categories_names = ''\n # fetch categories collection to find real name\n for category_in_location in nearest_location['categories']:\n for category in db.categories.find():\n if category_in_location == category['type']:\n categories_names = categories_names + (category['name']) + '\\n'\n break\n\n # send category info\n update.message.reply_text(\n 'Ось що знайшов поблизу:\\n\\n{}\\n{}\\n{}\\n\\n*{}*\\n{}км'.format(nearest_location['name'],\n nearest_location['address'],\n nearest_location['workingHours'],\n categories_names,\n int(min_distance.km)),\n parse_mode=ParseMode.MARKDOWN)\n\n # send the Location object\n nearest_latitude, nearest_longitude = reversed(nearest_location['coordinates'])\n update.message.bot.send_location(chat_id=update.effective_chat.id,\n latitude=nearest_latitude,\n longitude=nearest_longitude)\n\n # buttons to display after location has been sent\n buttons = [\n [InlineKeyboardButton(text='Так', callback_data='show_how_to_prepare_category')],\n [InlineKeyboardButton(text='До головного меню', callback_data='to_main_menu')] # add common button\n ]\n\n # create keyboard instance\n reply_markup = InlineKeyboardMarkup(buttons)\n # send message on /show_how_to_prepare action\n update.message.reply_text('Розказати, як підготувати його до здачі?', reply_markup=reply_markup)\n\n return FLOW_SHOW_NEAREST_LOCATION\n\n\ndef show_how_to_prepare_category(update, context):\n selected_category_type = context.user_data['selected_category_type']\n\n selected_category = db.categories.find_one({'type': selected_category_type})\n\n button = [\n [InlineKeyboardButton(text='До головного меню', callback_data='to_main_menu')] # add common button\n ]\n\n reply_markup = InlineKeyboardMarkup(button)\n\n # update.message.reply_text(\n # text='Як підготувати сміття категорії *{'+nearest_location['description']+'}* до переробки:\\n',\n # reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN)\n\n update.message.reply_text( # add formatters\n 'Як підготувати сміття категорії *{}* до переробки:\\n\\n{}\\n\\n✅{}\\n\\n❌{}\\n\\nℹ️{}'.format(\n selected_category['name'],\n selected_category['description'],\n selected_category['do'],\n selected_category['dont'],\n selected_category['steps']),\n reply_markup=reply_markup,\n parse_mode=ParseMode.MARKDOWN)\n\n return FLOW_SHOW_NEAREST_LOCATION\n\n# category_type = update.callback_query.data.partition('_')[2]\n#\n# description = db.categories.find_one({\"type\": str(category_type)})['description']\n#\n# update.message.reply_text(description)\n","repo_name":"keeelori/MotiWasteBot","sub_path":"flow_show_nearest_location.py","file_name":"flow_show_nearest_location.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"19633035589","text":"\nfrom environment import *\nfrom sensor import *\nfrom target import *\n\n# env_testing.py \n# version 0.2 : initial development \n\nenv_test = Environment((1200, 800))\n#env_test = Environment((800, 600))\n#env_test = Environment((600, 400))\n\n#target_list = env_test.generate_target_list(10) # generate a batch of targets\n\n# 4 fixed sensors at the intersection\n#sensor_list = [(650,450, 90), (550,450, 90), (550,350, 90), (650,350, 90)]\n#sensor_list = [(650,450, 90)] # bottom right 1x1 \nsensor_list = [(650,450, 90), (550,350, 90)] # bottom right & top left 1x1 \n# create the environment\ntarget_1, sensor_1, buildings =env_test.create_env(0, # number of targets \n sensor_list, # list of sensor positions\n 1, # number of vertical lanes\n 1) # number of horizontal lanes\n\n# run the simulation\nenv_test.run_env(target_1, sensor_1, buildings)\n\nenv_test.env_stats()\n\n\n\n","repo_name":"CTGlodek/DREAM","sub_path":"Versions/feDQN/env_testing.py","file_name":"env_testing.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32287048371","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport tempfile\nimport os\nimport copy\nimport shutil\n\nfrom corral import run, db\n\nimport sh\n\nimport numpy as np\n\nfrom ..models import Pawprint\nfrom .. import bin\n\n\nPAWPRINTS_DEFAULT_PARAMS = {\n \"dtype\": {\n \"names\": [\n 'ra_h', 'ra_m', 'ra_s', 'dec_d', 'dec_m', 'dec_s',\n 'x', 'y', 'mag', 'mag_err',\n 'chip_nro', 'stel_cls', 'elip', 'pos_ang',\n ],\n \"formats\": [\n int, int, float, int, int, float,\n float, float, float, float,\n int, int, float, float,\n ]\n }\n}\n\n\nclass MeasurePawprint(run.Step):\n\n model = Pawprint\n conditions = [model.status == \"raw\"]\n procno = 3\n production_procno = 30\n groups = [\"measurement\"]\n\n @classmethod\n def class_setup(cls):\n\n def chunk_it(seq, num):\n avg = len(seq) / float(num)\n out = []\n last = 0.0\n while last < len(seq):\n out.append(seq[int(last):int(last + avg)])\n last += avg\n return sorted(out, reverse=True)\n\n with db.session_scope() as session:\n all_ids = tuple(\n r[0] for r in\n session.query(cls.model.id).filter(*cls.conditions))\n db.engine.dispose()\n cls.chunks = chunk_it(all_ids, cls.get_procno())\n\n def generate(self):\n if not self.chunks:\n return ()\n ids = self.chunks[self.current_proc]\n if not ids:\n return ()\n query = self.session.query(self.model).filter(self.model.id.in_(ids))\n return query\n\n def setup(self):\n self.work_path = tempfile.mkdtemp(\"_measure_pawprint\")\n self.asc_path = os.path.join(self.work_path, \"catalogue.asc\")\n if os.path.isfile(self.asc_path):\n raise IOError(\"Duplicated {}\".format(self.asc_path))\n self.fitsio_cat_list = sh.Command(bin.get(\"fitsio_cat_list\"))\n os.chdir(self.work_path)\n\n def teardown(self, *args, **kwargs):\n if os.path.isdir(self.work_path):\n shutil.rmtree(self.work_path)\n\n def ra_to_degree(self, arr):\n return 15 * (\n arr['ra_h'] +\n arr['ra_m'] / 60.0 +\n arr['ra_s'] / 3600.0)\n\n def dec_to_degree(self, arr):\n return np.sign(arr['dec_d']) * (\n np.abs(arr['dec_d']) +\n arr['dec_m'] / 60.0 +\n arr['dec_s'] / 3600.0)\n\n def to_array(self, path):\n filename = os.path.basename(path)\n\n tmp_file_path = os.path.join(self.work_path, filename)\n os.symlink(path, tmp_file_path)\n\n self.fitsio_cat_list(tmp_file_path)\n\n odata = np.genfromtxt(self.asc_path, **PAWPRINTS_DEFAULT_PARAMS)\n\n ra_deg = self.ra_to_degree(odata)\n dec_deg = self.dec_to_degree(odata)\n\n conf = copy.deepcopy(PAWPRINTS_DEFAULT_PARAMS)\n conf[\"dtype\"][\"names\"].insert(0, \"dec_deg\")\n conf[\"dtype\"][\"names\"].insert(0, \"ra_deg\")\n conf[\"dtype\"][\"formats\"].insert(0, float)\n conf[\"dtype\"][\"formats\"].insert(0, float)\n\n data = np.empty(len(odata), **conf)\n for name in data.dtype.names:\n if name == \"ra_deg\":\n data[name] = ra_deg\n elif name == \"dec_deg\":\n data[name] = dec_deg\n else:\n data[name] = odata[name]\n return data\n\n def process(self, pwp):\n path = pwp.file_path()\n pwp.data = self.to_array(path)\n pwp.data_size = len(pwp.data)\n pwp.data_readed = 0\n pwp.status = \"measured\"\n","repo_name":"carpyncho/yeolde_carpyncho","sub_path":"carpyncho2/carpyncho/steps/measure_pawprint.py","file_name":"measure_pawprint.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22473508896","text":"import plotly.graph_objects as go\n\ndef plot():\n fig = go.Figure()\n fig.add_trace(go.Bar(\n y = [3, 2, 1],\n name = \"data1\"\n ))\n\n fig.update_layout(\n title=\"Plot One\",\n xaxis_title=\"Plot One X Axis\",\n yaxis_title=\"Plot One Y Axis\"\n )\n print(\"Plot One\")\n fig.show()\n###\n fig2 = go.Figure()\n fig2.add_trace(go.Bar(\n y = [1, 2, 3],\n name = \"data2\"\n ))\n fig2.update_layout(\n title=\"Plot Two\",\n xaxis_title=\"Plot Two X Axis\",\n yaxis_title=\"Plot Two Y Axis\"\n )\n print(\"Plot Two\")\n fig2.show()\ntest = plot()\ntest\n","repo_name":"carlosofscience/developers-stats-analysing-tool","sub_path":"project/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35384497285","text":"import json\nfrom typing import List, Optional\nimport requests\nimport sys\nimport os\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n\nfrom domain import StockPrice\nfrom api.type import AddStockPriceRequestType\n\nHOST = os.getenv(\"TOKO_HOST\")\nPORT = os.getenv(\"TOKO_PORT\")\n\ndef addPrice(props: AddStockPriceRequestType, isPrintLog: bool = False) -> Optional[StockPrice]:\n url = \"{}:{}/company/{}/stock\".format(HOST, PORT, props[\"companyID\"])\n try:\n result = requests.post(url, json=({\"props\": props}))\n except requests.exceptions.InvalidJSONError:\n # NOTE: いずれかの情報がyfinance APIから取得出来ていない場合\n return None\n\n price: StockPrice = json.loads(result.content.decode('utf-8'))\n if isPrintLog:\n print(\"[addPrice] result: {}\".format(price))\n return price\n\ndef getPriceList(companyID: int, isPrintLog: bool = False) -> List[StockPrice]:\n url = \"{}:{}/company/{}/stock\".format(HOST, PORT, companyID)\n result = requests.get(url)\n priceList: List[StockPrice] = json.loads(result.content.decode('utf-8'))\n if isPrintLog:\n print(\"[getPriceList] result: {}\".format(priceList))\n return priceList\n\n\ndef getPrice(companyID: int, id: int, isPrintLog: bool = False) -> StockPrice:\n url = \"{}:{}/company/{}/stock/{}\".format(HOST, PORT, companyID, id)\n result = requests.get(url)\n price: StockPrice = json.loads(result.content.decode('utf-8'))\n if isPrintLog:\n print(\"[getPrice] result: {}\".format(price))\n return price\n\n\nif __name__ == \"__main__\":\n # addPrice(\"test\", 1, 3)\n getPriceList(1)\n # getPriceList()\n","repo_name":"ruritoBlogger/Ange","sub_path":"src/api/stockPrice.py","file_name":"stockPrice.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39740707572","text":"from socket import *\nimport sys\n\n#Check input\nif len(sys.argv) != 4:\n print (\"Your command is not right. Please be in this format:client.py server_host server_port filename\")\n sys.exit(0)\n\n#Connect to server from input\nserverName = str(sys.argv[1])\nserverPort = int(sys.argv[2])\nclientSocket = socket(AF_INET, SOCK_STREAM)\nclientSocket.connect((serverName,serverPort))\n\n#Send request to server\nrequest = \"\\nGET /\" + str(sys.argv[3]) + \" HTTP/1.1\\n\\n\"\nclientSocket.send(request.encode())\n\n#Receive response from server\nmodifiedSentence = clientSocket.recv(1024)\nprint ('From Server:')\nwhile True:\n if not modifiedSentence:\n break\n print(modifiedSentence.decode())\n modifiedSentence = clientSocket.recv(1024)\n\n#Close client socket\nclientSocket.close()","repo_name":"ginsama01/webserver","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40220485214","text":"import RPi.GPIO as GPIO\n#import alarm\nfrom Bodythermo import setColor\nfrom buzzer import buzz\nledPin = 12 # define ledPin\nbuttonPinY = 37 # define buttonPin\nbuttonPinR = 35###\nledState = False\nRGBState = False\n\ndef setup():\n GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering\n GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode\n GPIO.setup(buttonPinY, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode\n GPIO.setup(buttonPinR, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode\n\ndef buttonEventR(channel): # When button is pressed, this function will be executed\n global ledState\n print ('buttonEvent GPIO%d' %channel)\n ledState = not ledState\n if ledState :\n print ('Alarm turned on >>>')\n setColor(0,100,100)\n GPIO.output(ledPin,ledState)\n buzz() \n else :\n print ('Alarm turned off <<<')\n setColor(100,100,100)\n GPIO.output(ledPin,ledState)\n #GPIO.output(ledPin,ledState)\n\ndef buttonEventY(channel):\n global RGBState\n print ('buttonEvent GPIO%d' %channel)\n RGBState = not RGBState\n if RGBState :\n setColor(0,0,0)#Flashlight enable>>requires yellow button still\n print(\"flashlight on\")\n else:\n print(\"flashlight off\")\n setColor(100,100,100)\n \ndef loop():\n #Button detect\n GPIO.add_event_detect(buttonPinR,GPIO.FALLING,callback = buttonEventR,bouncetime=300)\n GPIO.add_event_detect(buttonPinY,GPIO.FALLING,callback = buttonEventY,bouncetime=300)\n print(\"button enabled\")\n #while True:\n #pass\n\n\ndef destroy():\n GPIO.cleanup() # Release GPIO resource\nif __name__ == '__main__': # Program entrance\n print ('Program is starting...')\n setup()\n try:\n loop()\n except KeyboardInterrupt: # Press ctrl-c to end the program.\n destroy()","repo_name":"AdaptiveResonance/Pippy4Deck","sub_path":"Code/buttons.py","file_name":"buttons.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"11682366673","text":"import os.path\nimport sys\n\nfrom glideinwms.factory.tools.lib import gWftLogParser\n\nSTARTUP_DIR = sys.path[0]\nsys.path.append(os.path.join(STARTUP_DIR, \"../../..\"))\n\nUSAGE = \"Usage: cat_named_log.py [-monitor] \"\n\n\ndef main():\n if sys.argv[1] == \"-monitor\":\n lname = sys.argv[2]\n fname = sys.argv[3]\n # ((name1)|(name2)) allows to check for multiple names\n condor_log_id = f\"{lname}.monitor\"\n else:\n condor_log_id = sys.argv[1]\n fname = sys.argv[2]\n\n try:\n print(gWftLogParser.get_CondorLog(fname, condor_log_id))\n except:\n sys.stderr.write(\"%s\\n\" % USAGE)\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"glideinWMS/glideinwms","sub_path":"factory/tools/cat_named_log.py","file_name":"cat_named_log.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"3"}
+{"seq_id":"15961632124","text":"# <<교재 6장 시작>>\n\n# <6-1. 구구단 2단 만들기>\n# 함수 이름 GuGu\n# 입력받는 값 2\n# 출력하는 값 2단(2, 4, 6, 8, …, 18)\n# 결과는 리스트로 저장\ndef GuGu(n):\n result = []\n i = 1\n while i < 10:\n result.append(n*i)\n i = i +1\n return result\nprint(GuGu(2))\n# [2, 4, 6, 8, 10, 12, 14, 16, 18]\n\n# <6-2. 3과 5의 배수 합하기>\n# 10 미만의 자연수에서 3과 5의 배수를 구하면 3, 5, 6, 9이다.\n# 이들의 총합은 23이다.\n# 1000 미만의 자연수에서 3의 배수와 5의 배수의 총합을 구하라.\n\n# 1000미만의 자연수 구하기\nn =1\nwhile n < 1000:\n print(n)\n n += 1\nfor n in range(1,1000):\n print(n)\n\n# 3의 배수 찾기\nfor n in range(1,1000):\n if n%3 == 0:\n print(n)\n\n# 최종 결과\nresult = 0\nfor n in range(1, 1000):\n if n%3 == 0 or n%5 == 0:\n result += n\nprint(result)\n\n# <6-3. 게시판 페이징하기>\n# 함수 이름: getTotalPage\n# 입력 받는 값 :게시물의 총 건수(m), 한 페이지에 보여줄 게시물 수(n)\n# 출력하는 값: 총 페이지수\n\n# 총 페이지수 = (총 건수 / 한 페이지당 보여 줄 건수) + 1\n# 한 페이지당 10건식 예) 5 = (49/10) + 1\ndef getTotalPage(m, n):\n return m // n + 1\nprint(getTotalPage(5, 10)) # 1\nprint(getTotalPage(15, 10)) # 2\nprint(getTotalPage(25, 10)) # 3\nprint(getTotalPage(30, 10)) # 4\n\n# 총페이지가 0, 페이지 나눈 값이 0 일 때 오류 해결\ndef getTotalPage(m, n):\n if m == 0:\n print('게시물이 없습니다.')\n elif m % n ==0:\n return m // n\n else:\n return m // n + 1\n\nprint(getTotalPage(0, 10))\nprint(getTotalPage(15, 10))\nprint(getTotalPage(25, 10))\nprint(getTotalPage(30, 10))\n\n# <6-4. 간단한 메모장 만들기> : 생략\n\n# <6-5. 탭을 4개의 공백을 바꾸기> : 생략\n\n# <6-6. 하위 디렉토리 검색하기>\n# 1. 디렉토리 파일을 검색\nimport os\ndef search(dirname):\n filenames = os.listdir(dirname)\n for filename in filenames:\n full_filename = os.path.join(dirname, filename)\n print (full_filename)\nsearch(\"c:/\")\n# os.listdir를 사용하면 해당 디렉터리에 있는 파일들의 리스트를 구할 수 있다.\n# 파일 리스트는 파일 이름만 포함되어 있으므로 경로를 포함한 파일 이름을\n# 구하기 위해서는 입력으로 받은 dirname을 앞에 덧붙여 주어야 한다.\n# os 모듈에는 디렉터리와 파일 이름을 이어 주는 os.path.join 함수가 있으므로\n# 이 함수를 사용하면 디렉터리를 포함한 전체 경로를 쉽게 구할 수 있다.\n\n# 2.확장자가 .py인 파일만을 출력\nimport os\ndef search(dirname):\n filenames = os.listdir(dirname)\n for filename in filenames:\n full_filename = os.path.join(dirname, filename)\n ext = os.path.splitext(full_filename)[-1]\n if ext == '.py':\n print(full_filename)\nsearch(\"c:/\")\n\n# os.path.splitext는 파일 이름을 확장자를 기준으로 두 부분으로 나누어 준다.\n# os.path.splitext(full_filename)[-1]은 해당 파일의 확장자 이름이 된다.\n\n# 3. 하위 디렉토리도 검색\ndef search(dirname):\n try:\n filenames = os.listdir(dirname)\n for filename in filenames:\n full_filename = os.path.join(dirname, filename)\n if os.path.isdir(full_filename):\n search(full_filename) # 재귀\n else:\n ext = os.path.splitext(full_filename)[-1]\n if ext == '.py':\n print(full_filename)\n except PermissionError:\n pass\nsearch(\"c:/\")\n# try ... except PermissionError로 함수\n# os.listdir를 수행할 때 권한이 없는 디렉터리에 접근하더라도\n# 프로그램이 오류로 종료되지 않고 그냥 수행되도록 하기 위해서이다.\n\n# full_filename이 디렉터리인지 파일인지 구별하기 위하여\n# os.path.isdir 함수를 사용하였고 디렉터리일 경우\n# 해당 경로를 입력받아 다시 search 함수를 호출하였다.\n\n# 참고. 하위 디렉터리 검색을 쉽게 해주는 os.walk\nimport os\nfor (path, dir, files) in os.walk(\"c:/\"):\n for filename in files:\n ext = os.path.splitext(filename)[-1]\n if ext == '.py':\n print(\"%s/%s\" %(path, filename))\n\n# <6-7. 파이보>\n# 파이보 : https://pybo.kr\n# 질문 답변 게시판\n\n# <6-8. 코딩도장>\n# 코딩도장 : http://codingdojang.com\n# 코딩 문제 사이트\n\n# <<교재 6장 끝>>\n","repo_name":"skwang89/workspace","sub_path":"worktotal/work-Python/pywork5.py","file_name":"pywork5.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38133782359","text":"import pandas as pd\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nfrom matplotlib import pyplot as plt\nimport requests\n\nurl = 'https://finance.naver.com/item/sise_day.nhn?code=068270&page=1'\n\n# 전체 페이지 수 확인\nwith requests.get(url, headers={'User-agent': 'Mozilla/5.0'}) as doc:\n # doc : 파일경로나, url넘겨주는 위치, lxml : 웹페이지를 파싱할 방식\n html = BeautifulSoup(doc.text, 'lxml')\n pgrr = html.find('td', class_='pgRR')\n # pgRR : 맨 오른쪽 페이지\n # class_ : 파이썬에 class라는 지시어가 존재하기 때문에 구분하기 위해\n s = str(pgrr.a['href']).split('=')\n last_page = s[-1]\n # 마지막 원소가 전체 페이지 수\n\nprint(last_page)\n\n# 전체 페이지 읽어오기\ndf = pd.DataFrame()\nsise_url = 'https://finance.naver.com/item/sise_day.nhn?code=068270'\nfor page in range(1, int(last_page)+1):\n page_url = '{}&page={}'.format(sise_url, page)\n df = df.append(pd.read_html(page_url, header=0)[0])\n\ndf = df.dropna()\n# 값이 빠진 행 제거\ndf = df.iloc[0:30]\ndf = df.sort_values(by='날짜')\n\nplt.title('Celltrion (close)')\nplt.xticks(rotation=45)\nplt.plot(df['날짜'], df['종가'], 'co-')\nplt.grid(color='gray', linestyle='--')\nplt.show()","repo_name":"Banghyungjin/coding_test","sub_path":"백준/beautifulsoup_test.py","file_name":"beautifulsoup_test.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"8086786171","text":"\"\"\"\n====================================================================================\nGRID SEARCH MODEL HYPERPARAMETER OPTIMIZATION\nauthor : Gerardo Cano Perea\ndate : March 30, 2021.\n====================================================================================\n\"\"\"\n\n# Importing\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nplt.style.use('ggplot')\n\n# Dataset.\ndataset = pd.read_csv('Social_Network_Ads.csv')\nX = dataset.iloc[:, [2, 3]].values\ny = dataset.iloc[:, 4].values\n\n# Split into train/test\nfrom sklearn.model_selection import train_test_split\n\n[X_train, X_test, y_train, y_test] = train_test_split(X, y, test_size = 0.25, random_state = 0)\n\n# Scale Variables.\nfrom sklearn.preprocessing import StandardScaler\n\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n\n# SVC Machine Model.\nfrom sklearn.svm import SVC\n\nclassifier = SVC(kernel = 'rbf', random_state = 0)\nclassifier.fit(X_train, y_train)\n\n# Predictions.\ny_pred = classifier.predict(X_test)\n\n# Precision Metrics.\n# Confusion Matrix.\nfrom sklearn.metrics import confusion_matrix\n\ncm = confusion_matrix(y_test, y_pred)\n# k-Fold Cross Validation.\nfrom sklearn.model_selection import cross_val_score\n\naccuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)\naccuracies.mean()\naccuracies.std()\n\n# Grid Search Hyperparameter Tuning.\nfrom sklearn.model_selection import GridSearchCV\nparameters = [{'C': [1, 10, 100, 1000], 'kernel': ['linear']},\n {'C': [1, 10, 100, 1000], 'kernel': ['rbf'], 'gamma': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]}]\ngrid_search = GridSearchCV(estimator = classifier,\n param_grid = parameters,\n scoring = 'accuracy',\n cv = 10,\n n_jobs = -1)\ngrid_search = grid_search.fit(X_train, y_train)\n\nbest_accuracy = grid_search.best_score_\nbest_parameters = grid_search.best_params_\n\n\n","repo_name":"GCanoP/General-Machine-Learning","sub_path":"Machine Learning Courses/UDEMY Course Machine Learning/Section 9 Selection and Boosting/Model 1 Standard Grid Search/GCP_Grid_Search_Model.py","file_name":"GCP_Grid_Search_Model.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"44429780999","text":"\"\"\"Preload features lazily\n\nThe main purpose of this is to enable fast browsing of the h5 file.\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nfrom config import configuration as config\nfrom models.utils import ApproximationFile\nfrom models.exceptions import (\n FeatureNotFoundError,\n OrganismNotFoundError,\n MeasurementTypeNotFoundError,\n SimilarityMethodError,\n)\n\n# This dict has (organism, measurement_type) as keys and pandas series as\n# values. For each series, the *index* is the array of features, the values\n# are increasing integers to be used as an index in the h5 file\nfeature_series = {}\n\n\ndef load_features(organism, measurement_type=\"gene_expression\"):\n \"\"\"Preload list of features for an organism\"\"\"\n approx_path = config[\"paths\"][\"compressed_atlas\"].get(organism, None)\n if approx_path is None:\n raise OrganismNotFoundError(f\"Organism not found: {organism}\")\n\n with ApproximationFile(approx_path) as db:\n if measurement_type not in db:\n raise MeasurementTypeNotFoundError(\n f\"Measurement type not found: {measurement_type}\"\n )\n features = db[measurement_type][\"features\"].asstr()[:]\n features_lower = pd.Index(features).str.lower()\n features_lower = pd.Series(\n np.arange(len(features)), index=features_lower,\n ).to_frame(name='index')\n features_lower['name'] = features\n feature_series[(organism, measurement_type)] = features_lower\n\n\ndef get_features(organism, measurement_type=\"gene_expression\"):\n \"\"\"Get list of all features in an organism\"\"\"\n if (organism, measurement_type) not in feature_series:\n load_features(organism, measurement_type)\n\n features = feature_series[(organism, measurement_type)].index.values\n return features\n\n\ndef get_feature_index(\n organism,\n feature_name,\n measurement_type=\"gene_expression\",\n):\n \"\"\"Get the numeric index for a single feature in the h5 file\"\"\"\n if (organism, measurement_type) not in feature_series:\n load_features(organism, measurement_type)\n\n try:\n idx = feature_series[(organism, measurement_type)].at[feature_name, 'index']\n except KeyError as exc:\n raise FeatureNotFoundError(\n f\"Feature not found: {feature_name}\",\n feature=feature_name,\n ) from exc\n\n return idx\n\n\ndef get_feature_names(\n organism,\n measurement_type=\"gene_expression\",\n):\n \"\"\"Get the list of all features in an organism, with correct capitalization.\"\"\"\n if (organism, measurement_type) not in feature_series:\n load_features(organism, measurement_type)\n\n features = feature_series[(organism, measurement_type)]['name'].values\n return features\n","repo_name":"fabilab/cell_atlas_approximations_API","sub_path":"web/models/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20521268128","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 2 23:03:44 2018\n\n@author: justinxin\n\"\"\"\n\n\n\n\n''' wrapper function for Sklearn '''\nSEED=12345\nntrain = x_train.shape[0]\nntest = x_test.shape[0]\n\n#x_train = x_train[features]\n#x_test = x_test[features]\n\n#kf = KFold(n_splits = NFOLDS, shuffle=True, random_state=SEED)\n\nclass SklearnWrapper(object):\n def __init__(self, clf, seed=0, params=None):\n params['random_state'] = seed\n self.clf = clf(**params)\n\n def train(self, x_train, y_train):\n self.clf.fit(x_train, y_train)\n\n def predict(self, x):\n return self.clf.predict_proba(x)[:,1]\n\net_params = {\n 'n_jobs': 16,\n 'n_estimators': 200,\n 'max_features': 0.5,\n 'max_depth': 12,\n 'min_samples_leaf': 2,\n}\n\nrf_params = {\n 'n_jobs': 16,\n 'n_estimators': 200,\n 'max_features': 0.2,\n 'max_depth': 12,\n 'min_samples_leaf': 2,\n}\n\n\n#xg = XgbWrapper(seed=SEED, params=xgb_params)\net = SklearnWrapper(clf=ExtraTreesClassifier, seed=SEED, params=et_params)\nrf = SklearnWrapper(clf=RandomForestClassifier, seed=SEED, params=rf_params)\n\net.train(x_train,y_train)\nrf.train(x_train,y_train)","repo_name":"xinjustin/DS_standardfunction","sub_path":"modelling/sklearn_wrapper.py","file_name":"sklearn_wrapper.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"69883753363","text":"import pandas as pd\nimport glob\nimport itertools\nfrom gensim.models import Word2Vec\n\nword2vec_model = Word2Vec.load(\"word2vec_usc.model\")\n\ndef get_vector(word):\n if word == \"null\":\n return False\n try:\n word2vec_model.wv.get_vector(word, norm=True)\n except KeyError:\n try:\n word = word[0].upper()+word[1:] if word[0].islower() else word[0].lower()+word[1:]\n word2vec_model.wv.get_vector(word, norm=True)\n except KeyError:\n return False\n else:\n return True\n except:\n return False\n else:\n return True\n\nusc_dfs = glob.glob(\"parsed/*.csv\")\n\nentries = []\n\ndef create_entry(identifier, keywords):\n print(identifier, keywords)\n if not isinstance(keywords, str):\n return []\n\n return [{\"keyword\": keyword, \"identifier\": identifier} for keyword in keywords.split(\":\") if get_vector(keyword)]\n\nfor df_dir in usc_dfs:\n print(df_dir)\n df = pd.read_csv(df_dir)\n entries.extend(itertools.chain(*[create_entry(identifier, keywords) for identifier, keywords in zip(df[\"identifier\"], df[\"keywords\"])]))\n\nindex = pd.DataFrame(entries)\nindex.dropna(inplace=True)\nindex.to_csv(\"keyword_index.csv\", index=False)","repo_name":"Dashadower/w2v_uscode","sub_path":"create_keyword_index.py","file_name":"create_keyword_index.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6460982522","text":"\"\"\"\napi/Community.py\n\nAuthor: Trey Stout\nDate Added: Mon Aug 28 15:32:30 CDT 2006\n\nCentral community/global calls\n\"\"\"\n## STD LIBS\nfrom datetime import datetime\n\n## OUR LIBS\nfrom decorators import stack, zapi\nfrom AZTKAPI import AZTKAPI\nimport errors\n\n## 3RD PARTY LIBS\nfrom twisted.internet.defer import Deferred, DeferredList\nfrom twisted.web import xmlrpc\n\nclass Community(AZTKAPI, xmlrpc.XMLRPC):\n\t\"\"\"\n\tAPI for community activity\n\t\"\"\"\n\tenable_node = True\n\tenable_zapi = True\n\t\n\t_depends = ['network']\n\t\n\tdef start(self):\n\t\t\"\"\"\n\t\t@return: Nothing\n\t\t@rtype: Nothing\n\t\t\"\"\"\n\t\treturn\n\n\t@stack\n\tdef get_activity(self, activity_type=0, after_date=None, limit=20):\n\t\t\"\"\"\n\t\tGet activity entries from the system\n\n\t\t@param activity_type: A registered activity type, or 0 for all types\n\t\t@type activity_type: Integer\n\n\t\t@param after_date: A date to consider the first possible entry and all after it\n\t\t@type after_date: Datetime\n\n\t\t@param limit: The maximum number of entries to retreive at once\n\t\t@type liimt: Integer\n\n\t\t@return: list of dictionaries\n\t\t@rtype: List\n\t\t\"\"\"\n\t\tclauses = [\"(t5.can_view IS NULL OR t5.can_view = true)\"]\n\t\tif activity_type:\n\t\t\tclauses.append('activity_type = %s' % activity_type)\n\t\tif after_date:\n\t\t\tclauses.append('entry_date > \\'%s\\'' % after_date)\n\n\t\tclause_string = \"\"\n\t\tclause_string = \"WHERE %s\" % \" AND \".join(clauses)\n\n\t\tdef format_data(results):\n\t\t\treturn (0, results);\n\n\t\td = self.app.db.query(\"\"\"\n\t\t\tSELECT\n\t\t\t\tentry_id,\n\t\t\t\tentry_date,\n\t\t\t\tactivity_userid,\n\t\t\t\tt3.username AS activity_username,\n\t\t\t\tactivity_type,\n\t\t\t\tt2.activity_name,\n\t\t\t\tzoto_get_latest_id(image_id) as media_id,\n\t\t\t\timage_id,\n\t\t\t\tt4.username AS owner_username,\n\t\t\t\towner_userid,\n\t\t\t\textra_text,\n\t\t\t\textra_int,\n\t\t\t\textra_boolean\n\t\t\tFROM\n\t\t\t\tactivity_log t1\n\t\t\t\tJOIN activity_types t2 \tON (t1.activity_type = t2.activity_id)\n\t\t\t\tLEFT JOIN users t3 ON (t1.activity_userid = t3.userid)\n\t\t\t\tLEFT JOIN users t4 ON (t1.owner_userid = t4.userid)\n\t\t\t\tLEFT JOIN zoto_image_public_permissions_matview t5 USING (image_id)\n\t\t\t%s\n\t\t\tORDER BY\n\t\t\t\tentry_date asc\n\t\t\tLIMIT\n\t\t\t\t%%s\n\t\t\t\"\"\" % clause_string, (limit,))\n\t\td.addCallback(format_data)\n\t\td.addErrback(lambda _: (-1, 'Oops: %s' % _.getErrorMessage()))\n\t\treturn d\n\n\t@zapi(\"Get activity entries from the system\",\n\t\t[('activity_type', 'Activity Type ID', int),\n\t\t('after_date', 'Datetime to search forward from', str),\n\t\t('limit', 'Limit', int)])\n\tdef xmlrpc_get_activity(self, info, activity_type, after_date, limit):\n\t\treturn self.get_activity(activity_type, after_date, limit)\n","repo_name":"kordless/zoto-server","sub_path":"aztk/api/Community.py","file_name":"Community.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"19249247995","text":"from __future__ import annotations\nfrom qtpy import QtWidgets as QtW\nfrom . import _utils\n\n\nclass QAbstractEval(QtW.QWidget):\n _BUTTON_TEXT = \"\"\n _PLACEHOLDER_TEXT = \"\"\n\n def __init__(self, parent: QtW.QWidget | None = None):\n super().__init__(parent)\n self._label = QtW.QLabel(\">>>\", self)\n self._line = _utils.QCompletableLineEdit(self)\n self._btn = QtW.QPushButton(self._BUTTON_TEXT)\n self._btn.clicked.connect(self.callback)\n self._line.enterClicked.connect(self.callback)\n self._line.setPlaceholderText(self._PLACEHOLDER_TEXT)\n\n _layout = QtW.QHBoxLayout()\n _layout.addWidget(self._label)\n _layout.addWidget(self._line)\n _layout.addWidget(self._btn)\n self.setLayout(_layout)\n self._btn.setFixedHeight(self._line.sizeHint().height())\n\n self.setToolTip(self.__class__.__doc__.replace(\"\\n \", \"\\n\").strip())\n\n def callback(self):\n raise NotImplementedError()\n\n def lineEdit(self) -> QtW.QLineEdit:\n return self._line\n\n\nclass QLiteralEvalWidget(QAbstractEval):\n \"\"\"\n Evaluate literal string.\n\n >>> result = val * 3 # Update or create \"result\" column\n >>> val_norm = val - val.mean() # Use DataFrame method\n \"\"\"\n\n _BUTTON_TEXT = \"Eval\"\n _PLACEHOLDER_TEXT = \"e.g. result = val * 3\"\n\n def callback(self):\n \"\"\"Evaluate the current text as a Python expression.\"\"\"\n text = self._line.text()\n if text == \"\":\n return\n table = self._line.currentPyTable(assert_mutable=True)\n table.query(text)\n self._line.toHistory()\n\n\nclass QLiteralFilterWidget(QAbstractEval):\n \"\"\"\n Apply filter using literal string.\n\n Examples\n --------\n >>> variable < 1.4 # values in \"variable\" column is < 1.4\n >>> a < b # values in \"a\" column < values in \"b\" column\n >>> None # reset filter\n \"\"\"\n\n _BUTTON_TEXT = \"Filter\"\n _PLACEHOLDER_TEXT = \"e.g. length < 3.5\"\n\n def callback(self):\n \"\"\"Update the filter of the current table using the expression.\"\"\"\n text = self._line.text()\n if text == \"\":\n return\n table = self._line.currentPyTable()\n table.proxy.filter(text)\n self._line.toHistory()\n","repo_name":"hanjinliu/tabulous","sub_path":"tabulous/_qt/_table_stack/_eval.py","file_name":"_eval.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"3"}
+{"seq_id":"37028778698","text":"import numpy as np\n\n\nclass ExpMovAvg:\n\n def __init__(self, size_max):\n self.w = [0]*size_max\n self.activated = False\n\n def get(self, interval, alpha, beta):\n\n for i in range(1, len(interval)):\n if interval[i] > interval[i-1]:\n self.w[i] = alpha*self.w[i-1] + (1-alpha)*interval[i]\n else:\n self.w[i] = beta*self.w[i-1] + (1-beta)*interval[i]\n\n avg_w = sum(self.w)/len(self.w)\n if avg_w > 53:\n self.activated = True\n\n else:\n self.activated = False\n\n return self.w, self.activated\n","repo_name":"KTH-HL2032/MedEng_project_G7","sub_path":"src/oBCI_prc/expmovavg.py","file_name":"expmovavg.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"16739520871","text":"n=int(input().strip())\nlst=[]\nfor i in range(n):\n s=input().strip().split()\n lst.append(list(s)+[True])\nfor i in range(n//2):\n for j in range(n):\n if lst[j][2]==True:\n lst[j][2]=False\n idx1=j\n break\n for j in range(n-1,-1,-1):\n if lst[j][2]==True and lst[j][0]!=lst[idx1][0]:\n lst[j][2]=False\n print(lst[idx1][1],lst[j][1])\n break","repo_name":"toooooodo/python-programming","sub_path":"7-2 一帮一 (15 分).py","file_name":"7-2 一帮一 (15 分).py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"ja","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"}
+{"seq_id":"15796224112","text":"#!/usr/bin/python3\ndef weight_average(my_list=[]):\n if my_list == []:\n return None\n tot = 0\n weight = 0\n for k in my_list:\n tot += (k[0] * k[1])\n weight += k[1]\n return (tot/weight)\n","repo_name":"1awesomeJ/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/100-weight_average.py","file_name":"100-weight_average.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25929497064","text":"from txt_reader import TxtReader\r\nfrom txt_writer import TxtWriter\r\n\r\n\r\nclass TxtProxyWriterReader:\r\n def __init__(self, file_path):\r\n self.__result = ''\r\n self.__is_actual = False\r\n self.__txt_reader = TxtReader(file_path)\r\n self.__txt_writer = TxtWriter(file_path)\r\n\r\n def read_file(self):\r\n if self.__is_actual:\r\n return self.__result\r\n else:\r\n self.__result = self.__txt_reader.read()\r\n self.__is_actual = True\r\n return self.__result\r\n\r\n def write_to_file(self):\r\n new_data = input()\r\n if new_data == self.__result:\r\n return self.__result\r\n else:\r\n self.__is_actual = False\r\n self.__txt_writer.write(new_data)\r\n return self.read_file()\r\n","repo_name":"Tetiana-Kulyk/Homeworks","sub_path":"HW_14/txt_proxy_writer_reader.py","file_name":"txt_proxy_writer_reader.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15583151741","text":"# Define a function to cast a spell\ndef cast_spell(caster, spell, target):\n print(caster.name, \"casts\", spell.name, \"on\", target.name)\n spell_level = caster.spell_slots[spell.level] - 1\n if spell_level >= 0:\n caster.spell_slots[spell.level] = spell_level\n if spell.target_type == \"self\":\n spell.effect(caster)\n print(caster.name, \"is affected by\", spell.name)\n elif spell.target_type == \"enemy\":\n spell.effect(caster, target)\n print(target.name, \"is affected by\", spell.name)\n elif spell.target_type == \"ally\":\n spell.effect(caster, target)\n print(target.name, \"is affected by\", spell.name)\n else:\n print(\"Invalid target type for spell!\")\n else:\n print(\"Insufficient spell slots to cast spell!\")\n\n# Define a class to represent a spell\nclass Spell:\n def __init__(self, name, level, target_type, effect):\n self.name = name\n self.level = level\n self.target_type = target_type\n self.effect = effect\n\n# Example usage: create a character, some spells, and cast a spell\ncharacter = Character(\"Gandalf\", \"Human\", \"Wizard\", 16, 14, 12, 18, 10, 8)\nfireball = Spell(\"Fireball\", 3, \"enemy\", lambda caster, target: target.take_damage(roll_die(6) + 5))\nheal = Spell(\"Heal\", 1, \"ally\", lambda caster, target: target.heal(roll_die(8) + 2))\nprint(character.name, \"has\", character.spell_slots, \"spell slots\")\nenemy = Character(\"Goblin\", \"Goblin\", \"Fighter\", 10, 14, 8, 6, 10, 8)\ncast_spell(character, fireball, enemy)\ncast_spell(character, heal, character)\n","repo_name":"quajap/D-D","sub_path":"cast_spell.py","file_name":"cast_spell.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13797468033","text":"import sys\nimport configparser\nimport requests\nfrom datetime import datetime\nfrom eeris_nilm import utils\n\ntry:\n inst = sys.argv[1]\nexcept IndexError:\n raise SystemExit(f\"Usage: {sys.argv[0]} installation_id\")\n\nconf_file = 'ini/eeris.ini'\nconfig = configparser.ConfigParser()\nconfig.read(conf_file)\npsk = config['REST']['jwt_psk']\nurl = config['REST']['url'] + '/' + inst + '/' + 'recomputation'\n# Set this to the time you want to go back (in seconds)\nstart = datetime.now().timestamp() - 3600 * 24 * 2\nend = datetime.now().timestamp()\nparams = {\n 'start': int(start),\n 'end': int(end),\n 'step': 2*3600\n}\ntoken = utils.get_jwt('nilm', psk)\nresp = requests.post(url, params=params, headers={'Authorization':\n 'jwt %s' % (token)})\nprint('Response: %d, %s' % (resp.status_code, resp.text))\n","repo_name":"eeris-nilm/eeris_nilm","sub_path":"tests/send_recomputation_request.py","file_name":"send_recomputation_request.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"3"}
+{"seq_id":"34176426362","text":"import pandas as pd\n\ndef cvs_read():\n data_frame = pd.read_csv(\"data.csv\")\n\n # Pandas will only print out the first 5 and last 5 rows if the dataframe is to large\n # Use the to_string method to print out the full data_frame\n # use dataframe.head(number or rows to print) to print the amount of rows from the begining you want. \n print(data_frame.to_string())\n print(\"--------------------------------------------------------------\")\n # To see how many rows your machine will display\n print(pd.options.display.max_rows)\n\ndef main():\n cvs_read()\n\nif __name__ == '__main__':\n main()\n","repo_name":"Beau28713/Data_Camp_Courses","sub_path":"Pandas/csv_read.py","file_name":"csv_read.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71543694801","text":"import struct\n\nclass Multiboot2HeaderFormatError(Exception):\n pass\n\nclass multiboot2:\n ADDR_MAGIC = 0xFFFFFFFF\n def __init__(self, path):\n f = open(path, \"rb\")\n self.data = f.read()\n f.close()\n \n #header_addr\n self.header_addr = self.ADDR_MAGIC\n self.header_addr_off = self.get_next_offset(0)\n if self.header_addr_off == None:\n raise Multiboot2HeaderFormatError()\n\n #load_addr\n self.load_addr = self.ADDR_MAGIC\n self.load_addr_off = self.get_next_offset(self.header_addr_off + 4)\n if self.load_addr_off == None:\n raise Multiboot2HeaderFormatError()\n\n #load_end_addr\n self.load_end_addr = self.ADDR_MAGIC\n self.load_end_addr_off = self.get_next_offset(self.load_addr_off + 4)\n if self.load_end_addr_off == None:\n raise Multiboot2HeaderFormatError()\n\n #bss_end_addr\n self.bss_end_addr = self.ADDR_MAGIC\n self.bss_end_addr_off = self.get_next_offset(self.load_end_addr_off + 4)\n if self.bss_end_addr_off == None:\n raise Multiboot2HeaderFormatError()\n\n #entry_addr\n self.entry_addr = self.ADDR_MAGIC\n self.entry_addr_off = self.get_next_offset(self.bss_end_addr_off + 4)\n if self.entry_addr_off == None:\n raise Multiboot2HeaderFormatError()\n\n def get_next_offset(self, begining):\n offset = begining\n while offset < len(self.data):\n num = struct.unpack(\" 0 and ([item for item in alist if item[1] == a['id']] == []):\n alist.append((a['name'], a['id'], gc))\n return sorted(alist, key = custom_sort, reverse = True)\n \n# used to faciliate recursive calls - \n# allows me to find the related artists in each level of separation from the root\n# before moving on to the root artist\ndef ra_rec(lst, genres, followers, lessthan):\n global query_count\n lst2 = []\n for a in lst:\n if query_count < 10:\n lst2+=(ra_help(a[1], genres))\n query_count += 1\n# print(\"ra_rec ra_help\" + str(query_count))\n if query_count < 10:\n lst2 += (ra_rec((sorted(lst2, key = custom_sort)), genres, followers, lessthan)) \n \n return sorted(lst2, key = custom_sort, reverse = True)\n\ndef related_artists(artname='', artid='', genre='', followers=-1, lessthan = True):\n if (artname == '' and artid == '' and genre == ''):\n print('please include name, id, or genre')\n return\n else:\n global query_count\n query_count = 0\n alist = []\n if (artname != ''):\n se = sp.search(q = artname, limit = 1, type = 'artist')\n query_count += 1\n print(\"related_artists search \" + str(query_count))\n if (se['artists']['total'] > 0):\n artist = se['artists']['items'][0]\n artid = artist['id']\n genres = artist['genres']\n elif (artid != ''):\n artist = sp.artist(artid)\n genres = artist['genres']\n\n lst = ra_help(artid, genres)\n# print(lst)\n query_count += 1\n print(\"related_artists ra_help \" + str(query_count))\n \n if query_count < 10:\n lst+=(ra_rec(lst, genres, followers, lessthan))\n \n print(len(lst))\n \n print(len(sorted(list(set(lst)), key = custom_sort)))\n \n return sorted(list(set(lst)), key = custom_sort, reverse = True) \n\n# related_artists(artid = '0WjtdWS6su0f3jrW9aqEHl') \n","repo_name":"kalebts/kalebtsegaye_MnM4SDS_project","sub_path":"py files/spotify_functions.py","file_name":"spotify_functions.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5478885041","text":"\"\"\"\nSupport for scoring alignments using arbitrary scoring matrices, arbitrary\nalphabets, and affine gap penalties.\n\"\"\"\n\nfrom numpy import (\n float32,\n int32,\n ones,\n zeros,\n)\n\n\nclass ScoringScheme:\n # note that gap_open and gap_extend are penalties, which means you should make them positive\n def __init__(\n self,\n gap_open,\n gap_extend,\n default=-100,\n alphabet1=\"ACGT\",\n alphabet2=None,\n gap1=\"-\",\n gap2=None,\n text1_range=128,\n text2_range=None,\n typecode=int32,\n ):\n if text2_range is None:\n text2_range = text1_range\n if alphabet2 is None:\n alphabet2 = alphabet1\n if gap2 is None:\n gap2 = gap1 # (scheme with gap1=gap2=None is legit)\n if isinstance(alphabet1, str):\n alphabet1 = [ch for ch in alphabet1]\n if isinstance(alphabet2, str):\n alphabet2 = [ch for ch in alphabet2]\n self.table = ones((text1_range, text2_range), typecode)\n self.table *= default\n self.gap_open = gap_open\n self.gap_extend = gap_extend\n self.gap1 = gap1\n self.gap2 = gap2\n self.alphabet1 = alphabet1\n self.alphabet2 = alphabet2\n # private _set_score and _get_score allow subclasses to override them to\n # implement a different underlying table object\n\n def _set_score(self, a_b_pair, val):\n (a, b) = a_b_pair\n self.table[a, b] = val\n\n def _get_score(self, a_b_pair):\n (a, b) = a_b_pair\n return self.table[a, b]\n\n def set_score(self, a, b, val, foldcase1=False, foldcase2=False):\n self._set_score((a, b), val)\n if foldcase1:\n aCh = chr(a)\n if aCh.isupper():\n aa = ord(aCh.lower())\n elif aCh.islower():\n aa = ord(aCh.upper())\n else:\n foldcase1 = False\n if foldcase2:\n bCh = chr(b)\n if bCh.isupper():\n bb = ord(bCh.lower())\n elif bCh.islower():\n bb = ord(bCh.upper())\n else:\n foldcase2 = False\n if foldcase1 and foldcase2:\n self._set_score((aa, b), val)\n self._set_score((a, bb), val)\n self._set_score((aa, bb), val)\n elif foldcase1:\n self._set_score((aa, b), val)\n elif foldcase2:\n self._set_score((a, bb), val)\n\n def score_alignment(self, a):\n return score_alignment(self, a)\n\n def score_texts(self, text1, text2):\n return score_texts(self, text1, text2)\n\n def __str__(self):\n isDna1 = \"\".join(self.alphabet1) == \"ACGT\"\n isDna2 = \"\".join(self.alphabet2) == \"ACGT\"\n labelRows = not (isDna1 and isDna2)\n width = 3\n for a in self.alphabet1:\n for b in self.alphabet2:\n score = self._get_score((ord(a), ord(b)))\n if isinstance(score, float):\n s = \"%8.6f\" % score\n else:\n s = \"%s\" % score\n if len(s) + 1 > width:\n width = len(s) + 1\n lines = []\n line = []\n if labelRows:\n if isDna1:\n line.append(\" \")\n else:\n line.append(\" \")\n for b in self.alphabet2:\n if isDna2:\n s = b\n else:\n s = \"%02X\" % ord(b)\n line.append(\"%*s\" % (width, s))\n lines.append((\"\".join(line)) + \"\\n\")\n for a in self.alphabet1:\n line = []\n if labelRows:\n if isDna1:\n line.append(a)\n else:\n line.append(\"%02X\" % ord(a))\n for b in self.alphabet2:\n score = self._get_score((ord(a), ord(b)))\n if isinstance(score, float):\n s = \"%8.6f\" % score\n else:\n s = \"%s\" % score\n line.append(\"%*s\" % (width, s))\n lines.append((\"\".join(line)) + \"\\n\")\n return \"\".join(lines)\n\n\ndef read_scoring_scheme(f, gap_open, gap_extend, gap1=\"-\", gap2=None, **kwargs):\n \"\"\"\n Initialize scoring scheme from a file containint a blastz style text blob.\n f can be either a file or the name of a file.\n \"\"\"\n close_it = False\n if isinstance(f, str):\n f = open(f)\n close_it = True\n ss = build_scoring_scheme(\"\".join([line for line in f]), gap_open, gap_extend, gap1=gap1, gap2=gap2, **kwargs)\n if close_it:\n f.close()\n return ss\n\n\ndef build_scoring_scheme(s, gap_open, gap_extend, gap1=\"-\", gap2=None, **kwargs):\n \"\"\"\n Initialize scoring scheme from a blastz style text blob, first line\n specifies the bases for each row/col, subsequent lines contain the\n corresponding scores. Slaw extensions allow for unusual and/or\n asymmetric alphabets. Symbols can be two digit hex, and each row\n begins with symbol. Note that a row corresponds to a symbol in text1\n and a column to a symbol in text2.\n\n examples:\n\n blastz slaw\n\n A C G T 01 02 A C G T\n 91 -114 -31 -123 01 200 -200 -50 100 -50 100\n -114 100 -125 -31 02 -200 200 100 -50 100 -50\n -31 -125 100 -114\n -123 -31 -114 91\n \"\"\"\n # perform initial parse to determine alphabets and locate scores\n bad_matrix = \"invalid scoring matrix\"\n s = s.rstrip(\"\\n\")\n lines = s.split(\"\\n\")\n rows = []\n symbols2 = lines.pop(0).split()\n symbols1 = None\n rows_have_syms = False\n a_la_blastz = True\n for i, line in enumerate(lines):\n row_scores = line.split()\n if len(row_scores) == len(symbols2): # blastz-style row\n if symbols1 is None:\n if len(lines) != len(symbols2):\n raise bad_matrix\n symbols1 = symbols2\n elif rows_have_syms:\n raise bad_matrix\n elif len(row_scores) == len(symbols2) + 1: # row starts with symbol\n if symbols1 is None:\n symbols1 = []\n rows_have_syms = True\n a_la_blastz = False\n elif not rows_have_syms:\n raise bad_matrix\n symbols1.append(row_scores.pop(0))\n else:\n raise bad_matrix\n rows.append(row_scores)\n # convert alphabets from strings to characters\n try:\n alphabet1 = [sym_to_char(sym) for sym in symbols1]\n alphabet2 = [sym_to_char(sym) for sym in symbols2]\n except ValueError:\n raise bad_matrix\n if (alphabet1 != symbols1) or (alphabet2 != symbols2):\n a_la_blastz = False\n if a_la_blastz:\n alphabet1 = [ch.upper() for ch in alphabet1]\n alphabet2 = [ch.upper() for ch in alphabet2]\n # decide if rows and/or columns should reflect case\n if a_la_blastz:\n foldcase1 = foldcase2 = True\n else:\n foldcase1 = \"\".join(alphabet1) == \"ACGT\"\n foldcase2 = \"\".join(alphabet2) == \"ACGT\"\n # create appropriately sized matrix\n text1_range = text2_range = 128\n if ord(max(alphabet1)) >= 128:\n text1_range = 256\n if ord(max(alphabet2)) >= 128:\n text2_range = 256\n typecode = int32\n for i, row_scores in enumerate(rows):\n for j, score in enumerate(map(int_or_float, row_scores)):\n if isinstance(score, float):\n typecode = float32\n if isinstance(gap_open, float):\n typecode = float32\n if isinstance(gap_extend, float):\n typecode = float32\n ss = ScoringScheme(\n gap_open,\n gap_extend,\n alphabet1=alphabet1,\n alphabet2=alphabet2,\n gap1=gap1,\n gap2=gap2,\n text1_range=text1_range,\n text2_range=text2_range,\n typecode=typecode,\n **kwargs,\n )\n # fill matrix\n for i, row_scores in enumerate(rows):\n for j, score in enumerate(map(int_or_float, row_scores)):\n ss.set_score(ord(alphabet1[i]), ord(alphabet2[j]), score)\n if foldcase1 and foldcase2:\n ss.set_score(ord(alphabet1[i].lower()), ord(alphabet2[j].upper()), score)\n ss.set_score(ord(alphabet1[i].upper()), ord(alphabet2[j].lower()), score)\n ss.set_score(ord(alphabet1[i].lower()), ord(alphabet2[j].lower()), score)\n elif foldcase1:\n ss.set_score(ord(alphabet1[i].lower()), ord(alphabet2[j]), score)\n elif foldcase2:\n ss.set_score(ord(alphabet1[i]), ord(alphabet2[j].lower()), score)\n return ss\n\n\ndef int_or_float(s):\n try:\n return int(s)\n except ValueError:\n return float(s)\n\n\n# convert possible two-char symbol to a single character\n\n\ndef sym_to_char(sym):\n if len(sym) == 1:\n return sym\n elif len(sym) != 2:\n raise ValueError\n else:\n return chr(int(sym, base=16))\n\n\ndef score_alignment(scoring_scheme, a):\n score = 0\n ncomps = len(a.components)\n for i in range(ncomps):\n for j in range(i + 1, ncomps):\n score += score_texts(scoring_scheme, a.components[i].text, a.components[j].text)\n return score\n\n\ndef score_texts(scoring_scheme, text1, text2):\n rval = 0\n last_gap_a = last_gap_b = False\n for i in range(len(text1)):\n a = text1[i]\n b = text2[i]\n # Ignore gap/gap pair\n if a == scoring_scheme.gap1 and b == scoring_scheme.gap2:\n continue\n # Gap in first species\n elif a == scoring_scheme.gap1:\n rval -= scoring_scheme.gap_extend\n if not last_gap_a:\n rval -= scoring_scheme.gap_open\n last_gap_a = True\n last_gap_b = False\n # Gap in second species\n elif b == scoring_scheme.gap2:\n rval -= scoring_scheme.gap_extend\n if not last_gap_b:\n rval -= scoring_scheme.gap_open\n last_gap_a = False\n last_gap_b = True\n # Aligned base\n else:\n rval += scoring_scheme._get_score((ord(a), ord(b)))\n last_gap_a = last_gap_b = False\n return rval\n\n\ndef accumulate_scores(scoring_scheme, text1, text2, skip_ref_gaps=False):\n \"\"\"\n Return cumulative scores for each position in alignment as a 1d array.\n\n If `skip_ref_gaps` is False positions in returned array correspond to each\n column in alignment, if True they correspond to each non-gap position (each\n base) in text1.\n \"\"\"\n if skip_ref_gaps:\n rval = zeros(len(text1) - text1.count(scoring_scheme.gap1))\n else:\n rval = zeros(len(text1))\n score = 0\n pos = 0\n last_gap_a = last_gap_b = False\n for i in range(len(text1)):\n a = text1[i]\n b = text2[i]\n # Ignore gap/gap pair\n if a == scoring_scheme.gap1 and b == scoring_scheme.gap2:\n continue\n # Gap in first species\n elif a == scoring_scheme.gap1:\n score -= scoring_scheme.gap_extend\n if not last_gap_a:\n score -= scoring_scheme.gap_open\n last_gap_a = True\n last_gap_b = False\n # Gap in second species\n elif b == scoring_scheme.gap2:\n score -= scoring_scheme.gap_extend\n if not last_gap_b:\n score -= scoring_scheme.gap_open\n last_gap_a = False\n last_gap_b = True\n # Aligned base\n else:\n score += scoring_scheme._get_score((ord(a), ord(b)))\n last_gap_a = last_gap_b = False\n if not (skip_ref_gaps) or a != scoring_scheme.gap1:\n rval[pos] = score\n pos += 1\n return rval\n\n\nhox70 = build_scoring_scheme(\n \"\"\" A C G T\n 91 -114 -31 -123\n -114 100 -125 -31\n -31 -125 100 -114\n -123 -31 -114 91 \"\"\",\n 400,\n 30,\n)\n","repo_name":"bxlab/bx-python","sub_path":"lib/bx/align/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":12070,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"3"}
+{"seq_id":"17966736533","text":"from django.shortcuts import render\nfrom ..models import Dimenzija, Sestavina, Vnos, Kontejner, Sprememba, Dnevna_prodaja\nfrom ..models import Baza, Zaloga, Cena\nfrom django.shortcuts import redirect\nfrom django.contrib.auth.decorators import login_required\nimport json \nfrom .. import funkcije\nfrom request_funkcije import pokazi_stran, vrni_slovar\nfrom request_funkcije import vrni_dimenzijo as dimenzija_iz_requesta\nfrom django.urls import reverse\nfrom django.http import JsonResponse\n\ndef spremeni_vnos(request):\n if request.method==\"POST\":\n stevilo = request.POST.get('stevilo')\n cena = request.POST.get('cena')\n tip = request.POST.get('tip')\n vnos = Vnos.objects.get(pk = int(request.POST.get('pk')))\n if stevilo and stevilo != \"\":\n vnos.stevilo = int(stevilo)\n if tip and tip != \"\" :\n vnos.tip = tip\n if cena and cena != \"\" :\n vnos.cena = float(cena)\n vnos.save()\n baza = vnos.baza\n data = podatki_vnosa(vnos)\n data.update(podatki_baze(baza))\n data.update({'action':'sprememba'})\n return JsonResponse(data)\n\ndef nov_vnos(request):\n if request.method == \"POST\":\n dimenzija = dimenzija_iz_requesta(request)\n stevilo = int(request.POST.get('stevilo'))\n tip = request.POST.get('tip')\n pk = int(request.POST.get('pk'))\n baza = Baza.objects.get(pk = pk)\n zaloga = baza.zaloga\n cena = None\n if baza.tip == \"vele_prodaja\":\n cena = Sestavina.objects.get(zaloga=zaloga,dimenzija__dimenzija=dimenzija).cena('vele_prodaja',tip)\n elif baza.tip == \"racun\":\n cena = Sestavina.objects.get(zaloga=zaloga,dimenzija__dimenzija=dimenzija).cena('dnevna_prodaja',tip)\n vnos = Vnos.objects.create(\n dimenzija = dimenzija,\n stevilo = stevilo,\n tip = tip,\n cena = cena,\n baza = baza)\n vnosi = Vnos.objects.all().filter(baza=baza).order_by('dimenzija').values('pk','dimenzija__dimenzija')\n pk = vnos.pk\n index = 0\n for slovar in vnosi:\n if slovar['pk'] == pk:\n break\n index += 1\n data = podatki_vnosa(vnos)\n data.update(podatki_baze(baza))\n data.update({'action':'novo','index':index})\n return JsonResponse(data)\n\ndef izbrisi_vnos(request):\n if request.method==\"POST\":\n pk = int(request.POST.get('pk'))\n vnos = Vnos.objects.get(pk = pk)\n baza = vnos.baza\n pk = vnos.baza.pk\n vnos.delete()\n data = podatki_vnosa(vnos)\n data.update(podatki_baze(baza))\n data.update({'action':'izbris'})\n return JsonResponse(data)\n \ndef spremeni_ladijski_prevoz(request):\n if request.method==\"POST\":\n pk = int(request.POST.get('pk'))\n baza = Baza.objects.get(pk=pk)\n prevoz = request.POST.get('ladijski_prevoz',0)\n try:\n prevoz = float(prevoz)\n except:\n prevoz = 0\n baza.ladijski_prevoz = prevoz\n baza.save()\n data = podatki_baze(baza)\n return JsonResponse(data) \n\ndef spremeni_popust(request):\n if request.method==\"POST\":\n pk = int(request.POST.get('pk'))\n baza = Baza.objects.get(pk=pk)\n popust = request.POST.get('popust')\n if popust and popust != \"\":\n try:\n popust = float(popust)\n except:\n popust = 0\n baza.popust = popust\n baza.save()\n data = podatki_baze(baza)\n return JsonResponse(data) \n\ndef spremeni_prevoz(request):\n if request.method==\"POST\":\n pk = int(request.POST.get('pk'))\n baza = Baza.objects.get(pk=pk)\n prevoz = request.POST.get('prevoz')\n if prevoz and prevoz != \"\":\n try:\n prevoz = float(prevoz)\n except:\n prevoz = 0\n baza.prevoz = prevoz\n baza.save()\n data = podatki_baze(baza)\n return JsonResponse(data) \n\ndef spremeni_ceno(request):\n data = {}\n if request.method == \"POST\":\n try:\n pk = int(request.POST.get('pk'))\n nova_cena = float(request.POST.get('cena'))\n cena = Cena.objects.get(pk = pk)\n cena.cena = nova_cena\n cena.save()\n data['cena'] = str(nova_cena)\n except:\n data['cena'] = 0\n return JsonResponse(data)\n\n\ndef izbrisi_racun(request):\n data = {}\n if request.method == \"POST\":\n pk = int(request.POST.get('pk'))\n racun = Baza.objects.get(pk = pk)\n prodaja = racun.dnevna_prodaja\n print(prodaja)\n racun.delete()\n print('po')\n data['skupno_stevilo'] = prodaja.skupno_stevilo\n print('po')\n data['skupna_cena'] = prodaja.skupna_cena\n print('po')\n return JsonResponse(data) \n#############################################################################\n#############################################################################\ndef vrni_bazo(request):\n data = {}\n try:\n baza = Baza.objects.get(pk = int(request.GET.get('pk')))\n data.update(podatki_baze(baza))\n data['vnosi'] = [podatki_vnosa(vnos) for vnos in baza.vnos_set.all()]\n except:\n pass\n return JsonResponse(data)\n\n\ndef vrni_dimenzijo(request):\n data = {}\n try:\n dimenzija = dimenzija_iz_requesta(request).dimenzija \n except:\n dimenzija = Dimenzija.objects.first().dimenzija\n data['dimenzija'] = dimenzija\n return JsonResponse(data)\n \ndef vrni_zalogo(request):\n data = {}\n try:\n dimenzija = request.GET.get('dimenzija')\n tip = request.GET.get('tip')\n zaloga = int(request.GET.get('zaloga'))\n stevilo = getattr(Sestavina.objects.all().get(zaloga=zaloga,dimenzija__dimenzija=dimenzija),tip)\n data['zaloga'] = stevilo\n except:\n data['zaloga'] = 0\n return JsonResponse(data)\n\n##############################################################################\n##############################################################################\ndef podatki_vnosa(vnos):\n data = {}\n data['pk'] = str(vnos.pk)\n data['cena'] = str(vnos.cena)\n data['cena_vnosa'] = str(vnos.skupna_cena)\n data['stevilo'] = str(vnos.stevilo)\n data['dimenzija'] = str(vnos.dimenzija)\n data['varna_dimenzija'] = str(vnos.dimenzija).replace('/','-')\n data['tip'] = vnos.tip\n data['dolgi_tip'] = vnos.get_tip_display()\n return data\n\ndef podatki_baze(baza):\n data = {}\n data['pk_baze'] = baza.pk\n data['title'] = baza.title\n data['cas'] = baza.cas\n data['prodajalec'] = str(baza.author.username)\n data['popust'] = str(baza.popust)\n data['cena_popusta'] = str(baza.cena_popusta)\n data['cena_prevoza'] = str(baza.cena_prevoza)\n data['prevoz'] = str(baza.prevoz)\n data['koncna_cena'] = str(baza.koncna_cena)\n data['skupna_cena'] = str(baza.skupna_cena)\n data['skupno_stevilo'] = str(baza.skupno_stevilo)\n data['ladijski_prevoz'] = str(baza.ladijski_prevoz)\n return data","repo_name":"TadejGrof/LaBodega","sub_path":"zaloga/my_views/baza_views.py","file_name":"baza_views.py","file_ext":"py","file_size_in_byte":7097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34972338258","text":"\ndef check_pysam_version(min_pysam_ver=\"0.8.4\"):\n \"\"\"Checks that the imported version of pysam is greater than\n or equal to provided version. Returns 0 if version is high enough,\n raises ImportWarning otherwise.\"\"\"\n import pysam\n\n min_ver = [int(x) for x in min_pysam_ver.split(\".\")]\n pysam_ver = [int(x) for x in pysam.__version__.split(\".\")]\n\n n_ver = min(len(pysam_ver), len(min_pysam_ver))\n \n for i in range(n_ver):\n if pysam_ver[i] < min_ver[i]:\n raise ImportWarning(\"pysam version is %s, but pysam version %s \"\n \"or greater is required\" % (pysam.__version__,\n min_pysam_ver))\n if pysam_ver[i] > min_ver[i]:\n # version like 1.0 beats version like 0.8\n break\n \n return 0\n\n\ndef check_pytables_version():\n \"\"\"Checks that PyTables version 3 is being used. PyTables version 3 \n changes the names of many functions and is not backwards compatible\n with PyTables 2. Previous versions of WASP used version 2, but switch\n to version 3 was made at same time as switch to python3.\"\"\"\n import tables\n\n pytables_ver = [int(x) for x in tables.__version__.split(\".\")]\n\n if pytables_ver[0] < 3:\n raise ImportWarning(\"pytables version is %s, but pytables version \"\n \">=3 is required\" % (tables.__version__))\n\n return 0\n\n\ndef is_gzipped(filename):\n \"\"\"Checks first two bytes of provided filename and looks for\n gzip magic number. Returns true if it is a gzipped file\"\"\"\n f = open(filename, \"rb\")\n\n # read first two bytes\n byte1 = f.read(1)\n byte2 = f.read(1)\n \n f.close()\n\n # check against gzip magic number 1f8b\n return (byte1 == b'\\x1f') and (byte2== b'\\x8b')\n","repo_name":"bmvdgeijn/WASP","sub_path":"CHT/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"3"}
+{"seq_id":"24853418979","text":"#!/usr/bin/env python3\nimport argparse\nimport sys\nimport os\nimport os.path\nimport yaml\nimport glob\nimport warnings\nfrom pathlib import Path\n\ndef get_rule_yaml(rule_file, custom=False):\n \"\"\" Takes a rule file, checks for a custom version, and returns the yaml for the rule\n \"\"\"\n resulting_yaml = {}\n names = [os.path.basename(x) for x in glob.glob('../custom/rules/**/*.yaml', recursive=True)]\n file_name = os.path.basename(rule_file)\n # if file_name in names:\n # print(f\"Custom settings found for rule: {rule_file}\")\n # try:\n # override_path = glob.glob('../custom/rules/**/{}'.format(file_name), recursive=True)[0]\n # except IndexError:\n # override_path = glob.glob('../custom/rules/{}'.format(file_name), recursive=True)[0]\n # with open(override_path) as r:\n # rule_yaml = yaml.load(r, Loader=yaml.SafeLoader)\n # r.close()\n # else:\n # with open(rule_file) as r:\n # rule_yaml = yaml.load(r, Loader=yaml.SafeLoader)\n # r.close()\n if custom:\n print(f\"Custom settings found for rule: {rule_file}\")\n try:\n override_path = glob.glob('../custom/rules/**/{}'.format(file_name), recursive=True)[0]\n except IndexError:\n override_path = glob.glob('../custom/rules/{}'.format(file_name), recursive=True)[0]\n with open(override_path) as r:\n rule_yaml = yaml.load(r, Loader=yaml.SafeLoader)\n else:\n with open(rule_file) as r:\n rule_yaml = yaml.load(r, Loader=yaml.SafeLoader)\n \n try:\n og_rule_path = glob.glob('../rules/**/{}'.format(file_name), recursive=True)[0]\n except IndexError:\n #assume this is a completely new rule\n og_rule_path = glob.glob('../custom/rules/**/{}'.format(file_name), recursive=True)[0]\n resulting_yaml['customized'] = [\"customized rule\"]\n \n # get original/default rule yaml for comparison\n with open(og_rule_path) as og:\n og_rule_yaml = yaml.load(og, Loader=yaml.SafeLoader)\n\n for yaml_field in og_rule_yaml:\n #print('processing field {} for rule {}'.format(yaml_field, file_name))\n if yaml_field == \"references\":\n if not 'references' in resulting_yaml:\n resulting_yaml['references'] = {}\n for ref in og_rule_yaml['references']:\n try:\n if og_rule_yaml['references'][ref] == rule_yaml['references'][ref]:\n resulting_yaml['references'][ref] = og_rule_yaml['references'][ref]\n else:\n resulting_yaml['references'][ref] = rule_yaml['references'][ref]\n except KeyError:\n # reference not found in original rule yaml, trying to use reference from custom rule\n try:\n resulting_yaml['references'][ref] = rule_yaml['references'][ref]\n except KeyError:\n resulting_yaml['references'][ref] = og_rule_yaml['references'][ref]\n try: \n if \"custom\" in rule_yaml['references']:\n resulting_yaml['references']['custom'] = rule_yaml['references']['custom']\n if 'customized' in resulting_yaml:\n if 'customized references' not in resulting_yaml['customized']:\n resulting_yaml['customized'].append(\"customized references\")\n else:\n resulting_yaml['customized'] = [\"customized references\"]\n except:\n pass\n \n else: \n try:\n if og_rule_yaml[yaml_field] == rule_yaml[yaml_field]:\n #print(\"using default data in yaml field {}\".format(yaml_field))\n resulting_yaml[yaml_field] = og_rule_yaml[yaml_field]\n else:\n #print('using CUSTOM value for yaml field {} in rule {}'.format(yaml_field, file_name))\n resulting_yaml[yaml_field] = rule_yaml[yaml_field]\n if 'customized' in resulting_yaml:\n resulting_yaml['customized'].append(\"customized {}\".format(yaml_field))\n else:\n resulting_yaml['customized'] = [\"customized {}\".format(yaml_field)]\n except KeyError:\n resulting_yaml[yaml_field] = og_rule_yaml[yaml_field]\n\n return resulting_yaml\n\ndef main():\n parser = argparse.ArgumentParser(description='Given a profile, create JSON custom schema to use in Jamf.')\n parser.add_argument(\"baseline\", default=None, help=\"Baseline YAML file used to create the JSON custom schema.\", type=argparse.FileType('rt'))\n\n results = parser.parse_args()\n try:\n \n output_basename = os.path.basename(results.baseline.name)\n output_filename = os.path.splitext(output_basename)[0]\n baseline_name = os.path.splitext(output_basename)[0]\n file_dir = os.path.dirname(os.path.abspath(__file__))\n parent_dir = os.path.dirname(file_dir)\n # stash current working directory\n original_working_directory = os.getcwd()\n\n # switch to the scripts directory\n os.chdir(file_dir)\n build_path = os.path.join(parent_dir, 'build', f'{baseline_name}')\n output = build_path + \"/\" + baseline_name + \".json\"\n\n if not (os.path.isdir(build_path)):\n try:\n os.makedirs(build_path)\n except OSError:\n print(f\"Creation of the directory {build_path} failed\")\n print('Profile YAML:', results.baseline.name)\n print('Output path:', output)\n \n \n \n except IOError as msg:\n parser.error(str(msg))\n\n profile_yaml = yaml.load(results.baseline, Loader=yaml.SafeLoader)\n\n json = '''\n {{\n \"title\": \"org.{0}.audit.plist\",\n \"description\": \"Preference Domain: org.{0}.audit, Application: macOS Security Compliance Project\",\n \"__version\": \"1.0\",\n \"__feedback\": \"boberito@mac.com\",\n \"type\": \"object\",\n \"options\": {{\n \"remove_empty_properties\": true\n }},\n \"properties\": {{'''.format(baseline_name,baseline_name)\n\n\n for sections in profile_yaml['profile']:\n if sections['section'] == \"Supplemental\":\n continue\n \n for profile_rule in sections['rules']:\n \n\n if glob.glob('../custom/rules/**/{}.yaml'.format(profile_rule),recursive=True):\n rule = glob.glob('../custom/rules/**/{}.yaml'.format(profile_rule),recursive=True)[0]\n custom=True\n \n elif glob.glob('../rules/*/{}.yaml'.format(profile_rule)):\n rule = glob.glob('../rules/*/{}.yaml'.format(profile_rule))[0]\n custom=False\n \n rule_yaml = get_rule_yaml(rule, custom)\n\n \n if \"inherent\" in rule_yaml['tags'] or \"n_a\" in rule_yaml['tags'] or \"permanent\" in rule_yaml['tags']:\n continue\n\n json = json + '''\n \"{0}\": {{\n \"title\": \"{0}\",\n \"description\": \"{1}\",\n \"property_order\": 1,\n \"anyOf\": [\n {{\n \"type\": \"null\",\n \"title\": \"Not Configured\"\n }},\n {{\n \"title\": \"Configured\",\n \"type\": \"object\",\n \"properties\": {{\n \"exempt\": {{\n \"description\": \"If value is true, exempt_reason is required\",\n \"type\": \"boolean\"\n }},\n \"exempt_reason\": {{\n \"description\": \"Specify Exempt Reasoning\",\n \"type\": \"string\"\n }}\n }}\n }}\n ]\n }},'''.format(rule_yaml['id'],rule_yaml['title'])\n \n json = json[:-1]\n\n json = json + '''\n }}'''\n\n with open(output,'w') as rite:\n rite.write(json)\n rite.close()\n \n os.chdir(original_working_directory)\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"boberito/mscp_jamf","sub_path":"generate_json.py","file_name":"generate_json.py","file_ext":"py","file_size_in_byte":8001,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"35078254237","text":"import os, sys\n\nif sys.version_info[:2] > (3, 0):\n from configparser import RawConfigParser\nelse:\n from ConfigParser import RawConfigParser\n \nfrom setuptools import setup, find_packages\n\nname = 'files'\nbase_dir = os.path.dirname(__file__)\n\n# read test requirements from tox.ini\nconfig = RawConfigParser()\nconfig.read(os.path.join(base_dir, 'tox.ini'))\ntest_requires = []\nfor item in config.get('testenv', 'deps').split():\n test_requires.append(item)\n# Tox doesn't need itself, but we need it for testing.\ntest_requires.append('tox')\n\nsetup(\n name=name,\n version='1.0dev',\n author='Chris Withers',\n author_email='chris@simplistix.co.uk',\n license='MIT',\n description=\"Handy utilities for working with files, directories and their permissions.\",\n long_description=open(os.path.join(base_dir,'docs','description.txt')).read(),\n url='http://www.simplistix.co.uk/software/python/dir',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n # 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n ],\n packages=find_packages(),\n zip_safe=False,\n include_package_data=True,\n extras_require=dict(\n test=test_requires,\n docs=['sphinx',\n 'zc.rst2',\n 'pkginfo >= 1.0b2',\n 'setuptools-git'],\n dev='setuptools-git'\n )\n )\n","repo_name":"simplistix/files","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"4506167520","text":"from django.urls import path\nfrom . import views\nfrom rest_framework.routers import DefaultRouter\n\nurlpatterns = [\n path('', views.BookList.as_view(), name='book_list'),\n path('books/', views.BookList.as_view(), name='book_list'),\n path('book/', views.BookDetail.as_view(), name='book_detail'),\n path('authors/', views.AuthorList.as_view(), name='author_list'),\n path('author/', views.AuthorDetail.as_view(), name='author_detail'),\n path('genres/', views.GenreList.as_view(), name='genre_list'),\n path('genre/', views.GenreDetail.as_view(), name='genre_detail'),\n]\n","repo_name":"AMassock/GA_Coursework","sub_path":"drf-book-api-hw/book/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"6709022136","text":"from django.core.exceptions import BadRequest\nfrom django.http import HttpResponse, FileResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import CustomUser\nfrom .utils import generate_points_create_csv, is_user_exists, Points\n\n\n@csrf_exempt\ndef register(request):\n username = request.GET['username']\n password = request.GET['password']\n\n if request.method == 'POST':\n user = CustomUser.objects.create_user(username=username, password=password)\n csv_file_path, plot_file_path = generate_points_create_csv()\n user.generated_points.name = csv_file_path\n user.plot_with_points.name = plot_file_path\n user.save(update_fields=['generated_points', 'plot_with_points'])\n return HttpResponse('User was successfully register
')\n else:\n raise BadRequest('Invalid request.')\n\n\ndef get_users_csv_file(request):\n username = request.GET['username']\n user_exists = is_user_exists(username)\n\n if request.method == 'GET' and user_exists:\n users_csv_file = CustomUser.objects.get(username=username).generated_points\n response = FileResponse(open(users_csv_file.path, 'rb'))\n return response\n else:\n raise BadRequest('The user does not register yet or invalid request method')\n\n\ndef get_users_plot(request):\n username = request.GET['username']\n user_exists = is_user_exists(username)\n\n if request.method == 'GET' and user_exists:\n users_plot = CustomUser.objects.get(username=username).plot_with_points\n return HttpResponse(users_plot, content_type=\"image/png\")\n else:\n raise BadRequest('The user does not register yet or invalid request method')\n\n\n@csrf_exempt\ndef regenerate_users_csv_file(request):\n username = request.GET['username']\n user_exists = is_user_exists(username)\n\n try:\n if request.method == 'POST' and user_exists:\n user = CustomUser.objects.get(username=username)\n\n csv_file_path = user.generated_points.path\n plot_file_path = user.plot_with_points.path\n Points.remove_files(csv_file_path, plot_file_path)\n\n user.generated_points = ''\n user.plot_with_points = ''\n user.save(update_fields=['generated_points', 'plot_with_points'])\n\n new_csv_file_path, new_plot_file_path = generate_points_create_csv()\n user.generated_points.name = new_csv_file_path\n user.plot_with_points.name = new_plot_file_path\n user.save(update_fields=['generated_points', 'plot_with_points'])\n return HttpResponse('User was successfully regenerated new points
')\n except Exception:\n print(\"Oops! Something went wrong\")\n","repo_name":"Hyper-glitch/Sreda_test","sub_path":"sreda/rest_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28508615354","text":"class User:\n def __init__(self, name, email):\n self.name = name \n self.email = email \n self.account = 100000\n\n def make_deposit(self, amount):\n self.account += amount\n return self\n\n def make_withdrawal(self, amount):\n self.account -= amount\n return self\n \n def display_user_balance(self):\n self.name, self.account\n return self\n\nclass BankAccount:\n def __init__(self, int_rate, balance):\n self.int_rate = int_rate\n self.balance = balance\n self.int_rate = 0.01\n\n def deposit(self, amount):\n self.balance += amount\n return self\n\n def withdraw(self, amount):\n self.balance -= amount\n return self\n\n def display_account_info(self):\n print(self.balance)\n return self\n\n def yield_interest(self):\n self.int_rate\n return self\n\nchecking = BankAccount(0.01, 5000 )\nsaving = BankAccount(0.08, 25000 )\n\nprince = User(\"prince\", \"piwejuo@gmail.com\")\ncollins = User(\"collins\", \"cebozue@gmail.com\")\narinze = User(\"arinze\", \"aobiora@gmail.com\")\n\ncollins.account = 10000\narinze.account = 7000\n\nprince.make_deposit(10000).make_deposit(1000).make_deposit(500)\nprint(prince.account)\n\nprince.make_withdrawal(11500).display_user_balance()\nprint(prince.account)\nprint(prince.name, prince.account)\n\ncollins.make_deposit(500).make_deposit(500).make_withdrawal(1000).make_withdrawal(500).display_user_balance()\nprint(collins.name, collins.account)\n\narinze.make_deposit(4000).make_withdrawal(1000).make_withdrawal(500).make_withdrawal(2000).display_user_balance()\nprint(arinze.name, arinze.account)","repo_name":"PrinceIwejuo/UserswithBankacc","sub_path":"useracct.py","file_name":"useracct.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12549636123","text":"import os\nos.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = \"hide\"\nimport sys, math, pygame, random, time\nfrom repo import NME, Player\n\ndef clear():\n os.system('cls' if os.name=='nt' else 'clear')\n\ndef pause():\n input(\"Press ENTER to continue...\")\n print('\\n\\n')\n time.sleep(0.5)\n\nplayer2 = 0\nplayer3 = 0\nplayer4 = 0\nplayerNO = 1\n\ndef setstat(NO):\n pass\n\nprint('welcome to the Amesia Machine')\nstattxt = ('Enter Player {} Stat:\\n')\np0 = Player()\np0.Name = str(input('Enter Player Name:\\n'))\np0.SAVFIL = open(\"%s.txt\" %p0.Name, \"a\")\nprint(\"Player name is {}.\".format(p0.Name))\np0.ST = int(input(stattxt.format('Strength')))\np0.SP = int(input(stattxt.format('Speed')))\np0.MI = int(input(stattxt.format('Mind')))\np0.WT = int(input(stattxt.format('Wit')))\ncont = input('add another player?\\n')\nif cont == 'Yes':\n player2 = 1\n playerNO = 2\n p1 = Player()\n p1.Name = str(input('Enter Player Name:\\n'))\n print(\"Player name is {}.\".format(p1.Name))\n p1.ST = int(input(stattxt.format('Strength')))\n p1.SP = int(input(stattxt.format('Speed')))\n p1.MI = int(input(stattxt.format('Mind')))\n p1.WT = int(input(stattxt.format('Wit')))\n cont = input('add another player?\\n')\n if cont == 'Yes':\n player3 = 1\n playerNO = 3\n p2 = Player()\n p2.Name = str(input('Enter Player Name:\\n'))\n print(\"Player name is {}.\".format(p2.Name))\n p2.ST = int(input(stattxt.format('Strength')))\n p2.SP = int(input(stattxt.format('Speed')))\n p2.MI = int(input(stattxt.format('Mind')))\n p2.WT = int(input(stattxt.format('Wit')))\n cont = input('add another player?\\n')\n if cont == 'Yes':\n player4 = 1\n playerNO = 4\n p3 = Player()\n p3.Name = str(input('Enter Player Name:\\n'))\n print(\"Player name is {}.\".format(p3.Name))\n p3.ST = int(input(stattxt.format('Strength')))\n p3.SP = int(input(stattxt.format('Speed')))\n p3.MI = int(input(stattxt.format('Mind')))\n p3.WT = int(input(stattxt.format('Wit')))\n print('you have reached max number of Players\\n')\n\n\nclear()\nprint('calculating stats...')\np0.MXHP = int(30 + (p0.ST + 4)*2)\nif p0.MXHP < 24:\n p0.MXHP = 24\np0.HP = p0.MXHP\nif p0.ST >= p0.SP:\n p0.MXINJ = 3 + p0.ST\nelif p0.SP > p0.ST:\n p0.MXINJ = 3 + int(0.5*p0.SP)\nif p0.MXINJ < 1:\n p0.MXINJ = 1\np0.INJ = p0.MXINJ\nif p0.MI >= p0.WT:\n p0.MXMP = int(2*(p0.MI + 1) + 2)\nif p0.WT > p0.MI:\n p0.MXMP = int(2*(p0.WT + 1) + 2)\np0.MP = p0.MXMP\np0.MOV = 5*(p0.SP + 4)\nif p0.MOV < 10:\n p0.MOV = 10\nif p0.ST >= p0.SP:\n p0.PFS = p0.ST\nelif p0.SP > p0.ST:\n p0.PFS = p0.SP\n\n\nif player2 == 1:\n p1.MXHP = 30 + (p1.ST + 4)*2\n if p1.MXHP < 24:\n p1.MXHP = 24\n p1.HP = p1.MXHP\n if p1.ST >= p1.SP:\n p1.MXINJ = 3 + p1.ST\n elif p1.SP > p1.ST:\n p1.MXINJ = 3 + int(0.5*p1.SP)\n if p1.MXINJ < 1:\n p1.MXINJ = 1\n p1.INJ = p1.MXINJ\n if p1.MI >= p1.WT:\n p1.MXMP = int(2*(p1.MI + 1) + 2)\n if p1.WT > p1.MI:\n p1.MXMP = int(2*(p1.WT + 1) + 2)\n p1.MP = p1.MXMP\n p1.MOV = 5*(p1.SP + 4)\n if p1.MOV < 10:\n p1.MOV = 10\n if p1.ST >= p1.SP:\n p1.PFS = p1.ST\n elif p1.SP > p1.ST:\n p1.PFS = p1.SP\n\n\nif player3 == 1:\n p2.MXHP = 30 + (p2.ST + 4)*2\n if p2.MXHP < 24:\n p2.MXHP = 24\n p2.HP = p2.MXHP\n if p2.ST >= p2.SP:\n p2.MXINJ = 3 + p2.ST\n elif p2.SP > p2.ST:\n p2.MXINJ = 3 + int(0.5*p2.SP)\n if p2.MXINJ < 1:\n p2.MXINJ = 1\n p2.INJ = p2.MXINJ\n if p2.MI >= p2.WT:\n p2.MXMP = int(2*(p2.MI + 1) + 2)\n if p2.WT > p2.MI:\n p2.MXMP = int(2*(p2.WT + 1) + 2)\n p2.MP = p2.MXMP\n p2.MOV = 5*(p2.SP + 4)\n if p2.MOV < 10:\n p2.MOV = 10\n if p2.ST >= p2.SP:\n p2.PFS = p2.ST\n elif p2.SP > p2.ST:\n p2.PFS = p2.SP\n\n\nif player4 == 1:\n p3.MXHP = 30 + (p3.ST + 4)*2\n if p3.MXHP < 24:\n p3.MXHP = 24\n p3.HP = p3.MXHP\n if p3.ST >= p3.SP:\n p3.MXINJ = 3 + p3.ST\n elif p3.SP > p3.ST:\n p3.MXINJ = 3 + int(0.5*p3.SP)\n if p3.MXINJ < 1:\n p3.MXINJ = 1\n p3.INJ = p3.MXINJ\n if p3.MI >= p3.WT:\n p3.MXMP = int(2*(p3.MI + 1) + 2)\n if p3.WT > p3.MI:\n p3.MXMP = int(2*(p3.WT + 1) + 2)\n p3.MP = p3.MXMP\n p3.MOV = 5*(p3.SP + 4)\n if p3.MOV < 10:\n p3.MOV = 10\n if p3.ST >= p3.SP:\n p3.PFS = p3.ST\n elif p3.SP > p3.ST:\n p3.PFS = p3.SP\n\nclear()\n\necho = 'Player {} {} stat is {}'\nprint (echo.format('1', 'Might', p0.ST))\nprint (echo.format('1', 'Speed', p0.SP))\nprint (echo.format('1', 'Mind', p0.MI))\nprint (echo.format('1', 'Wit', p0.WT))\nprint (echo.format('1', 'HP', p0.MXHP))\nprint (echo.format('1', 'Injuries', p0.MXINJ))\nprint (echo.format('1', 'Mana', p0.MXMP))\nprint (echo.format('1', 'Movement', p0.MOV))\nprint('\\n\\n')\nif player2 == 1:\n print (echo.format('2', 'Might', p1.ST))\n print (echo.format('2', 'Speed', p1.SP))\n print (echo.format('2', 'Mind', p1.MI))\n print (echo.format('2', 'Wit', p1.WT))\n print (echo.format('2', 'HP', p1.MXHP))\n print (echo.format('2', 'Injuries', p1.MXINJ))\n print (echo.format('2', 'Mana', p1.MXMP))\n print (echo.format('2', 'Movement', p1.MOV))\n print('\\n\\n')\nif player3 == 1:\n print (echo.format('3', 'Might', p2.ST))\n print (echo.format('3', 'Speed', P2.SP))\n print (echo.format('3', 'Mind', p2.MI))\n print (echo.format('3', 'Wit', p2.WT))\n print (echo.format('3', 'HP', p2.MXHP))\n print (echo.format('3', 'Injuries', p2.MXINJ))\n print (echo.format('3', 'Mana', p2.MXMP))\n print (echo.format('3', 'Movement', p2.MOV))\n print('\\n\\n')\nif player4 == 1:\n print (echo.format('4', 'Might', p3.ST))\n print (echo.format('4', 'Speed', P3.SP))\n print (echo.format('4', 'Mind', p3.MI))\n print (echo.format('4', 'Wit', p3.WT))\n print (echo.format('4', 'HP', p3.MXHP))\n print (echo.format('4', 'Injuries', p3.MXINJ))\n print (echo.format('4', 'Mana', p3.MXMP))\n print (echo.format('4', 'Movement', p3.MOV))\n print('\\n\\n')\npause()\nclear()\n\nGBLN = NME()\nGBLN.HP = 20\nGBLN.INIT = 5\nprint(\"A wild goblin attacks the party!\\n\\n\")\nif GBLN.INIT >= (p0.SP + p0.WT):\n print(\"The crafty goblin goes first!\\n\\n\")\n TURN = \"NME\"\nelif GBLN.INIT < (p0.SP + p0.WT):\n print(\"The party has the upper hand!\\n\\n\")\n TURN = \"PTY\"\npause()\nwhile GBLN.HP > 0 and p0.HP > 0:\n echo = 'Player {} {} stat is {}'\n print (echo.format('1', 'HP', p0.HP))\n print (echo.format('1', 'Injuries', p0.INJ))\n print (echo.format('1', 'Mana', p0.MP))\n print('\\n\\n')\n if TURN == \"NME\":\n print('The goblin enters a stance...' '\\n')\n GBLN.STANCE = random.randint(1, 3)\n if GBLN.STANCE == 1:\n GBLN.AN = 6\n GBLN.RN = 14\n if GBLN.STANCE == 2:\n GBLN.AN = 10\n GBLN.RN = 10\n if GBLN.STANCE == 3:\n GBLN.AN = 14\n GBLN.RN = 6\n print('The goblin attacks!' '\\n')\n if (GBLN.AN + 3) > (p0.RN + p0.PFS):\n GBLN.DMG = int(8*(GBLN.AN + 3 - p0.RN + p0.PFS)/10)\n p0.HP -= GBLN.DMG\n print('The goblin hits for ', str(GBLN.DMG), ' damage!' '\\n\\n')\n elif not (GBLN.AN + 3) > (p0.RN + p0.PFS):\n print('The goblin misses!' '\\n\\n')\n pause()\n TURN = \"PTY\"\n if TURN == \"PTY\":\n p0.STANCE = input('Choose your stance: \\n\\n \"1\" - Defensive(6, 14) \\n \"2\" - Neutral(10, 10) \\n \"3\" - Offensive(14, 6) \\n\\n')\n if p0.STANCE == 1:\n p0.AN = 6\n p0.RN = 14\n if p0.STANCE == 2:\n p0.AN = 10\n p0.RN = 10\n if p0.STANCE == 3:\n p0.AN = 14\n p0.RN = 6\n if (GBLN.AN + 3) < (p0.RN + p0.PFS):\n p0.DMG = int(8*(p0.RN + p0.PFS - GBLN.AN + 3)/10)\n GBLN.HP -= p0.DMG\n print('You hit the goblin for ', str(p0.DMG), ' damage!' '\\n\\n')\n elif not (GBLN.AN + 3) < (p0.RN + p0.PFS):\n print('The goblin dodges!' '\\n\\n')\n pause()\n TURN = \"NME\"\n","repo_name":"Anonymous-crow/Amnesia-Machine","sub_path":"amnesia_machine.py","file_name":"amnesia_machine.py","file_ext":"py","file_size_in_byte":8078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33208647914","text":"import sys\nfrom collections import deque\ninput = sys.stdin.readline\n\n\nn, k = map(int, input().split())\nlistN = []\nhasSame = False\nfor i in str(n):\n if int(i) in listN:\n hasSame = True\n listN.append(int(i))\nm = len(listN)\n\ndef bfs():\n if m == 1:\n return [[-1]]\n\n i = 0\n dq = deque([(listN, 0)])\n answer = []\n\n while dq:\n for _ in range(len(dq)):\n arr, cnt = dq.popleft()\n\n if cnt == k:\n answer.append(arr)\n continue\n\n if i >= m:\n if hasSame:\n answer.append(arr)\n else:\n now = arr[-1]\n arr[-1] = arr[-2]\n arr[-2] = now\n if arr[0] != 0:\n dq.append((arr, cnt+1))\n continue\n\n ListJ = []\n M = arr[i] + 1\n for jj in range(i+1, m):\n if arr[jj] > M:\n M = arr[jj]\n ListJ = [jj]\n elif arr[jj] == M:\n ListJ.append(jj)\n\n if len(ListJ) == 0:\n dq.append((arr, cnt))\n\n for j in ListJ:\n newArr = arr[:]\n now = newArr[i]\n newArr[i] = newArr[j]\n newArr[j] = now\n dq.append((newArr, cnt+1))\n\n i += 1\n\n return answer\n\nanswer = -1\nresult = bfs()\nfor arr in result:\n s = \"\".join(map(str, arr))\n answer = max(answer, int(s))\n\nprint(answer)\n\n\n","repo_name":"hyukji/AlgorithmProblem","sub_path":"Python/5000/1039.py","file_name":"1039.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35364099179","text":"\"\"\"\nA file which holds Deck class declaration\n\"\"\"\nimport random\nimport card\n\nclass Deck():\n \"\"\"\n Class which implements a standard 52 deck with 4 suits\n \"\"\"\n suits = [\"♥\", \"♢\", \"♧\", \"♤\",]\n ranks = [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\", \"A\"]\n\n def __init__(self):\n self.cards = []\n for suts in Deck.suits:\n for raks in Deck.ranks:\n self.cards.append(card.Card(raks, suts))\n\n def __str__(self):\n res = \"\"\n for crd in self.cards:\n res += crd.rank +crd.suit + \" \"\n return res\n\n def pull_card(self):\n \"\"\"\n Removes a card-object from list of cards of the deck. Returns the removed object\n \"\"\"\n crd = random.choice(self.cards)\n self.cards.remove(crd)\n return crd\n\n def reshuffle(self):\n \"\"\"\n Gets back the deck\n \"\"\"\n self.cards.clear()\n self.__init__()\n","repo_name":"GKM364/BlackJack","sub_path":"deck.py","file_name":"deck.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8991565142","text":"# Author: RT\n# Date: 2022-08-07T15:20:21.380Z\n# URL: https://leetcode.com/problems/count-vowels-permutation/\n\n\nfrom functools import cache\n\n\nclass Solution:\n def countVowelPermutation(self, n: int) -> int:\n G = {\n \"a\": [\"e\"],\n \"e\": [\"a\", \"i\"],\n \"i\": [\"a\", \"e\", \"o\", \"u\"],\n \"o\": [\"i\", \"u\"],\n \"u\": [\"a\"],\n }\n M = 1_000_000_007\n\n @cache\n def dp(u, i):\n if i == n:\n return 1\n\n return sum(dp(v, i + 1) % M for v in G[u]) % M\n\n return sum(dp(start, 1) % M for start in G.keys()) % M\n\n def bottom_up(self, n: int, G: dict[str, list[str]], M: int) -> int:\n # dp[c][i] number of permutations starting with char c of length i + 1\n dp = {start: [1] * n for start in G.keys()}\n\n # conceptually building the string backwards\n ans = 0\n for i in range(1, n):\n for u in G.keys():\n # only previous value of every starting chars is needed, can be\n # further compressed to O(1) space\n dp[u][i] = sum(dp[v][i - 1] for v in G[u]) % M\n\n return sum(dp[start][-1] for start in G.keys()) % M\n","repo_name":"Roytangrb/dsa","sub_path":"leetcode/python/1220-count-vowels-permutation.py","file_name":"1220-count-vowels-permutation.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"}
+{"seq_id":"6242662214","text":"import numpy as np\n\n# ============================================================================================================= #\ndef ide_solve(idefun, Core, delays_int, history, tspan, stepsize, delays=False, overlapping=False):\n # idefun - right-hand side function (t - time, y - solution, z - dicrete delays, i - integral)\n # Core - Kernel (integrated function)\n # delays_int - distributed delays function (lower integration limit)\n # History - history function\n # tspan - solution interval\n # stepsize - step of numerical Runge-Kutta method\n # delays - (optional) discrete delays function (if idefun has 'z')\n # overlapping - (optional) if equation has overlapping in discrete delays. This option uses the 7-step method\n\n t0 = tspan[0] # t begin\n tf = tspan[1] # t end\n y0 = history(t0) # initial solution\n neq = np.size(y0) # number of equations\n htry = stepsize # constant mesh step-size\n h = htry # current step-size (for the last step)\n\n if delays is not False:\n d_t0 = delays(t0, y0)\n nz = np.size(d_t0)\n else:\n nz = 1\n # ============================================================== #\n\n\n if overlapping:\n # VIDE Runge-Kutta Tavernini\n A = np.array([[0, 1, 3/8, 1/2, 5/24, 1/6],\n [0, 0, 1/8, 1/2, 0, 0],\n [0, 0, 0, 0, 1/3, -1/3],\n [0, 0, 0, 0, -1/24, 1/6],\n [0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0]])\n\n b = np.array([1/6, 0, 0, 0, 2/3, 1/6])\n c = np.array([0, 1, 1/2, 1, 1/2, 1])\n d = np.array([1/2, 1/2, 1/2, 1/2, 1])\n b4 = b4_Tav\n F_stages_calc = [1, 2]\n method = \"Tav\"\n else:\n # VIDE Runge-Kutta 4\n A = np.array([[0, 1/2, 0, 0],\n [0, 0, 1/2, 0],\n [0, 0, 0, 1],\n [0, 0, 0, 0]])\n\n b = np.array([1/6, 1/3, 1/3, 1/6])\n c = np.array([0, 1/2, 1/2, 1])\n d = np.array([1/2, 1/2, 1])\n b4 = b4_RK4\n F_stages_calc = [1, 3]\n method = \"RK4\"\n\n s = len(b)\n # ============================================================== #\n nint = np.size(delays_int(t0))\n # Calculate integral (F) in history\n F = np.zeros(nint)\n \n tj = delays_int(t0) # Begin\n for ij in range(nint):\n step = int((t0 - tj[ij])/h) # The number of memorized intervals of history\n tj_1 = t0 - step * h # End\n tj_half = (tj[ij] + tj_1) / 2 # Half segment\n\n # Calculate Kernel values at the nodes\n Core_tj = Core(t0, tj[ij], history(tj[ij]))\n Core_tj_1 = Core(t0, tj_1, history(tj_1))\n Core_tj_h = Core(t0, tj_half, history(tj_half))\n\n # Simpson's method\n F[ij] = F[ij] + int_simpson(tj_1 - tj[ij], Core_tj[ij], Core_tj_1[ij], Core_tj_h[ij])\n\n # Main integral over the mesh points\n Core_tj = Core_tj_1\n for j in range(step - 1, -1, -1):\n tj_1 = t0 - j * h\n tj_half = tj_1 - h / 2\n\n # Calculate Kernel values at the nodes\n Core_tj_h = Core(t0, tj_half, history(tj_half))\n Core_tj_1 = Core(t0, tj_1, history(tj_1))\n\n # Simpson's method\n F[ij] = F[ij] + int_simpson(h, Core_tj[ij], Core_tj_1[ij], Core_tj_h[ij])\n\n # Kernel of tj_1 is equal to tj of the next step\n Core_tj = Core_tj_1\n \n # F = (exp(-delays_int(t0)*t0 + delays_int(t0)) - exp(-t0*t0 + t0))/(t0 - 1)\n # ============================================================== #\n # Initialization | First Step | Y | K\n t = [t0]\n y = np.zeros((neq, 1))\n y[:, 0] = y0\n k = 0 # step\n \n z = np.zeros((neq, nz))\n if delays is not False:\n for kz in range(nz):\n z[:, kz] = history(d_t0[kz])\n \n Y = np.zeros((neq, s))\n K = np.zeros((neq, s, 1))\n \n K[:, 0, k] = idefun(t[k], y[:, 0], z, F)\n Core_di = np.zeros((nint, s))\n \n while t[k] < tf:\n # ============================================================== #\n # Last step\n if t[k] + h > tf:\n h = tf - t[k]\n # ============================================================== #\n Z = np.zeros((nint, s))\n Y[:, 0] = y[:, k]\n \n for i in range(1, s):\n ti = t[k] + c[i] * h\n # ============================================================== #\n # Calculate integral (F)\n if i in F_stages_calc: # c[3] = c[2] so the same F value is used\n F = np.zeros(nint)\n \n dtk_begin = delays_int(ti) # lower integration limit\n for ij in range(nint):\n if dtk_begin[ij] < t0:\n # ============================================================== #\n # Integral begins in the history\n\n # Step of delays(ti) in the history\n step = int((t0 - dtk_begin[ij]) / htry)\n\n # Add piece from dtk_begin to the next mesh point in the history\n tj = dtk_begin[ij]\n tj_1 = t0 - step * htry\n tj_half = (tj + tj_1) / 2\n\n # Calculate Kernel values at the nodes\n Core_tj = Core(ti, tj, history(tj))\n Core_tj_1 = Core(ti, tj_1, history(tj_1))\n Core_tj_h = Core(ti, tj_half, history(tj_half))\n\n # Simpson's method\n F[ij] = F[ij] + int_simpson(tj_1 - tj, Core_tj[ij], Core_tj_1[ij], Core_tj_h[ij])\n\n # Main integral in the history\n Core_tj = Core_tj_1\n for j in range(step - 1, -1, -1):\n tj_1 = t0 - j * htry\n tj_half = tj_1 - htry / 2\n\n # Calculate Kernel values at the nodes\n Core_tj_1 = Core(ti, tj_1, history(tj_1))\n Core_tj_h = Core(ti, tj_half, history(tj_half))\n\n # Simpson's method\n F[ij] = F[ij] + int_simpson(htry, Core_tj[ij], Core_tj_1[ij], Core_tj_h[ij])\n\n # Kernel of tj_1 is equal to tj of the next step \n Core_tj = Core_tj_1\n \n # Add integral in the solution to t(k)\n for j in range(1, k + 1):\n tj_half = t[j] - htry / 2\n y_half = y[:, j - 1] + htry * np.dot(K[:, :, j - 1], b4(1/2))\n # Calculate Kernel values at the nodes\n Core_tj_h = Core(ti, tj_half, y_half)\n Core_tj_1 = Core(ti, t[j], y[:, j])\n\n # Simpson's method\n F[ij] = F[ij] + int_simpson(htry, Core_tj[ij], Core_tj_1[ij], Core_tj_h[ij])\n\n # Kernel of tj_1 is equal to tj of the next step \n Core_tj = Core_tj_1\n # ============================================================== #\n else:\n # ============================================================== #\n # Integral only over the solution\n\n # Step of delays(ti) in the solution\n step = int((dtk_begin[ij] - t0) / htry)\n\n # Add piece from dtk_begin to the mesh point in the solution\n tj_half = (t[step+1] + dtk_begin[ij]) / 2\n\n y_begin = y[:, step] + htry * np.dot(K[:, :, step], b4((dtk_begin[ij] - t[step]) / htry))\n y_begin_h = y[:, step] + htry * np.dot(K[:, :, step], b4((tj_half - t[step]) / htry))\n\n # Calculate Kernel values at the nodes\n Core_tj = Core(ti, dtk_begin[ij], y_begin)\n Core_tj_1 = Core(ti, t[step+1], y[:, step+1])\n Core_tj_h = Core(ti, tj_half, y_begin_h)\n\n # Simpson's method\n F[ij] = F[ij] + int_simpson(t[step+1]-dtk_begin[ij], Core_tj[ij], Core_tj_1[ij], Core_tj_h[ij])\n\n # Main integral to t(k)\n Core_tj = Core_tj_1\n for j in range(step + 2, k + 1):\n tj_half = t[j] - htry / 2\n y_half = y[:, j - 1] + htry * np.dot(K[:, :, j - 1], b4(1/2))\n\n # Calculate Kernel values at the nodes\n Core_tj_h = Core(ti, tj_half, y_half)\n Core_tj_1 = Core(ti, t[j], y[:, j])\n\n # Simpson's method\n F[ij] = F[ij] + int_simpson(htry, Core_tj[ij], Core_tj_1[ij], Core_tj_h[ij])\n\n # Kernel of tj_1 is equal to tj of the next step \n Core_tj = Core_tj_1\n # ============================================================== #\n if method == \"Tav\":\n if i == 1:\n F_1 = F\n else:\n F_half = F\n else:\n if i == 1:\n F_half = F\n if method == \"Tav\":\n if i == 3 or i == 5:\n F = F_1\n elif i == 4:\n F = F_half\n else:\n if i == 2:\n F = F_half\n\n # F = (exp(-t[k]*ti + t[k]) - exp(-delays_int(ti)*ti + delays_int(ti)))/(1 - ti)\n # ============================================================== #\n # Y2-S\n Y[:, i] = y[:, k] + h * np.dot(K[:, 0:i, k], A[0:i, i])\n \n # Z2-S\n Core_di[:, i-1] = Core(t[k] + d[i-1] * h, t[k] + c[i-1] * h, Y[:, i-1])\n Z[:, i] = h * np.dot(Core_di[:, 0:i], A[0:i, i])\n # ============================================================== #\n #Finding delays Z\n if delays is not False:\n d_ti = delays(ti, Y[:, i])\n\n for kz in range(nz):\n if d_ti[kz] < t0:\n z[:, kz] = history(d_ti[kz])\n elif ti < d_ti[kz]:\n # wrong overlapping\n raise NameError(\"Delays went ahead\")\n elif t[k] - d_ti[kz] <= 0:\n # overlapping\n if method == \"Tav\":\n teta = (d_ti[kz] - t[k]) / h\n z[:, kz] = y[:, k] + h * np.dot(K[:, 0:i, k], MatrixA(teta, i))\n else:\n raise NameError(\"Overlapping. Choose method Tavernini with key 'overlapping=true'\")\n else:\n # find t\n # ============Binary search algorithm=========== #\n tcur = d_ti[kz]\n iz = 0\n jz = len(t) - 1\n nstep = int(jz / 2)\n\n while (t[nstep+1] < tcur or t[nstep] > tcur) and iz < jz:\n if tcur > t[nstep]:\n iz = nstep + 1\n else:\n jz = nstep - 1\n nstep = int((iz + jz) / 2)\n # ============================================== #\n\n # find z\n theta = (tcur - t[nstep])/htry\n z[:, kz] = y[:, nstep] + htry * np.dot(K[:, :, nstep], b4(theta))\n \n # K2-S\n K[:, i, k] = idefun(ti, Y[:, i], z, F + Z[:, i])\n # ============================================================== #\n # Final approximation of RK Method\n t.append(t[k] + h)\n y = np.append(y, np.zeros((neq, 1)), axis=1)\n y[:, k+1] = y[:, k] + h * np.dot(K[:, :, k], b)\n # ============================================================== #\n # Calculate K(1) for next step\n # Hermite extrapolation for K(1,k+1)\n y_k_half = 3/4 * y[:, k] + 1/4 * y[:, k+1] + h/4 * K[:, 0, k]\n \n Core_tj = Core(t[k+1], t[k], y[:, k])\n Core_tk_half = Core(t[k+1], t[k] + h / 2, y_k_half)\n Core_tk = Core(t[k+1], t[k+1], y[:, k+1])\n \n for ij in range(nint):\n F[ij] = F[ij] + int_simpson(h, Core_tj[ij], Core_tk[ij], Core_tk_half[ij])\n \n K = np.append(K, np.zeros((neq, s, 1)), axis=2)\n K[:, 0, k+1] = idefun(t[k+1], y[:, k+1], z, F)\n \n k = k + 1\n \n if neq == 1:\n y = y[0, :]\n return t, y\n# ============================================================================================================= #\n\n\ndef int_simpson(h, y_begin, y_end, y_half):\n # Simpson's method\n y_begin = np.array(y_begin)\n y_end = np.array(y_end)\n y_half = np.array(y_half)\n return h/6 * (y_begin + 4 * y_half + y_end)\n\n\ndef b4_Tav(a):\n x = np.zeros(6)\n sqrA = a ** 2\n x[0] = a * (1 + a * (-3/2 + a * 2/3))\n x[1] = 0\n x[2] = 0\n x[3] = 0\n x[4] = sqrA * (2 + a * -4/3)\n x[5] = sqrA * (-1/2 + a * 2/3)\n return x\n\n\ndef b4_RK4(a):\n x = np.zeros(4)\n sqrA = a ** 2\n x[0] = a * (1 + a * (-3/2 + a * 2/3))\n x[1] = sqrA * (1 + a * -2/3)\n x[2] = sqrA * (1 + a * -2/3)\n x[3] = sqrA * (-1/2 + a * 2/3)\n return x\n\n\ndef MatrixA(a, step):\n MatrixA_switch = {\n 0: 0,\n 1: a,\n 2: [a * (1 - a * 1/2), 1/2 * a * a],\n 3: [a * (1 - a * 1/2), 1/2 * a * a, 0],\n 4: [a * (1 + a * (-3/2 + a * 2/3)), 0, a**2 * (2 - a * 4/3), a**2 * (-1/2 + a * 2/3)],\n 5: [a * (1 + a * (-3/2 + a * 2/3)), 0, a**2 * (1 - a * 4/3), a**2 * (-1/2 + a * 2/3), a**2]\n }\n return MatrixA_switch[step]\n","repo_name":"vitesempl/RK-IDE-Python","sub_path":"RK/ide.py","file_name":"ide.py","file_ext":"py","file_size_in_byte":14274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38421165657","text":"import json\nfrom os import urandom\nimport werkzeug\n\nimport blowfish\n\nconfig = {\n 'CIPHER_key' : b'\\xf4\\'\\xc3(L\\xd0\\xcfD\"B/g', \n 'initialization_vector' : b'7Cp\\x95\\x85\\x029#',\n}\n\n\nclass BlowfishException(werkzeug.exceptions.BadRequest):\n def __init__(self, message):\n self.message = message\n\n def __str__(self):\n return str(self.message)\n\n\nclass Blowfish:\n AVAILABLE_MODES = ['cbc_cts', 'cfb', 'ofb', 'ecb_cts']\n DEFAULT_MODE = 'cbc_cts'\n CIPHER = blowfish.Cipher(config['CIPHER_key'])\n IV = config['initialization_vector']\n\n #This shouldn't really be called directly - it's just a way to shorten code. \n #Rather just use encrypt_data() and decrypt_data()\n @staticmethod\n def _handle_data(action, data, mode = None):\n if not mode: mode = Blowfish.DEFAULT_MODE\n\n elif mode not in Blowfish.AVAILABLE_MODES: \n raise BlowfishException('Mode not supported: ' + str(mode))\n\n if action not in ['encrypt', 'decrypt']:\n raise BlowfishException(\"Called _handle_data() with action: ' + str(action) + '. Must be `encrypt` or `decrypt`. Protip: You probably shouldn't directly call _handle_data. \")\n\n action = '%s_%s' % (action, mode)\n\n #There might be a better way to implement this, which will also allow us to support multiple modes. \n args = [data, Blowfish.IV]\n if mode == 'ecb_cts' : \n args = [data]\n\n handled_data = b\"\".join(getattr(Blowfish.CIPHER, action)(*args))\n return handled_data\n\n @staticmethod\n def encrypt(data, mode = None):\n data = data.encode('utf-8')\n encrypted_data = Blowfish._handle_data('encrypt', data, mode)\n encrypted_data = encrypted_data.hex()\n return encrypted_data\n\n @staticmethod\n def decrypt(data, mode = None):\n data = bytes.fromhex(data)\n decrypted_data = Blowfish._handle_data('decrypt', data, mode)\n print ('Data : ', decrypted_data)\n try:\n decrypted_data = decrypted_data.decode('utf-8')\n except UnicodeDecodeError:\n return str(decrypted_data)\n return decrypted_data\n","repo_name":"rafaeelaudibert/Encryptor","sub_path":"encryptor/encryptors/blowfish.py","file_name":"blowfish.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"}
+{"seq_id":"15093851573","text":"#Ejercicio01\ndef descuento(tipo,prestamo):\n # Si el tipo de cliente es EXCLUSIVO\n # Aqui se usa la funcion upper()\n if (tipo.upper()== \"COMPULSIVO\"):\n return 0.10 * prestamo\n else:\n return 0\ndef reporte_prestamo(nombre,precio,descuento):\n print(\"##################################\")\n print(\"# ficha de boleta #\")\n print(\"#nombre: \" +nombre+ \"\")\n print(\"#precio: s/. \"+str(precio)+\"\")\n print(\"#descuento: s/. \"+str(descuento)+\"\")\n print(\"##################################\")\n\n#Ejercicio02\ndef validar_nombre(strNombre):\n #1. El tipo de dato de strNombre es str\n #2. La longitud de la cadena es al menos de 3\n if ( isinstance(strNombre, str) ):\n if ( len(strNombre) >= 3):\n return True # Es un nombre valido\n else:\n return False # Insuficients caracteres\n else:\n return False # No es str\n#fin_validar_nombre\n\n#Ejercicio03\n# Funcion : Verifica si intNum es un entero\n# Parametros: intNum => Numero entero\n# Retorna : bool\ndef validar_entero(intNum):\n if ( isinstance(intNum, int)):\n return True\n else:\n return False\n#fin_validar_entero\n\n#Ejercicio04\n# Funcion : Verifica si fltNum es un real\n# Parametros: fltNum => Numero real\n# Retorna : bool\ndef validar_real(fltNum):\n if ( isinstance(fltNum, float)):\n return True\n else:\n return False\n\n#Ejercicio05\n# Funcion : Devuelve la calificacion del promedio\n# Parametros: flotProm ==\n# Retorna : str\ndef calificacion(fltProm):\n if ( fltProm == 20.0):\n return \"Excelente\"\n if ( fltProm == 16.0):\n return \"Muy Bien \"\n if ( fltProm == 12.0):\n return \"Regular\"\n if ( fltProm == 5.0):\n return \"Bajo\"\n if ( fltProm == 0.0):\n return \"Muy Bajo\"\n else:\n return \"\"\n#fin_calificacion\n\n#Ejercicio06\n# Funcion : Devuelve el bonus por puntaje\n# Parametros: strCalif == Puntaje\n# Retorna : float\ndef obtenerBonus(strPuntaje):\n if ( strPuntaje == \"Excelente\"):\n return 300.0\n if ( strPuntaje==\"Muy Bien\"):\n return 200.0\n if ( strPuntaje == \"Regular\"):\n return 100.0\n else:\n return 0.0\n#fin_obtenerBonus\n\n#Ejercicio07\ndef validar_obrero(strObrero):\n #1. El tipo de dato de strObrero es str\n #2. La longitud de la cadena es al menos de 5\n if ( isinstance(strObrero, str) ):\n if ( len(strObrero) >= 5):\n return True # Es un nombre valido\n else:\n return False # Insuficients caracteres\n else:\n return False # No es str\n#fin_validar_obrero\n\n#Ejercicio08\ndef validar_codigo (strCodigo):\n #1. strCodigo es una cadena de 5 caracteres\n #2. El primer caracter de strCodigo es el signo #\n if (len(strCodigo) != 5):\n return False\n if (strCodigo[0] == \"#\"):\n return True\n #fin_if\n#fin_validar_codigo\n\n#Ejercicio09\ndef validar_anio(intAnio):\n #1.El tipo de dato es intAnio es int\n #2.La longitud del entero es al menos de 2050\n if(isinstance(intAnio,int)):\n if((intAnio) >= 2050):\n return True #Es anio valido\n else:\n return False\n else:\n return False #No es int\n\n#Ejercicio10\n# Funcion : Devuelve la calificacion del puntaje\n# Parametros: StrPuntaje => Puntaje\n# Retorna : float\ndef pasa_pedido(strPuntaje):\n if ( strPuntaje == \"Excelente\"):\n return 100.0\n if ( strPuntaje == \"Bajo\"):\n return 50.0\n if ( strPuntaje == \"Muy bajo\"):\n return 20.0\n else:\n return 0.0\n#fin_pasa_pedido\n\n#Ejercicio11\n# Funcion : Verifica si intNum es un entero\n# Parametros: intNum => Numero entero\n# Retorna : bool\ndef ganancia(intNum):\n if ( isinstance(intNum, int)):\n return True\n else:\n return False\n#fin_ganancia\n\n#Ejercicio12\n# Funcion : Devuelve el puntaje minimo\n# Parametros: floatPuntmin ==\n# Retorna : str\ndef puntaje_minimo(fltPuntmin):\n if ( fltPuntmin == 220.0):\n return \"Alcanza puntaje, pase pedido\"\n if ( fltPuntmin == 180.0):\n return \"Muy bien, le falta poco \"\n if ( fltPuntmin == 100.0):\n return \"Sigue ofreciendo\"\n else:\n return \"\"\n#fin_puntaje_minimo\n\n#Ejercicio13\ndef validar_empleado(strEmpleado):\n #1. El tipo de dato de strEmpleado es str\n #2. La longitud de la cadena es al menos de 5\n if ( isinstance(strEmpleado, str) ):\n if ( len(strEmpleado) >= 6):\n return True # Es un nombre valido\n else:\n return False # Insuficients caracteres\n else:\n return False # No es str\n#fin_validar_empleado\n\n#Ejercicio14\ndef validar_contrasena (strContrasena):\n #1. strContrasena es una cadena de 5 caracteres\n #2. El primer caracter de strContrasena es el signo #\n if (len(strContrasena) != 5):\n return False\n if (strContrasena[0] == \"#\"):\n return True\n #fin_if\n#fin_validar_contrasena\n\n#Ejercicio15\ndef es_valido (strNum):\n #1. strNum puede ser un numero de 0-2 o letras de A-C\n if (strNum == \"0\" or strNum ==\"1\" or strNum ==\"2\" or\n strNum==\"A\" or strNum ==\"B\" or strNum==\"C\"):\n return True\n else:\n return False\n #fin_if\n#fin_es_valido\n","repo_name":"Diana-rufasto/t08_rufasto.llontop","sub_path":"Rufasto.Torres/libreria.py","file_name":"libreria.py","file_ext":"py","file_size_in_byte":5241,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18822995808","text":"\"\"\"\\\nInterfaces for JSON:API representations of application objects.\n\n\"\"\"\n\nimport re\nimport typing\n\nimport zope.interface\nimport zope.interface.common.interfaces\nimport zope.interface.common.mapping\nimport zope.interface.common.sequence\nimport zope.schema\nimport zope.schema.interfaces\n\n\n_re_gac = r'[a-zA-Z0-9\\u0080-\\uffff]'\n_re_memch = r'[-a-zA-Z0-9\\u0080-\\uffff_ ]'\n\n_re_member_name = f'{_re_gac}({_re_memch}*{_re_gac})?$'\n_rx_member_name = re.compile(_re_member_name.replace(' ', ''))\n\n\n# --------------------\n# Exception interfaces\n\n\nclass IQueryStringException(zope.interface.common.interfaces.IValueError):\n \"\"\"Interface for QueryStringException instances.\"\"\"\n\n key = zope.schema.TextLine(\n title='Key',\n description='Name of key in query string',\n required=True,\n )\n\n\nclass IInvalidNameException(zope.interface.common.interfaces.IException):\n \"\"\"Interface for the Invalid* exceptions.\"\"\"\n\n field = zope.schema.Object(\n description='Field which failed validation',\n schema=zope.schema.interfaces.IField,\n required=True,\n )\n\n value = zope.interface.Attribute(\"Value determined to be invalid\")\n\n\nclass IInvalidResultStructure(zope.interface.common.interfaces.IValueError):\n \"\"\"Interface for InvalidResultStructure instances.\"\"\"\n\n kind = zope.schema.TextLine(\n description=('Name of the structure as defined in the'\n ' JSON:API specification'),\n required=True,\n )\n\n\n# ----------\n# Exceptions\n\n\n@zope.interface.implementer(IInvalidNameException)\nclass _InvalidName(zope.schema.interfaces.ValidationError):\n \"\"\"Name is invalid according to JSON:API.\"\"\"\n\n\nclass InvalidMemberName(_InvalidName):\n \"\"\"Member name is invalid according to JSON:API.\"\"\"\n\n\nclass InvalidRelationshipPath(_InvalidName):\n \"\"\"Relationship path includes invalid member name according to JSON:API.\n \"\"\"\n\n\nclass InvalidTypeName(_InvalidName):\n \"\"\"Type name is invalid according to JSON:API.\"\"\"\n\n\n@zope.interface.implementer(IQueryStringException)\nclass QueryStringException(ValueError):\n \"\"\"Something is wrong with the format or content of the query string.\"\"\"\n\n def __init__(self, message, key):\n \"\"\"Initialize with an error message and the key from query string.\"\"\"\n super(QueryStringException, self).__init__(message)\n self.key = key\n\n\nclass InvalidQueryKey(QueryStringException):\n \"\"\"A key in the query string is malformed.\"\"\"\n\n\nclass InvalidQueryKeyUsage(QueryStringException):\n \"\"\"A key in the query string is used inconsistently.\"\"\"\n\n\nclass InvalidQueryKeyValue(QueryStringException):\n \"\"\"A key in the query string has an unsupported value.\"\"\"\n\n def __init__(self, message, key, value):\n \"\"\"Initialize with message, key and value from query string.\"\"\"\n super(InvalidQueryKeyValue, self).__init__(message, key)\n self.value = value\n\n\n@zope.interface.implementer(IInvalidResultStructure)\nclass InvalidResultStructure(ValueError):\n \"\"\"Serialization resulted in an invalid structure.\"\"\"\n\n def __init__(self, kind):\n \"\"\"Construct exception for a specific *kind* of structure.\n\n *kind* should be a term defined in the JSON:API specification.\n\n \"\"\"\n super(InvalidResultStructure, self).__init__(kind)\n self.kind = kind\n\n def __str__(self):\n return f'serialization generated invalid structure for {self.kind}'\n\n\n# -----------------\n# Field definitions\n\n\nclass _Name(zope.schema.TextLine):\n\n def __init__(self, *args, **kwargs):\n # The constructor for zope.interface.Element uses __name__ for\n # __doc__, and sets __name__ to None, if there's a space in\n # __name__. Since our field names are generated based on user\n # input, this is wrong behavior for us, so work around it.\n name = kwargs.pop('__name__', None)\n kwargs['__name__'] = 'xxx'\n super(_Name, self).__init__(*args, **kwargs)\n self.__name__ = name\n\n def constraint(self, value):\n if _rx_member_name.match(value) is None:\n raise self._exception().with_field_and_value(self, value)\n else:\n return True\n\n\nclass MemberName(_Name):\n \"\"\"Member name, as defined by JSON:API.\n\n Allowed member names are `constrained by the specification\n `__.\n This definition applies to the names of attributes and relationships.\n\n Raises :exc:`InvalidMemberName` when constraints are not satisfied.\n\n \"\"\"\n\n _exception = InvalidMemberName\n\n\nclass RelationshipPath(_Name):\n \"\"\"Dotted sequence of member names, as defined by JSON:API.\n\n Allowed member names are `constrained by the specification\n `__.\n This definition applies to the names of attributes and relationships.\n\n Raises :exc:`InvalidRelationshipPath` when constraints are not satisfied.\n\n \"\"\"\n\n _exception = InvalidRelationshipPath\n\n def constraint(self, value):\n try:\n for part in value.split('.'):\n super(RelationshipPath, self).constraint(part)\n except InvalidRelationshipPath as e:\n e.value = value\n raise\n else:\n return True\n\n\nclass TypeName(_Name):\n \"\"\"Type name, as defined by JSON:API.\n\n Allowed type names are `constrained by the specification\n `__\n in the same way as member names.\n\n Raises :exc:`InvalidTypeName` when constraints are not satisfied.\n\n \"\"\"\n\n _exception = InvalidTypeName\n\n\nclass URL(zope.schema.TextLine):\n\n def __init__(self, title=None, description=None, min_length=None,\n **kwargs):\n kwargs.update(\n title=(title or 'URL'),\n description=(description or 'Absolute or relative URL'),\n min_length=(min_length or 1),\n )\n super(URL, self).__init__(**kwargs)\n\n\n# ---------------------------------------------\n# Interfaces used when everything is going well\n\n\nclass IFieldMapping(zope.interface.common.mapping.IEnumerableMapping):\n \"\"\"Mapping from field names to JSON-encodable values.\n\n Keys are only strings that conform to the JSON:API field name\n constraints.\n\n \"\"\"\n\n\nclass IRelationships(zope.interface.common.mapping.IEnumerableMapping):\n \"\"\"Mapping from field names to IRelationship instances.\n\n Keys are only strings that conform to the JSON:API field name\n constraints.\n\n \"\"\"\n\n\nclass IMetadataProvider(zope.interface.Interface):\n\n def meta() -> IFieldMapping:\n \"\"\"Retrieve a mapping containing non-standard, named metadata fields.\n\n The mapping may be empty.\n\n \"\"\"\n\n\nclass ILink(IMetadataProvider):\n\n href = URL(required=True)\n\n rel = zope.schema.ASCIILine(\n description='The :rfc:`8288` relationship type of the link.',\n min_length=1,\n required=False,\n missing_value=None,\n )\n\n describedby = zope.schema.Object(\n description='''\n Link to a description document describing the link target.\n This is usualy a specification such as OpenAPI, JSON Schema,\n or XML Schema.\n ''',\n # NB: This gets fixed up below; we can't refer to ILink yet.\n schema=IMetadataProvider,\n required=False,\n missing_value=None,\n )\n\n title = zope.schema.TextLine(\n description='''\n Human-facing title for the link, possibly suitable as a\n menu entry. This is not necessarily the title of the\n linked document.\n ''',\n min_length=1,\n required=False,\n missing_value=None,\n )\n\n type = zope.schema.ASCIILine(\n description='Media type of the document referenced by *href*.',\n min_length=3,\n required=False,\n missing_value=None,\n )\n\n hreflang = zope.interface.Attribute('hreflang', '''\n String or sequence of strings specifying languages the target\n document is available in. Each entry must conform to\n :rfc:`5646`. May be `None`.\n ''')\n\n\nILink.get('describedby').schema = ILink\n\n\nclass ILinksProvider(zope.interface.Interface):\n\n def links() -> IFieldMapping:\n \"\"\"Retrieve a mapping containing standard, named links.\n\n The mapping may be empty.\n\n Consumers are not required to support link names that are not\n defined in the JSON:API specification.\n\n \"\"\"\n\n\nclass IResourceIdentifer(IMetadataProvider):\n\n id = zope.schema.Text(\n title='Identifier',\n description=('Identifier to distinguish resource from'\n ' from others of the same type'),\n required=True,\n readonly=True,\n )\n\n type = MemberName(\n title='Type',\n description='JSON:API resource type identifier',\n required=True,\n readonly=True,\n )\n\n\nclass IResource(IResourceIdentifer, ILinksProvider):\n\n def attributes() -> IFieldMapping:\n \"\"\"Return mapping of attribute names to values.\"\"\"\n\n def relationships() -> IRelationships:\n \"\"\"Return mapping of relationship names to relationship objects.\"\"\"\n\n\nclass ICollection(ILinksProvider, IMetadataProvider):\n\n def resources():\n \"\"\"Return sequence of resources of collection.\n\n This method will only be called once, and the return value will\n only be interated over once.\n\n \"\"\"\n\n\nclass IFilterableCollection(ICollection):\n\n def set_filter(filter):\n \"\"\"Apply filtering parameters from the request.\n\n If the specific filtering parameters provided are not\n supported, an appropriate ``BadRequest`` exception must be\n raised.\n\n This will not be invoked if no filtering parameters were\n supplied; the collection should behave as if no filtering were\n requested.\n\n If filtering is requested, this will be called *before* the\n :meth:`~kt.jsonapi.interfaces.ICollection.resources` method is\n called.\n\n Filtering parameters will be applied before sorting parameters\n (if applicable) or pagination parameters (if applicable).\n\n \"\"\"\n\n\nclass ISortableCollection(ICollection):\n\n def set_sort(sort):\n \"\"\"Apply sorting parameters from the request.\n\n If the specific sorting parameters provided are not supported,\n an appropriate ``BadRequest`` exception must be raised.\n\n This will not be invoked if no sorting parameters were supplied;\n the collection should behave as if no sorting were requested.\n\n If sorting is requested, this will be called *before* the\n :meth:`~kt.jsonapi.interfaces.ICollection.resources` method is\n called.\n\n Sorting parameters will be applied after filtering parameters\n (if applicable) and before pagination (if applicable).\n\n \"\"\"\n\n\nclass IPagableCollection(ICollection):\n\n def set_pagination(page):\n \"\"\"Apply pagination parameters from the request.\n\n This is expected to affect the results returned by the\n :meth:`~ICollection.resources` and :meth:`~ICollection.links`\n methods.\n\n If the specific pagination parameters provided are not\n supported, an appropriate ``BadRequest`` exception must be\n raised.\n\n This will not be invoked if no pagination parameters were\n supplied; the collection should behave as if default pagination\n were requested.\n\n If pagination parameters are provided, this will be called\n *before* the :meth:`~kt.jsonapi.interfaces.ICollection.resources`\n method is called.\n\n Pagination parameters will be applied after filtering parameters\n (if applicable) and sorting parameters (if applicable).\n\n \"\"\"\n\n\nclass IRelationshipBase(ILinksProvider, IMetadataProvider):\n\n includable = zope.schema.Bool(\n title='Includable',\n description=\"\"\"\n Indicates whether relationship can be included via ``include``\n query string parameter.\n\n If a non-includable relationship is requested for inclusion\n via ``include``, an exception triggering a **400 Bad Request**\n response will be raised during serialization.\n\n When a non-includable relationship is serialized, no ``data``\n member will be generated. For to-one relationships, the'\n resource will not be retrieved from the relationship, and for\n to-many relationships, the collection's ``resources()`` method\n will not be called.\n\n \"\"\",\n required=True,\n readonly=True,\n )\n\n name = MemberName(\n title='Name',\n description=\"\"\"\n Field name of the relationship.\n\n .. versionadded:: 1.4.0\n *name* added to relationship interfaces. Relationships\n without a value for this attribute cannot be returned as\n primary data when ``fields`` or ``include`` are specified\n in the request.\n \"\"\",\n missing_value=None,\n # Can't require this, since we're adding this in a later version.\n required=False,\n readonly=True,\n )\n\n source = zope.schema.Object(\n title='Source',\n description='Resource containing this relationship.',\n schema=IResource,\n # Can't require this, since we're adding this in a later version.\n required=False,\n readonly=True,\n )\n\n\nclass IToOneRelationship(IRelationshipBase):\n\n def resource() -> typing.Optional[IResource]:\n \"\"\"Return resource referenced by to-one relationship, or None.\"\"\"\n\n\nclass IToManyRelationship(IRelationshipBase):\n\n def collection() -> ICollection:\n \"\"\"Return collection of resources of to-many relationship.\n\n The collection may be filterable, sortable, or pagable, as\n appropriate. Those additional aspects will only be invoked if\n the relationship is rendered as the primary data in a response.\n\n \"\"\"\n\n\nclass IError(ILinksProvider, IMetadataProvider):\n \"\"\"Presentation of a single error.\n\n See `Error Objects `__\n for discussion on the specific information that each field or method\n result represents.\n\n \"\"\"\n\n id = zope.schema.Text(\n title='Identifier',\n description='Identifier for this particular instance of a problem',\n required=False,\n missing_value=None,\n )\n\n status = zope.schema.Int(\n title='Status code',\n description='HTTP status code',\n min=400,\n max=599,\n required=False,\n missing_value=None,\n )\n\n code = zope.schema.TextLine(\n title='Code',\n description='Error code identifying the specific application error',\n required=False,\n missing_value=None,\n )\n\n title = zope.schema.TextLine(\n title='Title',\n description='Human-facing title describing the application error',\n required=False,\n missing_value=None,\n )\n\n detail = zope.schema.Text(\n title='Detailed description',\n description='Human-facing description of this instance of the problem',\n required=False,\n missing_value=None,\n )\n\n def source() -> IFieldMapping:\n \"\"\"Returns mapping containing references to the source of the error.\n\n The mapping may be empty.\n\n \"\"\"\n\n\nclass IErrors(zope.interface.common.sequence.IMinimalSequence):\n \"\"\"Interface representing a collection of `IError` instances.\n\n When generating a JSON:API response from an exception, the exception\n will be adapted to this interface if possible. On success, each\n entry in the ``errors`` property in the generated response will\n correspond to an entry in this sequence.\n\n This sequence cannot be empty.\n\n \"\"\"\n","repo_name":"keepertech/kt.jsonapi","sub_path":"src/kt/jsonapi/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":15868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10403104893","text":"\"\"\"Test aggregation functions.\"\"\"\n\nimport contextlib\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom pandas import Timestamp\n\nfrom cyclops.process.aggregate import AGGFUNCS, Aggregator\nfrom cyclops.process.column_names import (\n ENCOUNTER_ID,\n EVENT_NAME,\n EVENT_TIMESTAMP,\n EVENT_VALUE,\n RESTRICT_TIMESTAMP,\n START_TIMESTAMP,\n START_TIMESTEP,\n STOP_TIMESTAMP,\n TIMESTEP,\n)\nfrom cyclops.process.constants import MEAN, MEDIAN\n\n\nDATE1 = datetime(2022, 11, 3, hour=13)\nDATE2 = datetime(2022, 11, 3, hour=14)\nDATE3 = datetime(2022, 11, 4, hour=3)\nDATE4 = datetime(2022, 11, 4, hour=13)\n\n\n@pytest.fixture()\ndef test_input():\n \"\"\"Create a test events input.\"\"\"\n data = [\n [1, \"eventA\", 10, DATE2, \"wash\"],\n [2, \"eventA\", 19, DATE2, \"clean\"],\n [2, \"eventA\", 11, DATE4, \"dog\"],\n [2, \"eventA\", 18, DATE4, \"pet\"],\n [2, \"eventA\", 12, DATE3, \"store\"],\n [2, \"eventA\", 16, DATE3, \"kobe\"],\n [2, \"eventA\", np.nan, DATE3, \"bryant\"],\n [2, \"eventB\", 13, DATE3, \"trump\"],\n [2, \"eventB\", np.nan, DATE3, \"tie\"],\n [2, \"eventB\", np.nan, DATE1, \"aaa\"],\n ]\n columns = [\n ENCOUNTER_ID,\n EVENT_NAME,\n EVENT_VALUE,\n EVENT_TIMESTAMP,\n \"some_str_col\",\n ]\n\n data = pd.DataFrame(data, columns=columns)\n\n window_start_data = [\n [2, DATE2],\n ]\n window_start = pd.DataFrame(\n window_start_data,\n columns=[ENCOUNTER_ID, RESTRICT_TIMESTAMP],\n )\n window_start = window_start.set_index(ENCOUNTER_ID)\n\n window_stop_data = [\n [2, DATE3],\n ]\n window_stop = pd.DataFrame(\n window_stop_data,\n columns=[ENCOUNTER_ID, RESTRICT_TIMESTAMP],\n )\n window_stop = window_stop.set_index(ENCOUNTER_ID)\n\n return data, window_start, window_stop\n\n\ndef test_aggregate_events(\n test_input,\n):\n \"\"\"Test aggregation function.\"\"\"\n data, _, _ = test_input\n\n # Test initializations of Aggregator.\n aggregator = Aggregator(\n aggfuncs={EVENT_VALUE: MEAN},\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n agg_meta_for=EVENT_VALUE,\n )\n res = aggregator(data)\n\n assert res.index.names == [ENCOUNTER_ID, EVENT_NAME, TIMESTEP]\n assert res.loc[(2, \"eventA\", 1)][EVENT_VALUE] == 19\n assert res.loc[(2, \"eventA\", 14)][EVENT_VALUE] == 14\n assert np.isnan(res.loc[(2, \"eventB\", 0)][EVENT_VALUE])\n assert res.loc[(2, \"eventB\", 14)][EVENT_VALUE] == 13\n\n assert res.loc[(2, \"eventB\", 0)][START_TIMESTEP] == DATE1\n\n\ndef test_aggregate_window_duration(\n test_input,\n):\n \"\"\"Test aggregation window duration functionality.\"\"\"\n data, _, _ = test_input\n\n aggregator = Aggregator(\n aggfuncs={EVENT_VALUE: MEAN},\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n window_duration=12,\n )\n\n res = aggregator(data)\n res = res.reset_index()\n assert (res[TIMESTEP] < 2).all()\n\n\ndef test_aggregate_start_stop_windows(\n test_input,\n):\n \"\"\"Test manually providing start/stop time windows.\"\"\"\n data, window_start_time, window_stop_time = test_input\n\n aggregator = Aggregator(\n aggfuncs={EVENT_VALUE: MEAN},\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n )\n\n res = aggregator(\n data,\n window_start_time=window_start_time,\n window_stop_time=window_stop_time,\n )\n\n assert res.loc[(2, \"eventA\", 0)][START_TIMESTEP] == DATE2\n\n res = res.reset_index().set_index(ENCOUNTER_ID)\n assert res.loc[2][TIMESTEP].max() <= 13\n\n aggregator = Aggregator(\n aggfuncs={EVENT_VALUE: MEAN},\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n window_duration=10,\n )\n try:\n res = aggregator(data, window_stop_time=window_stop_time)\n raise ValueError(\n \"\"\"Should have raised an error that window_duration cannot be set when\n window_stop_time is specified.\"\"\",\n )\n except ValueError:\n pass\n\n\ndef test_aggregate_strings(\n test_input,\n):\n \"\"\"Test that using aggregation strings is equivalent to inputting the functions.\"\"\"\n data, _, _ = test_input\n\n for string, func in AGGFUNCS.items():\n aggregator_str = Aggregator(\n aggfuncs={EVENT_VALUE: string},\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n window_duration=20,\n )\n\n aggregator_fn = Aggregator(\n aggfuncs={EVENT_VALUE: func},\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n window_duration=20,\n )\n\n assert aggregator_str(data).equals(aggregator_fn(data))\n\n with contextlib.suppress(ValueError):\n aggregator_str = Aggregator(\n aggfuncs={EVENT_VALUE: \"shubaluba\"},\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n window_duration=20,\n )\n\n\ndef test_aggregate_multiple(\n test_input,\n):\n \"\"\"Test with multiple columns over which to aggregate.\"\"\"\n data, _, _ = test_input\n\n data[\"event_value2\"] = 2 * data[EVENT_VALUE]\n\n aggregator = Aggregator(\n aggfuncs={\n EVENT_VALUE: MEAN,\n \"event_value2\": MEAN,\n },\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n window_duration=20,\n )\n\n res = aggregator(data)\n\n res = res.reset_index()\n assert res[\"event_value2\"].equals(res[EVENT_VALUE] * 2)\n\n\ndef test_aggregate_one_group_outlier():\n \"\"\"Test very specific one group outlier case (currently still broken).\n\n If only one group in the agg_by and the timesteps form a range, e.g., 0-N, then the\n agg_by columns and TIMESTEP are dropped and an index range is returned.\n\n An example of this setup can be seen below, and currently it is still broken.\n\n \"\"\"\n data = [\n [\n 0,\n \"eventA\",\n 10.0,\n Timestamp(\"2022-11-03 14:00:00\"),\n \"wash\",\n Timestamp(\"2022-11-03 14:00:00\"),\n Timestamp(\"2022-11-03 14:00:00\"),\n 0,\n ],\n [\n 0,\n \"eventA\",\n 10.0,\n Timestamp(\"2022-11-03 14:00:00\"),\n \"wash\",\n Timestamp(\"2022-11-03 14:00:00\"),\n Timestamp(\"2022-11-03 14:00:00\"),\n 1,\n ],\n [\n 0,\n \"eventA\",\n 10.0,\n Timestamp(\"2022-11-03 14:00:00\"),\n \"wash\",\n Timestamp(\"2022-11-03 14:00:00\"),\n Timestamp(\"2022-11-03 14:00:00\"),\n 2,\n ],\n ]\n columns = [\n ENCOUNTER_ID,\n EVENT_NAME,\n EVENT_VALUE,\n EVENT_TIMESTAMP,\n \"some_str_col\",\n START_TIMESTAMP,\n STOP_TIMESTAMP,\n TIMESTEP,\n ]\n\n data = pd.DataFrame(data, columns=columns)\n\n aggregator = Aggregator(\n aggfuncs={EVENT_VALUE: MEAN},\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n )\n\n _ = data.groupby(aggregator.agg_by, sort=False, group_keys=False).apply(\n aggregator._compute_aggregation,\n )\n\n\ndef test_vectorization(\n test_input,\n):\n \"\"\"Test vectorization of aggregated data.\"\"\"\n data, _, _ = test_input\n\n data[\"event_value2\"] = 2 * data[EVENT_VALUE]\n data[\"event_value3\"] = 3 * data[EVENT_VALUE]\n\n aggregator = Aggregator(\n aggfuncs={\n EVENT_VALUE: MEAN,\n \"event_value2\": MEAN,\n \"event_value3\": MEDIAN,\n },\n timestamp_col=EVENT_TIMESTAMP,\n time_by=ENCOUNTER_ID,\n agg_by=[ENCOUNTER_ID, EVENT_NAME],\n timestep_size=1,\n window_duration=15,\n )\n\n aggregated = aggregator(data)\n\n vectorized_obj = aggregator.vectorize(aggregated)\n vectorized, indexes = vectorized_obj.data, vectorized_obj.indexes\n\n agg_col_index, encounter_id_index, event_name_index, timestep_index = indexes\n\n assert set(encounter_id_index) == {1, 2}\n assert set(event_name_index) == {\"eventA\", \"eventB\"}\n assert set(timestep_index) == set(range(15))\n\n assert vectorized.shape == (3, 2, 2, 15)\n assert np.array_equal(\n vectorized[list(agg_col_index).index(EVENT_VALUE)] * 2,\n vectorized[list(agg_col_index).index(\"event_value2\")],\n equal_nan=True,\n )\n assert np.array_equal(\n vectorized[list(agg_col_index).index(EVENT_VALUE)] * 3,\n vectorized[list(agg_col_index).index(\"event_value3\")],\n equal_nan=True,\n )\n","repo_name":"VectorInstitute/cyclops","sub_path":"tests/cyclops/process/test_aggregate.py","file_name":"test_aggregate.py","file_ext":"py","file_size_in_byte":9149,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"3"}
+{"seq_id":"25335910990","text":"# Runtime: 64 ms, faster than 98.58% of Python3 online submissions for Delete Node in a BST.\n# Memory Usage: 16.9 MB, less than 100.00% of Python3 online submissions for Delete Node in a BST.\n# 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 deleteNode(self, root: TreeNode, key: int) -> TreeNode:\n if root is None:\n return \n if root.val == key:\n if root.left:\n # Find the right of most leaf of the left sub-tree\n left_right_most = root.left\n while left_right_most.right:\n left_right_most = left_right_most.right\n # Attach right child to the right of that leaf\n left_right_most.right = root.right\n # Return left child instead of root, delete root\n return root.left\n else:\n return root.right\n elif root.val > key:\n root.left = self.deleteNode(root.left, key)\n else:\n root.right = self.deleteNode(root.right, key)\n return root\n","repo_name":"daidai21/Leetcode","sub_path":"Algorithms/Python3.x/450-Delete_Node_in_a_BST.py","file_name":"450-Delete_Node_in_a_BST.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"70440099602","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @author: Tomas Vitvar, https://vitvar.com, tomas@vitvar.com\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport codecs\nimport os\nimport re\nimport sys\nimport argparse\nimport glob\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n# read file content\ndef read(*parts):\n path = os.path.join(os.path.dirname(__file__), *parts)\n with codecs.open(path, encoding='utf-8') as fobj:\n return fobj.read()\n\n# Read the version number from __init__.py\nhere = os.path.abspath(os.path.dirname(__file__))\nversion_file = os.path.join(here, 'ja2mqtt', '__init__.py')\nexec(open(version_file).read())\n\n# setup main\n# required modules\ninstall_requires = [\n 'click>=8.0.4',\n 'Jinja2>=3.0.3',\n 'paho-mqtt>=1.6.1',\n 'pyserial>=3.5',\n 'PyYAML>=6.0',\n 'jsonschema>=4.0.0',\n 'pytz>=2023.3'\n]\n\nsetup(\n name='ja2mqtt',\n version=__version__,\n description='Jablotron MQTT bridge',\n long_description=read('README-pypi.text'),\n py_modules=['ja2mqtt'],\n author='Tomas Vitvar',\n author_email='tomas@vitvar.com',\n packages=find_packages(exclude=['tests.*', 'tests']),\n include_package_data=True,\n install_requires=install_requires,\n python_requires='>=3.6.0',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python :: 3.7',\n ],\n entry_points='''\n [console_scripts]\n ja2mqtt=ja2mqtt.commands.ja2mqtt:ja2mqtt\n ''',\n)\n","repo_name":"tomvit/ja2mqtt","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"22419700660","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport sys\nimport time\nimport requests\nimport json\nimport RPi.GPIO as GPIO\n\n# 距離を読む関数\ndef read_distance():\n\t# 必要なライブラリのインポート・設定\n\n\t# 使用するピンの設定\n\tGPIO.setmode(GPIO.BOARD)\n\tTRIG = 11 # ボード上の11番ピン(GPIO17)\n\tECHO = 13 # ボード上の13番ピン(GPIO27)\n\n\t# ピンのモードをそれぞれ出力用と入力用に設定\n\tGPIO.setup(TRIG,GPIO.OUT)\n\tGPIO.setup(ECHO,GPIO.IN)\n\tGPIO.output(TRIG, GPIO.LOW)\n\n\t# TRIG に短いパルスを送る\n\tGPIO.output(TRIG, GPIO.HIGH)\n\ttime.sleep(0.00001)\n\tGPIO.output(TRIG, GPIO.LOW)\n\n\t# ECHO ピンがHIGHになるのを待つ\n\tsignaloff = time.time()\n\twhile GPIO.input(ECHO) == GPIO.LOW:\n\t\tsignaloff = time.time()\n\n\t# ECHO ピンがLOWになるのを待つ\n\tsignalon = signaloff\n\twhile time.time() < signaloff + 0.1:\n\t\tif GPIO.input(ECHO) == GPIO.LOW:\n\t\t\tsignalon = time.time()\n\t\t\tbreak\n\n\t# GPIO を初期化しておく\n\tGPIO.cleanup()\n\n\t# 時刻の差から、物体までの往復の時間を求め、距離を計算する\n\ttimepassed = signalon - signaloff\n\tdistance = timepassed * 17000\n\n\t# 500cm 以上の場合はノイズと判断する\n\tif distance <= 500:\n\t\tprint(\"データ取得\")\n\t\treturn distance\n\telse:\n\t\tprint(\"距離500㎝以上:ノイズ判定\")\n\t\treturn distance\n\n# SORACOM Harvestへ送る\ndef send_to_Harvest(Data_distance):\n\t\"\"\"\n\t@description: 距離情報をソラコムハーベストに送信する\n\t@param : Data_distance(距離情報)\n\t@\n\t\"\"\"\n\tif Data_distance:\n\t\t\tprint(\"距離: {:.1f} cm\".format(Data_distance))\n\t\t\theaders = {'Content-Type': 'application/json'}\n\t\t\tpayload = {'distance': round(Data_distance*10)/10 }\n\t\t\tprint(\"データ送信\")\n\n\ttry:\n\t\tprint(requests.post('http://harvest.soracom.io', data=json.dumps(payload), headers=headers, timeout=5))\n\n\texcept requests.exceptions.ConnectTimeout:\n\t\tprint(\"ERROR: 接続がタイムアウトしました。connect_air.sh は実行していますか?\")\n\t\tsys.exit(1)\n\t\t\n\tif (requests.post('http://harvest.soracom.io', data=json.dumps(payload), headers=headers, timeout=5)).status_code == 400:\n\t\t\tprint('ERROR: データ送信に失敗しました。Harvest が有効になっていない可能性があります。')\n\t\t\tsys.exit(1)\n\n\nif __name__ == '__main__':\n\t# 第一引数を interval に設定\n\tinterval=5 if len(sys.argv)==1 else int(sys.argv[1])\n\n\twhile True:\n\t\tstart_time = time.time()\n\t\tdistance = read_distance()\n\n\t\tsend_to_Harvest(distance)\n\t\t\t\t\n\t\t# 指定した秒数に1回実行するためのウェイトを入れる\n\t\twait = start_time + interval - start_time\n\t\tif wait > 0:\n\t\t\ttime.sleep(wait)\n\n","repo_name":"Yuki2Kisaragi/RoomMonitor","sub_path":"src/DistanceData.py","file_name":"DistanceData.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23871913299","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 18 16:51:20 2023\n\n@author: thibaud michelet\n\nThis is a library that make the linguee python api easy to use\n\nhttps://github.com/imankulov/linguee-api\nthis must be installed\n\"\"\"\n\nimport requests\n\n\ndef translateSingleWord(string, src, dest):\n \n results = Results()\n \n api_root = \"https://linguee-api.fly.dev/api/v2\"\n \n print(\"Word to translate :\", string)\n print(src, \"to\", dest)\n resp = requests.get(f\"{api_root}/translations\", params={\"query\": string, \"src\": src, \"dst\": dest})\n\n json = resp.json()\n print(json)\n \n if (len(json) == 0):\n results.success = False\n results.error_msg = \"Word not found\"\n return results\n \n if (\"message\" in json) :\n if (json[\"message\"] == \"Translation not found\") :\n results.success = False\n results.error_msg = \"Word not found\"\n return results\n \n json = json[0]\n \n results.translation = json[\"translations\"][0][\"text\"]\n # this is the convoluted path in the json that lead to the list of example phrases\n try :\n results.examples = json[\"translations\"][0][\"examples\"]\n \n except :\n results.examples = []\n \n print(json)\n if (len(json) > 0):\n print(results.translation)\n return results\n else:\n return results\n \ndef ExamplesForWord(word, src, dst) :\n \n api_root = \"https://linguee-api.fly.dev/api/v2\"\n \n json = requests.get(f\"{api_root}/examples\", params={\"query\": word, \"src\": src, \"dst\": dst})\n resp = json.json()\n \n print(resp)\n return\n\n\nclass Results :\n \n def __init__(self) :\n \n self.success = True\n self.translation = \"\"\n self.examples = \"\"\n self.error_msg = \"\"","repo_name":"BOX268/Mnajik_II","sub_path":"W_interface/LingueeInterface.py","file_name":"LingueeInterface.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15424813122","text":"import numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras.engine import base_layer\nfrom tensorflow.python.keras.engine import base_preprocessing_layer\nfrom tensorflow.python.keras.utils import layer_utils\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import bincount_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util.tf_export import keras_export\n\nINT = \"int\"\nONE_HOT = \"one_hot\"\nMULTI_HOT = \"multi_hot\"\nCOUNT = \"count\"\n\n\n@keras_export(\"keras.layers.experimental.preprocessing.CategoryEncoding\")\nclass CategoryEncoding(base_layer.Layer):\n \"\"\"Category encoding layer.\n\n This layer provides options for condensing data into a categorical encoding\n when the total number of tokens are known in advance. It accepts integer\n values as inputs and outputs a dense representation (one sample = 1-index\n tensor of float values representing data about the sample's tokens) of those\n inputs. For integer inputs where the total number of tokens is not known, see\n `tf.keras.layers.experimental.preprocessing.IntegerLookup`.\n\n Examples:\n\n **One-hot encoding data**\n\n >>> layer = tf.keras.layers.experimental.preprocessing.CategoryEncoding(\n ... num_tokens=4, output_mode=\"one_hot\")\n >>> layer([3, 2, 0, 1])\n \n\n **Multi-hot encoding data**\n\n >>> layer = tf.keras.layers.experimental.preprocessing.CategoryEncoding(\n ... num_tokens=4, output_mode=\"multi_hot\")\n >>> layer([[0, 1], [0, 0], [1, 2], [3, 1]])\n \n\n **Using weighted inputs in `\"count\"` mode**\n\n >>> layer = tf.keras.layers.experimental.preprocessing.CategoryEncoding(\n ... num_tokens=4, output_mode=\"count\")\n >>> count_weights = np.array([[.1, .2], [.1, .1], [.2, .3], [.4, .2]])\n >>> layer([[0, 1], [0, 0], [1, 2], [3, 1]], count_weights=count_weights)\n \n\n Args:\n num_tokens: The total number of tokens the layer should support. All inputs\n to the layer must integers in the range 0 <= value < num_tokens or an\n error will be thrown.\n output_mode: Specification for the output of the layer.\n Defaults to `\"multi_hot\"`. Values can be `\"one_hot\"`, `\"multi_hot\"` or\n `\"count\"`, configuring the layer as follows:\n - `\"one_hot\"`: Encodes each individual element in the input into an\n array of `num_tokens` size, containing a 1 at the element index. If\n the last dimension is size 1, will encode on that dimension. If the\n last dimension is not size 1, will append a new dimension for the\n encoded output.\n - `\"multi_hot\"`: Encodes each sample in the input into a single array\n of `num_tokens` size, containing a 1 for each vocabulary term present\n in the sample. Treats the last dimension as the sample dimension, if\n input shape is (..., sample_length), output shape will be\n (..., num_tokens).\n - `\"count\"`: As `\"multi_hot\"`, but the int array contains a count of the\n number of times the token at that index appeared in the sample.\n sparse: Boolean. If true, returns a `SparseTensor` instead of a dense\n `Tensor`. Defaults to `False`.\n\n Call arguments:\n inputs: A 2D tensor `(samples, timesteps)`.\n count_weights: A 2D tensor in the same shape as `inputs` indicating the\n weight for each sample value when summing up in `count` mode. Not used in\n `\"multi_hot\"` mode.\n \"\"\"\n\n def __init__(self,\n num_tokens=None,\n output_mode=MULTI_HOT,\n sparse=False,\n **kwargs):\n # max_tokens is an old name for the num_tokens arg we continue to support\n # because of usage.\n if \"max_tokens\" in kwargs:\n logging.warning(\n \"max_tokens is deprecated, please use num_tokens instead.\")\n num_tokens = kwargs[\"max_tokens\"]\n del kwargs[\"max_tokens\"]\n\n super(CategoryEncoding, self).__init__(**kwargs)\n base_preprocessing_layer.keras_kpl_gauge.get_cell(\"CategoryEncoding\").set(\n True)\n\n # Support deprecated names for output_modes.\n if output_mode == \"binary\":\n output_mode = MULTI_HOT\n # 'output_mode' must be one of (COUNT, ONE_HOT, MULTI_HOT)\n layer_utils.validate_string_arg(\n output_mode,\n allowable_strings=(COUNT, ONE_HOT, MULTI_HOT),\n layer_name=\"CategoryEncoding\",\n arg_name=\"output_mode\")\n\n if num_tokens is None:\n raise ValueError(\"num_tokens must be set to use this layer. If the \"\n \"number of tokens is not known beforehand, use the \"\n \"IntegerLookup layer instead.\")\n if num_tokens < 1:\n raise ValueError(\"num_tokens must be >= 1.\")\n\n self.num_tokens = num_tokens\n self.output_mode = output_mode\n self.sparse = sparse\n\n def compute_output_shape(self, input_shape):\n if not input_shape:\n return tensor_shape.TensorShape([self.num_tokens])\n if self.output_mode == ONE_HOT and input_shape[-1] != 1:\n return tensor_shape.TensorShape(input_shape + [self.num_tokens])\n else:\n return tensor_shape.TensorShape(input_shape[:-1] + [self.num_tokens])\n\n def compute_output_signature(self, input_spec):\n output_shape = self.compute_output_shape(input_spec.shape.as_list())\n if self.sparse:\n return sparse_tensor.SparseTensorSpec(\n shape=output_shape, dtype=dtypes.int64)\n else:\n return tensor_spec.TensorSpec(shape=output_shape, dtype=dtypes.int64)\n\n def get_config(self):\n config = {\n \"num_tokens\": self.num_tokens,\n \"output_mode\": self.output_mode,\n \"sparse\": self.sparse,\n }\n base_config = super(CategoryEncoding, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def call(self, inputs, count_weights=None):\n if isinstance(inputs, (list, np.ndarray)):\n inputs = ops.convert_to_tensor_v2_with_dispatch(inputs)\n\n def expand_dims(inputs, axis):\n if tf_utils.is_sparse(inputs):\n return sparse_ops.sparse_expand_dims(inputs, axis)\n else:\n return array_ops.expand_dims(inputs, axis)\n\n original_shape = inputs.shape\n # In all cases, we should uprank scalar input to a single sample.\n if inputs.shape.rank == 0:\n inputs = expand_dims(inputs, -1)\n # One hot will unprank only if the final output dimension is not already 1.\n if self.output_mode == ONE_HOT:\n if inputs.shape[-1] != 1:\n inputs = expand_dims(inputs, -1)\n\n # TODO(b/190445202): remove output rank restriction.\n if inputs.shape.rank > 2:\n raise ValueError(\n \"Received input shape {}, which would result in output rank {}. \"\n \"Currently only outputs up to rank 2 are supported.\".format(\n original_shape, inputs.shape.rank))\n\n if count_weights is not None and self.output_mode != COUNT:\n raise ValueError(\n \"`count_weights` is not used when `output_mode` is not `'count'`. \"\n \"Received `count_weights={}`.\".format(count_weights))\n\n out_depth = self.num_tokens\n binary_output = self.output_mode in (MULTI_HOT, ONE_HOT)\n if isinstance(inputs, sparse_tensor.SparseTensor):\n max_value = math_ops.reduce_max(inputs.values)\n min_value = math_ops.reduce_min(inputs.values)\n else:\n max_value = math_ops.reduce_max(inputs)\n min_value = math_ops.reduce_min(inputs)\n condition = math_ops.logical_and(\n math_ops.greater(\n math_ops.cast(out_depth, max_value.dtype), max_value),\n math_ops.greater_equal(\n min_value, math_ops.cast(0, min_value.dtype)))\n assertion = control_flow_ops.Assert(condition, [\n \"Input values must be in the range 0 <= values < num_tokens\"\n \" with num_tokens={}\".format(out_depth)\n ])\n with ops.control_dependencies([assertion]):\n if self.sparse:\n return sparse_bincount(inputs, out_depth, binary_output,\n count_weights)\n else:\n return dense_bincount(inputs, out_depth, binary_output,\n count_weights)\n\n\ndef sparse_bincount(inputs, out_depth, binary_output, count_weights=None):\n \"\"\"Apply binary or count encoding to an input and return a sparse tensor.\"\"\"\n result = bincount_ops.sparse_bincount(\n inputs,\n weights=count_weights,\n minlength=out_depth,\n maxlength=out_depth,\n axis=-1,\n binary_output=binary_output)\n if inputs.shape.rank == 1:\n output_shape = (out_depth,)\n else:\n result = math_ops.cast(result, backend.floatx())\n batch_size = array_ops.shape(result)[0]\n output_shape = (batch_size, out_depth)\n result = sparse_tensor.SparseTensor(\n indices=result.indices,\n values=result.values,\n dense_shape=output_shape)\n return result\n\n\ndef dense_bincount(inputs, out_depth, binary_output, count_weights=None):\n \"\"\"Apply binary or count encoding to an input.\"\"\"\n result = bincount_ops.bincount(\n inputs,\n weights=count_weights,\n minlength=out_depth,\n maxlength=out_depth,\n dtype=backend.floatx(),\n axis=-1,\n binary_output=binary_output)\n if inputs.shape.rank == 1:\n result.set_shape(tensor_shape.TensorShape((out_depth,)))\n else:\n batch_size = inputs.shape.as_list()[0]\n result.set_shape(tensor_shape.TensorShape((batch_size, out_depth)))\n return result\n","repo_name":"graphcore/tensorflow","sub_path":"tensorflow/python/keras/layers/preprocessing/category_encoding.py","file_name":"category_encoding.py","file_ext":"py","file_size_in_byte":10296,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"3"}
+{"seq_id":"16116525017","text":"from django.shortcuts import render, redirect \nfrom django.http import HttpResponse\nfrom django.forms import inlineformset_factory\nfrom django.contrib.auth.forms import UserCreationForm\n\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth import logout as d_logout\n\nfrom django.contrib import messages\n\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.template.loader import render_to_string\n\n# Create your views here.\nfrom .models import *\nfrom .forms import OrderForm, CreateUserForm\nfrom .filters import OrderFilter\n\ndef registerPage(request):\n\tif request.user.is_authenticated:\n\t\treturn redirect('home')\n\telse:\n\t\tform = CreateUserForm()\n\t\tif request.method == 'POST':\n\t\t\tform = CreateUserForm(request.POST)\n\t\t\tif form.is_valid():\n\t\t\t\tform.save()\n\t\t\t\tuser = form.cleaned_data.get('username')\n\t\t\t\tmessages.success(request, 'Account was created for ' + user)\n\n\t\t\t\treturn redirect('login')\n\t\t\t\n\n\t\tcontext = {'form':form}\n\t\treturn render(request, 'accounts/register.html', context)\n\ndef loginPage(request):\n\tif request.user.is_authenticated:\n\t\treturn redirect('home')\n\telse:\n\t\tif request.method == 'POST':\n\t\t\tusername = request.POST.get('username')\n\t\t\tpassword =request.POST.get('password')\n\n\t\t\tuser = authenticate(request, username=username, password=password)\n\n\t\t\tif user is not None:\n\t\t\t\tlogin(request, user)\n\t\t\t\treturn redirect('home')\n\t\t\telse:\n\t\t\t\tmessages.info(request, 'Username OR password is incorrect')\n\n\t\tcontext = {}\n\t\treturn render(request, 'accounts/login.html', context)\n\n\n@login_required(login_url='login')\ndef home(request):\n\torders = Order.objects.all()\n\tcustomers = Customer.objects.all()\n\n\ttotal_customers = customers.count()\n\n\ttotal_orders = orders.count()\n\tdelivered = orders.filter(status='Delivered').count()\n\tpending = orders.filter(status='Pending').count()\n\n\tcontext = {'orders':orders, 'customers':customers,\n\t'total_orders':total_orders,'delivered':delivered,\n\t'pending':pending }\n\n\treturn render(request, 'accounts/dashboard.html', context)\n\n@login_required(login_url='login')\ndef todo(request):\n\treturn render(request, 'accounts/todo.html')\n\n@login_required(login_url='login')\ndef pomodoro(request):\n\treturn render(request, 'accounts/pomodoro.html')\n\n@login_required(login_url='login')\ndef logout(request):\n\td_logout(request)\n\tmessages.info(request, \"Logged out successfully!\")\n\treturn redirect(\"home\")\n\n #return redirect(\"main:home\")\n\n\n\n\n","repo_name":"dikshyant3/Task-management-web-app","sub_path":"backend/notes app backend/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33692654230","text":"#-*- coding: UTF-8 -*-\nimport jieba.posseg as pseg\nimport jieba\nimport sys, multiprocessing, os\nimport charagram_util as cutil\n\ng_punctations = set(['!',',','.','(',')','...','?','!',',','。','。。。','(',')','=','+','_','?'])\ndef remove_punctation_sent(line):\n word_pos_list = pseg.cut(line)\n ret = ''\n pre = ''\n for word, pos in word_pos_list:\n if pos == 'x':# or pos == 'm':# x: puntation, m: liangci\n if pre != ' ':\n ret += ' punction '\n pre = ' '\n elif pos == 'm':\n if pre != ' ':\n ret += ' measure '\n pre = ' '\n else:\n ret += word.encode('utf8')\n pre = 'h'\n return ret\n \ndef remove_punctation_file(infile, outfile):\n fout = open(outfile,'w')\n for line in open(infile,'r'):\n if len(line.strip().split('\\t')) != 3:\n continue\n gid, title, content = line.strip().split('\\t')\n fout.write(gid+'\\t'+remove_punctation_sent(title)+'\\t'+remove_punctation_sent(content)+'\\n')\n fout.close()\n\ndef content_clear(line):\n clear_set = set(['网讯'])\n for word in clear_set:\n idx = line.find(word)\n if idx != -1 and idx < 21:\n line = line[idx+len(word):]\n lidx = line.find('(')\n ridx = line.find(')',lidx)\n clear_set2 = set(['记者','通讯'])\n for word in clear_set2:\n idx = line.find(word)\n if idx > lidx and idx < ridx:\n line = line[:lidx] + ' ' + line[ridx+1:]\n return line \n\ndef word_segment(line, out_dict, mode=2, clear=False):\n line = remove_punctation_sent(line)\n if clear:\n line = content_clear(line)\n if mode == 1:\n words = jieba.cut(line, cut_all=True)\n elif mode == 2:\n words = jieba.cut(line, cut_all=False)\n else:\n words = jieba.cut_for_search(line)\n words = [word.encode('utf8') for word in words if word.encode('utf8') != ' ']\n for word in words:\n out_dict.setdefault(word,0)\n out_dict[word] += 1\n return ' '.join(words)\n\ndef word_segment_file(infile, outfile, out_dict_file, mode=2):# mode = 3 search engine\n fout = open(outfile,'w')\n out_dict = {}\n for line in open(infile,'r'):\n if len(line.strip().split('\\t')) != 3:\n continue\n gid, title, content = line.strip().split('\\t')\n fout.write(gid+'\\t'+word_segment(title, out_dict)+'\\t'+word_segment(content, out_dict)+'\\n')\n fout.close()\n fdict = open(out_dict_file, 'w')\n for word in out_dict:\n fdict.write(word+'\\t'+str(out_dict[word])+'\\n')\n fdict.close()\n\ndef word_filt(word):\n filt_set = set(['小姐','女士','先生'])\n for filt_word in filt_set:\n if word.endswith(filt_word) and len(word) == 3*len(filt_word)/2:\n return False\n return True\n\ndef multiProcessEngine(infile, outfile, out_dict_file, processNum):\n in_dir_tmp = 'in_dir_tmp'\n out_dir_tmp = 'out_dir_tmp'\n out_dict_dir_tmp = 'out_dict_dir_tmp'\n cutil.createDir(in_dir_tmp)\n cutil.createDir(out_dir_tmp)\n cutil.createDir(out_dict_dir_tmp)\n total_line = cutil.getFileLineNum(infile)\n fouts = [open(in_dir_tmp+'/'+infile+'_'+str(i),'w') for i in range(processNum)]\n count = 0\n for line in open(infile,'r'):\n fouts[count%processNum].write(line)\n count += 1\n for fout in fouts:\n fout.close()\n ps = []\n for i in range(processNum):\n file_name = infile+'_'+str(i)\n p = multiprocessing.Process(target=word_segment_file, args=(in_dir_tmp+'/'+file_name, out_dir_tmp+'/'+file_name, \\\n out_dict_dir_tmp+'/'+file_name, ))\n ps.append(p)\n for p in ps:\n p.start()\n for p in ps:\n p.join()\n fout_result = open(outfile,'w')\n for i in range(processNum):\n for line in open(out_dir_tmp+'/'+infile+'_'+str(i),'r'):\n fout_result.write(line)\n fout_result.close()\n dict_all = {}\n for i in range(processNum):\n for line in open(out_dict_dir_tmp+'/'+infile+'_'+str(i),'r'):\n word, cnt = line.strip().split('\\t')\n dict_all.setdefault(word,0)\n dict_all[word] += int(cnt)\n fout_dict = open(out_dict_file,'w')\n word_id = 1\n dict_sorted = sorted(dict_all.items(), key=lambda x:x[1], reverse=True)\n for item in dict_sorted:\n fout_dict.write(item[0] + '\\t' + str(word_id) + '\\t' + str(item[1]) + '\\n')\n word_id += 1\n fout_dict.close()\n \n#remove_punctation_file(sys.argv[1],sys.argv[2])\n#word_segment_file(sys.argv[1], sys.argv[2], sys.argv[3])\nmultiProcessEngine(sys.argv[1], sys.argv[2], sys.argv[3], 20)\n","repo_name":"BetaLearner/textfairy","sub_path":"ngram/data_engine.py","file_name":"data_engine.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39500149033","text":"import pytorch_lightning as pl\nimport torch\nimport torch.nn as nn\n\n\nclass ResNetBase(pl.LightningModule):\n\n FEATURE_LENGTH: int = 2048\n\n def __init__(self, dropout: float = 0.5, resnet_type=\"resnet50\") -> None:\n super().__init__()\n\n resnet = torch.hub.load(\"pytorch/vision:v0.9.0\", resnet_type, pretrained=False)\n self.features = nn.Sequential(*(list(resnet.children())[:-1]))\n self.fully_connected = nn.Sequential(nn.Dropout(p=dropout), nn.Flatten())\n\n def forward(self, x):\n x = self.features(x)\n return self.fully_connected(x)\n","repo_name":"Bodomit/JLU","sub_path":"jlu/models/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22703232035","text":"import sys\n\nif len(sys.argv) != 2:\n print(\"usage: \", sys.argv[0], \" file \")\n exit(1)\n\nnames = [\"DE_int\", \"DE_tildePauli\", \"DEexc\", \"DEpauli\", \\\n \"DEpauli\", \"DEelect\", \"DEorb\"]\nenergies = {}\nfor name in names:\n energies[name] = 0.0\n\n\nfp = open(sys.argv[1])\n\nfor line in fp:\n\n for name in names:\n if line.find(name) >= 0:\n energies[name] = float(line.split()[-1])\n \n j = 1\n for i in range(1, 13, 2):\n if line.find(\"nocv_%d pair eigenvalue\"%(i)) >= 0:\n energies[\"nocv_%d\"%(j)] = 2.0 * float(line.split()[-1])\n j += 1\n \n\nprint(\"\\\\begin{table}[]\")\nprint(\"\\\\begin{tabular}{ll}\")\nprint(\"\\\\hline\")\nfor name in energies:\n print(name.replace(\"_\", \"\") + \" & %12.4f\"%( energies[name]) + \"\\\\\\\\ \\\\hline\")\nprint(\"\\\\end{tabular}\")\nprint(\"\\\\end{table}\")\n#print(\"\\\\end{document}\")\n\n\n","repo_name":"BERTHA-4c-DKS/pybertha","sub_path":"pynocveda/data/SHE/extractintE.py","file_name":"extractintE.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"3013389754","text":"\"\"\"\n Psudo Code to find Solution\n\"\"\"\ndef findSolution(n, bribes, groom):\n\n ans = 0 ### Answer\n count_m = groom.count('m') ### Count for each 'm' in GROOMS Array\n count_r = groom.count('r') ### Count for each 'r' in BRIBES array\n\n array = [value for value in bribes] ### Making a list of brides\n\n ### Iterating over each element of Bribe and check for relevant condition\n for x in bribes:\n\n \"\"\" \n If the value is 'r' then:\n 1. Check if r is count of 'r' is zero, if yes, then ans is length of array\n 2. Or if no, decrease the value of count of r and pop the first element from array. \n \"\"\"\n if x == 'r':\n if count_r == 0: ### IF there are no 'r' in the queue\n ans = len(array)\n break\n count_r -= 1\n array.pop(0)\n \n \n elif x == 'm':\n if count_m == 0: ### If there are no 'm' in the queue\n ans = len(array)\n break\n count_m -= 1\n array.pop(0)\n\n \"\"\" \n Return answer\n \"\"\"\n return ans\n\n\n### Main function()\n#### Driver Code\ndef main():\n n = int(input())\n bribes = input()\n groom = input()\n print(findSolution(n, bribes, groom))\n\n\n\nif __name__ == '__main__':\n main()\n\n\"\"\"\n4\nrmrm\nmmmr\n\n4\nrrmm\nmrmr\n\"\"\"\n\n### 0\n### 2","repo_name":"itsvivekghosh/CodeVita2020-Round2","sub_path":"Problem A - Swayambar.py","file_name":"Problem A - Swayambar.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31346635289","text":"import os\nimport pathlib\n\nimport ffmpeg\nimport numpy as np\nimport torch as th\nfrom torch.utils.data import Dataset\n\n\nclass VideosDataset(Dataset):\n def list_files(\n self,\n ):\n \"\"\"\n List all files in a directory with the given extensions.\n \"\"\"\n files = [\n str(file)\n for ext in self.extensions\n for file in pathlib.Path(self.directory).rglob(f\"*.{ext}\")\n ]\n return files\n\n def __init__(\n self,\n directory,\n extensions=(\"mp4\", \"MP4\", \"avi\", \"AVI\", \"mov\", \"MOV\"),\n frame_rate=1,\n size=112,\n center_crop=False,\n ):\n self.directory = directory\n self.extensions = extensions\n self.center_crop = center_crop\n self.size = size\n self.frame_rate = frame_rate\n self.video_paths = self.list_files()\n\n def __getitem__(self, index):\n video_path = self.video_paths[index]\n if os.path.isfile(video_path):\n try:\n h, w = self._get_video_dim(video_path)\n except Exception as e:\n print(f\"ffprobe failed at: {video_path}\")\n return th.zeros(1), video_path\n height, width = self._get_output_dim(h, w)\n cmd = (\n ffmpeg.input(video_path)\n .filter(\"fps\", fps=self.frame_rate)\n .filter(\"scale\", width, height)\n )\n if self.center_crop:\n x = int((width - self.size) / 2.0)\n y = int((height - self.size) / 2.0)\n cmd = cmd.crop(x, y, self.size, self.size)\n out, _ = cmd.output(\"pipe:\", format=\"rawvideo\", pix_fmt=\"rgb24\").run(\n capture_stdout=True, quiet=True\n )\n if self.center_crop and isinstance(self.size, int):\n height, width = self.size, self.size\n video = np.frombuffer(out, np.uint8).reshape([-1, height, width, 3])\n video = th.from_numpy(video.astype(\"float32\"))\n video = video.permute(0, 3, 1, 2)\n else:\n video = th.zeros(1)\n\n return video, video_path\n\n def __len__(self):\n return len(self.video_paths)\n\n def _get_video_dim(self, video_path):\n probe = ffmpeg.probe(video_path)\n video_stream = next(\n (stream for stream in probe[\"streams\"] if stream[\"codec_type\"] == \"video\"),\n None,\n )\n width = int(video_stream[\"width\"])\n height = int(video_stream[\"height\"])\n return height, width\n\n def _get_output_dim(self, h, w):\n if isinstance(self.size, tuple) and len(self.size) == 2:\n return self.size\n elif h >= w:\n return int(h * self.size / w), self.size\n else:\n return self.size, int(w * self.size / h)\n","repo_name":"iamirmasoud/video_deduplicator","sub_path":"videos_dataset.py","file_name":"videos_dataset.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"3531007622","text":"import textbase\nfrom textbase.message import Message\nfrom textbase import models\nimport json\nimport os\nfrom typing import List, Tuple, Union, Dict\nimport requests\nfrom textbase.trail import Trail\n\nmodels.OpenAI.api_key = os.getenv(\"OPENAI_KEY\")\n\n# Prompt for GPT-3.5 Turbo\nSYSTEM_PROMPT = \"\"\"\nYou are an AI bike trail expert. You need to help users plan their bike trail journeys.\nThe user will ask you about the available bike trails in an area.\nIf the user asks anything not related to bike trails, you must tell the user to ask anything relavant to bike trails.\nIf you do not know the answer to the user's question, politely say that you don't know and ask the user if he or she would want help in any other bike trail information.\n\nIn the beginning, introduce yourself by telling that you can help find the best bike trails in the world and urge the user to ask anything abpout bike trails.\n\"\"\"\n\n\n\n\n@textbase.chatbot(\"talking-bot\")\ndef on_message(message_history: List[Message], state: dict = None):\n \"\"\"Your chatbot logic here\n message_history: List of user messages\n state: A dictionary to store any stateful information\n\n Return a string with the bot_response or a tuple of (bot_response: str, new_state: dict)\n \"\"\"\n\n if state is None or \"counter\" not in state:\n state = {\"counter\": 0}\n else:\n state[\"counter\"] += 1\n\n # # Generate GPT-3.5 Turbo response\n bot_response = models.OpenAI.generate(\n system_prompt=SYSTEM_PROMPT,\n message_history=message_history,\n model=\"gpt-3.5-turbo\",\n )\n\n return bot_response, state\n","repo_name":"arijitde92/bike_trail_chatbot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10136638967","text":"import requests\nimport pprint\nimport time\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n\ndef draw_graph(graph):\n g = nx.convert.from_dict_of_lists(graph)\n nx.draw(g)\n plt.savefig(\"graph.png\")\n\n\nWIKIPEDIA_API_URL = \"https://en.wikipedia.org/w/api.php\"\n\ndef get_page_links(page_title):\n \"\"\"\n Docs: https://www.mediawiki.org/wiki/API:Links\n \"\"\"\n MAX_LINKS_RETURNED = 2\n ARTICLE_NAMESPACE = \"0\" # https://en.wikipedia.org/wiki/Wikipedia:Namespace\n\n formatted_page_title = page_title.replace(\" \", \"_\")\n\n params = {\n \"action\": \"query\",\n \"titles\": formatted_page_title,\n \"format\": \"json\",\n \"prop\": \"links\",\n \"plnamespace\": ARTICLE_NAMESPACE,\n \"pllimit\": MAX_LINKS_RETURNED\n }\n r = requests.get(url=WIKIPEDIA_API_URL, params=params)\n page_data = r.json()\n\n page_id_key = list(page_data[\"query\"][\"pages\"].keys())\n page_id = page_id_key[0]\n\n if int(page_id) != -1:\n page_links_list = page_data[\"query\"][\"pages\"][page_id][\"links\"]\n filtered_pages = [page_link[\"title\"] for page_link in page_links_list]\n return filtered_pages\n else:\n return []\n\ndef recursive_consume_list(page_titles, graph, pages_set, count=0):\n for title in page_titles:\n count+=1\n new_page_titles = get_page_links(title)\n graph[title] = new_page_titles\n pages_set.update(new_page_titles)\n\n if count < 6:\n recursive_consume_list(new_page_titles, graph, pages_set, count)\n\nif __name__ == \"__main__\":\n kevin_bacon_page_links = get_page_links(\"Kevin Bacon\")\n graph = {\n \"Kevin Bacon\": kevin_bacon_page_links\n }\n pages_set = set()\n\n recursive_consume_list(kevin_bacon_page_links, graph, pages_set)\n\n graph_existing_keys = set(graph.keys())\n keys_not_present_in_graph = pages_set.difference(graph)\n nodes_without_connection = dict.fromkeys(keys_not_present_in_graph, [])\n graph.update(nodes_without_connection)\n\n print(f'graph: {graph}\\n')\n pretty_print = pprint.PrettyPrinter()\n pretty_print.pprint(graph)\n\n draw_graph(graph)","repo_name":"projeto-de-algoritmos/Grafos1_Find_Bacon","sub_path":"wikipedia.py","file_name":"wikipedia.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"11826354395","text":"from dueno import Dueno\nclass menuDueno:\n \"\"\"docstring menuDueno.\"\"\"\n def __init__(self, conexion, cursor ):\n self.dueno = Dueno(conexion, cursor)\n while True:\n print(\"1) Agregar Dueño\")\n print(\"2) Mostrar Dueños\")\n print(\"0) Salir\")\n op = input()\n if op == \"1\":\n self.agregarDueno()\n elif op == \"2\":\n self.mostarDueno()\n elif op == \"0\":\n break\n def agregarDueno(self):\n nombre = input(\"Dame tu nombre: \")\n apellido = input(\"Dame tu apellido\")\n self.dueno.crear(nombre,apellido)\n def mostarDueno(self):\n resultados = self.dueno.recuperar()\n #print (resultados)\n for r in resultados:\n print(\"{0:3} {1:10} {2:15}\".format(r[0],r[1],r[2]))\n","repo_name":"jorgeTira/invernadero_18","sub_path":"menuDueno.py","file_name":"menuDueno.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71506238482","text":"\"\"\"A custom rule that threats all its dependencies as direct dependencies.\"\"\"\n\n# buildifier: disable=bzl-visibility\nload(\"//rust/private:providers.bzl\", \"BuildInfo\", \"CrateInfo\", \"DepInfo\", \"DepVariantInfo\")\n\n# buildifier: disable=bzl-visibility\nload(\"//rust/private:rustc.bzl\", \"rustc_compile_action\")\n\ndef _generator_impl(ctx):\n rs_file = ctx.actions.declare_file(ctx.label.name + \"_generated.rs\")\n ctx.actions.run_shell(\n outputs = [rs_file],\n command = \"\"\"cat < {}\nuse direct::direct_fn;\nuse transitive::transitive_fn;\n\npub fn call_both() {}\n direct_fn();\n transitive_fn();\n{}\nEOF\n\"\"\".format(rs_file.path, \"{\", \"}\"),\n mnemonic = \"WriteRsFile\",\n )\n\n toolchain = ctx.toolchains[Label(\"//rust:toolchain_type\")]\n\n # Determine unique hash for this rlib\n output_hash = repr(hash(rs_file.path))\n crate_name = ctx.label.name\n crate_type = \"rlib\"\n\n rust_lib_name = \"{prefix}{name}-{lib_hash}{extension}\".format(\n prefix = \"lib\",\n name = crate_name,\n lib_hash = output_hash,\n extension = \".rlib\",\n )\n\n deps = [DepVariantInfo(\n crate_info = dep[CrateInfo] if CrateInfo in dep else None,\n dep_info = dep[DepInfo] if DepInfo in dep else None,\n build_info = dep[BuildInfo] if BuildInfo in dep else None,\n cc_info = dep[CcInfo] if CcInfo in dep else None,\n ) for dep in ctx.attr.deps]\n\n rust_lib = ctx.actions.declare_file(rust_lib_name)\n return rustc_compile_action(\n ctx = ctx,\n attr = ctx.attr,\n toolchain = toolchain,\n crate_info_dict = dict(\n name = crate_name,\n type = crate_type,\n root = rs_file,\n srcs = depset([rs_file]),\n deps = depset(deps),\n proc_macro_deps = depset([]),\n aliases = {},\n output = rust_lib,\n owner = ctx.label,\n edition = \"2018\",\n compile_data = depset([]),\n compile_data_targets = depset([]),\n rustc_env = {},\n is_test = False,\n ),\n output_hash = output_hash,\n force_all_deps_direct = True,\n )\n\ngenerator = rule(\n implementation = _generator_impl,\n attrs = {\n \"deps\": attr.label_list(),\n \"_cc_toolchain\": attr.label(\n default = Label(\"@bazel_tools//tools/cpp:current_cc_toolchain\"),\n ),\n \"_error_format\": attr.label(\n default = Label(\"//:error_format\"),\n ),\n \"_process_wrapper\": attr.label(\n default = Label(\"//util/process_wrapper\"),\n executable = True,\n allow_single_file = True,\n cfg = \"exec\",\n ),\n },\n toolchains = [\n \"@rules_rust//rust:toolchain_type\",\n \"@bazel_tools//tools/cpp:toolchain_type\",\n ],\n incompatible_use_toolchain_transition = True,\n fragments = [\"cpp\"],\n)\n","repo_name":"bazelbuild/rules_rust","sub_path":"test/unit/force_all_deps_direct/generator.bzl","file_name":"generator.bzl","file_ext":"bzl","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":568,"dataset":"github-code","pt":"3"}
+{"seq_id":"35836890731","text":"class FenTree (object):\n def __init__ (self, array):\n self.array, self.tree = [0] * len (array), [0] * (len (array) + 1)\n for i in range (len (array)):\n self.update (i, array [i])\n\n def get_parent (self, child):\n return (child - (child & -child))\n\n def get_next (self, index):\n return (index + (index & -index))\n\n def update (self, index, item):\n current, self.array [index] = self.array [index], item\n item -= current\n index += 1\n while (index <= len (self.array)):\n self.tree [index] += item\n index = self.get_next (index)\n\n def prefix_sum (self, index):\n index += 1\n total = 0\n while (index > 0):\n total += self.tree [index]\n index = self.get_parent (index)\n return (total)\n\n def range_sum (self, x, y):\n return (self.prefix_sum (max (x, y)) - self.prefix_sum (min (x, y) - 1))\n\n def describe (self):\n print ('ARRAY =>\\t', self.array)\n print ('Binary Indexed Tree =>\\t', self.tree)\n\nif (__name__ == '__main__'):\n arr = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3]\n ft = FenTree(arr)\n # ft = FenFt ([3,2,-1,6,5,4])\n# ft = FenFt ([int (i) for i in input ('Enter the array (space-separated integers): ').split ()])\n ft.describe ()\n\n # ft.update (4, 8) #replaces 5 with 8 in the list given to the fenwick ft\n ft.update (1, 4) #replaces 5 with 8 in the list given to the fenwick ft\n\n ft.describe ()\n\n # print (ft.range_sum (1, 5)) #returns 2-1+6+5+4\n # print (ft.prefix_sum (5)) #returns 3+2-1+6+5+4\n print('range (2, 5)', ft.range_sum(2, 5))\n","repo_name":"s-surineni/atice","sub_path":"tushar_roy/tree/fentree.py","file_name":"fentree.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29225901165","text":"def es_primo(num):\n for n in range(2, num):\n if num % n == 0:\n return False\n return True\nn = int(input())\ni = 0\nsw = True\nj = 2\na = 1\ncntS = 2\nwhile i < n:\n if es_primo(j):\n if sw:\n print(a,'/',j,sep='')\n sw = False\n else:\n print(j,'/',a,sep='')\n sw = True\n a = a + cntS\n cntS = cntS +1\n i= i+1\n j = j + 1\n\n\n","repo_name":"Paupau18me/EjerciciosPatitoPython2021","sub_path":"Sesion intrductoria/serie4.py","file_name":"serie4.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14567757606","text":"from typing import List, Tuple, Union\nfrom heapq import heappop, heappush, heapify, heappushpop, heapreplace\nfrom collections import defaultdict, deque, Counter\nfrom itertools import accumulate, permutations, combinations, product, compress\nfrom math import perm, comb, gcd, lcm\nfrom functools import cache, lru_cache, reduce\nfrom sortedcontainers import SortedList, SortedSet, SortedDict\nfrom bisect import bisect_left, bisect_right\n\n\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n buc = defaultdict(int)\n res = 1\n index = 0\n n = len(fruits)\n max_window = 0\n # 初始化最大窗口\n while index < n:\n f = fruits[index]\n if f not in buc and len(buc.keys()) == 2:\n break\n buc[fruits[index]] += 1\n max_window += 1\n index += 1\n\n for i in range(n):\n if i + max_window >= n:\n break\n rear = i\n front = i + max_window\n buc[fruits[rear]] -= 1\n buc[fruits[front]] += 1\n if buc[fruits[rear]] == 0:\n del buc[fruits[rear]]\n j = front + 1\n while j < n and len(buc.keys()) <= 2:\n f = fruits[j]\n if f not in buc and len(buc.keys()) == 2:\n break\n buc[f] += 1\n max_window += 1\n j += 1\n return max_window\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.totalFruit([5, 0, 0, 7, 0, 7, 2, 7]))\n print(s.totalFruit(fruits=[1, 2, 1]))\n print(s.totalFruit(fruits=[0, 1, 2, 2]))\n print(s.totalFruit(fruits=[1, 2, 3, 2, 2]))\n print(s.totalFruit(fruits=[3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4]))\n","repo_name":"ccctw-ma/leetcode","sub_path":"src/Medium/SlidingWindow/totalFruit.py","file_name":"totalFruit.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26607156481","text":"from collections import deque\n\nimport numpy as np\nimport rclpy\nimport torch\nimport whisper\nfrom rclpy.node import Node\nfrom rclpy.qos import qos_profile_system_default\nfrom std_msgs.msg import Int16MultiArray, String\n\n\nclass WhisperInferenceNode(Node):\n def __init__(self, node_name: str) -> None:\n super().__init__(node_name)\n self.declare_parameter(\"model\", \"base\")\n self.declare_parameter(\"language\", \"english\")\n model = self.get_parameter(\"model\").value\n language = self.get_parameter(\"language\").value\n\n self.whisper_model_ = whisper.load_model(model)\n self.whisper_options_ = whisper.DecodingOptions(language=language)\n\n self.declare_parameters(\n namespace=\"\",\n parameters=[(\"audio_activation_threshold\", 0.3), (\"inference_period\", 1.0)],\n )\n self.audio_activation_threshold_ = (\n self.get_parameter(\"audio_activation_threshold\")\n .get_parameter_value()\n .double_value\n )\n self.inference_period_ = (\n self.get_parameter(\"inference_period\").get_parameter_value().double_value\n )\n\n self.audio_subscriber_ = self.create_subscription(\n Int16MultiArray,\n \"/audio_listener_node/audio\",\n self.audio_subscriber_callback_,\n qos_profile_system_default,\n )\n self.audio_buffer_ = deque(\n maxlen=int(16000.0 / 1024 * self.inference_period_)\n ) # buffer length to record self.inference_period_ seconds\n\n self.whisper_timer_ = self.create_timer(\n 1.0 / self.inference_period_, self.whisper_timer_callback_\n )\n\n self.text_publisher_ = self.create_publisher(\n String, \"~/text\", qos_profile_system_default\n )\n\n self.device_ = \"cpu\"\n if torch.cuda.is_available():\n self.get_logger().info(\"CUDA is available. Using GPU.\")\n self.device_ = \"cuda\"\n self.whisper_model_ = self.whisper_model_.to(self.device_)\n\n def audio_subscriber_callback_(self, audio_msg: Int16MultiArray) -> None:\n self.audio_buffer_.append(audio_msg.data)\n\n def whisper_timer_callback_(self):\n if len(self.audio_buffer_) == self.audio_buffer_.maxlen:\n audio = (\n np.concatenate(self.audio_buffer_) / 32768.0\n ) # normalization in whisper https://github.com/openai/whisper/blob/0f39c89d9212e4d0c64b915cf7ba3c1f0b59fecc/whisper/audio.py#L49\n audio = torch.from_numpy(audio).float()\n if audio.abs().max() < self.audio_activation_threshold_:\n return\n audio = whisper.pad_or_trim(audio)\n mel = whisper.log_mel_spectrogram(audio).to(self.device_)\n result = whisper.decode(self.whisper_model_, mel, self.whisper_options_)\n\n text_msg = String(data=result.text)\n self.text_publisher_.publish(text_msg)\n\n\ndef main(args=None):\n rclpy.init(args=args)\n whisper_inference_node = WhisperInferenceNode(\"whisper_inference_node\")\n rclpy.spin(whisper_inference_node)\n rclpy.shutdown()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mhubii/ros2_whisper","sub_path":"ros2_whisper/whisper_inference_node.py","file_name":"whisper_inference_node.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"}
+{"seq_id":"1360419727","text":"#!/usr/local/bin/python3\n# coding: utf-8\n\n#--------------------------------------------- Import Necessary Libraries --------------------------------------------#\n\nimport copy\nimport sys\n\n#-------------------------------------------------- Global Variables -------------------------------------------------#\n\n\n\n#---------------------------------------------- Utilities Implementation ---------------------------------------------#\n\ndef build_house(file):\n\thousefp = open(\"maps/\" + file, \"r\")\n\tmyhouse = []\n\tline = housefp.readline()\n\twhile line:\n\t\tmyhouse.append(list(line))\n\t\tline = housefp.readline()\n\treturn myhouse\n\n\ndef print_house(h, sr, sc): # house, row, col\n\tth = copy.deepcopy(h)\n\tth[sr][sc] = \"@\"\n\tprint(\"\\n\")\n\tfor i in th:\n\t\tprint(''.join(str(x) for x in i), end='')\n\tprint(\"\\n\")\n\n\ndef print_keys(keys):\n\tat_least_one_k = False\n\tprint(\"Keys:\", end=' ')\n\tfor k in range(0, len(keys)):\n\t\tif(keys[k] == True):\n\t\t\tprint(str(k) + \", \", end='')\n\t\t\tat_least_one_k = True\n\tif(not at_least_one_k):\n\t\tprint(\"No keys collected...\", end='')\n\n\ndef room(h, sr, sc):\n\tif(h[sr][sc] == '*'): return False\n\telse: return True\n\n\ndef get_treasure(h, sr, sc):\n\tif(h[sr][sc] == 't'): return True\n\telse: return False\n\n\ndef stop():\n\tprint(\"Sorry, you cant go that way.\")\n\n\ndef is_door(h, sr, sc):\n\tif(h[sr][sc] in ['5','6','7','8','9']): return True\n\telse: return False\n\n\ndef is_key(h, sr, sc):\n\tif(h[sr][sc] in ['0','1','2','3','4']): return True\n\telse: return False\n\n\ndef get_key(h, keys, sr, sc):\n\tloc = h[sr][sc]\n\tif(is_key(h, sr, sc)):\n\t\tkeys[int(loc)] = True\n\t\th[sr][sc] = ' '\n\telse: return False\n\n\ndef can_unlock(h, keys, sr, sc):\n\tloc = h[sr][sc]\n\tif(is_door(h, sr, sc) and keys[int(loc)-5]):\n\t\th[sr][sc] = ' '\n\t\treturn True\n\telse:\n\t\treturn False\n\n\ndef open_door():\n\tprint(\"You unlocked the door!\")\n\n#---------------------------------------------------------------------------------------------------------------------#\n","repo_name":"Lexxeous/py_house_treasure","sub_path":"py_house_treasure_utils.py","file_name":"py_house_treasure_utils.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17287605679","text":"\"\"\"\nadding multiple DYNAMIC POPUP markers from data file lec 78\n\"\"\"\n\n\nimport pandas\nimport folium\n\n\ndata = pandas.read_csv(\"Volcanoes.txt\")#reads csvfile in the folder\n\n#conversion of LAT,LON column into list from the data\nlat = list(data[\"LAT\"])\nlon = list(data[\"LON\"])\nelev = list(data[\"ELEV\"])\n\n#map.add_child(folium.Marker(location=[80.01,-100.01],popup=\"This is test marker\", icon=folium.Icon(color='green')))\n\ndef color_producer(elevation):\n if elevation < 1000:\n return 'green'\n elif 1000 <= elevation < 3000:\n return 'orange'\n else:\n return 'red'\n\nmap = folium.Map(location=[44,-120], zoom_start=4) #creates map\n\n#creates map object for marker\nfg = folium.FeatureGroup(name=\"My Map\")\n\n#for loop for multiplecoordinates as list\nfor lt, ln, el in zip(lat, lon, elev):\n fg.add_child(folium.CircleMarker(location=[lt, ln],popup=str(el)+\" m\", radius=10, fill_opacity=0.6, fill_color=color_producer(el), color=color_producer(el)))\n map.add_child(fg)\n #CircleMarker with parameters radius, fill_color, color, fill_opacity\n #popup accepts only string characters\n #changed from icon=folium.Icon(color=color_producer(el))\n\nmap.save(\"maptest6.html\")\n","repo_name":"akshaypatil26/Webmap-Python-Udemy-git","sub_path":"maptest6.py","file_name":"maptest6.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28874831955","text":"import itertools\nimport math\nfrom random import Random\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport os\nfrom mpi4py import MPI\n\nfrom docopt import docopt\nfrom ntu.votes.candidate import *\nfrom ntu.votes.profilepreference import *\nfrom ntu.votes.tiebreaking import *\nfrom ntu.votes.utility import *\nfrom ntu.votes.voter import *\nfrom helper import *\n\n\nclass Measurements:\n \"\"\"Holds the complete set of measures of (50?) alleles: same voters, same candidates, same profile, different\n random scenarios.\"\"\"\n n_voters: int\n n_candidates: int\n percentage_of_convergence: float\n average_time_to_convergence: float\n average_social_welfare: float\n # How many different stable states we have across all iteration sequences of the same preference profile\n stable_states_sets: set\n winning_sets: set\n percentage_truthful_winner_wins: float\n percentage_winner_is_weak_condorcet: float\n percentage_winner_is_strong_condorcet: float\n\n def __init__(self):\n self.stable_states_sets = set()\n self.winning_sets = set()\n\n def __str__(self):\n sss = self.stable_states_sets\n ws = self.winning_sets\n return f\"n_voters = {self.n_voters}\\n\" \\\n f\"n_candidates = {self.n_candidates}\\n\" \\\n f\"percentage_of_convergence = {self.percentage_of_convergence}\\n\" \\\n f\"average_time_to_convergence = {self.average_time_to_convergence}\\n\" \\\n f\"average_social_welfare = {self.average_social_welfare}\\n\" \\\n f\"stable_states_sets: count = {len(sss)}, repr = {[set(s) for s in sss]}\\n\" \\\n f\"winning_sets: count = {len(ws)}, repr = {[set(s) for s in ws]}\\n\" \\\n f\"percentage_truthful_winner_wins = {self.percentage_truthful_winner_wins}%\\n\" \\\n f\"percentage_winner_is_weak_condorcet = {self.percentage_winner_is_weak_condorcet}%\\n\" \\\n f\"percentage_winner_is_strong_condorcet = {self.percentage_winner_is_strong_condorcet}%\"\n\n\ndef aggregate_alleles(alleles: list, all_voters: list, profile: list, utility: Utility,\n tiebreakingrule: TieBreakingRule) -> Measurements:\n measurements = Measurements()\n measurements.n_voters = len(profile) # len(all_voters) is also OK\n measurements.n_candidates = len(profile[0])\n convergence_counter = welfare = truthful_winner_wins_counter = winner_is_weak_condorcet_counter = \\\n winner_is_strong_condorcet_counter = 0.0\n steps_before_convergence = []\n for allele in alleles:\n initial_state: Status = allele[0]\n converged: bool = allele[-1]\n final_status = allele[-2]\n # lastAction: UpdateEvent = allele[-3] # not needed\n final_status_toppers = final_status.toppers\n\n if isinstance(tiebreakingrule, RandomTieBreakingRule):\n initial_winner_s = frozenset(initial_state.toppers)\n final_winner_s = frozenset(final_status_toppers)\n elif isinstance(tiebreakingrule, LexicographicTieBreakingRule):\n initial_winner_s = frozenset([tiebreakingrule.get_winner(initial_state.toppers)])\n final_winner_s = frozenset([tiebreakingrule.get_winner(final_status_toppers)])\n else:\n raise TypeError(\"Tie breaking rule not known\")\n\n measurements.winning_sets.add(final_winner_s)\n\n if initial_winner_s == final_winner_s:\n truthful_winner_wins_counter += 1\n\n if converged:\n convergence_counter += 1\n # initial state, final boolean, 2 entries each step\n steps_before_convergence.append((len(allele) - 1 - 1) / 2)\n # A stable states is simply the state of a converged system.\n measurements.stable_states_sets.add(final_winner_s)\n\n for voter in all_voters:\n welfare += utility.total_utility(voter.profile, final_status_toppers, tiebreakingrule)\n\n # if not is_condorcet _winner(profile, final_status.toppers[0]):\n # others = profile[0].copy()\n # others.remove(final_status.toppers[0])\n # for other in others:\n # if is_condorcet_winner(profile, other):\n # print(\"found\", other, repr(profile))\n\n for winner in final_winner_s:\n if not is_condorcet_winner(profile, winner, week=True):\n break\n else: # else of the (for loop), not of the (if statement)\n winner_is_weak_condorcet_counter += 1\n # test again for strong condorcet winner\n for winner in final_winner_s:\n if not is_condorcet_winner(profile, winner, week=False):\n break\n else:\n winner_is_strong_condorcet_counter += 1\n\n len_steps_before_convergence = len(steps_before_convergence)\n len_alleles = len(alleles)\n measurements.percentage_of_convergence = convergence_counter * 100.0 / len_steps_before_convergence \\\n if len_steps_before_convergence else 100\n measurements.average_time_to_convergence = sum(steps_before_convergence) / len_steps_before_convergence \\\n if len_steps_before_convergence else 0\n measurements.average_social_welfare = welfare / len_alleles # TODO Discuss\n measurements.percentage_truthful_winner_wins = truthful_winner_wins_counter * 100 / len_alleles\n measurements.percentage_winner_is_weak_condorcet = winner_is_weak_condorcet_counter * 100 / len_alleles\n measurements.percentage_winner_is_strong_condorcet = winner_is_strong_condorcet_counter * 100 / len_alleles\n\n return measurements\n\n\ndef is_condorcet_winner(profile: list, query: Candidate, week=True) -> bool:\n result = dict()\n strong_only = not week\n others = profile[0].copy()\n others.remove(query)\n for other in others:\n result.clear()\n result[query] = 0\n result[other] = 0\n for voter_profile in profile:\n for candidate in voter_profile:\n # They are ordered according to preference. Who appears first is the voter's winner\n if candidate == query:\n result[query] = result[query] + 1\n break\n elif candidate == other:\n result[other] = result[other] + 1\n break\n if result[query] < result[other]:\n return False\n elif strong_only and result[query] == result[other]:\n return False\n return True\n\n\ndef main():\n doc = \"\"\"Iterative voting engine\n\nUsage:\n engine.py [options]\n engine.py [options] [--utility borda]\n engine.py [options] [--utility expo [ []]]\n\n\nOptions:\n -c, --cmin=CMIN Min number of candidates [Default: 5]\n -C, --cmax=CMAX Max number of candidates [Default: 7]\n -v, --vmin=VMIN Min number of Voters [Default: cmin]\n -V, --vmax=VMAX Max number of Voters [Default: 12]\n -l, --log=LFILE Log file (if ommitted or -, output to stdout) [Default: -]\n -o, --out-folder=OFOLDER Output folder where all scenarios are written [Default: ./out]\n -r, --random-search Don't perform exhaustive search of profiles [Default: Yes]\n -u, --utility=UTILITY User Utility function (borda | expo) [Default: borda]\n -p, --preference=PREFERENCE How a voter forms his ballot order \n (single-peaked | general) [Default: single-peaked]\n --conv-threshold=THRESHOLD Threshold of similarity of different profiles \n sampling before considering the curve converged [Default: 0.05]\n -t, --tiebreakingrule=TIEBREAKINGRULE How to behave in cases of draws \n (lexicographic | random) [Default: lexicographic]\n -i, --initial-run-size=SIZE Initial number of runs before testing for \n convergence [Default: 100]\n --voters=VOTERS Type of voters (general | truthful | lazy) [Default: general]\n -s, --seed=SEED Randomization seed [Default: 12345]\n --show Show results\n -h, --help Print the help screen\n --version Prints the version and exits\n BASE The base [default: 2]\n EXPO_STEP The exponent increment [Default: 1]\n\n\n\"\"\"\n\n args = docopt(doc, version='0.1.0')\n # print(args)\n seed = int(args['--seed'])\n all_simulations_per_all_seeds = dict()\n log = None\n\n comm = MPI.COMM_WORLD\n if comm.Get_rank() == 0:\n log_arg = args['--log']\n if log_arg == '-':\n log = sys.stdout\n else:\n if not os.path.exists(log_arg):\n dirname = os.path.dirname(log_arg)\n if dirname != '': # If just a file name without a folder\n os.makedirs(dirname, exist_ok=True)\n log = open(log_arg, 'w')\n\n exhaustive = not bool(args['--random-search'])\n # print('exhaustive =', exhaustive)\n if exhaustive and 'general' == (args.get('--preference', None)):\n raise TypeError('Exhaustive search can be performed only with single-peaked preference (till now).')\n\n all_previously_run = dict() # To hold all runs from all seeds simulated on all threads\n seeds__rank = comm.Get_rank()\n seeds__num_processors = comm.Get_size()\n seeds__all_previously_run_count = 0\n seeds__run_base = seed\n seeds__run_size = int(args['--initial-run-size'])\n\n target_measurements = [\n ('percentage_winner_is_weak_condorcet', False), ('percentage_winner_is_strong_condorcet', False),\n ('percentage_truthful_winner_wins', False), ('percentage_of_convergence', False),\n ('average_time_to_convergence', False), ('average_social_welfare', False),\n ('stable_states_sets', True), ('winning_sets', True)\n ]\n\n more_work = True\n\n while more_work:\n seeds__chunk_size = int(math.ceil(seeds__run_size / seeds__num_processors))\n seeds__chunk_base = seeds__run_base + (seeds__rank * seeds__chunk_size) # inclusive\n seeds__chunk_end = min((seeds__chunk_base + seeds__chunk_size), (seeds__run_base + seeds__run_size)) # excl\n # print(seeds__run_size, seeds__rank, seeds__run_base, seeds__run_size, seeds__chunk_size, seeds__chunk_base)\n if seeds__rank == 0:\n msg = f'going to start a run of {seeds__run_size} on {seeds__num_processors} batches, ' \\\n f'{seeds__chunk_size} runs each'\n log.write(msg + '\\n')\n log.write(f'Thread {seeds__rank} starts with seed {seeds__chunk_base} (in) to {seeds__chunk_end} (ex)\\n')\n log.flush()\n\n for assigned_seed in range(seeds__chunk_base, seeds__chunk_end):\n out_path = os.path.join(args['--out-folder'], f'out-{assigned_seed:05}.log')\n if not os.path.exists(out_path):\n os.makedirs(os.path.dirname(out_path), exist_ok=True)\n out = open(out_path, 'w')\n\n # to be run in a separate MPI process or node\n args[\"assigned_seed\"] = assigned_seed\n args['log'] = log\n args['out'] = out\n all_simulations_per_all_seeds[assigned_seed] = run_all_simulations_per_seed(args)\n out.close()\n # collect the simulations results from several threads\n buffer = comm.gather(all_simulations_per_all_seeds, root=0)\n if seeds__rank == 0:\n # Add all (gather new) values\n for returned_dict in buffer: # [{seed, [measurements, ...]}, ...]\n for key in iter(returned_dict):\n all_previously_run[key] = returned_dict[key]\n\n # sort results\n all_measurements_by_candidates, all_measurements_by_voters = sort_measurements(all_previously_run)\n\n # check for convergence\n more_work = not (\n run_converged(all_measurements_by_candidates, seeds__all_previously_run_count, target_measurements,\n max_sum_abs_diffs=float(args['--conv-threshold']))\n and\n run_converged(all_measurements_by_voters, seeds__all_previously_run_count, target_measurements,\n max_sum_abs_diffs=float(args['--conv-threshold']))\n )\n\n if not more_work:\n # generate graph(s)\n generate_graphs(all_measurements_by_candidates, all_measurements_by_voters, target_measurements,\n args['--out-folder'])\n else:\n more_work = None\n more_work = comm.bcast(more_work, root=0)\n # print(f'Thread {seeds__rank} more work =', more_work, flush=True)\n\n seeds__run_base += seeds__run_size\n seeds__run_size = int(math.ceil((seeds__run_size + seeds__all_previously_run_count) / 2))\n if seeds__rank == 0:\n seeds__all_previously_run_count = len(all_previously_run)\n seeds__all_previously_run_count = comm.bcast(seeds__all_previously_run_count, root=0)\n\n if seeds__rank == 0:\n log.write(\"Done.\\n\")\n log.flush()\n log.close()\n if bool(args['--show']):\n plt.show()\n\n\ndef run_converged(all_measurements_sorted: dict, seeds_all_previously_run_count: int, target_measurements: list,\n max_sum_abs_diffs=0.10\n # , extremities=0.05\n ) -> bool:\n # print('=============================')\n if not seeds_all_previously_run_count:\n return False\n for attr_name, len_attr in target_measurements:\n for level1 in all_measurements_sorted.items():\n for level2 in level1[1].items():\n msrmnt_lst = level2[1]\n old_values = [\n len(operator.attrgetter(attr_name)(msrmnt)) if len_attr else operator.attrgetter(attr_name)(msrmnt)\n for msrmnt in msrmnt_lst[:seeds_all_previously_run_count]\n ]\n current_values = [\n len(operator.attrgetter(attr_name)(msrmnt)) if len_attr else operator.attrgetter(attr_name)(msrmnt)\n for msrmnt in msrmnt_lst\n ]\n # After much consideration, I simply decided to take the wider distribution and apply it\n # to the smaller one (the subset) keeping the same bin boundaries.\n # len_extremity = int(len(current_values) * extremities / 2)\n # old_values_barred = current_values[len_extremity: -1-len_extremity]\n # lbound = current_values[len_extremity]\n # ubound = current_values[-1 - len_extremity]\n\n current_hist, edges = np.histogram(current_values, bins='auto', density=True)\n # print(level1[0], level2[0], attr_name, current_values)\n # print(edges, np.diff(edges), current_hist, flush=True)\n old_hist, edges = np.histogram(old_values, bins=edges, density=True)\n diff_edges = np.diff(edges)\n # print(np.multiply(old_hist, diff_edges))\n # print(np.multiply(current_hist, diff_edges))\n subtract = np.subtract(np.multiply(old_hist, diff_edges), np.multiply(current_hist, diff_edges))\n sum_abs_diffs = np.sum(abs(subtract))\n # print(subtract, np.abs(subtract), sum_abs_diffs)\n if sum_abs_diffs > max_sum_abs_diffs:\n return False\n else:\n print('============> Run Converged <============', flush=True)\n return True\n\n\ndef run_all_simulations_per_seed(args) -> list:\n \"\"\"Run different candidates numbers [5-7]* different voters numbers [cmin -12]* 50 repeat\n\n :param args: all arguments after adjusting THIS suit seed\n :return: list of measures, one for every profile (candidates/voters/preferences)\n \"\"\"\n out = args['out']\n log = args['log']\n assigned_seed = args['assigned_seed']\n utility = {\n 'borda': BordaUtility(),\n 'expo': ExpoUtility(base=args[''] if args[''] else 2,\n exponent_step=args[''] if args[''] else 1),\n }.get(args['--utility'], None)\n cmin = int(args['--cmin'])\n cmax = int(args['--cmax'])\n # vmin = int(args['--vmin'])\n vmin = cmin if 'cmin' == args['--vmin'] else int(args['--vmin'])\n vmax = int(args['--vmax'])\n rand = random.Random(assigned_seed)\n exhaustive = not bool(args['--random-search']) # duplicate code of the outer line\n preference = {\n 'single-peaked': SinglePeakedProfilePreference(),\n 'general': GeneralProfilePreference(rand),\n }.get(args['--preference'], None)\n tie_breaking_rule = {\n 'lexicographic': LexicographicTieBreakingRule(),\n 'random': RandomTieBreakingRule(rand),\n }.get(args['--tiebreakingrule'], None)\n # print(utility, preference, tie_breaking_rule)\n all_profiles_measurements = []\n n_candidates_range = range(cmin, cmax + 1)\n for n_candidates in n_candidates_range:\n # Generate deterministic list of candidates\n terminal_gap = False\n inter_gaps = True\n all_candidates = generate_candidates(n_candidates, exhaustive, rand, terminal_gap, inter_gaps)\n # print(n_candidates, all_candidates, flush=True)\n\n # number of n_candidates <= n_voters <= 12\n n_voters_range = range(max(vmin, n_candidates), vmax + 1)\n for n_voters in n_voters_range:\n if n_voters % 2:\n continue\n\n out.write(f'\\n------------ voters = {n_voters}, Candidates = {n_candidates}-------------------\\n')\n out.flush()\n # log.write(f'\\n------------ voters = {n_voters}, Candidates = {n_candidates}-------------------\\n')\n\n if exhaustive:\n # Generate deterministic list of voters\n # adjust bins acc to terminal and internal gaps\n terminal = 1 if terminal_gap else 0\n delta = 2 if inter_gaps else 1\n last_bin = terminal + (n_candidates * delta)\n if terminal and not inter_gaps:\n last_bin += 1\n deterministic_list_of_voters_choices = permute_identityless(list(range(last_bin)), n_voters, False, list())\n # print('len = ', len(deterministic_list_of_voters_choices), deterministic_list_of_voters_choices, flush=True)\n \n\n # Use it :)\n determinant = deterministic_list_of_voters_choices[assigned_seed % len(deterministic_list_of_voters_choices)] if exhaustive else rand\n\n all_voters = generate_voters(n_voters, args['--voters'], utility, determinant)\n # print(all_voters, flush=True)\n\n # voters build their preferences\n for voter in all_voters:\n voter.build_profile(all_candidates, preference)\n # collective profile\n profile = [voter.getprofile() for voter in all_voters]\n initial_status = Status.from_profile(profile)\n\n # print(n_candidates, n_voters, assigned_seed, all_voters, flush=True)\n # continue # FIXME for development purpose only\n streams = {'log': log, 'out': out}\n measurements = run_simulation_alleles(all_candidates, all_voters, initial_status, profile, rand, streams,\n tie_breaking_rule, utility)\n all_profiles_measurements.append(measurements)\n return all_profiles_measurements\n\n\ndef run_simulation_alleles(all_candidates, all_voters, initial_status, profile, rand, streams, tie_breaking_rule,\n utility):\n alleles = [] # Alleles are scenarios\n for run in range(50):\n scenario = run_simulation(all_candidates, all_voters, initial_status, tie_breaking_rule, rand,\n **streams)\n alleles.append(scenario)\n measurements = aggregate_alleles(alleles, all_voters, profile, utility, tie_breaking_rule)\n # log.write(\"-------measurements\\n\")\n # log.write(str(measurements)+'\\n')\n # log.write(\"-------\\n\")\n return measurements\n\n\ndef run_simulation(all_candidates: list, all_voters: list, current_status: Status, tie_breaking_rule: TieBreakingRule,\n rand: Random, **streams) -> list:\n \"\"\"\n\n :param tie_breaking_rule:\n :param current_status:\n :param all_voters:\n :param all_candidates:\n :param rand:\n :type rand: Random\n \"\"\"\n # log = streams['log']\n out = streams['out']\n scenario = []\n # only increase\n abstaining_voters_indices = []\n # now for the initial status\n out.write(f'{current_status}\\tInitial state\\n')\n out.flush()\n scenario.append(current_status.copy())\n step = 0\n max_steps = len(all_voters) * len(all_candidates)\n while step < max_steps:\n # recalculated every step, always decrease\n active_voters_indices = list(itertools.filterfalse(lambda i: i in abstaining_voters_indices,\n range(len(all_voters))))\n n_toppers = len(current_status.toppers)\n if n_toppers < 2:\n active_voters_indices = list(\n filter(lambda i: all_voters[i].most_recent_vote != current_status.toppers[0], active_voters_indices))\n else:\n # This condition needs to be double checked for all corner cases\n active_voters_indices = list(\n filter(lambda i: tie_breaking_rule.winning_probability(\n current_status.toppers, all_voters[i].most_recent_vote) < (1 / n_toppers), active_voters_indices))\n\n status_changed = None\n # Select one voter randomly from Current active_voters_indices list\n while active_voters_indices and step < max_steps: # Note that we check number of steps as well\n status_changed = False\n # pick a voter from ACTIVE voters\n index = rand.choice(active_voters_indices)\n voter = all_voters[index]\n # ask him to vote\n response = voter.vote(current_status, tie_breaking_rule)\n scenario.append(response)\n step += 1\n\n out.write(f'{current_status}\\t{index:#2}\\t{response}\\t')\n # evaluate the status\n if response.to is None:\n # couldn't enhance\n active_voters_indices.remove(index)\n if isinstance(voter, LazyVoter):\n abstaining_voters_indices.append(index)\n out.write('\\tAbstain\\n')\n\n if active_voters_indices:\n out.write('\\n')\n else:\n return simulation_converged(current_status, scenario, **streams)\n # elif response.frm == response.to:\n # # voter was satisfied (currently a dead case)\n # out.write('\\n')\n else:\n out.write(\"<-- enhancement\\n\")\n # update ballot counts\n current_status.votes[response.frm] -= 1\n current_status.votes[response.to] += 1\n # then reorder candidates\n current_status.in_order()\n\n scenario.append(current_status.copy())\n status_changed = True\n break\n\n # if there were NO active voters (corner case, everyone is already satisfied with the same single candidate)\n if status_changed is None:\n # print('Corner case', len(all_candidates), len(all_voters), flush=True)\n return simulation_converged(current_status, scenario, write_converged=False, **streams)\n\n # Now we know we entered and exited the inner loop and are sure the active voters list was not exhausted\n if status_changed:\n # we broke from the inner loop because the last step was successful.\n # Go back to the top of outer loop to continue based on the new status\n continue # No actual need for the keyword 'continue' here. It is just a place holder like 'pass'\n else:\n # we gracefully exited the inner loop because max steps was exhausted\n return simulation_not_converged(current_status, scenario, **streams)\n else:\n # we gracefully exited the outer loop because max steps was exhausted\n return simulation_not_converged(current_status, scenario, **streams)\n\n\ndef sort_measurements(all_previously_run: dict):\n temp = all_previously_run.popitem()\n seed, sample_measurements_arr = temp[0], temp[1]\n all_previously_run[seed] = sample_measurements_arr\n n_candidates_range = sorted({msrmnt.n_candidates for msrmnt in sample_measurements_arr})\n n_voters_range = sorted({msrmnt.n_voters for msrmnt in sample_measurements_arr})\n # print(n_candidates_range)\n # print(n_voters_range, flush=True)\n all_measurements_by_candidates = dict()\n all_measurements_by_voters = dict()\n for n_candidates in n_candidates_range:\n all_measurements_by_candidates[n_candidates] = dict()\n for n_voters in n_voters_range:\n if n_voters < n_candidates:\n continue\n msrmnt_arr = [msrmnt\n for sample_measurements_arr in all_previously_run.values()\n for msrmnt in sample_measurements_arr\n if msrmnt.n_candidates == n_candidates and msrmnt.n_voters == n_voters]\n # measurements_summary = MeasurementsSummary.from_iterable(msrmnt_arr, n_candidates, n_voters)\n all_measurements_by_candidates[n_candidates][n_voters] = msrmnt_arr\n all_measurements_by_voters.setdefault(n_voters, dict())[n_candidates] = msrmnt_arr\n return all_measurements_by_candidates, all_measurements_by_voters\n\n\ndef generate_graphs(all_measurements_by_candidates: dict, all_measurements_by_voters: dict, target_measurements: list,\n out_dir: str):\n generate_graphs_one_side(all_measurements_by_candidates, target_measurements, 'Candidates', 'Voters', 'o-', out_dir)\n generate_graphs_one_side(all_measurements_by_voters, target_measurements, 'Voters', 'Candidates', '^-', out_dir)\n\n\ndef generate_graphs_one_side(all_measurements_by_candidates, target_measurements, y_label: str, x_label: str,\n mark: str, out_dir: str = './') -> None:\n for attr_name, len_attr in target_measurements:\n plt.figure()\n\n for level1_dict in all_measurements_by_candidates.items():\n n_level1, level2_dict = level1_dict[0], level1_dict[1]\n lst = []\n for n_level2, measurements_lst in level2_dict.items():\n attr_summary = np.average([\n len(operator.attrgetter(attr_name)(msrmnt)) if len_attr else operator.attrgetter(attr_name)(msrmnt)\n for msrmnt in measurements_lst])\n lst.append((n_level2, attr_summary))\n print(n_level1, lst)\n separate_x_y = list(zip(*lst))\n print(\"separate: \", separate_x_y)\n if separate_x_y:\n plt.plot(separate_x_y[0], separate_x_y[1], mark, label=f'{y_label} = {n_level1}')\n\n title = attr_name.replace('_', ' ')\n if len_attr:\n title = 'len of ' + title\n plt.title(title)\n plt.legend()\n plt.xlabel(x_label)\n\n filename = f'{out_dir}/{attr_name} different {y_label}.png'\n plt.savefig(filename, trnsparent=True)\n # plt.show(block=False)\n\n\ndef simulation_converged(last_status: Status, scenario: list, write_converged=True, **streams) -> list:\n out = streams['out']\n if write_converged:\n out.write(\"Converged\\n\")\n out.write(f'{last_status}\\tFinal state\\n')\n out.flush()\n scenario.append(last_status.copy())\n scenario.append(True)\n return scenario\n\n\ndef simulation_not_converged(last_status: Status, scenario: list, **streams) -> list:\n out = streams['out']\n out.write(f'{last_status} No convergence\\n')\n out.flush()\n scenario.append(last_status.copy())\n scenario.append(False)\n return scenario\n\n\ndef generate_voters(n_voters: int, voter_type: str, utility: Utility, determinant):\n all_voters = []\n exhaustive = isinstance(determinant, list)\n if exhaustive:\n deterministic_list_of_voters_choices: list = determinant\n for i in range(n_voters):\n v: Voter = Voter.make_voter(voter_type, deterministic_list_of_voters_choices[i], utility)\n all_voters.append(v)\n # raise NotImplementedError(\"Not yet implemented\")\n else:\n for i in range(n_voters):\n rand: Random = determinant\n # v: Voter = Voter.make_voter(voter_type, rand.randrange(positions_range), utility)\n v: Voter = Voter.make_voter(voter_type, rand.random(), utility)\n all_voters.append(v)\n return all_voters\n\n\ndef generate_candidates(n_candidates: int, exhaustive: bool, rand: Random, terminal_gap=False, inter_gaps=True):\n all_candidates = []\n if exhaustive:\n offset = 1 if terminal_gap else 0\n delta = 2 if inter_gaps else 1\n for i in range(n_candidates):\n c: Candidate = Candidate(chr(b'A'[0] + i), offset + (i * delta))\n all_candidates.append(c)\n else:\n for i in range(n_candidates):\n # c: Candidate = Candidate(chr(b'A'[0] + i), i+1)\n c: Candidate = Candidate(chr(b'A'[0] + i), rand.random())\n all_candidates.append(c)\n return all_candidates\n\n\n# --------------------------\nif __name__ == '__main__':\n main()\n","repo_name":"aalhossary/IterativeVotes","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":29620,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"11077614247","text":"import random\nfrom datetime import datetime, timedelta\nfrom functools import wraps\nfrom http import HTTPStatus\nfrom json import dumps, loads\nfrom typing import List, Optional\n\nfrom flask import jsonify, request\nfrom flask_jwt_extended import (create_access_token, create_refresh_token,\n get_jwt, get_jwt_identity, jwt_required,\n set_access_cookies, unset_jwt_cookies)\n\nfrom core.cache_conf import cache_client\nfrom models.devices import Devices\nfrom models.history import History\nfrom models.roles import Roles\nfrom models.user_role import UserRole\nfrom models.users import Users\n\n\ndef create_admin_user():\n \"\"\"Создание пользователя в правми admin\"\"\"\n user = Users(\n login=\"admin\",\n password=\"admin\",\n email=\"admin@gmail.com\",\n first_name=\"Admin\",\n last_name=\"Adminov\",\n )\n if not user.get_first_raw({\"login\": user.login}):\n user.hash_password()\n user.save_to_storage()\n\n # добавить все роли для админа\n role = Roles().get_first_raw({\"name\": \"admin\"})\n UserRole(user_id=user.id, role_id=role.id).save_to_storage()\n\n\ndef login_process(\n etalone_user: Users,\n device_name: Optional[str] = None,\n access_token: Optional[str] = None,\n refresh_token: Optional[str] = None,\n):\n if device_name:\n login_device = Devices(name=device_name)\n if not login_device.get_first_raw({\"name\": login_device.name}):\n login_device.save_to_storage()\n else:\n login_device = login_device.get_first_raw({\"name\": login_device.name})\n\n # выбор случайного устройства из списка (сделано для тестирования, чтобы заносить разные записи)\n device_type = random.choice([\"web\", \"mobile\", \"smart\"])\n\n History(\n user_id=etalone_user.id,\n device_id=login_device.id,\n user_device_type=device_type,\n ).save_to_storage()\n\n additional_claims = {\n \"user\": etalone_user.login,\n \"roles\": [role.name for role in etalone_user.role.all()],\n }\n if not access_token:\n access_token = create_access_token(\n identity=etalone_user.login, additional_claims=additional_claims\n )\n if not refresh_token:\n refresh_token = create_refresh_token(\n identity=etalone_user.login, additional_claims=additional_claims\n )\n ret = {\"access_token\": access_token, \"refresh_token\": refresh_token}\n\n response = jsonify(ret)\n access_token = ret[\"access_token\"]\n\n current_date = datetime.now()\n ret[\"datetime_create_token\"] = current_date.strftime(\"%Y-%m-%d %H:%M:%S\")\n ret[\"datetime_end_token\"] = (current_date + timedelta(hours=1)).strftime(\n \"%Y-%m-%d %H:%M:%S\"\n )\n ret[\"roles\"] = [role.name for role in etalone_user.role.all()]\n ret[\"is_superuser\"] = etalone_user.is_superuser\n cache_client.set(etalone_user.login, dumps(ret))\n\n set_access_cookies(response, access_token)\n\n return response, HTTPStatus.OK\n\n\ndef check_roles(roles: List):\n \"\"\"Декоратор проверка прав доступа\"\"\"\n\n def decorate(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n # если был выполнен запрос, то выполняем проверку\n if request:\n user_name = get_jwt_identity()\n user_info = loads(cache_client.get(user_name))\n if user_info.get(\"is_superuser\"):\n return fn(*args, **kwargs)\n for role in user_info[\"roles\"]:\n if role in roles:\n return fn(*args, **kwargs)\n return jsonify({\"msg\": \"access is denied\"})\n\n return wrapper\n\n return decorate\n","repo_name":"mburdonos/flask_auth","sub_path":"flask_app/utils/auth_utils.py","file_name":"auth_utils.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16519304022","text":"import sys\nimport warnings\n\n# Internal module imports\nfrom . import commands\nfrom . import networks\nfrom . import sandbox\nfrom . import network_views\n\n# Internal module convenience imports\nfrom .exceptions import CyError\nfrom .py4cytoscape_utils import *\nfrom .py4cytoscape_logger import cy_log\nfrom .py4cytoscape_sandbox import get_abs_sandbox_path\n\n# ==============================================================================\n# I. Style management functions\n# ------------------------------------------------------------------------------\n\n@cy_log\ndef copy_visual_style(from_style, to_style, base_url=DEFAULT_BASE_URL):\n \"\"\"Create a new visual style by copying a specified style.\n\n Args:\n from_style (str): Name of visual style to copy\n to_style (str): Name of new visual style\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n str: ''\n\n Raises:\n CyError: if style doesn't exist\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> copy_visual_style('Solid', 'SolidCopy')\n ''\n \"\"\"\n current_names = get_visual_style_names(base_url=base_url)\n if from_style not in current_names:\n raise CyError(f'Cannot copy from a non-existent visual style \"{from_style}\"')\n\n # get the current style from Cytoscape\n res = commands.cyrest_get(f'styles/{from_style}', base_url=base_url)\n style_from_to = res\n style_from_to['title'] = to_style\n\n # and send it to Cytoscape as a new style with a new name\n res = commands.cyrest_post('styles', body=style_from_to, base_url=base_url)\n\n # get and update dependencies as well\n res = commands.cyrest_get(f'styles/{from_style}/dependencies', base_url=base_url)\n # TODO: Shouldn't we be throwing exceptions if these return results are bad?\n res = commands.cyrest_put(f'styles/{to_style}/dependencies', body=res, base_url=base_url, require_json=False)\n return res\n\n@cy_log\ndef get_visual_style_JSON(style_name, css=False, base_url=DEFAULT_BASE_URL):\n \"\"\"Get all defaults and mappings for a visual style\n\n Args:\n style_name (str): name of style\n css (bool): True to create a CytoscapeJS CSS style, False to create a generic JSON version\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n dict or list: dict if generic JSON, list if CSS\n\n Raises:\n CyError: if empty style name\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> get_visual_style_JSON('galFiltered Style')\n {'title': 'galFiltered Style', 'defaults': [{'visualProperty': 'COMPOUND_NODE_PADDING', 'value': 10.0}...]}\n >>> get_visual_style_JSON('galFiltered Style', css=True)\n [{'format_version': '1.0', 'generated_by': 'cytoscape-3.9.1', 'target_cytoscapejs_version': '~2.1'...}]\n \"\"\"\n if style_name == None or len(style_name.strip()) == 0:\n raise CyError(f'No style name provided')\n\n if css:\n style_name += '.json' # get CSS-style JSON for CytoscapeJS usage\n else:\n pass # this is the default ... leave style_name alone\n\n res = commands.cyrest_get(f'styles/{style_name}', base_url=base_url)\n return res\n\n\n@cy_log\ndef create_visual_style(style_name, defaults=None, mappings=None, base_url=DEFAULT_BASE_URL):\n \"\"\"Create a style from defaults and predefined mappings.\n\n Requires visual property mappings to be previously created, see ``map_visual_property``.\n\n Args:\n style_name (str): name for style\n defaults (dict or list): for dict, key-value pairs for default mappings. for list, [{'visualProperty': prop-name, 'value': default-val}, ...]\n mappings (list): visual property mappings, see ``map_visual_property``\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n dict: {'title': new style name}\n\n Raises:\n CyError: if mappings or defaults contain invalid values\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> defaults = {'NODE_SHAPE': 'diamond', 'NODE_SIZE': 30, 'EDGE_TRANSPARENCY': 120, 'NODE_LABEL_POSITION': 'W,E,c,0.00,0.00'}\n >>> node_labels = map_visual_property('node label', 'COMMON', 'p')\n >>> node_fills = map_visual_property('node fill color', 'Degree', 'd', ['1', '2'], ['#FF9900', '#66AAAA'])\n >>> arrow_shapes = map_visual_property('Edge Target Arrow Shape', 'interaction', 'd', ['pp', 'pd'], ['Arrow', 'T'])\n >>> edge_width = map_visual_property('edge width', 'EdgeBetweenness', 'p')\n >>> create_visual_style('NewStyle', defaults=defaults, mappings=[node_labels, node_fills, arrow_shapes, edge_width])\n {'title': 'NewStyle'}\n >>> defaults = [{'visualProperty': 'NODE_SHAPE', 'value': 'diamond'}, {'visualProperty': 'NODE_SIZE', 'value': 30}]\n >>> create_visual_style('NewStyle1', defaults=defaults)\n {'title': 'NewStyle1'}\n\n Note:\n To apply the style to a network, first create the network and then call ``set_visual_style``\n\n This function can be used directly with the ``defaults`` and ``mappings`` members returned by ``get_visual_style_JSON``\n\n See Also:\n :meth:`map_visual_property`, :meth:`set_visual_style`, :meth:`get_visual_style_JSON`\n \"\"\"\n if mappings is None: mappings = []\n if defaults is None:\n style_def = []\n elif isinstance(defaults, list):\n style_def = defaults # already in [{'visualProperty':xxx, 'value':yyy}, ... ] format\n else:\n style_def = [{'visualProperty': key, 'value': val} for key, val in defaults.items()]\n style = {'title': style_name, 'defaults': style_def, 'mappings': mappings}\n res = commands.cyrest_post('styles', body=style, base_url=base_url)\n return res\n\n@cy_log\ndef delete_visual_style(style_name, base_url=DEFAULT_BASE_URL):\n \"\"\"Delete the specified visual style from current session.\n\n Args:\n style_name (str): name of style to delete\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n str: ''\n\n Raises:\n CyError: if the style doesn't exist\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> delete_visual_style('NewStyle')\n ''\n \"\"\"\n res = commands.cyrest_delete(f'styles/{style_name}', base_url=base_url, require_json=False)\n return res\n\n@cy_log\ndef delete_all_visual_styles(base_url=DEFAULT_BASE_URL):\n \"\"\"Delete all visual styles from current Cytoscape session.\n\n The 'default' style remains after all other styles are deleted.\n\n Args:\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n str: ''\n\n Raises:\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> delete_all_visual_styles()\n ''\n \"\"\"\n res = commands.cyrest_delete(f'styles', base_url=base_url, require_json=False)\n return res\n\n@cy_log\ndef export_visual_styles(filename=None, type='XML', styles=None, base_url=DEFAULT_BASE_URL, *, overwrite_file=False):\n \"\"\"Save one or more visual styles to file.\n\n Args:\n filename (str): Full path or path relavtive to current working directory, in addition to\n the name of the file. Extension is automatically added based on the ``type`` argument.\n Default is \"styles.xml\"\n type (str): Type of data file to export, e.g., XML, JSON (case sensitive).\n Default is XML. Note: Only XML can be read by ``import_visual_styles()``.\n styles (str) The styles to be exported, listed as a comma-separated string. If no styles are\n specified, only the current one is exported.\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n overwrite_file (bool): False allows Cytoscape show a message box before overwriting the file if the file already\n exists; True allows Cytoscape to overwrite it without asking\n Returns:\n dict: {'file': name of file written}\n\n Raises:\n CyError: if the output file can't be created, or if file exists and user opts to not overwrite it\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> export_visual_styles() # export the current style to styles.xml in the current directory\n {'file': 'C:\\\\Users\\\\CyDeveloper\\\\styles.xml'}\n >>> export_visual_styles('curstyle') # export the current style to curstyle.xml in the current directory\n {'file': 'C:\\\\Users\\\\CyDeveloper\\\\curstyle.xml'}\n >>> export_visual_styles('curstyle', overwrite_file=True) # overwrite any existing curstyle.xml file\n {'file': 'C:\\\\Users\\\\CyDeveloper\\\\curstyle.xml'}\n >>> export_visual_styles('curstyle', type='json') # export the current style in cytoscape.js format\n {'file': 'C:\\\\Users\\\\CyDeveloper\\\\curstyle.json'}\n\n See Also:\n :meth:`import_visual_styles`\n \"\"\"\n cmd_string = 'vizmap export' # minmum command\n if styles is not None: cmd_string += ' styles=\"' + styles + '\"'\n cmd_string += ' options=\"' + type + '\"'\n\n if filename is None: filename = 'styles'\n ext = '.' + type.lower() + '$'\n if re.search(ext, filename.lower()) is None: filename += '.' + type.lower()\n\n file_info = sandbox.sandbox_get_file_info(filename, base_url=base_url)\n if len(file_info['modifiedTime']) and file_info['isFile']:\n if overwrite_file:\n sandbox.sandbox_remove_file(filename, base_url=base_url)\n else:\n narrate('This file already exists. A Cytoscape popup will be generated to confirm overwrite.')\n full_filename = file_info['filePath']\n\n cmd_string += f' OutputFile=\"{full_filename}\"'\n\n res = commands.commands_post(cmd_string, base_url=base_url)\n return res\n\n@cy_log\ndef import_visual_styles(filename=\"styles.xml\", base_url=DEFAULT_BASE_URL):\n \"\"\"Load styles from an XML file and returns the names of the loaded styles.\n\n Note:\n To load a style file from cloud storage, use the file's URL and the ``sandbox_url_to`` function to download\n the file to a sandbox, and then use ``import_visual_styles`` to load it from there.\n\n Args:\n filename (str): Name of the style file to load. Only reads XML files. Default is \"styles.xml\".\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n list: [names of styles loaded]\n\n Raises:\n CyError: if the input file can't be read\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> import_visual_styles() # export styles.xml in the current directory\n ['galFiltered Style']\n >>> import_visual_styles('curstyle.xml') # export curstyle.xml in the current directory\n ['galFiltered Style']\n\n See Also:\n :meth:`export_visual_styles`\n \"\"\"\n res = commands.commands_post(f'vizmap load file file=\"{get_abs_sandbox_path(filename)}\"', base_url=base_url)\n return res\n\n@cy_log\ndef get_visual_style_names(base_url=DEFAULT_BASE_URL):\n \"\"\"Retrieve a list of all visual style names.\n\n Args:\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n list: [names of styles in session]\n\n Raises:\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> visual_style_names()\n ['Universe', 'Marquee', 'Big Labels', 'BioPAX_SIF', 'Ripple', 'Metallic', 'default black', ...]\n \"\"\"\n res = commands.cyrest_get('apply/styles', base_url=base_url)\n return res\n\n\n@cy_log\ndef set_visual_style(style_name, network=None, base_url=DEFAULT_BASE_URL):\n \"\"\"Apply a visual style to a network.\n\n Args:\n style_name (str): Name of a visual style\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n dict: {'message': 'Visual Style applied.'}\n\n Raises:\n CyError: if style doesn't exist or network doesn't exist\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> set_visual_style('default')\n {'message': 'Visual Style applied.'}\n >>> set_visual_style('galFiltered Style', network=51)\n {'message': 'Visual Style applied.'}\n \"\"\"\n net_suid = networks.get_network_suid(network, base_url=base_url)\n current_names = get_visual_style_names(base_url=base_url)\n\n # inform user if they want to set style that does not exist\n if style_name not in current_names:\n raise CyError(f'Cannot use non-existent visual style \"{style_name}\"')\n\n res = commands.cyrest_get(f'apply/styles/{style_name}/{net_suid}', base_url=base_url)\n return res\n\n\n@cy_log\ndef get_arrow_shapes(base_url=DEFAULT_BASE_URL):\n \"\"\"Get Arrow Shapes.\n\n Retrieve the names of the currently supported 'arrows' -- the decorations can (optionally) appear at\n the ends of edges, adjacent to the nodes they connect, and conveying information about the nature of\n the nodes' relationship.\n\n Args:\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n list: [arrow shape names]\n\n Raises:\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> get_arrow_shapes()\n ['OPEN_CIRCLE', 'SQUARE', 'CIRCLE', 'DELTA_SHORT_2', 'DELTA', 'DIAMOND_SHORT_2', ...]\n \"\"\"\n res = commands.cyrest_get('styles/visualproperties/EDGE_TARGET_ARROW_SHAPE/values', base_url=base_url)\n return res['values']\n\n\n@cy_log\ndef get_line_styles(base_url=DEFAULT_BASE_URL):\n \"\"\"Get Line Styles.\n\n Retrieve the names of the currently supported line types -- values which can be used to render edges, and thus\n can be used in calls to ``set_edge_line_style_rule()``.\n\n Args:\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n list: [line style names]\n\n Raises:\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> get_line_styles()\n ['MARQUEE_DASH_DOT', 'SOLID', 'BACKWARD_SLASH', 'EQUAL_DASH', 'CONTIGUOUS_ARROW', ...]\n \"\"\"\n res = commands.cyrest_get('styles/visualproperties/EDGE_LINE_TYPE/values', base_url=base_url)\n return res['values']\n\n@cy_log\ndef get_node_shapes(base_url=DEFAULT_BASE_URL):\n \"\"\"Get Node Shapes.\n\n Retrieve the names of the currently supported node shapes, which can then be used in calls to\n ``set_node_shape_rule()`` and ``set_default_viz_map_value()``.\n\n Args:\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n list: [node shape names]\n\n Raises:\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> get_node_shapes()\n ['ROUND_RECTANGLE', 'VEE', 'TRIANGLE', 'HEXAGON', 'PARALLELOGRAM', 'ELLIPSE', 'OCTAGON', ...]\n \"\"\"\n res = commands.cyrest_get('styles/visualproperties/NODE_SHAPE/values', base_url=base_url)\n return res['values']\n\n\n@cy_log\ndef get_visual_property_names(base_url=DEFAULT_BASE_URL):\n \"\"\"Retrieve the names of all possible visual properties.\n\n Args:\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n list: [visual property names]\n\n Raises:\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> get_visual_property_names()\n ['COMPOUND_NODE_PADDING', 'COMPOUND_NODE_SHAPE', 'DING_RENDERING_ENGINE_ROOT', 'EDGE', ...]\n \"\"\"\n res = commands.cyrest_get('styles/default/defaults', base_url=base_url)\n visual_properties = [prop['visualProperty'] for prop in res['defaults']]\n return visual_properties\n\n\n@cy_log\ndef get_current_style(network=None, base_url=DEFAULT_BASE_URL):\n \"\"\"Get the current visual style applied to a network.\n\n Args:\n network (str or SUID or None): Name or SUID of the network or view. Default is the \"current\" network active in Cytoscape.\n If a network view SUID is provided, then it is validated and returned.\n base_url (str): Ignore unless you need to specify a custom domain,\n port or version to connect to the CyREST API. Default is http://127.0.0.1:1234\n and the latest version of the CyREST API supported by this version of py4cytoscape.\n\n Returns:\n str: Name of style\n\n Raises:\n CyError: if style doesn't exist or network doesn't exist\n requests.exceptions.RequestException: if can't connect to Cytoscape or Cytoscape returns an error\n\n Examples:\n >>> get_current_style()\n \"default\"\n \"\"\"\n net_suid = networks.get_network_suid(network, base_url=base_url)\n view_suid = network_views.get_network_view_suid(net_suid, base_url=base_url)\n res = commands.cyrest_get(f'networks/{net_suid}/views/{view_suid}/currentStyle', base_url=base_url)\n return res['title']\n","repo_name":"cytoscape/py4cytoscape","sub_path":"py4cytoscape/styles.py","file_name":"styles.py","file_ext":"py","file_size_in_byte":19852,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"3"}
+{"seq_id":"3278163686","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('maestros', '0030_detallecalculo_cadena'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Nivel2',\n fields=[\n ('codigo', models.CharField(max_length=50, serialize=False, primary_key=True)),\n ('nivel', models.CharField(max_length=50)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","repo_name":"jespoz/panel_precios","sub_path":"apps/maestros/migrations/0031_nivel2.py","file_name":"0031_nivel2.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34509755098","text":"import re\nimport sys\nimport argparse\nfrom pymysqlreplication import BinLogStreamReader\nfrom pymysqlreplication.row_event import (\n WriteRowsEvent,\n UpdateRowsEvent,\n DeleteRowsEvent\n)\n\n# 设置命令行参数\nparser = argparse.ArgumentParser(description='Binlog Analysis Tool')\n\nparser.add_argument('-H', '--host', metavar='', type=str, required=True,\n help='the MySQL server host (default: 127.0.0.1)')\nparser.add_argument('-P', '--port', metavar='', type=int, default=3306,\n help='the MySQL server port (default: 3306)')\nparser.add_argument('-u', '--user', metavar='', type=str, required=True,\n help='the MySQL user name')\nparser.add_argument('-p', '--password', metavar='', type=str, required=True,\n help='the MySQL password')\nparser.add_argument('-d', '--database', metavar='', type=str, required=True,\n help='the database schema name')\nparser.add_argument('-c', '--charset', metavar='', type=str, default='utf8',\n help='the MySQL connection character set (default: utf8)')\nparser.add_argument('-s', '--start', metavar='', type=str, required=True,\n help='the start index of binlog files, e.g. mysql-bin.000001')\nparser.add_argument('-e', '--end', metavar='', type=str,\n help='the end index of binlog files, e.g. mysql-bin.000003')\n \nargs = parser.parse_args()\n\n# 定义MySQL连接设置\nsource_mysql_settings = {\n \"host\": args.host,\n \"port\": args.port,\n \"user\": args.user,\n \"passwd\": args.password,\n \"database\": args.database,\n \"charset\": args.charset\n}\n\n# 解析起始和结束索引\nstart_index = int(args.start.split('.')[-1])\nend_index = int(args.end.split('.')[-1]) if args.end else start_index\n\n# 根据开始和结束索引生成文件名列表\nlog_files = []\nfor i in range(start_index, end_index+1):\n # 将文件名拼接起来\n file_name = args.start.split('.')[0] + f'.{i:06d}'\n log_files.append(file_name)\n\nprint(f'process binlog files is : {log_files}\\n')\n\n# 定义记录表的字典\ntable_counts = {}\n\n# 定义Binlog解析器\nfor log_file in log_files:\n # 提取文件名中的数字部分\n file_number = int(re.search(r'\\d+', log_file).group())\n \n stream = BinLogStreamReader(connection_settings=source_mysql_settings, \n server_id=123456789,\n log_file=log_file, \n resume_stream=False)\n\n # 开始读取日志\n for binlogevent in stream:\n # 只处理数据行事件\n if isinstance(binlogevent, (WriteRowsEvent, UpdateRowsEvent, DeleteRowsEvent)):\n # 获取事件的表名和操作类型\n table = binlogevent.table\n event_type = type(binlogevent).__name__\n \n # 初始化记录表的计数器\n if table not in table_counts:\n table_counts[table] = {'insert': 0, 'update': 0, 'delete': 0}\n \n # 根据操作类型更新计数器\n if event_type == 'WriteRowsEvent':\n table_counts[table]['insert'] += 1\n elif event_type == 'UpdateRowsEvent':\n table_counts[table]['update'] += 1\n elif event_type == 'DeleteRowsEvent':\n table_counts[table]['delete'] += 1\n\n\n# 按照操作次数排序输出最终结果\nsorted_table_counts = sorted(table_counts.items(), \n key=lambda x: sum(x[1].values()), reverse=True)\n\n# 打印当前文件的统计结果\nfor table, counts in sorted_table_counts:\n print(f'{table}: {counts}\\n')\n","repo_name":"hcymysql/binlog_analysis","sub_path":"binlog_analysis.py","file_name":"binlog_analysis.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"9290173889","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 06 14:28:29 2015\n\n@author: breiche\n\nYou are part of a team developing software to help students learn basic mathematics. \nYou are to write one part of that software, which is to display possibly improper \nfractions as mixed fractions. A proper fraction is one where the numerator is \nless than the denominator; a mixed fraction is a whole number followed by a \nproper fraction. For example the improper fraction 27/12 is equivalent to the \nmixed fraction 2 3/12. You should not reduce the fraction (i.e. don’t \nchange 3/12 to 1/4).\n\"\"\"\n\nimport unittest\n\nclass MixedFractionsSolution(object):\n def mixedFractions(self, fractionAsString):\n '''\n input: a string with two integers, seperated by a space\n output: string displaying mixed fraction as a whole number, space, \n followed by a proper fraction\n '''\n numerator, denominator = fractionAsString.split(\" \")\n \n numerator = int(numerator)\n denominator = int(denominator)\n \n wholenum = 0\n remainder = 0\n \n if numerator >= denominator:\n wholenum = numerator / denominator\n remainder = numerator % denominator\n \n return \"{0} {1}/{2}\".format(str(wholenum), str(remainder), str(denominator))\n \n \nclass MixedFractionsTest(unittest.TestCase):\n \n def test1(self):\n s = MixedFractionsSolution()\n answer = s.mixedFractions(\"27 12\")\n expected = \"2 3/12\"\n self.assertEqual(answer, expected)\n \n def test2(self):\n s = MixedFractionsSolution()\n answer = s.mixedFractions(\"2460000 98400\")\n expected = \"25 0/98400\"\n self.assertEqual(answer, expected)\n \n def test3(self):\n s = MixedFractionsSolution()\n answer = s.mixedFractions(\"3 4000\")\n expected = \"0 3/4000\"\n self.assertEqual(answer, expected)\n \n \nif __name__ == '__main__':\n unittest.main()\n\n ","repo_name":"bridgette/Python100","sub_path":"mixed_fractions.py","file_name":"mixed_fractions.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"29497494156","text":"'''\n有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。\n\n在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j] 由 [0,1,...,N-1] 中的一个整数表示,其中 N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。\n\n最初,除 0 号房间外的其余所有房间都被锁住。\n\n你可以自由地在房间之间来回走动。\n\n如果能进入每个房间返回 true,否则返回 false。\n\n示例 1:\n\n输入: [[1],[2],[3],[]]\n输出: true\n解释:\n我们从 0 号房间开始,拿到钥匙 1。\n之后我们去 1 号房间,拿到钥匙 2。\n然后我们去 2 号房间,拿到钥匙 3。\n最后我们去了 3 号房间。\n由于我们能够进入每个房间,我们返回 true。\n示例 2:\n\n输入:[[1,3],[3,0,1],[2],[0]]\n输出:false\n解释:我们不能进入 2 号房间。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/keys-and-rooms\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n'''\n\nclass Solution:\n def canVisitAllRooms(self, rooms: [[int]]) -> bool:\n visited = [0] * len(rooms)\n queue = [0]\n\n while queue:\n cur = queue.pop(0)\n #钥匙全拿,再考虑去过的房间\n if visited[cur] == 0:\n queue.extend(rooms[cur])\n visited[cur] = 1\n if 0 in visited:\n return False\n return True\n\n def canVisitAllRooms_1(self, rooms: [[int]]) -> bool:\n '''\n 逻辑优化版\n '''\n visited,queue = {0},[0]\n\n while queue:\n cur_room = queue.pop(0)\n #只拿没去过房间的钥匙\n for key in rooms[cur_room]:\n if key not in visited:\n queue.append(key)\n visited.add(key)\n return len(visited) == len(rooms)\n\n def canVisitAllRooms_dfs(self, rooms: [[int]]) -> bool:\n visited,stack = {0},[0]\n\n while stack:\n cur = stack.pop()\n for key in rooms[cur]:\n if key not in visited:\n stack.append(key)\n visited.add(key)\n return len(visited) == len(rooms)\n\n def canVisitAllRooms_dfs_R(self, rooms: [[int]]) -> bool:\n visited = {0}\n def dfs(cur,visited):\n visited.add(cur)\n for key in rooms[cur]:\n if key not in visited:\n dfs(key,visited)\n dfs(0,visited)\n return len(visited) == len(rooms)\n\n\n#测试\nrooms = [[1,3],[3,2,1],[2],[0]]\nres = Solution().canVisitAllRooms_dfs_R(rooms)\nprint(res)","repo_name":"Da1anna/Data-Structed-and-Algorithm_python","sub_path":"leetcode/图/general/钥匙和房间.py","file_name":"钥匙和房间.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26082138423","text":"from multiprocessing import Process, Value\nfrom time import sleep\n\n\ndef main():\n process = CustomProcess()\n process.start()\n print('Awaiting processes...')\n process.join()\n print(f'Parent got {process.data.value}')\n\n\nclass CustomProcess(Process):\n def __init__(self):\n Process.__init__(self)\n self.data = Value('i', 0)\n\n def run(self):\n sleep(1)\n self.data.value = 99\n print(f'Child stored: {self.data.value}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"damiansp/completePython","sub_path":"oneoffs/multiprocessing/02_extend_the_process_class/custom_process_with_return_val.py","file_name":"custom_process_with_return_val.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"3749860641","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.fft import fft\nfrom sklearn.metrics import mean_squared_error\n\nLENGTH_INPUT = 300\nPOPULATION_SIZE = 50\nMAX_GENERATIONS = 100\n\n\n# define the standalone discriminator model\nclass Discriminator(nn.Module):\n def __init__(self, n_inputs=LENGTH_INPUT):\n super(Discriminator, self).__init__()\n self.model = nn.Sequential(\n nn.Linear(n_inputs, LENGTH_INPUT),\n nn.ReLU(),\n nn.Linear(LENGTH_INPUT, 250),\n nn.ReLU(),\n nn.Linear(250, 100),\n nn.ReLU(),\n nn.Linear(100, 1),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n return self.model(x)\n\n\n# define the standalone generator model\nclass Generator(nn.Module):\n def __init__(self, input_size, output_size):\n super(Generator, self).__init__()\n self.model = nn.Sequential(\n nn.Linear(input_size, 128),\n nn.ReLU(),\n nn.Linear(128, 256),\n nn.ReLU(),\n nn.Linear(256, 512),\n nn.ReLU(),\n nn.Linear(512, output_size),\n nn.Tanh()\n )\n\n def forward(self, x):\n return self.model(x)\n\n\n# generate n real samples with class labels\ndef generate_faulty_samples(n, fault_type):\n amps = np.arange(0.1, 10, 0.1)\n bias = np.arange(0.1, 10, 0.1)\n freqs = np.linspace(1, 2, 1000)\n X2 = np.linspace(-5, 5, LENGTH_INPUT)\n X1 = []\n for x in range(n):\n noise = np.random.normal(size=len(X2))\n\n if fault_type == 'ball':\n fault_frequency = 500\n elif fault_type == 'outer_race':\n fault_frequency = 1000\n elif fault_type == 'inner_race':\n fault_frequency = 1500\n elif fault_type == 'roller':\n fault_frequency = 2000\n else:\n raise ValueError(\"Invalid fault type. Supported types: 'ball', 'outer_race', 'inner_race', 'roller'\")\n\n X1.append(\n np.random.choice(amps) * np.sin(X2 * fault_frequency) + np.random.choice(bias) + 0.3 * noise)\n X1 = np.array(X1).reshape(n, LENGTH_INPUT)\n # generate class labels\n y = np.ones((n, 1))\n return X1, y\n\n\n# generate points in latent space as input for the generator\ndef generate_latent_points(latent_dim, n):\n # generate points in the latent space\n x_input = np.random.randn(n, latent_dim)\n # reshape into a batch of inputs for the network\n x_input = x_input.reshape(n, latent_dim)\n return x_input\n\n\n# use the generator to generate n fake examples, with class labels\ndef generate_fake_samples(generator, latent_dim, n):\n # Generate points in latent space\n x_input = generate_latent_points(latent_dim, n)\n # Convert to PyTorch tensor\n x_input = torch.from_numpy(x_input).float()\n # Generate output\n X = generator(x_input)\n # Create fake labels\n y = torch.zeros((n, 1))\n return X, y\n\n# calculate the fitness score for a set of chromosomes\ndef calculate_fitness(chromosomes, gan_model, generation):\n fitness_scores = []\n for chromosome in chromosomes:\n latent_dim = chromosome.shape[3] # Update to match the new chromosome shape\n generator, discriminator = gan_model\n\n # Reshape the chromosome to match the expected shape\n resized_chromosome = chromosome.reshape((1, 1, 1, latent_dim))\n\n # Convert the chromosome to a PyTorch tensor\n resized_chromosome = torch.from_numpy(resized_chromosome).float()\n\n # Print the shape of the generator's weight tensor\n print(\"Generator's weight shape before expansion:\", generator.model[0].weight.shape)\n\n # Expand the chromosome tensor to match the generator's weight shape\n expanded_chromosome = resized_chromosome.expand(generator.model[0].weight.shape[0], -1, -1, -1)\n\n # Create a new state dictionary and update generator's weights\n state_dict = generator.state_dict()\n state_dict['model.0.weight'] = expanded_chromosome.squeeze()\n generator.load_state_dict(state_dict, strict=False)\n\n # Create a new state dictionary\n state_dict = {\n 'model.0.weight': generator.model[0].weight,\n 'model.0.bias': generator.model[0].bias,\n 'model.2.weight': generator.model[2].weight,\n 'model.2.bias': generator.model[2].bias,\n 'model.4.weight': generator.model[4].weight,\n 'model.4.bias': generator.model[4].bias,\n 'model.6.weight': generator.model[6].weight,\n 'model.6.bias': generator.model[6].bias\n }\n\n # Update generator's weights\n generator.load_state_dict(state_dict, strict=False)\n\n # Generate fake samples\n X, y = generate_fake_samples(generator, latent_dim, POPULATION_SIZE)\n\n # Evaluate GAN performance\n mse = evaluate_gan_performance(X, discriminator)\n fitness_scores.append(1 / mse)\n\n return fitness_scores\n\n\n# evaluate the GAN performance\ndef evaluate_gan_performance(samples, discriminator):\n y_pred = discriminator(samples)\n y_true = torch.zeros(samples.size(0), 1)\n mse = mean_squared_error(y_true.detach().numpy(), y_pred.detach().numpy())\n return mse\n\n\n# generate random sample of input noise for the generator\ndef generate_noise(latent_dim, n):\n x_input = np.random.randn(n, 1, 1, latent_dim)\n return x_input\n\n# train the generator and discriminator\ndef train(gan_model, n_epochs, n_eval=10):\n generator, discriminator = gan_model\n latent_dim = generator.model[0].in_features\n population = [generate_noise(latent_dim, 1) for _ in range(POPULATION_SIZE)]\n best_chromosome = None\n best_fitness = float('-inf')\n all_fitness = []\n\n for generation in range(n_epochs):\n fitness_scores = calculate_fitness(population, gan_model, generation)\n all_fitness.append(max(fitness_scores))\n\n if max(fitness_scores) > best_fitness:\n best_fitness = max(fitness_scores)\n best_chromosome = population[np.argmax(fitness_scores)]\n\n if (generation + 1) % n_eval == 0:\n print(f\"Generation {generation + 1}, Best Fitness: {best_fitness}\")\n\n # Generate and save the graph\n plt.figure(figsize=(12, 5))\n plt.title(f'Generation {generation + 1}')\n with torch.no_grad():\n gen_samples, _ = generate_fake_samples(generator, latent_dim, 1)\n real_samples, _ = generate_faulty_samples(latent_dim, 'ball')\n\n real_samples_tensor = torch.Tensor(real_samples)\n fft_real_samples = torch.fft.fft(real_samples_tensor)\n\n gen_samples_tensor = torch.Tensor(gen_samples)\n fft_fake_samples = torch.fft.fft(gen_samples_tensor)\n\n plt.subplot(1, 2, 2)\n plt.plot(np.abs(fft_fake_samples[0]), '-', label='Random Fake FFT Sample', color='firebrick')\n plt.plot(np.abs(fft_real_samples[0]), '-', label='Random Real FFT Sample', color='navy')\n plt.title('FFT signal')\n plt.legend(fontsize=10)\n\n plt.subplot(1, 2, 1)\n plt.plot(gen_samples[0], '-', label='Random Fake Sample', color='firebrick')\n plt.plot(real_samples[0], '-', label='Random Real Sample', color='navy')\n plt.title('Signal')\n plt.legend(fontsize=10)\n\n plt.legend(fontsize=10)\n plt.tight_layout()\n plt.savefig(f'img/Ver2-ball-graph_g-{generation + 1}.png')\n plt.close()\n\n # Select parents for reproduction\n parents = np.random.choice(np.array(population).reshape(-1), size=POPULATION_SIZE // 2, replace=False)\n # Perform crossover\n offspring = []\n for parent in parents:\n index = np.random.randint(0, latent_dim)\n offspring.append(np.concatenate((best_chromosome[:index], parent[index:])))\n offspring = parents + offspring\n # Update population with offspring\n population = offspring\n\n # Save the generator model\n torch.save(generator.state_dict(), 'generator_model.pth')\n\n return best_chromosome\n\n# define the GAN model\ndef define_gan(latent_dim, output_size):\n generator = Generator(latent_dim, output_size)\n discriminator = Discriminator()\n gan_model = (generator, discriminator)\n return gan_model\n\n\n# define the number of dimensions in the latent space\nlatent_dim = 10\noutput_size = LENGTH_INPUT\n\n# define the GAN model\ngan_model = define_gan(latent_dim, output_size)\n\n# set the device for training\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ngenerator, discriminator = gan_model\ngenerator = generator.to(device)\ndiscriminator = discriminator.to(device)\n\n# train the GAN\nbest_chromosome = train(gan_model, MAX_GENERATIONS)\n\nprint(\"Best chromosome:\")\nprint(best_chromosome)\n\n# Save the generator model\ntorch.save(generator.state_dict(), 'generator_model.pth')\n","repo_name":"HanJaemin-kr/Industrial-AI","sub_path":"bearing/siganlGeneratorByGan/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":9021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29931162514","text":"#####################################################################\r\n#\r\n# FileName : UnderTargetScreener\r\n#\r\n# Usage : This python script takes one parameter - the csv file\r\n# containing one symbol per line, of all the Stock Symbols\r\n# you wish to check against the screener. Defaults to use the\r\n# SP500ListAll.csv included in the input directory.\r\n#\r\n#####################################################################\r\n\r\n# import required libraries and modules\r\nimport os\r\nimport pandas as pd\r\nimport sys\r\nimport datetime as dt\r\nfrom CommonUtilities import CommonUtilities as util\r\nfrom ZacksUtilities import ZacksList as zlist\r\nfrom ZacksUtilities import ZacksCalculations as zcalc\r\n\r\nprint(\"Begin Screener.py\")\r\n\r\n# cd to the current directory\r\nworkingdirectory = os.getcwd()\r\nos.chdir(workingdirectory)\r\n\r\nprint(workingdirectory)\r\n\r\n# declare the input paramater csv file name\r\nimport_file_name = ''\r\n\r\n# it considers no parameters as 1 parameter, the first paramater being the script name. This will be the 0 index aka sys.argv[0].\r\nif(len(sys.argv) > 1):\r\n import_file_name = sys.argv[1]\r\n\r\n# if the parameter is not supplied, default to all S&P500 stocks\r\nif(len(import_file_name) == 0):\r\n import_file_name = 'SP500ListAll.csv'\r\n\r\n# import the csv stock list\r\nimport_csv_filename = path_or_buf=workingdirectory +'/input/'+ import_file_name\r\nprint(\"Screener: using \" + import_csv_filename + \" for symbols\")\r\nsymbols = []\r\nif(util.PathExists(import_csv_filename)):\r\n symbols_csv = pd.read_csv(import_csv_filename)\r\n symbols = symbols_csv['Stocks'] # grab the stocks column, this is the only one and will convert this to a list\r\n\r\nprint(\"Get Zacks Info Map for symbols\")\r\ninfo_map = zlist.GetZacksInfoMap(symbols)\r\nprint(\"Get Zacks Company Report for symbols\")\r\nreport_map = zlist.GetZacksCompanyReportMap(symbols)\r\n\r\nvalid_ranks =[\"Strong Buy\",\"Buy\"]\r\nprint(\",\".join(valid_ranks))\r\nprint(\"Run checks on symbols for given valid rankings\")\r\n\r\nvalidated_list = zcalc.GetUndervaluedByRank(symbols, report_map, info_map, True, valid_ranks)\r\n\r\nprint('\\nResults:')\r\nif(\"Strong Buy\" in valid_ranks):\r\n print('Strong Buys are:\\n')\r\n print(validated_list['Strong_Buy'])\r\n print('===================================')\r\nif(\"Buy\" in valid_ranks):\r\n print('Buys are:\\n')\r\n print(validated_list['Buy'])\r\n print('===================================')\r\nif(\"Hold\" in valid_ranks):\r\n print('Holds are:\\n')\r\n print(validated_list['Hold'])\r\n print('===================================')\r\nif(\"Sell\" in valid_ranks):\r\n print('Sells are:\\n')\r\n print(validated_list['Sell'])\r\n print('===================================')\r\nif(\"Strong Sell\" in valid_ranks):\r\n print('Strong Sells are:\\n')\r\n print(validated_list['Strong_Sell'])\r\n \r\nbuys_str = \",\".join(validated_list['Strong_Buy']) \r\nif(buys_str):\r\n buys_str += \",\"\r\nbuys_str += \",\".join(validated_list['Buy'])\r\n\r\ntoday = dt.datetime.today().strftime('%Y-%m-%d')\r\nnew_file = path_or_buf=workingdirectory + '/output/UnderTargetScreenerResults'+today+'.txt'\r\nwith open(new_file, \"w\") as text_file:\r\n text_file.write(buys_str)","repo_name":"cantoniam/ZacksTrading","sub_path":"UnderTargetScreener.py","file_name":"UnderTargetScreener.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27550663222","text":"# Reference - https://github.com/isegura/MultimodalFakeNewsDetection\n\n\n# Import libraries\nimport numpy as np # version - 1.21.6\nimport optuna # version - 3.0.3\nimport matplotlib # version - 3.5.3\nimport matplotlib.image as mpimg\nimport pandas as pd # version - 1.3.5\nimport matplotlib.pyplot as plt\nfrom sklearn.feature_extraction.text import TfidfVectorizer # sklearn version - 1.0.2\nimport nltk # version - 3.7\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom nltk.corpus import stopwords\nfrom nltk import word_tokenize\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport re # version - 2.2.1\nfrom tensorflow.keras.preprocessing.text import Tokenizer # tensorflow version - 2.6.4\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import classification_report, accuracy_score, confusion_matrix\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import classification_report\n\n\n# Train data (with and without images)\ntraindata_all = pd.read_csv(\"./all_train.tsv\", sep='\\t') # path to be changed based on the path of data file\n# Validation data (with and without images)\nvalidata_all = pd.read_csv(\"./all_validate.tsv\", sep='\\t') # path to be changed based on the path of data file\n# Test data (with and without images)\ntestdata_all = pd.read_csv(\"./all_test_public.tsv\", sep='\\t') # path to be changed based on the path of data file\n\n# cleaning the training data\ntrain_data_all = traindata_all[traindata_all['clean_title'].notnull().to_numpy()]\n# cleaning the validation data\nvalid_data_all = validata_all[validata_all['clean_title'].notnull().to_numpy()]\n# cleaning the testing data\ntest_data_all = testdata_all[testdata_all['clean_title'].notnull().to_numpy()]\n\n# separating the data and labels\ntrain_frame = train_data_all[\"clean_title\"]\ntrain_labels = train_data_all[\"2_way_label\"]\n\nvalid_frame = valid_data_all[\"clean_title\"]\nvalid_labels = valid_data_all[\"2_way_label\"]\n\ntest_frame = test_data_all[\"clean_title\"]\ntest_labels = test_data_all[\"2_way_label\"]\n\n# first we remove punctuations and numbers and also multiple spaces\n\ntrain_list = list(train_frame)\nvalid_list = list(valid_frame)\ntest_list = list(test_frame)\n\ntrain_labels_list = list(train_labels)\nvalid_labels_list = list(valid_labels)\ntest_labels_list = list(test_labels)\n\n\ndef preprocess_text(sen):\n # Remove punctuations and numbers\n sentence = re.sub('[^a-zA-Z]', ' ', sen)\n\n # Removing multiple spaces\n sentence = re.sub(r'\\s+', ' ', sentence)\n\n return sentence\n\n\ntrain_news_clean_1 = []\nvalid_news_clean_1 = []\ntest_news_clean_1 = []\n\nfor new in train_list:\n train_news_clean_1.append(preprocess_text(new))\n\nfor new in valid_list:\n valid_news_clean_1.append(preprocess_text(new))\n\nfor new in test_list:\n test_news_clean_1.append(preprocess_text(new))\n\n\n# Function to remove stop words and perform lemmatization\n# Initialize lemmatizer\nimport nltk\nnltk.download('stopwords')\nnltk.download('wordnet')\nnltk.download('omw-1.4')\nlemmatizer = WordNetLemmatizer()\n\n# Initialize stemmer and stop_words\n#stemmer = PorterStemmer()\nstop_words = set(stopwords.words('english')) \n\n\n# Function to remove stopwords\ndef remove_stopwords_lem(text):\n text = word_tokenize(text)\n # Stop words removal\n text = [word for word in text if word not in stop_words]\n # Lematization\n lemmatized_text = []\n for word in text:\n word1 = lemmatizer.lemmatize(word, pos = \"n\")\n word2 = lemmatizer.lemmatize(word1, pos = \"v\")\n word3 = lemmatizer.lemmatize(word2, pos = (\"a\"))\n lemmatized_text.append(word3) \n text_done = ' '.join(lemmatized_text)\n return text_done\n\n\ntrain_lemmatized = [remove_stopwords_lem(text) for text in train_news_clean_1]\n\nvalid_lemmatized = [remove_stopwords_lem(text) for text in valid_news_clean_1]\n\ntest_lemmatized = [remove_stopwords_lem(text) for text in test_news_clean_1]\n\n\n# Finding best hyper-parameters for multinomial naive bayes\ndef objective_Bayes(trial):\n \n # Sample values for the hyper-parameters\n n = trial.suggest_int(\"n\", 1, 2)\n sub_tf = trial.suggest_categorical(\"sub_tf\", [\"True\", \"False\"])\n min_df = trial.suggest_int(\"min_df\",5,25)\n # Create pipeline\n Bayes_pipe = Pipeline([('vect', CountVectorizer(ngram_range = (1, n), min_df = min_df)),\n ('tfidf', TfidfTransformer(sublinear_tf = sub_tf)),('classifier', MultinomialNB() )])\n # Fit model\n clf_Bayes = Bayes_pipe.fit(train_lemmatized, train_labels_list)\n # Obtain the predictions\n predictions = Bayes_pipe.predict(valid_lemmatized)\n # Obtain the accuracy\n acc = accuracy_score(valid_labels_list, predictions)\n \n return acc\n\n\n# Select budget and set seed \nbudget = 40\nnp.random.seed(0)\n# Optimize hyper-parameters\nstudy_Bayes = optuna.create_study(direction=\"maximize\")\nstudy_Bayes.optimize(objective_Bayes, n_trials=budget,show_progress_bar=False)\n\n# Best hyper-parameters\nprint(\"Best hyper-parameters: \")\nprint(study_Bayes.best_params)\n# Best score\nprint(\"Best score: \")\nprint(study_Bayes.best_value)\n\n\n# Finding best hyper-parameters for logistic regression\ndef objective_Logistic(trial):\n \n # Sample values for the hyper-parameters\n max_iter = trial.suggest_int(\"max_iter\", 320, 420)\n solver = trial.suggest_categorical(\"solver\", [\"newton-cg\"])\n multi_class = trial.suggest_categorical(\"multi_class\",[\"ovr\", \"multinomial\"])\n n = trial.suggest_int(\"n\", 1, 2)\n min_df = trial.suggest_int(\"min_df\",5,25)\n sub_tf = trial.suggest_categorical(\"sub_tf\", [\"True\", \"False\"])\n # Create pipeline\n Logistic_pipe = Pipeline([('vect', CountVectorizer(ngram_range = (1, n), min_df = min_df)),\n ('tfidf', TfidfTransformer(sublinear_tf = sub_tf)),('classifier', LogisticRegression(random_state = 3,\n solver = solver, multi_class = multi_class, max_iter = max_iter ) )])\n\n # Fit model\n clf_Logistic = Logistic_pipe.fit(train_lemmatized, train_labels_list)\n # Obtain the predictions\n predictions = Logistic_pipe.predict(valid_lemmatized)\n # Obtain the accuracy\n acc = accuracy_score(valid_labels_list, predictions)\n \n return acc\n\n\n# Select budget and set seed \nbudget = 40\nnp.random.seed(0)\n# Optimize hyper-parameters\nstudy_Logistic = optuna.create_study(direction=\"maximize\")\nstudy_Logistic.optimize(objective_Logistic, n_trials=budget,show_progress_bar=False)\n\n# Best hyper-parameters\nprint(\"Best hyper-parameters: \")\nprint(study_Logistic.best_params)\n# Best score\nprint(\"Best score: \")\nprint(study_Logistic.best_value)\n\n\n# Finding best hyper-parameters for random forests\ndef objective_Forest(trial):\n \n # Sample values for the hyper-parameters\n n_estimators = trial.suggest_int(\"n_estimators\", 100, 300)\n criterion = trial.suggest_categorical(\"criterion\", [\"gini\", \"entropy\"])\n max_depth = trial.suggest_int(\"max_depth\", 3, 6)\n n = trial.suggest_int(\"n\", 1, 2)\n min_df = trial.suggest_int(\"min_df\",5,25)\n sub_tf = trial.suggest_categorical(\"sub_tf\", [\"True\", \"False\"])\n # Create pipeline\n Forest_pipe = Pipeline([('vect', CountVectorizer(ngram_range = (1, n), min_df = min_df)),\n ('tfidf', TfidfTransformer(sublinear_tf = sub_tf)),('classifier', RandomForestClassifier(\n random_state = 3, n_estimators = n_estimators, criterion = criterion,\n max_depth = max_depth ) )])\n\n # Fit model\n clf_Forest = Forest_pipe.fit(train_lemmatized, train_labels_list)\n # Obtain the predictions\n predictions = Forest_pipe.predict(valid_lemmatized)\n # Obtain the accuracy\n acc = accuracy_score(valid_labels_list, predictions)\n \n return acc\n\n\n# Select budget and set seed \nbudget = 40\nnp.random.seed(0)\n# Optimize hyper-parameters\nstudy_Forest = optuna.create_study(direction=\"maximize\")\nstudy_Forest.optimize(objective_Forest, n_trials=budget,show_progress_bar=False)\n\n# Best hyper-parameters\nprint(\"Best hyper-parameters: \")\nprint(study_Forest.best_params)\n# Best score\nprint(\"Best score: \")\nprint(study_Forest.best_value)\n\n\n# Finding best hyper-parameters for linear SVM\ndef objective_SVC(trial):\n \n # Sample values for the hyper-parameters\n max_iter = trial.suggest_int(\"max_iter\", 1000, 3000)\n loss = trial.suggest_categorical(\"loss\", [\"hinge\", \"squared_hinge\"])\n n = trial.suggest_int(\"n\", 1, 2)\n min_df = trial.suggest_int(\"min_df\",5,25)\n sub_tf = trial.suggest_categorical(\"sub_tf\", [\"True\", \"False\"])\n # Create pipeline\n SVC_pipe = Pipeline([('vect', CountVectorizer(ngram_range = (1, n), min_df = min_df)),\n ('tfidf', TfidfTransformer(sublinear_tf = sub_tf)),('classifier', LinearSVC(\n random_state = 3, max_iter = max_iter,\n loss = loss) )])\n\n # Fit model\n clf_SVC = SVC_pipe.fit(train_lemmatized, train_labels_list)\n # Obtain the predictions\n predictions = SVC_pipe.predict(valid_lemmatized)\n # Obtain the accuracy\n acc = accuracy_score(valid_labels_list, predictions)\n \n return acc\n\n\n# Select budget and set seed \nbudget = 40\nnp.random.seed(0)\n# Optimize hyper-parameters\nstudy_SVC = optuna.create_study(direction=\"maximize\")\nstudy_SVC.optimize(objective_SVC, n_trials=budget,show_progress_bar=False)\n\n# Best hyper-parameters\nprint(\"Best hyper-parameters: \")\nprint(study_SVC.best_params)\n# Best score\nprint(\"Best score: \")\nprint(study_SVC.best_value)\n\n\n# Join train and validation sets\ntraining_lemmatized = train_lemmatized + valid_lemmatized\n\n# Joining train and validation labels\ntraining_labels = train_labels_list + valid_labels_list\n\n\n# Training and testing the multinomial naive bayes classifier\nBayes_pipe_lem = Pipeline([('vect', CountVectorizer(ngram_range = (1, 2), min_df = 5)),\n ('tfidf', TfidfTransformer(sublinear_tf = 'True')),('classifier', MultinomialNB() )])\nBayes_pipe_lem.fit(training_lemmatized, training_labels)\n\n# Evaluation of the model\npredictions_Bayes_lem = Bayes_pipe_lem.predict(test_lemmatized)\nprint(classification_report(np.array(test_labels).reshape(len(test_labels),1),predictions_Bayes_lem))\n\n# Confusion matrix\nprint(confusion_matrix(np.array(test_labels).reshape(len(test_labels),1),predictions_Bayes_lem))\n\n\n# Training and testing logistic regression\nLogistic_pipe_lem = Pipeline([('vect', CountVectorizer(ngram_range = (1, 2), min_df = 5)),\n ('tfidf', TfidfTransformer(sublinear_tf = 'True')),('classifier', LogisticRegression(random_state = 3,\n solver = 'newton-cg', multi_class = 'multinomial', max_iter = 337 ) )])\nLogistic_pipe_lem.fit(training_lemmatized, training_labels)\n\n# Evaluation of the model\npredictions_Logistic_lem = Logistic_pipe_lem.predict(test_lemmatized)\nprint(classification_report(np.array(test_labels).reshape(len(test_labels),1),predictions_Logistic_lem))\n\n# Confusion matrix\nprint(confusion_matrix(np.array(test_labels).reshape(len(test_labels),1),predictions_Logistic_lem))\n\n\n# Training and testing random forests\nForest_pipe_lem = Pipeline([('vect', CountVectorizer(ngram_range = (1, 2), min_df = 9)),\n ('tfidf', TfidfTransformer(sublinear_tf = 'True')),('classifier', RandomForestClassifier(\n random_state = 3, n_estimators = 290, criterion = 'entropy',\n max_depth = 6) )])\nForest_pipe_lem.fit(training_lemmatized, training_labels)\n\n# Evaluation of the model\npredictions_Forest_lem = Forest_pipe_lem.predict(test_lemmatized)\nprint(classification_report(np.array(test_labels).reshape(len(test_labels),1),predictions_Forest_lem))\n\n# Confusion matrix\nprint(confusion_matrix(np.array(test_labels).reshape(len(test_labels),1),predictions_Forest_lem))\n\n\n# Training and testing linear SVM\nSVC_pipe_lem = Pipeline([('vect', CountVectorizer(ngram_range = (1, 2), min_df = 5)),\n ('tfidf', TfidfTransformer(sublinear_tf = 'True')),('classifier', LinearSVC(\n random_state = 3, max_iter = 1214,\n loss = 'squared_hinge') )])\nSVC_pipe_lem.fit(training_lemmatized, training_labels)\n\n# Evaluation of the model\npredictions_SVC_lem = SVC_pipe_lem.predict(test_lemmatized)\n\n# Classification report\nprint(classification_report(np.array(test_labels).reshape(len(test_labels),1),predictions_SVC_lem))\n\n# Confusion matrix\nprint(confusion_matrix(np.array(test_labels).reshape(len(test_labels),1),predictions_SVC_lem))\n\n\n\n\n\n\n","repo_name":"krishchilvery/MultiModalityFakeNews","sub_path":"basic_models.py","file_name":"basic_models.py","file_ext":"py","file_size_in_byte":12890,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"22484470641","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Global variable name for each element in figures to fetch elements in svg files\n @ Yixuan Wei\n @ weiyx16@mails.tsinghua.edu.cn\n\"\"\"\n\n\ndef element_init():\n global FIGURE_ID, FIGURE_PATCH_ID\n global AXES_ID, AXES_PATCH_ID\n global TITLE_ID\n global LEGEND_ID, LEGEND_PATCH_ID, LEGEND_TITLE_ID, LEGEND_SYMBOL_ID, LEGEND_TEXT_ID, LEGEND_PACKER_ID\n global X_AXIS_ID, X_AXIS_LABEL_ID, X_AXIS_OFFSET_ID, X_AXIS_LINE_ID\n global Y_AXIS_ID, Y_AXIS_LABEL_ID, Y_AXIS_OFFSET_ID, Y_AXIS_LINE_ID\n global X_AXIS_MAJOR_TICK_ID, X_AXIS_MAJOR_TICKLABEL_ID, X_AXIS_MAJOR_TICKLINE_ID, X_AXIS_MAJOR_GRID_ID\n global Y_AXIS_MAJOR_TICK_ID, Y_AXIS_MAJOR_TICKLABEL_ID, Y_AXIS_MAJOR_TICKLINE_ID, Y_AXIS_MAJOR_GRID_ID\n global X_AXIS_MINOR_TICK_ID, X_AXIS_MINOR_TICKLABEL_ID, X_AXIS_MINOR_TICKLINE_ID, X_AXIS_MINOR_GRID_ID\n global Y_AXIS_MINOR_TICK_ID, Y_AXIS_MINOR_TICKLABEL_ID, Y_AXIS_MINOR_TICKLINE_ID, Y_AXIS_MINOR_GRID_ID\n global POLAR_AXIS_TICKLABEL_ID\n global DRAWING_OBJECT_ID, OBJECT_TEXT_ID\n\n FIGURE_ID, FIGURE_PATCH_ID = \"the_figure\", \"the_figure_patch\"\n AXES_ID, AXES_PATCH_ID = \"the_axes\", \"the_axes_patch\"\n TITLE_ID = \"the_title\"\n LEGEND_ID, LEGEND_PATCH_ID, LEGEND_TITLE_ID, LEGEND_SYMBOL_ID, LEGEND_TEXT_ID, LEGEND_PACKER_ID = \\\n \"the_legend\", \"the_legend_patch\", \"the_legend_title\", \"the_legend_symbol_\", \"the_legend_text_\", \"the_legend_packer_\"\n X_AXIS_ID, X_AXIS_LABEL_ID, X_AXIS_OFFSET_ID, X_AXIS_LINE_ID = \\\n \"the_x_axis\", \"the_x_axis_label\", \"the_x_axis_offset\", \"the_x_axis_line\"\n Y_AXIS_ID, Y_AXIS_LABEL_ID, Y_AXIS_OFFSET_ID, Y_AXIS_LINE_ID = \\\n \"the_y_axis\", \"the_y_axis_label\", \"the_y_axis_offset\", \"the_y_axis_line\"\n X_AXIS_MAJOR_TICK_ID, X_AXIS_MAJOR_TICKLABEL_ID, X_AXIS_MAJOR_TICKLINE_ID, X_AXIS_MAJOR_GRID_ID = \\\n \"the_x_axis_major_tick_\", \"the_x_axis_major_ticklabel_\", \"the_x_axis_major_tickline_\", \"the_x_axis_major_gridline_\"\n Y_AXIS_MAJOR_TICK_ID, Y_AXIS_MAJOR_TICKLABEL_ID, Y_AXIS_MAJOR_TICKLINE_ID, Y_AXIS_MAJOR_GRID_ID = \\\n \"the_y_axis_major_tick_\", \"the_y_axis_major_ticklabel_\", \"the_y_axis_major_tickline_\", \"the_y_axis_major_gridline_\"\n X_AXIS_MINOR_TICK_ID, X_AXIS_MINOR_TICKLABEL_ID, X_AXIS_MINOR_TICKLINE_ID, X_AXIS_MINOR_GRID_ID = \\\n \"the_x_axis_minor_tick_\", \"the_x_axis_minor_ticklabel_\", \"the_x_axis_minor_tickline_\", \"the_x_axis_minor_gridline_\"\n Y_AXIS_MINOR_TICK_ID, Y_AXIS_MINOR_TICKLABEL_ID, Y_AXIS_MINOR_TICKLINE_ID, Y_AXIS_MINOR_GRID_ID = \\\n \"the_y_axis_minor_tick_\", \"the_y_axis_minor_ticklabel_\", \"the_y_axis_minor_tickline_\", \"the_y_axis_minor_gridline_\"\n POLAR_AXIS_TICKLABEL_ID = \"the_polar_axis_ticklabel_\"\n DRAWING_OBJECT_ID, OBJECT_TEXT_ID = \"the_drawing_object_\", \"the_object_text_\"\n\ndef asso_init():\n global ASSO_TYPE\n ASSO_TYPE = {\n 'self': -1,\n 'none': 0,\n 'relation': 1,\n 'measure': 2,\n 'similarity': 3\n }\n\ndef aesthetic_init():\n global ALL_LINE, ALL_MARKER, ALL_COLOR\n ALL_LINE = ['-', '--', '-.', ':']\n ALL_MARKER = ['.', ',', 'o', 'v', '^', '>', '<', 's', 'p', '*', 'h', 'H', 'D', 'd', '1', '2', '3', '4', 'x']\n ALL_COLOR = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']","repo_name":"weiyx16/VisualNet","sub_path":"Figure_elements_ID.py","file_name":"Figure_elements_ID.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36053559465","text":"def searchIndex(str):\n for i in range(3):\n for j in range(10):\n if keyboard[i][j] == str:\n return [i, j]\n\ndef distance(last, cur):\n dis = abs((last[0] - cur[0])) + abs((last[1] - cur[1]))\n return dis\n\n\nif __name__ == '__main__':\n keyboard = []\n keyboard.append(list(\"qwertyuiop\"))\n keyboard.append(list(\"asdfghjkl \"))\n keyboard.append(list(\"zxcvbnm \"))\n\n a = list(input().replace(' ', ''))\n start_L = searchIndex(a[0]) # 왼손 시작점\n start_R = searchIndex(a[1]) # 오른손 시작점\n\n b = list(input())\n ZOAC = []\n for i in b:\n ZOAC.append(searchIndex(i))\n\n sum = 0\n last_L, last_R = start_L, start_R\n for s in ZOAC:\n if s[0] <= 1:\n if s[1] <= 4:\n sum += distance(last_L, s) + 1\n last_L = s\n else:\n sum += distance(last_R, s) + 1\n last_R = s\n else:\n if s[1] <= 3:\n sum += distance(last_L, s) + 1\n last_L = s\n else:\n sum += distance(last_R, s) + 1\n last_R = s\n\n print(sum)","repo_name":"Sangmin627/AlgoStudy2023","sub_path":"창재/백준/구현/week2/20436/20436.py","file_name":"20436.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"20828826661","text":"from core.models import Libro\nfrom django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned\n\ndef DALC_getbookbyisbn(isbn) -> Libro:\n try:\n if isbn == 0:\n raise ObjectDoesNotExist\n libros:Libro\n libros = Libro.objects.get(isbn=isbn)\n return libros\n except ObjectDoesNotExist:\n raise f\"Error en DALC_GetusuariobyUser -> {ObjectDoesNotExist}\"\n except MultipleObjectsReturned:\n raise f\"Error en DALC_GetusuariobyUser -> {MultipleObjectsReturned}\"","repo_name":"AngelloFD/biblioteca_online","sub_path":"biblioteca_online/core/coredalc/librodalc.py","file_name":"librodalc.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23161174946","text":"import random\nfrom datetime import timedelta\nfrom enum import Enum\nfrom nation_data.coordination.retreive_and_convert import retreive_coords, convert_coords\nimport json as js\n\nfrom game.ai.nation_ai import NationAI\n\nflags = {\n \"1910\": \"../flags/netherlands/vector-illustration-of-netherlands-flag.jpg\",\n \"1914\": \"../flags/netherlands/vector-illustration-of-netherlands-flag.jpg\",\n \"1918\": \"../flags/netherlands/vector-illustration-of-netherlands-flag.jpg\",\n \"1932\": \"../flags/netherlands/vector-illustration-of-netherlands-flag.jpg\",\n \"1936\": \"../flags/netherlands/vector-illustration-of-netherlands-flag.jpg\",\n \"1939\": \"../flags/netherlands/vector-illustration-of-netherlands-flag.jpg\"\n}\n\nleader_images = {\"1910\": \"../leaders/netherlands/skirmer_1910.png\",\n \"1914\": \"../leaders/netherlands/250px-Pieter_Cort_van_der_Linden_1914-1918.jpg\",\n \"1918\": \"../leaders/netherlands/250px-Pieter_Cort_van_der_Linden_1914-1918.jpg\",\n \"1932\": \"../leaders/netherlands/Beerenbrouck_1932.jpg\",\n \"1936\": \"../leaders/netherlands/Hendrik_Colijn_(1925)_1936-1939.jpg\",\n \"1939\": \"../leaders/netherlands/Hendrik_Colijn_(1925)_1936-1939.jpg\"\n }\n\n\"\"\"Population Dictionaries\"\"\"\npopulation = {\n \"1910\": 5910000,\n \"1914\": 6270000,\n \"1918\": 6640000,\n \"1932\": 8060000,\n \"1936\": 8450000,\n \"1939\": 8760000\n}\n\n\"\"\"Political Dictionaries\"\"\"\nleaders = {\n \"1910\": \"Theo Heemskerk\",\n \"1914\": \"Pieter Cort der Linden\",\n \"1918\": \"Pieter Cort van der Linden\",\n \"1932\": \"Charles Ruijs de Beerenbrouck\",\n \"1936\": \"Hendrikus Colijn\",\n \"1939\": \"Hendrikus Colijn\"\n}\n\nmonarchs = {\n \"1910\": \"Wilhelmina\",\n \"1914\": \"Wilhelmina\",\n \"1918\": \"Wilhelmina\",\n \"1932\": \"Wilhelmina\",\n \"1936\": \"Wilhelmina\",\n \"1939\": \"Wilhelmina\"\n}\n\ngdp = {\n \"1910\": 865645049,\n \"1914\": 1111426098,\n \"1918\": 1844390540,\n \"1932\": 2118539364,\n \"1936\": 3213537630,\n \"1939\": 3201339327\n}\n\nclass EconomicState(Enum):\n RECESSION = 1\n DEPRESSION = 2\n EXPANSION = 3\n RECOVERY = 4\n\nclass Netherlands(NationAI):\n def __init__(self, globe):\n super().__init__(globe)\n self.date_checker = globe.date + timedelta(days=3)\n self.nation_color = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255))\n self.region = \"europe\"\n self.name = \"Netherlands\"\n # social variables\n \"\"\"population\"\"\"\n self.population = population[str(globe.date.year)]\n # political\n self.political_typology = \"Democratic\"\n self.leader = leaders[str(globe.date.year)]\n self.leader_image = leader_images[str(globe.date.year)]\n self.flag = flags[str(globe.date.year)]\n self.political_power = 200\n self.political_exponent = 1.56\n # economic\n self.current_gdp = gdp[str(globe.date.year)]\n \"\"\"Components of GDP\"\"\"\n self.consumer_spending = 200\n self.investment = 300\n self.government_spending = 350\n self.exports = 1000\n self.imports = 1200\n # other\n self.coordinates = []\n self.land = [\"Dutch East Indies\", \"Netherlands\", \"Netherlands Antilles\"]\n self.foreign_relations = {\"foreign relations\": []}\n def establish_foreign_objectives(self):\n if self.date.year > 1918:\n objectives_enemy = [\"Contain Germany\", \"Contain Italy\", \"Contain Russia\", \"Contain Bulgaria\",\n \"Contain Japan\"]\n objectives_allies = [\"Improve relations with United States\", \"Improve relations with France\",\n \"Improve relations with Canada\", \"Improve relations with Belgium\",\n \"Improve relations with Luxembourg\", \"Improve relations with Great Britain\"]\n\n for enemy in objectives_enemy:\n self.objectives[\"objectives\"][0]['foreign'].append(enemy)\n\n for ally in objectives_allies:\n self.objectives[\"objectives\"][0]['foreign'].append(ally)\n def establish_map_coordinates(self):\n file_path = 'C:/Users/wilbu/Desktop/Capstone-Project/nation_data/nation.json'\n with open(file_path, 'r') as file:\n nation_json = js.load(file)\n\n for land in range(0, len(self.land)):\n for i in range(0, len(nation_json['countries'])):\n if self.land[land] == nation_json['countries'][i]['nation_name']:\n self.coordinates.append((nation_json['countries'][i]['coordinates']))\n self.coordinates = (retreive_coords(self.coordinates))","repo_name":"BWilb/Capstone-Project","sub_path":"nation_state/europe/netherlands/netherlands_ai.py","file_name":"netherlands_ai.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41633934876","text":"#!/usr/bin/env python3\n\nfrom pycons3rt3.cons3rtapi import Cons3rtApi\n\nc = Cons3rtApi(config_file='/path/to/config.json')\n\nc.set_project_token('Project Name')\n\nidentity = c.create_host_identity(\n dr_id=12345,\n host_id=6789,\n service_type='BUCKET',\n service_identifier='testbucket-12345678910'\n)\n\nprint(identity)\n","repo_name":"cons3rt/pycons3rt3","sub_path":"scripts/create_identity.py","file_name":"create_identity.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"39364446599","text":"import json\nimport requests\nfrom utils.utils import anti_https_warnings\nimport yaml\n\n\nclass Admin(object):\n api_provider = '百度'\n ak = ''\n sk = ''\n\n @anti_https_warnings\n def accessToken(self, from_config: bool = True) -> str:\n \"\"\"\n 获取调用百度OCR api所必需的token\n :return:token\n \"\"\"\n\n # 走本地配置\n if from_config is True:\n with open('../config/admin.yml', 'rb') as f:\n data = yaml.load(f)\n if data:\n self.ak = data.get('api_key')\n self.sk = data.get('secret_key')\n\n\n url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'\n res = requests.get(url=url.format(self.ak, self.sk), verify=False, timeout=10)\n\n return res.json().get('access_token')\n\n def __repr__(self):\n obj_data = {'aip_provider': self.api_provider, 'api_ak': self.ak, 'api_sk': self.sk}\n return json.dumps(obj_data, ensure_ascii=False)\n\n\nif __name__ == '__main__':\n admin = Admin()\n print(admin.accessToken())\n","repo_name":"amoyshmily/learning","sub_path":"Projects/screenOCR/obj/Admin.py","file_name":"Admin.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37530878044","text":"import json\nimport sys\nfrom pathlib import Path\n\nimport typer\n\napp = typer.Typer()\n\n\ndef _write_files(\n seq_root: Path, min_flow: float, max_flow: float, selected_keys: list[str], cam_name: str\n):\n\n if min_flow > 0:\n with open(seq_root / \"flow_median.json\", encoding=\"utf-8\") as fp:\n flow_medians = json.load(fp)\n else:\n flow_medians = {}\n\n image_dir = seq_root / \"image\" / cam_name\n basenames = sorted([x.stem for x in image_dir.glob(\"*.jpg\")])\n\n files_list = []\n for bname in basenames:\n files = {}\n for key in [\n \"gt_depth\",\n ]:\n if key in selected_keys:\n files[key] = seq_root / key / cam_name / f\"{bname}.png\"\n\n for key in [\n \"image\",\n ]:\n if key in selected_keys:\n files[key] = seq_root / key / cam_name / f\"{bname}.jpg\"\n\n if \"meta\" in selected_keys:\n files[\"meta\"] = seq_root / f\"{cam_name}.json\"\n\n for key, val in files.items():\n assert val.is_file(), val\n files[key] = str(val)\n\n if min_flow > 0:\n\n # Scan prev 3 frames\n accum = 0\n prev_images = []\n for offset in range(-1, -4, -1):\n flow = flow_medians.get(f\"{int(bname)+offset:010d}\")\n if flow is None:\n break\n\n accum += flow\n if accum > min_flow:\n prev_images.append(\n str(seq_root / \"image\" / cam_name / f\"{int(bname)+offset:010d}.jpg\")\n )\n if accum > max_flow:\n break\n if len(prev_images) == 0:\n continue\n\n # Scan next 3 frames\n accum = 0\n next_images = []\n for offset in range(1, 4):\n flow = flow_medians.get(f\"{int(bname)+offset-1:010d}\")\n if flow is None:\n break\n\n accum += flow\n if accum > min_flow:\n next_images.append(\n str(seq_root / \"image\" / cam_name / f\"{int(bname)+offset:010d}.jpg\")\n )\n if accum > max_flow:\n break\n if len(next_images) == 0:\n continue\n\n # Add adjacent frames to files\n files[\"prev_images\"] = prev_images\n files[\"next_images\"] = next_images\n\n files_list.append(files)\n else:\n files_list.append(files)\n\n return files_list\n\n\ndef write_files(\n data_root: Path,\n min_flow: float,\n max_flow: float,\n selected_keys: list[str],\n out_json_fname: str,\n):\n seq_roots = sorted(x for x in data_root.iterdir() if x.is_dir())\n\n files_list = []\n for it, seq_root in enumerate(seq_roots):\n\n sys.stdout.write(f\"\\r{it+1}/{len(seq_roots)}: {seq_root.name}\")\n sys.stdout.flush()\n\n cam_list = [x.name for x in (seq_root / \"image\").iterdir() if x.is_dir()]\n for cam_name in cam_list:\n files_list += _write_files(seq_root, min_flow, max_flow, selected_keys, cam_name)\n print(\"\")\n\n json_path = SPLITS_ROOT / out_json_fname\n with open(json_path, \"w\", encoding=\"utf-8\") as fp:\n json.dump(files_list, fp, indent=4, sort_keys=True)\n print(\"Writing Done\", json_path)\n\n\n@app.command()\ndef write_kitti_depth_train_dynamic():\n data_root = Path(\"Data\") / \"KITTI_DEPTH_train\"\n write_files(\n data_root,\n min_flow=2.5,\n max_flow=2.5,\n selected_keys=[\"image\", \"meta\"],\n out_json_fname=\"kitti_depth_train_dynamic.json\",\n )\n\n\n@app.command()\ndef write_nuscenes_dynamic():\n data_root = Path(\"Data\") / \"NUSCENES\"\n write_files(\n data_root,\n min_flow=1.5,\n max_flow=1.5,\n selected_keys=[\"image\", \"meta\"],\n out_json_fname=\"nuscenes_dynamic.json\",\n )\n\n\n@app.command()\ndef write_ddad_dynamic():\n data_root = Path(\"Data\") / \"DDAD_DEPTH\"\n write_files(\n data_root,\n min_flow=1.5,\n max_flow=1.5,\n selected_keys=[\"image\", \"meta\"],\n out_json_fname=\"ddad_depth_dynamic.json\",\n )\n\n\n@app.command()\ndef write_waymo_train_dynamic():\n data_root = Path(\"Data\") / \"WAYMO_train\"\n write_files(\n data_root,\n min_flow=1.5,\n max_flow=1.5,\n selected_keys=[\"image\", \"meta\"],\n out_json_fname=\"waymo_train_dynamic.json\",\n )\n\n\n@app.command()\ndef write_season_depth_train_dynamic():\n data_root = Path(\"Data\") / \"SeasonDepth_train\"\n write_files(\n data_root,\n min_flow=1.5,\n max_flow=1.5,\n selected_keys=[\"image\", \"meta\"],\n out_json_fname=\"season_depth_train_dynamic.json\",\n )\n\n\n@app.command()\ndef write_season_depth_val_dynamic():\n data_root = Path(\"Data\") / \"SeasonDepth_val\"\n write_files(\n data_root,\n min_flow=1.5,\n max_flow=1.5,\n selected_keys=[\"image\", \"meta\"],\n out_json_fname=\"season_depth_val_dynamic.json\",\n )\n\n\n@app.command()\ndef write_season_depth_val():\n data_root = Path(\"Data\") / \"SeasonDepth_val\"\n write_files(\n data_root,\n min_flow=0.0,\n max_flow=0.0,\n selected_keys=[\"image\", \"gt_depth\", \"meta\"],\n out_json_fname=\"season_depth_val.json\",\n )\n\n\nif __name__ == \"__main__\":\n SPLITS_ROOT = Path(\"Data\") / \"splits\"\n SPLITS_ROOT.mkdir(exist_ok=True)\n\n app()\n","repo_name":"jaehyuck0103/season_depth_submission","sub_path":"scripts/dataset_gen/gen_splits.py","file_name":"gen_splits.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"28642493799","text":"from django.db import models\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User\nfrom django.db.models import Avg\nfrom geoposition.fields import GeopositionField\n\n\nimport os\nimport uuid\n\nRATING_CHOICES = (\n\t(0, 'None'),\n\t(1, '*'),\n\t(2, '**'),\n\t(3, '***'),\n\t(4, '****'),\n\t(5, '*****'),\n\t)\n\nYESNO_CHOICES = (\n\t(1, 'No'),\n\t(2, 'Yes'),\n\t)\n\nGENDER_CHOICES = (\n\t(1, 'Male'),\n\t(2, 'Female'),\n\t(3, 'Other'),\n\t)\n\ndef upload_to_location(instance, filename):\n blocks = filename.split('.')\n ext = blocks[-1]\n filename = \"%s.%s\" % (uuid.uuid4(), ext)\n instance.title = blocks[0]\n return os.path.join('uploads/', filename)\n\ndef upload_to_profile(instance, filename):\n blocks = filename.split('.')\n ext = blocks[-1]\n filename = \"%s.%s\" % (uuid.uuid4(), ext)\n instance.title = blocks[0]\n return os.path.join('profiles/', filename)\n\n# Create your models here.\n\nclass Location(models.Model):\n\ttitle = models.CharField(max_length=300, verbose_name='Name of Your Gym')\n\tdescription = models.TextField(null=True, blank=True, verbose_name='Description of Your Gym')\n\taddress = models.CharField(null=True, blank=True, max_length=300, verbose_name='Address')\n\tcity = models.CharField(null=True, blank=True, max_length=300, verbose_name='City')\n\tstate = models.CharField(null=True, blank=True, max_length=300, verbose_name='State')\n\tzipcode = models.CharField(null=True, blank=True, max_length=300, verbose_name='Zip Code')\n\tposition = GeopositionField(null=True, blank=True)\n\tphone = models.CharField(null=True, blank=True, max_length=300, verbose_name='Phone')\n\thours = models.CharField(null=True, blank=True, max_length=300, verbose_name='Hours')\n\timage_file = models.ImageField(upload_to=upload_to_location, null=True, blank=True, verbose_name='Image')\n\tshowers = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Showers')\n\tkids_area = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Kids Area')\n\tdrop_ins = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Drop Ins')\n\tlifting_platforms = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Lifting Platforms')\n\tcrossfit_kids = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='CrossFit Kids')\n\twomens_only = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Womens Only Classes')\n\tcorporate_training = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Corporate Training')\n\tspec_youth = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Youth Training')\n\tspec_senior = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Senior Training')\n\tspec_nutrition = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Nutrition')\n\tspec_weightmgmt = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Weight Management')\n\tspec_injuryrec = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Injury Recovery')\n\tspec_sporttrain = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Sport Specific Training')\n\tspec_oly = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True, verbose_name='Olympic Style Weightlifting')\n\tcreated_at = models.DateTimeField(auto_now_add=True)\n\n\tdef __unicode__(self):\n\t\treturn self.title\n\n\tdef get_absolute_url(self):\n\t\treturn reverse(viewname=\"location_list\", args=[self.id])\n\n\tdef get_average_rating(self):\n\t\taverage = self.review_set.all().aggregate(Avg('rating'))['rating__avg']\n\t\tif average == None:\n\t\t\treturn average\n\t\telse:\n\t\t\treturn int(average)\n\n\tdef get_average_parking(self):\n\t\taverage = self.review_set.all().aggregate(Avg('parking'))['parking__avg']\n\t\tif average == None:\n\t\t\treturn average\n\t\telse:\n\t\t\treturn int(average)\n\n\tdef get_average_trainers(self):\n\t\taverage = self.review_set.all().aggregate(Avg('trainers'))['trainers__avg']\n\t\tif average == None:\n\t\t\treturn average\n\t\telse:\n\t\t\treturn int(average)\n\n\tdef get_average_friendliness(self):\n\t\taverage = self.review_set.all().aggregate(Avg('friendliness'))['friendliness__avg']\n\t\tif average == None:\n\t\t\treturn average\n\t\telse:\n\t\t\treturn int(average)\n\n\tdef get_average_intensity(self):\n\t\taverage = self.review_set.all().aggregate(Avg('intensity'))['intensity__avg']\n\t\tif average == None:\n\t\t\treturn average\n\t\telse:\n\t\t\treturn int(average)\n\n\tdef get_reviews(self):\n\t\treturn self.review_set.all()\n\nclass Review(models.Model):\n\tlocation = models.ForeignKey(Location)\n\tuser = models.ForeignKey(User)\n\tdescription = models.TextField(null=True, blank=True)\n\trating = models.IntegerField(choices=RATING_CHOICES, null=True, blank=True)\n\ttrainers = models.IntegerField(choices=RATING_CHOICES, null=True, blank=True)\n\tparking = models.IntegerField(choices=RATING_CHOICES, null=True, blank=True)\n\tfriendliness = models.IntegerField(choices=RATING_CHOICES, null=True, blank=True)\n\tintensity = models.IntegerField(choices=RATING_CHOICES, null=True, blank=True)\n\tcreated_at = models.DateTimeField(auto_now_add=True)\n\nclass UserProfile(models.Model):\n\t# Links UserProfile to a User model instance.\n\tuser = models.OneToOneField(User)\n\n\t# Additional attributes for User Profile\n\tage = models.IntegerField(null=True, blank=True, verbose_name='Age')\n\tgender = models.IntegerField(choices=GENDER_CHOICES, null=True, blank=True, verbose_name='Gender')\n\tprofile_image = models.ImageField(upload_to=upload_to_profile, null=True, blank=True, verbose_name='Profile Image')\n\n\t# Override the __unicode__() method to return out something meaningful\n\tdef __unicode__(self):\n\t\treturn self.user\n\n\n","repo_name":"theperfectfuel/boxapp","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5734,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"38668715674","text":"from datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\nfrom odoo import api, fields, models, SUPERUSER_ID, _\nfrom odoo.osv import expression\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT\nfrom odoo.tools.float_utils import float_compare\nfrom odoo.exceptions import UserError, AccessError\nfrom odoo.tools.misc import formatLang\nfrom odoo.addons import decimal_precision as dp\n\n\nclass inherit_AccountInvoice(models.Model):\n _inherit = 'account.invoice'\n\n \n def _prepare_invoice_line_from_po_line(self, line):\n if line.product_id.purchase_method == 'purchase':\n qty = line.product_qty - line.qty_invoiced\n else:\n qty = line.qty_received - line.qty_invoiced\n if float_compare(qty, 0.0, precision_rounding=line.product_uom.rounding) <= 0:\n qty = 0.0\n taxes = line.taxes_id\n invoice_line_tax_ids = line.order_id.fiscal_position_id.map_tax(taxes, line.product_id, line.order_id.partner_id)\n invoice_line = self.env['account.invoice.line']\n date = self.date or self.date_invoice\n data = {\n 'purchase_line_id': line.id,\n 'name': line.order_id.name + ': ' + line.name,\n 'origin': line.order_id.origin,\n 'uom_id': line.product_uom.id,\n 'product_id': line.product_id.id,\n 'account_id': invoice_line.with_context({'journal_id': self.journal_id.id, 'type': 'in_invoice'})._default_account(),\n 'price_unit': line.order_id.currency_id._convert(\n line.price_unit, self.currency_id, line.company_id, date or fields.Date.today(), round=False),\n 'quantity': qty,\n 'discount': 0.0,\n 'account_analytic_id': line.account_analytic_id.id,\n 'analytic_tag_ids': line.analytic_tag_ids.ids,\n 'invoice_line_tax_ids': invoice_line_tax_ids.ids\n }\n account = invoice_line.get_invoice_line_account('in_invoice', line.product_id, line.order_id.fiscal_position_id, self.env.user.company_id)\n if account:\n # dn cut to budget\n # data['account_id'] = line.budget_line_id.general_budget_id.account_id.id\n # data['budget_line_id'] = line.budget_line_id.id\n # dn cut to budget\n \n data['account_id'] = account.id\n return data\n\n @api.multi\n def action_invoice_open(self):\n # lots of duplicate calls to action_invoice_open, so we remove those already open\n\n # kondisi pada saat validate vendor bill\n if self.type == 'in_invoice':\n print('type in_invoice')\n for line_invoice in self.invoice_line_ids:\n print(line_invoice.product_id.is_asset,' asset product')\n print(line_invoice.product_id.product_tmpl_id.is_asset,' asset template product')\n print(len(line_invoice.asset_category_id),' id asset')\n\n # product yg merupakan asset harus memiliki kategory asset pada saat validate vendor bill\n if (line_invoice.product_id.is_asset==True or line_invoice.product_id.product_tmpl_id.is_asset==True) and len(line_invoice.asset_category_id) <= 0:\n raise UserError(_('Item '+line_invoice.product_id.name+' must have asset category !'))\n\n # exit()\n\n # dn cut cek to budget\n # cek apakah budget masih ada\n # self.env.cr.execute(\"\"\"\n # SELECT DISTINCT budget_line_id,sum(price_subtotal) as sum_subtotal\n # FROM\n # account_invoice_line\n # WHERE\n # invoice_id = %s\n # GROUP BY budget_line_id\"\"\"%(int(self.id)))\n # line_distinct = self.env.cr.dictfetchall()\n\n # for line in line_distinct:\n # print(line,' line')\n # print(line['budget_line_id'],' line2')\n # budget = self.env['crossovered.budget.lines'].search([('id', '=', int(line['budget_line_id']))])\n # print(budget,' budget')\n # planned_budget = budget.planned_amount\n # sum_subtotal_pr = line['sum_subtotal']\n # new_practical_amount = budget.practical_amount-sum_subtotal_pr\n\n # print(planned_budget,' plan')\n # print(sum_subtotal_pr,' sum_subtotal_pr')\n # print(new_practical_amount,' new_practical_amount') \n\n # # exit()\n\n # if new_practical_amount < planned_budget:\n # raise UserError(_('Value from '+str(budget.name)+' is not enough, plese use another budget !'))\n\n # dn cut cek to budget\n\n\n to_open_invoices = self.filtered(lambda inv: inv.state != 'open')\n\n # print(to_open_invoices,' open inv')\n # exit()\n\n if to_open_invoices.filtered(lambda inv: not inv.partner_id):\n raise UserError(_(\"The field Vendor is required, please complete it to validate the Vendor Bill.\"))\n if to_open_invoices.filtered(lambda inv: inv.state != 'draft'):\n raise UserError(_(\"Invoice must be in draft state in order to validate it.\"))\n if to_open_invoices.filtered(lambda inv: float_compare(inv.amount_total, 0.0, precision_rounding=inv.currency_id.rounding) == -1):\n raise UserError(_(\"You cannot validate an invoice with a negative total amount. You should create a credit note instead.\"))\n if to_open_invoices.filtered(lambda inv: not inv.account_id):\n raise UserError(_('No account was found to create the invoice, be sure you have installed a chart of account.'))\n to_open_invoices.action_date_assign()\n to_open_invoices.action_move_create()\n return to_open_invoices.invoice_validate()\n\n\nclass inherit_AccountInvoiceLine(models.Model):\n \"\"\" Override AccountInvoice_line to add the link to the purchase order line it is related to\"\"\"\n _inherit = 'account.invoice.line'\n\n budget_line_id = fields.Many2one('crossovered.budget.lines', string='Budget', store=True,domain=\"[('crossovered_budget_id.state','=','validate')]\")\n account_asset_id = fields.Many2one('account.account', string='Account Asset',related='asset_category_id.account_asset_id', domain=[('deprecated', '=', False)],\n help=\"The income or expense account related to the selected product.\")\n capex = fields.Boolean(string='Capex', store=True,related='budget_line_id.capex')\n\n @api.onchange('asset_category_id')\n def onchange_asset_category_id(self):\n if self.invoice_id.type == 'out_invoice' and self.asset_category_id:\n self.account_asset_id = self.asset_category_id.account_asset_id.id\n elif self.invoice_id.type == 'in_invoice' and self.asset_category_id:\n self.account_asset_id = self.asset_category_id.account_asset_id.id\n\n\n @api.one\n def asset_create(self):\n if self.asset_category_id:\n vals = {\n 'name': self.name,\n 'code': self.invoice_id.number or False,\n 'category_id': self.asset_category_id.id,\n 'value': self.price_subtotal_signed,\n 'partner_id': self.invoice_id.partner_id.id,\n 'company_id': self.invoice_id.company_id.id,\n 'currency_id': self.invoice_id.company_currency_id.id,\n 'date': self.invoice_id.date_invoice,\n 'invoice_id': self.invoice_id.id,\n }\n print(vals,'vals')\n\n\n changed_vals = self.env['account.asset.asset'].onchange_category_id_values(vals['category_id'])\n print(changed_vals,' changed_vals')\n \n vals.update(changed_vals['value'])\n asset = self.env['account.asset.asset'].create(vals)\n if self.asset_category_id.open_asset:\n asset.validate()\n return True","repo_name":"rachmadona48/inagro","sub_path":"inagro_budget/models/inherit_invoice.py","file_name":"inherit_invoice.py","file_ext":"py","file_size_in_byte":7868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29057983207","text":"from contextlib import contextmanager\nimport json\nfrom unittest import mock\nfrom datetime import datetime as dt\n\nimport pytest\n\nfrom billing.monthclosing.operations.instantiate_event_artifact.lib.main import (\n main,\n r_objs,\n)\n\n\n@contextmanager\ndef does_not_raise():\n yield\n\n\nclass MockParams:\n def __init__(self, **params):\n self.params = params\n\n def get_parameters(self):\n return self.params\n\n\ndef patched_main(**params):\n with mock.patch('nirvana.job_context.context') as nv:\n nv.return_value = MockParams(**params)\n main()\n\n return\n\n\n@pytest.mark.parametrize(\n 'pre_check_allowed_statuses, user_time, artifact_attributes, last_instance, expectation, error',\n [\n (\n ['ACTIVE'],\n '2021-11-09 10:00:00',\n {'value': '1'},\n mock.Mock(\n metadata=mock.Mock(\n type_='/yandex.reactor.artifact.EventArtifactValueProto',\n dict_obj={'value': '1'},\n ),\n status=r_objs.ArtifactInstanceStatus.ACTIVE,\n user_time=dt(2021, 11, 9, 10),\n ),\n does_not_raise(),\n None,\n ),\n (\n ['ACTIVE'],\n '2021-11-09 10:00:00',\n {'value': '1'},\n mock.Mock(\n metadata=mock.Mock(\n type_='/yandex.reactor.artifact.IntArtifactValueProto',\n dict_obj={'value': '1'},\n ),\n status=r_objs.ArtifactInstanceStatus.DEPRECATED,\n user_time=dt(2021, 11, 9, 10),\n ),\n does_not_raise(),\n None,\n ),\n (\n [],\n '',\n {'value': '1'},\n mock.Mock(\n metadata=mock.Mock(\n type_='/yandex.reactor.artifact.IntArtifactValueProto',\n dict_obj={'value': '1'},\n ),\n status=r_objs.ArtifactInstanceStatus.DEPRECATED,\n user_time=dt(2021, 11, 9, 10),\n ),\n pytest.raises(RuntimeError),\n \"Option 'user_time' is required\",\n ),\n (\n ['ACTIVE'],\n '2021-11-09 10:00:00',\n {'value': '1'},\n mock.Mock(\n metadata=mock.Mock(\n type_='/yandex.reactor.artifact.IntArtifactValueProto',\n dict_obj={'value': '1'},\n ),\n status=r_objs.ArtifactInstanceStatus.ACTIVE,\n user_time=dt(2021, 11, 9, 10),\n ),\n pytest.raises(RuntimeError),\n 'Incorrect artifact type, expected: EventArtifactValueProto, got: IntArtifactValueProto',\n ),\n ],\n)\ndef test_main(\n pre_check_allowed_statuses,\n user_time,\n artifact_attributes,\n last_instance,\n expectation,\n error,\n):\n params = {\n 'pre_check_allowed_statuses': pre_check_allowed_statuses,\n 'user_time': user_time,\n 'artifact_path': 0,\n 'oauth_token': 'test',\n 'artifact_attributes': json.dumps(artifact_attributes),\n 'environment': 'testing',\n }\n\n for k in ('user_time', 'pre_check_allowed_statuses'):\n if not params.get(k):\n params.pop(k)\n\n with expectation as exc, mock.patch(\n 'reactor_client.reactor_api.ArtifactInstanceEndpoint'\n ) as aie_mock:\n artifact_instance_endpoint = aie_mock.return_value\n artifact_instance_endpoint.last = lambda artifact_identifier: last_instance\n\n patched_main(**params)\n\n if error:\n assert error in str(exc)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"billing/tests/func/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"3337787541","text":"from virtualisation.clock.abstractclock import AbstractClock\n\n__author__ = 'Marten Fischer (m.fischer@hs-osnabrueck.de)'\n\nfrom abstractannotation import AbstractAnnotation\nimport saopy\nimport uuid\nimport rdflib\n\nclass GenericAnnotation(AbstractAnnotation):\n \"\"\"\n Class to annotate observation.\n \"\"\"\n # avoid namespace prefixes in the exported graph, that are not required.\n # namespaceBindings = {\n # # \"owl\":\"http://www.w3.org/2002/07/owl#\",\n # \"sao\": \"http://purl.oclc.org/NET/UNIS/sao/sao#\",\n # # \"xs\": \"http://www.w3.org/2001/XMLSchema\",\n # # \"skos\": \"http://www.w3.org/2004/02/skos/core#\",\n # \"qoi\": \"http://purl.oclc.org/NET/UASO/qoi#\",\n # # \"xml\": \"http://www.w3.org/XML/1998/namespace\",\n # # \"rdfs\": \"http://www.w3.org/2000/01/rdf-schema#\",\n # # \"wot\": \"http://xmlns.com/wot/0.1/\",\n # # \"daml\": \"http://www.daml.org/2001/03/daml+oil#\",\n # \"muo\": \"http://purl.oclc.org/NET/muo/muo#\",\n # \"foaf\": \"http://xmlns.com/foaf/0.1/\",\n # # \"DUL\": \"http://www.loa-cnr.it/ontologies/DUL.owl#\",\n # # \"time\": \"http://www.w3.org/2006/time#\",\n # \"dc\": \"http://purl.org/dc/elements/1.1/\",\n # \"ssn\": \"http://purl.oclc.org/NET/ssnx/ssn#\",\n # \"ces\": \"http://www.insight-centre.org/ces#\",\n # # \"tzont\": \"http://www.w3.org/2006/timezone#\",\n # # \"go\": \"http://www.daml.org/services/owl-s/1.2/Grounding.owl#\",\n # # \"geo\": \"http://www.w3.org/2003/01/geo/wgs84_pos#\",\n # # \"so\": \"http://www.daml.org/services/owl-s/1.2/Service.owl#\",\n # # \"sp\": \"http://www.daml.org/services/owl-s/1.2/ServiceParameter.owl#\",\n # # \"rdf\": \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\",\n # # \"xsd\": \"http://www.w3.org/2001/XMLSchema#\",\n # \"prov\": \"http://www.w3.org/ns/prov#\",\n # \"tl\": \"http://purl.org/NET/c4dm/timeline.owl#\",\n # \"ct\": \"http://ict-citypulse.eu/city#\"\n # }\n\n allowedNamespaceBindings = [\"sao\", \"muo\", \"ssn\", \"ces\", \"geo\", \"owlss\", \"prov\", \"tl\", \"qoi\"]\n namespaceBindings = {}\n for anb in allowedNamespaceBindings:\n namespaceBindings[anb] = saopy.model.namespaceBindings[anb]\n namespaceBindings[\"ct\"] = \"http://ict-citypulse.eu/city#\"\n\n QOI_METRIC_FUNCTION_MAP = {} #{'Correctness': , 'Latency': , 'Age': , 'Frequency': , 'Completeness': }\n\n def annotateObservation(self, data, sensordescription, clock, quality):\n saoOut = saopy.SaoInfo()\n saoOut.namespaceBindings = GenericAnnotation.namespaceBindings\n\n if not isinstance(data, list):\n data = [data]\n if not isinstance(quality, list):\n quality = [quality]\n\n # for data_item in data:\n for i in range(0, len(data)):\n data_item = data[i]\n quality_item = quality[i] if i < len(quality) else None\n samplingTime = None\n resultTime = None\n qualityProperties = []\n if len(data_item.fields) > 0:\n # prepare sampling and result time\n firstField = data_item[data_item.fields[0]]\n samplingTime = saopy.tl.Instant(\"%s/SamplingTime-%s\" % (sensordescription.fullSensorID, firstField.observationID))\n samplingTime.at = rdflib.Literal(str(firstField.observationSamplingTime), datatype=rdflib.XSD.dateTime) #firstField.observationSamplingTime\n saoOut.add(samplingTime)\n\n resultTime = saopy.tl.Instant(\"%s/ResultTime-%s\" % (sensordescription.fullSensorID, firstField.observationID))\n if sensordescription.isTimestampedStream():\n resultTime.at = rdflib.Literal(str(firstField.observationResultTime), datatype=rdflib.XSD.dateTime)\n else:\n resultTime.at = rdflib.Literal(str(firstField.observationSamplingTime), datatype=rdflib.XSD.dateTime)\n saoOut.add(resultTime)\n\n # prepare the quality properties\n if quality_item:\n for qoiName in quality_item:\n qoiMetric = getattr(saopy.qoi, qoiName)(\"%scity#%s-%s\" % (sensordescription.namespace, qoiName, data_item[data_item.fields[0]].observationID))\n setattr(qoiMetric, \"hasRatedQuality\", \"%.3f\" % float(quality_item[qoiName].ratedValue))\n setattr(qoiMetric, \"hasAbsoluteQuality\", \"%.3f\" % float(quality_item[qoiName].absoluteValue))\n setattr(qoiMetric, \"hasUnitOfMeasurement\", saopy.muo.UnitOfMeasurement(\"%s\" % quality_item[qoiName].unit))\n qualityProperties.append(qoiMetric)\n saoOut.add(qoiMetric)\n\n # sensor = saopy.ssn.Sensor(sensordescription.namespace + sensordescription.sensorName)\n sensor = saopy.ssn.Sensor(sensordescription.namespace + \"SensorID-\" + sensordescription.uuid)\n\n for fieldname in data_item.fields:\n if sensordescription.isTimestampedStream() and fieldname == sensordescription.timestamp.inField:\n continue\n if \"skip_annotation\" in sensordescription.field[fieldname] and sensordescription.field[fieldname].skip_annotation:\n continue\n # TODO missing fields can not be annotated\n if not fieldname in data_item:\n continue\n field = data_item[fieldname]\n observation = saopy.sao.Point(\"%s/Observation-%s\" % (sensordescription.fullSensorID, field.observationID))\n observation.value = str(field.value)\n observation.observedBy = sensor\n\n if samplingTime: # in this case there should also be a result time\n observation.observationSamplingTime = samplingTime\n observation.observationResultTime = resultTime\n\n # if \"unit\" in field:\n if \"unit\" in sensordescription.field[fieldname]:\n mu = saopy.muo.UnitOfMeasurement(sensordescription.field[fieldname].unit)\n observation.hasUnitOfMeasurement = mu\n saoOut.add(mu)\n prop = saopy.ssn.Property(\"\".join([field.propertyURI, \"-\", sensordescription.uuid]))\n observation.observedProperty = prop\n saoOut.add(observation)\n\n # add quality data\n for qProperty in qualityProperties:\n observation.hasQuality.add(qProperty)\n\n return saopy.RDFInterface.exportRDFGraph(saoOut)\n\n def annotateAggregation(self, aggregationdata, sensordescription):\n saoOut = saopy.SaoInfo()\n saoOut.namespaceBindings = GenericAnnotation.namespaceBindings\n sensor = saopy.ssn.Sensor(sensordescription.fullSensorID)\n sensorproperty = saopy.ssn.Property(aggregationdata.data['field'].propertyURI)\n sensorproperty.description = aggregationdata.data['field'].propertyName\n sensor.observes.add(sensorproperty)\n\n interval = saopy.tl.Interval(sensordescription.namespace+\"timeinterval\")\n interval.beginsAtDateTime = str(aggregationdata.start)\n interval.endsAtDateTime = str(aggregationdata.end)\n\n aggregationId = sensordescription.namespace + \"Aggregation-\" + str(uuid.uuid4())\n if aggregationdata.aggregationMethod is 'dft':\n aggregation = saopy.sao.DiscreteFourierTransform(aggregationId)\n if aggregationdata.aggregationMethod is 'paa':\n aggregation = saopy.sao.PiecewiseAggregateApproximation(aggregationId)\n if aggregationdata.aggregationMethod is 'sensorsax':\n aggregation = saopy.sao.SensorSAX(aggregationId)\n else: #if aggregationdata.aggregationMethod is 'sax':\n aggregation = saopy.sao.SymbolicAggregateApproximation(aggregationId)\n aggregation.value = aggregationdata.graph\n aggregation.wasAttributedTo = sensorproperty\n aggregation.time = interval\n aggregation.alphabetsize\n aggregation.segmentsize = aggregationdata.size\n mu = saopy.muo.UnitOfMeasurement(sensordescription.namespace+'unit:'+ aggregationdata.data['field'].unit)\n aggregation.hasUnitOfMeasurement = mu\n\n saoOut.add(aggregation)\n saoOut.add(sensorproperty)\n saoOut.add(sensor)\n return saopy.RDFInterface.exportRDFGraph(saoOut)\n\n def annotateEvent(self, eventdata, eventdescription):\n saoOut = saopy.SaoInfo()\n saoOut.namespaceBindings = GenericAnnotation.namespaceBindings\n event = saopy.sao.StreamEvent(eventdescription.namespace + \"StreamEvent-\" + str(eventdata.ceID))\n event.openid = saopy.foaf.Document(eventdescription.namespace + str(eventdata.ceID))\n event.name = eventdata.ceName # uco:hasLabel\n\n location = saopy.prov.Location(eventdescription.namespace + \"Location\")\n #FIXME where to place to coordinates?\n location.description = eventdata.ceCoordinate # event:place as geo:SpatialThing\n event.atLocation = location\n\n \"\"\"\n @Marten Fischer: I am not sure if this is right,\n I will ask Thu what the description of the event is\n \"\"\"\n event.description = eventdata.ceType # uco:hasCategory (class)\n \"\"\"\n @Marten Fischer: Possibly ceTime contains more information\n than just the timestamp (e.g. start/end time). In that case,\n this needs to be parsed and annotated.\n @ DanielP: At the moment the timestamp is only a Long. Apparently\n there will be a 'StopEvent'.\n \"\"\"\n event.Timestamp = eventdescription.parseTimestamp(eventdata[eventdescription.timestamp.inField]).strftime(AbstractClock.format) # event:time as time:TemporalEntity\n \"\"\"\n @Marten Fischer: Do we have something which is equivalent\n to ceWeight in the ontology?\n @ Daniel P: I haven't seen one.\n \"\"\"\n agent = saopy.foaf.Agent(eventdescription.namespace + eventdescription.author)\n\n event.label = str(eventdata.ceLevel) # uco:hasLevel a xsd:integer\n\n event.creator = agent\n\n saoOut.add(event)\n saoOut.add(agent)\n saoOut.add(location)\n return saopy.RDFInterface.exportRDFGraph(saoOut)","repo_name":"CityPulse/Resource-Manager","sub_path":"virtualisation/annotation/genericannotation.py","file_name":"genericannotation.py","file_ext":"py","file_size_in_byte":10227,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"18669082157","text":"import os\nfrom glob import glob\nimport json\nimport cv2\n\nimport pyvista as pv\nimport numpy as np\nimport numpy.linalg as la\n\nDATASET_DIR = \"E:/A2D2/\"\nLIDAR_SENSORS = [\"cam_front_left\", \"cam_front_right\", \"cam_rear_center\", \"cam_side_left\", \"cam_side_right\"]\n#\"cam_front_center\", \nEPSILON = 1.0e-10 # norm should not be small\n\ndef get_origin_of_a_view(view):\n return view['origin']\n\ndef get_axes_of_a_view(view):\n x_axis = view['x-axis']\n y_axis = view['y-axis']\n \n x_axis_norm = la.norm(x_axis)\n y_axis_norm = la.norm(y_axis)\n \n if (x_axis_norm < EPSILON or y_axis_norm < EPSILON):\n raise ValueError(\"Norm of input vector(s) too small.\")\n \n # normalize the axes\n x_axis = x_axis / x_axis_norm\n y_axis = y_axis / y_axis_norm\n \n # make a new y-axis which lies in the original x-y plane, but is orthogonal to x-axis\n y_axis = y_axis - x_axis * np.dot(y_axis, x_axis)\n \n # create orthogonal z-axis\n z_axis = np.cross(x_axis, y_axis)\n \n # calculate and check y-axis and z-axis norms\n y_axis_norm = la.norm(y_axis)\n z_axis_norm = la.norm(z_axis)\n \n if (y_axis_norm < EPSILON) or (z_axis_norm < EPSILON):\n raise ValueError(\"Norm of view axis vector(s) too small.\")\n \n # make x/y/z-axes orthonormal\n y_axis = y_axis / y_axis_norm\n z_axis = z_axis / z_axis_norm\n \n return x_axis, y_axis, z_axis\n\ndef get_transform_to_global(view):\n # get axes\n x_axis, y_axis, z_axis = get_axes_of_a_view(view)\n \n # get origin \n origin = get_origin_of_a_view(view)\n transform_to_global = np.eye(4)\n \n # rotation\n transform_to_global[0:3, 0] = x_axis\n transform_to_global[0:3, 1] = y_axis\n transform_to_global[0:3, 2] = z_axis\n \n # origin\n transform_to_global[0:3, 3] = origin\n \n return transform_to_global\n\ndef get_transform_from_global(view):\n # get transform to global\n transform_to_global = get_transform_to_global(view)\n trans = np.eye(4)\n rot = np.transpose(transform_to_global[0:3, 0:3])\n trans[0:3, 0:3] = rot\n trans[0:3, 3] = np.dot(rot, -transform_to_global[0:3, 3])\n \n return trans\n\ndef transform_from_to(src, target):\n transform = np.dot(get_transform_from_global(target), \\\n get_transform_to_global(src))\n \n return transform\n\n\nif __name__ == \"__main__\":\n\n f = open(DATASET_DIR + \"/cams_lidars.json\")\n CONFIG = json.load(f)\n f.close()\n\n sequence_paths = [ os.path.dirname(path) for path in glob(DATASET_DIR + \"*/\")]\n\n for sequence_path in sequence_paths:\n\n sequence_path = os.path.basename(sequence_path)\n sequence_name = sequence_path.replace(\"_\", \"\")\n \n f = open(DATASET_DIR + \"/\" + sequence_name + \"_bus_signals.json\")\n BUS_SIGNAL = json.load(f)\n f.close()\n\n print(BUS_SIGNAL.keys())\n\n lidar_paths = dict()\n lidar_names = dict()\n LIDAR = dict()\n\n for lidar_sensor in LIDAR_SENSORS:\n lidar_paths[lidar_sensor] = glob(DATASET_DIR + \"/\" + sequence_path + \"/lidar/\" + lidar_sensor + \"/*.npz\")\n lidar_names[lidar_sensor] = [os.path.basename(path)[:-4][-9:] for path in lidar_paths[lidar_sensor]]\n for name, path in zip(lidar_names[lidar_sensor], lidar_paths[lidar_sensor]):\n if name in LIDAR:\n LIDAR[name][lidar_sensor] = path\n else: \n LIDAR[name] = { lidar_sensor: path }\n\n SYNC_NAMES = sorted(list(set.intersection(*map(set, lidar_names.values()))))\n\n for sync_name in SYNC_NAMES:\n\n lidar_data = LIDAR[sync_name]\n output_points = None\n\n for lidar_sensor in LIDAR_SENSORS: \n lidar_points = np.load(lidar_data[lidar_sensor])\n\n points = lidar_points[\"pcloud_points\"]\n\n src_view = CONFIG['cameras'][lidar_sensor[4:]]['view']\n\n vehicle_view = CONFIG['vehicle']['view']\n\n trans = transform_from_to(src_view, vehicle_view)\n points_hom = np.ones((points.shape[0], 4))\n points_hom[:, 0:3] = points\n points_trans = (np.dot(trans, points_hom.T)).T \n \n points = points_trans[:,0:3].astype(np.float16)\n\n if output_points is None:\n output_points = points\n else:\n output_points = np.concatenate((output_points, points))\n\n output_points = output_points\n\n print(sync_name, output_points.shape, output_points.dtype)\n\n # np.savez_compressed(DATASET_DIR + sequence_path + \"/lidar_360/\" + sync_name + \".npz\", points=output_points)\n\n # pdata = pv.PolyData(output_points.astype(np.float32))\n # pdata.plot(cmap='jet')\n\n\n grid = np.zeros((1000, 1000), dtype=np.uint8)\n\n points = output_points\n\n x = points[:, 0]\n y = points[:, 1]\n\n point2d = np.copy(points[:, :2])\n point2d = point2d * 10\n point2d = point2d.astype(int)\n point2d = point2d + 500\n\n point2d = point2d[point2d[:, 0] < 1000]\n point2d = point2d[point2d[:, 1] < 1000]\n\n grid[point2d[:, 0], point2d[:, 1]] = 1\n\n cv2.imshow(\"points\", grid * 255)\n cv2.waitKey(5)\n","repo_name":"n-rocher/3D-Consistency-Grid","sub_path":"a2d2/open-lidar.py","file_name":"open-lidar.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42498081235","text":"from django.core.exceptions import ObjectDoesNotExist\n\nfrom bdr_registry.models import Account, Company, Obligation\n\n\nclass CompanyMixin(object):\n def get_obligations(self, default=True, no_user=False):\n if not no_user:\n obligations = self.request.user and self.request.user.obligations.values()\n else:\n obligations = False\n default = True\n if default and not obligations:\n obligations = Obligation.objects.values()\n return [o[\"id\"] for o in obligations]\n\n def get_companies(self, default=True, no_user=False):\n o_ids = self.get_obligations(default=default, no_user=no_user)\n return Company.objects.filter(obligation__id__in=o_ids).all()\n\n def get_account(self, uid):\n try:\n return Account.objects.get(uid=uid)\n except ObjectDoesNotExist:\n return None\n\n def get_account_company(self, uid, obligation_code):\n account = self.get_account(uid)\n if account:\n try:\n return Company.objects.get(\n account=account, obligation__code=obligation_code\n )\n except ObjectDoesNotExist:\n return None\n\n def dispatch(self, request, *args, **kwargs):\n # if request.user and not request.user.obligations.count():\n # messages.warning(\n # request, _('You have no obligations assigned to this user')\n # )\n return super(CompanyMixin, self).dispatch(request, *args, **kwargs)\n","repo_name":"eea/bdr-registry","sub_path":"bdr_management/views/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"44179446983","text":"# Description: Borrowing the code that I wrote for the roller coaster program, and then adding successive if-statements :D & then further adding logical operators\n\n# Task: \n# Use logical operators to make tickets free for people going through their mid-life crisis\n# Ages b/w [45 - 55]\n\n# Declare variables\nbill = 0\n\nprint(\"Welcome to the rollercoaster!\")\nheight = int(input(\"What is your height in cm? \"))\n\nif height >= 120:\n print(\"You can ride the rollercoaster!\")\n age = int(input(\"What is your age? \"))\n if age < 12:\n bill = 5\n print(f\"Please pay ${bill}\")\n elif age <= 18:\n bill = 7\n print(f\"Please pay ${bill}\")\n elif age >= 45 and age <= 55:\n bill = 0\n print(\"Rest assured, everything will turn out fine, enjoy a free ride!!! :D\")\n else:\n bill = 12\n print(f\"Please pay ${bill}\")\n \n want_photo = (input(\"Do you want to take a picture? (y / n) \"))\n if want_photo == \"y\":\n bill += 3 # as the bill increments by $3 for the ticket\n \n print(f\"Please pay ${bill}\")\n\nelse:\n print(\"Sorry, you have to grow taller before you can ride :D\")\n","repo_name":"SM-7603/100-Days-Of-Code-Python-Edition","sub_path":"Day_03/08_logical_operators.py","file_name":"08_logical_operators.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26962263385","text":"\"\"\"\n781. Rabbits in Forest\n\nIn a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them.\n Those answers are placed in an array.\n\nReturn the minimum number of rabbits that could be in the forest.\n\nExamples:\nInput: answers = [1, 1, 2]\nOutput: 5\nExplanation:\nThe two rabbits that answered \"1\" could both be the same color, say red.\nThe rabbit than answered \"2\" can't be red or the answers would be inconsistent.\nSay the rabbit that answered \"2\" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.\n\nInput: answers = [10, 10, 10]\nOutput: 11\n\nInput: answers = []\nOutput: 0\nNote:\n\nanswers will have length at most 1000.\nEach answers[i] will be an integer in the range [0, 999].\n\nCompanies\nWish\n\"\"\"\n\nclass Solution(object):\n def numRabbits(self, answers):\n \"\"\"\n :type answers: List[int]\n :rtype: int\n \"\"\"\n result, mapr = 0, dict()\n for num in answers:\n # if num is 0, that means there no other rabbits of that color, so we add 1\n if num == 0:\n result += 1\n\n else:\n if num not in mapr:\n # this particular color is not asked so far, so we add num (for others) and 1 for that rabit\n mapr[num] = 1\n result += num + 1\n else:\n mapr[num] += 1\n # check if mapr[num] exceeds num that means there are other colors with the same count\n # for example [1, 1, 1] --> this means that there is red color rabits 2 and 1 blue color\n # [1, 1] --> means that there are 2 red color rabits\n if mapr[num] > num:\n mapr.pop(num)\n\n return result\n","repo_name":"tejamupparaju/LeetCode_Python","sub_path":"leet_code781.py","file_name":"leet_code781.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24061652524","text":"from datetime import date, datetime\n\nimport numpy as np\nimport pandas as pd\n\ndf = pd.DataFrame({\n 'a': [1, 2, 3],\n 'b': [2., 3., 4.],\n 'c': ['string1', 'string2', 'string3'],\n 'd': [date(2000, 1, 1), date(2000, 2, 1), date(2000, 3, 1)],\n 'e': [datetime(2000, 1, 1, 12, 0), datetime(2000, 1, 2, 12, 0), datetime(2000, 1, 3, 12, 0)]\n})\ndf_number = pd.DataFrame(np.random.randn(6, 4), index=pd.date_range(\"20130101\", periods=6), columns=list(\"ABCD\"))\ndf_left = pd.DataFrame({\"key\": [\"foo\", \"foo\"], \"lval\": [1, 2]})\ndf_right = pd.DataFrame({\"key\": [\"foo\", \"foo\"], \"rval\": [4, 5]})\n# %%\n# append rows\ndf = df.set_index(\"a\")\ndf_append_ignore_index = df.append(df, ignore_index=True) # index 포함 안함. 0부터 시작하는 index를 새로 만듬 [0,1,2,3,4,5]\ndf_append_with_index = df.append(df) # index도 포함하여, append됨. [1,2,3,1,2,3]\ndf_append_single_ignore_index = df.append({ # index disappear\n 'b': 2,\n 'c': 's1',\n 'd': date(2022, 1, 1),\n 'e': date(2022, 1, 1),\n}, ignore_index=True)\n\ndf_append_single_with_index = df.append(pd.DataFrame([{ # same index is added\n 'a': 1,\n 'b': 2,\n 'c': 's1',\n 'd': date(2022, 1, 1),\n 'e': date(2022, 1, 1),\n}]).set_index(\"a\"))\n\n# Concat\n# same with union() on spark\ndf_concat = pd.concat([df_append_with_index[:1], df_append_with_index[2:3], df_append_with_index[4:], df_append_with_index[4:]])\n","repo_name":"dss99911/ds-study","sub_path":"python/pandas/pandas_concat.py","file_name":"pandas_concat.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38402948979","text":"# N, M = map(int, input().split())\n\n# if M != N*3:\n# print(\"please enter the value of M which is equvalent of N*3.\")\n# exit()\n\n# # Top part of the door mat\n# for i in range(N//2):\n# pattern = '.|.'*(2*i+1)\n# print(pattern.center(M, '-'))\n\n# # Middle part of the door mat with 'WELCOME' written in the center\n# print('WELCOME'.center(M, '-'))\n\n# # Bottom part of the door mat\n# for i in range(N//2-1, -1, -1):\n# pattern = '.|.'*(2*i+1)\n# print(pattern.center(M, '-'))\n\n# size = int(input())\n# for i in range(1,size+1):\n# for j in range(1,i+1):\n# print(\"*\",end =\" \")\n# print()\ndef print_rangoli(size):\n import string\n alpha = string.ascii_lowercase\n n = size\n width = 4 * n - 3\n mid = width // 2\n res = []\n for i in range(n):\n left = \"-\".join(alpha[n-1:n-i-1:-1] + alpha[n-i-1:n])\n res.append(left[::-1] + left[1:])\n res = res[:n-1] + res[::-1]\n for i in res:\n print(i.center(width, '-'))\n\nif __name__ == '__main__':\n n = int(input())\n print_rangoli(n)\n","repo_name":"imlnr/hackerrank","sub_path":"rangolipattern.py","file_name":"rangolipattern.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28893573098","text":"from itertools import combinations\r\n\r\ndata = input().split()\r\nstring = ''.join(sorted(data[0]))\r\nk = int(data[1])\r\n\r\nfor i in range(1, k+1):\r\n comb = combinations(string, i)\r\n for x in comb:\r\n print(*x, sep = '')\r\n ","repo_name":"IvanMV/HackerRank_Tasks","sub_path":"PYTHON/itertools/itertools.combinations().py","file_name":"itertools.combinations().py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9996809906","text":"from tkinter import *\n\nwindow = Tk()\nwindow.title(\"angela first gui program\")\nwindow.minsize(width=500, height=300)\nwindow.config(padx=20, pady=20)\n\n\ndef button_clicked():\n new_text = my_input.get()\n my_label.config(text=new_text)\n\n\n# label\nmy_label = Label(text=\"I am a label\", font=(\"Arial\", 24, \"bold\"))\nmy_label[\"text\"] = \"some new text\"\n# or\nmy_label.config(text=\"label\")\nmy_label.grid(column=0, row=0)\n# any input value n the kwarg can easily be change as we would have change dictionary value.\n# new button\\\nbutton2 = Button(text=\"don't click me\")\nbutton2.grid(column=2, row=0)\n# Button\nbutton = Button(text=\"click me\", command=button_clicked)\nbutton.grid(column=1, row=1)\n\n# Entry, this is basically input in gui\nmy_input = Entry()\nmy_input.grid(column=3, row=3)\n\nwindow.mainloop()\n","repo_name":"DeFidelity/Python","sub_path":"GUi start/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2759604399","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef DataVisualization(dfs): \n\n ## Data Visualization\n fig, axes = plt.subplots(2, 2, figsize = (25, 10))\n fig.subplots_adjust(wspace = 0.2, hspace = 0.5)\n\n ## Set up legend\n positions = ['C', 'F', 'G']\n\n for i in range(3):\n axes[0, 0].plot(dfs[0].iloc[:,i], label=positions[i])\n axes[0, 1].plot(dfs[1].iloc[:,i], label=positions[i])\n axes[1, 0].plot(dfs[2].iloc[:,i], label=positions[i])\n axes[1, 1].plot(dfs[3].iloc[:,i], label=positions[i])\n\n ## Upper left, visualize players' average field goal attempts vs position over year\n axes[0, 0].legend()\n axes[0, 0].set_title('Average Field Goal Attempt vs Position over year')\n axes[0, 0].set_xlabel('year')\n axes[0, 0].set_ylabel('average FGA')\n x_ticks_1 = np.arange(1998, 2019, 1)\n y_ticks_1 = np.arange(6, 11, 0.5)\n axes[0, 0].set_xticks(x_ticks_1)\n axes[0, 0].set_yticks(y_ticks_1)\n\n ## Upper right, visualize players' average usage percentange vs position over year \n axes[0, 1].legend()\n axes[0, 1].set_title('Average Usage Percentange vs Position over year')\n axes[0, 1].set_xlabel('year')\n axes[0, 1].set_ylabel('average USG%')\n x_ticks_2 = np.arange(1998, 2019, 1)\n y_ticks_2 = np.arange(15, 22, 1)\n axes[0, 1].set_xticks(x_ticks_2)\n axes[0, 1].set_yticks(y_ticks_2)\n\n ## Bottom left, visualize players' average salaries vs position over year \n axes[1, 0].legend()\n axes[1, 0].set_title('Average Salary vs Position over year')\n axes[1, 0].set_xlabel('year')\n axes[1, 0].set_ylabel('average salary (ten million dollars)')\n x_ticks_3 = np.arange(1998, 2019, 1)\n y_ticks_3 = np.arange(5000000, 25000000, 1000000)\n axes[1, 0].set_xticks(x_ticks_3)\n axes[1, 0].set_yticks(y_ticks_3)\n\n ## Bottom right, visualize sum of players' expected values in draft vs position over year \n axes[1, 1].legend()\n axes[1, 1].set_title(\"Sum of Draft's Expected Value vs Position over year\")\n axes[1, 1].set_xlabel('year')\n axes[1, 1].set_ylabel('sum of EV')\n x_ticks_4 = np.arange(1998, 2019, 1)\n y_ticks_4 = np.arange(100, 1000, 100)\n axes[1, 1].set_xticks(x_ticks_4)\n axes[1, 1].set_yticks(y_ticks_4)\n\n ## Export figure \n #fig.show()\n fig.savefig('Visualization')","repo_name":"Jiachengliu1/NBA-Positional-Revolution-Analysis","sub_path":"src/DataVisualization.py","file_name":"DataVisualization.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31791356686","text":"\"\"\"\nDownload and unzip raw ESA Landcover data from Copernicus CDS\n\n\"\"\"\n\nimport os\nimport cdsapi\nimport pandas as pd\nimport glob\nimport zipfile\nfrom utility import run_tasks, get_current_timestamp\n\nc = cdsapi.Client()\n\ntimestamp = get_current_timestamp('%Y_%m_%d_%H_%M')\n\nv207_years = range(1992, 2016)\nv211_years = range(2016, 2020)\n\n# -------------------------------------\n\n# download directory\nraw_dir = \"/sciclone/aiddata10/REU/geo/raw/esa_landcover\"\n\n# accepts int or str\nyears = range(1992, 2020)\n\nmode = \"parallel\"\n\nmax_workers = 30\n\n# -------------------------------------\n\n\ndef download(version, year):\n overwrite = False\n dl_path = os.path.join(raw_dir, \"compressed\", f\"{year}.zip\")\n try:\n if len(glob.glob(dl_path)) == 0 or overwrite:\n dl_meta = {\n 'variable': 'all',\n 'format': 'zip',\n 'version': version,\n 'year': year,\n }\n c.retrieve('satellite-land-cover', dl_meta, dl_path)\n except Exception as e:\n return (1, e, year)\n try:\n zipfile_glob = glob.glob(dl_path)\n if len(zipfile_glob) != 1:\n raise Exception(f\"Multiple or no ({len(zipfile_glob)}) zip file found for {year}\")\n zipfile_path = zipfile_glob[0]\n print(f\"Unzipping {zipfile_path}...\")\n with zipfile.ZipFile(zipfile_path) as zf:\n netcdf_namelist = [i for i in zf.namelist() if i.endswith(\".nc\")]\n if len(netcdf_namelist) != 1:\n raise Exception(f\"Multiple or no ({len(netcdf_namelist)}) net cdf files found in zip for {year}\")\n if not os.path.isfile(os.path.join(raw_dir, \"uncompressed\", netcdf_namelist[0])) or overwrite:\n zf.extract(netcdf_namelist[0], os.path.join(raw_dir, \"uncompressed\"))\n print(f\"Unzip complete: {zipfile_path}...\")\n else:\n print(f\"Unzip exists: {zipfile_path}...\")\n except Exception as e:\n return (2, e, year)\n else:\n return (0, \"Success\", year)\n\n\n\nif __name__ == \"__main__\":\n\n os.makedirs(os.path.join(raw_dir, \"compressed\"), exist_ok=True)\n os.makedirs(os.path.join(raw_dir, \"uncompressed\"), exist_ok=True)\n\n qlist = []\n\n for year in years:\n if year in v207_years:\n version = 'v2.0.7cds'\n elif year in v211_years:\n version = 'v2.1.1'\n else:\n raise Exception(\"Invalid year {}\".format(year))\n qlist.append((version, year))\n\n df = pd.DataFrame(qlist, columns=[ 'version', 'year'])\n\n\n results = run_tasks(download, qlist, mode, max_workers)\n\n\n # join download function results back to df\n results_df = pd.DataFrame(results, columns=[\"status\", \"message\", \"year\"])\n output_df = df.merge(results_df, on=\"year\", how=\"left\")\n\n print(\"Results:\")\n\n errors_df = output_df[output_df[\"status\"] != 0]\n print(\"{} errors found out of {} tasks\".format(len(errors_df), len(output_df)))\n\n for ix, row in errors_df.iterrows():\n print(row)\n\n # output results to csv\n output_path = os.path.join(raw_dir, f\"download_{timestamp}.csv\")\n output_df.to_csv(output_path, index=False)\n","repo_name":"sgoodm/geo-datasets-test","sub_path":"esa_landcover/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"71343996242","text":"from django.shortcuts import get_object_or_404\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ModelViewSet\n\nfrom pin.models import Pin\n\nfrom .models import Profile, User, UserFollowing\nfrom .serializers import (PinDeleteSerializer, ProfileSerializer,\n ProfileUpdateSerializer, UpdatePasswordSerializer,\n UserFollowersSerializer, UserFollowingSerializer)\n\n\n@permission_classes([])\nclass ProfileViewSet(ModelViewSet):\n serializer_class = ProfileSerializer\n\n def get_queryset(self):\n username = self.request.query_params.get('username')\n if username:\n return Profile.objects.filter(user__username=username)\n\n return Profile.objects.filter(user=self.request.user.id)\n\n def get_serializer_context(self):\n return {'request': self.request}\n\n\nclass ProfileDetailsViewSet(ModelViewSet):\n serializer_class = ProfileSerializer\n queryset = Profile.objects.all()\n\n def get_serializer_context(self):\n return {'request': self.request}\n\n\n@api_view(['GET'])\ndef follow(request, u_id):\n current_profile = Profile.objects.get(user=request.user)\n\n try:\n f_user = get_object_or_404(Profile, id=u_id)\n\n follow = UserFollowing.objects.create(\n user=current_profile, followed_user=f_user)\n return Response(data={'msg': follow.__str__()}, status=status.HTTP_201_CREATED)\n except:\n return Response(data={'msg': 'user not found'}, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET'])\ndef unfollow(request, u_id):\n current_profile = Profile.objects.get(user__username=request.user)\n\n try:\n f_user = get_object_or_404(Profile, id=u_id)\n try:\n UserFollowing.objects.get(\n user=current_profile, followed_user=f_user).delete()\n return Response(data={'msg': f\"{request.user} unfollowed {f_user.user.username}\"}, status=status.HTTP_200_OK)\n except:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except:\n return Response(data={'msg': 'user not found'}, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass FollowersViewSet(ModelViewSet):\n serializer_class = UserFollowersSerializer\n\n def get_queryset(self):\n current_profile = Profile.objects.get(user=self.request.user)\n username = self.request.query_params.get('username')\n if username:\n follower = get_object_or_404(Profile, user__username=username)\n return UserFollowing.objects.filter(followed_user=follower)\n\n return UserFollowing.objects.filter(followed_user=current_profile)\n\n def get_serializer_context(self):\n return {\"request\": self.request}\n\n\nclass FollowingViewSet(ModelViewSet):\n serializer_class = UserFollowingSerializer\n\n def get_queryset(self):\n username = self.request.query_params.get('username')\n current_profile = Profile.objects.get(user__username=self.request.user)\n\n if username:\n following = get_object_or_404(Profile, user__username=username)\n return UserFollowing.objects.filter(user=following)\n\n return UserFollowing.objects.filter(user=current_profile)\n\n def get_serializer_context(self):\n return {\"request\": self.request}\n\n\nclass PinDeleteViewSet(ModelViewSet):\n serializer_class = PinDeleteSerializer\n queryset = Pin.objects.all()\n\n\nclass ProfileUpdateViewSet(ModelViewSet):\n serializer_class = ProfileUpdateSerializer\n\n def get_queryset(self):\n return Profile.objects.filter(user__username=self.request.user)\n\n def get_serializer_context(self):\n return {\n 'username': self.request.data.get('username'),\n 'email': self.request.data.get('email'),\n }\n\n\n@api_view(['DELETE'])\ndef delete_user(request):\n try:\n User.objects.get(username=request.user).delete()\n return Response(data={'msg': 'account deleted successfully'}, status=status.HTTP_204_NO_CONTENT)\n except Exception as e:\n return Response(data={'msg': f\"error while delete {e}\"}, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['PUT'])\ndef update_password(request):\n serializer = UpdatePasswordSerializer(\n data=request.data, context={'request': request})\n\n if serializer.is_valid():\n serializer.save()\n return Response(data={'msg': 'password changed successfully'}, status=status.HTTP_200_OK)\n\n return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"mamume/pinterest","sub_path":"user_profile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"70040668561","text":"from __future__ import print_function\nimport time\nimport os\nfrom neo.lib.app import buildOptionParser\n\nimport_warning = (\n \"WARNING: This is not the recommended way to import data to NEO:\"\n \" you should use the Importer backend instead.\\n\"\n \"NEO also does not implement IStorageRestoreable interface, which\"\n \" means that undo information is not preserved when using this tool:\"\n \" conflict resolution could happen when undoing an old transaction.\"\n)\n\n@buildOptionParser\nclass NEOMigrate(object):\n\n from neo.lib.config import OptionList\n\n @classmethod\n def _buildOptionParser(cls):\n parser = cls.option_parser\n parser.description = \"NEO <-> FileStorage conversion tool\"\n parser('c', 'cluster', required=True, help='the NEO cluster name')\n parser.bool('q', 'quiet', help='print nothing to standard output')\n parser.argument('source', help='the source database')\n parser.argument('destination', help='the destination database')\n\n def __init__(self, config):\n self.name = config.pop('cluster')\n self.source = config.pop('source')\n self.destination = config.pop('destination')\n self.quiet = config.pop('quiet', False)\n\n from ZODB.FileStorage import FileStorage\n from neo.client.Storage import Storage as NEOStorage\n if os.path.exists(self.source):\n if not self.quiet:\n print(import_warning)\n self.src = FileStorage(file_name=self.source, read_only=True)\n self.dst = NEOStorage(master_nodes=self.destination, name=self.name,\n **config)\n else:\n self.src = NEOStorage(master_nodes=self.source, name=self.name,\n read_only=True, **config)\n self.dst = FileStorage(file_name=self.destination)\n\n def run(self):\n if not self.quiet:\n print(\"Migrating from %s to %s\" % (self.source, self.destination))\n start = time.time()\n self.dst.copyTransactionsFrom(self.src)\n if not self.quiet:\n elapsed = time.time() - start\n print(\"Migration done in %3.5f\" % elapsed)\n\n\ndef main(args=None):\n config = NEOMigrate.option_parser.parse(args)\n NEOMigrate(config).run()\n","repo_name":"Nexedi/neoppod","sub_path":"neo/scripts/neomigrate.py","file_name":"neomigrate.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"3"}
+{"seq_id":"43700110500","text":"# @author Ataago \n# @license GPL-3.0\n\nimport discord\nfrom discord.ext import commands\nfrom goInfo import Ataago\nimport roles\n\nclass Admin():\n def __init__(self, GoBot):\n self.GoBot = GoBot\n\n @commands.command(pass_context = True)\n async def say(self, ctx):\n message = ctx.message\n prefix = message.content.split(\" \")[0]\n invoke = message.content.split(\" \")[1]\n\n messageStartsFrom = len(prefix) + len(invoke) + 1\n\n #check if user has xprole, import roles\n if not await roles.Admin.check_role(self, ctx.message, 'adminrole'):\n await self.GoBot.say(\"You dont have Permissions\")\n return\n\n await self.GoBot.delete_message(message)\n await self.GoBot.say(message.content[messageStartsFrom : ])\n \ndef setup(GoBot):\n GoBot.add_cog(Admin(GoBot))","repo_name":"Ataago/GO-BOT-Discord","sub_path":"src/commands/say.py","file_name":"say.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"9387202276","text":"from memory_db import MemoryDB\nfrom add_hourly_employee import AddHourlyEmployee\nimport datetime\nfrom add_time_card import AddTimeCard\nfrom hourly_classification import HourlyClassification\n\ndef test_adding_a_time_card():\n db = MemoryDB()\n t = AddHourlyEmployee(\"Bill\", \"Home\", 15.25, db)\n empId = t.execute()\n date = datetime.date(2005, 3, 30)\n tct = AddTimeCard(empId, date, 8.0, db)\n tct.execute()\n\n e = db.get_employee(empId)\n assert e is not None\n\n pc = e.classification\n assert isinstance(pc, HourlyClassification)\n\n tc = pc.get_time_card(date)\n assert tc.hours == 8.0\n assert tc.date == date\n","repo_name":"kaiserprogrammer/payroll-in-python","sub_path":"test/TestAddTimeCard.py","file_name":"TestAddTimeCard.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"3"}
+{"seq_id":"11047150166","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 4 20:35:55 2018\n\n@author: yy\n\"\"\"\nfrom __future__ import division\nimport tensorflow as tf\nimport keras.backend as K\n\nfrom keras.engine.topology import InputSpec\nfrom keras.engine.topology import Layer\n\nclass DecodeDetections(Layer):\n \n def __init__(self,\n confidence_thresh=0.01,\n iou_threshold=0.45,\n top_k=200,\n nms_max_output_size=400,\n coords='centroids',\n normalize_coords=True,\n img_height=None,\n img_width=None,\n **kwargs):\n \n if K.backend() != 'tensorflow':\n raise TypeError(\"This layer only supports TensorFlow at the moment, but you are using the {} backend.\".format(K.backend()))\n\n if normalize_coords and ((img_height is None) or (img_width is None)):\n raise ValueError(\"If relative box coordinates are supposed to be converted to absolute coordinates, the decoder needs the image size in order to decode the predictions, but `img_height == {}` and `img_width == {}`\".format(img_height, img_width))\n\n if coords != 'centroids':\n raise ValueError(\"The DetectionOutput layer currently only supports the 'centroids' coordinate format.\")\n\n self.confidence_thresh = confidence_thresh\n self.iou_threshold = iou_threshold\n self.top_k = top_k\n self.normalize_coords = normalize_coords\n self.img_height = img_height\n self.img_width = img_width\n self.coords = coords\n self.nms_max_output_size = nms_max_output_size\n\n self.tf_confidence_thresh = tf.constant(self.confidence_thresh, name='confidence_thresh')\n self.tf_iou_threshold = tf.constant(self.iou_threshold, name='iou_threshold')\n self.tf_top_k = tf.constant(self.top_k, name='top_k')\n self.tf_normalize_coords = tf.constant(self.normalize_coords, name='normalize_coords')\n self.tf_img_height = tf.constant(self.img_height, dtype=tf.float32, name='img_height')\n self.tf_img_width = tf.constant(self.img_width, dtype=tf.float32, name='img_width')\n self.tf_nms_max_output_size = tf.constant(self.nms_max_output_size, name='nms_max_output_size')\n\n super(DecodeDetections, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.input_spec = [InputSpec(shape=input_shape)]\n super(DecodeDetections, self).build(input_shape)\n\n def call(self, y_pred, mask=None):\n \n # 转换: anchor box offsets -》 image offsets.\n cx = y_pred[...,-12] * y_pred[...,-4] * y_pred[...,-6] + y_pred[...,-8] # cx = cx_pred * cx_variance * w_anchor + cx_anchor\n cy = y_pred[...,-11] * y_pred[...,-3] * y_pred[...,-5] + y_pred[...,-7] # cy = cy_pred * cy_variance * h_anchor + cy_anchor\n w = tf.exp(y_pred[...,-10] * y_pred[...,-2]) * y_pred[...,-6] # w = exp(w_pred * variance_w) * w_anchor\n h = tf.exp(y_pred[...,-9] * y_pred[...,-1]) * y_pred[...,-5] # h = exp(h_pred * variance_h) * h_anchor\n\n # 转换: centroids -》 corners\n xmin = cx - 0.5 * w\n ymin = cy - 0.5 * h\n xmax = cx + 0.5 * w\n ymax = cy + 0.5 * h\n\n # 归一化\n def normalized_coords():\n xmin1 = tf.expand_dims(xmin * self.tf_img_width, axis=-1)\n ymin1 = tf.expand_dims(ymin * self.tf_img_height, axis=-1)\n xmax1 = tf.expand_dims(xmax * self.tf_img_width, axis=-1)\n ymax1 = tf.expand_dims(ymax * self.tf_img_height, axis=-1)\n return xmin1, ymin1, xmax1, ymax1\n def non_normalized_coords():\n return tf.expand_dims(xmin, axis=-1), tf.expand_dims(ymin, axis=-1), tf.expand_dims(xmax, axis=-1), tf.expand_dims(ymax, axis=-1)\n\n xmin, ymin, xmax, ymax = tf.cond(self.tf_normalize_coords, normalized_coords, non_normalized_coords)\n\n # 连接 the one-hot class confidences 和 结果张量\n y_pred = tf.concat(values=[y_pred[...,:-12], xmin, ymin, xmax, ymax], axis=-1)\n\n \n ##过滤结果\n n_classes = y_pred.shape[2] - 4\n\n # 三方面过滤:\n # -- confidence thresholding\n # -- non-maximum suppression (NMS)\n # -- top-k filtering\n def filter_predictions(batch_item):\n\n # class\n def filter_single_class(index):\n\n confidences = tf.expand_dims(batch_item[..., index], axis=-1)\n class_id = tf.fill(dims=tf.shape(confidences), value=tf.to_float(index))\n box_coordinates = batch_item[...,-4:]\n\n single_class = tf.concat([class_id, confidences, box_coordinates], axis=-1)\n\n # confidence\n threshold_met = single_class[:,1] > self.tf_confidence_thresh\n single_class = tf.boolean_mask(tensor=single_class,\n mask=threshold_met)\n\n # NMS\n def perform_nms():\n scores = single_class[...,1]\n\n xmin = tf.expand_dims(single_class[...,-4], axis=-1)\n ymin = tf.expand_dims(single_class[...,-3], axis=-1)\n xmax = tf.expand_dims(single_class[...,-2], axis=-1)\n ymax = tf.expand_dims(single_class[...,-1], axis=-1)\n boxes = tf.concat(values=[ymin, xmin, ymax, xmax], axis=-1)\n\n maxima_indices = tf.image.non_max_suppression(boxes=boxes,\n scores=scores,\n max_output_size=self.tf_nms_max_output_size,\n iou_threshold=self.iou_threshold,\n name='non_maximum_suppresion')\n maxima = tf.gather(params=single_class,\n indices=maxima_indices,\n axis=0)\n return maxima\n\n def no_confident_predictions():\n return tf.constant(value=0.0, shape=(1,6))\n\n single_class_nms = tf.cond(tf.equal(tf.size(single_class), 0), no_confident_predictions, perform_nms)\n\n padded_single_class = tf.pad(tensor=single_class_nms,\n paddings=[[0, self.tf_nms_max_output_size - tf.shape(single_class_nms)[0]], [0, 0]],\n mode='CONSTANT',\n constant_values=0.0)\n\n return padded_single_class\n\n filtered_single_classes = tf.map_fn(fn=lambda i: filter_single_class(i),\n elems=tf.range(1,n_classes),\n dtype=tf.float32,\n parallel_iterations=128,\n back_prop=False,\n swap_memory=False,\n infer_shape=True,\n name='loop_over_classes')\n\n filtered_predictions = tf.reshape(tensor=filtered_single_classes, shape=(-1,6))\n\n def top_k():\n return tf.gather(params=filtered_predictions,\n indices=tf.nn.top_k(filtered_predictions[:, 1], k=self.tf_top_k, sorted=True).indices,\n axis=0)\n def pad_and_top_k():\n padded_predictions = tf.pad(tensor=filtered_predictions,\n paddings=[[0, self.tf_top_k - tf.shape(filtered_predictions)[0]], [0, 0]],\n mode='CONSTANT',\n constant_values=0.0)\n return tf.gather(params=padded_predictions,\n indices=tf.nn.top_k(padded_predictions[:, 1], k=self.tf_top_k, sorted=True).indices,\n axis=0)\n\n top_k_boxes = tf.cond(tf.greater_equal(tf.shape(filtered_predictions)[0], self.tf_top_k), top_k, pad_and_top_k)\n\n return top_k_boxes\n\n output_tensor = tf.map_fn(fn=lambda x: filter_predictions(x),\n elems=y_pred,\n dtype=None,\n parallel_iterations=128,\n back_prop=False,\n swap_memory=False,\n infer_shape=True,\n name='loop_over_batch')\n\n return output_tensor\n\n def compute_output_shape(self, input_shape):\n batch_size, n_boxes, last_axis = input_shape\n return (batch_size, self.tf_top_k, 6) \n\n def get_config(self):\n config = {\n 'confidence_thresh': self.confidence_thresh,\n 'iou_threshold': self.iou_threshold,\n 'top_k': self.top_k,\n 'nms_max_output_size': self.nms_max_output_size,\n 'coords': self.coords,\n 'normalize_coords': self.normalize_coords,\n 'img_height': self.img_height,\n 'img_width': self.img_width,\n }\n base_config = super(DecodeDetections, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n","repo_name":"YIYIMZ/my_keras_ssd","sub_path":"layer_decode_detections.py","file_name":"layer_decode_detections.py","file_ext":"py","file_size_in_byte":9527,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"4279766358","text":"# green is what is missing, white is what's correct, red is what you wrote extra\nimport sys\nfrom tempfile import NamedTemporaryFile as TF\nfrom subprocess import check_output, STDOUT\nimport os\n\nDIFF=os.environ.get('DIFF', 'git --no-pager diff --word-diff=color --word-diff-regex=. ')\n\n\ndef report_error(cond, correct, output, kind):\n if cond:\n print('PASS')\n return True\n with TF('w') as cf, TF('w') as of:\n cf.write(correct)\n cf.flush()\n if kind == 'all':\n of.write(output)\n elif kind == 'start':\n of.write(output[:len(correct)])\n elif kind == 'end':\n of.write(output[-len(correct)-1:])\n\n of.flush()\n os.system(f'{DIFF} {of.name} {cf.name}')\n print('FAIL')\n return False\n\nif len(sys.argv) != 2:\n print('usage: python3 test.py ex.txt', file=sys.stderr)\n raise SystemExit(1)\ntest_file = sys.argv[1]\ntests = [a.lstrip() for a in ''.join(open(test_file)).split('---')]\nfor test in tests[int(os.environ.get('START', 0)):]:\n i, _, do = test.partition('\\n')\n do = do.replace('\\r', '')\n print(i)\n assert i.startswith('$'), f\"the first character of a test case must be $, got {i}\"\n ro = check_output(i.lstrip('$ '), shell=True, stderr=STDOUT, universal_newlines=True, encoding='utf-8')\n if '...' in do:\n start, end = do.split('...')\n if report_error(ro.startswith(start), start, ro, 'start'):\n report_error(ro.endswith(end), end, ro, 'end')\n else:\n report_error(ro == do, do, ro, 'all')\n","repo_name":"JosefKuchar/ios-hw1","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24691168939","text":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.rnn import LSTMStateTuple\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.keras import initializers\n\n\nclass BNSTAR_cell(tf.contrib.rnn.BasicLSTMCell):\n def __init__(self, num_units, t_max=784, training=True,\n **kwargs):\n '''\n t_max should be a float value corresponding to the longest possible\n time dependency in the input.\n '''\n self.num_units = num_units\n self.t_max = 784\n self.training = training\n super(BNSTAR_cell, self).__init__(num_units, **kwargs)\n\n def __call__(self, x, state, scope=None):\n \"\"\"BN-STAR.\"\"\"\n with tf.variable_scope(scope or type(self).__name__):\n if self._state_is_tuple:\n h, _ = state\n else:\n h, _ = tf.split(value=state, num_or_size_splits=2, axis=1)\n\n\n x_size = x.get_shape().as_list()[1]\n \n W_zx = tf.get_variable('W_xh_z',\n [x_size, 1 * self.num_units], initializer=initializers.get('orthogonal')) \n W_Kx = tf.get_variable('W_xh_K',\n [x_size, 1 * self.num_units], initializer=initializers.get('orthogonal'))\n W_Kh = tf.get_variable('W_hh',\n [self.num_units, 1 * self.num_units], initializer=initializers.get('orthogonal'))\n \n\n if self.t_max is None:\n print('Zero initializer ')\n bias = tf.get_variable('bias', [2 * self.num_units],\n initializer=bias_initializer(2))\n else:\n print('Using chrono initializer ...')\n bias = tf.get_variable('bias', [2 * self.num_units],\n initializer=chrono_init(self.t_max,\n 2))\n \n bias_f = bias[self.num_units:,...]\n bias_j = bias[:self.num_units,...] \n\n fx = tf.matmul(x, W_Kx)\n fh = tf.matmul(h, W_Kh)\n \n j = tf.matmul(x, W_zx)\n \n \n bn_f = batch_norm(fx, 'fx', self.training) + batch_norm(fh, 'fh', self.training)\n bn_j = batch_norm(j, 'j', self.training)\n\n \n bn_f = tf.nn.bias_add(bn_f, bias_f)\n bn_j = tf.nn.bias_add(bn_j, bias_j)\n\n beta = 1\n new_h = tf.sigmoid(bn_f)*h + (1-tf.sigmoid(bn_f-beta))*tf.tanh(bn_j)\n \n# bn_f = tf.sigmoid(bn_f)\n# bn_j = tf.tanh(bn_j)\n# new_h = bn_f * h + (1-bn_f) * bn_j\n new_h = tf.tanh(new_h)\n\n if self._state_is_tuple:\n new_state = LSTMStateTuple(new_h, new_h)\n else:\n new_state = tf.concat([new_h, new_h], 1)\n return new_h, new_state\n\n\ndef chrono_init(t_max, num_gates):\n def _initializer(shape, dtype=tf.float32, partition_info=None):\n num_units = shape[0]//num_gates\n uni_vals = tf.log(random_ops.random_uniform([num_units], minval=1.0,\n maxval=t_max, dtype=dtype,\n seed=42))\n\n bias_j = tf.zeros(num_units)\n bias_f = uni_vals\n\n return tf.concat([bias_j, bias_f], 0)\n\n return _initializer\n\n\ndef bias_initializer(num_gates):\n def _initializer(shape, dtype=tf.float32, partition_info=None):\n p = np.zeros(shape)\n num_units = int(shape[0]//num_gates)\n # i, j, o, f\n # f:\n p[-num_units:] = np.ones(num_units)\n\n return tf.constant(p, dtype)\n\n return _initializer\n\n\ndef batch_norm(x, name_scope, training, epsilon=1e-3, decay=0.999):\n '''Assume 2d [batch, values] tensor'''\n\n with tf.variable_scope(name_scope):\n size = x.get_shape().as_list()[1]\n\n scale = tf.get_variable('scale', [size], initializer=tf.constant_initializer(0.1))\n offset = tf.get_variable('offset', [size])\n\n pop_mean = tf.get_variable('pop_mean', [size], initializer=tf.zeros_initializer, trainable=False)\n pop_var = tf.get_variable('pop_var', [size], initializer=tf.ones_initializer, trainable=False)\n batch_mean, batch_var = tf.nn.moments(x, [0])\n\n train_mean_op = tf.assign(pop_mean, pop_mean * decay + batch_mean * (1 - decay))\n train_var_op = tf.assign(pop_var, pop_var * decay + batch_var * (1 - decay))\n\n def batch_statistics():\n with tf.control_dependencies([train_mean_op, train_var_op]):\n return tf.nn.batch_normalization(x, batch_mean, batch_var, offset, scale, epsilon)\n\n def population_statistics():\n return tf.nn.batch_normalization(x, pop_mean, pop_var, offset, scale, epsilon)\n\n return tf.cond(training, batch_statistics, population_statistics)\n","repo_name":"0zgur0/STAckable-Recurrent-network","sub_path":"bn_star.py","file_name":"bn_star.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"3"}
+{"seq_id":"29414394679","text":"from sptest import __main__, __version__\nfrom typer.testing import CliRunner\n\nrunner = CliRunner()\n\n\ndef test_version():\n assert __version__ == \"0.1.0\"\n\n\ndef test_servers():\n result = runner.invoke(__main__.app, [\"servers\", \"--server-limit=1\", \"--ping-num=1\"])\n assert result.exit_code == 0\n assert \"check\" in result.stdout\n assert \"Server list sorted by latency_median\" in result.stdout\n","repo_name":"faruryo/sptest","sub_path":"tests/test_sptest.py","file_name":"test_sptest.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7330223669","text":"import click, time\n\nfrom rich.console import Console\nfrom rich.live import Live\n\nfrom services import tables, ec2_requests\n\n\n# 'Rich' lib console instance to display pretty output\nconsole = Console()\n\n\n@click.group()\ndef cli() -> None:\n \"\"\" A tool for controlling instances \"\"\"\n pass\n\n@click.command(help='Show a list of all instances')\n@click.option('-l', is_flag=True, default=False, \n help='Display a table of instances in live mode.')\ndef list_instances(l:bool) -> None:\n \"\"\" Show a list of all instances \"\"\"\n if l:\n req_count = 0\n\n with Live(tables.generate_table(), refresh_per_second=1) as live:\n print('\\nTo STOP use CTR + C')\n # For endless cycle use: while True\n while req_count != 5: # send only 5 requests \n time.sleep(5) # 5 sec pause between each requests to server\n live.update(tables.generate_table())\n req_count += 1\n else:\n table = tables.generate_table()\n console.print(table)\n \n\n@click.command(help='Start an instance')\n@click.option('-id', prompt='Enter instance ID', help='Start instance by ID')\ndef start_instance(id:str) -> None:\n \"\"\" Start instance by ID \"\"\"\n start_response = ec2_requests.start_instance(instance_id=id)\n output_table = tables.start_instance_output(data=start_response)\n console.print(output_table)\n\n\n@click.command(help='Stop an instance')\n@click.option('-id', prompt='Enter instance ID', help='Stop instance by ID')\ndef stop_instance(id:str) -> None:\n \"\"\" Stop instance by ID \"\"\"\n stop_response = ec2_requests.stop_instance(instance_id=id)\n output_table = tables.stop_instance_output(data=stop_response)\n console.print(output_table)\n \n\n# initialize functions as commands\ncli.add_command(list_instances)\ncli.add_command(start_instance)\ncli.add_command(stop_instance)\n\n\nif __name__=='__main__':\n cli()","repo_name":"SaviolaX/AWS_EC2_CLI_control_tool","sub_path":"cli_app.py","file_name":"cli_app.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29568507472","text":"import tensorflow as tf\n\ndef layer(inputs, weight_shape, bias_shape):\n '''定义一个 relu 层'''\n \n # 设定初始化方法, 由于 relu 的特性, 所以使用常态分配来初始化\n w_init = tf.random_normal_initializer(stddev=(2.0/weight_shape[0])**0.5)\n bias_init = tf.constant_initializer(value=0)\n \n # 定义每一层有 bias 个神经元\n w = tf.get_variable('w', weight_shape, initializer=w_init)\n b = tf.get_variable('b', bias_shape, initializer=bias_init)\n \n # 回传使用 relu 运算\n return tf.nn.relu( tf.matmul(inputs, w) + b )\n\ndef inference(x):\n '''定义推测的步骤, 传入一笔或多笔资料, 经过两个隐藏层后, 直接输出推测结果'''\n \n # 定义两个隐藏层, 两个隐藏层都有256个神经元, 与上一层全连结\n # 特别使用 variable_scope 这个特殊的方法, 这在图上可以清楚看到\n # 后面会看到, 当我们要取得里面的节点, 就需要加上这个变数区域\n with tf.variable_scope('hidden_1'):\n hidden_1 = layer(x, [784, 256], [256])\n with tf.variable_scope('hidden_2'):\n hidden_2 = layer(hidden_1, [256, 256], [256])\n \n # 定义一个输出层, 与上一层全连结, 特别注意没有softmax运算\n with tf.variable_scope('output'):\n output = layer(hidden_2, [256, 10], [10])\n \n return hidden_1, hidden_2, output\n \ndef loss(output, y):\n '''定义误差函数计算的步骤, 这边使用的是交叉嫡'''\n \n # 这个模型在这时候才使用 softmax 并进行交叉嫡运算\n xentropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=output, labels=y) \n \n # 直接将所有的数字揉在一起做平均\n loss = tf.reduce_mean(xentropy)\n \n return loss\n\ndef training(cost, global_step, lr): \n '''定义训练的步骤, 用梯度下降法'''\n \n # 纪录过程\n tf.summary.scalar('cost', cost)\n \n # 定义训练的方法, 使用梯度下降法\n optimizer = tf.train.GradientDescentOptimizer(lr)\n \n # 进行误差最小化任务\n train_op = optimizer.minimize(cost, global_step=global_step)\n \n return train_op\n \ndef training_no_optimizer(cost, optimizer, global_step, name='train'): \n '''定义训练的步骤, 用梯度下降法'''\n \n # 纪录过程\n tf.summary.scalar('cost', cost)\n \n # 进行误差最小化任务\n train_op = optimizer.minimize(cost, global_step=global_step, name='train')\n \n return train_op\n \ndef evaluate(output, y, name='eva'):\n '''定义评估的方式, 输入标签以及预测标签, 输出准确率'''\n \n # 找出标签与预测标签的最大信心水准, 比较是否相同\n correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(y, 1))\n \n # 沿着 0 维度降维, 算出一个准确率\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='eva')\n \n # 纪录过程\n tf.summary.scalar('validation_error', (1. - accuracy))\n \n \n return accuracy\n \n","repo_name":"willy11342002/DeepLearning","sub_path":"my_model.py","file_name":"my_model.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"17719272743","text":"#!/usr/bin/python3\n\nimport argparse\n\nap = argparse.ArgumentParser()\nap.add_argument(\"--dsn\", required=False)\n# Combine all arguments into a list called args\nargs = vars(ap.parse_args())\nif args[\"dsn\"] is not None:\n# do something\n print (\"dsn has been set (value is %s)\" % args[\"dsn\"] )\n","repo_name":"boulaypa/pyAWR","sub_path":"tmp/src/test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1669586732","text":"from creature1 import Creature\nimport random\nimport pygame\nimport writerandom\n\n\n# Trained creature type\n# This creature is the trained creature (oliver is the training class)\n# To use, use oliver creature class (\"class1\" on main becomes Oliver\n# \"Class2\" is what you're training \"Oliver\" against\n# follow instructions (say 1 to \"are you training the oliver class\")\n# Switch to trained (edit \"class1\" to be Trained)\nclass Trained(Creature):\n actions = []\n\n # Inherits Creature's initialization function and adds 2 new features\n def __init__(self, x, y, startingDirection):\n super().__init__(x, y, startingDirection)\n self.images = [\n pygame.image.load(\"resources/trained_up.png\").convert_alpha(),\n pygame.image.load(\"resources/trained_right.png\").convert_alpha(),\n pygame.image.load(\"resources/trained_down.png\").convert_alpha(),\n pygame.image.load(\"resources/trained_left.png\").convert_alpha()\n ]\n self.image = self.images[self.direct]\n self.action = self.takeAction\n self.num = 0\n self.actions = []\n # Puts procedure into \"self.actions\"\n self.initActions()\n\n # Used to print out a Trained object\n def __str__(self) -> str:\n return \"Trained\"\n\n # Puts actions into \"self.actions\"\n def initActions(self):\n self.actions = []\n # If quick actions access is empty, reads actions file (this case would be trained Oliver class)\n # (\"developedCreature.txt\")\n # then writes them to the class for future objects\n if not Trained.actions:\n file = open(\"texts/developedCreature.txt\", \"r\")\n for line in file:\n self.actions.append(line.strip())\n Trained.actions = self.actions.copy()\n else:\n self.actions = Trained.actions.copy()\n","repo_name":"OliverSBeresford/Darwin-s-World","sub_path":"trained.py","file_name":"trained.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30317573014","text":"# -*- coding: UTF-8 -*-\n'''\nCreated on Wed May 6 16:11:21 2020\n\n@author: Damon Li\n'''\n\nfrom tensorflow.contrib import learn\nimport numpy as np\nimport re\nimport json\nimport jieba\nimport copy\n\n\nclass text_cls_data_loader(object):\n\n def __init__(self, setting):\n self.config = setting\n self.vocab_dir = setting.text_cls_vocab_dir\n self.num_classes = setting.num_classes\n self.train_data_dir = setting.text_cls_train_dir\n self.max_sentence_len = setting.text_cls_sentence_len\n self.val_sample_ratio = setting.text_cls_val_sample_ratio\n self.text_cls_embedding_dir = setting.text_cls_embedding_dir\n\n self.embedding = None\n self.embedding_shape = 0\n\n self.word_id_dict = dict()\n self.reverse_word_id_dict = dict()\n\n\n def load_embedding(self, debug=False):\n self.embedding = np.load(self.text_cls_embedding_dir)\n self.embedding_shape = np.shape(self.embedding)[-1]\n\n with open(self.vocab_dir, encoding=\"utf-8\") as json_file:\n self.word_id_dict = json.load(json_file)\n\n self.reverse_word_id_dict = {}\n for each in self.word_id_dict: # each 是word_id_dict 字典的key 不是(key,value)组合\n self.reverse_word_id_dict.setdefault(self.word_id_dict[each], each)\n\n if debug:\n return self.embedding, self.embedding_shape, self.word_id_dict, self.reverse_word_id_dict\n\n\n def text_input_to_array(self, text, debug=False):\n text_array = np.zeros([1, self.config.text_cls_sentence_len], dtype=np.int32) # self.config.text_cls_sentence_len=20\n data_line = text.strip().split(' ')\n for pos in range(min(len(data_line), self.config.text_cls_sentence_len)):\n text_array[0, pos] = int(self.reverse_word_id_dict.get(data_line[pos], 0))\n\n if debug:\n return text_array, data_line\n\n return text_array\n\n\n def load_raw_data(self, filepath):\n \"\"\"\n Loads MR polarity data from files, splits the data into words and generates labels.\n Returns split sentences and labels.\n \"\"\"\n # Load data from files\n train_datas = []\n with open(filepath, 'r', encoding='utf-8',errors='ignore') as f:\n train_datas = f.readlines()\n one_hot_labels = []\n x_datas = []\n for line in train_datas:\n parts = line.encode('utf-8').decode('utf-8-sig').strip().split(' ',1)\n if len(parts)<2 or (len(parts[1].strip()) == 0):\n continue\n x_datas.append(parts[1])\n one_hot_label = [0]*self.num_classes\n label = int(parts[0])\n one_hot_label[label] = 1\n one_hot_labels.append(one_hot_label)\n print (' data size = ' ,len(train_datas))\n return [x_datas, np.array(one_hot_labels)]\n\n\n def load_data(self):\n \"\"\"Loads starter word-vectors and train/dev/test data.\"\"\"\n print(\"Loading word2vec and textdata...\")\n x_text, y = self.load_raw_data(self.train_data_path)\n\n max_document_length = max([len(x.split(\" \")) for x in x_text])\n print('len(x) = ', len(x_text), ' ', len(y))\n print(' max_document_length = ', max_document_length)\n x = []\n x = self.get_data_idx(x_text)\n np.random.seed(10)\n shuffle_indices = np.random.permutation(np.arange(len(y)))\n x_shuffled = x[shuffle_indices]\n y_shuffled = y[shuffle_indices]\n\n dev_sample_index = -1 * int(self.dev_sample_percentage * float(len(y)))\n x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]\n y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]\n\n return x_train, x_dev, y_train, y_dev\n\n\n def clean_str(self, string):\n \"\"\"\n Tokenization/string cleaning for all datasets except for SST.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n \"\"\"\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n\n\n def load_data_and_labels(self, positive_data_file, negative_data_file):\n \"\"\"\n Loads MR polarity data from files, splits the data into words and generates labels.\n Returns split sentences and labels.\n \"\"\"\n # Load data from files\n positive_examples = list(open(positive_data_file, \"r\", encoding='utf-8').readlines())\n positive_examples = [s.strip() for s in positive_examples]\n negative_examples = list(open(negative_data_file, \"r\", encoding='utf-8').readlines())\n negative_examples = [s.strip() for s in negative_examples]\n # Split by words\n x_text = positive_examples + negative_examples\n x_text = [self.clean_str(sent) for sent in x_text]\n # Generate labels\n positive_labels = [[0, 1] for _ in positive_examples]\n negative_labels = [[1, 0] for _ in negative_examples]\n y = np.concatenate([positive_labels, negative_labels], 0)\n return [x_text, y]\n\n\n def batch_iter(self, data, batch_size, num_epochs, shuffle=True):\n \"\"\"\n Generates a batch iterator for a dataset.\n \"\"\"\n data = np.array(data)\n data_size = len(data)\n num_batches_per_epoch = int((len(data)-1)/batch_size) + 1\n for epoch in range(num_epochs):\n # Shuffle the data at each epoch\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_data = data[shuffle_indices]\n else:\n shuffled_data = data\n for batch_num in range(num_batches_per_epoch):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, data_size)\n yield shuffled_data[start_index:end_index]\n\n\n def data_processing(self, train_data_dir):\n print(\"[INFO] Loading data...\")\n x_text, y = text_cls_data_loader.load_raw_data(train_data_dir)\n\n # Build vocabulary\n max_document_length = max([len(x.split(\" \")) for x in x_text])\n vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)\n x = np.array(list(vocab_processor.fit_transform(x_text)))\n\n # Randomly shuffle data\n np.random.seed(10)\n shuffle_indices = np.random.permutation(np.arange(len(y)))\n x_shuffled = x[shuffle_indices]\n y_shuffled = y[shuffle_indices]\n\n # Split train/test set\n # TODO: This is very crude, should use cross-validation\n dev_sample_index = -1 * int(self.val_sample_ratio * float(len(y)))\n x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]\n y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]\n\n del x, y, x_shuffled, y_shuffled\n\n print(\"[INFO] Vocabulary Size: {:d}\".format(len(vocab_processor.vocabulary_)))\n print(\"[INFO] Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\n\n return x_train, y_train, vocab_processor, x_dev, y_dev\n\n\nclass ner_data_loader(object):\n\n def __init__(self, setting):\n self.config = setting\n\n self.train_data_dir = setting.ner_train_dir\n self.train_label_dir = setting.ner_train_label_dir\n self.test_data_dir = setting.ner_test_dir\n self.test_label_dir = setting.ner_test_label_dir\n\n self.vocab_dir = setting.ner_vocab_dir\n self.state_dict = setting.state_dict\n self.batch_size = setting.ner_batch_size\n self.sentence_len = setting.ner_sentence_len\n self.embedding_dir = setting.ner_embedding_dir\n self.val_sample_ratio = setting.ner_val_sample_ratio\n self.reverse_state_dict = dict((v, k) for k, v in self.state_dict.items()) # id2state\n\n self.train_data_raw = list()\n self.train_label_raw = list()\n self.valid_data_raw = list()\n self.valid_label_raw = list()\n self.test_data_raw = list()\n self.test_label_raw = list()\n\n self.embedding = None\n self.embedding_shape = 0\n\n self.word_id_dict = None\n self.reverse_word_id_dict = None\n\n\n def load_embedding(self, debug=False):\n self.embedding = np.load(self.embedding_dir)\n self.embedding_shape = np.shape(self.embedding)[-1]\n\n with open(self.vocab_dir, encoding=\"utf8\") as file:\n self.word_id_dict = json.load(file)\n\n self.reverse_word_id_dict = {}\n for each in self.word_id_dict:\n self.reverse_word_id_dict.setdefault(self.word_id_dict[each], each)\n\n if debug:\n return self.embedding, self.embedding_shape, self.word_id_dict, self.reverse_word_id_dict\n\n\n def input_text_process(self, text, debug=False):\n # 初步处理输入文本\n words_x_list = list()\n seq_len_list = list()\n output_x_list = list()\n raw_input_list = list()\n data_cut_by_jieba_list = list(jieba.cut(text.strip()))\n\n count = len(data_cut_by_jieba_list) // self.sentence_len\n\n if len(data_cut_by_jieba_list) % self.sentence_len:\n count += 1\n\n for j in range(count):\n raw_input_list.append(data_cut_by_jieba_list[j*self.sentence_len: (j+1)*self.sentence_len])\n\n for idx, raw_input in enumerate(raw_input_list):\n _words = [word for word in raw_input]\n seq_len_list.append(min(self.sentence_len, len(raw_input)))\n _data_trans = [int(self.reverse_word_id_dict.get(word, 0)) for word in raw_input]\n\n pad_data = self.pad_sequence(_data_trans, self.sentence_len, 0) # 填充\n output_x_list.append(pad_data)\n words_x_list.append(_words)\n if debug:\n print('[DEBUG] ', str(idx), ' _words = ', _words, '\\n')\n print('[DEBUG] ', str(idx), ' _data_trans = ', _data_trans, '\\n')\n print('[DEBUG] ', str(idx), ' pad_data =', pad_data, '\\n')\n\n if debug:\n return raw_input_list, output_x_list, words_x_list, seq_len_list, count, data_cut_by_jieba_list\n\n return words_x_list, output_x_list, seq_len_list\n\n\n def pad_sequence(self, seq, obj_len, pad_value=None):\n '''\n :param seq: 待填充的序列\n :param obj_len: 填充的目标长度\n :return:\n '''\n seq_copy = copy.deepcopy(seq[:obj_len]) #若seq过长就截断,若短于obj_len就复制全部元素\n if pad_value is None:\n seq_copy = seq_copy * (1 + int((0.5 + obj_len) / (len(seq_copy))))\n seq_copy = seq_copy[:obj_len]\n else:\n seq_copy = seq_copy + [pad_value] * (obj_len - len(seq_copy))\n return seq_copy\n\n\n\nif __name__ == '__main__':\n import settings\n\n setting = settings.setting()\n\n obj = text_cls_data_loader(setting)\n obj.load_embedding()\n text_array = obj.text_input_to_array('你好,我是李自然')\n print(obj.reverse_word_id_dict.get('你好', 0))\n print(obj.reverse_word_id_dict.get('痔宁片', 0))\n print(obj.reverse_word_id_dict.get('儿泻', 0))","repo_name":"DemonDamon/medichat","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25877383624","text":"# In[ ]:\n# -*- coding: utf-8 -*-\nimport pymongo\nfrom pymongo import MongoClient\nimport datetime as dt\nimport time\nimport json\nfrom time import gmtime, strftime\n\nimport GetWordclouds\n\n\n#In[]:\n# client = MongoClient('mongodb://localhost:27017/University')\nclient = MongoClient('mongodb://superadmin:4rFV5tGB@45.32.105.145:27017/University?authSource=admin')\ndb = client.University\n\n\n#In[]:\n\nfrom random import seed\nfrom random import randint\nseed(1)\ndef test():\n timestamp = 1587168000000\n chulaPM = []\n thammasatPM = []\n mahidolPM = []\n kasetsartPM = []\n chiangMaiPM = []\n khonKaenPM = []\n srinakharinwirotPM = []\n MahasarakhamPM = []\n BuraphaPM = []\n maeFahLuangPM = []\n\n chula = 0\n thammasat = 0\n mahidol = 0\n kasetsart = 0\n chiangMai = 0\n khonKaen = 0\n srinakharinwirot = 0\n Mahasarakham = 0\n Burapha = 0\n maeFahLuang = 0\n\n for i in range(144):\n chula += randint(50, 150)\n thammasat += randint(0, 50)\n mahidol += randint(30, 40)\n kasetsart += randint(70, 100)\n chiangMai += randint(20, 50)\n khonKaen += randint(30, 50)\n srinakharinwirot += randint(0, 10)\n Mahasarakham += randint(2, 5)\n Burapha += randint(0, 20)\n maeFahLuang += randint(0, 10)\n chulaPM.append([timestamp,chula])\n thammasatPM.append([timestamp,thammasat])\n mahidolPM.append([timestamp,mahidol])\n kasetsartPM.append([timestamp,kasetsart])\n chiangMaiPM.append([timestamp,chiangMai])\n khonKaenPM.append([timestamp,khonKaen])\n srinakharinwirotPM.append([timestamp,srinakharinwirot])\n MahasarakhamPM.append([timestamp,Mahasarakham])\n BuraphaPM.append([timestamp,Burapha])\n maeFahLuangPM.append([timestamp,maeFahLuang])\n timestamp+= 600000\n db.graph_retweet_UI.delete_many({})\n db.graph_retweet_UI.insert_one({\n \"name\":\"จุฬาลงกรณ์มหาวิทยาลัย\",\n \"data\":chulaPM\n })\n db.graph_retweet_UI.insert_one({\n \"name\":\"มหาวิทยาลัยธรรมศาสตร์\",\n \"data\":thammasatPM\n })\n db.graph_retweet_UI.insert_one({\n \"name\":\"มหาวิทยาลัยมหิดล\",\n \"data\":mahidolPM\n })\n db.graph_retweet_UI.insert_one({\n \"name\":\"มหาวิทยาลัยเกษตรศาสตร์\",\n \"data\":kasetsartPM\n })\n db.graph_retweet_UI.insert_one({\n \"name\":\"มหาวิทยาลัยเชียงใหม่\",\n \"data\":chiangMaiPM\n })\n db.graph_retweet_UI.insert_one({\n \"name\":\"มหาวิทยาลัยขอนแก่น\",\n \"data\":khonKaenPM\n })\n db.graph_retweet_UI.insert_one({\n \"name\":\"มหาวิทยาลัยศรีนครินทรวิโรฒ\",\n \"data\":srinakharinwirotPM\n })\n db.graph_retweet_UI.insert_one({\n \"name\":\"มหาวิทยาลัยมหาสารคาม\",\n \"data\":MahasarakhamPM\n })\n db.graph_retweet_UI.insert_one({\n \"name\":\"มหาวิทยาลัยบูรพา\",\n \"data\":BuraphaPM\n })\n db.graph_retweet_UI.insert_one({\n \"name\":\"มหาวิทยาลัยแม่ฟ้าหลวง\",\n \"data\":maeFahLuangPM\n })\n\ndef sort_by_retweet(d):\n return d['retweet']\n\ndef test2():\n tweetTrends = []\n updateTrend = []\n removeTrend = []\n # thistime = dt.datetime.today()\n dataB = db.retweet_permin_data.aggregate([\n {\"$match\": {\"timeUpdate\":{\"$gte\":thistime - dt.timedelta(minutes=120)}}},\n { \"$group\": {\n \"_id\": \"$id_str\",\n \"retweetNow\": { \n \"$sum\": { \n \"$cond\": [\n { \"$gte\": [ \"$timeUpdate\", thistime - dt.timedelta(minutes=120) ] },\n \"$retweet\", \n 0\n ]\n }\n },\n }},\n ])\n for item in dataB:\n tweetTrends.append({'id':item['_id'],'retweet':item['retweetNow']})\n tweetTrends.sort(key=sort_by_retweet, reverse=True)\n dataA = db.master_data.find({'trend':{\"$gte\":1}})\n for i in range(10):\n print(tweetTrends[i]['id'])\n print(tweetTrends[i]['retweet'])\n for i in dataA:\n removeTrend.append((pymongo.UpdateOne(\n {\n 'id_str':i['id_str']\n },\n {\n '$set': {\n \"trend\": 0\n }\n },upsert=True)))\n if(len(removeTrend)>0):\n db.master_data.bulk_write(removeTrend,ordered=False)\n for i in range(10):\n updateTrend.append((pymongo.UpdateOne(\n {\n 'id_str':tweetTrends[i]['id']\n },\n {\n '$set': {\n \"trend\": i+1\n }\n },upsert=True)))\n if(len(updateTrend)>0):\n db.master_data.bulk_write(updateTrend,ordered=False)\n\n# def test3():\n# count = 0\n# dataA = db.retweet_permin_data.find({'id_str':'1255532245437214720'})\n# for i in dataA:\n# count+=i['retweet']\n# print(count)\n\ndef test3():\n updateTrend = []\n dataA = db.master_data.find({})\n for i in dataA:\n updateTrend.append((pymongo.UpdateOne(\n {\n 'id_str':i['id_str']\n },\n {\n '$set': {\n \"retweet_1Day\":0\n }\n },upsert=True)))\n if(len(updateTrend)>0):\n db.master_data.bulk_write(updateTrend,ordered=False)\n\ndef sort_by_re(d):\n '''a helper function for sorting'''\n return d['y']\n\ndef test4():\n checkRetweet = []\n chula2 = 0\n thammasat2 = 0\n mahidol2 = 0\n kasetsart2 = 0\n chiangMai2 = 0\n khonKaen2 = 0\n srinakharinwirot2 = 0\n Mahasarakham2 = 0\n Burapha2 = 0\n maeFahLuang2 = 0\n\n dataA = db.retweet_permin_data.aggregate([\n {\"$match\": {\"timeUpdate\":{\"$gte\":dt.datetime(2020, 6, 2, 0, 0, 0, 0)}}},\n { \"$group\": {\n \"_id\": \"$university\",\n \"retweetNow\": { \n \"$sum\": { \n \"$cond\": [\n { \"$gte\": [ \"$timeUpdate\", dt.datetime(2020, 6, 2, 0, 0, 0, 0) ] },\n \"$retweet\", \n 0\n ]\n }\n },\n }},\n ])\n for i in dataA:\n if i['_id'] == 'Thammasat':\n thammasat2 = i['retweetNow']\n if i['_id'] == 'Chula':\n chula2 = i['retweetNow']\n if i['_id'] == 'Mahidol':\n mahidol2 = i['retweetNow']\n if i['_id'] == 'Kasetsart':\n kasetsart2 = i['retweetNow']\n if i['_id'] == 'Chiang Mai':\n chiangMai2 = i['retweetNow']\n if i['_id'] == 'Khon Kaen':\n khonKaen2 = i['retweetNow']\n if i['_id'] == 'Srinakharinwirot':\n srinakharinwirot2 = i['retweetNow']\n if i['_id'] == 'Mahasarakham':\n Mahasarakham2 = i['retweetNow']\n if i['_id'] == 'Burapha':\n Burapha2 = i['retweetNow']\n if i['_id'] == 'Mae Fah Luang':\n maeFahLuang2 = i['retweetNow']\n \n checkRetweet.append({\"x\":\"1\",\n \"y\":chula2})\n checkRetweet.append({\"x\":\"2\",\n \"y\":thammasat2})\n checkRetweet.append({\"x\":\"3\",\n \"y\":mahidol2})\n checkRetweet.append({\"x\":\"4\",\n \"y\":kasetsart2})\n checkRetweet.append({\"x\":\"5\",\n \"y\":chiangMai2})\n checkRetweet.append({\"x\":\"6\",\n \"y\":khonKaen2})\n checkRetweet.append({\"x\":\"7\",\n \"y\":srinakharinwirot2})\n checkRetweet.append({\"x\":\"8\",\n \"y\":Mahasarakham2})\n checkRetweet.append({\"x\":\"9\",\n \"y\":Burapha2})\n checkRetweet.append({\"x\":\"10\",\n \"y\":maeFahLuang2})\n checkRetweet.sort(key=sort_by_re, reverse=True)\n\ndef test5():\n toxic = 'เย็ด'\n delete = []\n dataA = db.wordCloud_UI.find()\n for i in dataA:\n if toxic in i['text']:\n delete.append(i['text'])\n db.wordCloud_UI.delete_many({\"text\": {\"$in\": delete}})\n\nif __name__ == \"__main__\":\n thistime = dt.datetime.today() \n t1 = time.time()\n # test5()\n # GetWordclouds.wordcloudUI(thistime)\n t2 = time.time()\n t3 = t2 - t1\n print(t3)","repo_name":"chanapat1752/Senior-Project-Picktoptrend.com","sub_path":"src/crawler/DataVisualization.py","file_name":"DataVisualization.py","file_ext":"py","file_size_in_byte":8905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"4825008003","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\nREQUIRED_PACKAGES = ['six', 'absl-py', 'numpy']\nEXTRA_PACKAGES = {\n 'tensorflow': ['tensorflow>=1.8.0'],\n 'tensorflow with gpu': ['tensorflow-gpu>=1.8.0'],\n 'sonnet': ['dm-sonnet>=1.26'],\n 'sonnet with gpu': ['dm-sonnet-gpu>=1.26'],\n}\n\n\ndef ibp_test_suite():\n test_loader = unittest.TestLoader()\n test_suite = test_loader.discover('interval_bound_propagation/tests',\n pattern='*_test.py')\n return test_suite\n\nsetup(\n name='interval_bound_propagation',\n version='1.1',\n description='A library to train verifiably robust neural networks.',\n url='https://github.com/deepmind/interval_bound_propagation',\n author='DeepMind',\n author_email='no-reply@google.com',\n # Contained modules and scripts.\n packages=find_packages(),\n install_requires=REQUIRED_PACKAGES,\n extras_require=EXTRA_PACKAGES,\n platforms=['any'],\n license='Apache 2.0',\n test_suite='setup.ibp_test_suite',\n)\n","repo_name":"deepmind/interval-bound-propagation","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":139,"dataset":"github-code","pt":"3"}
+{"seq_id":"29256346497","text":"import datetime as dt\nimport pytest\nfrom unittest import mock\n\nfrom bson.objectid import ObjectId\nimport pytz\n\nfrom maps.garden.sdk.core import Version\nfrom maps.garden.sdk.resources import PythonResource\nfrom maps.garden.libs_server.task.yt_task import (\n ContourSettings,\n SchedulerTaskEvent,\n YtTask\n)\nfrom maps.garden.libs_server.task import task_storage\n\nCONTOUR_NAME = \"contour_name\"\n\nNOW = dt.datetime(2020, 8, 25, 16, 20, 00, tzinfo=pytz.utc)\n\n\n@pytest.fixture\ndef tasks_collection(db):\n return db.task_log\n\n\n@pytest.mark.freeze_time(NOW)\ndef test_save_task(db, freezer):\n storage = task_storage.TaskStorage(db)\n yt_task = _make_yt_task()\n\n storage.insert(task_storage.TaskRecord.from_yt_task(yt_task))\n\n expected_task_record = task_storage.TaskRecord(\n mongo_id=yt_task.task_key,\n name=\"task_name\",\n garden_task_id=\"1\",\n module_name=\"test_module\",\n build_id=10,\n contour_name=CONTOUR_NAME,\n input_proto=b\"mocked input\",\n output_proto=None,\n created_at=NOW,\n updated_at=NOW,\n )\n actual_task_record = storage.find_by_key(yt_task.task_key)\n assert actual_task_record == expected_task_record\n\n freezer.move_to(NOW + dt.timedelta(hours=1))\n storage.update(\n task_key=yt_task.task_key,\n invocation_status=task_storage.TaskInvocationStatus.RUNNING,\n )\n expected_task_record.updated_at = NOW + dt.timedelta(hours=1)\n expected_task_record.invocation_status = task_storage.TaskInvocationStatus.RUNNING\n actual_task_record = storage.find_by_key(yt_task.task_key)\n assert actual_task_record == expected_task_record\n\n freezer.move_to(NOW + dt.timedelta(hours=2))\n storage.update(\n task_key=yt_task.task_key,\n invocation_status=task_storage.TaskInvocationStatus.FINISHED,\n output_proto=b\"mocked output\"\n )\n expected_task_record.updated_at = NOW + dt.timedelta(hours=2)\n expected_task_record.invocation_status = task_storage.TaskInvocationStatus.FINISHED\n expected_task_record.output_proto = b\"mocked output\"\n actual_task_record = storage.find_by_key(yt_task.task_key)\n assert actual_task_record == expected_task_record\n\n freezer.move_to(NOW + dt.timedelta(hours=3))\n storage.update(\n task_key=yt_task.task_key,\n invocation_status=task_storage.TaskInvocationStatus.RUNNING\n )\n actual_task_record = storage.find_by_key(yt_task.task_key)\n assert actual_task_record == expected_task_record\n\n\n@pytest.mark.freeze_time(NOW)\ndef test_find_tasks(db, freezer):\n storage = task_storage.TaskStorage(db)\n\n yt_task1 = _make_yt_task()\n storage.insert(task_storage.TaskRecord.from_yt_task(yt_task1))\n storage.update(\n task_key=yt_task1.task_key,\n invocation_status=task_storage.TaskInvocationStatus.RUNNING\n )\n\n freezer.move_to(NOW + dt.timedelta(hours=2))\n yt_task2 = _make_yt_task()\n storage.insert(task_storage.TaskRecord.from_yt_task(yt_task2))\n\n assert set(\n str(t.mongo_id) for t in storage.find(invocation_statuses=[task_storage.TaskInvocationStatus.RUNNING])\n ) == {yt_task1.task_key}\n\n assert set(str(t.mongo_id) for t in storage.find(updated_before=NOW + dt.timedelta(hours=1))) == {yt_task1.task_key}\n assert set(str(t.mongo_id) for t in storage.find(updated_after=NOW + dt.timedelta(hours=1))) == {yt_task2.task_key}\n\n\n@pytest.mark.use_local_mongo\ndef test_pick_by_key_and_update(db):\n # use local db, because current version of mongomock can't work with \"$cond\" into update()\n storage = task_storage.TaskStorage(db)\n\n yt_task = _make_yt_task()\n storage.insert(task_storage.TaskRecord.from_yt_task(yt_task))\n storage.update(task_key=yt_task.task_key)\n\n old_task_record = storage.pick_by_key_and_update(\n task_key=yt_task.task_key,\n operation_id=\"new_operation_id\",\n job_id=\"new_job_id\"\n )\n\n assert not old_task_record.input_was_used\n assert old_task_record.operation_id is None\n assert old_task_record.job_id is None\n\n new_task_record = storage.find_by_key(yt_task.task_key)\n\n assert new_task_record.input_was_used\n assert new_task_record.operation_id == \"new_operation_id\"\n assert new_task_record.job_id == \"new_job_id\"\n\n storage.pick_by_key_and_update(\n task_key=yt_task.task_key,\n operation_id=\"another_operation_id\",\n job_id=\"another_job_id\"\n )\n\n extra_new_task_record = storage.find_by_key(yt_task.task_key)\n assert extra_new_task_record.operation_id == \"new_operation_id\"\n assert extra_new_task_record.job_id == \"new_job_id\"\n\n unknown_task_record = storage.pick_by_key_and_update(\n task_key=str(ObjectId()),\n operation_id=\"any_operation_id\",\n job_id=\"any_job_id\"\n )\n assert unknown_task_record is None\n\n\ndef _make_yt_task():\n task = mock.Mock(\n displayed_name=\"task_name\",\n insert_traceback=\"some traceback\",\n )\n task.make_task_call_stdin.return_value = b\"mocked input\"\n\n versioned_task = mock.Mock(\n request_ids=[1, 2],\n task=task,\n contour_name=CONTOUR_NAME,\n module_name=\"test_module\",\n module_version=\"1234\",\n retries=1,\n ready_for_execution_at=dt.datetime.now(pytz.utc),\n )\n\n demands_resource = PythonResource(\"demands_resource\")\n demands_resource.version = Version(properties={\"date\": \"dateA\"})\n\n creates_resource = PythonResource(\"creates_resource\")\n creates_resource.version = Version(properties={\"date\": \"dateB\"})\n\n task = YtTask(\n task_id=1,\n contour_name=CONTOUR_NAME,\n module_name=versioned_task.module_name,\n build_id=10,\n task_key=str(ObjectId()),\n consumption={\"cpu\": 1},\n log_file_basename=\"log_file_basename\",\n versioned_task=versioned_task,\n operation_id=\"vanilla_operation_id\",\n job_id=\"job_id\",\n demands={\n \"demands_resource\": demands_resource\n },\n creates={\n \"creates_resource\": creates_resource\n },\n contour_settings=ContourSettings(\n environment_settings={\n \"logs_storage\": {\n \"type\": \"s3\",\n \"bucket\": \"bucket-for-logs\",\n \"key_prefix\": \"\"\n },\n \"s3\": {\n \"host\": \"localhost\",\n \"port\": 1000\n }\n },\n environment_settings_ypath=\"\",\n yt_work_dir=\"\",\n )\n )\n task.register_event(SchedulerTaskEvent.RESOURCES_ALLOCATED)\n return task\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"maps/tests/test_task_storage.py","file_name":"test_task_storage.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38103385202","text":"import csv\n\n\ndef write_file(file_path, head_list: list, content_list:list):\n \"\"\"\n 写入文件\n :param file_path:\n :param head_list:\n :param content_list:\n :return:\n \"\"\"\n f = open(file_path, 'w', encoding='utf-8-sig', newline='')\n csv_writer = csv.writer(f)\n csv_writer.writerow(head_list)\n if content_list is not None:\n csv_writer.writerows(content_list)\n\n f.close()\n","repo_name":"hjcenry/bill_analysis","sub_path":"util/csv_writer.py","file_name":"csv_writer.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"13395832119","text":"from multiprocessing.sharedctypes import Value\nfrom turtle import onclick\nimport streamlit as st\nimport requests\n# from requests.adapters import HTTPAdapter\n# from requests.packages.urllib3.util.retry import Retry\nfrom typing import List, Tuple\n# import base64 # 나중에 이미지 업로드 용\n\nst.markdown(\"하루의 마침표
\", unsafe_allow_html=True)\nst.markdown(\"당신의 감정에 맞는 컨텐츠를 소개해드립니다.
\", unsafe_allow_html=True) # TODO: 이 밑에 여백 넣기!\nuser_diary = st.text_area(label =\"\", placeholder = f\"오늘 하루는 어떠셨나요? 일기든, 감정을 나타내는 키워드든 자유로운 형식으로 정리해보세요.\", height=250)\n\n### avoiding refresing the entire page when clicking a button\n\n### session state\nif 'user_button' not in st.session_state:\n st.session_state.user_button = True\n\nif 'user_button' not in st.session_state:\n st.session_state.user_button = True\n# def update_session():\n# st.session_state.update = \n\n### column \n_, col, _ = st.columns([1.5]*2+[1])\nuser_feelings_button = col.button(\"내 감정 정리하기!\", key='user_button') # st.button은 session_state를 지원하지 않아서 임시방편으로 chckbox를 사용함\n\n\nst.markdown(\"***\", unsafe_allow_html=True)\n\n### TODO: 기록 확인하기 (유저 history data)\n\n### 필요한 부분들을 미리 선언해둡니다. \nemotions = []\nuser_label_dict = {}\n## 이 부분은 나중에 GET으로 처리예정\nKOTE_label = ['불평/불만', '환영/호의', '감동/감탄', '지긋지긋', '고마움', '슬픔', '화남/분노', '존경', '기대감', '우쭐댐/무시함', '안타까움/실망', '비장함', '의심/불신', '뿌듯함', '편안/쾌적', '신기함/관심', '아껴주는', '부끄러움', '공포/무서움', '절망', '한심함', '역겨움/징그러움', '짜증', '어이없음', '없음', '패배/자기혐오', '귀찮음', '힘듦/지침', '즐거움/신남', '깨달음', '죄책감', '증오/혐오', '흐뭇함(귀여움/예쁨)', '당황/난처', '경악', '부담/안_내킴', '서러움', '재미없음', '불쌍함/연민', '놀람', '행복', '불안/걱정', '기쁨', '안심/신뢰']\nKOTE_label_dict = {i:KOTE_label[i] for i in range(len(KOTE_label))}\noption1, option2, option3 = '', '', ''\n### 사용자 일기 받아서 respose 받아오기\n\ndef get_feelings_from_diary(user_diary: str) -> List:\n response = requests.post(url=\"http://localhost:8000/diary/input\", json = {\"diary_content\": user_diary})\n emotions = eval(response.text)\n return emotions\n\n\ndef get_songs_from_emotions(user_selection: List) -> List:\n response = requests.post(url=\"http://localhost:8000/diary/input\", json = {\"now_feelings\": user_selection})\n playlists = eval(response.text)\n\n\ndef select_emotion_label(temp_data: Tuple) -> List:\n temp_data = return_user_feelings()\n if temp_data[0] == \"KOTE\":\n final_selection = [x for x, y in zip(KOTE_label, index) if y == True]\n else:\n final_selection = [x for x, y in zip(emotions, index) if y == True]\n\n return final_selection\n\n\n# @st.cache(suppress_st_warning=True)\ndef return_user_feelings() -> List:\n global emotions\n global user_label_dict\n print(\"emotions from get_feelings_from_diary\", emotions)\n emotions = get_feelings_from_diary(user_diary)\n print(emotions, len(emotions), type(emotions))\n\n there_is_no_emotions = st.button(\"원하는 감정이 없어요!\",)\n # there_is_no_emotions = st.radio(label=\"원하는 감정이 없다면 아래 radio를 선택하세요!\", options=['원하는 감정이 없어요'], key='emotion_checkbox', disabled=False)\n\n if there_is_no_emotions:\n for i in range(len(KOTE_label)):\n globals()[f'options_{i}'] = st.checkbox(KOTE_label[i])\n index = [f'options_{i}' for i in range(len(KOTE_label))]\n return (\"KOTE\", index)\n else:\n option1 = st.checkbox(emotions[0])\n option2 = st.checkbox(emotions[1])\n option3 = st.checkbox(emotions[2])\n index = [option1, option2, option3]\n\n return (\"emotions\", index)\n\nemotion_data = return_user_feelings()\nfinal_selection = select_emotion_label(emotion_data)\nprint(\"final_selection: \", final_selection)\n\n\n# def main():\n# # emotions = return_user_feelings(user_feelings_button)\n# print(\"emotions: \", emotions)\n# print(\"-----------------------------------------------\")\n# # print(user_label_dict)\n# # print(user_label_dict[0], user_label_dict[1], user_label_dict[2])\n# # print(f1, f2, f3)\n# st.write('Select three known variables:')\n\n# option_1 = st.checkbox(\"A\")\n# # option_2 = st.checkbox(emotions[1])\n# # option_1 = st.multiselect(label = \"감정을 골라보세요!\", options = emotions)\n\n# # print(option_1, option_2, option_3)\n# # f1, f2, f3 = return_user_feelings(user_feelings_button)\n# st.write(\"지금의 감정들이 맞는지 확인한 후 선택해주세요. 만약 없다면 하단의 버튼을 클릭해주세요. \")\n\n\n# main()\n\n\n\n\n# TODO: 사용자 감정을 받아서 checkbox로 출력\n\n\n\n\n# for i in range(len(emotions)):\n# user_label_dict[f\"options_{i}\"] = st.checkbox(emotions[i])\n\n# print(d)\n# user_contents_selection = st.multiselect(\n# \"지금의 감정들이 맞는지 확인해주세요. 만약 아니라면, 다음을 선택해주세요!\",\n# string\n# )\n\n# print(user_contents_selection)\n# show_me_other_feelings = st.button(\"다른 감정들을 보여주세요\")\n\n# if show_me_other_feelings:\n# for i in range(len(KOTE_label)):\n# KOTE_label[i] = st.checkbox(KOTE_label[i])\n\n# st.write(\"이런 감정들을 선택하셨어요!\")\n# ## 사용자의 일기를 분석하여 감정을 보여줍니다. \n# show_user_feelings = st.multiselect(\n# \"지금 느끼는 감정들을 선택해주세요\", string\n# )\n\n\n\n# print(user_contents[1], user_contents[2], user_contents[3]) ## check selection\n\n# user_contents_selection = ''\n### radio button만들기\n\n# TODO 1: 사용자에게 감정 입력 받는 박스 만들기 (입력: 문장, 키워드, 일기 등 -> 출력: 감정 라벨)\n# if user_feeling_button:\n# print(\"Hello World!\") # 사용자의 감정을 정리해줍니다. 누가? 모델이.\n\n\n# TODO 2: 사용자가 감정을 입력하면 이를 키워드로 나타내는 모델과 연결시키기\n\n##","repo_name":"boostcampaitech3/final-project-level3-nlp-01","sub_path":"app/frontend/write_page_streamlit.py","file_name":"write_page_streamlit.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28061846543","text":"import cv2\n\ndef sketch(img):\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img_gray_blur = cv2.GaussianBlur(img_gray, (5,5), 0) # clean up the noise in the image\n canny_edges = cv2.Canny(img_gray_blur, 20, 60)\n ret, mask = cv2.threshold(canny_edges, 60, 255, cv2.THRESH_BINARY_INV)\n return mask\n\nif __name__ == \"__main__\":\n capture = cv2.VideoCapture(0)\n while True:\n ret, frame = capture.read()\n cv2.imshow(\"LIVE sketch... \", sketch(frame))\n if cv2.waitKey(1) == 13: # 13 is the Enter key\n break\n capture.release()\n cv2.destroyAllWindows()\n","repo_name":"tanveer-sayyed/Experiments","sub_path":"Edge detector via webcam.py","file_name":"Edge detector via webcam.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16929233286","text":"import collections\n\n\ndef doc(s):\n if hasattr(s, '__call__'):\n s = s.__doc__\n\n def f(g):\n g.__doc__ = s\n return g\n\n return f\n\n\ndef _swap(arr, i, j):\n arr[i], arr[j] = arr[j], arr[i]\n arr[i][2] = i\n arr[j][2] = j\n\n\ndef _set(arr, i, item):\n arr[i] = item\n item[2] = i\n\n\ndef heappush(heap, item):\n \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n item[2] = len(heap)\n heap.append(item)\n _siftdown(heap, 0, len(heap) - 1)\n\n\ndef heappop(heap):\n \"\"\"Pop the smallest item off the heap, maintaining the heap invariant.\"\"\"\n lastelt = heap.pop() # raises appropriate IndexError if heap is empty\n if heap:\n returnitem = heap[0]\n _set(heap, 0, lastelt)\n _siftup(heap, 0)\n return returnitem\n return lastelt\n\n\n# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos\n# is the index of a leaf with a possibly out-of-order value. Restore the\n# heap invariant.\ndef _siftdown(heap, startpos, pos):\n newitem = heap[pos]\n # Follow the path to the root, moving parents down until finding a place\n # newitem fits.\n while pos > startpos:\n parentpos = (pos - 1) >> 1\n parent = heap[parentpos]\n if newitem[0] < parent[0]:\n _set(heap, pos, parent)\n pos = parentpos\n continue\n break\n _set(heap, pos, newitem)\n\n\ndef _siftup(heap, pos):\n endpos = len(heap)\n startpos = pos\n newitem = heap[pos]\n # Bubble up the smaller child until hitting a leaf.\n childpos = 2 * pos + 1 # leftmost child position\n while childpos < endpos:\n # Set childpos to index of smaller child.\n rightpos = childpos + 1\n if rightpos < endpos and not heap[childpos][0] < heap[rightpos][0]:\n childpos = rightpos\n # Move the smaller child up.\n _set(heap, pos, heap[childpos])\n pos = childpos\n childpos = 2 * pos + 1\n # The leaf at pos is empty now. Put newitem there, and bubble it up\n # to its final resting place (by sifting its parents down).\n _set(heap, pos, newitem)\n _siftdown(heap, startpos, pos)\n\n\nclass heapdict(collections.MutableMapping):\n __marker = object()\n\n def _check_invariants(self):\n # the 3rd entry of each heap entry is the position in the heap\n for i, e in enumerate(self.heap):\n assert e[2] == i\n # the parent of each heap element must not be larger than the element\n for i in range(1, len(self.heap)):\n parent = (i - 1) >> 1\n assert self.heap[parent][0] <= self.heap[i][0]\n\n def __init__(self, *args, **kw):\n self.heap = []\n self.d = {}\n self.update(*args, **kw)\n\n @doc(dict.clear)\n def clear(self):\n del self.heap[:]\n self.d.clear()\n\n @doc(dict.__setitem__)\n def __setitem__(self, key, value):\n if key in self.d:\n del self[key]\n wrapper = [value, key, -2]\n self.d[key] = wrapper\n heappush(self.heap, wrapper)\n\n @doc(dict.__delitem__)\n def __delitem__(self, key):\n wrapper = self.d[key]\n i = wrapper[2]\n lastindex = len(self.heap) - 1\n # swap with last item\n _swap(self.heap, i, lastindex)\n self.heap.pop()\n if self.heap and i < lastindex:\n _siftup(self.heap, i)\n _siftdown(self.heap, 0, i)\n del self.d[key]\n\n @doc(dict.__getitem__)\n def __getitem__(self, key):\n return self.d[key][0]\n\n @doc(dict.__iter__)\n def __iter__(self):\n return iter(self.d)\n\n def pop(self, *args):\n \"\"\"D.pop([k,[,d]]) -> v, if no key is specified, remove the key with the lowest\nvalue and return the corresponding value, raising IndexError if list is empty.\nIf a key is specified, then it is removed instead if present and the\ncorresponding value is returned. If the key is specified and not present, then\nd is returned if given, otherwise KeyError is raised\"\"\"\n if len(args) == 0:\n if len(self.d) == 0:\n raise IndexError(\"pop from empty heapdict\")\n (k, _) = self.popitem()\n else:\n k = super(heapdict, self).pop(*args)\n return k\n\n def popitem(self):\n \"\"\"D.popitem() -> (k, v), remove and return the (key, value) pair with lowest\\nvalue; but raise KeyError if D is empty.\"\"\"\n wrapper = heappop(self.heap)\n del self.d[wrapper[1]]\n return wrapper[1], wrapper[0]\n\n @doc(dict.__len__)\n def __len__(self):\n return len(self.d)\n\n def peekitem(self):\n \"\"\"D.peekitem() -> (k, v), return the (key, value) pair with lowest value;\\n but raise KeyError if D is empty.\"\"\"\n return (self.heap[0][1], self.heap[0][0])\n\n\ndel doc\n__all__ = ['heapdict']\n","repo_name":"urielha/heapdict","sub_path":"heapdict.py","file_name":"heapdict.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"44161862381","text":"from pdf2image import convert_from_path, convert_from_bytes\r\nfrom pdf2image.exceptions import (\r\n PDFInfoNotInstalledError,\r\n PDFPageCountError,\r\n PDFSyntaxError\r\n)\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\n\r\n\r\ndef convert_pdf_to_jpeg(folder_name):\r\n images_folder_name = 'images/'\r\n files = [f for f in listdir(folder_name) if isfile(join(folder_name, f))]\r\n for file in files:\r\n print(file)\r\n images = convert_from_path(folder_name+'/'+file, poppler_path=r\"C:\\Program Files\\Release-21.03.0\\poppler-21.03.0\\Library\\bin\")\r\n i = 0\r\n for im in images:\r\n im.save(images_folder_name + str(i) + '.jpg')\r\n i += 1\r\n return images_folder_name\r\n","repo_name":"KarinaGanieva-sl/OCR-with-super-resolution","sub_path":"pdf_to_image.py","file_name":"pdf_to_image.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"13681927063","text":"lista = [49, 42, True]\n\ndef somaTeste(val1, val2, imprime = False):\n resultado = val1 + val2\n if imprime:\n print(f\"Soma: {resultado}\")\n return resultado\n\ntotal = somaTeste(*lista)\n\nlista = [49, 42, True]\n\ndef somaTeste1(imprime, *valores):\n total = 0\n for valor in valores:\n total += valor\n if imprime:\n print(f\"SomaTeste1: {total}\")\n return total\n\nx = somaTeste1(False, 10,20,25,50,60,70)\nprint(x)","repo_name":"DiegoSantosWS/estudos-python","sub_path":"estudo-8/temp1.py","file_name":"temp1.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35525725051","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.jingle_home,name='jingle-home'),\n path('results//', views.jingle_top_search,name='jingle-results'),\n path('song//', views.jingle_results,name='jingle-song'),\n path('feedback/', views.jingle_feedback,name='jingle-feedback'),\n path('top_results/', views.jingle_topfifty,name='jingle-topfifty'),\n path('about/', views.about_page,name='jingle-about'),\n #path('topfifty//', views.jingle_results,name='jingle-results'),\n #path('error', views.jinge_error,name='jingle-error'),\n]\n","repo_name":"dantecoupet/jingle","sub_path":"Iteration3/SourceCode/jingle/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"25225881834","text":"from django.urls import path\nfrom .views import UsuarioList, UsuarioDelete, UsuarioCreate, UsuarioLogin\n\n\nurlpatterns = [\n path('list', UsuarioList.as_view()),\n path('create', UsuarioCreate.as_view()),\n path('delete/', UsuarioDelete.as_view()),\n path('login', UsuarioLogin.as_view()),\n]\n","repo_name":"PatrickDiestra/PruebaDjangoRest","sub_path":"apps/usuarios/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8064510281","text":"import math\n\nclass Node:\n def __init__(self, state, parent, actions, heuristic, totalCost):\n self.state = state\n self.parent = parent\n self.actions = actions\n self.heuristic = heuristic # Euclidean Distance.\n self.totalCost = totalCost\n\n# Define the get_neighbors, value, and state functions specific to your problem\n\ndef get_neighbors(node):\n return [graph[action[0]] for action in node.actions]\n\ndef value(node):\n return node.heuristic\n\ndef state(node):\n return node.state\n\n# Hill Climbing Algorithm Function\ndef hill_climbing(graph, initial_state, goal_state):\n current = graph[initial_state]\n\n while current.state != goal_state:\n neighbors = get_neighbors(current)\n\n if not neighbors:\n return None # No solution found\n\n # Find the neighbor with the highest heuristic value\n neighbor = max(neighbors, key=lambda node: value(node))\n\n if value(neighbor) <= value(current):\n return None # Local maximum reached\n\n current = neighbor\n\n return current.state\n\nif __name__ == \"__main__\":\n # Define your graph based on the provided nodes and actions\n graph = {\n \"A\": Node(\"A\", None, [(\"F\", 1)], (0, 0), 0),\n \"B\": Node(\"B\", None, [(\"C\", 1), (\"G\", 1)], (0, 2), 0),\n \"C\": Node(\"C\", None, [(\"B\", 1), (\"D\", 1)], (0, 3), 0),\n \"D\": Node(\"D\", None, [(\"C\", 1), (\"E\", 1)], (0, 4), 0),\n \"E\": Node(\"E\", None, [(\"D\", 1)], (0, 5), 0),\n \"F\": Node(\"F\", None, [(\"A\", 1), (\"H\", 1)], (1, 0), 0),\n \"G\": Node(\"G\", None, [(\"B\", 1), (\"J\", 1)], (1, 2), 0),\n \"H\": Node(\"H\", None, [(\"F\", 1), (\"I\", 1), (\"M\", 1)], (2, 0), 0),\n \"I\": Node(\"I\", None, [(\"N\", 1), (\"J\", 1)], (2, 1), 0),\n \"J\": Node(\"J\", None, [(\"G\", 1), (\"I\", 1)], (2, 2), 0),\n \"K\": Node(\"K\", None, [(\"L\", 1), (\"P\", 1)], (2, 4), 0),\n \"L\": Node(\"L\", None, [(\"K\", 1), (\"Q\", 1)], (2, 5), 0),\n \"M\": Node(\"M\", None, [(\"H\", 1), (\"N\", 1), (\"R\", 1)], (3, 0), 0),\n \"N\": Node(\"N\", None, [(\"I\", 1), (\"M\", 1), (\"S\", 1)], (3, 1), 0),\n \"O\": Node(\"O\", None, [(\"P\", 1), (\"U\", 1)], (3, 3), 0),\n \"P\": Node(\"P\", None, [(\"Q\", 1), (\"O\", 1)], (3, 4), 0),\n \"Q\": Node(\"Q\", None, [(\"L\", 1), (\"P\", 1), (\"V\", 1)], (3, 5), 0),\n \"R\": Node(\"R\", None, [(\"M\", 1), (\"S\", 1)], (4, 0), 0),\n \"S\": Node(\"S\", None, [(\"N\", 1), (\"R\", 1), (\"T\", 1)], (4, 1), 0),\n \"T\": Node(\"T\", None, [(\"S\", 1), (\"U\", 1), (\"W\", 1)], (4, 2), 0),\n \"U\": Node(\"U\", None, [(\"O\", 1), (\"T\", 1)], (4, 3), 0),\n \"V\": Node(\"V\", None, [(\"Q\", 1), (\"Y\", 1)], (4, 5), 0),\n \"W\": Node(\"W\", None, [(\"T\", 1)], (5, 2), 0),\n \"X\": Node(\"X\", None, [(\"Y\", 1)], (5, 4), 0),\n \"Y\": Node(\"Y\", None, [(\"V\", 1), (\"X\", 1)], (5, 5), 0),\n}\n\n initial_state = \"A\"\n goal_state = \"Y\"\n\n solution = hill_climbing(graph, initial_state, goal_state)\n\n if solution is not None:\n print(\"Solution found:\", solution)\n else:\n print(\"No solution found or local maximum reached.\")","repo_name":"HassanMahmoodAwan/Artificial-Intelligence-Course-in-Python","sub_path":"Hill_Climbing_Algo/Hill Climibing Algo.py","file_name":"Hill Climibing Algo.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72604244561","text":"from connect import *\n\n# Create a function to dump data into the songs table\n\ndef dataDump():\n # Load the songs.sql (script file)\n with open(r'Pt9_10DB\\songs.sql') as sqlScript:\n dumpData = sqlScript.read()\n dbCursor.executescript(dumpData)\n dbCon.commit()\n\nif __name__ == '__main__':\n dataDump()\n print('Data dumped successfully')\n","repo_name":"RGk1986/Python","sub_path":"Pt9_10DB/dataDump.py","file_name":"dataDump.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"3618898083","text":"# 7월 15일\n\n# 땅따먹기\n# https://programmers.co.kr/learn/courses/30/lessons/12913\n# lv2 연습문제 (DP?)\n\n# DP적인 관점으로 문제를 봐야한다.\n# 최대 N이 100,000 * 4라서 O(400,000)이 되어도 큰 문제는 없다.\n# DP적인 관점으로 자기 열을 제외한 최댓값을 누적하며 내려오자. \n\n# 시간 복잡도 O(N)\n\ndef solution(land):\n d = [[0, 0, 0, 0] for _ in range(len(land))]\n\n d[0] = land[0]\n\n for y in range(1, len(land)):\n for x in range(4):\n tmp = []\n for k in range(4):\n if x != k:\n tmp.append(d[y-1][k])\n\n d[y][x] = land[y][x] + max(tmp)\n\n return max(d[len(land) - 1])\n\nprint(solution([[1,2,3,5],[5,6,7,8],[4,3,2,1]]))","repo_name":"lee-gyu/happy_algorithm","sub_path":"20_07_July/0715_lee_programmers_12913.py","file_name":"0715_lee_programmers_12913.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16434273122","text":"import efuncs\nimport states\nimport magic\nimport random\nimport weapons\nimport items\n## PLAYER / CHARACTER ##\nclass Character():\n name = ''\n weapon = ''\n currenthealth = 0\n maxhealth = 0\n attack = 0\n baseattack = 0\n defense = 0\n magic = 0\n basemagic = 0\n spells = []\n mp = 0\n currentmp = 0\n resistance = 0\n speed = 0\n lvl = 0\n xp = 0\n tnl = 0\n state = ''\n armor = {}\n bag = []\n credits = 0\n spells_to_learn = []\n def __init__(self, name, weapon, currenthealth, maxhealth, attack, baseattack, defense, magic, basemagic, spells, mp, currentmp, resistance, speed, lvl, xp, tnl, state, armor, bag, credits, spells_to_learn):\n self.name = name\n self.weapon = weapon\n self.currenthealth = currenthealth\n self.maxhealth = maxhealth\n self.attack = attack\n self.baseattack = baseattack\n self.defense = defense\n #add basedefense for armor \n self.magic = magic\n self.basemagic = basemagic\n self.spells = spells\n self.mp = mp\n self.currentmp = currentmp\n self.resistance = resistance\n self.speed = speed\n self.lvl = lvl\n self.xp = xp\n self.tnl = tnl\n self.state = state\n self.armor = armor \n self.bag = bag\n self.credits = credits\n self.spells_to_learn = spells_to_learn\n def print_stats(self):\n print(f\"\"\"\n{self.name.title()}'s stats are as follows: \nWeapon: {self.weapon.name} \nCurrent HP: {str(self.currenthealth)} \nMax HP: {str(self.maxhealth)} \nATK: {str(self.attack)} \nBase ATK: {str(self.baseattack)} \nDEF: {str(self.defense)} \nMAG: {str(self.magic)} \nBase MAG: {str(self.basemagic)}\nSpells: [{efuncs.list_print(self.spells)}]\nMP: {str(self.mp)} \nCurrent MP: {str(self.currentmp)}\nRES: {str(self.resistance)} \nSPD: {str(self.speed)} \nLVL: {str(self.lvl)} \nXP: {str(self.xp)} \nTo next level: {str(self.tnl)}\nBag: [{efuncs.list_print(self.bag)}]\nCredits: {str(self.credits)}\n\"\"\")\n def use_magic(self, target, spell):\n print()\n if spell not in self.spells:\n print(f\"{self.name.title()} does not know that spell.\")\n else:\n if isinstance(spell, magic.Heal):\n print(f\"{self.name.title()} used {spell.name}!\")\n if (target.currenthealth + spell.heals) > (target.maxhealth):\n target.currenthealth = target.maxhealth\n else: \n target.currenthealth += spell.heals\n print(f\"{target.name.title()}\\'s health is now {target.currenthealth}!\")\n self.currentmp -= spell.cost\n elif isinstance(spell, magic.Buff):\n increased_by = spell.atkadd\n spell.value_buffer = target.attack\n target.attack += increased_by\n print(f\"{target.name.title()}\\'s ATK is now {str(target.attack)} for {str(spell.duration)} turns.\")\n self.currentmp -= spell.cost\n elif isinstance(spell, magic.Boost_Magic):\n print(f\"{self.name} used {spell.name}! {spell.attr_to_boost.title()} + {spell.boost_amt} for {spell.duration} turns.\")\n self.currentmp -= spell.cost \n target.adjust_val(spell.attr_to_boost, spell.boost_amt, spell.duration)\n elif isinstance(spell, magic.attack_spell):\n print(f\"{self.name.title()} used {spell.name}!\")\n self.magic += spell.damage\n if spell.kind == \"P\":\n defense_type = target.defense\n elif spell.kind == \"M\":\n defense_type = target.resistance\n spell_damage = (self.magic - defense_type) \n if spell_damage <= 0:\n spell_damage = 1\n spell_damage = int(round(spell_damage))\n target.currenthealth -= spell_damage\n print(f\"{target.name.title()} took {str(spell_damage)} damage. Their health is now {str(target.currenthealth)}\")\n self.magic = self.basemagic + self.weapon.mag\n self.currentmp -= spell.cost\n affliction_yes = random.randint(0, 10)\n if affliction_yes == 8:\n if spell.affliction == states.fire:\n states.set_player_state(target, states.fire)\n elif spell.affliction == states.frozen:\n states.set_player_state(target, states.frozen)\n def view_spells(self):\n print()\n spelldictionary = efuncs.make_temp_dictionary(self.spells)\n while True:\n try:\n print(\"Get more info on which spell?\")\n print(efuncs.pretty_print(self.spells)) \n detail = int(input(\">\\t\")) \n spellarg = spelldictionary[detail]\n efuncs.detailed_spell_view(spellarg)\n break \n except (ValueError, TypeError, IndexError):\n print(\"Invalid choice.\")\n continue\n def player_attack(self, enemy):\n damage = (self.attack - enemy.defense) \n if damage <= 0:\n damage = 1\n enemy.currenthealth -= damage\n print(f\"{self.name.title()} attacks {enemy.name.title()} for {damage} damage!\\n{enemy.name.title()}'s health is now {enemy.currenthealth}.\")\n if (self.speed - enemy.speed) >= 5:\n print(f\"Speed supremacy! {self.name.title()} gets another, weaker hit in!\")\n weak_damage = int(round(damage / 2))\n enemy.currenthealth -= weak_damage\n print(f\"{enemy.name.title()}\\'s health is now {enemy.currenthealth}.\")\n def equip_weapon(self, weapon):\n current_weapon = self.weapon\n if weapon.name == 'Athena\\'s Kiss':\n print(f\"{self.name} equips {weapon.name}. They feel their MAG strengthen.\")\n self.basemagic += 5\n if weapon.name == 'Draco\\'s Polearm':\n print(f\"{self.name} equips {weapon.name}. They feel their feet lighten.\")\n self.speed += 5\n if weapon.name == 'Lightning Sword':\n print(f\"{self.name} equips {weapon.name}. They feel their skin strengthen.\")\n self.defense += 3\n if weapon.name == 'Lightning Axe':\n print(f\"{self.name} equips {weapon.name}. They feel like they can deliver stronger blows to the enemy.\")\n self.baseattack += 3\n names_vals = {'Athena\\'s Kiss': (self.basemagic, 5), 'Draco\\'s Polearm': (self.speed, 5), 'Lightning Sword': (self.defense, 3), 'Lightning Axe': (self.baseattack, 3)}\n if current_weapon.name in names_vals.keys():\n resetattr = names_vals[current_weapon.name][0]\n resetamt = names_vals[current_weapon.name][1]\n resetattr -= resetamt\n print(f\"{self.name} unequipped {current_weapon.name}. They lost its positive effects.\")\n self.weapon = weapon\n self.attack = (self.baseattack + weapon.atk)\n self.magic = (self.basemagic + weapon.mag)\n if self == protag:\n print(f\"{self.name} now has an attack of {str(self.attack)} and a magic of {str(self.magic)}. They equipped {self.weapon.name}.\")\n def unequip_weapon(self):\n self.attack = self.baseattack\n self.mag = self.basemagic\n print(f\"{self.name} now has an attack of {str(self.attack)} and a magic of {str(self.magic)}. They unequipped {self.weapon}.\")\n self.weapon = 'Fisticuffs'\n def use_item(self, target, item):\n if item not in self.bag:\n print(f\"{self.name} does not have that item in their bag.\")\n else:\n if isinstance(item, items.Health_Potion):\n if (item.increase_amt + target.currenthealth) >= target.maxhealth:\n target.currenthealth = target.maxhealth\n else:\n target.currenthealth += item.increase_amt\n print(f\"{self.name} used {item.name}!\\n{target.name}'s HP is now {target.currenthealth}.\")\n if isinstance(item, items.Ether):\n if (item.increase_amt + target.currentmp) >= target.mp:\n target.currentmp = target.mp \n else:\n target.currentmp += item.increase_amt\n print(f\"{self.name} used {item.name}!\\nTarget MP is now {target.currentmp}.\")\n self.bag.remove(item)\n def adjust_val(self, attr, amt, duration, spell):\n before_adjust = getattr(self, attr)\n spell.value_buffer = before_adjust\n setattr(self, attr, (before_adjust + amt))\n #Adjust_val takes in a str and val and increments the attr by the val\n def xpcheck(self):\n if self.xp - self.tnl >= 0:\n startlvl = self.lvl\n while (self.xp - self.tnl) >= 0:\n self.lvl += 1\n extraxp = (self.xp - self.tnl)\n self.tnl = round((self.tnl + (self.tnl / 2))) \n self.currenthealth += 8\n self.maxhealth += 8\n self.baseattack += 5\n self.defense += 5\n self.basemagic += 5\n self.mp += 5\n self.currentmp += 5\n self.resistance += 5\n self.speed += 5\n self.xp = extraxp\n self.attack = (self.baseattack + self.weapon.atk)\n self.magic = (self.basemagic + self.weapon.mag)\n print(f\"{self.name.title()} gained {self.lvl - startlvl} level(s)!\")\n self.print_stats()\n else: \n needed = (self.tnl - self.xp)\n print(f\"{self.name} needs {str(needed)} more XP to level up.\\n\")\n def detail_str(self): \n detail = f\"{self.name} (HP: {self.currenthealth} / {self.maxhealth}, ATK: {self.attack}, MAG: {self.magic}, DEF: {self.defense}, RES: {self.resistance}, SPD: {self.speed})\"\n return detail\n\nparty = []\npartynames = []\ndef add_to_party(char):\n global party\n global partynames\n party.append(char)\n partynames.append(char.name)\n print(f\"{char.name} has joined the party.\")\ndef assign_party_leader():\n if len(party) <= 1:\n print(\"No one else is in contention for party leader.\")\n else:\n while True: \n try:\n desired = int(input(f\"\\nMake who the party leader?\\n{efuncs.pretty_print(party)}\\n>\\t\"))\n desired -= 1\n replacementidx = party.index(party[desired])\n temp = party[0]\n party[0] = 'temp'\n party[0] = party[replacementidx]\n party[replacementidx] = temp\n print(f\"{party[0].name} is now the party leader.\")\n break\n except ValueError:\n print(\"Not an option.\")\n continue\n except IndexError:\n print(\"Index error\")\n continue\n return party\n\n#Characters\n#name, weapon, currenthealth, maxhealth, attack, baseattack, defense, magic, basemagic, spells, mp, currentmp, resistance, speed, lvl, xp, tnl, state, armor, bag, credits, spells_to_learn\nprotag = Character('protag', weapons.fisticuffs, 140, 140, 15, 15, 15, 15, 15, [magic.healI, magic.fireball, magic.raze1], 45, 45, 15, 10, 1, 0, 50, states.normal, {}, [items.health_potion2], 0, [magic.healII, magic.buffII, magic.raze2, magic.fireball2, magic.luminaire, magic.healIV])\n\nkurita = Character('Kurita', weapons.fisticuffs, 210, 210, 40, 40, 35, 45, 45, [magic.healI, magic.buffI, magic.fireball], 85, 85, 45, 45, 5, 0, 75, states.normal, {}, [], 0, [magic.fireball2, magic.grand_fireball, magic.healIII, magic.healIV, magic.buffIII, magic.napalm])\n\nralf = Character('Ralf', weapons.fisticuffs, 300, 300, 65, 65, 40, 20, 20, [], 30, 30, 40, 50, 7, 0, 125, states.normal, {}, [], 0, [magic.healII, magic.icecicle_spear, magic.glacier])\n\nsakura = Character('Sakura', weapons.fisticuffs, 250, 250, 20, 20, 25, 60, 60, [magic.healII, magic.buffII, magic.fireball2, magic.raze1, magic.icecicle_spear2, magic.zapzap], 120, 120, 45, 20, 9, 0, 250, states.normal, {}, [], 0, [magic.healIV, magic.healV, magic.raze2, magic.scorched_earth])\n\nall_characters = [protag, kurita, ralf, sakura]\nrecruitable_chars = [kurita, ralf, sakura]\n\nstarting_weapons = [weapons.baseSword, weapons.poleArm, weapons.handAxe, weapons.wand]\n\ndef assign_weapon(sw):\n swd = efuncs.make_temp_dictionary(sw)\n while True:\n wp = input(f\"\\nWhat weapon would you like to wield?\\n{efuncs.pretty_print(sw)}\\nI: View weapon details\\n>\\t\")\n try:\n if wp in {'i', 'I'}:\n wpdetail = int(input(f\"\\nView details for what weapon?\\n1:\\tSword\\n2:\\tPolearm\\n3:\\tAxe\\n4:\\tWand\\n>\\t\"))\n efuncs.weapon_detail(swd[wpdetail])\n continue\n else:\n wp = int(wp)\n protag.equip_weapon(swd[wp])\n break\n except (ValueError, IndexError, KeyError):\n print(\"That's not an option.\")\n continue\n\n## BOSS / ENEMY ##\n\nclass Boss():\n name = ''\n weapon = ''\n currenthealth = 0\n maxhealth = 0\n attack = 0\n baseattack = 0\n defense = 0\n magic = 0\n basemagic = 0\n spells = []\n mp = 0\n currentmp = 0\n resistance = 0\n speed = 0\n state = ''\n def __init__(self, name, weapon, currenthealth, maxhealth, attack, baseattack, defense, magic, basemagic, spells, mp, currentmp, resistance, speed, state):\n self.name = name\n self.weapon = weapon\n self.currenthealth = currenthealth\n self.maxhealth = maxhealth\n self.attack = attack\n self.baseattack = baseattack\n self.defense = defense\n self.magic = magic\n self.basemagic = basemagic\n self.spells = spells\n self.mp = mp\n self.currentmp = currentmp\n self.resistance = resistance\n self.speed = speed\n self.state = state \n def print_boss_stats(self):\n print(f\"\"\"\n{self.name}\\'s stats are as follows: \nWeapon: {self.weapon.name} \nCurrent HP: {str(self.currenthealth)} \nMax HP: {str(self.maxhealth)} \nATK: {str(self.attack)} \nBase ATK: {str(self.baseattack)} \nDEF: {str(self.defense)} \nMAG: {str(self.magic)} \nBase MAG: {str(self.basemagic)} \nSpells: [{efuncs.list_print(self.spells)}]\nMP: {str(self.mp)} \nCurrent MP: {str(self.currentmp)}\nRES: {str(self.resistance)} \nSPD: {str(self.speed)} \n \"\"\")\n def equip_boss_weapon(self, weapon):\n if weapon.elemental_affinity == 'S':\n self.basemagic += 5\n if weapon == weapons.throwing_knives: \n self.speed += 5\n if weapon == weapons.club:\n self.baseattack += 3\n self.weapon = weapon \n self.attack = (self.baseattack + weapon.atk)\n self.magic = (self.basemagic + weapon.mag)\n def enemy_use_magic(self, target, spell):\n print()\n if spell not in self.spells: \n print(f\"{self.name.title()} tried to use a spell that they don\\'t know.\")\n else: \n if isinstance(spell, magic.Heal):\n print(f\"{self.name.title()} used {spell.name.title()}!\")\n if (self.currenthealth + spell.heals) > (self.maxhealth):\n self.currenthealth = self.maxhealth\n else: \n self.currenthealth += spell.heals\n print(f\"{self.name.title()}\\'s HP is now {self.currenthealth}!\")\n self.currentmp -= spell.cost\n elif isinstance(spell, magic.Buff):\n print(f\"{self.name.title()} used {spell.name.title()}!\")\n spell.value_buffer = self.attack\n self.attack += spell.atkadd\n print(f\"{self.name.title()}\\'s ATK is now {self.attack}!\")\n self.currentmp -= spell.cost\n elif isinstance(spell, magic.attack_spell):\n print(f\"{self.name.title()} used {spell.name}!\")\n self.magic += spell.damage\n if spell.aoe == True:\n for player in party: \n if spell.kind == \"P\":\n defense_type = player.defense\n elif spell.kind == \"M\":\n defense_type = player.resistance\n spell_damage = (self.magic - defense_type)\n if spell_damage <= 0:\n spell_damage = 1 \n spell_damage = int(round(spell_damage)) \n player.currenthealth -= spell_damage\n print(f\"{player.name.title()} took {str(spell_damage)} damage. Their health is now {str(player.currenthealth)}\")\n else:\n if spell.kind == \"P\":\n defense_type = target.defense\n elif spell.kind == \"M\":\n defense_type = target.resistance\n spell_damage = (self.magic - defense_type)\n if spell_damage <= 0:\n spell_damage = 1 \n spell_damage = int(round(spell_damage))\n target.currenthealth -= spell_damage\n print(f\"{target.name.title()} took {str(spell_damage)} damage. Their health is now {str(target.currenthealth)}\") \n self.magic = self.basemagic + self.weapon.mag\n self.currentmp -= spell.cost\n affliction_yes = random.randint(0, 10)\n if affliction_yes == 8:\n if spell.affliction == states.fire:\n states.set_player_state(target, states.fire)\n elif spell.affliction == states.frozen:\n states.set_player_state(target, states.frozen)\n elif isinstance(spell, magic.Boost_Magic): \n print(f\"{self.name} used {spell.name}! {spell.attr_to_boost.title()} + {spell.boost_amt} for {spell.duration} turns.\")\n self.currentmp -= spell.cost \n self.adjust_val(spell.attr_to_boost, spell.boost_amt, spell.duration, spell) \n def enemy_attack(self, enemy):\n print()\n damage = (self.attack - enemy.defense) \n if damage <= 0:\n damage = 1\n enemy.currenthealth -= damage\n print(f\"{self.name.title()} attacks {enemy.name.title()} for {damage} damage!\\n{enemy.name.title()}'s health is now {enemy.currenthealth}.\")\n if (self.speed - enemy.speed) >= 5:\n print(f\"Speed supremacy! {self.name.title()} gets another, weaker hit in!\")\n weak_damage = int(round(damage / 2))\n enemy.currenthealth -= weak_damage\n print(f\"{enemy.name.title()}\\'s health is now {enemy.currenthealth}.\")\n def adjust_val(self, attr, amt, duration, spell):\n before_adjust = getattr(self, attr)\n spell.value_buffer = before_adjust\n setattr(self, attr, (before_adjust + amt))\n def detail_str(self): \n detail = f\"{self.name} (HP: {self.currenthealth} / {self.maxhealth}, ATK: {self.attack}, MAG: {self.magic}, DEF: {self.defense}, RES: {self.resistance}, SPD: {self.speed})\"\n return detail\n\n## Bosses ## \n#name, weapon, currenthealth, maxhealth, attack, baseattack, defense, magic, basemagic, spells, mp, currentmp, resistance, speed, state\n\nmagus = Boss('Magus', weapons.fisticuffs, 360, 360, 25, 25, 40, 40, 40, [magic.healIII, magic.barrier, magic.dark_matter, magic.dark_mist], 150, 150, 50, 40, states.normal)\n\nerika = Boss('Erika', weapons.fisticuffs, 290, 290, 25, 20, 45, 15, 15, [magic.healII, magic.buffII, magic.rainbow_storm, magic.wind_waltz], 80, 80, 45, 35, states.normal)\n\nzombor = Boss('Zombor', weapons.fisticuffs, 375, 375, 30, 30, 70, 10, 10, [magic.healII, magic.flame_strike, magic.annihilation_ray], 65, 65, 70, 10, states.normal)\n\nqueen_zeal = Boss('Queen Zeal', weapons.fisticuffs, 500, 500, 45, 45, 65, 45, 45, [magic.healIII, magic.gears_of_darkness, magic.starburst, magic.evil_within, magic.reality_inversion], 160, 160, 65, 40, states.normal)\n\nmagus_2 = Boss('Magus II', weapons.fisticuffs, 525, 525, 30, 30, 55, 55, 55, [magic.healV, magic.barrier2, magic.dark_matter, magic.eternal_darkness, magic.shadow_scythe], 250, 250, 75, 30, states.normal)\n\nerika_2 = Boss(\"Erika II\", weapons.fisticuffs, 450, 450, 40, 40, 75, 30, 30, [magic.healIV, magic.buffIII, magic.rainbow_hurricane, magic.tornado_tango], 155, 155, 60, 60, states.normal)\n\nbosses = [magus, erika, zombor]\nsuperbosses = [magus_2, erika_2, queen_zeal]\nbosses_defeated = []\nsuperbosses_defeated = []\n\n## Enemies ##\n\nclass Enemy():\n name = ''\n weapon = ''\n currenthealth = 0\n maxhealth = 0\n attack = 0\n baseattack = 0\n defense = 0\n magic = 0\n basemagic = 0\n spells = []\n mp = 0\n currentmp = 0\n resistance = 0\n speed = 0\n state = ''\n bounty = 0\n xpbounty = 0\n def __init__(self, name, weapon, currenthealth, maxhealth, attack, baseattack, defense, magic, basemagic, spells, mp, currentmp, resistance, speed, state, bounty, xpbounty): \n self.name = name\n self.weapon = weapon\n self.currenthealth = currenthealth\n self.maxhealth = maxhealth\n self.attack = attack\n self.baseattack = baseattack\n self.defense = defense\n self.magic = magic\n self.basemagic = basemagic\n self.spells = spells\n self.mp = mp\n self.currentmp = currentmp\n self.resistance = resistance\n self.speed = speed\n self.state = state \n self.bounty = bounty\n self.xpbounty = xpbounty\n def print_enemy_stats(self):\n print(f\"\"\"\n{self.name.title()}\\'s stats are as follows: \nWeapon: {self.weapon.name} \nCurrent HP: {str(self.currenthealth)} \nMax HP: {str(self.maxhealth)} \nATK: {str(self.attack)} \nBase ATK: {str(self.baseattack)} \nDEF: {str(self.defense)} \nMAG: {str(self.magic)} \nBase MAG: {str(self.basemagic)} \nSpells: [{efuncs.list_print(self.spells)}]\nMP: {str(self.mp)} \nCurrent MP: {str(self.currentmp)}\nRES: {str(self.resistance)} \nSPD: {str(self.speed)}\nBounty: {str(self.bounty)} CR\nXP Bounty: {str(self.xpbounty)} XP\n \"\"\") \n def equip_enemy_weapon(self, weapon):\n if weapon.elemental_affinity == 'S':\n self.basemagic += 5\n if weapon == weapons.throwing_knives: \n self.speed += 5\n if weapon == weapons.club:\n self.baseattack += 3\n self.weapon = weapon\n self.attack = (self.baseattack + weapon.atk)\n self.magic = (self.basemagic + weapon.mag)\n def enemy_use_magic(self, target, spell):\n print()\n if spell not in self.spells: \n print(f\"{self.name.title()} tried to use a spell that they don\\'t know.\")\n else: \n if isinstance(spell, magic.Heal):\n print(f\"{self.name.title()} used {spell.name}!\")\n if (self.currenthealth + spell.heals) > (self.maxhealth):\n self.currenthealth = self.maxhealth\n else: \n self.currenthealth += spell.heals\n print(f\"{self.name.title()}\\'s HP is now {self.currenthealth}!\")\n self.currentmp -= spell.cost\n elif isinstance(spell, magic.Buff):\n print(f\"{self.name} used {spell.name}!\")\n spell.value_buffer = self.attack\n self.attack += spell.atkadd\n print(f\"{self.name.title()}\\'s ATK is now {self.attack}!\")\n self.currentmp -= spell.cost\n elif isinstance(spell, magic.attack_spell):\n print(f\"{self.name.title()} used {spell.name}!\")\n self.magic += spell.damage\n if spell.aoe == True:\n for player in party: \n if spell.kind == \"P\":\n defense_type = player.defense\n elif spell.kind == \"M\":\n defense_type = player.resistance\n spell_damage = (self.magic - defense_type)\n if spell_damage <= 0:\n spell_damage = 1 \n spell_damage = int(round(spell_damage)) \n player.currenthealth -= spell_damage\n print(f\"{player.name.title()} took {str(spell_damage)} damage. Their health is now {str(player.currenthealth)}\")\n else:\n if spell.kind == \"P\":\n defense_type = target.defense\n elif spell.kind == \"M\":\n defense_type = target.resistance\n spell_damage = (self.magic - defense_type)\n if spell_damage <= 0:\n spell_damage = 1 \n spell_damage = int(round(spell_damage))\n target.currenthealth -= spell_damage\n print(f\"{target.name.title()} took {str(spell_damage)} damage. Their health is now {str(target.currenthealth)}\") \n self.magic = self.basemagic + self.weapon.mag\n self.currentmp -= spell.cost\n affliction_yes = random.randint(0, 10)\n if affliction_yes == 8:\n if spell.affliction == states.fire:\n states.set_player_state(target, states.fire)\n elif spell.affliction == states.frozen:\n states.set_player_state(target, states.frozen) \n elif isinstance(spell, magic.Boost_Magic):\n print(f\"{self.name} used {spell.name}! {spell.attr_to_boost.title()} + {spell.boost_amt} for {spell.duration} turns.\")\n self.currentmp -= spell.cost\n self.adjust_val(spell.attr_to_boost, spell.boost_amt, spell.duration, spell) \n def enemy_attack(self, enemy):\n print()\n damage = (self.attack - enemy.defense)\n if damage <= 0:\n damage = 1\n enemy.currenthealth -= damage\n print(f\"{self.name.title()} attacks {enemy.name.title()} for {damage} damage!\\n{enemy.name.title()}'s health is now {enemy.currenthealth}.\")\n if (self.speed - enemy.speed) >= 5:\n print(f\"Speed supremacy! {self.name.title()} gets another, weaker hit in!\")\n weak_damage = int(round(damage / 2))\n enemy.currenthealth -= weak_damage\n print(f\"{enemy.name.title()}\\'s health is now {enemy.currenthealth}.\")\n def adjust_val(self, attr, amt, duration, spell):\n before_adjust = getattr(self, attr)\n spell.value_buffer = before_adjust\n setattr(self, attr, (before_adjust + amt))\n def detail_str(self): \n detail = f\"{self.name} (HP: {self.currenthealth} / {self.maxhealth}, ATK: {self.attack}, MAG: {self.magic}, DEF: {self.defense}, RES: {self.resistance}, SPD: {self.speed})\"\n return detail\n\n#name, weapon, currenthealth, maxhealth, attack, baseattack, defense, magic, basemagic, spells, mp, currentmp, resistance, speed, state, bounty, xpbounty\n\n#Physical enemies\ngoblin = Enemy('Goblin', weapons.fisticuffs, 50, 50, 10, 10, 20, 0, 0, [], 0, 0, 0, 5, states.normal, 115, 25)\ngogoblin = Enemy('Gogoblin', weapons.fisticuffs, 75, 75, 15, 15, 20, 0, 0, [], 0, 0, 5, 10, states.normal, 230, 75)\n\nskelly = Enemy('Skelly', weapons.fisticuffs, 60, 60, 20, 20, 40, 0, 0, [], 0, 0, 0, 10, states.normal, 485, 185)\nbigskelly = Enemy('Big Skelly', weapons.fisticuffs, 120, 120, 25, 25, 45, 0, 0, [], 0, 0, 15, 15, states.normal, 550, 365)\n\ncyclops = Enemy('Cyclops', weapons.fisticuffs, 150, 150, 30, 30, 30, 10, 10, [], 0, 0, 35, 10, states.normal, 720, 425)\nredcyclops = Enemy('Red Cyclops', weapons.fisticuffs, 175, 175, 30, 30, 35, 0, 0, [], 0, 0, 30, 15, states.normal, 825, 475)\n\ndactyl = Enemy('Dactyl', weapons.fisticuffs, 90, 90, 10, 10, 10, 0, 0, [], 0, 0, 10, 20, states.normal, 500, 125) \n\nbongo_nongo = Enemy(\"Bongo Nongo\", weapons.fisticuffs, 200, 200, 30, 30, 50, 5, 5, [magic.healII], 55, 55, 50, 5, states.normal, 1000, 500)\n\n#Magic enemies \n\npracticioner = Enemy('Practicioner', weapons.fisticuffs, 125, 125, 20, 20, 15, 30, 30, [magic.healII, magic.buffII, magic.fireball, magic.icecicle_spear, magic.zipzip], 55, 55, 20, 20, states.normal, 330, 220)\n\nblack_mage = Enemy(\"Black Mage\", weapons.fisticuffs, 130, 130, 20, 20, 25, 40, 40, [magic.healIII, magic.ominous_wind, magic.fireball, magic.ground_fault, magic.sigil_of_fire], 80, 80, 45, 40, states.normal, 750, 440)\n\nrogue = Enemy('Rogue', weapons.fisticuffs, 150, 150, 34, 34, 25, 36, 36, [magic.healII, magic.icecicle_spear, magic.zapzap], 70, 70, 30, 75, states.normal, 2675, 560)\n\nshadow_mage = Enemy(\"Shadow Mage\", weapons.fisticuffs, 185, 185, 30, 30, 30, 45, 45, [magic.healIII, magic.sigil_of_darkness, magic.magical_protection, magic.ominous_wind, magic.sigil_of_fire, magic.sigil_of_earth], 80, 80, 40, 50, states.normal, 1000, 650)\n\nacolyte_of_magus = Enemy(\"Acolyte of Magus\", weapons.fisticuffs, 200, 200, 37, 37, 40, 55, 55, [magic.healIV, magic.ominous_wind, magic.reality_inversion, magic.dreadful_hymn, magic.sigil_of_darkness], 110, 110, 50, 50, states.normal, 1250, 1000)\n\nenemies = [goblin, gogoblin, skelly, bigskelly, cyclops, redcyclops, dactyl, bongo_nongo, practicioner, black_mage, rogue, shadow_mage, acolyte_of_magus]","repo_name":"arbitrarycorrelations/Text_RPG_3","sub_path":"players.py","file_name":"players.py","file_ext":"py","file_size_in_byte":29368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22038772614","text":"import sys\n\nclass Monkey:\n operator = {\n \"+\": lambda x,y: x+y,\n \"-\": lambda x,y: x-y,\n \"*\": lambda x,y: x*y,\n \"/\": lambda x,y: x/y,\n }\n\n operatorA = {\n \"+\": lambda x,y: x-y,\n \"-\": lambda x,y: y-x,\n \"*\": lambda x,y: x/y,\n \"/\": lambda x,y: y/x,\n \"=\": lambda x,y: y\n }\n\n operatorB = {\n \"+\": lambda x,y: x-y,\n \"-\": lambda x,y: x+y,\n \"*\": lambda x,y: x/y,\n \"/\": lambda x,y: x*y,\n \"=\": lambda x,y: y\n }\n def __init__(self,exp):\n split = exp.strip().split(\" \") \n self.a = self.op = self.b = None\n self.value = None\n if len(split)==1:\n self.value = int(exp)\n else:\n self.a, self.op, self.b = split\n def solve(self, monkeys):\n if self.value:\n return self.value\n\n a = monkeys[self.a].solve(monkeys)\n b = monkeys[self.b].solve(monkeys)\n self.value = Monkey.operator[self.op](a,b)\n return self.value\n def solveP2(self, monkeys, expected):\n if self.value:\n return self.value\n if not self.a and not self.b:\n self.value = expected\n return expected\n try:\n operator = Monkey.operatorA\n other = self.b\n result = monkeys[self.a].solve(monkeys)\n except:\n operator = Monkey.operatorB\n other = self.a\n result = monkeys[self.b].solve(monkeys)\n\n expected = operator[self.op](expected,result)\n \n return monkeys[other].solveP2(monkeys, expected)\n\nmonkeys = {}\nfor l in sys.stdin:\n id, exp = l.strip().split(\":\")\n monkeys[id]=Monkey(exp)\n\nmonkeys['humn'].value = None\nmonkeys[\"root\"].op = \"=\"\nprint(monkeys[\"root\"].solveP2(monkeys,0))","repo_name":"matheusstutzel/adventOfCode","sub_path":"2022/21/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"2427023552","text":"# coding: UTF-8\n'''\nCreated on 2013-3-28\n\n@author: tianwei\n\nDesc: School URL defination\n'''\n\nfrom django.conf.urls import patterns, include, url\nfrom django.conf.urls.defaults import *\nfrom django.views.generic.simple import direct_to_template\n\nfrom school import views as school_views\n\n\nurlpatterns = patterns(\n '',\n url(\n r'^application/(?P.{36})$',\n school_views.application_report_view,\n ),\n url(r'^open/(?P.{36})$',\n school_views.open_report_view,\n ),\n\n url(r'^final/(?P.{36})$',\n school_views.final_report_view,\n ),\n url(r'^mid/(?P.{36})$',\n school_views.mid_report_view,\n ),\n url(r'^title_change/$',\n school_views.title_change,\n ),\n\n url(r'^memberchange/(?P.{36})$',\n school_views.member_change),\n url(\n r'^$',\n school_views.home_view,\n name='school_home'\n \t ),\n url(\n r'^dispatch$',\n school_views.dispatch,\n ),\n url(\n r'^project_limitnumSettings$',\n school_views.project_limitnumSettings,\n ),\n# url(\n# r'^subject_rating$',\n# school_views.SubjectRating,\n# ),\n url(\n r'^fundsmanage/$',\n school_views.funds_manage,\n ),\n url(\n r'^fundschange/(?P.{36}$)',\n school_views.funds_change,\n ),\n url(\n r'^subject_alloc$',\n school_views.SubjectAlloc,\n ),\n url(\n r'^subject_alloc_new$',\n school_views.NewSubjectAlloc,\n ),\n url(\n r'^project_control$',\n school_views.project_control,\n ),\n url(\n r'^processrecord_view/(?P.{36})$',\n school_views.record_view\n ),\n url(\n r'^project_informationexport$',\n school_views.project_informationexport\n ),\n url(r'^file_download/(?P.{36})$',\n school_views.file_download,name=\"school_downloadfile\"),\n)\n","repo_name":"School-of-Innovation-Experiment/provinceManagement","sub_path":"school/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"33851095146","text":"from silenttrinity.core.utils import get_path_in_package\nfrom silenttrinity.core.teamserver.module import Module\n\n\nclass STModule(Module):\n def __init__(self):\n self.name = 'boo/wmipersistence'\n self.language = 'boo'\n self.description = 'Creates a WMI Event, Consumer and Binding to execuate a payload.'\n self.author = '@Daudau'\n self.references = [\"System.Management\"]\n self.options = {\n 'EventName': {\n 'Description' : 'An arbitrary name to be assigned to the new WMI Event.',\n 'Required' : True,\n 'Value' : ''\n },\n 'EventConsumer': {\n 'Description' : 'Specifies the action to carry out.\\r\\nThe options are 1 (CommandLine, i.e. OS Command) and 2 (ActiveScript, i.e. JScript or VBScript).',\n 'Required' : True,\n 'Value' : ''\n },\n 'Payload': {\n 'Description' : 'Specifies the CommandLine or ActiveScript payload to run.',\n 'Required' : True,\n 'Value' : ''\n },\n 'ProcessName': {\n 'Description' : 'Specifies the process name when the ProcessStart trigger is selected. Defaults to notepad.exe.',\n 'Required' : True,\n 'Value' : 'notepad.exe'\n },\n 'ScriptingEngine': {\n 'Description' : 'Specifies the scripting engine when the ActiveScript consumer is selected. Defaults to VBScript.\\r\\nThe options are 1 (JScript) and 2 (VBScript).',\n 'Required' : True,\n 'Value' : '2' }\n }\n\n def payload(self):\n with open(get_path_in_package('core/teamserver/modules/boo/src/wmipersistence.boo'), 'r') as module_src:\n src = module_src.read()\n src = src.replace('EVENT_NAME', self.options['EventName']['Value'])\n src = src.replace('EVENT_CONSUMER', self.options['EventConsumer']['Value'])\n src = src.replace('PAYLOAD', self.options['Payload']['Value'])\n src = src.replace('PROCESS_NAME', self.options['ProcessName']['Value'])\n src = src.replace('SCRIPTING_ENGINE', self.options['ScriptingEngine']['Value'])\n return src\n","repo_name":"byt3bl33d3r/SILENTTRINITY","sub_path":"silenttrinity/core/teamserver/modules/boo/wmipersistence.py","file_name":"wmipersistence.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":2079,"dataset":"github-code","pt":"3"}
+{"seq_id":"9430269170","text":"import random\nprint('Угадай число')\nrandom_number = random.randint(1,5)\n\nprint(random_number)\n\n\n\nwhile True:\n user_number = input('Вводи число')\n if int(random_number) == int(user_number):\n print(\"You`re right\")\n break\n else:\n print(\"Try again\")\n continue\n ","repo_name":"zdimon/wezom-python-course2","sub_path":"students/DmytroSerhiyovich/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19714295027","text":"class Solution:\n def setZeroes(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: void Do not return anything, modify matrix in-place instead.\n \"\"\"\n stack = []\n n = len(matrix[0]) #col\n m = len(matrix) #row\n for i in range(m):\n for j in range(n):\n if matrix[i][j] == 0:\n stack.append([i, j])\n for item in stack:\n matrix[item[0]] = [0 for i in range(n)]\n for i in range(m):\n matrix[i][item[1]] = 0\n\n\nif __name__ == \"__main__\":\n a = Solution()\n matrix = [[1,1,1],[1,0,1],[1,1,1]]\n a.setZeroes(matrix)\n print(matrix)\n\n\n\n","repo_name":"isabella0428/Leetcode","sub_path":"python/73.py","file_name":"73.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"18566437133","text":"\nfrom core.platform_device import PlatformDevice\n\nclass DeviceKoradKA3005P(PlatformDevice):\n \"\"\"Power Supply From Korad\n \"\"\"\n\n def _PZA_DEV_config(self):\n \"\"\"\n \"\"\"\n return {\n \"family\": \"BPS\",\n \"model\": \"KA3005P\",\n \"manufacturer\": \"Korad\"\n }\n\n def _PZA_DEV_interfaces_generator(self):\n \"\"\"\n \"\"\"\n\n port = self.get_settings().get(\"serial_port\")\n baudrate = 9600\n number_of_channel = 1\n\n interfaces = []\n for chan in range(0, number_of_channel):\n interfaces.append(\n {\n \"name\": f\":channel_{chan}:_ctrl\",\n \"driver\": \"korad.ka3005p.bpc\",\n \"settings\": {\n \"serial_port_name\": port,\n \"serial_baudrate\": baudrate\n }\n }\n )\n interfaces.append(\n {\n \"name\": f\":channel_{chan}:_vm\",\n \"driver\": \"korad.ka3005p.voltmeter\",\n \"settings\": {\n \"serial_port_name\": port,\n \"serial_baudrate\": baudrate\n }\n }\n )\n interfaces.append(\n {\n \"name\": f\":channel_{chan}:_am\",\n \"driver\": \"korad.ka3005p.ammeter\",\n \"settings\": {\n \"serial_port_name\": port,\n \"serial_baudrate\": baudrate\n }\n }\n )\n\n return interfaces\n\n\n\n","repo_name":"Panduza/panduza-py","sub_path":"platform/panduza_platform/devices/korad/ka3005.py","file_name":"ka3005.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"}
+{"seq_id":"34159837125","text":"import pickle\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport click\n\n\n@click.command(\"predict\")\n@click.option(\"--input-dir\")\n@click.option(\"--output-dir\")\n@click.option(\"--model-dir\")\ndef predict(input_dir: str, output_dir: str, model_dir: str):\n data = pd.read_csv(os.path.join(input_dir, \"data.csv\"), index_col=0)\n with open(os.path.join(model_dir, \"model.pkl\"), \"rb\") as input_file:\n model = pickle.load(input_file)\n with open(os.path.join(model_dir, \"scaler.pkl\"), \"rb\") as input_file:\n scaler = pickle.load(input_file)\n\n preds = model.predict(scaler.transform(data.values)).astype(np.int)\n os.makedirs(output_dir, exist_ok=True)\n np.savetxt(os.path.join(output_dir, \"prediction.csv\"), preds)\n\n\nif __name__ == '__main__':\n predict()\n","repo_name":"made-ml-in-prod-2021/ruk0sh","sub_path":"airflow_ml_dags/images/airflow-predict/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12910580322","text":"import numpy as np\nimport cv2\nimport os\nimport sys\nimport time\nimport imutils\nfrom matplotlib import pyplot as plt\n\n\n\nclass Annotate:\n def __init__(self, filename_ext):\n self.filename_ext = filename_ext\n self.filename = filename_ext[:len(self.filename_ext) - 4] # remove .avi\n self.frame = None\n self.count = 1\n\n def process_video(self):\n video = cv2.VideoCapture(self.filename_ext)\n print('loaded video {}'.format(self.filename))\n\n cv2.namedWindow('video {}'.format(self.filename))\n\n found = False\n #SIFT stuff\n bumpSignPic = cv2.imread('/home/chowder/Desktop/bumpSign.png',0)\n #cv2.imshow('bumpSignPic', bumpSignPic)\n #key = cv2.waitKey(0) & 0xFF\n #bumpSignPic = cv2.cvtColor(bumpSignPic ,cv2.COLOR_BGR2GRAY)\n sift = cv2.xfeatures2d.SIFT_create()\n Samplekp, Sampledes = sift.detectAndCompute(bumpSignPic,None)\n\n frame_number = 0\n while video.isOpened():\n ret, self.frame = video.read()\n\n if not ret:\n break\n\n\n\n # how to Test\n #show the blurred image\n #show the Binary image\n #show the image with all the contours\n #get permiter of sign to filter\n #show image with all 4 sided contours\n #show the four sided contours\n #show the ORB comparison\n\n #hella reduce the resolution\n lowRez = cv2.resize(self.frame, (0,0), fx=0.3, fy=0.3)\n\n cv2.imshow('lowRez', lowRez)\n key = cv2.waitKey(0) & 0xFF\n cv2.destroyAllWindows()\n\n #convert to grayscale\n gray = cv2.cvtColor(lowRez, cv2.COLOR_BGR2GRAY)\n\n #apply gaussian blur\n #blurred = cv2.GaussianBlur(gray, (11, 11), 0)\n\n #cv2.imshow('blurred', blurred)\n #key = cv2.waitKey(0) & 0xFF\n #cv2.destroyAllWindows()\n\n #automatically convert to binary\n (thresh, bandw) = cv2.threshold(gray.copy(), 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n\n cv2.imshow('bandw', bandw)\n key = cv2.waitKey(0) & 0xFF\n cv2.destroyAllWindows()\n\n #find contours\n cnts = cv2.findContours(bandw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if imutils.is_cv2() else cnts[1]\n possSigns = []\n print(\"number of Contours\", len(cnts))\n\n #print(\"Average Length of Contours\", np.average(cnts))\n cv2.imshow('rawCont', cv2.drawContours(gray.copy(),cnts, -1, (200,255,0), 1))\n key = cv2.waitKey(0) & 0xFF\n cv2.destroyAllWindows()\n\n #iterate through approvimations with 4 sides\n forSides = 0\n gr8rThan10 = 0\n for c in cnts:\n #apply approximate\n peri = cv2.arcLength(c, True)\n if (peri > 50):#if it's big enough then check the sides\n approx = cv2.approxPolyDP(c, 0.04 * peri, True)\n gr8rThan10 += 1\n if len(approx) == 4:\n possSigns.append(c)\n forSides += 1\n print(\"number of Contours with primiter greater than 10\", gr8rThan10)\n print(\"number of Contours with 4 sides\", forSides)\n cv2.imshow('rawCont', cv2.drawContours(gray.copy(),possSigns, -1, (200,255,255), 1))\n key = cv2.waitKey(0) & 0xFF\n cv2.destroyAllWindows()\n\n\n #iterate through approvimations with 4 sides\n for psc in possSigns:\n cv2.imshow('rawCont', cv2.drawContours(gray.copy(),psc, -1, (200,255,255), 1))\n key = cv2.waitKey(0) & 0xFF\n cv2.destroyAllWindows()\n #get the approximating rectangle\n x,y,w,h = cv2.boundingRect(psc)\n print(x,y,w,h)\n #crop\n crop = gray.copy()[y:y+h, x:x+w]\n cv2.imshow('rawCont',crop)\n key = cv2.waitKey(0) & 0xFF\n cv2.destroyAllWindows()\n\"\"\" #use ORB to compare\n kp2, des2 = sift.detectAndCompute(crop,None)\n # Using FLANN based Matcher for matching the descriptors\n FLANN_INDEX_KDTREE = 0\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n search_params = dict(checks = 500)\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n matches = flann.knnMatch(des1,des2,k=2)\n # Sort them in the order of their distance.\n matches = sorted(matches, key = lambda x:x.distance)\n\n # Draw first 10 matches.\n img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:10], flags=2)\n\n plt.imshow(img3),plt.show()\n\n if len(matches) > 5:\n print (\"found!\")\n found = True\n #iterate through polygons using orb to tell if they're the shit\n\n\n\n lastFrame = self.frame\n subframe = diff[200:201, 0:1920]\n\n thresh = 127\n v_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]\n\n print(np.average(subframe))\n cv2.imshow('window', diff)\n cv2.imshow('video {}'.format(self.filename), subframe)\n\n key = cv2.waitKey(0) & 0xFF\n if key == ord('h'):\n plt.hist(subframe.ravel(), 256, [0, 256])\n plt.show()\n\n elif key == ord('q'):\n exit()\n\n frame_number += 1\n\n cv2.destroyAllWindows()\n\"\"\"\n\nif __name__ == '__main__':\n a = Annotate(sys.argv[1])\n a.process_video()\n","repo_name":"ASUVisionHack/bumps","sub_path":"bump.py","file_name":"bump.py","file_ext":"py","file_size_in_byte":5830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32266378575","text":"import os\nimport sys\n\nimport numpy as np\nnp.set_printoptions(threshold=sys.maxsize)\n\nimport bmesh\nimport bpy\n\ndef import_global():\n global sk, kimimaro, multiprocess, trimesh, creation, scipy\n import skeletor as sk\n import kimimaro\n import multiprocess\n import trimesh\n from trimesh.voxel import creation\n import scipy\n\n\n# Future work: Use this section to define skeleton import function.\n#axis_forward = 'Y'\n#axis_up = 'Z'\n#bpy.ops.import_scene.obj(filepath=fname, axis_forward=axis_forward, axis_up=axis_up)\n# Currently, importing a skeleton OBJ file through Blender's OBJ import may not align it correctly. Setting the orientations is important.\n \ndef saveSkeletonObjFile(fname=\"\"):\n if fname == \"\":\n print(\"No output file specified.\")\n return(0)\n bpy.ops.export_scene.obj(filepath=fname+\"/\"+bpy.context.object.name+\".obj\", use_selection=True)\n\nclass export_operator_sk(bpy.types.Operator):\n \"\"\"Tooltip\"\"\"\n bl_idname = \"sk.export\"\n bl_label = \"Save skeleton\"\n bl_description = \"Save skeleton as a .OBJ file\"\n\n @classmethod\n def poll(cls, context):\n return context.active_object is not None\n\n def execute(self, context):\n saveSkeletonObjFile(fname=bpy.context.scene.my_tool_skeleton.path_skeleton)\n return {'FINISHED'}\n\nclass MESH_OT_skeletonize(bpy.types.Operator):\n bl_idname = \"mesh.skeletonize\"\n bl_label = \"Skeletonize\"\n bl_description = \"Skeletonize selected mesh/object\"\n\n def execute(self, context):\n import_global()\n \n bm = bmesh.new()\n bm.from_mesh(bpy.context.object.data)\n\n verts = np.array([list(v.co) for v in bm.verts])\n edges = np.array([list([e.verts[0].index,e.verts[1].index]) for e in bm.edges])\n\n # To get triangulated meshes, do this\n bmt = bmesh.ops.triangulate(bm, faces=bm.faces[:])\n faces = np.array([list([f.verts[0].index,f.verts[1].index,f.verts[2].index]) for f in bmt['faces']])\n\n #bmt['faces'][1].verts[0].index\n\n print(\"Vertices:\", verts.shape)\n print(\"Edges:\", edges.shape)\n print(\"Faces:\", faces.shape)\n\n mesh = trimesh.Trimesh(vertices=verts, faces=faces)\n\n #print(mesh)\n #print(mesh.vertices)\n min_mesh = np.min(mesh.vertices, axis=0)\n max_mesh = np.max(mesh.vertices, axis=0)\n print(\"Minimum of mesh vertices:\", min_mesh)\n print(\"Maximum of mesh vertices:\", max_mesh)\n\n self.translate_x = min_mesh[0]\n self.translate_y = min_mesh[1]\n self.translate_z = min_mesh[2]\n print(\"Translation parameters:\", self.translate_x, self.translate_y, self.translate_z)\n\n ######### Depricated section\n def skeletonize_skeletor():\n # Optional skeletonization method.\n #sk.pre.simplify(mesh, 0.5)\n\n fixed = sk.pre.fix_mesh(mesh, remove_disconnected=5, inplace=False)\n skel = sk.skeletonize.by_wavefront(fixed, waves=1, step_size=10)\n\n print(\"Skeleton before cleanup:\", skel)\n sk.post.clean_up(skel, inplace=True)\n print(\"Skeleton after cleanup:\", skel)\n\n skelmesh = bpy.data.meshes.new('emptyMesh')\n skelobj = bpy.data.objects.new(\"skeleton\", skelmesh)\n bpy.context.collection.objects.link(skelobj)\n skelmesh.from_pydata(skel.vertices, skel.edges, [])\n skelmesh.update()\n\n #mesh = sk.example_mesh()\n #fixed = sk.pre.fix_mesh(mesh, remove_disconnected=5, inplace=False)\n #skel = sk.skeletonize.by_wavefront(fixed, waves=1, step_size=1)\n #print(skel)\n\n #skeletonize_skeletor()\n ######### END Depricated section\n\n def skeletonize_kimimaro():\n # Preferred skeletonization method.\n \n voxelsize = 0.05#0.1 #0.5 # 0.03\n volume = trimesh.voxel.creation.voxelize(mesh, voxelsize, method='subdivide')\n voxels = scipy.ndimage.morphology.binary_fill_holes(volume.matrix)\n #print(voxels.astype(int))\n #print(volume)\n #print(\"***** voxels\")\n #print(type(voxels))\n #print(\"***\")\n\n skels = kimimaro.skeletonize(\n voxels,\n teasar_params={\n 'scale': float(1), #self.kimimaro_scale_entry.get()), # 1,#0.1,#4,\n 'const': float(500), #self.kimimaro_const_entry.get()), # 2000,#500,\n 'pdrf_exponent': 4,\n 'pdrf_scale': 100000,\n 'soma_detection_threshold': 1100,\n 'soma_acceptance_threshold': 3500,\n 'soma_invalidation_scale': 1.0,\n 'soma_invalidation_const': 300,\n },\n dust_threshold=1000,\n anisotropy=(voxelsize, voxelsize, voxelsize), #(nm_x, nm_y, nm_z),\n fix_branching=True,\n progress=False, # default False, show progress bar\n fix_borders=True, # default True\n parallel=1, # <= 0 all cpu, 1 single process, 2+ multiprocess\n parallel_chunk_size=100 # how many skeletons to process before updating progress bar\n )\n\n print(\"Skeletonization done.\")\n print(skels)\n\n # Merge skeletons into one skeleton object\n if not skels:\n print(\"No skeleton found\")\n return{'FINISHED'}\n skel_keys = sorted(skels.keys())\n self.skel_full = skels[skel_keys[0]]\n for l in skel_keys[1:]:\n print(\"Merging skeleton\", skel_keys[0], \"with skeleton\", l, \".\")\n self.skel_full = self.skel_full.merge(skels[l])\n\n print(\"Merged skeleton.\")\n print(self.skel_full)\n \n # Use translation parameters (see above) to reposition the skeleton.\n print(\"Before skel_full vertices shape:\", self.skel_full.vertices.shape)\n print(self.skel_full.vertices[:5])\n self.skel_full.vertices = self.skel_full.vertices + np.array([self.translate_x, self.translate_y, self.translate_z])\n print(\"After skel_full vertices shape:\", self.skel_full.vertices.shape)\n print(self.skel_full.vertices[:5])\n \n skelmesh = bpy.data.meshes.new('emptyMesh')\n skelobj = bpy.data.objects.new(bpy.context.object.name+\".skeleton\", skelmesh)\n bpy.context.collection.objects.link(skelobj)\n skelmesh.from_pydata(self.skel_full.vertices, self.skel_full.edges, [])\n skelmesh.update()\n\n skeletonize_kimimaro()\n \n return{'FINISHED'}\n\nclass MySettings_skeleton(bpy.types.PropertyGroup):\n path_skeleton: bpy.props.StringProperty(\n name=\"\",\n description=\"Path to Directory\",\n default=\"\",\n maxlen=1024,\n subtype='DIR_PATH'\n )\n","repo_name":"utraf-pasteur-institute/CellWalker-blender","sub_path":"Cellwalker/Skeleton.py","file_name":"Skeleton.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"32832892483","text":"from shared.helper import chunk_by_blank_lines\nfrom typing import Dict, List, Set, Tuple\nfrom shared.helper import get_input\nfrom dataclasses import dataclass\nimport math\nimport re\n\ndata = get_input(__file__)\n\n\nRules = Dict[str, List[Set[int]]]\n\n@dataclass\nclass TicketData():\n rules: Rules\n my_ticket: List[int]\n nearby_tickets: List[Set[int]]\n nearby_tickets_as_lists: List[List[int]]\n\ndef parse_ticket_data(data: List[str]) -> TicketData:\n ticket_data: List[List[str]] = chunk_by_blank_lines(data)\n\n rules, my_ticket, nearby_tickets = ticket_data[0], ticket_data[1], ticket_data[2]\n\n return TicketData(\n parse_rules(rules),\n [int(num) for num in my_ticket[1].split(\",\")],\n [{int(num) for num in ticket.split(\",\")} for ticket in nearby_tickets[1:]],\n [[int(num) for num in ticket.split(\",\")] for ticket in nearby_tickets[1:]]\n )\n\n\ndef parse_rules(data: List[str]) -> Rules:\n rule_pattern = r\"^(?P.+): (?P[0-9]+-[0-9]+) or (?P[0-9]+-[0-9]+)\"\n rules = (\n (line.group(\"name\"), line.group(\"first_range\").split(\"-\"), line.group(\"second_range\").split(\"-\"))\n for matches in data\n for line in re.finditer(rule_pattern, matches) \n )\n\n return {\n name: [\n set(range(int(first_range[0]), int(first_range[1]) + 1)),\n set(range(int(second_range[0]), int(second_range[1]) + 1)),\n ]\n for name, first_range, second_range in rules\n }\n \ndef get_all_valid_numbers(ranges: List[Set[int]]) -> Set[int]:\n return set().union(*ranges)\n\ndef filter_out_invalid_tickets(data: TicketData) -> TicketData:\n\n valid_nums = get_all_valid_numbers([nums for rule in data.rules.values() for nums in rule])\n\n data.nearby_tickets = [ticket for ticket in data.nearby_tickets if ticket.issubset(valid_nums)]\n data.nearby_tickets_as_lists = [ticket for ticket in data.nearby_tickets_as_lists if set(ticket).issubset(valid_nums)]\n\n return data\n\ndef slice_tickets_into_columns(data:TicketData) -> List[List[int]]:\n ticket_columns: List[List[int]] = []\n\n for ticket_numbers in data.nearby_tickets_as_lists:\n for idx, num in enumerate(ticket_numbers):\n try: \n ticket_columns[idx].append(num)\n except IndexError:\n ticket_columns.append([num])\n\n return ticket_columns\n\ndef get_ticket_scanning_error_rate(data: List[str]) -> int:\n\n ticket_data = parse_ticket_data(data)\n\n rules = ticket_data.rules\n nearby_tickets = ticket_data.nearby_tickets\n\n valid_nums = get_all_valid_numbers([nums for rule in rules.values() for nums in rule])\n\n invalid_tickets = (ticket for ticket in nearby_tickets if not ticket.issubset(valid_nums))\n\n invalid_nums = (num for ticket in invalid_tickets for num in ticket if num not in valid_nums)\n \n return sum(invalid_nums)\n\ndef get_rule_positions(data: List[str]) -> Tuple[Dict[str, int], TicketData]:\n \n ticket_data = filter_out_invalid_tickets(parse_ticket_data(data))\n\n ticket_columns = slice_tickets_into_columns(ticket_data)\n\n possible_rule_position: Dict[str, List[int]] = {}\n\n for key, rule_sets in ticket_data.rules.items():\n\n rule_nums: Set[int] = set().union(*rule_sets)\n\n for idx, column in enumerate(ticket_columns):\n if set(column).issubset(rule_nums) and idx not in possible_rule_position.values():\n\n if key not in possible_rule_position.keys():\n possible_rule_position[key] = []\n\n possible_rule_position[key] = possible_rule_position[key] + [idx]\n\n actual_positions: Dict[str, int] = {}\n possible_positions = possible_rule_position.items()\n\n while possible_positions:\n key, position = min(possible_positions, key=lambda p: len(p[1]))\n\n actual_positions[key] = position[0]\n\n possible_positions = [\n (k, [p for p in positions if p != position[0]]) \n for k, positions in possible_positions if k != key\n ]\n\n return actual_positions, ticket_data\n\ndef get_product_of_departure_fields(data: List[str]) -> int:\n rule_positions, ticket_data = get_rule_positions(data) \n positions_of_departure_fields = [x for key, x in rule_positions.items() if \"departure\" in key]\n\n assert len(positions_of_departure_fields) == 6\n values = (x for idx, x in enumerate(ticket_data.my_ticket) if idx in positions_of_departure_fields)\n return math.prod(values)\n\ndef problem_1():\n return get_ticket_scanning_error_rate(data)\n\ndef problem_2():\n return get_product_of_departure_fields(data)\n\nif __name__ == '__main__':\n # problem_1()\n # 576481 is too low...?\n problem_2()","repo_name":"mducharm/advent_of_code_2020","sub_path":"day16/solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"19402131452","text":"# coding: utf-8\n# @Author : lryself\n# @Date : 2020/12/14 0:40\n# @Software: PyCharm\nfrom typing import List\n\n\nclass Solution:\n def groupAnagrams(self, strs: List[str]):\n import collections\n chlist = collections.defaultdict(list)\n for st in strs:\n chlist[\"\".join(sorted(st))].append(st)\n\n return list(chlist.values())\n","repo_name":"lryself/python_learning","sub_path":"project_demo/leetcode/s49.py","file_name":"s49.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"28836666234","text":"from enum import Enum\n\n\nclass EnumParser(object):\n @classmethod\n def parse_from_int(cls, enum_type: Enum, value: int):\n for webshop in enum_type:\n if webshop.value == value:\n return webshop\n \n raise ValueError(f\"No {enum_type.__name__} member with value {value}\")\n \n\n @classmethod\n def parse_from_string(cls, enum_type: Enum, value: str):\n try:\n return enum_type[value]\n except KeyError:\n raise ValueError(f\"No {enum_type.__name__} member with name {value}\")\n \n \n @classmethod\n def string_from_enum(cls, enum_type: Enum, enum_member: Enum):\n for key, value in enum_type.__members__.items():\n if value == enum_member:\n return key\n \n raise ValueError(\"Enum member not found\")","repo_name":"GiancarloDoriaBedek/webshop_scraper_api","sub_path":"webshop_scraper/api/helpers/enum_parser.py","file_name":"enum_parser.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71281570001","text":"import sys\nfrom .charDef import *\nfrom . import utils\nfrom termcolor import cprint\n\nclass BulletCli:\n def __init__(self, bullets = [], indent = 0, color = \"cyan\"):\n self.bullets = bullets\n self.pos = 0\n self.indent = indent\n self.color = color\n \n def renderBullets(self):\n for i in range(len(self.bullets)):\n self.printBullet(i)\n utils.forceWrite('\\n')\n \n def printBullet(self, idx):\n utils.forceWrite(' ' * self.indent)\n if idx == self.pos:\n cprint(\"● \", self.color, end = '')\n else:\n utils.forceWrite(\" \")\n utils.forceWrite(self.bullets[idx])\n utils.moveCursorHead()\n\n def moveBullet(self, up = True):\n if up:\n if self.pos - 1 < 0:\n return\n else:\n utils.clearLine()\n old_pos = self.pos\n self.pos -= 1\n self.printBullet(old_pos)\n utils.moveCursorUp(1)\n self.printBullet(self.pos)\n else:\n if self.pos + 1 >= len(self.bullets):\n return\n else:\n utils.clearLine()\n old_pos = self.pos\n self.pos += 1\n self.printBullet(old_pos)\n utils.moveCursorDown(1)\n self.printBullet(self.pos)\n\n def launch(self):\n self.renderBullets()\n utils.moveCursorUp(len(self.bullets))\n while True:\n c = utils.getchar()\n i = c if c == UNDEFINED_KEY else ord(c)\n if i == NEWLINE_KEY:\n utils.moveCursorDown(len(self.bullets) - self.pos)\n return self.bullets[self.pos]\n elif i == ARROW_UP_KEY:\n self.moveBullet()\n elif i == ARROW_DOWN_KEY:\n self.moveBullet(up = False)\n \n\nif __name__ == \"__main__\":\n cli = BulletCli([\"apple\", \"banana\", \"orange\", \"watermelon\", \"strawberry\"], indent = 4)\n result = cli.launch()\n print(result)","repo_name":"bchao1/vocabs","sub_path":"vocab/lib/clilib/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","stars":239,"dataset":"github-code","pt":"3"}
+{"seq_id":"30978893464","text":"# -*- coding: UTF-8 -*-\n#!/usr/bin/env python3\n\nimport os\nimport zmq\nimport pyperclip\nfrom time import sleep\nfrom threading import Thread\n\n__author__ = 'Jahângir (me [at] jahangir [dAt] ninja)'\n\ncontext = zmq.Context()\nSELF, OTHER = None, None\nPORT = 8484\n\nif os.name == 'nt':\n SELF, OTHER = '192.168.190.1', '192.168.190.130'\nelif os.name == 'posix': # mac\n OTHER, SELF = '192.168.190.1', '192.168.190.130'\nelse:\n raise NotImplementedError(\"Undefined OS: {}\".format(os.name))\n\nSERVERS = [[OTHER, PORT],]\n\ndef receiver():\n global context, PORT\n socket = context.socket(zmq.REP)\n print(\"clipsync bound to: tcp://{}:{}\".format(SELF, PORT))\n socket.bind(\"tcp://{}:{}\".format(SELF, PORT))\n\n while True:\n # Wait for next request from client\n cb = socket.recv_unicode()\n try: \n pyperclip.copy(cb)\n print(\"set::{}{}\".format(cb[:100].replace('\\n', '\\\\n'), '...' if len(cb) > 100 else ''))\n except: pass\n # Send reply back to client\n socket.send_unicode(\"1\")\n\n\ndef sender():\n global context, SERVERS\n last = None\n while True:\n try: cb = pyperclip.paste()\n except: sleep(1); continue\n ctn = False\n if not cb or cb == last:\n ctn = True\n sleep(0.7)\n if ctn: continue\n last = cb\n \n cbex = '{}{}'.format(cb[:100].replace('\\n', '\\\\n'), '...' if len(cb) > 100 else '')\n \n for ip, port in SERVERS:\n print(\"{}:{}::{}\".format(ip, port, cbex))\n socket = context.socket(zmq.REQ)\n socket.connect(\"tcp://{}:{}\".format(ip, port))\n \n socket.send_unicode(cb)\n \n # Get the reply.\n message = socket.recv()\n # print(\"Received reply [ %s ]\" % message)\n\nif __name__ == '__main__':\n sthread = Thread(None, sender, daemon=True)\n rthread = Thread(None, receiver, daemon=True)\n sthread.start(); rthread.start()\n rthread.join(); sthread.join()\n \n","repo_name":"j4hangir/clipsync","sub_path":"clipsync.py","file_name":"clipsync.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39794824995","text":"from copy import deepcopy\n\nimport pandas\nfrom numpy import sum\n\n# Marginal control distribution\ncensus_income = pandas.read_csv(\"data/population/census_income.csv\", sep=\";\")\ncensus_occupation = pandas.read_csv(\"data/population/census_occupation.csv\", sep=\";\")\n\n# household travel survey\nhts = pandas.read_csv(\"data/population/hts.csv\", sep=\";\")\n\n# total iterations\ntotal_iterations = 50\n\n# -------------------------------\n# code starts\n# -------------------------------\nhts = hts.set_index(\"occupation\")\ncensus_occupation = census_occupation.set_index(\"occupation\")\ncensus_income = census_income.set_index(\"income\")\n\nori_hts = deepcopy(hts)\n\niter = 0\nwhile iter <= total_iterations:\n # update rows\n for i in range(len(hts.index)):\n cur_occupation_index = hts.index[i] # e.g., teacher, doctor etc.\n original_total_row = sum(hts.iloc[i].values)\n target_total_row = census_occupation.loc[cur_occupation_index].values[0]\n cur_factor = target_total_row / original_total_row\n\n hts.loc[cur_occupation_index] *= cur_factor\n\n # update columns\n for i in range(len(hts.columns)):\n cur_income_index = hts[hts.columns[i]] # e.g., 500, 1000, etc.\n original_total_columns = sum(hts[hts.columns[i]] )\n target_total_columns = census_income.loc[int(hts.columns[i])].values[0]\n cur_factor = target_total_columns / original_total_columns\n\n hts[hts.columns[i]] *= cur_factor\n \n iter += 1\n\nprint(\"population synthesis\")\nprint(hts)\n\nprint(\"population sample\")\nprint(ori_hts)\n\n\n\n","repo_name":"jzanetti/Sijin_matsim","sub_path":"scripts/simple_population_synthesis.py","file_name":"simple_population_synthesis.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38344783188","text":"import socket\nimport sys\nimport json\n\nBUF_SIZE = 1024\nSERVER = sys.argv[1]\nPORT = int(sys.argv[2])\nplay = True\nletter_attempts = set()\nincorrect_attempts = []\nprevious_guess = \"\"\nprevious_server_message = \"\"\n\ns = socket.socket()\ns.connect((SERVER, PORT))\n\ndef generate_client_message(data):\n length = 1 if type(data) == int else len(data)\n client_message = json.dumps({\"msg_length\": length, \"data\": data})\n return client_message\n\nwhile True:\n user_response = input(\"Ready to start game? (y/n)\").lower()\n # print(user_response)\n if user_response.isnumeric():\n word_index = int(user_response) - 1\n s.sendall(generate_client_message(word_index).encode())\n break\n elif user_response == \"y\":\n s.sendall(generate_client_message(-1).encode())\n break\n elif user_response == \"n\":\n s.sendall(generate_client_message(-2).encode())\n play = False\n break\n else:\n print(\"Input not valid. Try again.\")\n \nwhile play:\n try:\n server_message = s.recv(BUF_SIZE)\n server_message = json.loads(server_message.decode())\n except:\n print(\"Server refused to connect.\")\n break\n # server_message = s.recv(BUF_SIZE)\n # if not server_message:\n # print(\"Server refused to connect.\")\n # break\n # server_message = json.loads(server_message.decode())\n\n # print server message right away\n print(server_message[\"data\"])\n\n if server_message[\"msg_flag\"] > 0:# check if server sent \"message\"\n if server_message[\"data\"] == \"Game Over!\":\n break\n else:# server sent \"game progress\"\n if server_message[\"data\"] == previous_server_message:\n if previous_guess:\n incorrect_attempts.append(previous_guess.upper())\n else:\n previous_server_message = server_message[\"data\"]\n print(\"Incorrect Guesses: \", \" \".join(incorrect_attempts))\n\n user_guess = input(\"\\nLetter to guess: \").lower()\n while user_guess < 'a' or user_guess > 'z' or len(user_guess) != 1 or user_guess in letter_attempts:\n if user_guess in letter_attempts:\n print(\"Error! Letter \" + user_guess.upper() + \" has been guessed before, please guess another letter.\")\n else:\n print(\"Error! Please guess ONE letter.\")\n user_guess = input(\"\\nLetter to guess: \").lower()\n letter_attempts.add(user_guess)\n previous_guess = user_guess\n s.sendall(generate_client_message(user_guess).encode())\n\ns.close()","repo_name":"seongyoolee/CS3251_P2","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32442925870","text":"import ach\nfrom ctypes import Structure,c_uint16,c_double,c_ubyte,c_uint32,c_int16\n# import ach\n# import sys\n\n\nCRITR_SERVER_IP = '104.131.172.175'\nCRITR_SERVER_PORT = '1234'\nCRITR_JOINT_COUNT = 20\nCRITR_DC_COUNT = 2\nCRITR_CHAN_REF_NAME = 'critr-ref'\nCRITR_LOOP_PERIOD = 0.005\n\n#struct with joint references\nclass CRITR_REF(Structure):\n _pack_ = 1\n _fields_ = [(\"ref\", c_int16*CRITR_JOINT_COUNT),\n (\"dcref\", c_int16*CRITR_DC_COUNT)]\n","repo_name":"cward13/critr_ach_prototype_1","sub_path":"critr_ach.py","file_name":"critr_ach.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8304740893","text":"import requests\r\nimport re\r\n\r\nheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'}\r\n\r\ndef baidu(company):\r\n url = 'https://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=' + company \r\n res = requests.get(url, headers=headers).text\r\n # print(res)\r\n p_info = '(.*?)
'\r\n \r\n p_href = '
'\n .format(abc_url=settings.ABC_URL, destination=data.metaservice)\n )\n\n assert expected_service in mailoutbox[0].body\n assert expected_parent in mailoutbox[0].body\n assert 'был успешно перенесен' in mailoutbox[0].body\n assert name in mailoutbox[0].subject\n assert mailoutbox[0].to == [head_membership.staff.email]\n\n\ndef test_moving_service_clears_readonly(data, move_services_subtasks):\n MOVING = 'moving'\n\n parent = factories.ServiceFactory(\n parent=data.metaservice,\n readonly_state=MOVING,\n readonly_start_time=timezone.now()\n )\n child = factories.ServiceFactory(\n parent=parent,\n readonly_state=MOVING,\n readonly_start_time=timezone.now()\n )\n grandchild = factories.ServiceFactory(\n parent=child,\n readonly_state=MOVING,\n readonly_start_time=timezone.now()\n )\n check_model_denormalized_fields('services.Service')\n\n move_request = factories.ServiceMoveRequestFactory(service=parent, state='approved')\n\n tasks.move_service(move_request.id)\n\n for service in (parent, child, grandchild):\n service.refresh_from_db()\n assert service.readonly_state is None\n\n\ndef test_moving_flips_is_exportable(data, move_services_subtasks):\n move_request = factories.ServiceMoveRequestFactory(\n service=data.service, destination=data.metaservice, state='approved')\n tasks.move_service(move_request.id)\n data.service.refresh_from_db()\n assert data.service.is_exportable\n\n move_request = factories.ServiceMoveRequestFactory(\n service=data.service, destination=data.meta_other, state='approved')\n tasks.move_service(move_request.id)\n data.service.refresh_from_db()\n assert not data.service.is_exportable\n\n move_request = factories.ServiceMoveRequestFactory(\n service=data.service, destination=data.submeta_other, state='approved')\n tasks.move_service(move_request.id)\n data.service.refresh_from_db()\n assert not data.service.is_exportable\n\n\ndef test_moving_flips_is_exportable_on_entire_family(data, move_services_subtasks):\n parent = factories.ServiceFactory(parent=data.meta_other)\n child = factories.ServiceFactory(parent=parent)\n grandchild = factories.ServiceFactory(parent=child)\n check_model_denormalized_fields('services.Service')\n\n family = (parent, child, grandchild)\n\n # there\n move_request = factories.ServiceMoveRequestFactory(\n service=parent, destination=data.metaservice, state='approved')\n tasks.move_service(move_request.id)\n\n for service in family:\n service.refresh_from_db()\n assert service.is_exportable is True\n\n # and back again\n move_request = factories.ServiceMoveRequestFactory(\n service=parent, destination=data.meta_other, state='approved')\n tasks.move_service(move_request.id)\n\n for service in family:\n service.refresh_from_db()\n assert service.is_exportable is False\n\n\n@patch('plan.services.tasks.move_service_abc_side')\n@patch('plan.api.idm.actions.move_service')\n@patch('plan.api.idm.actions.assert_service_node_exists', Mock())\ndef test_move_service_retry(move_service, move_service_abc_side, data):\n move_request = factories.ServiceMoveRequestFactory(service=data.service, destination=data.metaservice)\n move_request._approve_transition(Person(data.moderator))\n move_request.save()\n\n move_service.side_effect = (IDMError, IDMError, IDMError, IDMError, IDMError, DEFAULT)\n\n tasks.move_service.delay(move_request.id)\n\n assert move_service.called\n assert move_service_abc_side.apply_async.called\n\n\n@patch('plan.services.tasks.move_service_abc_side')\n@patch('plan.api.idm.actions.move_service')\ndef test_move_service_retry_fail(move_service, move_service_abc_side, data):\n move_request = factories.ServiceMoveRequestFactory(service=data.service, destination=data.metaservice)\n move_request._approve_transition(Person(data.moderator))\n move_request.save()\n\n move_service.side_effect = (IDMError, IDMError, IDMError, IDMError, IDMError, IDMError, DEFAULT)\n\n tasks.move_service.delay(move_request.id)\n\n assert move_service.called\n assert not move_service_abc_side.delay.called\n\n\n@patch('plan.services.tasks.move_service_abc_side')\n@patch('plan.api.idm.actions.assert_service_node_exists')\n@pytest.mark.parametrize(\"move_service_abc_side_called, idm_exceptions\", [\n (True, (IDMError, IDMError, IDMError, IDMError, IDMError, DEFAULT)),\n (False, (IDMError, IDMError, IDMError, IDMError, IDMError, IDMError, DEFAULT)),\n])\ndef test_verify_and_move_service_retry(assert_service_node_exists, move_service_abc_side, data,\n move_service_abc_side_called, idm_exceptions):\n move_request = factories.ServiceMoveRequestFactory(service=data.service, destination=data.metaservice)\n move_request._approve_transition(Person(data.moderator))\n move_request.process_oebs()\n move_request.process_d()\n move_request.process_idm()\n move_request.save()\n\n assert_service_node_exists.side_effect = idm_exceptions\n\n tasks.verify_and_move_service.delay(move_request.id)\n assert assert_service_node_exists.call_count == settings.ABC_IDM_MAX_RETRY + 1\n assert move_service_abc_side.apply_async.called is move_service_abc_side_called\n\n\n@patch('plan.api.idm.actions.delete_service')\ndef test_delete_service(delete_service, service_with_owner):\n service = service_with_owner\n service2 = factories.ServiceFactory()\n\n move_request = factories.ServiceMoveRequestFactory(\n service=service,\n destination=service2,\n state=models.ServiceMoveRequest.REQUESTED,\n )\n\n models.ServiceDeleteRequest.request(service, Person(service.owner))\n\n assert delete_service.call_count == 0\n\n service.refresh_from_db()\n assert service.state == SERVICE_STATE.IN_DEVELOP\n\n move_request.refresh_from_db()\n assert move_request.state == models.ServiceMoveRequest.REQUESTED\n\n\n@patch('plan.api.idm.actions.delete_service')\ndef test_delete_service_with_schedule(delete_service, service_with_owner):\n service = service_with_owner\n schedule = factories.ScheduleFactory(service=service)\n with patch('plan.services.tasks.drop_requests'):\n with patch('plan.services.models.get_unclosable_services') as get_unclosable_services:\n get_unclosable_services.return_value = []\n models.ServiceDeleteRequest.request(service, Person(service.owner))\n\n assert delete_service.call_count == 1\n\n service.refresh_from_db()\n assert service.state == SERVICE_STATE.DELETED\n\n schedule.refresh_from_db()\n\n assert schedule.status == Schedule.DELETED\n\n\ndef test_delete_service_with_moving_descendants(service_with_owner):\n service = service_with_owner\n with patch('plan.services.models.Service.has_moving_descendants', return_value=True) as mock:\n models.ServiceDeleteRequest.request(service, Person(service.owner))\n assert mock.call_count == 6 # 1 + 5 (max_retries)\n service.refresh_from_db()\n assert service.state == SERVICE_STATE.IN_DEVELOP\n\n\n@patch('plan.common.utils.startrek.get_lsr_amount')\n@patch('plan.common.utils.startrek.get_filter_amount')\ndef test_update_kpi(get_filter_amount, get_lsr_amount, service):\n get_filter_amount.return_value = 1\n get_lsr_amount.return_value = 2\n\n ct_bugs = factories.ContactTypeFactory(code=settings.STARTREK_BUGS_CONTACT)\n factories.ServiceContactFactory(\n service=service,\n type=ct_bugs,\n )\n\n tasks.update_services_kpi()\n\n service.refresh_from_db()\n assert service.kpi_bugs_count == 1\n assert service.kpi_release_count is None\n assert service.kpi_lsr_count == 2\n\n\n@patch('plan.common.utils.startrek.get_lsr_amount')\n@patch('plan.common.utils.startrek.get_filter_amount')\ndef test_update_kpi_double(get_filter_amount, get_lsr_amount, service):\n get_filter_amount.return_value = 3\n get_lsr_amount.return_value = 2\n\n ct_bugs = factories.ContactTypeFactory(code=settings.STARTREK_BUGS_CONTACT)\n factories.ServiceContactFactory(service=service, type=ct_bugs)\n factories.ServiceContactFactory(service=service, type=ct_bugs)\n\n tasks.update_services_kpi()\n\n service.refresh_from_db()\n assert service.kpi_bugs_count == 6\n\n\n@patch('plan.common.utils.startrek.get_lsr_amount')\ndef test_skip_kpi(get_lsr_amount, service):\n get_lsr_amount.return_value = None\n\n def bad_save(self, *args, **kwargs):\n raise ValueError()\n\n original_save = models.Service.save\n models.Service.save = bad_save\n\n tasks.update_services_kpi()\n\n models.Service.save = original_save\n\n\ndef test_service_ancestors():\n metaservice = factories.ServiceFactory()\n parent = factories.ServiceFactory(parent=metaservice)\n service = factories.ServiceFactory(parent=parent)\n factories.ServiceFactory(parent=parent)\n\n tasks.update_service_fields(parent.id)\n\n metaservice.refresh_from_db()\n assert metaservice.children_count == 1\n assert metaservice.descendants_count == 3\n\n parent.refresh_from_db()\n assert parent.children_count == 2\n assert parent.descendants_count == 2\n assert [rec['id'] for rec in parent.ancestors] == [metaservice.id]\n\n service.refresh_from_db()\n assert [rec['id'] for rec in service.ancestors] == [metaservice.id, parent.id]\n\n\ndef test_service_ancestors_tag_serialization():\n metaservice = factories.ServiceFactory()\n parent = factories.ServiceFactory(parent=metaservice)\n service = factories.ServiceFactory(parent=parent)\n\n meta_tag = factories.ServiceTagFactory()\n metaservice.tags.add(meta_tag)\n\n parent_tag = factories.ServiceTagFactory()\n parent.tags.add(parent_tag)\n\n tasks.update_service_fields(parent.id)\n\n service.refresh_from_db()\n\n ancestors = {ancestor['id']: ancestor for ancestor in service.ancestors}\n\n for ancestor in (metaservice, parent):\n assert len(ancestors[ancestor.id]['tags']) == 1\n\n tag = ancestors[ancestor.id]['tags'][0]\n assert set(tag.keys()) == {'id', 'name', 'color', 'slug', 'description'}\n\n\ndef test_notification_move_request():\n person = factories.StaffFactory()\n person2 = factories.StaffFactory()\n service = factories.ServiceFactory()\n service2 = factories.ServiceFactory(owner=person2)\n\n request = factories.ServiceMoveRequestFactory(\n requester=person,\n service=service,\n destination=service2,\n approver_outgoing=person2,\n )\n\n tasks.notify_move_request(request.id)\n\n assert len(mail.outbox) == 1\n\n email = mail.outbox[0]\n assert email.subject == 'Запрос на перенос сервиса %s' % service.name\n assert 'руководителем которого вы являетесь' in email.body\n assert person.first_name in email.body\n\n\n@patch('plan.api.idm.actions.move_service')\n@patch('plan.api.idm.actions.assert_service_node_exists')\n@patch('plan.api.idm.actions.rerequest_requested', Mock())\ndef test_move_to_root(assert_service_node_exists, move_service,\n mailoutbox, data, owner_role):\n name = 'Новые щенята & ^ # кусь 2 '\n typograf_name = 'Новые щенята & ^ # кусь 2 <script>console.log(1)</script>'\n data.service.name = name\n data.service.save()\n tasks.move_to_root(data.service, Person(data.moderator))\n\n data.service.refresh_from_db()\n assert data.service.parent is None\n\n move_service.assert_called_once_with(data.service, None)\n assert_service_node_exists.assert_called_once_with(data.service, None)\n assert len(mailoutbox) == 1\n\n expected_service = (\n 'Дочерний сервис {name} вашего сервиса '\n '{parent_service.name}'\n\n ).format(service=data.service, abc_url=settings.ABC_URL, name=typograf_name, parent_service=data.meta_other)\n\n assert expected_service in mailoutbox[0].body\n assert name in mailoutbox[0].subject\n assert 'был успешно перенесен' in mailoutbox[0].body\n assert 'Сервис стал корневым
' in mailoutbox[0].body\n assert mailoutbox[0].to == [data.meta_other.owner.email]\n\n\n@patch('plan.services.tasks.drop_requests')\n@patch('plan.services.tasks.notify_staff')\ndef test_close_service(notify_staff, drop_requests, data):\n tasks.close_service_admin(data.service.id)\n notify_staff.apply_async.assert_called_once_with(\n args=[data.service.id],\n countdown=settings.ABC_DEFAULT_COUNTDOWN\n )\n drop_requests.apply_async.assert_called_once_with(\n args=[data.service.id],\n countdown=settings.ABC_DEFAULT_COUNTDOWN\n )\n\n\ndef test_update_idm_roles_count(patch_tvm):\n service = factories.ServiceFactory()\n mock_response = MockIdmResponse({\n 'meta': {\n 'total_count': 2,\n 'next': None\n },\n 'objects': ['some test objects'],\n })\n\n def mocked_session_send(*args, **kwargs):\n return Response(200, mock_response.response)\n\n with patch('requests.Session.send') as patched:\n patched.side_effect = mocked_session_send\n tasks.update_service_idm_roles_count(service.id)\n\n service.refresh_from_db()\n assert service.idm_roles_count == 2\n\n\ndef test_update_puncher_rules_count_from_api():\n service = factories.ServiceFactory()\n\n def mocked_session_send(*args, **kwargs):\n response = {\n 'count': 5,\n 'rules': []\n }\n\n return Response(200, json.dumps(response))\n\n with patch('requests.Session.send') as patched:\n patched.side_effect = mocked_session_send\n tasks.update_service_puncher_rules_count_from_api([service.id])\n\n service.refresh_from_db()\n assert service.puncher_rules_count == 5\n\n\ndef test_sync_owners(owner_role):\n user = factories.StaffFactory()\n another_user = factories.StaffFactory()\n\n service_with_no_owner = factories.ServiceFactory(slug='no_owner')\n factories.ServiceMemberFactory(\n service=service_with_no_owner,\n role=owner_role,\n staff=user,\n )\n service_with_no_owner.owner = None\n service_with_no_owner.save()\n\n service_with_two_heads = factories.ServiceFactory(slug='two_heads')\n to_delete = factories.ServiceMemberFactory(service=service_with_two_heads, role=owner_role, staff=user)\n factories.ServiceMemberFactory(service=service_with_two_heads, role=owner_role, staff=service_with_two_heads.owner)\n assert models.ServiceMember.objects.filter(service=service_with_two_heads, role=owner_role).count() == 2\n\n service_with_different_head_and_owner = factories.ServiceFactory(slug='different_head_and_owner')\n factories.ServiceMemberFactory(service=service_with_different_head_and_owner, role=owner_role, staff=user)\n service_with_different_head_and_owner.owner = another_user\n service_with_different_head_and_owner.save()\n\n with patch('plan.api.idm.actions.deprive_role') as deprive_role:\n tasks.sync_owners()\n\n deprive_role.assert_called_once_with(\n to_delete, comment='Неактуальный руководитель'\n )\n\n service_with_no_owner.refresh_from_db()\n service_with_no_owner.fetch_owner()\n assert service_with_no_owner.owner is not None\n\n service_with_different_head_and_owner.refresh_from_db()\n service_with_different_head_and_owner.fetch_owner()\n head_sm = models.ServiceMember.objects.get(service=service_with_different_head_and_owner, role=owner_role)\n head = head_sm.staff\n assert service_with_different_head_and_owner.owner == head\n\n\ndef test_sync_owners_two_heads(owner_role):\n \"\"\"\n Роль старого руководителя по какой-то причине создана позже, чем нового.\n Остаться должна роль, указанная в service.owner\n \"\"\"\n\n user = factories.StaffFactory()\n service_with_two_heads = factories.ServiceFactory(slug='two_heads')\n factories.ServiceMemberFactory(\n service=service_with_two_heads,\n role=owner_role,\n staff=service_with_two_heads.owner\n )\n to_delete = factories.ServiceMemberFactory(service=service_with_two_heads, role=owner_role, staff=user)\n\n assert models.ServiceMember.objects.filter(service=service_with_two_heads, role=owner_role).count() == 2\n\n with patch('plan.api.idm.actions.deprive_role') as deprive_role:\n tasks.sync_owners()\n\n deprive_role.assert_called_once_with(\n to_delete, comment='Неактуальный руководитель'\n )\n\n\ndef test_notify_services_owners(mailoutbox):\n top_owner = factories.StaffFactory()\n child_owner = factories.StaffFactory()\n top_service = factories.ServiceFactory(owner=top_owner)\n factories.ServiceFactory(parent=top_service, owner=child_owner)\n factories.ServiceFactory(owner=top_owner)\n\n tasks.notify_services_owners()\n assert len(mailoutbox) == 2\n\n\ndef test_cleanup_service_requests():\n source = factories.ServiceFactory()\n move_request_a = factories.ServiceMoveRequestFactory(\n service=source,\n updated_at=timezone.now(),\n state=models.ServiceMoveRequest.REQUESTED,\n )\n move_request_b = factories.ServiceMoveRequestFactory(\n service=source,\n updated_at=timezone.now() + timezone.timedelta(seconds=1),\n state=models.ServiceMoveRequest.REQUESTED,\n )\n other_request = factories.ServiceMoveRequestFactory(\n state=models.ServiceMoveRequest.REQUESTED,\n )\n tasks.cleanup_service_requests()\n\n for request in [move_request_a, move_request_b, other_request]:\n request.refresh_from_db()\n\n assert move_request_a.state == models.ServiceMoveRequest.REJECTED\n assert move_request_b.state == models.ServiceMoveRequest.REQUESTED\n assert other_request.state == models.ServiceMoveRequest.REQUESTED\n\n\ndef test_find_memberships_in_staff():\n factories.ServiceFactory(slug='meta_other')\n service = factories.ServiceFactory()\n member1 = factories.ServiceMemberFactory(service=service)\n member2 = factories.ServiceMemberFactory(service=service)\n member3 = factories.ServiceMemberFactory(service=service)\n\n with patch('plan.staff.tasks.MembershipStaffImporter.get_objects') as get_objects:\n get_objects.return_value = [\n {\n 'id': member1.id,\n 'person': {'login': member1.staff.login},\n 'group': {'url': f'svc_{member1.service.slug}'},\n },\n {\n 'id': member1.id,\n 'person': {'login': member1.staff.login},\n 'group': {'url': f'svc_{member1.service.slug}_{member1.role.scope.slug}'},\n },\n {\n 'id': member3.id,\n 'person': {'login': member3.staff.login},\n 'group': {'url': f'svc_{member3.service.slug}'},\n },\n {\n 'id': member3.id,\n 'person': {'login': member3.staff.login},\n 'group': {'url': f'role_svc_{member3.service.slug}_{member3.role.scope.slug}'},\n },\n ]\n tasks.find_memberships_in_staff()\n\n for member, found in [\n (member1, True),\n (member2, False),\n (member3, True),\n ]:\n member.refresh_from_db()\n assert (member.found_in_staff_at is not None) == found\n\n\n@pytest.mark.parametrize('ok', [True, False])\ndef test_find_interactive_services(robot, ok, patch_tvm, responsible_role):\n service = factories.ServiceFactory()\n moves = []\n for i in range(10):\n moves.append(factories.ServiceMoveRequestFactory(service=service, completed_at=timezone.now()))\n with patch('plan.idm.manager.Manager._run_request') as run_request:\n response = Mock()\n response.ok = ok\n response.text = 'x'\n response.json.return_value = {}\n run_request.return_value = response\n tasks.find_interactive_services()\n\n for i in range(10):\n moves[i].refresh_from_db()\n if ok:\n assert moves[i].interactive_at is not None\n else:\n assert moves[i].interactive_at is None\n\n\ndef test_finish_all_service_move_requests():\n service_a = factories.ServiceFactory(parent=None, slug='A')\n service_b = factories.ServiceFactory(parent=None, slug='B')\n service_c = factories.ServiceFactory(parent=None, slug='C')\n requests = [\n factories.ServiceMoveRequestFactory(\n service=source,\n destination=destination,\n state=models.ServiceMoveRequest.PROCESSING_ABC,\n # чтобы письмо не собиралось\n from_creation=True,\n )\n for source, destination in [(service_b, service_a), (service_c, service_b)]\n ]\n tasks.finish_all_service_move_requests()\n for request in requests:\n request.refresh_from_db()\n assert request.state == models.ServiceMoveRequest.COMPLETED\n service_b.refresh_from_db()\n assert service_b.parent == service_a\n service_c.refresh_from_db()\n assert service_c.parent == service_b\n\n\n@pytest.mark.parametrize('async_mode', [False])\ndef test_move_service_abc_side(async_mode):\n \"\"\"Меняется родитель перемещаемого сервиса и обновляются уровни всех его потомков.\"\"\"\n service_a = factories.ServiceFactory(parent=None, slug='A')\n service_b = factories.ServiceFactory(parent=None, slug='B')\n factories.ServiceFactory(parent=service_b, slug='C')\n request = factories.ServiceMoveRequestFactory(\n service=service_b,\n destination=service_a,\n state=models.ServiceMoveRequest.PROCESSING_ABC,\n # чтобы письмо не собиралось\n from_creation=True,\n )\n with override_switch('async_move_service_abc_side', active=async_mode):\n tasks.move_service_abc_side(request.id)\n request.refresh_from_db()\n assert request.state == models.ServiceMoveRequest.COMPLETED\n service_b.refresh_from_db()\n assert service_b.parent == service_a\n with patch('plan.unistat.tasks.fix_service_closuretree_levels') as fix_service_closuretree_levels_mock:\n assert service_level_broken() == 0\n fix_service_closuretree_levels_mock.apply_async.assert_not_called()\n\n\ndef test_move_service_abc_side_to_root(service):\n \"\"\"Сервис перемещается на верхний уровень, уровни всех его потомков обновляются.\"\"\"\n factories.ServiceFactory(parent=service, slug='C')\n request = factories.ServiceMoveRequestFactory(\n service=service,\n destination=None,\n state=models.ServiceMoveRequest.PROCESSING_ABC,\n # чтобы письмо не собиралось\n from_creation=True,\n )\n tasks.move_service_abc_side(request.id)\n request.refresh_from_db()\n assert request.state == models.ServiceMoveRequest.COMPLETED\n service.refresh_from_db()\n assert service.parent is None\n with patch('plan.unistat.tasks.fix_service_closuretree_levels') as fix_service_closuretree_levels_mock:\n assert service_level_broken() == 0\n fix_service_closuretree_levels_mock.apply_async.assert_not_called()\n\n\ndef test_deep_disable_membership_inheritance():\n root = factories.ServiceFactory()\n factories.ServiceFactory(parent=root, membership_inheritance=True)\n node = factories.ServiceFactory(parent=root, membership_inheritance=True)\n factories.ServiceFactory(parent=node, membership_inheritance=True)\n factories.ServiceFactory(parent=node, membership_inheritance=False)\n services = (root, *root.get_descendants())\n\n assert any(s.membership_inheritance is True for s in services)\n call_command('deep_disable_membership_inheritance', service_id=root.id)\n for s in services:\n s.refresh_from_db()\n assert all(s.membership_inheritance is False for s in services)\n\n\ndef test_sync_department_members_state():\n active_state = models.ServiceMember.states.ACTIVE\n deprved_state = models.ServiceMember.states.DEPRIVED\n service = factories.ServiceFactory()\n department_deprived = factories.ServiceMemberDepartmentFactory(\n state=deprved_state,\n service=service,\n )\n member_should_be_deprived = factories.ServiceMemberFactory(\n from_department=department_deprived,\n state=active_state,\n service=service,\n )\n member_out_of_department = factories.ServiceMemberFactory(\n state=active_state,\n service=service,\n )\n department_active = factories.ServiceMemberDepartmentFactory(\n state=active_state,\n service=service,\n )\n member_should_stay_active = factories.ServiceMemberFactory(\n from_department=department_active,\n state=active_state,\n service=service,\n )\n\n tasks.sync_department_members_state()\n\n member_out_of_department.refresh_from_db()\n member_should_stay_active.refresh_from_db()\n\n assert member_should_stay_active.state == active_state\n assert member_out_of_department.state == active_state\n\n deprived_member = models.ServiceMember.all_states.get(pk=member_should_be_deprived.pk)\n assert deprived_member.state == deprved_state\n\n\n@pytest.mark.parametrize('tag_slug', settings.REVIEW_REQUIRED_TAG_SLUGS)\n@pytest.mark.parametrize('review_required', [True, False, None])\n@pytest.mark.parametrize('service_review_required', [True, False])\ndef test_update_service_review_policy(review_required_tags, review_required, service_review_required, tag_slug):\n service = factories.ServiceFactory()\n tag = models.ServiceTag.objects.get(slug=tag_slug)\n if service_review_required:\n service.tags.add(tag)\n\n with patch('plan.idm.nodes.Node.update') as node_update_mock:\n tasks.update_service_review_policy(service_slug=service.slug, review_required=review_required)\n\n node_update_mock.assert_has_calls([\n {'review_required': review_required is None and service_review_required or review_required}\n for _ in service.role_set.all()\n ])\n\n\n@pytest.mark.parametrize('tag_slug', settings.REVIEW_REQUIRED_TAG_SLUGS)\ndef test_check_service_review_policy_enabled(review_required_tags, tag_slug):\n fake_manager = object()\n tag = models.ServiceTag.objects.get(slug=tag_slug)\n\n class FakeFetchDataMethod:\n def __init__(self, results: list = None):\n self._results = results or []\n self.call_count = 0\n\n def __call__(self, *args, **kwargs):\n result = self._results[self.call_count]\n self.call_count += 1\n return result\n\n service = factories.ServiceFactory()\n\n sox_service = factories.ServiceFactory()\n sox_service.tags.add(tag)\n custom_roles = [\n factories.RoleFactory(service=service),\n factories.RoleFactory(service=sox_service),\n ]\n default_roles_count = models.Role.objects.filter(service=None).count()\n\n fake_fetch_responses = [\n {'review_required': bool(random.randint(0, 1))}\n for _ in range(len([role for role in custom_roles if role.service.review_required]) + default_roles_count)\n ]\n\n with patch('plan.api.idm.actions.idm_manager', return_value=fake_manager), \\\n patch(\n 'plan.idm.nodes.Node.fetch_data',\n new=FakeFetchDataMethod(fake_fetch_responses),\n ) as node_fetch_data_mock, \\\n patch('plan.idm.nodes.Node.update') as update_node_mock:\n tasks.check_service_review_policy_enabled()\n\n assert node_fetch_data_mock.call_count == \\\n len(fake_fetch_responses)\n update_node_mock.assert_has_calls([\n ((), {'manager': fake_manager, 'review_required': True})\n for fake_response in fake_fetch_responses if not fake_response['review_required']\n ])\n\n\n@pytest.mark.parametrize('diff_source', ['name', 'name_en', 'use_for_hr', 'leaf_code', 'parent'])\ndef test_sync_oebs_structure(data, yql_query_oebs_mock, diff_source):\n \"\"\"\n Проверяем синхронизацию данных с oebs выгрузкой в YT\n У одного сервиса сменили родителя, другой из выгрузки пропал\n Соответственно такие же изменения должны произойти у нас\n \"\"\"\n\n oebs_type = factories.ResourceTypeFactory(code=settings.OEBS_PRODUCT_RESOURCE_TYPE_CODE)\n factories.ServiceResourceFactory(\n service=data.service,\n resource=factories.ResourceFactory(type=oebs_type),\n type_id=oebs_type.id,\n state='granted',\n attributes={\n 'parent_oebs_id': 'GROUP_CODE',\n 'leaf_oebs_id': 'FAKE_ONE' if diff_source == 'leaf_code' else 'LEAF_CODE',\n },\n )\n\n data.service.name = 'some'\n data.service.name_en = 'some_en'\n data.service.use_for_group_only = True\n data.service.use_for_hr = False\n data.service.use_for_procurement = False\n data.service.use_for_revenue = True\n data.service.oebs_parent_id = 42\n\n if diff_source == 'name_en':\n deviation_reason = OEBS_DEVIATIONS_REASONS.NAME\n data.service.name_en = 'hello'\n elif diff_source == 'name':\n deviation_reason = OEBS_DEVIATIONS_REASONS.NAME\n data.service.name = 'hello'\n elif diff_source == 'use_for_hr':\n deviation_reason = OEBS_DEVIATIONS_REASONS.FLAG\n data.service.use_for_hr = True\n elif diff_source == 'leaf_code':\n deviation_reason = OEBS_DEVIATIONS_REASONS.RESOURCE\n else:\n deviation_reason = OEBS_DEVIATIONS_REASONS.PARENT\n\n data.metaservice.oebs_parent_id = 50\n data.metaservice.oebs_data = {\n 'smth': 'else',\n 'deviation_reason': 'flag'\n }\n data.service.save()\n data.metaservice.save()\n\n tasks.sync_oebs_structure()\n yql_query_oebs_mock.assert_called_once()\n\n data.service.refresh_from_db()\n data.metaservice.refresh_from_db()\n\n assert data.service.oebs_parent_id == 30\n assert data.service.oebs_data == {\n 'leaf_oebs_id': 'LEAF_CODE', 'name': 'some',\n 'name_en': 'some_en', 'oebs_parent_id': 30,\n 'parent_oebs_id': 'GROUP_CODE',\n 'use_for_group_only': True, 'use_for_hr': False,\n 'use_for_procurement': False,\n 'use_for_revenue': True,\n 'deviation_reason': deviation_reason,\n }\n\n assert data.metaservice.oebs_parent_id is None\n assert data.metaservice.oebs_data == {}\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Intranet/tests/unit/services/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":40232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8390255993","text":"from flask import Flask, render_template, request\nfrom parcer import parcing_base_horoscope, parcing_personal_horoscope\nfrom scripts import random_img, zodiac_sign, name_zodiac, create_home\nfrom scripts.birthday import write_and_read_birthday\nfrom scripts.constructor import constructor_horoscope\nimport create_db\n\napp = Flask(__name__)\n\n\n@app.route('/home')\ndef home():\n zodiac_numb = 12\n images = create_home.template_home(zodiac_numb)\n\n return render_template('home.html', data=images)\n\n\n@app.route('/zodiac_sign//')\ndef gemini_data(sign, date):\n zodiac_name = name_zodiac.get_name_zodiac(sign)\n image = random_img.random_image_horoscope_base(sign)\n\n if date == 'today' or date == 'tomorrow':\n text = parcing_base_horoscope.get_horoscope_by_day_and_tomorrow(sign, date)\n\n if text is None:\n text = constructor_horoscope.create_horoscope(date)\n\n return render_template('zodiacs.html', texts=text, len_texts=len(text), name=zodiac_name,\n sign=sign)\n else:\n texts = parcing_base_horoscope.get_horoscope_by_week_and_month(sign, date)\n\n if texts is None:\n texts = constructor_horoscope.create_horoscope(date)\n\n return render_template('zodiacs.html', texts=texts, len_texts=len(texts), file=image,\n name=zodiac_name, sign=sign)\n\n\n@app.route('/home_filter/', methods=['POST', 'GET'])\ndef get_data_form(date):\n if request.method == 'POST':\n name = request.form.get('text')\n birthday = request.form.get('date')\n\n sign = zodiac_sign.get_sign_from_form(birthday)\n image_1, image_2 = random_img.random_image_horoscope_personal(sign)\n\n if date == 'today' or 'tomorrow':\n texts = parcing_personal_horoscope.get_personal_horoscope_by_day_and_tomorrow(sign, date)\n\n else:\n texts = parcing_personal_horoscope.get_personal_horoscope_by_week_and_month(sign, date)\n\n if texts is None:\n texts = constructor_horoscope.create_horoscope(date)\n\n write_and_read_birthday.write_birthday(name, birthday, sign)\n\n return render_template('personal_horoscope.html', name=name, texts=texts, len_texts=len(texts),\n file_1=image_1, file_2=image_2)\n else:\n name, birthday, sign = write_and_read_birthday.read_birthday()\n image_1, image_2 = random_img.random_image_horoscope_personal(sign)\n\n if date == 'today' or date == 'tomorrow':\n texts = parcing_personal_horoscope.get_personal_horoscope_by_day_and_tomorrow(sign, date)\n else:\n texts = parcing_personal_horoscope.get_personal_horoscope_by_week_and_month(sign, date)\n\n if texts is None:\n texts = constructor_horoscope.create_horoscope(date)\n\n return render_template('personal_horoscope.html', name=name, texts=texts, len_texts=len(texts),\n file_1=image_1, file_2=image_2)\n\n\n@app.route('/news')\ndef news():\n result = create_db.main_db()\n return render_template('news.html', result=result)\n\n\nif __name__ == \"__main__\":\n app.run(port=8080, debug=True)\n","repo_name":"IlyaCherevachenko/Web-site-Horoscope-","sub_path":"horoscope.py","file_name":"horoscope.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"31394915413","text":"import json\nimport re\n\nimport pymorphy2\nfrom razdel import tokenize, sentenize\n\nmorph = pymorphy2.MorphAnalyzer()\nfrom natasha import (\n Segmenter,\n NewsEmbedding,\n NewsNERTagger,\n\n Doc\n)\nfrom collections import Counter\n\n\n# Текст\nwith open('ТЗ - короткое.txt', 'r', encoding='utf-8-sig') as file:\n text = file.read()\n# print(text)\n\n# Выделение ссылок, адресов, NE,\nurl_extract_pattern = \"https?:\\\\/\\\\/(?:www\\\\.)?[-a-zA-Z0-9@:%._\\\\+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,6}\\\\b(?:[-a-zA-Z0-9()@:%_\\\\+.~#?&\\\\/=]*)\"\ntext = re.sub(url_extract_pattern, '', text)\n\ndoc = Doc(text)\nsegmenter = Segmenter()\ndoc.segment(segmenter)\nemb = NewsEmbedding()\nner_tagger = NewsNERTagger(emb)\n\ndoc.tag_ner(ner_tagger)\nner_dict = {}\nfor i in doc.spans:\n ner_dict[i.text] = i.type\n\n# Токенизация текста\n\ntext_newline = text.split('\\n')\nsents = []\nfor part in text_newline:\n sents.append(list(sentenize(part))[0].text)\n\nsents = list(sentenize(text))\n# print(sents)\nfor sent in sents:\n tokens = list(tokenize(text))\n# print(tokens)\n\n# POS-taggingл\npos_list = []\nfor i in tokens:\n pos_list.append([i.text, str(morph.parse(i.text)[0].tag)[:4]])\nprint(pos_list)\n\nfor pair in pos_list:\n for word, tag in ner_dict.items():\n if pair[0] == word:\n pair[1] = tag\n\nwith open('POS_tagging.json', 'w', encoding='utf-8-sig') as file:\n json.dump(pos_list, file, indent=4, ensure_ascii=False)\n\n\n# выводим пос-тэггинг по парам\nwith open(\"POS_tagging.json\", \"r\", encoding='utf-8-sig') as read_file:\n data = json.load(read_file)\n\nex_tags = ['PNCT']\ntags = []\nfor i in range(len(data)-1):\n if data[i][1] in ex_tags or data[i+1][1] in ex_tags:\n pass\n else:\n # print(data[i], data[i+1])\n new_str = str(data[i][1] + ' ' + data[i+1][1])\n tags.append(new_str)\nc = Counter(tags)\n\n","repo_name":"tertiadecima/SRS-Russian-CFG","sub_path":"POS-tagging.py","file_name":"POS-tagging.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43563098129","text":"# Create the new DataFrame: tracks\ntracks = billboard[['year', 'artist', 'track','time']]\n\n# Print info of tracks\nprint(tracks.info())\n\n# Drop the duplicates: tracks_no_duplicates\ntracks_no_duplicates = tracks.drop_duplicates()\n\n# Print info of tracks\nprint(tracks_no_duplicates.info())\n#-----------------------------\n# fill missing values \n# Calculate the mean of the Ozone column: oz_mean\noz_mean = airquality.Ozone.mean()\n\n# Replace all the missing values in the Ozone column with the mean\nairquality['Ozone'] = airquality.fillna(oz_mean)\n\n# Print the info of airquality\nprint(airquality.info())\n\n#---- assert -------------------\n\n# Assert that there are no missing values\nassert pd.notnull(ebola).all().all()\n\n# Assert that all values are >= 0\nassert (ebola >= 0).all().all()\n","repo_name":"JitenKumar/Data-Science-Practice-With-Python","sub_path":"Cleaning Data in Python/duplicates.py","file_name":"duplicates.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"8311051544","text":"import random\n\ndef random_gift(category):\n books = ['Чистый код', 'Совершенный код', 'Паттерны ООП']\n gadgets = ['Умные часы', 'Умные Весы', 'Робот пылесос']\n games = ['Village', 'Halo Infinite', 'Far Cry 6']\n\n if category =='игры':\n return random.sample(games, 1)[0]\n elif category == 'книги':\n return random.sample(books, 1)[0]\n elif category == 'гаджеты':\n return random.sample(gadgets, 1)[0]\n else:\n return 'Нет подарков'\n\nprint(random_gift('игры'))\nprint(random_gift('книги'))\nprint(random_gift('гаджеты'))\n","repo_name":"W83w/Course-2-Django","sub_path":"Г1 5.1.5Подаркипотипу/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6366555376","text":"import copy\nfrom typing import TypeVar\n\nfrom torch.nn import Module, Parameter\n\nT = TypeVar(\"T\")\n\n\ndef module_only_deepcopy(obj: T, memo=None) -> T:\n \"\"\"Recursively copy but only modules, not the weights.\n In the return value, all weights are still shared with those in `obj`.\"\"\"\n\n memo = {}\n\n def recursive_scan_parameters(obj_):\n # Don't recurse down primitive types\n if isinstance(obj_, (int, float, bool, complex, str, bytes)):\n return\n # Additionally share all buffers of Module. For example, this accounts for\n # running_{mean|var} in BatchNorm.\n if isinstance(obj_, Module):\n buffers = obj_.__dict__.get(\"_buffers\")\n for buffer in buffers.values():\n memo[id(buffer)] = buffer\n # Share all parameters.\n if isinstance(obj_, Parameter):\n memo[id(obj_)] = obj_\n # Walk down all other types.\n elif isinstance(obj_, dict):\n for k in obj_.keys():\n recursive_scan_parameters(k)\n for v in obj_.values():\n recursive_scan_parameters(v)\n elif isinstance(obj_, (list, tuple)):\n for x in obj_:\n recursive_scan_parameters(x)\n elif hasattr(obj_, \"__dict__\"):\n for x in obj_.__dict__.values():\n recursive_scan_parameters(x)\n\n # Populate `memo`, and then deepcopy with `memo` so that things in memo are not copied.\n recursive_scan_parameters(obj)\n # noinspection PyArgumentList\n copied = copy.deepcopy(obj, memo)\n return copied\n","repo_name":"vzyrianov/hpvm-autograd","sub_path":"hpvm/projects/predtuner/predtuner/approxes/_copy.py","file_name":"_copy.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33203256990","text":"import maya.cmds as cmds\r\nimport maya.mel as mel\r\nfrom sys import exit\r\n\r\n\r\n#VARIABLES FOR USER TO ADJUST\r\nconstraintType = \"parent\" # \"orient\" for rotation, \"point\" for translation, \"parent\" for both\r\nbakeInterval = 1 # You can choose to bake on 1s, 2s, 3s, whatever interval you set\r\nsmartBake = False # Choose between True/False, on whether to use the Smart Bake option\r\nsmartBakeIntensity = 5 #This is the intensity of the smart bake. Bigger number means less keys but less accurate animation\r\n\r\n\r\n#FUNCTIONS\r\ndef assistMessage(message, time, toExit):\r\n #POPS UP A MESSAGE ON THE USER'S SCREEN TO INFORM THEM OF SOMETHING\r\n cmds.inViewMessage(amg=message, pos='midCenter', fade=True, fst=time, ck=True)\r\n if toExit == True:\r\n exit()\r\n \r\n \r\ndef hideAttributes(type, *controls):\r\n#HIDES UNNECESSARY ATTRIBUTES ON THE CONTROLS \r\n for item in controls:\r\n for attr in [\".\" + type + \"X\", \".\" + type + \"Y\", \".\" + type + \"Z\"]:\r\n cmds.setAttr(item + attr, k=False, cb=False)\r\n\r\n\r\ndef setConstraint(constraintType, parent, child, translateCurves, rotateCurves):\r\n #CONSTRAINT FUNCTION\r\n if constraintType == \"parent\":\r\n constraint = cmds.parentConstraint(parent, child, skipTranslate = translateCurves, skipRotate = rotateCurves)[0]\r\n elif constraintType == \"orient\":\r\n constraint = cmds.orientConstraint(parent, child, skip = rotateCurves)[0]\r\n elif constraintType == \"point\":\r\n constraint = cmds.pointConstraint(parent, child, skip = translateCurves)[0]\r\n \r\n return constraint\r\n\r\n\r\ndef getConstraintAttribute(constraintType):\r\n #SETS A KEY ON THE START AND END OF THE TIMELINE, SO THAT WE ENSURE THERE'S A BLEND NODE ALL THE TIME. IF THERE'S NO KEY BEFORE ADDING THE SETUP, THE SCRIPT WON'T APPLY A SWITCH ON THE BLEND NODE\r\n if constraintType == \"orient\":\r\n tempAttribute = \"rotate\"\r\n elif constraintType == \"point\":\r\n tempAttribute = \"translate\"\r\n elif constraintType == \"parent\":\r\n tempAttribute = [\"translate\", \"rotate\"]\r\n return tempAttribute\r\n \r\ndef getLockedCurves(obj, attribute):\r\n #GETS A LIST OF THE LOCKED CURVES FOR EITHER TRANSLATE, ROTATE OR SCALE, SO THE CONSTRAINTS KNOW WHICH CURVES TO AVOID\r\n curves = {\".{0}X\".format(attribute):\"x\", \".{0}Y\".format(attribute):\"y\", \".{0}Z\".format(attribute):\"z\"}\r\n for curve in curves.copy():\r\n if cmds.getAttr(obj+curve, l=True) == False:\r\n curves.pop(curve)\r\n curves = list(curves.values())\r\n return curves\r\n \r\ndef setup(obj, tempControl, constraintType, timelineStart, timelineEnd, translateCurves, rotateCurves):\r\n #ADDS A LOCATORS ONTO EVERY SELECTION AND SWITCHES IT TO WORLD SPACE BY REVERSING THE CONSTRAINTS\r\n cmds.currentTime(timelineStart)\r\n cmds.matchTransform(tempControl, obj)\r\n original_RO = cmds.getAttr(obj + \".rotateOrder\") #STORES THE ROTATION ORDER OF THE CURRENT CONTROL, TO BE ASSIGNED TO THE TEMP CONTROLS\r\n cmds.setAttr(tempControl + \".rotateOrder\", original_RO)\r\n matchScale(obj, tempControl)\r\n setConstraint(constraintType, obj, tempControl, translateCurves, rotateCurves)\r\n cmds.select(tempControl)\r\n cmds.bakeResults(t=(timelineStart, timelineEnd), pok=True, simulation=False, sr = [smartBake,smartBakeIntensity], sampleBy=bakeInterval)\r\n if smartBake == True:\r\n cmds.keyTangent(tempControl, e=True, itt=\"auto\", ott=\"auto\", t=(timelineStart, timelineEnd))\r\n cmds.filterCurve(tempControl + \".translate\", tempControl + \".rotate\")\r\n cmds.delete(cmds.listRelatives(type=\"constraint\"))\r\n\r\n\r\ndef createControl(name):\r\n #CREATES THE SHAPE OF THE CONTROL\r\n tempControl = cmds.curve(n=name, degree=1, point=[[-1, 0, -0], [1, 0, 0], [0,0,0], [0,0,-1], [0, 0, 1], [0,0,0], [0,-1,0], [0,1,0]])\r\n\r\n cmds.setAttr(tempControl + \".lineWidth\", 3)\r\n cmds.setAttr(tempControl + \".overrideEnabled\", 1)\r\n cmds.setAttr(tempControl + \".overrideColor\", 6)\r\n return tempControl\r\n \r\ndef matchScale(parent, children, scale=True):\r\n #SCALE UP AN OBJECT TO ANOTHER ONE'S BOUNDING BOX SCALE, INCASE IT'S BEEN FREEZE-TRANSFORMED. THIS WAY THE USER DOESN'T HAVE TO MANUALLY ADJUST THE SIZE\r\n children = cmds.ls(children, flatten=True)\r\n parentShapeNode = cmds.listRelatives(parent, shapes=True)[0]\r\n \r\n xMin, yMin, zMin, xMax, yMax, zMax = cmds.exactWorldBoundingBox(parentShapeNode)\r\n parentDistanceX, parentDistanceY, parentDistanceZ = [xMax-xMin, yMax-yMin, zMax-zMin]\r\n \r\n #result=[]\r\n for child in children:\r\n xMin, yMin, zMin, xMax, yMax, zMax = cmds.exactWorldBoundingBox(child)\r\n childDistanceX, childDistanceY, childDistanceZ = [xMax-xMin, yMax-yMin, zMax-zMin]\r\n \r\n #WE QUERY THE ORIGINAL SCALE OF THE LOCATOR \r\n originalX, originalY, originalZ = cmds.xform(child, q=True, s=True, r=True)\r\n \r\n \r\n divisionX, divisionY, divisionZ = [parentDistanceX/childDistanceX, parentDistanceY/childDistanceY, parentDistanceZ/childDistanceZ]\r\n \r\n #WE GET THE FINAL SCALE HERE, WE TAKE THE LONGEST NUMBER AND APPLY THAT TO ALL SCALE AXIS\r\n largestAxis = max([originalX*divisionX, originalY*divisionY, originalZ*divisionZ]) * 2\r\n newScale = [largestAxis, largestAxis, largestAxis]\r\n \r\n #this part is for return the information outside the function\r\n #[result.append(i) for i in newScale]\r\n\r\n if scale:\r\n cmds.xform(child, scale=newScale)\r\n \r\n\r\ndef add(a,b):\r\n result = a + b\r\n return result\r\ndef subtract(a,b):\r\n result = a - b\r\n return result \r\n \r\n\r\n\r\ndef divideInfluence(curve, timelineStart, timelineEnd, operator, value):\r\n #USUALLY APPLIED ON AN EMPTY SPACE WHERE THE RANGE ISN'T TOUCHING ANY PRE-EXISTING RANGES, SO IT HANDLES BOTH SIDES - THE START AND END\r\n cmds.setKeyframe(curve, t=(timelineStart, timelineEnd), value=value) \r\n cmds.setKeyframe(curve, t=(timelineStart-1, timelineEnd+1), value=operator(value,1)) \r\n\r\ndef adjustInfluence(curve, frame, offset, operator, value):\r\n #USUALLY USED WHEN THE RANGE WE'RE APPLYING IS RIGHT NEXT TO THE END OR START OF AN EXISTING RANGE, SO WE MERGE ONE PART, AND ONLY ADD KEYS ON THE OTHER PART. \r\n cmds.setKeyframe(curve, t=(frame), value=value) \r\n cmds.setKeyframe(curve, t=(frame + offset), value=operator(value,1)) \r\n\r\n\r\n\r\ndef applyInfluenceSwitch(curve, selectionShapeNode, timelineStart, timelineEnd, operator, value, storedFrameValue):\r\n #FUNCTION THAT HANDLES APPLYING A SWITCH ON THE CONSTRAINT INFLUENCE, AS WELL AS THE VISIBILITY \r\n \r\n keyframes = cmds.keyframe(curve, q=True)\r\n storedFrames = []\r\n\r\n #WE CHECK TO SEE WHAT EXISTING KEYFRAMES HAVE THE VALUE OF 0 OR 1 (DEPENDING ON IF YOU'VE CHOSEN THE VISIBILITY OR BLEND INDEX CURVES), AND STORE THEM IN A LIST SO THAT WE CAN PAIR THEM UP IN A DICTIONARY\r\n if keyframes != None:\r\n for keyframe in keyframes:\r\n if cmds.keyframe(curve, q=True, t=(keyframe, keyframe), eval=True)[0] == storedFrameValue:\r\n storedFrames.append(keyframe)\r\n \r\n pairedFrames = {storedFrames[frame]: storedFrames[frame + 1] for frame in range(0, len(storedFrames), 2)}\r\n timelineRange = []\r\n \r\n #IF THE TIMELINE RANGE IS IN-BETWEEN 1 OR 2 PAIRS, WE STORE THE START OR THE END OF THE TIMELINE RANGE IN A LIST FOR LATER COMPARISON \r\n for start,end in pairedFrames.items(): \r\n if start - 1 <= timelineStart <= end + 1:\r\n timelineRange.append(timelineStart)\r\n \r\n if start - 1 <= timelineEnd <= end + 1: \r\n timelineRange.append(timelineEnd)\r\n \r\n \r\n for start,end in pairedFrames.items():\r\n #IF OUR TIMELINE RANGE OVERSHADOWS A GIVEN PAIRING OR IS IN-BETWEEN IT, THE SCRIPT WILL ABORT AND THE LOCATOR WON'T BE ADDED\r\n if timelineStart <= int(start) and int(end) <= timelineEnd or int(start) <= timelineStart and timelineEnd <= int(end) or timelineStart < int(end) and int(start) < timelineEnd :\r\n assistMessage(\"Error: This locator overlaps with another locator on the timeline. \", 5000, True)\r\n \r\n confirmation = []\r\n #IF TIMELINE RANGE IS 0, THAT MEANS THAT OUR RANGE IS NOT INTERSECING WITH ANY EXISTING PAIRINGS AND CAN BE APPLIED NORMALLY\r\n if len(timelineRange) == 0:\r\n confirmation = 1\r\n divideInfluence(curve, timelineStart, timelineEnd, operator, value)\r\n \r\n #IF WE'RE TRYING TO FIT A TIMELINE RANGE INBETWEEN 2 OTHER RANGES, THIS CODE GETS EXECUTED \r\n \r\n elif len(timelineRange) == 2:\r\n cmds.cutKey(curve, t=(timelineStart, timelineStart - 1))\r\n cmds.cutKey(curve, t=(timelineEnd, timelineEnd + 1))\r\n confirmation = 1\r\n else:\r\n #IF TIMELINE RANGE IS 1, WE CHECK TO SEE IF OUR TIMELINESTART AND TIMELINEEND ARE TOUCHING THE VALUE STORED IN TIMELINERANGE. IF IT IS TOUCHING, WE MERGE THE POINT THEY TOUCH AND EXTEND UP TOWARDS THE OTHER END\r\n for start,end in pairedFrames.items():\r\n if timelineStart == int(end) + 1:\r\n confirmation = 1\r\n cmds.cutKey(curve, t=(timelineStart - 1, timelineEnd))\r\n adjustInfluence(curve, timelineEnd, 1, operator, value )\r\n elif int(start) - 1 == timelineEnd :\r\n confirmation = 1\r\n cmds.cutKey(curve, t=(timelineStart, timelineEnd + 1))\r\n adjustInfluence(curve, timelineStart, -1, operator, value )\r\n \r\n #IF TIMELINE RANGE IS 1 OR 2, BUT IT'S OVERLAPPING RATHER THAN TOUCHING ON ONE OF THE ENDS, WELL THEN WE PROCLAIM THAT THE USER CAN'T APPLY THE SETUP\r\n if confirmation != 1 and selectionShapeNode == curve:\r\n assistMessage(\"Error: This locator overlaps with another locator on the timeline. \", 5000, True)\r\n\r\n\r\n\r\n\r\naTimeSlider = mel.eval('$tmpVar=$gPlayBackSlider')\r\ntimeRange = cmds.timeControl(aTimeSlider, q=True, rangeArray=True)\r\n\r\nif 2 < (timeRange[1] - timeRange[0]):\r\n specificTimelineMode = True\r\n timelineStart = timeRange[0]\r\n timelineEnd = timeRange[1]\r\nelse:\r\n specificTimelineMode = False\r\n #QUERIES THE START AND END FRAME OF THE CURRENT TIMELINE\r\n timelineStart = cmds.playbackOptions(min=True, q=True)\r\n timelineEnd = cmds.playbackOptions(max=True, q=True)\r\n\r\n#PREVENTS THE USER FROM APPLYING THE SETUP IN A NEGATIVE RANGE TIMELINE\r\nif timelineStart < 0 or timelineEnd <0:\r\n assistMessage(\"Error: You can't apply a locator setup on a negative time-range \", 5000, True)\r\n\r\nselection = cmds.ls(sl=True)\r\n\r\n\r\n\r\n#ADVISES THE USER TO SELECT SOMETHING BEFORE RUNNING THIS SCRIPT\r\nif len(selection) == 0:\r\n assistMessage(\"You need to select at least 1 object to turn into world space\", 4000, True)\r\nelse: \r\n for obj in selection:\r\n #PREVENTS THE USER FROM APPLYING A LOCATOR SETUP ON TOP OF AN EXISTING LOCATOR\r\n if \"Petar3D\" in obj:\r\n assistMessage(\"Error: You can't stack locator setups\", 4000, True)\r\n \r\n #CHECKS TO SEE IF THERE'S ALREADY AN ORIENT OR A POINT CONSTRAINT, SO THAT IT DOESN'T TRY TO APPLY A PARENT CONSTRAINT, AND VICE VERSA\r\n if cmds.listConnections(obj, c=True) != None:\r\n for item in cmds.ls(\"*_Petar3D_worldSpaceLocator*\", tr=True):\r\n if obj + \"_Petar3D_worldSpaceLocator_point\" in item and constraintType == \"parent\" or obj + \"_Petar3D_worldSpaceLocator_orient\" in item and constraintType == \"parent\":\r\n assistMessage(\"Error: You already have an orient/point point constraint applied, you can't apply a parent constraint \", 5000, True)\r\n if obj + \"_Petar3D_worldSpaceLocator_parent\" in item and constraintType == \"orient\" or obj + \"_Petar3D_worldSpaceLocator_parent\" in item and constraintType == \"point\":\r\n assistMessage(\"Error: You already have a parent cosntraint applied, you can't applied an orient/point constraint \", 5000, True)\r\n\r\n\r\n #CHECKS TO SEE IF THERE'S ALREADY A NIS-TYPE OF LOCATOR SETUO, AND IF SO IT DOESN'T LET THE USER APPLY AN IFS-TYPE LOCATOR, AND VICE VERSA\r\n for item in cmds.ls(obj + \"_Petar3D*\", tr=True):\r\n if \"NIS\" in item and specificTimelineMode == True:\r\n assistMessage(\"Error: You already have a locator with overall influence over this selection. You can't mix overall with partial influence locators\", 4000, True)\r\n elif \"IFS\" in item and specificTimelineMode == False:\r\n assistMessage(\"Error: You already have a locator with partial influence over this selection. You can't mix partial with overall influence locators\", 4000, True)\r\n \r\n #GETS A LIST OF ALL THE LOCKED CURVES SO THAT THE CONSTRAINTS KNOW WHICH CURVES TO SKIP OVER\r\n translateCurves = getLockedCurves(obj, \"translate\") \r\n rotateCurves = getLockedCurves(obj, \"rotate\")\r\n \r\n #WE CHECK TO SEE IF ALL ROTATE AND TRANSLATE CHANNELS ARE LOCKED. IF THEY ARE, THERE'S NO POINT IN APPLYING THIS SCRIPT\r\n if len(translateCurves + rotateCurves) != 6: \r\n \r\n #SWITCHES THE VISIBILITY ON THE ORIGINAL SELECTION,\r\n selectionShapeNode = cmds.listRelatives(obj, shapes=True, children=True)[0] \r\n if specificTimelineMode:\r\n applyInfluenceSwitch(selectionShapeNode + \".v\", selectionShapeNode + \".v\", timelineStart, timelineEnd, add, 0, 0)\r\n else:\r\n cmds.setAttr(selectionShapeNode + \".v\", 0)\r\n \r\n #CREATES THE TEMP LOCATOR \r\n if specificTimelineMode:\r\n tempControl = createControl(obj + \"_Petar3D_worldSpaceLocator_{0}_IFS_{1}_{2}\".format(constraintType, int(timelineStart), int(timelineEnd))) \r\n else:\r\n tempControl = createControl(obj + \"_Petar3D_worldSpaceLocator_{0}_NIS\".format(constraintType)) \r\n \r\n #POSITIONS THE LOCATOR TO THE ORIGINAL SELECTION AND BAKES IT DOWN\r\n setup(obj, tempControl, constraintType, timelineStart, timelineEnd, translateCurves, rotateCurves) \r\n locatorShapeNode = cmds.listRelatives(tempControl, shapes=True, children=True)[0] \r\n \r\n hideAttributes(\"scale\", tempControl)\r\n cmds.lockNode(tempControl, l=True)\r\n \r\n #VISIBILITY SWITCH FOR LOCATOR\r\n if specificTimelineMode:\r\n applyInfluenceSwitch(locatorShapeNode + \".v\", selectionShapeNode + \".v\", timelineStart, timelineEnd, subtract, 1, 0)\r\n \r\n \r\n #CHECKS WHICH ATTRIBUTE TO PLACE THE INITIAL KEYS ON\r\n tempAttribute = getConstraintAttribute(constraintType)\r\n \r\n #CHECKS TO SEE IF THE ORIGINAL CONTROL HAS ANY KEYS ON ITS CURVES ALREADY, AND IF NOT IT PLACES THEM TO ACTIVATE THE BLEND INDEX\r\n if cmds.keyframe(selection, at =tempAttribute, q=True) == None:\r\n cmds.setKeyframe(obj, t=(timelineStart, timelineEnd), at=tempAttribute) \r\n else:\r\n cmds.setKeyframe(obj, t=(timelineStart, timelineEnd), at=tempAttribute, pcs=True, i=True) \r\n \r\n \r\n #LOCATOR CONSTRAINT SECTION \r\n constraint = setConstraint(constraintType, tempControl, obj, translateCurves, rotateCurves)\r\n #IF THE CONSTRAINT TYPE IS ORIENT, WE APPLY A REVERSE POINT CONSTRAINT\r\n if constraintType == \"orient\":\r\n pointConstraint = setConstraint(\"point\", obj, tempControl, translateCurves, rotateCurves) \r\n \r\n #IF THE RIG IS REFERENCED, WE STORE THE NAME OF THE TEMP LOCATOR WITHOUT THE NAMESPACE, BECAUSE THE COSNTRAINT WE'LL INFLUENCE DON'T HAVE THE NAMESPACE INSIDE\r\n if cmds.referenceQuery(obj, isNodeReferenced=True) or \":\" in obj: \r\n tempControl = tempControl.split(\":\")[1]\r\n \r\n #WE'RE TRYING TO FIND THE INDEX AT THE END OF THE CONSTRAINT'S WEIGHT ATTRIBUTE. BECAUSE THERE COULD BE MANY CONSTRAINTS APPLIED ON THE SAME OBJECT, WE CAN'T ALWAYS KNOW WHAT THAT NUMBER WILL BE\r\n for item in cmds.listConnections(constraint, c=True): \r\n if \"{0}.{1}W\".format(constraint, tempControl) in item:\r\n constraintIndex = item[-1:]\r\n \r\n #THE CONSTRAINT HAVE A NUMBER AT THE END, WE STORE THIS NUMBER IN A VARIABLE SO WE KNOW WHICH NUMBER TO ATTACHA WHEN WE INFLUENCE THE BLEND NODE\r\n if specificTimelineMode:\r\n applyInfluenceSwitch(\"{0}.{1}W{2}\".format(constraint, tempControl, constraintIndex), selectionShapeNode + \".v\", timelineStart, timelineEnd, subtract, 1, 0) \r\n blendIndex = constraint[-1:] \r\n \r\n #BLEND NODE SWITCH SECTION \r\n if specificTimelineMode:\r\n applyInfluenceSwitch(\"{0}.blend{1}{2}\".format(obj, constraintType.capitalize(), blendIndex), selectionShapeNode + \".v\", timelineStart, timelineEnd, subtract, 1, 1)\r\n \r\n #GIVES THIS ERROR IF ALL 6 CURVES ARE LOCKED AND THERE'S NO POINT IN APPLYING THE SCRIPT\r\n else:\r\n assistMessage(\"Error: All translate and rotate curves on this selection are locked - {0} \".format(obj), 4000, False)\r\n ","repo_name":"PetarPehchevski3D/World_Space_Conversion_Maya_Python_Script","sub_path":"World_Space_Conversion - ApplyLocator.py","file_name":"World_Space_Conversion - ApplyLocator.py","file_ext":"py","file_size_in_byte":17455,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"11864194462","text":"\"\"\"empty message\n\nRevision ID: 5cef6dbead0a\nRevises: 1beffd33a2f2\nCreate Date: 2023-05-16 01:57:32.993552\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5cef6dbead0a'\ndown_revision = '1beffd33a2f2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('collaborator',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('project_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['project_id'], ['project.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('collaborator')\n # ### end Alembic commands ###\n","repo_name":"olaracode/wave-api","sub_path":"migrations/versions/5cef6dbead0a_.py","file_name":"5cef6dbead0a_.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34721127221","text":"\"\"\"\nPython et la POO\n\"\"\"\nfrom enum import Enum\nfrom abc import ABC, abstractmethod\n\nclass TypeEvaluation(Enum):\n CONTROLE = 1\n EXAMEN = 2\n\nclass Module:\n \"\"\"\n Permet de mémoriser les informations sur un module\n \"\"\"\n def __init__(self, id=None, nom_module=None, volume_horaire=None, coefficient=None):\n \"\"\"Initialiseur de la classe Module \"\"\"\n self.id = id\n self.nom_module = nom_module\n self.volume_horaire = volume_horaire\n self.coefficient = coefficient\n \n def __str__(self):\n return f\"Id: {self.id}\\nNom: {self.nom_module} \\\n \\nVolume horaire: {self.volume_horaire} \\\n \\nCoefficient: {self.coefficient}\"","repo_name":"Eduildo/Base-python","sub_path":"gestion_etudiant/Modules/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"42656578893","text":"from datetime import datetime\nfrom typing import Optional, cast\n\nimport torch\nfrom rich import inspect, print\nfrom transformers import logging as t_logging\n\nimport predict\nimport preprocess\nimport tune\nfrom params import PARAMS\nimport models\nimport logging\n\n\nimport typer\n\napp = typer.Typer()\n\n\n@app.command(help=\"Train model on the `train` dataset.\")\ndef train(\n pretrain: bool = typer.Option(False, help=\"Whether to include pretrain step.\"),\n save_model: Optional[str] = typer.Option(\n None,\n \"--save\",\n help=\"Whether to save the trained model and its name (dist/model.().(timestamp).pt).\",\n ),\n context: int = typer.Option(\n 9, help=\"How many utterances are included in the question as context.\"\n ),\n freeze_layers: int = typer.Option(\n 9, help=\"How many BERT layers are freezed during (pre)training.\"\n ),\n data_size: int = typer.Option(1500, help=\"Size of training data.\"),\n learning_rate: float = typer.Option(\n 5e-5, \"--lr\", help=\"Learning rate of training step.\"\n ),\n batch_size: int = typer.Option(16, help=\"Batch size of training step.\"),\n):\n PARAMS.BATCH_SIZE = batch_size\n PARAMS.CONTEXT_LENGTH = context\n PARAMS.DATA_SIZE = data_size\n PARAMS.FREEZE_LAYERS = freeze_layers\n PARAMS.LEARNING_RATE = learning_rate\n\n timestamp = datetime.now().strftime(\"%m%dT%H%M%S\")\n\n # Load pretrained BERT from Huggingface Hub\n tokenizer, bert = tune.get_pretrained()\n model = models.ModelMultipleChoice(cast(models.BertModel, bert))\n\n # A pretrain step on a next sentence prediction task\n if pretrain:\n dataloader_pretrain = preprocess.get_nsp_dataloader(tokenizer=tokenizer)\n model = tune.pretrain_on_nsp(\n model, dataloader=dataloader_pretrain, device=torch.device(0)\n )\n\n dataloader_train = preprocess.get_dataloader(\"train\", tokenizer=tokenizer)\n dataloader_valid = preprocess.get_dataloader(\"valid\", tokenizer=tokenizer)\n\n # Train (Finetune)\n model = tune.train(\n model=model,\n dataloader=dataloader_train,\n device=torch.device(0),\n dataloader_eval=dataloader_valid,\n )\n\n timestamp_to = datetime.now().strftime(\"%m%dT%H%M%S\")\n\n if save_model is not None:\n torch.save(model, f\"models/model.{save_model}.{timestamp}.{timestamp_to}.pt\")\n\n\n@app.command(help=\"Evaluate model with `valid` dataset.\")\ndef eval(\n name: str,\n valid_size: Optional[int] = typer.Option(\n None,\n help=\"Sampling amount of validation on samples. Leave `None` for no sampling.\",\n ),\n):\n print(f\"[blue bold]eval: [underline]{name}\")\n PARAMS.VALID_SIZE = valid_size\n\n tokenizer, model = tune.get_pretrained(name)\n dataloader = preprocess.get_dataloader(\"valid\", tokenizer=tokenizer)\n\n # Evaluate the model\n model = tune.eval(model, dataloader=dataloader, device=torch.device(0))\n\n\n@app.command(help=\"Predict labels on the `test` dataset.\")\ndef test(name: str):\n print(f\"[green bold]test: [underline]{name}\")\n tokenizer, model = tune.get_pretrained(name)\n dataloader = preprocess.get_test_dataloader(tokenizer=tokenizer)\n\n with open(\"data/test_label.json\", \"w\") as buf:\n predict.predict(\n model, buffer=buf, dataloader=dataloader, device=torch.device(0)\n )\n\n\nif __name__ == \"__main__\":\n # Suppress `huggingface` warnings\n t_logging.set_verbosity_error()\n logging.getLogger(\"transformers.tokenization_utils\").setLevel(logging.ERROR)\n\n # CLI entrance\n app()\n","repo_name":"Yixuan-Wang/datamine-xiangsheng","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"44181286943","text":"from dataclasses import dataclass\nimport sys\nimport os\ncurrent_dir = os.path.dirname(__file__)\nsys.path.append(current_dir)\n\nfrom custom_classifier import _CustomClassifier\n# from SBMLKinetics.common.simple_sbml import SimpleSBML\n# from SBMLKinetics.common.reaction import Reaction\nfrom typing import List, Dict, Optional\nfrom SBMLKinetics.common.simple_sbml import SimpleSBML\nimport util\nfrom results import Results\n\nimport antimony\nimport libsbml\nimport os\nimport re\nimport sympy as sp\n\nfrom typing import List, Any\n\nZERO = \"ZERO\"\nUNDR1 = \"UNDR1\"\nUNDR2 = \"UNDR2\"\nUNDR3 = \"UNDR3\"\nUNDR_A1 = \"UNDR-A1\"\nUNDR_A2 = \"UNDR-A2\"\nUNDR_A3 = \"UNDR-A3\"\nBIDR11 = \"BIDR11\"\nBIDR12 = \"BIDR12\"\nBIDR21 = \"BIDR21\"\nBIDR22 = \"BIDR22\"\nBIDR_A11 = \"BIDR-A11\"\nBIDR_A12 = \"BIDR-A12\"\nBIDR_A21 = \"BIDR-A21\"\nBIDR_A22 = \"BIDR-A22\"\nMM = \"MM\"\nMM_CAT = \"MMcat\"\nAMM = \"AMM\"\nIMM = \"IMM\"\nRMM = \"RMM\"\nRMM_CAT = \"RMMcat\"\nHILL = \"Hill\"\n\nNON_MM_KEYS = [\n ZERO, UNDR1, UNDR2, UNDR3, UNDR_A1, UNDR_A2, UNDR_A3,\n BIDR11, BIDR12, BIDR21, BIDR22, BIDR_A11, BIDR_A12, BIDR_A21, BIDR_A22\n]\n\nMM_KEYS = [MM, MM_CAT, AMM, IMM, RMM, RMM_CAT]\n\nUNDR_KEYS = [UNDR1, UNDR2, UNDR3]\n\nUNDR_A_KEYS = [UNDR_A1, UNDR_A2, UNDR_A3]\n\nBIDR_ALL_KEYS = [BIDR11, BIDR12, BIDR21, BIDR22,\n BIDR_A11, BIDR_A12, BIDR_A21, BIDR_A22]\n\nMM_CAT_KEYS = [MM_CAT, AMM, IMM, RMM_CAT]\n\nUNDR_SBOS = [41, 43, 44, 45, 47, 49, 50, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 140, 141, 142, 143, 144, 145, 146, 163, 166, 333, 560, 561, 562, 563, 564, 430, 270, 458,\n 275, 273, 379, 440, 443, 451, 454, 456, 260, 271, 378, 387, 262, 265, 276, 441, 267, 274, 444, 452, 453, 455, 457, 386, 388, 442, 277, 445, 446, 447, 448, 266, 449, 450]\n\nUNDR_A_SBOS = [41, 43, 44, 45, 47, 49, 50, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n 140, 141, 142, 143, 144, 145, 146, 163, 166, 333, 560, 561, 562, 563, 564]\n\nBI_SBOS = [42, 69, 78, 88, 109, 646, 70, 71, 74, 79, 80, 81, 84, 89, 99, 110, 120, 130, 72, 73, 75, 76, 77, 82, 83, 85, 86, 87, 90, 91, 92, 95, 100, 101, 102, 105, 111, 112,\n 113, 116, 121, 122, 123, 126, 131, 132, 133, 136, 93, 94, 96, 97, 98, 103, 104, 106, 107, 108, 114, 115, 117, 118, 119, 124, 125, 127, 128, 129, 134, 135, 137, 138, 139]\n\nMM_SBOS = [28, 29, 30, 31, 199]\n\nMM_CAT_SBOS = [28, 29, 30, 31, 199, 430, 270, 458, 275, 273, 379, 440, 443, 451, 454, 456, 260, 271, 378, 387,\n 262, 265, 276, 441, 267, 274, 444, 452, 453, 455, 457, 386, 388, 442, 277, 445, 446, 447, 448, 266, 449, 450]\n\nHILL_SBOS = [192, 195, 198]\n\n\n@dataclass\nclass ReactionData:\n reaction_id: str\n kinetics: str\n kinetics_sim: str\n reactant_list: List[str]\n product_list: List[str]\n species_in_kinetic_law: List[str]\n parameters_in_kinetic_law: List[str]\n ids_list: List[str]\n sorted_species: List[str]\n boundary_species: List[str]\n parameters_in_kinetic_law_only: List[str]\n compartment_in_kinetic_law: List[str]\n is_reversible: bool\n sbo_term: int\n codes: List[int]\n\n\nclass Analyzer:\n \"\"\"\n The Analyzer class analyzes SBML models to check if the rate laws are following \n some rules. It uses sympy for processing mathematical symbol expressions, libsbmlpython \n for processing SBML models, and SBMLKinetics for analyzing SBML models and classifying \n rate laws. The class can return errors and warnings based on the specified checks.\n \"\"\"\n\n def __init__(self, model_str: str, rate_law_classifications_path: str = None):\n \"\"\"\n Initializes the Analyzer class.\n\n Args:\n model_str (str): Path to the model file, or the string representation of model.\n rate_law_classifications_path (str): Path to the rate law classification file.\n customized rate law classification.\n\n Examples:\n import Analyzer from ratesb_python.common.analyzer\n analyzer = Analyzer(\"path/to/biomodel.xml\", \"path/to/rate_laws.json\")\n analyzer.check_all()\n results = analyzer.results\n print(str(results))\n str(results)\n \"\"\"\n splitted_path = os.path.splitext(model_str)\n ext = splitted_path[1]\n xml = ''\n if ext == '.ant' or ext == '.txt':\n ant = util.get_model_str(model_str, False)\n load_int = antimony.loadAntimonyString(ant)\n if load_int > 0:\n xml = antimony.getSBMLString()\n else:\n raise ValueError(\"Invalid Antimony model.\")\n elif ext == '.xml':\n xml = util.get_model_str(model_str, True)\n else:\n raise ValueError(\n \"Invalid file format, accepting .xml, .ant, and .txt\")\n reader = libsbml.SBMLReader()\n document = reader.readSBMLFromString(xml)\n util.checkSBMLDocument(document)\n self.model = document.getModel()\n self.simple = SimpleSBML(self.model)\n self.custom_classifier = None\n self.default_classifications = {}\n self.custom_classifications = {}\n self.results = Results()\n self.default_classifier = _CustomClassifier(os.path.join(\n os.path.dirname(__file__), \"default_classifier.json\"))\n\n if rate_law_classifications_path:\n self.custom_classifier = _CustomClassifier(\n rate_law_classifications_path)\n if len(self.custom_classifier.warning_message) > 0:\n print(self.custom_classifier.warning_message)\n\n def check(self, code: Optional[int] = None):\n \"\"\"\n Performs a check based on the provided error or warning code. If no code is provided, \n all checks are performed.\n\n Args:\n code (Optional[int]): Code of the check to perform. If None, all checks are performed.\n\n Updates:\n The results of the check(s) to self.results.\n \"\"\"\n if code is None:\n self.check_except([])\n else:\n self.checks([code])\n\n def check_except(self, excluded_codes: Optional[List[int]] = []):\n \"\"\"\n Performs all checks except the ones corresponding to the provided list of error or warning codes.\n\n Args:\n excluded_codes (Optional[List[int]]): List of codes of the checks to exclude. If None, all checks are performed.\n\n Updates:\n The results of the check(s) to self.results.\n \"\"\"\n all_checks = []\n for i in range(1, 3):\n all_checks.append(i)\n for i in range(1001, 1007):\n all_checks.append(i)\n for i in range(1010, 1011):\n all_checks.append(i)\n for i in range(1020, 1023):\n all_checks.append(i)\n for i in range(1030, 1038):\n all_checks.append(i)\n for i in range(1040, 1045):\n all_checks.append(i)\n self.checks(list(set(all_checks) - set(excluded_codes)))\n\n def check_all(self):\n \"\"\"\n Performs all checks.\n\n Updates:\n The results of the check_all to self.results.\n \"\"\"\n self.check_except([])\n\n def checks(self, codes):\n \"\"\"\n Performs multiple checks based on the provided list of error or warning codes. If no codes are provided, \n all checks are performed.\n\n Args:\n codes (List[int]): List of codes of the checks to perform.\n\n Updates:\n The results of the checks to self.results.\n \"\"\"\n \n self.default_classifications = {}\n self.custom_classifications = {}\n self.results.clear_results()\n\n for reaction in self.simple.reactions:\n reaction.kinetic_law.formula = reaction.kinetic_law.formula.replace(\n '^', '**')\n ids_list = list(dict.fromkeys(reaction.kinetic_law.symbols))\n\n libsbml_kinetics = reaction.kinetic_law.libsbml_kinetics\n sbo_term = -1\n if libsbml_kinetics:\n sbo_term = libsbml_kinetics.getSBOTerm()\n\n reaction_id = reaction.getId()\n sorted_species = self._get_sorted_species(reaction.reaction)\n species_list, parameter_list, compartment_list, kinetics, kinetics_sim = self._preprocess_reactions(\n reaction)\n reactant_list, product_list = self._extract_kinetics_details(\n reaction)\n species_in_kinetic_law, parameters_in_kinetic_law_only, compartment_in_kinetic_law, others_in_kinetic_law = self._identify_parameters_in_kinetics(\n ids_list, species_list, parameter_list, compartment_list)\n boundary_species = self._get_boundary_species(\n reactant_list, product_list)\n\n data = ReactionData(\n reaction_id=reaction_id,\n kinetics=kinetics,\n kinetics_sim=kinetics_sim,\n reactant_list=reactant_list,\n product_list=product_list,\n species_in_kinetic_law=species_in_kinetic_law,\n parameters_in_kinetic_law=parameters_in_kinetic_law_only + others_in_kinetic_law,\n ids_list=ids_list,\n sorted_species=sorted_species,\n boundary_species=boundary_species,\n parameters_in_kinetic_law_only=parameters_in_kinetic_law_only,\n compartment_in_kinetic_law=compartment_in_kinetic_law,\n is_reversible=reaction.reaction.getReversible(),\n sbo_term=sbo_term,\n codes=codes\n )\n\n self._set_kinetics_type(**data.__dict__)\n if 1 in codes:\n self._check_empty_kinetics(**data.__dict__)\n if 2 in codes:\n self._check_floating_species(**data.__dict__)\n if 1001 in codes:\n self._check_pure_number(**data.__dict__)\n if 1002 in codes:\n self._check_unrecognized_rate_law(**data.__dict__)\n if 1003 in codes:\n self._check_flux_increasing_with_reactant(**data.__dict__)\n if 1004 in codes:\n self._check_flux_decreasing_with_product(**data.__dict__)\n if 1005 in codes:\n self._check_boundary_floating_species(**data.__dict__)\n if 1006 in codes:\n self._check_constant_parameters(**data.__dict__)\n if 1010 in codes:\n self._check_irreversibility(**data.__dict__)\n if 1020 in codes or 1021 in codes or 1022 in codes:\n self._check_naming_conventions(**data.__dict__)\n if any(isinstance(num, int) and 1030 <= num <= 1037 for num in codes):\n self._check_formatting_conventions(**data.__dict__)\n if any(isinstance(num, int) and 1040 <= num <= 1044 for num in codes):\n self._check_sboterm_annotations(**data.__dict__)\n\n # self._check_empty_kinetics(**kwargs)\n # self._check_boundary_floating_species(**kwargs)\n\n def _get_sorted_species(self, reaction):\n sorted_species_reference = [reaction.getReactant(n) for n in range(\n reaction.getNumReactants())] + [reaction.getProduct(n) for n in range(reaction.getNumProducts())]\n sorted_species = []\n for species_reference in sorted_species_reference:\n sorted_species.append(species_reference.getSpecies())\n return sorted_species\n\n def _preprocess_reactions(self, reaction):\n # Extract and process necessary data from the reaction\n species_num = self.model.getNumSpecies()\n parameter_num = self.model.getNumParameters()\n compartment_num = self.model.getNumCompartments()\n\n species_list = [self.model.getSpecies(\n i).getId() for i in range(species_num)]\n parameter_list = [self.model.getParameter(\n i).getId() for i in range(parameter_num)]\n compartment_list = [self.model.getCompartment(\n i).getId() for i in range(compartment_num)]\n\n kinetics = reaction.kinetic_law.expanded_formula\n\n try:\n kinetics_sim = str(sp.simplify(kinetics))\n except:\n kinetics_sim = kinetics\n\n return species_list, parameter_list, compartment_list, kinetics, kinetics_sim\n\n def _extract_kinetics_details(self, reaction):\n reactant_list = [r.getSpecies() for r in reaction.reactants]\n product_list = [p.getSpecies() for p in reaction.products]\n return reactant_list, product_list\n\n def _identify_parameters_in_kinetics(self, ids_list, species_list, parameter_list, compartment_list):\n species_in_kinetic_law = []\n parameters_in_kinetic_law_only = []\n compartment_in_kinetic_law = []\n others_in_kinetic_law = []\n\n for id in ids_list:\n if id in species_list:\n species_in_kinetic_law.append(id)\n elif id in parameter_list:\n parameters_in_kinetic_law_only.append(id)\n elif id in compartment_list:\n compartment_in_kinetic_law.append(id)\n others_in_kinetic_law.append(id)\n else:\n others_in_kinetic_law.append(id)\n\n return species_in_kinetic_law, parameters_in_kinetic_law_only, compartment_in_kinetic_law, others_in_kinetic_law\n\n def _get_boundary_species(self, reactant_list, product_list):\n boundary_species = [reactant for reactant in reactant_list if self.model.getSpecies(\n reactant).getBoundaryCondition()]\n boundary_species += [product for product in product_list if self.model.getSpecies(\n product).getBoundaryCondition()]\n return boundary_species\n\n def _set_kinetics_type(self, **kwargs):\n reaction_id = kwargs[\"reaction_id\"]\n self.default_classifications[reaction_id] = self.default_classifier.custom_classify(\n is_default=True, **kwargs)\n if self.custom_classifier:\n self.custom_classifications[reaction_id] = self.custom_classifier.custom_classify(\n **kwargs)\n\n def _check_empty_kinetics(self, **kwargs):\n \"\"\"\n Checks if the given reaction has an empty kinetic law.\n Code: 1\n\n Args:\n reaction_id (str): The reaction's id'.\n kinetics (str): The kinetic law\n\n Adds:\n An error message to results specifying that no rate law was entered for the reaction.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n kinetics = kwargs[\"kinetics\"]\n if len(kinetics.replace(' ', '')) == 0:\n self.results.add_message(\n reaction_id, 1, f\"No rate law entered.\", False)\n\n def _check_floating_species(self, **kwargs):\n \"\"\"\n Checks if all reactants in the rate law of the given reaction are defined as species, excluding boundary species.\n Code: 2\n\n Args:\n reaction_id (str): The reaction's id'.\n species_in_kinetic_law (list): A list of species present in the rate law.\n reactant_list (list): A list of reactants for the reaction.\n boundary_species (list): A list of boundary species in the model.\n\n Adds:\n An error message to results specifying the missing reactants that are expected in the rate law.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n species_in_kinetic_law = kwargs[\"species_in_kinetic_law\"]\n reactant_list = kwargs[\"reactant_list\"]\n boundary_species = kwargs[\"boundary_species\"]\n\n floating_species = []\n for reactant in reactant_list:\n if reactant not in species_in_kinetic_law:\n if reactant not in boundary_species:\n floating_species.append(reactant)\n if len(floating_species) > 0:\n floating_species = \",\".join(floating_species)\n self.results.add_message(\n reaction_id, 2, f\"Expecting reactants in rate law: {floating_species}\", False)\n\n def _check_pure_number(self, **kwargs):\n \"\"\"\n Checks if the rate law contains only number\n Code: 1001\n\n Args:\n reaction_id (str): The reaction's id'.\n kinetics_sim: string-simplified kinetics\n\n Adds:\n A warning message to results specifying that the rate law contains only numbers.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n kinetics_sim = kwargs[\"kinetics_sim\"]\n try:\n float(kinetics_sim)\n self.results.add_message(\n reaction_id, 1001, \"Rate law contains only number.\")\n except:\n return\n\n def _check_unrecognized_rate_law(self, **kwargs):\n \"\"\"\n Checks if the rate law from the standard and custom list (if given) is recognized\n Code: 1002\n\n Args:\n reaction_id (str): The reaction's id'.\n\n Adds:\n A warning message to results specifying that the rate law is unrecognized.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n if len(self.custom_classifications) > 0:\n if not (any(self.default_classifications[reaction_id].values()) or any(self.custom_classifications[reaction_id].values())):\n self.results.add_message(\n reaction_id, 1002, \"Unrecognized rate law from the standard list and the custom list.\")\n else:\n if not any(self.default_classifications[reaction_id].values()):\n self.results.add_message(\n reaction_id, 1002, \"Unrecognized rate law from the standard list.\")\n\n def _check_flux_increasing_with_reactant(self, **kwargs):\n \"\"\"\n Checks if the flux is increasing as the reactant increases.\n Code: 1003\n\n Args:\n reaction_id (str): The reaction's id'.\n reactant_list (str): List of reactants in reaction\n kinetics (str): the kinetic law\n\n Adds:\n A warning message to results specifying if the flux is not increasing as reactant increases.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n reactant_list = kwargs[\"reactant_list\"]\n kinetics = kwargs[\"kinetics\"]\n\n if not util.check_symbols_derivative(sp.sympify(kinetics), reactant_list):\n self.results.add_message(\n reaction_id, 1003, \"Flux is not increasing as reactant increases.\")\n\n def _check_flux_decreasing_with_product(self, **kwargs):\n \"\"\"\n Checks if the flux is increasing as the product decreases.\n Code: 1004\n\n Args:\n reaction_id (str): The reaction's id'.\n is_reversible (bool): the reaction's reversibility\n product_list (list): List of products in reaction\n kinetics (str): the kinetic law\n\n Adds:\n A warning message to results specifying if the flux is not decreasing as product increases.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n is_reversible = kwargs[\"is_reversible\"]\n product_list = kwargs[\"product_list\"]\n kinetics = kwargs[\"kinetics\"]\n\n if is_reversible:\n if not util.check_symbols_derivative(sp.sympify(kinetics), product_list, False):\n self.results.add_message(\n reaction_id, 1004, \"Flux is not decreasing as product increases.\")\n\n def _check_boundary_floating_species(self, **kwargs):\n \"\"\"\n Checks if any reactant in the rate law of the given reaction is a boundary species.\n Code: 1005\n\n Args:\n reaction_id (str): The reaction's id'.\n species_in_kinetic_law: A list of species present in the rate law.\n reactant_list: A list of reactants for the reaction.\n boundary_species: A list of boundary species in the model.\n\n Adds:\n A warning message to results specifying the boundary species reactants found in the rate law.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n species_in_kinetic_law = kwargs[\"species_in_kinetic_law\"]\n reactant_list = kwargs[\"reactant_list\"]\n boundary_species = kwargs[\"boundary_species\"]\n\n boundary_floating_species = []\n for reactant in reactant_list:\n if reactant not in species_in_kinetic_law:\n if reactant in boundary_species:\n boundary_floating_species.append(reactant)\n if len(boundary_floating_species) > 0:\n boundary_floating_species = \",\".join(boundary_floating_species)\n self.results.add_message(\n reaction_id, 1005, f\"Expecting boundary species reactant in rate law: {boundary_floating_species}\")\n\n def _check_constant_parameters(self, **kwargs):\n \"\"\"\n Checks if the parameters in the rate law are constants.\n Code: 1006\n TODO remove libsbml dependency\n\n Args:\n reaction_id (str): The reaction's id'.\n parameters_in_kinetic_law_only (list): the parameters in kinetic law\n\n Adds:\n A warning message to results specifying if the parameters are not constants.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n parameters_in_kinetic_law_only = kwargs[\"parameters_in_kinetic_law_only\"]\n non_constant_params = []\n for param in parameters_in_kinetic_law_only:\n libsbml_param = self.model.getParameter(param)\n if not libsbml_param.getConstant():\n non_constant_params.append(param)\n if len(non_constant_params) > 0:\n non_constant_params = \",\".join(non_constant_params)\n self.results.add_message(\n reaction_id, 1006, f\"Expecting these parameters to be constants: {non_constant_params}\")\n\n def _check_irreversibility(self, **kwargs):\n \"\"\"\n Checks if an irreversible reaction's kinetic law contains products.\n Code: 1010\n\n Args:\n reaction_id (str): The reaction's id'.\n is_reversible (bool): the reaction's reversibility\n species_in_kinetic_law: A list of species present in the rate law.\n product_list: A list of products for the reaction.\n\n Returns:\n An error message specifying the products found in the rate law of an irreversible reaction.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n is_reversible = kwargs[\"is_reversible\"]\n species_in_kinetic_law = kwargs[\"species_in_kinetic_law\"]\n product_list = kwargs[\"product_list\"]\n\n inconsistent_products = []\n if not is_reversible:\n for product in product_list:\n if product in species_in_kinetic_law:\n inconsistent_products.append(product)\n if len(inconsistent_products) > 0:\n inconsistent_products = \",\".join(inconsistent_products)\n self.results.add_message(\n reaction_id, 1010, f\"Irreversible reaction kinetic law contains products: {inconsistent_products}\")\n\n def _check_naming_conventions(self, **kwargs):\n \"\"\"\n Checks if certain parameters in the rate law follow the recommended naming convention (starting with 'k', 'K', or 'V').\n Code: 1020, 1021, 1022\n\n Args:\n reaction_id (str): The reaction's id'.\n\n Adds:\n A warning message to results specifying that certain parameters in the rate law are not following the recommended naming convention.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n parameters_in_kinetic_law = kwargs[\"parameters_in_kinetic_law\"]\n kinetics_sim = kwargs[\"kinetics_sim\"]\n ids_list = kwargs[\"ids_list\"]\n codes = kwargs[\"codes\"]\n\n naming_convention_warnings = {'k': [], 'K': [], 'V': []}\n if any(self.default_classifications[reaction_id][key] for key in NON_MM_KEYS):\n naming_convention_warnings['k'] = self._check_symbols_start_with(\n 'k', parameters_in_kinetic_law)\n elif self.default_classifications[reaction_id]['MM']:\n eq = self._numerator_denominator(kinetics_sim, ids_list)\n eq0 = [param for param in parameters_in_kinetic_law if param in eq[0]]\n eq1 = [param for param in parameters_in_kinetic_law if param in eq[1]]\n naming_convention_warnings['V'] = self._check_symbols_start_with(\n 'V', eq0)\n naming_convention_warnings['K'] = self._check_symbols_start_with(\n 'K', eq1)\n elif self.default_classifications[reaction_id]['MMcat']:\n eq = self._numerator_denominator(kinetics_sim, ids_list)\n eq0 = [param for param in parameters_in_kinetic_law if param in eq[0]]\n eq1 = [param for param in parameters_in_kinetic_law if param in eq[1]]\n naming_convention_warnings['K'] = self._check_symbols_start_with('K', eq0)\n naming_convention_warnings['K'] = self._check_symbols_start_with('K', eq1)\n elif self.default_classifications[reaction_id]['Hill']:\n eq = self._numerator_denominator(kinetics_sim, ids_list)\n eq0 = [param for param in parameters_in_kinetic_law if param in eq[0]]\n eq1 = [param for param in parameters_in_kinetic_law if param in eq[1]]\n naming_convention_warnings['K'] = self._check_symbols_start_with(\n 'K', eq1)\n\n if 1020 in codes and len(naming_convention_warnings['k']) > 0:\n naming_convention_warnings_k = \",\".join(\n naming_convention_warnings['k'])\n self.results.add_message(\n reaction_id, 1020, f\"We recommend that these parameters start with 'k': {naming_convention_warnings_k}\")\n if 1021 in codes and len(naming_convention_warnings['K']) > 0:\n naming_convention_warnings_K = \",\".join(\n naming_convention_warnings['K'])\n self.results.add_message(\n reaction_id, 1021, f\"We recommend that these parameters start with 'K': {naming_convention_warnings_K}\")\n if 1022 in codes and len(naming_convention_warnings['V']) > 0:\n naming_convention_warnings_V = \",\".join(\n naming_convention_warnings['V'])\n self.results.add_message(\n reaction_id, 1022, f\"We recommend that these parameters start with 'V': {naming_convention_warnings_V}\")\n\n def _check_symbols_start_with(self, start, symbols):\n ret = []\n for symbol in symbols:\n if not symbol.startswith(start):\n ret.append(symbol)\n return ret\n\n def _numerator_denominator(self, kinetics_sim, ids_list):\n \"\"\"\n Get the numerator and denominator of a \"fraction\" function.\n\n Parameters\n ---- \n kinetics_sim: string-simplified kinetics\n ids_list: list-id list including all the ids in kinetics, reactants and products\n\n Returns\n -------\n Type - the numerator and the denominator of the fraction\n \"\"\"\n\n strange_func = 0\n pre_symbols = ''\n for i in range(len(ids_list)):\n pre_symbols += ids_list[i]\n pre_symbols += ' '\n pre_symbols = pre_symbols[:-1] # remove the space at the end\n pre_symbols_comma = pre_symbols.replace(\" \", \",\")\n stmt = \"%s = sp.symbols('%s')\" % (pre_symbols_comma, pre_symbols)\n try: # sometimes there is \"invalid syntax error\"\n exec(stmt, globals())\n except:\n strange_func = 1\n\n try: # check if there is strange func (i.e. delay) in kinetic law;\n # sometimes ids_list is not enough for all the ids in kinetics\n eq_stat = \"kinetics_eq = \" + kinetics_sim\n exec(eq_stat, globals())\n except:\n strange_func = 1\n\n eq = ['', '']\n\n if strange_func == 0:\n try:\n numerator = str(kinetics_eq.as_numer_denom()[0])\n denominator = str(kinetics_eq.as_numer_denom()[1])\n eq[0] = numerator\n eq[1] = denominator\n except:\n pass\n\n return eq\n\n def _numerator_denominator_order_remained(self, kinetics, ids_list):\n # Split the fraction at the '/' character\n split_fraction = kinetics.split('/')\n\n # Check if there's a numerator and a denominator\n if len(split_fraction) != 2:\n return ['', '']\n\n # Return the numerator and the denominator as a tuple\n return split_fraction[0].strip(), split_fraction[1].strip()\n\n def _find_positions_in_rate_law(self, element_list, rate_law):\n largest_position = -1\n smallest_position = sys.maxsize\n prev_position = -1\n increasing_flag = True\n\n for element in element_list:\n pattern = re.compile(rf\"\\b{re.escape(element)}\\b\")\n match = pattern.search(rate_law)\n if match:\n index = match.start()\n largest_position = max(index, largest_position)\n smallest_position = min(index, smallest_position)\n if index < prev_position:\n increasing_flag = False\n prev_position = index\n return largest_position, smallest_position, increasing_flag\n\n def _check_product_of_terms_format(self, kinetics, compartment_in_kinetic_law, parameters_in_kinetic_law_only, sorted_species):\n comp_stats = self._find_positions_in_rate_law(\n compartment_in_kinetic_law, kinetics)\n param_stats = self._find_positions_in_rate_law(\n parameters_in_kinetic_law_only, kinetics)\n spec_stats = self._find_positions_in_rate_law(sorted_species, kinetics)\n is_formatted = (comp_stats[0] < param_stats[1] or param_stats[1] == sys.maxsize) and \\\n (param_stats[0] < spec_stats[1] or spec_stats[1] == sys.maxsize) and \\\n (comp_stats[0] < spec_stats[1]\n or spec_stats[1] == sys.maxsize)\n increasing_flag = comp_stats[2] and param_stats[2] and spec_stats[2]\n if is_formatted:\n return 0 if increasing_flag else 1\n return 2\n\n def _check_expression_format(self, kinetics, compartment_in_kinetic_law, parameters_in_kinetic_law_only, sorted_species):\n compartment_in_kinetic_law.sort()\n parameters_in_kinetic_law_only.sort()\n product_of_terms = re.split(r\"[+-]\", kinetics)\n ret = 0\n for term in product_of_terms:\n format_status = self._check_product_of_terms_format(\n term, compartment_in_kinetic_law, parameters_in_kinetic_law_only, sorted_species)\n if format_status > ret:\n ret = format_status\n return ret\n\n def _check_formatting_conventions(self, **kwargs):\n reaction_id = kwargs[\"reaction_id\"]\n compartment_in_kinetic_law = kwargs[\"compartment_in_kinetic_law\"]\n kinetics = kwargs[\"kinetics\"]\n ids_list = kwargs[\"ids_list\"]\n parameters_in_kinetic_law_only = kwargs[\"parameters_in_kinetic_law_only\"]\n codes = kwargs[\"codes\"]\n sorted_species = kwargs[\"sorted_species\"]\n\n flag = 0\n assert len(self.default_classifications[reaction_id]) > 0\n if any(self.default_classifications[reaction_id][key] for key in MM_KEYS):\n eq = self._numerator_denominator_order_remained(\n kinetics, ids_list) # _numerator_denominator not provided\n flag = self._check_expression_format(\n eq[0], compartment_in_kinetic_law, parameters_in_kinetic_law_only, sorted_species)\n flag += 3 * self._check_expression_format(\n eq[1], compartment_in_kinetic_law, parameters_in_kinetic_law_only, sorted_species)\n else:\n flag = self._check_expression_format(\n kinetics, compartment_in_kinetic_law, parameters_in_kinetic_law_only, sorted_species)\n if flag == 1 and 1030 in codes:\n self.results.add_message(\n reaction_id, 1030, f\"Elements of the same type are not ordered alphabetically\")\n if flag == 2 and 1031 in codes:\n self.results.add_message(\n reaction_id, 1031, f\"Formatting convention not followed (compartment before parameters before species)\")\n # TODO: currently the default classification does not classify these as MM, so these checks are not performed\n if flag == 3 and 1032 in codes:\n self.results.add_message(\n reaction_id, 1032, f\"Denominator not in alphabetical order\")\n if flag == 4 and 1033 in codes:\n self.results.add_message(\n reaction_id, 1033, f\"Numerator and denominator not in alphabetical order\")\n if flag == 5 and 1034 in codes:\n self.results.add_message(\n reaction_id, 1034, f\"Numerator convention not followed and denominator not in alphabetical order\")\n if flag == 6 and 1035 in codes:\n self.results.add_message(\n reaction_id, 1035, f\"Denominator convention not followed\")\n if flag == 7 and 1036 in codes:\n self.results.add_message(\n reaction_id, 1036, f\"Numerator not in alphabetical order and denominator convention not followed\")\n if flag == 8 and 1037 in codes:\n self.results.add_message(\n reaction_id, 1037, f\"Numerator and denominator convention not followed\")\n\n def _check_sboterm_annotations(self, **kwargs):\n \"\"\"\n Checks if the SBOTerm annotations for the rate law follow recommended SBO terms.\n Code: 1040, 1041, 1042, 1043, 1044\n\n Args:\n reaction_id (str): The reaction's id'.\n sbo_term (int): the sbo_term annotation for the kinetic law, -1 if not annotated\n\n Adds:\n A warning message to results specifying that the annotations for the rate law do not follow recommended SBO terms.\n \"\"\"\n reaction_id = kwargs[\"reaction_id\"]\n sbo_term = kwargs[\"sbo_term\"]\n codes = kwargs[\"codes\"]\n assert len(self.default_classifications) > 0\n flag = 0\n if sbo_term < 0:\n flag = 0\n elif any(self.default_classifications[reaction_id][key] for key in UNDR_KEYS):\n if sbo_term not in UNDR_SBOS:\n flag = 1\n elif any(self.default_classifications[reaction_id][key] for key in UNDR_A_KEYS):\n if sbo_term not in UNDR_A_SBOS:\n flag = 2\n elif any(self.default_classifications[reaction_id][key] for key in BIDR_ALL_KEYS):\n if sbo_term not in BI_SBOS:\n flag = 3\n elif self.default_classifications[reaction_id]['MM']:\n if sbo_term not in MM_SBOS:\n flag = 4\n elif any(self.default_classifications[reaction_id][key] for key in MM_CAT_KEYS):\n if sbo_term not in MM_CAT_SBOS:\n flag = 5\n elif self.default_classifications[reaction_id]['Hill']:\n if sbo_term not in HILL_SBOS:\n flag = 6\n if flag == 1 and 1040 in codes:\n self.results.add_message(\n reaction_id, 1040, f\"Uni-directional mass action annotation not following recommended SBO terms, we recommend annotations to be subclasses of: SBO_0000430, SBO_0000041\")\n elif flag == 2 and 1041 in codes:\n self.results.add_message(\n reaction_id, 1041, f\"Uni-Directional Mass Action with an Activator annotation not following recommended SBO terms, we recommend annotations to be subclasses of: SBO_0000041\")\n elif flag == 3 and 1042 in codes:\n self.results.add_message(\n reaction_id, 1042, f\"Bi-directional mass action (with an Activator) annotation not following recommended SBO terms, we recommend annotations to be subclasses of: SBO_0000042\")\n elif flag == 4 and 1043 in codes:\n self.results.add_message(\n reaction_id, 1043, f\"Michaelis-Menten kinetics without an explicit enzyme annotation not following recommended SBO terms, we recommend annotations to be subclasses of: SBO_0000028\")\n elif flag == 5 and 1044 in codes:\n self.results.add_message(\n reaction_id, 1044, f\"Michaelis-Menten kinetics with an explicit enzyme annotation not following recommended SBO terms, we recommend annotations to be subclasses of: SBO_0000028, SBO_0000430\")\n","repo_name":"sys-bio/ratesb_python","sub_path":"ratesb_python/common/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":36307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28395218401","text":"'''----------------------------------------------------------------------------\\\n| ||\\\\ //|| /|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\\ |\n| || \\\\ // || (o_ / | SUPPLEMENTARY FILE | |\n| || \\\\// || //\\/ | ---- | |\n| || \\/ || V_/_ | SETTINGS COMMANDS | |\n| || || |‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗/ |\n\\----------------------------------------------------------------------------'''\n\nimport discord\nfrom discord.ext import commands\nfrom datetime import datetime\n\nfrom foundationBotDatabaseStuff import update_setting\n\n# import logger\nfrom foundationBotLogger import *\nlogger = Logger()\n\nclass SettingsCommands(commands.Cog):\n def __init__(self, bot, conn, settings):\n self.bot = bot\n self.conn = conn\n self.settings = settings\n \n @commands.group()\n @commands.has_guild_permissions(administrator=True)\n async def set(self, ctx):\n if ctx.invoked_subcommand is None:\n await ctx.send('You need to provide a setting to set!')\n \n @set.command(description='Displays the Current Settings')\n async def check(self, ctx):\n embed = discord.Embed(\n title = 'Current Settings',\n colour = discord.Colour.dark_green()\n )\n settingsList = ('botActive\\n'\n 'guildID\\n'\n 'excludedRoles\\n'\n 'pinsChannel\\n'\n 'pinsRoles\\n'\n 'leaderboardEmoji\\n'\n 'leaderboardInterval\\n'\n 'leaderboardChannel\\n'\n 'screenshotChannel\\n'\n 'screenshotPostTime\\n'\n 'messagesPostTime\\n'\n 'moddingChannel\\n'\n 'rankingChannel\\n'\n 'rankingMessage\\n\\n'\n 'labourEmoji\\n'\n 'clergyEmoji\\n'\n 'kingdomEmoji\\n'\n 'defaultRole\\n'\n 'labourRole1\\n'\n 'labourRole2\\n'\n 'labourRole3\\n'\n 'labourRole4\\n'\n 'clergyRole1\\n'\n 'clergyRole2\\n'\n 'clergyRole3\\n'\n 'clergyRole4\\n'\n 'kingdomRole1\\n'\n 'kingdomRole2\\n'\n 'kingdomRole3\\n'\n 'kingdomRole4\\n'\n 'highestRole\\n'\n 'expLevel1\\n'\n 'expLevel2\\n'\n 'expLevel3\\n'\n 'expLevel4\\n'\n 'expLevelH\\n'\n )\n \n if self.settings.guildID != None:\n guildIDstr = ctx.bot.get_guild(self.settings.guildID).name\n else:\n guildIDstr = 'Not Set'\n if self.settings.excludedRoles:\n excludedRolesstr = ''\n for i,role in enumerate(self.settings.excludedRoles):\n if i == 0:\n excludedRolesstr += ctx.guild.get_role(role).mention\n else:\n excludedRolesstr += ', ' + ctx.guild.get_role(role).mention\n else:\n excludedRolesstr = 'Not Set'\n if self.settings.pinsChannel != None:\n pinsChannelstr = self.bot.get_channel(self.settings.pinsChannel).mention\n else:\n pinsChannelstr = 'Not Set'\n if self.settings.pinsRoles:\n pinsRolesstr = ''\n for i,role in enumerate(self.settings.pinsRoles):\n if i == 0:\n pinsRolesstr += ctx.guild.get_role(role).mention\n else:\n pinsRolesstr += ', ' + ctx.guild.get_role(role).mention\n else:\n pinsRolesstr = 'Not Set'\n if self.settings.leaderboardEmoji != None:\n leaderboardEmojistr = str(self.bot.get_emoji(self.settings.leaderboardEmoji))\n else:\n leaderboardEmojistr = 'Not Set'\n if self.settings.leaderboardInterval != None:\n leaderboardIntervalstr = str(self.settings.leaderboardInterval)\n else:\n leaderboardIntervalstr = 'Not Set'\n if self.settings.leaderboardChannel != None:\n leaderboardChannelstr = self.bot.get_channel(self.settings.leaderboardChannel).mention\n else:\n leaderboardChannelstr = 'Not Set'\n if self.settings.screenshotChannel != None:\n screenshotChannelstr = self.bot.get_channel(self.settings.screenshotChannel).mention\n else:\n screenshotChannelstr = 'Not Set'\n if self.settings.screenshotPostTime != None:\n date = datetime.fromtimestamp(self.settings.screenshotPostTime)\n screenshotPostTimestr = str(date.strftime('%d/%m/%Y %H:%M'))\n else:\n screenshotPostTimestr = 'Not Set'\n if self.settings.messagesPostTime != None:\n date = datetime.fromtimestamp(self.settings.messagesPostTime)\n messagesPostTimestr = str(date.strftime('%d/%m/%Y %H:%M'))\n else:\n messagesPostTimestr = 'Not Set'\n if self.settings.moddingChannel != None:\n moddingChannelstr = self.bot.get_channel(self.settings.moddingChannel).mention\n else:\n moddingChannelstr = 'Not Set'\n if self.settings.rankingChannel != None:\n rankingChannelstr = self.bot.get_channel(self.settings.rankingChannel).mention\n else:\n rankingChannelstr = 'Not Set'\n if self.settings.rankingMessage != None:\n rankingMessage = await self.bot.get_channel(self.settings.rankingChannel).fetch_message(self.settings.rankingMessage)\n rankingMessagestr = rankingMessage.jump_url\n else:\n rankingMessagestr = 'Not Set\\n'\n if self.settings.labourEmoji != None:\n labourEmojistr = str(self.bot.get_emoji(self.settings.labourEmoji))\n else:\n labourEmojistr = 'Not Set'\n if self.settings.clergyEmoji != None:\n clergyEmojistr = str(self.bot.get_emoji(self.settings.clergyEmoji))\n else:\n clergyEmojistr = 'Not Set'\n if self.settings.kingdomEmoji != None:\n kingdomEmojistr = str(self.bot.get_emoji(self.settings.kingdomEmoji))\n else:\n kingdomEmojistr = 'Not Set'\n if self.settings.defaultRole != None:\n defaultRolestr = ctx.guild.get_role(self.settings.defaultRole).mention\n else:\n defaultRolestr = 'Not Set'\n if self.settings.labourRole1 != None:\n labourRole1str = ctx.guild.get_role(self.settings.labourRole1).mention\n else:\n labourRole1str = 'Not Set'\n if self.settings.labourRole2 != None:\n labourRole2str = ctx.guild.get_role(self.settings.labourRole2).mention\n else:\n labourRole2str = 'Not Set'\n if self.settings.labourRole3 != None:\n labourRole3str = ctx.guild.get_role(self.settings.labourRole3).mention\n else:\n labourRole3str = 'Not Set'\n if self.settings.labourRole4 != None:\n labourRole4str = ctx.guild.get_role(self.settings.labourRole4).mention\n else:\n labourRole4str = 'Not Set'\n if self.settings.clergyRole1 != None:\n clergyRole1str = ctx.guild.get_role(self.settings.clergyRole1).mention\n else:\n clergyRole1str = 'Not Set'\n if self.settings.clergyRole2 != None:\n clergyRole2str = ctx.guild.get_role(self.settings.clergyRole2).mention\n else:\n clergyRole2str = 'Not Set'\n if self.settings.clergyRole3 != None:\n clergyRole3str = ctx.guild.get_role(self.settings.clergyRole3).mention\n else:\n clergyRole3str = 'Not Set'\n if self.settings.clergyRole4 != None:\n clergyRole4str = ctx.guild.get_role(self.settings.clergyRole4).mention\n else:\n clergyRole4str = 'Not Set'\n if self.settings.kingdomRole1 != None:\n kingdomRole1str = ctx.guild.get_role(self.settings.kingdomRole1).mention\n else:\n kingdomRole1str = 'Not Set'\n if self.settings.kingdomRole2 != None:\n kingdomRole2str = ctx.guild.get_role(self.settings.kingdomRole2).mention\n else:\n kingdomRole2str = 'Not Set'\n if self.settings.kingdomRole3 != None:\n kingdomRole3str = ctx.guild.get_role(self.settings.kingdomRole3).mention\n else:\n kingdomRole3str = 'Not Set'\n if self.settings.kingdomRole4 != None:\n kingdomRole4str = ctx.guild.get_role(self.settings.kingdomRole4).mention\n else:\n kingdomRole4str = 'Not Set'\n if self.settings.highestRole != None:\n highestRolestr = ctx.guild.get_role(self.settings.highestRole).mention\n else:\n highestRolestr = 'Not Set'\n if self.settings.expLevel1 != None:\n expLevel1str = str(self.settings.expLevel1)\n else:\n expLevel1str = 'Not Set'\n if self.settings.expLevel2 != None:\n expLevel2str = str(self.settings.expLevel2)\n else:\n expLevel2str = 'Not Set'\n if self.settings.expLevel3 != None:\n expLevel3str = str(self.settings.expLevel3)\n else:\n expLevel3str = 'Not Set'\n if self.settings.expLevel4 != None:\n expLevel4str = str(self.settings.expLevel4)\n else:\n expLevel4str = 'Not Set'\n if self.settings.expLevelH != None:\n expLevelHstr = str(self.settings.expLevelH)\n else:\n expLevelHstr = 'Not Set'\n \n values = (str(self.settings.botActive) + '\\n' +\n guildIDstr + '\\n' +\n excludedRolesstr + '\\n' +\n pinsChannelstr + '\\n' +\n pinsRolesstr + '\\n' +\n leaderboardEmojistr + '\\n' +\n leaderboardIntervalstr + '\\n' +\n leaderboardChannelstr + '\\n' +\n screenshotChannelstr + '\\n' +\n screenshotPostTimestr + '\\n' +\n messagesPostTimestr + '\\n' +\n moddingChannelstr + '\\n' +\n rankingChannelstr + '\\n' +\n rankingMessagestr + '\\n' +\n labourEmojistr + '\\n' +\n clergyEmojistr + '\\n' +\n kingdomEmojistr + '\\n' +\n defaultRolestr + '\\n' +\n labourRole1str + '\\n' +\n labourRole2str + '\\n' +\n labourRole3str + '\\n' +\n labourRole4str + '\\n' +\n clergyRole1str + '\\n' +\n clergyRole2str + '\\n' +\n clergyRole3str + '\\n' +\n clergyRole4str + '\\n' +\n kingdomRole1str + '\\n' +\n kingdomRole2str + '\\n' +\n kingdomRole3str + '\\n' +\n kingdomRole4str + '\\n' +\n highestRolestr + '\\n' +\n expLevel1str + '\\n' +\n expLevel2str + '\\n' +\n expLevel3str + '\\n' +\n expLevel4str + '\\n' +\n expLevelHstr + '\\n'\n )\n embed.add_field(name='Setting' , value=settingsList, inline=True)\n embed.add_field(name='Value', value=values, inline=True)\n await ctx.send(embed=embed)\n \n @set.command(description='Sets the Bot Status')\n async def botActive(self, ctx, status: str):\n status = status.lower()\n if status == 'on' or status == 'true' or status == 'yes':\n update_setting(self.conn, ('True','botActive'))\n self.settings.botActive = True\n await ctx.send('botActive set to: `True`')\n elif status == 'off' or status == 'false' or status == 'no':\n update_setting(self.conn, ('False','botActive'))\n self.settings.botActive = False\n await ctx.send('botActive set to: `False`')\n \n @set.command(description='Sets the Guild ID')\n async def guildID(self, ctx):\n update_setting(self.conn, (str(ctx.guild.id),'guildID'))\n self.settings.guildID = ctx.guild.id\n await ctx.send('guildID set to: ' + ctx.bot.get_guild(self.settings.guildID).name)\n \n @set.command(description='Sets the Roles to exclude from the Leaderboards')\n async def excludedRoles(self, ctx, *, roles: str):\n roles = roles.split(',')\n rolesList = [0]*len(roles)\n rolesmsg = ''\n savestring = ''\n for i,role in enumerate(roles):\n try:\n role = int(role)\n if ctx.guild.get_role(role) != None:\n rolesList[i] = role\n if i == 0:\n rolesmsg += ctx.guild.get_role(role).mention\n savestring += str(role)\n else:\n rolesmsg += ', ' + ctx.guild.get_role(role).mention\n savestring += ',' + str(role)\n else:\n await ctx.send('At least one of the provided role IDs is invalid!')\n return\n except ValueError as e:\n await ctx.send('At least one of the provided role IDs is invalid!')\n return\n update_setting(self.conn, (savestring,'excludedRoles'))\n self.settings.excludedRoles = rolesList\n await ctx.send('excludedRoles set to: ' + rolesmsg)\n \n @set.command(description='Sets the Channel for the Pinning System')\n async def pinsChannel(self, ctx, channel: str):\n try:\n if self.bot.get_channel(int(channel)) != None:\n update_setting(self.conn, (channel,'pinsChannel'))\n self.settings.pinsChannel = int(channel)\n await ctx.send('pinsChannel set to: ' + self.bot.get_channel(int(channel)).mention)\n else:\n await ctx.send('No channel with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The channel ID should only consist of an integer number!')\n \n @set.command(description='Sets the Roles to activate the Pinning System')\n async def pinsRoles(self, ctx, *, roles: str):\n roles = roles.split(',')\n rolesList = [0]*len(roles)\n rolesmsg = ''\n savestring = ''\n for i,role in enumerate(roles):\n try:\n role = int(role)\n if ctx.guild.get_role(role) != None:\n rolesList[i] = role\n if i == 0:\n rolesmsg += ctx.guild.get_role(role).mention\n savestring += str(role)\n else:\n rolesmsg += ', ' + ctx.guild.get_role(role).mention\n savestring += ',' + str(role)\n else:\n await ctx.send('At least one of the provided role IDs is invalid!')\n return\n except ValueError as e:\n await ctx.send('At least one of the provided role IDs is invalid!')\n return\n update_setting(self.conn, (savestring,'pinsRoles'))\n self.settings.pinsRoles = rolesList\n await ctx.send('pinsRoles set to: ' + rolesmsg)\n \n @set.command(description='Sets the Emoji to activate the Screenshot Leaderboard')\n async def leaderboardEmoji(self, ctx, emoji: str):\n try:\n if self.bot.get_emoji(int(emoji)) != None:\n update_setting(self.conn, (emoji,'leaderboardEmoji'))\n self.settings.leaderboardEmoji = int(emoji)\n await ctx.send('leaderboardEmoji set to: ' + str(self.bot.get_emoji(int(emoji))))\n else:\n await ctx.send('No emoji with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The emoji ID should only consist of an integer number!')\n \n @set.command(description='Sets the Emoji to activate the Screenshot Leaderboard')\n async def leaderboardInterval(self, ctx, days: str):\n try:\n self.settings.leaderboardInterval = int(days)\n update_setting(self.conn, (days,'leaderboardInterval'))\n await ctx.send('leaderboardInterval set to: ' + days + ' days')\n except ValueError as e:\n await ctx.send('Invalid Number of Days! The number of days should only consist of an integer number!')\n \n @set.command(description='Sets the Channel to post the Leaderboards')\n async def leaderboardChannel(self, ctx, channel: str):\n try:\n if self.bot.get_channel(int(channel)) != None:\n update_setting(self.conn, (channel,'leaderboardChannel'))\n self.settings.leaderboardChannel = int(channel)\n await ctx.send('leaderboardChannel set to: ' + self.bot.get_channel(int(channel)).mention)\n else:\n await ctx.send('No channel with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The channel ID should only consist of an integer number!')\n \n @set.command(description='Sets the Channel for the Screenshot Leaderboard')\n async def screenshotChannel(self, ctx, channel: str):\n try:\n if self.bot.get_channel(int(channel)) != None:\n update_setting(self.conn, (channel,'screenshotChannel'))\n self.settings.screenshotChannel = int(channel)\n await ctx.send('screenshotChannel set to: ' + self.bot.get_channel(int(channel)).mention)\n else:\n await ctx.send('No channel with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The channel ID should only consist of an integer number!')\n \n @set.command(description='Sets the Time for the next Screenshot Leaderboard Post')\n async def screenshotPostTime(self, ctx, *, dateTime: str):\n try:\n date = datetime.strptime(dateTime + ' UTC+0000', '%d/%m/%Y %H:%M %Z%z')\n timeStamp = date.timestamp()\n update_setting(self.conn, (timeStamp,'screenshotPostTime'))\n self.settings.screenshotPostTime = int(timeStamp)\n await ctx.send('screenshotPostTime set to: ' + dateTime + ' UTC. The screenshot leaderboard will be posted according to the leaderboardInterval starting then.')\n except ValueError as e:\n await ctx.send('Invalid dateTime! The dateTime format should be input as: DD/MM/YYYY HH:mm!')\n \n @set.command(description='Sets the Time for the next Messages Leaderboard Post')\n async def messagesPostTime(self, ctx, *, dateTime: str):\n try:\n date = datetime.strptime(dateTime + ' UTC+0000', '%d/%m/%Y %H:%M %Z%z')\n timeStamp = date.timestamp()\n update_setting(self.conn, (timeStamp,'messagesPostTime'))\n self.settings.messagesPostTime = int(timeStamp)\n await ctx.send('messagesPostTime set to: ' + dateTime + ' UTC. The messages leaderboard will be posted according to the leaderboardInterval starting then.')\n except ValueError as e:\n await ctx.send('Invalid dateTime! The dateTime format should be input as: DD/MM/YYYY HH:mm!')\n \n @set.command(description='Sets the Channel for the Modding Help Command')\n async def moddingChannel(self, ctx, channel: str):\n try:\n if self.bot.get_channel(int(channel)) != None:\n update_setting(self.conn, (channel,'moddingChannel'))\n self.settings.moddingChannel = int(channel)\n await ctx.send('moddingChannel set to: ' + self.bot.get_channel(int(channel)).mention)\n else:\n await ctx.send('No channel with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The channel ID should only consist of an integer number!')\n \n @set.command(description='Initialises Ranking Emojis on the Ranking Message')\n async def ranking(self, ctx):\n if self.settings.rankingChannel != None \\\n and self.settings.rankingMessage != None \\\n and self.settings.labourEmoji != None \\\n and self.settings.clergyEmoji != None \\\n and self.settings.kingdomEmoji != None:\n channel = self.bot.get_channel(self.settings.rankingChannel)\n message = await channel.fetch_message(self.settings.rankingMessage)\n await message.add_reaction(discord.utils.get(channel.guild.emojis, id=self.settings.labourEmoji))\n await message.add_reaction(discord.utils.get(channel.guild.emojis, id=self.settings.clergyEmoji))\n await message.add_reaction(discord.utils.get(channel.guild.emojis, id=self.settings.kingdomEmoji))\n await message.add_reaction('♂')\n await message.add_reaction('♀')\n else:\n await ctx.send('At least one of the Required Parameters for the Ranking System has not been set, consult `/set check`!')\n \n @set.command(description='Sets the Channel for the Ranking Message')\n async def rankingChannel(self, ctx, channel: str):\n try:\n if self.bot.get_channel(int(channel)) != None:\n update_setting(self.conn, (channel,'rankingChannel'))\n self.settings.rankingChannel = int(channel)\n await ctx.send('rankingChannel set to: ' + self.bot.get_channel(int(channel)).mention)\n if self.settings.rankingMessage != None:\n update_setting(self.conn, (None,'rankingMessage'))\n self.settings.rankingMessage = None\n await ctx.send('The Ranking Channel was changed and thus the Ranking Message has been reset!\\nUse `/set rankingMessage MessageID` to set it again!')\n else:\n await ctx.send('No channel with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The channel ID should only consist of an integer number!')\n \n @set.command(description='Sets the Message for the Ranking Reactions')\n async def rankingMessage(self, ctx, message: str):\n try:\n actualMessage = await self.bot.get_channel(self.settings.rankingChannel).fetch_message(int(message))\n self.settings.rankingMessage = int(message)\n update_setting(self.conn, (message,'rankingMessage'))\n await ctx.send('rankingMessage set to: ' + actualMessage.jump_url)\n except ValueError as e:\n await ctx.send('Invalid ID! The message ID should only consist of an integer number!')\n \n @rankingMessage.error\n async def rankingMessage_error(self, ctx, error):\n if isinstance(error, commands.CommandInvokeError):\n if isinstance(error.original, discord.errors.NotFound):\n await ctx.send('No message with the provided ID was found! Make sure you have set the correct Channel with `/set rankingChannel`!')\n \n @set.command(description='Sets the Emoji for the Labour Ranking Tree')\n async def labourEmoji(self, ctx, emoji: str):\n try:\n if self.bot.get_emoji(int(emoji)) != None:\n update_setting(self.conn, (emoji,'labourEmoji'))\n self.settings.labourEmoji = int(emoji)\n await ctx.send('labourEmoji set to: ' + str(self.bot.get_emoji(int(emoji))))\n else:\n await ctx.send('No emoji with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The emoji ID should only consist of an integer number!')\n \n @set.command(description='Sets the Emoji for the Clergy Ranking Tree')\n async def clergyEmoji(self, ctx, emoji: str):\n try:\n if self.bot.get_emoji(int(emoji)) != None:\n update_setting(self.conn, (emoji,'clergyEmoji'))\n self.settings.clergyEmoji = int(emoji)\n await ctx.send('clergyEmoji set to: ' + str(self.bot.get_emoji(int(emoji))))\n else:\n await ctx.send('No emoji with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The emoji ID should only consist of an integer number!')\n \n @set.command(description='Sets the Emoji for the Kingdom Ranking Tree')\n async def kingdomEmoji(self, ctx, emoji: str):\n try:\n if self.bot.get_emoji(int(emoji)) != None:\n update_setting(self.conn, (emoji,'kingdomEmoji'))\n self.settings.kingdomEmoji = int(emoji)\n await ctx.send('kingdomEmoji set to: ' + str(self.bot.get_emoji(int(emoji))))\n else:\n await ctx.send('No emoji with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The emoji ID should only consist of an integer number!')\n \n @set.command(description='Sets the starting Role for the Ranking System')\n async def defaultRole(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'defaultRole'))\n self.settings.defaultRole = int(role)\n await ctx.send('defaultRole set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 1 Role for the Labour Ranking Tree')\n async def labourRole1(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'labourRole1'))\n self.settings.labourRole1 = int(role)\n await ctx.send('labourRole1 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 2 Role for the Labour Ranking Tree')\n async def labourRole2(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'labourRole2'))\n self.settings.labourRole2 = int(role)\n await ctx.send('labourRole2 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 3 Role for the Labour Ranking Tree')\n async def labourRole3(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'labourRole3'))\n self.settings.labourRole3 = int(role)\n await ctx.send('labourRole3 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 4 Role for the Labour Ranking Tree')\n async def labourRole4(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'labourRole4'))\n self.settings.labourRole4 = int(role)\n await ctx.send('labourRole4 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 1 Role for the Clergy Ranking Tree')\n async def clergyRole1(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'clergyRole1'))\n self.settings.clergyRole1 = int(role)\n await ctx.send('clergyRole1 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 2 Role for the Clergy Ranking Tree')\n async def clergyRole2(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'clergyRole2'))\n self.settings.clergyRole2 = int(role)\n await ctx.send('clergyRole2 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 3 Role for the Clergy Ranking Tree')\n async def clergyRole3(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'clergyRole3'))\n self.settings.clergyRole3 = int(role)\n await ctx.send('clergyRole3 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 4 Role for the Clergy Ranking Tree')\n async def clergyRole4(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'clergyRole4'))\n self.settings.clergyRole4 = int(role)\n await ctx.send('clergyRole4 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 1 Role for the Kingdom Ranking Tree')\n async def kingdomRole1(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'kingdomRole1'))\n self.settings.kingdomRole1 = int(role)\n await ctx.send('kingdomRole1 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 2 Role for the Kingdom Ranking Tree')\n async def kingdomRole2(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'kingdomRole2'))\n self.settings.kingdomRole2 = int(role)\n await ctx.send('kingdomRole2 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 3 Role for the Kingdom Ranking Tree')\n async def kingdomRole3(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'kingdomRole3'))\n self.settings.kingdomRole3 = int(role)\n await ctx.send('kingdomRole3 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the level 4 Role for the Kingdom Ranking Tree')\n async def kingdomRole4(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'kingdomRole4'))\n self.settings.kingdomRole4 = int(role)\n await ctx.send('kingdomRole4 set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the Highest Role all Ranking Trees lead to')\n async def highestRole(self, ctx, role: str):\n try:\n if ctx.guild.get_role(int(role)) != None:\n update_setting(self.conn, (role,'highestRole'))\n self.settings.highestRole = int(role)\n await ctx.send('highestRole set to: ' + ctx.guild.get_role(int(role)).mention)\n else:\n await ctx.send('No role with the provided ID was found!')\n except ValueError as e:\n await ctx.send('Invalid ID! The role ID should only consist of an integer number!')\n \n @set.command(description='Sets the Experience Required for Level 1')\n async def expLevel1(self, ctx, exp: str):\n try:\n self.settings.expLevel1 = int(exp)\n update_setting(self.conn, (exp,'expLevel1'))\n await ctx.send('expLevel1 set to: ' + exp + ' messages')\n except ValueError as e:\n await ctx.send('Invalid Amount of Experience! The experience amount should only consist of an integer number!')\n \n @set.command(description='Sets the Experience Required for Level 2')\n async def expLevel2(self, ctx, exp: str):\n try:\n self.settings.expLevel2 = int(exp)\n update_setting(self.conn, (exp,'expLevel2'))\n await ctx.send('expLevel2 set to: ' + exp + ' messages')\n except ValueError as e:\n await ctx.send('Invalid Amount of Experience! The experience amount should only consist of an integer number!')\n \n @set.command(description='Sets the Experience Required for Level 3')\n async def expLevel3(self, ctx, exp: str):\n try:\n self.settings.expLevel3 = int(exp)\n update_setting(self.conn, (exp,'expLevel3'))\n await ctx.send('expLevel3 set to: ' + exp + ' messages')\n except ValueError as e:\n await ctx.send('Invalid Amount of Experience! The experience amount should only consist of an integer number!')\n \n @set.command(description='Sets the Experience Required for Level 4')\n async def expLevel4(self, ctx, exp: str):\n try:\n self.settings.expLevel4 = int(exp)\n update_setting(self.conn, (exp,'expLevel4'))\n await ctx.send('expLevel4 set to: ' + exp + ' messages')\n except ValueError as e:\n await ctx.send('Invalid Amount of Experience! The experience amount should only consist of an integer number!')\n \n @set.command(description='Sets the Experience Required for the Highest Level')\n async def expLevelH(self, ctx, exp: str):\n try:\n self.settings.expLevelH = int(exp)\n update_setting(self.conn, (exp,'expLevelH'))\n await ctx.send('expLevelH set to: ' + exp + ' messages')\n except ValueError as e:\n await ctx.send('Invalid Amount of Experience! The experience amount should only consist of an integer number!')\n \n @set.command(aliases=['commands'], description='Displays this help message')\n async def help(self, ctx):\n helpMessage1 = '```Available Settings Commands\\n\\n'\n helpMessage2 = '```'\n settingsCog = self.bot.get_cog('SettingsCommands')\n maxLength = 0\n for command in settingsCog.walk_commands():\n length = 0\n if len(command.aliases) > 0:\n for alias in command.aliases:\n length += len(alias) + 7\n length += len(command.name)\n else:\n length = len(command.name)\n if length > maxLength:\n maxLength = length\n \n settingsCommands = []\n for command in settingsCog.walk_commands():\n settingsCommands.append(command)\n settingsCommands.pop(0)\n settingsCommands.sort(key=lambda command: command.name)\n \n for i,command in enumerate(settingsCommands):\n if i < len(settingsCommands)/2:\n spaces = ''\n length = 0\n if len(command.aliases) > 0:\n aliasStr = ''\n for alias in command.aliases:\n length += len(alias) + 7\n aliasStr += ', /set ' + alias\n length += len(command.name)\n for _ in range(length,maxLength + 4):\n spaces += ' '\n helpMessage1 += '/set ' + command.name + aliasStr + spaces + command.description + '\\n'\n else:\n length = len(command.name)\n for _ in range(length,maxLength + 4):\n spaces += ' '\n helpMessage1 += '/set ' + command.name + spaces + command.description + '\\n'\n else:\n spaces = ''\n length = 0\n if len(command.aliases) > 0:\n aliasStr = ''\n for alias in command.aliases:\n length += len(alias) + 7\n aliasStr += ', /set ' + alias\n length += len(command.name)\n for _ in range(length,maxLength + 4):\n spaces += ' '\n helpMessage2 += '/set ' + command.name + aliasStr + spaces + command.description + '\\n'\n else:\n length = len(command.name)\n for _ in range(length,maxLength + 4):\n spaces += ' '\n helpMessage2 += '/set ' + command.name + spaces + command.description + '\\n'\n \n helpMessage1 += '```'\n helpMessage2 += '```'\n await ctx.send(helpMessage1)\n await ctx.send(helpMessage2)\n","repo_name":"Minotorious/FoundationBot","sub_path":"foundationBotSettingsCommands.py","file_name":"foundationBotSettingsCommands.py","file_ext":"py","file_size_in_byte":39397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30513488332","text":"_base_ = ['slowfast_r50_8xb8-8x8x1-256e_kinetics400-rgb.py']\n\nmodel = dict(backbone=dict(slow_pathway=dict(lateral_norm=True)))\n\nparam_scheduler = [\n dict(\n type='LinearLR',\n start_factor=0.1,\n by_epoch=True,\n begin=0,\n end=34,\n convert_to_iter_based=True),\n dict(\n type='MultiStepLR',\n begin=0,\n end=256,\n by_epoch=True,\n milestones=[94, 154, 196],\n gamma=0.1)\n]\n","repo_name":"open-mmlab/mmaction2","sub_path":"configs/recognition/slowfast/slowfast_r50_8xb8-8x8x1-steplr-256e_kinetics400-rgb.py","file_name":"slowfast_r50_8xb8-8x8x1-steplr-256e_kinetics400-rgb.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":3560,"dataset":"github-code","pt":"3"}
+{"seq_id":"4281660193","text":"class InvalidInputException(Exception):\n def __str__(self):\n return \"Invalid Input given.\"\n\n\ndef numShortestPaths(g, start, end):\n \"\"\"graph, start node, end node -> int\n Purpose: find the number of shortest paths between two nodes in a graph\n Raises: raise InvalidInputException if an input is None, or \n if start or end are not in g\"\"\"\n shortestPath = []\n found = False\n queue = []\n decorate = {}\n\n # add start node to queue\n queue.append(start)\n # iterate on queue and decorate neighbors that have not been decorated\n while len(queue) != 0 and not found:\n vertex = queue.pop(0)\n # get to last node, and trace back to first node\n if vertex is end:\n found = True\n #count paths\n while vertex is not start:\n shortestPath.insert(0, vertex)\n vertex = decorate[vertex]\n shortestPath.insert(0, start)\n\n for edge in g.incidentEdges(vertex):\n nextVertex = g.opposite(vertex, edge)\n if nextVertex not in decorate:\n decorate[nextVertex] = [vertex]\n queue.append(nextVertex)\n else:\n decorate[nextVertex].append(vertex)\n\n # or else return empty list\n return shortestPath\n","repo_name":"AT1924/Homework","sub_path":"hw9/numShortestPaths.py","file_name":"numShortestPaths.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36524834017","text":"import numpy as np\nfrom sympy import *\nfrom sympy import Symbol, Derivative, solve\nfrom scipy.interpolate import InterpolatedUnivariateSpline\n\n\ndef inver(s):\n return (-(1250*s - 81*((10000*s)/81 + 4)**(1/2) + 162)/(1250*s))**(1/2)/2 + 1/2\n\ndef f(s):\n return 0.1296*(s**2/(s**2+(1-s)**2))\n\ndef df(s):\n return 0.1296*(-2*(s-1)*s/(2*s**2-2*s+1)**2);\n\ndef BL_exact(S0,x, fi, A, Swr, Sor, ftime):\n\n SL = 1 - Sor;\n SR = 0 + Swr;\n inf_point=0.5;\n St = 0.7071;\n\n tstep = 0.2;\n S = S0;\n t = ftime;\n for i in range(len(x)-1):\n if SRpos:\n S[i]=S[i+1];\n\n\n elif inf_point<=SR and SR(x[i]/t):\n S[i]=inver(x[i]/t)\n elif ss<(x[i]/t):\n S[i]=S[i+1]\n\n return S\n","repo_name":"DudaGalindo/compositional_adm","sub_path":"case_plots/BL_exact_Gustavo.py","file_name":"BL_exact_Gustavo.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"857978922","text":"from django.shortcuts import render\nfrom .models import Order, Product, Client\nfrom datetime import date\n\n\ndef get_orders(request):\n orders = Order.objects.all()\n context = {\"orders\": orders}\n return render(request, \"hw3/orders.html\", context)\n\n\ndef get_order(request, order_id):\n order = Order.objects.get(pk=order_id)\n products = Product.objects.filter(order=order)\n # products = Product.objects.select_related()\n context = {\n 'order': order,\n 'products': products,\n }\n return render(request, \"hw3/order.html\", context)\n\n\ndef get_order_gt(request, delta):\n order_list = []\n orders = Order.objects.all()\n corrent_date = date.today()\n\n for order in orders:\n res_delta = (corrent_date - order.date_order).days\n if res_delta > delta:\n order_list.append(order)\n context = {\n 'delta': delta,\n 'orders': order_list,\n }\n return render(request, \"hw3/delta.html\", context)\n\n\ndef get_order_sort(request):\n order_list_sort = {}\n orders = Order.objects.all()\n corrent_date = date.today()\n\n for order in orders:\n res_delta = (corrent_date - order.date_order).days\n order_list_sort.setdefault(order, res_delta)\n print(order_list_sort)\n context = {\n 'orders': order_list_sort,\n }\n return render(request, \"hw3/delta_sort.html\", context)\n","repo_name":"ArhipovVladimir/Django","sub_path":"Seminar1/hw3/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29265691551","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\na = np.array([[8,9,20], [10,31,22]])\nb = np.array([[1,2,3], [4,5,6]])\nprint(a-b)\n\n\n# In[5]:\n\n\ns=np.array([ [1,2,3], [4,5,6] ])\n\nprint(s.shape)\n\n\n# In[6]:\n\n\nimport numpy as np\nb = np.array([[1,2], [3,4]])\nprint(b.transpose())\n\n\n# In[7]:\n\n\n4\nimport numpy as np\nb = np.array([[1,2], [3,4]])\nprint(np.sum (b, axis = 1))\n\n\n# In[10]:\n\n\n1\ns = 'Sheher mein'\na = 'aeiouAEIOU'\nfor i in range(len(s)):\n\n if(s.index(s[i])%2 == 0): \n print(i)\n\n if(s[i] in a):\n\n s = s.replace(s[i], '_')\n\nprint(s)\n\n\n# In[11]:\n\n\n123\ns = 'The Joy of Computing'\nprint(s[3:12])\n\n\n# In[15]:\n\n\n1\n2\na = ['', 'h', 'e', 'l','','l']\nprint('.'.join(a))\n\n\n# In[17]:\n\n\ns = 'Hello Everyone' \nprint(s.lower())\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Chirayu2727/NPTEL--THE-JOY-OF-COMPUTING-OF-PYTHON","sub_path":"_ Assignment 10 .py","file_name":"_ Assignment 10 .py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18614418661","text":"import asyncio\n\nfrom aiohttp.web import Application\nfrom aiohttp_json_rpc import JsonRpc\n\nimport logging\n\nfrom .utils import TYPE_CHECKING, NewType\n\nif TYPE_CHECKING:\n from .bot import Red\n\nlog = logging.getLogger('red.rpc')\nJsonSerializable = NewType('JsonSerializable', dict)\n\n_rpc = JsonRpc(logger=log)\n\n_rpc_server = None # type: asyncio.AbstractServer\n\n\nasync def initialize(bot: \"Red\"):\n global _rpc_server\n\n app = Application(loop=bot.loop)\n app.router.add_route('*', '/rpc', _rpc)\n\n handler = app.make_handler()\n\n _rpc_server = await bot.loop.create_server(handler, '127.0.0.1', 6133)\n\n log.debug('Created RPC _rpc_server listener.')\n\n\ndef add_topic(topic_name: str):\n \"\"\"\n Adds a topic for clients to listen to.\n\n Parameters\n ----------\n topic_name\n \"\"\"\n _rpc.add_topics(topic_name)\n\n\ndef notify(topic_name: str, data: JsonSerializable):\n \"\"\"\n Publishes a notification for the given topic name to all listening clients.\n\n data MUST be json serializable.\n\n note::\n\n This method will fail silently.\n\n Parameters\n ----------\n topic_name\n data\n \"\"\"\n _rpc.notify(topic_name, data)\n\n\ndef add_method(prefix, method):\n \"\"\"\n Makes a method available to RPC clients. The name given to clients will be as\n follows::\n\n \"{}__{}\".format(prefix, method.__name__)\n\n note::\n\n This method will fail silently.\n\n Parameters\n ----------\n prefix\n method\n MUST BE A COROUTINE OR OBJECT.\n \"\"\"\n _rpc.add_methods(\n ('', method),\n prefix=prefix\n )\n\n\ndef clean_up():\n if _rpc_server is not None:\n _rpc_server.close()\n","repo_name":"ATeddyBear/Niddbot","sub_path":"redbot/core/rpc.py","file_name":"rpc.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"36055676500","text":"import cv2\nimport urllib\n\nIMAGES_URL = {\n 'lena.png': 'https://i.imgur.com/ncE3dty.png',\n 'ednaldo.jpg': 'https://i.imgur.com/JnJD9FB.jpg',\n 'batman.jpg': 'https://i.imgur.com/8jKnbg5.jpg',\n 'calculista.jpg': 'https://i.imgur.com/MQNty8H.jpg',\n 'vacilao.jpg': 'https://i.imgur.com/cgp0aY9.jpg',\n 'harold.jpg': 'https://i.imgur.com/C8YrIjB.jpg',\n 'tool.jpg': 'https://i.imgur.com/bgyZxWt.jpg'\n}\n\n# Load Face classifier\nfrontal_face_classifier = cv2.CascadeClassifier(\n cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')\n\n# Load Eye classifier\neye_classifier = cv2.CascadeClassifier(\n cv2.data.haarcascades + 'haarcascade_eye.xml')\n\n# Load Smile classifier\nsmile_classifier = cv2.CascadeClassifier(\n cv2.data.haarcascades + 'haarcascade_smile.xml')\n\n# Load Upper Body classifier\nupperbody_classifier = cv2.CascadeClassifier(\n cv2.data.haarcascades + 'haarcascade_upperbody.xml')\n\n# Load Profile Face classifier\nprofile_face_classifier = cv2.CascadeClassifier(\n cv2.data.haarcascades + 'haarcascade_profileface.xml')\n\n# Load Hand classifier\nurllib.request.urlretrieve('https://raw.githubusercontent.com/Aravindlivewire/Opencv/master/haarcascade/aGest.xml', filename='xml/aGest.xml')\nhand_classifier = cv2.CascadeClassifier('xml/aGest.xml')\n\n# Create classifiers dictionary\nDEFAULT_CLASSIFIERS = {\n 'frontal_face':\n { \n 'c_name' : 'Frontal face',\n 'classifier' : frontal_face_classifier,\n 'minNeighbors': 5,\n 'color' : (255,0,0),\n 'sub_search' : True,\n 'is_sub' : False,\n 'sub_class' : ['eye','smile']\n },\n 'profile_face':\n {\n 'c_name' : 'Profile face',\n 'classifier' : profile_face_classifier,\n 'minNeighbors': 5,\n 'color' : (255,0,255),\n 'sub_search' : True,\n 'is_sub' : False,\n 'sub_class' : ['eye','smile']\n },\n 'hand':\n {\n 'c_name' : 'Hand',\n 'classifier' : hand_classifier,\n 'minNeighbors': 3,\n 'color' : (255,255,0),\n 'sub_search' : False,\n 'is_sub' : False,\n 'sub_class' : None\n },\n 'eye':\n {\n 'c_name' : 'Eye',\n 'classifier' : eye_classifier,\n 'minNeighbors': 8,\n 'color' : (0,0,255),\n 'sub_search' : False,\n 'is_sub' : True,\n 'sub_class' : None\n },\n 'smile':\n {\n 'c_name' : 'Smile',\n 'classifier' : smile_classifier,\n 'minNeighbors': 10,\n 'color' : (0,255,0),\n 'sub_search' : False,\n 'is_sub' : True,\n 'sub_class' : None\n },\n}","repo_name":"baiochi/Unstructured-Data-Analysis","sub_path":"src/defines.py","file_name":"defines.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"8515300482","text":"from pydub import AudioSegment\nfrom pydub.silence import split_on_silence\nimport os\nimport requests\nimport json\nimport unidecode\nimport base64\n\ndef split_audio(filename):\n sound = AudioSegment.from_file(filename+'_adjusted.wav')\n\n audio_chunks = split_on_silence(sound, \n # must be silent for at least half a second\n min_silence_len=1000,\n\n # consider it silent if quieter than -16 dBFS\n silence_thresh=-32\n )\n\n if not os.path.isdir(filename+'_splitted'):\n os.mkdir(filename+'_splitted')\n\n print(\"Number of chunks splitteds: \", len(audio_chunks))\n\n base64chunks = []\n for i, chunk in enumerate(audio_chunks):\n out_file = filename+\"_splitted/chunk(2)-{0}.wav\".format(i)\n print(\"exporting\", out_file)\n chunk.export(out_file, format=\"ogg\")\n\n f1 = open(out_file, 'rb')\n encoded_f1 = base64.b64encode(f1.read())\n base64chunks.append(str(encoded_f1,'ascii', 'ignore'))\n \n return base64chunks\n\nserverurl = '104.131.48.82'\nlocalurl = '127.0.0.1:8080'\n\ndata_query_auth = '{\"username\": \"desenvolvimento@tagchat.com\", \"password\": \"Devs@tagchat!@#\"}'\nmy_headers_auth = {'Content-Type': 'application/json'}\nresponse = requests.post('http://'+localurl+'/auth', data=data_query_auth, headers=my_headers_auth)\n\naccess_token = 'JWT ' + str(response.json()['access_token'])\nprint(access_token)\n\nbase64chunks = split_audio('../Audios/audio3')\nfinal_response = \"\"\n\nmy_headers = {'Authorization': access_token}\nfor base64chunk in base64chunks:\n data_query = {\"base64audio\": base64chunk}\n response = requests.post('http://'+serverurl+'/audio-to-text', data=json.dumps(data_query), headers=my_headers)\n print(response.json())\n print(type(response))\n print(response)\n final_response += \" \" + response.json()\n\nprint(final_response)","repo_name":"DCandelero/Audio-Management","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15639590627","text":"import xmlrunner\nimport unittest\nimport logging\nimport configparser\nimport xlsxwriter as xl\nimport xlrd\nfrom itertools import zip_longest\nimport sys\nimport os\n\n\nlogger = logging.getLogger()\nlogger.level = logging.ERROR\nstream_handler = logging.StreamHandler(sys.stdout)\nlogger.addHandler(stream_handler)\n\n\nclass piHiValidation(unittest.TestCase):\n\n def setUp(self):\n \"\"\"code will parse the configuration to get the path and HSS and TRUST\"\"\"\n config = configparser.ConfigParser()\n config.read('config.ini')\n global path\n global path_HI\n global HSS_id\n global TRUST_NAME\n global wb\n global file\n file = open(\"logfile.txt\", \"w\")\n wb = xlrd.open_workbook('piHI_Mapping.xlsx')\n path = config['DEV']['PATH']\n path_HI = config['DEV']['PATH_HI']\n HSS_id = config['DEV']['HSS_ID']\n TRUST_NAME = config['DEV']['TRUST_NAME']\n\n def add_log(self, text):\n file.write(text + '\\n')\n\n def test_piHiComparison(self):\n \"\"\"PI CDE text file comparison with HI for needed HSS and TRUST\"\"\"\n self.PI_CDE_files = [x for x in os.listdir(path) if x.__contains__(HSS_id + '_' + TRUST_NAME)]\n \"\"\"pick up the excel files from HI downloaded from Vertica\"\"\"\n self.HI_CDE_files = [x for x in os.listdir(path_HI) if x.startswith('EDWUK')]\n \"\"\"convert the CDE PI files before comparison\"\"\"\n self.pi_file_convert(self.PI_CDE_files)\n \"\"\"pick all the converted excel files for PI\"\"\"\n self.PI_CDE_excel_list = [x for x in os.listdir(path) if x.__contains__('.xlsx')]\n \"\"\"all the files are ready for data validation\"\"\"\n piHiValidation.prepare(self, self.PI_CDE_excel_list, self.HI_CDE_files)\n\n \"\"\"check the files for appropriate CDE type and rename before comparison\"\"\"\n def rename(self, text_file):\n ws = wb.sheet_by_index(0)\n for row_act in range(1, ws.nrows):\n if ws.row_values(row_act)[0] in text_file:\n renamed_txt = text_file.replace(text_file, 'PI_' + ws.row_values(row_act)[1])\n piHiValidation.conversion(self, renamed_txt, text_file)\n\n \"\"\"convert the CDE PI text file to CDE excel from PI\"\"\"\n def conversion(self, text, text_file):\n workbook = xl.Workbook(path + text + \".xlsx\")\n worksheet = workbook.add_worksheet(text)\n with open(path + text_file, \"r\", errors='ignore') as file: # this is to ignore the encoding on the file\n for r, row in enumerate(file.readlines()):\n for c, value in enumerate(row.split('|')):\n worksheet.write(r, c, value)\n # os.remove(path + text_file) # remove the text CDE PI files after conversion\n workbook.close()\n\n \"\"\"check the number of CDE PI files before conversion\"\"\"\n def pi_file_convert(self, files):\n if len(files) > 1:\n for filename in files:\n piHiValidation.rename(self, filename)\n elif len(files) == 0:\n self.assertNotEqual(files, [], msg='no PI CDE files or with expected naming convention')\n else:\n piHiValidation.rename(self, files[0])\n\n \"\"\"making sure the PI and HI excel are ready for comparison after removal of unnecessary columns\"\"\"\n def prepare(self, pi_list, hi_list):\n for count in range(0, max(len(pi_list), len(hi_list))):\n pi_excel = xlrd.open_workbook(path+pi_list[count])\n hi_excel = xlrd.open_workbook(path_HI+hi_list[count])\n # to remove the unwanted columns\n # new_hi = pd.ExcelFile(path_HI+hi_list[count]).parse(sheet_name=0).drop(['nhs_trust_nbr', 'health_system_id', 'health_system_source_id', 'cde_trigger_date', 'update_dt_tm'], axis=1)\n # new_hi.to_excel(path_HI+hi_list[count], index=False)\n print('Comparing- ' + hi_list[count])\n piHiValidation.add_log(self, '\\n' + 'Comparing- ' + hi_list[count])\n piHiValidation.compare(self, pi_excel, hi_excel)\n\n \"\"\"compare the excel line by line for data validation\"\"\"\n def compare(self, pi_excel, hi_excel):\n self.fail = 0\n sheet1 = pi_excel.sheet_by_index(0)\n sheet2 = hi_excel.sheet_by_index(0)\n for rownum in range(max(sheet1.nrows, sheet2.nrows)):\n if rownum < sheet2.nrows:\n try:\n pi_rb1 = sheet1.row_values(rownum)\n hi_rb2 = sheet2.row_values(rownum)\n for colnum, (c1, c2) in enumerate(zip_longest(pi_rb1, hi_rb2)):\n if c1 != c2:\n self.fail = 1\n self.assertNotEqual(c1, c2)\n print(\"=======================================================================================\")\n piHiValidation.add_log(self, \"=======================================================================================\")\n print(\"ISSUE in ROW {} COL {} - {} IN PI IS NOT SAME AS {} IN ABOVE MENTIONED HI \".format(rownum + 1, colnum + 1, c1, c2))\n piHiValidation.add_log(self, 'ISSUE in ROW {} COL {} - \"{}\" IN PI IS NOT SAME AS \"{}\" IN ABOVE MENTIONED HI '.format(rownum + 1, colnum + 1, c1, c2))\n else:\n self.assertEqual(c1, c2)\n except IndexError:\n print(\"Total Rows in PI - {} and total rows in HI - {} aren't same\".format(sheet1.nrows, sheet2.nrows))\n piHiValidation.add_log(self, \"Total Rows in PI - {} and total rows in HI - {} aren't same\".format(sheet1.nrows, sheet2.nrows))\n else:\n print(\"Row {} missing in HI excel file\".format(rownum + 1))\n piHiValidation.add_log(self, \"Row {} missing in HI excel file\".format(rownum + 1))\n if self.fail == 0:\n print(\"=======================================================================================\")\n piHiValidation.add_log(self, \"=======================================================================================\")\n print(\"Comparison was successful\\n\")\n piHiValidation.add_log(self, \"Comparison was successful\\n\")\n if self.fail == 1:\n print(\"Comparison was unsuccessful with above issue(s), refer \" + file.name + \" for more details\\n\")\n piHiValidation.add_log(self, \"Comparison was unsuccessful with above issue(s)\\n\")\n\n\nif __name__ == \"__main__\":\n unittest.main(testRunner=xmlrunner.XMLTestRunner(output=\"./xml_logs\"))\n\n\n","repo_name":"vivekrkini/CernerUK","sub_path":"HelloWorld/Comparison/piHIComparison.py","file_name":"piHIComparison.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23183418721","text":"# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\n\n# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n\n# 错误的思路,这样12位数以下还可以,20位太慢了\n# def smallest_multiple(n):\n# num = 1\n# flag = 0\n# while flag!=n:\n# num+=1\n# for i in range(1,n+1):\n# # print(\"i=\",i )\n# if num % i != 0:\n# flag = 0\n \n# else:\n# flag+=1\n# # print(\"@:\",num)\n\n# print(\"#:\",num)\n\ndef biggest_common(a,b):\n result = 1\n small = 1\n if a < b:\n small = a\n else:\n small = b\n\n for i in range(1,small+1):\n if a % i == 0 and b % i ==0:\n result = i\n print('bigggestcommon=',result)\n return result\n\ndef smallest_multiple(a,b):\n c = biggest_common(a, b)\n a1 = a//c\n b1 = b//c\n print(\"a=\",a,\"b=\",b,\"c=\",c,a1,b1)\n return c*a1*b1\n\ndef find_smallest_multiple(n):\n result = 1\n for i in range(1, n+1):\n result = smallest_multiple(i,result)\n print(result)\n\nif __name__ == \"__main__\":\n find_smallest_multiple(20)\n","repo_name":"greatabel/puzzle_I_cracked","sub_path":"3ProjectEuler/i1_25/i05smallest_multiple.py","file_name":"i05smallest_multiple.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"}
+{"seq_id":"31763251646","text":"import json\n\nimport requests\nfrom sqlalchemy.orm import Session\n\nfrom core.config import settings\nfrom sql_app.crud import get_label\nfrom sql_app.models import Label\nfrom sql_app.models import Task\n\nurl = \"https://api.trello.com/1\"\n\nheaders = {\"Accept\": \"application/json\"}\n\ndefault_query = {\n \"idList\": settings.TRELLO_TO_DO_LIST_ID,\n \"key\": settings.TRELLO_API_KEY,\n \"token\": settings.TRELLO_API_TOKEN,\n}\n\n\nasync def validate_fields(type: str, title: str, description: str, category: str):\n errors = {}\n if type not in [x[0] for x in Task.TYPES]:\n errors[\"type\"] = f\"'{type}' is an invalid type for tasks.\"\n if not category and type == Task.TASK:\n errors[\"category\"] = f\"The type '{type}' required caregory field.\"\n if category:\n if type != Task.TASK:\n errors[\"category\"] = f\"The type '{type}' don't support caregory field.\"\n else:\n if category not in [x[0] for x in Task.CATEGORIES]:\n errors[\"category\"] = f\"'{category}' is an invalid category.\"\n if title and type == Task.BUG:\n errors[\"title\"] = f\"The type '{type}' don't support title field.\"\n if not title and type != Task.BUG:\n errors[\"title\"] = f\"The type '{type}' required title field.\"\n if description and type == Task.TASK:\n errors[\"description\"] = f\"The type '{type}' don't support description field.\"\n if not description and type != Task.TASK:\n errors[\"description\"] = f\"The type '{type}' required description field.\"\n return errors\n\n\nasync def get_id_label(label: str, db: Session):\n label_id = None\n label_obj = get_label(db=db, label=label)\n if not label_obj:\n label_id = await create_label(label=label, db=db)\n else:\n label_id = label_obj.trello_id\n return label_id\n\n\nasync def create_label(label: str, db: Session):\n label_obj = Label(name=label)\n query = default_query.copy()\n query[\"idBoard\"] = settings.TRELLO_BOARD_ID\n query[\"name\"] = label\n response = requests.request(\"POST\", f\"{url}/labels\", headers=headers, params=query)\n response_data = json.loads(response.text)\n label_id = response_data[\"id\"]\n label_obj.trello_id = label_id\n db.add(label_obj)\n db.commit()\n db.refresh(label_obj)\n return label_id\n\n\nasync def sync_with_trello(task: Task, db: Session):\n query = default_query.copy()\n if task.title:\n query[\"name\"] = str(task.title)\n if task.description:\n query[\"desc\"] = task.description\n if task.category:\n query[\"idLabels\"] = await get_id_label(label=task.category, db=db)\n if task.type == Task.BUG:\n query[\"idLabels\"] = await get_id_label(label=\"bug\", db=db)\n requests.request(\"POST\", f\"{url}/cards\", headers=headers, params=query)\n","repo_name":"emmanuel-santos1/space-x","sub_path":"task/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25009592308","text":"import pytest\n\nfrom .task2 import sort_array\n\n\n@pytest.mark.parametrize(\n \"arr, expected\",\n [\n ([3, 7, 8, 9], [8, 3, 9, 7]),\n ([9, 7, 8, 3], [8, 3, 9, 7]),\n ([], []),\n (\"abc\", \"Function accepting only list\"),\n ],\n)\ndef test_sort_array(arr, expected):\n assert sort_array(arr) == expected\n","repo_name":"Dm1triiSmirnov/tasks","sub_path":"task2/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29525034452","text":"# 練習題decorator\n\ndef revise_divide(func):\n def inner(n, d):\n if d == 0:\n print(\"除數不可為0\")\n else:\n m = func(n, d)\n print(m)\n return inner\n\ndef divide(n, d):\n return n/d\n\nn = input(\"請輸入被除數: \")\nd = input(\"請輸入除數: \")\nn = int(n)\nd = int(d)\ndivide = revise_divide(divide)\ndivide(n, d)","repo_name":"PaulSurgeon/decorator","sub_path":"div.py","file_name":"div.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70682633363","text":"import os\nfrom datetime import datetime # 导入时间函数\n\nif not os.path.exists('./6_7'): # 创建文件夹\n os.mkdir('./6_7')\nfp = open('暂时.txt','a',encoding = 'utf-8') # 创建文件 ,类型.txt.(a,w均可文件不存在时创建新的文件,且把写入的字符串加入到文件末尾)\n\na = datetime.now() # 获取当前时间,类型位\n# print(a) # 打印现在的时间\n# print(type(a))\ntime_now = a.strftime(\"%A, %d. %B %Y %I:%M%p\") # 时间格式化,类型为\n# print(time_now)\n# print(type(time_now))\n# print(a)\n# time_now = str(a)\nfp.writelines(time_now+'\\n') # 写入时间 weitelines 我用'\\n'符加入进去还是一列","repo_name":"jihaikang/2021-","sub_path":"新建文件夹.py","file_name":"新建文件夹.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32677203284","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\nimport six\n\nfrom tensorflow_docs.api_generator import tf_inspect\n\n\ndef maybe_singleton(py_object):\n \"\"\"Returns `True` if `py_object` might be a singleton value .\n\n Many immutable values in python act like singletons: small ints, some strings,\n Bools, None, the empty tuple.\n\n We can't rely on looking these up by their `id()` to find their name or\n duplicates.\n\n This function checks if the object is one of those maybe singleton values.\n\n Args:\n py_object: the object to check.\n\n Returns:\n A bool, True if the object might be a singleton.\n \"\"\"\n # isinstance accepts nested tuples of types.\n is_immutable_type = isinstance(\n py_object, (six.integer_types, six.string_types, six.binary_type,\n six.text_type, float, complex, bool, type(None)))\n\n # Check if the object is the empty tuple.\n return is_immutable_type or py_object is () # pylint: disable=literal-comparison\n\n\nclass ApiTreeNode(object):\n \"\"\"Represents a single API end-point.\n\n Attributes:\n path: A tuple of strings containing the path to the object from the root\n like `('tf', 'losses', 'hinge')`\n obj: The python object.\n children: A dictionary from short name to `ApiTreeNode`, including the\n children nodes.\n parent: The parent node.\n short_name: The last path component\n full_name: All path components joined with \".\"\n \"\"\"\n\n def __init__(self, path, obj, parent):\n self.path = path\n self.obj = obj\n self.children = {}\n self.parent = parent\n\n @property\n def short_name(self):\n return self.path[-1]\n\n @property\n def full_name(self):\n return '.'.join(self.path)\n\n\nclass ApiTree(object):\n \"\"\"Represents all api end-points as a tree.\n\n Items must be inserted in order, from root to leaf.\n\n Attributes:\n index: A dict, mapping from path tuples to `ApiTreeNode`.\n aliases: A dict, mapping from object ids to a list of all `ApiTreeNode` that\n refer to the object.\n root: The root `ApiTreeNode`\n \"\"\"\n\n def __init__(self):\n root = ApiTreeNode((), None, None)\n self.index = {(): root}\n self.aliases = collections.defaultdict(list)\n self.root = root\n\n def __contains__(self, path):\n \"\"\"Returns `True` if path exists in the tree.\n\n Args:\n path: A tuple of strings, the api path to the object.\n\n Returns:\n True if `path` exists in the tree.\n \"\"\"\n return path in self.index\n\n def __getitem__(self, path):\n \"\"\"Fetch an item from the tree.\n\n Args:\n path: A tuple of strings, the api path to the object.\n\n Returns:\n An `ApiTreeNode`.\n\n Raises:\n KeyError: If no node can be found at that path.\n \"\"\"\n return self.index[path]\n\n def __setitem__(self, path, obj):\n \"\"\"Add an object to the tree.\n\n Args:\n path: A tuple of strings.\n obj: The python object.\n \"\"\"\n parent_path = path[:-1]\n parent = self.index[parent_path]\n\n node = ApiTreeNode(path=path, obj=obj, parent=parent)\n\n self.index[path] = node\n if not maybe_singleton(obj):\n # We cannot use the duplicate mechanism for some constants, since e.g.,\n # id(c1) == id(c2) with c1=1, c2=1. This isn't problematic since constants\n # have no usable docstring and won't be documented automatically.\n self.aliases[id(obj)].append(node)\n parent.children[node.short_name] = node\n\n\nclass DocGeneratorVisitor(object):\n \"\"\"A visitor that generates docs for a python object when __call__ed.\"\"\"\n\n def __init__(self):\n \"\"\"Make a visitor.\n\n This visitor expects to be called on each node in the api. It is passed the\n path to an object, the object, and the filtered list of the object's\n children. (see the `__call__` method for details.\n\n This object accumulates the various data-structures necessary to build the\n docs, including (see the property definitions for details.):\n\n In the decsription below \"master name\" is the object's preferred fully\n qualified name.\n\n Params:\n index: A mapping from master names to python python objects.\n tree: A mapping from master names to a list if attribute names.\n reverse_index: Mapping from python object ids to master names.\n Note that this doesn't work for python numbers, strings or tuples.\n duplicate_of: A mapping from a fully qualified names to the object's\n master name. The master names are not included as keys.\n duplicates: A mapping from master names to lists of other fully qualified\n names for the object.\n \"\"\"\n self._index = {}\n self._tree = {}\n self._reverse_index = None\n self._duplicates = None\n self._duplicate_of = None\n\n self._api_tree = ApiTree()\n\n @property\n def index(self):\n \"\"\"A map from fully qualified names to objects to be documented.\n\n The index is filled when the visitor is passed to `traverse`.\n\n Returns:\n The index filled by traversal.\n \"\"\"\n return self._index\n\n @property\n def tree(self):\n \"\"\"A map from fully qualified names to all its child names for traversal.\n\n The full name to member names map is filled when the visitor is passed to\n `traverse`.\n\n Returns:\n The full name to member name map filled by traversal.\n \"\"\"\n return self._tree\n\n @property\n def reverse_index(self):\n \"\"\"A map from `id(object)` to the preferred fully qualified name.\n\n This map only contains non-primitive objects (no numbers or strings) present\n in `index` (for primitive objects, `id()` doesn't quite do the right thing).\n\n It is computed when it, `duplicate_of`, or `duplicates` are first accessed.\n\n Returns:\n The `id(object)` to full name map.\n \"\"\"\n self._maybe_find_duplicates()\n return self._reverse_index\n\n @property\n def duplicate_of(self):\n \"\"\"A map from duplicate full names to a preferred fully qualified name.\n\n This map only contains names that are not themself a preferred name.\n\n It is computed when it, `reverse_index`, or `duplicates` are first accessed.\n\n Returns:\n The map from duplicate name to preferred name.\n \"\"\"\n self._maybe_find_duplicates()\n return self._duplicate_of\n\n @property\n def duplicates(self):\n \"\"\"A map from preferred full names to a list of all names for this symbol.\n\n This function returns a map from preferred (master) name for a symbol to a\n lexicographically sorted list of all aliases for that name (incl. the master\n name). Symbols without duplicate names do not appear in this map.\n\n It is computed when it, `reverse_index`, or `duplicate_of` are first\n accessed.\n\n Returns:\n The map from master name to list of all duplicate names.\n \"\"\"\n self._maybe_find_duplicates()\n return self._duplicates\n\n def __call__(self, parent_path, parent, children):\n \"\"\"Visitor interface, see `tensorflow/tools/common:traverse` for details.\n\n This method is called for each symbol found in a traversal using\n `tensorflow/tools/common:traverse`. It should not be called directly in\n user code.\n\n Args:\n parent_path: A tuple of strings. The fully qualified path to a symbol\n found during traversal.\n parent: The Python object referenced by `parent_name`.\n children: A list of `(name, py_object)` pairs enumerating, in alphabetical\n order, the children (as determined by `tf_inspect.getmembers`) of\n `parent`. `name` is the local name of `py_object` in `parent`.\n\n Returns:\n The list of children, with any __metaclass__ removed.\n\n Raises:\n RuntimeError: If this visitor is called with a `parent` that is not a\n class or module.\n \"\"\"\n parent_name = '.'.join(parent_path)\n self._index[parent_name] = parent\n self._tree[parent_name] = []\n if parent_path not in self._api_tree:\n self._api_tree[parent_path] = parent\n\n if not (tf_inspect.ismodule(parent) or tf_inspect.isclass(parent)):\n raise RuntimeError('Unexpected type in visitor -- %s: %r' % (parent_name,\n parent))\n\n for (name, child) in children:\n self._api_tree[parent_path + (name,)] = child\n\n full_name = '.'.join([parent_name, name]) if parent_name else name\n self._index[full_name] = child\n self._tree[parent_name].append(name)\n\n return children\n\n def _score_name(self, name):\n \"\"\"Return a tuple of scores indicating how to sort for the best name.\n\n This function is meant to be used as the `key` to the `sorted` function.\n\n This returns a score tuple composed of the following scores:\n defining_class: Prefers method names pointing into the defining class,\n over a subclass (`ParentClass.method` over `Subclass.method`, if it\n referrs to the same method implementation).\n experimental: Prefers names that are not in \"contrib\" or \"experimental\".\n keras: Prefers keras names to non-keras names.\n module_length: Prefers submodules (tf.sub.thing) over the root namespace\n (tf.thing) over deeply nested paths (tf.a.b.c.thing)\n name: Fallback, sorts lexicographically on the full_name.\n\n Args:\n name: the full name to score, for example `tf.estimator.Estimator`\n\n Returns:\n A tuple of scores. When sorted the preferred name will have the lowest\n value.\n \"\"\"\n parts = name.split('.')\n short_name = parts[-1]\n if len(parts) == 1:\n return (-99, -99, -99, -99, short_name)\n\n container = self._index['.'.join(parts[:-1])]\n\n defining_class_score = 1\n if tf_inspect.isclass(container):\n if short_name in container.__dict__:\n # prefer the defining class\n defining_class_score = -1\n\n experimental_score = -1\n if 'contrib' in parts or any('experimental' in part for part in parts):\n experimental_score = 1\n\n keras_score = 1\n if 'keras' in parts:\n keras_score = -1\n\n while parts:\n container = self._index['.'.join(parts)]\n if tf_inspect.ismodule(container):\n break\n parts.pop()\n\n module_length = len(parts)\n\n if len(parts) == 2:\n # `tf.submodule.thing` is better than `tf.thing`\n module_length_score = -1\n else:\n # shorter is better\n module_length_score = module_length\n\n return (defining_class_score, experimental_score, keras_score,\n module_length_score, name)\n\n def _maybe_find_duplicates(self):\n \"\"\"Compute data structures containing information about duplicates.\n\n Find duplicates in `index` and decide on one to be the \"master\" name.\n\n Computes a reverse_index mapping each object id to its master name.\n\n Also computes a map `duplicate_of` from aliases to their master name (the\n master name itself has no entry in this map), and a map `duplicates` from\n master names to a lexicographically sorted list of all aliases for that name\n (incl. the master name).\n\n All these are computed and set as fields if they haven't already.\n \"\"\"\n if self._reverse_index is not None:\n return\n\n # Maps the id of a symbol to its fully qualified name. For symbols that have\n # several aliases, this map contains the first one found.\n # We use id(py_object) to get a hashable value for py_object. Note all\n # objects in _index are in memory at the same time so this is safe.\n reverse_index = {}\n\n # Decide on master names, rewire duplicates and make a duplicate_of map\n # mapping all non-master duplicates to the master name. The master symbol\n # does not have an entry in this map.\n duplicate_of = {}\n\n # Duplicates maps the main symbols to the set of all duplicates of that\n # symbol (incl. itself).\n duplicates = {}\n\n for path, node in six.iteritems(self._api_tree.index):\n if not path:\n continue\n full_name = node.full_name\n py_object = node.obj\n object_id = id(py_object)\n if full_name in duplicates:\n continue\n\n aliases = self._api_tree.aliases[object_id]\n if not aliases:\n aliases = [node]\n\n names = [alias.full_name for alias in aliases]\n\n names = sorted(names)\n # Choose the master name with a lexical sort on the tuples returned by\n # by _score_name.\n master_name = min(names, key=self._score_name)\n\n if names:\n duplicates[master_name] = list(names)\n\n names.remove(master_name)\n for name in names:\n duplicate_of[name] = master_name\n\n # Set the reverse index to the canonical name.\n if not maybe_singleton(py_object):\n reverse_index[object_id] = master_name\n\n self._duplicate_of = duplicate_of\n self._duplicates = duplicates\n self._reverse_index = reverse_index\n","repo_name":"DpD-Nightmare/Li-Ion-Battery-SOC-estimation-Using-Back-propogation-algorithm","sub_path":"docs-master/tools/tensorflow_docs/api_generator/doc_generator_visitor.py","file_name":"doc_generator_visitor.py","file_ext":"py","file_size_in_byte":12697,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"10402658353","text":"\"\"\"Classes for computing sensitivity metrics.\"\"\"\n\nfrom typing import Literal, Optional\n\nfrom cyclops.evaluate.metrics.metric import Metric\nfrom cyclops.evaluate.metrics.precision_recall import (\n BinaryRecall,\n MulticlassRecall,\n MultilabelRecall,\n)\n\n\nclass BinarySensitivity(BinaryRecall, registry_key=\"binary_sensitivity\"):\n \"\"\"Computes sensitivity score for binary classification.\n\n Parameters\n ----------\n pos_label : int, default=1\n Label of the positive class.\n threshold : float, default=0.5\n Threshold for deciding the positive class.\n zero_division : Literal[\"warn\", 0, 1], default=\"warn\"\n Value to return when there is a zero division. If set to \"warn\", this\n acts as 0, but warnings are also raised.\n\n Examples\n --------\n >>> from cyclops.evaluation.metrics import BinarySensitivity\n >>> target = [0, 1, 0, 1]\n >>> preds = [0, 1, 1, 0]\n >>> metric = Sensitivity()\n >>> metric(target, preds)\n 0.5\n >>> metric.reset_state()\n >>> target = [[0, 1, 0, 1], [0, 0, 1, 1]]\n >>> preds = [[0.1, 0.9, 0.8, 0.2], [0.2, 0.3, 0.6, 0.1]]\n >>> for t, p in zip(target, preds):\n ... metric.update_state(t, p)\n >>> metric.compute()\n 0.5\n\n \"\"\"\n\n def __init__(\n self,\n pos_label: int = 1,\n threshold: float = 0.5,\n zero_division: Literal[\"warn\", 0, 1] = \"warn\",\n ) -> None:\n \"\"\"Initialize the metric.\"\"\"\n super().__init__(\n pos_label=pos_label,\n threshold=threshold,\n zero_division=zero_division,\n )\n\n\nclass MulticlassSensitivity(MulticlassRecall, registry_key=\"multiclass_sensitivity\"):\n \"\"\"Compute the sensitivity score for multiclass classification tasks.\n\n Parameters\n ----------\n num_classes : int\n Number of classes in the dataset.\n top_k : int, optional\n If given, and predictions are probabilities/logits, the sensitivity will\n be computed only for the top k classes. Otherwise, ``top_k`` will be\n set to 1.\n average : Literal[\"micro\", \"macro\", \"weighted\", None], default=None\n If ``None``, return the sensitivity score for each class. Otherwise,\n use one of the following options to compute the average score:\n\n - ``micro``: Calculate metric globally from the total count of true\n positives and false negatives.\n - ``macro``: Calculate metric for each class, and find their\n unweighted mean. This does not take label imbalance into account.\n - ``weighted``: Calculate metric for each class, and find their\n average weighted by the support (the number of true instances\n for each class). This alters \"macro\" to account for class\n imbalance.\n zero_division : Literal[\"warn\", 0, 1], default=\"warn\"\n Value to return when there is a zero division. If set to \"warn\", this\n acts as 0, but warnings are also raised.\n\n Examples\n --------\n >>> from cyclops.evaluation.metrics import MulticlassSensitivity\n >>> target = [0, 1, 2, 0]\n >>> preds = [2, 0, 2, 1]\n >>> metric = MulticlassSensitivity(num_classes=3)\n >>> metric(target, preds)\n array([0., 0., 1.])\n >>> metric.reset_state()\n >>> target = [[0, 1, 2, 0], [2, 1, 2, 0]]\n >>> preds = [\n ... [[0.1, 0.6, 0.3],\n ... [0.05, 0.1, 0.85],\n ... [0.2, 0.7, 0.1],\n ... [0.9, 0.05, 0.05]],\n ... [[0.1, 0.6, 0.3],\n ... [0.05, 0.1, 0.85],\n ... [0.2, 0.7, 0.1],\n ... [0.9, 0.05, 0.05]]\n ... ]\n >>> for t, p in zip(target, preds):\n ... metric.update_state(t, p)\n >>> metric.compute()\n array([0.66666667, 0. , 0. ])\n\n \"\"\"\n\n def __init__(\n self,\n num_classes: int,\n top_k: Optional[int] = None,\n average: Literal[\"micro\", \"macro\", \"weighted\", None] = None,\n zero_division: Literal[\"warn\", 0, 1] = \"warn\",\n ) -> None:\n \"\"\"Initialize the metric.\"\"\"\n super().__init__(\n num_classes=num_classes,\n top_k=top_k,\n average=average,\n zero_division=zero_division,\n )\n\n\nclass MultilabelSensitivity(MultilabelRecall, registry_key=\"multilabel_sensitivity\"):\n \"\"\"Compute the sensitivity score for multilabel classification tasks.\n\n Parameters\n ----------\n num_labels : int\n Number of labels in the dataset.\n threshold : float, default=0.5\n Threshold for deciding the positive class.\n average : Literal[\"micro\", \"macro\", \"weighted\", None], default=None\n If ``None``, return the score for each class. Otherwise,\n use one of the following options to compute the average score:\n\n - ``micro``: Calculate metric globally from the total count of true\n positives and false negatives.\n - ``macro``: Calculate metric for each label, and find their\n unweighted mean. This does not take label imbalance into account.\n - ``weighted``: Calculate metric for each label, and find their\n average weighted by the support (the number of true instances\n for each label). This alters \"macro\" to account for label\n imbalance.\n zero_division : Literal[\"warn\", 0, 1], default=\"warn\"\n Value to return when there is a zero division. If set to \"warn\", this\n acts as 0, but warnings are also raised.\n\n Examples\n --------\n >>> from cyclops.evaluation.metrics import MultilabelSensitivity\n >>> target = [[0, 1, 0, 1], [0, 0, 1, 1]]\n >>> preds = [[0.1, 0.9, 0.8, 0.2], [0.2, 0.3, 0.6, 0.1]]\n >>> metric = MultilabelSensitivity(num_labels=4)\n >>> metric(target, preds)\n array([0., 1., 1. , 0. ])\n >>> metric.reset_state()\n >>> target = [[[0, 1, 0, 1], [0, 0, 1, 1]], [[0, 1, 0, 1], [0, 0, 1, 1]]]\n >>> preds = [[[0.1, 0.9, 0.8, 0.2], [0.2, 0.3, 0.6, 0.1]],\n ... [[0.1, 0.9, 0.8, 0.2], [0.2, 0.3, 0.6, 0.1]]]\n >>> for t, p in zip(target, preds):\n ... metric.update_state(t, p)\n >>> metric.compute()\n array([0., 1., 1., 0.])\n\n \"\"\"\n\n def __init__(\n self,\n num_labels: int,\n threshold: float = 0.5,\n top_k: Optional[int] = None,\n average: Literal[\"micro\", \"macro\", \"weighted\", None] = None,\n zero_division: Literal[\"warn\", 0, 1] = \"warn\",\n ) -> None:\n \"\"\"Initialize the metric.\"\"\"\n super().__init__(\n num_labels=num_labels,\n threshold=threshold,\n top_k=top_k,\n average=average,\n zero_division=zero_division,\n )\n\n\nclass Sensitivity(Metric, registry_key=\"sensitivity\", force_register=True):\n \"\"\"Compute the sensitivity score for different types of classification tasks.\n\n This metric can be used for binary, multiclass, and multilabel classification\n tasks. It creates the appropriate class based on the ``task`` parameter.\n\n Parameters\n ----------\n task : Literal[\"binary\", \"multiclass\", \"multilabel\"]\n Type of classification task.\n pos_label : int, default=1\n Label to consider as positive for binary classification tasks.\n num_classes : int, default=None\n Number of classes for the task. Required if ``task`` is ``\"multiclass\"``.\n threshold : float, default=0.5\n Threshold for deciding the positive class. Only used if ``task`` is\n ``\"binary\"`` or ``\"multilabel\"``.\n top_k : int, optional\n If given, and predictions are probabilities/logits, the precision will\n be computed only for the top k classes. Otherwise, ``top_k`` will be\n set to 1. Only used if ``task`` is ``\"multiclass\"`` or ``\"multilabel\"``.\n num_labels : int, default=None\n Number of labels for the task. Required if ``task`` is ``\"multilabel\"``.\n average : Literal[\"micro\", \"macro\", \"weighted\", None], default=None\n If ``None``, return the sensitivity score for each label/class. Otherwise,\n use one of the following options to compute the average score:\n\n - ``micro``: Calculate metrics globally by counting the total true\n positives and false negatives.\n - ``macro``: Calculate metrics for each class/label, and find their\n unweighted mean. This does not take label imbalance into account.\n - ``weighted``: Calculate metrics for each label/class, and find\n their average weighted by support (the number of true instances\n for each label/class). This alters ``macro`` to account for\n label/class imbalance.\n zero_division : Literal[\"warn\", 0, 1], default=\"warn\"\n Value to return when there is a zero division. If set to \"warn\", this\n acts as 0, but warnings are also raised.\n\n Examples\n --------\n >>> # (binary)\n >>> from cyclops.evaluation.metrics import Sensitivity\n >>> target = [0, 1, 0, 1]\n >>> preds = [0, 1, 1, 1]\n >>> metric = Sensitivity(task=\"binary\")\n >>> metric.update_state(target, preds)\n >>> metric.compute()\n 1.\n >>> metric.reset_state()\n >>> target = [[0, 1, 0, 1], [0, 0, 1, 1]]\n >>> preds = [[0.1, 0.9, 0.8, 0.2], [0.2, 0.3, 0.6, 0.1]]\n >>> for t, p in zip(target, preds):\n ... metric.update_state(t, p)\n >>> metric.compute()\n 0.5\n\n >>> # (multiclass)\n >>> from cyclops.evaluation.metrics import Sensitivity\n >>> target = [0, 1, 2, 0]\n >>> preds = [0, 2, 1, 0]\n >>> metric = Sensitivity(task=\"multiclass\", num_classes=3)\n >>> metric(target, preds)\n array([1. , 0. , 0.])\n >>> metric.reset_state()\n >>> target = [[0, 1, 2, 0], [2, 1, 2, 0]]\n >>> preds = [\n ... [[0.1, 0.6, 0.3],\n ... [0.05, 0.1, 0.85],\n ... [0.2, 0.7, 0.1],\n ... [0.9, 0.05, 0.05]],\n ... [[0.1, 0.6, 0.3],\n ... [0.05, 0.1, 0.85],\n ... [0.2, 0.7, 0.1],\n ... [0.9, 0.05, 0.05]]\n ... ]\n >>> for t, p in zip(target, preds):\n ... metric.update_state(t, p)\n >>> metric.compute()\n array([0.66666667, 0. , 0. ])\n\n >>> # (multilabel)\n >>> from cyclops.evaluation.metrics import Sensitivity\n >>> target = [[0, 1], [1, 1]]\n >>> preds = [[0.1, 0.9], [0.2, 0.8]]\n >>> metric = Sensitivity(task=\"multilabel\", num_labels=2)\n >>> metric(target, preds)\n array([0., 1.])\n >>> metric.reset_state()\n >>> target = [[[0, 1], [1, 1]], [[1, 1], [1, 0]]]\n >>> preds = [\n ... [[0.1, 0.7], [0.2, 0.8]],\n ... [[0.5, 0.9], [0.3, 0.4]]\n ... ]\n >>> for t, p in zip(target, preds):\n ... metric.update_state(t, p)\n >>> metric.compute()\n array([0.33333333, 1. ])\n\n \"\"\"\n\n def __new__( # type: ignore # mypy expects a subclass of Sensitivity\n cls,\n task: Literal[\"binary\", \"multiclass\", \"multilabel\"],\n pos_label: int = 1,\n num_classes: Optional[int] = None,\n threshold: float = 0.5,\n top_k: Optional[int] = None,\n num_labels: Optional[int] = None,\n average: Literal[\"micro\", \"macro\", \"weighted\", None] = None,\n zero_division: Literal[\"warn\", 0, 1] = \"warn\",\n ) -> Metric:\n \"\"\"Create a task-specific metric for computing the sensitivity score.\"\"\"\n if task == \"binary\":\n return BinarySensitivity(\n threshold=threshold,\n pos_label=pos_label,\n zero_division=zero_division,\n )\n if task == \"multiclass\":\n assert (\n isinstance(num_classes, int) and num_classes > 0\n ), \"Number of classes must be specified for multiclass classification.\"\n return MulticlassSensitivity(\n num_classes=num_classes,\n top_k=top_k,\n average=average,\n zero_division=zero_division,\n )\n if task == \"multilabel\":\n assert (\n isinstance(num_labels, int) and num_labels > 0\n ), \"Number of labels must be specified for multilabel classification.\"\n return MultilabelSensitivity(\n num_labels=num_labels,\n threshold=threshold,\n top_k=top_k,\n average=average,\n zero_division=zero_division,\n )\n raise ValueError(\n f\"Task '{task}' not supported, expected 'binary', 'multiclass' or \"\n f\"'multilabel'.\",\n )\n","repo_name":"VectorInstitute/cyclops","sub_path":"cyclops/evaluate/metrics/sensitivity.py","file_name":"sensitivity.py","file_ext":"py","file_size_in_byte":12381,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"3"}
+{"seq_id":"27210017761","text":"from django.shortcuts import render, get_object_or_404\nfrom django.urls import reverse\nfrom django.http.response import HttpResponseRedirect\nfrom . import models\n\n# Create your views here.\ndef index_view(request): \n todo_list = models.ToDoItem.objects.all()\n context = {\n 'todo_list_context': todo_list\n }\n return render(request, 'todo_app/index.html', context)\n\ndef save_todo_item(request):\n todo_dict = request.POST\n todo_string = todo_dict['todo_name']\n priority_id = int(request.POST['priority'])\n priority_object = get_object_or_404(models.Priority, pk=priority_id)\n todo_object = models.ToDoItem.objects.create(text=todo_string, priority=priority_object)\n print(priority_object, todo_object)\n return HttpResponseRedirect(reverse('todo_app:index_name'))\n ","repo_name":"PdxCodeGuild/class_HB2","sub_path":"code/zach/Django/lab01-todo/todo_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"22909331846","text":"import torch\nimport pandas as pd\nimport torch.nn as nn\nimport numpy as np\n\n\n\"\"\"# Data Preparation\"\"\"\n\ndef get_df_vindr(root,pathology,cross_eval=False):\n \n train_df=pd.read_csv(root+'/image_labels_train.csv')\n valid_df=pd.read_csv(root+'/image_labels_test.csv')\n \n train_df=train_df.loc[(train_df[pathology]==1)|((train_df[pathology]==0) & (train_df['No finding']==1))]\n valid_df=valid_df.loc[(valid_df[pathology]==1)|((valid_df[pathology]==0) & (valid_df['No finding']==1))]\n train_df=train_df.drop_duplicates(subset='image_id')\n valid_df=valid_df.drop_duplicates(subset='image_id')\n #Handle the partitioning better for the sake of evaluating in the entire dataset\n test=['test' for x in range(len(valid_df))]\n valid_df=valid_df.assign(partition=test)\n train=['train' for x in range(len(train_df))]\n train_df=train_df.assign(partition=train)\n eval_df=pd.concat([train_df,valid_df],ignore_index=True)\n \n if cross_eval:\n return eval_df\n else:\n return train_df,valid_df","repo_name":"dafisilva/attention-contrastive-learning-icmla","sub_path":"utilities/vindr_utils.py","file_name":"vindr_utils.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24982668175","text":"import pandas as pd\r\n\r\ndef getinput(onefile, dlimiter, colname, formula):\r\n if not dlimiter: \r\n df = pd.DataFrame(onefile)\r\n univariate(df, colname, formula)\r\n else:\r\n df = pd.DataFrame(onefile,sep=dlimiter)\r\n univariate(df, colname, formula)\r\n \r\ndef univariate(df, colname, formula):\r\n \r\n #Formula application\r\n Salary = colname[1]\r\n output = eval(formula)\r\n \r\n #Replace missing value by mean\r\n updateddataframe = df.fillna(output)\r\n\r\ndef main():\r\n dlimiter = \";\"\r\n filepath = \"Salary_Data.csv\"\r\n #Mean calculation or anything\r\n formula = \"Salary*2\"\r\n onefile = pd.read_csv(filepath)\r\n columnname = \"Salary, Yearsofexperience\"\r\n colname = columnname.split(',')\r\n getinput(onefile, dlimiter, colname, formula)\r\n \r\nif __name__ == \"__main__\":\r\n main()","repo_name":"Lav2891/python","sub_path":"taskthreefn.py","file_name":"taskthreefn.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"524313924","text":"from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Optional, Sequence\n\nimport tensorflow as tf\n\nfrom trieste.types import TensorType\n\n\n@dataclass(frozen=True)\nclass Dataset:\n \"\"\"\n Container for the query points and corresponding observations from an\n :class:`~trieste.observer.Observer`.\n \"\"\"\n\n query_points: TensorType\n \"\"\" The points at which the :class:`~trieste.observer.Observer` was queried. \"\"\"\n\n observations: TensorType\n \"\"\" The observed output of the :class:`~trieste.observer.Observer` for each query point. \"\"\"\n\n def __post_init__(self) -> None:\n \"\"\"\n :raise ValueError (or InvalidArgumentError): If ``query_points`` or ``observations`` have \\\n rank less than two, or they have unequal shape in any but their last dimension.\n \"\"\"\n tf.debugging.assert_rank_at_least(self.query_points, 2)\n tf.debugging.assert_rank_at_least(self.observations, 2)\n\n if 0 in (self.query_points.shape[-1], self.observations.shape[-1]):\n raise ValueError(\n f\"query_points and observations cannot have dimension 0, got shapes\"\n f\" {self.query_points.shape} and {self.observations.shape}.\"\n )\n\n if (\n self.query_points.shape[:-1] != self.observations.shape[:-1]\n # can't check dynamic shapes, so trust that they're ok (if not, they'll fail later)\n and None not in self.query_points.shape[:-1]\n ):\n raise ValueError(\n f\"Leading shapes of query_points and observations must match. Got shapes\"\n f\" {self.query_points.shape}, {self.observations.shape}.\"\n )\n\n def __add__(self, rhs: Dataset) -> Dataset:\n r\"\"\"\n Return the :class:`Dataset` whose query points are the result of concatenating the\n `query_points` in each :class:`Dataset` along the zeroth axis, and the same for the\n `observations`. For example:\n\n >>> d1 = Dataset(\n ... tf.constant([[0.1, 0.2], [0.3, 0.4]]),\n ... tf.constant([[0.5, 0.6], [0.7, 0.8]])\n ... )\n >>> d2 = Dataset(tf.constant([[0.9, 1.0]]), tf.constant([[1.1, 1.2]]))\n >>> (d1 + d2).query_points\n \n >>> (d1 + d2).observations\n \n\n :param rhs: A :class:`Dataset` with the same shapes as this one, except in the zeroth\n dimension, which can have any size.\n :return: The result of concatenating the :class:`Dataset`\\ s.\n :raise InvalidArgumentError: If the shapes of the `query_points` in each :class:`Dataset`\n differ in any but the zeroth dimension. The same applies for `observations`.\n \"\"\"\n return Dataset(\n tf.concat([self.query_points, rhs.query_points], axis=0),\n tf.concat([self.observations, rhs.observations], axis=0),\n )\n\n def __len__(self) -> tf.Tensor:\n \"\"\"\n :return: The number of query points, or equivalently the number of observations.\n \"\"\"\n return tf.shape(self.observations)[0]\n\n def __deepcopy__(self, memo: dict[int, object]) -> Dataset:\n return self\n\n def astuple(self) -> tuple[TensorType, TensorType]:\n \"\"\"\n **Note:** Unlike the standard library function `dataclasses.astuple`, this method does\n **not** deepcopy the attributes.\n\n :return: A 2-tuple of the :attr:`query_points` and :attr:`observations`.\n \"\"\"\n return self.query_points, self.observations\n\n\ndef check_and_extract_fidelity_query_points(\n query_points: TensorType, max_fidelity: Optional[int] = None\n) -> tuple[TensorType, TensorType]:\n \"\"\"Check whether the final column of a tensor is close enough to ints\n to be reasonably considered to represent fidelities.\n\n The final input column of multi-fidelity data should be a reference to\n the fidelity of the query point. We cannot have mixed type tensors, but\n we can check that thhe final column values are suitably close to integers.\n\n :param query_points: Data to check final column of.\n :raise: ValueError: If there are not enough columns to be multifidelity data\n :raise InvalidArgumentError: If any value in the final column is far from an integer\n :return: Query points without fidelity column\n and the fidelities of each of the query points\n \"\"\"\n # Check we have sufficient columns\n if query_points.shape[-1] < 2:\n raise ValueError(\n \"Query points do not have enough columns to be multifidelity,\"\n f\" need at least 2, got {query_points.shape[1]}\"\n )\n input_points = query_points[..., :-1]\n fidelity_col = query_points[..., -1:]\n # Check fidelity column values are close to ints\n tf.debugging.assert_equal(\n tf.round(fidelity_col),\n fidelity_col,\n message=\"Fidelity column should be float(int), but got a float that\"\n \" was not close to an int\",\n )\n # Check fidelity column values are non-negative\n\n tf.debugging.assert_non_negative(fidelity_col, message=\"Fidelity must be non-negative\")\n if max_fidelity is not None:\n max_input_fid = tf.reduce_max(fidelity_col)\n max_fidelity_float = tf.cast(max_fidelity, dtype=query_points.dtype)\n tf.debugging.assert_less_equal(\n max_input_fid,\n max_fidelity_float,\n message=(\n f\"Model only supports fidelities up to {max_fidelity},\"\n f\" but {max_input_fid} was passed\"\n ),\n )\n\n return input_points, fidelity_col\n\n\ndef split_dataset_by_fidelity(dataset: Dataset, num_fidelities: int) -> Sequence[Dataset]:\n \"\"\"Split dataset into individual datasets without fidelity information\n\n :param dataset: Dataset for which to split fidelities\n :param num_fidlities: Number of fidelities in the problem (not just dataset)\n :return: Ordered list of datasets with lowest fidelity at index 0 and highest at -1\n \"\"\"\n if num_fidelities < 1:\n raise ValueError(f\"Data must have 1 or more fidelities, got {num_fidelities}\")\n datasets = [get_dataset_for_fidelity(dataset, fidelity) for fidelity in range(num_fidelities)]\n return datasets\n\n\ndef get_dataset_for_fidelity(dataset: Dataset, fidelity: int) -> Dataset:\n \"\"\"Get a dataset with only the specified fidelity of data in\n\n :param dataset: The dataset from which to extract the single fidelity data\n :param fidelity: The fidelity to extract the data for\n :return: Dataset with a single fidelity and no fidelity column\n \"\"\"\n\n input_points, fidelity_col = check_and_extract_fidelity_query_points(\n dataset.query_points\n ) # [..., D], [..., 1]\n mask = fidelity_col == fidelity # [..., ]\n inds = tf.where(mask)[..., 0] # [..., ]\n inputs_for_fidelity = tf.gather(input_points, inds, axis=0) # [..., D]\n observations_for_fidelity = tf.gather(dataset.observations, inds, axis=0) # [..., 1]\n return Dataset(query_points=inputs_for_fidelity, observations=observations_for_fidelity)\n\n\ndef add_fidelity_column(query_points: TensorType, fidelity: int) -> TensorType:\n \"\"\"Add fidelity column to query_points without fidelity data\n\n :param query_points: query points without fidelity to add fidelity column to\n :param fidelity: fidelity to populate fidelity column with\n :return: TensorType of query points with fidelity column added\n \"\"\"\n fidelity_col = tf.ones((tf.shape(query_points)[-2], 1), dtype=query_points.dtype) * fidelity\n query_points_for_fidelity = tf.concat([query_points, fidelity_col], axis=-1)\n return query_points_for_fidelity\n","repo_name":"secondmind-labs/trieste","sub_path":"trieste/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":7924,"program_lang":"python","lang":"en","doc_type":"code","stars":190,"dataset":"github-code","pt":"3"}
+{"seq_id":"73981713362","text":"import os, fnx, jax, re\r\nimport haiku as hk\r\nfrom functools import partial\r\nimport jax.numpy as jnp\r\nimport numpy as np\r\n\r\ncolor_mean = np.asarray([0.485, 0.456, 0.406])\r\ncolor_std = np.asarray([0.229, 0.224, 0.225])\r\ndef preprocess(color):\r\n color = color / 255.0\r\n color = (color - color_mean) / color_std\r\n return color\r\n\r\nconfig = fnx.intercept.chain(\r\n fnx.intercept.replace(fnx.norm, fnx.layernorm),\r\n fnx.intercept.replace(fnx.act, jax.nn.gelu),\r\n fnx.config.pytorch,\r\n)\r\n\r\nclass Builder:\r\n def __init__(self, variant, patch_size, pos_embed_shape, url):\r\n self.encoder = vars(fnx.vit)[f\"vit_{variant}\"]\r\n self.patch_size = patch_size\r\n self.pos_embed_shape = pos_embed_shape\r\n self.url = url\r\n self.preprocess = preprocess\r\n\r\n @fnx.module(name=\"model\", is_unbound_method=True)\r\n def __call__(self, x):\r\n def model_fn(x):\r\n def replace(next_interceptor, func, args, kwargs, context):\r\n # 1. They don't use layerscale\r\n # 2. They don't have normalization in patch embedding\r\n if context.fullname.endswith(\"scale\") or context.fullname.endswith(\"patch_embed/norm\") or context.fullname.endswith(\"encode/norm\"):\r\n return args[0]\r\n else:\r\n return next_interceptor(func, args, kwargs)\r\n\r\n with config:\r\n with fnx.intercept.custom(replace):\r\n x = self.encoder(x, pos_embed_shape=self.pos_embed_shape, patch_size=self.patch_size, prefix_tokens=1)\r\n with fnx.scope(\"classifier\"):\r\n x = jnp.mean(x[:, 1:], axis=1)\r\n x = fnx.norm(x)\r\n x = fnx.linear(x, channels=1000, bias=True, name=\"logits\")\r\n x = jax.nn.softmax(x, axis=-1)\r\n return x\r\n\r\n file = fnx.pretrained.weights.download(self.url)\r\n weights = fnx.pretrained.weights.load_pytorch(file)\r\n\r\n # 3. They add an additional positional embedding onto class token, we add positional embedding only on image tokens\r\n pos_embed = weights[\"pos_embed\"]\r\n cls_token = weights[\"cls_token\"]\r\n weights[\"cls_token\"] = cls_token + pos_embed[:, :1, :]\r\n weights[\"pos_embed\"] = pos_embed[:, 1:, :].reshape((1, self.pos_embed_shape[0], self.pos_embed_shape[1], pos_embed.shape[-1]))\r\n\r\n model_fn = fnx.pretrained.weights.init(model_fn, weights, hints=[(\"attn/norm\", \"norm1\")])\r\n\r\n return model_fn(x)\r\n\r\nvit_large_patch14_196_eva_in22k_ft_in22k_in1k = Builder(\"large\", 14, (14, 14), \"https://huggingface.co/timm/eva_large_patch14_196.in22k_ft_in22k_in1k/blob/main/pytorch_model.bin\")\r\nvit_large_patch14_336_eva_in22k_ft_in22k_in1k = Builder(\"large\", 14, (24, 24), \"https://huggingface.co/timm/eva_large_patch14_336.in22k_ft_in22k_in1k/blob/main/pytorch_model.bin\")\r\n\r\nvit_large_patch14_196_eva_in22k_ft_in1k = Builder(\"large\", 14, (14, 14), \"https://huggingface.co/timm/eva_large_patch14_196.in22k_ft_in1k/blob/main/pytorch_model.bin\")\r\nvit_large_patch14_336_eva_in22k_ft_in1k = Builder(\"large\", 14, (24, 24), \"https://huggingface.co/timm/eva_large_patch14_336.in22k_ft_in1k/blob/main/pytorch_model.bin\")\r\n","repo_name":"fferflo/fnx","sub_path":"fnx/pretrained/timm/vit.py","file_name":"vit.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"31296628193","text":"from __future__ import division, absolute_import\n\nfrom zope.interface.verify import verifyObject\n\ntry:\n from twisted.conch.ssh import channel\n from twisted.conch.ssh.address import SSHTransportAddress\n from twisted.conch.ssh.transport import SSHServerTransport\n from twisted.conch.ssh.service import SSHService\n from twisted.internet import interfaces\n from twisted.internet.address import IPv4Address\n from twisted.test.proto_helpers import StringTransport\n skipTest = None\nexcept ImportError:\n skipTest = 'Conch SSH not supported.'\n SSHService = object\nfrom twisted.trial import unittest\nfrom twisted.python.compat import intToBytes\n\n\nclass MockConnection(SSHService):\n \"\"\"\n A mock for twisted.conch.ssh.connection.SSHConnection. Record the data\n that channels send, and when they try to close the connection.\n\n @ivar data: a L{dict} mapping channel id #s to lists of data sent by that\n channel.\n @ivar extData: a L{dict} mapping channel id #s to lists of 2-tuples\n (extended data type, data) sent by that channel.\n @ivar closes: a L{dict} mapping channel id #s to True if that channel sent\n a close message.\n \"\"\"\n\n def __init__(self):\n self.data = {}\n self.extData = {}\n self.closes = {}\n\n\n def logPrefix(self):\n \"\"\"\n Return our logging prefix.\n \"\"\"\n return \"MockConnection\"\n\n\n def sendData(self, channel, data):\n \"\"\"\n Record the sent data.\n \"\"\"\n self.data.setdefault(channel, []).append(data)\n\n\n def sendExtendedData(self, channel, type, data):\n \"\"\"\n Record the sent extended data.\n \"\"\"\n self.extData.setdefault(channel, []).append((type, data))\n\n\n def sendClose(self, channel):\n \"\"\"\n Record that the channel sent a close message.\n \"\"\"\n self.closes[channel] = True\n\n\n\ndef connectSSHTransport(service, hostAddress=None, peerAddress=None):\n \"\"\"\n Connect a SSHTransport which is already connected to a remote peer to\n the channel under test.\n\n @param service: Service used over the connected transport.\n @type service: L{SSHService}\n\n @param hostAddress: Local address of the connected transport.\n @type hostAddress: L{interfaces.IAddress}\n\n @param peerAddress: Remote address of the connected transport.\n @type peerAddress: L{interfaces.IAddress}\n \"\"\"\n transport = SSHServerTransport()\n transport.makeConnection(StringTransport(\n hostAddress=hostAddress, peerAddress=peerAddress))\n transport.setService(service)\n\n\n\nclass ChannelTests(unittest.TestCase):\n \"\"\"\n Tests for L{SSHChannel}.\n \"\"\"\n\n skip = skipTest\n\n def setUp(self):\n \"\"\"\n Initialize the channel. remoteMaxPacket is 10 so that data is able\n to be sent (the default of 0 means no data is sent because no packets\n are made).\n \"\"\"\n self.conn = MockConnection()\n self.channel = channel.SSHChannel(conn=self.conn,\n remoteMaxPacket=10)\n self.channel.name = b'channel'\n\n\n def test_interface(self):\n \"\"\"\n L{SSHChannel} instances provide L{interfaces.ITransport}.\n \"\"\"\n self.assertTrue(verifyObject(interfaces.ITransport, self.channel))\n\n\n def test_init(self):\n \"\"\"\n Test that SSHChannel initializes correctly. localWindowSize defaults\n to 131072 (2**17) and localMaxPacket to 32768 (2**15) as reasonable\n defaults (what OpenSSH uses for those variables).\n\n The values in the second set of assertions are meaningless; they serve\n only to verify that the instance variables are assigned in the correct\n order.\n \"\"\"\n c = channel.SSHChannel(conn=self.conn)\n self.assertEqual(c.localWindowSize, 131072)\n self.assertEqual(c.localWindowLeft, 131072)\n self.assertEqual(c.localMaxPacket, 32768)\n self.assertEqual(c.remoteWindowLeft, 0)\n self.assertEqual(c.remoteMaxPacket, 0)\n self.assertEqual(c.conn, self.conn)\n self.assertIsNone(c.data)\n self.assertIsNone(c.avatar)\n\n c2 = channel.SSHChannel(1, 2, 3, 4, 5, 6, 7)\n self.assertEqual(c2.localWindowSize, 1)\n self.assertEqual(c2.localWindowLeft, 1)\n self.assertEqual(c2.localMaxPacket, 2)\n self.assertEqual(c2.remoteWindowLeft, 3)\n self.assertEqual(c2.remoteMaxPacket, 4)\n self.assertEqual(c2.conn, 5)\n self.assertEqual(c2.data, 6)\n self.assertEqual(c2.avatar, 7)\n\n\n def test_str(self):\n \"\"\"\n Test that str(SSHChannel) works gives the channel name and local and\n remote windows at a glance..\n \"\"\"\n self.assertEqual(\n str(self.channel), '')\n self.assertEqual(\n str(channel.SSHChannel(localWindow=1)),\n '')\n\n\n def test_bytes(self):\n \"\"\"\n Test that bytes(SSHChannel) works, gives the channel name and\n local and remote windows at a glance..\n\n \"\"\"\n self.assertEqual(\n self.channel.__bytes__(),\n b'')\n self.assertEqual(\n channel.SSHChannel(localWindow=1).__bytes__(),\n b'')\n\n\n def test_logPrefix(self):\n \"\"\"\n Test that SSHChannel.logPrefix gives the name of the channel, the\n local channel ID and the underlying connection.\n \"\"\"\n self.assertEqual(self.channel.logPrefix(), 'SSHChannel channel '\n '(unknown) on MockConnection')\n\n\n def test_addWindowBytes(self):\n \"\"\"\n Test that addWindowBytes adds bytes to the window and resumes writing\n if it was paused.\n \"\"\"\n cb = [False]\n def stubStartWriting():\n cb[0] = True\n self.channel.startWriting = stubStartWriting\n self.channel.write(b'test')\n self.channel.writeExtended(1, b'test')\n self.channel.addWindowBytes(50)\n self.assertEqual(self.channel.remoteWindowLeft, 50 - 4 - 4)\n self.assertTrue(self.channel.areWriting)\n self.assertTrue(cb[0])\n self.assertEqual(self.channel.buf, b'')\n self.assertEqual(self.conn.data[self.channel], [b'test'])\n self.assertEqual(self.channel.extBuf, [])\n self.assertEqual(self.conn.extData[self.channel], [(1, b'test')])\n\n cb[0] = False\n self.channel.addWindowBytes(20)\n self.assertFalse(cb[0])\n\n self.channel.write(b'a'*80)\n self.channel.loseConnection()\n self.channel.addWindowBytes(20)\n self.assertFalse(cb[0])\n\n\n def test_requestReceived(self):\n \"\"\"\n Test that requestReceived handles requests by dispatching them to\n request_* methods.\n \"\"\"\n self.channel.request_test_method = lambda data: data == b''\n self.assertTrue(self.channel.requestReceived(b'test-method', b''))\n self.assertFalse(self.channel.requestReceived(b'test-method', b'a'))\n self.assertFalse(self.channel.requestReceived(b'bad-method', b''))\n\n\n def test_closeReceieved(self):\n \"\"\"\n Test that the default closeReceieved closes the connection.\n \"\"\"\n self.assertFalse(self.channel.closing)\n self.channel.closeReceived()\n self.assertTrue(self.channel.closing)\n\n\n def test_write(self):\n \"\"\"\n Test that write handles data correctly. Send data up to the size\n of the remote window, splitting the data into packets of length\n remoteMaxPacket.\n \"\"\"\n cb = [False]\n def stubStopWriting():\n cb[0] = True\n # no window to start with\n self.channel.stopWriting = stubStopWriting\n self.channel.write(b'd')\n self.channel.write(b'a')\n self.assertFalse(self.channel.areWriting)\n self.assertTrue(cb[0])\n # regular write\n self.channel.addWindowBytes(20)\n self.channel.write(b'ta')\n data = self.conn.data[self.channel]\n self.assertEqual(data, [b'da', b'ta'])\n self.assertEqual(self.channel.remoteWindowLeft, 16)\n # larger than max packet\n self.channel.write(b'12345678901')\n self.assertEqual(data, [b'da', b'ta', b'1234567890', b'1'])\n self.assertEqual(self.channel.remoteWindowLeft, 5)\n # running out of window\n cb[0] = False\n self.channel.write(b'123456')\n self.assertFalse(self.channel.areWriting)\n self.assertTrue(cb[0])\n self.assertEqual(data, [b'da', b'ta', b'1234567890', b'1', b'12345'])\n self.assertEqual(self.channel.buf, b'6')\n self.assertEqual(self.channel.remoteWindowLeft, 0)\n\n\n def test_writeExtended(self):\n \"\"\"\n Test that writeExtended handles data correctly. Send extended data\n up to the size of the window, splitting the extended data into packets\n of length remoteMaxPacket.\n \"\"\"\n cb = [False]\n def stubStopWriting():\n cb[0] = True\n # no window to start with\n self.channel.stopWriting = stubStopWriting\n self.channel.writeExtended(1, b'd')\n self.channel.writeExtended(1, b'a')\n self.channel.writeExtended(2, b't')\n self.assertFalse(self.channel.areWriting)\n self.assertTrue(cb[0])\n # regular write\n self.channel.addWindowBytes(20)\n self.channel.writeExtended(2, b'a')\n data = self.conn.extData[self.channel]\n self.assertEqual(data, [(1, b'da'), (2, b't'), (2, b'a')])\n self.assertEqual(self.channel.remoteWindowLeft, 16)\n # larger than max packet\n self.channel.writeExtended(3, b'12345678901')\n self.assertEqual(data, [(1, b'da'), (2, b't'), (2, b'a'),\n (3, b'1234567890'), (3, b'1')])\n self.assertEqual(self.channel.remoteWindowLeft, 5)\n # running out of window\n cb[0] = False\n self.channel.writeExtended(4, b'123456')\n self.assertFalse(self.channel.areWriting)\n self.assertTrue(cb[0])\n self.assertEqual(data, [(1, b'da'), (2, b't'), (2, b'a'),\n (3, b'1234567890'), (3, b'1'), (4, b'12345')])\n self.assertEqual(self.channel.extBuf, [[4, b'6']])\n self.assertEqual(self.channel.remoteWindowLeft, 0)\n\n\n def test_writeSequence(self):\n \"\"\"\n Test that writeSequence is equivalent to write(''.join(sequece)).\n \"\"\"\n self.channel.addWindowBytes(20)\n self.channel.writeSequence(map(intToBytes, range(10)))\n self.assertEqual(self.conn.data[self.channel], [b'0123456789'])\n\n\n def test_loseConnection(self):\n \"\"\"\n Tesyt that loseConnection() doesn't close the channel until all\n the data is sent.\n \"\"\"\n self.channel.write(b'data')\n self.channel.writeExtended(1, b'datadata')\n self.channel.loseConnection()\n self.assertIsNone(self.conn.closes.get(self.channel))\n self.channel.addWindowBytes(4) # send regular data\n self.assertIsNone(self.conn.closes.get(self.channel))\n self.channel.addWindowBytes(8) # send extended data\n self.assertTrue(self.conn.closes.get(self.channel))\n\n\n def test_getPeer(self):\n \"\"\"\n L{SSHChannel.getPeer} returns the same object as the underlying\n transport's C{getPeer} method returns.\n \"\"\"\n peer = IPv4Address('TCP', '192.168.0.1', 54321)\n connectSSHTransport(service=self.channel.conn, peerAddress=peer)\n\n self.assertEqual(SSHTransportAddress(peer), self.channel.getPeer())\n\n\n def test_getHost(self):\n \"\"\"\n L{SSHChannel.getHost} returns the same object as the underlying\n transport's C{getHost} method returns.\n \"\"\"\n host = IPv4Address('TCP', '127.0.0.1', 12345)\n connectSSHTransport(service=self.channel.conn, hostAddress=host)\n\n self.assertEqual(SSHTransportAddress(host), self.channel.getHost())\n","repo_name":"wistbean/learn_python3_spider","sub_path":"stackoverflow/venv/lib/python3.6/site-packages/twisted/conch/test/test_channel.py","file_name":"test_channel.py","file_ext":"py","file_size_in_byte":12000,"program_lang":"python","lang":"en","doc_type":"code","stars":14022,"dataset":"github-code","pt":"3"}
+{"seq_id":"37360646769","text":"import luigi\nfrom time import time\nimport random \nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport os\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.neighbors import NearestNeighbors\n\ndef data_check(df):\n df.info()\n df.describe()\n df.isnull().sum() #count number of null values in each column \n df.fillna(0) #fix null values (e.g. Replace with 0, mean, etc)\n\ndef moviesDataIngestion():\n movies = pd.read_csv('ml-latest/movies.csv', header=0)\n movies.to_csv('movies.csv', index=False)\n return movies\n\ndef moviesDataIngestionCheck(movies):\n data_check(movies)\n movies.to_csv('moviesChecked.csv', index=False)\n return movies\n\ndef ratingsDataIngestion():\n ratings = pd.read_csv('ml-latest/ratings.csv', header=0)\n ratings.to_csv('ratings.csv', index=False)\n return ratings\n\ndef ratingsDataIngestionCheck(ratings):\n data_check(ratings)\n ratings.to_csv('ratingsChecked.csv', index=False)\n return ratings\n\ndef linksDataIngestion():\n links = pd.read_csv('ml-latest/links.csv', header=0)\n links.to_csv('links.csv', index=False)\n return links\n\ndef linksDataIngestionCheck(links):\n data_check(links)\n links.to_csv('linksChecked.csv', index=False)\n return links\n\ndef tagsDataIngestion():\n tags = pd.read_csv('ml-latest/tags.csv', header=0)\n tags.to_csv('tags.csv', index=False)\n return tags\n\ndef tagsDataIngestionCheck(tags):\n data_check(tags)\n tags.to_csv('tagsChecked.csv', index=False)\n return tags\n\ndef genome_tagsDataIngestion():\n genome_tags = pd.read_csv('ml-latest/genome-tags.csv', header=0)\n genome_tags.to_csv('genome_tags.csv', index=False)\n return genome_tags\n\ndef genome_tagsDataIngestionCheck(genome_tags):\n data_check(genome_tags)\n genome_tags.to_csv('genome_tagsChecked.csv', index=False)\n return genome_tags\n\ndef genome_scoresDataIngestion():\n genome_scores = pd.read_csv('ml-latest/genome-scores.csv', header=0)\n genome_scores.to_csv('genome_scores.csv', index=False)\n return genome_scores\n\ndef genome_scoresDataIngestionCheck(genome_scores):\n data_check(genome_scores)\n genome_scores.to_csv('genome_scoresChecked.csv', index=False)\n return genome_scores\n\ndef DataPreProcessing1(movies, genome_score, genome_tags): \n\n data = pd.merge(movies, genome_scores, how='inner', on='movieId')\n data = pd.merge(data, genome_tags, how='inner', on='tagId')\n data = data.sort_values(['movieId','tagId'])\n \n #data = data[:1]\n \n data.to_csv('preProcessedData1.csv', index=False)\n \n return data\n\ndef DataPreProcessing1Check(data1):\n \n #data quality check: each movieId should have relevance scores for all the tags\n sample = random.sample(list(data1.movieId.unique()),100)\n temp = [list(data1.loc[data1.movieId==i].tagId) for i in sample]\n compare = [i==[j for j in range(1,len(data1.tagId.unique())+1)] for i in temp]\n \n if False in compare: \n raise Exception(\"Data quality check failed: Not all movieId's have relevance scores for all the tags\")\n \n #check dimension of df\n if len(data1) != (len(data1.movieId.unique())*len(data1.tagId.unique())): \n raise Exception(\"Data quality check failed: Incorrect dataframe dimension\")\n\n data1.to_csv('preProcessedData1Checked.csv', index=False)\n \n return data1 \n\ndef DataPreProcessing2a(data1checked): \n \n relevance = np.asarray(data1checked.relevance)\n data1a = np.reshape(relevance,(len(data1checked.movieId.unique()),len(data1checked.tagId.unique())))\n \n #X = X[1:]\n\n pd.DataFrame(data1a).to_csv('preProcessedData2a.csv', index=False)\n\n return data1a \n\ndef DataPreProcessing2aCheck(data1Checked, data2a):\n\n #data quality check: mean score for each movie should equal to the ones calculated pre-transformation\n if max(abs(np.array(list(data1Checked.groupby(data1Checked.movieId).relevance.mean())) - np.array(list(data2a.mean(axis=1))))) > 0.001:\n raise Exception(\"Data quality check failed: Mean score for each movie not equal to the ones pre-transformation\")\n \n #check dimension of df\n if data2a.shape != (len(data1Checked.movieId.unique()), len(data1Checked.tagId.unique())):\n raise Exception(\"Data quality check failed: Incorrect dataframe dimension\")\n\n pd.DataFrame(data2a).to_csv('DataPreProcessing2aChecked.csv', index=False)\n \n return data2a\n\ndef DataPreProcessing2b(data1Checked): \n \n data2b = data1Checked.sort_values(by=['tagId','movieId'])[:len(data1Checked.movieId.unique())] \n \n #data2 = data2[1:]\n \n data2b.to_csv('preProcessedData2b.csv', index=False)\n \n return data2b\n\ndef DataPreProcessing2bCheck(data1Checked, data2b):\n\n #check dimension of df\n if len(data2b) != len(data1Checked.movieId.unique()):\n raise Exception(\"Data quality check failed: Incorrect number of rows (movies)\")\n\n data2b.to_csv('DataPreProcessing2bChecked.csv', index=False)\n \n return data2b \n\ndef TrainKMeans(movies, data2aChecked, data2bChecked):\n\n n_clusters = 10 # number of clusters\n n = 20 # number of movies to show in each cluster \n \n kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(data2aChecked)\n \n labels = pd.DataFrame(kmeans.labels_)\n labels['movieId'] = labels.index\n labels.reset_index(level=0, inplace=False)\n labels.columns = ['cluster', 'movieId']\n labels2 = pd.merge(labels, movies, how='left', on='movieId')\n labels2.title.fillna(labels2.movieId, inplace=True)\n labels2.genres.fillna(labels2.movieId, inplace=True)\n \n clusters = labels2.groupby('cluster').groups\n clusters2 = dict()\n \n for k in clusters: \n clusters2[k] = clusters[k][:n]\n \n clusters2 = pd.DataFrame(clusters2)\n clusters2.index += 1\n \n for i in clusters2.columns: \n clusters2[i] = clusters2[i].map(data2bChecked.title)\n \n clusters2.columns = ['cluster '+str(i) for i in range(0,n_clusters)]\n \n print(clusters2)\n \n pd.DataFrame(clusters2).to_csv('clusters.csv', index=False)\n\ndef TrainNearestNeighbors(data2aChecked, data2bChecked):\n\n n = 20 # number of movies to show in each cluster \n\n neighbors = NearestNeighbors(n_neighbors=n+1, algorithm='ball_tree').fit(data2aChecked)\n distances, indices = neighbors.kneighbors(data2aChecked)\n indices = np.delete(indices,0,1)\n distances = np.delete(distances,0,1)\n\n indices2 = pd.DataFrame(np.transpose(indices))\n indices2.index += 1\n \n for i in indices2.columns: \n indices2[i] = indices2[i].map(data2bChecked.title)\n \n indices2.columns = [data2bChecked.title]\n \n most_similar_movies = indices2\n \n print(most_similar_movies)\n \n pd.DataFrame(most_similar_movies).to_csv('most_similar_movies.csv', index=False)\n\nif __name__ == '__main__':\n \n #Data ingestion and check \n movies = moviesDataIngestion()\n moviesChecked = moviesDataIngestionCheck(movies) \n ratings = ratingsDataIngestion()\n ratingsChecked = ratingsDataIngestionCheck(ratings)\n links = linksDataIngestion()\n linksChecked = linksDataIngestionCheck(links)\n tags = tagsDataIngestion()\n tagsChecked = tagsDataIngestionCheck(tags)\n genome_tags = genome_tagsDataIngestion()\n genome_tagsChecked = genome_tagsDataIngestionCheck(genome_tags)\n genome_scores = genome_scoresDataIngestion()\n genome_scoresChecked = genome_scoresDataIngestionCheck(genome_scores)\n \n #Data processing \n data1 = DataPreProcessing1(moviesChecked, genome_scoresChecked, genome_tagsChecked)\n data1Checked = DataPreProcessing1Check(data1)\n data2a = DataPreProcessing2a(data1Checked)\n data2b = DataPreProcessing2b(data1Checked) \n data2aChecked = DataPreProcessing2aCheck(data1Checked, data2a)\n data2bChecked = DataPreProcessing2bCheck(data1Checked, data2b)\n \n #Modeling \n TrainKMeans(moviesChecked, data2aChecked, data2bChecked)\n \n TrainNearestNeighbors(data2aChecked, data2bChecked)\n \n \n \n","repo_name":"user2017/luigi_movielens","sub_path":"movielens_modular.py","file_name":"movielens_modular.py","file_ext":"py","file_size_in_byte":7996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2352179611","text":"# imports\n\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup as bs\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport datetime as dt\n\n# scrape all function\ndef scrape_all():\n \n executable_path = {'executable_path': ChromeDriverManager().install()}\n browser = Browser('chrome', **executable_path, headless=False)\n\n \n \n \n \n news_title, news_paragraph = scrape_news(browser)\n\n mars_data = {\n 'news_title': news_title,\n 'news_paragraph': news_paragraph,\n 'featured_image': scrape_feature_img(browser),\n 'facts': scrape_facts(browser),\n 'hemispheres': scrape_hemispheres(browser),\n 'last_updated': dt.datetime.now()\n }\n\n browser.quit()\n\n return mars_data\n\n\n\n\n# scrape mars news page\ndef scrape_news(browser):\n url = 'https://redplanetscience.com/'\n browser.visit(url)\n\n\n\n browser.is_element_present_by_css('div.list_text', wait_time=1)\n html = browser.html\n news_soup = bs(html, 'html.parser')\n\n slide_elem = news_soup.select_one('div.list_text')\n\n news_title = slide_elem.find('div', class_='content_title').get_text()\n\n news_p = slide_elem.find('div', class_='article_teaser_body').get_text()\n\n return news_title, news_p\n\n# scrape featured image page\ndef scrape_feature_img(browser):\n url = 'https://spaceimages-mars.com'\n browser.visit(url)\n full_image_link = browser.find_by_tag('button')\n full_image_link[1].click()\n html = browser.html\n img_soup = bs(html, 'html.parser')\n img_url_rel = img_soup.find('img', class_='fancybox-image').get('src')\n img_url = f'https://spaceimages-mars.com/{img_url_rel}'\n return img_url\n\n# scrape facts page\ndef scrape_facts(browser):\n url = 'https://galaxyfacts-mars.com/'\n browser.visit(url)\n html = browser.html\n fact_soup = bs(html, 'html.parser')\n facts_loc = fact_soup.find('div', class_='diagram mt-4')\n fact_table = facts_loc.find('table')\n facts = ''\n facts += str(fact_table)\n return facts\n\n# scrape hemispheres page\ndef scrape_hemispheres(browser):\n url = 'https://marshemispheres.com/'\n browser.visit(url)\n # create a list to hold the images and title\n hemisphere_image_urls = []\n for i in range(4):\n hemisphereInfo = {}\n browser.find_by_css('a.product-item img')[i].click()\n sample = browser.links.find_by_text('Sample').first\n hemisphereInfo['img_url'] = sample['href']\n hemisphereInfo['title'] =browser.find_by_css('h2.title').text\n hemisphere_image_urls.append(hemisphereInfo)\n browser.back()\n return hemisphere_image_urls\n\n# stop the webdriver\n \n\n# set up as a flask app\n\nif __name__ == \"__main__\":\n print(scrape_all())","repo_name":"danskan/web-scraping-challenge","sub_path":"scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27173038262","text":"'''\nCreated on Aug 5, 2013\n\n@author: justin\n'''\nimport wx, wx.lib.customtreectrl, wx.gizmos\ntry:\n import treemixin \nexcept ImportError:\n from wx.lib.mixins import treemixin\n\noverview = treemixin.__doc__\n\n\nclass TreeListCtrl(treemixin.VirtualTree, treemixin.DragAndDrop, \n treemixin.ExpansionState, wx.gizmos.TreeListCtrl):\n\n '''holds the domain objects that are shown in the different\n tree controls. Each domain object is simply a two-tuple consisting of\n a label and a list of child tuples, i.e. ([list of labels], [list of child tuples]). \n ''' \n \n def __init__(self, *args, **kwargs):\n self.items = []\n self.itemCounter = 0\n kwargs['style'] = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT\n super(TreeListCtrl, self).__init__(*args, **kwargs)\n \n self.AddColumn('Column 0')\n self.AddColumn('Column 1')\n self.AddColumn('Column 2')\n\n self.AddChild((), [\"value1\", \"value2\", \"value3\"])\n self.AddChild((), [\"value8\", \"value2\", \"value3\"])\n self.AddChild((1,), [\"value7\", \"value5\", \"value6\"])\n self.AddChild((1,), [\"value4\", \"value5\", \"value6\"])\n self.RefreshItems()\n \n #Helper functions\n def GetItem(self, indices):\n text, children = 'Hidden root', self.items\n for index in indices:\n text, children = children[index]\n return text, children\n\n def GetText(self, indices, column):\n return self.GetItem(indices)[0][column]\n\n def GetChildren(self, indices):\n return self.GetItem(indices)[1]\n\n def GetChildrenCount(self, indices):\n return len(self.GetChildren(indices))\n\n def AddChild(self, indicies, labels):\n \"\"\"\n Adds a child to the tree\n \"\"\"\n self.GetChildren(indicies).append((labels, []))\n \n def RemoveChild(self, indicies):\n \"\"\"\n Removes a child from the tree\n \"\"\"\n pass\n\n #For moving items around\n def MoveItem(self, itemToMoveIndex, newParentIndex):\n itemToMove = self.GetItem(itemToMoveIndex)\n newParentChildren = self.GetChildren(newParentIndex)\n newParentChildren.append(itemToMove)\n oldParentChildren = self.GetChildren(itemToMoveIndex[:-1])\n oldParentChildren.remove(itemToMove)\n #overloading for virtual tree\n def OnGetItemText(self, indices, column=0):\n return self.GetText(indices, column)\n\n def OnGetChildrenCount(self, indices):\n return self.GetChildrenCount(indices)\n\n #Overloading for drag and drop\n def OnDrop(self, dropTarget, dragItem):\n dropIndex = self.GetIndexOfItem(dropTarget)\n #dropText = self.GetText(dropIndex,0)\n dragIndex = self.GetIndexOfItem(dragItem)\n #dragText = self.GetText(dragIndex)\n\n self.MoveItem(dragIndex, dropIndex)\n self.RefreshItems()\n\n\n# class VirtualTreeListCtrl(DemoTreeMixin, wx.gizmos.TreeListCtrl):\n# def __init__(self, *args, **kwargs):\n# kwargs['style'] = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT\n# super(VirtualTreeListCtrl, self).__init__(*args, **kwargs)\n# self.AddColumn('Column 0')\n# self.AddColumn('Column 1')\n# self.AddColumn('Column 2')\n# \n# self.model.AddChild((), [\"value1\", \"value2\", \"value3\"])\n# self.model.AddChild((), [\"value1\", \"value2\", \"value3\"])\n# self.model.AddChild((1,), [\"value4\", \"value5\", \"value6\"])\n# self.model.AddChild((1,), [\"value4\", \"value5\", \"value6\"])\n# self.RefreshItems()\n# # def OnGetItemText(self, indices, column=0):\n# # # Return a different label depending on column.\n# # return '%s, column %d'%\\\n# # (super(VirtualTreeListCtrl, self).OnGetItemText(indices), column)\n# \n# def GetIndicesOfSelectedItems(self):\n# \n# if self.GetSelections():\n# return [self.GetIndexOfItem(item) for item in self.GetSelections()]\n# else:\n# return [()]\n\nclass TreeModel(object):\n ''' TreeModel holds the domain objects that are shown in the different\n tree controls. Each domain object is simply a two-tuple consisting of\n a label and a list of child tuples, i.e. (label, [list of child tuples]). \n '''\n def __init__(self, *args, **kwargs):\n self.items = []\n self.itemCounter = 0\n super(TreeModel, self).__init__(*args, **kwargs)\n\n def GetItem(self, indices):\n text, children = 'Hidden root', self.items\n for index in indices:\n text, children = children[index]\n return text, children\n\n def GetText(self, indices):\n return self.GetItem(indices)[0]\n\n def GetChildren(self, indices):\n return self.GetItem(indices)[1]\n\n def GetChildrenCount(self, indices):\n return len(self.GetChildren(indices))\n\n def SetChildrenCount(self, indices, count):\n children = self.GetChildren(indices)\n while len(children) > count:\n children.pop()\n while len(children) < count:\n children.append(('item %d'%self.itemCounter, []))\n self.itemCounter += 1\n\n def MoveItem(self, itemToMoveIndex, newParentIndex):\n itemToMove = self.GetItem(itemToMoveIndex)\n newParentChildren = self.GetChildren(newParentIndex)\n newParentChildren.append(itemToMove)\n oldParentChildren = self.GetChildren(itemToMoveIndex[:-1])\n oldParentChildren.remove(itemToMove)\n\n\nclass DemoTreeMixin(treemixin.VirtualTree, treemixin.DragAndDrop, \n treemixin.ExpansionState):\n def __init__(self, *args, **kwargs):\n self.model = kwargs.pop('treemodel')\n self.log = kwargs.pop('log')\n super(DemoTreeMixin, self).__init__(*args, **kwargs)\n self.CreateImageList()\n\n def CreateImageList(self):\n size = (16, 16)\n self.imageList = wx.ImageList(*size)\n for art in wx.ART_FOLDER, wx.ART_FILE_OPEN, wx.ART_NORMAL_FILE:\n self.imageList.Add(wx.ArtProvider.GetBitmap(art, wx.ART_OTHER, \n size))\n self.AssignImageList(self.imageList)\n\n def OnGetItemText(self, indices):\n return self.model.GetText(indices)\n\n def OnGetChildrenCount(self, indices):\n return self.model.GetChildrenCount(indices)\n\n def OnGetItemFont(self, indices):\n # Show how to change the item font. Here we use a small font for\n # items that have children and the default font otherwise.\n if self.model.GetChildrenCount(indices) > 0:\n return wx.SMALL_FONT\n else:\n return super(DemoTreeMixin, self).OnGetItemFont(indices)\n\n def OnGetItemTextColour(self, indices):\n # Show how to change the item text colour. In this case second level\n # items are coloured red and third level items are blue. All other\n # items have the default text colour.\n if len(indices) % 2 == 0:\n return wx.RED\n elif len(indices) % 3 == 0:\n return wx.BLUE\n else:\n return super(DemoTreeMixin, self).OnGetItemTextColour(indices)\n\n def OnGetItemBackgroundColour(self, indices):\n # Show how to change the item background colour. In this case the\n # background colour of each third item is green.\n if indices[-1] == 2:\n return wx.GREEN\n else: \n return super(DemoTreeMixin, \n self).OnGetItemBackgroundColour(indices)\n\n def OnGetItemImage(self, indices, which):\n # Return the right icon depending on whether the item has children.\n if which in [wx.TreeItemIcon_Normal, wx.TreeItemIcon_Selected]:\n if self.model.GetChildrenCount(indices):\n return 0\n else:\n return 2\n else:\n return 1\n\n def OnDrop(self, dropTarget, dragItem):\n dropIndex = self.GetIndexOfItem(dropTarget)\n dropText = self.model.GetText(dropIndex)\n dragIndex = self.GetIndexOfItem(dragItem)\n dragText = self.model.GetText(dragIndex)\n self.log.write('drop %s %s on %s %s'%(dragText, dragIndex,\n dropText, dropIndex))\n self.model.MoveItem(dragIndex, dropIndex)\n self.GetParent().RefreshItems()\n\n\nclass VirtualTreeListCtrl(DemoTreeMixin, wx.gizmos.TreeListCtrl):\n def __init__(self, *args, **kwargs):\n kwargs['style'] = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT\n super(VirtualTreeListCtrl, self).__init__(*args, **kwargs)\n self.AddColumn('Column 0')\n self.AddColumn('Column 1')\n\n def OnGetItemText(self, indices, column=0):\n # Return a different label depending on column.\n return '%s, column %d'%\\\n (super(VirtualTreeListCtrl, self).OnGetItemText(indices), column)\n\n def GetIndicesOfSelectedItems(self):\n\n if self.GetSelections():\n return [self.GetIndexOfItem(item) for item in self.GetSelections()]\n else:\n return [()]\n\n def RefreshItems(self):\n\n self.RefreshItems()\n self.UnselectAll()\n \n\nclass TreeNotebook(wx.Notebook):\n def __init__(self, *args, **kwargs):\n treemodel = kwargs.pop('treemodel')\n log = kwargs.pop('log')\n super(TreeNotebook, self).__init__(*args, **kwargs)\n self.trees = []\n for class_, title in [(VirtualTreeListCtrl, 'TreeListCtrl')]:\n tree = class_(self, treemodel=treemodel, log=log)\n self.trees.append(tree)\n self.AddPage(tree, title)\n self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged)\n\n def OnPageChanged(self, event):\n oldTree = self.GetPage(event.OldSelection)\n newTree = self.GetPage(event.Selection)\n newTree.RefreshItems()\n newTree.SetExpansionState(oldTree.GetExpansionState())\n event.Skip()\n\n def GetIndicesOfSelectedItems(self):\n tree = self.trees[self.GetSelection()]\n if tree.GetSelections():\n return [tree.GetIndexOfItem(item) for item in tree.GetSelections()]\n else:\n return [()]\n\n def RefreshItems(self):\n tree = self.trees[self.GetSelection()]\n tree.RefreshItems()\n tree.UnselectAll()\n\n\nclass TestPanel(wx.Panel):\n def __init__(self, parent, log):\n self.log = log\n super(TestPanel, self).__init__(parent)\n self.treemodel = TreeModel()\n self.CreateControls()\n self.LayoutControls()\n\n def CreateControls(self):\n self.notebook = TreeNotebook(self, treemodel=self.treemodel, \n log=self.log)\n self.label = wx.StaticText(self, label='Number of children: ')\n self.childrenCountCtrl = wx.SpinCtrl(self, value='0', max=10000)\n self.button = wx.Button(self, label='Update children')\n self.button.Bind(wx.EVT_BUTTON, self.OnEnter)\n\n def LayoutControls(self):\n hSizer = wx.BoxSizer(wx.HORIZONTAL)\n options = dict(flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=2)\n hSizer.Add(self.label, **options)\n hSizer.Add(self.childrenCountCtrl, 2, **options)\n hSizer.Add(self.button, **options)\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(self.notebook, 1, wx.EXPAND)\n sizer.Add(hSizer, 0, wx.EXPAND)\n self.SetSizer(sizer)\n\n def OnEnter(self, event):\n indicesList = self.notebook.GetIndicesOfSelectedItems()\n newChildrenCount = self.childrenCountCtrl.GetValue()\n for indices in indicesList:\n text = self.treemodel.GetText(indices)\n oldChildrenCount = self.treemodel.GetChildrenCount(indices)\n self.log.write('%s %s now has %d children (was %d)'%(text, indices,\n newChildrenCount, oldChildrenCount))\n self.treemodel.SetChildrenCount(indices, newChildrenCount)\n self.notebook.RefreshItems()\n\n\ndef runTest(frame, nb, log):\n win = TestPanel(nb, log)\n return win\n\n\nif __name__ == '__main__':\n import sys, os, run\n run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])\n\n","repo_name":"Paladiamors/ProjectManager","sub_path":"src/UI/treeListCtrl.py","file_name":"treeListCtrl.py","file_ext":"py","file_size_in_byte":12039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39634506304","text":"class Solution:\n def climbStairs(self, n: int) -> int:\n hm = dict()\n def aux(n):\n if n == 0:\n return 1\n if n < 0:\n return 0\n res = (aux(n-1) if n-1 not in hm else hm[n-1]) + (aux(n-2) if n-2 not in hm else hm[n-2])\n hm[n] = res\n return res\n return aux(n)","repo_name":"pyl/leetcode","sub_path":"70-climbing-stairs/70-climbing-stairs.py","file_name":"70-climbing-stairs.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6528754314","text":"\n# coding: utf-8\n\n# In[3]:\n\nimport numpy as np\nimport sys\nimport argparse\nfrom seq2seqLSTM import translate\nfrom seq2seqLSTM import learning\nfrom seq2seqLSTM import save_model\n\n\n# In[1]:\n\nparser = argparse.ArgumentParser(description='Enlish to French translator.')\nsubparsers = parser.add_subparsers()\nstranslate = subparsers.add_parser('translate', aliases=['t'])\nstranslate.add_argument('text', help='English text file')\nstranslate.set_defaults(which='translate')\n\nlearn = subparsers.add_parser('learn', aliases=['l'])\nlearn.add_argument('X', help='learning input (English)')\nlearn.add_argument('Y', help='learning output (French)')\nlearn.add_argument('-vs', '--vocab_size', help='vocabulary size (default=0 if vocab.txt should stay unchanged)', type=int, default=0)\nlearn.add_argument('-lcn', '--layer_cell_number', help='number of cells in a layer', type=int, default=1000)\nlearn.set_defaults(which='learn')\n\nprint(\"Reading input\")\nargs=vars(parser.parse_args())\n\nif args['which'] == 'translate':\n translate(args['text'])\nelse:\n print(\"Learning - train & test\")\n model=learning(args['X'], args['Y'], args['vocab_size'], args['layer_cell_number'])\n print(\"Saving model\")\n save_model(model)\n\n","repo_name":"nikola-sp/projekatNIZ","sub_path":"seq2seqLSTM_start.py","file_name":"seq2seqLSTM_start.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18124349012","text":"#investigate scrapy\n#async efficiency\n# https://sempioneer.com/python-for-seo/asynchronous-web-scraping-python/#How_Is_Asychronous_Web_Scraping_Different_To_Using_Python_Requests\n# import aiohttp\n# import asyncio\nimport requests\nimport lxml\nimport chardet\nimport sys\nimport datetime\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nfrom forex_python.converter import CurrencyRates\n\n# Iterate through all pages of search results\ndef iterateSeach():\n page = requests.get(baseURL)\n soup = BeautifulSoup(page.content, 'lxml')\n lastPage = int(soup.find('ul',class_=\"paging-middle centertext\").find_all('li')[-1].text.strip())\n print(lastPage)\n print(\"-Iterating through search pages...\")\n thePage = lastPage\n for i in range(0,thePage,1):\n print(\"*SCRAPING PAGE \" + str(i))\n URL = \"https://www.pinkbike.com/buysell/list/?region=3&page=\" + str(i) + \"&category=2\"\n scrapeSearchPage(URL)\n\n# Iterates through all pages of search results - Starting From End\ndef iterateSeachBtoF():\n page = requests.get(baseURL)\n soup = BeautifulSoup(page.content, 'lxml')\n lastPage = int(soup.find('ul',class_=\"paging-middle centertext\").find_all('li')[-1].text.strip())\n print(lastPage)\n print(\"-Iterating through search pages BtoF...\")\n thePage = lastPage\n for i in range(thePage,0,-1):\n print(\"*SCRAPING PAGE \" + str(i))\n URL = \"https://www.pinkbike.com/buysell/list/?region=3&page=\" + str(i) + \"&category=2\"\n scrapeSearchPage(URL)\n\n#Iterates through all bikes in a result page \ndef scrapeSearchPage(URL):\n page = requests_session.get(URL)\n soup = BeautifulSoup(page.content, 'html.parser')\n bikeElements = soup.find_all('div', class_=\"bsitem\")\n # lastPage = int(soup.find('ul',class_=\"paging-middle centertext\").find_all('li')[-1].text.strip())\n for bikeElement in bikeElements:\n scrapeElement(bikeElement)\n \n#Scrapes a single bike element, its details, and adds it to the database\ndef scrapeElement(bikeElement):\n global theCount\n if theCount == 20000:\n sys.exit(\"Firebase Limit Reached: 20000 Writes\")\n pbID = bikeElement.get('id').replace(\"csid\",\"\")\n print(\" ID: \" + pbID)\n bikeURL = \"https://www.pinkbike.com/buysell/\" + pbID\n\n bikeData = bikeElement.find_all('td')\n bikeSpecs = bikeData[1].find_all(\"div\")\n #check for all necessary information\n if len(bikeSpecs) < 7:\n print(\"Missing Specs Data\")\n return\n title = bikeData[1].a.string\n condition = bikeSpecs[1].text.split(\":\",1)[1].strip()\n frameSize = bikeSpecs[2].text.split(\":\",1)[1].strip()\n wheelSize = bikeSpecs[3].text.split(\":\",1)[1].replace('\"',\"\").strip()\n material = bikeSpecs[4].text.split(\":\",1)[1].strip()\n frontTravel = bikeSpecs[5].text.split(\":\",1)[1].strip()\n rearTravel = bikeSpecs[6].text.split(\":\",1)[1].strip()\n\n bikeInfo = bikeData[1].find_all(\"tr\")\n location = bikeInfo[0].text.strip()\n # seller = bikeInfo[1].text.split(\":\")[1].split(\"|\")[0].replace(\"Outside+\", \"\").strip()\n seller = bikeInfo[1].a.text.replace(\"Outside+\", \"\").strip()\n price = int(bikeInfo[2].text.replace(\"$\",\"\").split(\" \")[0].strip())\n #if price is in CAD, rough conversion to USD\n if((bikeInfo[2].text.replace(\"$\",\"\").split(\" \")[1].strip()) == \"CAD\"):\n price = price * exchangeRate\n price = int(price)\n\n #get listing data from Bike's page by pbID\n bikePage = requests_session.get(bikeURL)\n bikeSoup = BeautifulSoup(bikePage.content, 'lxml') \n bikeDetails = bikeSoup.find_all(\"div\",class_=\"buysell-details-column\")[1].get_text(strip=True, separator='\\n').splitlines()\n postDate = datetime.strptime((bikeDetails[1].split(\" \")[0].replace(\"-\",\" \")), '%b %d %Y')\n repostDate = datetime.strptime((bikeDetails[3].split(\" \")[0].replace(\"-\",\" \")), '%b %d %Y')\n if(bikeDetails[5] == \"since\"):\n forSale = bikeDetails[6]\n viewCount = int(bikeDetails[8].replace(\",\", \"\"))\n watchCount = int(bikeDetails[10].replace(\",\", \"\"))\n else:\n forSale = bikeDetails[5]\n viewCount = int(bikeDetails[7].replace(\",\", \"\"))\n watchCount = int(bikeDetails[9].replace(\",\", \"\"))\n\n \n #publish data as json to fireStore\n doc_ref = db.collection(u'trailEnduro').document(pbID)\n doc_ref.set({\n u'title': title,\n u'location': location,\n u'seller': seller,\n u'price_usd': price,\n u'spec': {\n u'condition': condition,\n u'frame_size': frameSize,\n u'wheel_size': wheelSize,\n u'material': material,\n u'front_travel': frontTravel,\n u'rear_travel': rearTravel\n },\n u'listing': {\n u'post_date': postDate,\n u'repost_date': repostDate,\n u'for_sale': forSale,\n u'view_count': viewCount,\n u'watch_count': watchCount,\n },\n })\n theCount += 1\n # print(\" \" + theCount)\n\n# def scrapeListing():\n# print(\"Scraping Listing\")\n\n# def publishData():\n# print(\"Publishing Data\")\n\ndef assessTitle(title):\n print(\"Assessing Title\")\n\n# Get CAD to USD conversion rate\ndef getExchange():\n global exchangeRate\n exchangeRate = CurrencyRates().get_rate('CAD', 'USD')\n exchangeRate = round(exchangeRate, 2)\n\nif __name__ == '__main__':\n cred = credentials.Certificate('/Users/seangaffney/Documents/Code/pb-analytics-616-firebase-adminsdk-5rw79-c5f78deb10.json')\n firebase_admin.initialize_app(cred)\n db = firestore.client()\n\n #URL = 'https://www.pinkbike.com/buysell/list/?lat=37.6806&lng=-122.4073&distance=101&category=2' #local Trail\n baseURL = 'https://www.pinkbike.com/buysell/list/?region=3&category=2' #All Trail\n theCount = 0\n requests_session = requests.Session()\n getExchange()\n\n iterateSeachBtoF()\n # scrapeSearchPage(baseURL)","repo_name":"seangaff/pb-analytics","sub_path":"Scraper/pbScraper.py","file_name":"pbScraper.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27741360011","text":"import re\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.options import Options\nfrom bs4 import BeautifulSoup\nimport sqlite3 # We sometimes need to directly query the database\nimport random\nimport requests # Check for 404s and other undesireables\n\nfrom tomodb import Database # local\n\ndriver = webdriver.Firefox() # You can change this to `webdriver.Chrome`, but results may vary\n\ndef get_curseforge_id(url: str, driver: webdriver = None):\n \"\"\"Scrapes the provided CurseForge page for the project identifier.\"\"\"\n driver.get(url)\n is_404 = \"\"\n try:\n is_404 = driver.find_element(By.CSS_SELECTOR, \".error-page__message--not-found\")\n except:\n pass\n if not is_404:\n tag = driver.find_element(By.CSS_SELECTOR, \"div.mb-3:nth-child(2) > div:nth-child(1) > span:nth-child(2)\") # Complicated CSS selector to extract the project ID from the HTML; this could change in the future\n return tag.get_attribute(\"innerHTML\"), True\n else:\n print(\"Bad URL: \" + url)\n return None, False\n\n\ndb = Database(\"urls.sqlite3\")\n\ndef store_project_ids(driver: webdriver = None):\n conn = sqlite3.connect(\"./urls.sqlite3\")\n c = conn.cursor()\n c.execute(\"SELECT title, curseforge_url FROM mods WHERE curseforge_project_id IS NULL\")\n rows = c.fetchall()\n \n for row in rows:\n title, url = row\n id, is_live = get_curseforge_id(url, driver=driver)\n if is_live:\n try:\n db.update({\"title\": title, \"curseforge_url\": url, \"curseforge_project_id\": id})\n time.sleep(random.randint(2, 4))\n except sqlite3.IntegrityError:\n print(f\"IntegrityError: {{'title': title, 'curseforge_url': url, 'curseforge_project_id': id}}\")\n else:\n pass\n \n conn.commit()\n\n conn.close()\n\nstore_project_ids(driver=driver)\n\n# We're all done here folks\ndriver.quit()\ndb.close()\n","repo_name":"tomodachi94/wikidata-things","sub_path":"scripts/scrape-curseforge/curseforge_urls_to_project_ids.py","file_name":"curseforge_urls_to_project_ids.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10303827846","text":"''' 10989번 수 정렬하기 3 '''\nimport sys\ninput = sys.stdin.readline\nN = int(input().rstrip())\n\ncount = [0] * 10001\nfor _ in range(N):\n temp = int(input().rstrip())\n count[temp] += 1 # Increase the value in the index.\n\n\nfor i in range(len(count)): # Check the sort information recorded on the list.\n for j in range(count[i]):\n print(i) # Print each index as many times as it appears.","repo_name":"kingbj940429/Coding_Test_Solution","sub_path":"beak_joon/b_10989.py","file_name":"b_10989.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38050655895","text":"from django.shortcuts import render\nfrom .models import Product\nfrom .forms import ProductForm\n# Create your views here.\n\ndef product_create_view1(request):\n\tform = ProductForm() #request.POST or None\n\terror = []\n\tprint(request.POST)\n\tif request.method == 'POST':\n\t\ttitle = request.POST.get('title')\n\t\tif not title:\n\t\t\terror.append(\"title reuqired\")\n\t\tform = ProductForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tobj = form.save()\n\t\t\tform = ProductForm()\n\t\telse:\n\t\t\tprint(\"error\")\t\n\tcontext = {\n\t'form': form\n\t}\n\t# context = {\n\t# \t\"title\": obj.title,\n\t# \t\"description\" : obj.description\n\t# }\n\treturn render(request,\"products/product_create.html\",context)\n\n\n\n\n# def product_detail_view(request):\n# \tobj=Product.objects.get(id=1)\n# \t# context = {\n# \t# \t\"title\": obj.title,\n# \t# \t\"description\" : obj.description\n# \t# }\n# \tcontext = {\n# \t\t'object' : obj\n# \t}\n# \treturn render(request,\"products/product_detail.html\",context)","repo_name":"AbdulrahmanSerhan/html_login_form","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36193840442","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom libs.promiseLib import PromiseLib, CategoryLib\nfrom libs.statusLib import APILib\n\nfrom helpers import Collection\n\nimport json\n\n# Create your views here.\ndef index(request):\n promiseLib = PromiseLib()\n topPromises = promiseLib.get_top_promises()\n response = {'topPromises':topPromises,'status':{'name':'paul'}}\n return render(request,'pinarayi_meter/index.html',response)\n\ndef promise(request, uuid):\n reqObj = Collection()\n reqObj.uuid = uuid\n\n promiseLib =PromiseLib()\n promiseDetails = promiseLib.get_promise(reqObj)\n response = {'promiseDetails':promiseDetails}\n return render(request,'pinarayi_meter/promise.html',response)\n\ndef statusApi(request):\n reqObj = Collection()\n apiLib = APILib()\n response = apiLib.getPromiseStatus(reqObj)\n return JsonResponse(response)\n\ndef categoryApi(request):\n reqObj = Collection()\n reqObj.categoryList = request.GET.getlist('categoryList')\n reqObj.type = request.GET.dict()['type']\n categoryLib = CategoryLib()\n response = categoryLib.get_promise_by_category(reqObj)\n return JsonResponse(response)\n\ndef thirtFivePoint(request):\n reqObj = Collection()\n reqObj.category = 'Thirty Five Point Programme'\n promiseLib = PromiseLib()\n response = {}\n response['promises'] = promiseLib.get_promise_by_category(reqObj)\n return render(request, 'pinarayi_meter/thirty_five.html',response)\n\ndef category(request,category_name):\n reqObj = Collection()\n response = {}\n reqObj.category_name = category_name\n promiseLib = PromiseLib()\n response = promiseLib.get_promise_by_category_list(reqObj)\n \n return render(request, 'pinarayi_meter/category.html',response)\n\n","repo_name":"ashwineaso/pinarayi-meter","sub_path":"pinarayiMeter/pinarayi_meter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"8846436789","text":"from random import randint\n\nnames_string = input('Input the name of guests seperating them by a comma: ')\nnames = names_string.split( ', ' )\n\ndef banker_roulette(a):\n i = randint( 0, len( a ) -1 )\n payee = a[i]\n return f'{payee} is going to buy the meal today!'\n\n\nif __name__ == '__main__':\n result = banker_roulette(names)\n print(result)","repo_name":"reubendevries/100-days-of-code-python","sub_path":"day-04/banker_roulette.py","file_name":"banker_roulette.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14941360853","text":"#define a function that take list of words as a argument and this function will return the reverse of every element in that list\n#exapmle: ['abc','tuv','xyz']\n#output: ['cba','vut','zyx']\n\nList = ['abc', 'tuv', 'xyz']\nprint(f\"List is: {List}\")\n\ndef reverse_List(list):\n element = []\n for i in list:\n element.append(i[::-1])\n return element\nprint(f\"reverse of each element in list: {reverse_List(List)}\")","repo_name":"BeenashPervaiz/Command_Line_Task","sub_path":"list_Ex3.py","file_name":"list_Ex3.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1578993074","text":"import sys\nimport cgitb\n\nfrom PyQt5.QtWidgets import QWidget, QApplication, QTreeWidgetItem, QCheckBox, QSpinBox, QDateTimeEdit, QComboBox\nfrom PyQt5.QtCore import pyqtSignal, QDateTime\nfrom ui_py.ui_setting import Ui_widget_setting\n\n\nclass Setting(QWidget, Ui_widget_setting):\n signal_core_number = pyqtSignal(int)\n signal_suspend_status = pyqtSignal(bool)\n signal_waiting_min = pyqtSignal(int)\n signal_schedule_status = pyqtSignal(bool)\n signal_cancel_plan = pyqtSignal(str)\n signal_change_language = pyqtSignal(str)\n\n def __init__(self, suspend, cores, schedule_status, waiting_min, language):\n super().__init__()\n self.setupUi(self)\n # ----------init variable------------\n self.suspend = suspend\n self.cores = cores\n self.schedule_status = schedule_status\n self.waiting_min = waiting_min\n self.language = language\n self.language_list = ['English', 'Chinese']\n # ----------init widget--------------\n self.label_suspend = QTreeWidgetItem()\n self.checkbox_suspend = QCheckBox()\n self.label_cores = QTreeWidgetItem()\n self.edit_cores = QSpinBox()\n self.label_plan = QTreeWidgetItem()\n self.edit_plan_datetime = QDateTimeEdit()\n self.label_about = QTreeWidgetItem()\n self.label_language = QTreeWidgetItem()\n self.combobox_lauguage = QComboBox()\n # -----------init function----------------\n self.ui_set()\n self.btn()\n self.init_data_show()\n self.self_translate(language)\n self.show()\n\n def btn(self):\n self.tree_setting.itemClicked.connect(self.effect_expand)\n self.tree_setting.itemChanged.connect(self.enable_schedule)\n self.combobox_lauguage.activated.connect(self.choose_language)\n self.checkbox_suspend.stateChanged.connect(self.change_suspend_status)\n\n def ui_set(self):\n # style\n self.setStyleSheet(\"QSpinBox{border:1.5px solid #778899;border-radius:4px; padding:2px 2px}\"\n \"QDateTimeEdit{border:1.5px solid #778899;border-radius:4px; padding:2px 2px}\")\n self.tree_setting.setColumnWidth(0, 180)\n self.tree_setting.expandItem(self.tree_setting.topLevelItem(0))\n self.tree_setting.topLevelItem(1).setCheckState(1, 0)\n self.edit_cores.setMaximumSize(50, 25)\n self.edit_cores.setContentsMargins(0, 4, 0, 0)\n self.edit_cores.setMinimum(1)\n self.edit_cores.setMaximum(132)\n self.label_plan.setDisabled(True)\n self.edit_plan_datetime.setMaximumSize(135, 28)\n self.edit_plan_datetime.setDisabled(True)\n self.combobox_lauguage.setMaximumSize(135, 28)\n self.combobox_lauguage.addItems(self.language_list)\n self.combobox_lauguage.setCurrentText(self.language)\n\n # function\n self.add_tree_item(0, self.label_suspend, \"暂停队列\", self.checkbox_suspend)\n self.add_tree_item(0, self.label_cores, \"使用核数\", self.edit_cores)\n self.add_tree_item(1, self.label_plan, \"计划启动于\", self.edit_plan_datetime)\n self.add_tree_item(2, self.label_language, \"语言选择\", self.combobox_lauguage)\n\n def add_tree_item(self, top_level_index, label, label_name, input_edit):\n label.setText(0, label_name)\n self.tree_setting.topLevelItem(top_level_index).addChild(label)\n self.tree_setting.setItemWidget(label, 1, input_edit)\n\n def effect_expand(self, item, column):\n index = self.tree_setting.indexOfTopLevelItem(item)\n if index >= 0:\n if item.isExpanded():\n item.setExpanded(False)\n else:\n item.setExpanded(True)\n\n def enable_schedule(self, item, column):\n index = self.tree_setting.indexOfTopLevelItem(item)\n if index == 1:\n check_state = item.checkState(column)\n self.schedule_status = bool(check_state)\n self.label_plan.setDisabled(2 - check_state)\n self.edit_plan_datetime.setEnabled(check_state)\n item.setExpanded(2 - check_state)\n self.reset_date_edit()\n self.suspend = self.checkbox_suspend.checkState()\n self.checkbox_suspend.setCheckState(self.suspend + check_state)\n self.checkbox_suspend.setDisabled(check_state)\n\n def init_data_show(self):\n self.edit_cores.setValue(self.cores)\n self.checkbox_suspend.setCheckState(self.suspend * 2)\n if self.schedule_status:\n self.tree_setting.topLevelItem(1).setCheckState(1, 2)\n self.label_plan.setDisabled(False)\n self.edit_plan_datetime.setEnabled(True)\n self.tree_setting.topLevelItem(1).setExpanded(True)\n waiting_seconds = self.waiting_min * 60\n self.edit_plan_datetime.setDisplayFormat(\"yyyy/MM/dd HH:mm\")\n self.edit_plan_datetime.setDateTime(QDateTime.currentDateTime().addSecs(waiting_seconds))\n else:\n self.reset_date_edit()\n\n def reset_date_edit(self):\n self.edit_plan_datetime.setDisplayFormat(\"yyyy/MM/dd HH:mm\")\n self.edit_plan_datetime.setDateTime(QDateTime.currentDateTime())\n self.edit_plan_datetime.setMinimumDateTime(QDateTime.currentDateTime())\n self.edit_plan_datetime.setMaximumDateTime(QDateTime.currentDateTime().addDays(5))\n self.edit_plan_datetime.setCalendarPopup(True)\n\n def change_suspend_status(self, status):\n self.suspend = bool(status)\n\n def plan_start(self):\n curr_time = QDateTime.currentSecsSinceEpoch()\n schedule_time = self.edit_plan_datetime.dateTime().toSecsSinceEpoch()\n self.waiting_min = int(round((schedule_time - curr_time) / 60, 0))\n print('waiting min', self.waiting_min)\n self.signal_waiting_min.emit(self.waiting_min)\n\n def choose_language(self):\n language = self.combobox_lauguage.currentText()\n self.signal_change_language.emit(language)\n self.self_translate(language)\n\n def self_translate(self, language):\n if language == 'English':\n self.label_suspend.setText(0, 'Suspend next')\n self.label_cores.setText(0, 'Threads number')\n self.label_plan.setText(0, 'Scheduled in')\n self.label_language.setText(0, 'Language')\n else:\n self.label_suspend.setText(0, \"暂停队列\")\n self.label_cores.setText(0, \"使用核数\")\n self.label_plan.setText(0, \"计划启动于\")\n self.label_language.setText(0, \"语言选择\")\n self.retranslateUi(self)\n\n def closeEvent(self, event):\n self.cores = self.edit_cores.value()\n suspend_status = self.checkbox_suspend.checkState()\n self.signal_core_number.emit(self.cores)\n self.signal_schedule_status.emit(self.schedule_status)\n if self.schedule_status:\n self.plan_start()\n else:\n self.signal_cancel_plan.emit(' ')\n self.signal_suspend_status.emit(bool(suspend_status))\n self.close()\n\n\nif __name__ == '__main__':\n cgitb.enable(format='text')\n app = QApplication(sys.argv)\n suspend = True\n cores = 24\n schedule_status = True\n waiting_min = 60\n language = 'English'\n myWin = Setting(suspend, cores, schedule_status, waiting_min, language)\n app.installEventFilter(myWin)\n sys.exit(app.exec_())\n\n\n","repo_name":"qweaxdzsc/fluent_add_on","sub_path":"fluent_queue/func/func_setting.py","file_name":"func_setting.py","file_ext":"py","file_size_in_byte":7369,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"40203123878","text":"# import datetime\n# from dateutil.relativedelta import relativedelta\nimport re\n\nfrom django.core.exceptions import ValidationError\nfrom django.forms import DateInput, ModelForm\nimport django_filters\n\nfrom students.models import Student\n\n\nclass StudentBaseForm(ModelForm):\n class Meta:\n model = Student\n fields = [\n 'first_name',\n 'last_name',\n 'age',\n 'birthdate',\n 'email',\n 'phone_number',\n 'enroll_date',\n 'graduate_date',\n 'graduate_date2',\n 'group',\n ]\n # fields = '__all__'\n widgets = {\n 'birthdate': DateInput(attrs={'type': 'date'}),\n 'enroll_date': DateInput(attrs={'type': 'date'}),\n 'graduate_date': DateInput(attrs={'type': 'date'}),\n 'graduate_date2': DateInput(attrs={'type': 'date'}),\n }\n\n\n @staticmethod\n def normalize_name(value):\n return value.lower().capitalize()\n\n\n def clean_first_name(self):\n first_name = self.cleaned_data['first_name']\n result = self.normalize_name(first_name)\n return result\n\n\n def clean_last_name(self):\n last_name = self.cleaned_data['last_name']\n result = self.normalize_name(last_name)\n return result\n\n\n def clean_phone_number(self):\n if self.cleaned_data['phone_number']:\n return re.sub('[^+0-9]','',self.cleaned_data['phone_number'])\n else: \n return self.cleaned_data['phone_number']\n # result = re.sub('[^+0-9]','',self.cleaned_data['phone_number'])\n # if Student.objects.filter(phone_number=result).exclude(id=self.instance.id).exists():\n # raise ValidationError('The phone number already exists. Please try another one.')\n # return result\n\n\n # def clean_birthdate(self):\n # birthdate = self.cleaned_data['birthdate']\n # age = datetime.datetime.now().year - birthdate.year\n # if age < 18:\n # raise ValidationError('Age should be greater than 18 y.o.')\n #\n # return birthdate\n\n\n def clean(self):\n enroll_date = self.cleaned_data['enroll_date']\n graduate_date = self.cleaned_data['graduate_date']\n if enroll_date > graduate_date:\n raise ValidationError('Enroll date coudnt be greater than graduate date!')\n\n\nclass StudentCreateForm(StudentBaseForm):\n pass\n\n\nclass StudentUpdateForm(StudentBaseForm):\n class Meta(StudentBaseForm.Meta):\n exclude = ['age']\n # class Meta(StudentBaseForm.Meta):\n # fields = [\n # 'first_name',\n # 'last_name',\n # 'age',\n # 'birthdate',\n # 'email',\n # 'phone_number',\n # 'enroll_date',\n # 'graduate_date',\n # 'graduate_date2',\n # 'group',\n # ]\n\n\nclass StudentsFilter(django_filters.FilterSet):\n class Meta:\n model = Student\n fields = {\n 'age': ['gt', 'lt',],\n 'first_name': ['exact', 'icontains'],\n 'last_name': ['exact', 'startswith'],\n 'group': ['exact'],\n }\n","repo_name":"RenKus96/test_django","sub_path":"students/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32696773031","text":"import math, os\nimport numpy as np\nfrom collections import deque\n\n\nimport pkg_resources\nimport rclpy\nfrom rclpy.node import Node\nfrom std_msgs.msg import String\n\nfrom tqdm import tqdm\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\n# from pykdtree.kdtree import KDTree\nfrom scipy.spatial import cKDTree as KDTree\n\ntry:\n #### for debug ######\n from HDMap import HDmap\n from pcc.main import PCC_algorithm\n from coord_tranform import Coord_Trans\nexcept:\n ##### for release #####\n from trajectory_planner.pcc.main import PCC_algorithm\n from trajectory_planner.HDMap import HDmap\n from trajectory_planner.coord_tranform import Coord_Trans\n\nfrom ad_map_server_py.ad_map_server import CoordTrans\nfrom ament_index_python.packages import get_package_share_directory\npackage_share_directory = get_package_share_directory('trajectory_planner')\n\nclass OfflinePCC(Node):\n # add some contraint here\n def __init__(self, start_point, end_point):\n super().__init__('offline_pcc')\n self._map = HDmap()\n\n self.pcc_file_dir = os.path.join(package_share_directory, \"offline_pcc.txt\")\n self.global_plan_dir = os.path.join(package_share_directory, \"global_routing.txt\")\n\n ## trucksim coord start and end\n self.coord_trans = CoordTrans(-225.151904, -6337.384475)\n self.start_point = self.coord_trans.trucksim_to_map(start_point[0], start_point[1]) +[start_point[2]]\n self.end_point = self.coord_trans.trucksim_to_map(end_point[0], end_point[1]) + [end_point[2]]\n ## map coord \n\n self._global_plan = self._map.GlobalPlanner_waypoints(self.start_point, self.end_point)\n self._speed_profile = deque(maxlen=1000000000000000000)\n self._x = deque(maxlen=1000000000000000000)\n self.speed_planner = PCC_algorithm()\n self.grad_x = None\n self.grad = None\n\n ## reference/target speed for pcc\n self.target_speed = 16.67\n \n def pcc_peak_adjust(self, pcc_x, pcc_v, grad_x, grad):\n def find_peak(array_like):\n peak_indexs_up = []\n peak_indexs_down = []\n peak_indexs = []\n direction_signal = 0\n for i in range(len(array_like)-1):\n #down peak\n if array_like[i]array_like[i-1]:\n if direction_signal != -1:\n peak_indexs_up.append(i)\n peak_indexs.append(i)\n direction_signal = -1\n else:\n pass\n return peak_indexs_up, peak_indexs_down, peak_indexs\n \n pcc_v_peaks_up, pcc_v_peaks_down, pcc_v_peaks = find_peak(pcc_v)\n grad_peaks_up, grad_peaks_down, grad_peaks = find_peak(grad)\n\n def find_nearest_pcc_peak(peaks_list, peak):\n dist = 10000\n candidiate_idx = 0\n for i in range(len(peaks_list)):\n if dist>(peaks_list[i]-peak)**2:\n dist = (peaks_list[i]-peak)**2\n candidiate_idx = i\n return candidiate_idx\n\n previous_pcc_peak_idx = 0\n for i in range(0, len(grad_peaks)):\n ## find nearest pcc peak comparing to grad peak\n choosen_pcc_peaks = pcc_v_peaks_up\n for itm in grad_peaks_up:\n if grad_peaks[i] == itm:\n choosen_pcc_peaks = pcc_v_peaks_down\n break\n this_pcc_peak_idx = find_nearest_pcc_peak(choosen_pcc_peaks, grad_peaks[i])\n for j in range(len(pcc_v_peaks)):\n if pcc_v_peaks[j] == choosen_pcc_peaks[this_pcc_peak_idx]:\n this_pcc_peak_idx = j\n break\n leng_old = pcc_x[pcc_v_peaks[this_pcc_peak_idx]]-pcc_x[pcc_v_peaks[previous_pcc_peak_idx]]\n leng_new = grad_x[grad_peaks[i]]-pcc_x[pcc_v_peaks[previous_pcc_peak_idx]]\n this_peak_offset = grad_x[grad_peaks[i]] - pcc_x[pcc_v_peaks[this_pcc_peak_idx]]\n pcc_x[pcc_v_peaks[this_pcc_peak_idx]] = grad_x[grad_peaks[i]]\n for idx in range(pcc_v_peaks[previous_pcc_peak_idx]+1, pcc_v_peaks[this_pcc_peak_idx]):\n pcc_x[idx] = leng_new*(pcc_x[idx]-pcc_x[pcc_v_peaks[previous_pcc_peak_idx]])/leng_old + pcc_x[pcc_v_peaks[previous_pcc_peak_idx]]\n for idxp in range(pcc_v_peaks[this_pcc_peak_idx]+1, len(pcc_x)):\n pcc_x[idxp] = pcc_x[idxp]+this_peak_offset\n previous_pcc_peak_idx = this_pcc_peak_idx\n return pcc_x, pcc_v\n\n \n def compute_speed_profile(self):\n def compute_distance(loc1, loc2):\n return math.sqrt((loc1[0]-loc2[0])**2+(loc1[1]-loc2[1])**2)\n grad_x, grad = self._map.query_gradient(self._global_plan)\n self.grad_x = grad_x\n self.grad = grad\n step_size = 10000\n grad_x_step = np.array(grad_x[::step_size])\n grad_step = grad[::step_size]\n pcc_v, pcc_x = self.speed_planner.pcc_speed_planner(grad_x_step.tolist(), grad_step, self.target_speed)\n pcc_x, pcc_v = self.pcc_peak_adjust(pcc_x, pcc_v, grad_x_step, grad_step)\n for v, x in zip(pcc_v, pcc_x):\n self._speed_profile.append(v)\n self._x.append(x)\n\n def write_planning_result(self):\n with open(self.pcc_file_dir, \"w\") as f:\n for i in range(len(self._speed_profile)):\n write_line = str(self._x[i])+\" \"+str(self._speed_profile[i])+\"\\n\"\n f.write(write_line)\n\n def write_global_plan(self):\n with open(self.global_plan_dir, \"w\") as f:\n for i in range(len(self._global_plan)):\n write_line = str(self._global_plan[i][0])+\" \"+str(self._global_plan[i][1])+\" \"+str(self._global_plan[i][2])+\" \"+str(self.grad_x[i])+\" \"+str(self.grad[i])+\"\\n\"\n f.write(write_line)\n\nclass PCCReader(object):\n def __init__(self, pcc_file_dir = None, global_plan_dir = None):\n\n if pcc_file_dir == None:\n self.pcc_file_dir = os.path.join(package_share_directory, \"offline_pcc.txt\")\n else:\n self.pcc_file_dir = pcc_file_dir\n\n if global_plan_dir == None:\n self.global_plan_dir = os.path.join(package_share_directory, \"global_routing.txt\")\n else:\n self.global_plan_dir = global_plan_dir\n\n self.f = open(self.pcc_file_dir, \"r\")\n self.gp_f = open(self.global_plan_dir)\n self.pcc_x = []\n self.pcc_v = []\n self.global_plan=None\n self.x = []\n self.y = []\n self.z = []\n self.grad = []\n self.xp = []\n self.xy_xp = None\n self.tree = None\n self.xy_numpy = []\n self._process_file()\n\n \n ## no use if there is offline planned routing, use read global plan instead\n def set_global_plan(self, global_plan, xp):\n self.global_plan = global_plan\n self.xp = xp\n x = []\n y = []\n step = 1000\n for waypoint in self.global_plan:\n x.append(waypoint[0])\n y.append(waypoint[1])\n self.xy_xp = interpolate.interp2d(x[0:-1:step], y[0:-1:step], self.xp[0:-1:step])\n \n def read_global_plan(self):\n return self.global_plan\n\n def _process_file(self):\n ## offline pcc speed profile\n for line in self.f.readlines():\n processed_line = line.split( )\n self.pcc_x.append(float(processed_line[0]))\n self.pcc_v.append(float(processed_line[1]))\n self.pcc_v_f = interpolate.interp1d(self.pcc_x, self.pcc_v, kind='linear', fill_value='extrapolate')\n\n ## offline routing\n step = 100\n for line in self.gp_f.readlines():\n processed_line = line.split( )\n self.x.append(float(processed_line[0]))\n self.y.append(float(processed_line[1]))\n self.z.append(float(processed_line[2]))\n self.xp.append(float(processed_line[3]))\n self.xy_numpy.append([float(processed_line[0]),float(processed_line[1])])\n self.xy_numpy = np.array(self.xy_numpy[::step])\n self.xp = np.array(self.xp[::step])\n self.tree = KDTree(self.xy_numpy)\n\n\n def qurey_x(self, x, y):\n dist, ind = self.tree.query([x,y], k=1)\n return self.xp[ind]\n\n def qurey_v(self, x):\n return self.pcc_v_f(x)\n\n def plot_road_grad(self):\n x_node = self.xp\n h_node = self.z\n dx_elem = np.array([x_node[i+1] - x_node[i] for i in range(0, len(x_node)-1, 1000)])\n dh_elem = np.array([h_node[i+1] - h_node[i] for i in range(0, len(h_node)-1, 1000)])\n Ge = dh_elem/dx_elem\n x = np.array([x_node[i] for i in range(0, len(x_node)-1, 1000)])\n plt.plot(x, Ge)\n plt.show()\n\nclass PCCReader2(Node):\n def __init__(self, pcc_file_dir = None):\n super().__init__('pcc_reader')\n if pcc_file_dir == None:\n self.pcc_file_dir = os.path.join(package_share_directory, \"new_pcc_result.txt\")\n else:\n self.pcc_file_dir = pcc_file_dir\n\n self.f = open(self.pcc_file_dir, \"r\")\n self.coord_trans = CoordTrans()\n self.pcc_v = []\n self.x = []\n self.y = []\n self.z = []\n self.xy_numpy = []\n self.tree = None\n \n self.v_scaling = 16.67/16.67\n \n self._process_file()\n\n def utm_to_enu(self, xyz):\n if len(xyz) == 3:\n return [xyz[0]-572196.963588907, xyz[1]-4026790.1365981903,xyz[2]]\n if len(xyz) == 2:\n return [xyz[0]-572196.963588907, xyz[1]-4026790.1365981903]\n \n\n def _process_file(self):\n ## offline pcc speed profile\n for line in self.f.readlines():\n processed_line = line.split( )\n wx, wy, wz = float(processed_line[0]),float(processed_line[1]),float(processed_line[2])\n [x, y, z] = self.utm_to_enu([wx, wy, wz])\n self.x.append(float(x))\n self.y.append(float(y))\n self.z.append(float(z))\n self.xy_numpy.append([x,y])\n self.pcc_v.append(float(processed_line[3]))\n self.xy_numpy = np.array(self.xy_numpy)\n self.tree = KDTree(self.xy_numpy)\n \n \n def qurey_v(self, x, y):\n dist, ind = self.tree.query([x,y], k=1)\n if self.pcc_v[ind] < 10:\n v = 10\n else:\n v = self.pcc_v[ind]\n return v*self.v_scaling\n\n def plot_pcc_result(self):\n ax = plt.gca()\n distance_list = []\n time_tick = []\n t = np.array([i for i in range(len(self.x))])\n ax.plot(t, np.array(self.z)/7)\n ax.plot(t, self.pcc_v)\n for i in range(len(self.x)-1):\n distance_list.append(math.sqrt((self.x[i]-self.x[i+1])**2+(self.y[i]-self.y[i+1])**2+(self.z[i]-self.z[i+1])**2))\n time_tick.append(distance_list[i]/(self.pcc_v[i]+1e-100))\n self.pcc_v = np.array(self.pcc_v)\n \n plt.show()\n \n def test(self, x_list, y_list, z_list):\n ax = plt.gca()\n t = np.array([i for i in range(len(x_list[::1000]))])\n ax.plot(t, (np.array(z_list[::1000])-300)/5)\n v = []\n for x, y in zip(x_list[::1000], y_list[::1000]):\n v.append(self.qurey_v(x, y))\n ax.plot(t, v)\n plt.show()\n\n\n################## main entrance ######################\ndef main(args=None):\n rclpy.init(args=args)\n # offline_pcc_node = OfflinePCC([-229.323,-6344.25,297.901], [686.306,6672.5,408.462])\n offline_pcc_node = OfflinePCC([-170.51309600000002, 102.1044750000001, 295.313], [927.53599-2.114085999999986, 12948.4684-3.2139649999999165, 408.727])\n offline_pcc_node.compute_speed_profile()\n offline_pcc_node.write_planning_result()\n offline_pcc_node.write_global_plan()\n offline_pcc_node.destroy_node()\n rclpy.shutdown()\n\ndef test_pcc_reader(args=None):\n rclpy.init(args=args)\n pcc_reader = PCCReader2()\n pcc_reader.plot_pcc_result()\n pcc_reader_previous = PCCReader()\n pcc_reader.destroy_node()\n rclpy.shutdown()\n\n\nif __name__ == \"__main__\":\n # main()\n test_pcc_reader()","repo_name":"Forrest-Z/IITS","sub_path":"planning/trajectory_planner/trajectory_planner/offline_pcc.py","file_name":"offline_pcc.py","file_ext":"py","file_size_in_byte":12348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"11808584093","text":"\"\"\"This script is used to get and install non-commercial Houdini licenses.\"\"\"\n\n# Future\nfrom __future__ import annotations\n\n# Standard Library\nimport argparse\nimport socket\nimport subprocess\nfrom typing import List\n\n# SideFX\nimport sidefx\n\nACCESS_TOKEN_URL = \"https://www.sidefx.com/oauth2/application_token\"\nENDPOINT_URL = \"https://www.sidefx.com/api/\"\nPRODUCTS_TO_INSTALL = \"HOUDINI-NC;RENDER-NC\"\n\n\ndef build_parser() -> argparse.ArgumentParser:\n \"\"\"Build an argument parser to get the command line data.\n\n Returns:\n An argument parser to get the required input information.\n\n \"\"\"\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"client_id\")\n\n parser.add_argument(\"client_secret\")\n\n return parser\n\n\ndef get_keys_to_install(\n client_id: str,\n client_secret_key: str,\n server_name: str,\n server_code: str,\n) -> List[str]:\n \"\"\"Get a list of non-commercial license keys to install.\n\n Args:\n client_id: The SideFX client id.\n client_secret_key: The SideFX client secret.\n server_name: The local server name.\n server_code: The local server code.\n\n Returns:\n The list of license keys to install.\n \"\"\"\n service = sidefx.service(\n access_token_url=ACCESS_TOKEN_URL,\n client_id=client_id,\n client_secret_key=client_secret_key,\n endpoint_url=ENDPOINT_URL,\n )\n\n license_strings = service.license.get_non_commercial_license(\n server_name=server_name,\n server_code=server_code,\n products=PRODUCTS_TO_INSTALL,\n )\n return license_strings[\"license_keys\"]\n\n\ndef get_server_code() -> str:\n \"\"\"Get the server code for the locally running server.\n\n Returns:\n The sesinetd server code.\n \"\"\"\n result = subprocess.check_output([\"sesictrl\", \"print-server\"])\n server_code = result.decode().split(\"\\n\")[1].split()[2]\n\n return server_code\n\n\ndef install_licenses(license_keys: List[str]) -> None:\n \"\"\"Install a list of license keys.\n\n Args:\n license_keys: The licenses keys to install.\n \"\"\"\n for license_key in license_keys:\n subprocess.call([\"sesictrl\", \"install\", license_key])\n\n\ndef main() -> None:\n \"\"\"The main execution function.\"\"\"\n # Parse the args from the action execution.\n parser = build_parser()\n parsed_args = parser.parse_args()\n\n server_code = get_server_code()\n server_name = socket.getfqdn()\n\n license_keys = get_keys_to_install(\n parsed_args.client_id,\n parsed_args.client_secret,\n server_name,\n server_code,\n )\n\n install_licenses(license_keys)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"captainhammy/install-houdini-apprentice-license-action","sub_path":"install_apprentice_keys.py","file_name":"install_apprentice_keys.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26457640992","text":"import blessed \nterm = blessed.Terminal()\nfrom random import randint\nimport socket\nimport time\n\n\ndef create_server_socket(local_port, verbose):\n \"\"\"Creates a server socket.\n \n Parameters\n ----------\n local_port: port to listen to (int)\n verbose: True if verbose (bool)\n \n Returns\n -------\n socket_in: server socket (socket.socket)\n \n \"\"\"\n \n socket_in = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_in.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # deal with a socket in TIME_WAIT state\n\n if verbose:\n print(' binding on local port %d to accept a remote connection' % local_port)\n \n try:\n socket_in.bind(('', local_port))\n except:\n raise IOError('local port %d already in use by your group or the referee' % local_port)\n socket_in.listen(1)\n \n if verbose:\n print(' done -> can now accept a remote connection on local port %d\\n' % local_port)\n \n return socket_in\n\n\ndef create_client_socket(remote_IP, remote_port, verbose):\n \"\"\"Creates a client socket.\n \n Parameters\n ----------\n remote_IP: IP address to send to (int)\n remote_port: port to send to (int)\n verbose: True if verbose (bool)\n \n Returns\n -------\n socket_out: client socket (socket.socket)\n \n \"\"\"\n\n socket_out = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_out.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # deal with a socket in TIME_WAIT state\n \n connected = False\n msg_shown = False\n \n while not connected:\n try:\n if verbose and not msg_shown:\n print(' connecting on %s:%d to send orders' % (remote_IP, remote_port))\n \n socket_out.connect((remote_IP, remote_port))\n connected = True\n \n if verbose:\n print(' done -> can now send orders to %s:%d\\n' % (remote_IP, remote_port))\n except:\n if verbose and not msg_shown:\n print(' connection failed -> will try again every 100 msec...')\n \n time.sleep(.1)\n msg_shown = True\n \n return socket_out\n \n \ndef wait_for_connection(socket_in, verbose):\n \"\"\"Waits for a connection on a server socket.\n \n Parameters\n ----------\n socket_in: server socket (socket.socket)\n verbose: True if verbose (bool)\n \n Returns\n -------\n socket_in: accepted connection (socket.socket)\n \n \"\"\"\n \n if verbose:\n print(' waiting for a remote connection to receive orders')\n \n socket_in, remote_address = socket_in.accept()\n \n if verbose:\n print(' done -> can now receive remote orders from %s:%d\\n' % remote_address)\n \n return socket_in \n\n\ndef create_connection(your_group, other_group=0, other_IP='127.0.0.1', verbose=False):\n \"\"\"Creates a connection with a referee or another group.\n \n Parameters\n ----------\n your_group: id of your group (int)\n other_group: id of the other group, if there is no referee (int, optional)\n other_IP: IP address where the referee or the other group is (str, optional)\n verbose: True only if connection progress must be displayed (bool, optional)\n \n Returns\n -------\n connection: socket(s) to receive/send orders (dict of socket.socket)\n \n Raises\n ------\n IOError: if your group fails to create a connection\n \n Notes\n -----\n Creating a connection can take a few seconds (it must be initialised on both sides).\n \n If there is a referee, leave other_group=0, otherwise other_IP is the id of the other group.\n \n If the referee or the other group is on the same computer than you, leave other_IP='127.0.0.1',\n otherwise other_IP is the IP address of the computer where the referee or the other group is.\n \n The returned connection can be used directly with other functions in this module.\n \n \"\"\"\n \n # init verbose display\n if verbose:\n print('\\n[--- starts connection -----------------------------------------------------\\n')\n \n # check whether there is a referee\n if other_group == 0:\n if verbose:\n print('** group %d connecting to referee on %s **\\n' % (your_group, other_IP))\n \n # create one socket (client only)\n socket_out = create_client_socket(other_IP, 42000+your_group, verbose)\n \n connection = {'in':socket_out, 'out':socket_out}\n \n if verbose:\n print('** group %d successfully connected to referee on %s **\\n' % (your_group, other_IP))\n else:\n if verbose:\n print('** group %d connecting to group %d on %s **\\n' % (your_group, other_group, other_IP))\n\n # create two sockets (server and client)\n socket_in = create_server_socket(42000+your_group, verbose)\n socket_out = create_client_socket(other_IP, 42000+other_group, verbose)\n \n socket_in = wait_for_connection(socket_in, verbose)\n \n connection = {'in':socket_in, 'out':socket_out}\n\n if verbose:\n print('** group %d successfully connected to group %d on %s **\\n' % (your_group, other_group, other_IP))\n \n # end verbose display\n if verbose:\n print('----------------------------------------------------- connection started ---]\\n')\n\n return connection\n \n \ndef bind_referee(group_1, group_2, verbose=False):\n \"\"\"Put a referee between two groups.\n \n Parameters\n ----------\n group_1: id of the first group (int)\n group_2: id of the second group (int)\n verbose: True only if connection progress must be displayed (bool, optional)\n \n Returns\n -------\n connections: sockets to receive/send orders from both players (dict)\n \n Raises\n ------\n IOError: if the referee fails to create a connection\n \n Notes\n -----\n Putting the referee in place can take a few seconds (it must be connect to both groups).\n \n connections contains two connections (dict of socket.socket) which can be used directly\n with other functions in this module. connection of first (second) player has key 1 (2).\n \n \"\"\"\n \n # init verbose display\n if verbose:\n print('\\n[--- starts connection -----------------------------------------------------\\n')\n\n # create a server socket (first group)\n if verbose:\n print('** referee connecting to first group %d **\\n' % group_1) \n\n socket_in_1 = create_server_socket(42000+group_1, verbose)\n socket_in_1 = wait_for_connection(socket_in_1, verbose)\n\n if verbose:\n print('** referee succcessfully connected to first group %d **\\n' % group_1) \n \n # create a server socket (second group)\n if verbose:\n print('** referee connecting to second group %d **\\n' % group_2) \n\n socket_in_2 = create_server_socket(42000+group_2, verbose)\n socket_in_2 = wait_for_connection(socket_in_2, verbose)\n\n if verbose:\n print('** referee succcessfully connected to second group %d **\\n' % group_2) \n \n # end verbose display\n if verbose:\n print('----------------------------------------------------- connection started ---]\\n')\n\n return {1:{'in':socket_in_1, 'out':socket_in_1},\n 2:{'in':socket_in_2, 'out':socket_in_2}}\n\n\ndef close_connection(connection):\n \"\"\"Closes a connection with a referee or another group.\n \n Parameters\n ----------\n connection: socket(s) to receive/send orders (dict of socket.socket)\n \n \"\"\"\n \n # get sockets\n socket_in = connection['in']\n socket_out = connection['out']\n \n # shutdown sockets\n socket_in.shutdown(socket.SHUT_RDWR) \n socket_out.shutdown(socket.SHUT_RDWR)\n \n # close sockets\n socket_in.close()\n socket_out.close()\n \n \ndef notify_remote_orders(connection, orders):\n \"\"\"Notifies orders to a remote player.\n \n Parameters\n ----------\n connection: sockets to receive/send orders (dict of socket.socket)\n orders: orders to notify (str)\n \n Raises\n ------\n IOError: if remote player cannot be reached\n \n \"\"\"\n\n # deal with null orders (empty string)\n if orders == '':\n orders = 'null'\n \n # send orders\n try:\n connection['out'].sendall(orders.encode())\n except:\n raise IOError('remote player cannot be reached')\n\n\ndef get_remote_orders(connection):\n \"\"\"Returns orders from a remote player.\n\n Parameters\n ----------\n connection: sockets to receive/send orders (dict of socket.socket)\n \n Returns\n ----------\n player_orders: orders given by remote player (str)\n\n Raises\n ------\n IOError: if remote player cannot be reached\n \n \"\"\"\n \n # receive orders \n try:\n orders = connection['in'].recv(65536).decode()\n except:\n raise IOError('remote player cannot be reached')\n \n # deal with null orders\n if orders == 'null':\n orders = ''\n \n return orders\n\ndef read_file(file):\n \"\"\" \n Read the file and turn it into a data structure \n Parameters\n -----------\n file : file of the game (file)\n\n Returns\n -------\n food: food on the map (dict)\n player_1: wolves of the player 1 (dict)\n player_2: wolves of the player 2 (dict)\n width: width of the map (int)\n height: height of the map (int)\n\n Versions\n --------\n specification : Aurélie Genot (v.1 17/02/2022)\n specification: Eline Mota (v.2 24/02/2022)\n Implementation: Eline Mote (v.1 24/02/2022)\n \"\"\"\n f = open(file, 'r')\n i = 0\n player_1 = {}\n player_2 = {}\n height = 0\n width = 0\n food = {}\n for lines in f.readlines():\n i+=1\n if i == 2:\n liste = lines.split(' ')\n height = int(liste[0])\n width = int(liste[1])\n\n elif i >= 4 and i <= 12:\n liste = lines.split(' ')\n coordonate = (int(liste[1]), int(liste[2]))\n y = liste[3] #enlève le retour à la ligne\n y = y[0:-1]\n player_1[coordonate] = {'type': y, 'life': 100, 'pacifie': 'non'}\n \n elif i > 12 and i <= 21:\n liste = lines.split(' ')\n coordonate = (int(liste[1]), int(liste[2]))\n y = liste[3]\n y = y[0:-1]\n player_2[coordonate] = {'type': y, 'life': 100, 'pacifie': 'non'}\n \n elif i > 22:\n liste = lines.split(' ')\n coordonate = (int(liste[0]), int(liste[1]))\n food[coordonate] = {'type': liste[2], 'life': int(liste[3])}\n\n return width, height, player_1, player_2, food \n\ndef trans_coord(x, y):\n \"\"\"Adapt and return the coordonates of an element for the map\n Parameters:\n -----------\n x: coordonate x (int)\n y: coordonate y (int)\n \n Return:\n -------\n x: coordonate x (int)\n y: coordonate y (int)\n Version:\n --------\n specification: Eline Mota (v.1 1/03/2022)\n implementation: Eline Mota (v.1 1/03/2022) \"\"\"\n\n\n x = (x-1)*3 + 1\n y = y-1\n return x, y\n\ndef can_eat (player_A, orders) :\n \"\"\"\n Check if a wolf can eat \n Parametres :\n ------------\n player_A: wolves of the player eating (dict)\n orders: orders of player_A (str)\n Returns :\n ---------\n maybe : The fact that the wolf can eat or not (bool)\n Versions :\n ----------\n specification : Aline Boulanger (v.1 10/03/2022)\n implementation : Louise Delpierre (v.1 10/03/2022)\n \n \"\"\"\n order = turn_list(orders)\n \n for elements in order :\n if \"<\" in elements :\n coords = elements.split (\":<\") \n i = 0\n for coord in coords : \n i += 1\n coord = coord.split (\"-\")\n if i == 1 :\n x_A = int(coord[0])\n y_A = int(coord[1])\n coords_wolfs = (x_A, y_A)\n elif i == 2 : \n x_food = int(coord[0])\n y_food = int(coord[1]) \n coords_food = (x_food, y_food) \n\n distance = count_cases(coords_food, coords_wolfs)\n distance_x = distance[0]\n distance_y = distance[1]\n if distance_x <= 1 and distance_y <= 1 :\n return True\n else : \n return False\ndef check_life(player_A, case):\n \"\"\"Check if a wolf has zero life\n\n Parameters:\n ----------\n player_A: wolves of the player playing (dict)\n case: place of the wolf we want to check (tuple)\n\n Return:\n -------\n Result: True if the wolf has zero life, False otherwise (bool)\n\n Versions:\n ---------\n specification: Eline Mota (v.1 19/02/2022)\n implementation: Aline Boulanger (v.1 03/03/2022)\n\n \"\"\"\n for wolves in player_A:\n if wolves == case:\n if player_A[wolves]['life'] == 0:\n return True\n else:\n None\n else:\n None\n return False\ndef can_pacify(player_A, x_A, y_A):\n \"\"\"Check if a wolf has enough energy to pacify and if he is an omega.\n Parameters:\n -----------\n player_A: wolves of the player playing (dict)\n x_A : the absisse of the wolf's position (int)\n y_A : the ordonate of the wolf's position (int)\n Return:\n -------\n Result: True if it can, False otherwise (bool)\n Versions:\n ---------\n specification: Aline Boulanger (v.1 19/02/2022)\n specification : Aline Boulanger (v.2 03/03/2022)\n implementation : Aline Boulanger (v.1 03/03/2022)\n \"\"\"\n #vérifie d'abord si le loup en x_A, y_A fait bien partie des loups du joueur_A\n for key in player_A:\n if key != (x_A, y_A):\n return False\n #Vérifie si le loup du joueur_A est bien un omega et si il a au moins 40 de vie\n if player_A[x_A, y_A][\"type\"] == \"omega\" :\n if player_A[x_A, y_A][\"life\"] >= 40 :\n return True\n else :\n return False\n else :\n return False\n\n\n#utiliser cette fonction après avoir adapter les coordonnées.\ndef clear_pos(x,y):\n \"\"\"Clear a position after moving a wolf\n Parameters:\n -----------\n x: coordonate x of the position (int)\n y: coordonate y of the position (int)\n \n Versions:\n ---------\n specification: Eline Mota (v.1 01/03/2022)\n implementation: Eline Mota (v.1 01/03/2022)\n \"\"\"\n if (x+y) % 2 ==0:\n print(term.move_xy(x, y) + term.on_snow2 + ' ')\n else:\n print(term.move_xy(x,y) + term.on_lavenderblush3 + ' ')\n\n\n\n\ndef color (team):\n \"\"\"\n Return the color of each team\n \n Parameters:\n -----------\n player_A: wolf of a player (dict)\n \n Return:\n -------\n term.stateblue1 : color of team 1 (var)\n term.purple4 : color of team 2 (var)\n \n Version:\n ---------\n specification: Eline Mota (v.1 03/03/2022)\n implementation: Eline Mota (v.1 03/03/2022)\"\"\"\n \n if team == 1:\n return term.slateblue1\n elif team == 2:\n return term.purple4\n else:\n return ''\n\ndef type_wolf(player_A, x, y):\n \"\"\"Return the type of a wolf\n \n Parameters:\n ------------\n player_A: wolves of a player (dict)\n x: coordonate x of a wolf (int)\n y: coordonate y of a wolf (int)\n \n Return:\n -------\n type: type of the wolf (A, O or L)\n\n Versions:\n ---------\n specification: Eline Mota (03/03/2022)\n implementation: Eline Mota (03/03/2022)\n \"\"\"\n type = player_A[(x,y)]['type']\n if type == 'alpha':\n return 'A'\n elif type == 'omega':\n return 'O'\n elif type == 'normal':\n return 'L'\n else:\n None\n\n\ndef update_life(player_A, number, x, y):\n \"\"\"Print on the map the life of the wolf\n\n Parameters:\n ------------\n player_A: wolves of a player (dict)\n number: number of the team playing (int)\n x: coordonate x of a wolf (int)\n y: coordonate y of a wolf (int)\n\n Versions:\n ----------\n specificaion: Eline Mota (v.1 03/03/2022)\n specification: Eline Mota (v.2 18/03/2022)\n implementation: Eline Mota (v.1 03/03/2022)\n \"\"\"\n colore = color(number) #la couleur de la team\n type = type_wolf(player_A, x, y) #le type du loup\n life = player_A[(x,y)]['life']\n pacifie = player_A[(x,y)]['pacifie']\n x, y = trans_coord(x,y) #adapte les coordonnées avec le plateau\n if life > 60 and life <= 100:\n print(term.move_xy(x,y) + colore + term.on_darkolivegreen3 + type)\n elif life <= 60 and life > 30:\n print(term.move_xy(x,y) + colore + term.on_yellow + type)\n elif life <= 30 and life > 0:\n print(term.move_xy(x,y) + colore + term.on_orangered + type)\n elif life == 0:\n print(term.move_xy(x, y) + colore + term.on_orangered + 'H')\n else:\n None\n if pacifie == 'oui':\n print(term.move_xy(x, y) + colore + 'P')\n else:\n None\n print(term.move_xy(20,20))\n\n\ndef turn_list(order):\n \"\"\"Turn an order into a list\n Parameters:\n -----------\n order: the order that a player has given (list)\n Return:\n -------\n order: the order turned into a list (list)\n Version:\n --------\n specification: Aurélie Genot (v.1 19/02/2022)\n implementation: Aurélie Genot (v.1 24/02/2022) \n \"\"\"\n order = order.split(\" \")\n return order\ndef check_case(case, dictionnary_checked):\n \"\"\"Check if there is an element of the dictionnary on a case \n \n Parameters:\n -----------\n case: a case of the map (tuple)\n dictionnary_checked: dictionnary in which we check the information(dict)\n\n Return:\n -------\n Result: True if there is a item on the case, False otherwise (bool)\n\n Versions:\n ---------\n specification: Louise Delpierre (v.1 19/02/2022)\n specification: Aurélie Genot (v.2 03/03/2022)\n implementation: Aurélie Genot (v.1 03/03/2022)\n \"\"\"\n for key in dictionnary_checked :\n if case == key :\n return True \n return False\n\n\ndef can_use(order, x, y):\n \"\"\"Check if a wolf can play, if it hasn't already been used\n\n Parameters:\n ------------\n order: order for the wolves (str)\n x: coordonate x of the wolf (str)\n y: coordonate y of the wolf (str)\n \n Return:\n -------\n result: True if he can play, False otherwise \n\n Versions:\n ---------\n specification: Eline Mota (v.1 11/03/2022)\n implementation: Eline Mota (v.1 11/03/2022)\n \"\"\"\n i = 0\n if ':' in order:\n order = turn_list(order)\n for element in order: \n element = element.split(':')\n element = element[0]\n element = element.split('-')\n if int(element[0]) == x and int(element[1]) == y:\n i += 1\n if i >= 2:\n return False\n elif i < 1:\n return True\n else:\n return False\n\ndef count_cases(e1, e2):\n \"\"\"\n Count the cases that separes two elements\n \n Parameters:\n ------------\n e1: position of the first element (tuple)\n e2: position of the second element (tuple) \n \n Returns:\n --------\n distance: the difference of the two positions (with the X and the Y) (tuple)\n \n Versions:\n ----------\n specification: Louise Delpierre (v.1 19/02/2022)\n specification: Aurélie Genot (v.2 07/03/2022)\n implementation : Aline Boulanger (v.1 3/03/2022)\n \"\"\"\n x_1 = e1[0]\n y_1 = e1[1]\n x_2 = e2[0]\n y_2 = e2[1]\n\n x = x_2 - x_1\n distance_x = abs(x)\n y = y_2 - y_1\n distance_y = abs(y)\n distance = (distance_x, distance_y)\n return distance\n \n\ndef type_food(type):\n \"\"\"Identify the type of the food\n\n Parameters:\n -----------\n type: type of the food (str)\n\n Return:\n -------\n types: type of the food (str)\n\n Version:\n --------\n specification: Louise Delpierre (v.1 03/03/2022)\n implementation: Eline Mota (v.1 03/03/2022)\n \"\"\"\n\n\n if type == 'berries':\n types = 'b'\n elif type == 'apples':\n types = 'a'\n elif type == 'mice':\n types = 'm'\n elif type == 'rabbits':\n types = 'r'\n elif type == 'deers':\n types = 'd'\n return types\n\n\ndef update_food(food):\n \"\"\"Print the food on the map\n\n Parameters:\n -----------\n food: food on the map (dict)\n\n Versions:\n ---------\n specification: Eline Mota (v.1 03/03/2022)\n implementation: Eline Mota (v.1 03/03/2022)\n \"\"\"\n for coord in food:\n type = type_food(food[coord]['type'])\n x = coord[0]\n y = coord[1]\n x, y = trans_coord(x,y)\n life = food[coord]['life']\n if life > 60:\n print(term.move_xy(x, y) + term.black + term.on_darkolivegreen3 + type)\n elif life <= 60 and life > 30:\n print(term.move_xy(x, y) + term.black + term.on_yellow + type)\n elif life <= 30 and life > 0:\n print(term.move_xy(x, y) + term.black + term.on_orangered + type)\n elif life == 0:\n print(term.move_xy(x,y) + term.black + term.on_orangered + '0')\n else:\n raise ValueError('you cannot have a negative life')\n\ndef create_map(width, height, player_1, player_2, food): \n \"\"\" \n Create the map of the board \n Parameters\n ----------\n width: width of the map (int)\n height: height of the map (int)\n player_1: wolves of the player 1 (dict)\n player_2: wolves of the player 2 (dict)\n food : food on the map (dict)\n Versions\n --------\n specification : Louise Delpierre (v1 17/02/2022)\n implementation: Eline Mota (v.1 28/02/2022)\n implementation: Eline Mota (v.2 10/03/2022)\n \"\"\"\n print(term.home + term.clear)\n #crée le plateau\n for x in range(0, width * 3, 3):\n for y in range(0, height, 1):\n if (x+y)%2 ==0:\n print(term.move_xy(x, y) + term.on_lavenderblush3 + ' ')\n else:\n print(term.move_xy(x, y) + term.on_snow2 + ' ')\n #positionne les loups des deux joueurs et la nourriture\n for key in player_1:\n x = key[0]\n y = key[1]\n update_life(player_1, 1, x, y)\n for key in player_2:\n x = key[0]\n y = key[1]\n update_life(player_2, 2, x, y)\n\n for key in food:\n x = key[0]\n y = key[1]\n update_food(food)\n\ndef bonus(player_A, case):\n '''\n Get a bonus to the wolves of the player who is playing \n Parameters\n ----------\n player_A : wolves of the player who plays (dict) # peut-être juste utilisé player\n case : the case of the wolf who wants to have a bonus (tuple) \n Returns\n --------\n power_up_wolves: wolves with their bonus (dict)\n Versions\n --------\n specification : Aurélie Genot (v.1 17/02/2022) \n implementation : Louise Delpierre (v.1 9/03/2022)\n '''\n bonusL = 0\n bonusA = 0\n\n for key in player_A :\n distance = count_cases (case, key)\n distance_x = distance[0]\n distance_y = distance[1]\n if distance_x + distance_y != 0 :#Empêche le bonus de s'activer sur la case du loup même\n if player_A [key]['type'] == 'normal': \n if distance_x <= 2 and distance_y <= 2: \n bonusL += 10\n if player_A [key]['type'] == 'alpha': \n if distance_x <= 4 and distance_y <= 4 :\n bonusA += 30\n bonusTotal = bonusL + bonusA \n\n return bonusTotal\n\ndef attack(player_A, player_B, orders, number, i): \n '''\n Attacks the wolves of the other player \n\n Parameters\n ----------\n player_A : wolves of the player who attacks (dict)\n player_B : wolves of the player who is attacked (dict)\n orders : orders of the player who attacks (str)\n number: number of the team attacked (int)\n i:\n\n Returns\n --------\n player_1: wolves of the player 1 (dict)\n player_2: wolves of the player 2 (dict)\n\n Versions\n --------\n specification : Eline Mota (v.1 17/02/2022)\n implementation: Louise Delpierre, Aline Boulanger (v.1 24/02/2022)\n implementation: Eline Mota (v.2, 03/03/2022)\n '''\n bonuss = 0\n order = turn_list(orders) \n\n for elements in order:\n \n if '*' in elements:\n coords = elements.split (\":*\")\n \n i = 0\n for coord in coords:\n i += 1\n\n coord = coord.split (\"-\")\n if i == 1:\n x_A = int(coord[0])\n y_A = int(coord[1])\n elif i == 2 :\n x_B = int(coord[0])\n y_B = int(coord[1])\n #vérifie une série de choses avant que le loup puisse attaquer afin d'éviter les erreurs \n if check_life(player_A, (x_A, y_A)) == False and check_case((x_B, y_B), player_B) == True and can_use(orders, x_A, y_A) == True:\n if player_A[(x_A, y_A)]['pacifie'] == 'non':\n vie = player_A[(x_A,y_A)][\"life\"]\n bonuss = bonus(player_A, (x_A, y_A))\n vie += bonuss\n attaque = vie/10\n #boucle pour éviter de tomber dans les négatifs\n while player_B [(x_B,y_B)][\"life\"] > 0 and attaque > 0:\n player_B [(x_B,y_B)][\"life\"] -= 1 \n attaque -= 1 \n update_life(player_B, number, x_B, y_B )\n i = 0\n else:\n i += 1\n\n return player_A, player_B, i\n\ndef eat(food, player_A, orders, team):\n \"\"\"\n Add energy point to a wolf depending on what he eats\n \n Parameters:\n -----------\n food: food placed on the map (dict)\n player_A: wolves of the player eating (dict)\n orders: orders of player_A (str)\n team: team of the player eating (int)\n Return:\n -------\n player_A: wolves of the player who has eaten (dict)\n food : food placed on the map (dict)\n Versions:\n ---------\n specifiaction: Aline Boulanger (v.1 19/02/2022)\n specification: Eline Mota (v.2 18/03/2022)\n implementation : Aline Boulanger (v.1 02/03/2022)\n \"\"\"\n \n order = turn_list(orders)\n\n for elements in order :\n if \"<\" in elements :\n coords = elements.split (\":<\")\n i = 0\n for coord in coords : \n i += 1\n coord = coord.split (\"-\")\n if i == 1 :\n x_A = int(coord[0])\n y_A = int(coord[1])\n elif i == 2 : \n x_food = int(coord[0])\n y_food = int(coord[1]) \n coords_food = (x_food, y_food)\n for key in food :\n if coords_food == key and can_use(orders, x_A, y_A) and can_eat(player_A, orders) and check_case((x_A, y_A),player_A) == True:\n #boucle pour éviter de dépasser 100 ou pour éviter que la vie de la nourriture soit négative\n while player_A[(x_A, y_A)][\"life\"] < 100 and food[x_food, y_food][\"life\"] > 0 :\n player_A[(x_A, y_A)][\"life\"] += 1\n food[x_food, y_food][\"life\"] -= 1\n update_food(food)\n update_life(player_A, team, x_A, y_A)\n else:\n None\n\n return food, player_A \n\n \ndef in_map(case, width, height): \n \"\"\"To check if the case where the wolf wants to go is well in the map\n Parameters:\n -----------\n case: the case who has to be checked (tuple)\n width: width of the map (int)\n height: height of the map (int)\n Return:\n -------\n Result: True if the case is in the map, False otherwise (bool)\n Versions:\n ----------\n specification: Aurélie Genot (v.1 19/02/2022)\n specification: Aurélie Genot (v.2 03/03/2022)\n specification: Eline Mota (v.3 18/03/2022)\n implementation: Aurélie Genot (v.1 03/03/2022)\n \"\"\"\n \n x = case[0]\n y = case[1]\n\n if x >= 1 and x<= width and y>=1 and y<= height: \n return True\n else:\n return False\n\n\ndef move(player_A, player_B, orders, width, height, team, food):\n \"\"\"\n Move a wolf on the board\n Parameters:\n -----------\n player_A: wolves of the player who is playing (dict)\n player_B: wolves of the other player (dict)\n orders : order of the player_A (str)\n width: width of the map (int)\n height: height of the map (int)\n team: team of the player moving (int)\n food: food on the map (dict)\n Returns:\n ---------\n player_A: wolves of the player who is playing after moving (dict)\n Versions:\n --------\n specification: Eline Mota (v.1 19/02/2022)\n specification: Eline Mota (v.2 18/03/2022)\n implementation : Aurélie Genot (v.1 03/03/2022)\n implementation: Aurélie Genot (v.2 07/03/2022)\n implementation: Eline Mota (v.3 18/03/2022)\n \"\"\"\n\n order = turn_list(orders) \n for elements in order:\n \n\n if '@' in elements: # Pour chaque @ dans l'ordre\n coords = elements.split (\":@\") #Met en liste les éléments entourant @ \n i = 0\n for coord in coords:\n i += 1\n\n coord = coord.split (\"-\") # Pour récupérer les coordonnées X et Y \n if i == 1:\n actual_x = int(coord[0])\n actual_y = int(coord[1])\n elif i == 2 :\n future_x = int(coord[0])\n future_y = int(coord[1])\n \n actual_pos = (actual_x, actual_y)\n future_pos = (future_x, future_y)\n\n # 1ère étape: Regarder si déplacement possible (ckeck_case, can_use et in_map) \n\n if check_case(actual_pos, player_A) == True and check_case(future_pos, player_A) == False and check_case(future_pos, player_B) == False and in_map(future_pos, width, height) == True and can_use(orders, actual_x, actual_y) == True:\n \n\n # 2ème étape: vérifie que c'est un déplacement d'une case maximumum (avec count_case)\n distance = count_cases(actual_pos, future_pos) \n distance_x = distance[0]\n distance_y = distance[1] \n if distance_x <=1 and distance_y <=1: \n \n #3ème étape: faire le déplacement \n case_deleted = player_A.pop(actual_pos) # Supprimer l'emplacement actuel\n value_case_deleted = case_deleted\n player_A[(future_pos)] = value_case_deleted # Créer le nouvel emplacement\n #change sur le plateau\n x, y = trans_coord(actual_x, actual_y)\n clear_pos(x, y)\n if team == 1:\n update_food(food)\n update_life(player_A, 1, future_x, future_y)\n elif team == 2:\n update_food(food)\n update_life(player_A, 2, future_x, future_y)\n else:\n None\n\n\n\n\n return player_A\n\n\ndef pacification(player_A, player_B, orders):\n \"\"\" \n Pacification of the wolves of the other player \n Parameters\n ----------\n player_A : the player who wants to pacify (dict)\n player_B : the player who is pacify (dict) \n orders : orders of the player who attacks (str)\n Returns\n --------\n player_A : the player with the type modification (dict)\n player_B : the player with the type modification (dict) \n Versions\n --------\n specification : Aline Boulanger (v.1 17/02/2022) \n implementation : Louise Delpierre (v.1 5/03/2022)\n \"\"\"\n order = turn_list(orders) \n for elements in order : \n if 'pacify' in elements: # recherche pacify dans order \n coords = elements.split (\":pacify\")\n i = 0\n for coord in coords:\n i += 1\n coord = coord.split (\"-\")\n if i == 1:\n x_A = int(coord[0])\n y_A = int(coord[1])\n coords_omega = (x_A, y_A)\n \n if can_pacify(player_A, x_A, y_A) == True and can_use(orders, x_A, y_A): # vérifie si player_A est un omega \n for key in player_A:\n distance = count_cases (key,coords_omega)\n distance_x = distance[0]\n distance_y = distance[1]\n if distance_x <= 6 and distance_y <= 6 and key != coords_omega: # la distance pour pacifier \n player_A[key]['pacifie'] = 'oui'\n else:\n None\n for key in player_B:\n distance = count_cases (key,coords_omega)\n distance_x = distance[0]\n distance_y = distance[1]\n if distance_x <= 6 and distance_y <= 6 and key != coords_omega: # la distance pour pacifier \n player_B[key]['pacifie']= 'oui'\n\n else :\n None \n player_A[coords_omega]['life'] -= 40\n else : \n None \n return player_A, player_B\n\ndef choose_random_move(wolf): \n \"\"\" \n To give a ramdom position for a move possible on the map\n \n Parameters\n -----------\n wolf : the wolf who will move (tuple)\n Returns \n --------\n coords_chosen: the coords chosen randomly (str)\n \n Versions\n ---------\n specification: Aurélie Genot (v.1 10/03/2022)\n implementation: Auréie Genot (v.1 10/03/2022)\n \"\"\"\n actual_x = wolf[0]\n actual_y = wolf[1]\n\n #Choisit un déplacement possible\n x_chosen= str(randint(actual_x-1,actual_x+1)) \n y_chosen= str(randint(actual_y-1,actual_y+1))\n\n coords_chosen = x_chosen + \"-\" + y_chosen\n\n return coords_chosen \n\ndef IA_game(player_A, player_B, food):\n \"\"\"\n Return a random order\n\n Parameters\n ----------\n player_A : wolves of the IA (dict)\n player_B : wolves of the other player (dict)\n food: food of the game (dict)\n\n Returns\n -------\n orders: orders of the IA (str)\n\n Versions:\n ---------\n specification: Aurélie Genot (v.1 10/03/2022)\n implementation: Aurélie Genot (v.1 10/03/2022)\n implementation : Aurélie Genot (v.2 15/03/2022)\n implemantation : Eline Mota (v.3 21/03/2022)\n \"\"\"\n orders = ''\n #se nourrir\n for wolves in player_A:\n for foods in food:\n \n distance = count_cases(wolves, foods)\n distance_x = distance[0]\n distance_y = distance[1]\n #vérifie une série de chose pour que l'action de se nourrir ait un minimum de sens\n if distance_x <= 1 and distance_y <= 1 and player_A[wolves]['life'] < 100 and food[foods]['life'] > 0 : \n eat_x = str(wolves[0])\n eat_y = str(wolves[1])\n eaten_x = str(foods[0])\n eaten_y = str(foods[1])\n action_2 = ':<'\n\n orders = orders + eat_x + '-' + eat_y + action_2 + eaten_x + '-' + eaten_y + ' '\n\n #l'attaque\n for wolves in player_A: \n for wolvess in player_B:\n\n distance = count_cases(wolves, wolvess)\n distance_x = distance[0]\n distance_y = distance[1]\n #vérifie une série de chose pour que l'attaque ait un minimum de sens\n if distance_x <= 1 and distance_y <= 1 and player_A[wolves]['life'] > 0: \n attacking_x = str(wolves[0])\n attacking_y = str(wolves[1])\n attacked_x = str(wolvess[0])\n attacked_y = str(wolvess[1])\n orders = orders + attacking_x + \"-\" + attacking_y + \":*\" + attacked_x + \"-\" + attacked_y + ' '\n #voir commentaire ci-dessous pour comprendre\n i = 0\n for wolves in player_A:\n x = wolves[0]\n y = wolves[1]\n order = str(x) + '-' + str(y)\n if order not in orders:\n i += 1\n q = 0\n for wolves in player_A:\n q += 1\n x = wolves[0]\n y = wolves[1]\n order = str(x) + '-' + str(y)\n if order not in orders:\n\n x = str(wolves[0])\n y = str(wolves[1])\n coords_chosen = choose_random_move(wolves)\n #on vérifie ça pour que le dernier ordre donné ne se temrine pas par un espace (pour éviter les problèmes)\n if q < i:\n orders = orders + x + '-' + y + ':@' + coords_chosen + ' '\n else:\n orders = orders + x + '-' + y + ':@' + coords_chosen\n \n\n return orders\n\n\ndef play_game(map_path, group_1, type_1, group_2, type_2):\n \"\"\"Play a game.\n \n Parameters\n ----------\n map_path: path of map file (str)\n group_1: group of player 1 (int)\n type_1: type of player 1 (str)\n group_2: group of player 2 (int)\n type_2: type of player 2 (str)\n \n Notes\n -----\n Player type is either 'human', 'AI' or 'remote'.\n \n If there is an external referee, set group id to 0 for remote player.\n \n \"\"\"\n #lit le fichier\n width, height, player_1, player_2, food = read_file(map_path)\n if type_1 == 'remote':\n connection = create_connection(group_2, group_1)\n elif type_2 == 'remote':\n connection = create_connection(group_1, group_2)\n\n #identifie l'alpha dans chaque team \n for key in player_1:\n if player_1[key]['type'] == 'alpha':\n alpha1 = key\n else:\n None\n for key in player_2:\n if player_2[key]['type'] == 'alpha':\n alpha2 = key\n else:\n None\n\n #crée la map\n create_map(width, height, player_1, player_2, food)\n\n i = 0\n #continue à jouer tant que les deux aplhas ont plus de 0 HP et que moins de deux cents tours ont été joués\n while player_1[alpha1]['life'] > 0 and player_2[alpha2]['life'] > 0 and i <= 200:\n\n\n #évite d'avoir les ordres sur le plateau\n print(term.move_xy(25,25))\n\n #définit le type de \"personne qui va jouer\"\n\n if type_1 == 'human':\n orders1 = input('choose an order')\n elif type_1 == 'AI':\n orders1 = IA_game(player_1, player_2, food)\n elif type_1 == 'remote':\n orders1 = get_remote_orders(connection)\n if type_2 == 'human':\n orders2 = input('choose an order')\n elif type_2 == 'AI': \n orders2 = IA_game(player_2, player_1, food)\n elif type_2 == 'remote':\n orders2 = get_remote_orders(connection)\n \n if '*' not in orders1 and '*' not in orders2:\n i += 1\n\n\n \n #phase 1: pacification\n player_1, player_2 = pacification(player_1, player_2, orders1)\n player_2, player_1 = pacification(player_2, player_1, orders2)\n #phase 2: se nourrir\n food, player_1 = eat(food, player_1, orders1, 1)\n food, player_2 = eat(food, player_2, orders2, 2)\n \n #phase 3: se déplacer\n player_1 = move(player_1, player_2, orders1, width, height, 1, food)\n player_2 = move(player_2, player_1, orders2, width, height, 2, food)\n\n\n player_2b = player_2 #ne donne pas un désavantage pour attaquer à l'équipe deux \n #phase 4 et 5: attaque et bonus\n player_1, player_2b, i = attack(player_1, player_2b, orders1, 2, i)\n player_2, player_1, i = attack(player_2, player_1, orders2, 1, i)\n #effectue les changements de l'attaque au joueur deux\n player_2 = player_2b\n\n \n\n #rénitialise le pacifie et effectue les changements après l'attaque\n for wolves in player_1:\n x = wolves[0]\n y = wolves[1]\n player_1[wolves]['pacifie'] = 'non'\n update_life(player_1, 1, x, y )\n for wolves in player_2:\n x = wolves[0]\n y = wolves[1]\n player_2[wolves]['pacifie'] = 'non'\n update_life(player_2, 2, x, y )\n #update la position de l'alpha pour la boucle\n for wolves in player_1:\n if player_1[wolves]['type'] == 'alpha':\n alpha1 = wolves\n for wolves in player_2:\n if player_2[wolves]['type'] == 'alpha':\n alpha2 = wolves\n \n\n #Annonce le gagnant ou pas....\n if player_1[alpha1]['life'] > 0 and i < 200:\n print('PLAYER 1 HAS WON')\n elif player_2[alpha2]['life'] > 0 and i < 200:\n print('PLAYER 2 HAS WON')\n elif player_2[alpha2]['life'] == 0 and player_1[alpha1]['life'] == 0:\n print('EQUALITY')\n else:\n tot_live1 = 0\n tot_live2 = 0\n for wolves in player_1:\n tot_live1 += player_1[wolves]['life']\n for wolves in player_2:\n tot_live2 += player_2[wolves]['life']\n \n if tot_live1 > tot_live2:\n print('Player 1 has won')\n elif tot_live2 > tot_live1:\n print('Player 2 has won')\n else:\n print('EQUALITY')\n\n if type_1 == 'remote' or type_2 == 'remote':\n close_connection(connection)\n\n\nplay_game('testfichier.txt', 1, 'AI', 2, 'AI')\n","repo_name":"Mozinou2013/INFOB132-Programmation-Project","sub_path":"THEGAME.py","file_name":"THEGAME.py","file_ext":"py","file_size_in_byte":41162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41719729735","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom rest_framework_simplejwt.views import TokenVerifyView\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api-auth', include('rest_framework.urls')),\n path('login/', include('user.api.loginURL')),\n path('users/', include('user.api.urls')),\n path('verify/', TokenVerifyView.as_view()),\n]","repo_name":"PrasaDesk/DjangoRepo","sub_path":"Auth_CS/auth_ms/auth_ms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"18331376951","text":"import sys\nimport math\nfrom collections import deque\n\nsys.setrecursionlimit(1000000)\nMOD = 10 ** 9 + 7\ninput = lambda: sys.stdin.readline().strip()\nNI = lambda: int(input())\nNMI = lambda: map(int, input().split())\nNLI = lambda: list(NMI())\nSI = lambda: input()\n\n\n# Nの素因数分解を辞書で返す(単体)\ndef prime_fact(n):\n root = int(n**0.5) + 1\n prime_dict = {}\n for i in range(2, root):\n cnt = 0\n while n % i == 0:\n cnt += 1\n n = n // i\n if cnt:\n prime_dict[i] = cnt\n if n != 1:\n prime_dict[n] = 1\n return prime_dict\n\n\ndef divisors(x):\n res = set()\n for i in range(1, int(x**0.5)+2):\n if x % i == 0:\n res.add(i)\n res.add(x//i)\n return res\n\n\ndef main():\n N = NI()\n AB = [NLI() for _ in range(N)]\n\n AG = divisors(AB[0][0])\n BG = divisors(AB[0][1])\n\n ans = 1\n\n for ag in AG:\n for bg in BG:\n ok = True\n for a, b in AB:\n if (a % ag or b % bg) and (a % bg or b % ag):\n ok = False\n break\n if ok:\n ans = max(ans, ag * bg // math.gcd(ag, bg))\n\n print(ans)\n\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Mao-beta/AtCoder","sub_path":"ARC/ARC124/ARC124C.py","file_name":"ARC124C.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16233394758","text":"\"\"\"Functional tests for the data_io integrals module.\"\"\"\n\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\n\nfrom rimseval.data_io import integrals\n\n\ndef test_export(crdproc_int):\n \"\"\"Export of integrals with default filename.\"\"\"\n integrals.export(crdproc_int)\n fname = Path(crdproc_int.fname)\n fname = fname.with_name(fname.stem + \"_int\").with_suffix(\".csv\").absolute()\n assert fname.is_file()\n\n\ndef test_export_fname(crdproc_int, tmpdir):\n \"\"\"Export of integrals with given filename.\"\"\"\n fname = Path(tmpdir.strpath).joinpath(\"test\")\n integrals.export(crdproc_int, fname)\n assert fname.with_suffix(\".csv\").is_file()\n\n\ndef test_export_valueerror(crdproc_int):\n \"\"\"Export of integrals with CRDProcessor class with no integrals.\"\"\"\n crdproc_int.integrals = None\n with pytest.raises(ValueError):\n integrals.export(crdproc_int)\n\n\ndef test_load(crdproc_int, tmpdir):\n \"\"\"Assure that export and load end up with the same data.\"\"\"\n fname = Path(tmpdir.strpath).joinpath(\"test.csv\")\n integrals.export(crdproc_int, fname)\n name_ld, timestamp_ld, peaks_ld, int_ld = integrals.load(fname)\n\n assert name_ld == crdproc_int.name\n assert timestamp_ld == crdproc_int.timestamp\n assert peaks_ld == crdproc_int.def_integrals[0]\n np.testing.assert_allclose(int_ld, crdproc_int.integrals)\n","repo_name":"RIMS-Code/RIMSEval","sub_path":"tests/func/data_io/test_integrals.py","file_name":"test_integrals.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15712169592","text":"\"\"\"\ntextgame.parser\n=====================\n\nThis module's main class is :class:`textgame.parser.Parser`. The parser can take\nuser input, call a function that's associated to the input and return to the user a\nmessage describing what happened.\n\nUse ``actionmap`` and ``legal_verbs`` to define how verbs should be mapped to functions, eg:\n\n.. code-block:: python\n\n parser.actionmap.update({\n \"scream\": player.scream\n })\n parser.legal_verbs.update({\n \"scream\": \"scream\",\n \"shout\": \"scream\"\n })\n\nYou can use ``legal_nouns`` to define synonyms for nouns.\n\nA parser is the only thing needed to during the main loop of a game:\n\n.. code-block:: python\n\n parser = textgame.parser.Parser(player)\n while player.status[\"alive\"]:\n response = parser.understand( input(\"> \") )\n print(response)\n\n\nThis module also provides :class:`textgame.parser.EnterYesNoLoop`. If a function\ncalled by the parser returns an ``EnterYesNoLoop`` instead of a string, the parser falls\ninto a mode where it only allows 'yes' and 'no' as an answer. An object of type\n``EnterYesNoLoop`` also provides strings/functions to print/call for each case.\n\nExample: a player method that saves the user from drinking poison\n\n.. code-block:: python\n\n @action_method\n def drink(self, noun):\n if noun == \"poison\":\n\n def actually_do_it():\n self.status[\"alive\"] = False\n return \"You drink the poison and die.\"\n\n return textgame.parser.EnterYesNoLoop(\n question = \"Do you really want to drink poison?\",\n yes = actually_do_it,\n no = \"You stay alive\")\n else:\n # ...\n\n\"\"\"\n\nfrom collections import namedtuple\nimport pickle\nimport os\nimport logging\nlogger = logging.getLogger(\"textgame.parser\")\nlogger.addHandler(logging.NullHandler())\n\nfrom textgame.globals import INFO\n\n\nclass EnterYesNoLoop:\n \"\"\"\n :param question: a yes/no question\n :type question: string\n :param yes: string to return or a function with signature ``f() -> str`` or ``f() -> EnterYesNoLoop`` that should get called if player answeres 'yes' to the question\n :param no: same as yes\n \"\"\"\n\n def __init__(self, question, yes, no):\n self.question = question\n self._yes = yes\n self._no = no\n\n def yes(self):\n \"\"\"\n if yes is callable, return its result, else return it\n \"\"\"\n if callable(self._yes):\n return self._yes()\n return self._yes\n\n def no(self):\n \"\"\"\n if no is callable, return its result, else return it\n \"\"\"\n if callable(self._no):\n return self._no()\n return self._no\n\n\nclass Parser:\n \"\"\"\n :param player: :class:`textgame.player.Player` object\n \"\"\"\n\n def __init__(self, player):\n\n self.player = player\n\n self.in_yesno = False # are we inside a yes/no conversation?\n # yesno_backup must be a function that takes a bool and returns\n # user output. it will be executed if yes/no conversation ends with yes\n self.yesno_backup = None\n\n self.legal_verbs = {\n \"\": \"continue\", # dont do anything on empty input\n \"attack\": \"attack\",\n \"back\": \"back\",\n \"close\": \"close\",\n \"d\": \"down\",\n \"down\": \"down\",\n \"drop\": \"drop\",\n \"e\": \"east\",\n \"east\": \"east\",\n \"enter\": \"go\",\n \"go\": \"go\",\n \"grab\": \"take\",\n \"hear\": \"listen\",\n \"hint\": \"hint\",\n \"inventory\": \"inventory\",\n \"kill\": \"attack\",\n \"listen\": \"listen\",\n \"lock\": \"close\",\n \"look\": \"look\",\n \"n\": \"north\",\n \"north\": \"north\",\n \"open\": \"open\",\n \"s\": \"south\",\n \"score\": \"score\",\n \"south\": \"south\",\n \"take\": \"take\",\n \"u\": \"up\",\n \"up\": \"up\",\n \"w\": \"west\",\n \"walk\": \"go\",\n \"west\": \"west\",\n \"save\": \"save\",\n \"load\": \"load\",\n }\n\n # this may be used to define synonyms\n self.legal_nouns = {\n \"d\": \"down\",\n \"e\": \"east\",\n \"n\": \"north\",\n \"s\": \"south\",\n \"u\": \"up\",\n \"w\": \"west\",\n }\n\n # the lambdas are there because the values in this dict must be\n # callable with exactly one argument\n self.actionmap = {\n \"attack\": player.attack,\n \"back\": lambda x: player.go(\"back\"),\n \"continue\": lambda x: \"\",\n \"down\": lambda x: player.go(\"down\"),\n \"drop\": player.drop,\n \"east\": lambda x: player.go(\"east\"),\n \"go\": player.go,\n \"hint\": player.ask_hint,\n \"inventory\": player.list_inventory,\n \"listen\": player.listen,\n \"look\": player.look,\n \"close\": player.close,\n \"north\": lambda x: player.go(\"north\"),\n \"open\": player.open,\n \"score\": player.show_score,\n \"south\": lambda x: player.go(\"south\"),\n \"take\": player.take,\n \"up\": lambda x: player.go(\"up\"),\n \"west\": lambda x: player.go(\"west\"),\n \"save\": lambda session=\"\": self.save_game(session=session),\n \"load\": lambda session=\"\": self.load_game(session=session),\n }\n\n self.check()\n\n\n def save_game(self, path=\"\", session=\"\"):\n \"\"\"\n dump self.player as textgame_session.pickle\n \"\"\"\n if session:\n filename = os.path.join(path, \"textgame_{}.pickle\".format(session))\n else:\n filename = os.path.join(path, \"textgame.pickle\")\n logger.info(\"saving game to {}\".format(filename))\n with open(filename, \"wb\") as f:\n pickle.dump(self.player, f, pickle.HIGHEST_PROTOCOL)\n return INFO.SAVED\n\n\n def load_game(self, path=\"\", session=\"\"):\n \"\"\"\n load textgame_session.pickle (player object) and reinitialize parser with it\n \"\"\"\n if session:\n filename = os.path.join(path, \"textgame_{}.pickle\".format(session))\n else:\n filename = os.path.join(path, \"textgame.pickle\")\n try:\n with open(filename, \"rb\") as f:\n logger.info(\"reinitializing parser with loaded player object\")\n self.__init__(pickle.load(f))\n except FileNotFoundError:\n return \"There's no game with the name '{}'.\".format(session)\n return INFO.LOADED\n\n\n def delete_game(self, path=\"\", session=\"\"):\n \"\"\"\n delete path/textgame_session.pickle if present\n \"\"\"\n if session:\n filename = os.path.join(path, \"textgame_{}.pickle\".format(session))\n else:\n filename = os.path.join(path, \"textgame.pickle\")\n if os.path.isfile(filename):\n os.remove(filename)\n\n\n def lookup_verb(self, verb):\n return self.legal_verbs.get(verb)\n\n\n def lookup_noun(self, noun):\n return self.legal_nouns.get(noun)\n\n\n def check(self):\n \"\"\"\n check if every verb in self.legal_verbs has a function mapped to.\n if not, the game will crash on the input of this verb\n\n logs the error\n \"\"\"\n for verb in set(self.legal_verbs.values()):\n if verb not in self.actionmap:\n logger.error(\"{} is a legal verb but has no definition\"\n \"in actionmap\".format(verb))\n\n\n def check_result(self, result):\n \"\"\"\n checks if result is EnterYesNoLoop or str, if it's EnterYesNoLoop,\n return the question and fall back to yes/no mode\n \"\"\"\n if type(result) is str:\n return result\n else:\n # assume that result is of type enteryesnoloop\n self.in_yesno = True\n self.yesno_backup = result\n return result.question\n\n\n def do(self, verb, noun):\n \"\"\"\n call function associated with verb with noun as argument\n \"\"\"\n return self.actionmap[verb](noun)\n\n\n def _split_input(self, input):\n \"\"\"\n take input and return verb and noun\n \"\"\"\n args = input.split()\n if len(args) > 2:\n # this gets catched in Parser.understand\n raise ValueError()\n elif len(args) == 2:\n verb, noun = args\n elif len(args) == 1:\n verb = args[0]\n noun = \"\"\n else:\n verb = \"\"\n noun = \"\"\n return verb, noun\n\n\n def understand(self, input):\n \"\"\"\n based on the input, perform player method and return its output\n the return value is what can be printed to the user\n \"\"\"\n try:\n verb, noun = self._split_input(input)\n except ValueError:\n return INFO.TOO_MANY_ARGUMENTS\n\n # if a yes/no conversation is going on, only allow yes/no as answers\n if self.in_yesno:\n if verb != \"yes\" and verb != \"no\":\n return INFO.YES_NO\n elif verb == \"yes\":\n self.in_yesno = False\n # return the yes case\n result = self.yesno_backup.yes()\n return self.check_result(result)\n else:\n self.in_yesno = False\n # return the no case\n result = self.yesno_backup.no()\n return self.check_result(result)\n\n commandverb = self.lookup_verb(verb)\n commandnoun = self.lookup_noun(noun)\n # if noun is illegal, reset to it's original value and feed it to\n # the actionmethods. More creative output if erronous input :)\n if not commandnoun:\n commandnoun = noun\n logger.debug(\"I understood: verb={} noun={}\".format(repr(commandverb), repr(commandnoun)))\n\n # illegal nouns are okay but illegal verbs are not\n if not commandverb:\n return INFO.NOT_UNDERSTOOD\n\n # perform the associated method\n result = self.do(commandverb, commandnoun)\n\n return self.check_result(result)\n","repo_name":"davekch/textgame","sub_path":"textgame/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":10128,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"10046018151","text":"import abc\nfrom piecewise.lcs.hyperparams import get_hyperparam\n\n\nclass IFitnessUpdateStrategy(metaclass=abc.ABCMeta):\n @abc.abstractmethod\n def __call__(self, action_set):\n raise NotImplementedError\n\n\nclass XCSAccuracyFitnessUpdate(IFitnessUpdateStrategy):\n _MAX_ACCURACY = 1.0\n\n def __call__(self, action_set):\n \"\"\"UPDATE FITNESS function from 'An Algorithmic Description of XCS'\n (Butz and Wilson, 2002).\n \"\"\"\n accuracy_vec, accuracy_sum = \\\n self._calc_accuracy_vec_and_accuracy_sum(action_set)\n self._update_fitness_values(action_set, accuracy_vec, accuracy_sum)\n\n def _calc_accuracy_vec_and_accuracy_sum(self, action_set):\n accuracy_sum = 0\n accuracy_vec = []\n for classifier in action_set:\n is_below_error_threshold = classifier.error < \\\n get_hyperparam(\"epsilon_nought\")\n if is_below_error_threshold:\n accuracy = self._MAX_ACCURACY\n else:\n accuracy = self._calc_accuracy(classifier)\n accuracy_vec.append(accuracy)\n accuracy_sum += accuracy * classifier.numerosity\n return accuracy_vec, accuracy_sum\n\n def _calc_accuracy(self, classifier):\n return get_hyperparam(\"alpha\") * \\\n (classifier.error / get_hyperparam(\"epsilon_nought\"))\\\n ** (-1 * get_hyperparam(\"nu\"))\n\n def _update_fitness_values(self, action_set, accuracy_vec, accuracy_sum):\n for (classifier, accuracy) in zip(action_set, accuracy_vec):\n adjustment = \\\n ((accuracy*classifier.numerosity/accuracy_sum) -\n classifier.fitness)\n classifier.fitness += get_hyperparam(\"beta\") * adjustment\n\n\nclass NullFitnessUpdate(IFitnessUpdateStrategy):\n def __call__(self, action_set):\n pass\n","repo_name":"jtbish/piecewise","sub_path":"piecewise/lcs/component/fitness_update.py","file_name":"fitness_update.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"43179372230","text":"T = int(input())\n\ntest = {'ZRO': 0, 'ONE': 1, 'TWO': 2, 'THR': 3, 'FOR': 4, 'FIV':5,\n 'SIX': 6, 'SVN': 7, 'EGT': 8, 'NIN': 9}\ntext_n = {0: 'ZRO', 1: 'ONE', 2: 'TWO', 3: 'THR', 4: 'FOR', 5: 'FIV',\n 6: 'SIX', 7: 'SVN', 8: 'EGT', 9: 'NIN'}\nfor TC in range(1,T+1):\n\n tc = list(input().split())\n tc_len = int(tc[1])\n li = list(input().split())\n li_n = [0] * tc_len\n for i in range(tc_len):\n li_n[i] = test[li[i]]\n li_n.sort()\n print(f'#{TC}')\n for i in li_n:\n print(text_n[i], end=' ')\n print()","repo_name":"sondongmin0419/study","sub_path":"python/s_1221.py","file_name":"s_1221.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39258557442","text":"import json\r\nimport spotipy\r\nimport webbrowser\r\nfrom spotipy.oauth2 import SpotifyOAuth\r\n\r\nusername = 'hsj7sxkq9hszo93uqei13o884'\r\nclientID = '04857dcfb612420baf59d1ec15b1b402'\r\nclientSecret = '24af9fea164b43e8b8bc64b377d6e73c'\r\nredirect_Uri = 'http://google.com/callback/'\r\n\r\nsp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(client_id=clientID,client_secret=clientSecret,redirect_uri=redirect_Uri, scope='user-read-playback-state,user-modify-playback-state'))\r\n\r\noauth_object = spotipy.SpotifyOAuth(clientID, clientSecret, redirect_Uri)\r\ntoken_dict = oauth_object.get_access_token()\r\ntoken = token_dict['access_token']\r\nspotifyObject = spotipy.Spotify(auth=token)\r\nuser_name = spotifyObject.current_user()\r\n \r\n# To print the response in readable format.\r\nprint(json.dumps(user_name, sort_keys=True, indent=4))\r\n\r\nwhile True:\r\n print(\"Welcome to the project, \" + user_name['display_name'])\r\n print(\"0 - Exit the console\")\r\n print(\"1 - Search for a Song\")\r\n user_input = int(input(\"Enter Your Choice: \"))\r\n if user_input == 1:\r\n search_song = input(\"Enter the song name: \")\r\n results = spotifyObject.search(search_song, 1, 0, \"track\")\r\n songs_dict = results['tracks']\r\n song_items = songs_dict['items']\r\n song = song_items[0]['external_urls']['spotify']\r\n webbrowser.open(song)\r\n # sp.start_playback(uris=['spotify:track:0HUTL8i4y4MiGCPId7M7wb'])\r\n print(song)\r\n print('Song has opened in your browser.')\r\n elif user_input == 0:\r\n print(\"Good Bye, Have a great day!\")\r\n break\r\n else:\r\n print(\"Please enter valid user-input.\")","repo_name":"raj9426/practice-mini-codes","sub_path":"mini project/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5121085377","text":"import logging\nfrom loguru import logger\nfrom config import DEBUG, SYSTEM\n\n\ndef init_log():\n\n if SYSTEM == 'Windows':\n rotation = None\n elif SYSTEM == 'Linux':\n rotation = '1 day'\n else:\n rotation = None\n\n _format = '{time:YY-MM-DD HH:mm:ss.SSS} - {process.name} - {thread.name} - {function} - {line} - {level} - {message}'\n logger.remove()\n handlers = [\n {\n # 'sink': 'log/error-{time:YYMMDD}.log',\n 'sink': 'log/error.log',\n # 'sink': write,\n 'format': _format,\n 'level': 'ERROR',\n 'rotation': rotation,\n 'enqueue': True,\n 'encoding': 'utf-8',\n 'backtrace': True\n },\n {\n 'sink': 'log/log.log',\n 'format': _format,\n 'level': 'INFO',\n 'rotation': rotation,\n 'enqueue': True,\n 'encoding': 'utf-8',\n 'backtrace': True\n }\n ]\n\n if DEBUG:\n handlers.append({\n 'sink': 'log/debug.log',\n 'format': _format,\n 'level': 'DEBUG',\n 'rotation': rotation,\n 'enqueue': True,\n 'encoding': 'utf-8',\n 'backtrace': True\n })\n\n handlers.append({\n 'sink': logging.StreamHandler(),\n 'format': _format,\n 'level': 'DEBUG',\n 'enqueue': True,\n 'backtrace': True\n })\n\n logger.configure(handlers=handlers)\n\n return logger\n","repo_name":"shadowmimosa/mzitu","sub_path":"common/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39188682000","text":"\nimport os\n\nfrom zope import interface\nfrom zope.dottedname.resolve import resolve\n\nfrom ctrl.core.constants import RUN_FOREVER\nfrom ctrl.core.interfaces import ISubcommand\n\nfrom .pubsub import ZMQPublisher\nfrom .rpc import ZMQRPCClient\n\n\nclass ZMQUpCommand(object):\n\n @property\n def apps(self):\n return [\n (k[8:], v.split(' ')[0], v.split(' ')[1:])\n for k, v\n in os.environ.items()\n if k.startswith('ZMQ_APP')]\n\n @property\n def router(self):\n if 'ZMQ_ROUTER' in os.environ:\n router = os.environ['ZMQ_ROUTER'].split(' ')\n return router[0], router[1:]\n\n async def handle(self, *args, loop=None):\n if self.router:\n await resolve(self.router[0])().route(*self.router[1])\n for k, app, args in self.apps:\n handler = resolve(app)(k, args[0], loop=loop)\n response = await handler.run(*args[1:])\n if response is not None:\n print(response)\n return RUN_FOREVER\n\n\n@interface.implementer(ISubcommand)\nclass ZMQSubcommand(object):\n\n def __init__(self, context):\n self.context = context\n\n async def handle(self, command, *args, loop=None):\n return await getattr(self, 'handle_%s' % command)(*args, loop=loop)\n\n async def handle_rpc(self, server_addr, command, *args, loop=None):\n client = ZMQRPCClient('rpc', server_addr)\n return await client.handle(command, *args)\n\n async def handle_publish(self, server_addr, command, *args, loop=None):\n client = ZMQPublisher(loop, server_addr)\n return await client.handle(command, *args)\n\n async def handle_up(self, *args, loop=None):\n return await ZMQUpCommand().handle(*args)\n","repo_name":"phlax/ctrl.zmq","sub_path":"ctrl/zmq/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33235719914","text":"def table_rename_column(self, old_colname: str, new_colname: str, tablename: str) -> None:\n \"\"\"\n - Change a column name for a table in SQL\n\n Arguments:\n old_colname (str): name of the original column\n new_colname (str): desired name of the column\n tablename (str): name of the table to update\n\n Returns:\n None: but updates the column name in-place\n \"\"\"\n\n query = f\"ALTER TABLE {tablename} RENAME {old_colname} TO {new_colname};\"\n self.execute(query)\n\n\ndef table_add_uid_column(self, tablename: str, uid_col: str = \"uid\") -> None:\n \"\"\"\n - Add a unique ID column to a table as a SERIAL PRIMARY KEY type\n - If the `uid_col` already exists, it's dropped before being recreated\n\n Arguments:\n tablename (str): name of the table to add a primary key column to\n uid_col (str): name of the new column, defaults to 'uid'\n\n Returns:\n None: but adds a primary key column to the table\n \"\"\"\n\n query = f\"\"\"\n ALTER TABLE {tablename}\n DROP COLUMN IF EXISTS {uid_col};\n\n ALTER TABLE {tablename}\n ADD {uid_col} serial PRIMARY KEY;\n \"\"\"\n self.execute(query)\n","repo_name":"aaronfraint/pg-data-etl","sub_path":"pg_data_etl/database/actions/query/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40021602682","text":"from flask import Flask,render_template,redirect,url_for,request,flash\nfrom wtforms import StringField,TextAreaField,Form\nfrom flask_mail import Mail,Message\n\n\n\n\nclass ContactForm(Form):\n email=StringField(\"Mail adresiniz\")\n detay=TextAreaField(\"Detaylı bilgi\")\n\n\n\napp=Flask(__name__)\napp.config['MAIL_SERVER']='smtp.gmail.com'\napp.config['MAIL_PORT'] = 465\napp.config['MAIL_USERNAME'] = 'reklamvereneleman@gmail.com'\napp.config['MAIL_PASSWORD'] = '147852963Dark'\napp.config['MAIL_USE_TLS'] = False\napp.config['MAIL_USE_SSL'] = True\napp.config['MAIL_DEFAULT_SENDER'] = \"reklamvereneleman@gmail.com\"\napp.config['SECRET_KEY'] = \"denemedenemedımdımdım\"\n\nmail = Mail(app)\n\n\n\n\n@app.route(\"/\",methods=[\"GET\",\"POST\"])\ndef index():\n form=ContactForm(request.form)\n if request.method==\"POST\":\n try:\n \n \n email=form.email.data\n detay=form.detay.data\n \n msg=Message(\"DouSoftware Mesajı\",\n sender=\"reklamvereneleman@gmail.com\",\n recipients=[\"gozluklubukalemun@gmail.com\"])\n\n msg.body=email+\" \"+\"tarafından gelen mesaj\\n\"+\" \"+detay\n mail.send(msg)\n flash(\"Gönderme Başarılı\",\"succes\")\n return redirect(url_for(\"index\",form=form))\n except Exception as e:\n return(str(e))\n \n else:\n return render_template(\"index.html\",form=form)\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__==\"__main__\":\n app.run(debug=True)","repo_name":"sonic03/dousoftwareflask","sub_path":"dou.py","file_name":"dou.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35669247242","text":"import aws_cdk as cdk\nfrom aws_cdk import Stack\nfrom aws_cdk import aws_iam as iam\nfrom aws_cdk import aws_lambda as _lambda\nfrom aws_cdk import aws_logs as logs\nfrom aws_cdk import aws_s3 as s3\nfrom aws_cdk import aws_sns as sns\nfrom aws_cdk import aws_sqs as sqs\nfrom aws_cdk import aws_ssm as ssm\nfrom aws_cdk.aws_lambda_event_sources import SqsEventSource, SnsEventSource\nfrom constructs import Construct\n\nPROJECK_NAME = \"CollectYouTubeChatApp\"\nDESCRIPTION = \"Collect YouTube Chat Messages\"\n\n\ndef build_resource_name(resource_name: str, service_name: str) -> str:\n return f\"{resource_name}_{service_name}_cdk\"\n\n\nclass CollectYouTubeChatAppStack(Stack):\n\n def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n\n role = iam.Role(\n self, build_resource_name(\"rol\", \"collect_youtube_chat_role\"),\n assumed_by=iam.ServicePrincipal(\"lambda.amazonaws.com\"),\n managed_policies=[\n iam.ManagedPolicy.from_aws_managed_policy_name(\n \"service-role/AWSLambdaBasicExecutionRole\")\n ],\n role_name=build_resource_name(\n \"rol\", \"collect_youtube_chat_role\"),\n description=DESCRIPTION\n )\n cdk.Tags.of(role).add(\"service_name\", build_resource_name(\n \"rol\", \"collect_youtube_chat_role\"))\n\n layer = _lambda.LayerVersion(\n self, build_resource_name(\"lyr\", \"request\"),\n code=_lambda.Code.from_asset(\"layer\"),\n layer_version_name=build_resource_name(\"lyr\", \"request\"),\n compatible_runtimes=[_lambda.Runtime.PYTHON_3_9],\n description=\"Python lib: request\",\n )\n\n fn = _lambda.Function(\n self, build_resource_name(\"lmd\", \"collect_youtube_chat_service\"),\n code=_lambda.Code.from_asset(\"lambda\"),\n handler=\"lambda_function.handler\",\n runtime=_lambda.Runtime.PYTHON_3_9,\n function_name=build_resource_name(\n \"lmd\", \"collect_youtube_chat_service\"),\n environment={\n \"LOG_LEVEL\": \"INFO\",\n },\n description=DESCRIPTION,\n timeout=cdk.Duration.seconds(300),\n memory_size=256,\n role=role,\n log_retention=logs.RetentionDays.THREE_MONTHS,\n layers=[layer]\n )\n cdk.Tags.of(role).add(\"service_name\", build_resource_name(\n \"lmd\", \"collect_youtube_chat_service\"))\n\n bucket = s3.Bucket(\n self, \"s3s-collect-youtube-chat-bucket-cdk\",\n bucket_name=\"s3s-collect-youtube-chat-bucket-cdk\",\n )\n bucket.grant_put(role)\n cdk.Tags.of(role).add(\"service_name\",\n \"s3s-collect-youtube-chat-bucket-cdk\")\n fn.add_environment(\n key=\"BUCKET_NAME\",\n value=bucket.bucket_name\n )\n\n queue = sqs.Queue(\n self, build_resource_name(\"sqs\", \"collect_youtube_chat_queue\"),\n queue_name=build_resource_name(\n \"sqs\", \"collect_youtube_chat_queue\"),\n visibility_timeout=cdk.Duration.seconds(500)\n )\n queue.grant_send_messages(role)\n cdk.Tags.of(role).add(\"service_name\", build_resource_name(\n \"sqs\", \"collect_youtube_chat_queue\"))\n fn.add_environment(\n key=\"QUE_URL\",\n value=queue.queue_url\n )\n sqs_event = SqsEventSource(queue)\n fn.add_event_source(sqs_event)\n\n topic_collect = sns.Topic(\n self, build_resource_name(\"sns\", \"collect_youtube_chat_topic\"),\n topic_name=build_resource_name(\n \"sns\", \"collect_youtube_chat_topic\"),\n )\n topic_collect.grant_publish(role)\n cdk.Tags.of(role).add(\"service_name\", build_resource_name(\n \"sns\", \"collect_youtube_chat_topic\"))\n fn.add_environment(\n key=\"TOPIC_ARN\",\n value=topic_collect.topic_arn\n )\n\n collect_youtube_api_key = ssm.StringParameter.from_secure_string_parameter_attributes(\n self, \"collect_youtube_api_key\",\n version=1,\n parameter_name=\"collect_youtube_api_key\",\n )\n collect_youtube_api_key.grant_read(role)\n fn.add_environment(\n key=\"YOUTUBE_API_KEY\",\n value=collect_youtube_api_key.parameter_name,\n )\n\n topic_schedule = sns.Topic.from_topic_arn(\n self, \"sns_post_twitter_service_cdk\",\n topic_arn=f\"arn:aws:sns:{cdk.Stack.of(self).region}:{cdk.Stack.of(self).account}:sns_post_twitter_service_cdk\"\n )\n sns_event = SnsEventSource(topic_schedule)\n fn.add_event_source(sns_event)\n\n for resource in [role, fn, bucket, queue, topic_collect]:\n cdk.Tags.of(resource).add(\"project\", PROJECK_NAME)\n cdk.Tags.of(resource).add(\"creater\", \"cdk\")\n","repo_name":"tsuji-tomonori/CollectYouTubeChatApp","sub_path":"collect_you_tube_chat_app/collect_you_tube_chat_app_stack.py","file_name":"collect_you_tube_chat_app_stack.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"73769746962","text":"import sys\r\n\r\ncnt = 0\r\n\r\nn, k = map(int, sys.stdin.readline().split())\r\n\r\nfor i in range(1, n+1):\r\n if n % i ==0:\r\n cnt += 1\r\n if cnt == k:\r\n print(i)\r\n exit()\r\n\r\nprint(0)","repo_name":"gouyeonch/Algorithm","sub_path":"백준/Bronze/2501. 약수 구하기/약수 구하기.py","file_name":"약수 구하기.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"2136533232","text":"from torch import nn\n\nclass LeNetTiny(nn.Module):\n def __init__(self):\n super(LeNetTiny, self).__init__()\n self.layer1 = nn.Sequential( # (batch_size,1,28,28)\n nn.Conv2d(in_channels=1,out_channels=6,kernel_size=5,stride=1,padding=0), # (batch_size,6,24,24)\n nn.MaxPool2d(kernel_size=2) # (batch_size,6,12,12)\n )\n self.layer2 = nn.Sequential(\n nn.Conv2d(in_channels=6,out_channels=16,kernel_size=5,stride=1,padding=0), # (batch_size,16,8,8)\n nn.MaxPool2d(kernel_size=2) # (batch_size,16,4,4)\n )\n self.fc = nn.Sequential(\n nn.Linear(16*4*4,120),\n nn.Linear(120,84),\n nn.Linear(84,10)\n )\n\n def forward(self,input):\n input = self.layer1(input)\n input = self.layer2(input)\n input = input.view(input.size(0),-1) # 展平数据 size(0)指第0维度 此句表示将输入形状转化为(1,n) 4*16*5*5\n # input = F.softmax(input,dim=0) 这里的dim=0指以0维度为单位进行softmax操作,此时1维度和为1\n output = self.fc(input)\n return output\n","repo_name":"Highler23/DL-learning","sub_path":"project/target-identification/digital_identification/modules/lenet_tiny.py","file_name":"lenet_tiny.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29137475397","text":"import furl\nimport pytest\nfrom async_asgi_testclient import TestClient\nfrom starlette import status\nfrom tortoise.contrib.test import TestCase\n\nfrom app.core.config import settings\nfrom app.schemas.call_center import CallCenterInCreateSchema, CallCenterInUpdateSchema\nfrom tests.helpers.random_data import random_lower_string\n\npytestmark = pytest.mark.asyncio\n\n_prefix = furl.furl(settings.API_V1_STR) / \"call-centers/\"\n\n\n@pytest.mark.usefixtures(\"create_superuser\", \"async_client_class\", \"superuser_token_headers_class\")\nclass TestCallCenters(TestCase):\n async_client: TestClient\n\n async def test_read_all_empty(self):\n expected = []\n res = await self.async_client.get(_prefix.url, headers=self.superuser_token_headers)\n assert status.HTTP_200_OK == res.status_code\n assert expected == res.json()\n\n async def test_read_all_some_and_batch_delete(self):\n call_center_in = CallCenterInCreateSchema(\n name=random_lower_string(), bunker_name=random_lower_string(), region_id=1\n )\n call_center_in2 = CallCenterInCreateSchema(\n name=random_lower_string(), bunker_name=random_lower_string(), region_id=1\n )\n await self.async_client.post(\n _prefix.url, headers=self.superuser_token_headers, json=call_center_in.dict(exclude_unset=True)\n )\n await self.async_client.post(\n _prefix.url, headers=self.superuser_token_headers, json=call_center_in2.dict(exclude_unset=True)\n )\n\n call_centers = await self.async_client.get(_prefix.url, headers=self.superuser_token_headers)\n\n assert status.HTTP_200_OK == call_centers.status_code\n ids = []\n for cc in call_centers.json():\n ids.append(cc[\"id\"])\n assert len(call_centers.json()) == 2\n path = _prefix / \"batch\"\n path.args = {\"ids\": ids}\n await self.async_client.delete(path.url, headers=self.superuser_token_headers)\n\n async def test_delete(self):\n call_center_in = CallCenterInCreateSchema(\n name=random_lower_string(), bunker_name=random_lower_string(), region_id=1\n )\n await self.async_client.post(\n _prefix.url, headers=self.superuser_token_headers, json=call_center_in.dict(exclude_unset=True)\n )\n call_center = await self.async_client.get(_prefix.url, headers=self.superuser_token_headers)\n url = _prefix / f\"{call_center.json()[0]['id']}\"\n response = await self.async_client.delete(url.url, headers=self.superuser_token_headers)\n assert response.status_code == status.HTTP_204_NO_CONTENT\n\n async def test_update(self):\n call_center_in = CallCenterInCreateSchema(\n name=random_lower_string(), bunker_name=random_lower_string(), region_id=1\n )\n call_center_in2 = CallCenterInUpdateSchema(name=random_lower_string())\n call_center = await self.async_client.post(\n _prefix.url, headers=self.superuser_token_headers, data=call_center_in.json()\n )\n path = _prefix / f\"{call_center.json()['id']}\"\n resp = await self.async_client.patch(\n path.url, json=call_center_in2.dict(exclude_unset=True), headers=self.superuser_token_headers\n )\n resp_json = resp.json()\n assert resp_json[\"name\"] == call_center_in2.name\n assert resp_json[\"region_id\"] == call_center_in.region_id\n await self.async_client.delete(path.url, headers=self.superuser_token_headers)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"classfields/tests/api/v1/test_call_centers.py","file_name":"test_call_centers.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7378240166","text":"from textobjects import templates, exceptions, regex\nfrom textobjects.textobject import StructuredText\nfrom typing import Iterable, Mapping\nfrom copy import deepcopy\n\ndef create(name, template, post=None, construct=None, scope={}):\n cls = templates.parse(template, name)\n if not post:\n post = lambda o: None\n\n init = cls.__init__\n def __init__(self, *args, scope=scope, **kwargs):\n init(self, *args, **kwargs)\n post(self)\n cls.__init__ = __init__\n __match = cls.__match__\n\n @classmethod\n def __match__(cls, *args, **kwargs):\n obj = __match(*args, scope=scope, **kwargs)\n post(obj)\n return obj\n cls.__match__ = __match__\n\n __findall = cls.__findall__\n\n @classmethod\n def __findall__(cls, *args, **kwargs):\n lst = __findall(*args, **kwargs)\n for obj in lst:\n post(obj)\n return lst\n cls.__findall__ = __findall__\n\n\n __search = cls.__search__\n\n @classmethod\n def __search__(cls, *args, **kwargs):\n obj = __search(*args, **kwargs)\n post(obj)\n return obj\n cls.__search__ = __search__\n\n if construct:\n new = cls.__new__\n def __new__(cls, *args, **kwargs):\n newargs = construct(*args, **kwargs)\n if isinstance(newargs, Mapping):\n return new(cls, **newargs)\n if isinstance(newargs, Iterable) and not isinstance(newargs, str):\n return new(cls, *newargs)\n return new(cls, newargs)\n cls.__new__ = __new__\n return cls\n\ndef re(name, template):\n \"\"\"create a textobject class based on the template\n\n .. note::\n\n Only regular placeholders (no wildcards) are supported at this time\n\n \"\"\"\n return regex.parse(name, template)\n\ndef match(Type: StructuredText, text: str, enclosing=None):\n return Type.__match__(text, enclosing)\n\ndef search(Type: StructuredText, text, enclosing=None):\n return Type.__search__(text, enclosing)\n\ndef findall(Type: StructuredText, text):\n return Type.__findall__(text)\n\ndef matchlines(Type: StructuredText, text: str) -> Iterable[StructuredText]:\n lines = text.split('\\n')\n results = []\n for line in lines:\n try:\n m = Type.__match__(line, text)\n results.append(m)\n except:\n pass\n return results\n\ndef searchlines(Type: StructuredText, text: str) -> Iterable[StructuredText]:\n lines = text.split('\\n')\n results = []\n for line in lines:\n try:\n results.append(search(Type, line, text))\n except:\n pass\n return results\n","repo_name":"BlakeASmith/textobjects","sub_path":"lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23189570594","text":"import math\n\n# 01. Faça um programa que receba um numero e mostre qual deles é o maior.\nnum1 = int(input('01. Valor1: '))\nnum2 = int(input('Valor2: '))\nprint(max(num1, num2))\n\n# 02. Receba um valor do usuario, caso seja positivo calcule a raiz quadrada dele, caso contrario informe que o valor\n# é invalido.\nnum = int(input('02. Digite um valor:'))\nif num > 0:\n msg = math.sqrt(num)\nelse:\n msg = 'Valor invalido.'\n\nprint(msg)\n\n# 03. Leia um numero real, se ele for positivo imprima a raiz quadrada, se for negativo imprima o valor ao quadrado.\nnum = float(input('03. Digite um valor:'))\nif num > 0:\n msg = math.sqrt(num)\nelse:\n msg = num.__pow__(2)\n\nprint(msg)\n\n# 04. Leia um valor e caso ele seja positivo apresente o valor dele ao quadrado e sua raiz quadrada.\nnum = int(input('04. Digite um valor:'))\nif num > 0:\n raiz = math.sqrt(num)\n exp = num.__pow__(2)\n print(f'Raiz quadrada: {raiz} \\n Elevado ao quadrado: {exp}')\n\n# 05. Receba um numero inteiro e verifique se ele é par ou impar.\nnum = int(input('05. Digite um valor:'))\nif num % 2 == 0:\n msg = \"É par.\"\nelse:\n msg = \"É impar.\"\n\nprint(msg)\n\n# 06. Receba 2 numeros inteiros, mostre qual é o maior e a diferença entre eles.\nnum1 = int(input('06. Valor1: '))\nnum2 = int(input('Valor2: '))\nmaior = max(num1, num2)\ndif = maior - min(num1, num2)\nprint(f'Maior: {maior}\\nDiferença: {dif}')\n\n# 07. Receba dois valores e mostre o maior, caso sejam iguais imprima 'Valores iguais.'\nnum1 = int(input('07. Valor1: '))\nnum2 = int(input('Valor2: '))\nif num1 == num2:\n print('Valores iguais.')\nelse:\n print(f'{max(num1, num2)}')\n\n# 08. Leia 2 notas entre 0.0 e 10.0 e informe a media delas, caso alguma não esteja nesse escopo, informe.\nnota1 = int(input('08. nota1: '))\n\nif 0.0 <= nota1 <= 10.0:\n nota2 = int(input('nota2: '))\n if 0.0 <= nota2 <= 10.0:\n msg = (nota1 + nota2) / 2\n else:\n msg = \"Notas invalidas, favor verificar.\"\nelse:\n msg = \"Notas invalidas, favor verificar.\"\n\nprint(msg)\n\n# 09. Leia o salario de um trabalhador e o valor do emprestimo solicitado, caso seja menor que 20% do salaraio,\n# imprima \"Emprestimo concedido\", caso contraio, imprima \"Emprestimo não concedido\".\nsalario = float(input('09. Valor do salario: '))\nemp = float(input('Emprestimo solicitado: '))\nif emp < salario * 0.2:\n msg = \"Emprestimo concedido\"\nelse:\n msg = \"Emprestimo não concedido\"\n\nprint(msg)\n\n# 10. Receba a altura e o sexo de uma pessoa e mostre o seu peso ideal.\naltura = float(input('Digite sua altura: '))\nsexo = input('Digite o sexo: ')\nif 'M' or 'm' in sexo:\n pIdeal = (72.7 * altura) - 58\nelse:\n pIdeal = (62.1 * altura) - 44.7\n\nprint(f'Seu peso ideal é {pIdeal}')\n","repo_name":"Furtado145/GeekUniversity_-_Python_Exercicios","sub_path":"Secao05/Exec 01-10.py","file_name":"Exec 01-10.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13810756634","text":"import cmath\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nfrom decimal import Decimal\r\n\r\n# Функция форматирования вывода\r\ndef format_float(f):\r\n d5 = Decimal(str(f));\r\n return d5.quantize(Decimal(1)) if d5 == d5.to_integral() else d5.normalize()\r\n\r\nprint('Введите коэффициенты квадратного уравнения:')\r\n\r\na = int(input('a = '))\r\nb = int(input('b = '))\r\nc = int(input('c = '))\r\n\r\n# Подсчет дискриминанта\r\nd = b ** 2 - 4 * a * c\r\n\r\nif a == 0 and b == 0:\r\n print('Решений нет')\r\nelif d == 0:\r\n print('Дискриминант = 0, следовательно, имеем два одинаковых корня:')\r\n x1 = -b / (2 * a)\r\n\r\n print('x=', format_float(x1))\r\n\r\n # Построение графика\r\n y1 = a * x1 * x1 + b * x1 + c\r\n\r\n x = np.linspace((-10 + x1), (x1 + 10), 50)\r\n y = a * x * x + b * x + c\r\n\r\n plt.plot(x, y)\r\n plt.plot(x1, y1, 'ro')\r\n plt.title(\"График квадратного уравнения\") # заголовок\r\n plt.xlabel(\"x\") # ось абсцисс\r\n plt.ylabel(\"y\") # ось ординат\r\n plt.grid()\r\n plt.show()\r\nelif d > 0:\r\n print('Дискриминант > 0, следовательно, имеем два действительных корня:')\r\n x1 = round((-b + d ** (0.5)) / (2 * a), 1)\r\n x2 = round((-b - d ** (0.5)) / (2 * a), 1)\r\n print('x_1 =', format_float(x1), ', x_2 =', format_float(x2))\r\n\r\n # Построение графика\r\n y1 = a * x1 * x1 + b * x1 + c\r\n y2 = a * x2 * x2 + b * x2 + c\r\n\r\n max1 = max([x1, x2])\r\n min1 = min([x1, x2])\r\n\r\n x = np.linspace((-10 + min1), (10 + max1), 50)\r\n y = a * x * x + b * x + c\r\n\r\n plt.plot(x, y)\r\n plt.plot([x1, x2], [y1, y2], 'ro')\r\n plt.title(\"График квадратного уравнения\") # заголовок\r\n plt.xlabel(\"x\") # ось абсцисс\r\n plt.ylabel(\"y\") # ось ординат\r\n plt.grid()\r\n plt.show()\r\nelse:\r\n print('Дискриминант < 0, следовательно, имеем два комплексных корня:')\r\n d1 = round(-b / (2 * a), 1)\r\n m1 = round((abs(d) ** (0.5)) / (2 * a), 1)\r\n d2 = round(-b / (2 * a), 1)\r\n m2 = round((abs(d) ** (0.5)) / (2 * a), 1)\r\n print(f'x_1 = {format_float(d1)} + {format_float(m1)}i,',\r\n f' x_2 = {format_float(d2)} - {format_float(m2)}i')\r\n # print('x_1 = ', (-b + cmath.sqrt(d)) / (2 * a), ', x_2 = ', (-b - cmath.sqrt(d)) / (2 * a))\r\n\r\n # Построение графика\r\n plt.plot([d1, d2], [m1, -m2], 'ro')\r\n plt.title(\"График комплексных решений\") # заголовок\r\n plt.xlabel(\"Rez(x)\") # ось абсцисс\r\n plt.ylabel(\"Im(y)\") # ось ординат\r\n plt.grid()\r\n plt.show()\r\n","repo_name":"Ahmetova/Project0","sub_path":"pet_project_00/quadratic.py","file_name":"quadratic.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71569499283","text":"from threading import Thread\nimport asyncio\nimport sys\nimport nest_asyncio\nimport time\n\nnest_asyncio.apply()\n\n\n# Setup the asyncio event loop for subprocess management\nALOOP = asyncio.new_event_loop()\nALOOP_FOREVER = Thread(target=ALOOP.run_forever)\nALOOP_FOREVER.start()\n\n\nasync def test(index):\n \"\"\"\n Launch an asyncio subprocess.\n\n :param AigisPlugin plugin: the plugin\n \"\"\"\n print(\"Hello World \" + index)\n _ext_proc = await asyncio.create_subprocess_exec(\n *[\n sys.executable,\n \"-c\", \"import time;time.sleep(2);print('Sub done')\"\n ]\n )\n await waitforsub(_ext_proc)\n print(\"Checkem\")\n\nasync def waitforsub(index):\n print(\"Waiting for sub\")\n await index.wait()\n print(\"Done waiting for sub\")\n\n\nasync def normalwait():\n print(\"Sleeping...\")\n time.sleep(2)\n print(\"Woke\")\n\nasyncio.run_coroutine_threadsafe(normalwait(), ALOOP)\n\nasyncio.run_coroutine_threadsafe(test('A'), ALOOP)\n\n\nprint(\"Done\")","repo_name":"Zaltu/simple-examples","sub_path":"AsyncProcessWait/eternaloop.py","file_name":"eternaloop.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30869310771","text":"## Sort sentence pseudo-alphabetically\r\n## 6 kyu\r\n## https://www.codewars.com/kata/52dffa05467ee54b93000712\r\n\r\n\r\ndef pseudo_sort(st):\r\n st = ''.join(char for char in st if char not in '!@#$%^&*(),.?:;\"')\r\n words = st.split()\r\n upper = sorted([word.strip() for word in words if word[0] == word[0].upper()], reverse=True)\r\n lower = sorted([word.strip() for word in words if word[0] == word[0].lower()])\r\n sentence = lower + upper\r\n return ' '.join(sentence)\r\n \r\n","repo_name":"stereoabuse/codewars","sub_path":"problems/sort_sentence_pseudoalphabetically.py","file_name":"sort_sentence_pseudoalphabetically.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37039920678","text":"import streamlit as st\nimport numpy as np\nimport time\nimport sys\nimport itertools\n\n# Functions for helping us calculating alignments\n\nmatch = 3\nmismatch = -1\ngap = -2\n\n# A scoring function for two letters.\ndef match_score(letterA,letterB): # Score an individual alignment position\n if letterA == '-' and letterB == '-':\n return 0 # Irrelevant position\n elif letterA == '-' or letterB == '-':\n return gap # Gap penalty\n elif letterA == letterB:\n return match # Match\n else:\n return mismatch # Mismatch\n\n# A function that give a global alignmen scor of two gapped sequences.\ndef scoreSequences(a_seq,b_seq): # Score a alignment\n score, score_seq = 0, \"\"\n for a, b in zip(a_seq, b_seq):\n s = match_score(a, b)\n score += s\n score_seq += f\"{s:3}\"\n return score, score_seq\n\n\n# Utility function that creates a gapped sequence from a sequence and a list of insertions.\ndef getSeq(seq, inserts, alignment_length):\n out = \"\"\n for i,s in zip(inserts,seq):\n out += '-'*i\n out += s\n out += '-'*(alignment_length-len(out))\n return out\n\n\n\n\n# Streamlit code setting up a webform\nst.set_page_config(layout=\"wide\", page_icon=\"🎓\", page_title=\"Naive Alignment Calculator\")\nst.title(\"🎓 Naive Alignment Calculator\")\n\nst.write(\n \"This shows you a very naive way to calculate an optimal alignment\"\n)\n\nleft, mid, right = st.columns(3)\n\nleft.write(\"Fill in the two sequences you want to align:\")\nmid.write(\"Calculations:\")\nright.write(\"Optimal Alignment:\")\n\nform = left.form(\"template_form\")\na_seq = form.text_input(\"sequence A\",\"CGA\")\nb_seq = form.text_input(\"sequence B\",\"ACG\")\nmatch = form.number_input(\"match score\", value = match, max_value = 9, min_value = -9)\nmismatch = form.number_input(\"mismatch score\", value = mismatch, max_value = 9, min_value = -9)\ngap = form.number_input(\"gap penalty\", value = gap, max_value = 9, min_value = -9)\nsubmit = form.form_submit_button(\"Calculate!\")\n\nalignment_length = max(len(a_seq),len(b_seq))**2\n\n\na_box, b_box, score_seq_box, score_box = mid.empty(), mid.empty(), mid.empty(), mid.empty()\nm_a_box, m_b_box, m_score_seq_box, m_score_box = right.empty(), right.empty(), right.empty(), right.empty()\n\n\nif submit:\n # execute an excaustive alignment algorithm\n m = - sys.maxsize\n # Loop over all possible insertions in sequence a\n for a_inserts in itertools.product(list(range(len(a_seq))), repeat = len(a_seq)):\n a = getSeq(a_seq, a_inserts, alignment_length)\n a_box.text(' '.join(list(a)))\n # Loop over all possible insertions in sequence b\n for b_inserts in itertools.product(list(range(len(b_seq))),repeat = len(b_seq)):\n b = getSeq(b_seq,b_inserts, alignment_length)\n # Update status text.\n b_box.text(' '.join(list(b)))\n # Calculate the score of the alignment\n score, score_seq = scoreSequences(a, b)\n # Output the score to the webform\n score_box.text(f\"{score: >3}\")\n score_seq_box.text(score_seq)\n\n # Update the best alignment if we found a better one.\n if score > m:\n m_a_box.text(' '.join(list(a)))\n m_b_box.text(' '.join(list(b)))\n m_score_seq_box.text(score_seq)\n m_score_box.text(f\"{score}\")\n m = score\n # Slow us down a bit.\n time.sleep(.5) \n st.balloons()\n","repo_name":"kth-gt/cb2442","sub_path":"lect/align/code/naive.py","file_name":"naive.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43031946708","text":"\"\"\"\n给你一个包含n个整数的数组nums,判断 nums 中是否存在三个元素a,b,c,使得 a + b + c = 0 ?\n请你找出所有和为 0 且不重复的三元组。\n注意:答案中不可以包含重复的三元组。\n\n输入:nums = [-1,0,1,2,-1,-4]\n输出:[[-1,-1,2],[-1,0,1]]\n输入:nums = []\n输出:[]\n输入:nums = [0]\n输出:[]\n\n执行1: 解答错误 ([0,0,0] -> []) 错误考虑边界条件(>0的情况才应该排除,而不是>=0)\n执行2: 解答错误 ([-2,0,0,2,2] -> [[-2,0,2],[-2,0,2]]) 解决执行1的错误时没有举一反三想到左右指针所指元素也可能出现完全重复的情况\n\"\"\"\n\nfrom typing import Set\n\n\nclass Solution:\n def threeSum(self, nums: list) -> list:\n # 边界维护\n if len(nums) < 3:\n return []\n\n # 数组中不存在负数/0,不可能存在三元组\n SortedList = sorted(nums)\n if SortedList[0] > 0:\n return []\n\n # 从最小数开始使用左右指针查找\n Result = []\n ListLength = len(SortedList)\n a_idx = 0\n while ((a_idx < ListLength - 2) and SortedList[a_idx] <= 0):\n a = SortedList[a_idx]\n left_node = a_idx + 1\n right_node = ListLength - 1\n # print(\"start finding: a: {0}|{1}, leftnode: {2}, rightnode:{3}\".format(a_idx, a,left_node,right_node))\n\n # 左右指针\n while (left_node < right_node):\n b = SortedList[left_node]\n c = SortedList[right_node]\n CurrentSum = a + b + c\n # print(\"iter: a - ({0},{1}), b - ({2},{3}), c - ({4},{5})\".format(a_idx,a,left_node,b,right_node,c))\n if (CurrentSum == 0):\n # 添加结果\n Result.append([a,b,c])\n # print(\"find one: {0}|{1}|{2}\".format(a_idx, left_node, right_node))\n # 移动指针,跳过相同大小元素\n while (left_node < ListLength) and (SortedList[left_node] == b):\n left_node += 1\n while (right_node >= 0) and (SortedList[right_node] == c):\n right_node -= 1\n continue\n \n # 和比0小,移动左指针\n elif (CurrentSum < 0):\n left_node += 1\n \n # 和比0大,移动右指针\n else:\n right_node -= 1\n \n # 更新初始数所在位置\n while (a_idx + 1 < ListLength) and (SortedList[a_idx] == a):\n a_idx += 1\n # print(\"after update: a - {0}|{1}\".format(a_idx, SortedList[a_idx]))\n\n return Result\n\nsolution = Solution()\nnums = [-1]\nprint(solution.threeSum(nums))","repo_name":"AlAaraaf/leetcodelog","sub_path":"normal/leetcode15.py","file_name":"leetcode15.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27549700206","text":"class Person:\r\n def __init__(self, first_name, email):\r\n self.first_name = first_name\r\n self._email = email\r\n\r\n\r\ntk = Person('TK', 'tk@mail.com')\r\n# print(tk._email) # tk@mail.com\r\n# [pylint] W0212:Access to a protected member _email of a client class\r\n\r\n\"\"\"\r\nWe can access and update it. Non-public variables are just a convention and should be treated as a non-public part of the API.\r\n\"\"\"\r\n","repo_name":"loggar/py","sub_path":"py-core/class-object/class.8.private_var_constructor.py","file_name":"class.8.private_var_constructor.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2697909335","text":"import pybullet as p\nimport pybullet_data\n\n\nclass Plane:\n \"\"\"\n Class defining the Plane in the simulation environment.\n \"\"\"\n\n def __init__(self, client):\n \"\"\"\n Initializes the Plane object.\n\n Parameters:\n - client: the id of the physics client.\n \"\"\"\n\n # Set the search path to include PyBullet data\n p.setAdditionalSearchPath(pybullet_data.getDataPath())\n\n # Load the URDF model of the plane\n p.loadURDF('plane.urdf',\n basePosition=[0, 0, 0],\n physicsClientId=client)\n","repo_name":"jcob-sikorski/aicar","sub_path":"Driving/driving/resources/plane.py","file_name":"plane.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30271592848","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[8]:\n\n\nfrom pathlib import Path\nimport pandas as pd\nimport json\n\n\n# In[3]:\n\n\njsons = list(Path(\"./\").rglob(\"*.json\"))\n\n\n# In[4]:\n\n\njsons\n\n\n# structure that I want is, \n# 1 file per row, with a column that is named folder\n# \n# \n\n# In[29]:\n\n\ndef aggregator(jfile,collect):\n print(jfile)\n try:\n jdict= json.loads(open(f\"{jfile}\").read())\n for row in jdict:\n row[\"FolderName\"] = jfile.stem\n collect.extend(jdict)\n except Exception as e:\n print(e, jfile)\n \n \n\n\n# In[30]:\n\n\nres =[]\nfor j in jsons:\n aggregator(j,res)\n \n\n\n# In[31]:\n\n\ndf = pd.DataFrame(res)\n\ndf.to_csv(\"drive_files_analyzed.csv\")\n \n\n","repo_name":"DevinBayly/google_drive_size_profiling","sub_path":"drive-json-consolidator.py","file_name":"drive-json-consolidator.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23388770549","text":"import cv2 as cv\n\ndef face_detect_demo(img):\n #将图片灰度化\n gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)\n # 加载人脸特征数据\n face_detect = cv.CascadeClassifier(\n 'F:\\\\OpenCV\\\\opencv\\\\sources\\\\data\\\\haarcascades\\\\haarcascade_frontalface_default.xml')\n # 对人脸进行检测 返回值是人脸的左上角矩形区域的坐标以及宽度和高度\n faces = face_detect.detectMultiScale(gray,scaleFactor=1.01,minNeighbors=3,maxSize=(33,33),minSize=(28,28))#后三个参数控制人脸检测的效果\n for x,y,w,h in faces:\n cv.rectangle(img,(x,y),(x+w,y+h),color=(0,255,0),thickness=2)\n cv.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=2)\n #显示图片\n cv.imshow(\"img.jpg\",img)\n\n\n#加载图片\nimg = cv.imread(\"face2.jpg\")\n#调用人脸检测方法\nface_detect_demo(img)\ncv.waitKey(0)\ncv.destroyAllWindows()","repo_name":"YingnanHan/Python-400-Series","sub_path":"Python 400 集/Chapter25 人脸识别/06.检测多张人脸.py","file_name":"06.检测多张人脸.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"}
+{"seq_id":"15764810208","text":"from useragent import random_user_agent\nfrom lxml import etree, html\nimport feedparser\n\n\ndef read_rss(url: str, headers=None) -> list:\n items = list()\n headers = headers if headers else {\n 'User-Agent': random_user_agent(),\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',\n 'Accept': 'text/html,application/rss+xml,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',\n }\n feed = feedparser.parse(url, request_headers=headers)\n if feed:\n for item in feed['items']:\n link = item['guid']\n title = item['title']\n items.append({'url': link, 'title': title})\n else:\n print('Nothing found in feed', url)\n return\n return items\n\n\ndef extract_post_data(content: str) -> dict:\n tree = html.fragment_fromstring(content)\n post_text = tree.xpath(\"//div[@id='post-content-body']\")\n post_text = etree.tostring(post_text[0], pretty_print=True, encoding='utf-8').decode('utf-8')\n post_author = tree.xpath(\"//header/*/span[contains(@class, 'user-info__nickname') \"\n \"and contains(@class, 'user-info__nickname_small')]/text()\")[0]\n post_author_url = tree.xpath(\"//a[contains(@class, 'post__user-info') and contains(@class, 'user-info')]/@href\")[0]\n post_tags = tree.xpath(\"//ul[contains(@class, 'js-post-tags')]/*/a[contains(@class, 'inline-list__item-link') \"\n \"and contains(@class, 'post__tag')]/text()\")\n post_posted_at = tree.xpath(\"//span[contains(@class, 'post__time')]/@data-time_published\")[0]\n return {\n 'post_text': post_text,\n 'post_author': post_author,\n 'post_author_url': post_author_url,\n 'post_tags': post_tags,\n 'post_posted_at': post_posted_at,\n }\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"dorokhin/web_scraper","sub_path":"adapters/habr.py","file_name":"habr.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70336491922","text":"from train import BASEWIDTH\nfrom util import * \nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nfrom models.unet import *\n\n\nLEARNING_RATE = 1e-6\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nBATCH_SIZE = 1\nNUM_EPOCHS = 35\nNUM_WORKERS = 1\nIMAGE_HEIGHT = 368 \nIMAGE_WIDTH = 640 \nPIN_MEMORY = True\nLOAD_MODEL = True\nTRAIN_IMG_DIR = '/y/ayhassen/epick_object_crop/Images/crop_fit/train' \nTRAIN_MASK_DIR = '/y/ayhassen/epick_object_crop/Masks/crop_fit/train'\nVAL_IMG_DIR = '/y/ayhassen/epick_object_crop/Images/crop_fit/val' \nVAL_MASK_DIR = '/y/ayhassen/epick_object_crop/Masks/crop_fit/val' \n\n# TRAIN_IMG_DIR = '/y/ayhassen/epick_dataset/Images/train'\n# TRAIN_MASK_DIR = '/y/ayhassen/epick_dataset/Masks/train/objects'\n# VAL_IMG_DIR = '/y/ayhassen/epick_dataset/Images/val'\n# VAL_MASK_DIR = '/y/ayhassen/epick_dataset/Masks/val/objects'\n\n# TRAIN_MASK_DIR = \"/y/relh/epickitchens/Annotations/train\"\n# VAL_MASK_DIR = \"/y/relh/epickitchens/Annotations/val\"\n# TRAIN_IMG_DIR = \"/y/ayhassen/epick_dataset/Images/train\"\n# VAL_IMG_DIR = \"/y/ayhassen/epick_dataset/Images/val\"\n\n\ntrain_transform = A.Compose(\n [\n A.Resize(height=640, width=640),\n A.Normalize(\n mean=[0.0, 0.0, 0.0],\n std=[1.0, 1.0, 1.0],\n max_pixel_value=255.0,\n ),\n ToTensorV2(),\n ],\n) \n\nval_transforms = A.Compose(\n [\n A.Resize(height=640, width=640),\n A.Normalize(\n mean=[0.0, 0.0, 0.0],\n std=[1.0, 1.0, 1.0],\n max_pixel_value=255.0,\n ),\n ToTensorV2(),\n ],\n)\n\ntrain_loader, val_loader = get_loaders(\n TRAIN_IMG_DIR,\n TRAIN_MASK_DIR,\n VAL_IMG_DIR,\n VAL_MASK_DIR,\n BATCH_SIZE,\n train_transform,\n val_transforms,\n NUM_WORKERS,\n PIN_MEMORY,\n )\n\nmodel = Unet().to(DEVICE)\n\nif LOAD_MODEL:\n load_checkpoint(torch.load(\"./dilated_conv.pth\"), model)\n\n# check_accuracy(val_loader, model, device=DEVICE) \nsave_predictions_as_imgs(\n val_loader, model, folder=\"dilated_conv/\", device=DEVICE\n ) ","repo_name":"ashhass/HOS","sub_path":"random_stuff/dilated_convolution/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41219357626","text":"\"\"\"\nGiven an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.\n\nExample 1:\nInput: intervals = [[0,30],[5,10],[15,20]]\nOutput: 2\n\"\"\"\nimport heapq\n\n\nclass Solution(object):\n def minMeetingRooms(self, intervals):\n \"\"\"\n :type intervals: List[List[int]]\n :rtype: int\n \"\"\"\n # sort intervals in ascending order by start-i\n intervals.sort(key=lambda x: x[0])\n \n # use a heap to record the meeting rooms are currently using\n room_heap = []\n heapq.heappush(room_heap, intervals[0][1])\n\n # traverse the intervals\n for i in range(1, len(intervals)):\n cur_interval = intervals[i]\n\n # if there is no overlap between cur_interval and last meeting room time\n if room_heap[0] <= cur_interval[0]:\n heapq.heappop(room_heap)\n heapq.heappush(room_heap, cur_interval[1])\n\n return len(room_heap)","repo_name":"BrianQJN/Daily-Leecode-Prac","sub_path":"Intervals/253_Meeting_RoomsII.py","file_name":"253_Meeting_RoomsII.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24790298296","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nfrom PIL import Image\r\n\r\nusername = input(\"请输入用户名: \")\r\npassword = input(\"请输入登陆密码: \")\r\n\r\nimgurl = \"https://www.zhihu.com/captcha.gif?type=login\"\r\nurl = \"http://www.zhihu.com/login/{0}\".format(\"phone_num\")\r\nhome = \"https://www.zhihu.com\"\r\nheaders = {\r\n \"Host\":\"www.zhihu.com\",\r\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0\",\r\n \"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\r\n \"Accept-Language\":\"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3\",\r\n \"Accept-Encoding\":\"gzip, deflate, br\",\r\n \"Referer\":\"https://www.zhihu.com/\",\r\n \"Connection\":\"keep-alive\",\r\n \"Upgrade-Insecure-Requests\":\"1\"\r\n}\r\ns = requests.session()\r\nhtml = s.get(home,headers = headers).text\r\nbsj = BeautifulSoup(html,'lxml')\r\nxsrf = bsj.find(\"input\",{\"name\":\"_xsrf\"})['value']\r\n\r\nimg = s.get(imgurl,headers = headers).content\r\n\r\nwith open('captcha.gif','wb+') as f:\r\n f.write(img)\r\n f.close()\r\ncimg = Image.open('captcha.gif')\r\ncimg.show()\r\ncaptcha = input(\"请输入验证码: \")\r\n\r\npost_data = {\r\n \"_xsrf\":xsrf,\r\n \"password\":password,\r\n \"remember_me\":\"true\",\r\n \"phone_num\":username,\r\n \"captcha\":captcha\r\n}\r\nwer = s.post(url, data=post_data, headers=headers)\r\nif wer.json()[\"r\"] == 0:\r\n print(\"登录成功\")\r\nelse:\r\n print(\"登录失败\")\r\n print(\"错误信息 --->\", wer.json()[\"msg\"])\r\nhomeurl = \"https://www.zhihu.com/\"\r\nhomepage = s.get(homeurl,headers = headers)\r\nprint(homepage.text)\r\n\r\n\r\n\r\n","repo_name":"gaokaigithub/myspider","sub_path":"fen.py","file_name":"fen.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"33495638540","text":"# -*- coding: UTF-8 -*-\nimport sys\nimport os\nimport numpy as np\nimport time\n\ndef log_enable():\n\t#logging setting\n\timport logging\n\tif not os.path.exists('./log'):\n\t\tos.makedirs('./log')\n\n\tfile_name = os.path.basename(sys.argv[0])\n\ttimestr = time.strftime(\"%Y%m%d_%H%M%S\")\n\n\tlog_file = \"./log/\"+file_name+\"_\"+timestr+\".log\"\n\tlog_level = logging.DEBUG\n\tlogger = logging.getLogger(file_name)\n\thandler = logging.FileHandler(log_file, mode='w')\n\tformatter = logging.Formatter(\"[%(levelname)s][%(funcName)s]\\\n\t[%(asctime)s]%(message)s\")\n\thandler.setFormatter(formatter)\n\tlogger.addHandler(handler)\n\tlogger.setLevel(log_level)\n\n\treturn logger\n\ndef solve(Q, w2v_model, neighbor=1, logger=False):\n\tif logger:\n\t\t_logger = log_enable()\n\n\t## word2vec\n\tquestion = Q['question']\n\tchoices = Q['choices'].copy()\n\twordvec = []\n\tblank_index = question.index('')\n\n\tif len(question) is 0 or len(choices) is 0:\n\t\treturn None\n\n\t# convert question to vector\n\t#for i in range(blank_index-neighbor, blank_index+neighbor+1):\n\tfor i in range(len(question)):\n\t\tif question[i]=='':\n\t\t\tcontinue\n\t\tif question[i].decode('utf8') in w2v_model:\n\t\t\twordvec.append(w2v_model[question[i].decode('utf8')])\n\n\t# convert choices to vector\n\tfor key, value in choices.iteritems():\n\t\tif value.decode('utf8') in w2v_model:\n\t\t\tchoices[key] = w2v_model[value.decode('utf8')]\n\t\telse:\n\t\t\tchoices[key] = np.zeros(128)\n\n\tif logger:\n\t\t_logger.debug('wordvec')\n\t\t_logger.debug(wordvec)\n\t\t_logger.debug('choices')\n\t\t_logger.debug(choices)\n\n\t## calculate mean vector\n\t_mean = np.asarray(np.mean(wordvec, axis=0))\n\tif logger:\n\t\t_logger.debug('wordvec maen')\t\t\n\t\t_logger.debug(_mean)\n\n\t## find who is the closest one to mean\n\tdis = []\t\n\tfor key, value in choices.iteritems():\n\t\tchoices[key] = (np.linalg.norm(value-_mean))\n\n\t_sum = sum(list(choices.values()))\n\tfor key, value in choices.iteritems():\n\t\tchoices[key] = 1-value/_sum\n\t\t\n\t#ans = min(choices, key=choices.get)\n\n\t# calculate softmax\n\t_max = choices[max(choices, key=choices.get)]\n\t_sum = np.exp([x-_max for x in list(choices.values())]).sum()\n\t#_sum = sum(np.exp(choices.itervalues()))\n\tfor key, value in choices.iteritems():\n\t\tchoices[key] = np.exp(value - _max)/_sum\n\n\tif logger:\n\t\t_logger.debug('choices')\n\t\t_logger.debug(choices)\n\n\treturn choices","repo_name":"BlakePan/pixnethackathon2016_AI_Cloze","sub_path":"mymodel/mymodel_mk1.py","file_name":"mymodel_mk1.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2287501248","text":"#https://www.acmicpc.net/problem/9095\n\nimport sys\n\nT = int(sys.stdin.readline().strip())\n\narr = [-1 for _ in range(11)]\nresults = []\n\narr[0] = 0\narr[1] = 1\narr[2] = 2\narr[3] = 4\n\ndef dpSum(num):\n global arr\n if arr[num] == -1:\n arr[num] = dpSum(num-1) + dpSum(num-2) + dpSum(num-3)\n return arr[num]\n else:\n return arr[num]\n\n\nfor _ in range(T):\n results.append(dpSum(int(sys.stdin.readline().strip())))\n\nfor result in results:\n print(result)","repo_name":"Myunwoo/algorithm_study","sub_path":"solved.ac_3/baek9095.py","file_name":"baek9095.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"11215912692","text":"import sys\nimport getopt\n\nsys.path.append('/opt/trex/current/automation/trex_control_plane/stl/examples')\nsys.path.append('./v2.48/automation/automation/trex_control_plane/interactive/trex/examples')\nsys.path.append('./v2.48/automation/trex_control_plane/interactive/trex/examples/stl')\nsys.path.append('./v2.48/automation/trex_control_plane/stf/trex_stf_lib/')\nsys.path.append('./v2.49/automation/automation/trex_control_plane/interactive/trex/examples')\nsys.path.append('./v2.49/automation/trex_control_plane/interactive/trex/examples/stl')\nsys.path.append('./v2.49/automation/trex_control_plane/stf/trex_stf_lib/')\nsys.path.append('./v2.59/automation/trex_control_plane/interactive/trex/examples')\nsys.path.append('./v2.59/automation/trex_control_plane/interactive/trex/examples/stl')\nsys.path.append('./v2.59/automation/trex_control_plane/stf/trex_stf_lib/')\nsys.path.append(\"./v2.71/automation/trex_control_plane/interactive/trex/examples/\")\nsys.path.append(\"./v2.71/automation/trex_control_plane/interactive/trex/examples/stl\")\nsys.path.append(\"./v2.71/automation/trex_control_plane/stf/trex_stf_lib/\")\nsys.path.append(\"./v2.82/automation/trex_control_plane/interactive/trex/examples/\")\nsys.path.append(\"./v2.82/automation/trex_control_plane/interactive/trex/examples/stl\")\nsys.path.append(\"./v2.82/automation/trex_control_plane/stf/trex_stf_lib/\")\n\n\nimport trex_client\nimport trex_status\nimport stl_path\nfrom trex_stl_lib.api import *\nimport json\nimport argparse\n\nclass TrexTest(object):\n def __init__(self, trex_host,pkt_size=64,duration=10,max_try=10,vlan_flag=False,dst_mac=None):\n self.trex_host = trex_host\n self.pkt_size = pkt_size - 4\n self.duration = duration\n self.max_try = max_try \n self.vlan_flag = vlan_flag\n self.dst_mac = dst_mac\n pass\n \n def create_stl_client(self):\n self.client = None\n self.client = STLClient(server=self.trex_host)\n return self.client\n \n\n def build_test_stream_basic(self):\n l2 = Ether()\n if self.vlan_flag == True:\n self.base_pkt = l2/Dot1Q(vlan=3)/IP(src=\"192.168.100.10\",dst=\"192.168.100.20\")/UDP(dport=12, sport=1025)\n else:\n self.base_pkt = l2/IP(src=\"192.168.100.10\", dst=\"192.168.100.20\")/UDP(dport=12, sport=1025)\n\n self.pad = max(0, self.pkt_size - len(self.base_pkt)) * 'x'\n\n return STLStream(isg=10.0,\n packet=STLPktBuilder(pkt=self.base_pkt/self.pad),\n #flow_stats=STLFlowStats(pg_id=1),\n flow_stats=None,\n mode=STLTXCont(percentage=100)\n )\n\n def build_test_stream(self):\n self.all_stream = []\n temp_stream = self.build_test_stream_basic()\n self.all_stream.append(temp_stream)\n self.streams = STLProfile(streams=self.all_stream).get_streams()\n return self.streams\n\n def test_stream_create(self,src_mac,dst_mac):\n l2 = Ether(dst=dst_mac,src=src_mac)\n pad = max(0, self.pkt_size - len(l2)) * 'x'\n return STLStream(isg=10.0,\n packet=STLPktBuilder(pkt=l2 / pad),\n #flow_stats=STLFlowStats(pg_id=1),\n flow_stats=None,\n mode=STLTXCont(percentage=100)\n )\n \n def create_stream_for_pvp(self,dst_mac):\n l2 = Ether(dst=dst_mac)/IP(src=\"192.168.100.10\", dst=\"192.168.100.20\")/UDP(dport=12, sport=1025)\n pad = max(0, self.pkt_size - len(l2)) * 'x'\n return STLStream(isg=10.0,\n packet=STLPktBuilder(pkt=l2 / pad),\n #flow_stats=STLFlowStats(pg_id=1),\n flow_stats=None,\n mode=STLTXCont(percentage=100)\n )\n\n\n def test_conn_ok(self):\n if self.client:\n all_ports = self.client.get_all_ports()\n self.client.reset(all_ports)\n self.port_stream_map = {}\n self.dst_mac_list = str(self.dst_mac).split(\" \")\n all_stream = []\n\n all_stream.append(self.create_stream_for_pvp(self.dst_mac_list[0]))\n all_stream.append(self.create_stream_for_pvp(self.dst_mac_list[1]))\n\n print(self.client.get_port_attr(0))\n print(self.client.get_port_attr(1))\n for port in all_ports:\n for stream in all_stream:\n self.client.reset(all_ports)\n # self.client.set_port_attr(ports=all_ports, promiscuous=False)\n self.client.set_port_attr(ports=all_ports, promiscuous=True)\n self.client.acquire(ports=all_ports, force=True)\n self.client.add_streams(stream, ports=port)\n print(\"start test conn test with 1pps duration 10s \")\n #print(stream)\n #print(\"port:{} \".format(port))\n #stream.to_pkt_dump()\n self.client.start(ports=port,mult=\"1pps\", duration=10)\n self.client.wait_on_traffic(ports=all_ports)\n ret_stat=self.client.get_stats(ports = all_ports)\n # from pprint import pprint\n # pprint(ret_stat)\n \"\"\"\n 'total': {'ibytes': 680,\n 'ierrors': 0,\n 'ipackets': 10,\n 'obytes': 680,\n 'oerrors': 0,\n 'opackets': 10,\n 'rx_bps': 538.2561645507812,\n 'rx_bps_L1': 696.5668067932129,\n 'rx_pps': 0.9894415140151978,\n 'rx_util': 6.965668067932129e-06,\n 'tx_bps': 538.7817132472992,\n 'tx_bps_L1': 697.2469528019428,\n 'tx_pps': 0.9904077472165227,\n 'tx_util': 6.9724695280194286e-06}}\n \"\"\"\n if ret_stat[\"total\"][\"ipackets\"] >= ret_stat[\"total\"][\"opackets\"] and ret_stat[\"total\"][\"ipackets\"] > 0:\n print(\"***********************************************************************\")\n print(\"Port info {}\".format(port))\n print(self.client.get_port_attr(port))\n print(ret_stat[\"total\"])\n print(\"Below Stream Info\")\n stream.to_pkt_dump()\n print(\"***********************************************************************\")\n self.port_stream_map[port] = stream\n # import pdb\n # pdb.set_trace()\n if len(self.port_stream_map) > 0 :\n return True\n else:\n return False\n else:\n return False\n\n def test_one_cycle(self,speed_percent=\"100%\",duration=10):\n all_ports = self.client.get_all_ports()\n self.client.reset(all_ports)\n self.client.set_port_attr(ports=all_ports, promiscuous=True)\n self.client.acquire(ports=all_ports,force=True)\n #self.client.add_streams(self.port_stream_map[0],ports=all_ports)\n for key in self.port_stream_map.keys():\n self.client.add_streams(self.port_stream_map[key],ports=key)\n #self.client.add_streams(self.streams,ports=all_ports)\n self.client.clear_stats()\n print(\"start {} throughput begin\".format(speed_percent))\n self.client.start(ports=all_ports, mult=speed_percent, duration=duration)\n self.client.wait_on_traffic(ports=all_ports)\n return self.client.get_stats(ports=all_ports)\n\n def start_test(self):\n self.client.connect()\n self.test_conn_ok()\n print(\"Begin performance now\")\n #import time\n #time.sleep(10000)\n max_value = 100\n min_value = 0\n cur_value = 100\n for i in range(self.max_try):\n print(\"Current try {} cycle \".format(i))\n stat = self.test_one_cycle(str(cur_value)+\"%\")\n \"\"\"\n {\n \"global\": {\n \"cpu_util\": 20.869110107421875,\n \"rx_cpu_util\": 0.0,\n \"bw_per_core\": 21.410884857177734,\n \"tx_bps\": 15638914048.0,\n \"tx_pps\": 27150892.0,\n \"rx_bps\": 13119664128.0,\n \"rx_pps\": 22777192.0,\n \"rx_drop_bps\": 2519249920.0,\n \"queue_full\": 0\n },\n \"1\": {\n \"opackets\": 135869430,\n \"ipackets\": 113993959,\n \"obytes\": 9782598960,\n \"ibytes\": 8207565048,\n \"oerrors\": 0,\n \"ierrors\": 0,\n \"tx_bps\": 7819472384.0,\n \"tx_pps\": 13575472.0,\n \"tx_bps_L1\": 9991547904.0,\n \"tx_util\": 99.91547904,\n \"rx_bps\": 6560308736.0,\n \"rx_pps\": 11389424.0,\n \"rx_bps_L1\": 8382616576.0,\n \"rx_util\": 83.82616576000001\n },\n \"0\": {\n \"opackets\": 135869430,\n \"ipackets\": 113970768,\n \"obytes\": 9782598960,\n \"ibytes\": 8205895296,\n \"oerrors\": 0,\n \"ierrors\": 0,\n \"tx_bps\": 7819441664.0,\n \"tx_pps\": 13575420.0,\n \"tx_bps_L1\": 9991508864.0,\n \"tx_util\": 99.91508864000001,\n \"rx_bps\": 6559354880.0,\n \"rx_pps\": 11387768.0,\n \"rx_bps_L1\": 8381397760.0,\n \"rx_util\": 83.8139776\n },\n \"total\": {\n \"opackets\": 271738860,\n \"ipackets\": 227964727,\n \"obytes\": 19565197920,\n \"ibytes\": 16413460344,\n \"oerrors\": 0,\n \"ierrors\": 0,\n \"tx_bps\": 15638914048.0,\n \"tx_pps\": 27150892.0,\n \"tx_bps_L1\": 19983056768.0,\n \"tx_util\": 199.83056768,\n \"rx_bps\": 13119663616.0,\n \"rx_pps\": 22777192.0,\n \"rx_bps_L1\": 16764014336.0,\n \"rx_util\": 167.64014336000002\n },\n \"flow_stats\": {},\n \"latency\": {}\n }\n \"\"\"\n print(json.dumps(stat, indent=4, sort_keys=False))\n if stat[\"total\"][\"opackets\"] > stat[\"total\"][\"ipackets\"]:\n max_value = cur_value\n cur_value = (min_value + max_value)/(2 * 1.0)\n else:\n self.last_value = cur_value\n min_value = cur_value\n cur_value = (min_value + max_value)/(2 * 1.0)\n last_result = json.dumps(stat[\"total\"], indent=4, sort_keys=False)\n self.last_value = cur_value\n self.last_result = last_result\n print(last_result)\n \n self.client.disconnect()\n return self.last_result\n\n def report_test_result(self):\n print(\"x\"*100)\n \n if self.last_result:\n print(self.last_result)\n else:\n print(\"Trex throughput performance failed \")\n print(\"x\"*100)\n\n def start_trex_server(self):\n trex = trex_client.CTRexClient(self.trex_host,trex_args=\"--no-ofed-check\")\n #trex = trex_client.CTRexClient(self.trex_host)\n trex.force_kill(confirm=False)\n time.sleep(3)\n print(\"Before Running, TRex status is: {}\".format(trex.is_running()))\n print(\"Before Running, TRex status is: {}\".format(trex.get_running_status()))\n\n self.trex_config = trex.get_trex_config()\n import yaml\n t_config_obj = yaml.load(self.trex_config)\n \"\"\"\n - version: 2\n interfaces: ['05:00.0', '05:00.1']\n #interfaces: ['enp5s0f0', 'enp5s0f1']\n port_info:\n - dest_mac: 90:e2:ba:29:bf:15 # MAC OF LOOPBACK TO IT'S DUAL INTERFACE\n src_mac: 90:e2:ba:29:bf:14\n - dest_mac: 90:e2:ba:29:bf:14 # MAC OF LOOPBACK TO IT'S DUAL INTERFACE\n src_mac: 90:e2:ba:29:bf:15\n\n platform:\n master_thread_id: 0\n latency_thread_id: 1\n dual_if:\n - socket: 0\n threads: [2,4,6,8,10,12,14]\n \"\"\"\n core_num = len(t_config_obj[0]['platform']['dual_if'][0]['threads'])\n #t_config_obj[\"platform\"][\"dual_if\"][\"threads\"].len()\n trex.trex_args = \"-c {} {}\".format(core_num,\"--no-ofed-check\")\n trex.start_stateless()\n #trex.get_trex_config()\n print(\"After Starting, TRex status is: {},{}\".format(trex.is_running(), trex.get_running_status()))\n # import time\n # time.sleep(5)\n # print(\"Is TRex running? {},{}\".format(trex.is_running(), trex.get_running_status()))\n self.trex = trex \n self.trex_config = trex.get_trex_config()\n return self.trex\n\n def start_all_test(self):\n self.start_trex_server()\n #import time\n #time.sleep(60)\n self.create_stl_client()\n self.build_test_stream()\n self.start_test()\n self.report_test_result()\n\nif __name__ == \"__main__\":\n\n\n parser = argparse.ArgumentParser(description='Test ovs dpdk bonding trex')\n parser.add_argument('-c', '--connect', type=str,help='trex server ip ', required=True)\n parser.add_argument('-m', '--maxcycle', type=int,help='get no loss packets cycle times', required=False)\n parser.add_argument('-t', '--time', type=int,help='one time test duration', required=False)\n parser.add_argument('-s', '--pkt_size', type=int,help='init packet size', required=False)\n parser.add_argument('-v', '--vlan', type=bool,help='enable vlan or else', required=False)\n parser.add_argument('-d', '--dst_mac', type=str,help='packet dest mac', required=False)\n args = parser.parse_args()\n print(args)\n if args.connect:\n trex_obj = TrexTest(args.connect,\n pkt_size=args.pkt_size,\n duration=args.time,\n max_try=args.maxcycle,\n vlan_flag=args.vlan,\n dst_mac=args.dst_mac)\n trex_obj.start_all_test()\n else:\n parser.print_help()\n import sys\n sys.exit(1)\n\n\n\n","repo_name":"ctrautma/RHEL_NIC_QUALIFICATION","sub_path":"throughput-test/trex_sport.py","file_name":"trex_sport.py","file_ext":"py","file_size_in_byte":14418,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"}
+{"seq_id":"71920546962","text":"import pygame\nfrom math import sqrt\n\ndef dist(p1, p2):\n x = p1[0] - p2[0]\n y = p1[1] - p2[1]\n return sqrt(x * x + y * y)\n\ndef get_abc(p1, p2):\n a = 1\n if p1[1] - p2[1] != 0:\n b = -(p1[0] - p2[0]) / (p1[1] - p2[1])\n else:\n a = 0\n b = 1\n c = -(p1[0] + b * p1[1])\n return a, b, c\n\ndef true_coll(p1, p2, o, r):\n a = dist(p1, p2)\n b = dist(p1, o)\n c = dist(p2, o)\n p = (a + b + c) / 2\n s = sqrt(p * (p - a) * (p - b) * (p - c))\n h = s / a * 2\n if h <= r:\n a, b, c = get_abc(p1, p2)\n d = o[0]\n e = o[1]\n aa = b ** 2 + 1\n bb = 2 * (b * d + b * c - e)\n cc = (c + d) ** 2 + e ** 2 - r ** 2\n dd = bb ** 2 - 4 * aa * cc\n print(c, d, e)\n dd = sqrt(dd)\n y1 = (-bb + dd) / (2 * aa)\n y2 = (-bb - dd) / (2 * aa)\n yy1 = y1 >= min(p1[1], p2[1]) and y1 <= max(p1[1], p2[1])\n yy2 = y2 >= min(p1[1], p2[1]) and y2 <= max(p1[1], p2[1])\n return yy1 or yy2\n return False\n\ndef coll(p1, p2, o, r):\n a = dist(p1, p2)\n b = dist(p1, o)\n c = dist(p2, o)\n p = (a + b + c) / 2\n s = sqrt(p * (p - a) * (p - b) * (p - c))\n h = s / a * 2\n if h <= r:\n if not p2[0]-p1[0] == 0:\n a = (p2[1]-p1[1])/(p2[0]-p1[0])\n else:\n a=9999999999999999\n b = p1[1]-a*p1[0]\n aa = a ** 2 + 1\n bb = 2 * (o[0] - (b - o[1]) * a)\n cc = (b - o[1]) ** 2 - r ** 2 + o[0] ** 2\n d = bb ** 2 - 4 * aa * cc\n d = sqrt(d)\n x1 = (bb + d) / (2 * aa)\n x2 = (bb - d) / (2 * aa)\n xx1 = x1 > min(p1[0], p2[0]) and x1 < max(p1[0], p2[0])\n xx2 = x2 > min(p1[0], p2[0]) and x2 < max(p1[0], p2[0])\n y1 = a * x1 + b\n y2 = a * x2 + b\n return xx1 or xx2\n return False\n\nppos = [100, 100]\n\npv = [0, 0]\n\nr = 10\n\nline = [[200, 200], [300, 200]]\n\nscreen = pygame.display.set_mode((400, 400))\n\ndone = False\n\npoints = False\n\nwhile not done:\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n done = True\n if e.type == pygame.KEYDOWN:\n if e.scancode == 17:\n pv[1] = -0.1\n if e.scancode == 30:\n pv[0] = -0.1\n if e.scancode == 31:\n pv[1] = 0.1\n if e.scancode == 32:\n pv[0] = 0.1\n if e.type == pygame.KEYUP:\n if e.scancode == 17 and pv[1] < 0:\n pv[1] = 0\n if e.scancode == 30 and pv[0] < 0:\n pv[0] = 0\n if e.scancode == 31 and pv[1] > 0:\n pv[1] = 0\n if e.scancode == 32 and pv[0] > 0:\n pv[0] = 0\n screen.fill((0, 0, 0))\n ppos[0] += pv[0]\n points = true_coll(line[0], line[1], ppos, r)\n if points:\n ppos[0] -= pv[0]\n ppos[1] += pv[1]\n points = true_coll(line[0], line[1], ppos, r)\n if points:\n ppos[1] -= pv[1]\n\n pygame.draw.circle(screen, (255, 255, 255), [int(ppos[0]), int(ppos[1])], r)\n\n pygame.draw.line(screen, (255, 255, 255), line[0], line[1])\n\n #pygame.draw.circle(screen, (255, 255, 255), (200, 250), 3)\n #if points:\n # if points[0]:\n # pygame.draw.circle(screen, (0, 255, 0), [int(points[2][0]), int(points[2][1])], 3)\n # if points[1]:\n # pygame.draw.circle(screen, (0, 255, 0), [int(points[3][0]), int(points[3][1])], 3)\n\n pygame.display.update()\npygame.quit()\n","repo_name":"ArturLukianov/yandex-games","sub_path":"FallingDagger/collision.py","file_name":"collision.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26216856314","text":"#!/usr/bin/python\n# coding: utf-8\n\n\ndef test(n):\n \"\"\"Sums consecutive numbers from 0 to `n`.\n\n Parameters\n ----------\n n : int\n maximum integer\n \"\"\"\n\n s = 0\n for i in range(0, n):\n s += i\n return s\n","repo_name":"kgryte/micro-benchmarks-numeric-computing","sub_path":"benchmarks/python/tests/sum.py","file_name":"sum.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"40134004406","text":"import textwrap\nfrom utils import format\n\nimport string\nvalid_id = string.ascii_lowercase + string.ascii_uppercase + string.digits + \"_\"\ndef name_id(name, upper=False):\n if not upper:\n name = name.replace(\" \", \"\")\n else:\n name = name.upper().replace(\" \", \"_\")\n name = name.replace(\"-\", \"_\")\n name = \"\".join([char for char in name if char in valid_id])\n while name[0] in string.digits:\n name = name[1:]\n name = name[0].upper() + name[1:]\n return name\n\ndef Card(*, name, type, target, color, rarity, cost, const=None, flags=None, desc, upgrade_desc=None, **kwargs):\n if cost == \"x\":\n cost = -1\n if const is None:\n const = {}\n if flags is None:\n flags = {}\n\n if target == \"all_enemies\":\n flags[\"isMultiDamage\"] = \"true\"\n\n code = dict(use=None, upgrade=None, methods=\"\")\n arg = kwargs.pop(\"code\", None)\n if arg: code[\"use\"] = arg\n arg = kwargs.pop(\"upgrade_code\", None)\n if arg: code[\"upgrade\"] = textwrap.dedent(\"\"\"\n if (!this.upgraded) {{\n {}\n }}\n \"\"\").strip().format(textwrap.indent(textwrap.dedent(arg).strip(), \" \" * 4).lstrip())\n arg = kwargs.pop(\"upgrade_code_FULL\", None)\n if arg: code[\"upgrade\"] = arg\n arg = kwargs.pop(\"methods\", None)\n if arg: code[\"methods\"] = arg\n if not code[\"use\"] and type == \"power\":\n stacks = 1 if not \"MAGIC_NUMBER\" in const else \"magicNumber\"\n code[\"use\"] = format(\"\"\"\n AbstractDungeon.actionManager.addToBottom(\n new ApplyPowerAction(p, p, new {{ name_id(name) }}Power(p, {{ stacks }}), {{ stacks }})\n );\n \"\"\")\n code = {name: textwrap.dedent(impl).strip() for name, impl in code.items()}\n if kwargs:\n raise SyntaxError(kwargs)\n\n return dict(\n name = name,\n type = type,\n target = target,\n color = color,\n rarity = rarity,\n cost = cost,\n const = const,\n flags = flags,\n desc = desc,\n upgrade_desc = upgrade_desc,\n code = code,\n )\n\ndef Power(*, id=None, name, desc, init=None, code, icon=None, **kwargs):\n if id is None:\n id = name_id(name)\n id = id + \"Power\"\n if init:\n init = textwrap.dedent(init).strip()\n desc_code = None\n arg = kwargs.pop(\"desc_expr\", None)\n if arg: desc_code = \"description = {};\".format(arg)\n arg = kwargs.pop(\"desc_CODE\", None)\n if arg: desc_code = textwrap.dedent(arg).strip()\n code = textwrap.dedent(code).strip()\n if kwargs:\n raise SyntaxError(kwargs)\n return dict(\n id = id,\n name = name,\n desc = desc,\n desc_code = desc_code,\n init = init,\n code = code,\n icon = icon,\n )\n\ndef Action(*, id, args=None, flags=None, **kwargs):\n if args is not None:\n vars = [line.split() for line in args.strip().splitlines()]\n else:\n vars = []\n if flags is None:\n flags = {}\n code = None\n arg = kwargs.pop(\"code\", None)\n if arg: code = textwrap.dedent(\"\"\"\n @Override\n public void update() {{\n {}\n }}\n \"\"\").strip().format(textwrap.indent(textwrap.dedent(arg).strip(), \" \" * 4).lstrip())\n arg = kwargs.pop(\"code_FULL\", None)\n if arg: code = textwrap.dedent(arg).strip()\n if kwargs:\n raise SyntaxError(kwargs)\n\n return dict(\n id = id,\n vars = vars,\n flags = flags,\n code = code,\n )\n\ndef Java(*, path, base=None, code):\n path = path.split(\".\")\n code = textwrap.dedent(code).strip()\n return dict(\n package = path[:-1],\n name = path[-1],\n base = base,\n code = code,\n )\n","repo_name":"MrCoft/EngiMod","sub_path":"spire.py","file_name":"spire.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17921883544","text":"#coding:utf8\n\n#导入spark的相关包\nfrom pyspark import SparkConf,SparkContext\n\nif __name__ == '__main__':\n\n # 初始化执行环境,构建SparkContext对象\n conf = SparkConf().setAppName(\"test_create1\").setMaster(\"local[*]\")\n sc = SparkContext(conf=conf)\n\n #演示通过并行化集合的方式去创建RDD,本地集合->分布式对象的转化\n rdd1 = sc.parallelize([1, 2, 3, 4, 5, 6, 7, 8, 9])\n # 查看默认分区\n print(\"默认分区数:\",rdd1.getNumPartitions())\n\n rdd2 = sc.parallelize([1, 2, 3],3)\n print(\"分区数:\",rdd2.getNumPartitions())\n\n # collect方法,是将RDD中每个分区的数据,都发送到Driver中,形成一个Python LIst对象进行输出的\n print(rdd1.collect())\n\n\n\n\n\n\n","repo_name":"Jermyn-code/python_code","sub_path":"Spark/RDD-教师示例/01_RDD_create_parallelize.py","file_name":"01_RDD_create_parallelize.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23343721040","text":"import os\nfrom collections import Callable\n\nfrom dataclasses import dataclass\nfrom os import walk\nfrom typing import List\n\nfrom matplotlib import pyplot as plt\nfrom reamber.osu import OsuMap\nfrom keras.layers import Dense, Dropout, GRU\nfrom tqdm import tqdm\n\nfrom consts import CONSTS\nfrom input import Preprocessing\nfrom osrparse.mania import ManiaHitError\n\nimport numpy as np\nfrom tensorflow import keras\n\n\n\n@dataclass\nclass LSTMModel:\n regressor: keras.Model\n key: int\n threshold: int = CONSTS.NEIGHBOUR_THRESHOLD\n window:int = CONSTS.WINDOW\n epochs:int = CONSTS.EPOCHS\n batch_size:int = CONSTS.BATCH_SIZE\n verbose: int = 1\n overwrite_data: bool = False\n aggregated: bool = False\n aggregation_method: Callable = np.median\n\n @staticmethod\n def load_model(key: int, aggregated: bool = False, aggregation_method=CONSTS.AGG_METHOD):\n return LSTMModel(keras.models.load_model(LSTMModel.model_path(key, aggregated)), key,\n aggregated=aggregated, aggregation_method=aggregation_method)\n\n def save_model(self):\n self.regressor.save(LSTMModel.model_path(self.key, self.aggregated))\n\n @staticmethod\n def create_model(key, lstm_cells: int = 15, aggregated: bool = False, aggregation_method=CONSTS.AGG_METHOD):\n \"\"\" Creates a model by its key and aggregation. \"\"\"\n regressor = keras.Sequential()\n regressor.add(GRU(units=lstm_cells,\n return_sequences=True,\n input_shape=(None, LSTMModel._features(key))))\n regressor.add(Dense(units=30))\n regressor.add(Dense(units=20))\n if aggregated:\n regressor.add(Dense(units=1, activation=\"sigmoid\"))\n else:\n regressor.add(Dense(units=LSTMModel._output(key), activation=\"sigmoid\"))\n\n regressor.compile(optimizer='adam',\n loss='mean_squared_error')\n return LSTMModel(regressor, key, aggregated=aggregated, aggregation_method=aggregation_method)\n\n @staticmethod\n def _features(key):\n # Keys ^ 2 * Moments *\n return key ** 2 * CONSTS.FEATURE_PER_COMBO\n\n @staticmethod\n def _output(key):\n return key * 2\n\n @property\n def features(self):\n return self._features(self.key)\n\n def train_from_rsc(self, retrain=False, lim=None):\n trainables = self.get_trainables(retrain, lim)\n self.train(trainables)\n\n def get_trainables(self, retrain=False, lim=None) -> list:\n _, dirs, filenames = next(walk(f'{CONSTS.RSC_PATH}'))\n trainables = []\n if lim: dirs = np.asarray(dirs)[np.random.choice(len(dirs), lim, replace=False)]\n for map_dir in dirs:\n if self.aggregated:\n data_dir = f\"{CONSTS.RSC_PATH}/{map_dir}/{CONSTS.DATA_NAME}{CONSTS.AGG}\"\n data_path = f\"{data_dir}/{CONSTS.DATA_NAME}{CONSTS.AGG}.npy\"\n else:\n data_dir = f\"{CONSTS.RSC_PATH}/{map_dir}/{CONSTS.DATA_NAME}\"\n data_path = f\"{data_dir}/{CONSTS.DATA_NAME}.npy\"\n\n if not os.path.exists(data_path) or self.overwrite_data:\n # This means it's new data\n # There may be cases where the dir is generated but there's no data\n if not os.path.exists(data_dir):\n os.makedirs(data_dir)\n print(f\"Generating Data and Training on {map_dir}\")\n data = Preprocessing(self.threshold, self.window,\n aggregated=self.aggregated,\n aggregation_method=self.aggregation_method).features_from_rsc(map_dir)\n np.save(data_path, data)\n trainables.append(data)\n elif retrain:\n # This means it's processed data but we retrain\n data = np.load(f\"{data_path}\")\n print(f\"Training on {map_dir}\")\n trainables.append(data)\n\n if len(trainables) == 0:\n print(\"No new Data to train on.\")\n\n return trainables\n\n def train(self, data:List[np.ndarray]):\n \"\"\" Trains the model using the data generated. \"\"\"\n if not isinstance(data, list):\n data = [data]\n\n for ar in tqdm(data, desc=\"Training ... \"):\n if self.aggregated:\n assert ar.shape[-1] == self.features + 1,\\\n f\"Aggregated method is invalid. {self.aggregation_method},\" \\\n f\"{ar.shape[-1]} mismatched {self.features + 1}\"\n\n self.regressor.fit(x=ar[..., :self.features],\n y=ar[..., self.features:],\n epochs=self.epochs,\n batch_size=self.batch_size,\n verbose=self.verbose)\n\n def evaluate(self, data:np.ndarray):\n return self.regressor.evaluate(data[..., :self.features],\n data[..., self.features:])\n\n def predict(self, data:np.ndarray):\n return self.regressor.predict(data[..., :self.features])\n\n def predict_agg_and_plot(self, data:np.ndarray, map_path:str):\n\n m = ManiaHitError.parse_map(OsuMap.readFile(map_path))\n pred = self.predict(data[..., :self.features])\n\n # Flattened Map\n a = [i for k in m[:1] for j in k for i in j]\n\n # Predicted\n plt.subplot(3,1,1)\n if self.aggregated:\n plt.plot(pred.squeeze())\n else:\n plt.plot(self.aggregation_method(pred.squeeze(), axis=1))\n\n # Expected\n plt.subplot(3,1,2)\n plt.plot(self.aggregation_method(data.squeeze()[:,self.features:], axis=1))\n\n # Density\n plt.subplot(3,1,3)\n plt.hist(a, bins=300)\n plt.show()\n\n def predict_and_plot(self, data:np.ndarray, map_path:str):\n m = ManiaHitError.parse_map(OsuMap.readFile(map_path))\n pred = self.predict(data[..., :self.features])\n\n # Flattened Map\n a = [i for k in m[:1] for j in k for i in j]\n\n # Predicted\n plt.subplot(3,1,1)\n plt.plot(pred.squeeze(), c='r',alpha=0.3)\n\n # Expected\n plt.subplot(3,1,2)\n plt.plot(data.squeeze()[:,self.features:], c='blue', alpha=0.3)\n\n # Density\n plt.subplot(3,1,3)\n plt.hist(a, bins=100)\n\n plt.show()\n\n @staticmethod\n def model_path(key, aggregated):\n return CONSTS.MODEL_PATH + f'/estimator{key}{CONSTS.AGG}' if aggregated else \\\n CONSTS.MODEL_PATH + f'/estimator{key}'\n","repo_name":"Eve-ning/ARXScore","sub_path":"model/lstm_model.py","file_name":"lstm_model.py","file_ext":"py","file_size_in_byte":6538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8361744598","text":"from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType\nimport copy as _copy\n\n\nclass Delta(_BaseTraceHierarchyType):\n\n # class properties\n # --------------------\n _parent_path_str = \"indicator\"\n _path_str = \"indicator.delta\"\n _valid_props = {\n \"decreasing\",\n \"font\",\n \"increasing\",\n \"position\",\n \"prefix\",\n \"reference\",\n \"relative\",\n \"suffix\",\n \"valueformat\",\n }\n\n # decreasing\n # ----------\n @property\n def decreasing(self):\n \"\"\"\n The 'decreasing' property is an instance of Decreasing\n that may be specified as:\n - An instance of :class:`plotly.graph_objs.indicator.delta.Decreasing`\n - A dict of string/value properties that will be passed\n to the Decreasing constructor\n\n Supported dict properties:\n\n color\n Sets the color for increasing value.\n symbol\n Sets the symbol to display for increasing value\n\n Returns\n -------\n plotly.graph_objs.indicator.delta.Decreasing\n \"\"\"\n return self[\"decreasing\"]\n\n @decreasing.setter\n def decreasing(self, val):\n self[\"decreasing\"] = val\n\n # font\n # ----\n @property\n def font(self):\n \"\"\"\n Set the font used to display the delta\n\n The 'font' property is an instance of Font\n that may be specified as:\n - An instance of :class:`plotly.graph_objs.indicator.delta.Font`\n - A dict of string/value properties that will be passed\n to the Font constructor\n\n Supported dict properties:\n\n color\n\n family\n HTML font family - the typeface that will be\n applied by the web browser. The web browser\n will only be able to apply a font if it is\n available on the system which it operates.\n Provide multiple font families, separated by\n commas, to indicate the preference in which to\n apply fonts if they aren't available on the\n system. The Chart Studio Cloud (at\n https://chart-studio.plotly.com or on-premise)\n generates images on a server, where only a\n select number of fonts are installed and\n supported. These include \"Arial\", \"Balto\",\n \"Courier New\", \"Droid Sans\",, \"Droid Serif\",\n \"Droid Sans Mono\", \"Gravitas One\", \"Old\n Standard TT\", \"Open Sans\", \"Overpass\", \"PT Sans\n Narrow\", \"Raleway\", \"Times New Roman\".\n size\n\n Returns\n -------\n plotly.graph_objs.indicator.delta.Font\n \"\"\"\n return self[\"font\"]\n\n @font.setter\n def font(self, val):\n self[\"font\"] = val\n\n # increasing\n # ----------\n @property\n def increasing(self):\n \"\"\"\n The 'increasing' property is an instance of Increasing\n that may be specified as:\n - An instance of :class:`plotly.graph_objs.indicator.delta.Increasing`\n - A dict of string/value properties that will be passed\n to the Increasing constructor\n\n Supported dict properties:\n\n color\n Sets the color for increasing value.\n symbol\n Sets the symbol to display for increasing value\n\n Returns\n -------\n plotly.graph_objs.indicator.delta.Increasing\n \"\"\"\n return self[\"increasing\"]\n\n @increasing.setter\n def increasing(self, val):\n self[\"increasing\"] = val\n\n # position\n # --------\n @property\n def position(self):\n \"\"\"\n Sets the position of delta with respect to the number.\n\n The 'position' property is an enumeration that may be specified as:\n - One of the following enumeration values:\n ['top', 'bottom', 'left', 'right']\n\n Returns\n -------\n Any\n \"\"\"\n return self[\"position\"]\n\n @position.setter\n def position(self, val):\n self[\"position\"] = val\n\n # prefix\n # ------\n @property\n def prefix(self):\n \"\"\"\n Sets a prefix appearing before the delta.\n\n The 'prefix' property is a string and must be specified as:\n - A string\n - A number that will be converted to a string\n\n Returns\n -------\n str\n \"\"\"\n return self[\"prefix\"]\n\n @prefix.setter\n def prefix(self, val):\n self[\"prefix\"] = val\n\n # reference\n # ---------\n @property\n def reference(self):\n \"\"\"\n Sets the reference value to compute the delta. By default, it\n is set to the current value.\n\n The 'reference' property is a number and may be specified as:\n - An int or float\n\n Returns\n -------\n int|float\n \"\"\"\n return self[\"reference\"]\n\n @reference.setter\n def reference(self, val):\n self[\"reference\"] = val\n\n # relative\n # --------\n @property\n def relative(self):\n \"\"\"\n Show relative change\n\n The 'relative' property must be specified as a bool\n (either True, or False)\n\n Returns\n -------\n bool\n \"\"\"\n return self[\"relative\"]\n\n @relative.setter\n def relative(self, val):\n self[\"relative\"] = val\n\n # suffix\n # ------\n @property\n def suffix(self):\n \"\"\"\n Sets a suffix appearing next to the delta.\n\n The 'suffix' property is a string and must be specified as:\n - A string\n - A number that will be converted to a string\n\n Returns\n -------\n str\n \"\"\"\n return self[\"suffix\"]\n\n @suffix.setter\n def suffix(self, val):\n self[\"suffix\"] = val\n\n # valueformat\n # -----------\n @property\n def valueformat(self):\n \"\"\"\n Sets the value formatting rule using d3 formatting mini-\n languages which are very similar to those in Python. For\n numbers, see:\n https://github.com/d3/d3-format/tree/v1.4.5#d3-format.\n\n The 'valueformat' property is a string and must be specified as:\n - A string\n - A number that will be converted to a string\n\n Returns\n -------\n str\n \"\"\"\n return self[\"valueformat\"]\n\n @valueformat.setter\n def valueformat(self, val):\n self[\"valueformat\"] = val\n\n # Self properties description\n # ---------------------------\n @property\n def _prop_descriptions(self):\n return \"\"\"\\\n decreasing\n :class:`plotly.graph_objects.indicator.delta.Decreasing\n ` instance or dict with compatible properties\n font\n Set the font used to display the delta\n increasing\n :class:`plotly.graph_objects.indicator.delta.Increasing\n ` instance or dict with compatible properties\n position\n Sets the position of delta with respect to the number.\n prefix\n Sets a prefix appearing before the delta.\n reference\n Sets the reference value to compute the delta. By\n default, it is set to the current value.\n relative\n Show relative change\n suffix\n Sets a suffix appearing next to the delta.\n valueformat\n Sets the value formatting rule using d3 formatting\n mini-languages which are very similar to those in\n Python. For numbers, see:\n https://github.com/d3/d3-format/tree/v1.4.5#d3-format.\n \"\"\"\n\n def __init__(\n self,\n arg=None,\n decreasing=None,\n font=None,\n increasing=None,\n position=None,\n prefix=None,\n reference=None,\n relative=None,\n suffix=None,\n valueformat=None,\n **kwargs,\n ):\n \"\"\"\n Construct a new Delta object\n\n Parameters\n ----------\n arg\n dict of properties compatible with this constructor or\n an instance of\n :class:`plotly.graph_objs.indicator.Delta`\n decreasing\n :class:`plotly.graph_objects.indicator.delta.Decreasing\n ` instance or dict with compatible properties\n font\n Set the font used to display the delta\n increasing\n :class:`plotly.graph_objects.indicator.delta.Increasing\n ` instance or dict with compatible properties\n position\n Sets the position of delta with respect to the number.\n prefix\n Sets a prefix appearing before the delta.\n reference\n Sets the reference value to compute the delta. By\n default, it is set to the current value.\n relative\n Show relative change\n suffix\n Sets a suffix appearing next to the delta.\n valueformat\n Sets the value formatting rule using d3 formatting\n mini-languages which are very similar to those in\n Python. For numbers, see:\n https://github.com/d3/d3-format/tree/v1.4.5#d3-format.\n\n Returns\n -------\n Delta\n \"\"\"\n super(Delta, self).__init__(\"delta\")\n\n if \"_parent\" in kwargs:\n self._parent = kwargs[\"_parent\"]\n return\n\n # Validate arg\n # ------------\n if arg is None:\n arg = {}\n elif isinstance(arg, self.__class__):\n arg = arg.to_plotly_json()\n elif isinstance(arg, dict):\n arg = _copy.copy(arg)\n else:\n raise ValueError(\n \"\"\"\\\nThe first argument to the plotly.graph_objs.indicator.Delta\nconstructor must be a dict or\nan instance of :class:`plotly.graph_objs.indicator.Delta`\"\"\"\n )\n\n # Handle skip_invalid\n # -------------------\n self._skip_invalid = kwargs.pop(\"skip_invalid\", False)\n self._validate = kwargs.pop(\"_validate\", True)\n\n # Populate data dict with properties\n # ----------------------------------\n _v = arg.pop(\"decreasing\", None)\n _v = decreasing if decreasing is not None else _v\n if _v is not None:\n self[\"decreasing\"] = _v\n _v = arg.pop(\"font\", None)\n _v = font if font is not None else _v\n if _v is not None:\n self[\"font\"] = _v\n _v = arg.pop(\"increasing\", None)\n _v = increasing if increasing is not None else _v\n if _v is not None:\n self[\"increasing\"] = _v\n _v = arg.pop(\"position\", None)\n _v = position if position is not None else _v\n if _v is not None:\n self[\"position\"] = _v\n _v = arg.pop(\"prefix\", None)\n _v = prefix if prefix is not None else _v\n if _v is not None:\n self[\"prefix\"] = _v\n _v = arg.pop(\"reference\", None)\n _v = reference if reference is not None else _v\n if _v is not None:\n self[\"reference\"] = _v\n _v = arg.pop(\"relative\", None)\n _v = relative if relative is not None else _v\n if _v is not None:\n self[\"relative\"] = _v\n _v = arg.pop(\"suffix\", None)\n _v = suffix if suffix is not None else _v\n if _v is not None:\n self[\"suffix\"] = _v\n _v = arg.pop(\"valueformat\", None)\n _v = valueformat if valueformat is not None else _v\n if _v is not None:\n self[\"valueformat\"] = _v\n\n # Process unknown kwargs\n # ----------------------\n self._process_kwargs(**dict(arg, **kwargs))\n\n # Reset skip_invalid\n # ------------------\n self._skip_invalid = False\n","repo_name":"plotly/plotly.py","sub_path":"packages/python/plotly/plotly/graph_objs/indicator/_delta.py","file_name":"_delta.py","file_ext":"py","file_size_in_byte":11866,"program_lang":"python","lang":"en","doc_type":"code","stars":14438,"dataset":"github-code","pt":"3"}
+{"seq_id":"10275797958","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\n\nfrom typing import Dict, List # noqa: F401\nfrom datetime import date, datetime # noqa: F401\n\nfrom swagger_server import util\nfrom swagger_server.models.base_model_ import Model\n\n\nclass Item(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(\n self,\n name: str = None,\n size: List[str] = None,\n calories: int = None,\n price: List[float] = None,\n ): # noqa: E501\n \"\"\"Item - a model defined in Swagger\n\n :param name: The name of this Item. # noqa: E501\n :type name: str\n :param size: The size of this Item. # noqa: E501\n :type size: List[str]\n :param calories: The calories of this Item. # noqa: E501\n :type calories: int\n :param price: The price of this Item. # noqa: E501\n :type price: List[float]\n \"\"\"\n self.swagger_types = {\n \"name\": str,\n \"size\": List[str],\n \"calories\": int,\n \"price\": List[float],\n }\n\n self.attribute_map = {\n \"name\": \"name\",\n \"size\": \"size\",\n \"calories\": \"calories\",\n \"price\": \"price\",\n }\n self._name = name\n self._size = size\n self._calories = calories\n self._price = price\n\n @classmethod\n def from_dict(cls, dikt) -> \"Item\":\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The item of this Item. # noqa: E501\n :rtype: Item\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def name(self) -> str:\n \"\"\"Gets the name of this Item.\n\n the name of the drink # noqa: E501\n\n :return: The name of this Item.\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name: str):\n \"\"\"Sets the name of this Item.\n\n the name of the drink # noqa: E501\n\n :param name: The name of this Item.\n :type name: str\n \"\"\"\n\n self._name = name\n\n @property\n def size(self) -> List[str]:\n \"\"\"Gets the size of this Item.\n\n The available sizes of a beverage # noqa: E501\n\n :return: The size of this Item.\n :rtype: List[str]\n \"\"\"\n return self._size\n\n @size.setter\n def size(self, size: List[str]):\n \"\"\"Sets the size of this Item.\n\n The available sizes of a beverage # noqa: E501\n\n :param size: The size of this Item.\n :type size: List[str]\n \"\"\"\n\n self._size = size\n\n @property\n def calories(self) -> int:\n \"\"\"Gets the calories of this Item.\n\n The total calories of a drink # noqa: E501\n\n :return: The calories of this Item.\n :rtype: int\n \"\"\"\n return self._calories\n\n @calories.setter\n def calories(self, calories: int):\n \"\"\"Sets the calories of this Item.\n\n The total calories of a drink # noqa: E501\n\n :param calories: The calories of this Item.\n :type calories: int\n \"\"\"\n\n self._calories = calories\n\n @property\n def price(self) -> List[float]:\n \"\"\"Gets the price of this Item.\n\n A list of prices associated with sizes # noqa: E501\n\n :return: The price of this Item.\n :rtype: List[float]\n \"\"\"\n return self._price\n\n @price.setter\n def price(self, price: List[float]):\n \"\"\"Sets the price of this Item.\n\n A list of prices associated with sizes # noqa: E501\n\n :param price: The price of this Item.\n :type price: List[float]\n \"\"\"\n\n self._price = price\n","repo_name":"dgisolfi/PythonPackaging","sub_path":"api/swagger_server/models/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71652126481","text":"import numpy as np\nimport math\nfrom typing import Any, Tuple, List, Optional, Set, Callable\n\nfrom bpy.types import Area, Object\nfrom mathutils import Matrix, Quaternion, Vector\n\nfrom .version import BVersion\nfrom .kt_logging import KTLogger\nfrom .fake_context import get_fake_context\nfrom .bpy_common import (bpy_current_frame,\n bpy_render_frame,\n bpy_render_aspect,\n evaluated_mesh,\n bpy_background_mode)\nfrom .animation import get_safe_evaluated_fcurve\n\n\n_log = KTLogger(__name__)\n\n\ndef nearest_point(x: float, y: float, points: List[Tuple[float, float]],\n dist: float=4000000.0) -> Tuple[int, float]: # dist squared\n dist2 = dist\n nearest = -1\n for i, p in enumerate(points):\n d2 = (x - p[0]) ** 2 + (y - p[1]) ** 2\n if d2 < dist2:\n dist2 = d2\n nearest = i\n return nearest, dist2\n\n\ndef xy_to_xz_rotation_matrix_3x3() -> Any:\n return np.array([[1., 0., 0.],\n [0., 0., 1.],\n [0., -1., 0.]], dtype=np.float32)\n\n\ndef xz_to_xy_rotation_matrix_3x3() -> Any:\n return np.array([[1., 0., 0.],\n [0., 0., -1.],\n [0., 1., 0.]], dtype=np.float32)\n\n\ndef xy_to_xz_rotation_matrix_4x4() -> Any:\n return np.array([[1., 0., 0., 0.],\n [0., 0., 1., 0.],\n [0., -1., 0., 0.],\n [0., 0., 0., 1.]], dtype=np.float32)\n\n\ndef xz_to_xy_rotation_matrix_4x4() -> Any:\n return np.array([[1., 0., 0., 0.],\n [0., 0., -1., 0.],\n [0., 1., 0., 0.],\n [0., 0., 0., 1.]], dtype=np.float32)\n\n\ndef update_head_mesh_geom(obj: Object, geom: Any) -> None:\n mesh = obj.data\n assert(len(geom) == len(mesh.vertices))\n npbuffer = geom @ xy_to_xz_rotation_matrix_3x3()\n mesh.vertices.foreach_set('co', npbuffer.ravel())\n if mesh.shape_keys:\n mesh.shape_keys.key_blocks[0].data.foreach_set('co', npbuffer.ravel())\n mesh.update()\n\n\ndef update_head_mesh_neutral(fb: Any, head: Any) -> None:\n geom = fb.applied_args_vertices()\n update_head_mesh_geom(head.headobj, geom)\n\n\ndef update_head_mesh_expressions(fb: Any, head: Any, keyframe: int) -> None:\n geom = fb.applied_args_model_vertices_at(keyframe)\n update_head_mesh_geom(head.headobj, geom)\n\n\ndef update_head_mesh_non_neutral(fb: Any, head: Any) -> None:\n if head.should_use_emotions():\n kid = head.get_expression_view_keyframe()\n if kid == 0: # Neutral selected\n pass\n elif fb.is_key_at(kid):\n update_head_mesh_expressions(fb, head, kid)\n return\n else:\n _log.error(f'NO KEYFRAME: {kid} in {fb.keyframes()}')\n update_head_mesh_neutral(fb, head)\n\n\ndef projection_matrix(w: float, h: float, fl: float, sw: float,\n near: float, far: float, scale: float = 1.0,\n shift_x: float = 0.0, shift_y: float = 0.0) -> Any:\n z_diff = near - far\n fl_to_sw = fl / sw\n return np.array(\n [[scale * w * fl_to_sw, 0, 0, 0],\n [0, scale * w * fl_to_sw, 0, 0],\n [w * (2 * shift_x - 0.5), h * (2 * shift_y - 0.5), (near + far) / z_diff, -1],\n [0, 0, 2 * near * far / z_diff, 0]]\n ).transpose()\n\n\ndef _compensate_view_scale(w: float, h: float, inverse=False) -> float:\n if w == 0 or h == 0:\n return 1.0\n if w >= h:\n return 1.0\n if inverse:\n return w / h\n else:\n return h / w\n\n\ndef custom_projection_matrix(w: float, h: float, fl: float, sw: float,\n near: float, far: float,\n shift_x: float = 0, shift_y: float = 0) -> Any:\n return projection_matrix(w, h, fl, sw, near, far,\n _compensate_view_scale(w, h), shift_x, shift_y)\n\n\ndef focal_by_projection_matrix_mm(pm: Any, sw: float) -> float:\n return -0.5 * pm[0][0] * sw / pm[0][2]\n\n\ndef focal_by_projection_matrix_px(pm: Any) -> float:\n return pm[0][0]\n\n\ndef focal_mm_to_px(fl_mm: float, image_width: float, image_height: float,\n sensor_width: float=36.0) -> float:\n sc = _compensate_view_scale(image_width, image_height)\n return sc * fl_mm * image_width / sensor_width\n\n\ndef focal_px_to_mm(fl_px: float, image_width: float, image_height: float,\n sensor_width: float=36.0) -> float:\n sc = _compensate_view_scale(image_width, image_height, inverse=True)\n return sc * fl_px * sensor_width / image_width\n\n\ndef camera_sensor_width(camobj: Any) -> float:\n if not camobj or not camobj.data:\n return 36.0\n return camobj.data.sensor_width\n\n\ndef camera_focal_length(camobj: Any) -> float:\n if not camobj or not camobj.data:\n return 50.0\n return camobj.data.lens\n\n\ndef image_space_to_frame(x: float, y: float, shift_x: float=0.0,\n shift_y: float=0.0) -> Tuple[float, float]:\n \"\"\" Image centered Relative coords to Frame pixels \"\"\"\n w, h = bpy_render_frame()\n return (x + shift_x + 0.5) * w, (y + shift_y) * w + 0.5 * h\n\n\ndef frame_to_image_space(frame_x: float, frame_y: float,\n frame_w: float, frame_h: float,\n shift_x: float=0.0,\n shift_y: float=0.0) -> Tuple[float, float]:\n return (frame_x / frame_w - 0.5 - shift_x,\n (frame_y - 0.5 * frame_h) / frame_w - shift_y)\n\n\ndef image_space_to_region(x: float, y: float, x1: float, y1: float,\n x2: float, y2: float, shift_x: float = 0.0,\n shift_y: float = 0.0) -> Tuple[float, float]:\n \"\"\" Relative coords to Region (screen) space \"\"\"\n w = (x2 - x1)\n h = (y2 - y1)\n sc = w\n return x1 + (x + 0.5 + 2 * shift_x) * sc, \\\n (y1 + y2) * 0.5 + y * sc + 2 * shift_y * h\n\n\ndef get_image_space_coord(px: float, py: float, area: Area,\n shift_x: float = 0.0,\n shift_y: float = 0.0) -> Tuple[float, float]:\n x1, y1, x2, y2 = get_camera_border(area)\n x, y = region_to_image_space(px, py, x1, y1, x2, y2, shift_x, shift_y)\n return x, y\n\n\ndef region_to_image_space(x: float, y: float, x1: float, y1: float,\n x2: float, y2: float, shift_x: float = 0.0,\n shift_y: float = 0.0) -> Tuple[float, float]:\n w = (x2 - x1) if x2 != x1 else 1.0\n h = (y2 - y1) if y2 != y1 else 1.0\n sc = w\n asp = h / w if w != 0 else 1.0\n return (x - (x1 + x2) * 0.5) / sc - 2 * shift_x,\\\n (y - (y1 + y2) * 0.5) / sc - 2 * asp * shift_y\n\n\ndef pin_to_xyz_from_mesh(\n pin: Any, obj: Object) -> Optional[Tuple[float, float, float]]:\n \"\"\" Surface point from barycentric to XYZ using passed mesh\"\"\"\n sp = pin.surface_point\n gp = sp.geo_point_idxs\n bar = sp.barycentric_coordinates\n vv = obj.data.vertices\n verts_count = len(vv)\n if len(gp) < 3 or gp[0] >= verts_count or \\\n gp[1] >= verts_count or gp[2] >= verts_count:\n return None\n p = vv[gp[0]].co * bar[0] + vv[gp[1]].co * bar[1] + vv[gp[2]].co * bar[2]\n return p\n\n\ndef pin_to_xyz_from_geo_mesh(pin: Any, geo_mesh: Any) -> Tuple[float, float, float]:\n \"\"\" Surface point from barycentric to XYZ using geo_mesh\"\"\"\n sp = pin.surface_point\n gp = sp.geo_point_idxs\n bar = sp.barycentric_coordinates\n v1 = geo_mesh.point(gp[0])\n v2 = geo_mesh.point(gp[1])\n v3 = geo_mesh.point(gp[2])\n p = v1 * bar[0] + v2 * bar[1] + v3 * bar[2]\n return p\n\n\ndef pin_to_normal_from_geo_mesh(pin: Any, geo_mesh: Any) -> Vector:\n sp = pin.surface_point\n gp = sp.geo_point_idxs\n v1 = geo_mesh.point(gp[0])\n v2 = geo_mesh.point(gp[1])\n v3 = geo_mesh.point(gp[2])\n return Vector(np.cross(v2 - v1, v3 - v2)).normalized()\n\n\ndef calc_model_mat(model_mat: Any, head_mat: Any) -> Optional[Any]:\n \"\"\" Convert model matrix to camera matrix \"\"\"\n rot_mat = xy_to_xz_rotation_matrix_4x4()\n\n try:\n nm = np.array(model_mat @ rot_mat) @ np.linalg.inv(head_mat)\n im = np.linalg.inv(nm)\n return im.transpose()\n except Exception:\n return None\n\n\ndef get_area_region_3d(area: Optional[Area]) -> Optional[Any]:\n if not area or not area.spaces or not area.spaces.active:\n return None\n return area.spaces.active.region_3d\n\n\ndef get_area_region(area: Area) -> Optional[Any]:\n return area.regions[-1]\n\n\ndef blender_zoom_formula(factor: float) -> float:\n if factor < 0:\n factor = 0\n return (math.sqrt(factor) - math.sqrt(0.5)) * 100.0\n\n\ndef blender_zoom_scale_factor(z: float) -> float:\n return (z * 0.01 + math.sqrt(0.5)) ** 2\n\n\ndef get_camera_border(area: Area) -> Tuple[float, float, float, float]:\n if bpy_background_mode():\n context = get_fake_context()\n area = context.area\n\n region = get_area_region(area)\n assert region.type == 'WINDOW'\n reg_w, reg_h = region.width, region.height\n\n rv3d = get_area_region_3d(area)\n z = rv3d.view_camera_zoom\n f = blender_zoom_scale_factor(z)\n\n region_aspect = reg_w / reg_h\n render_aspect = bpy_render_aspect()\n\n offset = (rv3d.view_camera_offset[0] * reg_w * 2 * f,\n rv3d.view_camera_offset[1] * reg_h * 2 * f)\n\n # This works when Camera Sensor Mode is Auto\n if region_aspect >= 1.0:\n if render_aspect >= 1.0:\n # Horizontal image in horizontal View\n kx = f\n ky = f * region_aspect / render_aspect # (ry / rx) * (w / h)\n else:\n kx = f * render_aspect # (rx / ry)\n ky = f * region_aspect # (w / h)\n\n else:\n if render_aspect < 1.0:\n # Vertical image in vertical View\n kx = f * render_aspect / region_aspect # (rx / ry) * (h / w)\n ky = f\n else:\n kx = f / region_aspect # (h / w)\n ky = f / render_aspect # (ry / rx)\n\n x1 = reg_w * 0.5 - kx * reg_w * 0.5 - offset[0]\n x2 = reg_w * 0.5 + kx * reg_w * 0.5 - offset[0]\n y1 = reg_h * 0.5 - ky * reg_h * 0.5 - offset[1]\n y2 = reg_h * 0.5 + ky * reg_h * 0.5 - offset[1]\n return x1, y1, x2, y2\n\n\ndef calc_camera_zoom_and_offset(\n area: Area, region_x1: float, region_y1: float,\n width: float) -> Tuple[float, Tuple[float, float]]:\n region = get_area_region(area)\n reg_w, reg_h = region.width, region.height\n reg_asp = reg_w / reg_h\n render_asp = bpy_render_aspect()\n kx = width / reg_w\n if reg_asp >= 1.0:\n if render_asp >= 1.0:\n f = kx\n ky = f * reg_asp / render_asp\n else:\n f = kx / render_asp\n ky = f * reg_asp\n else:\n if render_asp < 1.0:\n f = kx * reg_asp / render_asp\n ky = f\n else:\n f = kx * reg_asp\n ky = f / render_asp\n z = blender_zoom_formula(f)\n offset_x = reg_w * 0.5 * (1.0 - kx) - region_x1\n offset_y = reg_h * 0.5 * (1.0 - ky) - region_y1\n offset = (offset_x / (reg_w * 2 * f),\n offset_y / (reg_h * 2 * f))\n return z, offset\n\n\ndef point_is_in_area(area: Area, x: float, y: float, *,\n bottom_limit: float = 0, left_limit: float = 0) -> bool:\n if bpy_background_mode():\n context = get_fake_context()\n area = context.area\n return (left_limit <= x <= area.width) and (bottom_limit <= y <= area.height)\n\n\ndef point_is_in_service_region(area: Area, x: float, y: float) -> bool:\n \"\"\" No guarantee that point is in area!\n Only check if point is in service region \"\"\"\n if bpy_background_mode():\n context = get_fake_context()\n area = context.area\n\n x0 = area.x\n y0 = area.y\n for r in area.regions:\n if r.type != 'WINDOW':\n if (r.x <= x + x0 <= r.x + r.width) and (\n r.y <= y + y0 <= r.y + r.height):\n return True\n return False\n\n\ndef get_pixel_relative_size(area: Area) -> float:\n \"\"\" One Pixel size in relative coords via current zoom \"\"\"\n if bpy_background_mode():\n context = get_fake_context()\n area = context.area\n\n w = area.width if area.width > 0 else 1.0\n space = area.spaces.active\n rv3d = space.region_3d\n f = blender_zoom_scale_factor(rv3d.view_camera_zoom)\n ps = 1.0 / (w * f)\n return ps\n\n\ndef get_mesh_verts(mesh: Any) -> Any:\n verts = np.empty((len(mesh.vertices), 3), dtype=np.float32)\n mesh.vertices.foreach_get(\n 'co', np.reshape(verts, len(mesh.vertices) * 3))\n return verts\n\n\ndef get_obj_verts(obj: Any) -> Any:\n return get_mesh_verts(obj.data)\n\n\ndef to_homogeneous(verts: Any) -> Any:\n vv = np.ones((len(verts), 4), dtype=np.float32)\n vv[:, :-1] = verts\n return vv\n\n\ndef multiply_verts_on_matrix_4x4(verts: Any, mat: Any) -> Any:\n vv = to_homogeneous(verts) @ mat\n return vv[:, :3]\n\n\ndef get_scale_vec_3_from_matrix_world(obj_matrix_world: Any) -> Any:\n return np.array(obj_matrix_world.to_scale(), dtype=np.float32)\n\n\ndef get_scale_vec_4_from_matrix_world(obj_matrix_world: Any) -> Any:\n return np.array(obj_matrix_world.to_scale().to_4d(), dtype=np.float32)\n\n\ndef get_scale_matrix_4x4_from_matrix_world(obj_matrix_world: Any) -> Any:\n scale_vec = get_scale_vec_4_from_matrix_world(obj_matrix_world)\n return np.diag(scale_vec)\n\n\ndef get_world_matrix_without_scale(obj_matrix_world: Any) -> Any:\n scale_vec = get_scale_vec_4_from_matrix_world(obj_matrix_world)\n scminv = np.diag(1.0 / scale_vec)\n return scminv @ np.array(obj_matrix_world, dtype=np.float32).transpose()\n\n\ndef get_scale_matrix_3x3_from_matrix_world(obj_matrix_world: Any) -> Any:\n scale_vec = get_scale_vec_3_from_matrix_world(obj_matrix_world)\n return np.diag(scale_vec)\n\n\ndef compensate_view_scale() -> float:\n image_width, image_height = bpy_render_frame()\n if image_width >= image_height:\n return 1.0\n return image_width / image_height\n\n\ndef ScaleMatrix(rank: int, sc: Tuple) -> Matrix:\n scm = Matrix.Identity(rank)\n scm[0][0], scm[1][1], scm[2][2] = sc[:]\n return scm\n\n\ndef InvScaleMatrix(rank: int, sc: Tuple) -> Matrix:\n scm = Matrix.Identity(rank)\n try:\n scm[0][0], scm[1][1], scm[2][2] = 1.0 / sc[0], 1.0 / sc[1], 1.0 / sc[2]\n except ZeroDivisionError:\n pass\n return scm\n\n\ndef UniformScaleMatrix(rank: int, sc: float) -> Matrix:\n return ScaleMatrix(rank, (sc, sc, sc))\n\n\ndef RotationMatrix(r: Quaternion) -> Matrix:\n r.normalized().to_matrix().to_4x4()\n\n\ndef LocRotScale_old(t: Tuple[float, float, float], r: Quaternion,\n sc: Tuple[float, float, float]) -> Matrix:\n scm = ScaleMatrix(4, sc)\n return Matrix.Translation(t) @ r.normalized().to_matrix().to_4x4() @ scm\n\n\nLocRotScale: Callable = Matrix.LocRotScale \\\n if BVersion.LocRotScale_exist else LocRotScale_old\n\n\ndef LocRotWithoutScale(mat: Matrix) -> Matrix:\n t, r, s = mat.decompose()\n return LocRotScale(t, r, (1, 1, 1))\n\n\ndef calc_bpy_camera_mat_relative_to_model(geom_matrix_world: Matrix,\n camera_matrix_world: Matrix,\n gt_model_mat: Any) -> Matrix:\n rot_mat2 = xz_to_xy_rotation_matrix_4x4()\n geom_scale_vec = get_scale_vec_4_from_matrix_world(geom_matrix_world)\n geom_scale_inv = np.diag(1.0 / geom_scale_vec)\n sc = camera_matrix_world.to_scale()\n try:\n mat = np.array(geom_matrix_world) @ geom_scale_inv \\\n @ rot_mat2 @ np.linalg.inv(gt_model_mat)\n t, r, _ = Matrix(mat).decompose()\n new_mat = LocRotScale(t, r, sc)\n except Exception:\n new_mat = Matrix.Identity(4)\n return new_mat\n\n\ndef calc_bpy_model_mat_relative_to_camera(geom_matrix_world: Matrix,\n camera_matrix_world: Matrix,\n gt_model_mat: Any) -> Matrix:\n rot_mat = xy_to_xz_rotation_matrix_4x4()\n t, r, _ = camera_matrix_world.decompose()\n camera_mat = LocRotScale(t, r, (1, 1, 1))\n scale_mat = get_scale_matrix_4x4_from_matrix_world(geom_matrix_world)\n np_mw = np.array(camera_mat) @ gt_model_mat @ rot_mat @ scale_mat\n return Matrix(np_mw)\n\n\ndef camera_projection(camobj: Object, frame: Optional[int]=None,\n image_width: Optional[int]=None,\n image_height: Optional[int]=None) -> Any:\n cam_data = camobj.data\n near = cam_data.clip_start\n far = cam_data.clip_end\n if image_width is None or image_height is None:\n image_width, image_height = bpy_render_frame()\n if frame is None:\n frame =bpy_current_frame()\n lens = get_safe_evaluated_fcurve(cam_data, frame, 'lens')\n proj_mat = custom_projection_matrix(image_width, image_height, lens,\n cam_data.sensor_width, near, far,\n cam_data.shift_x, cam_data.shift_y)\n return proj_mat\n\n\ndef get_triangulation_indices(mesh: Any, calculate: bool = True) -> Any:\n if calculate:\n mesh.calc_loop_triangles()\n indices = np.empty((len(mesh.loop_triangles), 3), dtype=np.int32)\n mesh.loop_triangles.foreach_get(\n 'vertices', np.reshape(indices, len(mesh.loop_triangles) * 3))\n return indices\n\n\ndef get_polygons_in_vertex_group(obj: Object,\n vertex_group_name: str,\n inverted=False) -> Set[int]:\n vertex_group_index = obj.vertex_groups.find(vertex_group_name)\n if vertex_group_index < 0:\n return set()\n\n mesh = evaluated_mesh(obj)\n verts_in_group = set([v.index for v in mesh.vertices\n if vertex_group_index in\n [g.group for g in v.groups]])\n\n polys_in_group = set()\n\n if not inverted:\n for polygon in mesh.polygons:\n if verts_in_group.issuperset(polygon.vertices[:]):\n polys_in_group.add(polygon.index)\n else:\n for polygon in mesh.polygons:\n if not verts_in_group.issuperset(polygon.vertices[:]):\n polys_in_group.add(polygon.index)\n\n return polys_in_group\n\n\ndef get_triangles_in_vertex_group(obj: Object,\n vertex_group_name: str,\n inverted=False) -> List:\n if vertex_group_name == '':\n return []\n\n polys_in_group = get_polygons_in_vertex_group(obj, vertex_group_name,\n inverted)\n if len(polys_in_group) == 0:\n return []\n\n mesh = evaluated_mesh(obj)\n mesh.calc_loop_triangles()\n return [tris.vertices[:] for tris in mesh.loop_triangles\n if tris.polygon_index in polys_in_group]\n\n\ndef distance_between_objects(obj1: Object, obj2: Object) -> float:\n ar1 = np.asarray(obj1.matrix_world)\n ar2 = np.asarray(obj2.matrix_world)\n return np.linalg.norm(ar1[:, 3] - ar2[:, 3], axis=0)\n\n\ndef change_near_and_far_clip_planes(camobj: Object, geomobj: Object,\n *, step: float = 1.05,\n prev_clip_start: float,\n prev_clip_end: float,\n minimal_clip_start: float = 1e-5) -> bool:\n if not camobj or not geomobj:\n return False\n dist = distance_between_objects(camobj, geomobj)\n\n changed_flag = False\n clip_end = camobj.data.clip_end\n clip_start = camobj.data.clip_start\n new_far_dist = dist * step\n\n if clip_end < dist:\n _log.output(f'OBJECT IS BEYOND THE CAMERA FAR CLIP PLANE:\\n '\n f'DIST: {dist} OLD CLIP_END: {clip_end}')\n camobj.data.clip_end = new_far_dist\n changed_flag = True\n elif clip_end > prev_clip_end > new_far_dist:\n _log.output(f'REVERT THE CAMERA FAR CLIP PLANE:\\n '\n f'DIST: {dist} OLD CLIP_END: {clip_end}\\n'\n f'REVERT: {prev_clip_end}')\n camobj.data.clip_end = prev_clip_end\n changed_flag = True\n\n # Magic formula for near clip distance calculation to prevent Z-fighting\n safe_clip_start = new_far_dist * new_far_dist / 65536\n if safe_clip_start > clip_start:\n camobj.data.clip_start = safe_clip_start\n changed_flag = True\n clip_start = camobj.data.clip_start\n\n new_clip_start = max(dist * 0.5, minimal_clip_start)\n too_close_limit = dist * 0.75\n if clip_start > too_close_limit:\n _log.output(f'OBJECT IS TOO CLOSE TO THE CAMERA NEAR CLIP PLANE:\\n '\n f'DIST: {dist} OLD CLIP_START: {clip_start}')\n camobj.data.clip_start = new_clip_start \\\n if new_clip_start < prev_clip_start else prev_clip_start\n changed_flag = True\n clip_start = camobj.data.clip_start\n\n if clip_start > prev_clip_start >= safe_clip_start:\n _log.output(f'REVERT THE CAMERA NEAR CLIP PLANE:\\n '\n f'DIST: {dist} OLD CLIP_START: {clip_start}\\n'\n f'REVERT: {prev_clip_start}')\n camobj.data.clip_start = prev_clip_start\n changed_flag = True\n\n return changed_flag\n\n\ndef make_indices_for_wide_edges(numb: int) -> Tuple[Any, Any]:\n arr = np.tile(np.arange(0, numb).reshape((-1, 2)), (1, 3))\n return arr.reshape((-1, 3)).ravel(), \\\n np.flip(arr, 1).reshape((-1, 3)).ravel()\n\n\ndef bound_box_center(obj: Object) -> Vector:\n if BVersion.bound_box_has_foreach_get:\n verts = np.empty((8, 3), dtype=np.float32)\n obj.bound_box.foreach_get(verts)\n else:\n verts = np.array([obj.bound_box[i] for i in range(8)], dtype=np.float32)\n return Vector(np.mean(verts, axis=0))\n","repo_name":"KeenTools/keentools-blender","sub_path":"keentools/utils/coords.py","file_name":"coords.py","file_ext":"py","file_size_in_byte":21655,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"3"}
+{"seq_id":"11710436751","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom django.contrib.auth.forms import UsernameField, UserCreationForm, UserChangeForm\nfrom django.forms import EmailField\nfrom django.utils.translation import gettext_lazy as _\nfrom rest_framework_simplejwt.token_blacklist.admin import OutstandingTokenAdmin as BaseOutstandingTokenAdmin\nfrom rest_framework_simplejwt.token_blacklist.models import OutstandingToken\n\nfrom users.models import User\n\n\nclass CustomUsernameField(UsernameField):\n \"\"\"UsernameField but without built-in value normalization if value is None\"\"\"\n\n def to_python(self, value):\n # do not perform any normalization if username is None or empty\n if not value:\n return\n # else normalize username\n return super().to_python(value)\n\n\nclass UserCreateForm(UserCreationForm):\n \"\"\"Custom User Creation Form in Admin interface\"\"\"\n\n class Meta:\n model = User\n fields = (\n \"email\",\n \"first_name\",\n \"last_name\",\n \"birth_date\",\n \"type\",\n )\n field_classes = {'username': CustomUsernameField, 'email': EmailField}\n\n\nclass UserModifyForm(UserChangeForm):\n \"\"\"Custom User Change Form in Admin interface\"\"\"\n\n class Meta:\n model = User\n fields = '__all__'\n field_classes = {'username': CustomUsernameField}\n\n\nclass UserAdmin(BaseUserAdmin):\n \"\"\"Custom User Admin interface\"\"\"\n\n list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'type')\n list_filter = ('type', 'is_staff', 'is_superuser', 'is_active')\n fieldsets = (\n (_('User details'), {'fields': ('email', 'username', 'password')}),\n (_('Personal info'), {'fields': ('first_name', 'last_name', 'birth_date', 'type')}),\n (_('Important dates'), {'fields': ('last_login', 'date_joined')}),\n (_('Permissions'), {\n 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),\n }),\n )\n add_fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': (\n 'email', 'first_name', 'last_name', 'birth_date', 'type', 'password1', 'password2'\n ),\n }),\n )\n form = UserModifyForm\n add_form = UserCreationForm\n\n\nclass OutstandingTokenAdmin(BaseOutstandingTokenAdmin):\n \"\"\"Overrides simple_jwt's token admin, so that deleting users is possible.\"\"\"\n\n def has_delete_permission(self, *args, **kwargs) -> bool:\n return True\n\n\nadmin.site.register(User, UserAdmin)\n\n# unregister model and later register it with a new admin\nadmin.site.unregister(OutstandingToken)\nadmin.site.register(OutstandingToken, OutstandingTokenAdmin)\n","repo_name":"BowellSolutions/bowell-backend","sub_path":"users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"30136936820","text":"from graphviz import Digraph\nimport torch\nfrom torch.autograd import Variable, Function\n\ndef iter_graph(root, callback):\n queue = [root]\n seen = set()\n while queue:\n fn = queue.pop()\n if fn in seen:\n continue\n seen.add(fn)\n for next_fn, _ in fn.next_functions:\n if next_fn is not None:\n queue.append(next_fn)\n callback(fn)\n\ndef register_hooks(var):\n fn_dict = {}\n def hook_cb(fn):\n def register_grad(grad_input, grad_output):\n fn_dict[fn] = grad_input\n fn.register_hook(register_grad)\n iter_graph(var.grad_fn, hook_cb)\n\n def is_bad_grad(grad_output):\n grad_output = grad_output.data\n return grad_output.ne(grad_output).any() or grad_output.gt(1e6).any()\n\n def make_dot():\n node_attr = dict(style='filled',\n shape='box',\n align='left',\n fontsize='12',\n ranksep='0.1',\n height='0.2')\n dot = Digraph(node_attr=node_attr, graph_attr=dict(size=\"12,12\"))\n\n def size_to_str(size):\n return '('+(', ').join(map(str, size))+')'\n\n def build_graph(fn):\n if hasattr(fn, 'variable'): # if GradAccumulator\n u = fn.variable\n node_name = 'Variable\\n ' + size_to_str(u.size())\n dot.node(str(id(u)), node_name, fillcolor='lightblue')\n else:\n assert fn in fn_dict, fn\n fillcolor = 'white'\n if any(is_bad_grad(gi) for gi in fn_dict[fn]):\n fillcolor = 'red'\n dot.node(str(id(fn)), str(type(fn).__name__), fillcolor=fillcolor)\n for next_fn, _ in fn.next_functions:\n if next_fn is not None:\n next_id = id(getattr(next_fn, 'variable', next_fn))\n dot.edge(str(next_id), str(id(fn)))\n iter_graph(var.grad_fn, build_graph)\n\n return dot\n\n return make_dot\n\nif __name__ == '__main__':\n x = Variable(torch.randn(10, 10), requires_grad=True)\n y = Variable(torch.randn(10, 10), requires_grad=True)\n\n z = x / (y * 0)\n z = z.sum() * 2\n get_dot = register_hooks(z)\n z.backward()\n dot = get_dot()\n dot.save('tmp.dot')\n","repo_name":"juefeix/pnn.pytorch","sub_path":"bad_grad_viz.py","file_name":"bad_grad_viz.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"3"}
+{"seq_id":"17835615167","text":"from django.shortcuts import render, redirect, get_object_or_404\n\n# LOGIN\nfrom django.contrib.auth.decorators import login_required\n\n# IMPORT[wishes]\nfrom .models import Wish\nfrom .forms import WishForm\n\n# IMPORT json\nimport os\nimport json\n\n# Create your views here.\ndef homePage(request):\n \"\"\"\n Project home page\n \"\"\"\n return render(request, 'page/home.html')\n\ndef rules(request):\n return render(request, 'page/rules.html')\n\n# LOGIN [LOGIN REQUEST]\n@login_required\ndef wishList(request):\n \"\"\"\n Reading the database\n ├── Args:\n └── request : Important Django requirement\n\n ├── Return:\n ├── wish_list : All database values sorted in order of creation\n \"\"\"\n\n wish_list = Wish.objects.all().order_by('-created_at')\n return render(request, 'page/list.html', {'wishes':wish_list})\n\n@login_required\ndef createWish(request):\n \"\"\"\n Create a new wish.\n ├── Args:\n └── request : Important Django requirement\n\n ├── Return:\n ├── wish_list : All database values sorted in order of creation\n └── form : create form\n \"\"\"\n\n if request.method == 'POST':\n form = WishForm(request.POST)\n if form.is_valid():\n wish = form.save(commit=False)\n wish.done = 'adn'\n wish.user = request.user\n wish.save()\n\n return redirect('/list/')\n\n else:\n form = WishForm()\n return render(request, 'page/create.html', {'form':form})\n\n@login_required\ndef updateWish(request, wish_id):\n \"\"\"\n Update selected wish\n ├── Args:\n ├── request : Important Django requirement\n └── wish_id : Wish's ID\n\n ├── Return:\n ├── wish : Get selected wish data\n └── form : update form\n \"\"\"\n wish = get_object_or_404(Wish, pk=wish_id)\n form = WishForm(instance=wish)\n\n if request.method == 'POST':\n form = WishForm(request.POST, instance=wish)\n\n if form.is_valid():\n wish.save()\n return redirect('/list/')\n\n else:\n content = {'form':form, 'wish':wish}\n return render(request, 'page/edit.html', content)\n\n@login_required\ndef deleteWish(request, wish_id):\n \"\"\"\n Delete selected wish\n ├── Args:\n ├── request : Important Django requirement\n └── wish_id : Wish's ID\n\n ├── Return:\n ├── wish : Get selected wish data\n \"\"\"\n wish = get_object_or_404(Wish, pk=wish_id)\n wish.delete()\n return redirect('/list/')\n\n@login_required\ndef statusWish(request, wish_id):\n \"\"\"\n Change wish status\n ├── Args:\n ├── request : Important Django requirement\n └── wish_id : Wish's ID\n\n ├── Return:\n ├── wish : Get selected wish data\n \"\"\"\n \n wish = get_object_or_404(Wish, pk=wish_id)\n\n if (wish.done == 'adn'):\n wish.done = 'rld'\n\n else:\n wish.done = 'adn'\n\n wish.save()\n return redirect('/list/')\n\n@login_required\ndef dashboard(request):\n wishAndamento = Wish.objects.filter(done='adn', user=request.user).count()\n wishRealizados = Wish.objects.filter(done='rld', user=request.user).count()\n wishContent = {'wish_adn': wishAndamento, 'wish_rld': wishRealizados}\n \n return render(request, 'page/dashboard.html', wishContent)","repo_name":"Baku-Stark/pythonEXE","sub_path":"Python Challenger/No 009 - WishList App Using Django/wish/wishes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8708332262","text":"from pullupclub.models import Student, PullUpSession\n\ndef run():\n for i in range(5):\n stu = Student()\n stu.name = \"TestStudent\" + str(i)\n stu.nickname = \"wetwater%d\" % i\n stu.slug = stu.name\n stu.save()\n\n pus = PullUpSession(student=stu)\n pus.count = i\n pus.save()","repo_name":"andrewhylee/proj_2_pullUpClub","sub_path":"scripts/script1.py","file_name":"script1.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39744807222","text":"from django.urls import path,include\n\nfrom . import views\nfrom api import views as APIviews\n\n\nurlpatterns = [\n path('test', views.TestTemplate.as_view(), name='TestTemplate'),\n path('logout', views.LogoutView.as_view(), name='LogoutView'),\n path('login', views.LoginTemplate.as_view(), name='LoginTemplate'),\n path('api/budget', APIviews.MockAPIView, name=\"MockAPIView\"),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n]","repo_name":"MachosV/fin_assignment","sub_path":"mysite/finloup/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9338488896","text":"from __future__ import annotations\n\nfrom typing import Any\n\nimport cv2\nimport numpy as np\n\nfrom .image_model import ImageModel\nfrom .types import ListValue, NumericalValue, StringValue\nfrom .utils import AnomalyResult\n\n\nclass AnomalyDetection(ImageModel):\n __model__ = \"AnomalyDetection\"\n\n def __init__(self, inference_adapter, configuration=dict(), preload=False):\n super().__init__(inference_adapter, configuration, preload)\n self._check_io_number(1, 1)\n self.normalization_scale: float\n self.image_threshold: float\n self.pixel_threshold: float\n self.task: str\n self.labels: list[str]\n\n def postprocess(self, outputs: dict[str, np.ndarray], meta: dict[str, Any]):\n \"\"\"Post-processes the outputs and returns the results.\n\n Args:\n outputs (Dict[str, np.ndarray]): Raw model outputs\n meta (Dict[str, Any]): Meta data containing the original image shape\n\n Returns:\n AnomalyResult: Results\n \"\"\"\n anomaly_map: np.ndarray | None = None\n pred_label: str | None = None\n pred_mask: np.ndarray | None = None\n pred_boxes: np.ndarray | None = None\n predictions = outputs[list(self.outputs)[0]]\n\n if len(predictions.shape) == 1:\n pred_score = predictions\n else:\n anomaly_map = predictions.squeeze()\n pred_score = anomaly_map.reshape(-1).max()\n\n pred_label = (\n self.labels[1] if pred_score > self.image_threshold else self.labels[0]\n )\n\n assert anomaly_map is not None\n pred_mask = (anomaly_map >= self.pixel_threshold).astype(np.uint8)\n anomaly_map = self._normalize(anomaly_map, self.pixel_threshold)\n pred_mask = cv2.resize(\n pred_mask, (meta[\"original_shape\"][1], meta[\"original_shape\"][0])\n )\n\n # normalize\n pred_score = self._normalize(pred_score, self.image_threshold)\n\n # resize outputs\n if anomaly_map is not None:\n anomaly_map = cv2.resize(\n anomaly_map, (meta[\"original_shape\"][1], meta[\"original_shape\"][0])\n )\n\n if self.task == \"detection\":\n pred_boxes = self._get_boxes(pred_mask)\n\n return AnomalyResult(\n anomaly_map=anomaly_map,\n pred_boxes=pred_boxes,\n pred_label=pred_label,\n pred_mask=pred_mask,\n pred_score=pred_score.item(),\n )\n\n @classmethod\n def parameters(cls) -> dict:\n parameters = super().parameters()\n parameters.update(\n {\n \"image_threshold\": NumericalValue(\n description=\"Image threshold\", min=0.0, default_value=0.5\n ),\n \"pixel_threshold\": NumericalValue(\n description=\"Pixel threshold\", min=0.0, default_value=0.5\n ),\n \"normalization_scale\": NumericalValue(\n description=\"Value used for normalization\",\n ),\n \"task\": StringValue(\n description=\"Task type\", default_value=\"segmentation\"\n ),\n \"labels\": ListValue(description=\"List of class labels\"),\n }\n )\n return parameters\n\n def _normalize(self, tensor: np.ndarray, threshold: float) -> np.ndarray:\n \"\"\"Currently supports only min-max normalization.\"\"\"\n normalized = ((tensor - threshold) / self.normalization_scale) + 0.5\n normalized = np.clip(normalized, 0, 1)\n return normalized\n\n @staticmethod\n def _get_boxes(mask: np.ndarray) -> np.ndarray:\n \"\"\"Get bounding boxes from mask.\n\n Args:\n mask (np.ndarray): Input mask of shapw (H, W)\n\n Returns:\n np.ndarray: array of shape (N,4) containing the bounding box coordinates of the objects in the masks in\n format [x1, y1, x2, y2]\n \"\"\"\n contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n boxes = []\n for contour in contours:\n x, y, w, h = cv2.boundingRect(contour)\n boxes.append([x, y, x + w, y + h])\n return np.array(boxes)\n","repo_name":"openvinotoolkit/model_api","sub_path":"model_api/python/openvino/model_api/models/anomaly.py","file_name":"anomaly.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"3"}
+{"seq_id":"21448828715","text":"from django_elasticsearch_dsl_drf.serializers import DocumentSerializer\nfrom rest_framework import serializers\n\nfrom .documents import LectureDocument\nfrom .models import Lecture\n\n\nclass LectureSerializer(serializers.ModelSerializer):\n class Meta:\n model = Lecture\n fields = \"__all__\"\n\n\nclass LectureDocumentSerializer(DocumentSerializer):\n class Meta:\n document = LectureDocument\n fields = (\n \"lecture_id\",\n \"title\",\n \"date\",\n \"corporate_author\",\n \"abstract\",\n \"series\",\n \"speaker\",\n \"speaker_details\",\n \"event_details\",\n \"thumbnail_picture\",\n \"language\",\n \"subject_category\",\n \"lecture_note\",\n \"imprint\",\n \"license\",\n \"sponsor\",\n \"keywords\",\n \"types\",\n \"files\",\n \"video_parts\",\n )\n","repo_name":"cern-sis/cern-academic-training","sub_path":"backend/cds/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"19899401996","text":"# A program that allows the user to type in a phrase and then outputs the acronym for that phrase.\r\n\r\ndef main():\r\n\r\n phrase = input(\"Enter a pharse:\")\r\n acronym = \"\"\r\n\r\n for word in phrase.split():\r\n acronym = acronym+word[0]\r\n acronym = acronym.upper()\r\n\r\n print(\"The acronym of the phrase is\", acronym)\r\n\r\nmain()\r\n \r\n \r\n \r\n","repo_name":"marjana2019/python_problems","sub_path":"acronym.py","file_name":"acronym.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20120076312","text":"\nfrom numpy import TooHardError\nimport pygame\nfrom pygame import *\nfrom tkinter import *\nfrom tkinter import messagebox as mb\nimport json\n\npygame.init()\n\n\nclass Quiz:\n\n def __init__(self):\n\n self.q_no = 0\n\n self.display_title()\n self.display_question()\n\n self.opt_selected = IntVar()\n\n self.opts = self.radio_buttons()\n\n self.display_options()\n\n self.buttons()\n\n self.data_size = len(question)\n\n self.correct = 0\n\n def display_result(self):\n\n wrong_count = self.data_size - self.correct\n correct = f\"Correct: {self.correct}\"\n wrong = f\"Wrong: {wrong_count}\"\n\n score = int(self.correct / self.data_size * 100)\n result = f\"Score: {score}%\"\n\n mb.showinfo(\n \"Result\", f\"{result}\\n{correct}\\n{wrong}\\n\\n The Correct answers were: \\n 1.Dry Gravel \\n 2. Wet Asphalt \\n 3. Dry Asphalt \\n 4.Snow \\n 5. Ice \\n 6. Wet Gravel\")\n\n def check_ans(self, q_no):\n\n if self.opt_selected.get() == answer[q_no]:\n\n return True\n\n def next_btn(self):\n\n if self.check_ans(self.q_no):\n\n self.correct += 1\n\n self.q_no += 1\n print(self.q_no)\n\n if self.q_no == self.data_size:\n\n self.display_result()\n\n gui.destroy()\n else:\n\n self.display_question()\n self.display_options()\n\n def buttons(self):\n\n next_button = Button(gui, text=\"Next\", command=self.next_btn,\n width=10, bg=\"cyan\", fg=\"black\", font=(\"ariel\", 20, \"bold\"))\n\n next_button.place(x=300, y=380)\n\n quit_button = Button(gui, text=\"Quit\", command=gui.destroy,\n width=5, bg=\"cyan\", fg=\"black\", font=(\"ariel\", 16, \" bold\"))\n\n quit_button.place(x=700, y=700)\n\n def display_options(self):\n val = 0\n\n self.opt_selected.set(0)\n\n for option in options[self.q_no]:\n self.opts[val]['text'] = option\n val += 1\n\n def display_question(self):\n\n q_no = Label(gui, text=question[self.q_no], width=60,\n font=('ariel', 18, 'bold'), anchor='w')\n\n q_no.place(x=70, y=200)\n\n def display_title(self):\n\n title1 = Label(gui, text=\"Guess The Road Condition! By: Ice Riderzzz\",\n width=50, bg=\"cyan\", fg=\"black\", font=(\"ariel\", 20, \"bold\"))\n\n title1.place(x=0, y=2)\n\n\n title2 = Label(gui, text=r\"https://github.com/TheLonelyFighter/Capstone\",\n width=50, bg=\"white\", fg=\"black\", font=(\"Courier\", 10, \"italic\"))\n\n title2.place(x=0, y=600)\n\n\n def radio_buttons(self):\n\n q_list = []\n y_pos = 270\n x_pos = 140\n while len(q_list) < 6:\n radio_btn = Radiobutton(gui, text=\" \", variable=self.opt_selected,\n value=len(q_list)+1, font=(\"ariel\", 14))\n\n q_list.append(radio_btn)\n radio_btn.place(x=x_pos, y=y_pos)\n if len(q_list) == 1:\n x_pos += 150\n elif len(q_list) == 2:\n x_pos += 150\n elif len(q_list) == 3:\n y_pos +=40\n x_pos -= 300\n elif len(q_list) == 4:\n x_pos += 150\n elif len(q_list) == 5:\n x_pos +=150\n return q_list\n\n\ngui = Tk()\ngui.geometry('800x800')\n\nmyframe = Frame(gui)\nmyframe.pack()\n\ngui.title(\"Guess The Road Condition! By: Ice Riderzzz\")\n\n\nwith open('json_for_quiz_game.json') as f:\n data = json.load(f)\n\n\ndef unpause():\n pygame.mixer.music.unpause()\n\n\ndef pause():\n pygame.mixer.music.pause()\n\n\nquestion = (data['question'])\noptions = (data['options'])\nanswer = (data['answer'])\n\n\nquiz = Quiz()\n\n\ndef play_dry_gravel():\n pygame.mixer.music.load('dry_gravel.wav')\n pygame.mixer.music.play(-1)\n\n\ndef play_wet_asphalt():\n pygame.mixer.music.load('wet_asphalt_new.wav')\n pygame.mixer.music.play(-1)\n\n\ndef play_dry_asphalt():\n pygame.mixer.music.load('dry_asphalt_new.wav')\n pygame.mixer.music.play(-1)\n\ndef play_ice():\n pygame.mixer.music.load('ice.wav')\n pygame.mixer.music.play(-1) #continuous\n\ndef play_snow():\n pygame.mixer.music.load('snow.wav')\n pygame.mixer.music.play(-1)\n\ndef play_wet_gravel():\n pygame.mixer.music.load('wet_gravel.wav')\n pygame.mixer.music.play(-1)\n\n\n\n\nbutton1 = Button(gui, text=\"Sound 3\",\n command=play_dry_asphalt, width=20)\nbutton1.pack(pady=5)\nbutton1.place(x=460, y=100)\nbutton2 = Button(gui, text=\"Sound 2\",\n command=play_wet_asphalt, width=20)\nbutton2.pack(pady=10)\nbutton2.place(x=300, y=100)\nbutton3 = Button(gui, text=\"Sound 1\",\n command=play_dry_gravel, width=20)\nbutton3.pack(pady=15)\nbutton3.place(x=140, y=100)\n\nbutton6 = Button(gui, text=\"Sound 4\",\n command=play_snow, width=20)\nbutton6.pack(pady=15)\nbutton6.place(x=140, y=130)\n\nbutton7 = Button(gui, text=\"Sound 5\",\n command=play_ice, width=20)\nbutton7.pack(pady=15)\nbutton7.place(x=300, y=130)\n\nbutton7 = Button(gui, text=\"Sound 6\",\n command=play_wet_gravel, width=20)\nbutton7.pack(pady=15)\nbutton7.place(x=460, y=130)\n\n\nbutton4 = Button(gui, text=\"Continue\", command=unpause, width=15)\nbutton4.pack(pady=5)\nbutton4.place(x=240, y=70)\n\nbutton5 = Button(gui, text=\"Pause\", command=pause, width=15)\nbutton5.pack(pady=5)\nbutton5.place(x=360, y=70)\n\n\ngui.configure(background='grey')\ngui.mainloop()\n\n\n\n#TODO \n\"\"\" Pickle or sqlite3 for data collection,\nchange GUI friendlier \"\"\"\n\n\n","repo_name":"TheLonelyFighter/Capstone","sub_path":"guess_the_road_condition/quiz_game_road.py","file_name":"quiz_game_road.py","file_ext":"py","file_size_in_byte":5553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29183902107","text":"import logging\nimport yaml\n\nfrom library.python import resource as rs\nfrom collections import namedtuple\n\nyaml_loader = getattr(yaml, 'CSafeLoader', yaml.SafeLoader)\nResource = namedtuple('Resource', [\n 'vcpu', 'memory',\n 'capacity_hdd', 'disk_bandwidth_hdd',\n 'capacity_ssd', 'disk_bandwidth_ssd'])\n\n\ndef test_quota_capacity(request, account_id, gc_max_object_age_minutes):\n resources = []\n for name, data in rs.iteritems('/stage'):\n resource = _parse(data)\n logging.info('%s resource usage: %s', name, resource)\n resources.append(resource)\n logging.info('total resource usage: %s', _merge_resources(resources))\n\n # TODO: fetch it from target cluster?\n requested_quota = {\n 'vcpu': 12000, # 12c\n 'memory': 10737418240, # 10G\n 'capacity_hdd': 1099511627776, # 1T\n 'disk_bandwidth_hdd': 3145728, # 3M/s\n 'capacity_ssd': 1099511627776, # 1T\n 'disk_bandwidth_ssd': 3145728 # 3M/s\n }\n\n run_freq = 30\n test_split_factor = request.config.option.modulo\n def approx_quota_limit(value, factor=1.5):\n return factor * value * test_split_factor * (gc_max_object_age_minutes / run_freq)\n\n # well... this is pretty lame estimation.\n # better way is to look for split_factor consumers which\n # have max sum consumption (and assume some good metric)\n max_resource_vector_dict = _merge_resources(resources, max)._asdict()\n for key, quota in requested_quota.items():\n requested_quota = approx_quota_limit(max_resource_vector_dict[key])\n assert requested_quota <= quota, \\\n f\"Requested resource {key} could overwhelm allowed quota ({requested_quota} > {quota}). \" \\\n f\"Make sure that this is ok and re-write this check or consider enlarging quota for account {account_id}.\"\n\n quota_order = {}\n for key, quota in max_resource_vector_dict.items():\n quota_order[key] = approx_quota_limit(quota, 2.)\n logging.info(\"Quota order: %s\", quota_order)\n\n\ndef _parse(data):\n stage_yaml = data.decode(\"utf-8\") % {'yp_cluster': 'fake_cluster'}\n stage_dict = yaml.load(stage_yaml, Loader=yaml_loader)\n resources = list(_find_resources(stage_dict))\n return _merge_resources(resources)\n\n\ndef _merge_resources(resources, f=sum):\n return Resource(\n f([r.vcpu for r in resources]),\n f([r.memory for r in resources]),\n f([r.capacity_hdd for r in resources]),\n f([r.disk_bandwidth_hdd for r in resources]),\n f([r.capacity_ssd for r in resources]),\n f([r.disk_bandwidth_ssd for r in resources]),\n )\n\n\ndef _process_replica_sets(stage_dict, function, *args, **kwargs):\n for du_id, du_spec in stage_dict.get('spec', {}).get('deploy_units', {}).items():\n yield function(du_id, du_spec.get('multi_cluster_replica_set', {}).get('replica_set', {}), *args, **kwargs)\n yield function(du_id, du_spec.get('replica_set', {}).get('replica_set_template', {}), *args, **kwargs)\n\n\ndef _find_resources(stage_dict):\n default_bandwith = {\n 'hdd': 1048576, # 1M/s\n 'ssd': 1048576 # 1M/s\n }\n def _patch_resources_and_volumes(du_id, replica_set_dict):\n pod_spec = replica_set_dict.get('pod_template_spec', {}).get('spec', {})\n for volume_request in pod_spec.get('disk_volume_requests', []):\n quota_policy = volume_request.get('quota_policy', {})\n storage_type = volume_request.get('storage_class', 'hdd')\n yield Resource(**{\n 'vcpu': 0,\n 'memory': 0,\n 'capacity_hdd': 0,\n 'disk_bandwidth_hdd': default_bandwith['hdd'],\n 'capacity_ssd': 0,\n 'disk_bandwidth_ssd': default_bandwith['ssd'],\n 'disk_bandwidth_' + storage_type: quota_policy.get('bandwidth_limit', default_bandwith[storage_type]),\n 'capacity_' + storage_type: quota_policy['capacity']\n })\n\n resource_requests = pod_spec.get('resource_requests', {})\n yield Resource(resource_requests.get('vcpu_limit', 0),\n resource_requests.get('memory_limit', 0),\n 0, 0, 0, 0)\n\n for resource in _process_replica_sets(stage_dict, _patch_resources_and_volumes):\n for r in resource:\n yield r\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"infra/tests/test_quota_capacity.py","file_name":"test_quota_capacity.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23001257304","text":"from datetime import timedelta\nfrom django.test import TestCase\nfrom django.contrib.auth import get_user_model\nfrom django.utils import timezone\nfrom accounts.models import Profile\nfrom models3d.models import Model3D\nfrom badges.constants import NB_VIEWS_FOR_STAR, TIMEDELTA_FOR_PIONNEER\nfrom badges.validator import BadgeValidator\nfrom mock import patch\n\nUser = get_user_model()\n\n\nclass ValidatorTests(TestCase):\n\n def setUp(self):\n user = User.objects.create_user(\n username=\"john\",\n email=\"john@beatles.com\",\n password=\"john123\")\n self.profile = Profile.objects.create(user=user)\n\n def test_check_star_badge(self):\n self.profile.nb_views = NB_VIEWS_FOR_STAR + 1\n self.profile.save()\n self.assertTrue(BadgeValidator.check_star_badge(self.profile))\n\n def test_check_star_badge_ko(self):\n self.profile.nb_views = NB_VIEWS_FOR_STAR - 1\n self.profile.save()\n self.assertFalse(BadgeValidator.check_star_badge(self.profile))\n\n @patch('badges.validator.NB_MODELS_FOR_COLLECTOR', 1)\n def test_check_collector_badge(self):\n Model3D.objects.create(profile=self.profile)\n self.assertTrue(BadgeValidator.check_collector_badge(self.profile))\n\n @patch('badges.validator.NB_MODELS_FOR_COLLECTOR', 1)\n def test_check_collector_badge_ko(self):\n self.assertFalse(BadgeValidator.check_collector_badge(self.profile))\n\n def test_check_pionneer_badge(self):\n self.profile.user.date_joined = timezone.now() - TIMEDELTA_FOR_PIONNEER - timedelta(seconds=1)\n self.profile.user.save()\n self.assertTrue(BadgeValidator.check_pionneer_badge(self.profile))\n\n def test_check_pionneer_badge_ko(self):\n self.profile.user.date_joined = timezone.now()\n self.profile.user.save()\n self.assertFalse(BadgeValidator.check_pionneer_badge(self.profile))\n","repo_name":"pleasedontbelong/badges","sub_path":"apps/badges/tests/test_validator.py","file_name":"test_validator.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34513028751","text":"import os\nimport vtk\n\nimport mooseutils\nfrom .. import base\n\nclass ImageAnnotationSource(base.ChiggerSource):\n \"\"\"\n Source for displaying images in 3D space.\n \"\"\"\n VTKACTOR_TYPE = vtk.vtkImageActor\n VTKMAPPER_TYPE = vtk.vtkImageSliceMapper\n\n @staticmethod\n def getOptions():\n \"\"\"\n Return default options for this object.\n \"\"\"\n opt = base.ChiggerSource.getOptions()\n opt.add('filename', None, \"The PNG file to read, this can be absolute or relative path to \"\n \"a PNG or just the name of a PNG located in the chigger/logos \"\n \"directory.\", vtype=str)\n return opt\n\n def __init__(self, **kwargs):\n super(ImageAnnotationSource, self).__init__(vtkactor_type=vtk.vtkImageActor,\n vtkmapper_type=vtk.vtkImageSliceMapper,\n **kwargs)\n\n self.__reader = vtk.vtkPNGReader()\n\n def getVTKSource(self):\n \"\"\"\n Return the image reader object. (override)\n \"\"\"\n return self.__reader\n\n def update(self, **kwargs):\n \"\"\"\n Updates the image reader. (override)\n \"\"\"\n super(ImageAnnotationSource, self).update(**kwargs)\n\n if self.isOptionValid('filename'):\n filename = self.getOption('filename')\n if not os.path.exists(filename):\n filename = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'logos',\n os.path.basename(filename)))\n if not os.path.exists(filename):\n raise mooseutils.MooseException('Unable to locate image file: {}'.format(filename))\n self.__reader.SetFileName(filename)\n self.__reader.Update()\n","repo_name":"mazajump/FEA-PhaseField-Moose","sub_path":"python/chigger/annotations/ImageAnnotationSource.py","file_name":"ImageAnnotationSource.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"4780781548","text":"\"\"\"\n#------------ Get OHLC top 15 cryto - exchange Kraken \nCryto\nbitcoin (btc), ethereum (eth), litecoin (ltc), polkadot (dot), monero (xmr), dogecoin (xdg), stellar lumens (xlm),\nripple (xrp), zcash (zec), nano (nano), tron (trx), bitcoin cash (bch), tezos (xtz), cardano (ada), orchid (oxt)\n \n\npath imports. \nadd the following bit of code to the beginning of your imports \n(as long as your notebook is inside a folder inside libs) it will tell Python to add the libs folder \nto the list of folders it looks for imports from \n(to see a list of folders Python is searching print sys.path after import.sys):\n\nimport sys\nimport os\nmodule_path = os.path.abspath(os.path.join('../..'))\nif module_path not in sys.path:\n sys.path.append(module_path)\n\nWhich then will allow you to import from our signals, data, or trading packages, i.e.:\nfrom libs.signals import signals.ewma_crossover\nfrom libs.trading import 'some_trading_function/library'\n\nto see a list of folders Python is searching print sys.path after import.sys):\n\n\nNote: you can remove a path by doing sys.path.remove('path_you_want_to_remove'), \nbut be really careful with that and don't remove any of the default paths!\nIf y'all would rather just move the files into the libs folder, \n\n\"\"\"\n\n# ---------- imports \nimport sys\nimport os\nmodule_path = os.path.abspath(os.path.join('../..'))\nif module_path not in sys.path:\n sys.path.append(module_path)\nsys.path\n\nfor p in (sys.path):\n print(p)\n\nos.getcwd()\n\nimport pandas as pd \nimport numpy as np\nimport datetime\nimport time, json, requests, sys\nfrom time import time, ctime\nfrom datetime import datetime\nimport pathlib\nfrom requests.exceptions import HTTPError\n#from libs.signals import signals \n\n\n\n#------------ functions \n\n#--- Get OHLC from Kraken\ndef Get_OHLC_Kraken(pair, interval='1440', since=''):\n response_json = {}\n url = 'https://api.kraken.com/0/public/OHLC' #only last 720 datapoints \n #pair = cryto\n #interval = '1440' # 1440 = 1 day \n #since = '' # return las 720 datapoints\n \n for i in range(3):\n try:\n response_kraken = requests.post(url, \n params=\n {'pair':pair,\n 'interval':interval, \n 'since':since}, \n headers={\"content-type\":\"application/json\"})\n \n # If the response was successful, no Exception will be raised\n response_kraken.raise_for_status()\n except HTTPError as http_err:\n print(f'HTTP error occurred: {http_err}') \n except Exception as err:\n print(f'Other error occurred: {err}') \n else:\n print('Success, URL found!')\n break\n print('-------------------- try #');print(i)\n time.sleep(5)\n\n if i == 2: sys.exit('URL error GGC') \n\n #print(response_kraken.json())\n #g = input(\"control 2 : \"); print (g)\n return response_kraken.json()\n\n\n# --- Process OHLC json into a list\ndef Process_Kraken_Jason(kraken_json, pair):\n i = 0\n l_price = []\n #pair = 'XXBTZUSD'\n \n while True:\n try:\n new_row = [ctime(kraken_json['result'][pair][i][0]), # Date \n kraken_json['result'][pair][i][1], # Open \n kraken_json['result'][pair][i][2], # High \n kraken_json['result'][pair][i][3], # Low \n kraken_json['result'][pair][i][4], # Close\n kraken_json['result'][pair][i][6] # Volume \n ] \n #print (new_row)\n l_price += [new_row]\n i += 1 \n\n except Exception as err:\n print(f'error Process_Kraken_Jason: {err}') \n break \n \n return l_price\n\n\n# --- tranform OHLC list into a DataFrame '\ndef l_price_into_df_price(l_price, pair):\n l_labels = ['Date', 'Open_'+pair[0:5], 'High_'+pair[0:5], 'Low_'+pair[0:5], 'Close_'+pair[0:5], 'Vol_'+pair[0:5]]\n\n df_price = pd.DataFrame.from_records(l_price, columns=l_labels) # l --> list, l_labels --> column names \n df_price['Date'] = pd.to_datetime(df_price['Date'])\n df_price.set_index('Date', inplace=True) \n\n return(df_price)\n\n\n# ---- concatenate pair dataframe with the global dataframe \ndef Concact_Prices(df_price, ft, df_all_prices):\n if ft == True:\n df_all_prices = pd.concat([df_price], axis=\"columns\", join=\"outer\")\n ft = False\n else:\n df_all_prices = pd.concat([df_all_prices, df_price], axis=\"columns\", join=\"outer\")\n\n return df_all_prices, ft\n\n\n# --- Export df to CSV \ndef export_df_csv(df_all_prices):\n #path_csv = 'Crypto_Bandyts/libs/data/'\n #name_csv = 'crypto_prices1.csv'\n #OHLC_csv = path_csv + name_csv\n\n path = pathlib.Path('/Users/gonzalogarciacontreras/rice15/Crypto_Bandyts/libs/data/crypto_pricesx.csv')\n\n df_all_prices.to_csv(path)\n\n return \n\n\n# --------- Main \n\ndef main():\n #bitcoin (btc), ethereum (eth), litecoin (ltc), polkadot (dot), monero (xmr), dogecoin (xdg), stellar lumens (xlm),\n #ripple (xrp), zcash (zec), nano (nano), tron (trx), bitcoin cash (bch), tezos (xtz), cardano (ada), orchid (oxt)\n #DOT, XDG, NANO, TRX, and OXT.\n \n cryto_list = ['XXBTZUSD']\n\n #cryto_list = ['XXBTZUSD', 'XETHZUSD', 'XLTCZUSD', 'DOTUSD', 'XXMRZUSD', 'XDGUSD', 'XXLMZUSD', 'XXRPZUSD', \n # 'XZECZUSD', 'NANOUSD', 'TRXUSD', 'BCHUSD', 'XTZUSD', 'ADAUSD', 'OXTUSD']\n\n\n interval = '1440'\n since = ''\n ft = True \n df_all_prices = pd.DataFrame()\n\n for pair in (cryto_list):\n kraken_json = Get_OHLC_Kraken(pair, interval, since)\n #print('\\n\\n')\n #print(kraken_json)\n\n l_price = Process_Kraken_Jason(kraken_json, pair)\n #print('\\n\\n')\n #print(l_price)\n\n df_price = l_price_into_df_price(l_price, pair)\n #print(df_price.head())\n\n df_all_prices, ft = Concact_Prices(df_price, ft, df_all_prices)\n \n print(df_all_prices.head())\n print(df_all_prices.tail())\n\n export_df_csv(df_all_prices)\n\n\n\nif __name__== \"__main__\":\n main()\n g = input(\"End Program .... Press any key : \"); print (g)\n\n \n","repo_name":"stew1922/Crypto_Bandyts","sub_path":"libs/notebooks/closings_kraken_btc.py","file_name":"closings_kraken_btc.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"73341014482","text":"import timeit\nstarttime = timeit.default_timer()\n\n# Hack to import the input file\nimport sys\nsys.path.append(\"../../../utils\")\nimport import_input\n\ndi = import_input.DailyImput(usr=\"mvp\")\ninput_file = di.get_input()\n\nasd = [\"$ cd /\",\n\"$ ls\",\n\"dir a\",\n\"14848514 b.txt\",\n\"8504156 c.dat\",\n\"dir d\",\n\"$ cd a\",\n\"$ ls\",\n\"dir e\",\n\"29116 f\",\n\"2557 g\",\n\"62596 h.lst\",\n\"$ cd e\",\n\"$ ls\",\n\"584 i\",\n\"$ cd ..\",\n\"$ cd ..\",\n\"$ cd d\",\n\"$ ls\",\n\"4060174 j\",\n\"8033020 d.log\",\n\"5626152 d.ext\",\n\"7214296 k\"]\n\n# Challenge\nimport re\nfile_pattern = re.compile(r\"(\\d*) (.*)\") # 14848514 b.txt\nimport sys\nsys.setrecursionlimit(2000)\n\nfolder = {\n \"parent\":None,\n \"size\":0,\n \"subfolders\":{},\n \"files\":{},\n \"name\":\"root\",\n}\n\ndef run_command(commands, current_folder):\n try:\n command = next(commands)\n except StopIteration:\n return 0\n if command == \"$ cd /\": #it just shows once\n run_command(commands, current_folder)\n elif command == \"$ ls\": #doesn't change anything, is just a header for the command list\n run_command(commands, current_folder) # ***\n elif command.startswith(\"dir\"): #creates a subfolder if it doesn't exist\n folder_name = command[4:]\n create_folder(folder_name, current_folder) # current_folder is a dict, representing the current folder\n run_command(commands, current_folder)\n elif command.startswith(\"$ cd ..\"): # goes up one folder\n run_command(commands, current_folder[\"parent\"])\n elif command.startswith(\"$ cd\"): # goes down one folder\n subfolder_name = command[5:]\n sub_folders_sum = run_command(commands, current_folder[\"subfolders\"][subfolder_name])\n current_folder[\"size\"] += sub_folders_sum # run the next command on the subfolder\n # current_folder[\"size\"] += run_command(commands, current_folder[\"subfolders\"][subfolder_name]) # run the next command on the subfolder\n elif file_pattern.match(command):\n file_size, file_name = file_pattern.match(command).groups()\n file_size = int(file_size)\n current_folder[\"files\"][file_name] = {\n \"size\":file_size,\n \"name\":file_name,\n }\n current_folder[\"size\"] += file_size + run_command(commands, current_folder)\n return current_folder[\"size\"]\n\ndef create_folder(subfolder_name, current_folder_dict):\n current_folder_dict[\"subfolders\"][subfolder_name] = {\n \"parent\":current_folder_dict,\n \"size\":0,\n \"subfolders\":{},\n \"files\":{},\n \"name\":subfolder_name,\n }\n # current_folder_dict[\"subfolders\"][subfolder_name][\"this\"] = current_folder_dict[\"subfolders\"][subfolder_name]\n\ninput69 = [\n\"$ cd /\",\n\"$ ls\",\n\"dir a\",\n\"$ cd a\",\n\"$ ls\",\n\"dir b\",\n\"$ cd b\",\n\"$ ls\",\n\"dir c\",\n\"dir d\",\n\"10 a.txt\",\n\"20 ba.txt\",\n\"30 ca.txt\",\n\"$ cd c\",\n\"$ ls\",\n\"30 asd.txt\",\n\"$ cd ..\",\n\"$ cd d\",\n\"$ ls\",\n\"10 absd.md\",\n\"90 pjq.m\"]\n\n'''\nroot (190)\n a (190)\n b (60 + 130 = 190)\n a.txt 10\n ba.txt 20\n ca.txt 30\n c (30)\n asd.txt 30\n d (100)\n absd.md 10\n pjq.m 90\n'''\n\ndef get_commands(command_list):\n for command in command_list:\n yield command.strip()\n\nrun_command(get_commands(input_file), folder)\n\ndef count_sizes_recursively(folder):\n #calculate recursively the sum of the folder size with the sum of all subfolders, but only if the folder or subfolder size is less or equan than 100000\n if folder[\"size\"] <= 100000:\n return folder[\"size\"] + sum(count_sizes_recursively(subfolder) for subfolder in folder[\"subfolders\"].values())\n else:\n return sum(count_sizes_recursively(subfolder) for subfolder in folder[\"subfolders\"].values())\n\nprint(count_sizes_recursively(folder))\nprint(f\"Root size = {folder['size']}\")\nprint(\"The time difference is :\", timeit.default_timer() - starttime)","repo_name":"astropingo/advent_of_code","sub_path":"challenges/07/c01/adv_2022_07_01.py","file_name":"adv_2022_07_01.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"30743063692","text":"from __future__ import annotations\n\nimport aiohttp\nimport asyncio\nimport enum\nimport sys\nimport typing\nfrom functools import partial\n\nfrom proxy_www.utils import get_logger, wrap_class_method\n\nlogger = get_logger('proxy_www')\n\n\n\"\"\"\nDEPRECATED OLD CODES.\nPRESERVED TO CHECK PREVIOUS IMPLEMENTATION LATER.\n\"\"\"\n\n\nclass HTTPMethod(enum.Enum):\n GET = enum.auto()\n HEAD = enum.auto()\n POST = enum.auto()\n PUT = enum.auto()\n DELETE = enum.auto()\n CONNECT = enum.auto()\n OPTIONS = enum.auto()\n TRACE = enum.auto()\n PATCH = enum.auto()\n\n\nfor http_mtd in HTTPMethod:\n setattr(sys.modules[__name__], http_mtd.name, http_mtd)\n\n\nclass ClassProxyMeta(type):\n def __new__(mcs, clsname: str, bases: tuple, attrs: dict):\n logger.debug('Creating new ClassProxy class with parameters : name={}, bases={}, attrs={}'.format(clsname, bases, attrs))\n\n # Preserve original __init__ function.\n if '__init__' in attrs:\n logger.debug(f'Found pre-defined __init__ method in class {clsname}')\n original_init = attrs['__init__']\n\n @wrap_class_method(clsname)\n def __init__(self, url: str):\n self.url = url\n self.args = []\n self.kwargs = {}\n # call original __init__\n original_init(self, url)\n else:\n @wrap_class_method(clsname)\n def __init__(self, url: str):\n self.url = url\n self.args = []\n self.kwargs = {}\n\n @wrap_class_method(clsname)\n def __getattr__(self, item):\n if item in self.__dict__:\n print(f'{item} is in self.__dict__!')\n return self.__dict__[item]\n if item.startswith('__'):\n print(super(ClassProxyMeta, self).__getattr__)\n return super(ClassProxyMeta, self).__getattr__(item)\n logger.debug('{} : getattr > item = {}'.format(self.url, item))\n self.url += '.{}'.format(item)\n return self\n\n @wrap_class_method(clsname)\n def __truediv__(self, other):\n if isinstance(other, str):\n self.url += '/{}'.format(other)\n print(self.url)\n return self\n else:\n return super().__truediv__(other)\n\n @wrap_class_method(clsname)\n def __call__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n return self\n\n @wrap_class_method(clsname)\n def __await__(self) -> aiohttp.ClientResponse:\n session = aiohttp.ClientSession()\n resp = yield from session._request(self.method, self.url, *self.args, **self.kwargs).__await__()\n yield from session.close().__await__()\n logger.debug('{} -> {} : session closed? > {}'.format(self.url, self.method, session.closed))\n return resp\n\n @wrap_class_method(clsname)\n def __repr__(self) -> str:\n return 'ClassProxy(class={}, url={}, method={})'.format(self.__class__.__name__, self.url, self.method)\n\n @wrap_class_method(clsname)\n def __getitem__(self, method: typing.Union[str, HTTPMethod]):\n if type(method) is str:\n method = method.upper()\n if method not in HTTPMethod.__members__:\n raise ValueError('HTTP Method must be one of valid HTTP methods, not {}'.format(method))\n self.method = method\n elif type(method) is HTTPMethod:\n self.method = method.name\n else:\n raise TypeError('HTTP Method must be HTTPMethod or string, not {}'.format(type(method)))\n\n return self\n\n attrs.update({\n '__await__': __await__,\n '__truediv__': __truediv__,\n '__getattr__': __getattr__,\n '__init__': __init__,\n '__repr__': __repr__,\n '__getitem__': __getitem__,\n 'method': 'GET'\n })\n\n logger.debug('Updated attrs for ClassProxy {}:'.format(clsname))\n logger.debug(attrs)\n logger.debug(super().__new__)\n cls = super(ClassProxyMeta, mcs).__new__(mcs, clsname, bases, attrs)\n return cls\n\n def __getattr__(self, item):\n logger.debug(f'{self}.__getattr__ > {item} in {self}.__dict__ == {item in self.__dict__}')\n if item in self.__dict__:\n return super().__getattr__(item)\n logger.debug('Creating {} proxy object for domain {}'.format(self.__name__, item))\n if self.__name__ == 'www':\n url = '{}://www.{}'.format('https' if self.https_default else 'http', item)\n else:\n url = '{}://{}'.format(self.__name__, item)\n instance = self(url)\n return instance\n\n def __repr__(self) -> str:\n return 'ClassProxy(class={})'.format(self.__name__)\n\n\nclass www(metaclass=ClassProxyMeta):\n url: str\n https_default: bool = False\n\n @property\n def is_secure(self) -> bool:\n return self.url.startswith('https://')\n\n def secure(self):\n if not self.is_secure:\n self.url = self.url.replace('http', 'https')\n return self\n\n def insecure(self):\n if self.is_secure:\n self.url = self.url.replace('https', 'http')\n return self\n\n def __call__(self):\n # return self.__sync_req__()\n raise NotImplementedError('Currently, sync request using ClassProxy.__call__ is WIP. Sorry for inconvenience :(')\n\n def __sync_req__(self):\n task_name: str = 'www.Future({} -> {})'.format(self.url, self.method)\n task: asyncio.Task = asyncio.create_task(self.__await__(), name=task_name)\n task.add_done_callback(partial(print, task_name))\n # result = next(future.__await__())\n # print(type(result), result)\n logger.debug('{}'.format(task_name, task))\n while True:\n if task.done():\n try:\n return task.result()\n except asyncio.CancelledError:\n return '{} has been cancelled :('.format(task_name, self.url)\n except Exception:\n raise task.exception()\n\n\nclass http(metaclass=ClassProxyMeta):\n @property\n def is_secure(self) -> bool:\n return False\n\n\nclass https(metaclass=ClassProxyMeta):\n @property\n def is_secure(self) -> bool:\n return True\n\n\nasync def test():\n async def async_test():\n print('async call')\n resp = await www.github.com\n print(resp)\n\n async def async_secure_test():\n print('secure in async call')\n req: www = www.github.com.secure()\n print('Request :', req)\n print('Is secure? :', req.is_secure)\n print(await req)\n\n async def div_test():\n http_member_req = http.www.github.com\n print(http_member_req)\n print(await http_member_req)\n div_path_req = www.github.com/'profile'\n print(div_path_req)\n print(await div_path_req)\n\n def sync_test():\n print('sync call')\n resp = www.github.com()\n print(resp)\n\n async def https_test():\n resp = await https.github.com\n print(resp)\n\n await div_test()\n\n\nif __name__ == '__main__':\n asyncio.get_event_loop().run_until_complete(test())\n","repo_name":"Lapis0875/proxy-www.py","sub_path":"proxy_www/old_implementation.py","file_name":"old_implementation.py","file_ext":"py","file_size_in_byte":7340,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"3"}
+{"seq_id":"31298212603","text":"import os\nimport time\nimport re\nimport stat\nimport errno\nimport fnmatch\n\ntry:\n import pwd, grp\nexcept ImportError:\n pwd = grp = None\n\nfrom zope.interface import Interface, implementer\n\n# Twisted Imports\nfrom twisted import copyright\nfrom twisted.internet import reactor, interfaces, protocol, error, defer\nfrom twisted.protocols import basic, policies\n\nfrom twisted.python import log, failure, filepath\nfrom twisted.python.compat import range, unicode\nfrom twisted.cred import error as cred_error, portal, credentials, checkers\n\n# constants\n# response codes\n\nRESTART_MARKER_REPLY = \"100\"\nSERVICE_READY_IN_N_MINUTES = \"120\"\nDATA_CNX_ALREADY_OPEN_START_XFR = \"125\"\nFILE_STATUS_OK_OPEN_DATA_CNX = \"150\"\n\nCMD_OK = \"200.1\"\nTYPE_SET_OK = \"200.2\"\nENTERING_PORT_MODE = \"200.3\"\nCMD_NOT_IMPLMNTD_SUPERFLUOUS = \"202\"\nSYS_STATUS_OR_HELP_REPLY = \"211.1\"\nFEAT_OK = '211.2'\nDIR_STATUS = \"212\"\nFILE_STATUS = \"213\"\nHELP_MSG = \"214\"\nNAME_SYS_TYPE = \"215\"\nSVC_READY_FOR_NEW_USER = \"220.1\"\nWELCOME_MSG = \"220.2\"\nSVC_CLOSING_CTRL_CNX = \"221.1\"\nGOODBYE_MSG = \"221.2\"\nDATA_CNX_OPEN_NO_XFR_IN_PROGRESS = \"225\"\nCLOSING_DATA_CNX = \"226.1\"\nTXFR_COMPLETE_OK = \"226.2\"\nENTERING_PASV_MODE = \"227\"\nENTERING_EPSV_MODE = \"229\"\nUSR_LOGGED_IN_PROCEED = \"230.1\" # v1 of code 230\nGUEST_LOGGED_IN_PROCEED = \"230.2\" # v2 of code 230\nREQ_FILE_ACTN_COMPLETED_OK = \"250\"\nPWD_REPLY = \"257.1\"\nMKD_REPLY = \"257.2\"\n\nUSR_NAME_OK_NEED_PASS = \"331.1\" # v1 of Code 331\nGUEST_NAME_OK_NEED_EMAIL = \"331.2\" # v2 of code 331\nNEED_ACCT_FOR_LOGIN = \"332\"\nREQ_FILE_ACTN_PENDING_FURTHER_INFO = \"350\"\n\nSVC_NOT_AVAIL_CLOSING_CTRL_CNX = \"421.1\"\nTOO_MANY_CONNECTIONS = \"421.2\"\nCANT_OPEN_DATA_CNX = \"425\"\nCNX_CLOSED_TXFR_ABORTED = \"426\"\nREQ_ACTN_ABRTD_FILE_UNAVAIL = \"450\"\nREQ_ACTN_ABRTD_LOCAL_ERR = \"451\"\nREQ_ACTN_ABRTD_INSUFF_STORAGE = \"452\"\n\nSYNTAX_ERR = \"500\"\nSYNTAX_ERR_IN_ARGS = \"501\"\nCMD_NOT_IMPLMNTD = \"502.1\"\nOPTS_NOT_IMPLEMENTED = '502.2'\nBAD_CMD_SEQ = \"503\"\nCMD_NOT_IMPLMNTD_FOR_PARAM = \"504\"\nNOT_LOGGED_IN = \"530.1\" # v1 of code 530 - please log in\nAUTH_FAILURE = \"530.2\" # v2 of code 530 - authorization failure\nNEED_ACCT_FOR_STOR = \"532\"\nFILE_NOT_FOUND = \"550.1\" # no such file or directory\nPERMISSION_DENIED = \"550.2\" # permission denied\nANON_USER_DENIED = \"550.3\" # anonymous users can't alter filesystem\nIS_NOT_A_DIR = \"550.4\" # rmd called on a path that is not a directory\nREQ_ACTN_NOT_TAKEN = \"550.5\"\nFILE_EXISTS = \"550.6\"\nIS_A_DIR = \"550.7\"\nPAGE_TYPE_UNK = \"551\"\nEXCEEDED_STORAGE_ALLOC = \"552\"\nFILENAME_NOT_ALLOWED = \"553\"\n\n\nRESPONSE = {\n # -- 100's --\n RESTART_MARKER_REPLY: '110 MARK yyyy-mmmm', # TODO: this must be fixed\n SERVICE_READY_IN_N_MINUTES: '120 service ready in %s minutes',\n DATA_CNX_ALREADY_OPEN_START_XFR: '125 Data connection already open, starting transfer',\n FILE_STATUS_OK_OPEN_DATA_CNX: '150 File status okay; about to open data connection.',\n\n # -- 200's --\n CMD_OK: '200 Command OK',\n TYPE_SET_OK: '200 Type set to %s.',\n ENTERING_PORT_MODE: '200 PORT OK',\n CMD_NOT_IMPLMNTD_SUPERFLUOUS: '202 Command not implemented, superfluous at this site',\n SYS_STATUS_OR_HELP_REPLY: '211 System status reply',\n FEAT_OK: ['211-Features:','211 End'],\n DIR_STATUS: '212 %s',\n FILE_STATUS: '213 %s',\n HELP_MSG: '214 help: %s',\n NAME_SYS_TYPE: '215 UNIX Type: L8',\n WELCOME_MSG: \"220 %s\",\n SVC_READY_FOR_NEW_USER: '220 Service ready',\n SVC_CLOSING_CTRL_CNX: '221 Service closing control connection',\n GOODBYE_MSG: '221 Goodbye.',\n DATA_CNX_OPEN_NO_XFR_IN_PROGRESS: '225 data connection open, no transfer in progress',\n CLOSING_DATA_CNX: '226 Abort successful',\n TXFR_COMPLETE_OK: '226 Transfer Complete.',\n ENTERING_PASV_MODE: '227 Entering Passive Mode (%s).',\n ENTERING_EPSV_MODE: '229 Entering Extended Passive Mode (|||%s|).', # where is epsv defined in the rfc's?\n USR_LOGGED_IN_PROCEED: '230 User logged in, proceed',\n GUEST_LOGGED_IN_PROCEED: '230 Anonymous login ok, access restrictions apply.',\n REQ_FILE_ACTN_COMPLETED_OK: '250 Requested File Action Completed OK', #i.e. CWD completed ok\n PWD_REPLY: '257 \"%s\"',\n MKD_REPLY: '257 \"%s\" created',\n\n # -- 300's --\n USR_NAME_OK_NEED_PASS: '331 Password required for %s.',\n GUEST_NAME_OK_NEED_EMAIL: '331 Guest login ok, type your email address as password.',\n NEED_ACCT_FOR_LOGIN: '332 Need account for login.',\n\n REQ_FILE_ACTN_PENDING_FURTHER_INFO: '350 Requested file action pending further information.',\n\n# -- 400's --\n SVC_NOT_AVAIL_CLOSING_CTRL_CNX: '421 Service not available, closing control connection.',\n TOO_MANY_CONNECTIONS: '421 Too many users right now, try again in a few minutes.',\n CANT_OPEN_DATA_CNX: \"425 Can't open data connection.\",\n CNX_CLOSED_TXFR_ABORTED: '426 Transfer aborted. Data connection closed.',\n\n REQ_ACTN_ABRTD_FILE_UNAVAIL: '450 Requested action aborted. File unavailable.',\n REQ_ACTN_ABRTD_LOCAL_ERR: '451 Requested action aborted. Local error in processing.',\n REQ_ACTN_ABRTD_INSUFF_STORAGE: '452 Requested action aborted. Insufficient storage.',\n\n # -- 500's --\n SYNTAX_ERR: \"500 Syntax error: %s\",\n SYNTAX_ERR_IN_ARGS: '501 syntax error in argument(s) %s.',\n CMD_NOT_IMPLMNTD: \"502 Command '%s' not implemented\",\n OPTS_NOT_IMPLEMENTED: \"502 Option '%s' not implemented.\",\n BAD_CMD_SEQ: '503 Incorrect sequence of commands: %s',\n CMD_NOT_IMPLMNTD_FOR_PARAM: \"504 Not implemented for parameter '%s'.\",\n NOT_LOGGED_IN: '530 Please login with USER and PASS.',\n AUTH_FAILURE: '530 Sorry, Authentication failed.',\n NEED_ACCT_FOR_STOR: '532 Need an account for storing files',\n FILE_NOT_FOUND: '550 %s: No such file or directory.',\n PERMISSION_DENIED: '550 %s: Permission denied.',\n ANON_USER_DENIED: '550 Anonymous users are forbidden to change the filesystem',\n IS_NOT_A_DIR: '550 Cannot rmd, %s is not a directory',\n FILE_EXISTS: '550 %s: File exists',\n IS_A_DIR: '550 %s: is a directory',\n REQ_ACTN_NOT_TAKEN: '550 Requested action not taken: %s',\n PAGE_TYPE_UNK: '551 Page type unknown',\n EXCEEDED_STORAGE_ALLOC: '552 Requested file action aborted, exceeded file storage allocation',\n FILENAME_NOT_ALLOWED: '553 Requested action not taken, file name not allowed'\n}\n\n\n\nclass InvalidPath(Exception):\n \"\"\"\n Internal exception used to signify an error during parsing a path.\n \"\"\"\n\n\n\ndef toSegments(cwd, path):\n \"\"\"\n Normalize a path, as represented by a list of strings each\n representing one segment of the path.\n \"\"\"\n if path.startswith('/'):\n segs = []\n else:\n segs = cwd[:]\n\n for s in path.split('/'):\n if s == '.' or s == '':\n continue\n elif s == '..':\n if segs:\n segs.pop()\n else:\n raise InvalidPath(cwd, path)\n elif '\\0' in s or '/' in s:\n raise InvalidPath(cwd, path)\n else:\n segs.append(s)\n return segs\n\n\ndef errnoToFailure(e, path):\n \"\"\"\n Map C{OSError} and C{IOError} to standard FTP errors.\n \"\"\"\n if e == errno.ENOENT:\n return defer.fail(FileNotFoundError(path))\n elif e == errno.EACCES or e == errno.EPERM:\n return defer.fail(PermissionDeniedError(path))\n elif e == errno.ENOTDIR:\n return defer.fail(IsNotADirectoryError(path))\n elif e == errno.EEXIST:\n return defer.fail(FileExistsError(path))\n elif e == errno.EISDIR:\n return defer.fail(IsADirectoryError(path))\n else:\n return defer.fail()\n\n\n_testTranslation = fnmatch.translate('TEST')\n\n\ndef _isGlobbingExpression(segments=None):\n \"\"\"\n Helper for checking if a FTPShell `segments` contains a wildcard Unix\n expression.\n\n Only filename globbing is supported.\n This means that wildcards can only be presents in the last element of\n `segments`.\n\n @type segments: C{list}\n @param segments: List of path elements as used by the FTP server protocol.\n\n @rtype: Boolean\n @return: True if `segments` contains a globbing expression.\n \"\"\"\n if not segments:\n return False\n\n # To check that something is a glob expression, we convert it to\n # Regular Expression.\n # We compare it to the translation of a known non-glob expression.\n # If the result is the same as the original expression then it contains no\n # globbing expression.\n globCandidate = segments[-1]\n globTranslations = fnmatch.translate(globCandidate)\n nonGlobTranslations = _testTranslation.replace('TEST', globCandidate, 1)\n\n if nonGlobTranslations == globTranslations:\n return False\n else:\n return True\n\n\nclass FTPCmdError(Exception):\n \"\"\"\n Generic exception for FTP commands.\n \"\"\"\n def __init__(self, *msg):\n Exception.__init__(self, *msg)\n self.errorMessage = msg\n\n\n def response(self):\n \"\"\"\n Generate a FTP response message for this error.\n \"\"\"\n return RESPONSE[self.errorCode] % self.errorMessage\n\n\n\nclass FileNotFoundError(FTPCmdError):\n \"\"\"\n Raised when trying to access a non existent file or directory.\n \"\"\"\n errorCode = FILE_NOT_FOUND\n\n\n\nclass AnonUserDeniedError(FTPCmdError):\n \"\"\"\n Raised when an anonymous user issues a command that will alter the\n filesystem\n \"\"\"\n\n errorCode = ANON_USER_DENIED\n\n\n\nclass PermissionDeniedError(FTPCmdError):\n \"\"\"\n Raised when access is attempted to a resource to which access is\n not allowed.\n \"\"\"\n errorCode = PERMISSION_DENIED\n\n\n\nclass IsNotADirectoryError(FTPCmdError):\n \"\"\"\n Raised when RMD is called on a path that isn't a directory.\n \"\"\"\n errorCode = IS_NOT_A_DIR\n\n\n\nclass FileExistsError(FTPCmdError):\n \"\"\"\n Raised when attempted to override an existing resource.\n \"\"\"\n errorCode = FILE_EXISTS\n\n\n\nclass IsADirectoryError(FTPCmdError):\n \"\"\"\n Raised when DELE is called on a path that is a directory.\n \"\"\"\n errorCode = IS_A_DIR\n\n\n\nclass CmdSyntaxError(FTPCmdError):\n \"\"\"\n Raised when a command syntax is wrong.\n \"\"\"\n errorCode = SYNTAX_ERR\n\n\n\nclass CmdArgSyntaxError(FTPCmdError):\n \"\"\"\n Raised when a command is called with wrong value or a wrong number of\n arguments.\n \"\"\"\n errorCode = SYNTAX_ERR_IN_ARGS\n\n\n\nclass CmdNotImplementedError(FTPCmdError):\n \"\"\"\n Raised when an unimplemented command is given to the server.\n \"\"\"\n errorCode = CMD_NOT_IMPLMNTD\n\n\n\nclass CmdNotImplementedForArgError(FTPCmdError):\n \"\"\"\n Raised when the handling of a parameter for a command is not implemented by\n the server.\n \"\"\"\n errorCode = CMD_NOT_IMPLMNTD_FOR_PARAM\n\n\n\nclass FTPError(Exception):\n pass\n\n\n\nclass PortConnectionError(Exception):\n pass\n\n\n\nclass BadCmdSequenceError(FTPCmdError):\n \"\"\"\n Raised when a client sends a series of commands in an illogical sequence.\n \"\"\"\n errorCode = BAD_CMD_SEQ\n\n\n\nclass AuthorizationError(FTPCmdError):\n \"\"\"\n Raised when client authentication fails.\n \"\"\"\n errorCode = AUTH_FAILURE\n\n\n\ndef debugDeferred(self, *_):\n log.msg('debugDeferred(): %s' % str(_), debug=True)\n\n\n# -- DTP Protocol --\n\n\n_months = [\n None,\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n\n\n@implementer(interfaces.IConsumer)\nclass DTP(protocol.Protocol, object):\n isConnected = False\n\n _cons = None\n _onConnLost = None\n _buffer = None\n _encoding = 'latin-1'\n\n def connectionMade(self):\n self.isConnected = True\n self.factory.deferred.callback(None)\n self._buffer = []\n\n def connectionLost(self, reason):\n self.isConnected = False\n if self._onConnLost is not None:\n self._onConnLost.callback(None)\n\n def sendLine(self, line):\n \"\"\"\n Send a line to data channel.\n\n @param line: The line to be sent.\n @type line: L{bytes}\n \"\"\"\n self.transport.write(line + b'\\r\\n')\n\n\n def _formatOneListResponse(self, name, size, directory, permissions, hardlinks, modified, owner, group):\n \"\"\"\n Helper method to format one entry's info into a text entry like:\n 'drwxrwxrwx 0 user group 0 Jan 01 1970 filename.txt'\n\n @param name: C{bytes} name of the entry (file or directory or link)\n @param size: C{int} size of the entry\n @param directory: evals to C{bool} - whether the entry is a directory\n @param permissions: L{twisted.python.filepath.Permissions} object\n representing that entry's permissions\n @param hardlinks: C{int} number of hardlinks\n @param modified: C{float} - entry's last modified time in seconds\n since the epoch\n @param owner: C{str} username of the owner\n @param group: C{str} group name of the owner\n\n @return: C{str} in the requisite format\n \"\"\"\n def formatDate(mtime):\n now = time.gmtime()\n info = {\n 'month': _months[mtime.tm_mon],\n 'day': mtime.tm_mday,\n 'year': mtime.tm_year,\n 'hour': mtime.tm_hour,\n 'minute': mtime.tm_min\n }\n if now.tm_year != mtime.tm_year:\n return '%(month)s %(day)02d %(year)5d' % info\n else:\n return '%(month)s %(day)02d %(hour)02d:%(minute)02d' % info\n\n format = ('%(directory)s%(permissions)s%(hardlinks)4d '\n '%(owner)-9s %(group)-9s %(size)15d %(date)12s '\n )\n\n msg = (format % {\n 'directory': directory and 'd' or '-',\n 'permissions': permissions.shorthand(),\n 'hardlinks': hardlinks,\n 'owner': owner[:8],\n 'group': group[:8],\n 'size': size,\n 'date': formatDate(time.gmtime(modified)),\n }).encode(self._encoding)\n return msg + name\n\n\n def sendListResponse(self, name, response):\n self.sendLine(self._formatOneListResponse(name, *response))\n\n # Proxy IConsumer to our transport\n def registerProducer(self, producer, streaming):\n return self.transport.registerProducer(producer, streaming)\n\n def unregisterProducer(self):\n self.transport.unregisterProducer()\n self.transport.loseConnection()\n\n def write(self, data):\n if self.isConnected:\n return self.transport.write(data)\n raise Exception(\"Crap damn crap damn crap damn\")\n\n\n # Pretend to be a producer, too.\n def _conswrite(self, bytes):\n try:\n self._cons.write(bytes)\n except:\n self._onConnLost.errback()\n\n def dataReceived(self, bytes):\n if self._cons is not None:\n self._conswrite(bytes)\n else:\n self._buffer.append(bytes)\n\n def _unregConsumer(self, ignored):\n self._cons.unregisterProducer()\n self._cons = None\n del self._onConnLost\n return ignored\n\n def registerConsumer(self, cons):\n assert self._cons is None\n self._cons = cons\n self._cons.registerProducer(self, True)\n for chunk in self._buffer:\n self._conswrite(chunk)\n self._buffer = None\n if self.isConnected:\n self._onConnLost = d = defer.Deferred()\n d.addBoth(self._unregConsumer)\n return d\n else:\n self._cons.unregisterProducer()\n self._cons = None\n return defer.succeed(None)\n\n def resumeProducing(self):\n self.transport.resumeProducing()\n\n def pauseProducing(self):\n self.transport.pauseProducing()\n\n def stopProducing(self):\n self.transport.stopProducing()\n\nclass DTPFactory(protocol.ClientFactory):\n \"\"\"\n Client factory for I{data transfer process} protocols.\n\n @ivar peerCheck: perform checks to make sure the ftp-pi's peer is the same\n as the dtp's\n @ivar pi: a reference to this factory's protocol interpreter\n\n @ivar _state: Indicates the current state of the DTPFactory. Initially,\n this is L{_IN_PROGRESS}. If the connection fails or times out, it is\n L{_FAILED}. If the connection succeeds before the timeout, it is\n L{_FINISHED}.\n\n @cvar _IN_PROGRESS: Token to signal that connection is active.\n @type _IN_PROGRESS: L{object}.\n\n @cvar _FAILED: Token to signal that connection has failed.\n @type _FAILED: L{object}.\n\n @cvar _FINISHED: Token to signal that connection was successfully closed.\n @type _FINISHED: L{object}.\n \"\"\"\n\n _IN_PROGRESS = object()\n _FAILED = object()\n _FINISHED = object()\n\n _state = _IN_PROGRESS\n\n # -- configuration variables --\n peerCheck = False\n\n # -- class variables --\n def __init__(self, pi, peerHost=None, reactor=None):\n \"\"\"\n Constructor\n\n @param pi: this factory's protocol interpreter\n @param peerHost: if peerCheck is True, this is the tuple that the\n generated instance will use to perform security checks\n \"\"\"\n self.pi = pi # the protocol interpreter that is using this factory\n self.peerHost = peerHost # the from FTP.transport.peerHost()\n self.deferred = defer.Deferred() # deferred will fire when instance is connected\n self.delayedCall = None\n if reactor is None:\n from twisted.internet import reactor\n self._reactor = reactor\n\n\n def buildProtocol(self, addr):\n log.msg('DTPFactory.buildProtocol', debug=True)\n\n if self._state is not self._IN_PROGRESS:\n return None\n self._state = self._FINISHED\n\n self.cancelTimeout()\n p = DTP()\n p.factory = self\n p.pi = self.pi\n self.pi.dtpInstance = p\n return p\n\n\n def stopFactory(self):\n log.msg('dtpFactory.stopFactory', debug=True)\n self.cancelTimeout()\n\n\n def timeoutFactory(self):\n log.msg('timed out waiting for DTP connection')\n if self._state is not self._IN_PROGRESS:\n return\n self._state = self._FAILED\n\n d = self.deferred\n self.deferred = None\n d.errback(\n PortConnectionError(defer.TimeoutError(\"DTPFactory timeout\")))\n\n\n def cancelTimeout(self):\n if self.delayedCall is not None and self.delayedCall.active():\n log.msg('cancelling DTP timeout', debug=True)\n self.delayedCall.cancel()\n\n\n def setTimeout(self, seconds):\n log.msg('DTPFactory.setTimeout set to %s seconds' % seconds)\n self.delayedCall = self._reactor.callLater(seconds, self.timeoutFactory)\n\n\n def clientConnectionFailed(self, connector, reason):\n if self._state is not self._IN_PROGRESS:\n return\n self._state = self._FAILED\n d = self.deferred\n self.deferred = None\n d.errback(PortConnectionError(reason))\n\n\n# -- FTP-PI (Protocol Interpreter) --\n\nclass ASCIIConsumerWrapper(object):\n def __init__(self, cons):\n self.cons = cons\n self.registerProducer = cons.registerProducer\n self.unregisterProducer = cons.unregisterProducer\n\n assert os.linesep == \"\\r\\n\" or len(os.linesep) == 1, \"Unsupported platform (yea right like this even exists)\"\n\n if os.linesep == \"\\r\\n\":\n self.write = cons.write\n\n def write(self, bytes):\n return self.cons.write(bytes.replace(os.linesep, \"\\r\\n\"))\n\n\n\n@implementer(interfaces.IConsumer)\nclass FileConsumer(object):\n \"\"\"\n A consumer for FTP input that writes data to a file.\n\n @ivar fObj: a file object opened for writing, used to write data received.\n @type fObj: C{file}\n \"\"\"\n def __init__(self, fObj):\n self.fObj = fObj\n\n\n def registerProducer(self, producer, streaming):\n self.producer = producer\n assert streaming\n\n\n def unregisterProducer(self):\n self.producer = None\n self.fObj.close()\n\n\n def write(self, bytes):\n self.fObj.write(bytes)\n\n\n\nclass FTPOverflowProtocol(basic.LineReceiver):\n \"\"\"FTP mini-protocol for when there are too many connections.\"\"\"\n _encoding = 'latin-1'\n\n def connectionMade(self):\n self.sendLine(RESPONSE[TOO_MANY_CONNECTIONS].encode(self._encoding))\n self.transport.loseConnection()\n\n\nclass FTP(basic.LineReceiver, policies.TimeoutMixin, object):\n \"\"\"\n Protocol Interpreter for the File Transfer Protocol\n\n @ivar state: The current server state. One of L{UNAUTH},\n L{INAUTH}, L{AUTHED}, L{RENAMING}.\n\n @ivar shell: The connected avatar\n @ivar binary: The transfer mode. If false, ASCII.\n @ivar dtpFactory: Generates a single DTP for this session\n @ivar dtpPort: Port returned from listenTCP\n @ivar listenFactory: A callable with the signature of\n L{twisted.internet.interfaces.IReactorTCP.listenTCP} which will be used\n to create Ports for passive connections (mainly for testing).\n\n @ivar passivePortRange: iterator used as source of passive port numbers.\n @type passivePortRange: C{iterator}\n\n @cvar UNAUTH: Command channel is not yet authenticated.\n @type UNAUTH: L{int}\n\n @cvar INAUTH: Command channel is in the process of being authenticated.\n @type INAUTH: L{int}\n\n @cvar AUTHED: Command channel was successfully authenticated.\n @type AUTHED: L{int}\n\n @cvar RENAMING: Command channel is between the renaming command sequence.\n @type RENAMING: L{int}\n \"\"\"\n\n disconnected = False\n\n # States an FTP can be in\n UNAUTH, INAUTH, AUTHED, RENAMING = range(4)\n\n # how long the DTP waits for a connection\n dtpTimeout = 10\n\n portal = None\n shell = None\n dtpFactory = None\n dtpPort = None\n dtpInstance = None\n binary = True\n PUBLIC_COMMANDS = ['FEAT', 'QUIT']\n FEATURES = ['FEAT', 'MDTM', 'PASV', 'SIZE', 'TYPE A;I']\n\n passivePortRange = range(0, 1)\n\n listenFactory = reactor.listenTCP\n _encoding = 'latin-1'\n\n def reply(self, key, *args):\n msg = RESPONSE[key] % args\n self.sendLine(msg)\n\n\n def sendLine(self, line):\n \"\"\"\n (Private) Encodes and sends a line\n\n @param line: L{bytes} or L{unicode}\n \"\"\"\n if isinstance(line, unicode):\n line = line.encode(self._encoding)\n super(FTP, self).sendLine(line)\n\n\n def connectionMade(self):\n self.state = self.UNAUTH\n self.setTimeout(self.timeOut)\n self.reply(WELCOME_MSG, self.factory.welcomeMessage)\n\n def connectionLost(self, reason):\n # if we have a DTP protocol instance running and\n # we lose connection to the client's PI, kill the\n # DTP connection and close the port\n if self.dtpFactory:\n self.cleanupDTP()\n self.setTimeout(None)\n if hasattr(self.shell, 'logout') and self.shell.logout is not None:\n self.shell.logout()\n self.shell = None\n self.transport = None\n\n def timeoutConnection(self):\n self.transport.loseConnection()\n\n def lineReceived(self, line):\n self.resetTimeout()\n self.pauseProducing()\n if bytes != str:\n line = line.decode(self._encoding)\n\n def processFailed(err):\n if err.check(FTPCmdError):\n self.sendLine(err.value.response())\n elif (err.check(TypeError) and any((\n msg in err.value.args[0] for msg in (\n 'takes exactly', 'required positional argument')))):\n self.reply(SYNTAX_ERR, \"%s requires an argument.\" % (cmd,))\n else:\n log.msg(\"Unexpected FTP error\")\n log.err(err)\n self.reply(REQ_ACTN_NOT_TAKEN, \"internal server error\")\n\n def processSucceeded(result):\n if isinstance(result, tuple):\n self.reply(*result)\n elif result is not None:\n self.reply(result)\n\n def allDone(ignored):\n if not self.disconnected:\n self.resumeProducing()\n\n spaceIndex = line.find(' ')\n if spaceIndex != -1:\n cmd = line[:spaceIndex]\n args = (line[spaceIndex + 1:],)\n else:\n cmd = line\n args = ()\n d = defer.maybeDeferred(self.processCommand, cmd, *args)\n d.addCallbacks(processSucceeded, processFailed)\n d.addErrback(log.err)\n\n # XXX It burnsss\n # LineReceiver doesn't let you resumeProducing inside\n # lineReceived atm\n from twisted.internet import reactor\n reactor.callLater(0, d.addBoth, allDone)\n\n\n def processCommand(self, cmd, *params):\n\n def call_ftp_command(command):\n method = getattr(self, \"ftp_\" + command, None)\n if method is not None:\n return method(*params)\n return defer.fail(CmdNotImplementedError(command))\n\n cmd = cmd.upper()\n\n if cmd in self.PUBLIC_COMMANDS:\n return call_ftp_command(cmd)\n\n elif self.state == self.UNAUTH:\n if cmd == 'USER':\n return self.ftp_USER(*params)\n elif cmd == 'PASS':\n return BAD_CMD_SEQ, \"USER required before PASS\"\n else:\n return NOT_LOGGED_IN\n\n elif self.state == self.INAUTH:\n if cmd == 'PASS':\n return self.ftp_PASS(*params)\n else:\n return BAD_CMD_SEQ, \"PASS required after USER\"\n\n elif self.state == self.AUTHED:\n return call_ftp_command(cmd)\n\n elif self.state == self.RENAMING:\n if cmd == 'RNTO':\n return self.ftp_RNTO(*params)\n else:\n return BAD_CMD_SEQ, \"RNTO required after RNFR\"\n\n\n def getDTPPort(self, factory):\n \"\"\"\n Return a port for passive access, using C{self.passivePortRange}\n attribute.\n \"\"\"\n for portn in self.passivePortRange:\n try:\n dtpPort = self.listenFactory(portn, factory)\n except error.CannotListenError:\n continue\n else:\n return dtpPort\n raise error.CannotListenError('', portn,\n \"No port available in range %s\" %\n (self.passivePortRange,))\n\n\n def ftp_USER(self, username):\n \"\"\"\n First part of login. Get the username the peer wants to\n authenticate as.\n \"\"\"\n if not username:\n return defer.fail(CmdSyntaxError('USER requires an argument'))\n\n self._user = username\n self.state = self.INAUTH\n if self.factory.allowAnonymous and self._user == self.factory.userAnonymous:\n return GUEST_NAME_OK_NEED_EMAIL\n else:\n return (USR_NAME_OK_NEED_PASS, username)\n\n # TODO: add max auth try before timeout from ip...\n # TODO: need to implement minimal ABOR command\n\n def ftp_PASS(self, password):\n \"\"\"\n Second part of login. Get the password the peer wants to\n authenticate with.\n \"\"\"\n if self.factory.allowAnonymous and self._user == self.factory.userAnonymous:\n # anonymous login\n creds = credentials.Anonymous()\n reply = GUEST_LOGGED_IN_PROCEED\n else:\n # user login\n creds = credentials.UsernamePassword(self._user, password)\n reply = USR_LOGGED_IN_PROCEED\n del self._user\n\n def _cbLogin(result):\n (interface, avatar, logout) = result\n assert interface is IFTPShell, \"The realm is busted, jerk.\"\n self.shell = avatar\n self.logout = logout\n self.workingDirectory = []\n self.state = self.AUTHED\n return reply\n\n def _ebLogin(failure):\n failure.trap(cred_error.UnauthorizedLogin, cred_error.UnhandledCredentials)\n self.state = self.UNAUTH\n raise AuthorizationError\n\n d = self.portal.login(creds, None, IFTPShell)\n d.addCallbacks(_cbLogin, _ebLogin)\n return d\n\n\n def ftp_PASV(self):\n \"\"\"\n Request for a passive connection\n\n from the rfc::\n\n This command requests the server-DTP to \\\"listen\\\" on a data port\n (which is not its default data port) and to wait for a connection\n rather than initiate one upon receipt of a transfer command. The\n response to this command includes the host and port address this\n server is listening on.\n \"\"\"\n # if we have a DTP port set up, lose it.\n if self.dtpFactory is not None:\n # cleanupDTP sets dtpFactory to none. Later we'll do\n # cleanup here or something.\n self.cleanupDTP()\n self.dtpFactory = DTPFactory(pi=self)\n self.dtpFactory.setTimeout(self.dtpTimeout)\n self.dtpPort = self.getDTPPort(self.dtpFactory)\n\n host = self.transport.getHost().host\n port = self.dtpPort.getHost().port\n self.reply(ENTERING_PASV_MODE, encodeHostPort(host, port))\n return self.dtpFactory.deferred.addCallback(lambda ign: None)\n\n\n def ftp_PORT(self, address):\n addr = tuple(map(int, address.split(',')))\n ip = '%d.%d.%d.%d' % tuple(addr[:4])\n port = addr[4] << 8 | addr[5]\n\n # if we have a DTP port set up, lose it.\n if self.dtpFactory is not None:\n self.cleanupDTP()\n\n self.dtpFactory = DTPFactory(pi=self, peerHost=self.transport.getPeer().host)\n self.dtpFactory.setTimeout(self.dtpTimeout)\n self.dtpPort = reactor.connectTCP(ip, port, self.dtpFactory)\n\n def connected(ignored):\n return ENTERING_PORT_MODE\n def connFailed(err):\n err.trap(PortConnectionError)\n return CANT_OPEN_DATA_CNX\n return self.dtpFactory.deferred.addCallbacks(connected, connFailed)\n\n\n def _encodeName(self, name):\n \"\"\"\n Encode C{name} to be sent over the wire.\n\n This encodes L{unicode} objects as UTF-8 and leaves L{bytes} as-is.\n\n As described by U{RFC 3659 section\n 2.2}::\n\n Various FTP commands take pathnames as arguments, or return\n pathnames in responses. When the MLST command is supported, as\n indicated in the response to the FEAT command, pathnames are to be\n transferred in one of the following two formats.\n\n pathname = utf-8-name / raw\n utf-8-name = \n raw = \n\n Which format is used is at the option of the user-PI or server-PI\n sending the pathname.\n\n @param name: Name to be encoded.\n @type name: L{bytes} or L{unicode}\n\n @return: Wire format of C{name}.\n @rtype: L{bytes}\n \"\"\"\n if isinstance(name, unicode):\n return name.encode('utf-8')\n return name\n\n\n def ftp_LIST(self, path=''):\n \"\"\" This command causes a list to be sent from the server to the\n passive DTP. If the pathname specifies a directory or other\n group of files, the server should transfer a list of files\n in the specified directory. If the pathname specifies a\n file then the server should send current information on the\n file. A null argument implies the user's current working or\n default directory.\n \"\"\"\n # Uh, for now, do this retarded thing.\n if self.dtpInstance is None or not self.dtpInstance.isConnected:\n return defer.fail(BadCmdSequenceError('must send PORT or PASV before RETR'))\n\n # Various clients send flags like -L or -al etc. We just ignore them.\n if path.lower() in ['-a', '-l', '-la', '-al']:\n path = ''\n\n def gotListing(results):\n self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)\n for (name, attrs) in results:\n name = self._encodeName(name)\n self.dtpInstance.sendListResponse(name, attrs)\n self.dtpInstance.transport.loseConnection()\n return (TXFR_COMPLETE_OK,)\n\n try:\n segments = toSegments(self.workingDirectory, path)\n except InvalidPath:\n return defer.fail(FileNotFoundError(path))\n\n d = self.shell.list(\n segments,\n ('size', 'directory', 'permissions', 'hardlinks',\n 'modified', 'owner', 'group'))\n d.addCallback(gotListing)\n return d\n\n\n def ftp_NLST(self, path):\n \"\"\"\n This command causes a directory listing to be sent from the server to\n the client. The pathname should specify a directory or other\n system-specific file group descriptor. An empty path implies the current\n working directory. If the path is non-existent, send nothing. If the\n path is to a file, send only the file name.\n\n @type path: C{str}\n @param path: The path for which a directory listing should be returned.\n\n @rtype: L{Deferred}\n @return: a L{Deferred} which will be fired when the listing request\n is finished.\n \"\"\"\n # XXX: why is this check different from ftp_RETR/ftp_STOR? See #4180\n if self.dtpInstance is None or not self.dtpInstance.isConnected:\n return defer.fail(\n BadCmdSequenceError('must send PORT or PASV before RETR'))\n\n try:\n segments = toSegments(self.workingDirectory, path)\n except InvalidPath:\n return defer.fail(FileNotFoundError(path))\n\n def cbList(results, glob):\n \"\"\"\n Send, line by line, each matching file in the directory listing, and\n then close the connection.\n\n @type results: A C{list} of C{tuple}. The first element of each\n C{tuple} is a C{str} and the second element is a C{list}.\n @param results: The names of the files in the directory.\n\n @param glob: A shell-style glob through which to filter results (see\n U{http://docs.python.org/2/library/fnmatch.html}), or L{None}\n for no filtering.\n @type glob: L{str} or L{None}\n\n @return: A C{tuple} containing the status code for a successful\n transfer.\n @rtype: C{tuple}\n \"\"\"\n self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)\n for (name, ignored) in results:\n if not glob or (glob and fnmatch.fnmatch(name, glob)):\n name = self._encodeName(name)\n self.dtpInstance.sendLine(name)\n self.dtpInstance.transport.loseConnection()\n return (TXFR_COMPLETE_OK,)\n\n def listErr(results):\n \"\"\"\n RFC 959 specifies that an NLST request may only return directory\n listings. Thus, send nothing and just close the connection.\n\n @type results: L{Failure}\n @param results: The L{Failure} wrapping a L{FileNotFoundError} that\n occurred while trying to list the contents of a nonexistent\n directory.\n\n @returns: A C{tuple} containing the status code for a successful\n transfer.\n @rtype: C{tuple}\n \"\"\"\n self.dtpInstance.transport.loseConnection()\n return (TXFR_COMPLETE_OK,)\n\n if _isGlobbingExpression(segments):\n # Remove globbing expression from path\n # and keep to be used for filtering.\n glob = segments.pop()\n else:\n glob = None\n\n d = self.shell.list(segments)\n d.addCallback(cbList, glob)\n # self.shell.list will generate an error if the path is invalid\n d.addErrback(listErr)\n return d\n\n\n def ftp_CWD(self, path):\n try:\n segments = toSegments(self.workingDirectory, path)\n except InvalidPath:\n # XXX Eh, what to fail with here?\n return defer.fail(FileNotFoundError(path))\n\n def accessGranted(result):\n self.workingDirectory = segments\n return (REQ_FILE_ACTN_COMPLETED_OK,)\n\n return self.shell.access(segments).addCallback(accessGranted)\n\n\n def ftp_CDUP(self):\n return self.ftp_CWD('..')\n\n\n def ftp_PWD(self):\n return (PWD_REPLY, '/' + '/'.join(self.workingDirectory))\n\n\n def ftp_RETR(self, path):\n \"\"\"\n This command causes the content of a file to be sent over the data\n transfer channel. If the path is to a folder, an error will be raised.\n\n @type path: C{str}\n @param path: The path to the file which should be transferred over the\n data transfer channel.\n\n @rtype: L{Deferred}\n @return: a L{Deferred} which will be fired when the transfer is done.\n \"\"\"\n if self.dtpInstance is None:\n raise BadCmdSequenceError('PORT or PASV required before RETR')\n\n try:\n newsegs = toSegments(self.workingDirectory, path)\n except InvalidPath:\n return defer.fail(FileNotFoundError(path))\n\n # XXX For now, just disable the timeout. Later we'll want to\n # leave it active and have the DTP connection reset it\n # periodically.\n self.setTimeout(None)\n\n # Put it back later\n def enableTimeout(result):\n self.setTimeout(self.factory.timeOut)\n return result\n\n # And away she goes\n if not self.binary:\n cons = ASCIIConsumerWrapper(self.dtpInstance)\n else:\n cons = self.dtpInstance\n\n def cbSent(result):\n return (TXFR_COMPLETE_OK,)\n\n def ebSent(err):\n log.msg(\"Unexpected error attempting to transmit file to client:\")\n log.err(err)\n if err.check(FTPCmdError):\n return err\n return (CNX_CLOSED_TXFR_ABORTED,)\n\n def cbOpened(file):\n # Tell them what to doooo\n if self.dtpInstance.isConnected:\n self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)\n else:\n self.reply(FILE_STATUS_OK_OPEN_DATA_CNX)\n\n d = file.send(cons)\n d.addCallbacks(cbSent, ebSent)\n return d\n\n def ebOpened(err):\n if not err.check(PermissionDeniedError, FileNotFoundError, IsADirectoryError):\n log.msg(\"Unexpected error attempting to open file for transmission:\")\n log.err(err)\n if err.check(FTPCmdError):\n return (err.value.errorCode, '/'.join(newsegs))\n return (FILE_NOT_FOUND, '/'.join(newsegs))\n\n d = self.shell.openForReading(newsegs)\n d.addCallbacks(cbOpened, ebOpened)\n d.addBoth(enableTimeout)\n\n # Pass back Deferred that fires when the transfer is done\n return d\n\n\n def ftp_STOR(self, path):\n \"\"\"\n STORE (STOR)\n\n This command causes the server-DTP to accept the data\n transferred via the data connection and to store the data as\n a file at the server site. If the file specified in the\n pathname exists at the server site, then its contents shall\n be replaced by the data being transferred. A new file is\n created at the server site if the file specified in the\n pathname does not already exist.\n \"\"\"\n if self.dtpInstance is None:\n raise BadCmdSequenceError('PORT or PASV required before STOR')\n\n try:\n newsegs = toSegments(self.workingDirectory, path)\n except InvalidPath:\n return defer.fail(FileNotFoundError(path))\n\n # XXX For now, just disable the timeout. Later we'll want to\n # leave it active and have the DTP connection reset it\n # periodically.\n self.setTimeout(None)\n\n # Put it back later\n def enableTimeout(result):\n self.setTimeout(self.factory.timeOut)\n return result\n\n def cbOpened(file):\n \"\"\"\n File was open for reading. Launch the data transfer channel via\n the file consumer.\n \"\"\"\n d = file.receive()\n d.addCallback(cbConsumer)\n d.addCallback(lambda ignored: file.close())\n d.addCallbacks(cbSent, ebSent)\n return d\n\n def ebOpened(err):\n \"\"\"\n Called when failed to open the file for reading.\n\n For known errors, return the FTP error code.\n For all other, return a file not found error.\n \"\"\"\n if isinstance(err.value, FTPCmdError):\n return (err.value.errorCode, '/'.join(newsegs))\n log.err(err, \"Unexpected error received while opening file:\")\n return (FILE_NOT_FOUND, '/'.join(newsegs))\n\n def cbConsumer(cons):\n \"\"\"\n Called after the file was opended for reading.\n\n Prepare the data transfer channel and send the response\n to the command channel.\n \"\"\"\n if not self.binary:\n cons = ASCIIConsumerWrapper(cons)\n\n d = self.dtpInstance.registerConsumer(cons)\n\n # Tell them what to doooo\n if self.dtpInstance.isConnected:\n self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)\n else:\n self.reply(FILE_STATUS_OK_OPEN_DATA_CNX)\n\n return d\n\n def cbSent(result):\n \"\"\"\n Called from data transport when tranfer is done.\n \"\"\"\n return (TXFR_COMPLETE_OK,)\n\n def ebSent(err):\n \"\"\"\n Called from data transport when there are errors during the\n transfer.\n \"\"\"\n log.err(err, \"Unexpected error received during transfer:\")\n if err.check(FTPCmdError):\n return err\n return (CNX_CLOSED_TXFR_ABORTED,)\n\n d = self.shell.openForWriting(newsegs)\n d.addCallbacks(cbOpened, ebOpened)\n d.addBoth(enableTimeout)\n\n # Pass back Deferred that fires when the transfer is done\n return d\n\n\n def ftp_SIZE(self, path):\n \"\"\"\n File SIZE\n\n The FTP command, SIZE OF FILE (SIZE), is used to obtain the transfer\n size of a file from the server-FTP process. This is the exact number\n of octets (8 bit bytes) that would be transmitted over the data\n connection should that file be transmitted. This value will change\n depending on the current STRUcture, MODE, and TYPE of the data\n connection or of a data connection that would be created were one\n created now. Thus, the result of the SIZE command is dependent on\n the currently established STRU, MODE, and TYPE parameters.\n\n The SIZE command returns how many octets would be transferred if the\n file were to be transferred using the current transfer structure,\n mode, and type. This command is normally used in conjunction with\n the RESTART (REST) command when STORing a file to a remote server in\n STREAM mode, to determine the restart point. The server-PI might\n need to read the partially transferred file, do any appropriate\n conversion, and count the number of octets that would be generated\n when sending the file in order to correctly respond to this command.\n Estimates of the file transfer size MUST NOT be returned; only\n precise information is acceptable.\n\n http://tools.ietf.org/html/rfc3659\n \"\"\"\n try:\n newsegs = toSegments(self.workingDirectory, path)\n except InvalidPath:\n return defer.fail(FileNotFoundError(path))\n\n def cbStat(result):\n (size,) = result\n return (FILE_STATUS, str(size))\n\n return self.shell.stat(newsegs, ('size',)).addCallback(cbStat)\n\n\n def ftp_MDTM(self, path):\n \"\"\"\n File Modification Time (MDTM)\n\n The FTP command, MODIFICATION TIME (MDTM), can be used to determine\n when a file in the server NVFS was last modified. This command has\n existed in many FTP servers for many years, as an adjunct to the REST\n command for STREAM mode, thus is widely available. However, where\n supported, the \"modify\" fact that can be provided in the result from\n the new MLST command is recommended as a superior alternative.\n\n http://tools.ietf.org/html/rfc3659\n \"\"\"\n try:\n newsegs = toSegments(self.workingDirectory, path)\n except InvalidPath:\n return defer.fail(FileNotFoundError(path))\n\n def cbStat(result):\n (modified,) = result\n return (FILE_STATUS, time.strftime('%Y%m%d%H%M%S', time.gmtime(modified)))\n\n return self.shell.stat(newsegs, ('modified',)).addCallback(cbStat)\n\n\n def ftp_TYPE(self, type):\n \"\"\"\n REPRESENTATION TYPE (TYPE)\n\n The argument specifies the representation type as described\n in the Section on Data Representation and Storage. Several\n types take a second parameter. The first parameter is\n denoted by a single Telnet character, as is the second\n Format parameter for ASCII and EBCDIC; the second parameter\n for local byte is a decimal integer to indicate Bytesize.\n The parameters are separated by a (Space, ASCII code\n 32).\n \"\"\"\n p = type.upper()\n if p:\n f = getattr(self, 'type_' + p[0], None)\n if f is not None:\n return f(p[1:])\n return self.type_UNKNOWN(p)\n return (SYNTAX_ERR,)\n\n def type_A(self, code):\n if code == '' or code == 'N':\n self.binary = False\n return (TYPE_SET_OK, 'A' + code)\n else:\n return defer.fail(CmdArgSyntaxError(code))\n\n def type_I(self, code):\n if code == '':\n self.binary = True\n return (TYPE_SET_OK, 'I')\n else:\n return defer.fail(CmdArgSyntaxError(code))\n\n def type_UNKNOWN(self, code):\n return defer.fail(CmdNotImplementedForArgError(code))\n\n\n\n def ftp_SYST(self):\n return NAME_SYS_TYPE\n\n\n def ftp_STRU(self, structure):\n p = structure.upper()\n if p == 'F':\n return (CMD_OK,)\n return defer.fail(CmdNotImplementedForArgError(structure))\n\n\n def ftp_MODE(self, mode):\n p = mode.upper()\n if p == 'S':\n return (CMD_OK,)\n return defer.fail(CmdNotImplementedForArgError(mode))\n\n\n def ftp_MKD(self, path):\n try:\n newsegs = toSegments(self.workingDirectory, path)\n except InvalidPath:\n return defer.fail(FileNotFoundError(path))\n return self.shell.makeDirectory(newsegs).addCallback(lambda ign: (MKD_REPLY, path))\n\n\n def ftp_RMD(self, path):\n try:\n newsegs = toSegments(self.workingDirectory, path)\n except InvalidPath:\n return defer.fail(FileNotFoundError(path))\n return self.shell.removeDirectory(newsegs).addCallback(lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,))\n\n\n def ftp_DELE(self, path):\n try:\n newsegs = toSegments(self.workingDirectory, path)\n except InvalidPath:\n return defer.fail(FileNotFoundError(path))\n return self.shell.removeFile(newsegs).addCallback(lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,))\n\n\n def ftp_NOOP(self):\n return (CMD_OK,)\n\n\n def ftp_RNFR(self, fromName):\n self._fromName = fromName\n self.state = self.RENAMING\n return (REQ_FILE_ACTN_PENDING_FURTHER_INFO,)\n\n\n def ftp_RNTO(self, toName):\n fromName = self._fromName\n del self._fromName\n self.state = self.AUTHED\n\n try:\n fromsegs = toSegments(self.workingDirectory, fromName)\n tosegs = toSegments(self.workingDirectory, toName)\n except InvalidPath:\n return defer.fail(FileNotFoundError(fromName))\n return self.shell.rename(fromsegs, tosegs).addCallback(lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,))\n\n\n def ftp_FEAT(self):\n \"\"\"\n Advertise the features supported by the server.\n\n http://tools.ietf.org/html/rfc2389\n \"\"\"\n self.sendLine(RESPONSE[FEAT_OK][0])\n for feature in self.FEATURES:\n self.sendLine(' ' + feature)\n self.sendLine(RESPONSE[FEAT_OK][1])\n\n def ftp_OPTS(self, option):\n \"\"\"\n Handle OPTS command.\n\n http://tools.ietf.org/html/draft-ietf-ftpext-utf-8-option-00\n \"\"\"\n return self.reply(OPTS_NOT_IMPLEMENTED, option)\n\n def ftp_QUIT(self):\n self.reply(GOODBYE_MSG)\n self.transport.loseConnection()\n self.disconnected = True\n\n def cleanupDTP(self):\n \"\"\"\n Call when DTP connection exits\n \"\"\"\n log.msg('cleanupDTP', debug=True)\n\n log.msg(self.dtpPort)\n dtpPort, self.dtpPort = self.dtpPort, None\n if interfaces.IListeningPort.providedBy(dtpPort):\n dtpPort.stopListening()\n elif interfaces.IConnector.providedBy(dtpPort):\n dtpPort.disconnect()\n else:\n assert False, \"dtpPort should be an IListeningPort or IConnector, instead is %r\" % (dtpPort,)\n\n self.dtpFactory.stopFactory()\n self.dtpFactory = None\n\n if self.dtpInstance is not None:\n self.dtpInstance = None\n\n\nclass FTPFactory(policies.LimitTotalConnectionsFactory):\n \"\"\"\n A factory for producing ftp protocol instances\n\n @ivar timeOut: the protocol interpreter's idle timeout time in seconds,\n default is 600 seconds.\n\n @ivar passivePortRange: value forwarded to C{protocol.passivePortRange}.\n @type passivePortRange: C{iterator}\n \"\"\"\n protocol = FTP\n overflowProtocol = FTPOverflowProtocol\n allowAnonymous = True\n userAnonymous = 'anonymous'\n timeOut = 600\n\n welcomeMessage = \"Twisted %s FTP Server\" % (copyright.version,)\n\n passivePortRange = range(0, 1)\n\n def __init__(self, portal=None, userAnonymous='anonymous'):\n self.portal = portal\n self.userAnonymous = userAnonymous\n self.instances = []\n\n def buildProtocol(self, addr):\n p = policies.LimitTotalConnectionsFactory.buildProtocol(self, addr)\n if p is not None:\n p.wrappedProtocol.portal = self.portal\n p.wrappedProtocol.timeOut = self.timeOut\n p.wrappedProtocol.passivePortRange = self.passivePortRange\n return p\n\n def stopFactory(self):\n # make sure ftp instance's timeouts are set to None\n # to avoid reactor complaints\n [p.setTimeout(None) for p in self.instances if p.timeOut is not None]\n policies.LimitTotalConnectionsFactory.stopFactory(self)\n\n# -- Cred Objects --\n\n\nclass IFTPShell(Interface):\n \"\"\"\n An abstraction of the shell commands used by the FTP protocol for\n a given user account.\n\n All path names must be absolute.\n \"\"\"\n\n def makeDirectory(path):\n \"\"\"\n Create a directory.\n\n @param path: The path, as a list of segments, to create\n @type path: C{list} of C{unicode}\n\n @return: A Deferred which fires when the directory has been\n created, or which fails if the directory cannot be created.\n \"\"\"\n\n\n def removeDirectory(path):\n \"\"\"\n Remove a directory.\n\n @param path: The path, as a list of segments, to remove\n @type path: C{list} of C{unicode}\n\n @return: A Deferred which fires when the directory has been\n removed, or which fails if the directory cannot be removed.\n \"\"\"\n\n\n def removeFile(path):\n \"\"\"\n Remove a file.\n\n @param path: The path, as a list of segments, to remove\n @type path: C{list} of C{unicode}\n\n @return: A Deferred which fires when the file has been\n removed, or which fails if the file cannot be removed.\n \"\"\"\n\n\n def rename(fromPath, toPath):\n \"\"\"\n Rename a file or directory.\n\n @param fromPath: The current name of the path.\n @type fromPath: C{list} of C{unicode}\n\n @param toPath: The desired new name of the path.\n @type toPath: C{list} of C{unicode}\n\n @return: A Deferred which fires when the path has been\n renamed, or which fails if the path cannot be renamed.\n \"\"\"\n\n\n def access(path):\n \"\"\"\n Determine whether access to the given path is allowed.\n\n @param path: The path, as a list of segments\n\n @return: A Deferred which fires with None if access is allowed\n or which fails with a specific exception type if access is\n denied.\n \"\"\"\n\n\n def stat(path, keys=()):\n \"\"\"\n Retrieve information about the given path.\n\n This is like list, except it will never return results about\n child paths.\n \"\"\"\n\n\n def list(path, keys=()):\n \"\"\"\n Retrieve information about the given path.\n\n If the path represents a non-directory, the result list should\n have only one entry with information about that non-directory.\n Otherwise, the result list should have an element for each\n child of the directory.\n\n @param path: The path, as a list of segments, to list\n @type path: C{list} of C{unicode} or C{bytes}\n\n @param keys: A tuple of keys desired in the resulting\n dictionaries.\n\n @return: A Deferred which fires with a list of (name, list),\n where the name is the name of the entry as a unicode string or\n bytes and each list contains values corresponding to the requested\n keys. The following are possible elements of keys, and the\n values which should be returned for them:\n\n - C{'size'}: size in bytes, as an integer (this is kinda required)\n\n - C{'directory'}: boolean indicating the type of this entry\n\n - C{'permissions'}: a bitvector (see os.stat(foo).st_mode)\n\n - C{'hardlinks'}: Number of hard links to this entry\n\n - C{'modified'}: number of seconds since the epoch since entry was\n modified\n\n - C{'owner'}: string indicating the user owner of this entry\n\n - C{'group'}: string indicating the group owner of this entry\n \"\"\"\n\n\n def openForReading(path):\n \"\"\"\n @param path: The path, as a list of segments, to open\n @type path: C{list} of C{unicode}\n\n @rtype: C{Deferred} which will fire with L{IReadFile}\n \"\"\"\n\n\n def openForWriting(path):\n \"\"\"\n @param path: The path, as a list of segments, to open\n @type path: C{list} of C{unicode}\n\n @rtype: C{Deferred} which will fire with L{IWriteFile}\n \"\"\"\n\n\n\nclass IReadFile(Interface):\n \"\"\"\n A file out of which bytes may be read.\n \"\"\"\n\n def send(consumer):\n \"\"\"\n Produce the contents of the given path to the given consumer. This\n method may only be invoked once on each provider.\n\n @type consumer: C{IConsumer}\n\n @return: A Deferred which fires when the file has been\n consumed completely.\n \"\"\"\n\n\n\nclass IWriteFile(Interface):\n \"\"\"\n A file into which bytes may be written.\n \"\"\"\n\n def receive():\n \"\"\"\n Create a consumer which will write to this file. This method may\n only be invoked once on each provider.\n\n @rtype: C{Deferred} of C{IConsumer}\n \"\"\"\n\n def close():\n \"\"\"\n Perform any post-write work that needs to be done. This method may\n only be invoked once on each provider, and will always be invoked\n after receive().\n\n @rtype: C{Deferred} of anything: the value is ignored. The FTP client\n will not see their upload request complete until this Deferred has\n been fired.\n \"\"\"\n\ndef _getgroups(uid):\n \"\"\"\n Return the primary and supplementary groups for the given UID.\n\n @type uid: C{int}\n \"\"\"\n result = []\n pwent = pwd.getpwuid(uid)\n\n result.append(pwent.pw_gid)\n\n for grent in grp.getgrall():\n if pwent.pw_name in grent.gr_mem:\n result.append(grent.gr_gid)\n\n return result\n\n\ndef _testPermissions(uid, gid, spath, mode='r'):\n \"\"\"\n checks to see if uid has proper permissions to access path with mode\n\n @type uid: C{int}\n @param uid: numeric user id\n\n @type gid: C{int}\n @param gid: numeric group id\n\n @type spath: C{str}\n @param spath: the path on the server to test\n\n @type mode: C{str}\n @param mode: 'r' or 'w' (read or write)\n\n @rtype: C{bool}\n @return: True if the given credentials have the specified form of\n access to the given path\n \"\"\"\n if mode == 'r':\n usr = stat.S_IRUSR\n grp = stat.S_IRGRP\n oth = stat.S_IROTH\n amode = os.R_OK\n elif mode == 'w':\n usr = stat.S_IWUSR\n grp = stat.S_IWGRP\n oth = stat.S_IWOTH\n amode = os.W_OK\n else:\n raise ValueError(\"Invalid mode %r: must specify 'r' or 'w'\" % (mode,))\n\n access = False\n if os.path.exists(spath):\n if uid == 0:\n access = True\n else:\n s = os.stat(spath)\n if usr & s.st_mode and uid == s.st_uid:\n access = True\n elif grp & s.st_mode and gid in _getgroups(uid):\n access = True\n elif oth & s.st_mode:\n access = True\n\n if access:\n if not os.access(spath, amode):\n access = False\n log.msg(\"Filesystem grants permission to UID %d but it is inaccessible to me running as UID %d\" % (\n uid, os.getuid()))\n return access\n\n\n\n@implementer(IFTPShell)\nclass FTPAnonymousShell(object):\n \"\"\"\n An anonymous implementation of IFTPShell\n\n @type filesystemRoot: L{twisted.python.filepath.FilePath}\n @ivar filesystemRoot: The path which is considered the root of\n this shell.\n \"\"\"\n def __init__(self, filesystemRoot):\n self.filesystemRoot = filesystemRoot\n\n\n def _path(self, path):\n return self.filesystemRoot.descendant(path)\n\n\n def makeDirectory(self, path):\n return defer.fail(AnonUserDeniedError())\n\n\n def removeDirectory(self, path):\n return defer.fail(AnonUserDeniedError())\n\n\n def removeFile(self, path):\n return defer.fail(AnonUserDeniedError())\n\n\n def rename(self, fromPath, toPath):\n return defer.fail(AnonUserDeniedError())\n\n\n def receive(self, path):\n path = self._path(path)\n return defer.fail(AnonUserDeniedError())\n\n\n def openForReading(self, path):\n \"\"\"\n Open C{path} for reading.\n\n @param path: The path, as a list of segments, to open.\n @type path: C{list} of C{unicode}\n @return: A L{Deferred} is returned that will fire with an object\n implementing L{IReadFile} if the file is successfully opened. If\n C{path} is a directory, or if an exception is raised while trying\n to open the file, the L{Deferred} will fire with an error.\n \"\"\"\n p = self._path(path)\n if p.isdir():\n # Normally, we would only check for EISDIR in open, but win32\n # returns EACCES in this case, so we check before\n return defer.fail(IsADirectoryError(path))\n try:\n f = p.open('r')\n except (IOError, OSError) as e:\n return errnoToFailure(e.errno, path)\n except:\n return defer.fail()\n else:\n return defer.succeed(_FileReader(f))\n\n\n def openForWriting(self, path):\n \"\"\"\n Reject write attempts by anonymous users with\n L{PermissionDeniedError}.\n \"\"\"\n return defer.fail(PermissionDeniedError(\"STOR not allowed\"))\n\n\n def access(self, path):\n p = self._path(path)\n if not p.exists():\n # Again, win32 doesn't report a sane error after, so let's fail\n # early if we can\n return defer.fail(FileNotFoundError(path))\n # For now, just see if we can os.listdir() it\n try:\n p.listdir()\n except (IOError, OSError) as e:\n return errnoToFailure(e.errno, path)\n except:\n return defer.fail()\n else:\n return defer.succeed(None)\n\n\n def stat(self, path, keys=()):\n p = self._path(path)\n if p.isdir():\n try:\n statResult = self._statNode(p, keys)\n except (IOError, OSError) as e:\n return errnoToFailure(e.errno, path)\n except:\n return defer.fail()\n else:\n return defer.succeed(statResult)\n else:\n return self.list(path, keys).addCallback(lambda res: res[0][1])\n\n\n def list(self, path, keys=()):\n \"\"\"\n Return the list of files at given C{path}, adding C{keys} stat\n informations if specified.\n\n @param path: the directory or file to check.\n @type path: C{str}\n\n @param keys: the list of desired metadata\n @type keys: C{list} of C{str}\n \"\"\"\n filePath = self._path(path)\n if filePath.isdir():\n entries = filePath.listdir()\n fileEntries = [filePath.child(p) for p in entries]\n elif filePath.isfile():\n entries = [os.path.join(*filePath.segmentsFrom(self.filesystemRoot))]\n fileEntries = [filePath]\n else:\n return defer.fail(FileNotFoundError(path))\n\n results = []\n for fileName, filePath in zip(entries, fileEntries):\n ent = []\n results.append((fileName, ent))\n if keys:\n try:\n ent.extend(self._statNode(filePath, keys))\n except (IOError, OSError) as e:\n return errnoToFailure(e.errno, fileName)\n except:\n return defer.fail()\n\n return defer.succeed(results)\n\n\n def _statNode(self, filePath, keys):\n \"\"\"\n Shortcut method to get stat info on a node.\n\n @param filePath: the node to stat.\n @type filePath: C{filepath.FilePath}\n\n @param keys: the stat keys to get.\n @type keys: C{iterable}\n \"\"\"\n filePath.restat()\n return [getattr(self, '_stat_' + k)(filePath) for k in keys]\n\n\n def _stat_size(self, fp):\n \"\"\"\n Get the filepath's size as an int\n\n @param fp: L{twisted.python.filepath.FilePath}\n @return: C{int} representing the size\n \"\"\"\n return fp.getsize()\n\n\n def _stat_permissions(self, fp):\n \"\"\"\n Get the filepath's permissions object\n\n @param fp: L{twisted.python.filepath.FilePath}\n @return: L{twisted.python.filepath.Permissions} of C{fp}\n \"\"\"\n return fp.getPermissions()\n\n\n def _stat_hardlinks(self, fp):\n \"\"\"\n Get the number of hardlinks for the filepath - if the number of\n hardlinks is not yet implemented (say in Windows), just return 0 since\n stat-ing a file in Windows seems to return C{st_nlink=0}.\n\n (Reference:\n U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})\n\n @param fp: L{twisted.python.filepath.FilePath}\n @return: C{int} representing the number of hardlinks\n \"\"\"\n try:\n return fp.getNumberOfHardLinks()\n except NotImplementedError:\n return 0\n\n\n def _stat_modified(self, fp):\n \"\"\"\n Get the filepath's last modified date\n\n @param fp: L{twisted.python.filepath.FilePath}\n @return: C{int} as seconds since the epoch\n \"\"\"\n return fp.getModificationTime()\n\n\n def _stat_owner(self, fp):\n \"\"\"\n Get the filepath's owner's username. If this is not implemented\n (say in Windows) return the string \"0\" since stat-ing a file in\n Windows seems to return C{st_uid=0}.\n\n (Reference:\n U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})\n\n @param fp: L{twisted.python.filepath.FilePath}\n @return: C{str} representing the owner's username\n \"\"\"\n try:\n userID = fp.getUserID()\n except NotImplementedError:\n return \"0\"\n else:\n if pwd is not None:\n try:\n return pwd.getpwuid(userID)[0]\n except KeyError:\n pass\n return str(userID)\n\n\n def _stat_group(self, fp):\n \"\"\"\n Get the filepath's owner's group. If this is not implemented\n (say in Windows) return the string \"0\" since stat-ing a file in\n Windows seems to return C{st_gid=0}.\n\n (Reference:\n U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})\n\n @param fp: L{twisted.python.filepath.FilePath}\n @return: C{str} representing the owner's group\n \"\"\"\n try:\n groupID = fp.getGroupID()\n except NotImplementedError:\n return \"0\"\n else:\n if grp is not None:\n try:\n return grp.getgrgid(groupID)[0]\n except KeyError:\n pass\n return str(groupID)\n\n\n def _stat_directory(self, fp):\n \"\"\"\n Get whether the filepath is a directory\n\n @param fp: L{twisted.python.filepath.FilePath}\n @return: C{bool}\n \"\"\"\n return fp.isdir()\n\n\n\n@implementer(IReadFile)\nclass _FileReader(object):\n def __init__(self, fObj):\n self.fObj = fObj\n self._send = False\n\n def _close(self, passthrough):\n self._send = True\n self.fObj.close()\n return passthrough\n\n def send(self, consumer):\n assert not self._send, \"Can only call IReadFile.send *once* per instance\"\n self._send = True\n d = basic.FileSender().beginFileTransfer(self.fObj, consumer)\n d.addBoth(self._close)\n return d\n\n\n\nclass FTPShell(FTPAnonymousShell):\n \"\"\"\n An authenticated implementation of L{IFTPShell}.\n \"\"\"\n\n def makeDirectory(self, path):\n p = self._path(path)\n try:\n p.makedirs()\n except (IOError, OSError) as e:\n return errnoToFailure(e.errno, path)\n except:\n return defer.fail()\n else:\n return defer.succeed(None)\n\n\n def removeDirectory(self, path):\n p = self._path(path)\n if p.isfile():\n # Win32 returns the wrong errno when rmdir is called on a file\n # instead of a directory, so as we have the info here, let's fail\n # early with a pertinent error\n return defer.fail(IsNotADirectoryError(path))\n try:\n os.rmdir(p.path)\n except (IOError, OSError) as e:\n return errnoToFailure(e.errno, path)\n except:\n return defer.fail()\n else:\n return defer.succeed(None)\n\n\n def removeFile(self, path):\n p = self._path(path)\n if p.isdir():\n # Win32 returns the wrong errno when remove is called on a\n # directory instead of a file, so as we have the info here,\n # let's fail early with a pertinent error\n return defer.fail(IsADirectoryError(path))\n try:\n p.remove()\n except (IOError, OSError) as e:\n return errnoToFailure(e.errno, path)\n except:\n return defer.fail()\n else:\n return defer.succeed(None)\n\n\n def rename(self, fromPath, toPath):\n fp = self._path(fromPath)\n tp = self._path(toPath)\n try:\n os.rename(fp.path, tp.path)\n except (IOError, OSError) as e:\n return errnoToFailure(e.errno, fromPath)\n except:\n return defer.fail()\n else:\n return defer.succeed(None)\n\n\n def openForWriting(self, path):\n \"\"\"\n Open C{path} for writing.\n\n @param path: The path, as a list of segments, to open.\n @type path: C{list} of C{unicode}\n @return: A L{Deferred} is returned that will fire with an object\n implementing L{IWriteFile} if the file is successfully opened. If\n C{path} is a directory, or if an exception is raised while trying\n to open the file, the L{Deferred} will fire with an error.\n \"\"\"\n p = self._path(path)\n if p.isdir():\n # Normally, we would only check for EISDIR in open, but win32\n # returns EACCES in this case, so we check before\n return defer.fail(IsADirectoryError(path))\n try:\n fObj = p.open('w')\n except (IOError, OSError) as e:\n return errnoToFailure(e.errno, path)\n except:\n return defer.fail()\n return defer.succeed(_FileWriter(fObj))\n\n\n\n@implementer(IWriteFile)\nclass _FileWriter(object):\n def __init__(self, fObj):\n self.fObj = fObj\n self._receive = False\n\n def receive(self):\n assert not self._receive, \"Can only call IWriteFile.receive *once* per instance\"\n self._receive = True\n # FileConsumer will close the file object\n return defer.succeed(FileConsumer(self.fObj))\n\n def close(self):\n return defer.succeed(None)\n\n\n\n@implementer(portal.IRealm)\nclass BaseFTPRealm:\n \"\"\"\n Base class for simple FTP realms which provides an easy hook for specifying\n the home directory for each user.\n \"\"\"\n def __init__(self, anonymousRoot):\n self.anonymousRoot = filepath.FilePath(anonymousRoot)\n\n\n def getHomeDirectory(self, avatarId):\n \"\"\"\n Return a L{FilePath} representing the home directory of the given\n avatar. Override this in a subclass.\n\n @param avatarId: A user identifier returned from a credentials checker.\n @type avatarId: C{str}\n\n @rtype: L{FilePath}\n \"\"\"\n raise NotImplementedError(\n \"%r did not override getHomeDirectory\" % (self.__class__,))\n\n\n def requestAvatar(self, avatarId, mind, *interfaces):\n for iface in interfaces:\n if iface is IFTPShell:\n if avatarId is checkers.ANONYMOUS:\n avatar = FTPAnonymousShell(self.anonymousRoot)\n else:\n avatar = FTPShell(self.getHomeDirectory(avatarId))\n return (IFTPShell, avatar,\n getattr(avatar, 'logout', lambda: None))\n raise NotImplementedError(\n \"Only IFTPShell interface is supported by this realm\")\n\n\n\nclass FTPRealm(BaseFTPRealm):\n \"\"\"\n @type anonymousRoot: L{twisted.python.filepath.FilePath}\n @ivar anonymousRoot: Root of the filesystem to which anonymous\n users will be granted access.\n\n @type userHome: L{filepath.FilePath}\n @ivar userHome: Root of the filesystem containing user home directories.\n \"\"\"\n def __init__(self, anonymousRoot, userHome='/home'):\n BaseFTPRealm.__init__(self, anonymousRoot)\n self.userHome = filepath.FilePath(userHome)\n\n\n def getHomeDirectory(self, avatarId):\n \"\"\"\n Use C{avatarId} as a single path segment to construct a child of\n C{self.userHome} and return that child.\n \"\"\"\n return self.userHome.child(avatarId)\n\n\n\nclass SystemFTPRealm(BaseFTPRealm):\n \"\"\"\n L{SystemFTPRealm} uses system user account information to decide what the\n home directory for a particular avatarId is.\n\n This works on POSIX but probably is not reliable on Windows.\n \"\"\"\n def getHomeDirectory(self, avatarId):\n \"\"\"\n Return the system-defined home directory of the system user account with\n the name C{avatarId}.\n \"\"\"\n path = os.path.expanduser('~' + avatarId)\n if path.startswith('~'):\n raise cred_error.UnauthorizedLogin()\n return filepath.FilePath(path)\n\n\n\n# --- FTP CLIENT -------------------------------------------------------------\n\n####\n# And now for the client...\n\n# Notes:\n# * Reference: http://cr.yp.to/ftp.html\n# * FIXME: Does not support pipelining (which is not supported by all\n# servers anyway). This isn't a functionality limitation, just a\n# small performance issue.\n# * Only has a rudimentary understanding of FTP response codes (although\n# the full response is passed to the caller if they so choose).\n# * Assumes that USER and PASS should always be sent\n# * Always sets TYPE I (binary mode)\n# * Doesn't understand any of the weird, obscure TELNET stuff (\\377...)\n# * FIXME: Doesn't share any code with the FTPServer\n\nclass ConnectionLost(FTPError):\n pass\n\nclass CommandFailed(FTPError):\n pass\n\nclass BadResponse(FTPError):\n pass\n\nclass UnexpectedResponse(FTPError):\n pass\n\nclass UnexpectedData(FTPError):\n pass\n\nclass FTPCommand:\n def __init__(self, text=None, public=0):\n self.text = text\n self.deferred = defer.Deferred()\n self.ready = 1\n self.public = public\n self.transferDeferred = None\n\n def fail(self, failure):\n if self.public:\n self.deferred.errback(failure)\n\n\nclass ProtocolWrapper(protocol.Protocol):\n def __init__(self, original, deferred):\n self.original = original\n self.deferred = deferred\n def makeConnection(self, transport):\n self.original.makeConnection(transport)\n def dataReceived(self, data):\n self.original.dataReceived(data)\n def connectionLost(self, reason):\n self.original.connectionLost(reason)\n # Signal that transfer has completed\n self.deferred.callback(None)\n\n\n\nclass IFinishableConsumer(interfaces.IConsumer):\n \"\"\"\n A Consumer for producers that finish.\n\n @since: 11.0\n \"\"\"\n\n def finish():\n \"\"\"\n The producer has finished producing.\n \"\"\"\n\n\n\n@implementer(IFinishableConsumer)\nclass SenderProtocol(protocol.Protocol):\n def __init__(self):\n # Fired upon connection\n self.connectedDeferred = defer.Deferred()\n\n # Fired upon disconnection\n self.deferred = defer.Deferred()\n\n #Protocol stuff\n def dataReceived(self, data):\n raise UnexpectedData(\n \"Received data from the server on a \"\n \"send-only data-connection\"\n )\n\n def makeConnection(self, transport):\n protocol.Protocol.makeConnection(self, transport)\n self.connectedDeferred.callback(self)\n\n def connectionLost(self, reason):\n if reason.check(error.ConnectionDone):\n self.deferred.callback('connection done')\n else:\n self.deferred.errback(reason)\n\n #IFinishableConsumer stuff\n def write(self, data):\n self.transport.write(data)\n\n def registerProducer(self, producer, streaming):\n \"\"\"\n Register the given producer with our transport.\n \"\"\"\n self.transport.registerProducer(producer, streaming)\n\n def unregisterProducer(self):\n \"\"\"\n Unregister the previously registered producer.\n \"\"\"\n self.transport.unregisterProducer()\n\n def finish(self):\n self.transport.loseConnection()\n\n\ndef decodeHostPort(line):\n \"\"\"\n Decode an FTP response specifying a host and port.\n\n @return: a 2-tuple of (host, port).\n \"\"\"\n abcdef = re.sub('[^0-9, ]', '', line)\n parsed = [int(p.strip()) for p in abcdef.split(',')]\n for x in parsed:\n if x < 0 or x > 255:\n raise ValueError(\"Out of range\", line, x)\n a, b, c, d, e, f = parsed\n host = \"%s.%s.%s.%s\" % (a, b, c, d)\n port = (int(e) << 8) + int(f)\n return host, port\n\ndef encodeHostPort(host, port):\n numbers = host.split('.') + [str(port >> 8), str(port % 256)]\n return ','.join(numbers)\n\ndef _unwrapFirstError(failure):\n failure.trap(defer.FirstError)\n return failure.value.subFailure\n\nclass FTPDataPortFactory(protocol.ServerFactory):\n \"\"\"\n Factory for data connections that use the PORT command\n\n (i.e. \"active\" transfers)\n \"\"\"\n noisy = 0\n def buildProtocol(self, addr):\n # This is a bit hackish -- we already have a Protocol instance,\n # so just return it instead of making a new one\n # FIXME: Reject connections from the wrong address/port\n # (potential security problem)\n self.protocol.factory = self\n self.port.loseConnection()\n return self.protocol\n\n\n\nclass FTPClientBasic(basic.LineReceiver):\n \"\"\"\n Foundations of an FTP client.\n \"\"\"\n debug = False\n _encoding = 'latin-1'\n\n def __init__(self):\n self.actionQueue = []\n self.greeting = None\n self.nextDeferred = defer.Deferred().addCallback(self._cb_greeting)\n self.nextDeferred.addErrback(self.fail)\n self.response = []\n self._failed = 0\n\n def fail(self, error):\n \"\"\"\n Give an error to any queued deferreds.\n \"\"\"\n self._fail(error)\n\n def _fail(self, error):\n \"\"\"\n Errback all queued deferreds.\n \"\"\"\n if self._failed:\n # We're recursing; bail out here for simplicity\n return error\n self._failed = 1\n if self.nextDeferred:\n try:\n self.nextDeferred.errback(failure.Failure(ConnectionLost('FTP connection lost', error)))\n except defer.AlreadyCalledError:\n pass\n for ftpCommand in self.actionQueue:\n ftpCommand.fail(failure.Failure(ConnectionLost('FTP connection lost', error)))\n return error\n\n def _cb_greeting(self, greeting):\n self.greeting = greeting\n\n\n def sendLine(self, line):\n \"\"\"\n Sends a line, unless line is None.\n\n @param line: Line to send\n @type line: L{bytes} or L{unicode}\n \"\"\"\n if line is None:\n return\n elif isinstance(line, unicode):\n line = line.encode(self._encoding)\n basic.LineReceiver.sendLine(self, line)\n\n\n def sendNextCommand(self):\n \"\"\"\n (Private) Processes the next command in the queue.\n \"\"\"\n ftpCommand = self.popCommandQueue()\n if ftpCommand is None:\n self.nextDeferred = None\n return\n if not ftpCommand.ready:\n self.actionQueue.insert(0, ftpCommand)\n reactor.callLater(1.0, self.sendNextCommand)\n self.nextDeferred = None\n return\n\n # FIXME: this if block doesn't belong in FTPClientBasic, it belongs in\n # FTPClient.\n if ftpCommand.text == 'PORT':\n self.generatePortCommand(ftpCommand)\n\n if self.debug:\n log.msg('<-- %s' % ftpCommand.text)\n self.nextDeferred = ftpCommand.deferred\n self.sendLine(ftpCommand.text)\n\n def queueCommand(self, ftpCommand):\n \"\"\"\n Add an FTPCommand object to the queue.\n\n If it's the only thing in the queue, and we are connected and we aren't\n waiting for a response of an earlier command, the command will be sent\n immediately.\n\n @param ftpCommand: an L{FTPCommand}\n \"\"\"\n self.actionQueue.append(ftpCommand)\n if (len(self.actionQueue) == 1 and self.transport is not None and\n self.nextDeferred is None):\n self.sendNextCommand()\n\n def queueStringCommand(self, command, public=1):\n \"\"\"\n Queues a string to be issued as an FTP command\n\n @param command: string of an FTP command to queue\n @param public: a flag intended for internal use by FTPClient. Don't\n change it unless you know what you're doing.\n\n @return: a L{Deferred} that will be called when the response to the\n command has been received.\n \"\"\"\n ftpCommand = FTPCommand(command, public)\n self.queueCommand(ftpCommand)\n return ftpCommand.deferred\n\n def popCommandQueue(self):\n \"\"\"\n Return the front element of the command queue, or None if empty.\n \"\"\"\n if self.actionQueue:\n return self.actionQueue.pop(0)\n else:\n return None\n\n def queueLogin(self, username, password):\n \"\"\"\n Login: send the username, send the password.\n\n If the password is L{None}, the PASS command won't be sent. Also, if\n the response to the USER command has a response code of 230 (User logged\n in), then PASS won't be sent either.\n \"\"\"\n # Prepare the USER command\n deferreds = []\n userDeferred = self.queueStringCommand('USER ' + username, public=0)\n deferreds.append(userDeferred)\n\n # Prepare the PASS command (if a password is given)\n if password is not None:\n passwordCmd = FTPCommand('PASS ' + password, public=0)\n self.queueCommand(passwordCmd)\n deferreds.append(passwordCmd.deferred)\n\n # Avoid sending PASS if the response to USER is 230.\n # (ref: http://cr.yp.to/ftp/user.html#user)\n def cancelPasswordIfNotNeeded(response):\n if response[0].startswith('230'):\n # No password needed!\n self.actionQueue.remove(passwordCmd)\n return response\n userDeferred.addCallback(cancelPasswordIfNotNeeded)\n\n # Error handling.\n for deferred in deferreds:\n # If something goes wrong, call fail\n deferred.addErrback(self.fail)\n # But also swallow the error, so we don't cause spurious errors\n deferred.addErrback(lambda x: None)\n\n def lineReceived(self, line):\n \"\"\"\n (Private) Parses the response messages from the FTP server.\n \"\"\"\n # Add this line to the current response\n if bytes != str:\n line = line.decode(self._encoding)\n\n if self.debug:\n log.msg('--> %s' % line)\n self.response.append(line)\n\n # Bail out if this isn't the last line of a response\n # The last line of response starts with 3 digits followed by a space\n codeIsValid = re.match(r'\\d{3} ', line)\n if not codeIsValid:\n return\n\n code = line[0:3]\n\n # Ignore marks\n if code[0] == '1':\n return\n\n # Check that we were expecting a response\n if self.nextDeferred is None:\n self.fail(UnexpectedResponse(self.response))\n return\n\n # Reset the response\n response = self.response\n self.response = []\n\n # Look for a success or error code, and call the appropriate callback\n if code[0] in ('2', '3'):\n # Success\n self.nextDeferred.callback(response)\n elif code[0] in ('4', '5'):\n # Failure\n self.nextDeferred.errback(failure.Failure(CommandFailed(response)))\n else:\n # This shouldn't happen unless something screwed up.\n log.msg('Server sent invalid response code %s' % (code,))\n self.nextDeferred.errback(failure.Failure(BadResponse(response)))\n\n # Run the next command\n self.sendNextCommand()\n\n def connectionLost(self, reason):\n self._fail(reason)\n\n\n\nclass _PassiveConnectionFactory(protocol.ClientFactory):\n noisy = False\n\n def __init__(self, protoInstance):\n self.protoInstance = protoInstance\n\n def buildProtocol(self, ignored):\n self.protoInstance.factory = self\n return self.protoInstance\n\n def clientConnectionFailed(self, connector, reason):\n e = FTPError('Connection Failed', reason)\n self.protoInstance.deferred.errback(e)\n\n\n\nclass FTPClient(FTPClientBasic):\n \"\"\"\n L{FTPClient} is a client implementation of the FTP protocol which\n exposes FTP commands as methods which return L{Deferred}s.\n\n Each command method returns a L{Deferred} which is called back when a\n successful response code (2xx or 3xx) is received from the server or\n which is error backed if an error response code (4xx or 5xx) is received\n from the server or if a protocol violation occurs. If an error response\n code is received, the L{Deferred} fires with a L{Failure} wrapping a\n L{CommandFailed} instance. The L{CommandFailed} instance is created\n with a list of the response lines received from the server.\n\n See U{RFC 959} for error code\n definitions.\n\n Both active and passive transfers are supported.\n\n @ivar passive: See description in __init__.\n \"\"\"\n connectFactory = reactor.connectTCP\n\n def __init__(self, username='anonymous',\n password='twisted@twistedmatrix.com',\n passive=1):\n \"\"\"\n Constructor.\n\n I will login as soon as I receive the welcome message from the server.\n\n @param username: FTP username\n @param password: FTP password\n @param passive: flag that controls if I use active or passive data\n connections. You can also change this after construction by\n assigning to C{self.passive}.\n \"\"\"\n FTPClientBasic.__init__(self)\n self.queueLogin(username, password)\n\n self.passive = passive\n\n def fail(self, error):\n \"\"\"\n Disconnect, and also give an error to any queued deferreds.\n \"\"\"\n self.transport.loseConnection()\n self._fail(error)\n\n def receiveFromConnection(self, commands, protocol):\n \"\"\"\n Retrieves a file or listing generated by the given command,\n feeding it to the given protocol.\n\n @param commands: list of strings of FTP commands to execute then receive\n the results of (e.g. C{LIST}, C{RETR})\n @param protocol: A L{Protocol} B{instance} e.g. an\n L{FTPFileListProtocol}, or something that can be adapted to one.\n Typically this will be an L{IConsumer} implementation.\n\n @return: L{Deferred}.\n \"\"\"\n protocol = interfaces.IProtocol(protocol)\n wrapper = ProtocolWrapper(protocol, defer.Deferred())\n return self._openDataConnection(commands, wrapper)\n\n def queueLogin(self, username, password):\n \"\"\"\n Login: send the username, send the password, and\n set retrieval mode to binary\n \"\"\"\n FTPClientBasic.queueLogin(self, username, password)\n d = self.queueStringCommand('TYPE I', public=0)\n # If something goes wrong, call fail\n d.addErrback(self.fail)\n # But also swallow the error, so we don't cause spurious errors\n d.addErrback(lambda x: None)\n\n def sendToConnection(self, commands):\n \"\"\"\n XXX\n\n @return: A tuple of two L{Deferred}s:\n - L{Deferred} L{IFinishableConsumer}. You must call\n the C{finish} method on the IFinishableConsumer when the file\n is completely transferred.\n - L{Deferred} list of control-connection responses.\n \"\"\"\n s = SenderProtocol()\n r = self._openDataConnection(commands, s)\n return (s.connectedDeferred, r)\n\n def _openDataConnection(self, commands, protocol):\n \"\"\"\n This method returns a DeferredList.\n \"\"\"\n cmds = [FTPCommand(command, public=1) for command in commands]\n cmdsDeferred = defer.DeferredList([cmd.deferred for cmd in cmds],\n fireOnOneErrback=True, consumeErrors=True)\n cmdsDeferred.addErrback(_unwrapFirstError)\n\n if self.passive:\n # Hack: use a mutable object to sneak a variable out of the\n # scope of doPassive\n _mutable = [None]\n def doPassive(response):\n \"\"\"Connect to the port specified in the response to PASV\"\"\"\n host, port = decodeHostPort(response[-1][4:])\n\n f = _PassiveConnectionFactory(protocol)\n _mutable[0] = self.connectFactory(host, port, f)\n\n pasvCmd = FTPCommand('PASV')\n self.queueCommand(pasvCmd)\n pasvCmd.deferred.addCallback(doPassive).addErrback(self.fail)\n\n results = [cmdsDeferred, pasvCmd.deferred, protocol.deferred]\n d = defer.DeferredList(results, fireOnOneErrback=True, consumeErrors=True)\n d.addErrback(_unwrapFirstError)\n\n # Ensure the connection is always closed\n def close(x, m=_mutable):\n m[0] and m[0].disconnect()\n return x\n d.addBoth(close)\n\n else:\n # We just place a marker command in the queue, and will fill in\n # the host and port numbers later (see generatePortCommand)\n portCmd = FTPCommand('PORT')\n\n # Ok, now we jump through a few hoops here.\n # This is the problem: a transfer is not to be trusted as complete\n # until we get both the \"226 Transfer complete\" message on the\n # control connection, and the data socket is closed. Thus, we use\n # a DeferredList to make sure we only fire the callback at the\n # right time.\n\n portCmd.transferDeferred = protocol.deferred\n portCmd.protocol = protocol\n portCmd.deferred.addErrback(portCmd.transferDeferred.errback)\n self.queueCommand(portCmd)\n\n # Create dummy functions for the next callback to call.\n # These will also be replaced with real functions in\n # generatePortCommand.\n portCmd.loseConnection = lambda result: result\n portCmd.fail = lambda error: error\n\n # Ensure that the connection always gets closed\n cmdsDeferred.addErrback(lambda e, pc=portCmd: pc.fail(e) or e)\n\n results = [cmdsDeferred, portCmd.deferred, portCmd.transferDeferred]\n d = defer.DeferredList(results, fireOnOneErrback=True, consumeErrors=True)\n d.addErrback(_unwrapFirstError)\n\n for cmd in cmds:\n self.queueCommand(cmd)\n return d\n\n def generatePortCommand(self, portCmd):\n \"\"\"\n (Private) Generates the text of a given PORT command.\n \"\"\"\n\n # The problem is that we don't create the listening port until we need\n # it for various reasons, and so we have to muck about to figure out\n # what interface and port it's listening on, and then finally we can\n # create the text of the PORT command to send to the FTP server.\n\n # FIXME: This method is far too ugly.\n\n # FIXME: The best solution is probably to only create the data port\n # once per FTPClient, and just recycle it for each new download.\n # This should be ok, because we don't pipeline commands.\n\n # Start listening on a port\n factory = FTPDataPortFactory()\n factory.protocol = portCmd.protocol\n listener = reactor.listenTCP(0, factory)\n factory.port = listener\n\n # Ensure we close the listening port if something goes wrong\n def listenerFail(error, listener=listener):\n if listener.connected:\n listener.loseConnection()\n return error\n portCmd.fail = listenerFail\n\n # Construct crufty FTP magic numbers that represent host & port\n host = self.transport.getHost().host\n port = listener.getHost().port\n portCmd.text = 'PORT ' + encodeHostPort(host, port)\n\n def escapePath(self, path):\n \"\"\"\n Returns a FTP escaped path (replace newlines with nulls).\n \"\"\"\n # Escape newline characters\n return path.replace('\\n', '\\0')\n\n def retrieveFile(self, path, protocol, offset=0):\n \"\"\"\n Retrieve a file from the given path\n\n This method issues the 'RETR' FTP command.\n\n The file is fed into the given Protocol instance. The data connection\n will be passive if self.passive is set.\n\n @param path: path to file that you wish to receive.\n @param protocol: a L{Protocol} instance.\n @param offset: offset to start downloading from\n\n @return: L{Deferred}\n \"\"\"\n cmds = ['RETR ' + self.escapePath(path)]\n if offset:\n cmds.insert(0, ('REST ' + str(offset)))\n return self.receiveFromConnection(cmds, protocol)\n\n retr = retrieveFile\n\n def storeFile(self, path, offset=0):\n \"\"\"\n Store a file at the given path.\n\n This method issues the 'STOR' FTP command.\n\n @return: A tuple of two L{Deferred}s:\n - L{Deferred} L{IFinishableConsumer}. You must call\n the C{finish} method on the IFinishableConsumer when the file\n is completely transferred.\n - L{Deferred} list of control-connection responses.\n \"\"\"\n cmds = ['STOR ' + self.escapePath(path)]\n if offset:\n cmds.insert(0, ('REST ' + str(offset)))\n return self.sendToConnection(cmds)\n\n stor = storeFile\n\n\n def rename(self, pathFrom, pathTo):\n \"\"\"\n Rename a file.\n\n This method issues the I{RNFR}/I{RNTO} command sequence to rename\n C{pathFrom} to C{pathTo}.\n\n @param: pathFrom: the absolute path to the file to be renamed\n @type pathFrom: C{str}\n\n @param: pathTo: the absolute path to rename the file to.\n @type pathTo: C{str}\n\n @return: A L{Deferred} which fires when the rename operation has\n succeeded or failed. If it succeeds, the L{Deferred} is called\n back with a two-tuple of lists. The first list contains the\n responses to the I{RNFR} command. The second list contains the\n responses to the I{RNTO} command. If either I{RNFR} or I{RNTO}\n fails, the L{Deferred} is errbacked with L{CommandFailed} or\n L{BadResponse}.\n @rtype: L{Deferred}\n\n @since: 8.2\n \"\"\"\n renameFrom = self.queueStringCommand('RNFR ' + self.escapePath(pathFrom))\n renameTo = self.queueStringCommand('RNTO ' + self.escapePath(pathTo))\n\n fromResponse = []\n\n # Use a separate Deferred for the ultimate result so that Deferred\n # chaining can't interfere with its result.\n result = defer.Deferred()\n # Bundle up all the responses\n result.addCallback(lambda toResponse: (fromResponse, toResponse))\n\n def ebFrom(failure):\n # Make sure the RNTO doesn't run if the RNFR failed.\n self.popCommandQueue()\n result.errback(failure)\n\n # Save the RNFR response to pass to the result Deferred later\n renameFrom.addCallbacks(fromResponse.extend, ebFrom)\n\n # Hook up the RNTO to the result Deferred as well\n renameTo.chainDeferred(result)\n\n return result\n\n\n def list(self, path, protocol):\n \"\"\"\n Retrieve a file listing into the given protocol instance.\n\n This method issues the 'LIST' FTP command.\n\n @param path: path to get a file listing for.\n @param protocol: a L{Protocol} instance, probably a\n L{FTPFileListProtocol} instance. It can cope with most common file\n listing formats.\n\n @return: L{Deferred}\n \"\"\"\n if path is None:\n path = ''\n return self.receiveFromConnection(['LIST ' + self.escapePath(path)], protocol)\n\n\n def nlst(self, path, protocol):\n \"\"\"\n Retrieve a short file listing into the given protocol instance.\n\n This method issues the 'NLST' FTP command.\n\n NLST (should) return a list of filenames, one per line.\n\n @param path: path to get short file listing for.\n @param protocol: a L{Protocol} instance.\n \"\"\"\n if path is None:\n path = ''\n return self.receiveFromConnection(['NLST ' + self.escapePath(path)], protocol)\n\n\n def cwd(self, path):\n \"\"\"\n Issues the CWD (Change Working Directory) command.\n\n @return: a L{Deferred} that will be called when done.\n \"\"\"\n return self.queueStringCommand('CWD ' + self.escapePath(path))\n\n\n def makeDirectory(self, path):\n \"\"\"\n Make a directory\n\n This method issues the MKD command.\n\n @param path: The path to the directory to create.\n @type path: C{str}\n\n @return: A L{Deferred} which fires when the server responds. If the\n directory is created, the L{Deferred} is called back with the\n server response. If the server response indicates the directory\n was not created, the L{Deferred} is errbacked with a L{Failure}\n wrapping L{CommandFailed} or L{BadResponse}.\n @rtype: L{Deferred}\n\n @since: 8.2\n \"\"\"\n return self.queueStringCommand('MKD ' + self.escapePath(path))\n\n\n def removeFile(self, path):\n \"\"\"\n Delete a file on the server.\n\n L{removeFile} issues a I{DELE} command to the server to remove the\n indicated file. Note that this command cannot remove a directory.\n\n @param path: The path to the file to delete. May be relative to the\n current dir.\n @type path: C{str}\n\n @return: A L{Deferred} which fires when the server responds. On error,\n it is errbacked with either L{CommandFailed} or L{BadResponse}. On\n success, it is called back with a list of response lines.\n @rtype: L{Deferred}\n\n @since: 8.2\n \"\"\"\n return self.queueStringCommand('DELE ' + self.escapePath(path))\n\n\n def removeDirectory(self, path):\n \"\"\"\n Delete a directory on the server.\n\n L{removeDirectory} issues a I{RMD} command to the server to remove the\n indicated directory. Described in RFC959.\n\n @param path: The path to the directory to delete. May be relative to\n the current working directory.\n @type path: C{str}\n\n @return: A L{Deferred} which fires when the server responds. On error,\n it is errbacked with either L{CommandFailed} or L{BadResponse}. On\n success, it is called back with a list of response lines.\n @rtype: L{Deferred}\n\n @since: 11.1\n \"\"\"\n return self.queueStringCommand('RMD ' + self.escapePath(path))\n\n\n def cdup(self):\n \"\"\"\n Issues the CDUP (Change Directory UP) command.\n\n @return: a L{Deferred} that will be called when done.\n \"\"\"\n return self.queueStringCommand('CDUP')\n\n\n def pwd(self):\n \"\"\"\n Issues the PWD (Print Working Directory) command.\n\n The L{getDirectory} does the same job but automatically parses the\n result.\n\n @return: a L{Deferred} that will be called when done. It is up to the\n caller to interpret the response, but the L{parsePWDResponse} method\n in this module should work.\n \"\"\"\n return self.queueStringCommand('PWD')\n\n\n def getDirectory(self):\n \"\"\"\n Returns the current remote directory.\n\n @return: a L{Deferred} that will be called back with a C{str} giving\n the remote directory or which will errback with L{CommandFailed}\n if an error response is returned.\n \"\"\"\n def cbParse(result):\n try:\n # The only valid code is 257\n if int(result[0].split(' ', 1)[0]) != 257:\n raise ValueError\n except (IndexError, ValueError):\n return failure.Failure(CommandFailed(result))\n path = parsePWDResponse(result[0])\n if path is None:\n return failure.Failure(CommandFailed(result))\n return path\n return self.pwd().addCallback(cbParse)\n\n\n def quit(self):\n \"\"\"\n Issues the I{QUIT} command.\n\n @return: A L{Deferred} that fires when the server acknowledges the\n I{QUIT} command. The transport should not be disconnected until\n this L{Deferred} fires.\n \"\"\"\n return self.queueStringCommand('QUIT')\n\n\n\nclass FTPFileListProtocol(basic.LineReceiver):\n \"\"\"\n Parser for standard FTP file listings\n\n This is the evil required to match::\n\n -rw-r--r-- 1 root other 531 Jan 29 03:26 README\n\n If you need different evil for a wacky FTP server, you can\n override either C{fileLinePattern} or C{parseDirectoryLine()}.\n\n It populates the instance attribute self.files, which is a list containing\n dicts with the following keys (examples from the above line):\n - filetype: e.g. 'd' for directories, or '-' for an ordinary file\n - perms: e.g. 'rw-r--r--'\n - nlinks: e.g. 1\n - owner: e.g. 'root'\n - group: e.g. 'other'\n - size: e.g. 531\n - date: e.g. 'Jan 29 03:26'\n - filename: e.g. 'README'\n - linktarget: e.g. 'some/file'\n\n Note that the 'date' value will be formatted differently depending on the\n date. Check U{http://cr.yp.to/ftp.html} if you really want to try to parse\n it.\n\n It also matches the following::\n -rw-r--r-- 1 root other 531 Jan 29 03:26 I HAVE\\ SPACE\n - filename: e.g. 'I HAVE SPACE'\n\n -rw-r--r-- 1 root other 531 Jan 29 03:26 LINK -> TARGET\n - filename: e.g. 'LINK'\n - linktarget: e.g. 'TARGET'\n\n -rw-r--r-- 1 root other 531 Jan 29 03:26 N S -> L S\n - filename: e.g. 'N S'\n - linktarget: e.g. 'L S'\n\n @ivar files: list of dicts describing the files in this listing\n \"\"\"\n fileLinePattern = re.compile(\n r'^(?P.)(?P.{9})\\s+(?P\\d*)\\s*'\n r'(?P\\S+)\\s+(?P\\S+)\\s+(?P\\d+)\\s+'\n r'(?P...\\s+\\d+\\s+[\\d:]+)\\s+(?P.{1,}?)'\n r'( -> (?P[^\\r]*))?\\r?$'\n )\n delimiter = b'\\n'\n _encoding = 'latin-1'\n\n def __init__(self):\n self.files = []\n\n def lineReceived(self, line):\n if bytes != str:\n line = line.decode(self._encoding)\n d = self.parseDirectoryLine(line)\n if d is None:\n self.unknownLine(line)\n else:\n self.addFile(d)\n\n def parseDirectoryLine(self, line):\n \"\"\"\n Return a dictionary of fields, or None if line cannot be parsed.\n\n @param line: line of text expected to contain a directory entry\n @type line: str\n\n @return: dict\n \"\"\"\n match = self.fileLinePattern.match(line)\n if match is None:\n return None\n else:\n d = match.groupdict()\n d['filename'] = d['filename'].replace(r'\\ ', ' ')\n d['nlinks'] = int(d['nlinks'])\n d['size'] = int(d['size'])\n if d['linktarget']:\n d['linktarget'] = d['linktarget'].replace(r'\\ ', ' ')\n return d\n\n def addFile(self, info):\n \"\"\"\n Append file information dictionary to the list of known files.\n\n Subclasses can override or extend this method to handle file\n information differently without affecting the parsing of data\n from the server.\n\n @param info: dictionary containing the parsed representation\n of the file information\n @type info: dict\n \"\"\"\n self.files.append(info)\n\n def unknownLine(self, line):\n \"\"\"\n Deal with received lines which could not be parsed as file\n information.\n\n Subclasses can override this to perform any special processing\n needed.\n\n @param line: unparsable line as received\n @type line: str\n \"\"\"\n pass\n\ndef parsePWDResponse(response):\n \"\"\"\n Returns the path from a response to a PWD command.\n\n Responses typically look like::\n\n 257 \"/home/andrew\" is current directory.\n\n For this example, I will return C{'/home/andrew'}.\n\n If I can't find the path, I return L{None}.\n \"\"\"\n match = re.search('\"(.*)\"', response)\n if match:\n return match.groups()[0]\n else:\n return None\n","repo_name":"wistbean/learn_python3_spider","sub_path":"stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py","file_name":"ftp.py","file_ext":"py","file_size_in_byte":105954,"program_lang":"python","lang":"en","doc_type":"code","stars":14022,"dataset":"github-code","pt":"3"}
+{"seq_id":"12828285247","text":"import os, sys, praw, json, datetime\nimport pprint as p\n\n\nbanned_subs = (\n\t\"SuicideWatch\",\n\t\"depression\",\n\t\"test\", # would comment without being asked to because it replies to u/MarkdownShadowBot\n\t\"discordapp\", # those fuckers banned me so no need to waste cpu time here\n)\n\nif not os.path.isfile(\"checked_comments.json\"):\n\tchecked_comments = []\nelse:\n\twith open(\"checked_comments.json\", \"r\") as f:\n\t\tchecked_comments = json.loads(f.read())\n\nwith open(\"image_list.json\", \"r\") as f:\n\tblackholed_urls = json.loads(f.read())\n\n# allow client secret and password to be set manually or by environment for automating\ntry:\n\tsecret = os.environ[\"CLIENT_SECRET\"]\nexcept KeyError:\n\tsecret = input(\"secret: \")\n\ntry:\n\tpw = os.environ[\"REDDIT_PASSWORD\"]\nexcept KeyError:\n\tpw = input(\"password: \")\n\nreddit = praw.Reddit(\n\tclient_id=\"0V1g_2X1ayVenw\",\n\tclient_secret=secret,\n\tuser_agent=\"unix:4x_jpeg_bot:alpha (by /u/4x_jpeg)\",\n\tusername=\"4x_jpeg\",\n\tpassword=pw\n)\n\nmorejpeg_auto = reddit.redditor(\"morejpeg_auto\")\n\ntry:\n\ti = 0\n\tfor comment in morejpeg_auto.comments.new(limit=10):\n\t\ti += 1\n\t\tsys.stdout.write(\"\\rChecking: #%d (%s)\" % (i, comment.permalink))\n\t\tsys.stdout.flush()\n\n\t\t# no need to check already checked comments\n\t\tskip = False\n\t\tfor checked_comment in checked_comments:\n\t\t\tif checked_comment[\"id\"] == comment.id:\n\t\t\t\tskip = True\n\t\t\t\tbreak\n\t\tif skip:\n\t\t\tcontinue\n\n\t\tfor sub in banned_subs:\n\t\t\tif comment.subreddit.display_name == sub:\n\t\t\t\tskip = True\n\t\t\t\tbreak\n\t\tif skip:\n\t\t\tcontinue\n\n\t\t# if this comment is new and stuff might change, we need a way to tell \n\t\t# later parts of the code to not record this\n\t\ttoo_early_to_skip = False\n\n\t\t# don't skip next run if u/morejpeg_auto's comment is less than 10h old\n\t\tif int(datetime.datetime.utcnow().timestamp()) < comment.created_utc + 36000:\n\t\t\ttoo_early_to_skip = True\n\n\n\t\t# for the record, out of curiosity (lul)\n\t\tanswered_by_us = False\n\n\t\t# something is broken with comment.replies if we don't do .refresh()\n\t\t# also .refresh() throws if the comment was deleted, so well need to catch that\n\t\ttry:\n\t\t\tcomment.refresh()\n\n\t\t\tfor reply in comment.replies:\n\t\t\t\t# don't answer if the comment is pretty new, we want to\n\t\t\t\t# give u/morejpeg some time (at least 10min)\n\t\t\t\tif int(datetime.datetime.utcnow().timestamp()) < reply.created_utc + 600:\n\t\t\t\t\ttoo_early_to_skip = True\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\tfor line in iter(reply.body.splitlines()):\n\t\t\t\t\t# if someone writes \"morejpeg\" they probably are just talking about\n\t\t\t\t\t# the bot and not actually requesting more jpeg\n\t\t\t\t\tif ((\"more\" in line.lower() and \"jpeg\" in line.lower())\n\t\t\t\t\t\tor (\"needs\" in line.lower() and \"jpeg\" in line.lower())\n\t\t\t\t\t\t) and not \"morejpeg\" in line.lower():\n\n\t\t\t\t\t\t# check if it was answered by u/morejpeg_auto\n\t\t\t\t\t\twas_answered = False\n\t\t\t\t\t\tfor replyreply in reply.replies:\n\t\t\t\t\t\t\tif (replyreply.author.name == \"morejpeg_auto\" or\n\t\t\t\t\t\t\t\treplyreply.author.name == \"4x_jpeg\"):\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\twas_answered = True\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\n\t\t\t\t\t\tif not was_answered:\n\t\t\t\t\t\t\treply.reply(\n\t\t\t\t\t\t\t\t\">%s\\n\"\n\t\t\t\t\t\t\t\t\"\\n\"\n\t\t\t\t\t\t\t\t\"u/morejpeg_auto doesn't seem to answer you,\"\n\t\t\t\t\t\t\t\t\" so I'll help out:\\n\"\n\t\t\t\t\t\t\t\t\"[Here you go!](%s)\\n\"\n\t\t\t\t\t\t\t\t\"\\n\"\n\t\t\t\t\t\t\t\t\"\\n\"\n\t\t\t\t\t\t\t\t\"^(I am a bot and I don't answer to replies, though my master might.)\\n\"\n\t\t\t\t\t\t\t\t\"[GitHub]\"\n\t\t\t\t\t\t\t\t\"(https://github.com/Nunu-Willump/4x_jpeg_bot.git)\\n\"\n\t\t\t\t\t\t\t\t\"\"\n\t\t\t\t\t\t\t\t% (\n\t\t\t\t\t\t\t\t\tline,\n\n\t\t\t\t\t\t\t\t\t# add number of checked comments to index\n\t\t\t\t\t\t\t\t\t# to have it not repeat after each run\n\t\t\t\t\t\t\t\t\tblackholed_urls[(i + len(checked_comments))\n\t\t\t\t\t\t\t\t\t\t% len(blackholed_urls)]\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tanswered_by_us = True\n\t\t\t\t\t\t\ttoo_early_to_skip = False\n\n\t\t\t\t\t\t# dont continue with this reply if the last line triggered the if\n\t\t\t\t\t\tcontinue\n\n\t\t# something is wrong with the comment, and that won't change as we already called\n\t\t# comment.refresh()\n\t\texcept AttributeError:\n\t\t\tpass\n\t\t# this happens at comment.refresh() if the comment was deleted\n\t\texcept praw.exceptions.ClientException:\n\t\t\tpass\n\n\t\tif not too_early_to_skip:\n\t\t\tchecked_comments.append({\"id\": comment.id,\n\t\t\t\t\"body\": comment.body, \"link\": \"https://reddit.com\" + comment.permalink,\n\t\t\t\t\"Answered\": answered_by_us})\n\nexcept Exception as e:\n\tsys.stdout.write(\"\\n\\nCaught %s.\" % repr(e))\n# also catch keyboard interrups and other shit so the json file always gets updated\nexcept:\n\tsys.stdout.write(\"\\n\\nCaught something. Idk though.\")\n\nprint(\"\\n\\nGimme a sec to update the json file...\")\nf = open(\"checked_comments.json\", \"w\")\nf.write(json.dumps(checked_comments, indent=4))\nf.close()\nexit(0)\n","repo_name":"llenck/4x_jpeg_bot","sub_path":"commenter.py","file_name":"commenter.py","file_ext":"py","file_size_in_byte":4542,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"7658062116","text":"\"\"\" Question 76:\nPlease write a program to output a random number, which is divisible by 5 and 7,\nbetween 0 and 10 inclusive using random module and list comprehension.\n\n\nHints:\nUse random.choice() to a random element from a list.\n\"\"\"\nimport random\n\nnum = None\nwhile True:\n num = random.randrange(0, 11)\n if num % 5 == 0 and num % 7 == 0:\n break\nprint(num)\n","repo_name":"neequole/my-python-programming-exercises","sub_path":"unsorted_solutions/question76.py","file_name":"question76.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30709565196","text":"class ApplicationState:\n instance = None\n\n def __init__(self):\n self.is_logged_in = False\n\n @staticmethod\n def get_app_state():\n if not ApplicationState.instance:\n ApplicationState.instance = ApplicationState()\n return ApplicationState.instance\n\n\nappstate1 = ApplicationState().get_app_state()\nprint(appstate1.is_logged_in)\nappstate1.is_logged_in = True\n\nprint(appstate1.is_logged_in)\nappstate2 = ApplicationState().get_app_state()\nprint(appstate2.is_logged_in)\n\nprint(appstate2 == appstate1)\n\n\n\n","repo_name":"pradeep-automation/Python-Practice","sub_path":"DesignPatterns/Singleton.py","file_name":"Singleton.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14386674872","text":"\"\"\"ProyectoCoder URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom AppCoder.views import *\nfrom AppCoder import views\nfrom django.contrib.auth.views import LogoutView\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', inicio),\n path('movies/', views.Movies),\n path('add_form/', views.add_form, name='add_form'),\n path('favorite/', views.Movies),\n path('fav_form/', views.fav_form, name='fav_form'),\n path('reviews/', views.Reviews),\n path('review_form/', views.review_form, name='review_form'),\n path('find_movie/', views.find_movie, name='find_movie'),\n path('resultados/',views.Resultados,name='resultados'),\n path('busqueda/',views.Busqueda),\n path('login/',views.login_request),\n path('register/',views.register),\n path('register/',views.register, name=\"register\"),\n path('logout/',LogoutView.as_view(template_name='logout.html'), name=\"logout\"),\n]\n","repo_name":"belchus/pythoncopy","sub_path":"ProyectoCoder/ProyectoCoder/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19667828136","text":"# time: O(nlogk)\n# just same logic as k closest points to x\nimport math\nimport heapq\nclass Solution:\n def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n heap= []\n for i in range(len(points)):\n dist= math.sqrt((points[i][0]**2)+(points[i][1]**2))\n heapq.heappush(heap,(-1*dist,points[i]))\n if len(heap)>k:\n heapq.heappop(heap)\n ans= []\n for i in range(len(heap)):\n ans.append(heap[i][1])\n return ans\n\n# better way of writing above code\nimport math\nimport heapq\nclass Solution:\n def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n heap= []\n for x,y in points:\n dist= sqrt(x**2 + y**2)\n heapq.heappush(heap,(-1*dist,x,y))\n if len(heap)>k:\n heapq.heappop(heap)\n return [(x,y) for (dist,x,y) in heap]\n\n\n# try later by quicksort method \n# https://leetcode.com/problems/k-closest-points-to-origin/discuss/219442/Python-with-quicksort-algorithm\n","repo_name":"Ravi-0412/DSA-Program-And-Notes","sub_path":"Heap/973_K_Closest_Point.py","file_name":"973_K_Closest_Point.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"3"}
+{"seq_id":"41470859169","text":"class Solution:\n def restoreIpAddresses(self, s: str) -> List[str]:\n N = len(s)\n ans =[]\n def recurse(index, left, current):\n if left < 0:\n return\n \n if index == N:\n if left == 0:\n ans.append(\".\".join(current))\n return\n \n if s[index] == \"0\":\n current.append(\"0\")\n recurse(index + 1, left -1,current)\n current.pop()\n return\n for i in range(3):\n if index + i < N and 0 <= int(s[index:index + i + 1]) <= 255:\n current.append(s[index:index +i + 1])\n recurse(index + i + 1, left-1, current)\n current.pop()\n \n recurse(0, 4, [])\n return ans","repo_name":"Imsachin010/Leetcode-problems","sub_path":"restoring Ip address/93.py","file_name":"93.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"69900292562","text":"from pprint import pprint\nfrom collections import deque\n\nprint('===== day 23 =====')\n\ndef to_cups(i: str):\n\treturn [int(x) for x in i]\n\ndef step(cups):\n\tcurrent = cups[0]\n\tpicked_up = cups[1:4]\n\tdel cups[0:4]\n\tcups.append(current)\n\tdest = find_dest(current - 1, cups)\n\ti = cups.index(dest)\n\tnext = cups[0:i+1] + picked_up + cups[i+1:]\n\treturn next\n\nMAX = 9\ndef find_dest(n, ns):\n\t#assert ns != []\n\t# assert len([x for x in ns if x > 9 or x < 1]) == 0\n\tn = wrap(n)\n\twhile n not in ns:\n\t\tn = wrap(n - 1)\n\treturn n\n\ndef wrap(n):\n\tif n < 1:\n\t\tn = MAX\n\treturn n\n\ndef run(cups, steps):\n\t#seen = dict()\n\tfor i in range(steps):\n\t\tif (i % 1000) == 0:\n\t\t\tprint(i)\n\t\t#h = str(cups)\n\t\t#seen[h] = i\n\t\t\n\t\tcups = step(cups)\n\t\t\n\t\tif False:\n\t\t\th = str(cups)\n\t\t\tif h in seen:\n\t\t\t\tprev = seen[h]\n\t\t\t\tprint('repeat! previously saw on step', prev, 'and seen again on step', i, ', delta', i - prev)\n\t\t\tseen[h] = i\n\treturn cups\n\ndef solution(cups):\n\ti = cups.index(1)\n\tresult = cups[i+1:] + cups[0:i]\n\treturn ''.join((str(x) for x in result))\n\nexample = to_cups(\"389125467\")\nreal_input = to_cups(\"716892543\")\n\np1_answer = solution(run(real_input, 100))\nprint('part 1 answer:', p1_answer)\nassert p1_answer == '49725386'\n\nONE_MIL = 1_000_000\nMAX = ONE_MIL\n\ndef grow_input(cups):\n\tc = max(cups)\n\tprint(c)\n\trest = list(range(c + 1, ONE_MIL + 1))\n\tresult = cups + rest\n\tassert max(result) == 1_000_000, 'max was %s' % max(result)\n\tassert len(result) == 1_000_000, 'len was %s - cups len %s - rest len %d' % (len(result), len(cups), len(rest))\n\treturn result\n\ndef solution2(cups):\n\ti = cups.index(1)\n\ta = cups[(i + 1) % len(cups)]\n\tb = cups[(i + 2) % len(cups)]\n\tresult = a*b\n\tprint('a', a, '- b', b, ' - part 2 solution', result)\n\treturn result\n\nexample = to_cups(\"389125467\")\nreal_input = to_cups(\"716892543\")\ne2 = grow_input(example)\na2 = grow_input(real_input)\n\nten_mil = 10_000_000\n\ndef p2(cups):\n\tprint('solving part 2')\n\tafter = run(cups, ten_mil)\n\tresult = solution2(after)\n\tprint('done')\n\treturn result\n\nexpected = 149245887792\nassert p2(e2) == expected\n\np2(a2)\n","repo_name":"jeremy-w/adventofcode-2020","sub_path":"src/day23.py","file_name":"day23.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"19275545273","text":"\"\"\"\n# O(n) time and space complexity solution\nclass Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n def get_text(text: str) -> str:\n cursor = 0\n text = list(text)\n for i in range(len(text)):\n if text[i] != '#':\n text[cursor] = text[i]\n cursor += 1\n else:\n cursor = max(0, cursor-1)\n return \"\".join(text[:cursor])\n\n s = get_text(s)\n t = get_text(t)\n\n return (s==t)\n\n\"\"\"\n\n# O(n) time complexity and O(1) space complexity\n\nclass Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n def get_next_index(string, index):\n count = 0\n while (index > -1):\n if string[index] != '#':\n if (count > 0):\n index -= 1\n count -= 1\n else:\n break\n else:\n count += 1\n index -= 1\n\n return index\n \n i, j = len(s)-1, len(t)-1\n while True:\n i = get_next_index(s, i)\n j = get_next_index(t, j)\n if ((i > -1) and (j >= -1)) and (s[i] == t[j]):\n i -= 1\n j -= 1\n else:\n break\n return ((i == -1) and (j == -1))\n\n","repo_name":"connectwithprakash/Leet-Code","sub_path":"problems/844_backspace_string_compare.py","file_name":"844_backspace_string_compare.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15441512640","text":"numbers_example = 1+1 #оператор с числом\nstring_example = \"a\" * 4 #оператор с строкой\n\nlist_example = list()\nlist_example.append(1) #метод листа\n\narray1 = [1,2,4]\narray2 = [2,3,5]\nresult_array = array2 + array1 #оператор и массивами\n\ntuple1 = (1,2)\ntuple2 = (2,3) \nresult_tuple = tuple1+ tuple2 #оператор и кортежи\n\nprint(numbers_example, string_example, list_example, result_array, result_tuple)","repo_name":"Clankyyy/Lab-1","sub_path":"Zadanie1.py","file_name":"Zadanie1.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"73215783761","text":"import random\n\ndef rolld100():\n \n result = 0\n bonusDice = 0\n penaltyDice = 0\n tens_die_rolls = []\n\n bonusDice = int(input('Any bonus dice?[0]') or \"0\")\n penaltyDice = int(input('Any penalty dice?[0]') or \"0\")\n resultDice = abs(bonusDice - penaltyDice) + 1\n\n # Roll the ones die\n d2 = random.randint(0,9)\n \n # Determine if bonus or penalty dice are to be rolled and roll the appropriate number of dice\n \n if bonusDice > penaltyDice:\n # Determine and print the number of Bonus dice to roll\n print('Rolling d100 with ' + str(resultDice -1) + ' bonus dice.\\n')\n\n for i in range(resultDice):\n tens_die_roll = random.randint(0,9)\n if d2 == 0 and tens_die_roll == 0:\n tens_die_roll =100 \n print('Tens die ' + str(i+1) + ': ' + str(tens_die_roll))\n tens_die_rolls.append(tens_die_roll)\n d1 = max(tens_die_rolls)\n\n elif penaltyDice > bonusDice:\n # Determine and print the number of Penalty dice to roll\n print('Rolling d100 with ' + str(resultDice -1) + ' penalty dice.\\n')\n \n for i in range(resultDice):\n tens_die_roll = random.randint(0,9)\n if d2 == 0 and tens_die_roll == 0:\n tens_die_roll =100 \n print('Tens die ' + str(i+1) + ': ' + str(tens_die_roll))\n tens_die_rolls.append(tens_die_roll)\n d1 = min(tens_die_rolls)\n\n else:\n # Determine and print the number of dice to roll\n print('Rolling d100 with no bonus or penalty dice.\\n')\n d1 = random.randint(0,9)\n print('Tens die: ' + str(d1))\n\n print (\"Ones die: \" + str(d2))\n\n if d1 == 100 and d2 == 0:\n result = 100\n else:\n result = d1 * 10 + d2\n return result\n\nprint(\"Final roll: \" + str(rolld100()))","repo_name":"dannable/DicePercent","sub_path":"dicepercent.py","file_name":"dicepercent.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33550743283","text":"from models.gert_noeqv import make_model\nfrom models.heads import PPIFeedForward\nfrom sklearn.metrics import roc_auc_score, average_precision_score\nfrom utils import get_mask\nimport data.ppi.ppi_dataloader as dl\nimport data.ppi.noneqv_db5_dataloader as test_dl\nimport os\nimport time\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nPROT_ATOMS = ('C', 'O', 'N', 'S', 'P')\nRES_LABEL = ('LEU', 'ILE', 'VAL', 'TYR', 'ARG', 'GLU', 'PHE', 'ASP', 'THR', 'LYS', \n 'ALA', 'GLY', 'TRP', 'SER', 'PRO', 'ASN', 'GLN', 'HIS', 'MET', 'CYS')\n\n\ndef train(epoch, transformer_model, ff_model, loader, criterion, optimizer, device, max_train_iter, print_frequency):\n transformer_model.train()\n ff_model.train()\n\n start = time.time()\n\n losses = [] \n total = 0\n for it, (subunit1, subunit2) in enumerate(loader):\n tick = time.time()\n subunit1.label, subunit2.label = subunit1.label.to(device), subunit2.label.to(device)\n subunit1.pos, subunit2.pos = subunit1.pos.to(device), subunit2.pos.to(device)\n optimizer.zero_grad()\n\n mask1 = get_mask(subunit1.pos)\n out1 = transformer_model(subunit1.pos, mask1)\n mask2 = get_mask(subunit2.pos)\n out2 = transformer_model(subunit2.pos, mask2)\n output = ff_model(out1, out2)\n loss = criterion(output, subunit1.label.float())\n loss.backward()\n losses.append(loss.item())\n optimizer.step()\n\n if it % print_frequency == 0:\n elapsed = time.time() - start\n print(f'Epoch {epoch}, iter {it}, train loss {np.mean(losses)}, avg it/sec {print_frequency / elapsed}')\n start = time.time()\n if it == max_train_iter:\n return np.mean(losses)\n\n return np.mean(losses)\n\n\n@torch.no_grad()\ndef test(transformer_model, ff_model, loader, criterion, device, max_test_iter, print_frequency):\n transformer_model.eval()\n ff_model.eval()\n\n losses = []\n total = 0\n\n y_true = []\n y_pred = []\n for it, (subunit1, subunit2) in enumerate(loader):\n if subunit1.pos.shape[1] == 1:\n continue\n subunit1.label, subunit2.label = subunit1.label.to(device), subunit2.label.to(device)\n subunit1.pos, subunit2.pos = subunit1.pos.to(device), subunit2.pos.to(device)\n mask1 = get_mask(subunit1.pos)\n out1 = transformer_model(subunit1.pos, mask1)\n mask2 = get_mask(subunit2.pos)\n out2 = transformer_model(subunit2.pos, mask2)\n output = ff_model(out1, out2)\n loss = criterion(output, subunit1.label.float())\n losses.append(loss.item())\n y_true.extend(subunit1.label.tolist())\n y_pred.extend(output.tolist())\n if it % print_frequency == 0:\n print(f'iter {it}, loss {np.mean(losses)}')\n if it == max_test_iter:\n break\n\n y_true = np.array(y_true)\n y_pred = np.array(y_pred)\n auroc = roc_auc_score(y_true, y_pred)\n auprc = average_precision_score(y_true, y_pred)\n\n return np.mean(losses), auroc, auprc\n\n\ndef train_noneqv_ppi(ex, use_attention, data_dir, device, log_dir, checkpoint, num_epochs, batch_size,\n hidden_dim, learning_rate, workers, betas, eps, d_ff, d_atom,\n eta, max_radius, num_atoms, num_heads, max_train_iter, max_test_iter,\n print_frequency, test_mode=False):\n train_set = dl.PPI_Dataset(os.path.join(data_dir, 'pairs_pruned_train@1000'), max_radius=max_radius)\n train_loader = dl.DataLoader(train_set, batch_size=batch_size, num_workers=workers)\n val_set = dl.PPI_Dataset(os.path.join(data_dir, 'pairs_pruned_val@1000'), max_radius=max_radius)\n val_loader = dl.DataLoader(val_set, batch_size=batch_size, num_workers=workers)\n \n transformer_model = make_model(\n num_heads=num_heads, \n d_model=hidden_dim, \n d_ff=d_ff, \n d_atom=d_atom,\n eta=eta, \n Rc=max_radius, \n num_atoms=num_atoms, \n N=2,\n num_dense=2,\n use_attention=use_attention).to(device)\n ff_model = PPIFeedForward(hidden_dim).to(device)\n\n model_parameters = filter(lambda p: p.requires_grad, transformer_model.parameters())\n num_parameters = sum([np.prod(p.size()) for p in model_parameters])\n print('Number of trainable parameters:', num_parameters)\n \n best_val_loss = 999\n \n params = [x for x in transformer_model.parameters()] + [x for x in ff_model.parameters()]\n\n criterion = nn.BCELoss().to(device)\n optimizer = torch.optim.Adam(params, lr=learning_rate, betas=betas, eps=eps)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min',\n factor=0.7, patience=2,\n min_lr=1e-6)\n\n if checkpoint:\n cpt = torch.load(checkpoint, map_location=device)\n transformer_model.load_state_dict(cpt['transformer_state_dict'])\n ff_model.load_state_dict(cpt['ff_state_dict'])\n optimizer.load_state_dict(cpt['optimizer_state_dict'])\n print('Loaded model from checkpoint')\n\n print(f'Training for {num_epochs} epochs')\n print('---------------------------------')\n for epoch in range(1, num_epochs+1):\n start = time.time()\n train_loss = train(\n epoch, \n transformer_model, \n ff_model, \n train_loader, \n criterion, \n optimizer,\n device,\n max_train_iter, \n print_frequency)\n ex.log_scalar('Train Loss', train_loss)\n print('Validating...')\n val_loss, auroc, auprc = test(\n transformer_model, \n ff_model, \n val_loader, \n criterion,\n device,\n max_test_iter,\n print_frequency)\n scheduler.step(val_loss)\n if val_loss < best_val_loss:\n torch.save({\n 'epoch': epoch,\n 'transformer_state_dict': transformer_model.state_dict(),\n 'ff_state_dict': ff_model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': train_loss,\n }, os.path.join(log_dir, f'best_weights.pt'))\n best_val_loss = val_loss\n elapsed = (time.time() - start)\n ex.log_scalar('Validation Loss', val_loss)\n ex.log_scalar('Validation AUROC', auroc)\n ex.log_scalar('Validation AUPRC', auprc)\n print('Epoch: {:03d}, Time: {:.3f} s'.format(epoch, elapsed))\n print(f'\\tTrain loss {train_loss}, Val loss {val_loss}, Val AUROC {auroc}, Val AUPRC {auprc}')\n\n\n if test_mode:\n print(\"Testing on DIPS...\")\n test_set = dl.PPI_Dataset(os.path.join(data_dir, 'pairs_pruned_test@1000'), max_radius=max_radius)\n test_loader = dl.DataLoader(test_set, batch_size=batch_size, num_workers=workers)\n cpt = torch.load(os.path.join(log_dir, f'best_weights.pt'))\n transformer_model.load_state_dict(cpt['transformer_state_dict'])\n ff_model.load_state_dict(cpt['ff_state_dict'])\n test_loss, auroc, auprc = test(\n transformer_model, \n ff_model, \n test_loader, \n criterion,\n device,\n max_test_iter,\n print_frequency)\n ex.log_scalar('Test Loss', test_loss)\n ex.log_scalar('Test AUROC', auroc)\n ex.log_scalar('Test AUPRC', auprc)\n print(f'\\tTest loss {test_loss}, Test AUROC {auroc}, Test AUPRC {auprc}')\n\n print(\"Testing on DB5...\")\n db5_dir = '/oak/stanford/groups/rondror/projects/atom3d/protein_protein_interfaces/DB5/'\n test_set = test_dl.PPI_Dataset(os.path.join(db5_dir, 'pairs@10'), max_radius=max_radius)\n test_loader = test_dl.DataLoader(test_set, batch_size=batch_size, num_workers=workers)\n cpt = torch.load(os.path.join(log_dir, f'best_weights.pt'))\n transformer_model.load_state_dict(cpt['transformer_state_dict'])\n ff_model.load_state_dict(cpt['ff_state_dict'])\n test_loss, auroc, auprc = test(\n transformer_model, \n ff_model, \n test_loader, \n criterion,\n device,\n max_test_iter,\n print_frequency)\n ex.log_scalar('Test Loss', test_loss)\n ex.log_scalar('Test AUROC', auroc)\n ex.log_scalar('Test AUPRC', auprc)\n print(f'\\tTest loss {test_loss}, Test AUROC {auroc}, Test AUPRC {auprc}')\n return test_loss, auroc, auprc\n else:\n return best_val_loss","repo_name":"drorlab/gert","sub_path":"src/atom3d_combined/tasks/ppi/train_ppi.py","file_name":"train_ppi.py","file_ext":"py","file_size_in_byte":8540,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"}
+{"seq_id":"1418071801","text":"import gradio as gr\ndict = {\n \"ko2en\" : {\n \"사과\" : \"apple\",\n \"사자\" : \"tiger\",\n \"사랑\" : \"love\"\n },\n \"en2ko\" : {\n \"apple\" : \"사과\",\n \"tiger\" : \"사자\",\n \"love\" : \"사랑\"\n }\n}\ndef trans(type, word):\n return dict[type][word]\nwith gr.Blocks() as app:\n result = gr.Textbox(label='결과')\n type = gr.Radio(label='종류', choices=['ko2en', 'en2ko'])\n word = gr.Textbox(label='단어', placeholder=\"한국어\")\n btn = gr.Button(value='실행')\n btn.click(\n fn = trans,\n inputs = [type, word],\n outputs = result\n )\napp.launch(debug=True, share=True)\n#public URL로 접근하면 전세계 어디서나 내 컴퓨터에 접속 가능\n#그러나! 72시간 후에 접속 안됨. 내 컴퓨터를 끄면 접속 안됨\n","repo_name":"gavy1004/AIHubWeb","sub_path":"gradioApp/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26961765735","text":"\"\"\"\n26. Remove Duplicates from Sorted Array\n\nGiven a sorted array, remove the duplicates in place such that each element appear only once and return the new length.\n\nDo not allocate extra space for another array, you must do this in place with constant memory.\n\nFor example,\nGiven input array nums = [1,1,2],\n\nYour function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.\n\nHide Company Tags Microsoft Bloomberg Facebook\nShow Tags\nShow Similar Problems.\n\n\"\"\"\n\nclass Solution(object):\n def removeDuplicates(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n\n Own Solution: two pointer, first pointer will point to current location where value should be replaced, second pointer moves forward to find next non repetitive num\n \"\"\"\n if len(nums) < 2:\n return len(nums)\n\n start, end, current = 1, 1, nums[0]\n while end < len(nums):\n if nums[end] != current:\n current = nums[start] = nums[end]\n start += 1\n end += 1\n\n return start","repo_name":"tejamupparaju/LeetCode_Python","sub_path":"leet_code26.py","file_name":"leet_code26.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9535499194","text":"import inspect\nimport collections\nimport ipywidgets as ipyw\nfrom collections.abc import Sequence\nfrom collections import OrderedDict\nfrom operator import attrgetter\nfrom functools import wraps\n\nMISSING = set()\ntry:\n import dataclasses\n MISSING.add(dataclasses.MISSING)\nexcept ImportError:\n pass\n\ntry:\n import attr\n MISSING.add(attr.NOTHING)\nexcept ImportError:\n pass\n\nWIDGET_MAP = {\n int: (ipyw.IntSlider, 'value'),\n float: (ipyw.FloatSlider, 'value'),\n str: (ipyw.Text, 'value'),\n bool: (ipyw.Checkbox, 'value'),\n list: (ipyw.Dropdown, 'options'),\n tuple: (ipyw.Dropdown, 'options'),\n set: (ipyw.Dropdown, 'options')\n}\n\nATTRS_FIELDS = '__attrs_attrs__'\nDATACLASS_FIELDS = '__dataclass_fields__'\n\nWIDGET = '__widget__'\n\nATTRS_FIELDS = '__attrs_attrs__'\nDATACLASS_FIELDS = '__dataclass_fields__'\n\nWIDGET = '__widget__'\n\ndef _fields(instance):\n \"\"\"Generator that will yield\n attribute name, attribute field, attribute type\n\n Arguments:\n field_list {[type]} -- [description]\n\n Keyword Arguments:\n types {[type]} -- [description] (default: {None})\n \"\"\"\n fields = getattr(instance, ATTRS_FIELDS, None)\n if fields is None:\n fields = getattr(instance, DATACLASS_FIELDS, None)\n if fields is None:\n raise TypeError\n return dataclasses.fields(instance)\n else:\n try:\n return attr.fields(instance)\n except TypeError:\n return attr.fields(instance.__class__)\n raise TypeError(\"Not an instance of dataclass or attrs\")\n\ndef _observe_handlers(instance):\n \"\"\"Return a map of attributes and handlers\n\n Arguments:\n instance {[type]} -- [description]\n \"\"\"\n handlers = collections.defaultdict(list)\n for name, obj in inspect.getmembers(instance):\n if name.startswith('__') and name.endswith('__'):\n # skip magic methods\n continue\n\n if inspect.isfunction(obj):\n observees = getattr(obj, '_observes', {})\n for observee, kwargs in observees.items():\n handlers[observee].append((-1, obj, kwargs))\n\n return handlers\n\ndef create_widgets(instance, public_attributes_only=True):\n fields = _fields(instance)\n\n handlers = _observe_handlers(instance)\n widgets = []\n __widgets = OrderedDict()\n for field in fields:\n if public_attributes_only and field.name.startswith('_'):\n continue\n kwargs = {'description': field.name}\n kwargs.update(field.metadata.get('__widget', {}))\n\n try:\n _type = field.type\n widget_class, dattr = WIDGET_MAP[_type]\n except KeyError:\n if field.default not in MISSING:\n _type = type(field.default)\n widget_class, dattr = WIDGET_MAP[_type]\n elif field.default_factory not in MISSING:\n _type = type(field.default_factory())\n widget_class, dattr = WIDGET_MAP[_type]\n else:\n raise TypeError(\"Unable to find widget type for {}\".format(field.name))\n\n if field.default not in MISSING:\n kwargs['value'] = field.default\n\n widget = widget_class(**kwargs)\n for _t, observer, kwargs in handlers[field.name]:\n widget.observe(observer, names='value')\n\n widgets.append(widget)\n __widgets[field.name] = widget\n\n instance.__widgets = __widgets\n return widgets\n\n\ndef _observer(instance, attribute, name):\n def _observe(event):\n setattr(instance, attribute, event[name])\n return _observe\n\n\nclass Sync(object):\n def __init__(self, method, observes, updates):\n self.method = method\n self.observes = observes\n self.updates = updates\n\n def _sync_to_widgets(self, instance):\n _widgets = getattr(instance, '__widgets', {})\n if not _widgets:\n return\n for attribute, trait in self.updates.items():\n setattr(_widgets[attribute], trait, getattr(instance, attribute))\n\n def __get__(self, instance, owner):\n @wraps(self.method)\n def method(*args, **kwargs):\n rv = self.method(instance, *args, **kwargs)\n if self.updates:\n self._sync_to_widgets(instance)\n return rv\n method._observes = self.observes\n method._updates = self.updates\n return method\n\ndef sync(observes=None, updates=None):\n def _sync(method):\n return Sync(method, observes or {}, updates or {})\n return _sync\n","repo_name":"groutr/datawidgets","sub_path":"datawidgets/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":4514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39750262383","text":"import re\nfrom urllib.parse import urlparse\nfrom uuid import UUID\nfrom datetime import datetime\n\nimport pytest\n\nfrom django.shortcuts import reverse\n\nfrom users.tests.factories import USER_PASSWORD\nfrom media_items.models import MediaItem\n\n\n@pytest.mark.django_db\ndef test_sign_upload_request_success(authenticated_client, monkeypatch):\n c, u = authenticated_client\n monkeypatch.setenv('MEDIA_UPLOAD_BUCKET_NAME', 'abcdefgh')\n monkeypatch.setenv('AWS_ACCESS_KEY_ID', 'XXXX22XXXXXX4XX2XXXX')\n monkeypatch.setenv('AWS_SECRET_ACCESS_KEY', '0AbbbCtSAfgpoi71w8WERw8AviFYatdIV3xcPGry')\n mime_type = 'image/jpeg'\n request_url = reverse('upload-request')\n response = c.post(request_url, {'mime_type': mime_type})\n assert response.status_code == 201\n assert 'Location' in response\n assert urlparse(response['Location']) is not None\n\n\n@pytest.mark.django_db\ndef test_sign_upload_request_logged_out(client):\n url = reverse('upload-request')\n response = client.post(url, {}, secure=True)\n assert response.status_code == 403\n\n\n@pytest.mark.django_db\ndef test_sign_upload_request_mime_type_missing(authenticated_client):\n c, u = authenticated_client\n url = reverse('upload-request')\n response = c.post(url, {})\n assert response.status_code == 400\n assert 'required parameter' in str(response.content)\n\n\n@pytest.mark.django_db\ndef test_sign_upload_request_mime_type_unsupported(authenticated_client):\n c, u = authenticated_client\n url = reverse('upload-request')\n response = c.post(url, {'mime_type': 'foobar'})\n assert response.status_code == 400\n assert 'not supported' in str(response.content)\n","repo_name":"ebridges/elektrum","sub_path":"application/media_items/tests/test_upload_request.py","file_name":"test_upload_request.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38732893695","text":"import datetime\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import Context, loader\nfrom django.template.context import RequestContext\nfrom wic.models import *\nfrom wic.forms import *\nfrom wic.authentication import APIAuth\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom djangorestframework.renderers import JSONRenderer, JSONPRenderer, XMLRenderer\nfrom djangorestframework.views import ListModelView, ListOrCreateModelView\nfrom djangorestframework.permissions import IsAuthenticated\n\nclass AuthenticatedListModelView(ListModelView):\n \"\"\"\n Extends django-rest-framework's ListModelView to add our authentication methods to it.\n \"\"\"\n authentication = { APIAuth, }\n permissions = (IsAuthenticated, )\n renderers = (\n JSONRenderer,\n JSONPRenderer,\n XMLRenderer\n )\n\nclass AuthenticatedListOrCreateModelView(ListOrCreateModelView):\n \"\"\"\n Extends django-rest-framework's ListOrCreateModelView to add our authentication methods to it.\n \"\"\"\n authentication = { APIAuth, }\n permissions = (IsAuthenticated, )\n renderers = (\n JSONRenderer,\n JSONPRenderer,\n XMLRenderer\n )\n\ndef main_index(request):\n news_articles = NewsArticle.objects.all().order_by('-article_date')\n paginator = Paginator(news_articles, 8)\n\n page = request.GET.get('page')\n try:\n articles = paginator.page(page)\n except PageNotAnInteger:\n articles = paginator.page(1)\n except EmptyPage:\n articles = paginator.page(paginator.num_pages)\n\n return render_to_response( 'index.html' , {\"articles\": articles})\n\ndef view_article(request, slug):\n news_articles = NewsArticle.objects.all().order_by('-article_date')\n paginator = Paginator(news_articles, 8)\n articles = paginator.page(1)\n return render_to_response( 'newsarticle.html' , {\n 'post': get_object_or_404(NewsArticle, slug=slug),\n 'articles': articles\n })\n\ndef view_gig(request, slug):\n post = get_object_or_404(Gig, slug=slug)\n return render_to_response( 'gigs/index.html' , {'post': post, } )\n\ndef band_index(request):\n members = BandMember.objects.filter(is_active=True)\n t = loader.get_template( 'band/index.html' )\n c = Context({\n 'members': members,\n })\n return HttpResponse(t.render(c))\n\ndef gigs_index(request):\n gig_list = Gig.objects.filter(end_date__gte=datetime.date.today()).order_by('start_date')\n t = loader.get_template( 'gigs/index.html' )\n c = Context({\n 'gig_list': gig_list,\n })\n return HttpResponse(t.render(c))\n\ndef gigs_old(request):\n gig_list = Gig.objects.filter(end_date__lt=datetime.date.today()).order_by('start_date')\n t = loader.get_template( 'gigs/previous.html' )\n c = Context({\n 'gig_list': gig_list,\n })\n return HttpResponse(t.render(c))\n\ndef band_index(request):\n band_members = BandMember.objects.all().order_by('first_name')\n t = loader.get_template( 'band/index.html' )\n c = Context({\n 'members': band_members,\n })\n return HttpResponse(t.render(c))\n\ndef media_photos(request):\n photos = Photo.objects.all().order_by('-flickr_id')\n paginator = Paginator(photos, 27)\n\n page = request.GET.get('page')\n try:\n pics = paginator.page(page)\n except PageNotAnInteger:\n pics = paginator.page(1)\n except EmptyPage:\n pics = paginator.page(paginator.num_pages)\n\n return render_to_response( 'media/photos.html' , {\"photos\": pics})\n\ndef media_discography(request):\n albums = Album.objects.all().order_by('-release_date')\n\n t = loader.get_template( 'media/discography.html' )\n c = Context({\n 'albums': albums,\n })\n return HttpResponse(t.render(c))\n\ndef media_videos(request):\n t = loader.get_template( 'media/videos.html' )\n c = Context({})\n return HttpResponse(t.render(c))\n\ndef contact(request):\n if request.method == 'POST':\n form = ContactForm(request.POST)\n if form.is_valid():\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n sender = form.cleaned_data['sender']\n\n recipients = ['walkincoma@hotmail.co.uk']\n\n from django.core.mail import send_mail\n send_mail(subject, message, sender, recipients)\n return HttpResponseRedirect('/thanks/')\n else:\n form = ContactForm()\n\n return render_to_response( 'contact.html' , {\n 'form': form,\n }, context_instance=RequestContext(request))","repo_name":"nickpack/WIC-Site","sub_path":"wic/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33484819451","text":"import os\nfrom pymacaron_unit import testcase\n\n\ndef load_port_host_token():\n \"\"\"Find out which host:port to run acceptance tests against,\n using the environment variables PYM_SERVER_HOST, PYM_SERVER_PORT\n \"\"\"\n\n server_host, server_port, token = (None, None, None)\n\n if 'PYM_SERVER_HOST' in os.environ:\n server_host = os.environ['PYM_SERVER_HOST']\n if 'PYM_SERVER_PORT' in os.environ:\n server_port = os.environ['PYM_SERVER_PORT']\n\n token = os.environ.get('PYM_JWT_TOKEN', None)\n\n if server_host:\n if server_host.startswith('http://'):\n server_host = server_host[7:]\n if server_host.startswith('https://'):\n server_host = server_host[8:]\n if server_host.endswith('/'):\n server_host = server_host[:-1]\n\n if not server_host or not server_port:\n raise Exception(\"Please set both of PYM_SERVER_HOST and PYM_SERVER_PORT envvironment variables\")\n\n return (server_host, server_port, token)\n\n\nclass PyMacaronTestCase(testcase.PyMacaronTestCase):\n\n token = None\n\n def setUp(self):\n super().setUp()\n self.maxDiff = None\n self.host, self.port, self.token = load_port_host_token()\n proto = 'https' if self.port in (443, '443') else 'http'\n self.base_url = '%s://%s:%s' % (proto, self.host, self.port)\n\n def assertIsVersion(self, j):\n self.assertTrue(type(j['apis']) is list)\n self.assertTrue(type(j['name']) is str)\n self.assertTrue(type(j['version']) is str)\n self.assertTrue(type(j['pym_env']) is str)\n\n def assertHasPing(self):\n return self.assertGetReturnOk('ping')\n\n def assertHasVersion(self, verify_ssl=True):\n j = self.assertGetReturnJson('version', 200, verify_ssl=verify_ssl)\n self.assertIsVersion(j)\n return j\n\n def assertHasAuthVersion(self, verify_ssl=True):\n self.assertGetReturnError('auth/version', 401, 'AUTHORIZATION_HEADER_MISSING', verify_ssl=verify_ssl)\n\n tests = [\n # header, status code, json code\n (\"\", 401, 'AUTHORIZATION_HEADER_MISSING'),\n (\"Bearer1234567890\", 401, 'TOKEN_INVALID'),\n (\"bearer foo bar\", 401, 'TOKEN_INVALID'),\n (\"Bearer 1234567890\", 401, 'TOKEN_INVALID'),\n ]\n\n for t in tests:\n token, status, error = t\n self.assertGetReturnError('auth/version', status, error, token, verify_ssl=verify_ssl)\n\n j = self.assertGetReturnJson('auth/version', 200, \"Bearer %s\" % self.token, verify_ssl=verify_ssl)\n self.assertIsVersion(j)\n return j\n","repo_name":"pymacaron/pymacaron","sub_path":"pymacaron/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"3"}
+{"seq_id":"38217920018","text":"# Write a program to check if two strings are a rotation of each other\r\n\r\ndef rotations(string1, string2):\r\n if len(string1) != len(string2):\r\n return False\r\n \r\n concatenated_strings = string1 + string1\r\n \r\n if string2 in concatenated_strings:\r\n return True\r\n \r\n return False\r\n\r\n# Example usage\r\nstr1 = \"yeshwenth\"\r\nstr2 = \"htnewhsey\"\r\nresult = rotations(str1, str2)\r\nprint(result)\r\n","repo_name":"yeshwenthgutta15/Assignment-1-Linear-Data-Structures-part1","sub_path":"program3.py","file_name":"program3.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8736308190","text":"from .models import Profile, FollowUser\n\n\ndef is_following(request, id):\n profile = Profile.objects.get(pk=id)\n try:\n following = FollowUser.objects.get(user=request.user, follow=profile)\n except FollowUser.DoesNotExist:\n following = None\n return following\n","repo_name":"chasedixon/chasedixon.github.io","sub_path":"portfolio/platter_social/mysite/users/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22572191376","text":"def mergeOverlappingIntervals(intervals):\n intervals = sorted(intervals, key=lambda x: x[0])\n print(f\"Sorted intervals: {intervals}\")\n for (idx, item) in enumerate(intervals[:-1]):\n next_item = intervals[idx+1]\n s_num, e_num = item\n n_s_num, n_e_num = next_item\n\n # two interval has overlap\n if e_num >= n_s_num and e_num < n_e_num:\n print(f\"merge {item} + {next_item} => [{s_num}, {n_e_num}]\")\n new_item = [s_num, n_e_num]\n # replace the merged interval(first)\n intervals[idx] = new_item\n # remove the merged interval(second)\n del intervals[idx+1]\n return mergeOverlappingIntervals(intervals)\n\n # next interval is subset of previous interval\n if e_num >= n_s_num and e_num >= n_e_num:\n del intervals[idx+1]\n return mergeOverlappingIntervals(intervals)\n\n return intervals","repo_name":"taigi0315/AlgoExpert","sub_path":"midium_questions/mergeOverlappingIntervals.py","file_name":"mergeOverlappingIntervals.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15304446290","text":"#!/usr/bin/python3\n\nimport rclpy\nfrom rclpy.node import Node\nfrom rclpy.time import Time\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import LaserScan\nfrom nav_msgs.msg import Odometry\n\nfrom math import cos, sin, degrees, radians, pi\nimport sys\nimport tf_transformations\nfrom tf2_ros import TransformBroadcaster\nfrom geometry_msgs.msg import TransformStamped\n\n# Change this path to your crazyflie-firmware folder\nsys.path.append('/home/Project/crazyflie-firmware')\nimport cffirmware\n\nclass sgbaDriver:\n\n def init(self, webots_node, properties):\n self.robot = webots_node.robot\n timestep = int(self.robot.getBasicTimeStep())\n ## Initialize motors\n self.m1_motor = self.robot.getDevice(\"m1_motor\")\n self.m1_motor.setPosition(float('inf'))\n self.m1_motor.setVelocity(-1)\n self.m2_motor = self.robot.getDevice(\"m2_motor\")\n self.m2_motor.setPosition(float('inf'))\n self.m2_motor.setVelocity(1)\n self.m3_motor = self.robot.getDevice(\"m3_motor\")\n self.m3_motor.setPosition(float('inf'))\n self.m3_motor.setVelocity(-1)\n self.m4_motor = self.robot.getDevice(\"m4_motor\")\n self.m4_motor.setPosition(float('inf'))\n self.m4_motor.setVelocity(1)\n\n self.target_twist = Twist()\n\n ## Initialize Sensors\n self.imu = self.robot.getDevice(\"inertial unit\")\n self.imu.enable(timestep)\n self.gps = self.robot.getDevice(\"gps\")\n self.gps.enable(timestep)\n self.gyro = self.robot.getDevice(\"gyro\")\n self.gyro.enable(timestep)\n self.range_front = self.robot.getDevice(\"range_front\")\n self.range_front.enable(timestep)\n self.range_left = self.robot.getDevice(\"range_left\")\n self.range_left.enable(timestep)\n self.range_back = self.robot.getDevice(\"range_back\")\n self.range_back.enable(timestep)\n self.range_right = self.robot.getDevice(\"range_right\")\n self.range_right.enable(timestep)\n\n #self.lidar = self.robot.getDevice(\"lidar\")\n #self.lidar.enable(timestep)\n\n ## Intialize Variables\n self.past_x_global = 0\n self.past_y_global = 0\n self.past_z_global = 0\n self.past_time = self.robot.getTime()\n\n self.first_pos = True\n self.first_x_global = 0.0\n self.first_y_global = 0.0\n\n\n cffirmware.controllerPidInit()\n\n rclpy.init(args=None)\n self.node = rclpy.create_node('sgba_controller')\n self.laser_publisher = self.node.create_publisher(LaserScan, 'scan', 10)\n self.odom_publisher = self.node.create_publisher(Odometry, 'odom', 10)\n\n self.tfbr = TransformBroadcaster(self.node)\n\n self.msg_laser = LaserScan()\n self.node.create_timer(1.0/30.0, self.publish_laserscan_data)\n\n def publish_laserscan_data(self):\n\n front_range = float(self.range_front.getValue()/1000.0)\n\n back_range = float(self.range_back.getValue()/1000.0)\n left_range = float(self.range_left.getValue()/1000.0)\n right_range = float(self.range_right.getValue()/1000.0)\n max_range = 3.49\n if front_range > max_range:\n front_range = 0.0\n if left_range > max_range:\n left_range = 0.0\n if right_range > max_range:\n right_range = 0.0\n if back_range > max_range:\n back_range = 0.0\n\n self.msg_laser = LaserScan()\n self.msg_laser.header.stamp = Time(seconds=self.robot.getTime()).to_msg()\n self.msg_laser.header.frame_id = 'base_link'\n self.msg_laser.range_min = 0.1\n self.msg_laser.range_max = max_range\n #print('print',back_range, left_range, front_range, right_range, back_range)\n self.msg_laser.ranges = [back_range, left_range, front_range, right_range, back_range]\n #self.msg_laser.ranges = [max_range, max_range, max_range, max_range, max_range]\n\n self.msg_laser.angle_min = 0.5 * 2*pi\n self.msg_laser.angle_max = -0.5 * 2*pi\n self.msg_laser.angle_increment = -1.0*pi/2\n self.laser_publisher.publish(self.msg_laser)\n \n def step(self):\n #rclpy.spin_once(self.node, timeout_sec=0)\n self.node.get_logger().error('pee')\n\n\n# def main(args=None):\n# rclpy.init(args=args)\n# sd = sgbaDriver()\n# rclpy.spin(sd)\n\n# rclpy.shutdown()\n# pass\n\n# if __name__ == '__main__':\n# main()","repo_name":"TomoCoder123/sgba-webots2.0","sub_path":"ros2_ws/src/crazyswarm2/crazyflie_ros2_sgba/crazyflie_ros2_sgba/sgba_controller.py","file_name":"sgba_controller.py","file_ext":"py","file_size_in_byte":4499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28922891491","text":"# -*- coding: utf-8 -*-\n\n__author__ = \"Petter Hetland\"\n__email__ = \"pehe@nmbu.no\"\n\n\n# Import pytest\nimport pytest\n\n\n# Median function sourced from ex03_pytest_intro.rst authored by\n# Yngve Mardal Moe\ndef median(data):\n \"\"\"\n Returns median of data.\n\n :param data: An iterable of containing numbers\n :return: Median of data\n \"\"\"\n\n sdata = sorted(data)\n n = len(sdata)\n if n % 2 == 1:\n return sdata[n // 2]\n else:\n return 0.5 * (sdata[n // 2 - 1] + sdata[n // 2])\n\n\ndef test_one_element_list():\n \"\"\"\"\". Tests that the median function returns\n the correct value for a one-element list.\n \"\"\"\n\n median_5 = median([5])\n assert median_5 == 5\n\n\ndef test_odd_n():\n \"\"\" Tests that the correct median is returned for lists with odd\n numbers of element.\n \"\"\"\n data = [5, 6, 8, 4, 2]\n data_median = median(data)\n assert data_median == 5\n\n\ndef test_even_n():\n \"\"\" Tests that the correct median is returned for lists with even\n numbers of elements.\n \"\"\"\n data = [5, 6, 8, 4, 2, 9]\n data_median = median(data)\n assert data_median == 5.5\n\n\ndef test_ordered_variations():\n \"\"\" Tests that the correct median is returned for lists with ordered,\n reverse-ordered and unordered elements\n \"\"\"\n data_1 = [1, 2, 3, 4, 5]\n data_2 = [5, 4, 3, 2, 1]\n data_3 = [4, 2, 3, 5, 1]\n data_1_median = median(data_1)\n data_2_median = median(data_2)\n data_3_median = median(data_3)\n assert data_1_median and data_2_median and data_3_median == 3\n\n\ndef test_empty_list():\n \"\"\" Tests that a IndexError is raised when\n the length of the given list is 0\n \"\"\"\n data = []\n with pytest.raises(IndexError):\n median(data)\n\n\ndef test_original_data():\n \"\"\" Tests that the median-function does not\n alter the original list of data\n \"\"\"\n data = [4, 5, 7, 6]\n data_median = median(data)\n assert data == [4, 5, 7, 6]\n\n\ndef test_tuples():\n \"\"\" Tests that the function works for tuples as well as lists\n \"\"\"\n tuple_data = (2, 4, 6, 8, 10)\n tuple_data_median = median(tuple_data)\n assert tuple_data_median == 6\n","repo_name":"pkhetland/Scientific-Python-exercises","sub_path":"Exercises/ex03_pytest_intro/test_median.py","file_name":"test_median.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"20667084959","text":"import tweepy\n\n# 認証キーの設定\nconsumer_key = \"hoge\"\nconsumer_secret = \"hoge\"\naccess_token = \"hoge\"\naccess_token_secret = \"hoge\"\n\n# OAuth認証\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\n# APIのインスタンスを生成\n# api = tweepy.API(auth)\napi = tweepy.API(\n auth,\n wait_on_rate_limit=True,\n wait_on_rate_limit_notify=True\n)\n\ndef getFollowers_ids(api, screen_name):\n followers_ids = tweepy.Cursor(api.followers_ids, screen_name=screen_name, cursor=-1).items()\n followers_ids_list = []\n try:\n followers_ids_list=[i for i in followers_ids]\n \n\n except tweepy.error.TweepError as e:\n print(e.reason)\n\n return followers_ids_list\n \n\n# Get Id list of followers\nfrom tqdm import tqdm\nimport time\nscreen_name=\"kyouyap\"\nfollowers_ids=getFollowers_ids(api, screen_name)\nname=[]\nscreen_name=[]\nurl=[]\ndescription=[]\nprotected=[]\nfolloerws_count=[]\nfriends_count=[]\nlisted_count=[]\nstatuses_count=[]\ncreated_at=[]\ntry:\n for i in tqdm(range(len(followers_ids))):\n if (i%900==0)and(i!=0):\n time.sleep(600)\n center_info = api.get_user(id=followers_ids[i])\n name.append(center_info.name)\n screen_name.append(center_info.screen_name)\n url.append(center_info.url)\n description.append(center_info.description)\n protected.append(center_info.protected)\n folloerws_count.append(center_info.followers_count)\n friends_count.append(center_info.friends_count)\n listed_count.append(center_info.listed_count)\n statuses_count.append(center_info.statuses_count)\n created_at.append(center_info.created_at)\n if (i%900==0)and(i!=0):\n time.sleep(900)\nexcept tweepy.error.TweepError as e:\n print(e.reason)\nimport pandas as pd\ndf=pd.DataFrame({\"name\":name,\"screen_name\":screen_name,\"url\":url\n ,\"description\":description,\"protected\":protected,\"folloerws_count\":folloerws_count,\"friends_count\":friends_count,\"listed_count\":listed_count,\"statuses_count\":statuses_count,\"created_at\":created_at})\ndf.to_csv(\"folower_information.csv\",index=None,encoding='utf_8_sig')\n\ndf.description=df.description.fillna(\"\")\n\nimport japanize_matplotlib\nimport re\nimport MeCab\nimport numpy as np\n\n# 対象の品詞\nTARGET_POS1 = ['名詞']\n \n# 対象の詳細分類1\nTARGET_POS2 = ['サ変接続', 'ナイ形容詞語幹', '形容動詞語幹', '一般', '固有名詞']\n \n# ストップワード\nSTOP_WORDS = ['*']\n \ndef remove_blank(chapter):\n # 空白行と段落先頭の空白を削除\n \n lines = chapter.splitlines()\n \n # 空白行削除\n # 行頭の空白削除\n lines_cleaned = [l.strip() for l in lines if len(l) != 0]\n \n return '\\n'.join(lines_cleaned)\n \ndef chapter2bform(chapter_l):\n # 章ごとに形態素解析して単語の原型のリストを作成\n \n m = MeCab.Tagger('-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd')\n m.parse('')\n \n bform_2l = []\n for i, chapter in enumerate(chapter_l):\n node = m.parseToNode(chapter)\n \n bform_l = []\n while node:\n feature_split = node.feature.split(',')\n \n pos1 = feature_split[0]\n pos2 = feature_split[1]\n base_form = feature_split[6]\n \n if pos1 in TARGET_POS1 and pos2 in TARGET_POS2 and base_form not in STOP_WORDS:\n bform_l.append(base_form)\n \n node = node.next\n \n bform_2l.append(bform_l)\n \n print('Term number of chapter {}: '.format(i+1), len(bform_l))\n return bform_2l\n\nfrom itertools import combinations, dropwhile\nfrom collections import Counter, OrderedDict\n \ndef bform2pair(bform_2l, min_cnt=5):\n # 単語ペアの出現章数をカウント\n \n # 全単語ペアのリスト\n pair_all = []\n \n for bform_l in bform_2l:\n # 章ごとに単語ペアを作成\n # combinationsを使うと順番が違うだけのペアは重複しない\n # ただし、同単語のペアは存在しえるのでsetでユニークにする\n pair_l = list(combinations(set(bform_l), 2))\n \n # 単語ペアの順番をソート\n for i,pair in enumerate(pair_l):\n pair_l[i] = tuple(sorted(pair))\n \n pair_all += pair_l\n \n # 単語ペアごとの出現章数\n pair_count = Counter(pair_all)\n \n # ペア数がmin_cnt以上に限定\n for key, count in dropwhile(lambda key_count: key_count[1] >= min_cnt, pair_count.most_common()):\n del pair_count[key]\n \n return pair_count\n \ndef pair2jaccard(pair_count, bform_2l, edge_th=0.4):\n # jaccard係数を計算\n \n # 単語ごとの出現章数\n word_count = Counter()\n for bform_l in bform_2l:\n word_count += Counter(set(bform_l))\n \n # 単語ペアごとのjaccard係数を計算\n jaccard_coef = []\n for pair, cnt in pair_count.items():\n jaccard_coef.append(cnt / (word_count[pair[0]] + word_count[pair[1]] - cnt))\n \n # jaccard係数がedge_th未満の単語ペアを除外\n jaccard_dict = OrderedDict()\n for (pair, cnt), coef in zip(pair_count.items(), jaccard_coef):\n if coef >= edge_th:\n jaccard_dict[pair] = coef\n print(pair, cnt, coef, word_count[pair[0]], word_count[pair[1]], sep='\\t')\n \n return jaccard_dict\n \n\nimport networkx as nx\n# matplotlibのターミナル対応\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n \ndef build_network(jaccard_dict):\n # 共起ネットワークを作成\n G = nx.Graph()\n \n # 接点/単語(node)の追加\n # ソートしないとネットワーク図の配置が実行ごとに変わる\n nodes = sorted(set([j for pair in jaccard_dict.keys() for j in pair]))\n G.add_nodes_from(nodes)\n \n print('Number of nodes =', G.number_of_nodes())\n \n # 線(edge)の追加\n for pair, coef in jaccard_dict.items():\n G.add_edge(pair[0], pair[1], weight=coef)\n \n print('Number of edges =', G.number_of_edges())\n \n plt.figure(figsize=(15, 15))\n \n # nodeの配置方法の指定\n seed = 0\n np.random.seed(seed)\n pos = nx.nx_agraph.graphviz_layout(\n G,\n prog='neato',\n args='-Goverlap=\"scalexy\" -Gsep=\"+6\" -Gnodesep=0.8 -Gsplines=\"polyline\" -GpackMode=\"graph\" -Gstart={}'.format(seed))\n\n \n # nodeの大きさと色をページランクアルゴリズムによる重要度により変える\n pr = nx.pagerank(G)\n nx.draw_networkx_nodes(\n G,\n pos,\n node_color=list(pr.values()),\n cmap=plt.cm.rainbow,\n alpha=0.7,\n node_size=[100000*v for v in pr.values()])\n \n # 日本語ラベルの設定\n nx.draw_networkx_labels(G, pos, fontsize=15, font_family='IPAexGothic', font_weight='bold')\n \n # エッジ太さをJaccard係数により変える\n edge_width = [d['weight'] * 8 for (u, v, d) in G.edges(data=True)]\n nx.draw_networkx_edges(G, pos, alpha=0.7, edge_color='darkgrey', width=edge_width, font_size=12, font_family='IPAexGothic')\n \n plt.axis('off')\n plt.tight_layout()\n plt.savefig('co-occurance.png', bbox_inches='tight')\n\n\n\n# 章ごとの単語原型リスト\nbform_2l = chapter2bform(list(df.description))\n\n# Jaccard係数の計算\npair_count = bform2pair(bform_2l, min_cnt=4)\njaccard_dict = pair2jaccard(pair_count, bform_2l, edge_th=0.4)\n\n# 共起ネットワーク作成\nbuild_network(jaccard_dict)","repo_name":"kyouyap/Co-occurrence_word","sub_path":"wordtwitter.py","file_name":"wordtwitter.py","file_ext":"py","file_size_in_byte":7420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14945481857","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport time\nimport os\nimport csv\nimport random\nimport json\n\nfrom bokeh.core.json_encoder import pd\nfrom bs4 import BeautifulSoup\nimport importlib\n\n\n# 要爬取热评的起始url\nurl = 'https://m.weibo.cn/comments/hotflow?id=4514782050289970&mid=4514782050289970&max_id_type=0'\n# cookie UA要换成自己的\nheaders = {\n 'Cookie': 'WEIBOCN_WM=9006_2001; WEIBOCN_FROM=1110006030; ALF=1597055017; SCF=AlFfFFXPNaDKgqx85KrtJ_D4OlIDpYusd-srzgU9N7wdCuyDFlppseRiusFDb6VRiMrfS6O-MldlxaC2qF-nBwM.; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WhLoqxGA9SeGA8PL_rcQ1Pv5JpX5K-hUgL.Fo-fSonEe05R1h52dJLoIE5LxK.L1K.LBoqLxKqL1K.LBKnLxKqL1KMLB-Bc1KnReBtt; SSOLoginState=1594463025; SUB=_2A25yDeNtDeRhGeNK7VIW-CrLyDqIHXVR8Y0lrDV6PUJbkdAKLXDQkW1NSUzFjEmYMYOtxSc6SOoyOceWns7NlhqM; SUHB=0vJIObHKmWEkoX; _T_WM=73630556534; MLOGIN=1; M_WEIBOCN_PARAMS=sourceType%3Dqq%26from%3D10A7095010%26featurecode%3Dnewtitle%26oid%3D4514782050289970%26luicode%3D20000061%26lfid%3D4514782050289970%26uicode%3D20000061%26fid%3D4514782050289970; XSRF-TOKEN=b85cc4',\n 'Referer': 'https://m.weibo.cn/status/4514782050289970?sourceType=qq&from=10A7095010&wm=9006_2001&featurecode=newtitle',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest'\n}\n\ndef get_page(max_id, id_type):\n params = {\n 'max_id': max_id,\n 'max_id_type': id_type\n }\n try:\n r = requests.get(url, params=params, headers=headers)\n if r.status_code == 200:\n return r.json()\n except requests.ConnectionError as e:\n print('请检查网络', e.args)\n\n\ndef parse_page(jsondata):\n if jsondata:\n items = jsondata.get('data')\n global item_max_id\n item_max_id = {}\n try:\n if items != None:\n item_max_id['max_id'] = items['max_id']\n item_max_id['max_id_type'] = items['max_id_type']\n return item_max_id\n except TypeError:\n print('有可能是IP被封了,若之后一直出现此消息,请更换IP')\n\ndef write_csv(jsondata):\n dataone = jsondata.get('data')\n global datas\n try:\n if dataone != None:\n datas = dataone.get('data')\n except AttributeError:\n print('这页没有东西了')\n pass\n\n if datas != None:\n for data in datas:\n created_at = data.get(\"created_at\")\n like_count = data.get(\"like_count\")\n source = data.get(\"source\")\n total_number = data.get(\"total_number\")\n username = data.get(\"user\").get(\"screen_name\")\n gender = data.get(\"user\").get(\"gender\")\n if gender == 'f':\n gender = '女'\n elif gender == 'm':\n gender = '男'\n comment = data.get(\"text\")\n #print(comment)\n emoji = BeautifulSoup(comment, 'lxml').find('img')\n #print(emoji)\n if emoji is None:\n continue\n elif emoji is not None:\n emoj = emoji.get('alt')\n #if emoj is not None:\n #continue\n #print(emoj)\n # elif emoji is None:\n #continue\n #elif emoji == '':\n #ontinue\n #print(emoj)\n comment = BeautifulSoup(comment, 'lxml').get_text()\n writer.writerow([username, gender, created_at, like_count, total_number, emoj,\n json.dumps(comment, ensure_ascii=False)])\n\n# 存为csv\npath = \"C:\\\\Users\\\\pc\\\\Desktop\\\\mojitocomment2.csv\"\ncsvfile = open(path, 'w', encoding = 'utf-8-sig')\nwriter = csv.writer(csvfile)\nwriter.writerow(['用户名', '性别', '发表时间', '点赞数', '评论数', '表情', '评论内容'])\n\nmaxpage = 3100 #爬取的数量\nmax_id = 0\nid_type = 0\nfor page in range(0, maxpage):\n print(page)\n jsondata = get_page(max_id, id_type)\n write_csv(jsondata)\n results = parse_page(jsondata)\n x = random.randint(6,8)\n time.sleep(x)\n if results != None:\n max_id = results['max_id']\n id_type = results['max_id_type']\n else:\n print('翻页方式错误')\n time.sleep(10)\n max_id = max_id\n id_type = id_type\n\n\n","repo_name":"TaoChenXu/Python","sub_path":"weibocomment/weibocomment.py","file_name":"weibocomment.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10657525094","text":"import math\nimport numpy as np\n\nclass Projector:\n \"\"\"Projects 2d points to 3d space defined by a homography matrix.\"\"\"\n \n def __init__(self, camera_matrix_file: str):\n\n # homography matrix: 3d -> 2d\n self.homography = np.zeros((3, 3))\n with open(camera_matrix_file, \"r\") as f:\n line = f.readline()\n PRE = \"Homography matrix:\"\n if line.startswith(PRE):\n line = line[len(PRE):]\n rows = line.split(\";\")\n for i, line in enumerate(rows):\n cols = line.strip().split()\n assert len(cols) == 3\n for j, x in enumerate(cols):\n self.homography[i, j] = float(x)\n self.inv_homography = np.linalg.inv(self.homography)\n \n def project3d(self, x, y):\n p = np.matmul(self.inv_homography, np.array([x, y, 1]))\n p /= p[2]\n return p[:2]\n\n\ndef dist(latlon1, latlon2) -> float:\n \"\"\"Distance between two gps coordinates.\n\n Uses the Haversine formula (https://www.movable-type.co.uk/scripts/latlong.html)\n\n Parameters:\n ----------\n latlon1: array_like[2]\n Latitude-longitude of point 1.\n latlon2: array_like[2]\n Latitude-longitude of point 2.\n \n Returns:\n -------\n d: float\n Distance between the two points in meters.\n \"\"\"\n R = 6371_000\n phi1 = latlon1[0] * math.pi / 180\n phi2 = latlon2[0] * math.pi / 180\n dphi = phi2 - phi1\n dlambda = (latlon2[1] - latlon1[1]) * math.pi / 180\n a = math.sin(dphi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2) ** 2\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))\n d = R * c\n return d\n\ndef dist_planar(latlon1, latlon2):\n \"\"\"Estimation of the distance between two points assuming planar earth.\"\"\"\n R = 6371_000\n y1 = latlon1[0] * math.pi / 180\n y2 = latlon2[0] * math.pi / 180\n x1 = latlon1[1] * math.pi / 180\n x2 = latlon2[1] * math.pi / 180\n\n dy = abs(y1 - y2) * R\n r_avg = R * math.cos((y1 + y2) / 2)\n dx = abs(x1 - x2) * r_avg\n return math.sqrt(dx ** 2 + dy ** 2)\n \n \n","repo_name":"regob/vehicle_mtmc","sub_path":"mot/projection_3d.py","file_name":"projection_3d.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"3"}
+{"seq_id":"44254108021","text":"from __future__ import print_function\nimport numpy as np\n\n\nclass HMM:\n\n def __init__(self, pi, A, B, obs_dict, state_dict):\n \"\"\"\n - pi: (1*num_state) A numpy array of initial probailities. pi[i] = P(Z_1 = s_i)\n - A: (num_state*num_state) A numpy array of transition probailities. A[i, j] = P(Z_t = s_j|Z_t-1 = s_i)\n - B: (num_state*num_obs_symbol) A numpy array of observation probabilities. B[i, k] = P(X_t = o_k| Z_t = s_i)\n - obs_dict: (num_obs_symbol*1) A dictionary mapping each observation symbol to their index in B\n - state_dict: (num_state*1) A dictionary mapping each state to their index in pi and A\n \"\"\"\n self.pi = pi\n self.A = A\n self.B = B\n self.obs_dict = obs_dict\n self.state_dict = state_dict\n\n def forward(self, Osequence):\n \"\"\"\n Inputs:\n - self.pi: (1*num_state) A numpy array of initial probailities. pi[i] = P(Z_1 = s_i)\n - self.A: (num_state*num_state) A numpy array of transition probailities. A[i, j] = P(Z_t = s_j|Z_t-1 = s_i)\n - self.B: (num_state*num_obs_symbol) A numpy array of observation probabilities. B[i, k] = P(X_t = o_k| Z_t = s_i)\n - Osequence: (1*L) A numpy array of observation sequence with length L\n\n Returns:\n - alpha: (num_state*L) A numpy array alpha[i, t] = P(Z_t = s_i, x_1:x_t | λ)\n \"\"\"\n S = len(self.pi)\n L = len(Osequence)\n alpha = np.zeros([S, L])\n ###################################################\n # Edit here\n for i in range(S):\n alpha[i,0] = self.pi[i] * self.B[i,self.obs_dict[Osequence[0]]]\n\n for t in range(1,L):\n for i in range(S):\n alpha[i,t] = self.B[i,self.obs_dict[Osequence[t]]] * sum([self.A[k, i] * alpha[k, t - 1] for k in range(S)])\n ###################################################\n return alpha\n\n def backward(self, Osequence):\n \"\"\"\n Inputs:\n - self.pi: (1*num_state) A numpy array of initial probailities. pi[i] = P(Z_1 = s_i)\n - self.A: (num_state*num_state) A numpy array of transition probailities. A[i, j] = P(Z_t = s_j|Z_t-1 = s_i)\n - self.B: (num_state*num_obs_symbol) A numpy array of observation probabilities. B[i, k] = P(X_t = o_k| Z_t = s_i)\n - Osequence: (1*L) A numpy array of observation sequence with length L\n\n Returns:\n - beta: (num_state*L) A numpy array beta[i, t] = P(x_t+1:x_T | Z_t = s_i, λ)\n \"\"\"\n S = len(self.pi)\n L = len(Osequence)\n beta = np.zeros([S, L])\n ###################################################\n # Edit here\n for i in range(S):\n beta[i, L-1] = 1\n\n for t in reversed(range(L-1)):\n for i in range(S):\n beta[i,t] = sum([beta[j, t + 1] * self.A[i, j] * self.B[j, self.obs_dict[Osequence[t + 1]]] for j in range(S)])\n ###################################################\n return beta\n\n def sequence_prob(self, Osequence):\n \"\"\"\n Inputs:\n - Osequence: (1*L) A numpy array of observation sequence with length L\n\n Returns:\n - prob: A float number of P(x_1:x_T | λ)\n \"\"\"\n prob = 0\n ###################################################\n # Edit here\n alpha = self.forward(Osequence)\n prob = sum(alpha[:, -1])\n ###################################################\n return prob\n\n def posterior_prob(self, Osequence):\n \"\"\"\n Inputs:\n - Osequence: (1*L) A numpy array of observation sequence with length L\n\n Returns:\n - prob: (num_state*L) A numpy array of P(s_t = i|O, λ)\n \"\"\"\n S = len(self.pi)\n L = len(Osequence)\n prob = np.zeros([S, L])\n ###################################################\n # Edit here\n alpha = self.forward(Osequence)\n beta = self.backward(Osequence)\n seq_prob = self.sequence_prob(Osequence)\n for i in range(S):\n for j in range(L):\n prob[i,j] = alpha[i,j] * beta[i,j] / seq_prob\n ###################################################\n return prob\n #TODO:\n def likelihood_prob(self, Osequence):\n \"\"\"\n Inputs:\n - Osequence: (1*L) A numpy array of observation sequence with length L\n\n Returns:\n - prob: (num_state*num_state*(L-1)) A numpy array of P(X_t = i, X_t+1 = j | O, λ)\n \"\"\"\n S = len(self.pi)\n L = len(Osequence)\n prob = np.zeros([S, S, L - 1])\n ###################################################\n # Edit here\n alpha = self.forward(Osequence)\n beta = self.backward(Osequence)\n seq_prob = self.sequence_prob(Osequence)\n for i in range(S):\n for j in range(S):\n for k in range(L-1):\n prob[i,j,k] = alpha[i,k] * self.A[i,j] * self.B[j, self.obs_dict[Osequence[k+1]]] * beta[j,k+1] / seq_prob\n ###################################################\n return prob\n\n def viterbi(self, Osequence):\n \"\"\"\n Inputs:\n - Osequence: (1*L) A numpy array of observation sequence with length L\n\n Returns:\n - path: A List of the most likely hidden state path k* (return state instead of idx)\n \"\"\"\n path = []\n ###################################################\n # Q3.3 Edit here\n S = len(self.pi)\n L = len(Osequence)\n delta = np.zeros([S, L])\n Delta = np.zeros([S, L], dtype=\"int\")\n delta[:, 0] = self.pi * self.B[:, self.obs_dict[Osequence[0]]]\n\n for t in range(1, L):\n for i in range(S):\n delta[i, t] = self.B[i, self.obs_dict[Osequence[t]]] * np.max(self.A[:, i] * delta[:, t - 1])\n Delta[i, t] = np.argmax(self.A[:, i] * delta[:, t - 1])\n z = np.argmax(delta[:, L - 1])\n path.append(z)\n\n for t in range(L - 1, 0, -1):\n z = Delta[z, t]\n path.append(z)\n path = path[::-1]\n\n new_dict = {v : k for k, v in self.state_dict.items()}\n for i in range(len(path)):\n path[i] = new_dict[path[i]]\n\n ###################################################\n return path\n","repo_name":"russell-lin/HMM","sub_path":"hmm.py","file_name":"hmm.py","file_ext":"py","file_size_in_byte":6329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42853887700","text":"from . import HobokenTestCase, hoboken\nimport os\nimport yaml\nfrom hoboken.tests.compat import parametrize, parametrize_class, unittest\n\nfrom hoboken.application import Request\nfrom hoboken.six import iteritems, text_type\nMatcher = hoboken.matchers.HobokenRouteMatcher\n\n\nclass TestMethods(HobokenTestCase):\n def after_setup(self):\n for meth in self.app.SUPPORTED_METHODS:\n self.app.add_route(meth, '/', self.body_func)\n\n def test_successful_methods(self):\n methods = list(self.app.SUPPORTED_METHODS)\n methods.remove(\"HEAD\")\n for meth in methods:\n self.assert_body_is('request body', method=meth)\n\n def test_HEAD_method(self):\n self.assert_body_is('', method=\"HEAD\")\n\n def test_failed_methods(self):\n for meth in self.app.SUPPORTED_METHODS:\n self.assert_not_found(path='/somebadpath')\n\n\nclass TestHeadFallback(HobokenTestCase):\n def after_setup(self):\n @self.app.get('/')\n def get_func():\n self.app.response.headers['X-Custom-Header'] = b'foobar'\n return 'get body'\n\n def test_HEAD_fallback(self):\n r = Request.build('/')\n r.method = \"HEAD\"\n resp = r.get_response(self.app)\n\n self.assertEqual(resp.status_int, 200)\n self.assertEqual(len(resp.body), 0)\n self.assertEqual(resp.headers['X-Custom-Header'], b'foobar')\n\n\n# Load our list of test cases from our yaml file.\ncurr_dir = os.path.abspath(os.path.dirname(__file__))\ntest_file = os.path.join(curr_dir, 'routing_tests.yaml')\nwith open(test_file, 'rb') as f:\n file_data = f.read()\ntest_cases = list(yaml.load_all(file_data))\n\n\n@parametrize_class\nclass TestRouting(unittest.TestCase):\n @parametrize('param', test_cases)\n def test_route(self, param):\n if 'skip' in param:\n if hasattr(unittest, 'SkipTest'):\n raise unittest.SkipTest(param['skip'])\n return\n\n matcher = Matcher(param['path'])\n regex = param['regex'].encode('latin-1')\n self.assertEqual(matcher.match_re.pattern, regex)\n\n class FakeRequest(object):\n path_info = None\n\n for succ in param.get('successes', []):\n r = FakeRequest()\n r.path_info = succ['route'].encode('latin-1')\n matched, args, kwargs = matcher.match(r)\n\n expected_args = [x.encode('latin-1') for x in succ.get('args', [])]\n expected_kwargs_str = succ.get('kwargs', {})\n expected_kwargs = {}\n for k, v in iteritems(expected_kwargs_str):\n if isinstance(v, text_type):\n v = v.encode('latin-1')\n expected_kwargs[k] = v\n self.assertTrue(matched)\n self.assertEqual(args, expected_args)\n self.assertEqual(kwargs, expected_kwargs)\n\n for fail in param.get('failures', []):\n r = FakeRequest()\n r.path = fail\n matched, _, _ = matcher.match(r)\n\n self.assertFalse(matched)\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestMethods))\n suite.addTest(unittest.makeSuite(TestHeadFallback))\n suite.addTest(unittest.makeSuite(TestRouting))\n\n return suite\n\n","repo_name":"andrew-d/Hoboken","sub_path":"hoboken/tests/test_routing.py","file_name":"test_routing.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"19389625476","text":"\"\"\"\n LaTeX2IMG takes an expression, and name and an extension to convert that\n expression to a image file named \"name.extension\"\n\"\"\"\n\nimport sys\nimport os\nfrom urllib.parse import quote\nfrom urllib.request import urlopen\nfrom PIL import Image, ImageOps\n\n\ndef img2webp(path):\n \"\"\"\n Takes a path of an image and converts it to webp\n \"\"\"\n file, ext = os.path.splitext(path)\n image = Image.open(path).convert(\"RGBA\")\n image = ImageOps.expand(image, 75)\n image.save(file + \".webp\", \"WEBP\")\n os.remove(path)\n\ndef latex2img(expression, filename, extension):\n \"\"\"\n Convert expression to an image called filename.extension\n \"\"\"\n webp = False\n\n if extension not in (\"gif\", \"png\", \"pdf\", \"swf\", \"emf\", \"svg\", \"webp\"):\n print(\"Not supported extension, exiting...\")\n sys.exit(-1)\n\n if extension == \"webp\":\n webp = True\n extension = \"png\"\n\n # Preparing text strings\n server = \"http://latex.codecogs.com/\" + extension + \".download?\"\n fullname = filename + \".\" + extension\n size = \"%5Cdpi%7B300%7D%20\"\n\n # Quote expression\n expression = quote(expression)\n url = server + size + expression\n\n # Download file from url and save to output_file:\n with urlopen(url) as response, open(fullname, 'wb') as output_file:\n data = response.read() # Un objeto \"bytes\"\n output_file.write(data) # Se escribe en disco\n\n if webp:\n img2webp(fullname)\n extension = \"webp\"\n\n return filename + \".\" + extension\n","repo_name":"29antonioac/LaTeX2IMG","sub_path":"LaTeX2IMG/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"}
+{"seq_id":"7480992864","text":"import random\nimport webbrowser\nimport os\nfrom time import sleep\nimport webbrowser\n\nvariable = [\"Wine Tasting\", 'Food', 'Skydiving', 'Symphony', 'Movie drive-in']\nrandom_choice = random.choice(variable)\n\n#placing in every location, along with the website for expense variable\ndef choices():\n #After random places is variable, it will go along with the if/elif system to correspond with its own function. \n print(\"After carefully selectings, we choose: \" + random_choice)\n if random_choice == 'Wine Tasting':\n # Function for Wine tasting, random will choose a key from Wine_choice and will depending what it is will open the webside automatically\n def Wine_Tasting():\n print('There are five basic steps in tasting wine: color, swirl, smell, taste, and savor.\\n These are also known as the \"five S\" steps: see, swirl, sniff, sip, savor.\\n Your job is to look for clarity, integration, expressiveness, complexity, and connectedness.\\n')\n Wine_choice = {\"Sable Gate Winery\": 'https://sablegatewinery.com/about/', 'Nice Winery':'https://www.nicewines.com/Visit-Us/Tastings', 'Decant Urban Winery': 'https://decantwinery.com','Ermarose Winery': 'https://ermarosewinery.com','Wild Stallion Vineyards': 'https://www.wildstallionvineyards.com'}\n sleep(10)\n entry = random.choice(list(Wine_choice))\n print('Your location for today\\'s adventure will be: ' + entry)\n print('A new page will open! Give me a sec for i can tranfer you over')\n sleep(10)\n\n while True:\n if entry == 'Sable Gate Winery':\n webbrowser.open('https://sablegatewinery.com/about')\n break\n elif entry == 'Nice Winery':\n webbrowser.open('https://www.nicewines.com')\n break\n elif entry == 'Decant Urban Winery':\n webbrowser.open('https://decantwinery.com')\n break\n elif entry == 'Ermarose Winery':\n webbrowser.open('https://ermarosewinery.com')\n break\n elif entry == 'Wild Stallion Vineyards':\n webbrowser.open('https://www.wildstallionvineyards.com')\n break\n Wine_Tasting()\n elif random_choice == 'Food':\n #function for food, this will place in a random answer from type of food and will go along with the if/elif to go with coressponding function\n def Food():\n os.system('clear')\n print('We have: Steak, Sushi, Italian')\n list = ['Steak','Sushi','Italian']\n Choice_food = random.choice(list)\n print(\"For today\\'s choice we have picked: \" + Choice_food)\n sleep(10)\n def Sushi():\n print(\"Sushi is a popular Japanese dish made from seasoned rice with fish, egg, or vegetables.\")\n Sushi_choice = ['Uchi', 'Hidden Omasake','MF Sushi','Kuu','Roka Akor']\n entry = random.choice(Sushi_choice)\n print('Your location for today\\'s adventure will be: ' + entry)\n print('A new page will open! Give me a sec for i can transfer you over')\n sleep(10)\n while True:\n if entry == 'Uchi':\n webbrowser.open('https://www.uchihouston.com')\n break\n elif entry == 'Hidden Omasake':\n webbrowser.open('https://hiddenomakase.com')\n break\n elif entry == 'MF Sushi':\n webbrowser.open('https://www.opentable.com/r/mf-sushi-houston')\n break\n elif entry == 'Kuu':\n webbrowser.open('https://kuurestaurant.com')\n break\n elif entry == 'Roka Akor':\n webbrowser.open('https://www.rokaakor.com')\n break\n\n def Steak():\n print(\"Steak is a food that can be described as tender, flavorful, juicy, and cooked to perfection\")\n Steak_choice = ['Vic & Anthony\\'s Steakhouse', 'B & B Butchers & Restaurant','Mastro\\'s Steakhouse','Tony\\'s','The Capital Grille']\n entry = random.choice(Steak_choice)\n print('Your location for today\\'s adventure will be: ' + entry + '!\\n' )\n print('A new page will open! Give me a sec for i can transfer you over')\n sleep(10)\n while True:\n if entry == 'Vic & Anthony\\'s Steakhouse':\n webbrowser.open('vicandanthonys.com')\n break\n elif entry == 'B & B Butchers & Restaurant':\n webbrowser.open('bbbutchers.com')\n break\n elif entry == 'Mastro\\'s Steakhouse':\n webbrowser.open('https://www.mastrosrestaurants.com')\n break\n elif entry == 'Tony\\'s':\n webbrowser.open('https://www.tonyshouston.com')\n break\n elif entry == 'The Capital Grille':\n webbrowser.open(' https://www.thecapitalgrille.com/locations/tx/houston/houston-the-galleria/8007')\n break\n\n def Italian():\n print(\"Squisito! If you want to pay someone the highest compliment for their cooking, an excellent alternative to buono is the word squisito meaning exquisite or delicious.\\n\")\n Sushi_choice = ['Sorrento Ristorante', 'Da Marco Italian Restaurant','La Griglia','Amore']\n entry = random.choice(Sushi_choice)\n print('Your location for today\\'s adventure will be: ' + entry + '!\\n' )\n print('A new page will open! Give me a sec for i can transfer you over')\n sleep(10)\n while True:\n if entry == 'Sorrento Ristorante':\n webbrowser.open('https://www.sorrentohouston.com')\n break\n elif entry == 'Da Marco Italian Restaurant':\n webbrowser.open('https://www.damarcohouston.com')\n break\n elif entry == 'La Griglia':\n webbrowser.open('https://www.lagrigliarestaurant.com')\n break\n elif entry == 'Amore':\n webbrowser.open('https://www.amorehouston.com')\n break\n#based om the option given it will go toward the elif and print that function\n if Choice_food == 'Sushi':\n Sushi()\n elif Choice_food == 'Steak':\n Steak()\n elif Choice_food == 'Italian':\n Italian()\n Food()\n elif random_choice == 'Skydiving':\n #skydiving function\n def Skydiving():\n print(\"Tired of something casual? Take it up to skies! \\n\")\n print('A new page will open! Give me a sec for i can transfer you over')\n sleep(10)\n webbrowser.open('https://www.skydivehouston.com')\n Skydiving()\n\n elif random_choice == 'Symphony':\n def Symphony():\n print(\"a large group of musicians who play together on a variety of string, wind and percussion instruments.\\n Find your sound, your melody, your rhythm, bring it to thy self!\")\n print('A new page will open! Give me a sec for i can transfer you over')\n sleep(10)\n webbrowser.open('https://houstonsymphony.org') \n Symphony()\n\n elif random_choice == 'Movie drive-in':\n def Movie_drive_in():\n print(\"Moviegoers are meant to drive into the theater and park their cars in front of a large screen that displays the movie.\")\n Movie_choice = ['Moonstruck', 'Showboat','Mastro\\'s Steakhouse','Rooftop Cinema Club','BlueMoon Cinemas']\n entry = random.choice(Movie_choice)\n print('Your location for today\\'s adventure will be: ' + entry + '!\\n' )\n print('A new page will open! Give me a sec for i can transfer you over')\n sleep(10)\n while True:\n if entry == 'Moonstruck':\n webbrowser.open('https://www.moonstruckdrivein.com')\n break\n elif entry == 'Showboat':\n webbrowser.open('https://www.showboathouston.com')\n break\n elif entry == 'Rooftop Cinema Club':\n webbrowser.open('https://rooftopcinemaclub.com/houston/')\n break\n elif entry == 'BlueMoon Cinemas':\n webbrowser.open('https://bmcinemas.com/index.html')\n break\n Movie_drive_in()\nchoices()","repo_name":"Jafet19/Help","sub_path":"options/expense.py","file_name":"expense.py","file_ext":"py","file_size_in_byte":9025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1889822481","text":"from fastapi import FastAPI\nfrom starlette.middleware.cors import CORSMiddleware\nimport uvicorn\nfrom fastapi.staticfiles import StaticFiles\n\napp = FastAPI()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"]\n)\n\n\napp.mount(\"/web\", StaticFiles(directory=\"./web\", html=True), name=\"web\")\n\n\ndef main():\n uvicorn.run(__name__ + \":app\", host=\"192.168.1.1\", port=3001, reload=True)\n\n\nif __name__ == \"__main__\":\n\n main()\n#\n","repo_name":"Tand0/Flutter_Example","sub_path":"pythonweb/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21905840882","text":"def turnAround(proc,wt,tat,n):\r\n for i in range(n):\r\n tat[i]=wt[i]+proc[i][1]\r\n\r\ndef findWaiting(proc,wt,n):\r\n wt[0]=0\r\n for i in range(1,n):\r\n wt[i]=proc[i-1][1]+wt[i-1]\r\n\r\ndef findAvg(proc,n):\r\n wt=[0]*n\r\n tat=[0]*n\r\n findWaiting(proc,wt,n)\r\n turnAround(proc,wt,tat,n)\r\n for i in range(n):\r\n print(proc[i][1],\" \",wt[i],\" \",tat[i],\" \")\r\ndef findPriority(proc,n):\r\n proc=sorted(proc,key=lambda proc: proc[2], reverse=True)\r\n print(\"Shorted list which will executed:\")\r\n for i in proc:\r\n print(i[0],\" \")\r\n findAvg(proc,n)\r\n\r\nif __name__==\"__main__\":\r\n proc=[[1, 10, 1],\r\n [2, 5, 0],\r\n [3, 8, 1]]\r\n n=3\r\n findPriority(proc,n)\r\n","repo_name":"Nirob-0812/AllTaskOfVarsity","sub_path":"CSE310/fortest.py","file_name":"fortest.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9315484017","text":"import csv\nimport sys\nimport math\nfrom reddit import *\nfrom line import *\nfrom point import *\nfrom path import *\nfrom analytics_combined import *\n\ndef time_analysis(filename):\n # locations = store_locations(\"atlas.json\")\n locations = store_locations(\"atlas_complete.json\")\n project_time = dict()\n with open(filename,'r') as file:\n # Skip first line (header row)\n next(file, None)\n \n reader = csv.reader(file)\n\n for r in reader:\n time = int(r[0])\n \n x = float(r[2])\n y = float(r[3])\n\n boundary_list = create_sorted_lists(locations)\n filter_lists(Point(x,y), boundary_list)\n for boundary in boundary_list:\n pic_id = boundary[0]\n path = locations.get(pic_id)\n if ( path.pixel_is_in_image(Point(x,y))):\n if project_time.get(pic_id) is None:\n project_time[pic_id] = {\"oldest\": time, \"newest\": time}\n else:\n if time < project_time.get(pic_id)[\"oldest\"]:\n project_time[pic_id][\"oldest\"] = time\n if time > project_time.get(pic_id)[\"newest\"]:\n project_time[pic_id][\"newest\"] = time\n\n with open(\"times_per_project.csv\",'w') as fileOut:\n writer = csv.writer(fileOut, delimiter = \",\")\n writer.writerow([\"Pic ID\", \"Newest Time\", \"Oldest Time\", \"Duration\"])\n for pic_id in project_time:\n newest_time = project_time.get(pic_id).get(\"newest\")\n oldest_time = project_time.get(pic_id).get(\"oldest\")\n duration = newest_time - oldest_time\n writer.writerow([pic_id, newest_time, oldest_time, duration])\n\n\ntime_analysis(\"final_canvas_tile_placements.csv\")\n","repo_name":"meredithxu/reddit_place_project","sub_path":"Python_code/time_analytics.py","file_name":"time_analytics.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"74893034961","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nAdvent of Code 2020 - Day 5 - Challenge 1\nhttps://adventofcode.com/2020/day/5\n\nSolution: 890\n\"\"\"\n\n__author__ = \"Filippo Corradino\"\n__email__ = \"filippo.corradino@gmail.com\"\n\n\ndef parse_tickets_id(ifile):\n with open(ifile) as file:\n for line in file:\n row = int(line[:7].replace('F', '0').replace('B', '1'), base=2)\n col = int(line[7:].replace('L', '0').replace('R', '1'), base=2)\n yield 8*row + col\n\n\ndef main(ifile='inputs/day_05_input.txt'):\n \"\"\"\n We'll use the fact that a ticket can be interpreted as two binary numbers\n E.g. FBFBBFF-RLR: FBFBBFF = 1010011 for the row, RLR = 101 for the column\n \"\"\"\n max_id = max(parse_tickets_id(ifile))\n print(f\"\\nThe max ticket ID is {max_id}\\n\")\n return max_id\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"filippocorradino/advent_of_code_2020","sub_path":"day05_1.py","file_name":"day05_1.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28008852","text":"# The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality\n# P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.\n# Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009.\n\nimport os\nimport warnings\nimport sys\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import ElasticNet\n\nimport mlflow\nimport mlflow.sklearn\nfrom time import time\nimport random\n\nimport logging\nlogging.basicConfig(level=logging.WARN)\nlogger = logging.getLogger(__name__)\n\n\ndef eval_metrics(actual, pred):\n rmse = np.sqrt(mean_squared_error(actual, pred))\n mae = mean_absolute_error(actual, pred)\n r2 = r2_score(actual, pred)\n return rmse, mae, r2\n\n\n\nif __name__ == \"__main__\":\n warnings.filterwarnings(\"ignore\")\n np.random.seed(42)\n\n # Read the wine-quality csv file from the URL\n FILENAME = \"winequality-red.csv\"\n csv_url = \\\n f\"http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/{FILENAME}\"\n\n if os.path.isfile(FILENAME):\n data = pd.read_csv(FILENAME, sep=\";\")\n else:\n try:\n data = pd.read_csv(csv_url, sep=\";\")\n except Exception as e:\n message = (f\"Unable to download training & test CSV, check your\\n\"\n \"internet connection. Error: {e}\") \n logger.exception(message)\n finally:\n sys.exit(1)\n\n\n # Split the data into training and test sets. (0.75, 0.25) split.\n train, test = train_test_split(data)\n\n # The predicted column is \"quality\" which is a scalar from [3, 9]\n train_x = train.drop([\"quality\"], axis=1)\n test_x = test.drop([\"quality\"], axis=1)\n train_y = train[[\"quality\"]]\n test_y = test[[\"quality\"]]\n\n # TALK NOTE Linear regression with combined L1 and L2 priors as regularizer.\n # alpha is weighting both losses ( how regularization we want) \n # 0 l1_ratio is mixing paramter, regularizing using ush L2 regularization\n # This\"ll set both params to 0.5 by default \n\n alpha = float(sys.argv[1]) if len(sys.argv) > 1 else 0.5 \n l1_ratio = float(sys.argv[2]) if len(sys.argv) > 2 else 0.5\n\n # TALK NOTE couldn't get this to work well by just setting the env variable\n # remote_server_uri = os.environ.get(\"MLFLOW_TRACKING_URL\", None) # set to your server URI\n # mlflow.set_tracking_uri(remote_server_uri)\n\n # TALK NOTE mlflow.start_run() return a ActiveRun with serves as a context manager\n # also create mlruns/ dir that support the ui (if the folder doesn\"t exit)\n with mlflow.start_run(): # \n lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, random_state=42)\n lr.fit(train_x, train_y)\n \n # TALK NOTE let time these predictions\n start_time = time()\n predicted_qualities = lr.predict(test_x)\n time_cost = time() - start_time\n (rmse, mae, r2) = eval_metrics(test_y, predicted_qualities)\n\n print(\"Elasticnet model (alpha=%f, l1_ratio=%f):\" % (alpha, l1_ratio))\n print(\" RMSE: %s\" % rmse)\n print(\" MAE: %s\" % mae)\n print(\" R2: %s\" % r2)\n\n # TALK NOTE let make slightly interesting\n # by addding a random inference speed\n # which we calling 'time_cost'\n mlflow.log_param(\"alpha\", alpha)\n mlflow.log_param(\"l1_ratio\", l1_ratio)\n mlflow.log_metric(\"rmse\", rmse)\n mlflow.log_metric(\"r2\", r2)\n mlflow.log_metric(\"mae\", mae)\n mlflow.log_metric(\"time_cost\",\n random.randint(0, 10))\n\n # TALK NOTE we\"re also serializing the elastic net model to disk\n mlflow.sklearn.log_model(sk_model=lr, \n artifact_path=\"model\",\n # registered_model_name=\"WineClassifier\" \n )\n","repo_name":"orsonadams/experiment-tracking-talk","sub_path":"examples/sklearn_elasticnet_wine/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19541400660","text":"import pytest\nimport requests\nimport gmaps\nimport wikipedia\nimport json\nimport os\nimport geojson\nimport re\n\n\ndef test_search_api_google():\n api_gmap_key = (os.environ['api_google_key'])\n url_maps = 'https://www.google.com/maps/search/?api=1&'\n search = 'ecouen'\n parameters = 'findplacefromtext/json?input=' + search + '&inputtype=textquery&fields=formatted_address,geometry,rating'\n # url_maps_json = 'https://maps.googleapis.com/maps/api/geocode/json?address='\n url_place = \"https://maps.googleapis.com/maps/api/place/\"\n response = requests.get(url_maps + search)\n assert response.status_code == 200\n response = requests.get(\n url_place + parameters + '&key=' + api_gmap_key\n )\n response_body = response.json()\n assert response_body[\n 'candidates'][0]['formatted_address'] == '95440 Écouen, France'\n\ndef test_search_api_wikipedia():\n lat_ecouen = 49.018834\n lng_ecouen = 2.378926\n list_res = [\"Château d'Écouen\", 'Écouen']\n res_wiki = wikipedia.geosearch(\n lat_ecouen, lng_ecouen)\n assert all([a == b for a, b in zip(res_wiki, list_res)])\n","repo_name":"davidbarat/P7_GrandPy-Bot","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"79511665","text":"# -*- coding: utf-8 -*-\r\n# @Author : ssbuild\r\n# @Time : 2022/11/4 13:31\r\n\r\nfrom transformers import AutoTokenizer, AutoConfig,AutoImageProcessor,AutoProcessor,AutoFeatureExtractor, CONFIG_MAPPING, PretrainedConfig\r\n\r\n__all__ = [\r\n 'load_tokenizer',\r\n 'load_configure',\r\n 'load_imageprocesser',\r\n 'load_processer',\r\n 'load_feature_extractor',\r\n]\r\n\r\ndef load_tokenizer(tokenizer_name,\r\n model_name_or_path=None,\r\n class_name = None,\r\n cache_dir=\"\",\r\n do_lower_case=None,\r\n use_fast_tokenizer=True,\r\n model_revision=\"main\",\r\n use_auth_token=None,\r\n **kwargs):\r\n tokenizer_kwargs = {\r\n \"cache_dir\": cache_dir,\r\n \"revision\": model_revision,\r\n \"use_auth_token\": True if use_auth_token else None,\r\n **kwargs\r\n }\r\n if do_lower_case is not None:\r\n tokenizer_kwargs['do_lower_case'] = do_lower_case\r\n\r\n if use_fast_tokenizer is not None:\r\n tokenizer_kwargs['use_fast'] = use_fast_tokenizer\r\n\r\n if class_name is not None:\r\n tokenizer = class_name.from_pretrained(tokenizer_name or model_name_or_path, **tokenizer_kwargs)\r\n elif tokenizer_name:\r\n tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, **tokenizer_kwargs)\r\n elif model_name_or_path:\r\n tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, **tokenizer_kwargs)\r\n else:\r\n raise ValueError(\r\n \"You are instantiating a new tokenizer from scratch. This is not supported by this script.\"\r\n \"You can do it from another script, save it, and load it from here, using --tokenizer_name.\"\r\n )\r\n return tokenizer\r\n\r\ndef load_configure(config_name,\r\n model_name_or_path=None,\r\n class_name = None,\r\n cache_dir=\"\",\r\n model_revision=\"main\",\r\n use_auth_token=None,\r\n model_type=None,\r\n config_overrides=None,\r\n bos_token_id=None,\r\n pad_token_id=None,\r\n eos_token_id=None,\r\n sep_token_id=None,\r\n return_dict=False,\r\n task_specific_params=None,\r\n **kwargs):\r\n config_kwargs = {\r\n \"cache_dir\": cache_dir,\r\n \"revision\": model_revision,\r\n \"use_auth_token\": True if use_auth_token else None,\r\n \"return_dict\": return_dict,\r\n **kwargs\r\n }\r\n tmp_kwargs = {\r\n \"bos_token_id\": bos_token_id,\r\n \"pad_token_id\": pad_token_id,\r\n \"eos_token_id\": eos_token_id,\r\n \"sep_token_id\": sep_token_id,\r\n \"task_specific_params\": task_specific_params,\r\n }\r\n for k in list(tmp_kwargs.keys()):\r\n if tmp_kwargs[k] is None:\r\n tmp_kwargs.pop(k)\r\n if tmp_kwargs:\r\n config_kwargs.update(tmp_kwargs)\r\n\r\n if class_name is not None:\r\n config = class_name.from_pretrained(config_name or model_name_or_path, **config_kwargs)\r\n elif isinstance(config_name,PretrainedConfig):\r\n for k,v in config_kwargs.items():\r\n setattr(config_name,k,v)\r\n config = config_name\r\n\r\n elif config_name:\r\n config = AutoConfig.from_pretrained(config_name, **config_kwargs)\r\n elif model_name_or_path:\r\n config = AutoConfig.from_pretrained(model_name_or_path, **config_kwargs)\r\n elif model_type:\r\n config = CONFIG_MAPPING[model_type].from_pretrained(model_name_or_path, **config_kwargs)\r\n else:\r\n raise ValueError(\r\n \"You are instantiating a new config_gpt2 from scratch. This is not supported by this script.\"\r\n \"You can do it from another script, save it, and load it from here, using --config_name.\"\r\n )\r\n if config_overrides is not None:\r\n config.update_from_string(config_overrides)\r\n return config\r\n\r\n\r\ndef load_imageprocesser(imageprocesser_name,\r\n model_name_or_path=None,\r\n class_name = None,\r\n cache_dir=\"\",\r\n model_revision=\"main\",\r\n use_auth_token=None,\r\n **kwargs):\r\n\r\n image_kwargs = {\r\n \"cache_dir\": cache_dir,\r\n \"revision\": model_revision,\r\n \"use_auth_token\": True if use_auth_token else None,\r\n **kwargs\r\n }\r\n\r\n if class_name is not None:\r\n image_processer = class_name.from_pretrained(imageprocesser_name or model_name_or_path, **image_kwargs)\r\n elif imageprocesser_name:\r\n image_processer = AutoImageProcessor.from_pretrained(imageprocesser_name, **image_kwargs)\r\n elif model_name_or_path:\r\n image_processer = AutoImageProcessor.from_pretrained(model_name_or_path, **image_kwargs)\r\n else:\r\n raise ValueError(\r\n \"You are instantiating a new imageprocesser from scratch. This is not supported by this script.\"\r\n \"You can do it from another script, save it, and load it from here, using --imageprocesser_name.\"\r\n )\r\n return image_processer\r\n\r\n\r\ndef load_processer(processer_name,\r\n model_name_or_path=None,\r\n class_name = None,\r\n cache_dir=\"\",\r\n model_revision=\"main\",\r\n use_auth_token=None,\r\n **kwargs):\r\n\r\n image_kwargs = {\r\n \"cache_dir\": cache_dir,\r\n \"revision\": model_revision,\r\n \"use_auth_token\": True if use_auth_token else None,\r\n **kwargs\r\n }\r\n\r\n if class_name is not None:\r\n processer = class_name.from_pretrained(processer_name or model_name_or_path, **image_kwargs)\r\n elif processer_name:\r\n processer = AutoProcessor.from_pretrained(processer_name, **image_kwargs)\r\n elif model_name_or_path:\r\n processer = AutoProcessor.from_pretrained(model_name_or_path, **image_kwargs)\r\n else:\r\n raise ValueError(\r\n \"You are instantiating a new processer from scratch. This is not supported by this script.\"\r\n \"You can do it from another script, save it, and load it from here, using --processer_name.\"\r\n )\r\n return processer\r\n\r\ndef load_feature_extractor(feature_extractor_name,\r\n model_name_or_path=None,\r\n class_name = None,\r\n cache_dir=\"\",\r\n model_revision=\"main\",\r\n use_auth_token=None,\r\n **kwargs):\r\n\r\n ft_kwargs = {\r\n \"cache_dir\": cache_dir,\r\n \"revision\": model_revision,\r\n \"use_auth_token\": True if use_auth_token else None,\r\n **kwargs\r\n }\r\n\r\n if class_name is not None:\r\n feature_extractor = class_name.from_pretrained(feature_extractor_name or model_name_or_path, **ft_kwargs)\r\n elif feature_extractor_name:\r\n feature_extractor = AutoFeatureExtractor.from_pretrained(feature_extractor_name, **ft_kwargs)\r\n elif model_name_or_path:\r\n feature_extractor = AutoFeatureExtractor.from_pretrained(model_name_or_path, **ft_kwargs)\r\n else:\r\n raise ValueError(\r\n \"You are instantiating a new processer from scratch. This is not supported by this script.\"\r\n \"You can do it from another script, save it, and load it from here, using --feature_extractor_name.\"\r\n )\r\n return feature_extractor\r\n\r\n","repo_name":"ssbuild/numpy_io","sub_path":"src/numpy_io/pytorch_loader/tokenizer_config_helper.py","file_name":"tokenizer_config_helper.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"32896809503","text":"from flask import Flask, render_template, url_for, request, redirect\nimport csv\napp = Flask(__name__)\n\n\n@app.route('/')\ndef my_home():\n return render_template(\"./index.html\")\n\n\n@app.route('/')\ndef html_page(page_name):\n return render_template(page_name)\n\n\ndef write_to_file(data):\n with open('database.txt', mode='a') as database:\n email = data['email']\n subject = data['subject']\n message = data['message']\n file = database.write(f'\\n{email},{subject},{message}')\n\n\ndef write_to_csv(data):\n with open('database.csv', mode='a', newline='') as database2:\n email = data['email']\n subject = data['subject']\n message = data['message']\n csv_writer = csv.writer(database2, delimiter=',',\n quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n csv_writer.writerow([email, subject, message])\n\n\n@app.route('/submit_form', methods=['POST', 'GET'])\ndef submit_form():\n if request.method == 'POST':\n try:\n data = request.form.to_dict()\n write_to_csv(data)\n return redirect('/thankyou.html')\n except:\n return 'Did not save to database'\n\n else:\n return 'something went wrong. Try again!'\n\n\n# app = Flask(__name__): to instantiate a member of the Flask class called app.\n# @app.route('/') is a generator used to create a directory on our website.\n# @app.route('/blog) is a generator used to create a sub-directory on our website.\n# Just save it as hello.py or something similar. Make sure to not call your application flask.py because this would conflict with Flask itself.\n# instead of just saving text documents into our server, flask has another function called render_template that can be used to serve html files.\n# but we need to create a folder called templates and save all the html files into this folder\n# render_template allows us to serve multiple html files at once.\n# in order to be able to serve our css and js files(flask static files),\n# we need to create a folder called static and save these files into this\n# folder.\n","repo_name":"codewithot/portfo","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40200452870","text":"import datetime as dt\nimport hashlib\nimport importlib\nimport inspect\nimport itertools\nimport logging\nimport os\nimport random\nimport re\nimport string\nimport sys\nimport traceback\nimport typing as t\nfrom collections import Iterable\nfrom contextlib import contextmanager\n\nimport netifaces\nimport requests\nimport six\nfrom cryptography.fernet import Fernet\nfrom flask import current_app\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass Singleton(type):\n \"\"\" Metaclass that creates a Singleton base type when called. \"\"\"\n _instances = {}\n\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(Singleton, cls) \\\n .__call__(*args, **kwargs)\n return cls._instances[cls]\n\n\nclass AttributeDict(dict):\n __getattr__ = dict.__getitem__\n __setattr__ = dict.__setitem__\n\n\ndef is_string_types(var):\n return isinstance(var, six.string_types)\n\n\ndef is_iterable(var):\n return isinstance(var, Iterable)\n\n\ndef is_iterable_not_string(var):\n return is_iterable(var) and not is_string_types(var)\n\n\nUUID_PATTERN = re.compile(r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')\n\n\ndef is_valid_uuid(var):\n # best performance with regular expression compiled and not using re.IGNORECASE\n if isinstance(var, str) and UUID_PATTERN.match(var):\n return True\n else:\n return False\n\n\ndef convert(d):\n for k, v in d.items():\n if isinstance(v, dict):\n d[k] = convert(v)\n return AttributeDict(d)\n\n\n# function to mock datetime.now\ndef get_now() -> dt.datetime:\n return dt.datetime.now(dt.timezone.utc)\n\n\ndef str_to_key(id_: str):\n key = []\n for x in id_.split('.'):\n try:\n x = int(x)\n except ValueError:\n pass\n finally:\n key.append(x)\n return tuple(key) if len(key) > 1 else key[0]\n\n\ndef key_to_str(key):\n if isinstance(key, t.Sequence):\n id_ = '.'.join([str(i) for i in key])\n else:\n id_ = str(key)\n return id_\n\n\ndef generate_url(destination, uri, protocol='https'):\n from dimensigon.domain.entities import Server\n try:\n forwarder = destination.mesh_best_route[0]\n except IndexError:\n forwarder = destination\n else:\n forwarder = Server.query.get(forwarder)\n\n return f\"{protocol}://{forwarder.name}:{forwarder.port}{uri}\"\n\n\ndef generate_symmetric_key():\n return Fernet.generate_key()\n\n\ndef encrypt_symmetric(data, key):\n cipher_suite = Fernet(key)\n return cipher_suite.encrypt(data)\n\n\ndef decrypt_symmetric(data, key):\n cipher_suite = Fernet(key)\n return cipher_suite.decrypt(data)\n\n\ndef encrypt(data: bytes, symmetric_key: bytes = None) -> \\\n t.Tuple[bytes, t.Optional[bytes]]:\n \"\"\"\n\n Parameters\n ----------\n data:\n data to encrypt.\n symmetric_key:\n symmetric key used for encrypting data. If set, cipher_key must be None\n\n Returns\n -------\n\n \"\"\"\n new_symmetric_key = None\n if not symmetric_key:\n symmetric_key = new_symmetric_key = generate_symmetric_key()\n cipher_data = encrypt_symmetric(data, symmetric_key)\n return cipher_data, new_symmetric_key\n\n\ndef decrypt(cipher_text: bytes, symmetric_key: bytes) -> bytes:\n \"\"\"\n\n Parameters\n ----------\n cipher_text:\n text to decrypt\n cipher_key:\n symmetric_key encrypted. If specified symmetric_key must be None (default)\n symmetric_key:\n symmetric_key. If specified cipher_token must be None (default)\n key:\n key used for decryption of cipher_key\n\n Returns\n -------\n decrypted data\n \"\"\"\n cipher_suite = Fernet(symmetric_key)\n dumped_data = cipher_suite.decrypt(cipher_text)\n return dumped_data\n\n\ndef get_logger(self=None):\n if self:\n name = '.'.join([\n self.__module__,\n self.__name__\n ])\n else:\n name = None\n try:\n current_app.logger\n except RuntimeError:\n logger = logging.getLogger(name)\n else:\n logger = current_app.logger\n return logger\n\n\ndef get_entities() -> t.List[t.Tuple['str', t.Any]]:\n from dimensigon.web import db\n entities = []\n for name, cls in inspect.getmembers(sys.modules['dimensigon.domain.entities'],\n lambda x: (inspect.isclass(x) and issubclass(x, db.Model))):\n entities.append((name, cls))\n\n return entities\n\n\ndef get_distributed_entities() -> t.List[t.Tuple['str', t.Any]]:\n from dimensigon.domain.entities.base import DistributedEntityMixin\n entities = []\n for name, cls in inspect.getmembers(sys.modules['dimensigon.domain.entities'],\n lambda x: (inspect.isclass(x) and issubclass(x, DistributedEntityMixin))):\n entities.append((name, cls)) if name == cls.__name__ else None\n\n\n return sorted(entities, key=lambda x: x[1].order or 99999)\n\n\ndef md5(fname):\n hash_md5 = hashlib.md5()\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\n\ndef get_filename_from_cd(cd):\n \"\"\"\n Get filename from content-disposition\n \"\"\"\n if not cd:\n return None\n fname = re.findall('filename=(.+)', cd)\n if len(fname) == 0:\n return None\n return fname[0]\n\n\ndef generate_dimension(name):\n from cryptography.hazmat.backends import default_backend\n from cryptography.hazmat.primitives import serialization\n from cryptography.hazmat.primitives.asymmetric import rsa\n from dimensigon.domain.entities import Dimension\n\n private_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=4096,\n backend=default_backend()\n )\n priv_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.TraditionalOpenSSL,\n encryption_algorithm=serialization.NoEncryption())\n pub_pem = private_key.public_key().public_bytes(encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.PKCS1)\n\n return Dimension(name=name, private=priv_pem, public=pub_pem)\n\n\ndef remove_prefix(s, prefix):\n return s[len(prefix):] if s.startswith(prefix) else s\n\n\ndef get_config_from_filename(filename):\n if not os.path.exists(filename):\n raise RuntimeError(\"%r doesn't exist\" % filename)\n\n ext = os.path.splitext(filename)[1]\n\n try:\n module_name = '__config__'\n if ext in [\".py\", \".pyc\"]:\n spec = importlib.util.spec_from_file_location(module_name, filename)\n else:\n msg = \"configuration file should have a valid Python extension.\\n\"\n loader_ = importlib.machinery.SourceFileLoader(module_name, filename)\n spec = importlib.util.spec_from_file_location(module_name, filename, loader=loader_)\n mod = importlib.util.module_from_spec(spec)\n sys.modules[module_name] = mod\n spec.loader.exec_module(mod)\n except Exception:\n print(\"Failed to read config file: %s\" % filename, file=sys.stderr)\n traceback.print_exc()\n sys.stderr.flush()\n sys.exit(1)\n\n return vars(mod)\n\n\nSQLITE_URL_PREFIX = \"sqlite://\"\n\n\ndef validate_sqlite_database(dbpath: str) -> bool:\n \"\"\"Run a quick check on an sqlite database to see if it is corrupt.\"\"\"\n import sqlite3 # pylint: disable=import-outside-toplevel\n\n dbpath = dbpath[len(SQLITE_URL_PREFIX):]\n\n if not os.path.exists(dbpath):\n # Database does not exist yet, this is OK\n return True\n\n try:\n conn = sqlite3.connect(dbpath)\n conn.cursor().execute(\"PRAGMA QUICK_CHECK\")\n conn.close()\n except sqlite3.DatabaseError:\n # _LOGGER.exception(\"The database at %s is corrupt or malformed.\", dbpath)\n return False\n\n return True\n\n\ndef get_ips(ipv4=True, ipv6=False) -> t.List[t.Tuple[str, int]]:\n ips = []\n\n if ipv4:\n ips.extend(list(itertools.chain(\n *[[ip['addr'] for ip in netifaces.ifaddresses(iface).get(netifaces.AF_INET, [])] for iface in\n netifaces.interfaces()])))\n if ipv6:\n iter_ips = itertools.chain(\n *[[ip['addr'] for ip in netifaces.ifaddresses(iface).get(netifaces.AF_INET6, [])] for iface in\n netifaces.interfaces()])\n\n for ip in iter_ips:\n if ip:\n if '%' in ip:\n ips.append(ip.rsplit('%')[0])\n else:\n ips.append(ip)\n return ips\n\n\ndef bind2gate(bind: t.List[str]) -> t.List[t.Tuple[str, int]]:\n from dimensigon import defaults\n specified_gates = set()\n for b in bind:\n if ':' in b:\n gate = b.rsplit(':')\n gate = (gate[0], int(gate[1]))\n else:\n gate = (b, defaults.DEFAULT_PORT)\n if gate[0] == '0.0.0.0':\n ips = get_ips(ipv4=True, ipv6=False)\n for ip in ips:\n specified_gates.update([(ip, int(gate[1]))])\n elif gate[0] == '::':\n ips = get_ips(ipv4=False, ipv6=True)\n for ip in ips:\n specified_gates.update([(ip, int(gate[1]))])\n else:\n specified_gates.update([gate])\n return list(specified_gates)\n\n\ndef clean_string(incoming_string):\n replace_char = '_'\n newstring = incoming_string\n newstring = newstring.replace(\"!\", replace_char)\n newstring = newstring.replace(\"@\", replace_char)\n newstring = newstring.replace(\"#\", replace_char)\n newstring = newstring.replace(\"$\", replace_char)\n newstring = newstring.replace(\"%\", replace_char)\n newstring = newstring.replace(\"^\", replace_char)\n newstring = newstring.replace(\"&\", replace_char)\n newstring = newstring.replace(\"*\", replace_char)\n newstring = newstring.replace(\"(\", replace_char)\n newstring = newstring.replace(\")\", replace_char)\n newstring = newstring.replace(\"+\", replace_char)\n newstring = newstring.replace(\"=\", replace_char)\n newstring = newstring.replace(\"?\", replace_char)\n newstring = newstring.replace(\"\\'\", replace_char)\n newstring = newstring.replace(\"\\\"\", replace_char)\n newstring = newstring.replace(\"{\", replace_char)\n newstring = newstring.replace(\"}\", replace_char)\n newstring = newstring.replace(\"[\", replace_char)\n newstring = newstring.replace(\"]\", replace_char)\n newstring = newstring.replace(\"<\", replace_char)\n newstring = newstring.replace(\">\", replace_char)\n newstring = newstring.replace(\"~\", replace_char)\n newstring = newstring.replace(\"`\", replace_char)\n newstring = newstring.replace(\":\", replace_char)\n newstring = newstring.replace(\";\", replace_char)\n newstring = newstring.replace(\"|\", replace_char)\n newstring = newstring.replace(\"\\\\\", replace_char)\n newstring = newstring.replace(\"/\", replace_char)\n newstring = newstring.replace(\"-\", replace_char)\n return newstring\n\n\n@contextmanager\ndef session_scope(session=None):\n \"\"\"Provide a transactional scope around a series of operations.\"\"\"\n if session is None:\n raise RuntimeError(\"Session required\")\n\n need_rollback = False\n try:\n yield session\n if session.transaction:\n need_rollback = True\n session.commit()\n except Exception as err:\n _LOGGER.error(\"Error executing query: %s\", err)\n if need_rollback:\n session.rollback()\n raise\n finally:\n session.close()\n\n\ndef format_exception(exc: Exception, with_traceback=True) -> str:\n if with_traceback:\n return ''.join(traceback.format_exception(exc, exc, exc.__traceback__))\n else:\n return str(exc) or exc.__qualname__\n\n\ndef str_resp(resp: requests.Response):\n try:\n return resp.json()\n except ValueError:\n return resp.text\n\n\ndef get_root(path: str):\n parent_path = os.path.dirname(os.path.abspath(os.path.expanduser(path)))\n if path == parent_path:\n return parent_path\n else:\n return get_root(parent_path)\n\n\ndef remove_root(path: str):\n return path.lstrip(get_root(path))\n\n\ndef get_random_string(length=8):\n letters = string.ascii_lowercase + string.digits\n return ''.join(random.choice(letters) for i in range(length))","repo_name":"dimensigon/dimensigon","sub_path":"dimensigon/utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":12339,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"36137646175","text":"import logging\nimport tkinter as tk\nfrom gui import gui_summarize\nfrom gui import gui_helpers as helper\nfrom gui import gui_analyze\nfrom gui import gui_research\n\nlogger = logging.getLogger(__name__)\n\n\nclass GUIMainMenu(tk.Tk):\n \"\"\"\n Class for create the main Form\n \"\"\"\n def __init__(self):\n \"\"\"\n Constructor for GUIMainMenu class\n \"\"\"\n super().__init__()\n\n self_width = 800\n self_height = 500\n\n center_x, center_y = helper.center_form(self, self_width, self_height) # Get center coordinates\n self.geometry(f\"{self_width}x{self_height}+{center_x}+{center_y}\")\n self.title(\"Research Tool\")\n self.configure(bg=\"#EEEEEE\")\n\n # *Build Canvas*\n\n canvas = tk.Canvas(\n self,\n bg=\"#EEEEEE\",\n height=500,\n width=800,\n bd=0,\n highlightthickness=0,\n relief=\"ridge\"\n )\n \n canvas.place(x=0, y=0)\n canvas.create_rectangle(\n 0.0,\n 0.0,\n 400.0,\n 500.0,\n fill=\"#00ADB5\",\n outline=\"\")\n \n # *Title, Description (Texts) and Images on Left Side*\n \n canvas.create_text(\n 50.0,\n 56.0,\n anchor=\"nw\",\n text=\"Research Tool\",\n fill=\"#EEEEEE\",\n font=(\"Roboto\", 48 * -1)\n )\n \n self.image_checkbox = tk.PhotoImage(\n file=helper.assets(\"img_checkbox.png\")\n )\n\n canvas.create_image(\n 96.0,\n 208.0,\n image=self.image_checkbox\n )\n \n canvas.create_image(\n 96.0,\n 273.0,\n image=self.image_checkbox\n )\n \n canvas.create_image(\n 96.0,\n 340.0,\n image=self.image_checkbox\n )\n canvas.create_image(\n 96.0,\n 406.0,\n image=self.image_checkbox\n\n )\n \n canvas.create_text(\n 125.0,\n 194.0,\n anchor=\"nw\",\n text=\"Summarize Text\",\n fill=\"#FFFFFF\",\n font=(\"Roboto\", 24 * -1)\n )\n \n canvas.create_text(\n 125.0,\n 324.0,\n anchor=\"nw\",\n text=\"Analyze Keywords\",\n fill=\"#FFFFFF\",\n font=(\"Roboto\", 24 * -1)\n )\n \n canvas.create_text(\n 125.0,\n 257.0,\n anchor=\"nw\",\n text=\"Identify Keywords\",\n fill=\"#FFFFFF\",\n font=(\"Roboto\", 24 * -1)\n )\n \n canvas.create_text(\n 125.0,\n 390.0,\n anchor=\"nw\",\n text=\"Further Research\",\n fill=\"#FFFFFF\",\n font=(\"Roboto\", 24 * -1)\n )\n \n canvas.create_text(\n 7.0,\n 481.0,\n anchor=\"nw\",\n text=\"© (2022) Christoph Beckmann\",\n fill=\"#FFFFFF\",\n font=(\"Roboto\", 12 * -1)\n )\n \n # Right Side: Subtitle and Buttons\n \n canvas.create_text(\n 415.0,\n 66.0,\n anchor=\"nw\",\n text=\"What should be done?\",\n fill=\"#222831\",\n font=(\"Roboto\", 36 * -1)\n )\n \n # *Buttons*\n\n # Summarized\n self.btn_image_Summarize = tk.PhotoImage(\n file=helper.assets(\"btn_Summarize.png\")\n )\n \n btn_summarize = tk.Button(\n self,\n image=self.btn_image_Summarize,\n borderwidth=0,\n highlightthickness=0,\n command=lambda: self.open_gui_summarize(),\n relief=\"flat\"\n )\n btn_summarize.place(\n x=500.0,\n y=197.0,\n width=200.0,\n height=58.0\n )\n\n # Keyword Analysis\n self.btn_image_Analyze = tk.PhotoImage(\n file=helper.assets(\"btn_Analyze.png\")\n )\n btn_analyze = tk.Button(\n self,\n image=self.btn_image_Analyze,\n borderwidth=0,\n highlightthickness=0,\n command=lambda: self.open_gui_analyze(),\n relief=\"flat\"\n )\n \n btn_analyze.place(\n x=500.0,\n y=288.0,\n width=200.0,\n height=58.0\n )\n\n # Further Research\n self.btn_image_Research = tk.PhotoImage(\n file=helper.assets(\"btn_Research.png\")\n )\n\n btn_research = tk.Button(\n self,\n image=self.btn_image_Research,\n borderwidth=0,\n highlightthickness=0,\n command=lambda: self.open_gui_research(),\n relief=\"flat\"\n )\n btn_research.place(\n x=500.0,\n y=379.0,\n width=200.0,\n height=58.0\n )\n\n self.btn_image_exit = tk.PhotoImage(\n file=helper.assets(\"btn_back.png\"))\n\n # Close Form\n btn_exit = tk.Button(\n self,\n image=self.btn_image_exit,\n borderwidth=0,\n highlightthickness=0,\n command=lambda: helper.close_window(self),\n relief=\"flat\"\n )\n btn_exit.place(\n x=367.0,\n y=442.0,\n width=65.0,\n height=58.0\n )\n\n self.resizable(False, False)\n\n # Functions to call TopLevel Windows\n\n def open_gui_summarize(self):\n \"\"\"\n Function to open TopLevel GUI Summarize\n \"\"\"\n form_summarize = gui_summarize.GUISummarize(self)\n form_summarize.grab_set()\n\n def open_gui_analyze(self):\n \"\"\"\n Function to open TopLevel GUI Analyze\n \"\"\"\n form_analyze = gui_analyze.GUIAnalyze(self)\n form_analyze.grab_set()\n\n def open_gui_research(self):\n \"\"\"\n Function to open TopLevel GUI Research\n \"\"\"\n form_research = gui_research.GUIResearch(self)\n form_research.grab_set()\n\n\n########################################################################################################################\n\n\nif __name__ == \"__main__\":\n # Set special variables. Python interpreter reads this first.\n # Prevent parts of code from being run when the modules are imported.\n # To get a deeper insight I used logging Package for debug, info and warning messages.\n import logging.config\n logging_config = helper.PROJECT_DIR / \"logging.conf\"\n logging.config.fileConfig(logging_config, disable_existing_loggers=False)\n\n # Create Class\n mainmenu = GUIMainMenu()\n mainmenu.mainloop()\n","repo_name":"Christoph-Beckmann/Research-Tool","sub_path":"gui/gui_mainmenu.py","file_name":"gui_mainmenu.py","file_ext":"py","file_size_in_byte":6679,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"32768940424","text":"from __future__ import division, print_function\nimport json\n\nimport numpy as np\nimport pandas as pd\nimport cooler\nimport h5py\nimport time\n\nTILESIZE = 256\n\nwhere = np.flatnonzero\nchromsizes = cooler.read_chromsizes(\n \"http://s3.amazonaws.com/pkerp/data/mm9/chromInfo.txt\"\n) # defaults to reading chr#,X,Y,M\nchromosomes = list(chromsizes.keys())\nchromid_map = dict(zip(chromosomes, range(len(chromosomes))))\ncumul_lengths = np.r_[0, np.cumsum(chromsizes)]\n\n\ndef absCoord2bin(c, pos):\n try:\n cid = where(cumul_lengths > pos)[0] - 1\n except IndexError:\n return c.info[\"nbins\"]\n chrom = chromosomes[cid]\n relPos = pos - cumul_lengths[cid]\n return c.offset((chrom, relPos, chromsizes[chrom]))\n\n\ndef getData(FILEPATH, zoomLevel, startPos1, endPos1, startPos2, endPos2):\n\n groupname = str(zoomLevel)\n\n with h5py.File(FILEPATH, \"r\") as f:\n c = cooler.Cooler(f[groupname])\n\n i0 = absCoord2bin(c, startPos1)\n i1 = absCoord2bin(c, endPos1)\n j0 = absCoord2bin(c, startPos2)\n j1 = absCoord2bin(c, endPos2)\n mat = c.matrix(balance=True)[i0:i1, j0:j1]\n\n flat = list(mat.toarray().ravel())\n\n return json.dumps({\"dense\": flat})\n\n\ndef getData2(cooler_matrix, zoomLevel, startPos1, endPos1, startPos2, endPos2):\n\n c = cooler_matrix[\"cooler\"]\n matrix = cooler_matrix[\"matrix\"]\n\n i0 = absCoord2bin(c, startPos1)\n i1 = absCoord2bin(c, endPos1)\n j0 = absCoord2bin(c, startPos2)\n j1 = absCoord2bin(c, endPos2)\n\n if (i1 - i0) == 0 or (j1 - j0) == 0:\n return pd.DataFrame(columns=[\"genome_start\", \"genome_end\", \"balanced\"])\n\n t1 = time.time()\n pixels = matrix[i0:i1, j0:j1]\n cid1 = pixels[\"chrom1\"].apply(chromid_map.get)\n cid2 = pixels[\"chrom2\"].apply(chromid_map.get)\n pixels[\"genome_start\"] = cumul_lengths[cid1] + pixels[\"start1\"]\n pixels[\"genome_end\"] = cumul_lengths[cid2] + pixels[\"end2\"]\n\n print(\"z:\", zoomLevel, \"t:\", time.time() - t1)\n return pixels[[\"genome_start\", \"genome_end\", \"balanced\"]]\n\n\ndef getData3(cooler_matrix, zoomLevel, startPos1, endPos1, startPos2, endPos2):\n c = cooler_matrix[\"cooler\"]\n\n i0 = absCoord2bin(c, startPos1)\n i1 = absCoord2bin(c, endPos1)\n j0 = absCoord2bin(c, startPos2)\n j1 = absCoord2bin(c, endPos2)\n\n if (i1 - i0) == 0 or (j1 - j0) == 0:\n return pd.DataFrame(columns=[\"genome_start\", \"genome_end\", \"balanced\"])\n\n pixels = c.matrix(as_pixels=True, max_chunk=np.inf)[i0:i1, j0:j1]\n\n if not len(pixels):\n return pd.DataFrame(columns=[\"genome_start\", \"genome_end\", \"balanced\"])\n\n lo = min(i0, j0)\n hi = max(i1, j1)\n bins = c.bins()[[\"chrom\", \"start\", \"end\", \"weight\"]][lo:hi]\n bins[\"chrom\"] = bins[\"chrom\"].cat.codes\n pixels = cooler.annotate(pixels, bins)\n pixels[\"genome_start\"] = cumul_lengths[pixels[\"chrom1\"]] + pixels[\"start1\"]\n pixels[\"genome_end\"] = cumul_lengths[pixels[\"chrom2\"]] + pixels[\"end2\"]\n pixels[\"balanced\"] = pixels[\"count\"] * pixels[\"weight1\"] * pixels[\"weight2\"]\n\n return pixels[[\"genome_start\", \"genome_end\", \"balanced\"]]\n\n\ndef getInfo(FILEPATH):\n\n with h5py.File(FILEPATH, \"r\") as f:\n total_length = int(cumul_lengths[-1])\n binsize = int(f[\"0\"].attrs[\"bin-size\"])\n binsize = 1000\n n_tiles = total_length / binsize / TILESIZE\n print(\"total_length:\", total_length, binsize, TILESIZE)\n n_zooms = int(np.ceil(np.log2(n_tiles)))\n max_width = binsize * TILESIZE * 2 ** n_zooms\n\n info = {\n \"min_pos\": [0.0, 0.0],\n \"max_pos\": [total_length, total_length],\n \"max_zoom\": n_zooms,\n \"max_width\": max_width,\n \"bins_per_dimension\": TILESIZE,\n }\n\n return info\n\n return json.dumps(info)\n","repo_name":"higlass/clodius","sub_path":"clodius/higlass_getter.py","file_name":"higlass_getter.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"3"}
+{"seq_id":"29027551237","text":"import pytest\n\nfrom django.conf import settings\nfrom django.core.management import call_command\nfrom django.utils import timezone\n\nfrom intranet.crt.core.models import PrivateKey, Certificate\nfrom intranet.crt.constants import CERT_TYPE, TASK_TYPE, ACTION_TYPE\nfrom __tests__.utils.common import create_certificate\nfrom __tests__.utils.ssl import generate_private_key\n\npytestmark = pytest.mark.django_db\n\n\ndef test_remove_private_keys_from_yav(users, certificate_types):\n cert1 = create_certificate(\n users['normal_user'],\n certificate_types[CERT_TYPE.HOST],\n uploaded_to_yav=False,\n private_key=PrivateKey.objects.create(data=generate_private_key()),\n )\n cert2 = create_certificate(\n users['normal_user'],\n certificate_types[CERT_TYPE.HOST],\n uploaded_to_yav=True,\n private_key=PrivateKey.objects.create(data=generate_private_key()),\n )\n\n old_time = timezone.now() - timezone.timedelta(settings.CRT_DAYS_TO_REMOVE_PRIVATE_KEYS + 1)\n Certificate.objects.filter(pk=cert2.pk).update(issued=old_time)\n\n call_command(TASK_TYPE.REMOVE_PRIVATE_KEYS)\n\n cert1.refresh_from_db()\n cert2.refresh_from_db()\n\n assert cert1.private_key_id\n assert not cert2.private_key_id\n assert cert1.actions.filter(type=ACTION_TYPE.CERT_PRIVATE_KEY_DELETED).count() == 0\n assert cert2.actions.filter(type=ACTION_TYPE.CERT_PRIVATE_KEY_DELETED).count() == 1\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Intranet/tests/tasks/test_remove_private_keys.py","file_name":"test_remove_private_keys.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31746199660","text":"from tkinter import *\r\n\r\n\r\nwindow=Tk()\r\n\r\ndef convert():\r\n print(e1_value.get())\r\n grams= float(e1_value.get())*1000\r\n pounds= float(e1_value.get())*2.20462\r\n ounces= float(e1_value.get())*35.274 \r\n t1.delete(\"1.0\", END) # Deletes the content of the Text box from start to END\r\n t1.insert(END,grams) # Fill in the text box with the value of gram variable\r\n t2.delete(\"1.0\", END)\r\n t2.insert(END,pounds)\r\n t3.delete(\"1.0\", END)\r\n t3.insert(END,ounces)\r\nb1= Button(window, text=\"convert\", command=convert)\r\nb1.grid(row=0,column=4)\r\n \r\n\r\ne2=Label(window,text=\"Kg\")\r\ne2.grid(row=0,column=0) \r\n\r\ne1_value=StringVar()\r\ne1= Entry(window, textvariable=e1_value)\r\ne1.grid(row=0, column=1)\r\n\r\nt1=Text(window, height=1, width=20)\r\nt1.grid(row=1, column=0)\r\n\r\nt2=Text(window, height=1, width=20)\r\nt2.grid(row=1, column=1)\r\n\r\nt3=Text(window, height=1, width=20)\r\nt3.grid(row=1, column=2)\r\n\r\nwindow.mainloop()","repo_name":"sakshi0710/Python_Application","sub_path":"LibraryApp/gui_sample.py","file_name":"gui_sample.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16480597608","text":"import numpy as np\nimport tensorflow as tf\nimport os\nfrom model.darknet import DarkNet448\nfrom utils.bbox_utils import bbox_iou\nimport time\n\ndarknet_cfg_path = './pre_weight/darknet19_448.cfg'\n\ndef create_cfg_dict():\n cfg = {}\n count = 0\n section_name = ''\n lines = open(darknet_cfg_path).readlines()\n for line in lines:\n line = line.strip()\n if line.startswith('['):\n section_name = line.strip('[]') + '_' + str(count)\n cfg[section_name] = {}\n count += 1\n elif line == '':\n continue\n else:\n if section_name == '':\n raise LookupError('The file format is unsupproted!')\n else:\n para_name, para_value = line.split('=')\n cfg[section_name][para_name.strip()] = para_value.strip()\n return cfg\n\n# d = create_cfg_dict()\n# print(d)\n\n\n# # test the bn initialization\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = '2'\n#\n# x = np.random.randn(1,3,3,3).astype('float32')\n# print(x.shape[-1:])\n#\n# gamma = np.array([1,2,3]).astype('float32')\n# beta = np.array([0,0,0]).astype('float32')\n# mean = np.array([0,0,0]).astype('float32')\n# var = np.array([1,1,1]).astype('float32')\n#\n# y1 = gamma*((x-mean)/np.sqrt(var+0.001))+beta\n# print(y1)\n#\n# y3 = tf.nn.batch_normalization(x, mean, var, beta, gamma, 0.001)\n#\n# gamma_init = tf.constant_initializer(gamma)\n# beta_init = tf.constant_initializer(beta)\n# mean_init = tf.constant_initializer(mean)\n# var_init = tf.constant_initializer(var)\n# y2 = tf.contrib.layers.batch_norm(x, center = True, scale = True, is_training = False,\n# param_initializers = {'gamma':gamma_init, 'beta':beta_init, 'moving_mean':mean_init, 'moving_variance':var_init})\n# with tf.Session() as sess:\n# sess.run(tf.global_variables_initializer())\n# y2 = sess.run(y2)\n# print(y2)\n# # print(y2 == x)\n# y3 = sess.run(y3)\n# print(y3)\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '2'\n# a = DarkNet448()\n# a.save_ckpt()\n# print(isinstance(a, DarkNet448))\n\n# a=[0,1,2,3]\n# b=[0,1,2,3,4]\n# c=tf.meshgrid(b,a)\n# e = tf.expand_dims(c[0], axis=0)\n\na = tf.ones((2,3))\nb = tf.cast(a>0, dtype=tf.float32)\nwith tf.Session() as sess:\n print(sess.run(b))\n # d = sess.run(c)\n # print(d[0])\n # print(d[1])\n # print(sess.run(e).shape)\n\n# a = np.array([[-1.2,-2.1, 1.2, 2.1], [-4.2,-3.1, 4.2, 3.1]])\n# b = np.array([[-1.4,-2.3, 1.4, 2.3], [-4.1,-3.2, 4.1, 3.2], [-4.0,-3.3, 4.0, 3.3]])\n# start = time.time()\n# iou = bbox_iou(a,b)\n# idx = np.argmax(iou, axis=1)\n# end = time.time()\n# print(iou)\n# print(idx)\n# print(end-start)","repo_name":"AGroupofProbiotocs/YOLO_V2_in_Tensorflow","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"74036601041","text":"from events.models import Event\nfrom events.event_types import EventTypes\nfrom posts.models import Post\n\n\nclass EventHandler:\n def __init__(self, events):\n self.events = events\n\n def process(self):\n # Update the event store.\n # Update the application state.\n # This should be a transaction.\n\n for event in self.events:\n # Event store update.\n event.save()\n\n if event.event_type == EventTypes.post_created_event:\n # Create the application state\n Post.objects.create(\n id=event.post_id,\n title=event.event_data.title,\n content=event.event_data.content,\n datetime=event.event_time\n )\n elif event.event_type == EventTypes.post_updated_event:\n # Get the post and update it.\n post = Post.objects.get(id=event.post_id)\n post.title = event.event_data.title\n post.content = event.event_data.content\n post.datetime = event.event_time\n\n post.save()\n","repo_name":"Dineshs91/django-cqrs","sub_path":"blog/events/event_handler.py","file_name":"event_handler.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"3"}
+{"seq_id":"6009116322","text":"from som.topologies import GridTopology\nfrom som import SelfOrganizingMap\n\nimport numpy as np\nimport os\nfrom collections import namedtuple\n\nSEED = 0\n\nSetup = namedtuple('Setup', 'dataset d grid_shape periodicities image_shape' )\n\nsetup_1 = Setup(dataset='uniform_colors', d=1, grid_shape=(64, 1, 1), periodicities=[True, False, False], image_shape=None)\nsetup_2 = Setup(dataset='uniform_colors', d=2, grid_shape=(8, 8, 1), periodicities=[False, False, False], image_shape=None)\nsetup_3 = Setup(dataset='uniform_colors', d=2, grid_shape=(8, 8, 1), periodicities=[True, False, False], image_shape=None)\nsetup_4 = Setup(dataset='uniform_colors', d=3, grid_shape=(4, 4, 4), periodicities=[False, False, False], image_shape=None)\nsetup_5 = Setup(dataset='color_blobs', d=1, grid_shape=(64, 1, 1), periodicities=[True, False, False], image_shape=None)\nsetup_6 = Setup(dataset='olivetti_faces', d=2, grid_shape=(20, 20, 1), periodicities=[False, False, False], image_shape=(64, 64))\nsetup_7 = Setup(dataset='cifar10', d=2, grid_shape=(16, 16, 1), periodicities=[False, False, False], image_shape=(32, 32))\nsetup_8 = Setup(dataset='digits', d=2, grid_shape=(8, 8, 1), periodicities=[False, False, False], image_shape=(8, 8))\n\nsetups = [setup_1, setup_2, setup_3, setup_4, setup_5, setup_6, setup_7, setup_8]\n\ndef load_dataset(dataset):\n DATASETS = ['uniform_colors', 'color_blobs', 'olivetti_faces', 'cifar10', 'digits']\n assert dataset in DATASETS\n\n if dataset == 'uniform_colors':\n N = 250\n\n X = np.random.rand(N, 3)\n return X, np.zeros(len(X), dtype=int)\n\n if dataset == 'color_blobs':\n from sklearn.datasets import make_blobs\n N = 250\n\n X, y = make_blobs(n_samples=N, centers=0.7*np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255]]), cluster_std=10, n_features=3)\n min = X.min()\n max = X.max()\n X = (X - min) / (max - min)\n return X, y\n\n if dataset == 'olivetti_faces':\n from sklearn.datasets import fetch_olivetti_faces\n N = None\n\n X, y = fetch_olivetti_faces(return_X_y=True)\n X, y = X[:N], y[:N]\n return X, y\n\n if dataset == 'cifar10':\n import os\n os.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\"\n import torchvision\n import torchvision.transforms as transforms\n N = 5000\n\n transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n dataset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\n X = dataset.data.reshape(len(dataset.data), -1) / 255\n y = np.array(dataset.targets)\n\n X, y = X[:N], y[:N]\n # classes = dataset.classes\n return X, y\n\n if dataset == 'digits':\n from sklearn.datasets import load_digits\n N = None\n\n X, y = load_digits(return_X_y=True)\n X /= X.max()\n\n X, y = X[:N], y[:N]\n return X, y\n\n\n\nif __name__ == '__main__':\n from matplotlib import cm\n\n for s in setups:\n\n np.random.seed(SEED)\n X, y = load_dataset(dataset=s.dataset)\n\n identifier = f\"{s.dataset}_{s.d}d_{'x'.join(list(map(str, s.grid_shape[:s.d])))}_p{'x'.join([str(int(b)) for b in s.periodicities[:s.d]])}\"\n print(\"-\"*128)\n print(\"Experiment:\\t\", identifier)\n print(\"Dataset:\\t X:\", X.shape, \"y:\", y.shape)\n print(\"-\"*128)\n\n if not os.path.isdir(os.path.join(\"imgs\", identifier)):\n os.makedirs(os.path.join(\"imgs\", identifier))\n else:\n continue\n\n NUM_COLORS = len(np.unique(y))\n colors = np.array([cm.gist_rainbow(1.*i / NUM_COLORS) for i in range(NUM_COLORS)])[:,:3]\n\n topo = GridTopology(*s.grid_shape, d=s.d, periodicities=s.periodicities)\n som = SelfOrganizingMap(topo, metric='euclidian')\n\n try:\n som.fit_and_animate(X, filename=f'{identifier}_fit_animation', rotate=True)\n except AssertionError:\n som.fit(X)\n\n som.plot_map(image_shape=s.image_shape, title=None, filename=f'imgs/{identifier}/map', animate=True)\n\n try:\n som.plot_nodes(title=None, filename=f'imgs/{identifier}/nodes', animate=True)\n except:\n pass\n\n som.plot_unified_distance_map(title=None, filename=f'imgs/{identifier}/umap', animate=False)\n som.plot_class_representation_map(y, colors, mode=\"discrete\", title=None, filename=f'imgs/{identifier}/crm', animate=False)\n","repo_name":"jonasgrebe/py-self-organizing-maps","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"}
+{"seq_id":"5057967222","text":"from django.contrib import messages\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render , get_object_or_404 , redirect\nfrom .models import OrderProducts , Order\nfrom products.models import Product\nfrom django.utils import timezone\nfrom django.http import HttpResponseRedirect\nfrom django.views.generic import DetailView ,View\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\n# Create your views here.\n@login_required\ndef add_to_cart(request,product_id):\n item = get_object_or_404(Product,id=product_id)\n order_item,created = OrderProducts.objects.get_or_create(\n product=item,\n user=request.user,\n orderd = False)\n order_qs = Order.objects.filter(user=request.user,orderd=False)\n if order_qs.exists():\n order = order_qs[0]\n if order.items.filter(product__id=item.id).exists():\n order_item.quantity +=1\n order_item.save()\n messages.info(request,'item quantity was updated')\n else:\n messages.info(request,'item added to your shoping cart')\n order.items.add(order_item)\n else:\n order_date = timezone.now()\n order = Order.objects.create(user=request.user,order_date=order_date)\n order.items.add(order_item)\n messages.info(request,'item added to your shoping cart')\n\n order.promo_discount = None\n order.save()\n \n return redirect('order-summary')\n\n@login_required\ndef remove_from_cart(request,product_id):\n item = get_object_or_404(Product,id=product_id)\n order_qs = Order.objects.filter(user=request.user,orderd=False)\n if order_qs.exists():\n order = order_qs[0]\n if order.items.filter(product__id=item.id).exists():\n order_item = OrderProducts.objects.filter(product=item,user=request.user,orderd = False)[0]\n messages.info(request,'your item removed properly')\n if order_item.quantity > 1:\n order_item.quantity -= 1\n order_item.save()\n else:\n order_item.delete()\n else:\n # item dose not exists\n messages.info(request,'item dose not exsist')\n # return redirect('product',product_id=product_id)\n return redirect('order-summary')\n else:\n # order dose not exist\n messages.info(request,'your cart is empty')\n return redirect('order-summary')\n # return redirect('product',product_id=product_id)\n order.promo_discount = None\n order.save()\n return redirect('order-summary')\n #return redirect('product',product_id=product_id)\n\n@login_required\ndef Delete_product_from_cart(request,product_id):\n item = get_object_or_404(Product,id=product_id)\n order_qs = Order.objects.filter(user=request.user,orderd=False)\n if order_qs.exists():\n order = order_qs[0]\n if order.items.filter(product__id=item.id).exists():\n order_item = OrderProducts.objects.filter(product=item,user=request.user,orderd = False)[0]\n messages.info(request,'your item Deleted')\n order_item.delete()\n else:\n # item dose not exists\n messages.info(request,'item dose not exsist')\n # return redirect('product',product_id=product_id)\n return redirect('order-summary')\n else:\n # order dose not exist\n messages.info(request,'your cart is empty')\n return redirect('order-summary')\n # return redirect('product',product_id=product_id)\n order.promo_discount = None\n order.save()\n return redirect('order-summary')\n #return redirect('product',product_id=product_id)\n\nclass AddToCart(LoginRequiredMixin,View):\n def post(self,*args,**kwargs):\n pass\n\n\nclass OrderSummaryView(LoginRequiredMixin,View):\n def get(self,*args,**kwargs):\n try:\n order = Order.objects.get(user=self.request.user,orderd=False)\n context = {\n 'object':order,\n }\n return render(self.request,'cart/order_summary.html',context=context)\n except ObjectDoesNotExist:\n return redirect('index')\n","repo_name":"mahanfarzaneh2000/DjangoEcommerce","sub_path":"cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"13644646359","text":"import re\r\nimport pkg_resources\r\n\r\ndef find_bank(context):\r\n # 用正則找到判決書中的車牌並回傳位置\r\n # context: string 整篇或部分判決書\r\n resource_filename = pkg_resources.resource_filename(__name__, 'assets/banklist.txt') # 尋找package底下的檔案路徑\r\n f = open(resource_filename, 'r',encoding='utf-8')\r\n bank_rgs = r\"(\"\r\n for line in f.readlines():\r\n bank_rgs += line.replace('\\n','') + '|'\r\n bank_rgs = bank_rgs[:-1] + ')'\r\n regex = \"((.{0,10})(銀行|郵局|郵政|信託|世華|金庫|商銀|企銀|開發|信合社|漁會|農會|信用合作社|中央信託局)(.{0,5})(帳號|帳戶)?(?:(?!年|元|月|萬|千|百|第)\\w)(.{0,15})(?:(?!年|元|月|萬|千|百|第)\\w)[0-9]{1,7}(-|─|-|—|–)?(?:(?!年|元|月|萬|千|百|第)\\w)[0-9]{3,15}(.{0,9})(-|─|-|—|–)?[0-9]{0,3}(帳戶|存簿))|((.{0,8})(銀行|郵局|郵政|信託|世華|金庫|商銀|企銀|開發|信合社|漁會|農會|信用合作社|中央信託局)+(.{0,15})(帳號|帳戶|局號)(.{0,15})(?:(?!年|元|月|萬|千|百|第)\\w)[0-9]{1,7}(-|─|-|—|–)?(?:(?!年|元|月|萬|千|百|第)\\w)[0-9]{3,15}[^至](-|─|-|—|–)?[0-9]{0,3}(?:(?!年|元|月|萬|千|百|第)\\w)(號)?(帳戶)?(、)?[0-9]*)\"\r\n\r\n\r\n match = re.finditer(regex, context)\r\n \r\n bank_list = []\r\n \r\n for one in match:\r\n# print(one)\r\n bank_name=''\r\n start=one.span()[0]\r\n orgin_start=start\r\n end=one.span()[1]\r\n orgin_end=end\r\n value=context[start:end]\r\n if value.find('函') !=-1 or value.find('明細') !=-1:\r\n continue\r\n \r\n \r\n regex_bankaccount=\"[0-9]{0,3}(-|─|-|—|–)?[0-9]{0,3}(-|─|-|—|–)?[0-9]{1,7}(-|─|-|—|–)?(?:(?!年|元|月|萬|千|百|第)\\w)[0-9]{3,15}(-|─|-|—|–)?[0-9]{0,8}\"\r\n match_bankaccount=re.finditer(regex_bankaccount, value)\r\n bank_accounts=[]\r\n for i in match_bankaccount:\r\n account_start=i.span()[0]\r\n account_end=i.span()[1]\r\n bank_accounts.append(value[account_start:account_end])\r\n\r\n start+=account_start\r\n end=start+account_end-account_start\r\n branch=''\r\n bank_name_start=0\r\n match_bankname=re.finditer(bank_rgs, value)\r\n for j in match_bankname:\r\n# print(j)\r\n \r\n if bank_name_start= len(input_fields):\n result = self._opts.get('missing', lambda s: None)(input_fields)\n else:\n result = (input_fields[input_fieldnum]\n or self._opts.get('empty',\n lambda s: '')(input_fields))\n if result is not None:\n if 'noboundaries' in self._opts:\n # sys.stderr.write(result)\n result = self._make_lemma_without_boundaries(\n result,\n input_fields[self._input_field_nums.get('word')])\n # sys.stderr.write(' -> ' + result + '\\n')\n if 'set' in self._opts or 'setconvert' in self._opts:\n result = fix_feature_set_attr(result,\n self._opts.get('unique'))\n elif 'setfirst' in self._opts:\n if result.startswith('|'):\n result = result[1:]\n result = result.split('|', 1)[0]\n elif 'setlast' in self._opts:\n if result.endswith('|'):\n result = result[:-1]\n result = result.split('|')[-1]\n if self._opts.get('setconvert'):\n result = result.replace('|', self._opts['setconvert'])\n if 'set' in self._opts:\n if self._char_encode_maps['set']:\n result = replace_substrings(\n result, self._char_encode_maps['set'])\n elif self._char_encode_maps['base']:\n result = replace_substrings(\n result, self._char_encode_maps['base'])\n return result\n\n def _make_lemma_without_boundaries_simple(self, lemma, wordform):\n return (self._compound_boundary_re.sub('', lemma)\n if len(lemma) > 2\n else lemma)\n\n # Adapted from vrt-add-parses.py\n def _make_lemma_without_boundaries_tdt(self, lemma, wordform):\n if len(lemma) < 3 or not self._compound_boundary_re.search(lemma):\n return lemma\n elif '-' not in wordform:\n return self._compound_boundary_re.sub('', lemma)\n else:\n # In some cases, the lemma has - replaced with a |; in\n # other cases not\n wordform_parts = wordform.split('-')\n lemma_parts = self._compound_boundary_re.split(lemma)\n if (len(wordform_parts) == len(lemma_parts)\n and '-' not in lemma):\n return self._compound_boundary_re.sub('-', lemma)\n else:\n lemma_without_boundaries = [lemma_parts[0]]\n lemma_prefix_len = len(lemma_parts[0])\n wf_prefix_len = len(wordform_parts[0])\n wf_partnr = 1\n for lemma_part in lemma_parts[1:]:\n if wf_partnr >= len(wordform_parts):\n lemma_without_boundaries.append(lemma_part)\n elif (lemma_part[:2] == wordform_parts[wf_partnr][:2]\n and abs(wf_prefix_len - lemma_prefix_len) <= 2):\n # FIXME: Devise a better heuristic\n lemma_without_boundaries.extend(['-', lemma_part])\n wf_prefix_len += len(wordform_parts[wf_partnr])\n wf_partnr += 1\n else:\n lemma_without_boundaries.append(lemma_part)\n lemma_prefix_len += len(lemma_part)\n return ''.join(lemma_without_boundaries)\n\n def get_input_fieldnum(self):\n return self._input_fieldnum\n\n def __repr__(self):\n return str(self._input_fieldnum) + ':' + repr(self._opts)\n\n def __init__(self, input_fields, output_fields, strip=False,\n empty_values=None, missing_values=None,\n copy_extra_fields=None, char_encode_maps=None,\n compound_boundary_marker=None,\n compound_boundary_hyphen=False):\n self._compound_boundary_marker = compound_boundary_marker\n self._compound_boundary_hyphen = compound_boundary_hyphen\n self._make_input_fields(input_fields)\n self._copy_extra_fields = value_or_default(copy_extra_fields,\n not output_fields)\n self._empty_field_values = self._make_default_field_values(empty_values)\n self._missing_field_values = self._make_default_field_values(\n missing_values)\n self._make_output_fields(output_fields, char_encode_maps)\n output_field_fieldnums = [output_field.get_input_fieldnum()\n for output_field in self._output_fields]\n self._max_fieldnum = max((output_field_fieldnums\n + list(self._empty_field_values.keys())\n + list(self._missing_field_values.keys()))\n or [-1])\n # print self._output_fields, output_field_fieldnums, self._max_fieldnum\n for num in range(max(output_field_fieldnums or [-1]) + 1,\n self._max_fieldnum + 1):\n opts = {}\n if num in self._set_fields:\n opts['set'] = True\n self._output_fields.append(\n self.OutputFieldSpec(\n str(num + 1), self._input_fields,\n compound_boundary_marker=self._compound_boundary_marker,\n compound_boundary_hyphen=self._compound_boundary_hyphen,\n options=opts))\n for type_, values in [('empty', self._empty_field_values),\n ('missing', self._missing_field_values)]:\n self._add_default_fieldvals(type_, values)\n # print self._output_fields\n self._strip = strip\n\n def _make_input_fields(self, fields):\n if fields:\n fieldlist = ' '.join(fields).strip().split()\n self._set_fields = set(num for num, name in enumerate(fieldlist)\n if name[-1] == '/')\n self._input_fields = dict((name, num)\n for num, name in enumerate(fieldlist))\n self._input_fields.update(dict((name.strip('/'), num)\n for num, name in enumerate(fieldlist)\n if name[-1] == '/'))\n else:\n self._set_fields = set()\n self._input_fields = {}\n\n def _make_default_field_values(self, fieldspec):\n if not fieldspec:\n return {}\n fieldvals_list = re.split(r'\\s*;\\s*', fieldspec)\n fieldvals = {}\n for field_numval in fieldvals_list:\n (fieldnumstr, fieldval) = re.split(r'\\s*:\\s*', field_numval)\n fieldnums = self._extract_fieldnums(fieldnumstr)\n for fieldnum in fieldnums:\n fieldvals[fieldnum] = fieldval\n return fieldvals\n\n def _extract_fieldnums(self, fieldnumstr):\n result = []\n for fieldrange in re.split(r'\\s*,\\s*', fieldnumstr):\n if fieldrange == '*':\n result.append(-1)\n else:\n if '-' in fieldrange:\n (start, end) = fieldrange.split('-', 1)\n else:\n start = end = fieldrange\n start = self._get_fieldnum(start)\n end = self._get_fieldnum(end)\n result.extend(list(range(start, end + 1)))\n return result\n\n def _get_fieldnum(self, num_or_name):\n if re.match(r'^\\d+$', num_or_name):\n return int(num_or_name) - 1\n else:\n return self._input_fields.get(num_or_name)\n\n def _make_output_fields(self, output_fieldslist, char_encode_maps):\n self._output_fields = []\n output_field_kwargs = dict(\n char_encode_maps=char_encode_maps,\n compound_boundary_marker=self._compound_boundary_marker,\n compound_boundary_hyphen=self._compound_boundary_hyphen)\n if output_fieldslist:\n for fields in output_fieldslist:\n fieldspecs = re.findall(r'(?:\\S|\\'[^\\']+\\'|\"[^\\\"]+\")+', fields)\n # print repr(fieldspecs)\n for fieldspec in fieldspecs:\n self._output_fields.append(\n self.OutputFieldSpec(\n fieldspec, self._input_fields,\n **output_field_kwargs))\n self._extra_output_field = self.OutputFieldSpec(\n '0', self._input_fields, **output_field_kwargs)\n\n def _add_default_fieldvals(self, type_, values):\n for fieldnum, fieldval in list(values.items()):\n if fieldnum != -1 and fieldnum <= self._max_fieldnum:\n self._output_fields[fieldnum].set_option(type_, fieldval)\n if -1 in values:\n for field in self._output_fields + [self._extra_output_field]:\n field.set_option(type_, values[-1], override=True)\n\n def convert_line(self, line, fieldsep='\\t'):\n return fieldsep.join(self.convert(line.strip().split(fieldsep)))\n\n def convert(self, fields):\n outfields = []\n\n def add_output_field(fields, outfield_spec, fieldnum=None):\n outfield = outfield_spec.make_field(fields, fieldnum)\n if outfield is not None:\n outfields.append(outfield)\n\n # print fields, self._output_fields, self._copy_extra_fields\n if self._strip:\n fields = [field.strip() for field in fields]\n for output_field in self._output_fields:\n add_output_field(fields, output_field)\n if self._copy_extra_fields:\n for fieldnum in range(self._max_fieldnum + 1, len(fields)):\n add_output_field(fields, self._extra_output_field, fieldnum)\n return outfields\n\n\nclass AttributeFixer:\n\n _xml_char_entities = {'quot': '\"',\n 'amp': '&',\n 'apos': '\\'',\n 'lt': '<',\n 'gt': '>'}\n _xml_char_entities_rev = dict(\n (val, key) for key, val in _xml_char_entities.items())\n _xml_char_entity_name_regex = \\\n r'#x[0-9a-fA-F]+|#[0-9]+|' + '|'.join(list(_xml_char_entities.keys()))\n\n def __init__(self, opts):\n self._opts = opts\n if self._opts.angle_brackets:\n self._opts.angle_brackets = self._opts.angle_brackets.split(',', 1)\n self._split_lines = (self._opts.compound_boundaries != 'keep'\n or self._opts.strip\n or self._opts.empty_field_values\n or self._opts.missing_field_values\n or self._opts.input_fields\n or self._opts.output_fields)\n self._encode_posattrs = (self._opts.encode_special_chars\n in ['all', 'pos'])\n self._encode_structattrs = (self._opts.encode_special_chars\n in ['all', 'struct'])\n self._special_char_encode_maps = {}\n self._special_char_encode_maps['base'] = [\n (c, (opts.encoded_special_char_prefix\n + chr(i + opts.encoded_special_char_offset)))\n for (i, c) in enumerate(opts.special_chars)]\n self._special_char_encode_maps['set'] = [\n (key, val) for key, val in self._special_char_encode_maps['base']\n if key != '|']\n if self._split_lines:\n self._make_pos_attr_converter()\n self._elem_renames = {}\n self._elem_ids = {}\n for rename_elem_str in self._opts.rename_element:\n for rename_spec in re.split(r'\\s*[,\\s]\\s*', rename_elem_str):\n oldname, newname = rename_spec.split(':')\n self._elem_renames[oldname] = newname\n for elemnames_str in self._opts.add_element_id:\n elemnames = re.split(r'\\s*[,\\s]\\s*', elemnames_str)\n for elemname in elemnames:\n self._elem_ids[elemname] = 0\n self._set_struct_attrs = self._init_set_struct_attrs()\n self._init_struct_attr_copy_info()\n\n def _make_pos_attr_converter(self):\n\n def make_field_list(last):\n return ' '.join(str(fieldnum + 1) for fieldnum in range(last))\n\n copy_extra_fields = None\n output_fields = self._opts.output_fields\n if not self._opts.output_fields:\n copy_extra_fields = True\n if self._opts.compound_boundaries == 'remove':\n output_fields = [(make_field_list(self._opts.lemma_field)\n + ':noboundaries')]\n elif self._opts.compound_boundaries == 'new':\n output_fields = [(\n make_field_list(self._opts.noncompound_lemma_field - 1)\n + ' ' + str(self._opts.lemma_field) + ':noboundaries')]\n # print repr(output_fields)\n char_encode_maps = (\n self._special_char_encode_maps if self._encode_posattrs\n else None)\n self._pos_attr_converter = PosAttrConverter(\n self._opts.input_fields, output_fields, strip=self._opts.strip,\n empty_values=self._opts.empty_field_values,\n missing_values=self._opts.missing_field_values,\n copy_extra_fields=copy_extra_fields,\n char_encode_maps=char_encode_maps,\n compound_boundary_marker=self._opts.compound_boundary_marker,\n compound_boundary_hyphen=self._opts.compound_boundary_hyphen)\n\n def _init_set_struct_attrs(self):\n set_struct_attrs = {}\n if self._opts.set_struct_attributes:\n for attr_spec_list in self._opts.set_struct_attributes:\n for attr_spec in attr_spec_list.split():\n if ':' in attr_spec:\n elemname, attrnames_str = attr_spec.split(':', 1)\n attrnames = set(re.split(r'[,+]', attrnames_str))\n elem_attrs = set_struct_attrs.setdefault(elemname,\n set())\n elem_attrs |= attrnames\n elif '_' in attr_spec:\n elemname, attrname = attr_spec.split('_', 1)\n elem_attrs = set_struct_attrs.setdefault(elemname,\n set())\n elem_attrs |= set([attrname])\n return set_struct_attrs\n\n def _init_struct_attr_copy_info(self):\n self._struct_attr_values = defaultdict(dict)\n self._struct_attr_copy_sources = defaultdict(set)\n self._struct_attr_copy_targets = defaultdict(list)\n for copyspec in self._opts.copy_struct_attribute:\n target, sources = re.split(r'\\s*:\\s*', copyspec, 1)\n sourcelist = re.split(r'\\s*;\\s*', sources)\n for source in sourcelist:\n elem, attrs = re.split(r'\\s*/\\s*', source, 1)\n attrlist = re.split(r'\\s*,\\s*', attrs)\n for attr in attrlist:\n self._struct_attr_copy_sources[elem].add(attr)\n self._struct_attr_copy_targets[target].append((elem, attr))\n # print self._struct_attr_copy_sources, self._struct_attr_copy_targets\n\n def process_files(self, files):\n if isinstance(files, list):\n for file_ in files:\n self.process_files(file_)\n elif isinstance(files, str):\n with open(files, 'r', encoding='utf-8-sig',\n errors=self._opts.encoding_errors) as f:\n self._fix_input(f)\n else:\n self._fix_input(files)\n\n def _fix_input(self, f):\n linenr = 1\n try:\n for line in korputil.whole_line_reader(f):\n sys.stdout.write(self._make_fixed_line(line))\n linenr += 1\n except SyntaxError:\n raise\n except Exception:\n sys.stderr.write(\n ('{prog}: An exception occurred while processing file {fname}'\n ', line {linenr} (approximately):\\n')\n .format(prog=sys.argv[0], fname=f.name, linenr=linenr))\n raise\n\n def _make_fixed_line(self, line):\n if re.match(r'^?[a-z0-9_]+(\\s([^>\\\"]|\\\"[^\\\"]*\\\")+)?>$',\n line.rstrip()):\n line = self._fix_structattrs(line.rstrip()) + '\\n'\n if self._encode_structattrs and line[1] != '/':\n return self._encode_special_chars_in_struct_attrs(line)\n else:\n return line\n elif line[0] == '<' and line[1] in '!?':\n return line\n else:\n return self._fix_posattrs(line)\n\n def _fix_posattrs(self, line):\n if self._opts.replace_xml_character_entities != 'none':\n line = self._replace_character_entities(line)\n if self._split_lines:\n attrs = line[:-1].split('\\t')\n attrs = self._pos_attr_converter.convert(attrs)\n line = '\\t'.join(attrs) + '\\n'\n if self._opts.space:\n line = line.replace(' ', self._opts.space)\n if self._opts.angle_brackets:\n line = (line.replace('<', self._opts.angle_brackets[0])\n .replace('>', self._opts.angle_brackets[1]))\n if self._encode_posattrs and not self._split_lines:\n line = self._encode_special_chars(line)\n line = self._fix_ampersands(line)\n return line\n\n def _encode_special_chars(self, s, encode_map_key='base'):\n \"\"\"Encode the special characters in s.\"\"\"\n return replace_substrings(\n s, self._special_char_encode_maps.get(encode_map_key, []))\n\n def _encode_special_chars_in_struct_attrs(self, s):\n \"\"\"Encode the special characters in the double- or single-quoted\n substrings of s.\n \"\"\"\n\n def encode_attr(mo, encode_map_key=None, elemname=None):\n encode_map_key = encode_map_key or (\n 'set' if (mo.group(1) in\n self._set_struct_attrs.get(elemname, set()))\n else 'base')\n # Strip possible whitespace around the equals sign.\n return (mo.group(1) + '='\n + self._encode_special_chars(mo.group(2), encode_map_key))\n\n elemname = re.search(r'(\\w+)', s).group(1)\n encode_map_key = None if elemname in self._set_struct_attrs else 'base'\n return re.sub(r'''(\\w+)\\s*=\\s*(\".*?\"|'.*?')''',\n lambda mo: encode_attr(mo, elemname=elemname,\n encode_map_key=encode_map_key), s)\n\n def _replace_character_entities(self, line, retain=None):\n numeric_only = (self._opts.replace_xml_character_entities\n in ['numeric', 'correctnumeric'])\n retain = retain or []\n\n def replace_char_entity_ref(matchobj):\n name = matchobj.group(1)\n if (name in self._xml_char_entities and not numeric_only\n and name not in retain):\n return self._xml_char_entities[name]\n elif name[0] == '#':\n chrval = (int(name[2:], base=16)\n if name[1] == 'x'\n else int(name[1:]))\n if chrval < 32:\n return name\n try:\n char = chr(chrval)\n except ValueError:\n return name\n if numeric_only and char in self._xml_char_entities_rev:\n return '&' + self._xml_char_entities_rev[char] + ';'\n else:\n return char\n else:\n return '&' + name + ';'\n\n line = re.sub(r'&(' + self._xml_char_entity_name_regex + r');',\n replace_char_entity_ref, line)\n if self._opts.replace_xml_character_entities in ['all', 'numeric']:\n line = re.sub(r'&(' + self._xml_char_entity_name_regex + r')(?=\\s)',\n replace_char_entity_ref, line)\n return line\n\n def _fix_ampersands(self, line):\n \"\"\"Replace ampersands with &: they always need to be encoded\"\"\"\n\n if '&' not in line:\n return line\n # First encode & in valid (numeric or predefined) XML\n # character entity references as \\x01, then replace the rest\n # with & and finally restore the correct ampersands. Could\n # we do this with a single regexp substitution and an\n # appropriate substitution function?\n line = re.sub(\n r'&(?=(?:amp|apos|gt|lt|quot|#(?:[0-9]+|x[0-9a-fA-F]+));)',\n '\\x01', line)\n line = line.replace('&', '&')\n return line.replace('\\x01', '&')\n\n def _fix_structattrs(self, line):\n if self._elem_renames:\n line = self._rename_elem(line)\n if line.startswith(''):\n if self._struct_attr_values:\n elemname = line[2:-2]\n if elemname in self._struct_attr_values:\n del self._struct_attr_values[elemname]\n else:\n if self._opts.replace_xml_character_entities != 'none':\n line = self._replace_character_entities(line,\n retain=['quot', 'apos'])\n if self._elem_ids:\n line = self._add_elem_id(line)\n if self._struct_attr_copy_sources:\n line = self._copy_struct_attrs(line)\n if self._set_struct_attrs:\n line = self._fix_set_struct_attrs(line)\n line = self._fix_ampersands(line)\n return line\n\n def _rename_elem(self, line):\n\n def rename_elem(matchobj):\n name = matchobj.group(2)\n return matchobj.group(1) + (self._elem_renames.get(name) or name)\n\n return re.sub(r'(?)(\\w+)', rename_elem, line)\n\n def _add_elem_id(self, line):\n elemname = re.search(r'(\\w+)', line).group(1)\n if elemname in self._elem_ids:\n self._elem_ids[elemname] += 1\n line = self._add_attrs(line,\n [('id', str(self._elem_ids[elemname]))])\n return line\n\n def _add_attrs(self, line, attrs):\n return (line[:-1] + ' '\n + ' '.join(name + '=\"' + val + '\"' for name, val in attrs)\n + line[-1:])\n\n def _copy_struct_attrs(self, line):\n # print self._struct_attr_values\n elemname = re.search(r'(\\w+)', line).group(1)\n if elemname in self._struct_attr_copy_sources:\n self._struct_attr_values[elemname] = \\\n self._extract_struct_attrs(line)\n if elemname in self._struct_attr_copy_targets:\n line = self._add_attrs(\n line, [(src_elem + '_' + attrname, value)\n for (src_elem, attrname, value)\n in self._get_struct_attr_values(\n self._struct_attr_copy_targets[elemname])])\n return line\n\n def _extract_struct_attrs(self, line):\n return dict((name, val.replace('\"', '"')) for name, _, val in\n re.findall(r'''(\\w+)\\s*=\\s*([\\\"\\'])(.*?)\\2''', line))\n\n def _get_struct_attr_values(self, elem_attrname_list):\n result = []\n for elem, attrname in elem_attrname_list:\n if elem in self._struct_attr_values:\n if attrname == '*':\n result.extend(\n [(elem, name, val) for name, val\n in sorted(self._struct_attr_values[elem].items())])\n else:\n result.append(\n (elem, attrname,\n self._struct_attr_values[elem].get(attrname, '')))\n return result\n\n def _fix_set_struct_attrs(self, line):\n\n def fix_vbars(mo, feat_set_attrs):\n if mo.group(1) in feat_set_attrs:\n # Strip possible whitespace around the equals sign.\n return (mo.group(1) + '=' + mo.group(2)\n + fix_feature_set_attr(mo.group(3)) + mo.group(2))\n else:\n return mo.group(0)\n\n elemname = re.search(r'(\\w+)', line).group(1)\n if elemname in self._set_struct_attrs:\n return re.sub(\n r'''(\\w+)\\s*=\\s*([\"'])(.*?)\\2''',\n lambda mo: fix_vbars(mo, self._set_struct_attrs[elemname]),\n line)\n else:\n return line\n\n\ndef getopts():\n optparser = OptionParser()\n optparser.add_option('--input-fields', '--input-pos-attributes',\n action='append', default=[])\n optparser.add_option('--output-fields', '--output-pos-attributes',\n action='append', default=[])\n optparser.add_option('--space', '--space-replacement', default=None)\n optparser.add_option('--no-strip', action='store_false', dest='strip',\n default=True)\n optparser.add_option('--angle-brackets', '--angle-bracket-replacement',\n default=None)\n optparser.add_option('--compound-boundaries', '--lemma-compound-boundaries',\n type='choice', choices=['keep', 'remove', 'new'],\n default='keep')\n optparser.add_option('--compound-boundary-marker', '--compound-marker',\n default='#')\n optparser.add_option('--compound-boundary-regexp', action='store_true')\n optparser.add_option('--compound-boundary-hyphen',\n '--compound-boundary-can-replace-hyphen',\n action='store_true')\n optparser.add_option('--lemma-field', type='int', default=2)\n optparser.add_option('--noncompound-lemma-field', '--noncompound-field',\n '--removed-compound-boundary-field', type='int',\n default=None)\n optparser.add_option('--encode-special-chars', type='choice',\n choices=['none', 'all', 'pos', 'struct'],\n default='none')\n optparser.add_option('--special-chars', default=' /<>|')\n optparser.add_option('--encoded-special-char-offset',\n '--special-char-offset', default='0x7F')\n optparser.add_option('--encoded-special-char-prefix',\n '--special-char-prefix', default='')\n optparser.add_option(\n '--set-struct-attributes', '--feature-set-valued-struct-attributes',\n action='append', default=[],\n help=('Treat the structural attributes specified in the attribute'\n ' specification ATTRSPEC as feature set attributes and do not'\n ' convert the vertical bar characters in them.'\n ' ATTRSPEC is a space-separated list of element definitions, of'\n ' the form ELEMNAME_ATTRNAME or ELEMNAME:ATTRNAMELIST, where'\n ' ELEMNAME is the name of the XML element, ATTRNAME is a single'\n ' attribute name and ATTRNAMELIST is a list of attribute names'\n ' separated by commas or pluses.'\n ' The first form can be used to specify multiple feature set'\n ' attributes for a single element type: for example, the values'\n ' \"elem_attr1 elem_attr2\" and \"elem:attr1,attr2\" are equivalent.'\n ' This option can be repeated.'),\n metavar='ATTRSPEC')\n optparser.add_option('--empty-field-values')\n optparser.add_option('--missing-field-values')\n optparser.add_option('--rename-element', action='append', default=[])\n optparser.add_option('--add-element-id', '--add-elem-id', action='append',\n default=[])\n optparser.add_option('--replace-xml-character-entities', type='choice',\n choices=['none', 'correct', 'all', 'numeric',\n 'correctnumeric'],\n default='correctnumeric')\n optparser.add_option('--copy-struct-attribute', action='append', default=[])\n optparser.add_option('--encoding-errors', '--character-encoding-errors',\n type='choice', choices=['strict', 'replace', 'ignore'],\n default='strict')\n (opts, args) = optparser.parse_args()\n if opts.noncompound_lemma_field is None:\n if opts.compound_boundaries == 'remove':\n opts.noncompound_lemma_field = opts.lemma_field\n else:\n opts.noncompound_lemma_field = opts.lemma_field + 1\n if opts.space == '':\n opts.space = ':'\n if opts.angle_brackets == '':\n opts.angle_brackets = '[,]'\n opts.encoded_special_char_offset = int(opts.encoded_special_char_offset,\n base=0)\n if not opts.compound_boundary_regexp:\n opts.compound_boundary_marker = re.escape(opts.compound_boundary_marker)\n return (opts, args)\n\n\ndef main_main():\n input_encoding = 'utf-8-sig'\n output_encoding = 'utf-8'\n korputil.set_sys_stream_encodings(\n input_encoding, output_encoding, output_encoding)\n (opts, args) = getopts()\n attr_fixer = AttributeFixer(opts)\n attr_fixer.process_files(args if args else sys.stdin)\n\n\ndef main():\n try:\n main_main()\n except IOError as e:\n if e.errno == errno.EPIPE:\n sys.stderr.write('Broken pipe\\n')\n else:\n sys.stderr.write(str(e) + '\\n')\n exit(1)\n except KeyboardInterrupt as e:\n sys.stderr.write('Interrupted\\n')\n exit(1)\n except:\n raise\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"CSCfi/Kielipankki-utilities","sub_path":"scripts/vrt-fix-attrs.py","file_name":"vrt-fix-attrs.py","file_ext":"py","file_size_in_byte":33937,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"}
+{"seq_id":"71597600721","text":"#\n# Avent of Code 2016, Day 3\n# http://adventofcode.com/2016/day/3\n#\n\ndef check(a, b, c):\n return (a < (b + c)) and (b < (a + c)) and (c < (a + b)) \n\ndef part1():\n\n input = open(\"data\\input.txt\", \"r\") \n\n count = 0\n good = 0\n\n for line in input:\n \n l = line.split()\n \n if len(l) != 3:\n raise ValueError(\"input not parsed to three values\", line, \": \", l)\n\n a = int(l[0])\n b = int(l[1])\n c = int(l[2])\n\n if check(a, b, c): \n good = good + 1\n\n count = count + 1\n \n print(\"part 1: \", good, \"/\", count)\n\ndef part2():\n\n input = open(\"data\\input.txt\", \"r\") \n\n count = 0\n good = 0\n i = 0\n t = [0,0,0],[0,0,0],[0,0,0]\n\n for line in input:\n \n l = line.split()\n \n t[0][i] = int(l[0])\n t[1][i] = int(l[1])\n t[2][i] = int(l[2])\n\n if (i == 2): \n for j in range(0, 3): \n if check(t[j][0], t[j][1], t[j][2]): \n good = good + 1\n #print(t[j][0], t[j][1], t[j][2]) \n i = 0\n else:\n i = i + 1\n\n count = count + 1\n \n print(\"part 2: \", good, \"/\", count)\n\npart1()\npart2()","repo_name":"davidvidmar/AdventOfCode2016","sub_path":"Day 3/Day_3.py","file_name":"Day_3.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12355875513","text":"from __future__ import annotations\nfrom math import acos, atan2, sqrt, cos, sin, atan\nfrom typing import Tuple\n\nimport numpy as np\n\n\nclass Point:\n x: float\n y: float\n\n def __init__(self, x: float, y: float):\n self.x = x\n self.y = y\n\n def __repr__(self) -> str:\n return f\"({self.x:.3f}, {self.y:.3f})\"\n\n def distance_to(self, other: Point) -> float:\n return sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)\n\n def oriented_angle_to(self, other: Point) -> float:\n return atan2(other.y - self.y, other.x - self.x)\n\n def __add__(self, other: Point) -> Point:\n return Point(self.x + other.x, self.y + other.y)\n\n def __sub__(self, other: Point) -> Point:\n return Point(self.x - other.x, self.y - other.y)\n\n def __mul__(self, scale: float) -> Point:\n return Point(self.x * scale, self.y * scale)\n\n def __truediv__(self, scale: float) -> Point:\n return Point(self.x / scale, self.y / scale)\n\n def ha1(self, s: float, v: float):\n return Point(\n self.x + s * cos(v),\n self.y + s * sin(v),\n )\n\n def ha2(self, other: Point):\n s = self.distance_to(other)\n v = self.oriented_angle_to(other)\n return s, v\n\n\n# Aus 3 Längen eines Dreiecks, ergibt die 3 (gegenüberliegenden) Winkel dieses Dreiecks\ndef Halbwinkelsatz(\n a: float,\n b: float,\n c: float,\n):\n s = (a + b + c) / 2\n alpha = 2 * atan(sqrt((s - b) * (s - c) / (s * (s - a))))\n beta = 2 * atan(sqrt((s - c) * (s - a) / (s * (s - b))))\n gamma = 2 * atan(sqrt((s - a) * (s - b) / (s * (s - c))))\n return alpha, beta, gamma\n\n\n# Bogenschnitt\n# Aus zwei Punkten (A, B) und den Längen ausgehend von diesen Punkten,\n# ergibt den Schnittpunkt (C) zweier Kreise mit diesen Radien.\n# Achtung: ABC ist im Uhrzeigersinn. Tauscht man A und B, gäbe es noch eine andere Lösung.\ndef Bogenschnitt(\n A: Point,\n B: Point,\n sAC: float,\n sBC: float,\n) -> Point:\n sAB, vAB = A.ha2(B)\n alpha, beta, gamma = Halbwinkelsatz(sBC, sAC, sAB)\n\n vAC = vAB + alpha\n C = A.ha1(sAC, vAC)\n\n # Alternativ:\n # vBC = vAB + (gon(200) - beta)\n # C = B.ha1(sBC, vBC)\n\n return C\n\n\n# Aus zwei Punkten und den orientierten Richtungen ausgehend von diesen Punkten, ergibt\n# den Schnittpunkt dieser Geraden.\ndef Vorwärtsschnitt_Richtung(\n A: Point,\n B: Point,\n vAC: float,\n vBC: float,\n) -> Point:\n sAB, vAB = A.ha2(B)\n\n sAC = sAB * sin(vBC - vAB) / sin(vBC - vAC)\n C = A.ha1(sAC, vAC)\n\n # Alternative:\n # sBC = sAB * sin(vAC - vAB) / sin(vBC - vAC)\n # C = B.ha1(sBC, vBC)\n\n return C\n\n\n# Aus zwei Punkten und den unorientierten Richtungen ausgehend von diesen Punkten, ergibt\n# den Schnittpunkt C dieser Geraden.\n# A, B, C sind im Uhrzeigersinn.\ndef Vorwärtsschnitt_Winkel(\n A: Point,\n B: Point,\n alpha: float,\n beta: float,\n) -> Point:\n\n sAB, vAB = A.ha2(B)\n sAC = sAB * sin(beta) / sin(alpha + beta)\n sBC = sAB * sin(alpha) / sin(alpha + beta)\n\n vAC = vAB + alpha\n C = A.ha1(sAC, vAC)\n\n # Alternative:\n # vBC = vAB + (pi - beta)\n # C = B.ha1(sBC, vBC)\n\n return C\n\n\n# Aus 3 Punkten (L, M, R), und zwei Winkeln von N zu den drei Punkten,\n# berechne den Punkt N.\ndef Rückwärtsschnitt(\n L: Point,\n M: Point,\n R: Point,\n rNL: float,\n rNM: float,\n rNR: float,\n) -> Point:\n alpha = rNM - rNL\n beta = rNR - rNM\n\n sML, vML = M.ha2(L)\n sMR, vMR = M.ha2(R)\n\n a = sin(alpha) / sML\n b = sin(-beta) / sMR\n\n va = vMR - beta\n vb = vML + alpha\n base = sin(vML - vMR + alpha + beta)\n gamma = (a * cos(va) - b * cos(vb)) / base\n mu = (a * sin(va) - b * sin(vb)) / base\n\n sMN_sq = 1 / (gamma**2 + mu**2)\n\n return Point(\n M.x + sMN_sq * gamma,\n M.y + sMN_sq * mu,\n )\n\n\n# Peripheriewinkelsatz!!\ndef Rückwärtsschnitt_Collins(\n L: Point,\n M: Point,\n R: Point,\n rNL: float,\n rNM: float,\n rNR: float,\n) -> Point:\n alpha = rNM - rNL\n beta = rNR - rNM\n\n H = Vorwärtsschnitt_Winkel(R, L, alpha, beta)\n sHL, vHL = H.ha2(L)\n sHM, vHM = H.ha2(M)\n sHR, vHR = H.ha2(R)\n\n gamma = vHM - vHR\n delta = vHL - vHM\n\n N = Vorwärtsschnitt_Winkel(L, R, gamma, delta)\n return N\n\n\nclass CoordinateTransformation:\n scale: float\n rotation: float\n translation: Point\n\n def __str__(self) -> str:\n return f\"scale={self.scale}, rotation={self.rotation}, translation={self.translation}\"\n\n def transform(self, point: Point) -> Point:\n point = point - self.translation\n point = point * self.scale\n\n point = Point(\n point.x * cos(self.rotation) - point.y * sin(self.rotation),\n point.x * sin(self.rotation) + point.y * cos(self.rotation),\n )\n\n return point\n\n\n# Given a pair of points in the coordinate system 1, and a pair of points in the coordinate system 2,\n# returns the transformation from cs1 -> cs2.\ndef HelmertTransform(\n points_cs1: Tuple[Point, Point],\n points_cs2: Tuple[Point, Point],\n) -> CoordinateTransformation:\n x1 = points_cs1[0].x\n y1 = points_cs1[0].y\n x2 = points_cs1[1].x\n y2 = points_cs1[1].y\n x1_ = points_cs2[0].x\n y1_ = points_cs2[0].y\n x2_ = points_cs2[1].x\n y2_ = points_cs2[1].y\n\n [a, b, c, d] = np.linalg.solve(\n [\n [x1_, -y1_, 1, 0],\n [y1_, x1_, 0, 1],\n [x2_, -y2_, 1, 0],\n [y2_, x2_, 0, 1],\n ],\n [x1, y1, x2, y2],\n )\n\n mu = 1 / (a**2 + b**2) ** 0.5\n phi = acos(a * mu)\n dx = c\n dy = d\n\n return CoordinateTransformation(\n scale=mu,\n rotation=phi,\n translation=Point(dx, dy),\n )\n","repo_name":"pothos-dev/study","sub_path":"Geomathematik I/lib2d.py","file_name":"lib2d.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29138825777","text":"from typing import Union, Optional\n\nimport sys\n\nsys.path.append(\"schema\")\nsys.path.append(\"../schema\")\n\nimport pytest\nfrom rest_api import Resources\nfrom rest_api.calculator import StatCalculator\nfrom vsml_common.proto import ProtoSerializable\nfrom rest_api.region_api import RegionTree\nfrom rest_api.catalog import Catalog\n\nimport schema.auto.api.response_model_pb2 as proto_response\nimport schema.auto.api.stats_model_pb2 as proto\n\nfrom rest_api.model import ResponseStatus, StatsMarkResponseV3, StatsModelResponseV3, StatsMark, StatsMarkModel, \\\n ModelPhotos, Price, DeprecatedPrice, AgeWithPrice, StatsModel, Model, TechParams, MostPopularTechParam, \\\n DurationOfSale, DataSource\n\ndatasource_mapping = {1: DataSource.MARK,\n 2: DataSource.MODEL,\n 3: DataSource.GENERATION,\n 4: DataSource.CONFIGURATION,\n 5: DataSource.TECH_PARAM,\n 6: DataSource.COMPLECTATION}\n\nresponse_status_mapping = {\n 0: ResponseStatus.SUCCESS,\n 1: ResponseStatus.ERROR\n}\n\n\n@pytest.fixture(scope='module')\ndef resources():\n resources = Resources()\n region_tree = RegionTree('data/geobase_export.json')\n resources.region_tree = region_tree\n catalog = Catalog('data/catalog.json')\n resources.catalog = catalog\n calculator = StatCalculator('data/auto_stats.tsv', resources)\n resources.calculator = calculator\n return resources\n\n\ndef _parse_mark(response: proto.MarkStats,\n status: proto_response.ResponseStatus) -> StatsMarkResponseV3:\n models = []\n for p_model in response.models:\n p_photo = p_model.photo\n photo = None\n if p_photo.ByteSize():\n photo = ModelPhotos(sizes=ModelPhotos.ModelPhotosSizes(\n cattouch=p_photo.sizes['cattouch'],\n cattouchret=p_photo.sizes['cattouchret']\n ))\n\n price = _parse_price(p_model.price)\n deprecation = _parse_deprecation(p_model.deprecation)\n\n model = StatsMarkModel(\n model=p_model.model,\n photo=photo,\n year_from=p_model.year_from,\n year_to=p_model.year_to,\n price=price,\n deprecation=deprecation\n )\n models.append(model)\n\n return StatsMarkResponseV3(status=response_status_mapping[status],\n stats=StatsMark(\n mark=StatsMark.StatsMarkInner(\n models=models\n )\n ))\n\n\ndef _parse_price(p_price: proto.PriceBlock) -> Optional[Price]:\n if p_price.ByteSize():\n return Price(\n data_source=datasource_mapping[p_price.data_source],\n min_price=p_price.min_price,\n max_price=p_price.max_price,\n average_price=p_price.average_price,\n offers_count=p_price.offers_count\n )\n\n\ndef _parse_deprecation(p_deprecation: proto.DeprecationPriceBlock) -> Optional[DeprecatedPrice]:\n if p_deprecation.ByteSize():\n price_percentage_diff = []\n for ic, age_diff in enumerate(p_deprecation.price_percentage_diff):\n diff = age_diff.price_percentage_diff\n if ic == 0 and diff == 0:\n diff = None\n price_percentage_diff.append(AgeWithPrice(\n age=age_diff.age,\n price=age_diff.price,\n price_percentage_diff=diff\n ))\n return DeprecatedPrice(\n data_source=datasource_mapping[p_deprecation.data_source],\n avg_in_percentage=p_deprecation.avg_in_percentage,\n price_percentage_diff=price_percentage_diff # or None\n )\n\n\ndef _parse_techparam(p_tech_params: proto.TechParamsBlock) -> Optional[TechParams]:\n if p_tech_params.ByteSize():\n p_most_popular = p_tech_params.most_popular_tech_param\n most_popular_tech_param = None\n if p_most_popular.ByteSize():\n most_popular_tech_param = MostPopularTechParam(\n mark=p_most_popular.mark,\n mark_name=p_most_popular.mark_name,\n model=p_most_popular.model,\n model_name=p_most_popular.model_name,\n super_gen_id=str(p_most_popular.super_gen_id),\n super_gen_name=p_most_popular.super_gen_name,\n configuration_id=str(p_most_popular.configuration_id),\n tech_param_id=str(p_most_popular.tech_param_id),\n body_type=p_most_popular.body_type,\n engine_type=p_most_popular.engine_type,\n displacement=p_most_popular.displacement,\n transmission=p_most_popular.transmission,\n horse_power=p_most_popular.horse_power\n )\n\n displacement_segments = p_tech_params.displacement_segments\n if displacement_segments:\n displacement_segments = {str(k): v for k, v in displacement_segments.items()}\n return TechParams(\n data_source=datasource_mapping[p_tech_params.data_source],\n most_popular_tech_param=most_popular_tech_param,\n displacement_segments=displacement_segments,\n engine_type_segments=p_tech_params.engine_type_segments,\n transmission_segments=p_tech_params.transmission_segments,\n gear_type_segments=p_tech_params.gear_type_segments\n )\n\n\ndef _parse_duration(p_duration: proto.DurationOfSaleBlock) -> Optional[DurationOfSale]:\n if p_duration.ByteSize():\n return DurationOfSale(\n data_source=datasource_mapping[p_duration.data_source],\n avg=p_duration.avg,\n vas=p_duration.vas,\n cert=p_duration.cert\n )\n\n\ndef _parse_model(response: proto.ModelStats,\n status: proto_response.ResponseStatus) -> StatsModelResponseV3:\n price = _parse_price(response.price)\n deprecation = _parse_deprecation(response.deprecation)\n tech_params = _parse_techparam(response.tech_params)\n duration_of_sale = _parse_duration(response.duration_of_sale)\n model = Model(\n price=price,\n deprecation=deprecation,\n tech_params=tech_params,\n duration_of_sale=duration_of_sale\n )\n\n return StatsModelResponseV3(status=response_status_mapping[status],\n stats=StatsModel(\n model=model\n ))\n\n\ndef parse_response_from_protobuf(\n response: proto_response.StatsSummaryResponse\n) -> Optional[Union[StatsMarkResponseV3, StatsModelResponseV3]]:\n mark = response.stats.mark\n model = response.stats.model\n status = response.status\n if response.stats.WhichOneof('data') == 'mark':\n return _parse_mark(mark, status)\n elif response.stats.WhichOneof('data') == 'model':\n return _parse_model(model, status)\n\n\ndef serde(response: ProtoSerializable):\n serialized = response.to_proto().SerializeToString()\n proto_deserialized = proto_response.StatsSummaryResponse()\n proto_deserialized.ParseFromString(serialized)\n return parse_response_from_protobuf(proto_deserialized)\n\n\ndef _test_query_v3(resources,\n rid: int,\n mark: str,\n model: str = None,\n super_gen: str = None,\n configuration_id: str = None,\n tech_param_id: str = None):\n expected_response = resources.calculator.stat_v3(rid=rid,\n mark=mark,\n model=model,\n super_gen=super_gen,\n configuration_id=configuration_id,\n tech_param_id=tech_param_id)\n\n deserialized_response = serde(expected_response)\n assert deserialized_response == expected_response\n\n\ndef _test_all_models_v3(resources, rid, mark):\n mark = resources.catalog.tree.get(mark)\n if not mark:\n return True\n for model_id in mark.models:\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id)\n\n # these tests does not match catalog tree, thus should accept properly only mark\n # (all other params are just silently dropped)\n _test_query_v3(resources, rid=rid, mark=mark.mark, model='does-not-exist')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model='3')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model='3',\n super_gen='7754738')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model='3',\n super_gen='7754738', configuration_id='7754744')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model='3',\n super_gen='7754738', configuration_id='7754744', tech_param_id='7754757')\n\n\ndef _test_all_supergen_v3(resources, rid, mark):\n mark = resources.catalog.tree.get(mark)\n if not mark:\n return True\n for model_id in mark.models:\n model = mark.models[model_id]\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen='does-not-exist')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen='7754738')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen='7754738', configuration_id='7754744')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen='7754738', configuration_id='7754744', tech_param_id='7754757')\n\n for supergen_id in model.supergens:\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id, super_gen=supergen_id)\n\n\ndef _test_all_configuration_v3(resources, rid, mark):\n mark = resources.catalog.tree.get(mark)\n if not mark:\n return True\n for model_id, model in mark.models.items():\n for supergen_id, supergen in model.supergens.items():\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen=supergen_id, configuration_id='does-not-exist')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen=supergen_id, configuration_id='7754744')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen=supergen_id, configuration_id='7754744', tech_param_id='7754757')\n for ic, (configuration_id, configuration) in enumerate(supergen.configurations.items()):\n if ic % 2 == 1: continue\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen=supergen_id, configuration_id=configuration_id)\n\n\ndef _test_all_techparam_v3(resources, rid, mark):\n mark = resources.catalog.tree.get(mark)\n if not mark:\n return True\n for model_id, model in mark.models.items():\n for supergen_id, supergen in model.supergens.items():\n for ic, (configuration_id, configuration) in enumerate(supergen.configurations.items()):\n if ic % 2 == 0: continue\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen=supergen_id, configuration_id=configuration_id, tech_param_id='does-not-exist')\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen=supergen_id, configuration_id=configuration_id, tech_param_id='7754757')\n for jc, (tech_param_id, tech_param) in enumerate(configuration.techparams.items()):\n if jc % 2 == 0: continue\n _test_query_v3(resources, rid=rid, mark=mark.mark, model=model_id,\n super_gen=supergen_id, configuration_id=configuration_id,\n tech_param_id=tech_param_id)\n\n\ndef test_mark_vaz_whole_earth(resources: Resources):\n _test_query_v3(resources, rid=10000, mark='VAZ')\n\n\ndef test_mark_vaz_spb(resources: Resources):\n _test_query_v3(resources, rid=2, mark='VAZ')\n\n\ndef test_mark_vaz_small_city(resources: Resources):\n _test_query_v3(resources, rid=121713, mark='VAZ')\n\n\ndef test_mark_bmw_whole_earth(resources: Resources):\n _test_query_v3(resources, rid=10000, mark='BMW')\n\n\ndef test_mark_bmw_moscow(resources: Resources):\n _test_query_v3(resources, rid=1, mark='BMW')\n\n\ndef test_mark_bmw_small_city(resources: Resources):\n _test_query_v3(resources, rid=159972, mark='BMW')\n\n\ndef test_mark_ac_whole_earth(resources: Resources):\n _test_query_v3(resources, rid=10000, mark='AC')\n\n\ndef test_mark_ac_moscow(resources: Resources):\n _test_query_v3(resources, rid=1, mark='AC')\n\n\ndef test_mark_ac_small_city(resources: Resources):\n _test_query_v3(resources, rid=159972, mark='AC')\n\n\ndef test_mark_unknown_mark_whole_earth(resources: Resources):\n _test_query_v3(resources, rid=10000, mark='BLABLABLA')\n\n\ndef test_mark_opel_unknown_region(resources: Resources):\n _test_query_v3(resources, rid=123321123, mark='OPEL')\n\n\ndef test_model_vaz_whole_earth(resources: Resources):\n _test_all_models_v3(resources, rid=10000, mark='VAZ')\n\n\ndef test_model_vaz_spb(resources: Resources):\n _test_all_models_v3(resources, rid=2, mark='VAZ')\n\n\ndef test_model_vaz_small_city(resources: Resources):\n _test_all_models_v3(resources, rid=121713, mark='VAZ')\n\n\ndef test_model_bmw_whole_earth(resources: Resources):\n _test_all_models_v3(resources, rid=10000, mark='BMW')\n\n\ndef test_model_bmw_moscow(resources: Resources):\n _test_all_models_v3(resources, rid=1, mark='BMW')\n\n\ndef test_model_bmw_small_city(resources: Resources):\n _test_all_models_v3(resources, rid=159972, mark='BMW')\n\n\ndef test_model_ac_whole_earth(resources: Resources):\n _test_all_models_v3(resources, rid=10000, mark='AC')\n\n\ndef test_model_ac_moscow(resources: Resources):\n _test_all_models_v3(resources, rid=1, mark='AC')\n\n\ndef test_model_ac_small_city(resources: Resources):\n _test_all_models_v3(resources, rid=159972, mark='AC')\n\n\ndef test_model_unknown_mark_whole_earth(resources: Resources):\n _test_all_models_v3(resources, rid=10000, mark='BLABLABLA')\n\n\ndef test_model_opel_unknown_region(resources: Resources):\n _test_all_models_v3(resources, rid=123321123, mark='OPEL')\n\n\n####################\n# SUPERGEN\n####################\n\ndef test_supergen_vaz_whole_earth(resources: Resources):\n _test_all_supergen_v3(resources, rid=10000, mark='VAZ')\n\n\ndef test_supergen_vaz_spb(resources: Resources):\n _test_all_supergen_v3(resources, rid=2, mark='VAZ')\n\n\ndef test_supergen_vaz_small_city(resources: Resources):\n _test_all_supergen_v3(resources, rid=121713, mark='VAZ')\n\n\ndef test_supergen_bmw_whole_earth(resources: Resources):\n _test_all_supergen_v3(resources, rid=10000, mark='BMW')\n\n\ndef test_supergen_bmw_moscow(resources: Resources):\n _test_all_supergen_v3(resources, rid=1, mark='BMW')\n\n\ndef test_supergen_bmw_small_city(resources: Resources):\n _test_all_supergen_v3(resources, rid=159972, mark='BMW')\n\n\ndef test_supergen_ac_whole_earth(resources: Resources):\n _test_all_supergen_v3(resources, rid=10000, mark='AC')\n\n\ndef test_supergen_ac_moscow(resources: Resources):\n _test_all_supergen_v3(resources, rid=1, mark='AC')\n\n\ndef test_supergen_ac_small_city(resources: Resources):\n _test_all_supergen_v3(resources, rid=159972, mark='AC')\n\n\ndef test_supergen_unknown_mark_whole_earth(resources: Resources):\n _test_all_supergen_v3(resources, rid=10000, mark='BLABLABLA')\n\n\ndef test_supergen_opel_unknown_region(resources: Resources):\n _test_all_supergen_v3(resources, rid=123321123, mark='OPEL')\n\n\n####################\n# configuration\n####################\n\ndef test_configuration_vaz_whole_earth(resources: Resources):\n _test_all_configuration_v3(resources, rid=10000, mark='VAZ')\n\n\ndef test_configuration_vaz_spb(resources: Resources):\n _test_all_configuration_v3(resources, rid=2, mark='VAZ')\n\n\ndef test_configuration_vaz_small_city(resources: Resources):\n _test_all_configuration_v3(resources, rid=121713, mark='VAZ')\n\n\ndef test_configuration_bmw_whole_earth(resources: Resources):\n _test_all_configuration_v3(resources, rid=10000, mark='BMW')\n\n\ndef test_configuration_bmw_moscow(resources: Resources):\n _test_all_configuration_v3(resources, rid=1, mark='BMW')\n\n\ndef test_configuration_bmw_small_city(resources: Resources):\n _test_all_configuration_v3(resources, rid=159972, mark='BMW')\n\n\ndef test_configuration_ac_whole_earth(resources: Resources):\n _test_all_configuration_v3(resources, rid=10000, mark='AC')\n\n\ndef test_configuration_ac_moscow(resources: Resources):\n _test_all_configuration_v3(resources, rid=1, mark='AC')\n\n\ndef test_configuration_ac_small_city(resources: Resources):\n _test_all_configuration_v3(resources, rid=159972, mark='AC')\n\n\ndef test_configuration_unknown_mark_whole_earth(resources: Resources):\n _test_all_configuration_v3(resources, rid=10000, mark='BLABLABLA')\n\n\ndef test_configuration_opel_unknown_region(resources: Resources):\n _test_all_configuration_v3(resources, rid=123321123, mark='OPEL')\n\n\n####################\n# techparam\n####################\n\ndef test_techparam_vaz_whole_earth(resources: Resources):\n _test_all_techparam_v3(resources, rid=10000, mark='VAZ')\n\n\ndef test_techparam_vaz_spb(resources: Resources):\n _test_all_techparam_v3(resources, rid=2, mark='VAZ')\n\n\ndef test_techparam_vaz_small_city(resources: Resources):\n _test_all_techparam_v3(resources, rid=121713, mark='VAZ')\n\n\ndef test_techparam_bmw_whole_earth(resources: Resources):\n _test_all_techparam_v3(resources, rid=10000, mark='BMW')\n\n\ndef test_techparam_bmw_moscow(resources: Resources):\n _test_all_techparam_v3(resources, rid=1, mark='BMW')\n\n\ndef test_techparam_bmw_small_city(resources: Resources):\n _test_all_techparam_v3(resources, rid=159972, mark='BMW')\n\n\ndef test_techparam_ac_whole_earth(resources: Resources):\n _test_all_techparam_v3(resources, rid=10000, mark='AC')\n\n\ndef test_techparam_ac_moscow(resources: Resources):\n _test_all_techparam_v3(resources, rid=1, mark='AC')\n\n\ndef test_techparam_ac_small_city(resources: Resources):\n _test_all_techparam_v3(resources, rid=159972, mark='AC')\n\n\ndef test_techparam_unknown_mark_whole_earth(resources: Resources):\n _test_all_techparam_v3(resources, rid=10000, mark='BLABLABLA')\n\n\ndef test_techparam_opel_unknown_region(resources: Resources):\n _test_all_techparam_v3(resources, rid=123321123, mark='OPEL')\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"classfields/tests/test_protobuf.py","file_name":"test_protobuf.py","file_ext":"py","file_size_in_byte":18661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20505176711","text":"#pathfinding\nimport pygame as pg\nfrom collections import deque\nfrom os import path\nvec = pg.math.Vector2\n\nTILESIZE = 32\nTILEWIDTH = 32\nTILEHEIGHT = 16\n\nWIDTH = TILEWIDTH * TILESIZE\nHEIGHT = TILEHEIGHT * TILESIZE\n\nFPS = 60\n\nWHITE = (255,255,255)\nBLACK = (0,0,0)\nRED = (255,0,0)\nBLUE = (0,0,255)\nGREEN = (0,255,0)\nGREY = (100,100,100)\nDARKGREY = (40,40,40)\nLIGHTGREY = (150,150,150)\nYELLOW = (255,255,0)\n\npremade_lab = [(0, 2), (1, 2), (2, 2), (2, 3), (2, 4), (2, 5), (5, 0), (5, 2), (5, 1), (5, 3), (6, 3), (7, 3), (8, 3), (8, 4),\n(8, 5), (5, 8), (5, 9), (4, 9), (3, 9), (2, 9), (2, 10), (2, 11), (2, 12), (1, 12), (0, 12), (3, 6), (2, 6), (6, 14), (7, 14),\n(8, 14), (9, 14), (10, 14), (10, 13), (10, 12), (10, 11), (10, 10), (10, 9), (10, 8), (11, 8), (12, 8), (13, 8), (6, 15),\n(12, 5), (12, 4), (12, 3), (12, 2), (13, 1), (12, 1), (14, 1), (15, 1), (11, 5), (16, 1), (17, 1), (18, 1), (19, 1), (20, 1),\n(20, 2), (20, 3), (20, 5), (20, 4), (19, 5), (18, 5), (17, 5), (16, 5), (16, 4), (16, 3), (23, 0), (23, 1), (24, 1), (25, 1),\n(25, 2), (25, 3), (26, 3), (27, 3), (28, 3), (28, 2), (31, 5), (30, 5), (29, 5), (29, 6), (29, 7), (28, 7), (27, 7), (12, 15),\n(12, 14), (13, 14), (13, 13), (13, 12), (13, 11), (14, 11), (15, 11), (16, 11), (16, 10), (16, 9), (16, 8), (16, 7), (17, 7),\n(18, 7), (21, 9), (20, 9), (20, 10), (20, 11), (20, 12), (19, 13), (20, 13), (18, 13), (18, 14), (18, 15), (17, 15), (28, 1),\n(26, 7), (26, 8), (26, 9), (26, 10), (27, 11), (26, 11), (28, 11), (29, 11), (29, 10), (31, 13), (30, 13), (29, 13), (29, 14),\n(26, 15), (26, 14), (26, 13), (25, 13), (24, 13), (23, 13), (21, 15), (22, 15), (24, 11), (24, 10), (24, 9), (24, 8), (24, 7),\n(23, 7), (22, 7), (21, 7), (20, 7), (22, 3), (22, 4), (22, 5), (23, 5), (24, 5), (4, 15), (4, 14), (4, 13), (4, 12), (5, 12),\n(6, 12), (7, 12), (7, 11), (7, 10), (7, 9), (7, 8), (8, 0), (8, 1), (9, 1), (10, 1), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9)]\n\npg.init()\nscreen = pg.display.set_mode((WIDTH,HEIGHT))\nclock = pg.time.Clock()\nrunning = True\n\n#dibuja la cuadricula de tiles\ndef draw_grid():\n for x in range(0,WIDTH,TILESIZE):\n pg.draw.line(screen,GREY,(x,0),(x,HEIGHT))\n for y in range(0,HEIGHT,TILESIZE):\n pg.draw.line(screen,GREY,(0,y),(WIDTH,y))\n\n#mapa que es conformado por cuadrados de igual area (tilemap)\nclass Squaregrid():\n def __init__(self, width, height):\n self.width = width #tile width of the map\n self.height = height #tile height of the map\n self.directions = [vec(1,0), vec(-1,0), vec(0,1), vec(0,-1)] #+ [vec(-1,-1), vec(1,-1), vec(-1,1), vec(1,1)]#allowed directions to move between nodes\n self.walls = []#all non passable nodes (tiles)\n\n def in_bounds(self, node):#check if a node is inside the grid\n if 0 <= node.x < self.width and 0 <= node.y < self.height:\n return True\n\n def passable(self, node):#check if a node is passable (is not a wall)\n if node not in self.walls:\n return True\n\n def find_neighbors(self, node):#find all the possible neighbors of a node\n neighbors = [node + direction for direction in self.directions]\n #fitrando los vecinos del nodo:\n neighbors = filter(self.in_bounds,neighbors)#verificando que los vecino esten dentro del mapa (in-bound (dentro de las esquinas))\n neighbors = filter(self.passable,neighbors)#verificando que se pueda pasar por los vecinos (que no sean walls)\n return neighbors\n\n def draw_walls(self):\n for wall in self.walls:\n rect = pg.Rect(wall * TILESIZE,(TILESIZE,TILESIZE))\n pg.draw.rect(screen,GREY,rect)\n\ndef vec2int(vector):#converts a vector object into a int tuple\n return (int(vector.x),int(vector.y))\n\ndef breadth_first_search(graph,goal,start):#encuentra el camino desde el nodo start hacia el goal\n #nota: el BFS hace la busqueda desde el goal hasta el start es decir al reves\n frontier = deque()\n frontier.append(goal)\n path = {}\n path[vec2int(goal)] = None\n\n while len(frontier) > 0:\n current = frontier.popleft()\n if current == start:\n break\n for next in graph.find_neighbors(current):\n if vec2int(next) not in path:\n frontier.append(next)\n path[vec2int(next)] = current - next\n return path\n\n#loading graphics\nimg_folder = path.join(path.dirname(__file__),\"icons\")\n\narrows = {}\narrow = pg.image.load(path.join(img_folder,\"arrowRight.png\"))\narrow = pg.transform.scale(arrow,(50,50))\nfor dir in [(1,0), (-1,0), (0,1), (0,-1), (-1,-1), (1,-1), (-1,1), (1,1)]:\n arrows[dir] = pg.transform.rotate(arrow, vec(dir).angle_to(vec(1,0)))\n\ngoal_img = pg.image.load(path.join(img_folder,\"home.png\"))\ngoal_img = pg.transform.scale(goal_img,(50,50))\ngoal_img_rect = goal_img.get_rect()\n\nstart_img = pg.image.load(path.join(img_folder,\"cross.png\"))\nstart_img = pg.transform.scale(start_img,(50,50))\nstart_img_rect = start_img.get_rect()\n\ndef draw_visited_nodes_to_find_path():\n for node in path:\n rect = pg.Rect(vec(node) * TILESIZE,(TILESIZE,TILESIZE))\n pg.draw.rect(screen,LIGHTGREY,rect)\n\n#charging graph (map of nodes)\nG = Squaregrid(TILEWIDTH,TILEHEIGHT)\nG.walls = [vec(cord) for cord in premade_lab]\n\n#calculando el path desde el start al goal\ngoal = vec(5,6)\nstart = vec(7,4)\npath = breadth_first_search(G,goal,start)\n\nwhile running:\n clock.tick(FPS)\n #events\n for event in pg.event.get():\n if event.type == pg.QUIT:\n running = False\n\n #adding walls by clicking\n if event.type == pg.MOUSEBUTTONDOWN:\n mouse_pos = vec(pg.mouse.get_pos()) // TILESIZE #getting the tile coordinates of the mouse_pos\n if event.button == 1:\n #spawning or destroying a wall\n if mouse_pos in G.walls:\n G.walls.remove(mouse_pos)\n else:\n G.walls.append(mouse_pos)\n if event.button == 3:\n #change the current goal of the path\n goal = mouse_pos\n #recalculating the path\n path = breadth_first_search(G,goal,start)\n\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_p:\n if len(G.walls) > 0:\n #elimina todas las paredes\n G.walls = []\n else:\n #spawnea las paredes del mapa incial\n G.walls = [vec(cord) for cord in premade_lab]\n #recalculation the path\n path = breadth_first_search(G,goal,start)\n\n if event.key == pg.K_m:\n #print the list of all the walls\n print([(int(wall.x),int(wall.y)) for wall in G.walls])\n\n #chage the staring point\n if event.key == pg.K_q:\n mouse_pos = vec(pg.mouse.get_pos()) // TILESIZE\n start = mouse_pos\n\n #recalculating the path\n path = breadth_first_search(G,goal,start)\n #update\n\n #drawing\n screen.fill(DARKGREY)\n draw_visited_nodes_to_find_path()\n pg.display.set_caption(\"{:.0f}\".format(clock.get_fps()))\n draw_grid()\n G.draw_walls()\n\n #drawing goal and start points\n x = (goal.x * TILESIZE) + TILESIZE//2\n y = (goal.y * TILESIZE) + TILESIZE//2\n goal_img_rect.center = (x,y)\n screen.blit(goal_img,goal_img_rect)\n\n x = (start.x * TILESIZE) + TILESIZE//2\n y = (start.y * TILESIZE) + TILESIZE//2\n start_img_rect.center = (x,y)\n screen.blit(start_img,start_img_rect)\n\n #drawing path from start to goal\n if vec2int(start) in path:\n current = start + path[vec2int(start)]#dibuja flechas a partir del siguiente nodo al start\n while current != goal:\n x = (current.x * TILESIZE) + TILESIZE//2\n y = current.y * TILESIZE + TILESIZE//2\n image = arrows[vec2int(path[vec2int(current)])]\n rect = image.get_rect(center=(x,y))\n\n screen.blit(image,rect)\n\n current += path[vec2int(current)]\n\n\n\n pg.display.flip()\n\npg.quit()\n","repo_name":"joaobose/public-repo","sub_path":"GameDev/Python/python-pygame-pathFinding-algorithms/BFS-shortest-path-and-optimazation.py","file_name":"BFS-shortest-path-and-optimazation.py","file_ext":"py","file_size_in_byte":8051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30829232535","text":"import scrapy\r\n\r\nfrom scrapy.utils.response import get_base_url\r\nfrom scrapy.utils.url import urljoin_rfc\r\n\r\nfrom scrapy_splash import SplashRequest\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom pyvirtualdisplay import Display\r\nimport traceback\r\n\r\nclass sjtuSpider(scrapy.Spider):\r\n name = \"sjtu\"\r\n\r\n def __init__(self, category=None, *args, **kwargs):\r\n super(sjtuSpider, self).__init__(*args, **kwargs)\r\n\r\n display = Display(visible=0, size=(800, 600))\r\n display.start()\r\n\r\n self.driver = webdriver.Chrome()\r\n self.driver.set_page_load_timeout(10)\r\n\r\n\r\n def start_requests(self):\r\n urls = [\r\n 'http://news.nju.edu.cn/mtjj.html'\r\n ]\r\n for url in urls:\r\n yield SplashRequest(url, self.parse,args={'wait': 0.5})\r\n\r\n def parse(self,response):\r\n url_set = set() # 话题url的集合\r\n\r\n print(response.url)\r\n print(response.css(\"a#next\").extract_first())\r\n self.driver.get(response.url)\r\n\r\n url_sum_lists = []\r\n while True:\r\n try:\r\n wait = WebDriverWait(self.driver, 10)\r\n #wait.until(lambda driver: driver.find_element_by_xpath('//div[@class=\"content\"]/ul/li/a'))\r\n wait.until(lambda driver: driver.find_element_by_xpath('//li[@class=\"t\"]/a'))\r\n except:\r\n pass\r\n\r\n sel_list = self.driver.find_elements_by_xpath('//li[@class=\"t\"]/a')\r\n\r\n url_list = []\r\n for sel in sel_list:\r\n try:\r\n url_list.append(sel.get_attribute(\"href\"))\r\n except:\r\n continue\r\n\r\n #url_list = [sel for sel in sel_list]\r\n url_sum_lists += url_list\r\n url_set |= set(url_list)\r\n\r\n print(len(url_set))\r\n\r\n\r\n\r\n try:\r\n wait = WebDriverWait(self.driver, 10)\r\n wait.until(lambda driver: driver.find_element_by_xpath(\"//a[@id='next']\"))\r\n next_page = self.driver.find_element_by_xpath(\"//a[@id='next']\")\r\n #print(\"@#@@#@!#!#!#\"+next_page.get_attribute('href'))\r\n #print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\\n\\n\\n\")\r\n #print(next_page)\r\n if(int(next_page.get_attribute('pn')) == 201):\r\n break\r\n self.driver.execute_script(\"arguments[0].click();\", next_page)\r\n\r\n #next_page.click() # 模拟点击下一页\r\n except Exception as e :\r\n traceback.print_exc()\r\n info = traceback.format_exc()\r\n print(\"#####Arrive thelast page.#####\")\r\n break\r\n\r\n #for url in url_sum_lists:\r\n #print(url)\r\n #print(\"\\n\\n\\nlen:\"+str(len(url_set)))\r\n\r\n print(\"len of sum is :\"+str(len(url_sum_lists)))\r\n for url in url_sum_lists:\r\n print(url)\r\n\r\n #print(\"\".join(response.css(\".next\").extract()))\r\n #yield response.css(\".next\").extract_first()\r\n #yield response.css(\".whj_border\").extract_first()\r\n def parse_news(self,response):\r\n yield {\"title\":response.css(\".article_title\").extract_first()}\r\n\r\n","repo_name":"zhengyima/scraper-school","sub_path":"tutorial/tutorial/spiders/sjtuSpider.py","file_name":"sjtuSpider.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"2581311124","text":"from django import forms\nfrom django.forms import ModelForm\nfrom django.forms.widgets import DateInput\nfrom .models import *\nimport datetime\n\n# Form for the add and update a product\nclass addProductForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['proBoughtDate'].initial = datetime.date.today()\n\n class Meta:\n model = t_products\n fields = ['proName', 'proNote', 'proImage', 'proBoughtPrice', 'proBoughtDate', 'fkType' ,'fkCategory']\n labels = {\n 'proName': 'Nom de produit :',\n 'proNote': 'Description :',\n 'proImage': 'Image :',\n 'proBoughtPrice': 'Prix d\\'achat :',\n 'proBoughtDate': 'Date d\\'achat :',\n 'fkCategory': 'Categorie : ',\n 'fkType': 'Type'\n }\n widgets = {\n 'proBoughtDate': DateInput(format=('%Y-%m-%d'),attrs={'type': 'date', 'class': 'dateForm'}),\n }\n \nclass articleForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n \n class Meta:\n model = t_article\n fields = ['artName', 'artNote','fkRoom','fkProduct', 'fkCupboard']\n labels = {\n 'artName': 'Label : ',\n 'fkProduct': 'Produit : ',\n 'artNote': 'Note : ',\n 'fkRoom': 'Labo : ',\n 'fkCupboard': 'Armoire : '\n }\n\nclass borrowForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['borDate'].initial = datetime.date.today()\n self.fields['borReturnDate'].initial = datetime.date.today() + datetime.timedelta(days=30)\n\n class Meta:\n model = t_borrow\n fields = ['borLocation', 'borDate', 'borReturnDate', 'borUser', 'fkArticle']\n labels = {\n 'borLocation': 'Lieu demprunt :',\n 'borDate': 'Date demprunt :',\n 'borReturnDate': 'Date de retour :',\n 'borUser': 'Emprunté par :',\n 'fkArticle': 'Article :',\n }\n widgets = {\n 'borDate': DateInput(format=('%Y-%m-%d'),attrs={'type': 'date', 'class': 'dateForm'}),\n 'borReturnDate': DateInput(format=('%Y-%m-%d'),attrs={'type': 'date', 'class': 'dateForm'}),\n }\n ","repo_name":"alessdangelo/tpi_gestock","sub_path":"app_gestock/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8063135692","text":"from old_ant import *\nfrom graph_data import *\n\n\n# g = Graph(\"O\", (\"O\", \"N1\", \"N2\", \"N3\", \"N4\", \"N5\", \"N6\", \"N7\"), ((\"O\", \"N1\", 3), (\"O\", \"N2\", 4), (\"O\", \"N3\", 3),\n# (\"N1\", \"N2\", 2), (\"N2\", \"N3\", 1), (\"N2\", \"N4\", 2),\n# (\"N3\", \"N5\", 5), (\"N2\", \"N3\", 1), (\"N4\", \"N5\", 1),\n# (\"N4\", \"N6\", 6), (\"N5\", \"N7\", 3), (\"N6\", \"N7\", 2)))\n\norigin, nodes, edges = generate_graph(100, 2000, 3, 10)\nwrite_graph(\"100-graph.json\", origin, nodes, edges)\n# origin, nodes, edges = read_graph(\"100-graph.json\")\n\ng = Graph(origin, nodes, edges)\n\nclny = Colony(10, 60, 600, g)\nclny.iterate(1)\n\nfor vehicle in clny.vehicles:\n print(vehicle.path)\n print(g.calculate_len(vehicle.path))\nprint(\"\\n\")\n\nclny.iterate(10)\n\nfor vehicle in clny.vehicles:\n print(vehicle.path)\n print(g.calculate_len(vehicle.path))\n\no = clny.graph.find_node(\"O\")\nfor e in o.edges:\n print(e.node1.name, e.node2.name, e.pheromone)\nfor _ in range(5):\n print(o.choose_path()[1].name)\n\nclny.iterate(100000)\n\nprint(\"\\n\")\nfor vehicle in clny.vehicles:\n print(vehicle.path)\n print(g.calculate_len(vehicle.path))\n\no = clny.graph.find_node(\"O\")\nfor e in o.edges:\n print(e.node1.name, e.node2.name, e.pheromone)\nfor _ in range(5):\n print(o.choose_path()[1].name)\n","repo_name":"neonbevz/AdFontes","sub_path":"Python/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38176219802","text":"import filecmp\nfrom pathlib import Path\n\nimport pytest\n\nfrom mocasin.common.graph import DataflowChannel, DataflowProcess, DataflowGraph\nfrom mocasin.mapper.partial import ComFullMapper, ProcPartialMapper\nfrom mocasin.platforms.odroid import DesignerPlatformOdroid\nfrom mocasin.platforms.platformDesigner import genericProcessor\nfrom mocasin.util.mapping_table import MappingTableReader, MappingTableWriter\n\n\n@pytest.fixture\ndef table_file():\n return Path(__file__).parent.absolute().joinpath(\"mapping_table.csv\")\n\n\n@pytest.fixture\ndef expected_csv():\n return (\n Path(__file__).parent.absolute().joinpath(\"expected_mapping_table.csv\")\n )\n\n\n@pytest.fixture\ndef graph():\n k = DataflowGraph(\"graph\")\n channel = DataflowChannel(\"ch\", 1)\n k.add_channel(channel)\n process_a = DataflowProcess(\"a\")\n process_a.connect_to_outgoing_channel(channel)\n process_b = DataflowProcess(\"b\")\n process_b.connect_to_incomming_channel(channel)\n k.add_process(DataflowProcess(\"a\"))\n k.add_process(DataflowProcess(\"b\"))\n return k\n\n\n@pytest.fixture\ndef platform():\n pe_little = genericProcessor(\"proc_type_0\")\n pe_big = genericProcessor(\"proc_type_1\")\n p = DesignerPlatformOdroid(pe_little, pe_big)\n return p\n\n\ndef test_mapping_table_reader(platform, graph, table_file):\n reader = MappingTableReader(\n platform, graph, table_file, attributes=[\"attribute1\"]\n )\n mappings = reader.form_mappings()\n assert len(mappings) == 4\n assert mappings[0][0].to_list() == [1, 3]\n assert mappings[0][0].metadata.exec_time == 10.23\n assert mappings[0][0].metadata.energy == 24.43\n assert mappings[0][1] == \"a\"\n assert mappings[1][0].to_list() == [1, 1]\n assert mappings[1][0].metadata.exec_time == 14.43\n assert mappings[1][0].metadata.energy == 21.56\n assert mappings[1][1] == \"b\"\n assert mappings[2][0].to_list() == [0, 1]\n assert mappings[2][1] == \"c\"\n assert mappings[3][0].to_list() == [0, 6]\n\n\ndef num_resources(mapping):\n return len(mapping.get_used_processors())\n\n\ndef test_mapping_table_writer(platform, graph, tmpdir, expected_csv):\n output_file = Path(tmpdir).joinpath(\"output_table.csv\")\n com_mapper = ComFullMapper(platform)\n mapper = ProcPartialMapper(graph, platform, com_mapper)\n\n mapping1 = mapper.generate_mapping([0, 0])\n mapping1.metadata.exec_time = 10.2\n mapping1.metadata.energy = 21.45\n\n mapping2 = mapper.generate_mapping([0, 3])\n mapping2.metadata.exec_time = 5.2\n mapping2.metadata.energy = 31.15\n\n attributes = {\"num_resources\": num_resources}\n writer = MappingTableWriter(\n platform, graph, output_file, attributes=attributes\n )\n writer.open()\n writer.write_header()\n writer.write_mapping(mapping1)\n writer.write_mapping(mapping2)\n writer.close()\n assert filecmp.cmp(output_file, expected_csv, shallow=False)\n\n\ndef test_mapping_table_writer_with(platform, graph, tmpdir, expected_csv):\n output_file = Path(tmpdir).joinpath(\"output_table.csv\")\n com_mapper = ComFullMapper(platform)\n mapper = ProcPartialMapper(graph, platform, com_mapper)\n\n mapping1 = mapper.generate_mapping([0, 0])\n mapping1.metadata.exec_time = 10.2\n mapping1.metadata.energy = 21.45\n\n mapping2 = mapper.generate_mapping([0, 3])\n mapping2.metadata.exec_time = 5.2\n mapping2.metadata.energy = 31.15\n\n attributes = {\"num_resources\": num_resources}\n with MappingTableWriter(\n platform, graph, output_file, attributes=attributes\n ) as writer:\n writer.write_header()\n writer.write_mapping(mapping1)\n writer.write_mapping(mapping2)\n assert filecmp.cmp(output_file, expected_csv, shallow=False)\n","repo_name":"tud-ccc/mocasin","sub_path":"mocasin/util/test/test_mapping_table.py","file_name":"test_mapping_table.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"30118112207","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\nfrom dm.skills.Common._common import CommonSkill\nfrom utilities import SkillEffect, CooldownType\n\nif TYPE_CHECKING:\n from dm.core.contexts import AttackContext\n from dm.core.game.game import DMGame\n from dm.core.objects.unit import DMUnit\n################################################################################\n\n__all__ = (\"ScarletMoon\",)\n\n################################################################################\nclass ScarletMoon(CommonSkill):\n\n def __init__(self, state: DMGame, parent: DMUnit = None):\n\n super().__init__(\n state, parent,\n _id=\"SKL-185\",\n name=\"Scarlet Moon\",\n description=(\n \"Apply 8 (+0.8*ATK) Vampire, 2 Bloodlust to all allies in \"\n \"the room.\"\n ),\n rank=4,\n cooldown=CooldownType.RoomWide,\n effect=SkillEffect(base=8, scalar=0.8)\n )\n\n################################################################################\n def execute(self, ctx: AttackContext) -> None:\n\n # For each ally in the room\n for unit in ctx.room.units_of_type(self.owner):\n # Apply Vampire\n unit.add_status(\"Vampire\", self.effect, self)\n # Apply Bloodlust\n unit.add_status(\"Bloodlust\", 2, self)\n\n################################################################################\n","repo_name":"AllegroVivo/DungeonDefense","sub_path":"dm/skills/Common/SRank/ScarletMoon.py","file_name":"ScarletMoon.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5006270963","text":"array = [7,5,9,0,3,1,6,2,9,1,4,8,0,5,2]\nN = len(array)\n\ncount = [0] * (N+1)\n\nfor i in range(N):\n count[array[i]] += 1\n\nfor i in range(len(count)):\n for j in range(count[i]):\n print(i,end=' ')","repo_name":"sskong777/Algorithm","sub_path":"이것이코딩테스트다/정렬/6_6_계수정렬.py","file_name":"6_6_계수정렬.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"14289700375","text":"import logging\nimport pickle\nimport time\n\nfrom golem.core.service import LoopingCallService\nfrom golem.core.variables import PAYMENT_DEADLINE\nfrom golem.ethereum.exceptions import NotEnoughFunds\n\nlogger = logging.getLogger(__name__)\n\n\nclass TaskFundsLock: # pylint: disable=too-few-public-methods\n def __init__(self, task):\n self.price = task.subtask_price\n self.num_tasks = task.total_tasks\n self.task_deadline = task.header.deadline\n\n @property\n def gnt_lock(self):\n return self.price * self.num_tasks\n\n\nclass FundsLocker(LoopingCallService):\n def __init__(self, transaction_system, datadir, persist=True,\n interval_seconds=60):\n super().__init__(interval_seconds)\n self.task_lock = {}\n self.transaction_system = transaction_system\n self.dump_path = datadir / \"fundslockv1.pickle\"\n self.persist = persist\n self.restore()\n\n def lock_funds(self, task):\n task_id = task.header.task_id\n if self.task_lock.get(task_id) is not None:\n logger.error(\"Tried to duplicate lock_fund with same \"\n \"task_id %r\", task_id)\n return\n\n tfl = TaskFundsLock(task)\n logger.info(\n 'Locking funds for task: %r price: %f num: %d',\n task_id,\n tfl.price,\n tfl.num_tasks,\n )\n self.task_lock[task_id] = tfl\n self.dump_locks()\n self.transaction_system.lock_funds_for_payments(\n tfl.price,\n tfl.num_tasks,\n )\n\n def remove_old(self):\n time_ = time.time()\n for task_id, task in list(self.task_lock.items()):\n if task.task_deadline + PAYMENT_DEADLINE < time_:\n del self.task_lock[task_id]\n self.dump_locks()\n\n def _run(self):\n self.remove_old()\n\n def restore(self):\n if not self.persist:\n return\n if not self.dump_path.exists():\n return\n with self.dump_path.open('rb') as f:\n try:\n self.task_lock = pickle.load(f)\n except (pickle.UnpicklingError, EOFError, AttributeError, KeyError):\n logger.exception(\"Problem restoring dumpfile: %s\",\n self.dump_path)\n return\n for task_id, task in self.task_lock.items():\n logger.info('Restoring old tasks locks: %r', task_id)\n # Bandait solution for increasing gas price\n try:\n self.transaction_system.lock_funds_for_payments(\n task.price,\n task.num_tasks,\n )\n except NotEnoughFunds:\n pass\n\n def dump_locks(self):\n if not self.persist:\n return\n with self.dump_path.open('wb') as f:\n pickle.dump(self.task_lock, f)\n\n def remove_subtask(self, task_id):\n task_lock = self.task_lock.get(task_id)\n if task_lock is None:\n logger.warning(\"I can't remove payment lock for subtask from task\"\n \"%r: unkown task.\", task_id)\n return\n logger.info('Removing subtask lock for task %r', task_id)\n task_lock.num_tasks -= 1\n self.dump_locks()\n self.transaction_system.unlock_funds_for_payments(task_lock.price, 1)\n\n def remove_task(self, task_id):\n task_lock = self.task_lock.get(task_id)\n if task_lock is None:\n logger.warning(\"I can't remove payment lock from task\"\n \"%r: unkown task.\", task_id)\n return\n logger.info('Removing task lock %r', task_id)\n del self.task_lock[task_id]\n self.dump_locks()\n self.transaction_system.unlock_funds_for_payments(\n task_lock.price,\n task_lock.num_tasks,\n )\n","repo_name":"albert19882016/golem","sub_path":"golem/ethereum/fundslocker.py","file_name":"fundslocker.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"29183767607","text":"from infra.ya_salt.lib.packages import action, transaction, transaction_validator, stateutil\n\nLO_STATE = [\n {\n \"name\": \"nvidia_driver_installed\",\n \"install_recommends\": False,\n \"refresh\": False,\n \"state\": \"pkg\",\n \"__id__\": \"nvidia_driver_installed\",\n \"fun\": \"installed\",\n \"__env__\": \"search_runtime\",\n \"__sls__\": \"components.nvidia.driver-418-v2\",\n \"order\": 10199,\n \"pkgs\": [\n {\n \"nvidia-418\": \"418.67-0ubuntu1\"\n },\n {\n \"nvidia-418-dev\": \"418.67-0ubuntu1\"\n },\n {\n \"nvidia-modprobe\": \"418.67-0ubuntu1\"\n },\n {\n \"libcuda1-418\": \"418.67-0ubuntu1\"\n },\n \"nvidia-common\",\n {\n \"libc6-i386\": \"2.23-0ubuntu10\"\n },\n {\n \"libc6-dev\": \"2.23-0ubuntu10\"\n },\n {\n \"libc6\": \"2.23-0ubuntu10\"\n },\n {\n \"libc-bin\": \"2.23-0ubuntu10\"\n },\n {\n \"libc-dev-bin\": \"2.23-0ubuntu10\"\n },\n {\n \"locales\": \"2.23-0ubuntu10\"\n },\n {\n \"multiarch-support\": \"2.23-0ubuntu10\"\n }\n ]\n },\n {\n \"name\": \"yandex-hbf-agent-purged\",\n \"state\": \"pkg\",\n \"pkgs\": [\n \"yandex-hbf-agent-static\",\n \"yandex-hbf-agent-init\"\n ],\n \"fun\": \"purged\",\n \"__env__\": \"search_runtime\",\n \"__sls__\": \"services.yandex-hbf-agent\",\n \"order\": 10229,\n \"__id__\": \"yandex-hbf-agent-purged\"\n }\n]\n\n\nclass TestTransaction(object):\n def test_install(self):\n tx = transaction.Transaction()\n tx.installed(action.Install('pkg-mock', 'ver-mock', 'src-mock'))\n assert len(tx.get_installed()) == 1\n assert tx.get_installed()['pkg-mock'][0].name == 'pkg-mock'\n assert tx.get_installed()['pkg-mock'][0].version == 'ver-mock'\n assert tx.get_installed()['pkg-mock'][0].src == 'src-mock'\n\n def test_remove(self):\n tx = transaction.Transaction()\n tx.removed(action.Remove('pkg-mock', 'src-mock'))\n assert len(tx.get_removed()) == 1\n assert tx.get_removed()['pkg-mock'][0].name == 'pkg-mock'\n assert tx.get_removed()['pkg-mock'][0].src == 'src-mock'\n\n def test_get_pkg_installed_version_of_installed_package(self):\n tx = transaction.Transaction()\n tx.installed(action.Install('pkg-mock', 'ver-mock', 'src-mock'))\n assert transaction.get_pkg_installed_version('pkg-mock', tx) == ('ver-mock', None,)\n\n def test_get_pkg_installed_version_of_not_installed_package(self):\n tx = transaction.Transaction()\n tx.installed(action.Install('pkg-mock', 'ver-mock', 'src-mock'))\n ver, err = transaction.get_pkg_installed_version('not-installed-pkg-mock', tx)\n assert ver is None\n assert err == 'package \"not-installed-pkg-mock\" is not scheduled to be installed'\n\n\nclass TestTransactionValidator(object):\n def test_validate_packages_loop(self):\n tx = transaction.Transaction()\n tx.installed(action.Install('pkg-mock', 'ver-mock', 'src-mock'))\n tx.removed(action.Remove('pkg-mock', 'other-src-mock'))\n messages = transaction_validator.validate_packages_loop(tx)\n expected_messages = [\n 'install-remove loop detected for package \"pkg-mock\" - '\n 'Remove(\"pkg-mock\", src: \"other-src-mock\"), '\n 'Install(\"pkg-mock\"=\"ver-mock\", src: \"src-mock\")'\n ]\n assert messages == expected_messages\n\n def test_validate_packages_versions_loop(self):\n tx = transaction.Transaction()\n tx.installed(action.Install('pkg-mock', 'v1', 'src1-mock'))\n tx.installed(action.Install('pkg-mock', 'v2', 'src2-mock'))\n messages = transaction_validator.validate_packages_versions_loop(tx)\n expected_messages = [\n 'version loop detected for package \"pkg-mock\" - '\n 'Install(\"pkg-mock\"=\"v1\", src: \"src1-mock\"), '\n 'Install(\"pkg-mock\"=\"v2\", src: \"src2-mock\")'\n ]\n assert messages == expected_messages\n\n def test_validate_packages_versions_present(self):\n tx = transaction.Transaction()\n tx.installed(action.Install('pkg-mock1', None, 'src1-mock'))\n tx.installed(action.Install('pkg-mock2', '', 'src2-mock'))\n messages = transaction_validator.validate_packages_versions_present(tx)\n expected_messages = sorted([\n 'package action Install(\"pkg-mock1\"=\"None\", src: \"src1-mock\") has no version',\n 'package action Install(\"pkg-mock2\"=\"\", src: \"src2-mock\") has no version',\n ])\n assert sorted(messages) == expected_messages\n\n def test_validate_transaction(self):\n tx = transaction.Transaction()\n tx.removed(action.Remove('pkg-mock', 'other-src-mock'))\n tx.installed(action.Install('pkg-mock', 'v1', 'src-mock'))\n tx.installed(action.Install('pkg-mock', 'v2', 'src2-mock'))\n tx.installed(action.Install('pkg-mock3', None, 'src3-mock'))\n messages = transaction_validator.validate_transaction(tx)\n expected_messages = [\n 'package action Install(\"pkg-mock3\"=\"None\", src: \"src3-mock\") has no version',\n\n 'install-remove loop detected for package \"pkg-mock\" - '\n 'Remove(\"pkg-mock\", src: \"other-src-mock\"), '\n 'Install(\"pkg-mock\"=\"v1\", src: \"src-mock\"), '\n 'Install(\"pkg-mock\"=\"v2\", src: \"src2-mock\")',\n\n 'version loop detected for package \"pkg-mock\" - '\n 'Install(\"pkg-mock\"=\"v1\", src: \"src-mock\"), '\n 'Install(\"pkg-mock\"=\"v2\", src: \"src2-mock\")'\n ]\n assert messages == expected_messages\n\n\nclass TestStatUtil(object):\n def test_extract_lo_packages_to_transaction(self):\n tx = transaction.Transaction()\n stateutil.extract_lo_packages_to_tx(LO_STATE, tx)\n assert len(tx.get_installed().keys()) == 12\n assert len(tx.get_removed().keys()) == 2\n assert transaction.get_pkg_installed_version('nvidia-common', tx) == (None, None,)\n assert transaction.get_pkg_installed_version('nvidia-418', tx) == ('418.67-0ubuntu1', None,)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"infra/tests/test_packages.py","file_name":"test_packages.py","file_ext":"py","file_size_in_byte":6336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42484093403","text":"\"\"\"\nhttps://stepik.org/lesson/24470/step/10?unit=6776\n\n\nВам дана последовательность строк.\nВыведите строки, содержащие обратный слеш \"\\\".\n\nSample Input:\n\n\\w denotes word character\nNo slashes here\n\nSample Output:\n\n\\w denotes word character\n\"\"\"\nimport re\nimport sys\n\npattern = r'.*\\\\.*'\n\nfor line in sys.stdin:\n line = line.rstrip()\n result = re.findall(pattern, line)\n for each_line in result:\n print(each_line)\n","repo_name":"DorogAD/stepik","sub_path":"stepik_tasks/python_basics_and_usage/unit3.2/task3-2-10.py","file_name":"task3-2-10.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12526918999","text":"import re\n\ndef parse_markdown(markdown):\n lines = markdown.split('\\n')\n response, in_list = '', False\n for line in lines:\n line = markdown_emphasis(line)\n line, in_list = markdown_list(line, in_list)\n if not in_list:\n line = markdown_titles(line)\n line = markdown_paragraph(line)\n response += line\n if in_list:\n response += ''\n return response\n\n\ndef markdown_emphasis(line):\n #bold\n for found in re.findall(r'\\b__.*__\\b', line):\n line = line.replace(found, f'{found[2:-2]}')\n\n #italic\n for found in re.findall(r'\\s_.*_\\s', line):\n line = line.replace(found, f' {found[2:-2]} ')\n\n return line\n\ndef markdown_titles(line):\n hashtags = re.match(r'^[#]+\\s', line)\n if hashtags:\n number = hashtags.group().count('#')\n line = f'' + line[number + 1:] + f''\n return line\n\ndef markdown_list(line, in_list):\n if re.match(r'^\\*\\s', line):\n line = '' + line[2:] + ''\n if not in_list:\n line = '' + line\n in_list = True\n else:\n if in_list:\n in_list = False\n line += '
'\n return line, in_list\n\ndef markdown_paragraph(line):\n if not re.match('{line}'\n return line","repo_name":"paulozava/exerciscm","sub_path":"python/markdown/markdown.py","file_name":"markdown.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19122694093","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n\nclass Attention_block(nn.Module):\n def __init__(self,F_g,F_l,F_int):\n super(Attention_block, self).__init__()\n self.W_g = nn.Sequential(\n nn.Conv3d(F_g, F_int, kernel_size =3, stride =1, padding =1),\n nn.BatchNorm3d(F_int)\n )\n self.W_x = nn.Sequential(\n nn.Conv3d(F_l, F_int, kernel_size =3, stride =1, padding =1),\n nn.BatchNorm3d(F_int)\n )\n self.psi = nn.Sequential(\n nn.Conv3d(F_int, 1, kernel_size =3, stride =1, padding =1),\n nn.BatchNorm3d(1),\n nn.Sigmoid()\n )\n self.relu = nn.ReLU(inplace = True)\n def forward(self, g, x):\n g1 = self.W_g(g)\n x1 = self.W_x(x)\n #print(g1.shape)\n #print(x1.shape)\n g1 = F.interpolate(g1, scale_factor = (x1.shape[2]/g1.shape[2],x1.shape[3]/g1.shape[3],x1.shape[4]/g1.shape[4]), mode = 'trilinear')\n #print(g1.shape)\n psi = self.relu(g1+x1)\n psi = self.psi(psi)\n #print(psi.shape)\n\n return x*psi\n\nclass conv_block(nn.Module):\n def __init__(self, ch_in, ch_out):\n super(conv_block,self).__init__()\n self.conv = nn.Sequential(\n nn.Conv3d(ch_in, ch_out, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(ch_out),\n nn.ReLU(inplace = True),\n nn.Conv3d(ch_in, ch_out, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(ch_out),\n nn.ReLU(inplace = True)\n )\n def forward(self,x):\n x = self.conv(x)\n return x\n \nclass up_conv(nn.Module):\n def __init__(self,ch_in,ch_out):\n super(up_conv, self).__init__()\n self.up = nn.Sequential(\n nn.Upsample(scale_factor =2),\n nn.Conv3d(ch_in,ch_out,3,stride =1 ,padding =1),\n nn.BatchNorm3d(ch_out),\n nn.ReLU(inpalce =True)\n )\n def forward(self, x):\n x =self.up(x)\n return x \n\n\n\nclass Att_Unet(nn.Module):\n def __init__(self, in_channel = 1, out_channel = 1, training = True):\n super(Att_Unet, self).__init__()\n self.trianing = training\n # encoder section\n self.encoder1 = nn.Sequential(\n nn.Conv3d(in_channel, 16, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(16),\n nn.ReLU(inplace = True),\n nn.Conv3d(16, 32, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(32),\n nn.ReLU(inplace = True)\n ).to(\"cuda:0\")\n self.encoder2 = nn.Sequential(\n nn.Conv3d(32, 32, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(32),\n nn.ReLU(inplace = True),\n nn.Conv3d(32, 64, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace = True)\n ).to(\"cuda:0\")\n\n self.encoder3 = nn.Sequential(\n nn.Conv3d(64, 64, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace = True),\n nn.Conv3d(64, 128, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(128),\n nn.ReLU(inplace = True)\n ).to(\"cuda:0\")\n\n self.encoder4 = nn.Sequential(\n nn.Conv3d(128, 128, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(128),\n nn.ReLU(inplace = True)\n ).to(\"cuda:0\")\n\n self.att1 = Attention_block(F_g =128, F_l =128, F_int =128).to(\"cuda:0\")\n\n self.encoder5 = nn.Sequential(\n nn.Conv3d(128, 256, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(256),\n nn.ReLU(inplace = True)\n ).to(\"cuda:0\")\n\n # decoder section\n self.decoder1 = nn.Sequential(\n nn.Conv3d(384, 64, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace = True)\n ).to('cuda:0')\n self.att2 = Attention_block(F_g=64, F_l=64, F_int =64).to(\"cuda:0\")\n self.decoder2 = nn.Sequential(\n nn.Conv3d(64, 64, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(64),\n nn.ReLU(inplace = True)\n ).to('cuda:0')\n self.decoder3 = nn.Sequential(\n nn.Conv3d(128, 32, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(32),\n nn.ReLU(inplace = True)\n ).to('cuda:1')\n self.att3 = Attention_block(F_g =32, F_l=32, F_int =32).to(\"cuda:1\")\n self.decoder4 = nn.Sequential(\n nn.Conv3d(32, 32, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(32),\n nn.ReLU(inplace = True)\n ).to('cuda:1')\n self.decoder5 = nn.Sequential(\n nn.Conv3d(64, 32, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(32),\n nn.ReLU(inplace = True)\n ).to('cuda:1')\n self.decoder6 = nn.Sequential(\n nn.Conv3d(32, 2, 3, stride = 1, padding = 1),\n nn.BatchNorm3d(2),\n nn.ReLU(inplace = True)\n ).to('cuda:1')\n self.decoder7 = nn.Sequential(\n nn.Conv3d(2, out_channel, 1)\n ).to('cuda:1')\n\n\n \n def forward(self, x):\n # encoder section\n x = x.to(\"cuda:0\")\n print('origin:',x.shape)\n x = self.encoder1(x).to(\"cuda:0\")# relu(4->8)\n f1 = x #(8)\n f1= f1.to(\"cuda:1\")\n print('f1:',x.shape)\n #print(\"encoder1_size:\",f1.shape)\n x = F.max_pool3d(x,kernel_size = 2,stride = 2,padding = 0).to(\"cuda:0\")# maxpool(8->8)\n #print(\"test\",x.shape)\n x = self.encoder2(x).to(\"cuda:0\")# relu(8->16)\n f2 = x #(16)\n f2 = f2.to(\"cuda:1\")\n print('f2:',x.shape)\n #print(\"encoder2_size:\",f2.shape)\n x = F.max_pool3d(x,kernel_size = 2,stride = 2,padding = 0).to(\"cuda:0\")# maxpool(16->16)\n \n x = self.encoder3(x).to(\"cuda:0\")# relu(16->32)\n f3 = x #(32)\n f3 =f3.to(\"cuda:0\")\n print('f3:',x.shape)\n #print(\"encoder3_size:\",f3.shape)\n x = F.max_pool3d(x,kernel_size = 2,stride = 2,padding = 0).to(\"cuda:0\")# maxpool(32->32)\n x = self.encoder4(x).to(\"cuda:0\")# relu(32->32)\n a1 = x\n x=x.to(\"cuda:0\")\n a1=a1.to(\"cuda:0\")\n print('x:',x.shape)\n A1 = self.att1(g = f3, x =a1).to(\"cuda:0\") #attention block1\n print('A1:',A1.shape)\n x = self.encoder5(x).to(\"cuda:0\") #relu(32->64)\n print('x:',x.shape)\n \n # decoder section\n\n x = F.interpolate(x, scale_factor = (f3.shape[2]/x.shape[2],f3.shape[3]/x.shape[3],f3.shape[4]/x.shape[4]), mode = 'trilinear').to(\"cuda:0\")# upsample(16->16)\n print('x:',x.shape)\n A1 = F.interpolate(A1, scale_factor = (f3.shape[2]/A1.shape[2],f3.shape[3]/A1.shape[3],f3.shape[4]/A1.shape[4]), mode = 'trilinear').to(\"cuda:0\")# upsample(16->16)\n print('A1:',A1.shape)\n x = torch.cat((x,A1),1).to(\"cuda:0\") #(64+32 = 96)\n print('x:',x.shape)\n x = x.to(\"cuda:0\")\n x = self.decoder1(x).to(\"cuda:0\") # relu(96 ->32)\n print('x:',x.shape)\n\n a2 = x #attention block2, size = 32\n a2 = a2.to(\"cuda:0\")\n print('a2:',a2.shape)\n print('f2:',f2.shape)\n f2 = f2.to('cuda:0')\n A2 = self.att2(g =f2,x=a2).to(\"cuda:0\") # size =32\n print('A2',A2.shape)\n A2 = F.interpolate(A2, scale_factor = (f2.shape[2]/A2.shape[2],f2.shape[3]/A2.shape[3],f2.shape[4]/A2.shape[4]), mode = 'trilinear').to(\"cuda:1\") # upsample(16->16)\n # x = x.to(\"cuda:1\")\n #print(\"decoder1_size:\",x.shape)\n # x = x.to(\"cuda:1\")\n x = self.decoder2(x).to(\"cuda:0\") #relu(32->32)\n print('x:',x.shape)\n x= x.to(\"cuda:1\")\n x = F.interpolate(x, scale_factor =(f2.shape[2]/x.shape[2],f2.shape[3]/x.shape[3],f2.shape[4]/x.shape[4]), mode = 'trilinear').to(\"cuda:1\") # upsample(256->256)\n print('A2:',A2.shape)\n x = torch.cat((x,A2),1).to(\"cuda:1\") #(4+4 = 8)\n # x = x.to(\"cuda:1\")\n print('x:',x.shape)\n x = self.decoder3(x).to(\"cuda:1\") # relu(8 ->2)\n print('x:',x.shape)\n #print(\"decoder2_size:\",x.shape)\n a3 = x#attention block2\n print('a3:',a3.shape)\n f1 = f1.to(\"cuda:1\")\n a3 = a3.to(\"cuda:1\")\n A3 = self.att3(g =f1,x=a3).to(\"cuda:1\")\n print('x:',x.shape)\n A3 = F.interpolate(A3, scale_factor = (f1.shape[2]/A3.shape[2],f1.shape[3]/A3.shape[3],f1.shape[4]/A3.shape[4]), mode = 'trilinear').to(\"cuda:1\") # upsample(16->16)\n print('A3:',A3.shape)\n # x = x.to(\"cuda:1\")\n x = self.decoder4(x).to(\"cuda:1\") #relu(2->2)\n print('x:',x.shape)\n x = F.interpolate(x, scale_factor =(f1.shape[2]/x.shape[2],f1.shape[2]/x.shape[2],f1.shape[2]/x.shape[2]), mode = 'trilinear').to(\"cuda:1\") # upsample(128->128)\n print('x:',x.shape)\n x = torch.cat((x,A3),1).to(\"cuda:1\") #(2+2 = 4)\n print('x:',x.shape)\n # x= x.to(\"cuda:2\")\n x = self.decoder5(x).to(\"cuda:1\") # relu(4 ->2)\n print('x:',x.shape)\n #print(\"decoder3_size:\",x.shape)\n x = self.decoder6(x).to(\"cuda:1\")\n print('x:',x.shape)\n x = self.decoder7(x).to(\"cuda:1\")\n print('x:',x.shape)\n x = F.interpolate(x, scale_factor = (f1.shape[2]/x.shape[2],f1.shape[3]/x.shape[3],f1.shape[4]/x.shape[4]), mode = 'trilinear').to(\"cuda:1\")\n\n\n return x","repo_name":"BrunoFANG1/3D-Laision-Seg","sub_path":"model/Baseline.py","file_name":"Baseline.py","file_ext":"py","file_size_in_byte":9335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34616752537","text":"import tools\nfrom tools import get_arrays_median, single_dags, dags\nimport matplotlib.pyplot as plt\n\nkwargs = {\"marker\": \"\", \"markersize\": 2}\n\nsingle_dags_paths = get_arrays_median(single_dags, \"paths\")\nsingle_dags_colors = get_arrays_median(single_dags, \"colors\")\nhash_dags_paths = get_arrays_median(dags, \"paths\")\nhash_dags_colors = get_arrays_median(dags, \"colors\")\n\nplt.xlabel(\"Frame\")\nplt.ylabel(\"Time (ms)\")\n\n# plt.xlim(0, 1000)\n# plt.ylim(0, 5)\n\nplt.plot(tools.indices, single_dags_paths, color=\"red\", label=\"paths (DAG)\", **kwargs)\nplt.plot(tools.indices, single_dags_colors, color=\"orange\", label=\"colors (DAG)\", **kwargs)\nplt.plot(tools.indices, hash_dags_paths, color=\"green\", label=\"paths (Hash DAG)\", **kwargs)\nplt.plot(tools.indices, hash_dags_colors, color=\"cyan\", label=\"colors (Hash DAG)\", **kwargs)\n\nplt.legend()\nplt.show()\n\n# plt.plot(tools.indices, (hash_dags_paths - single_dags_paths) / single_dags_paths, color=\"blue\", **kwargs)\n# plt.plot(tools.indices, (hash_dags_colors - single_dags_colors) / single_dags_colors, color=\"purple\", **kwargs)\n# plt.show()","repo_name":"Phyronnaz/HashDAG","sub_path":"python/plot_frames.py","file_name":"plot_frames.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":99,"dataset":"github-code","pt":"3"}
+{"seq_id":"25826720159","text":"# generic imports\nimport os\nimport numpy as np\nimport pandas as pd\n\n# torch imports\nimport torch\nfrom torch.utils.data import Dataset\n\n# pyg imports\nimport torch_geometric.data as PyGData\n\n# torch cluster imports\nfrom torch_cluster import knn_graph\n\n\nclass BasicDataset(Dataset):\n def __init__(self, batches, auxiliary=False, k_neighbors=1, scale=None):\n\n self.PATH_DATASET = '/mnt/d/waleed/kaggle/IceCube/data/'\n if batches is not None:\n self.batches = batches\n else:\n raise TypeError(\"List of files should contain at least 1 train parquet file\")\n\n self.scale = scale\n self.initialize()\n\n self.event_ids = np.unique(self.batches.index)\n self.items = dict(zip(np.arange(self.event_ids.shape[0]), self.event_ids))\n\n self.auxiliary = auxiliary\n self.k_neighbors = k_neighbors\n\n def initialize(self):\n self.meta_data = pd.read_parquet(os.path.join(self.PATH_DATASET, 'train_meta.parquet'))\n self.geometry = pd.read_csv(os.path.join(self.PATH_DATASET, 'sensor_geometry.csv'))\n if isinstance(self.batches, list):\n self.batches = pd.concat(self.batches, ignore_index=True)\n\n def getdata(self):\n df = self.data[self.features]\n x, y = df.iloc[:, 0:-1].to_numpy(), df.iloc[:, -1].to_numpy()\n if self.scale is not None:\n x /= self.scale\n\n return x, y\n\n def __getitem__(self, item):\n event_num = self.items.get(item)\n position = self.geometry.iloc[self.batches.loc[event_num].sensor_id.tolist(), 1:].to_numpy()\n features = self.batches.loc[event_num,['time', 'charge', 'auxiliary']].astype(float).to_numpy()\n\n data = np.hstack([position, features])\n target = self.meta_data[self.meta_data.event_id==event_num][['azimuth', 'zenith']].to_numpy().flatten()\n\n if self.auxiliary:\n good_idx = np.where(data[:,-1]==0)[0]\n data = data[good_idx][:, 1:]\n\n x = torch.tensor(data, dtype=torch.float32)\n y = self.meta_data[self.meta_data.event_id==event_num][['azimuth', 'zenith']].to_numpy().flatten()\n y = torch.tensor(y, dtype=torch.float32)\n # graph connecvtivety by k_nn algorithm\n knn_graph_edge_index = knn_graph(x[:, 0:3], k=self.k_neighbors)\n\n return {\"data\": PyGData.Data(x=x, y=y, edge_index=knn_graph_edge_index), \"targets\": y}\n\n def __len__(self):\n return self.event_ids.shape[0]\n","repo_name":"wesmail/IceCubeChallenge","sub_path":"data_handling.py","file_name":"data_handling.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35946026724","text":"import random\r\n\r\n# Dafault values\r\nplayer_choice = None\r\nwinner = \"Tie\"\r\n\r\n# Turns player letter selection into the selected word.\r\n\r\n\r\ndef translator(choice):\r\n if choice == \"R\":\r\n return \"Rock\"\r\n elif choice == \"P\":\r\n return \"Paper\"\r\n elif choice == \"S\":\r\n return \"Scissors\"\r\n\r\n\r\n# Determines the winner of the game.\r\ndef winner_calculator(player_selection, computer_selection):\r\n if player_selection == \"Rock\":\r\n if computer_selection == \"Rock\":\r\n return \"Tie\"\r\n elif computer_selection == \"Paper\":\r\n return \"Computer wins\"\r\n elif computer_selection == \"Scissors\":\r\n return \"Player wins\"\r\n elif player_selection == \"Paper\":\r\n if computer_selection == \"Rock\":\r\n return \"Player wins\"\r\n elif computer_selection == \"Paper\":\r\n return \"Tie\"\r\n elif computer_selection == \"Scissors\":\r\n return \"Computer wins\"\r\n elif player_selection == \"Scissors\":\r\n if computer_selection == \"Rock\":\r\n return \"Computer wins\"\r\n elif computer_selection == \"Paper\":\r\n return \"Player wins\"\r\n elif computer_selection == \"Scissors\":\r\n return \"Tie\"\r\n\r\n\r\n# Game loop. Goes until one player wins.\r\nwhile winner == \"Tie\":\r\n # Player makes selection\r\n print(\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nChoose rock (r), paper (p), or scissors (s).\")\r\n player_choice = input()\r\n player_choice = player_choice.upper()\r\n\r\n # Error handling for when the selection is not rock, paper, or scissors.\r\n while player_choice != \"R\" and player_choice != \"P\" and player_choice != \"S\":\r\n print(\"Invalid choice. Please choose again.\")\r\n print(\"Choose rock (r), paper (p), or scissors (s).\")\r\n player_choice = input()\r\n player_choice = player_choice.upper()\r\n\r\n # Turns player letter selection into the selected word.\r\n player_selection = translator(player_choice)\r\n\r\n # Computer Selection\r\n computer_choice_list = [\"R\", \"P\", \"S\"]\r\n computer_choice = computer_choice_list[random.randint(0, 2)]\r\n computer_selection = translator(computer_choice)\r\n\r\n # Player and computer printed results.\r\n print(f\"You chose {player_selection}\")\r\n print(f\"The computer chose {computer_selection}\")\r\n\r\n # Calculates winner.\r\n winner = winner_calculator(player_selection, computer_selection)\r\n print(winner_calculator(player_selection, computer_selection))\r\n if winner == \"Tie\":\r\n print(\"Play again.\")\r\n","repo_name":"BradyL271/Python-Mini-projects","sub_path":"RockPaperScissors.py","file_name":"RockPaperScissors.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19668452216","text":"# logic: when we are standing at any node then to have same path value to leaf from the current node\n# cost value to leaf from both the subtree must be same.\n# if not same then we will incr the value of node in subtree having lower value by their diff i.e abs(l- r)'.\n\n# Reason: current node will common to both (left and right subtree), so ans will depend on the left and right subtree value only.\n\n# will go bottom up.\n\n# After that at each function call(at each node), we will return the cost to leaf from the current node.\n\nclass Solution:\n def minIncrements(self, n: int, cost: List[int]) -> int:\n self.count= 0\n \n def dfs(index):\n # if leaf node\n if 2*index >= n and 2*index + 1 >= n:\n return cost[index -1]\n l= dfs(2*index)\n r= dfs(2*index + 1)\n # to make the both subtree to have same weight till leaf \n self.count+= abs(l - r)\n return cost[index -1] + max(l, r) # return the cost to leaf from this node\n \n dfs(1) # calling from index '1'.\n return self.count\n","repo_name":"Ravi-0412/DSA-Program-And-Notes","sub_path":"Tree/Binary Tree/2673. Make Costs of Paths Equal in a Binary Tree.py","file_name":"2673. Make Costs of Paths Equal in a Binary Tree.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"3"}
+{"seq_id":"14882931292","text":"import numpy as np\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport random\nimport pandas as pd\nfrom collections import Counter\nimport numpy as np\nfrom sklearn.datasets import fetch_20newsgroups\nfrom collections import Counter, defaultdict\nfrom nltk.corpus import stopwords\nfrom sklearn.model_selection import train_test_split\nimport re\nfrom sklearn.utils import shuffle\nimport os\nfrom tqdm import tqdm, trange\nfrom torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\nfrom keras.preprocessing.sequence import pad_sequences\nfrom transformers import AutoTokenizer\nfrom torch.optim import Adam\nfrom transformers import BertTokenizer, BertConfig\nfrom transformers import AdamW, BertForSequenceClassification, get_linear_schedule_with_warmup\nfrom torch.cuda.amp import autocast, GradScaler\nimport wandb\n\ndef set_seed(args):\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n\ndef corrupt_dataset(args, data, num_labels):\n total_number = len(data)\n new_data = data.clone()\n random_indices = torch.rand(int(args.noise_ratio * total_number)) * total_number\n random_indices = random_indices.int()\n new_labels = torch.rand(int(len(random_indices))) * num_labels\n new_labels = new_labels.int()\n for i in range(len(random_indices)):\n temp_label = data[random_indices[i]]\n while temp_label == new_labels[i]:\n new_labels[i] = (torch.rand(1)[0] * num_labels).int()\n new_data[random_indices[i]] = new_labels[i]\n return new_data \n\ndef corrupt_dataset_asymmetric(args, data, num_labels):\n total_number = len(data)\n new_data = data.clone()\n random_indices = torch.rand(int(args.noise_ratio * total_number)) * total_number\n random_indices = random_indices.int()\n for i in range(len(random_indices)):\n temp_label = data[random_indices[i]]\n new_data[random_indices[i]] = (new_data[random_indices[i]] + 1) % num_labels\n return new_data \n\ndef load_dataset(args, dataset):\n\n if dataset == 'sst':\n df_train = pd.read_csv(\"/localscratch/yzhuang43/datasets/SST-2/train.tsv\", delimiter='\\t', header=0)\n \n df_val = pd.read_csv(\"/localscratch/yzhuang43/datasets/SST-2/dev.tsv\", delimiter='\\t', header=0)\n \n df_test = pd.read_csv(\"/localscratch/yzhuang43/datasets/SST-2/sst-test.tsv\", delimiter='\\t', header=None, names=['sentence', 'label'])\n\n train_sentences = df_train.sentence.values\n val_sentences = df_val.sentence.values\n test_sentences = df_test.sentence.values\n train_labels = df_train.label.values\n val_labels = df_val.label.values\n test_labels = df_test.label.values \n \n\n if dataset == '20news':\n \n VALIDATION_SPLIT = 0.8\n newsgroups_train = fetch_20newsgroups(data_home=args.path, subset='train', shuffle=True, random_state=0)\n print(newsgroups_train.target_names)\n print(len(newsgroups_train.data))\n\n newsgroups_test = fetch_20newsgroups(data_home=args.path, subset='test', shuffle=False)\n\n print(len(newsgroups_test.data))\n\n train_len = int(VALIDATION_SPLIT * len(newsgroups_train.data))\n\n train_sentences = newsgroups_train.data[:train_len]\n val_sentences = newsgroups_train.data[train_len:]\n test_sentences = newsgroups_test.data\n train_labels = newsgroups_train.target[:train_len]\n val_labels = newsgroups_train.target[train_len:]\n test_labels = newsgroups_test.target \n \n return train_sentences, val_sentences, test_sentences, train_labels, val_labels, test_labels\n\ndef read_data(args, num_labels):\n # load dataset\n \n train_sentences, val_sentences, test_sentences, train_labels, val_labels, test_labels = load_dataset(args, args.dataset)\n\n tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)\n\n train_input_ids = []\n val_input_ids = []\n test_input_ids = []\n \n if args.dataset == '20news':\n MAX_LEN = 150\n else:\n MAX_LEN = 256\n\n for sent in train_sentences:\n # `encode` will:\n # (1) Tokenize the sentence.\n # (2) Prepend the `[CLS]` token to the start.\n # (3) Append the `[SEP]` token to the end.\n # (4) Map tokens to their IDs.\n encoded_sent = tokenizer.encode(\n sent, # Sentence to encode.\n add_special_tokens = True, # Add '[CLS]' and '[SEP]'\n # This function also supports truncation and conversion\n # to pytorch tensors, but we need to do padding, so we\n # can't use these features :( .\n max_length = MAX_LEN, # Truncate all sentences.\n #return_tensors = 'pt', # Return pytorch tensors.\n )\n # Add the encoded sentence to the list.\n train_input_ids.append(encoded_sent)\n \n\n for sent in val_sentences:\n encoded_sent = tokenizer.encode(\n sent, \n add_special_tokens = True, \n max_length = MAX_LEN, \n )\n val_input_ids.append(encoded_sent)\n\n for sent in test_sentences:\n encoded_sent = tokenizer.encode(\n sent, \n add_special_tokens = True, \n max_length = MAX_LEN, \n )\n test_input_ids.append(encoded_sent)\n\n # Pad our input tokens\n train_input_ids = pad_sequences(train_input_ids, maxlen=MAX_LEN, dtype=\"long\", truncating=\"post\", padding=\"post\")\n val_input_ids = pad_sequences(val_input_ids, maxlen=MAX_LEN, dtype=\"long\", truncating=\"post\", padding=\"post\")\n test_input_ids = pad_sequences(test_input_ids, maxlen=MAX_LEN, dtype=\"long\", truncating=\"post\", padding=\"post\")\n # Create attention masks\n train_attention_masks = []\n val_attention_masks = []\n test_attention_masks = []\n\n # Create a mask of 1s for each token followed by 0s for padding\n for seq in train_input_ids:\n seq_mask = [float(i>0) for i in seq]\n train_attention_masks.append(seq_mask)\n for seq in val_input_ids:\n seq_mask = [float(i>0) for i in seq]\n val_attention_masks.append(seq_mask)\n for seq in test_input_ids:\n seq_mask = [float(i>0) for i in seq]\n test_attention_masks.append(seq_mask)\n\n # Convert all of our data into torch tensors, the required datatype for our model\n\n train_inputs = torch.tensor(train_input_ids)\n validation_inputs = torch.tensor(val_input_ids)\n train_labels = torch.tensor(train_labels)\n validation_labels = torch.tensor(val_labels)\n train_masks = torch.tensor(train_attention_masks)\n validation_masks = torch.tensor(val_attention_masks)\n test_inputs = torch.tensor(test_input_ids)\n test_labels = torch.tensor(test_labels)\n test_masks = torch.tensor(test_attention_masks)\n\n if args.noise_type == 's':\n noisy_train_labels = corrupt_dataset(args, train_labels, num_labels)\n noisy_validation_labels = corrupt_dataset(args, validation_labels, num_labels)\n else:\n noisy_train_labels = corrupt_dataset_asymmetric(args, train_labels, num_labels)\n noisy_validation_labels = corrupt_dataset_asymmetric(args, validation_labels, num_labels)\n \n # Create an iterator of our data with torch DataLoader. \n return train_inputs, train_masks, train_labels, noisy_train_labels, validation_inputs, validation_masks, validation_labels, noisy_validation_labels, test_inputs, test_masks, test_labels\n\n \n\ndef create_dataset(args, inputs, masks, labels, batch_size, noisy_labels=None):\n if noisy_labels != None:\n data = TensorDataset(inputs, masks, labels, noisy_labels)\n else:\n data = TensorDataset(inputs, masks, labels)\n \n sampler = SequentialSampler(data)\n dataloader = DataLoader(data, sampler=sampler, batch_size=batch_size)\n return sampler, dataloader","repo_name":"night-chen/DyGen","sub_path":"src/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8131,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"}
+{"seq_id":"32092720241","text":"__author__ = 'sindre'\n\nimport glob\nimport logging\nimport os\n\nimport shutil\nimport subprocess\nimport sys\nimport zipfile\n\nimport tool\n\nlogger = logging.getLogger(__name__)\n\n\nclass InstallerBuilder(object):\n \"\"\"控制构建安装程序。这包括三个主要步骤:\n\n 1.在构建目录中安排必要的文件\n 2.填写模板NSI文件以控制NSIS\n 3.运行 “makensis” 来构建安装程序\n\n \"\"\"\n python_template = \"\"\"\n\n \n {extra_preamble}\n \n if __name__ == '__main__':\n from {module} import {func}\n {func}() \n \n \n \"\"\"\n\n def __init__(self,\n name,\n version,\n requirementstxt,\n entry_point,\n source_path,\n icon=\"config/logo.ico\",\n author=\"SindreYang\",\n licence=\"config/licence.rtf\",\n onefile=1,\n tobinary=1,\n thirdpriority=1,\n build_dir=\"./build_py2nsis\",\n python_version=None):\n self.appname =name.replace(\" \",\"\")\n self.version = version\n self.requirementsTxT = os.path.abspath(requirementstxt)\n self.icon = os.path.abspath(icon)\n self.author = os.path.abspath(author)\n self.licence = os.path.abspath(licence)\n self.OneFile = bool(int(onefile))\n self.ToBinary = bool(int(tobinary))\n self.ThirdPriority = bool(int(thirdpriority))\n self.build_dir = os.path.abspath(build_dir)\n self.third_dir = os.path.abspath(os.path.join(build_dir, \"third\"))\n self.entry_point = entry_point\n self.source_path = os.path.abspath(source_path)\n self.work_dir = os.getcwd()\n self.tmp_path = os.path.abspath(os.path.join(self.build_dir, \"tmp\"))\n self.python_path = os.path.abspath(os.path.join(self.build_dir, \"py\"))\n if python_version is None:\n version = sys.version_info\n version_number = f\"{version.major}.{version.minor}.{version.micro}\"\n self.python_version= version_number\n else:\n self.python_version = python_version\n\n\n\n def install_third(self):\n from pip._internal import main as pip_main\n #pip_main(['install', \"pyinstaller\", '--target', self.tmp_path])\n pip_main(['install', \"pip\", '--target', self.third_dir])\n # 读取 requirements.txt 文件\n with open(self.requirementsTxT, 'r') as file:\n requirements = file.readlines()\n name_str = self.entry_point.split(':')\n import_name, fun_name = name_str[0], name_str[1]\n\n if self.ThirdPriority:\n\n # 安装所有的whl文件到指定目录下\n for requirement in requirements:\n pip_main(['install', requirement.strip(), '--target', self.third_dir])\n code = f\"\"\"\nimport sys, os\nimport site\nscriptdir, script = os.path.split(os.path.abspath(__file__))\ninstalldir = scriptdir\nthirddir = os.path.join(scriptdir, 'third')\nappdir =os.path.join(scriptdir, 'app')\nsys.path.insert(0, thirddir)\nsys.path.insert(0, appdir)\nsite.addsitedir(thirddir)\nsite.addsitedir(appdir)\n\n\nif __name__ == '__main__':\n import qtmain\n {import_name}.{fun_name}()\n\"\"\"\n with open(os.path.join(self.build_dir, 'app.py', ), 'w', encoding=\"utf-8\") as f:\n f.write(code)\n\n else:\n shutil.copy(self.requirementsTxT, self.build_dir)\n # 否则写入脚本中,用户启动时在安装\n code = f\"\"\"\nimport sys, os\nimport site\nscriptdir, script = os.path.split(os.path.abspath(__file__))\ninstalldir = scriptdir\nthirddir = os.path.join(scriptdir, 'third')\nappdir =os.path.join(scriptdir, 'app')\nsys.path.insert(0, thirddir)\nsys.path.insert(0, appdir)\nsite.addsitedir(thirddir)\nsite.addsitedir(appdir)\n\n\nif __name__ == '__main__':\n try:\n import qtmain\n except Exception as e:\n print(\"import error:\",sys.path)\n try:\n from pip._internal import main as pip_main\n pip_main(['install', '-r', 'requirements.txt', '--target','third'])\n except Exception as e:\n print(\"pip error:\",e)\n {import_name}.{fun_name}()\n\"\"\"\n\n with open(os.path.join(self.build_dir, 'app.py', ), 'w', encoding=\"utf-8\") as f:\n f.write(code)\n\n def py2pyd(self):\n target_path = os.path.join(self.build_dir, \"app\")\n try:\n shutil.rmtree(target_path)\n except FileNotFoundError:\n pass\n shutil.copytree(self.source_path, target_path)\n if self.ToBinary:\n from setuptools import Extension, setup\n from Cython.Build import cythonize\n extensions = []\n py_files = []\n # 遍历目录下的所有文件\n for root, dirs, files in os.walk(target_path):\n for file in files:\n # 判断文件名是否以 .py 结尾\n if file.endswith('.py'):\n # 构建文件的完整路径\n file_path = os.path.join(root, file)\n py_files.append(file_path)\n\n # 构建扩展模块名称\n module_name = os.path.splitext(file)[0]\n\n # 构建扩展模块对象\n extension = Extension(module_name, sources=[file_path])\n extensions.append(extension)\n\n setup(\n ext_modules=cythonize(extensions, compiler_directives={'language_level': \"3\"}),\n script_args=[\"build_ext\", \"--inplace\", \"--build-lib\", f\"{target_path}\", \"--build-temp\",\n f\"{self.tmp_path}\"])\n\n # 删除.c和.py文件\n for file in glob.glob(os.path.join(target_path, \"**/*\"), recursive=True):\n if file.endswith((\".c\", \".py\")):\n os.remove(file)\n\n def py2exe_pyinstaller(self):\n # 调用命令行执行PyInstaller编译代码\n os.chdir(self.build_dir)\n check_file = \"onedir\"\n if self.OneFile:\n check_file = \"onefile\"\n\n code = f\"\"\"\nimport os\nimport sys\nscriptdir, script = os.path.split(os.path.abspath(__file__))\nthirddir = os.path.join(scriptdir, fR\"{self.tmp_path}\")\nthirddir2 = os.path.join(scriptdir, 'third')\nsys.path.insert(0, thirddir)\nsys.path.insert(0, thirddir2)\nimport PyInstaller.__main__\nPyInstaller.__main__.run([\n 'app.py',\n f'--{check_file}',\n '--add-data=app;app',\n '--add-data=third;third',\n '--specpath=./',\n '--distpath=./',\n '--workpath=./tmp',\n]) \n \n \"\"\"\n with open('installer.py', 'w', encoding=\"utf-8\") as f:\n f.write(code)\n\n subprocess.run([\"./py/python.exe\", \"./installer.py\"])\n def py2exe(self):\n # 调用命令行执行PyInstaller编译代码\n os.chdir(self.build_dir)\n code_c = R\"\"\"\n\n#include \n\nint main() {\n // 获取当前可执行文件的路径\n char exePath[MAX_PATH];\n GetModuleFileNameA(NULL, exePath, MAX_PATH);\n\n // 去除文件名部分,只保留目录路径\n char drive[_MAX_DRIVE];\n char dir[MAX_PATH];\n _splitpath_s(exePath, drive, sizeof(drive), dir, sizeof(dir), NULL, 0, NULL, 0);\n\n // 组合目录路径\n char dirPath[MAX_PATH];\n sprintf_s(dirPath, sizeof(dirPath), \"%s%s\", drive, dir);\n\n // 构建app.py的绝对路径\n char appPath[MAX_PATH];\n sprintf_s(appPath, sizeof(appPath), \"%sapp.py\", dirPath);\n\n // 构建python的绝对路径\n char pythonPath[MAX_PATH];\n sprintf_s(pythonPath, sizeof(pythonPath), \"%spy/python.exe\", dirPath);\n\n // 构建启动命令\n char command[MAX_PATH * 2];\n sprintf_s(command, sizeof(command), \"\\\"%s\\\" \\\"%s\\\"\", pythonPath, appPath);\n\n // 创建进程并执行命令\n STARTUPINFOA si = { sizeof(si) };\n PROCESS_INFORMATION pi;\n \n if (CreateProcessA(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {\n // 等待进程结束\n WaitForSingleObject(pi.hProcess, INFINITE);\n \n // 关闭进程和线程的句柄\n CloseHandle(pi.hProcess);\n CloseHandle(pi.hThread);\n }\n\n return 0;\n}\n \n \"\"\"\n with open('app.c', 'w', encoding=\"utf-8\") as f:\n f.write(code_c)\n code_steup = \"\"\"\nfrom distutils.ccompiler import new_compiler\nimport distutils.sysconfig\nimport sys\nimport os\nfrom pathlib import Path\n\ndef compile(src):\n src = Path(src)\n cc = new_compiler()\n exe = src.stem\n cc.add_include_dir(distutils.sysconfig.get_python_inc())\n cc.add_library_dir(os.path.join(sys.base_exec_prefix, 'libs'))\n # First the CLI executable\n objs = cc.compile([str(src)])\n cc.link_executable(objs, exe)\n # Now the GUI executable\n cc.define_macro('WINDOWS')\n objs = cc.compile([str(src)])\n cc.link_executable(objs, exe + 'w')\n\nif __name__ == \"__main__\":\n compile(\"app.c\") \n \n \"\"\"\n with open('app_setup.py', 'w', encoding=\"utf-8\") as f:\n f.write(code_steup)\n\n\n subprocess.run([\"./py/python.exe\", \"./app_setup.py\"])\n\n def exe2nsis(self):\n # 获取当前脚本的绝对路径\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n print(f\"exe2nsis工作目录:{os.getcwd()}\")\n self.exe_7z_path = os.path.abspath(\"../bin/7z/7z.exe\")\n self.exe_nsis_path = os.path.abspath(\"../bin/NSIS/makensis.exe\")\n self.config_path = os.path.abspath(\"../config\")\n # 压缩app目录\n files_to_compress =[f\"{os.path.abspath(self.build_dir)}/{i}\" for i in [\"app\", \"py\",\"third\",\"app.exe\",\"app.py\",\"requirements.txt\"]]\n subprocess.run([f\"{self.exe_7z_path}\", \"a\",f\"{self.work_dir}/app.7z\"]+files_to_compress)\n # 替换文件\n nsis_code =f\"\"\"\n# ====================== 自定义宏 产品信息==============================\n!define PRODUCT_NAME \t\t\"{self.appname}\"\n!define PRODUCT_PATHNAME \t\"{self.appname}\" #安装卸载项用到的KEY\n!define INSTALL_APPEND_PATH \"{self.appname}\" #安装路径追加的名称 \n!define INSTALL_DEFALT_SETUPPATH \"\" #默认生成的安装路径 \n!define EXE_NAME \t\t\"app.exe\" # 指定主运行程序,快捷方式也是用此程序生成\n!define PRODUCT_VERSION \t\t\"{self.version}\"\n!define PRODUCT_PUBLISHER \t\t\"{self.author}\"\n!define PRODUCT_LEGAL \t\t\"\"${{PRODUCT_PUBLISHER}} Copyright(c)2023\"\"\n!define INSTALL_OUTPUT_NAME \t\t\"{self.appname}_V{self.version}.exe\"\n\n# ====================== 自定义宏 安装信息==============================\n!define INSTALL_7Z_PATH \t \t\t\"{self.work_dir}\\\\app.7z\"\n!define INSTALL_7Z_NAME \t \t\t\"app.7z\"\n!define INSTALL_RES_PATH \t\t\"skin.zip\"\n!define INSTALL_LICENCE_FILENAME \"{self.licence}\"\n!define INSTALL_ICO \t\t\t\t\"{self.icon}\"\n\n\n!include \"ui.nsh\"\n\n# ==================== NSIS属性 ================================\n\n# 针对Vista和win7 的UAC进行权限请求.\n# RequestExecutionLevel none|user|highest|admin\nRequestExecutionLevel admin\n\n#SetCompressor zlib\n\n; 安装包名字.\nName \"${{PRODUCT_NAME}}\"\n\n# 安装程序文件名.\n\nOutFile \"{self.work_dir}\\\\{self.appname}_V{self.version}.exe\"\n\nInstallDir \"1\"\n\n# 安装和卸载程序图标\nIcon \"${{INSTALL_ICO}}\"\nUninstallIcon \"uninst.ico\"\n\n \n \"\"\"\n\n # 执行封装命令\n os.chdir(self.config_path)\n with open(\"output.nsi\", \"w\") as file:\n file.write(nsis_code)\n subprocess.run([f\"{self.exe_nsis_path}\", \"./output.nsi\"])\n\n\n\n\n def run(self,clean=False):\n \"\"\"\n 运行构建安装程序的所有步骤。\n \"\"\"\n\n try:\n # 从干净的构建目录开始\n shutil.rmtree(self.build_dir)\n except FileNotFoundError:\n pass\n os.makedirs(self.build_dir)\n os.makedirs(self.tmp_path)\n\n # 安装python\n tool.python_installer(self.python_path,version=self.python_version)\n\n\n #转换二进制\n self.py2pyd()\n\n # 安装依赖到指定文件夹\n self.install_third()\n\n # 生成单文件\n self.py2exe()\n\n\n # # 封装nsis\n self.exe2nsis()\n\n if clean:\n shutil.rmtree(self.build_dir)\n os.remove(f\"{self.work_dir}\\\\app.7z\")\n","repo_name":"SindreYang/py2nsis","sub_path":"py2nsis/src/installer_pipeline.py","file_name":"installer_pipeline.py","file_ext":"py","file_size_in_byte":12365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31243236911","text":"import itertools\nimport logging\nimport random\n\nfrom src.const import *\nfrom pygame.locals import *\n\nfrom src.paddle import Paddle\n\n\nclass Ball(pygame.sprite.Sprite):\n width = 50\n height = 50\n\n def __init__(self, game, pos, control=0):\n super().__init__()\n self.game = game\n self.x, self.y = pos\n self.dx, self.dy = 0, 0\n self.image = pygame.Surface((Ball.width, Ball.height))\n self.image.fill(D_GREY)\n self.rect = self.image.get_rect()\n self.rect.center = self.x, self.y\n self.send_delay = 3\n\n def update(self):\n self._handle_input()\n self.x += self.dx\n self.y += self.dy\n self.rect.center = self.x, self.y\n\n # rebound horizontally hitting paddle\n collidee = self.collide_with_paddle()\n if collidee:\n self.dx *= -1.5\n if abs(self.dx) > MAX_BALL_SPEED:\n self.dx = sign(self.dx) * MAX_BALL_SPEED\n self.dy += collidee.dy * 0.5\n\n # rebound vertically hitting floor or ceiling\n if self.rect.top < 0 or self.rect.bottom > DISPLAY_HEIGHT:\n self.dy *= -1\n # reset upon leaving horizontally\n if self.rect.right < 0 or self.rect.left > DISPLAY_WIDTH:\n self.game.ball.reset()\n if self.rect.right < 0:\n self.game.client.send_msg('win player2')\n else:\n self.game.client.send_msg('win player1')\n\n if self.game.control_type == 1:\n if self.send_delay == 0:\n self.game.client.send_msg(f'ball {self.x} {self.y}')\n self.send_delay = 3\n else:\n self.send_delay -= 1\n\n def draw(self):\n self.game.surface.blit(self.image, self.rect)\n\n def _handle_input(self):\n # single press\n for event in self.game.events:\n if event.type == KEYDOWN:\n key = event.key\n if key == pygame.K_SPACE:\n self.kick()\n\n def kick(self):\n rand_vel = (random.choice([-1, 1]) * random.randint(2, 4),\n random.choice([-1, 1]) * random.randint(2, 4))\n print(rand_vel)\n self.game.client.send_msg(f'b {rand_vel[0]} {rand_vel[1]}')\n self.dx = rand_vel[0]\n self.dy = rand_vel[1]\n\n def reset(self):\n self.x = DISPLAY_WIDTH / 2\n self.y = DISPLAY_HEIGHT / 2\n self.dx = 0\n self.dy = 0\n\n def collide_with_paddle(self):\n for sprite in self.game.entities:\n if self.rect.colliderect(sprite.rect) and isinstance(sprite, Paddle):\n return sprite\n","repo_name":"ozcer/PongPing","sub_path":"src/ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"29038217013","text":"from django.test import TestCase\nfrom django.contrib.auth import get_user_model\nfrom django.urls import reverse\n\nfrom core.models import User, Apartment\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\n\nAPARTMENTS_URL = reverse('apartment:apartment-list')\n\n\ndef detail_url(object_id):\n \"\"\"Return data_for_annotation detail URL\"\"\"\n return reverse('apartment:apartment-detail', args=[object_id])\n\n\ndef create_user(**params):\n \"\"\"Helper function to create new user\"\"\"\n return get_user_model().objects.create_user(**params)\n\n\ndef create_apartment(user, **params):\n \"\"\"Helper function to create new apartment\"\"\"\n return Apartment.objects.create(user= user,**params)\n\n\nclass ApartmentApiTestsForRealtor(TestCase):\n \"\"\"Test the apartments API for realtor\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n self.user = create_user(\n email='test@test.com',\n password='testpass',\n name='name'\n )\n self.user.role = User.REALTOR\n self.user.save()\n self.client.force_authenticate(user=self.user)\n\n def test_all_apartments_api(self):\n \"\"\"Test geting all apartments using realtor user\"\"\"\n res = self.client.get(APARTMENTS_URL)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n\n def test_add_apartment_api(self):\n \"\"\"Test adding all apartments using realtor user\"\"\"\n payload = {\n 'date': '2021-01-01',\n 'name': 'test name',\n 'description': 'test description',\n 'floor_area_size': 123.5,\n 'price_per_month': 123,\n 'number_of_rooms': 2,\n 'latitude': 123.3423,\n 'longitude': 123.3422,\n 'rented': False\n }\n res = self.client.post(APARTMENTS_URL, payload)\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n self.assertIn('name', res.data)\n self.assertIn('description', res.data)\n self.assertIn('floor_area_size', res.data)\n self.assertIn('price_per_month', res.data)\n self.assertIn('number_of_rooms', res.data)\n self.assertIn('latitude', res.data)\n self.assertIn('longitude', res.data)\n\n def test_update_apartment_api(self):\n \"\"\"Test updating all apartments using realtor user\"\"\"\n payload = {\n 'date': '2021-01-01',\n 'name': 'test name',\n 'description': 'test description',\n 'floor_area_size': 123.5,\n 'price_per_month': 123,\n 'number_of_rooms': 2,\n 'latitude': 123.34234,\n 'longitude': 123.34234,\n 'rented': True\n }\n apartment = create_apartment(self.user,**payload)\n payload['description'] = 'changed description'\n url = detail_url(apartment.pk)\n res = self.client.put(url, payload)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data['description'], payload['description'])\n\n def test_delete_apartment_api(self):\n \"\"\"Test deleting the apartment using realtor user\"\"\"\n payload = {\n \"name\": \"test name\",\n \"date\": \"2021-01-01\",\n \"description\": \"test description\",\n \"floor_area_size\": 123.5,\n \"price_per_month\": 123,\n \"number_of_rooms\": 2,\n \"latitude\": \"123.342300\",\n \"longitude\": \"123.342200\",\n \"rented\": False\n }\n apartment = create_apartment(self.user,**payload)\n url = detail_url(apartment.id)\n res = self.client.delete(url)\n self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)\n","repo_name":"baghoyanlevon/toptal_2","sub_path":"server/app/apartment/tests/test_apartments_for_realtor_api.py","file_name":"test_apartments_for_realtor_api.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27057204243","text":"import logging\nimport datetime\nfrom dataclasses import dataclass\nfrom decimal import Decimal\nfrom types import NoneType\nfrom typing import List, Optional, Literal, Collection, Iterable\n\nfrom web3.types import BlockIdentifier\n\nfrom eth_defi.aave_v3.rates import SECONDS_PER_YEAR\n\nfrom tradeexecutor.backtest.simulated_wallet import SimulatedWallet\nfrom tradeexecutor.ethereum.wallet import ReserveUpdateEvent\nfrom tradeexecutor.state.balance_update import BalanceUpdate\nfrom tradeexecutor.state.identifier import AssetIdentifier\nfrom tradeexecutor.state.position import TradingPosition\nfrom tradeexecutor.state.state import State\nfrom tradeexecutor.state.types import JSONHexAddress, BlockNumber\nfrom tradeexecutor.strategy.interest import update_interest, update_leveraged_position_interest\nfrom tradeexecutor.strategy.pricing_model import PricingModel\nfrom tradeexecutor.strategy.sync_model import SyncModel, OnChainBalance\nfrom tradeexecutor.strategy.trading_strategy_universe import TradingStrategyUniverse\nfrom tradeexecutor.testing.dummy_wallet import apply_sync_events\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass FundFlowEvent:\n \"\"\"One simulated deposit/redemption in backtest.\n\n - Events can be triggered any time with :py:meth:`BacktestSyncModel.simulate_funding`\n\n - Fund flow is added to the reserves during :py:meth:`BacktestSyncModel.sync_treasury`\n as it would be with live trading\n \"\"\"\n\n\n timestamp: datetime.datetime\n\n amount: Decimal\n\n\nclass BacktestSyncModel(SyncModel):\n \"\"\"Backtest sync model.\n\n Simulate deposit events to the backtest wallet.\"\"\"\n\n def __init__(self, wallet: SimulatedWallet, initial_deposit_amount: Decimal):\n assert isinstance(initial_deposit_amount, Decimal)\n self.wallet = wallet\n\n #: Simulated deposit/redemption events pending to be processed\n self.fund_flow_queue: List[FundFlowEvent] = []\n if initial_deposit_amount > 0:\n self.fund_flow_queue.append(FundFlowEvent(datetime.datetime.utcnow(), initial_deposit_amount))\n\n def get_token_storage_address(self) -> Optional[JSONHexAddress]:\n return None\n\n def sync_initial(self, state: State):\n \"\"\"Set up the initial sync details.\n\n For backtesting these are irrelevant.\n \"\"\"\n deployment = state.sync.deployment\n deployment.chain_id = None\n deployment.address = None\n deployment.block_number = None\n deployment.tx_hash = None\n deployment.block_mined_at = None\n deployment.vault_token_name = None\n deployment.vault_token_symbol = None\n\n def sync_treasury(\n self,\n strategy_cycle_ts: datetime.datetime,\n state: State,\n supported_reserves: Optional[List[AssetIdentifier]] = None,\n end_block: BlockNumber | NoneType = None,\n ) -> List[BalanceUpdate]:\n \"\"\"Apply the balance sync before each strategy cycle.\n\n .. warning::\n\n Old legacy code with wrong return signature compared to the parent class\n \"\"\"\n\n assert len(supported_reserves) == 1\n reserve_token = supported_reserves[0]\n\n assert end_block is None, \"Cannot use block ranges with backtesting\"\n\n reserve_update_events = [] # TODO: Legacy\n\n for funding_event in self.fund_flow_queue:\n\n past_balance = self.wallet.get_balance(reserve_token.address)\n\n # Update wallet\n self.wallet.update_balance(reserve_token.address, funding_event.amount)\n\n # Generate a deposit event\n reserve_update_events.append(\n ReserveUpdateEvent(\n asset=reserve_token,\n past_balance=past_balance,\n new_balance=self.wallet.get_balance(reserve_token.address),\n updated_at=strategy_cycle_ts,\n mined_at=funding_event.timestamp,\n )\n )\n\n balance_update_events = apply_sync_events(state, reserve_update_events)\n\n # Clear our pending funding simulation events\n self.fund_flow_queue = []\n\n return balance_update_events\n\n def simulate_funding(self, timestamp: datetime.datetime, amount: Decimal):\n \"\"\"Simulate a funding flow event.\n\n Call for the test to cause deposit or redemption for the backtest.\n The event goes to a queue and is processed in next `tick()`\n through `sync_portfolio()`.\n\n :param amount:\n Positive for deposit, negative for redemption\n\n \"\"\"\n self.fund_flow_queue.append(\n FundFlowEvent(timestamp, amount)\n )\n\n def create_transaction_builder(self) -> None:\n \"\"\"Backtesting does not need to care about how to build blockchain transactions.\"\"\"\n\n def calculate_accrued_interest(\n self,\n universe: TradingStrategyUniverse,\n position: TradingPosition,\n timestamp: datetime.datetime,\n interest_type: Literal[\"collateral\"] | Literal[\"borrow\"],\n ) -> Decimal:\n \"\"\"Calculate accrued interest of a position since last update.\"\"\"\n # get relevant candles for the position period since last update until now\n if interest_type == \"collateral\":\n interest = position.loan.collateral_interest\n amount = Decimal(interest.last_token_amount)\n elif interest_type == \"borrow\":\n interest = position.loan.borrowed_interest\n amount = Decimal(interest.last_token_amount)\n\n previous_update_at = interest.last_event_at\n\n df = universe.data_universe.lending_candles.supply_apr.df.copy()\n supply_df = df[\n (df[\"timestamp\"] >= previous_update_at)\n & (df[\"timestamp\"] <= timestamp)\n ].copy()\n\n if len(supply_df) == 0:\n # TODO: this is a temporary hack, we should make it better\n supply_df = df[\n (df[\"timestamp\"] >= position.opened_at)\n & (df[\"timestamp\"] <= timestamp)\n ].copy()\n\n assert len(supply_df) > 0, f\"No lending data for {position} from {previous_update_at} to {timestamp}\"\n\n # get average APR from high and low\n supply_df[\"avg\"] = supply_df[[\"high\", \"low\"]].mean(axis=1)\n avg_apr = Decimal(supply_df[\"avg\"].mean() / 100)\n\n duration = Decimal((timestamp - previous_update_at).total_seconds())\n accrued_interest_estimation = amount * avg_apr * duration / SECONDS_PER_YEAR\n\n return accrued_interest_estimation\n\n def sync_interests(\n self,\n timestamp: datetime.datetime,\n state: State,\n universe: TradingStrategyUniverse,\n positions: List[TradingPosition],\n pricing_model: PricingModel,\n ) -> List[BalanceUpdate]:\n\n assert universe.has_lending_data(), \"Cannot update credit positions if no data is available\"\n\n events = []\n for p in positions:\n if p.is_credit_supply():\n assert len(p.trades) <= 2, \"This interest calculation does not support increase/reduce position\"\n\n accrued = self.calculate_accrued_interest(\n universe,\n p,\n timestamp,\n \"collateral\",\n )\n\n new_amount = p.loan.collateral_interest.last_token_amount + accrued\n\n # TODO: the collateral is stablecoin so this can be hardcode for now\n # but make sure to fetch it from somewhere later\n price = 1.0\n\n evt = update_interest(\n state,\n p,\n p.pair.base,\n new_token_amount=new_amount,\n event_at=timestamp,\n asset_price=price,\n )\n events.append(evt)\n\n # Make atokens magically appear in the simulated\n # backtest wallet. The amount must be updated, or\n # otherwise we get errors when closing the position.\n self.wallet.update_balance(p.pair.base.address, accrued)\n elif p.is_leverage() and p.is_short():\n assert len(p.trades) <= 2, \"This interest calculation does not support increase/reduce position\"\n\n accrued_collateral_interest = self.calculate_accrued_interest(\n universe,\n p,\n timestamp,\n \"collateral\",\n )\n accrued_borrow_interest = self.calculate_accrued_interest(\n universe,\n p,\n timestamp,\n \"borrow\",\n )\n\n new_atoken_amount = p.loan.collateral_interest.last_token_amount + accrued_collateral_interest\n new_vtoken_amount = p.loan.borrowed_interest.last_token_amount + accrued_borrow_interest\n\n atoken_price = 1.0\n\n vtoken_price_structure = pricing_model.get_sell_price(\n timestamp,\n p.pair.get_pricing_pair(),\n p.loan.borrowed.quantity,\n )\n vtoken_price = vtoken_price_structure.price\n\n vevt, aevt = update_leveraged_position_interest(\n state,\n p,\n new_vtoken_amount=new_vtoken_amount,\n new_token_amount=new_atoken_amount,\n vtoken_price=vtoken_price,\n atoken_price=atoken_price,\n event_at=timestamp,\n )\n events.append(vevt)\n events.append(aevt)\n\n # Make aToken and vToken magically appear in the simulated\n # backtest wallet. The amount must be updated, or\n # otherwise we get errors when closing the position.\n self.wallet.rebase(p.pair.base.address, new_vtoken_amount)\n self.wallet.rebase(p.pair.quote.address, new_atoken_amount)\n\n return events\n\n def fetch_onchain_balances(\n self,\n assets: Collection[AssetIdentifier],\n filter_zero=True,\n block_identifier: BlockIdentifier = None,\n ) -> Iterable[OnChainBalance]:\n raise NotImplementedError(\"Backtesting does not know about on-chain balances\")","repo_name":"tradingstrategy-ai/trade-executor","sub_path":"tradeexecutor/backtest/backtest_sync.py","file_name":"backtest_sync.py","file_ext":"py","file_size_in_byte":10335,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"3"}
+{"seq_id":"71847400400","text":"num_as_str_in_list = input().split()\nintegers_to_remove = int(input())\nnum_list = [int(num_str) for num_str in num_as_str_in_list]\nsmallest_num = 0\nfor num in range(integers_to_remove):\n smallest_num = min(num_list)\n num_list.remove(smallest_num)\n#for element in num_list:\n# print(element, end= \" \")\nremaining_integers = [str(num) for num in num_list]\nresult_str = ', '.join(remaining_integers)\n\nprint(result_str)","repo_name":"MarioPetkov/Python_SoftUni","sub_path":"List basics/survival_of_the_biggest.py","file_name":"survival_of_the_biggest.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"13975333433","text":"'''Ler uma estrutura (lista, tupla ou conjunto), R de 5 elementos, inteiros, contendo o resultado da LOTO. \nA seguir ler outra estrutura (lista, tupla ou conjunto), A de 10 elementos inteiros contendo uma aposta. \nA seguir imprima quantos pontos fez o apostador.\n'''\n\nr = set()\na = set()\nx = set()\n\nfor i in range(0, 6):\n r.add(int(input(\"Valores da loto: \")))\n\nfor j in range(0, 9):\n a.add(int(input(\"Valores apostados: \")))\n\nx = r & a\n\nprint(f\"O número de pontos é {len(x)}\")","repo_name":"isaberamos/BSI-Algoritmos","sub_path":"Listas2/resultado-loto-conjuntos.py.py","file_name":"resultado-loto-conjuntos.py.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"73086285842","text":"from math import floor, sqrt\r\n\r\nx: int = int(input())\r\n\r\nif x == 0:\r\n print(\"inf\")\r\nelse:\r\n factors = 0\r\n for f in range(1, floor(sqrt(x)) + 1):\r\n q, r = divmod(x, f)\r\n if r == 0:\r\n factors += 1 + (q != f)\r\n print(factors)\r\n","repo_name":"xtevenx/sjudge","sub_path":"src/solutions/num_factors.py","file_name":"num_factors.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"31297682673","text":"from __future__ import absolute_import, division\n\nimport time\nimport re\nimport base64\nimport socket\nimport os\nimport random\nimport binascii\nimport warnings\n\nfrom email.utils import parseaddr\n\nfrom zope.interface import implementer\n\nfrom twisted import cred\nfrom twisted.copyright import longversion\nfrom twisted.protocols import basic\nfrom twisted.protocols import policies\nfrom twisted.internet import protocol\nfrom twisted.internet import defer\nfrom twisted.internet import error\nfrom twisted.internet import reactor\nfrom twisted.internet.interfaces import ITLSTransport, ISSLTransport\nfrom twisted.python import log\nfrom twisted.python import util\nfrom twisted.python.compat import (_PY3, range, long, unicode, networkString,\n nativeString, iteritems, _keys, _bytesChr,\n iterbytes)\nfrom twisted.python.runtime import platform\n\nfrom twisted.mail.interfaces import (IClientAuthentication,\n IMessageSMTP as IMessage,\n IMessageDeliveryFactory, IMessageDelivery)\nfrom twisted.mail._cred import (CramMD5ClientAuthenticator, LOGINAuthenticator,\n LOGINCredentials as _lcredentials)\nfrom twisted.mail._except import (\n AUTHDeclinedError, AUTHRequiredError, AddressError,\n AuthenticationError, EHLORequiredError, ESMTPClientError,\n SMTPAddressError, SMTPBadRcpt, SMTPBadSender, SMTPClientError,\n SMTPConnectError, SMTPDeliveryError, SMTPError, SMTPServerError,\n SMTPTimeoutError, SMTPTLSError as TLSError, TLSRequiredError,\n SMTPProtocolError)\n\n\nfrom io import BytesIO\n\n\n__all__ = [\n 'AUTHDeclinedError', 'AUTHRequiredError', 'AddressError',\n 'AuthenticationError', 'EHLORequiredError', 'ESMTPClientError',\n 'SMTPAddressError', 'SMTPBadRcpt', 'SMTPBadSender', 'SMTPClientError',\n 'SMTPConnectError', 'SMTPDeliveryError', 'SMTPError', 'SMTPServerError',\n 'SMTPTimeoutError', 'TLSError', 'TLSRequiredError', 'SMTPProtocolError',\n\n 'IClientAuthentication', 'IMessage', 'IMessageDelivery',\n 'IMessageDeliveryFactory',\n\n 'CramMD5ClientAuthenticator', 'LOGINAuthenticator', 'LOGINCredentials',\n 'PLAINAuthenticator',\n\n 'Address', 'User', 'sendmail', 'SenderMixin',\n 'ESMTP', 'ESMTPClient', 'ESMTPSender', 'ESMTPSenderFactory',\n 'SMTP', 'SMTPClient', 'SMTPFactory', 'SMTPSender', 'SMTPSenderFactory',\n\n 'idGenerator', 'messageid', 'quoteaddr', 'rfc822date', 'xtextStreamReader',\n 'xtextStreamWriter', 'xtext_codec', 'xtext_decode', 'xtext_encode'\n]\n\n\n# Cache the hostname (XXX Yes - this is broken)\nif platform.isMacOSX():\n # On macOS, getfqdn() is ridiculously slow - use the\n # probably-identical-but-sometimes-not gethostname() there.\n DNSNAME = socket.gethostname()\nelse:\n DNSNAME = socket.getfqdn()\n\n# Encode the DNS name into something we can send over the wire\nDNSNAME = DNSNAME.encode('ascii')\n\n# Used for fast success code lookup\nSUCCESS = dict.fromkeys(range(200, 300))\n\n\n\ndef rfc822date(timeinfo=None, local=1):\n \"\"\"\n Format an RFC-2822 compliant date string.\n\n @param timeinfo: (optional) A sequence as returned by C{time.localtime()}\n or C{time.gmtime()}. Default is now.\n @param local: (optional) Indicates if the supplied time is local or\n universal time, or if no time is given, whether now should be local or\n universal time. Default is local, as suggested (SHOULD) by rfc-2822.\n\n @returns: A L{bytes} representing the time and date in RFC-2822 format.\n \"\"\"\n if not timeinfo:\n if local:\n timeinfo = time.localtime()\n else:\n timeinfo = time.gmtime()\n if local:\n if timeinfo[8]:\n # DST\n tz = -time.altzone\n else:\n tz = -time.timezone\n\n (tzhr, tzmin) = divmod(abs(tz), 3600)\n if tz:\n tzhr *= int(abs(tz)//tz)\n (tzmin, tzsec) = divmod(tzmin, 60)\n else:\n (tzhr, tzmin) = (0, 0)\n\n return networkString(\"%s, %02d %s %04d %02d:%02d:%02d %+03d%02d\" % (\n ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timeinfo[6]],\n timeinfo[2],\n ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timeinfo[1] - 1],\n timeinfo[0], timeinfo[3], timeinfo[4], timeinfo[5],\n tzhr, tzmin))\n\n\n\ndef idGenerator():\n i = 0\n while True:\n yield i\n i += 1\n\n_gen = idGenerator()\n\n\n\ndef messageid(uniq=None, N=lambda: next(_gen)):\n \"\"\"\n Return a globally unique random string in RFC 2822 Message-ID format\n\n \n\n Optional uniq string will be added to strengthen uniqueness if given.\n \"\"\"\n datetime = time.strftime('%Y%m%d%H%M%S', time.gmtime())\n pid = os.getpid()\n rand = random.randrange(2**31-1)\n if uniq is None:\n uniq = ''\n else:\n uniq = '.' + uniq\n\n return '<%s.%s.%s%s.%s@%s>' % (datetime, pid, rand, uniq, N(), DNSNAME)\n\n\n\ndef quoteaddr(addr):\n \"\"\"\n Turn an email address, possibly with realname part etc, into\n a form suitable for and SMTP envelope.\n \"\"\"\n\n if isinstance(addr, Address):\n return b'<' + bytes(addr) + b'>'\n\n if isinstance(addr, bytes):\n addr = addr.decode('ascii')\n\n res = parseaddr(addr)\n\n if res == (None, None):\n # It didn't parse, use it as-is\n return b'<' + bytes(addr) + b'>'\n else:\n return b'<' + res[1].encode('ascii') + b'>'\n\nCOMMAND, DATA, AUTH = 'COMMAND', 'DATA', 'AUTH'\n\n\n# Character classes for parsing addresses\natom = br\"[-A-Za-z0-9!\\#$%&'*+/=?^_`{|}~]\"\n\nclass Address:\n \"\"\"Parse and hold an RFC 2821 address.\n\n Source routes are stipped and ignored, UUCP-style bang-paths\n and %-style routing are not parsed.\n\n @type domain: C{bytes}\n @ivar domain: The domain within which this address resides.\n\n @type local: C{bytes}\n @ivar local: The local (\\\"user\\\") portion of this address.\n \"\"\"\n\n tstring = re.compile(br'''( # A string of\n (?:\"[^\"]*\" # quoted string\n |\\\\. # backslash-escaped characted\n |''' + atom + br''' # atom character\n )+|.) # or any single character''', re.X)\n atomre = re.compile(atom) # match any one atom character\n\n\n def __init__(self, addr, defaultDomain=None):\n if isinstance(addr, User):\n addr = addr.dest\n if isinstance(addr, Address):\n self.__dict__ = addr.__dict__.copy()\n return\n elif not isinstance(addr, bytes):\n addr = str(addr).encode('ascii')\n\n self.addrstr = addr\n\n # Tokenize\n atl = list(filter(None, self.tstring.split(addr)))\n local = []\n domain = []\n\n while atl:\n if atl[0] == b'<':\n if atl[-1] != b'>':\n raise AddressError(\"Unbalanced <>\")\n atl = atl[1:-1]\n elif atl[0] == b'@':\n atl = atl[1:]\n if not local:\n # Source route\n while atl and atl[0] != b':':\n # remove it\n atl = atl[1:]\n if not atl:\n raise AddressError(\"Malformed source route\")\n atl = atl[1:] # remove :\n elif domain:\n raise AddressError(\"Too many @\")\n else:\n # Now in domain\n domain = [b'']\n elif (len(atl[0]) == 1 and\n not self.atomre.match(atl[0]) and\n atl[0] != b'.'):\n raise AddressError(\"Parse error at %r of %r\" % (atl[0], (addr, atl)))\n else:\n if not domain:\n local.append(atl[0])\n else:\n domain.append(atl[0])\n atl = atl[1:]\n\n self.local = b''.join(local)\n self.domain = b''.join(domain)\n if self.local != b'' and self.domain == b'':\n if defaultDomain is None:\n defaultDomain = DNSNAME\n self.domain = defaultDomain\n\n dequotebs = re.compile(br'\\\\(.)')\n\n\n def dequote(self, addr):\n \"\"\"\n Remove RFC-2821 quotes from address.\n \"\"\"\n res = []\n\n if not isinstance(addr, bytes):\n addr = str(addr).encode('ascii')\n\n atl = filter(None, self.tstring.split(addr))\n\n for t in atl:\n if t[0] == b'\"' and t[-1] == b'\"':\n res.append(t[1:-1])\n elif '\\\\' in t:\n res.append(self.dequotebs.sub(br'\\1', t))\n else:\n res.append(t)\n\n return b''.join(res)\n\n if _PY3:\n def __str__(self):\n return nativeString(bytes(self))\n else:\n def __str__(self):\n return self.__bytes__()\n\n\n def __bytes__(self):\n if self.local or self.domain:\n return b'@'.join((self.local, self.domain))\n else:\n return b''\n\n\n def __repr__(self):\n return \"%s.%s(%s)\" % (self.__module__, self.__class__.__name__,\n repr(str(self)))\n\n\n\nclass User:\n \"\"\"\n Hold information about and SMTP message recipient,\n including information on where the message came from\n \"\"\"\n def __init__(self, destination, helo, protocol, orig):\n try:\n host = protocol.host\n except AttributeError:\n host = None\n self.dest = Address(destination, host)\n self.helo = helo\n self.protocol = protocol\n if isinstance(orig, Address):\n self.orig = orig\n else:\n self.orig = Address(orig, host)\n\n\n def __getstate__(self):\n \"\"\"\n Helper for pickle.\n\n protocol isn't picklabe, but we want User to be, so skip it in\n the pickle.\n \"\"\"\n return { 'dest' : self.dest,\n 'helo' : self.helo,\n 'protocol' : None,\n 'orig' : self.orig }\n\n\n def __str__(self):\n return nativeString(bytes(self.dest))\n\n\n def __bytes__(self):\n return bytes(self.dest)\n\n\n\nclass SMTP(basic.LineOnlyReceiver, policies.TimeoutMixin):\n \"\"\"\n SMTP server-side protocol.\n\n @ivar host: The hostname of this mail server.\n @type host: L{bytes}\n \"\"\"\n\n timeout = 600\n portal = None\n\n # Control whether we log SMTP events\n noisy = True\n\n # A factory for IMessageDelivery objects. If an\n # avatar implementing IMessageDeliveryFactory can\n # be acquired from the portal, it will be used to\n # create a new IMessageDelivery object for each\n # message which is received.\n deliveryFactory = None\n\n # An IMessageDelivery object. A new instance is\n # used for each message received if we can get an\n # IMessageDeliveryFactory from the portal. Otherwise,\n # a single instance is used throughout the lifetime\n # of the connection.\n delivery = None\n\n # Cred cleanup function.\n _onLogout = None\n\n def __init__(self, delivery=None, deliveryFactory=None):\n self.mode = COMMAND\n self._from = None\n self._helo = None\n self._to = []\n self.delivery = delivery\n self.deliveryFactory = deliveryFactory\n self.host = DNSNAME\n\n\n @property\n def host(self):\n return self._host\n\n\n @host.setter\n def host(self, toSet):\n if not isinstance(toSet, bytes):\n toSet = str(toSet).encode('ascii')\n self._host = toSet\n\n\n\n def timeoutConnection(self):\n msg = self.host + b' Timeout. Try talking faster next time!'\n self.sendCode(421, msg)\n self.transport.loseConnection()\n\n\n def greeting(self):\n return self.host + b' NO UCE NO UBE NO RELAY PROBES'\n\n\n def connectionMade(self):\n # Ensure user-code always gets something sane for _helo\n peer = self.transport.getPeer()\n try:\n host = peer.host\n except AttributeError: # not an IPv4Address\n host = str(peer)\n self._helo = (None, host)\n self.sendCode(220, self.greeting())\n self.setTimeout(self.timeout)\n\n\n def sendCode(self, code, message=b''):\n \"\"\"\n Send an SMTP code with a message.\n \"\"\"\n lines = message.splitlines()\n lastline = lines[-1:]\n for line in lines[:-1]:\n self.sendLine(networkString('%3.3d-' % (code,)) + line)\n self.sendLine(networkString('%3.3d ' % (code,)) +\n (lastline and lastline[0] or b''))\n\n\n def lineReceived(self, line):\n self.resetTimeout()\n return getattr(self, 'state_' + self.mode)(line)\n\n\n def state_COMMAND(self, line):\n # Ignore leading and trailing whitespace, as well as an arbitrary\n # amount of whitespace between the command and its argument, though\n # it is not required by the protocol, for it is a nice thing to do.\n line = line.strip()\n\n parts = line.split(None, 1)\n if parts:\n method = self.lookupMethod(parts[0]) or self.do_UNKNOWN\n if len(parts) == 2:\n method(parts[1])\n else:\n method(b'')\n else:\n self.sendSyntaxError()\n\n\n def sendSyntaxError(self):\n self.sendCode(500, b'Error: bad syntax')\n\n\n def lookupMethod(self, command):\n \"\"\"\n\n @param command: The command to get from this class.\n @type command: L{str}\n @return: The function which executes this command.\n \"\"\"\n if not isinstance(command, str):\n command = nativeString(command)\n\n return getattr(self, 'do_' + command.upper(), None)\n\n\n def lineLengthExceeded(self, line):\n if self.mode is DATA:\n for message in self.__messages:\n message.connectionLost()\n self.mode = COMMAND\n del self.__messages\n self.sendCode(500, b'Line too long')\n\n\n def do_UNKNOWN(self, rest):\n self.sendCode(500, b'Command not implemented')\n\n\n def do_HELO(self, rest):\n peer = self.transport.getPeer()\n try:\n host = peer.host\n except AttributeError:\n host = str(peer)\n\n if not isinstance(host, bytes):\n host = host.encode('idna')\n\n self._helo = (rest, host)\n self._from = None\n self._to = []\n self.sendCode(250,\n self.host + b' Hello ' + host + b', nice to meet you')\n\n\n def do_QUIT(self, rest):\n self.sendCode(221, b'See you later')\n self.transport.loseConnection()\n\n # A string of quoted strings, backslash-escaped character or\n # atom characters + '@.,:'\n qstring = br'(\"[^\"]*\"|\\\\.|' + atom + br'|[@.,:])+'\n\n mail_re = re.compile(br'''\\s*FROM:\\s*(?P<> # Empty <>\n |<''' + qstring + br'''> # \n |''' + qstring + br''' # addr\n )\\s*(\\s(?P.*))? # Optional WS + ESMTP options\n $''', re.I|re.X)\n rcpt_re = re.compile(br'\\s*TO:\\s*(?P<' + qstring + br'''> # \n |''' + qstring + br''' # addr\n )\\s*(\\s(?P.*))? # Optional WS + ESMTP options\n $''', re.I|re.X)\n\n def do_MAIL(self, rest):\n if self._from:\n self.sendCode(503, b\"Only one sender per message, please\")\n return\n # Clear old recipient list\n self._to = []\n m = self.mail_re.match(rest)\n if not m:\n self.sendCode(501, b\"Syntax error\")\n return\n\n try:\n addr = Address(m.group('path'), self.host)\n except AddressError as e:\n self.sendCode(553, networkString(str(e)))\n return\n\n validated = defer.maybeDeferred(self.validateFrom, self._helo, addr)\n validated.addCallbacks(self._cbFromValidate, self._ebFromValidate)\n\n\n def _cbFromValidate(self, fromEmail, code=250,\n msg=b'Sender address accepted'):\n self._from = fromEmail\n self.sendCode(code, msg)\n\n\n def _ebFromValidate(self, failure):\n if failure.check(SMTPBadSender):\n self.sendCode(failure.value.code,\n (b'Cannot receive from specified address ' +\n quoteaddr(failure.value.addr) + b': ' +\n networkString(failure.value.resp)))\n elif failure.check(SMTPServerError):\n self.sendCode(failure.value.code,\n networkString(failure.value.resp))\n else:\n log.err(failure, \"SMTP sender validation failure\")\n self.sendCode(\n 451,\n b'Requested action aborted: local error in processing')\n\n\n def do_RCPT(self, rest):\n if not self._from:\n self.sendCode(503, b\"Must have sender before recipient\")\n return\n m = self.rcpt_re.match(rest)\n if not m:\n self.sendCode(501, b\"Syntax error\")\n return\n\n try:\n user = User(m.group('path'), self._helo, self, self._from)\n except AddressError as e:\n self.sendCode(553, networkString(str(e)))\n return\n\n d = defer.maybeDeferred(self.validateTo, user)\n d.addCallbacks(\n self._cbToValidate,\n self._ebToValidate,\n callbackArgs=(user,)\n )\n\n\n def _cbToValidate(self, to, user=None, code=250,\n msg=b'Recipient address accepted'):\n if user is None:\n user = to\n self._to.append((user, to))\n self.sendCode(code, msg)\n\n\n def _ebToValidate(self, failure):\n if failure.check(SMTPBadRcpt, SMTPServerError):\n self.sendCode(failure.value.code,\n networkString(failure.value.resp))\n else:\n log.err(failure)\n self.sendCode(\n 451,\n b'Requested action aborted: local error in processing'\n )\n\n\n def _disconnect(self, msgs):\n for msg in msgs:\n try:\n msg.connectionLost()\n except:\n log.msg(\"msg raised exception from connectionLost\")\n log.err()\n\n\n def do_DATA(self, rest):\n if self._from is None or (not self._to):\n self.sendCode(503, b'Must have valid receiver and originator')\n return\n self.mode = DATA\n helo, origin = self._helo, self._from\n recipients = self._to\n\n self._from = None\n self._to = []\n self.datafailed = None\n\n msgs = []\n for (user, msgFunc) in recipients:\n try:\n msg = msgFunc()\n rcvdhdr = self.receivedHeader(helo, origin, [user])\n if rcvdhdr:\n msg.lineReceived(rcvdhdr)\n msgs.append(msg)\n except SMTPServerError as e:\n self.sendCode(e.code, e.resp)\n self.mode = COMMAND\n self._disconnect(msgs)\n return\n except:\n log.err()\n self.sendCode(550, b\"Internal server error\")\n self.mode = COMMAND\n self._disconnect(msgs)\n return\n self.__messages = msgs\n\n self.__inheader = self.__inbody = 0\n self.sendCode(354, b'Continue')\n\n if self.noisy:\n fmt = 'Receiving message for delivery: from=%s to=%s'\n log.msg(fmt % (origin, [str(u) for (u, f) in recipients]))\n\n\n def connectionLost(self, reason):\n # self.sendCode(421, 'Dropping connection.') # This does nothing...\n # Ideally, if we (rather than the other side) lose the connection,\n # we should be able to tell the other side that we are going away.\n # RFC-2821 requires that we try.\n if self.mode is DATA:\n try:\n for message in self.__messages:\n try:\n message.connectionLost()\n except:\n log.err()\n del self.__messages\n except AttributeError:\n pass\n if self._onLogout:\n self._onLogout()\n self._onLogout = None\n self.setTimeout(None)\n\n\n def do_RSET(self, rest):\n self._from = None\n self._to = []\n self.sendCode(250, b'I remember nothing.')\n\n\n def dataLineReceived(self, line):\n if line[:1] == b'.':\n if line == b'.':\n self.mode = COMMAND\n if self.datafailed:\n self.sendCode(self.datafailed.code,\n self.datafailed.resp)\n return\n if not self.__messages:\n self._messageHandled(\"thrown away\")\n return\n defer.DeferredList([\n m.eomReceived() for m in self.__messages\n ], consumeErrors=True).addCallback(self._messageHandled\n )\n del self.__messages\n return\n line = line[1:]\n\n if self.datafailed:\n return\n\n try:\n # Add a blank line between the generated Received:-header\n # and the message body if the message comes in without any\n # headers\n if not self.__inheader and not self.__inbody:\n if b':' in line:\n self.__inheader = 1\n elif line:\n for message in self.__messages:\n message.lineReceived(b'')\n self.__inbody = 1\n\n if not line:\n self.__inbody = 1\n\n for message in self.__messages:\n message.lineReceived(line)\n except SMTPServerError as e:\n self.datafailed = e\n for message in self.__messages:\n message.connectionLost()\n state_DATA = dataLineReceived\n\n\n def _messageHandled(self, resultList):\n failures = 0\n for (success, result) in resultList:\n if not success:\n failures += 1\n log.err(result)\n if failures:\n msg = 'Could not send e-mail'\n resultLen = len(resultList)\n if resultLen > 1:\n msg += ' (%d failures out of %d recipients)'.format(\n failures, resultLen)\n self.sendCode(550, networkString(msg))\n else:\n self.sendCode(250, b'Delivery in progress')\n\n\n def _cbAnonymousAuthentication(self, result):\n \"\"\"\n Save the state resulting from a successful anonymous cred login.\n \"\"\"\n (iface, avatar, logout) = result\n if issubclass(iface, IMessageDeliveryFactory):\n self.deliveryFactory = avatar\n self.delivery = None\n elif issubclass(iface, IMessageDelivery):\n self.deliveryFactory = None\n self.delivery = avatar\n else:\n raise RuntimeError(\"%s is not a supported interface\" % (iface.__name__,))\n self._onLogout = logout\n self.challenger = None\n\n\n # overridable methods:\n def validateFrom(self, helo, origin):\n \"\"\"\n Validate the address from which the message originates.\n\n @type helo: C{(bytes, bytes)}\n @param helo: The argument to the HELO command and the client's IP\n address.\n\n @type origin: C{Address}\n @param origin: The address the message is from\n\n @rtype: C{Deferred} or C{Address}\n @return: C{origin} or a C{Deferred} whose callback will be\n passed C{origin}.\n\n @raise SMTPBadSender: Raised of messages from this address are\n not to be accepted.\n \"\"\"\n if self.deliveryFactory is not None:\n self.delivery = self.deliveryFactory.getMessageDelivery()\n\n if self.delivery is not None:\n return defer.maybeDeferred(self.delivery.validateFrom,\n helo, origin)\n\n # No login has been performed, no default delivery object has been\n # provided: try to perform an anonymous login and then invoke this\n # method again.\n if self.portal:\n\n result = self.portal.login(\n cred.credentials.Anonymous(),\n None,\n IMessageDeliveryFactory, IMessageDelivery)\n\n def ebAuthentication(err):\n \"\"\"\n Translate cred exceptions into SMTP exceptions so that the\n protocol code which invokes C{validateFrom} can properly report\n the failure.\n \"\"\"\n if err.check(cred.error.UnauthorizedLogin):\n exc = SMTPBadSender(origin)\n elif err.check(cred.error.UnhandledCredentials):\n exc = SMTPBadSender(\n origin, resp=\"Unauthenticated senders not allowed\")\n else:\n return err\n return defer.fail(exc)\n\n result.addCallbacks(\n self._cbAnonymousAuthentication, ebAuthentication)\n\n def continueValidation(ignored):\n \"\"\"\n Re-attempt from address validation.\n \"\"\"\n return self.validateFrom(helo, origin)\n\n result.addCallback(continueValidation)\n return result\n\n raise SMTPBadSender(origin)\n\n\n def validateTo(self, user):\n \"\"\"\n Validate the address for which the message is destined.\n\n @type user: L{User}\n @param user: The address to validate.\n\n @rtype: no-argument callable\n @return: A C{Deferred} which becomes, or a callable which\n takes no arguments and returns an object implementing C{IMessage}.\n This will be called and the returned object used to deliver the\n message when it arrives.\n\n @raise SMTPBadRcpt: Raised if messages to the address are\n not to be accepted.\n \"\"\"\n if self.delivery is not None:\n return self.delivery.validateTo(user)\n raise SMTPBadRcpt(user)\n\n\n def receivedHeader(self, helo, origin, recipients):\n if self.delivery is not None:\n return self.delivery.receivedHeader(helo, origin, recipients)\n\n heloStr = b\"\"\n if helo[0]:\n heloStr = b\" helo=\" + helo[0]\n domain = networkString(self.transport.getHost().host)\n\n from_ = b\"from \" + helo[0] + b\" ([\" + helo[1] + b\"]\" + heloStr + b\")\"\n by = b\"by %s with %s (%s)\" % (domain,\n self.__class__.__name__,\n longversion)\n for_ = b\"for %s; %s\" % (' '.join(map(str, recipients)),\n rfc822date())\n return b\"Received: \" + from_ + b\"\\n\\t\" + by + b\"\\n\\t\" + for_\n\n\n\nclass SMTPFactory(protocol.ServerFactory):\n \"\"\"\n Factory for SMTP.\n \"\"\"\n\n # override in instances or subclasses\n domain = DNSNAME\n timeout = 600\n protocol = SMTP\n\n portal = None\n\n def __init__(self, portal = None):\n self.portal = portal\n\n\n def buildProtocol(self, addr):\n p = protocol.ServerFactory.buildProtocol(self, addr)\n p.portal = self.portal\n p.host = self.domain\n return p\n\n\n\nclass SMTPClient(basic.LineReceiver, policies.TimeoutMixin):\n \"\"\"\n SMTP client for sending emails.\n\n After the client has connected to the SMTP server, it repeatedly calls\n L{SMTPClient.getMailFrom}, L{SMTPClient.getMailTo} and\n L{SMTPClient.getMailData} and uses this information to send an email.\n It then calls L{SMTPClient.getMailFrom} again; if it returns L{None}, the\n client will disconnect, otherwise it will continue as normal i.e. call\n L{SMTPClient.getMailTo} and L{SMTPClient.getMailData} and send a new email.\n \"\"\"\n\n # If enabled then log SMTP client server communication\n debug = True\n\n # Number of seconds to wait before timing out a connection. If\n # None, perform no timeout checking.\n timeout = None\n\n def __init__(self, identity, logsize=10):\n if isinstance(identity, unicode):\n identity = identity.encode('ascii')\n\n self.identity = identity or b''\n self.toAddressesResult = []\n self.successAddresses = []\n self._from = None\n self.resp = []\n self.code = -1\n self.log = util.LineLog(logsize)\n\n\n def sendLine(self, line):\n # Log sendLine only if you are in debug mode for performance\n if self.debug:\n self.log.append(b'>>> ' + line)\n\n basic.LineReceiver.sendLine(self,line)\n\n\n def connectionMade(self):\n self.setTimeout(self.timeout)\n\n self._expected = [ 220 ]\n self._okresponse = self.smtpState_helo\n self._failresponse = self.smtpConnectionFailed\n\n\n def connectionLost(self, reason=protocol.connectionDone):\n \"\"\"\n We are no longer connected\n \"\"\"\n self.setTimeout(None)\n self.mailFile = None\n\n\n def timeoutConnection(self):\n self.sendError(\n SMTPTimeoutError(\n -1, b\"Timeout waiting for SMTP server response\",\n self.log.str()))\n\n\n def lineReceived(self, line):\n self.resetTimeout()\n\n # Log lineReceived only if you are in debug mode for performance\n if self.debug:\n self.log.append(b'<<< ' + line)\n\n why = None\n\n try:\n self.code = int(line[:3])\n except ValueError:\n # This is a fatal error and will disconnect the transport\n # lineReceived will not be called again.\n self.sendError(SMTPProtocolError(-1,\n \"Invalid response from SMTP server: {}\".format(line),\n self.log.str()))\n return\n\n if line[0:1] == b'0':\n # Verbose informational message, ignore it\n return\n\n self.resp.append(line[4:])\n\n if line[3:4] == b'-':\n # Continuation\n return\n\n if self.code in self._expected:\n why = self._okresponse(self.code, b'\\n'.join(self.resp))\n else:\n why = self._failresponse(self.code, b'\\n'.join(self.resp))\n\n self.code = -1\n self.resp = []\n return why\n\n\n def smtpConnectionFailed(self, code, resp):\n self.sendError(SMTPConnectError(code, resp, self.log.str()))\n\n\n def smtpTransferFailed(self, code, resp):\n if code < 0:\n self.sendError(SMTPProtocolError(code, resp, self.log.str()))\n else:\n self.smtpState_msgSent(code, resp)\n\n\n def smtpState_helo(self, code, resp):\n self.sendLine(b'HELO ' + self.identity)\n self._expected = SUCCESS\n self._okresponse = self.smtpState_from\n\n\n def smtpState_from(self, code, resp):\n self._from = self.getMailFrom()\n self._failresponse = self.smtpTransferFailed\n if self._from is not None:\n self.sendLine(b'MAIL FROM:' + quoteaddr(self._from))\n self._expected = [250]\n self._okresponse = self.smtpState_to\n else:\n # All messages have been sent, disconnect\n self._disconnectFromServer()\n\n\n def smtpState_disconnect(self, code, resp):\n self.transport.loseConnection()\n\n\n def smtpState_to(self, code, resp):\n self.toAddresses = iter(self.getMailTo())\n self.toAddressesResult = []\n self.successAddresses = []\n self._okresponse = self.smtpState_toOrData\n self._expected = range(0, 1000)\n self.lastAddress = None\n return self.smtpState_toOrData(0, b'')\n\n\n def smtpState_toOrData(self, code, resp):\n if self.lastAddress is not None:\n self.toAddressesResult.append((self.lastAddress, code, resp))\n if code in SUCCESS:\n self.successAddresses.append(self.lastAddress)\n try:\n self.lastAddress = next(self.toAddresses)\n except StopIteration:\n if self.successAddresses:\n self.sendLine(b'DATA')\n self._expected = [ 354 ]\n self._okresponse = self.smtpState_data\n else:\n return self.smtpState_msgSent(code,'No recipients accepted')\n else:\n self.sendLine(b'RCPT TO:' + quoteaddr(self.lastAddress))\n\n\n def smtpState_data(self, code, resp):\n s = basic.FileSender()\n d = s.beginFileTransfer(\n self.getMailData(), self.transport, self.transformChunk)\n def ebTransfer(err):\n self.sendError(err.value)\n d.addCallbacks(self.finishedFileTransfer, ebTransfer)\n self._expected = SUCCESS\n self._okresponse = self.smtpState_msgSent\n\n\n def smtpState_msgSent(self, code, resp):\n if self._from is not None:\n self.sentMail(code, resp, len(self.successAddresses),\n self.toAddressesResult, self.log)\n\n self.toAddressesResult = []\n self._from = None\n self.sendLine(b'RSET')\n self._expected = SUCCESS\n self._okresponse = self.smtpState_from\n\n\n ##\n ## Helpers for FileSender\n ##\n def transformChunk(self, chunk):\n \"\"\"\n Perform the necessary local to network newline conversion and escape\n leading periods.\n\n This method also resets the idle timeout so that as long as process is\n being made sending the message body, the client will not time out.\n \"\"\"\n self.resetTimeout()\n return chunk.replace(b'\\n', b'\\r\\n').replace(b'\\r\\n.', b'\\r\\n..')\n\n\n def finishedFileTransfer(self, lastsent):\n if lastsent != b'\\n':\n line = b'\\r\\n.'\n else:\n line = b'.'\n self.sendLine(line)\n\n\n ##\n # these methods should be overridden in subclasses\n def getMailFrom(self):\n \"\"\"\n Return the email address the mail is from.\n \"\"\"\n raise NotImplementedError\n\n\n def getMailTo(self):\n \"\"\"\n Return a list of emails to send to.\n \"\"\"\n raise NotImplementedError\n\n\n def getMailData(self):\n \"\"\"\n Return file-like object containing data of message to be sent.\n\n Lines in the file should be delimited by '\\\\n'.\n \"\"\"\n raise NotImplementedError\n\n\n def sendError(self, exc):\n \"\"\"\n If an error occurs before a mail message is sent sendError will be\n called. This base class method sends a QUIT if the error is\n non-fatal and disconnects the connection.\n\n @param exc: The SMTPClientError (or child class) raised\n @type exc: C{SMTPClientError}\n \"\"\"\n if isinstance(exc, SMTPClientError) and not exc.isFatal:\n self._disconnectFromServer()\n else:\n # If the error was fatal then the communication channel with the\n # SMTP Server is broken so just close the transport connection\n self.smtpState_disconnect(-1, None)\n\n\n def sentMail(self, code, resp, numOk, addresses, log):\n \"\"\"\n Called when an attempt to send an email is completed.\n\n If some addresses were accepted, code and resp are the response\n to the DATA command. If no addresses were accepted, code is -1\n and resp is an informative message.\n\n @param code: the code returned by the SMTP Server\n @param resp: The string response returned from the SMTP Server\n @param numOK: the number of addresses accepted by the remote host.\n @param addresses: is a list of tuples (address, code, resp) listing\n the response to each RCPT command.\n @param log: is the SMTP session log\n \"\"\"\n raise NotImplementedError\n\n\n def _disconnectFromServer(self):\n self._expected = range(0, 1000)\n self._okresponse = self.smtpState_disconnect\n self.sendLine(b'QUIT')\n\n\n\nclass ESMTPClient(SMTPClient):\n \"\"\"\n A client for sending emails over ESMTP.\n\n @ivar heloFallback: Whether or not to fall back to plain SMTP if the C{EHLO}\n command is not recognised by the server. If L{requireAuthentication} is\n C{True}, or L{requireTransportSecurity} is C{True} and the connection is\n not over TLS, this fallback flag will not be honored.\n @type heloFallback: L{bool}\n\n @ivar requireAuthentication: If C{True}, refuse to proceed if authentication\n cannot be performed. Overrides L{heloFallback}.\n @type requireAuthentication: L{bool}\n\n @ivar requireTransportSecurity: If C{True}, refuse to proceed if the\n transport cannot be secured. If the transport layer is not already\n secured via TLS, this will override L{heloFallback}.\n @type requireAuthentication: L{bool}\n\n @ivar context: The context factory to use for STARTTLS, if desired.\n @type context: L{ssl.ClientContextFactory}\n\n @ivar _tlsMode: Whether or not the connection is over TLS.\n @type _tlsMode: L{bool}\n \"\"\"\n heloFallback = True\n requireAuthentication = False\n requireTransportSecurity = False\n context = None\n _tlsMode = False\n\n def __init__(self, secret, contextFactory=None, *args, **kw):\n SMTPClient.__init__(self, *args, **kw)\n self.authenticators = []\n self.secret = secret\n self.context = contextFactory\n\n\n def __getattr__(self, name):\n if name == \"tlsMode\":\n warnings.warn(\n \"tlsMode attribute of twisted.mail.smtp.ESMTPClient \"\n \"is deprecated since Twisted 13.0\",\n category=DeprecationWarning, stacklevel=2)\n return self._tlsMode\n else:\n raise AttributeError(\n '%s instance has no attribute %r' % (\n self.__class__.__name__, name,))\n\n\n def __setattr__(self, name, value):\n if name == \"tlsMode\":\n warnings.warn(\n \"tlsMode attribute of twisted.mail.smtp.ESMTPClient \"\n \"is deprecated since Twisted 13.0\",\n category=DeprecationWarning, stacklevel=2)\n self._tlsMode = value\n else:\n self.__dict__[name] = value\n\n\n def esmtpEHLORequired(self, code=-1, resp=None):\n \"\"\"\n Fail because authentication is required, but the server does not support\n ESMTP, which is required for authentication.\n\n @param code: The server status code from the most recently received\n server message.\n @type code: L{int}\n\n @param resp: The server status response from the most recently received\n server message.\n @type resp: L{bytes}\n \"\"\"\n self.sendError(EHLORequiredError(502, b\"Server does not support ESMTP \"\n b\"Authentication\", self.log.str()))\n\n\n def esmtpAUTHRequired(self, code=-1, resp=None):\n \"\"\"\n Fail because authentication is required, but the server does not support\n any schemes we support.\n\n @param code: The server status code from the most recently received\n server message.\n @type code: L{int}\n\n @param resp: The server status response from the most recently received\n server message.\n @type resp: L{bytes}\n \"\"\"\n tmp = []\n\n for a in self.authenticators:\n tmp.append(a.getName().upper())\n\n auth = b\"[%s]\" % b\", \".join(tmp)\n\n self.sendError(AUTHRequiredError(502, b\"Server does not support Client \"\n b\"Authentication schemes %s\" % auth, self.log.str()))\n\n\n def esmtpTLSRequired(self, code=-1, resp=None):\n \"\"\"\n Fail because TLS is required and the server does not support it.\n\n @param code: The server status code from the most recently received\n server message.\n @type code: L{int}\n\n @param resp: The server status response from the most recently received\n server message.\n @type resp: L{bytes}\n \"\"\"\n self.sendError(TLSRequiredError(502, b\"Server does not support secure \"\n b\"communication via TLS / SSL\", self.log.str()))\n\n\n def esmtpTLSFailed(self, code=-1, resp=None):\n \"\"\"\n Fail because the TLS handshake wasn't able to be completed.\n\n @param code: The server status code from the most recently received\n server message.\n @type code: L{int}\n\n @param resp: The server status response from the most recently received\n server message.\n @type resp: L{bytes}\n \"\"\"\n self.sendError(TLSError(code, b\"Could not complete the SSL/TLS \"\n b\"handshake\", self.log.str()))\n\n\n def esmtpAUTHDeclined(self, code=-1, resp=None):\n \"\"\"\n Fail because the authentication was rejected.\n\n @param code: The server status code from the most recently received\n server message.\n @type code: L{int}\n\n @param resp: The server status response from the most recently received\n server message.\n @type resp: L{bytes}\n \"\"\"\n self.sendError(AUTHDeclinedError(code, resp, self.log.str()))\n\n\n def esmtpAUTHMalformedChallenge(self, code=-1, resp=None):\n \"\"\"\n Fail because the server sent a malformed authentication challenge.\n\n @param code: The server status code from the most recently received\n server message.\n @type code: L{int}\n\n @param resp: The server status response from the most recently received\n server message.\n @type resp: L{bytes}\n \"\"\"\n self.sendError(AuthenticationError(501, b\"Login failed because the \"\n b\"SMTP Server returned a malformed Authentication Challenge\",\n self.log.str()))\n\n\n def esmtpAUTHServerError(self, code=-1, resp=None):\n \"\"\"\n Fail because of some other authentication error.\n\n @param code: The server status code from the most recently received\n server message.\n @type code: L{int}\n\n @param resp: The server status response from the most recently received\n server message.\n @type resp: L{bytes}\n \"\"\"\n self.sendError(AuthenticationError(code, resp, self.log.str()))\n\n\n def registerAuthenticator(self, auth):\n \"\"\"\n Registers an Authenticator with the ESMTPClient. The ESMTPClient will\n attempt to login to the SMTP Server in the order the Authenticators are\n registered. The most secure Authentication mechanism should be\n registered first.\n\n @param auth: The Authentication mechanism to register\n @type auth: L{IClientAuthentication} implementor\n\n @return: L{None}\n \"\"\"\n self.authenticators.append(auth)\n\n\n def connectionMade(self):\n \"\"\"\n Called when a connection has been made, and triggers sending an C{EHLO}\n to the server.\n \"\"\"\n self._tlsMode = ISSLTransport.providedBy(self.transport)\n SMTPClient.connectionMade(self)\n self._okresponse = self.esmtpState_ehlo\n\n\n def esmtpState_ehlo(self, code, resp):\n \"\"\"\n Send an C{EHLO} to the server.\n\n If L{heloFallback} is C{True}, and there is no requirement for TLS or\n authentication, the client will fall back to basic SMTP.\n\n @param code: The server status code from the most recently received\n server message.\n @type code: L{int}\n\n @param resp: The server status response from the most recently received\n server message.\n @type resp: L{bytes}\n\n @return: L{None}\n \"\"\"\n self._expected = SUCCESS\n\n self._okresponse = self.esmtpState_serverConfig\n self._failresponse = self.esmtpEHLORequired\n\n if self._tlsMode:\n needTLS = False\n else:\n needTLS = self.requireTransportSecurity\n\n if self.heloFallback and not self.requireAuthentication and not needTLS:\n self._failresponse = self.smtpState_helo\n\n self.sendLine(b\"EHLO \" + self.identity)\n\n\n def esmtpState_serverConfig(self, code, resp):\n \"\"\"\n Handle a positive response to the I{EHLO} command by parsing the\n capabilities in the server's response and then taking the most\n appropriate next step towards entering a mail transaction.\n \"\"\"\n items = {}\n for line in resp.splitlines():\n e = line.split(None, 1)\n if len(e) > 1:\n items[e[0]] = e[1]\n else:\n items[e[0]] = None\n\n self.tryTLS(code, resp, items)\n\n\n def tryTLS(self, code, resp, items):\n \"\"\"\n Take a necessary step towards being able to begin a mail transaction.\n\n The step may be to ask the server to being a TLS session. If TLS is\n already in use or not necessary and not available then the step may be\n to authenticate with the server. If TLS is necessary and not available,\n fail the mail transmission attempt.\n\n This is an internal helper method.\n\n @param code: The server status code from the most recently received\n server message.\n @type code: L{int}\n\n @param resp: The server status response from the most recently received\n server message.\n @type resp: L{bytes}\n\n @param items: A mapping of ESMTP extensions offered by the server. Keys\n are extension identifiers and values are the associated values.\n @type items: L{dict} mapping L{bytes} to L{bytes}\n\n @return: L{None}\n \"\"\"\n\n # has tls can tls must tls result\n # t t t authenticate\n # t t f authenticate\n # t f t authenticate\n # t f f authenticate\n\n # f t t STARTTLS\n # f t f STARTTLS\n # f f t esmtpTLSRequired\n # f f f authenticate\n\n hasTLS = self._tlsMode\n canTLS = self.context and b\"STARTTLS\" in items\n mustTLS = self.requireTransportSecurity\n\n if hasTLS or not (canTLS or mustTLS):\n self.authenticate(code, resp, items)\n elif canTLS:\n self._expected = [220]\n self._okresponse = self.esmtpState_starttls\n self._failresponse = self.esmtpTLSFailed\n self.sendLine(b\"STARTTLS\")\n else:\n self.esmtpTLSRequired()\n\n\n def esmtpState_starttls(self, code, resp):\n \"\"\"\n Handle a positive response to the I{STARTTLS} command by starting a new\n TLS session on C{self.transport}.\n\n Upon success, re-handshake with the server to discover what capabilities\n it has when TLS is in use.\n \"\"\"\n try:\n self.transport.startTLS(self.context)\n self._tlsMode = True\n except:\n log.err()\n self.esmtpTLSFailed(451)\n\n # Send another EHLO once TLS has been started to\n # get the TLS / AUTH schemes. Some servers only allow AUTH in TLS mode.\n self.esmtpState_ehlo(code, resp)\n\n\n def authenticate(self, code, resp, items):\n if self.secret and items.get(b'AUTH'):\n schemes = items[b'AUTH'].split()\n tmpSchemes = {}\n\n #XXX: May want to come up with a more efficient way to do this\n for s in schemes:\n tmpSchemes[s.upper()] = 1\n\n for a in self.authenticators:\n auth = a.getName().upper()\n\n if auth in tmpSchemes:\n self._authinfo = a\n\n # Special condition handled\n if auth == b\"PLAIN\":\n self._okresponse = self.smtpState_from\n self._failresponse = self._esmtpState_plainAuth\n self._expected = [235]\n challenge = base64.b64encode(\n self._authinfo.challengeResponse(self.secret, 1))\n self.sendLine(b\"AUTH %s %s\" % (auth, challenge))\n else:\n self._expected = [334]\n self._okresponse = self.esmtpState_challenge\n # If some error occurs here, the server declined the\n # AUTH before the user / password phase. This would be\n # a very rare case\n self._failresponse = self.esmtpAUTHServerError\n self.sendLine(b'AUTH ' + auth)\n return\n\n if self.requireAuthentication:\n self.esmtpAUTHRequired()\n else:\n self.smtpState_from(code, resp)\n\n\n def _esmtpState_plainAuth(self, code, resp):\n self._okresponse = self.smtpState_from\n self._failresponse = self.esmtpAUTHDeclined\n self._expected = [235]\n challenge = base64.b64encode(\n self._authinfo.challengeResponse(self.secret, 2))\n self.sendLine(b'AUTH PLAIN ' + challenge)\n\n\n def esmtpState_challenge(self, code, resp):\n self._authResponse(self._authinfo, resp)\n\n\n def _authResponse(self, auth, challenge):\n self._failresponse = self.esmtpAUTHDeclined\n try:\n challenge = base64.b64decode(challenge)\n except binascii.Error:\n # Illegal challenge, give up, then quit\n self.sendLine(b'*')\n self._okresponse = self.esmtpAUTHMalformedChallenge\n self._failresponse = self.esmtpAUTHMalformedChallenge\n else:\n resp = auth.challengeResponse(self.secret, challenge)\n self._expected = [235, 334]\n self._okresponse = self.smtpState_maybeAuthenticated\n self.sendLine(base64.b64encode(resp))\n\n\n def smtpState_maybeAuthenticated(self, code, resp):\n \"\"\"\n Called to handle the next message from the server after sending a\n response to a SASL challenge. The server response might be another\n challenge or it might indicate authentication has succeeded.\n \"\"\"\n if code == 235:\n # Yes, authenticated!\n del self._authinfo\n self.smtpState_from(code, resp)\n else:\n # No, not authenticated yet. Keep trying.\n self._authResponse(self._authinfo, resp)\n\n\n\nclass ESMTP(SMTP):\n ctx = None\n canStartTLS = False\n startedTLS = False\n\n authenticated = False\n\n def __init__(self, chal=None, contextFactory=None):\n SMTP.__init__(self)\n if chal is None:\n chal = {}\n self.challengers = chal\n self.authenticated = False\n self.ctx = contextFactory\n\n\n def connectionMade(self):\n SMTP.connectionMade(self)\n self.canStartTLS = ITLSTransport.providedBy(self.transport)\n self.canStartTLS = self.canStartTLS and (self.ctx is not None)\n\n\n def greeting(self):\n return SMTP.greeting(self) + b' ESMTP'\n\n\n def extensions(self):\n \"\"\"\n SMTP service extensions\n\n @return: the SMTP service extensions that are supported.\n @rtype: L{dict} with L{bytes} keys and a value of either L{None} or a\n L{list} of L{bytes}.\n \"\"\"\n ext = {b'AUTH': _keys(self.challengers)}\n if self.canStartTLS and not self.startedTLS:\n ext[b'STARTTLS'] = None\n return ext\n\n\n def lookupMethod(self, command):\n command = nativeString(command)\n\n m = SMTP.lookupMethod(self, command)\n if m is None:\n m = getattr(self, 'ext_' + command.upper(), None)\n return m\n\n\n def listExtensions(self):\n r = []\n for (c, v) in iteritems(self.extensions()):\n if v is not None:\n if v:\n # Intentionally omit extensions with empty argument lists\n r.append(c + b' ' + b' '.join(v))\n else:\n r.append(c)\n\n return b'\\n'.join(r)\n\n\n def do_EHLO(self, rest):\n peer = self.transport.getPeer().host\n\n if not isinstance(peer, bytes):\n peer = peer.encode('idna')\n\n self._helo = (rest, peer)\n self._from = None\n self._to = []\n self.sendCode(\n 250,\n (self.host + b' Hello ' + peer + b', nice to meet you\\n' +\n self.listExtensions())\n )\n\n\n def ext_STARTTLS(self, rest):\n if self.startedTLS:\n self.sendCode(503, b'TLS already negotiated')\n elif self.ctx and self.canStartTLS:\n self.sendCode(220, b'Begin TLS negotiation now')\n self.transport.startTLS(self.ctx)\n self.startedTLS = True\n else:\n self.sendCode(454, b'TLS not available')\n\n\n def ext_AUTH(self, rest):\n if self.authenticated:\n self.sendCode(503, b'Already authenticated')\n return\n parts = rest.split(None, 1)\n chal = self.challengers.get(parts[0].upper(), lambda: None)()\n if not chal:\n self.sendCode(504, b'Unrecognized authentication type')\n return\n\n self.mode = AUTH\n self.challenger = chal\n\n if len(parts) > 1:\n chal.getChallenge() # Discard it, apparently the client does not\n # care about it.\n rest = parts[1]\n else:\n rest = None\n self.state_AUTH(rest)\n\n\n def _cbAuthenticated(self, loginInfo):\n \"\"\"\n Save the state resulting from a successful cred login and mark this\n connection as authenticated.\n \"\"\"\n result = SMTP._cbAnonymousAuthentication(self, loginInfo)\n self.authenticated = True\n return result\n\n\n def _ebAuthenticated(self, reason):\n \"\"\"\n Handle cred login errors by translating them to the SMTP authenticate\n failed. Translate all other errors into a generic SMTP error code and\n log the failure for inspection. Stop all errors from propagating.\n\n @param reason: Reason for failure.\n \"\"\"\n self.challenge = None\n if reason.check(cred.error.UnauthorizedLogin):\n self.sendCode(535, b'Authentication failed')\n else:\n log.err(reason, \"SMTP authentication failure\")\n self.sendCode(\n 451,\n b'Requested action aborted: local error in processing')\n\n\n def state_AUTH(self, response):\n \"\"\"\n Handle one step of challenge/response authentication.\n\n @param response: The text of a response. If None, this\n function has been called as a result of an AUTH command with\n no initial response. A response of '*' aborts authentication,\n as per RFC 2554.\n \"\"\"\n if self.portal is None:\n self.sendCode(454, b'Temporary authentication failure')\n self.mode = COMMAND\n return\n\n if response is None:\n challenge = self.challenger.getChallenge()\n encoded = base64.b64encode(challenge)\n self.sendCode(334, encoded)\n return\n\n if response == b'*':\n self.sendCode(501, b'Authentication aborted')\n self.challenger = None\n self.mode = COMMAND\n return\n\n try:\n uncoded = base64.b64decode(response)\n except (TypeError, binascii.Error):\n self.sendCode(501, b'Syntax error in parameters or arguments')\n self.challenger = None\n self.mode = COMMAND\n return\n\n self.challenger.setResponse(uncoded)\n if self.challenger.moreChallenges():\n challenge = self.challenger.getChallenge()\n coded = base64.b64encode(challenge)\n self.sendCode(334, coded)\n return\n\n self.mode = COMMAND\n result = self.portal.login(\n self.challenger, None,\n IMessageDeliveryFactory, IMessageDelivery)\n result.addCallback(self._cbAuthenticated)\n result.addCallback(lambda ign: self.sendCode(235,\n b'Authentication successful.'))\n result.addErrback(self._ebAuthenticated)\n\n\n\nclass SenderMixin:\n \"\"\"\n Utility class for sending emails easily.\n\n Use with SMTPSenderFactory or ESMTPSenderFactory.\n \"\"\"\n done = 0\n\n def getMailFrom(self):\n if not self.done:\n self.done = 1\n return str(self.factory.fromEmail)\n else:\n return None\n\n\n def getMailTo(self):\n return self.factory.toEmail\n\n\n def getMailData(self):\n return self.factory.file\n\n\n def sendError(self, exc):\n # Call the base class to close the connection with the SMTP server\n SMTPClient.sendError(self, exc)\n\n # Do not retry to connect to SMTP Server if:\n # 1. No more retries left (This allows the correct error to be returned to the errorback)\n # 2. retry is false\n # 3. The error code is not in the 4xx range (Communication Errors)\n\n if (self.factory.retries >= 0 or\n (not exc.retry and not (exc.code >= 400 and exc.code < 500))):\n self.factory.sendFinished = True\n self.factory.result.errback(exc)\n\n\n def sentMail(self, code, resp, numOk, addresses, log):\n # Do not retry, the SMTP server acknowledged the request\n self.factory.sendFinished = True\n if code not in SUCCESS:\n errlog = []\n for addr, acode, aresp in addresses:\n if acode not in SUCCESS:\n errlog.append((addr + b\": \" +\n networkString(\"%03d\" % (acode,)) +\n b\" \" + aresp))\n\n errlog.append(log.str())\n\n exc = SMTPDeliveryError(code, resp, b'\\n'.join(errlog), addresses)\n self.factory.result.errback(exc)\n else:\n self.factory.result.callback((numOk, addresses))\n\n\n\nclass SMTPSender(SenderMixin, SMTPClient):\n \"\"\"\n SMTP protocol that sends a single email based on information it\n gets from its factory, a L{SMTPSenderFactory}.\n \"\"\"\n\n\n\nclass SMTPSenderFactory(protocol.ClientFactory):\n \"\"\"\n Utility factory for sending emails easily.\n\n @type currentProtocol: L{SMTPSender}\n @ivar currentProtocol: The current running protocol returned by\n L{buildProtocol}.\n\n @type sendFinished: C{bool}\n @ivar sendFinished: When the value is set to True, it means the message has\n been sent or there has been an unrecoverable error or the sending has\n been cancelled. The default value is False.\n \"\"\"\n\n domain = DNSNAME\n protocol = SMTPSender\n\n def __init__(self, fromEmail, toEmail, file, deferred, retries=5,\n timeout=None):\n \"\"\"\n @param fromEmail: The RFC 2821 address from which to send this\n message.\n\n @param toEmail: A sequence of RFC 2821 addresses to which to\n send this message.\n\n @param file: A file-like object containing the message to send.\n\n @param deferred: A Deferred to callback or errback when sending\n of this message completes.\n @type deferred: L{defer.Deferred}\n\n @param retries: The number of times to retry delivery of this\n message.\n\n @param timeout: Period, in seconds, for which to wait for\n server responses, or None to wait forever.\n \"\"\"\n assert isinstance(retries, (int, long))\n\n if isinstance(toEmail, unicode):\n toEmail = [toEmail.encode('ascii')]\n elif isinstance(toEmail, bytes):\n toEmail = [toEmail]\n else:\n toEmailFinal = []\n for _email in toEmail:\n if not isinstance(_email, bytes):\n _email = _email.encode('ascii')\n\n toEmailFinal.append(_email)\n toEmail = toEmailFinal\n\n self.fromEmail = Address(fromEmail)\n self.nEmails = len(toEmail)\n self.toEmail = toEmail\n self.file = file\n self.result = deferred\n self.result.addBoth(self._removeDeferred)\n self.sendFinished = False\n self.currentProtocol = None\n\n self.retries = -retries\n self.timeout = timeout\n\n\n def _removeDeferred(self, result):\n del self.result\n return result\n\n\n def clientConnectionFailed(self, connector, err):\n self._processConnectionError(connector, err)\n\n\n def clientConnectionLost(self, connector, err):\n self._processConnectionError(connector, err)\n\n\n def _processConnectionError(self, connector, err):\n self.currentProtocol = None\n if (self.retries < 0) and (not self.sendFinished):\n log.msg(\"SMTP Client retrying server. Retry: %s\" % -self.retries)\n\n # Rewind the file in case part of it was read while attempting to\n # send the message.\n self.file.seek(0, 0)\n connector.connect()\n self.retries += 1\n elif not self.sendFinished:\n # If we were unable to communicate with the SMTP server a ConnectionDone will be\n # returned. We want a more clear error message for debugging\n if err.check(error.ConnectionDone):\n err.value = SMTPConnectError(-1, \"Unable to connect to server.\")\n self.result.errback(err.value)\n\n\n def buildProtocol(self, addr):\n p = self.protocol(self.domain, self.nEmails*2+2)\n p.factory = self\n p.timeout = self.timeout\n self.currentProtocol = p\n self.result.addBoth(self._removeProtocol)\n return p\n\n\n def _removeProtocol(self, result):\n \"\"\"\n Remove the protocol created in C{buildProtocol}.\n\n @param result: The result/error passed to the callback/errback of\n L{defer.Deferred}.\n\n @return: The C{result} untouched.\n \"\"\"\n if self.currentProtocol:\n self.currentProtocol = None\n return result\n\n\n\nclass LOGINCredentials(_lcredentials):\n \"\"\"\n L{LOGINCredentials} generates challenges for I{LOGIN} authentication.\n\n For interoperability with Outlook, the challenge generated does not exactly\n match the one defined in the\n U{draft specification}.\n \"\"\"\n\n def __init__(self):\n _lcredentials.__init__(self)\n self.challenges = [b'Password:', b'Username:']\n\n\n\n@implementer(IClientAuthentication)\nclass PLAINAuthenticator:\n def __init__(self, user):\n self.user = user\n\n\n def getName(self):\n return b\"PLAIN\"\n\n\n def challengeResponse(self, secret, chal=1):\n if chal == 1:\n return self.user + b'\\0' + self.user + b'\\0' + secret\n else:\n return b'\\0' + self.user + b'\\0' + secret\n\n\n\nclass ESMTPSender(SenderMixin, ESMTPClient):\n\n requireAuthentication = True\n requireTransportSecurity = True\n\n def __init__(self, username, secret, contextFactory=None, *args, **kw):\n self.heloFallback = 0\n self.username = username\n\n if contextFactory is None:\n contextFactory = self._getContextFactory()\n\n ESMTPClient.__init__(self, secret, contextFactory, *args, **kw)\n\n self._registerAuthenticators()\n\n\n def _registerAuthenticators(self):\n # Register Authenticator in order from most secure to least secure\n self.registerAuthenticator(CramMD5ClientAuthenticator(self.username))\n self.registerAuthenticator(LOGINAuthenticator(self.username))\n self.registerAuthenticator(PLAINAuthenticator(self.username))\n\n\n def _getContextFactory(self):\n if self.context is not None:\n return self.context\n try:\n from twisted.internet import ssl\n except ImportError:\n return None\n else:\n try:\n context = ssl.ClientContextFactory()\n context.method = ssl.SSL.TLSv1_METHOD\n return context\n except AttributeError:\n return None\n\n\n\nclass ESMTPSenderFactory(SMTPSenderFactory):\n \"\"\"\n Utility factory for sending emails easily.\n\n @type currentProtocol: L{ESMTPSender}\n @ivar currentProtocol: The current running protocol as made by\n L{buildProtocol}.\n \"\"\"\n protocol = ESMTPSender\n\n def __init__(self, username, password, fromEmail, toEmail, file,\n deferred, retries=5, timeout=None,\n contextFactory=None, heloFallback=False,\n requireAuthentication=True,\n requireTransportSecurity=True):\n\n SMTPSenderFactory.__init__(self, fromEmail, toEmail, file, deferred, retries, timeout)\n self.username = username\n self.password = password\n self._contextFactory = contextFactory\n self._heloFallback = heloFallback\n self._requireAuthentication = requireAuthentication\n self._requireTransportSecurity = requireTransportSecurity\n\n\n def buildProtocol(self, addr):\n \"\"\"\n Build an L{ESMTPSender} protocol configured with C{heloFallback},\n C{requireAuthentication}, and C{requireTransportSecurity} as specified\n in L{__init__}.\n\n This sets L{currentProtocol} on the factory, as well as returning it.\n\n @rtype: L{ESMTPSender}\n \"\"\"\n p = self.protocol(self.username, self.password, self._contextFactory,\n self.domain, self.nEmails*2+2)\n p.heloFallback = self._heloFallback\n p.requireAuthentication = self._requireAuthentication\n p.requireTransportSecurity = self._requireTransportSecurity\n p.factory = self\n p.timeout = self.timeout\n self.currentProtocol = p\n self.result.addBoth(self._removeProtocol)\n return p\n\n\n\ndef sendmail(smtphost, from_addr, to_addrs, msg, senderDomainName=None, port=25,\n reactor=reactor, username=None, password=None,\n requireAuthentication=False, requireTransportSecurity=False):\n \"\"\"\n Send an email.\n\n This interface is intended to be a replacement for L{smtplib.SMTP.sendmail}\n and related methods. To maintain backwards compatibility, it will fall back\n to plain SMTP, if ESMTP support is not available. If ESMTP support is\n available, it will attempt to provide encryption via STARTTLS and\n authentication if a secret is provided.\n\n @param smtphost: The host the message should be sent to.\n @type smtphost: L{bytes}\n\n @param from_addr: The (envelope) address sending this mail.\n @type from_addr: L{bytes}\n\n @param to_addrs: A list of addresses to send this mail to. A string will\n be treated as a list of one address.\n @type to_addr: L{list} of L{bytes} or L{bytes}\n\n @param msg: The message, including headers, either as a file or a string.\n File-like objects need to support read() and close(). Lines must be\n delimited by '\\\\n'. If you pass something that doesn't look like a file,\n we try to convert it to a string (so you should be able to pass an\n L{email.message} directly, but doing the conversion with\n L{email.generator} manually will give you more control over the process).\n\n @param senderDomainName: Name by which to identify. If None, try to pick\n something sane (but this depends on external configuration and may not\n succeed).\n @type senderDomainName: L{bytes}\n\n @param port: Remote port to which to connect.\n @type port: L{int}\n\n @param username: The username to use, if wanting to authenticate.\n @type username: L{bytes} or L{unicode}\n\n @param password: The secret to use, if wanting to authenticate. If you do\n not specify this, SMTP authentication will not occur.\n @type password: L{bytes} or L{unicode}\n\n @param requireTransportSecurity: Whether or not STARTTLS is required.\n @type requireTransportSecurity: L{bool}\n\n @param requireAuthentication: Whether or not authentication is required.\n @type requireAuthentication: L{bool}\n\n @param reactor: The L{reactor} used to make the TCP connection.\n\n @rtype: L{Deferred}\n @returns: A cancellable L{Deferred}, its callback will be called if a\n message is sent to ANY address, the errback if no message is sent. When\n the C{cancel} method is called, it will stop retrying and disconnect\n the connection immediately.\n\n The callback will be called with a tuple (numOk, addresses) where numOk\n is the number of successful recipient addresses and addresses is a list\n of tuples (address, code, resp) giving the response to the RCPT command\n for each address.\n \"\"\"\n if not hasattr(msg, 'read'):\n # It's not a file\n msg = BytesIO(bytes(msg))\n\n\n def cancel(d):\n \"\"\"\n Cancel the L{twisted.mail.smtp.sendmail} call, tell the factory not to\n retry and disconnect the connection.\n\n @param d: The L{defer.Deferred} to be cancelled.\n \"\"\"\n factory.sendFinished = True\n if factory.currentProtocol:\n factory.currentProtocol.transport.abortConnection()\n else:\n # Connection hasn't been made yet\n connector.disconnect()\n\n d = defer.Deferred(cancel)\n\n if isinstance(username, unicode):\n username = username.encode(\"utf-8\")\n if isinstance(password, unicode):\n password = password.encode(\"utf-8\")\n\n factory = ESMTPSenderFactory(username, password, from_addr, to_addrs, msg,\n d, heloFallback=True, requireAuthentication=requireAuthentication,\n requireTransportSecurity=requireTransportSecurity)\n\n if senderDomainName is not None:\n factory.domain = networkString(senderDomainName)\n\n connector = reactor.connectTCP(smtphost, port, factory)\n\n return d\n\n\n\nimport codecs\ndef xtext_encode(s, errors=None):\n r = []\n for ch in iterbytes(s):\n o = ord(ch)\n if ch == '+' or ch == '=' or o < 33 or o > 126:\n r.append(networkString('+%02X' % (o,)))\n else:\n r.append(_bytesChr(o))\n return (b''.join(r), len(s))\n\n\n\ndef xtext_decode(s, errors=None):\n \"\"\"\n Decode the xtext-encoded string C{s}.\n\n @param s: String to decode.\n @param errors: codec error handling scheme.\n @return: The decoded string.\n \"\"\"\n r = []\n i = 0\n while i < len(s):\n if s[i:i+1] == b'+':\n try:\n r.append(chr(int(bytes(s[i + 1:i + 3]), 16)))\n except ValueError:\n r.append(ord(s[i:i + 3]))\n i += 3\n else:\n r.append(bytes(s[i:i+1]).decode('ascii'))\n i += 1\n return (''.join(r), len(s))\n\n\n\nclass xtextStreamReader(codecs.StreamReader):\n def decode(self, s, errors='strict'):\n return xtext_decode(s)\n\n\n\nclass xtextStreamWriter(codecs.StreamWriter):\n def decode(self, s, errors='strict'):\n return xtext_encode(s)\n\n\n\ndef xtext_codec(name):\n if name == 'xtext':\n return (xtext_encode, xtext_decode, xtextStreamReader, xtextStreamWriter)\ncodecs.register(xtext_codec)\n","repo_name":"wistbean/learn_python3_spider","sub_path":"stackoverflow/venv/lib/python3.6/site-packages/twisted/mail/smtp.py","file_name":"smtp.py","file_ext":"py","file_size_in_byte":71392,"program_lang":"python","lang":"en","doc_type":"code","stars":14022,"dataset":"github-code","pt":"3"}
+{"seq_id":"30753603107","text":"# -*- coding: utf-8 -*-\nimport json\nimport recipe\nimport requests\nfrom datetime import timedelta\nfrom django.db import IntegrityError\n\nfrom django.db.models import Q\nfrom django.core.files import File\nfrom os.path import basename\nfrom tempfile import TemporaryFile\nfrom urllib.parse import urlsplit\n\nfrom pathlib import Path\n\nfrom users.models import User\n\nfrom recipe.models import Ingredient, Recipe, RecipeImage\nfrom recipe.enums import Cuisines, Diets, RecipeTypes, \\\n Units, UNITS_KEYS\nfrom utils.helper import strip_links\n\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = \"Add recipes from json files in the data directory\"\n\n def add_arguments(self, parser):\n parser.add_argument(\"--user-id\", type=int, help=\"User ID to assign recipes\", required=True)\n parser.add_argument(\"--data-dir\", type=str, help=\"Data directory\")\n\n def handle(self, *args, **options):\n\n DIR = options.get('data_dir') or 'recipe_data'\n\n try:\n user = User.objects.get(pk=options.get('user_id'))\n except User.DoesNotExist as e:\n raise Exception(f\"User with id {options['user_id']} not found\") from e\n\n files = [f for f in Path.cwd().joinpath(DIR).iterdir() if f.suffix == '.json']\n\n for f in files:\n self.stdout.write(str(f))\n try:\n with open(f, 'r') as jf:\n recipe_data = json.load(jf)\n\n rc = RecipeCreator(recipe_data=recipe_data, user=user)\n recipe = rc.add_recipe()\n except IntegrityError:\n self.stdout.write(self.style.WARNING(f\"Recipe already exists\"))\n except Exception as e:\n self.stdout.write(self.style.ERROR(f\"Error: {e}\"))\n else:\n self.stdout.write(self.style.SUCCESS(f\"Recipe #{recipe.pk} added\"))\n\n\nclass RecipeCreator:\n \"\"\"\n Created Recipe models from necessary API by matching params\n \"\"\"\n\n def __init__(self, recipe_data: dict, user: User):\n self.recipe_data = recipe_data\n self.user = user\n\n def add_recipe(self):\n\n description = self.recipe_data.get('instructions') or self.recipe_data.get('summary', '-')\n\n recipe = Recipe.objects.create(\n title=self.recipe_data['title'],\n description=strip_links(description),\n user=self.user,\n cooking_time=timedelta(minutes=self.recipe_data['readyInMinutes']),\n cuisines=self._get_valid_cuisines(self.recipe_data['cuisines']),\n cooking_methods=self._get_valid_cooking_methods(),\n types=self._get_valid_types(self.recipe_data['dishTypes']),\n diet_restrictions=self._get_diet_restrictions(self.recipe_data),\n language='English',\n caption='unknown',\n status=Recipe.Status.ACCEPTED,\n publish_status=Recipe.PublishStatus.PUBLISHED,\n source_id=int(self.recipe_data['id']),\n source_url=self.recipe_data['sourceUrl'],\n is_parsed=True\n )\n\n if self.recipe_data.get('image'):\n self.download_to_recipe_image(recipe, self.recipe_data['image'])\n\n self.add_ingredients(\n recipe,\n self.recipe_data.get('extendedIngredients', [])\n )\n\n return recipe\n\n def download_to_recipe_image(self, recipe, url):\n \"\"\"\n https://goodcode.io/articles/django-download-url-to-file-field/\n \"\"\"\n ri = RecipeImage()\n ri.recipe = recipe\n ri.user = self.user\n with TemporaryFile() as tf:\n r = requests.get(url, stream=True)\n for chunk in r.iter_content(chunk_size=4096):\n tf.write(chunk)\n tf.seek(0)\n ri.file = File(tf, name=basename(urlsplit(url).path))\n ri.save()\n\n def add_ingredients(self, recipe, ingredients_list: list):\n\n def _get_unit(unit: str):\n for keys, unit_value in UNITS_KEYS.items():\n if unit in keys:\n return unit_value\n for choice in Units.choices:\n if unit == choice[0]:\n return unit\n return Units.EMPTY\n\n for ingredient_data in ingredients_list:\n Ingredient.objects.create(\n recipe=recipe,\n title=ingredient_data['originalName'],\n quantity=round(ingredient_data['amount'], 3),\n unit=_get_unit(ingredient_data['unit'])\n )\n\n def _get_valid_cuisines(self, cuisines_to_load: list) -> list:\n res = [v for v in Cuisines if v.label in cuisines_to_load]\n return res\n\n def _get_valid_cooking_methods(self) -> list:\n return []\n\n def _get_valid_types(self, dish_types:list) -> list:\n \"\"\"\n can have 'main course', 'main dish' values\n \"\"\"\n return [v for v in RecipeTypes if v.label.lower() in dish_types]\n\n def _get_diet_restrictions(self, recipe_data: dict) -> int:\n \"\"\"\n can have 'lacto ovo vegetarian'\n \"\"\"\n res = []\n if recipe_data.get('dairyFree'):\n res.append(Diets.DAIRY_FREE)\n if recipe_data.get('glutenFree'):\n res.append(Diets.GLUTEN_FREE)\n if recipe_data.get('lowFodmap'):\n res.append(Diets.FODMAP)\n if recipe_data.get('vegan'):\n res.append(Diets.VEGAN)\n if recipe_data.get('vegetarian'):\n res.append(Diets.VEGETARIAN)\n if 'pescatarian' in recipe_data['diets']:\n res.append(Diets.PESCETARIAN)\n if 'paleolitic' in recipe_data['diets']:\n res.append(Diets.PALEO)\n if 'primal' in recipe_data['diets']:\n res.append(Diets.PRIMAL)\n return res\n\n","repo_name":"Kartos102/eatchef_server","sub_path":"recipe/management/commands/add_recipes.py","file_name":"add_recipes.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29568722834","text":"from rest_framework import serializers\nfrom api.models import Question, Option, Quiz\n\n\nclass OptionSerializer(serializers.ModelSerializer):\n class Meta:\n model = Option\n fields = '__all__'\n read_only_fields = [\n 'question',\n ]\n\n\nclass QuestionSerializer(serializers.ModelSerializer):\n options = OptionSerializer(many=True)\n\n class Meta:\n model = Question\n fields = '__all__'\n\n def create(self,validated_data):\n options_data = validated_data.pop('options')\n question = Question.objects.create(**validated_data)\n\n for option in options_data:\n Option.objects.create(question=question,**option)\n \n return question\n\nclass QuestionListSerializer(serializers.ModelSerializer):\n class Meta:\n model = Question\n fields = '__all__'\n\n\nclass QuizRetrieveSerializer(serializers.ModelSerializer):\n questions = QuestionSerializer(many=True)\n class Meta:\n model = Quiz\n fields = '__all__'\n read_only_fields = [\n 'slug',\n 'id',\n 'number_of_questions',\n 'created_by',\n ]\n\nclass QuizListCreateSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(view_name='quiz-detail-update',lookup_field='slug')\n class Meta:\n model = Quiz\n fields = [\n 'id',\n 'title',\n 'slug',\n 'number_of_questions',\n 'url'\n ]\n read_only_fields = [\n 'slug',\n 'id',\n 'number_of_questions'\n ]","repo_name":"toptechschool/backend","sub_path":"api/serializers/ranking.py","file_name":"ranking.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72341973843","text":"import argparse\nimport os\nimport sys\nsys.path.append(os.getcwd())\nimport time\nimport numpy as np\nimport random\nfrom PIL import Image\nimport imageio\n\nimport yaml, shutil\nimport torch\nimport torch.nn as nn\nfrom tqdm import tqdm\nfrom torch.utils.data import DataLoader\nfrom torch.optim.lr_scheduler import MultiStepLR\nimport torch.nn.functional as F\n\nimport torchvision\n\nimport datasets\nimport models, losses\nimport utils\nimport matplotlib.pyplot as plt\nfrom einops import rearrange, repeat, reduce, parse_shape\n\nimport refine_svg\nfrom svgpathtools import svg2paths, parse_path, wsvg, Line, QuadraticBezier, CubicBezier, Path\nimport pydiffvg\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--outdir', required=True, type=str)\nparser.add_argument('--resume', required=True, type=str)\nparser.add_argument('--seed', default=42, type=int)\nparser.add_argument('--n-sample', default=20, type=int)\nparser.add_argument('--begin-index', default=0, type=int)\n\nargs = parser.parse_args()\n\ndef seed_all(seed):\n random.seed(seed) # Python\n np.random.seed(seed) # cpu vars\n torch.manual_seed(seed) # cpu vars\n\n if torch.cuda.is_available(): \n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed) # gpu vars\n torch.backends.cudnn.deterministic = True #needed\n torch.backends.cudnn.benchmark = False\n\ndef make_data_loader(spec, tag=''):\n if spec is None:\n return None\n\n dataset = datasets.make(spec['dataset'])\n\n loader = DataLoader(dataset, batch_size=spec['batch_size'],\n shuffle=spec['shuffle'], num_workers=12, pin_memory=True)\n return loader\n\ndef make_data_loaders(config):\n val_loader = make_data_loader(config.get('val_dataset'), tag='val')\n return val_loader\n\nref_char_list = [0,1]\n\nconfig_str = f'''\nloss:\n name: local-loss\n args:\n lam_render: 1\n lam_reg: 1.e-6\n'''\n\nseed = args.seed\nseed_all(seed)\nprint('seed:', seed)\n\nconfig = yaml.load(config_str, Loader=yaml.FullLoader)\noutput_dir = args.outdir\nos.makedirs(output_dir, exist_ok=True)\nos.makedirs(os.path.join(output_dir, 'all_rec'), exist_ok=True)\n\nsv_file = torch.load(args.resume)\n\nsystem = models.make(sv_file['model'], load_sd=True).cuda()\nsystem.init()\nsystem.eval()\nmodels.freeze(system)\n\nsidelength = 256\nloss_fn = losses.make(config['loss'])\nchar_nums = 52\n\nn_sample = args.n_sample\nsample_begin = args.begin_index\n\nwith open(os.path.join(output_dir, 'seed.txt'), 'w') as f:\n f.write(str(seed))\n\nfor sample_i in tqdm(range(sample_begin, sample_begin + n_sample)):\n parent_dir = os.path.join(output_dir, f'{sample_i:04d}')\n os.makedirs(parent_dir, exist_ok=True)\n\n with torch.no_grad():\n tgt_char_idx = torch.arange(char_nums).cuda()\n z_style = torch.randn(1, 256).cuda() * 1.5\n torch.save(z_style.detach().cpu(), os.path.join(parent_dir, 'z_style.pt'))\n\n z_style = z_style.expand(char_nums, -1)\n emb_char = system.cls_token(tgt_char_idx)\n z = system.merge(torch.cat([z_style, emb_char], dim=-1))\n curves = system.decoder(z)\n\n img_rec = system.decode_image_from_latent_vector(z)['rec']\n\n n = curves.shape[0]\n curves_np = curves.detach().cpu().numpy()\n curves_np = (curves_np + 1) * sidelength / 2\n targets = img_rec\n\n torchvision.utils.save_image(targets, os.path.join(output_dir, 'all_rec', f'{sample_i:04d}_rec.png'), nrow=13)\n\n for i in range(n):\n path_prefix = os.path.join(output_dir, f'{sample_i:04d}', f'{i:02d}')\n if os.path.exists(path_prefix + '_init.svg'):\n continue\n\n target = targets[i, 0]\n utils.tensor_to_image(img_rec[i, 0], path_prefix + '_rec.png')\n\n curve_np = curves_np[i]\n d_string_list = [models.gutils.path_d_from_control_points(cp, xy_flip=True) for cp in curve_np]\n path, d_string = refine_svg.merge_d_string(d_string_list)\n\n cps_list = refine_svg.convert_path_to_control_points(path, pruned=True)\n\n if len(cps_list) == 0:\n continue\n refine_svg.write_path_to_svg(cps_list, path_prefix + '_init.svg')\n continue","repo_name":"thuliu-yt16/dualvector","sub_path":"eval/sample_font.py","file_name":"sample_font.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"3"}
+{"seq_id":"7837676102","text":"# -*- coding:utf-8 -*-\n#\n# author: yangmqglobe\n# file: accessible.py\n# time: 2021/02/16\nfrom argparse import ArgumentParser\nimport pysam\n\nFRAGMENT = {\n 99: 'reference_start', 147: 'reference_end', 163: 'reference_start', 83: 'reference_start'\n}\n\nSHIFT_FACTOR = {99: 4, 147: -5, 163: 4, 83: -5}\n\n\ndef read_chromosome_sizes(filename):\n chromosome_sizes = dict()\n with open(filename) as f:\n for line in f:\n chromosome, sizes = line.strip().split('\\t')[:2]\n chromosome_sizes[chromosome] = int(sizes)\n return chromosome_sizes\n\n\ndef shift(read, chromosome_sizes, length=25):\n try:\n shift_pos = getattr(\n read, FRAGMENT[read.flag]) + SHIFT_FACTOR[read.flag]\n except KeyError:\n return None\n strand = '-' if read.is_reverse else '+'\n shift_start = max(shift_pos - length, 0)\n shift_end = min(shift_pos + length, chromosome_sizes[read.reference_name])\n return read.reference_name, shift_start, shift_end, '.', '.', strand\n\n\ndef run(in_bam, out_bed, chromosome_sizes_file, include=2, exclude=1024, mapq=10, length=25):\n chromosome_sizes = read_chromosome_sizes(chromosome_sizes_file)\n with pysam.AlignmentFile(in_bam, 'rb') as bam, open(out_bed, 'w') as bed:\n for chrom in chromosome_sizes.keys():\n for read in bam.fetch(chrom):\n if not read.flag & include:\n continue\n if read.flag & exclude:\n continue\n if read.mapq < mapq:\n continue\n record = shift(read, chromosome_sizes, length)\n if record is not None:\n bed.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(*record))\n\n\ndef main():\n parser = ArgumentParser(\n description='Shift reads to cut sizes for ATAC-Seq')\n parser.add_argument(\n '-l', dest='length', help='extend length of cut sizes', default=25, type=int\n )\n parser.add_argument(\n '-f', dest='include', help='only include reads with all of the FLAGs in INT present',\n default=2\n )\n parser.add_argument(\n '-F', dest='exclude', help='only include reads with none of the FLAGS in INT present',\n default=1028\n )\n parser.add_argument(\n '-q', dest='mapq', help='only include reads with mapping quality >= INT', default=10, type=int\n )\n parser.add_argument('', help='chromosome sizes file')\n parser.add_argument('', help='input bam file')\n parser.add_argument('', help='output bed file')\n args = vars(parser.parse_args())\n run(\n args[''], args[''], args[''],\n args['include'], args['exclude'], args['length']\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"suda-huanglab/circlehunter","sub_path":"tools/accessible.py","file_name":"accessible.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"73168249362","text":"\"\"\"Configuration for the dj_core_drf app.\"\"\"\nfrom datetime import timedelta\n\nfrom dj_core.config import Config as BaseConfig, DefaultProxy\n\n\nclass Config(BaseConfig):\n \"\"\"Override config to inject our defaults.\"\"\"\n\n defaults = BaseConfig.defaults.copy()\n defaults.update({\n 'ACCOUNT_AUTHENTICATION_METHOD': 'email',\n 'ACCOUNT_EMAIL_REQUIRED': True,\n 'ACCOUNT_EMAIL_VERIFICATION': 'none',\n 'ACCOUNT_USER_MODEL_USERNAME_FIELD': None,\n 'ACCOUNT_USERNAME_REQUIRED': False,\n 'ACCOUNT_REGISTRATION': 'enabled',\n 'REST_USE_JWT': True,\n 'SWAGGER_SETTINGS': {'api_version': '1'},\n 'JWT_AUTH': {\n 'JWT_EXPIRATION_DELTA': timedelta(hours=24),\n 'JWT_AUTH_HEADER_PREFIX': 'Token',\n },\n 'REST_FRAMEWORK': DefaultProxy({}, 'get_drf_settings'),\n 'REST_AUTH_SERIALIZERS': DefaultProxy({}, 'get_rest_auth_serializers'),\n 'REST_AUTH_REGISTER_SERIALIZERS':\n DefaultProxy({}, 'get_rest_auth_register_serializers'),\n })\n defaults.INSTALLED_APPS_REQUIRED = [\n 'dj_core_drf',\n 'rest_framework',\n 'rest_framework.authtoken',\n 'rest_framework_swagger',\n 'rest_auth',\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n 'rest_auth.registration',\n 'django_filters',\n ] + defaults.INSTALLED_APPS_REQUIRED\n defaults.INSTALLED_APPS_OPTIONAL += [\n 'revproxy',\n ]\n\n # pylint: disable=unused-argument,no-self-use\n def get_drf_settings(self, settings):\n \"\"\"Return a default settings dict for DRF.\"\"\"\n return {\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.IsAuthenticatedOrReadOnly'\n ],\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n ],\n 'DEFAULT_PAGINATION_CLASS':\n 'dj_core_drf.pagination.ThousandMaxLimitOffsetPagination',\n 'DEFAULT_FILTER_BACKENDS': [\n 'rest_framework_filters.backends.DjangoFilterBackend',\n ],\n 'DEFAULT_METADATA_CLASS':\n 'dj_core_drf.metadata.ModelChoicesMetadata',\n }\n\n # pylint: disable=unused-argument,no-self-use\n def get_rest_auth_serializers(self, settings):\n \"\"\"Return a default settings dict for rest_auth.\"\"\"\n return {\n 'USER_DETAILS_SERIALIZER':\n 'dj_core_drf.serializers.UserDetailsSerializer',\n 'PASSWORD_RESET_SERIALIZER':\n 'dj_core_drf.serializers.PasswordResetSerializer',\n 'LOGIN_SERIALIZER': 'dj_core_drf.serializers.LoginSerializer',\n }\n\n # pylint: disable=unused-argument,no-self-use\n def get_rest_auth_register_serializers(self, settings):\n \"\"\"Return a default settings dict for rest_auth.registration.\"\"\"\n return {\n 'REGISTER_SERIALIZER':\n 'dj_core_drf.serializers.RegisterSerializer',\n }\n","repo_name":"ionata/dj-core-drf","sub_path":"dj_core_drf/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16186785053","text":"import logging\nimport random\n\nfrom boltons.iterutils import chunked\nimport interactions\nfrom sqlalchemy import and_\nfrom sqlalchemy.exc import IntegrityError\n\nfrom bridge_discord import datastore\nfrom bridge_discord.extensions import utilities\n\n\ndef bbo_user_option_factory(description):\n return interactions.Option(\n name=\"bbo_user\",\n description=description,\n type=interactions.OptionType.STRING\n )\n\n\nclass TeamRRManagerExtension(interactions.Extension):\n @interactions.extension_command(\n name=\"create\",\n description=\"Creates a team round robin tournament\",\n default_member_permissions=interactions.Permissions.MANAGE_MESSAGES,\n options=[\n interactions.Option(\n name=\"tournament_name\",\n description=\"The name of the new tournament.\",\n type=interactions.OptionType.STRING,\n required=True\n )\n ]\n )\n async def create(self, ctx, tournament_name):\n with datastore.Session() as session:\n session.add(\n datastore.TeamRRTournament(state=datastore.TournamentState.SIGNUP, tournament_name=tournament_name)\n )\n session.commit()\n await ctx.send(\"Successfully created a new team round robin tournament!\", ephemeral=True)\n\n @interactions.extension_command(\n name=\"signup\",\n description=\"Sign up for the currently active team round robin tournament.\",\n options=[\n bbo_user_option_factory(\"BBO user if signing up for someone else.\"),\n ]\n )\n @utilities.SessionedGuard(\n active_tournament=utilities.assert_tournament_exists,\n bbo_user=utilities.assert_bbo_rep\n )\n async def signup(self, ctx, *, bbo_user=None):\n guard = self.signup.coro\n if guard.active_tournament.state is not datastore.TournamentState.SIGNUP:\n await utilities.failed_guard(ctx, \"The active tournament is not currently accepting signups.\")\n guard.session.add(\n datastore.TeamRREntry(\n tournament_id=guard.active_tournament.tournament_id,\n bbo_user=guard.bbo_user\n )\n )\n try:\n guard.session.commit()\n await ctx.send(\"Signed up for the upcoming tournament!\", ephemeral=True)\n except IntegrityError:\n await ctx.send(\"You are already signed up for the upcoming tournament.\", ephemeral=True)\n\n @interactions.extension_command(\n name=\"drop\",\n description=\"Drop registration from the currently active team round robin tournament.\",\n options=[\n bbo_user_option_factory(\"BBO user if dropping for someone else.\"),\n ]\n )\n @utilities.SessionedGuard(\n active_tournament=utilities.assert_tournament_exists,\n bbo_user=utilities.assert_bbo_rep\n )\n async def drop(self, ctx, *, bbo_user=None):\n guard = self.drop_tournament.coro\n entry_model = guard.session.get(datastore.TeamRREntry, (guard.active_tournament.tournament_id, guard.bbo_user))\n if not entry_model:\n await ctx.send(\n f\"{guard.bbo_user} is not currently signed up for the upcoming tournament.\",\n ephemeral=True\n )\n guard.session.delete(entry_model)\n guard.session.commit()\n await ctx.send(\"Successfully dropped out from the upcoming tournament!\", ephemeral=True)\n\n @interactions.extension_command(\n name=\"info\",\n description=\"Displays information about the currently active team round robin tournament.\",\n )\n @utilities.SessionedGuard(active_tournament=utilities.assert_tournament_exists)\n async def info(self, ctx):\n guard = self.tournament_info.coro\n\n profile_embed = interactions.Embed(title=f\"Team RR Tournament: {guard.active_tournament.tournament_name}\")\n profile_embed.add_field(\n name=\"Tournament Details\",\n value=\"\\n\".join(\n f\"{key}: {value}\"\n for key, value in {\n \"Challenge format\": guard.active_tournament.scoring_method,\n \"Boards per match\": guard.active_tournament.segment_boards,\n \"Created at\": guard.active_tournament.created_at\n }.items()\n )\n )\n if guard.active_tournament.state is datastore.TournamentState.SIGNUP:\n participant_strings = [\n await entry_model.bbo_profile.to_str_with_linked_mention(self.client)\n for entry_model in guard.active_tournament.participants\n ]\n profile_embed.add_field(name=\"Currently Registered Players\", value=\"\\n\".join(participant_strings))\n elif guard.active_tournament.state is datastore.TournamentState.STARTED:\n for team_number in range(guard.active_tournament.number_of_teams):\n team_members = guard.session.query(\n datastore.TeamRREntry\n ).join(datastore.BBOProfile).filter(\n and_(\n datastore.TeamRREntry.tournament_id == guard.active_tournament.tournament_id,\n datastore.TeamRREntry.team_number == team_number\n )\n ).order_by(datastore.BBOProfile.conservative_mmr_estimate).all()\n profile_embed.add_field(\n name=f\"Team {team_number + 1}\",\n value=\"\\n\".join(f\"•{member.bbo_user}\" for member in team_members),\n inline=team_number % 3 != 0 or team_number == 0\n )\n await ctx.send(embeds=profile_embed)\n\n @interactions.extension_command(\n name=\"start\",\n description=\"Ends the signup phase, starts matches.\",\n default_member_permissions=interactions.Permissions.MANAGE_MESSAGES\n )\n @utilities.SessionedGuard(active_tournament=utilities.assert_tournament_exists)\n async def start(self, ctx):\n guard = self.start_tournament.coro\n\n sorted_participants = sorted(\n guard.active_tournament.participants, key=lambda p: p.bbo_profile.conservative_mmr_estimate, reverse=True)\n for pot in chunked(sorted_participants, guard.active_tournament.number_of_teams):\n random.shuffle(pot)\n for ix, participant in enumerate(pot):\n participant.team_number = ix\n guard.active_tournament.state = datastore.TournamentState.STARTED\n guard.session.commit()\n await ctx.send(\"Tournament has been started and teams have been assigned.\", ephemeral=True)\n\n\ndef setup(client):\n datastore.setup_connection()\n with datastore.Session() as session:\n active_tournament = session.query(\n datastore.TeamRRTournament\n ).where(datastore.TeamRRTournament.state != datastore.TournamentState.INACTIVE).all()\n if active_tournament and len(active_tournament) > 1:\n logging.critical(\"There can only be one active Team RR tournament.\")\n raise ValueError(\"Failed setup assumptions.\")\n\n TeamRRManagerExtension(client)\n","repo_name":"edgy-raven/bridge-discord","sub_path":"bridge_discord/extensions/tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":7105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38506164446","text":"from django.db.models import Q\nfrom rest_framework import permissions, viewsets, generics, status\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth import get_user_model\nfrom .models import Offer, OfferStatus, OfferType, Contract\nfrom apps.children.models import Child\nfrom apps.adverts.models import Advert, AdvertType\nfrom .serializers import OfferSerializer, ContractSerializer\nfrom .permissions import IsSenderOrReceiver\nfrom rest_framework.response import Response\nimport pickle\nimport base64\n# Create your views here.\n\n\nclass OfferViewSet(viewsets.ModelViewSet):\n\n serializer_class = OfferSerializer\n\n http_method_names = ['get', 'head', 'delete', 'post']\n\n permission_classes = [IsSenderOrReceiver]\n\n def perform_create(self, serializer):\n if self.request.data.get('recipient'):\n #Vulnerable to SQL injection, user has direct access to application SQL - Eivind\n #Tested with input (hei' OR 1=1--) wich returned all usernames in database.\n result = get_user_model().objects.raw(\n \"SELECT * from users_user WHERE username = '%s'\" % self.request.data['recipient'])\n\n if self.request.user.username == self.request.data['recipient'].strip():\n raise ValidationError(\"Cannot send offer to yourself\")\n\n if len(result) > 0: # Check if a user exist with the given username\n r = \"\"\n for u in result:\n r += u.username + \" \"\n serializer.save(\n recipient=r.strip(), sender=self.request.user.username)\n else:\n raise ValidationError(\"User does not exist\")\n else:\n raise ValidationError(\"Missing parameter: recipient\")\n\n def get_queryset(self):\n queryset = Offer.objects.filter(\n Q(sender=self.request.user.username) | Q(recipient=self.request.user.username))\n\n return queryset\n\n\nclass ContractViewSet(viewsets.ModelViewSet):\n\n serializer_class = ContractSerializer\n\n http_method_names = ['get', 'head']\n\n def get_queryset(self):\n queryset = Contract.objects.filter(\n Q(parent=self.request.user) | Q(sitter=self.request.user))\n\n return queryset\n\n\nclass FinishContractView(generics.GenericAPIView):\n permission_classes = [permissions.IsAuthenticated]\n\n def post(self, request):\n if request.data.get('contractId'):\n # Pickle could be voulnrable when deserializing data\n # Quote from https://davidhamann.de/2020/04/05/exploiting-python-pickle/:\n # \"Warning: The pickle module is not secure. Only unpickle data you trust\".\n cId = base64.b64decode(request.data.get('contractId'))\n cId = pickle.loads(cId)\n contract = Contract.objects.get(id=cId)\n if request.user == contract.parent:\n contract.finished = True\n contract.save()\n return Response({'success': True, 'message': 'Contract finished'}, status=status.HTTP_200_OK)\n\n return Response({'success': False, 'message': 'Only parents can mark the contract as finished.'}, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass AnswerOfferView(generics.GenericAPIView):\n # Missing permission class here, all users can accept others' guardian offers - Eivind\n\n def post(self, request):\n\n if request.data.get('offerId') and request.data.get('status'):\n\n offer = Offer.objects.get(id=request.data['offerId'])\n state = request.data['status']\n\n if offer.status != OfferStatus.PENDING:\n return Response({'success': False, 'message': 'Offer already answered'}, status=status.HTTP_400_BAD_REQUEST)\n\n if state == 'D': # Declined offer\n offer.status = OfferStatus.DECLINED\n offer.save()\n return Response({'success': True, 'message': 'Offer declined'}, status=status.HTTP_200_OK)\n\n if state == 'A': # Accepted offer\n offer.status = OfferStatus.ACCEPTED\n\n if offer.offerType == OfferType.GUARDIAN_OFFER:\n parent = get_user_model().objects.get(username=offer.recipient)\n children = Child.objects.filter(parent=parent)\n sender = get_user_model().objects.get(username=offer.sender)\n\n for child in children:\n child.guardians.add(sender)\n child.save()\n if offer.offerType == OfferType.JOB_OFFER:\n ad = offer.advert # Advert.objects.get(offer.advert)\n if ad.advertType == AdvertType.IS_SITTER:\n parent = get_user_model().objects.get(username=offer.sender)\n sitter = get_user_model().objects.get(username=offer.recipient)\n\n if ad.advertType == AdvertType.NEED_SITTER:\n parent = get_user_model().objects.get(username=offer.recipient)\n sitter = get_user_model().objects.get(username=offer.sender)\n\n contract = Contract(\n parent=parent, sitter=sitter, date=ad.date, start_time=ad.start_time, end_time=ad.end_time, content=ad.content)\n ad.save()\n contract.save()\n\n offer.save()\n return Response({'success': True, 'message': 'Offer accepted'}, status=status.HTTP_200_OK)\n\n return Response({'success': False, 'message': 'Missing offerId or invalid status'}, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"edalholt/TDT4237-trustedSitters-Vulnerable-Application","sub_path":"backend/apps/offers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"73349022480","text":"#!/usr/bin/env python\n#\n# Code to plot the quantitiave comparisons of the Y image slices\n# between different codes\n#\n# 17 Jun 2016: written (Karl Gordon)\n#\nimport os.path\nimport argparse\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport matplotlib as mpl\n\nfrom astropy.table import Table\n\ndef plot_indiv_slice(ax, tau, waves, angles, run_tag,\n dcol, fontsize=16, irwaves=False):\n\n sym = ['-','--','-.',':']\n for n, wave in enumerate(waves):\n for k, angle in enumerate(angles):\n\n tab_name = 'dat/slab_t' + tau + '_i' + angle + '_w' + wave + \\\n '_image_comp' + run_tag\n \n cur_table = Table.read(tab_name+'.dat',\n format='ascii.commented_header')\n\n # initialize and get model names\n if n == 0 and k == 0:\n mvals = np.array(cur_table['model'])\n pvals = np.empty((len(mvals),len(angles)))\n \n pvals[:,k] = np.array(cur_table['cut1_stddev'])\n\n not_used_models = [\"DART-ray\",\"TRADING\"]\n for i, cmodel in enumerate(mvals):\n trans = 1.0\n if (tau == '1e1') and irwaves:\n if cmodel in not_used_models:\n trans = 0.25\n ax.plot(angles, pvals[i,:], dcol[cmodel]+sym[n], alpha=trans,\n label=cmodel + r' $\\lambda = ' + wave + '$')\n\n indxs = np.arange(len(mvals))\n if (tau == '1e1') and irwaves:\n for nmod in not_used_models:\n nindxs, = np.where(mvals[indxs] != nmod)\n indxs = indxs[nindxs]\n\n print('Y slice: ', tau, wave, np.max(pvals[indxs,:]))\n \n #sones = np.full((len(angles)),1.0)\n #ax.plot(angles,sones,'k--')\n #ax.plot(angles,5.0*sones,'k-.')\n\n ax.set_yscale('log') \n ax.set_ylim(0.5e-1,1e4)\n ax.set_ylabel(r'$\\bar{\\Delta}$ [%]')\n ax.set_xlabel(r'$\\theta$')\n\n ax.set_title(r'$\\tau_z =$ ' + tau + ' (Y slice)')\n\n return mvals\n\n #ax.legend(loc=3)\n\ndef plot_slice_all_taus(args, good_angles, waves, ax, dispstr,\n fontsize=14, plegend=True, irwaves=False):\n\n # setup the plot\n taus = ['1e0','1e1']\n tax = ax\n\n col = ['b','g','r','c','m','y','k']\n models = ['CRT','DART-ray','DIRTY','Hyperion','SKIRT',\n 'TRADING','SOC']\n dcol = dict(zip(models, col))\n\n for k, cur_ax in enumerate(tax):\n pmodels = plot_indiv_slice(cur_ax, taus[k], waves, good_angles, \n dispstr,dcol, irwaves=irwaves)\n if k == 0:\n save_pmodels = pmodels\n\n # Create two custom legends (more compact)\n\n # models\n if plegend:\n arts = [plt.Line2D((0,1),(0,0), color=dcol[cmodel], linestyle='-') \n for cmodel in save_pmodels]\n leg1 = tax[0].legend(arts,\n save_pmodels,\n fontsize=1.25*fontsize,\n loc='upper left',\n ncol=2)\n leg1.get_frame().set_linewidth(2)\n\n # Add the legend manually to the current Axes.\n #tax[0].add_artist(leg1)\n\n # waves\n if args.sto and not args.uvopt:\n arts = [plt.Line2D((0,1),(0,0), color='k', linestyle='-'),\n plt.Line2D((0,1),(0,0), color='k', linestyle='--'),\n plt.Line2D((0,1),(0,0), color='k', linestyle='-.')]\n labs = [r'$\\lambda = '+waves[0]+'$',\n r'$\\lambda = '+waves[1]+'$',\n r'$\\lambda = '+waves[2]+'$']\n else:\n arts = [plt.Line2D((0,1),(0,0), color='k', linestyle='-'),\n plt.Line2D((0,1),(0,0), color='k', linestyle='--')]\n labs = [r'$\\lambda = '+waves[0]+'$',\n r'$\\lambda = '+waves[1]+'$']\n \n leg2 = tax[1].legend(arts, labs,\n title='Y Slice',\n fontsize=1.25*fontsize,\n loc='upper center', \n bbox_to_anchor=(-0.05,0.97))\n leg2.get_title().set_fontsize(fontsize*1.5)\n leg2.get_frame().set_linewidth(2)\n\n # make y axis nice\n\n tax[1].yaxis.tick_right()\n tax[1].yaxis.set_ticks_position('both')\n tax[1].yaxis.set_label_position(\"right\")\n\nif __name__ == \"__main__\":\n\n good_angles = ['000','030','060','090','120','150','180']\n\n # commandline parser\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--uvopt\", action=\"store_true\",\n help=\"Display UV/optical results\")\n parser.add_argument(\"--eff\", action=\"store_true\",\n help=\"Display results for the effective grain \" + \\\n \"emission approximation [Default]\")\n parser.add_argument(\"--equ\", action=\"store_true\",\n help=\"Display results for the equilibrium heating \" + \\\n \"only approximation\")\n parser.add_argument(\"--sto\", action=\"store_true\",\n help=\"Display results for the full heating solution \" + \\\n \"(equilibrium + non-equilibrium)\")\n parser.add_argument(\"--eps\", help=\"Save the plot as an \" + \\\n \"encapsulated file\",\n action=\"store_true\")\n parser.add_argument(\"--pdf\", help=\"Save the plot as a \" + \\\n \"portable document file file\",\n action=\"store_true\")\n parser.add_argument(\"--png\", help=\"Save the plot as a \" + \\\n \"portable network graphics file\",\n action=\"store_true\")\n args = parser.parse_args()\n\n # setup the plots\n fontsize = 14\n font = {'size' : fontsize}\n\n mpl.rc('font', **font)\n\n mpl.rc('lines', linewidth=2)\n mpl.rc('axes', linewidth=2)\n mpl.rc('xtick.major', width=2)\n mpl.rc('ytick.major', width=2)\n\n if args.uvopt:\n waves = ['000.15','000.53']\n irwaves = False\n else:\n if args.sto:\n waves = ['008.11','023.10','151.99']\n else:\n waves = ['035.11','151.99']\n irwaves = True\n\n dispstr = 'eff'\n tagstr = ''\n if args.equ:\n dispstr = 'equ'\n tagstr = '_equ'\n elif args.sto:\n dispstr = 'sto'\n tagstr = '_sto'\n\n fig, ax = plt.subplots(ncols=2,figsize=(15,6))\n\n plot_slice_all_taus(args, good_angles, waves, ax, tagstr)\n\n fig.tight_layout()\n\n save_name = 'slab_qcomp_image_' + dispstr\n\n if args.uvopt:\n save_name += '_uvopt'\n else:\n save_name += '_ir'\n\n if args.png:\n fig.savefig(save_name+'.png')\n fig.savefig(save_name+'_small.png',dpi=11)\n elif args.eps:\n fig.savefig(save_name+'.eps')\n elif args.pdf:\n fig.savefig(save_name+'.pdf')\n else:\n plt.show()\n\n plt.close(fig)\n","repo_name":"karllark/trust_slab","sub_path":"plot_slab_quant_comp_image.py","file_name":"plot_slab_quant_comp_image.py","file_ext":"py","file_size_in_byte":6839,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"8280842848","text":"import numpy as np\nimport casadi as ca\nimport csv\n\nclass Near():\n def __init__(self, path=None):\n \n opt_option = {\n 'verbose': False,\n 'ipopt.tol': 1e-2,\n 'ipopt.acceptable_tol': 1e-2,\n 'ipopt.max_iter': 20,\n # 'ipopt.warm_start_init_point': 'yes',\n 'ipopt.print_level': 0,\n }\n\n if path==None:\n t = ca.SX.sym('t')\n traj_ploy = ca.SX.sym(\"traj_ploy\", 12, 2)\n dts = ca.SX.sym(\"dts\",2)\n pos = ca.SX.sym('pos', 3)\n\n obj = (self.traj_ploy(traj_ploy, dts, t)-pos).T@(self.traj_ploy(traj_ploy, dts, t)-pos)\n\n nlp_dect = {\n 'f': obj,\n 'x': t,\n 'p': ca.vertcat(traj_ploy[:,0], traj_ploy[:,1], dts, pos)\n }\n self._opt_solver = ca.nlpsol('opt', 'ipopt', nlp_dect, opt_option)\n else:\n self._opt_solver = ca.nlpsol('opt', 'ipopt', path, opt_option)\n\n def solve(self, coef1, coef2, dt1, dt2, pos):\n p = np.zeros(12*2+2+3)\n p[:12] = coef1\n p[12:24] = coef2\n p[24] = dt1\n p[25] = dt2\n p[26:] = pos\n\n res = self._opt_solver(\n x0=0,\n p=p\n )\n\n return res['x'].full().flatten()\n\n\n def traj_ploy(self, ploy_coef, dts, t):\n p=0\n\n a0=ploy_coef[:3,0]\n a1=ploy_coef[3:6,0]\n a2=ploy_coef[6:9,0]\n a3=ploy_coef[9:12,0]\n dt = dts[0]+t\n dtdt = dt*dt\n dtdtdt = dtdt*dt\n p+= (t<=0)*( a0+a1*dt+a2*dtdt+a3*dtdtdt )\n \n a0=ploy_coef[:3,1]\n a1=ploy_coef[3:6,1]\n a2=ploy_coef[6:9,1]\n a3=ploy_coef[9:12,1]\n dt = t\n dtdt = dt*dt\n dtdtdt = dtdt*dt\n p+= (t>0)*( a0+a1*dt+a2*dtdt+a3*dtdtdt )\n\n return p\n\nclass Trajectory():\n def __init__(self, csv_f=None, near_path=None):\n if csv_f != None:\n t = []\n pos = []\n vel = []\n quaternion = []\n omega = []\n self._N = 0\n ploynomials = []\n u = []\n acc = []\n with open(csv_f, 'r') as f:\n traj_reader = csv.DictReader(f)\n for s in traj_reader:\n t.append(float(s['t']))\n pos.append([ float(s[\"p_x\"]), float(s[\"p_y\"]), float(s[\"p_z\"]) ])\n vel.append([ float(s[\"v_x\"]), float(s[\"v_y\"]), float(s[\"v_z\"]), np.sqrt(float(s[\"v_x\"])*float(s[\"v_x\"])+float(s[\"v_y\"])*float(s[\"v_y\"])+float(s[\"v_z\"])*float(s[\"v_z\"])) ])\n quaternion.append([ float(s[\"q_w\"]), float(s[\"q_x\"]), float(s[\"q_y\"]), float(s[\"q_z\"]) ])\n omega.append([ float(s[\"w_x\"]), float(s[\"w_y\"]), float(s[\"w_z\"]) ])\n if \"u_1\" in s.keys():\n u.append([float(s[\"u_1\"]), float(s[\"u_2\"]), float(s[\"u_3\"]), float(s[\"u_4\"])])\n if \"a_x\" in s.keys():\n acc.append([float(s[\"a_x\"]), float(s[\"a_y\"]), float(s[\"a_z\"])])\n \n self._t = np.array(t)\n self._pos = np.array(pos)\n self._vel = np.array(vel)\n self._quaternion = np.array(quaternion)\n self._omega = np.array(omega)\n self._u = np.array(u)\n self._acc = np.array(acc)\n \n self._N = self._t.shape[0]-1\n assert(self._N>0)\n self._dt = self._t[1:]-self._t[:-1]\n for i in range(self._N):\n a0, a1, a2, a3 = self._ploynomial(self._pos[i], self._pos[i+1], self._vel[i,:3], self._vel[i+1,:3], self._dt[i])\n ploynomials.append( np.concatenate((a0,a1,a2,a3)) )\n self._ploynomials = np.array(ploynomials)\n\n else:\n self._t = np.array([])\n self._pos = np.array([])\n self._vel = np.array([])\n self._quaternion = np.array([])\n self._omega = np.array([])\n self._u = np.array([])\n self._acc = np.array([])\n self._N = 0\n self._dt = np.array([])\n self._ploynomials = np.array([])\n \n self._near = Near(near_path)\n \n def load_data(self, pos, vel, quat, omega, dt):\n self._pos = pos\n self._quaternion = quat\n self._omega = omega\n self._dt = dt\n self._N = self._pos.shape[0]-1\n\n self._vel = np.zeros([self._N+1, 4])\n self._vel[0,:3] = vel[0,:]\n self._vel[0,3] = np.linalg.norm(vel[0,:])\n self._t = np.zeros([self._N+1])\n self._t[0] = 0\n ploynomials = []\n for i in range(self._N):\n self._vel[i+1,:3] = vel[i+1,:]\n self._vel[i+1,3] = np.linalg.norm(vel[i+1,:])\n self._t[i+1] = self._t[i]+dt[i]\n \n a0, a1, a2, a3 = self._ploynomial(self._pos[i], self._pos[i+1], self._vel[i,:3], self._vel[i+1,:3], self._dt[i])\n ploynomials.append( np.concatenate((a0,a1,a2,a3)) )\n self._ploynomials = np.array(ploynomials)\n \n\n def __getitem__(self, idx):\n traj = Trajectory()\n traj._t = self._t[idx]\n traj._pos = self._pos[idx]\n traj._vel = self._vel[idx]\n traj._quaternion = self._quaternion[idx]\n traj._omega = self._omega[idx]\n traj._dt = traj._t[1:] - traj._t[:-1]\n traj._ploynomials = self._ploynomials[idx]\n if self._u.shape[0]!=0:\n traj._u = self._u[idx]\n if self._acc.shape[0]!=0:\n traj._acc = self._acc[idx]\n traj._N = traj._t.shape[0]-1\n return traj\n\n def _ploynomial(self, p1, p2, v1, v2, dt):\n a0 = p1\n a1 = v1\n a2 = (3*p2-3*p1-2*v1*dt-v2*dt)/dt/dt\n a3 = (2*p1-2*p2+v2*dt+v1*dt)/dt/dt/dt\n return a0, a1, a2, a3\n \n def _seg_pos_vel(self, poly_coef, dt):\n a0 = poly_coef[:3]\n a1 = poly_coef[3:6]\n a2 = poly_coef[6:9]\n a3 = poly_coef[9:12]\n\n dtdt = dt*dt\n dtdtdt = dtdt*dt\n pos = a0 + a1*dt + a2*dtdt +a3*dtdtdt\n vel = a1 + 2*a2*dt + 3*a3*dtdt\n return pos, vel\n\n def sample(self, n, pos):\n idx = np.argmin(np.linalg.norm(self._pos-pos, axis=1))\n idx -= 1 #\n\n traj_seg = np.zeros((n, 3))\n traj_v_seg = np.zeros((n, 3))\n traj_dt_seg = np.zeros(n)\n traj_polynomial_seg = np.zeros((n, 12))\n for i in range(n):\n traj_seg[i,:] = self._pos[(idx+int(i*1.0))%self._N]\n traj_v_seg[i,:] = self._vel[(idx+int(i*1.0))%self._N,:3]\n traj_dt_seg[i] = self._dt[(idx+int(i*1.0))%self._N]\n traj_polynomial_seg[i, :] = self._ploynomials[(idx+int(i*1.0))%self._N]\n\n return traj_seg, traj_v_seg, traj_dt_seg, traj_polynomial_seg\n \n def sample_dt_reset(self):\n self._sample_time_idx = 0\n self._sample_time = 0\n \n def sample_t(self, time_dt, dt, n, loop=True):\n self._sample_time += time_dt\n \n while self._sample_time - self._dt[self._sample_time_idx]>0:\n self._sample_time -= self._dt[self._sample_time_idx]\n self._sample_time_idx += 1\n if self._sample_time_idx >= self._N:\n if loop:\n self._sample_time_idx = 0\n else:\n self._sample_time_idx = self._N-1\n break\n \n traj_seg = np.zeros((n, 3))\n traj_v_seg = np.zeros((n, 3))\n for i in range(n):\n s_time = self._sample_time + (i+1)*dt\n s_idx = self._sample_time_idx\n while s_time - self._dt[s_idx]>0:\n s_time -= self._dt[s_idx]\n s_idx += 1\n if s_idx >= self._N:\n if loop:\n s_idx = 0\n else:\n s_idx = self._N-1\n break\n \n traj_seg[i,:], traj_v_seg[i,:] = self._seg_pos_vel(self._ploynomials[s_idx], s_time)\n \n return traj_seg, traj_v_seg\n \n def distance(self, pos):\n idx = np.argmin(np.linalg.norm(self._pos-pos, axis=1))\n if idx == 0:\n idx = 1\n ddt = self._near.solve(self._ploynomials[idx-1], self._ploynomials[idx], self._dt[idx-1], self._dt[idx], pos)\n idx_dt = 0\n if ddt<0:\n idx_dt = self._dt[idx-1]+ddt\n idx = idx-1\n else:\n idx_dt = ddt\n \n p, v = self._seg_pos_vel(self._ploynomials[idx], idx_dt)\n return np.linalg.norm(p-pos)\n \n def divide_loops(self, pos):\n loop_idx = []\n flag1 = 0\n flag2 = 0\n for i in range(self._N):\n if np.linalg.norm(self._pos[i]-pos)< 1:\n if flag1 == 0:\n l = np.linalg.norm(self._pos[i] - pos)\n flag1 = 1\n else:\n if l 0:\n warnings.warn(f\"There are {df.index.duplicated().sum()} duplicates in the index after cleaning\", RuntimeWarning)\n\n return df\n\n\ndef save_data(df, database_filename):\n \"\"\"\n Save messages and categories in dataframe to SQLite DB table 'messages'\n :param df: DataFrame with messages and category columns\n :param database_filename: Filename of the SQLite DB\n :return:\n \"\"\"\n engine = create_engine(f'sqlite:///{database_filename}')\n df.to_sql('messages', engine, index=False, if_exists='replace')\n\n\ndef main():\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'\n .format(messages_filepath, categories_filepath))\n messages, categories = load_data(messages_filepath, categories_filepath)\n\n print('Cleaning data...')\n df = clean_data(messages, categories)\n \n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n \n print('Cleaned data saved to database!')\n \n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()","repo_name":"schilli/disaster-response","sub_path":"data/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39710652127","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 14 16:29:28 2017\n\n@author: Tim\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Praktikum\n\n\ndata = Praktikum.lese_lab_datei('lab/Parallell_unendlich2.lab')\n\nf = data[:,-2]\nphi = data[:,-7]\nI = data[:,3]\nZ = data[:,-1]\nIC = data[:,-3]\nIL = data[:,-6]\n\n\nplt.figure(0)\nax1 = plt.subplot(111)\nplt.plot(f,I,label='I')\nplt.ylabel('I/A')\nplt.xlabel('f/Hz')\n\nax2 = ax1.twinx()\nplt.plot(f,Z,color = 'r',label='Z')\nplt.ylabel('Z/$\\Omega$')\n\nplt.show()\n\nplt.figure(1)\nplt.plot(f,phi,marker='.')\nplt.ylabel('$\\phi$/deg')\nplt.xlabel('f/Hz')\nplt.axhline(0)\nplt.show()\n\nplt.figure()\nplt.plot(f,IC)\nplt.plot(f,IL)\nplt.plot(f,I)\nplt.show()\n\n\n","repo_name":"thewhitecat/grundpraktikum1","sub_path":"grundpraktikum2/E-Lehre/Gruppe B/Parallel.py","file_name":"Parallel.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42516082715","text":"########################################################################################################################\n#\n# Create service API call\n#\n# Date created: 01.06.2020\n# Date last modified: 10.02.2021\n#\n# __author__ = Michel Schwandner (schwandner@geoville.com)\n# __version__ = 21.02\n#\n########################################################################################################################\n\nfrom error_classes.http_error_400.http_error_400 import BadRequestError\nfrom error_classes.http_error_500.http_error_500 import InternalServerErrorAPI\nfrom error_classes.http_error_503.http_error_503 import ServiceUnavailableError\nfrom flask_restx import Resource\nfrom geoville_ms_database.geoville_ms_database import execute_database\nfrom geoville_ms_logging.geoville_ms_logging import gemslog, LogLevel\nfrom init.init_env_variables import database_config_file, database_config_section_api\nfrom init.namespace_constructor import crm_namespace as api\nfrom lib.auth_header import auth_header_parser\nfrom lib.database_helper import check_service_name_existence\nfrom lib.hashing_helper import generate_service_id_hash\nfrom models.models_crm.service_models.service_models import service_creation_model, service_id_model\nfrom models.models_error.http_error_400 import error_400_model\nfrom models.models_error.http_error_401 import error_401_model\nfrom models.models_error.http_error_403 import error_403_model\nfrom models.models_error.http_error_500 import error_500_model\nfrom models.models_error.http_error_503 import error_503_model\nfrom oauth.oauth2 import require_oauth\nimport traceback\n\n\n########################################################################################################################\n# Resource definition for the create customer API call\n########################################################################################################################\n\n@api.expect(service_creation_model)\n@api.header('Content-Type', 'application/json')\nclass CreateService(Resource):\n \"\"\" Class for handling the POST request\n\n This class defines the API call for the create customer script. The class consists of one method which accepts a\n POST request. For the POST request a JSON with several parameters is required and defined in the corresponding model.\n\n \"\"\"\n\n ####################################################################################################################\n # Method for handling the POST request\n ####################################################################################################################\n\n @require_oauth(['admin'])\n @api.expect(auth_header_parser)\n @api.response(201, 'Operation successful', service_id_model)\n @api.response(400, 'Validation Error', error_400_model)\n @api.response(401, 'Unauthorized', error_401_model)\n @api.response(403, 'Forbidden', error_403_model)\n @api.response(500, 'Internal Server Error', error_500_model)\n @api.response(503, 'Service Unavailable', error_503_model)\n def post(self):\n \"\"\" POST definition for creating a new service\n\n This method defines the handler for the POST request of the create service\n script. It returns a message wrapped into a dictionary about the process of the insertion operation.
\n\n
Description:\n \n\n
Request headers:\n \n\n
Request payload:\n \n\n
Result:\n \n\n \"\"\"\n\n try:\n req_args = api.payload\n gemslog(LogLevel.INFO, f'Request payload: {req_args}', 'API-create_service')\n\n if check_service_name_existence(req_args['service_name'], database_config_file, database_config_section_api):\n error = BadRequestError('Service name exists already', '', '')\n gemslog(LogLevel.WARNING, f\"'message': {error.to_dict()}\", 'API-create_service')\n return {'message': error.to_dict()}, 400\n\n service_comment = None if 'service_comment' not in req_args else req_args['service_comment']\n service_id = generate_service_id_hash(req_args['service_name'], req_args['service_owner_geoville'])\n\n db_query = \"\"\"INSERT INTO customer.services\n ( \n service_id, service_name, service_validity, service_owner_geoville, service_comment, external\n ) \n VALUES\n (\n %s, %s, %s, %s, %s, %s\n );\n \"\"\"\n\n execute_database(db_query, (service_id, req_args['service_name'], req_args['service_validity'],\n req_args['service_owner_geoville'], service_comment, req_args['external']),\n database_config_file, database_config_section_api, True)\n\n except KeyError as err:\n error = BadRequestError(f'Key error resulted in a BadRequest: {err}', api.payload, traceback.format_exc())\n gemslog(LogLevel.WARNING, f\"'message': {error.to_dict()}\", 'API-create_service')\n return {'message': error.to_dict()}, 400\n\n except AttributeError:\n error = ServiceUnavailableError('Could not connect to the database server', '', '')\n gemslog(LogLevel.ERROR, f\"'message': {error.to_dict()}\", 'API-create_service')\n return {'message': error.to_dict()}, 503\n\n except Exception:\n error = InternalServerErrorAPI('Unexpected error occurred', api.payload, traceback.format_exc())\n gemslog(LogLevel.ERROR, f\"'message': {error.to_dict()}\", 'API-create_service')\n return {'message': error.to_dict()}, 500\n\n else:\n gemslog(LogLevel.INFO, 'Successfully created new service', 'API-create_service')\n return {'service_id': service_id}, 201\n","repo_name":"eea/CLMS_Production_System","sub_path":"03_Service_and_Data_Dissemination_API/services/backend_api/src/resources/resources_crm/create_service/create_service.py","file_name":"create_service.py","file_ext":"py","file_size_in_byte":6419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10665549287","text":"# -*- coding:utf-8 -*-\r\n# &Author AnFany\r\n\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndata = pd.read_csv(r'C:\\Users\\GWT9\\Desktop\\PRSA_data_2010.1.1-2014.12.31.csv')\r\n\r\n# 因为决策树回归和决策树分类程序,相似性很大,唯一的不同在于分类计算基尼系数,而回归计算MSE。\r\n# 因此回归的数据结构在此处和分类的相似\r\n\r\n# 因为原始数据中有些变量的值是离散的,但是是整数表示,因此这里需要将其变为字符串,\r\n# 这主要涉及的变量包括:year\tmonth\tday\thour\r\n\r\n'''第一部分:缺失值的处理'''\r\n# 因为Pm2.5是目标数据,对于缺失值直接删除这一条记录\r\n\r\n# 定义删除目标值为空值的行的函数, 其他列为缺失值则自动填充的函数,并将目标变量放置在数据集最后一列\r\ndef DeleteTargetNan(exdata, targetstr):\r\n # 首先判断目标字段是否有缺失值\r\n if exdata[targetstr].isnull().any():\r\n # 首先确定缺失值的行数\r\n loc = exdata[targetstr][data[targetstr].isnull().values == True].index.tolist()\r\n # 然后删除这些行\r\n exdata = exdata.drop(loc)\r\n # 凡是有缺失值的再一起利用此行的均值填充\r\n exdata = exdata.fillna(exdata.mean())\r\n # 将目标字段至放在最后的一列\r\n targetnum = exdata[targetstr].copy()\r\n del exdata[targetstr]\r\n exdata[targetstr] = targetnum\r\n return exdata\r\n\r\n# 因为此数据集中的year,month, day, hour均为整数型,再程序中会被当做连续的变量\r\n\r\n# 删除原始数据中不需要的字段名\r\ndef Shanchu(exdata, aiduan=['No']):\r\n for ai in aiduan:\r\n if ai in exdata.keys():\r\n del exdata[ai]\r\n return exdata\r\n\r\n\r\n# 因此这里将这4个变量变为字符串的形式\r\ndef TeshuHandle(exdata, ziduan=['year', 'month', 'day', 'hour'], tianjiastr=['年', '月', '日', '时']):\r\n for j, k in zip(ziduan, tianjiastr):\r\n if j in exdata.keys():\r\n exdata[j] = ['%d%s' % (j, k) for j in exdata[j]]\r\n return exdata\r\n\r\n# 数据处理后最终的数据集\r\n\r\nfirst = DeleteTargetNan(data, 'pm2.5')\r\ntwo = Shanchu(first)\r\nthird = TeshuHandle(two)\r\n\r\n# 将数据集按照7;1.5:1.5的比例分为训练,测试、预测数据集\r\n\r\ndef fenge(exdata, per=[0.15, 0.15]):\r\n # 总长度\r\n lent = len(exdata)\r\n alist = np.arange(lent)\r\n np.random.shuffle(alist)\r\n\r\n # 验证\r\n shu = int(lent * per[0])\r\n yu = int(lent * per[1])\r\n\r\n yanzheng = np.random.choice(alist, shu, replace=False)\r\n\r\n # 预测\r\n shengxai = np.array([i for i in alist if i not in yanzheng])\r\n\r\n yuce = np.random.choice(shengxai, yu, replace=False)\r\n\r\n # 训练\r\n train = np.array([j for j in alist if j not in yanzheng and j not in yuce])\r\n\r\n # 返回数据集\r\n dadata = {}\r\n dadata[0] = {}\r\n\r\n dadata[0]['train'] = exdata[train]\r\n dadata[0]['test'] = exdata[yanzheng]\r\n\r\n return dadata, exdata[yuce]\r\n\r\ndeeer = fenge(third.values)\r\n\r\n# 数据\r\ndt_data = deeer[0]\r\ntest_data = deeer[1]\r\n\r\n\r\n# 数据结构和决策树分类是相同的,\r\n","repo_name":"Anfany/Machine-Learning-for-Beginner-by-Python3","sub_path":"Decision Tree/DT_Regression/Data_DT_Regression.py","file_name":"Data_DT_Regression.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"zh","doc_type":"code","stars":405,"dataset":"github-code","pt":"3"}
+{"seq_id":"27769196130","text":"import requests\r\nimport json\r\n\r\n#To get the latest randomness from cloudflare:\r\nr = requests.get('https://drand.cloudflare.com/public/latest', headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0'})\r\ndata = r.json()\r\nlatest_randomness= data[\"randomness\"]\r\n\r\n#Digits is a list containing the hex's individual digits:\r\ndigits = list(latest_randomness.strip(' '))\r\n\r\nnum_length = len(digits)\r\n\r\n#Pairs is a list containing the pairs of digits that will later be converted:\r\npairs = [digits[i] + digits[i+1] for i in range(0, num_length-1, 2)]\r\n\r\nif (num_length % 2 == 1):\r\n pairs.append(digits[num_length-1])\r\n\r\n#Converts hex pairs to integers modulo 80:\r\nfor i in range(len(pairs)):\r\n pairs[i]= int(pairs[i],16) % 80\r\n \r\n#To remove any duplicate numbers:\r\npairs= list(set(pairs))\r\n\r\n#To get the last KINO winning numbers from the given link\r\nreq=requests.get(\"https://api.opap.gr/draws/v3.0/1100/last-result-and-active\")\r\ndata=req.json()\r\nkino_numbers= data[\"last\"][\"winningNumbers\"][\"list\"]\r\n\r\ncount=0 #How many of the pairs' numbers would win in the last KINO drawing\r\n\r\nfor i in range(len(pairs)):\r\n for k in range(len(kino_numbers)):\r\n if (pairs[i]==kino_numbers[k]):\r\n count+=1\r\n kino_numbers.pop(k) #If a number is found, remove it to make the search faster\r\n break\r\n continue\r\n\r\nprint(\"{} of the generated numbers would win in the last KINO drawing\".format(count))","repo_name":"MarinaTsl/Assignment_13","sub_path":"latest_randomness.py","file_name":"latest_randomness.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"2931046250","text":"# pylint: disable=too-many-locals,too-many-statements,too-many-nested-blocks\n\"\"\"\nGet optimal resolution method is defined here.\n\"\"\"\nfrom __future__ import annotations\n\nimport itertools as it\n\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom loguru import logger\nfrom matplotlib.axes import Axes\nfrom networkx.algorithms.community import greedy_modularity_communities\n\nfrom derevo.compatability import get_compatability_graph\n\n\ndef get_best_resolution(\n plants: pd.DataFrame,\n plants_with_limitations_resistance: pd.DataFrame,\n plants_suitable_for_light: pd.DataFrame,\n cohabitation_attributes: pd.DataFrame,\n graph_axes: Axes | None = None,\n) -> pd.DataFrame:\n \"\"\"\n Return dataframe with calculated best resolutions for current collection of species\n and limitation factors / light variants.\n\n If `graph_axes` is given, scatter plot will be drawn on it.\n \"\"\"\n plants = plants.copy()\n plants_with_lim_resist = plants_with_limitations_resistance.copy()\n plants_with_lig_resist = plants_suitable_for_light.copy()\n compatability_graph = get_compatability_graph(plants, cohabitation_attributes)\n lig_list = [1, 2, 3]\n lim_list = [1, 2, 3, 4, 5, 6]\n\n res_list = [x / 10 for x in range(0, 21, 1)]\n result: list[list] = []\n for lig in range(len(lig_list) + 1):\n for lig_subset in it.combinations(lig_list, lig):\n if len(list(lig_subset)) == 0:\n continue\n filtered_plants = plants_with_lig_resist[plants_with_lig_resist.light_type_id.isin(list(lig_subset))]\n light_comp = list(pd.unique(filtered_plants[\"name_ru\"]))\n for lim in range(len(lim_list) + 1):\n for lim_subset in it.combinations(lim_list, lim):\n filtered_plants = plants_with_lim_resist[\n plants_with_lim_resist.limitation_factor_id.isin(list(lim_subset))\n ]\n limitations_comp = filtered_plants.groupby(\"name_ru\").count().reset_index()\n limitations_comp = limitations_comp[\n limitations_comp.limitation_factor_id == limitations_comp.limitation_factor_id.max()\n ]\n limitations_comp = list(pd.unique(limitations_comp[\"name_ru\"]))\n\n # filtering species by environmental factors\n df_comp = plants[plants[\"name_ru\"].isin(light_comp)]\n if len(lim_subset) > 0:\n df_comp = df_comp[df_comp[\"name_ru\"].isin(limitations_comp)]\n\n comp_graph = compatability_graph.copy()\n comp_graph = comp_graph.subgraph(df_comp[\"name_ru\"])\n default_size_of_community = comp_graph.number_of_nodes()\n default_number_of_negative_edges = len(nx.to_pandas_edgelist(comp_graph).query(\"weight == 1\"))\n for res in res_list:\n communities_list = greedy_modularity_communities(comp_graph, weight=\"weight\", resolution=res)\n size_of_biggest_community = max(len(com) for com in communities_list)\n composition = [list(com) for com in communities_list if len(com) == size_of_biggest_community]\n if len(composition) == default_size_of_community:\n c_graph = comp_graph.subgraph(list(it.chain.from_iterable(composition)))\n number_of_remaining_nodes = c_graph.number_of_nodes()\n number_of_negative_edges = len(nx.to_pandas_edgelist(c_graph).query(\"weight == 1\"))\n tag = \"One node community\"\n result.append(\n [\n \", \".join(map(str, list(lig_subset)))\n + \"; \"\n + \", \".join(map(str, list(lim_subset))),\n list(pd.unique(df_comp[\"name_ru\"])),\n communities_list,\n number_of_remaining_nodes,\n number_of_negative_edges,\n res,\n default_size_of_community,\n default_number_of_negative_edges,\n tag,\n ]\n )\n elif len(composition) > 1:\n for comp in composition:\n c_graph = comp_graph.subgraph(comp)\n number_of_remaining_nodes = c_graph.number_of_nodes()\n number_of_negative_edges = len(nx.to_pandas_edgelist(c_graph).query(\"weight == 1\"))\n tag = \"Variable community\"\n result.append(\n [\n \", \".join(map(str, list(lig_subset)))\n + \"; \"\n + \", \".join(map(str, list(lim_subset))),\n list(pd.unique(df_comp[\"name_ru\"])),\n communities_list,\n number_of_remaining_nodes,\n number_of_negative_edges,\n res,\n default_size_of_community,\n default_number_of_negative_edges,\n tag,\n ]\n )\n else:\n c_graph = comp_graph.subgraph(list(it.chain.from_iterable(composition)))\n number_of_remaining_nodes = c_graph.number_of_nodes()\n number_of_negative_edges = len(nx.to_pandas_edgelist(c_graph).query(\"weight == 1\"))\n tag = \"Default community\"\n result.append(\n [\n \", \".join(map(str, list(lig_subset)))\n + \"; \"\n + \", \".join(map(str, list(lim_subset))),\n list(pd.unique(df_comp[\"name_ru\"])),\n communities_list,\n number_of_remaining_nodes,\n number_of_negative_edges,\n res,\n default_size_of_community,\n default_number_of_negative_edges,\n tag,\n ]\n )\n logger.debug(\"lim_subset done: {}\", list(lim_subset))\n logger.debug(\"lig_subset done: {}\", list(lig_subset))\n df_result = pd.DataFrame(\n result,\n columns=[\n \"variant_id\",\n \"precomposition\",\n \"communities_list\",\n \"size\",\n \"negative_edges\",\n \"resolution\",\n \"total_size\",\n \"total_edge_number\",\n \"tag\",\n ],\n )\n df_result[\"share_of_nodes\"] = df_result[\"size\"] / df_result[\"total_size\"]\n df_result[\"share_of_negative_edges\"] = df_result[\"negative_edges\"] / df_result[\"total_edge_number\"]\n df_result[\"composition_improvement\"] = df_result[\"share_of_nodes\"] - df_result[\"share_of_negative_edges\"]\n df_result[\"communities\"] = df_result.communities_list.map(\n lambda x: [list(com) for com in x if len(com) == max(len(com) for com in x)]\n )\n df_result[\"communities\"] = df_result.communities.map(lambda x: list(it.chain.from_iterable(x)))\n df_result[\"size\"] = df_result.communities.map(len)\n\n if graph_axes is not None:\n x_axis = list(df_result[\"resolution\"])\n y_axis = list(df_result[\"composition_improvement\"])\n\n graph_axes.scatter(x_axis, y_axis, marker=0)\n graph_axes.set_xticks(np.arange(min(x_axis), max(x_axis), 0.1), rotation=90)\n graph_axes.set_yticks(np.arange(min(y_axis), max(y_axis), 0.1))\n graph_axes.grid(True)\n graph_axes.set_xlabel(\"resolution\")\n graph_axes.set_ylabel(\"composition improvement\")\n\n return df_result\n","repo_name":"egov-itmo/derevo","sub_path":"method/derevo/optimal_resolution.py","file_name":"optimal_resolution.py","file_ext":"py","file_size_in_byte":8529,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"72733722320","text":"from openerp import api, fields, models, _\nfrom urllib import urlencode\nfrom urlparse import urljoin\nfrom openerp.exceptions import UserError\n\n\nclass SaleOrderExtend(models.Model):\n _inherit = 'sale.order'\n\n @api.multi\n def unlink(self):\n for order in self:\n if order.state not in ['draft','to_accept']:\n raise UserError(_('You can only delete draft quotations or Quotations Awaiting Acceptance!'))\n self.env.cr.execute(\"delete from sale_order where id = %s\" % order.id)\n\n\n @api.multi\n def copy(self, default=None):\n self.ensure_one()\n if default is None:\n default = {}\n res = super(SaleOrderExtend, self).copy(default)\n res.onchange_reach_limit()\n return res\n\n @api.multi\n def action_send_to_manager(self, msg):\n company_email = self.env.user.company_id.email.strip()\n sender_person_email = self.env.user.partner_id.email.strip()\n sender_person_name = self.env.user.name\n res = {}\n self.state = 'to_accept'\n\n if company_email and sender_person_email:\n # Custom Email Template\n mail_template = self.env.ref('kin_sales_double_validation.mail_templ_sale_send_to_manager')\n ctx = {}\n ctx.update({'sale_id': self.id})\n the_url = self._get_sale_order_url('sale', 'menu_sale_order', 'action_orders', ctx)\n\n user_ids = []\n group_obj = self.env.ref('kin_sales_double_validation.group_show_receive_send_to_manager')\n for user in group_obj.users:\n if user.partner_id.email and user.partner_id.email.strip():\n user_ids.append(user.id)\n ctx = {'system_email': company_email,\n 'sender_person_name': sender_person_name,\n 'sender_person_email': sender_person_email,\n 'notify_person_email': user.partner_id.email,\n 'notify_person_name': user.partner_id.name,\n 'url': the_url,\n }\n mail_template.with_context(ctx).send_mail(self.id, force_send=False)\n\n #Simulates Notification Dialog Box\n res = {\n 'name': 'Send to Manager Notification',\n 'view_mode': 'form',\n 'res_model': 'send.manager.wizard',\n 'type': 'ir.actions.act_window',\n 'target': 'new'\n }\n\n return res\n\n\n @api.multi\n def action_disapprove(self,msg):\n reason_for_dispproval = msg\n self.disapproved_by_user_id = self.env.user\n self.state = 'no_sale'\n\n # Send Email\n company_email = self.env.user.company_id.email.strip()\n disapprove_person_email = self.disapproved_by_user_id.partner_id.email.strip()\n disapprove_person_name = self.disapproved_by_user_id.name\n\n if company_email and disapprove_person_email:\n # Custom Email Template\n mail_template = self.env.ref('kin_sales_double_validation.mail_templ_sale_disapproved')\n ctx = {}\n ctx.update({'sale_id': self.id})\n the_url = self._get_sale_order_url('sale', 'menu_sale_order', 'action_orders', ctx)\n\n user_ids = []\n group_obj = self.env.ref('kin_sales_double_validation.group_receive_disapprove_sale_order_email')\n for user in group_obj.users:\n if user.partner_id.email and user.partner_id.email.strip():\n user_ids.append(user.id)\n ctx = {'system_email': company_email,\n 'disapprove_person_name': disapprove_person_name,\n 'disapprove_person_email': disapprove_person_email,\n 'notify_person_email': user.partner_id.email,\n 'notify_person_name': user.partner_id.name,\n 'url': the_url,\n 'reason_for_dispproval': reason_for_dispproval,\n }\n mail_template.with_context(ctx).send_mail(self.id, force_send=False)\n\n if user_ids :\n self.message_subscribe_users(user_ids=user_ids)\n # For Similar Odoo Kind of Email. Works fine\n #self.message_post( _(\"Sales Order has been Disapproved with reason: \" + reason_for_dispproval + \"\") ,subject='Please See the Disapproved Sales Order', subtype='mail.mt_comment')\n\n #Just Log the Note Only\n self.message_post(_(\"Sales Order has been Disapproved with reason: \" + reason_for_dispproval + \"\"), subject='Please See the Disapproved Sales Order')\n\n @api.multi\n def action_approve(self):\n res = super(SaleOrderExtend, self).action_confirm()\n self.approved_by_user_id = self.env.user\n\n # Send Email\n company_email = self.env.user.company_id.email.strip()\n approve_person_email = self.approved_by_user_id.partner_id.email.strip()\n approve_person_name = self.approved_by_user_id.name\n\n if company_email and approve_person_email:\n # Custom Email Template\n mail_template = self.env.ref('kin_sales_double_validation.mail_templ_sale_approved')\n ctx = {}\n ctx.update({'sale_id': self.id})\n the_url = self._get_sale_order_url('sale', 'menu_sale_order', 'action_orders', ctx)\n\n user_ids = []\n group_obj = self.env.ref('kin_sales_double_validation.group_receive_approve_sale_order_email')\n for user in group_obj.users:\n if user.partner_id.email and user.partner_id.email.strip():\n user_ids.append(user.id)\n ctx = {'system_email': company_email,\n 'approve_person_name': approve_person_name,\n 'approve_person_email': approve_person_email,\n 'notify_person_email': user.partner_id.email,\n 'notify_person_name': user.partner_id.name,\n 'url': the_url\n }\n mail_template.with_context(ctx).send_mail(self.id, force_send=False)\n if user_ids :\n self.message_subscribe_users(user_ids=user_ids)\n\n return res\n\n\n @api.multi\n def action_confirm(self):\n self.state = 'so_to_approve'\n self.confirmed_by_user_id = self.env.user\n\n # Give a SO ID\n if self.so_name:\n self.name = self.so_name\n else:\n self.quote_name = self.name\n self.name = self.env['ir.sequence'].get('so_id_code')\n self.so_name = self.name\n\n #Send FYI email notification\n company_email = self.env.user.company_id.email and self.env.user.company_id.email.strip()\n confirm_person_email = self.confirmed_by_user_id.partner_id.email.strip()\n confirm_person_name = self.confirmed_by_user_id.partner_id.name\n\n if company_email and confirm_person_email :\n # Custom Email Template\n mail_template = self.env.ref('kin_sales_double_validation.mail_templ_quote_confirmed')\n ctx = {}\n ctx.update({'sale_id':self.id})\n the_url = self._get_sale_order_url('sale','menu_sale_order','action_orders',ctx)\n\n user_ids = []\n group_obj = self.env.ref('kin_sales_double_validation.group_receive_quotation_confirmed_email')\n for user in group_obj.users:\n if user.partner_id.email and user.partner_id.email.strip():\n user_ids.append(user.id)\n ctx = {\n 'system_email': company_email,\n 'confirm_person_name': confirm_person_name ,\n 'confirm_person_email' :confirm_person_email,\n 'notify_person_email': user.partner_id.email,\n 'notify_person_name': user.partner_id.name,\n 'url':the_url\n }\n mail_template.with_context(ctx).send_mail(self.id, force_send=False)\n if user_ids:\n self.message_subscribe_users(user_ids=user_ids)\n\n #Send email for approval or disapproval\n mail_template = self.env.ref('kin_sales_double_validation.mail_templ_quote_confirmed_to_approve')\n user_ids = []\n group_obj = self.env.ref('kin_sales_double_validation.group_receive_quotation_confirmed_email_to_approve')\n for user in group_obj.users:\n if user.partner_id.email and user.partner_id.email.strip():\n user_ids.append(user.id)\n ctx = {\n 'system_email': company_email,\n 'confirm_person_name': confirm_person_name,\n 'confirm_person_email': confirm_person_email,\n 'notify_person_email': user.partner_id.email,\n 'notify_person_name': user.partner_id.name,\n 'url': the_url\n }\n mail_template.with_context(ctx).send_mail(self.id, force_send=False)\n if user_ids :\n self.message_subscribe_users(user_ids=user_ids)\n\n return\n\n # It acts as a helper for other sub classess to call the parent action_confirm() method\n @api.multi\n def action_confirm_subclass(self):\n res = super(SaleOrderExtend, self).action_confirm()\n\n @api.multi\n def action_cancel(self):\n res = super(SaleOrderExtend,self).action_cancel()\n\n #Send Email\n company_email = self.env.user.company_id.email.strip()\n sales_person_email = self.user_id.partner_id.email.strip()\n confirm_person_email = self.env.user.partner_id.email.strip()\n\n if company_email and sales_person_email and confirm_person_email and (sales_person_email != confirm_person_email ):\n # Custom Email Template\n mail_template = self.env.ref('kin_sales_double_validation.mail_templ_sale_canceled')\n ctx = {}\n ctx.update({'sale_id':self.id})\n the_url = self._get_sale_order_url('sale','menu_sale_order','action_orders',ctx)\n\n ctx = {'system_email': company_email,\n 'confirm_person_name': self.env.user.name ,\n 'confirm_person_email' :confirm_person_email,\n 'url':the_url\n }\n mail_template.with_context(ctx).send_mail(self.id,force_send=False)\n return res\n\n def onchange_reach_limit(self):\n for order in self:\n amount_total = order.amount_total\n sale_confirm_limit = self.env.user.sale_confirm_limit\n is_use_sale_confirm_limit = self.env.user.is_use_sale_confirm_limit\n if (amount_total < sale_confirm_limit) and is_use_sale_confirm_limit and order.state in ['draft','sent','to_accept']:\n self.env.cr.execute(\"update sale_order set state = 'so_to_approve' where id = %s\" % (self.id))\n elif ((amount_total >= sale_confirm_limit) and is_use_sale_confirm_limit and order.state in ['draft','sent']) :\n self.env.cr.execute(\"update sale_order set state = 'to_accept' where id = %s\" % (self.id))\n return\n\n\n\n @api.model\n def create(self, vals):\n order = super(SaleOrderExtend, self).create(vals)\n return order\n\n def _get_sale_order_url(self, module_name,menu_id,action_id, context=None):\n fragment = {}\n res = {}\n model_data = self.env['ir.model.data']\n base_url = self.env['ir.config_parameter'].get_param('web.base.url')\n fragment['menu_id'] = model_data.get_object_reference(module_name,menu_id)[1]\n fragment['model'] = 'sale.order'\n fragment['view_type'] = 'form'\n fragment['action']= model_data.get_object_reference(module_name,action_id)[1]\n query = {'db': self.env.cr.dbname}\n\n# for displaying tree view. Remove if you want to display form view\n# fragment['page'] = '0'\n# fragment['limit'] = '80'\n# res = urljoin(base_url, \"?%s#%s\" % (urlencode(query), urlencode(fragment)))\n\n\n # For displaying a single record. Remove if you want to display tree view\n\n fragment['id'] = context.get(\"sale_id\")\n res = urljoin(base_url, \"?%s#%s\" % (urlencode(query), urlencode(fragment)))\n return res\n\n @api.multi\n def action_send_for_confirm(self):\n\n for order in self:\n order.state = 'waiting'\n order.is_show_btn_send_for_confirm = False\n order.is_show_btn_approve = False\n order.is_show_btn_confirm = True\n\n is_po_check = order.env.user.company_id.is_po_check\n # is PO Check\n if is_po_check:\n if order.client_order_ref:\n client_order_ref = order.client_order_ref.strip()\n\n if len(client_order_ref) <= 0:\n raise UserError(\n 'Please Ensure that the Quote is confirmed from the customer and that the PO reference is set. e.g. you may put the po number, email, contact name, number of the customer that confirmed the Quote on the PO reference field')\n\n else:\n raise UserError(\n 'Please Ensure that the Quote is confirmed from the customer and that the PO reference is set. e.g. you may put the po number, email, contact name, number of the customer that confirmed the Quote')\n\n #Send Email\n company_email = order.env.user.company_id.email and order.env.user.company_id.email.strip()\n sales_person_email = order.user_id.partner_id.email.strip()\n\n if company_email and sales_person_email :\n # Custom Email Template\n mail_template = order.env.ref('kin_sales_double_validation.mail_templ_send_for_confirmation')\n ctx = {}\n ctx.update({'sale_id':order.id})\n the_url = order._get_sale_order_url('sale','menu_sale_order','action_orders',ctx)\n\n user_ids = []\n group_obj = self.env.ref('kin_sales_double_validation.group_receive_send_for_confirm_email')\n for user in group_obj.users :\n if user.partner_id.email and user.partner_id.email.strip() :\n user_ids.append(user.id)\n ctx = {'system_email': company_email,\n 'confirm_person_email':user.partner_id.email,\n 'confirm_person_name': user.partner_id.name ,\n 'url':the_url\n }\n mail_template.with_context(ctx).send_mail(order.id,force_send=False)\n\n if user_ids :\n order.message_subscribe_users(user_ids=user_ids)\n\n #self.message_post( _('Sales Order has been created %s.') % (self.name),subject='Please See the Created Sales Order', subtype='mail.mt_comment')\n\n partner_id = fields.Many2one(states={'draft': [('readonly', False)], 'sent': [('readonly', False)], 'to_accept': [('readonly', False)], 'waiting': [('readonly', False)], 'so_to_approve': [('readonly', False)]})\n partner_invoice_id = fields.Many2one(states={'draft': [('readonly', False)], 'sent': [('readonly', False)], 'to_accept': [('readonly', False)], 'waiting': [('readonly', False)], 'so_to_approve': [('readonly', False)]}, track_visibility='always')\n partner_shipping_id = fields.Many2one(states={'draft': [('readonly', False)], 'sent': [('readonly', False)], 'to_accept': [('readonly', False)], 'waiting': [('readonly', False)], 'so_to_approve': [('readonly', False)]}, track_visibility='always')\n pricelist_id = fields.Many2one('product.pricelist', string='Pricelist', required=True, readonly=True,\n states={'draft': [('readonly', False)],'to_accept': [('readonly', False)], 'sent': [('readonly', False)]},\n help=\"Pricelist for current sales order.\")\n #state = fields.Selection(selection_add=[('waiting', 'Waiting Approval')]) # it worked but , i could not sequence it\n state = fields.Selection([\n ('draft', 'Quotation'),\n ('sent', 'Quote Sent'),\n ('to_accept', 'Quote Awaiting Acceptance'),\n ('waiting', 'Quote Awaiting Conversion to SO'),\n ('so_to_approve', 'Sale Order To Approve'),\n ('sale', 'Sale Order Approved'),\n ('no_sale', 'Sale Order Disapproved'),\n ('credit_limit_by_pass_request', 'Credit Limit By Pass Request'),\n ('credit_limit_by_pass_confirm', 'Credit Limit By Pass Confirmed'),\n ('credit_limit_by_pass_approve', 'Credit Limit By Pass Approved'),\n ('credit_limit_by_pass_disapprove', 'Credit Limit By Pass DisApproved'),\n ('credit_limit_by_pass_cancel', 'Credit Limit By Pass Cancelled'),\n ('done', 'Done'),\n ('cancel', 'Cancelled'),\n ], string='Status', readonly=True, copy=False, index=True, track_visibility='onchange', default='draft')\n\n confirmed_by_user_id = fields.Many2one('res.users',string= 'Confirmed By')\n approved_by_user_id = fields.Many2one('res.users', string='Approved By')\n disapproved_by_user_id = fields.Many2one('res.users', string='Disapproved By')\n date_order = fields.Datetime(string='Order Date', required=True, readonly=True, index=True,\n states={'draft': [('readonly', False), ('required', False)],\n 'sent': [('readonly', False)], 'waiting': [('readonly', False)],\n 'so_to_approve': [('readonly', False)]}, copy=False)\n\n\n\n\nclass ResUsersExtend(models.Model):\n _inherit = 'res.users'\n\n sale_confirm_limit = fields.Float('Sales Confirmation Limit',help='If user exceeds this limit, expose the confirmation button for validation')\n is_use_sale_confirm_limit = fields.Boolean('Use Sales Confirm Limit')\n\n","repo_name":"kingsleyuk2003/ODEX","sub_path":"addons/kin_sales_double_validation/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":18270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38397716932","text":"from io import BytesIO\n\nimport requests\nfrom starlette.responses import StreamingResponse\nfrom fastapi import FastAPI, Request, Form, File, UploadFile\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi.logger import logger\n\napp = FastAPI()\n\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n\ntemplates = Jinja2Templates(directory=\"templates\")\n\n@app.get(\"/\")\nasync def get_root(request: Request):\n return templates.TemplateResponse(\"index.html\", {\"request\": request})\n\n\n@app.post(\"/process_text\")\nasync def process_text(text: str = Form(...)):\n req = requests.get(\"http://text2speech/text2speech\", params={\"text\": text})\n fd = BytesIO(req.content)\n\n return StreamingResponse(fd, headers=req.headers, media_type=req.headers['Content-Type'])\n\n\n@app.post(\"/process_audio\")\nasync def process_audio(audio: UploadFile = File(...)):\n\n file_data = {'file': (audio.filename, audio.file, audio.content_type)}\n req = requests.post(\"http://speech2text/\", files=file_data)\n\n response = {\"text\": req.text}\n logger.info(response)\n return response\n\n\n@app.post(\"/translate\")\nasync def translate(text: str = Form(...), source_language: str = Form(...), target_language: str = Form(...)):\n data = {\"source\": source_language, \"target\": target_language, \"q\": text}\n req = requests.get(\"http://taln.upf.edu/mmt-es_en/translate\", params=data)\n\n json_response = req.json()\n text = json_response['data']['translation']\n \n response = {\"text\": text}\n logger.info(response)\n return response\n\n\nif __name__ == \"__main__\":\n import uvicorn\n uvicorn.run(app, host=\"0.0.0.0\", port=8000)","repo_name":"rcarlini-upf/ingenious","sub_path":"integration/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33747446750","text":"import os\r\nimport cv2\r\nfrom visander.util import ImageSampler\r\nfrom visander.core import Entity\r\nfrom visander.color import BgrIntensityComponent, GrayscaleIntensityComponent,\\\r\n get_intensity, ensure_grayscale\r\n\r\nclass DirectoryBasedImageSource(object):\r\n '''\r\n An image source which is given a directory and will walk \r\n all files in the directory and all subdirectory and read in and\r\n return those files which look like images (based on the file extension)\r\n '''\r\n \r\n def __init__(self, root_dir):\r\n self.root_dir = root_dir\r\n self.image_extensions = ['.jpg','.png','.bmp','.tif','.tiff']\r\n \r\n @property\r\n def entities(self):\r\n '''\r\n A generator function which returns all of the images in this image source.\r\n '''\r\n for root,_,filenames in os.walk(self.root_dir):\r\n for filename in filenames:\r\n _,extension = os.path.splitext(filename)\r\n if extension.lower() in self.image_extensions:\r\n image = cv2.imread(os.path.join(root,filename))\r\n if image.shape[2] == 3:\r\n yield Entity(BgrIntensityComponent(image))\r\n else:\r\n yield Entity(GrayscaleIntensityComponent(image)) \r\n","repo_name":"westonpace/visander","sub_path":"src/visander/io/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17256756838","text":"#utility file for langevin_sim_mfpt_opt.py\n#bt TW 9th Oct 2023.\n# Path: langevin_approach/util.py\n\nimport numpy as np\nfrom scipy.linalg import eig\nfrom scipy.linalg import expm\nfrom scipy.linalg import inv\nfrom scipy.optimize import minimize\nfrom math import pi\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom tqdm import tqdm\n\nimport openmm\nimport config\n\n\"\"\"\n\ndef gaussian_2d(x, y, ax, bx, by, cx, cy): #deprecated\n return ax * np.exp(-((x-bx)**2/(2*cx**2) + (y-by)**2/(2*cy**2)))\n\"\"\"\ndef gaussian_2D(params, x, y):\n A, x0, y0, sigma_x, sigma_y = params\n return A * np.exp(-((x - x0)**2 / (2 * sigma_x**2) + (y - y0)**2 / (2 * sigma_y**2)))\n\ndef random_initial_bias_2d(initial_position, num_gaussians = 20):\n # initial position is a list e.g. [3,3]\n # note this is in \n #returns a set of random ax,ay, bx, by, cx, cy for the 2d Gaussian function\n\n #we convert the initial position from openmm quantity object to array with just the value.\n initial_position = initial_position.value_in_unit_system(openmm.unit.md_unit_system)[0] #this is in nm.\n rng = np.random.default_rng()\n a = np.ones(num_gaussians) * 0.1#* 4 #\n #ay = np.ones(num_gaussians) * 0.1 #there's only one amplitude!\n bx = rng.uniform(initial_position[0]-1, initial_position[0]+1, num_gaussians)\n by = rng.uniform(initial_position[1]-1, initial_position[1]+1, num_gaussians)\n cx = rng.uniform(1.0, 5.0, num_gaussians)\n cy = rng.uniform(1.0, 5.0, num_gaussians)\n #\"gaussian_param should be in A, x0, y0, sigma_x, sigma_y format.\"\n return np.concatenate((a, bx, by, cx, cy))\n\ndef get_total_bias_2d(x,y, gaussian_params):\n \"\"\"\n here we get the total bias at x,y.\n note: we used the transposed K matrix, we need to apply transposed total gaussian bias.\n \"\"\"\n N = x.shape[0] #N is the number of grid points.\n total_bias = np.zeros((N,N))\n num_gaussians = len(gaussian_params)//5\n a = gaussian_params[:num_gaussians]\n bx = gaussian_params[num_gaussians:2*num_gaussians]\n by = gaussian_params[2*num_gaussians:3*num_gaussians]\n cx = gaussian_params[3*num_gaussians:4*num_gaussians]\n cy = gaussian_params[4*num_gaussians:5*num_gaussians]\n for i in range(num_gaussians):\n total_bias = total_bias + gaussian_2D([a[i], bx[i], by[i], cx[i], cy[i]], x, y,)\n\n return total_bias\n\ndef compute_free_energy(K, kT):\n \"\"\"\n In 2D senario, we just need to reshape the peq and F.\n\n K is the transition matrix\n kT is the thermal energy\n peq is the stationary distribution #note this was defined as pi in Simian's code.\n F is the free energy\n eigenvectors are the eigenvectors of K\n\n first we calculate the eigenvalues and eigenvectors of K\n then we use the eigenvalues to calculate the equilibrium distribution: peq.\n then we use the equilibrium distribution to calculate the free energy: F = -kT * ln(peq)\n \"\"\"\n N = int(np.sqrt(K.shape[0]))\n evalues, evectors = eig(K)\n\n #sort the eigenvalues and eigenvectors\n index = np.argsort(evalues) #sort the eigenvalues, the largest eigenvalue is at the end of the list\n evalues_sorted = evalues[index] #sort the eigenvalues based on index\n\n #calculate the equilibrium distribution\n peq = evectors[:, index[-1]].T #normalize the eigenvector\n peq = peq / np.sum(peq)\n peq = peq.real\n #take the real part of the eigenvector i.e. the probability distribution at equilibrium.\n #calculate the free energy\n F = -kT * np.log(peq) #add a small number to avoid log(0))\n #F = F.reshape(N, N)\n return [peq, F, evectors, evalues, evalues_sorted, index]\n\ndef compute_free_energy_power_method(K, kT=0.5981):\n \"\"\"\n this use the power method to calculate the equilibrium distribution.\n num_iter is the number of iterations.\n \"\"\"\n num_iter = 1000\n N = K.shape[0]\n peq = np.ones(N) / N #initialise the peq\n for i in range(num_iter):\n peq = np.dot(peq, K)\n peq = peq / np.sum(peq)\n F = -kT * np.log(peq)\n return [peq, F]\n\ndef kemeny_constant_check(mfpt, peq):\n N2 = mfpt.shape[0]\n kemeny = np.zeros((N2, 1))\n for i in range(N2):\n for j in range(N2):\n kemeny[i] = kemeny[i] + mfpt[i, j] * peq[j]\n #print(\"Performing Kemeny constant check...\")\n #print(\"the min/max of the Kemeny constant is:\", np.min(kemeny), np.max(kemeny))\n \"\"\"\n if np.max(kemeny) - np.min(kemeny) > 1e-6:\n print(\"Kemeny constant check failed!\")\n raise ValueError(\"Kemeny constant check failed!\")\"\"\"\n return kemeny\n\ndef mfpt_calc(peq, K):\n \"\"\"\n peq is the probability distribution at equilibrium.\n K is the transition matrix.\n N is the number of states.\n \"\"\"\n N = K.shape[0] #K is a square matrix.\n onevec = np.ones((N, 1)) #, dtype=np.float64\n Qinv = np.linalg.inv(peq.T * onevec - K.T)\n\n mfpt = np.zeros((N, N)) #, dtype=np.float64\n for j in range(N):\n for i in range(N):\n #to avoid devided by zero error:\n if peq[j] == 0:\n mfpt[i, j] = 0\n else:\n mfpt[i, j] = 1 / peq[j] * (Qinv[j, j] - Qinv[i, j])\n \n #result = kemeny_constant_check(N, mfpt, peq)\n return mfpt\n\ndef Markov_mfpt_calc(peq, M):\n N = M.shape[0]\n onevec = np.ones((N, 1))\n Idn = np.diag(onevec[:, 0])\n A = (peq.reshape(-1, 1)) @ onevec.T #was peq.T @ onevec.T\n A = A.T\n Qinv = inv(Idn + A - M)\n mfpt = np.zeros((N, N))\n for j in range(N):\n for i in range(N):\n term1 = Qinv[j, j] - Qinv[i, j] + Idn[i, j]\n if peq[j] * term1 == 0:\n mfpt[i, j] = 1000000000000\n else:\n mfpt[i, j] = 1/peq[j] * term1\n #result = kemeny_constant_check(N, mfpt, peq)\n return mfpt\n\ndef try_and_optim_M(M, working_indices, N=20, num_gaussian=10, start_index=0, end_index=0, plot = False):\n \"\"\"\n here we try different gaussian params 1000 times\n and use the best one (lowest mfpt) to local optimise the gaussian_params\n \n returns the best gaussian params\n\n input:\n M: the working transition matrix, square matrix.\n working_indices: the indices of the working states.\n num_gaussian: number of gaussian functions to use.\n start_state: the starting state. note this has to be converted into the index space.\n end_state: the ending state. note this has to be converted into the index space.\n index_offset: the offset of the index space. e.g. if the truncated M (with shape [20, 20]) matrix starts from 13 to 33, then the index_offset is 13.\n \"\"\"\n #here we find the index of working_indices.\n # e.g. the starting index in the working_indices is working_indices[start_state_working_index]\n # and the end is working_indices[end_state_working_index]\n \n start_state_working_index = np.argmin(np.abs(working_indices - start_index))\n end_state_working_index = np.argmin(np.abs(working_indices - end_index))\n \n start_state_working_index_xy = np.unravel_index(working_indices[start_state_working_index], (N, N), order='C')\n end_state_working_index_xy = np.unravel_index(working_indices[end_state_working_index], (N, N), order='C')\n print(\"Try and Optim from state:\", start_state_working_index_xy, \"to state:\", end_state_working_index_xy)\n\n #now our M/working_indices could be incontinues. #N = M.shape[0]\n x,y = np.meshgrid(np.linspace(0, 2*np.pi, N), np.linspace(0, 2*np.pi, N)) #hard coded here. we need to change this.\n best_mfpt = 1e20 #initialise the best mfpt np.inf\n\n #here we find the x,y maximum and minimun in xy coordinate space, with those working index\n #we use this to generate the random gaussian params.\n working_indices_xy = np.unravel_index(working_indices, (N, N), order='C')\n\n for try_num in range(1000):\n rng = np.random.default_rng()\n a = np.ones(num_gaussian) * 2\n bx = rng.uniform(0, 2*np.pi, num_gaussian)\n by = rng.uniform(0, 2*np.pi, num_gaussian)\n cx = rng.uniform(0.3, 1.5, num_gaussian)\n cy = rng.uniform(0.3, 1.5, num_gaussian)\n gaussian_params = np.concatenate((a, bx, by, cx, cy))\n\n total_bias = get_total_bias_2d(x,y, gaussian_params)\n M_biased = np.zeros_like(M)\n\n #we truncate the total_bias to the working index.\n working_bias = total_bias[working_indices_xy] #say M is in shape[51,51], working bias will be in [51] shape.\n\n #now we have a discontinues M matrix. we need to apply the bias to the working index.\n for i in range(M.shape[0]):\n for j in range(M.shape[1]):\n u_ij = working_bias[j] - working_bias[i]\n M_biased[i,j] = M[i,j] * np.exp(-u_ij / (2*0.5981))\n M_biased[i,i] = M[i,i]\n #epsilon_offset = 1e-15\n #M_biased = M_biased / (np.sum(M_biased, axis=0)[:, None] + 1e-15)\n for i in range(M_biased.shape[0]):\n if np.sum(M_biased[i, :]) > 0:\n M_biased[i, :] = M_biased[i, :] / np.sum(M_biased[i, :])\n else:\n M_biased[i, :] = 0\n \n #note our M_biased is in working index. M.shape = (num_working_states, num_working_states)\n peq,F,_,_,_,_ = compute_free_energy(M_biased.T.astype(np.float64), kT=0.5981)\n #print(peq)\n #print(sum(peq))\n\n mfpts_biased = Markov_mfpt_calc(peq, M_biased)\n mfpt_biased = mfpts_biased[start_state_working_index, end_state_working_index]\n\n if try_num % 100 == 0:\n kemeny_constant_check(mfpts_biased, peq)\n print(\"random try:\", try_num, \"mfpt:\", mfpt_biased)\n if best_mfpt > mfpt_biased:\n best_mfpt = mfpt_biased\n best_params = gaussian_params\n\n print(\"best mfpt:\", best_mfpt)\n \n #now we use the best params to local optimise the gaussian params\n\n def mfpt_helper(gaussian_params, M, start_state_working_index = start_state_working_index, end_state_working_index = end_state_working_index, kT=0.5981, working_indices=working_indices):\n #print(\"Try and Optim from state:\", start_state_working_index_xy, \"to state:\", end_state_working_index_xy)\n total_bias = get_total_bias_2d(x,y, gaussian_params)\n M_biased = np.zeros_like(M)\n\n #we truncate the total_bias to the working index.\n working_bias = total_bias[working_indices_xy] #say M is in shape[51,51], working bias will be in [51] shape.\n\n #now we have a discontinues M matrix. we need to apply the bias to the working index.\n for i in range(M.shape[0]):\n for j in range(M.shape[1]):\n u_ij = working_bias[j] - working_bias[i]\n M_biased[i,j] = M[i,j] * np.exp(-u_ij / (2*0.5981))\n M_biased[i,i] = M[i,i]\n #epsilon_offset = 1e-15\n #M_biased = M_biased / (np.sum(M_biased, axis=0)[:, None] + 1e-15)\n for i in range(M_biased.shape[0]):\n if np.sum(M_biased[i, :]) > 0:\n M_biased[i, :] = M_biased[i, :] / np.sum(M_biased[i, :])\n else:\n M_biased[i, :] = 0\n \n #note our M_biased is in working index. M.shape = (num_working_states, num_working_states)\n peq,F,_,_,_,_ = compute_free_energy(M_biased.T.astype(np.float64), kT=0.5981)\n \n mfpts_biased = Markov_mfpt_calc(peq, M_biased)\n mfpt_biased = mfpts_biased[start_state_working_index, end_state_working_index]\n return mfpt_biased\n\n \n res = minimize(mfpt_helper, \n best_params, \n args=(M,\n start_state_working_index, \n end_state_working_index,\n working_indices), \n method='Nelder-Mead', \n bounds= [(0.1, 2)]*num_gaussian + [(0, 2*np.pi)]*num_gaussian + [(0, 2*np.pi)]*num_gaussian + [(0.3, 1.5)]*num_gaussian + [(0.3, 1.5)]*num_gaussian,\n tol=1e0)\n \n #print(\"local optimisation result:\", res.x)\n return res.x\n\ndef save_CV_total(CV_total, time_tag, prop_index):\n np.save(f\"./data/{time_tag}_{prop_index}_CV_total.npy\", CV_total[-1])\n\ndef save_gaussian_params(gaussian_params, time_tag, prop_index):\n np.save(f\"./data/{time_tag}_{prop_index}_gaussian_params.npy\", gaussian_params)\n\n\n\ndef apply_fes(system, particle_idx, gaussian_param=None, pbc = False, name = \"FES\", amp = 7, mode = \"gaussian\", plot = False, plot_path = \"./fes_visualization.png\"):\n \"\"\"\n this function apply the bias given by the gaussian_param to the system.\n \"\"\"\n pi = np.pi #we need convert this into nm.\n #at last we add huge barrier at the edge of the box. since we are not using pbc.\n #this is to prevent the particle from escaping the box.\n # if x<0, push the atom back to x=0\n\n\n k = 5 # Steepness of the sigmoid curve\n max_barrier = \"1e2\" # Scaling factor for the potential maximum\n offset = 0.5 #the offset of the boundary energy barrier.\n # Defining the potentials using a sigmoid function\n left_pot = openmm.CustomExternalForce(f\"{max_barrier} * (1 / (1 + exp({k} * x - (-{offset}))))\")\n right_pot = openmm.CustomExternalForce(f\"{max_barrier} * (1 / (1 + exp(-{k} * (x - (2 * {pi} + {offset})))))\")\n bottom_pot = openmm.CustomExternalForce(f\"{max_barrier} * (1 / (1 + exp({k} * y - (-{offset}))))\")\n top_pot = openmm.CustomExternalForce(f\"{max_barrier} * (1 / (1 + exp(-{k} * (y - (2 * {pi} + {offset})))))\")\n\n left_pot.addParticle(particle_idx)\n right_pot.addParticle(particle_idx)\n bottom_pot.addParticle(particle_idx)\n top_pot.addParticle(particle_idx)\n\n system.addForce(left_pot)\n system.addForce(right_pot)\n system.addForce(bottom_pot)\n system.addForce(top_pot)\n\n \n #unpack gaussian parameters\n if mode == \"gaussian\":\n num_gaussians = int(len(gaussian_param)/5)\n A = gaussian_param[0::5] * amp #*7\n x0 = gaussian_param[1::5]\n y0 = gaussian_param[2::5]\n sigma_x = gaussian_param[3::5]\n sigma_y = gaussian_param[4::5]\n\n #now we add the force for all gaussians.\n energy = \"0\"\n force = openmm.CustomExternalForce(energy)\n for i in range(num_gaussians):\n if pbc:\n energy = f\"A{i}*exp(-periodicdistance(x,0,0, x0{i},0,0)^2/(2*sigma_x{i}^2) - periodicdistance(0,y,0, 0,y0{i},0)^2/(2*sigma_y{i}^2))\"\n force = openmm.CustomExternalForce(energy)\n else:\n energy = f\"A{i}*exp(-(x-x0{i})^2/(2*sigma_x{i}^2) - (y-y0{i})^2/(2*sigma_y{i}^2))\"\n force = openmm.CustomExternalForce(energy)\n\n #examine the current energy term within force.\n\n print(force.getEnergyFunction())\n\n force.addGlobalParameter(f\"A{i}\", A[i])\n force.addGlobalParameter(f\"x0{i}\", x0[i])\n force.addGlobalParameter(f\"y0{i}\", y0[i])\n force.addGlobalParameter(f\"sigma_x{i}\", sigma_x[i])\n force.addGlobalParameter(f\"sigma_y{i}\", sigma_y[i])\n force.addParticle(particle_idx)\n #we append the force to the system.\n system.addForce(force)\n if plot:\n #plot the fes.\n x = np.linspace(0, 2*np.pi, 100)\n y = np.linspace(0, 2*np.pi, 100)\n X, Y = np.meshgrid(x, y)\n Z = np.zeros_like(X)\n for i in range(num_gaussians):\n Z += A[i] * np.exp(-(X-x0[i])**2/(2*sigma_x[i]**2) - (Y-y0[i])**2/(2*sigma_y[i]**2))\n plt.figure()\n plt.imshow(Z, cmap=\"coolwarm\", extent=[0, 2*np.pi,0, 2*np.pi], vmin=0, vmax=amp *12/7, origin=\"lower\")\n plt.xlabel(\"x\")\n plt.xlim([-1, 2*np.pi+1])\n plt.ylim([-1, 2*np.pi+1])\n plt.ylabel(\"y\")\n plt.title(\"FES mode = gaussian, pbc=False\")\n plt.colorbar()\n plt.savefig(plot_path)\n plt.close()\n fes = Z\n\n if mode == \"multiwell\":\n \"\"\"\n here we create a multiple well potential.\n essentially we deduct multiple gaussians from a flat surface, \n with a positive gaussian acting as an additional barrier.\n note we have to implement this into openmm CustomExternalForce.\n the x,y is [0, 2pi]\n eq:\n U(x,y) = amp * (1 #flat surface\n - A_i*exp(-(x-x0i)^2/(2*sigma_xi^2) - (y-y0i)^2/(2*sigma_yi^2))) ... #deduct gaussians\n + A_j * exp(-(x-x0j)^2/(2*sigma_xj^2) - (y-y0j)^2/(2*sigma_yj^2)) #add a sharp positive gaussian\n \"\"\"\n if pbc:\n raise NotImplementedError(\"pbc not implemented for multi-well potential.\")\n else:\n num_wells = 9\n num_barrier = 1\n\n #here's the well params\n A_i = np.array([0.9, 0.3, 0.5, 1, 0.2, 0.4, 0.9, 0.9, 0.9]) * amp #this is in kcal/mol.\n x0_i = [1.12, 1, 3, 4.15, 4, 5.27, 5.5, 6, 1] # this is in nm.\n y0_i = [1.34, 2.25, 2.31, 3.62, 5, 4.14, 4.5, 1.52, 5]\n sigma_x_i = [0.5, 0.3, 0.4, 2, 0.9, 1, 0.3, 0.5, 0.5]\n sigma_y_i = [0.5, 0.3, 1, 0.8, 0.2, 0.3, 1, 0.6, 0.7]\n\n #here's the barrier params\n # for example we define a diagonal barrier at x = pi\n A_j = np.array([0.3]) * amp\n x0_j = [np.pi]\n y0_j = [np.pi]\n sigma_x_j = [3]\n sigma_y_j = [0.3]\n\n #now we add the force for all gaussians.\n #note all energy is in Kj/mol unit.\n energy = str(amp * 4.184) #flat surface\n force = openmm.CustomExternalForce(energy)\n force.addParticle(particle_idx)\n system.addForce(force)\n for i in range(num_wells):\n energy = f\"-A{i}*exp(-(x-x0{i})^2/(2*sigma_x{i}^2) - (y-y0{i})^2/(2*sigma_y{i}^2))\"\n force = openmm.CustomExternalForce(energy)\n\n #examine the current energy term within force.\n\n print(force.getEnergyFunction())\n\n force.addGlobalParameter(f\"A{i}\", A_i[i] * 4.184) #convert kcal to kj\n force.addGlobalParameter(f\"x0{i}\", x0_i[i])\n force.addGlobalParameter(f\"y0{i}\", y0_i[i])\n force.addGlobalParameter(f\"sigma_x{i}\", sigma_x_i[i])\n force.addGlobalParameter(f\"sigma_y{i}\", sigma_y_i[i])\n force.addParticle(particle_idx)\n #we append the force to the system.\n system.addForce(force)\n \n for i in range(num_barrier):\n energy = f\"A{i+num_wells}*exp(-(x-x0{i+num_wells})^2/(2*sigma_x{i+num_wells}^2) - (y-y0{i+num_wells})^2/(2*sigma_y{i+num_wells}^2))\"\n force = openmm.CustomExternalForce(energy)\n\n #examine the current energy term within force.\n\n print(force.getEnergyFunction())\n\n force.addGlobalParameter(f\"A{i+num_wells}\", A_j[i])\n force.addGlobalParameter(f\"x0{i+num_wells}\", x0_j[i])\n force.addGlobalParameter(f\"y0{i+num_wells}\", y0_j[i])\n force.addGlobalParameter(f\"sigma_x{i+num_wells}\", sigma_x_j[i])\n force.addGlobalParameter(f\"sigma_y{i+num_wells}\", sigma_y_j[i])\n force.addParticle(particle_idx)\n #we append the force to the system.\n system.addForce(force)\n \n if plot:\n #plot the fes.\n x = np.linspace(0, 2*np.pi, 100)\n y = np.linspace(0, 2*np.pi, 100)\n X, Y = np.meshgrid(x, y)\n Z = np.zeros_like(X)\n Z += amp * 4.184 #flat surface\n for i in range(num_wells):\n Z -= A_i[i] * np.exp(-(X-x0_i[i])**2/(2*sigma_x_i[i]**2) - (Y-y0_i[i])**2/(2*sigma_y_i[i]**2))\n for i in range(num_barrier):\n Z += A_j[i] * np.exp(-(X-x0_j[i])**2/(2*sigma_x_j[i]**2) - (Y-y0_j[i])**2/(2*sigma_y_j[i]**2))\n \n #add the x,y boundary energy barrier.\n total_energy_barrier = np.zeros_like(X)\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(k * (X - (-offset))))) #left\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(-k * (X - (2 * pi + offset))))) #right\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(k * (Y - (-offset)))))\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(-k * (Y - (2 * pi + offset)))))\n Z += total_energy_barrier\n\n plt.figure()\n plt.imshow(Z, cmap=\"coolwarm\", extent=[0, 2*np.pi,0, 2*np.pi], vmin=0, vmax=amp* 12/7 * 4.184, origin=\"lower\")\n plt.xlabel(\"x\")\n plt.xlim([-1, 1+2*np.pi])\n plt.ylim([-1, 1+2*np.pi])\n plt.ylabel(\"y\")\n plt.title(\"FES mode = multiwell, pbc=False\")\n plt.colorbar()\n plt.savefig(plot_path)\n plt.close()\n fes = Z\n \n if mode == \"funnel\":\n \"\"\"\n this is funnel like potential.\n we start wtih a flat fes, then add/deduct sphrical gaussians\n eq:\n U = 0.7* amp * cos(2 * p * (sqrt((x-pi)^2 + (y-pi)^2))) #cos function. periodicity determines the num of waves.\n - amp exp(-((x-pi)^2+(y-pi)^2))\n + 0.4*amp*((x-pi/8)^2 + (y-pi/8)^2)\n \"\"\"\n if pbc:\n raise NotImplementedError(\"pbc not implemented for funnel potential.\")\n else:\n plot_3d = False\n periodicity = 8\n energy = f\"0.7*{amp} * cos({periodicity} * (sqrt((x-{pi})^2 + (y-{pi})^2))) - 0.6* {amp} * exp(-((x-{pi})^2+(y-{pi})^2)) + 0.4*{amp}*((x-{pi}/8)^2 + (y-{pi}/8)^2)\"\n \n force = openmm.CustomExternalForce(energy)\n force.addParticle(particle_idx)\n system.addForce(force)\n if plot:\n if plot_3d:\n import plotly.graph_objs as go\n\n # Define the x, y, and z coordinates\n x = np.linspace(0, 2*np.pi, 100)\n y = np.linspace(0, 2*np.pi, 100)\n X, Y = np.meshgrid(x, y)\n Z = np.zeros_like(X)\n Z += 0.9* amp * np.cos(periodicity * (np.sqrt((X-np.pi)**2 + (Y-np.pi)**2))) #cos function. periodicity determines the num of waves.\n Z -= 0.6* amp * np.exp(-((X-np.pi)**2/0.5+(Y-np.pi)**2)/0.5)\n Z += 0.4*amp*(((X-np.pi)/8)**2 + ((Y-np.pi)/8)**2)\n\n #add the x,y boundary energy barrier.\n total_energy_barrier = np.zeros_like(X)\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(k * (X - 0)))) #left\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(-k * (X - 2 * pi)))) #right\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(k * (Y - 0))))\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(-k * (Y - 2 * pi))))\n Z += total_energy_barrier\n\n # Create the 3D contour plot\n fig = go.Figure(data=[go.Surface(z=Z, x=X, y=Y, cmin = 0, cmax = amp *12/7)])\n fig.update_traces(contours_z=dict(show=True, usecolormap=True,\n highlightcolor=\"limegreen\", project_z=True))\n fig.update_layout(title='FES mode = funnel, pbc=False', autosize=True,\n width=800, height=800,\n scene = {\n \"xaxis\": {\"nticks\": 5},\n \"yaxis\": {\"nticks\": 5},\n \"zaxis\": {\"nticks\": 5},\n \"camera_eye\": {\"x\": 1, \"y\": 1, \"z\": 0.4},\n \"aspectratio\": {\"x\": 1, \"y\": 1, \"z\": 0.4}\n }\n )\n #margin=dict(l=65, r=50, b=65, t=90))\n #save fig.\n fig.write_image(plot_path)\n fes = Z\n \n else:\n #plot the fes.\n x = np.linspace(0, 2*np.pi, 100)\n y = np.linspace(0, 2*np.pi, 100)\n X, Y = np.meshgrid(x, y)\n Z = np.zeros_like(X)\n Z += 0.4* amp * np.cos(periodicity * (np.sqrt((X-np.pi)**2 + (Y-np.pi)**2))) #cos function. periodicity determines the num of waves.\n Z += 0.7* amp * np.exp(-((X-np.pi)**2/0.5+(Y-np.pi)**2/0.5))\n Z += 0.2*amp*(((X-np.pi)/8)**2 + ((Y-np.pi)/8)**2)\n\n #add the x,y boundary energy barrier.\n total_energy_barrier = np.zeros_like(X)\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(k * (X - 0)))) #left\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(-k * (X - 2 * pi)))) #right\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(k * (Y - 0))))\n total_energy_barrier += float(max_barrier) * (1 / (1 + np.exp(-k * (Y - 2 * pi))))\n Z += total_energy_barrier\n\n plt.figure()\n plt.imshow(Z, cmap=\"coolwarm\", extent=[0, 2*np.pi,0, 2*np.pi], vmin=0, vmax=amp *12/7, origin=\"lower\")\n plt.xlabel(\"x\")\n plt.xlim([-1, 2*np.pi+1])\n plt.ylim([-1, 2*np.pi+1])\n plt.ylabel(\"y\")\n plt.title(\"FES mode = funnel, pbc=False\")\n plt.colorbar()\n plt.savefig(plot_path)\n plt.close()\n fes = Z\n\n return system, fes #return the system and the fes (2D array for plotting.)\n\ndef sum_of_gaussians(params, x, y, n_gaussians, N=100):\n total = np.zeros((N,N))\n \n A = params[0::5]\n x0 = params[1::5]\n y0 = params[2::5]\n sigma_x = params[3::5]\n sigma_y = params[4::5]\n\n for i in range(n_gaussians):\n total += gaussian_2D([A[i], x0[i], y0[i], sigma_x[i], sigma_y[i]], x, y)\n return total\n\ndef apply_bias(system, particle_idx, gaussian_param, pbc = False, name = \"BIAS\", num_gaussians = 20):\n \"\"\"\n this applies a bias using customexternal force class. similar as apply_fes.\n note this leaves a set of global parameters Ag, x0g, y0g, sigma_xg, sigma_yg.\n as these parameters can be called and updated later.\n note this is done while preparing the system before assembling the context.\n \"\"\"\n assert len(gaussian_param) == 5 * num_gaussians, \"gaussian_param should be in A, x0, y0, sigma_x, sigma_y format.\"\n\n #unpack gaussian parameters gaussian_params = np.concatenate((a, bx, by, cx, cy))\n num_gaussians = len(gaussian_param)//5\n A = gaussian_param[:num_gaussians]\n x0 = gaussian_param[num_gaussians:2*num_gaussians]\n y0 = gaussian_param[2*num_gaussians:3*num_gaussians]\n sigma_x = gaussian_param[3*num_gaussians:4*num_gaussians]\n sigma_y = gaussian_param[4*num_gaussians:5*num_gaussians]\n\n #now we add the force for all gaussians. with num_gaussians terms.\n energy = \"0\"\n force = openmm.CustomExternalForce(energy)\n for i in range(num_gaussians):\n if pbc:\n raise NotImplementedError(\"pbc not implemented for gaussian potential.\")\n energy = f\"Ag{i}*exp(-periodicdistance(x,0,0, x0g{i},0,0)^2/(2*sigma_xg{i}^2) - periodicdistance(0,y,0, 0,y0g{i},0)^2/(2*sigma_yg{i}^2))\"\n force = openmm.CustomExternalForce(energy)\n else:\n energy = f\"Ag{i}*exp(-(x-x0g{i})^2/(2*sigma_xg{i}^2) - (y-y0g{i})^2/(2*sigma_yg{i}^2))\" #in openmm unit, kj/mol, nm.\n force = openmm.CustomExternalForce(energy)\n\n #examine the current energy term within force.\n\n print(force.getEnergyFunction())\n\n force.addGlobalParameter(f\"Ag{i}\", A[i] * 4.184) #convert to kJ/mol\n force.addGlobalParameter(f\"x0g{i}\", x0[i]) #convert to nm\n force.addGlobalParameter(f\"y0g{i}\", y0[i])\n force.addGlobalParameter(f\"sigma_xg{i}\", sigma_x[i])\n force.addGlobalParameter(f\"sigma_yg{i}\", sigma_y[i])\n force.addParticle(particle_idx)\n #we append the force to the system.\n system.addForce(force)\n \n print(\"system added with bias.\")\n return system\n\ndef update_bias(simulation, gaussian_param, name = \"BIAS\", num_gaussians = 20):\n \"\"\"\n given the gaussian_param, update the bias\n note this requires the context object. or a simulation object.\n # the context object can be accessed by simulation.context.\n \"\"\"\n assert len(gaussian_param) == 5 * num_gaussians, \"gaussian_param should be in A, x0, y0, sigma_x, sigma_y format.\"\n\n #unpack gaussian parameters gaussian_params = np.concatenate((a, bx, by, cx, cy))\n num_gaussians = len(gaussian_param)//5\n A = gaussian_param[:num_gaussians]\n x0 = gaussian_param[num_gaussians:2*num_gaussians]\n y0 = gaussian_param[2*num_gaussians:3*num_gaussians]\n sigma_x = gaussian_param[3*num_gaussians:4*num_gaussians]\n sigma_y = gaussian_param[4*num_gaussians:5*num_gaussians]\n\n #now we update the GlobalParameter for all gaussians. with num_gaussians terms. and update them in the system.\n #note globalparameter does NOT need to be updated in the context.\n for i in range(num_gaussians):\n simulation.context.setParameter(f\"Ag{i}\", A[i] * 4.184) #convert to kJ/mol\n simulation.context.setParameter(f\"x0g{i}\", x0[i]) #convert to nm\n simulation.context.setParameter(f\"y0g{i}\", y0[i])\n simulation.context.setParameter(f\"sigma_xg{i}\", sigma_x[i])\n simulation.context.setParameter(f\"sigma_yg{i}\", sigma_y[i])\n \n print(\"system bias updated\")\n return simulation\n","repo_name":"DerienFe/RL_MFPT","sub_path":"2D_langevin_sim/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":30034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41294610209","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# number of points\nnum_samples = 500\n\ndef painting(xc, yc, xr, yr):\n fig, ax = plt.subplots()\n\n # make a simple unit circle\n theta = np.linspace(0, 2*np.pi, num_samples)\n a, b = 1*np.cos(theta), 1*np.sin(theta)\n plt.plot(a, b, linestyle='-', linewidth=2, color='black', label='Circle')\n\n # painting the points\n plt.scatter(xr, yr, color='blue')\n plt.scatter(xc, yc, color='red')\n plt.axis([-1.5, 1.5, -1.5, 1.5])\n ax.set(xlabel='$x_1$', ylabel='$x_2$', title='Train data')\n plt.show()\n\ndef generate_points(num_samples):\n # generate the num_samples points within a rectangle [-1,5,1.5, -1.5, 1.5]\n point = -1.5+np.random.rand(num_samples, 2)*3\n px, py = list(point[:,0]), list(point[:,1])\n\n # divide points into two classes: in the circle and not.\n xc, yc = [], [] # points in the unit circle\n xr, yr = [], [] # points not in the unit circle\n for i in range(len(px)):\n if math.sqrt(px[i]**2+py[i]**2) <= 1:\n xc.append(px[i])\n yc.append(py[i])\n else:\n xr.append(px[i])\n yr.append(py[i])\n\n return xc, yc, xr, yr\n\ndef main():\n xc, yc, xr, yr = generate_points(num_samples)\n painting(xc, yc, xr, yr)\n\nif __name__ == '__main__':\n main()\n","repo_name":"htma/nn-trainer","sub_path":"plot_points.py","file_name":"plot_points.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30755007287","text":"# all global variables\n\ndatabase_path = '' # path for database\nmat_prefs_path = '' # path for mat_prefs\nmat_prefs = '' # actual mat_prefs student/section prefs\nsec_sec_matrix_path = '' # path for section/section prefs\nmatrix_sections = '' # actual sec_sec_matrix\n\nparameters = ''\npara_path = ''\n\n# conflict and preference parameters\nsec_time_con = -10000000\nsec_sameclass_pref = 2000\nsec_sameprof_pref = 2000\n\nstu_time_con = -5000\nstu_class_con = -500\nstu_prof_con = -500\nstu_year_pref = 1000\nstu_div_pref = 50000\nstu_skill_pref = 1000\nstu_time_pref = 500\nstu_class_pref = 500\nstu_prof_pref = 500\n","repo_name":"Katiedaisey/scheduling","sub_path":"interface/globalvars.py","file_name":"globalvars.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"7483335856","text":"import aiohttp\nimport asyncio\nimport urllib.parse\nimport os\nimport logging\nfrom discord import File, TextChannel, User\nfrom discord.errors import NotFound\nimport config\nfrom utils.image import modify_avatar\nfrom utils import tag\n\n\nclass AvatarManager:\n def __init__(\n self,\n loop,\n db,\n http_session: aiohttp.ClientSession,\n fetch_channel\n ):\n self.loop = loop\n self.db = db\n self.http_session = http_session\n self.fetch_channel = fetch_channel\n\n\n async def fetch(self, user: User) -> str:\n res = self.db.execute(\n \"\"\"\n SELECT original_avatar_url,\n modified_avatar_url,\n modified_avatar_message_id\n FROM users WHERE id = ?\n \"\"\",\n (user.id,)\n )\n data = res.fetchone()\n\n avatar_channel = await self.fetch_channel(config.AVATAR_STORE_CHANNEL_ID)\n\n if data is not None:\n (\n original_avatar_url,\n modified_avatar_url,\n modified_avatar_message_id\n ) = data\n\n # User hasn't changed their avatar since last time they did\n # |imitate, so we can use the cached modified avatar.\n if self._avatar_url_id(user.display_avatar.url) == self._avatar_url_id(original_avatar_url):\n return modified_avatar_url\n\n # Else, user has changed their avatar.\n # Respect the user's privacy by deleting the message with their old\n # avatar.\n # Don't wait for this operation to complete before continuing.\n asyncio.create_task(\n self._delete_message(avatar_channel, modified_avatar_message_id)\n )\n\n # User has changed their avatar since last time they did |imitate or has\n # not done |imitate before, so we must create a modified version of\n # their avatar.\n # We employ the classic Discord As A CDN method to cache the modified\n # avatars by posting them to a Discord channel and storing the message\n # IDs for later.\n modified_avatar, file_format = await modify_avatar(user)\n message = await avatar_channel.send(\n file=File(modified_avatar, f\"{user.id}.{file_format}\")\n )\n\n # Update the avatar database with the new avatar URL.\n self.db.execute(\n \"\"\"\n UPDATE users\n SET original_avatar_url = ?,\n modified_avatar_url = ?,\n modified_avatar_message_id = ?\n WHERE id = ?\n \"\"\",\n (\n user.display_avatar.url,\n message.attachments[0].url,\n message.id,\n user.id\n )\n )\n return message.attachments[0].url\n\n\n async def _delete_message(\n self,\n channel: TextChannel,\n message_id: int\n ) -> None:\n try:\n message = await channel.fetch_message(message_id)\n except NotFound:\n logging.warn(\n f\"Tried to delete message {message_id} from the avatar store, \"\n \"but it doesn't exist.\"\n )\n else:\n await message.delete()\n\n\n def _avatar_url_id(self, url: str) -> str:\n path = urllib.parse.urlparse(url).path\n return os.path.splitext(path)[0]\n","repo_name":"garlic-os/parrot","sub_path":"database/avatar_manager.py","file_name":"avatar_manager.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"6767440779","text":"import cv2\nimport numpy as np\nimport os\nfrom matplotlib import pyplot as plot\n\n\n########################################\n# Ler imagem original\nimg_path = \"Resources/Semaforo_verm_5.jpg\"\nimg = cv2.imread(img_path)\n\nredPixels=0\nyellowPixels=0\ngreenPixels=0\nnumero_redlights=0\nnumero_greenlights=0\nnumero_yellowlights=0\n\n\n# Aplicar Blur\nimg_blur = cv2.medianBlur(img,5)\n\n# Converter para HSV\nimg_hsv = cv2.cvtColor(img_blur, cv2.COLOR_BGR2HSV)\n\n# Criar Array com o numpy para consultar dados recebidos doa HSV\nimg_HSV_values = np.array(img_hsv)\n\n# # Mostrar dados array valores HSV\n# print(img_HSV_values)\n\n\n\n\n# Mostrar imagem original\ncv2.imshow('Original', img)\n\ncv2.waitKey()\n\n\n\n########################################\n# Red Color Range de HSV\nlower_range_red = np.array([161, 155, 84])\nupper_range_red = np.array([179, 255, 255])\n\n# Criar mascara à volta da zona RED\nred_mask = cv2.inRange(img_hsv, lower_range_red, upper_range_red)\n\n# Função para apenas a zona vermelha\nred_only = cv2.bitwise_and(img_hsv, img, mask=red_mask)\n\n# Mostrar mascaras aplicadas à zona red\ncv2.imshow(\"mascara red\", red_mask)\n#cv2.imshow(\"mascara red\", red_only)\nredPixels = cv2.countNonZero(red_mask)\n\nprint(\"Pixels Vermelhos \" + str(redPixels))\ncv2.waitKey()\n\n\n\n########################################\n# Green Color Range de HSV\nlower_range_green = np.array([48, 208, 0])\nupper_range_green = np.array([83, 255, 255])\n\n# Criar máscara à volta da zona Green\ngreen_mask = cv2.inRange(img_hsv, lower_range_green, upper_range_green)\n\n# Mostrar apenas a zona Green\ngreen_only = cv2.bitwise_and(img_hsv, img, mask=green_mask)\n\n# Mostrar mascaras aplicadas à zona red\ncv2.imshow(\"mascara Green\", green_mask)\n#cv2.imshow(\"mascara Green\", green_only)\ngreenPixels = cv2.countNonZero(green_mask)\n\nprint(\"Pixels Verdes \" + str(greenPixels))\ncv2.waitKey()\n\n\n\n########################################\n# Yellow Color Range de HSV\nlower_range_yellow = np.array([12, 173, 155])\nupper_range_yellow = np.array([42, 212, 255])\n\n# Criar máscara à volta da zona yellow\nyellow_mask = cv2.inRange(img_hsv, lower_range_yellow, upper_range_yellow)\n\n# Mostrar apenas a zona Green\nyellow_only = cv2.bitwise_and(img_hsv, img, mask=yellow_mask)\n\n# Mostrar mascaras aplicadas à zona red\ncv2.imshow(\"mascara Yellow\", yellow_mask)\n#cv2.imshow(\"mascara Yellow\", yellow_only)\nyellowPixels = cv2.countNonZero(yellow_mask)\n\nprint(\"Pixels Amarelos \" + str(yellowPixels))\ncv2.waitKey()\n\n\nif redPixels > 0:\n numero_redlights = numero_redlights + 1\n print (\"Está Amarelo em \"+str(numero_redlights)+\" Imagens\")\n\nif greenPixels > 0:\n numero_redlights = numero_redlights + 1\n print (\"Está Verde em \"+str(numero_greenlights)+\" Imagens\")\n\nif yellowPixels > 0:\n print (\"Está Amarelo em \"+str(numero_yellowlights)+\" Imagens\")\n\ncv2.waitKey()\n\n\n\n","repo_name":"blamelas/python-color-detection","sub_path":"ColorDetection.py","file_name":"ColorDetection.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12598112543","text":"\"\"\"\nDashboard view and supporting methods\n\"\"\"\n\n\nimport datetime\nimport logging\nfrom collections import defaultdict\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import redirect\nfrom django.urls import reverse\nfrom django.utils.translation import gettext as _\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom edx_django_utils import monitoring as monitoring_utils\nfrom edx_django_utils.plugins import get_plugins_view_context\nfrom edx_toggles.toggles import WaffleFlag\nfrom ipware.ip import get_client_ip\nfrom opaque_keys.edx.keys import CourseKey\nfrom openedx_filters.learning.filters import DashboardRenderStarted\nfrom pytz import UTC\n\nfrom lms.djangoapps.bulk_email.api import is_bulk_email_feature_enabled\nfrom lms.djangoapps.bulk_email.models import Optout\nfrom common.djangoapps.course_modes.models import CourseMode\nfrom common.djangoapps.edxmako.shortcuts import render_to_response, render_to_string\nfrom common.djangoapps.entitlements.models import CourseEntitlement\nfrom lms.djangoapps.commerce.utils import EcommerceService\nfrom lms.djangoapps.courseware.access import has_access\nfrom lms.djangoapps.learner_home.waffle import should_redirect_to_learner_home_mfe\nfrom lms.djangoapps.experiments.utils import get_dashboard_course_info, get_experiment_user_metadata_context\nfrom lms.djangoapps.verify_student.services import IDVerificationService\nfrom openedx.core.djangoapps.catalog.utils import (\n get_programs,\n get_pseudo_session_for_entitlement,\n get_visible_sessions_for_entitlement\n)\nfrom openedx.core.djangoapps.credit.email_utils import get_credit_provider_attribute_values, make_providers_strings\nfrom openedx.core.djangoapps.plugins.constants import ProjectType\nfrom openedx.core.djangoapps.programs.models import ProgramsApiConfig\nfrom openedx.core.djangoapps.programs.utils import ProgramDataExtender, ProgramProgressMeter\nfrom openedx.core.djangoapps.site_configuration import helpers as configuration_helpers\nfrom openedx.core.djangoapps.user_api.accounts.utils import is_secondary_email_feature_enabled\nfrom openedx.core.djangoapps.util.maintenance_banner import add_maintenance_banner\nfrom openedx.core.djangolib.markup import HTML, Text\nfrom openedx.features.content_type_gating.models import ContentTypeGatingConfig\nfrom openedx.features.course_duration_limits.access import get_user_course_duration, get_user_course_expiration_date\nfrom openedx.features.enterprise_support.api import (\n get_dashboard_consent_notification,\n get_enterprise_learner_portal_context,\n)\nfrom openedx.features.enterprise_support.utils import is_enterprise_learner\nfrom openedx.core.djangoapps.geoinfo.api import country_code_from_ip\nfrom common.djangoapps.student.api import COURSE_DASHBOARD_PLUGIN_VIEW_NAME\nfrom common.djangoapps.student.helpers import cert_info, check_verify_status_by_course, get_resume_urls_for_enrollments\nfrom common.djangoapps.student.models import (\n AccountRecovery,\n CourseEnrollment,\n CourseEnrollmentAttribute,\n DashboardConfiguration,\n PendingSecondaryEmailChange,\n UserProfile\n)\nfrom common.djangoapps.util.milestones_helpers import get_pre_requisite_courses_not_completed\nfrom xmodule.modulestore.django import modulestore # lint-amnesty, pylint: disable=wrong-import-order\n\nlog = logging.getLogger(\"edx.student\")\n\nEXPERIMENTS_NAMESPACE = 'student.experiments'\n\n\ndef get_org_black_and_whitelist_for_site():\n \"\"\"\n Returns the org blacklist and whitelist for the current site.\n\n Returns:\n (org_whitelist, org_blacklist): A tuple of lists of orgs that serve as\n either a blacklist or a whitelist of orgs for the current site. The\n whitelist takes precedence, and the blacklist is used if the\n whitelist is None.\n \"\"\"\n # Default blacklist is empty.\n org_blacklist = None\n # Whitelist the orgs configured for the current site. Each site outside\n # of edx.org has a list of orgs associated with its configuration.\n org_whitelist = configuration_helpers.get_current_site_orgs()\n\n if not org_whitelist:\n # If there is no whitelist, the blacklist will include all orgs that\n # have been configured for any other sites. This applies to edx.org,\n # where it is easier to blacklist all other orgs.\n org_blacklist = configuration_helpers.get_all_orgs()\n\n return org_whitelist, org_blacklist\n\n\ndef _get_recently_enrolled_courses(course_enrollments):\n \"\"\"\n Given a list of enrollments, filter out all but recent enrollments.\n\n Args:\n course_enrollments (list[CourseEnrollment]): A list of course enrollments.\n\n Returns:\n list[CourseEnrollment]: A list of recent course enrollments.\n \"\"\"\n seconds = DashboardConfiguration.current().recent_enrollment_time_delta\n time_delta = (datetime.datetime.now(UTC) - datetime.timedelta(seconds=seconds))\n return [\n enrollment for enrollment in course_enrollments\n # If the enrollment has no created date, we are explicitly excluding the course\n # from the list of recent enrollments.\n if enrollment.is_active and enrollment.created > time_delta\n ]\n\n\ndef _create_recent_enrollment_message(course_enrollments, course_modes): # lint-amnesty, pylint: disable=unused-argument\n \"\"\"\n Builds a recent course enrollment message.\n\n Constructs a new message template based on any recent course enrollments\n for the student.\n\n Args:\n course_enrollments (list[CourseEnrollment]): a list of course enrollments.\n course_modes (dict): Mapping of course ID's to course mode dictionaries.\n\n Returns:\n A string representing the HTML message output from the message template.\n None if there are no recently enrolled courses.\n\n \"\"\"\n recently_enrolled_courses = _get_recently_enrolled_courses(course_enrollments)\n\n if recently_enrolled_courses:\n enrollments_count = len(recently_enrolled_courses)\n course_name_separator = ', '\n # If length of enrolled course 2, join names with 'and'\n if enrollments_count == 2:\n course_name_separator = _(' and ')\n\n course_names = course_name_separator.join(\n [enrollment.course_overview.display_name for enrollment in recently_enrolled_courses]\n )\n\n platform_name = configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME)\n\n return render_to_string(\n 'enrollment/course_enrollment_message.html',\n {\n 'course_names': course_names,\n 'enrollments_count': enrollments_count,\n 'platform_name': platform_name,\n 'course_id': recently_enrolled_courses[0].course_overview.id if enrollments_count == 1 else None\n }\n )\n\n\ndef get_course_enrollments(user, org_whitelist, org_blacklist, course_limit=None):\n \"\"\"\n Given a user, return a filtered set of their course enrollments.\n\n Arguments:\n user (User): the user in question.\n org_whitelist (list[str]): If not None, ONLY courses of these orgs will be returned.\n org_blacklist (list[str]): Courses of these orgs will be excluded.\n course_limit: Number courses to load in dashboard if set to None then all the courses would be load.\n\n Returns:\n generator[CourseEnrollment]: a sequence of enrollments to be displayed\n on the user's dashboard.\n \"\"\"\n for enrollment in CourseEnrollment.enrollments_for_user_with_overviews_preload(user, course_limit):\n\n # If the course is missing or broken, log an error and skip it.\n course_overview = enrollment.course_overview\n if not course_overview:\n log.error(\n \"User %s enrolled in broken or non-existent course %s\",\n user.username,\n enrollment.course_id\n )\n continue\n\n # Filter out anything that is not in the whitelist.\n if org_whitelist and course_overview.location.org not in org_whitelist:\n continue\n\n # Conversely, filter out any enrollments in the blacklist.\n elif org_blacklist and course_overview.location.org in org_blacklist:\n continue\n\n # Else, include the enrollment.\n else:\n yield enrollment\n\n\ndef get_filtered_course_entitlements(user, org_whitelist, org_blacklist):\n \"\"\"\n Given a user, return a filtered set of their course entitlements.\n\n Arguments:\n user (User): the user in question.\n org_whitelist (list[str]): If not None, ONLY entitlements of these orgs will be returned.\n org_blacklist (list[str]): CourseEntitlements of these orgs will be excluded.\n\n Returns:\n generator[CourseEntitlement]: a sequence of entitlements to be displayed\n on the user's dashboard.\n \"\"\"\n course_entitlement_available_sessions = {}\n unfulfilled_entitlement_pseudo_sessions = {}\n course_entitlements = list(CourseEntitlement.get_active_entitlements_for_user(user))\n filtered_entitlements = []\n pseudo_session = None\n course_run_key = None\n\n for course_entitlement in course_entitlements:\n course_entitlement.update_expired_at()\n available_runs = get_visible_sessions_for_entitlement(course_entitlement)\n\n if not course_entitlement.enrollment_course_run:\n # Unfulfilled entitlements need a mock session for metadata\n pseudo_session = get_pseudo_session_for_entitlement(course_entitlement)\n unfulfilled_entitlement_pseudo_sessions[str(course_entitlement.uuid)] = pseudo_session\n\n # Check the org of the Course and filter out entitlements that are not available.\n if course_entitlement.enrollment_course_run:\n course_run_key = course_entitlement.enrollment_course_run.course_id\n elif available_runs:\n course_run_key = CourseKey.from_string(available_runs[0]['key'])\n elif pseudo_session:\n course_run_key = CourseKey.from_string(pseudo_session['key'])\n\n if course_run_key:\n # If there is no course_run_key at this point we will be unable to determine if it should be shown.\n # Therefore it should be excluded by default.\n if org_whitelist and course_run_key.org not in org_whitelist:\n continue\n elif org_blacklist and course_run_key.org in org_blacklist:\n continue\n\n course_entitlement_available_sessions[str(course_entitlement.uuid)] = available_runs\n filtered_entitlements.append(course_entitlement)\n\n return filtered_entitlements, course_entitlement_available_sessions, unfulfilled_entitlement_pseudo_sessions\n\n\ndef complete_course_mode_info(course_id, enrollment, modes=None):\n \"\"\"\n We would like to compute some more information from the given course modes\n and the user's current enrollment\n\n Returns the given information:\n - whether to show the course upsell information\n - numbers of days until they can't upsell anymore\n \"\"\"\n if modes is None:\n modes = CourseMode.modes_for_course_dict(course_id)\n\n mode_info = {'show_upsell': False, 'days_for_upsell': None}\n # we want to know if the user is already enrolled as verified or credit and\n # if verified is an option.\n if CourseMode.VERIFIED in modes and enrollment.mode in CourseMode.UPSELL_TO_VERIFIED_MODES:\n mode_info['show_upsell'] = True\n mode_info['verified_sku'] = modes['verified'].sku\n mode_info['verified_bulk_sku'] = modes['verified'].bulk_sku\n # if there is an expiration date, find out how long from now it is\n if modes['verified'].expiration_datetime:\n today = datetime.datetime.now(UTC).date()\n mode_info['days_for_upsell'] = (modes['verified'].expiration_datetime.date() - today).days\n mode_info['expiration_datetime'] = modes['verified'].expiration_datetime.date()\n\n return mode_info\n\n\ndef get_verification_error_reasons_for_display(verification_error_codes):\n \"\"\"\n Returns the display text for the given verification error codes.\n \"\"\"\n verification_errors = []\n verification_error_map = {\n 'photos_mismatched': _('Photos are mismatched'),\n 'id_image_missing_name': _('Name missing from ID photo'),\n 'id_image_missing': _('ID photo not provided'),\n 'id_invalid': _('ID is invalid'),\n 'user_image_not_clear': _('Learner photo is blurry'),\n 'name_mismatch': _('Name on ID does not match name on account'),\n 'user_image_missing': _('Learner photo not provided'),\n 'id_image_not_clear': _('ID photo is blurry'),\n }\n\n for error in verification_error_codes:\n error_text = verification_error_map.get(error)\n if error_text:\n verification_errors.append(error_text)\n\n return verification_errors\n\n\ndef reverification_info(statuses):\n \"\"\"\n Returns reverification-related information for *all* of user's enrollments whose\n reverification status is in statuses.\n\n Args:\n statuses (list): a list of reverification statuses we want information for\n example: [\"must_reverify\", \"denied\"]\n\n Returns:\n dictionary of lists: dictionary with one key per status, e.g.\n dict[\"must_reverify\"] = []\n dict[\"must_reverify\"] = [some information]\n \"\"\"\n reverifications = defaultdict(list)\n\n # Sort the data by the reverification_end_date\n for status in statuses:\n if reverifications[status]:\n reverifications[status].sort(key=lambda x: x.date)\n return reverifications\n\n\ndef credit_statuses(user, course_enrollments):\n \"\"\"\n Retrieve the status for credit courses.\n\n A credit course is a course for which a user can purchased\n college credit. The current flow is:\n\n 1. User becomes eligible for credit (submits verifications, passes the course, etc.)\n 2. User purchases credit from a particular credit provider.\n 3. User requests credit from the provider, usually creating an account on the provider's site.\n 4. The credit provider notifies us whether the user's request for credit has been accepted or rejected.\n\n The dashboard is responsible for communicating the user's state in this flow.\n\n Arguments:\n user (User): The currently logged-in user.\n course_enrollments (list[CourseEnrollment]): List of enrollments for the\n user.\n\n Returns: dict\n\n The returned dictionary has keys that are `CourseKey`s and values that\n are dictionaries with:\n\n * eligible (bool): True if the user is eligible for credit in this course.\n * deadline (datetime): The deadline for purchasing and requesting credit for this course.\n * purchased (bool): Whether the user has purchased credit for this course.\n * provider_name (string): The display name of the credit provider.\n * provider_status_url (string): A URL the user can visit to check on their credit request status.\n * provider_id (string): A unique alphanumeric (plus hyphens) string identifying the provider.\n * request_status (string): Either \"pending\", \"approved\", or \"rejected\"\n * error (bool): If true, an unexpected error occurred when retrieving the credit status,\n so the user should contact the support team.\n\n Example:\n >>> credit_statuses(user, course_enrollments)\n {\n CourseKey.from_string(\"edX/DemoX/Demo_Course\"): {\n \"course_key\": \"edX/DemoX/Demo_Course\",\n \"eligible\": True,\n \"deadline\": 2015-11-23 00:00:00 UTC,\n \"purchased\": True,\n \"provider_name\": \"Hogwarts\",\n \"provider_status_url\": \"http://example.com/status\",\n \"provider_id\": \"HSWW\",\n \"request_status\": \"pending\",\n \"error\": False\n }\n }\n\n \"\"\"\n from openedx.core.djangoapps.credit import api as credit_api\n\n # Feature flag off\n if not settings.FEATURES.get(\"ENABLE_CREDIT_ELIGIBILITY\"):\n return {}\n\n request_status_by_course = {\n request[\"course_key\"]: request[\"status\"]\n for request in credit_api.get_credit_requests_for_user(user.username)\n }\n\n credit_enrollments = {\n enrollment.course_id: enrollment\n for enrollment in course_enrollments\n if enrollment.mode == \"credit\"\n }\n\n # When a user purchases credit in a course, the user's enrollment\n # mode is set to \"credit\" and an enrollment attribute is set\n # with the ID of the credit provider. We retrieve *all* such attributes\n # here to minimize the number of database queries.\n purchased_credit_providers = {\n attribute.enrollment.course_id: attribute.value\n for attribute in CourseEnrollmentAttribute.objects.filter(\n namespace=\"credit\",\n name=\"provider_id\",\n enrollment__in=list(credit_enrollments.values())\n ).select_related(\"enrollment\")\n }\n\n provider_info_by_id = {\n provider[\"id\"]: provider\n for provider in credit_api.get_credit_providers()\n }\n\n statuses = {}\n for eligibility in credit_api.get_eligibilities_for_user(user.username):\n course_key = CourseKey.from_string(str(eligibility[\"course_key\"]))\n providers_names = get_credit_provider_attribute_values(course_key, 'display_name')\n status = {\n \"course_key\": str(course_key),\n \"eligible\": True,\n \"deadline\": eligibility[\"deadline\"],\n \"purchased\": course_key in credit_enrollments,\n \"provider_name\": make_providers_strings(providers_names),\n \"provider_status_url\": None,\n \"provider_id\": None,\n \"request_status\": request_status_by_course.get(course_key),\n \"error\": False,\n }\n\n # If the user has purchased credit, then include information about the credit\n # provider from which the user purchased credit.\n # We retrieve the provider's ID from the an \"enrollment attribute\" set on the user's\n # enrollment when the user's order for credit is fulfilled by the E-Commerce service.\n if status[\"purchased\"]:\n provider_id = purchased_credit_providers.get(course_key)\n if provider_id is None:\n status[\"error\"] = True\n log.error(\n \"Could not find credit provider associated with credit enrollment \"\n \"for user %s in course %s. The user will not be able to see their \"\n \"credit request status on the student dashboard. This attribute should \"\n \"have been set when the user purchased credit in the course.\",\n user.id, course_key\n )\n else:\n provider_info = provider_info_by_id.get(provider_id, {})\n status[\"provider_name\"] = provider_info.get(\"display_name\")\n status[\"provider_status_url\"] = provider_info.get(\"status_url\")\n status[\"provider_id\"] = provider_id\n\n if not status[\"provider_name\"] and not status[\"provider_status_url\"]:\n status[\"error\"] = True\n log.error(\n \"Could not find credit provider info for [%s] in [%s]. The user will not \"\n \"be able to see their credit request status on the student dashboard.\",\n provider_id, provider_info_by_id\n )\n\n statuses[course_key] = status\n\n return statuses\n\n\ndef show_load_all_courses_link(user, course_limit, course_enrollments):\n \"\"\"\n By default dashboard will show limited courses based on the course limit\n set in configuration.\n\n A link would be provided provided at the bottom to load all the courses if there are any courses.\n \"\"\"\n\n if course_limit is None:\n return False\n\n total_enrollments = CourseEnrollment.enrollments_for_user(user).count()\n return len(course_enrollments) < total_enrollments\n\n\ndef get_dashboard_course_limit():\n \"\"\"\n get course limit from configuration\n \"\"\"\n course_limit = getattr(settings, 'DASHBOARD_COURSE_LIMIT', None)\n return course_limit\n\n\ndef check_for_unacknowledged_notices(context):\n \"\"\"\n Checks the notices apps plugin context to see if there are any unacknowledged notices the user needs to take action\n on. If so, build a redirect url to the first unack'd notice.\n \"\"\"\n notice_url = None\n\n notices = context.get(\"plugins\", {}).get(\"notices\", {}).get(\"unacknowledged_notices\")\n if notices:\n # We will only show one notice to the user one at a time. Build a redirect URL to the first notice in the\n # list of unacknowledged notices.\n notice_url = f\"{settings.LMS_ROOT_URL}{notices[0]}?next={settings.LMS_ROOT_URL}/dashboard/\"\n\n return notice_url\n\n\n@login_required\n@ensure_csrf_cookie\n@add_maintenance_banner\ndef student_dashboard(request): # lint-amnesty, pylint: disable=too-many-statements\n \"\"\"\n Provides the LMS dashboard view\n\n TODO: This is lms specific and does not belong in common code.\n Note:\n To load the all courses set course_limit=None as parameter in GET. If its not None then default course\n limit will be used that is set in configuration\n Arguments:\n request: The request object.\n\n Returns:\n The dashboard response.\n\n \"\"\"\n user = request.user\n if not UserProfile.objects.filter(user=user).exists():\n return redirect(reverse('account_settings'))\n\n if should_redirect_to_learner_home_mfe(user):\n return redirect(settings.LEARNER_HOME_MICROFRONTEND_URL)\n\n platform_name = configuration_helpers.get_value(\"platform_name\", settings.PLATFORM_NAME)\n\n enable_verified_certificates = configuration_helpers.get_value(\n 'ENABLE_VERIFIED_CERTIFICATES',\n settings.FEATURES.get('ENABLE_VERIFIED_CERTIFICATES')\n )\n display_course_modes_on_dashboard = configuration_helpers.get_value(\n 'DISPLAY_COURSE_MODES_ON_DASHBOARD',\n settings.FEATURES.get('DISPLAY_COURSE_MODES_ON_DASHBOARD', True)\n )\n activation_email_support_link = configuration_helpers.get_value(\n 'ACTIVATION_EMAIL_SUPPORT_LINK', settings.ACTIVATION_EMAIL_SUPPORT_LINK\n ) or settings.SUPPORT_SITE_LINK\n hide_dashboard_courses_until_activated = configuration_helpers.get_value(\n 'HIDE_DASHBOARD_COURSES_UNTIL_ACTIVATED',\n settings.FEATURES.get('HIDE_DASHBOARD_COURSES_UNTIL_ACTIVATED', False)\n )\n empty_dashboard_message = configuration_helpers.get_value(\n 'EMPTY_DASHBOARD_MESSAGE', None\n )\n disable_unenrollment = configuration_helpers.get_value(\n 'DISABLE_UNENROLLMENT',\n settings.FEATURES.get('DISABLE_UNENROLLMENT')\n )\n\n disable_course_limit = request and 'course_limit' in request.GET\n course_limit = get_dashboard_course_limit() if not disable_course_limit else None\n\n # Get the org whitelist or the org blacklist for the current site\n site_org_whitelist, site_org_blacklist = get_org_black_and_whitelist_for_site()\n course_enrollments = list(get_course_enrollments(user, site_org_whitelist, site_org_blacklist, course_limit))\n\n # Get the entitlements for the user and a mapping to all available sessions for that entitlement\n # If an entitlement has no available sessions, pass through a mock course overview object\n (course_entitlements,\n course_entitlement_available_sessions,\n unfulfilled_entitlement_pseudo_sessions) = get_filtered_course_entitlements(\n user,\n site_org_whitelist,\n site_org_blacklist\n )\n\n # Record how many courses there are so that we can get a better\n # understanding of usage patterns on prod.\n monitoring_utils.accumulate('num_courses', len(course_enrollments))\n\n # Sort the enrollment pairs by the enrollment date\n course_enrollments.sort(key=lambda x: x.created, reverse=True)\n\n # Retrieve the course modes for each course\n enrolled_course_ids = [enrollment.course_id for enrollment in course_enrollments]\n __, unexpired_course_modes = CourseMode.all_and_unexpired_modes_for_courses(enrolled_course_ids)\n course_modes_by_course = {\n course_id: {\n mode.slug: mode\n for mode in modes\n }\n for course_id, modes in unexpired_course_modes.items()\n }\n\n # Check to see if the student has recently enrolled in a course.\n # If so, display a notification message confirming the enrollment.\n enrollment_message = _create_recent_enrollment_message(\n course_enrollments, course_modes_by_course\n )\n course_optouts = Optout.objects.filter(user=user).values_list('course_id', flat=True)\n\n # Display activation message\n activate_account_message = ''\n if not user.is_active:\n activate_account_message = Text(_(\n \"Check your {email_start}{email}{email_end} inbox for an account activation link from {platform_name}. \"\n \"If you need help, contact {link_start}{platform_name} Support{link_end}.\"\n )).format(\n platform_name=platform_name,\n email_start=HTML(\"\"),\n email_end=HTML(\"\"),\n email=user.email,\n link_start=HTML(\"\").format(\n activation_email_support_link=activation_email_support_link,\n ),\n link_end=HTML(\"\"),\n )\n\n enterprise_message = get_dashboard_consent_notification(request, user, course_enrollments)\n\n recovery_email_message = recovery_email_activation_message = None\n if is_secondary_email_feature_enabled():\n try:\n pending_email = PendingSecondaryEmailChange.objects.get(user=user) # lint-amnesty, pylint: disable=unused-variable\n except PendingSecondaryEmailChange.DoesNotExist:\n try:\n account_recovery_obj = AccountRecovery.objects.get(user=user) # lint-amnesty, pylint: disable=unused-variable\n except AccountRecovery.DoesNotExist:\n recovery_email_message = Text(\n _(\n \"Add a recovery email to retain access when single-sign on is not available. \"\n \"Go to {link_start}your Account Settings{link_end}.\")\n ).format(\n link_start=HTML(\"\").format(\n account_setting_page=reverse('account_settings'),\n ),\n link_end=HTML(\"\")\n )\n else:\n recovery_email_activation_message = Text(\n _(\n \"Recovery email is not activated yet. \"\n \"Kindly visit your email and follow the instructions to activate it.\"\n )\n )\n\n # Disable lookup of Enterprise consent_required_course due to ENT-727\n # Will re-enable after fixing WL-1315\n consent_required_courses = set()\n\n # Account activation message\n account_activation_messages = [\n message for message in messages.get_messages(request) if 'account-activation' in message.tags\n ]\n\n # Global staff can see what courses encountered an error on their dashboard\n staff_access = False\n errored_courses = {}\n if has_access(user, 'staff', 'global'):\n # Show any courses that encountered an error on load\n staff_access = True\n errored_courses = modulestore().get_errored_courses()\n\n show_courseware_links_for = {\n enrollment.course_id: has_access(request.user, 'load', enrollment.course_overview)\n for enrollment in course_enrollments\n }\n\n # Find programs associated with course runs being displayed. This information\n # is passed in the template context to allow rendering of program-related\n # information on the dashboard.\n meter = ProgramProgressMeter(request.site, user, enrollments=course_enrollments)\n ecommerce_service = EcommerceService()\n inverted_programs = meter.invert_programs()\n\n urls, programs_data = {}, {}\n bundles_on_dashboard_flag = WaffleFlag(f'{EXPERIMENTS_NAMESPACE}.bundles_on_dashboard', __name__) # lint-amnesty, pylint: disable=toggle-missing-annotation\n\n # TODO: Delete this code and the relevant HTML code after testing LEARNER-3072 is complete\n if bundles_on_dashboard_flag.is_enabled() and inverted_programs and list(inverted_programs.items()):\n if len(course_enrollments) < 4:\n for program in inverted_programs.values():\n try:\n program_uuid = program[0]['uuid']\n program_data = get_programs(uuid=program_uuid)\n program_data = ProgramDataExtender(program_data, request.user).extend()\n skus = program_data.get('skus')\n checkout_page_url = ecommerce_service.get_checkout_page_url(*skus)\n program_data['completeProgramURL'] = checkout_page_url + '&bundle=' + program_data.get('uuid')\n programs_data[program_uuid] = program_data\n except: # pylint: disable=bare-except\n pass\n\n # Construct a dictionary of course mode information\n # used to render the course list. We re-use the course modes dict\n # we loaded earlier to avoid hitting the database.\n course_mode_info = {\n enrollment.course_id: complete_course_mode_info(\n enrollment.course_id, enrollment,\n modes=course_modes_by_course[enrollment.course_id]\n )\n for enrollment in course_enrollments\n }\n\n # Determine the per-course verification status\n # This is a dictionary in which the keys are course locators\n # and the values are one of:\n #\n # VERIFY_STATUS_NEED_TO_VERIFY\n # VERIFY_STATUS_SUBMITTED\n # VERIFY_STATUS_APPROVED\n # VERIFY_STATUS_MISSED_DEADLINE\n #\n # Each of which correspond to a particular message to display\n # next to the course on the dashboard.\n #\n # If a course is not included in this dictionary,\n # there is no verification messaging to display.\n verify_status_by_course = check_verify_status_by_course(user, course_enrollments)\n cert_statuses = {\n enrollment.course_id: cert_info(request.user, enrollment)\n for enrollment in course_enrollments\n }\n\n # only show email settings for Mongo course and when bulk email is turned on\n show_email_settings_for = frozenset(\n enrollment.course_id for enrollment in course_enrollments if (\n is_bulk_email_feature_enabled(enrollment.course_id)\n )\n )\n\n # Verification Attempts\n # Used to generate the \"you must reverify for course x\" banner\n verification_status = IDVerificationService.user_status(user)\n verification_errors = get_verification_error_reasons_for_display(verification_status['error'])\n\n # Gets data for midcourse reverifications, if any are necessary or have failed\n statuses = [\"approved\", \"denied\", \"pending\", \"must_reverify\"]\n reverifications = reverification_info(statuses)\n\n enrolled_courses_either_paid = frozenset(\n enrollment.course_id for enrollment in course_enrollments\n if enrollment.is_paid_course()\n )\n\n # Checks if a course enrollment redeemed using a voucher is refundable\n enrolled_courses_voucher_refundable = frozenset(\n enrollment.course_id for enrollment in course_enrollments\n if enrollment.is_order_voucher_refundable()\n )\n\n # If there are *any* denied reverifications that have not been toggled off,\n # we'll display the banner\n denied_banner = any(item.display for item in reverifications[\"denied\"])\n\n # get list of courses having pre-requisites yet to be completed\n courses_having_prerequisites = frozenset(\n enrollment.course_id for enrollment in course_enrollments\n if enrollment.course_overview.pre_requisite_courses\n )\n courses_requirements_not_met = get_pre_requisite_courses_not_completed(user, courses_having_prerequisites)\n\n if 'notlive' in request.GET:\n redirect_message = _(\"The course you are looking for does not start until {date}.\").format(\n date=request.GET['notlive']\n )\n elif 'course_closed' in request.GET:\n redirect_message = _(\"The course you are looking for is closed for enrollment as of {date}.\").format(\n date=request.GET['course_closed']\n )\n elif 'access_response_error' in request.GET:\n # This can be populated in a generalized way with fields from access response errors\n redirect_message = request.GET['access_response_error']\n else:\n redirect_message = ''\n\n # Filter out any course enrollment course cards that are associated with fulfilled entitlements\n for entitlement in [e for e in course_entitlements if e.enrollment_course_run is not None]:\n course_enrollments = [\n enr for enr in course_enrollments if entitlement.enrollment_course_run.course_id != enr.course_id\n ]\n\n show_account_activation_popup = request.COOKIES.get(settings.SHOW_ACTIVATE_CTA_POPUP_COOKIE_NAME, None)\n\n enrollments_fbe_is_on = []\n for enrollment in course_enrollments:\n course_key = CourseKey.from_string(str(enrollment.course_id))\n gated_content = ContentTypeGatingConfig.enabled_for_enrollment(\n user=user,\n course_key=course_key\n )\n duration = get_user_course_duration(user, enrollment.course)\n deadline = duration and get_user_course_expiration_date(user, enrollment.course)\n fbe_is_on = deadline and gated_content\n if fbe_is_on:\n enrollments_fbe_is_on.append(course_key)\n\n ip_address = get_client_ip(request)[0]\n country_code = country_code_from_ip(ip_address).upper()\n\n context = {\n 'urls': urls,\n 'programs_data': programs_data,\n 'enterprise_message': enterprise_message,\n 'consent_required_courses': consent_required_courses,\n 'enrollment_message': enrollment_message,\n 'redirect_message': Text(redirect_message),\n 'account_activation_messages': account_activation_messages,\n 'activate_account_message': activate_account_message,\n 'course_enrollments': course_enrollments,\n 'course_entitlements': course_entitlements,\n 'course_entitlement_available_sessions': course_entitlement_available_sessions,\n 'unfulfilled_entitlement_pseudo_sessions': unfulfilled_entitlement_pseudo_sessions,\n 'course_optouts': course_optouts,\n 'staff_access': staff_access,\n 'errored_courses': errored_courses,\n 'show_courseware_links_for': show_courseware_links_for,\n 'all_course_modes': course_mode_info,\n 'cert_statuses': cert_statuses,\n 'credit_statuses': credit_statuses(user, course_enrollments),\n 'show_email_settings_for': show_email_settings_for,\n 'reverifications': reverifications,\n 'verification_display': verification_status['should_display'],\n 'verification_status': verification_status['status'],\n 'verification_expiry': verification_status['verification_expiry'],\n 'verification_status_by_course': verify_status_by_course,\n 'verification_errors': verification_errors,\n 'denied_banner': denied_banner,\n 'billing_email': settings.PAYMENT_SUPPORT_EMAIL,\n 'show_account_activation_popup': show_account_activation_popup,\n 'user': user,\n 'logout_url': reverse('logout'),\n 'platform_name': platform_name,\n 'enrolled_courses_either_paid': enrolled_courses_either_paid,\n 'enrolled_courses_voucher_refundable': enrolled_courses_voucher_refundable,\n 'provider_states': [],\n 'courses_requirements_not_met': courses_requirements_not_met,\n 'nav_hidden': True,\n 'inverted_programs': inverted_programs,\n 'show_program_listing': ProgramsApiConfig.is_enabled(),\n 'show_dashboard_tabs': True,\n 'disable_courseware_js': True,\n 'display_course_modes_on_dashboard': enable_verified_certificates and display_course_modes_on_dashboard,\n 'display_sidebar_account_activation_message': not(user.is_active or hide_dashboard_courses_until_activated),\n 'display_dashboard_courses': (user.is_active or not hide_dashboard_courses_until_activated),\n 'empty_dashboard_message': empty_dashboard_message,\n 'enrollments_fbe_is_on': enrollments_fbe_is_on,\n 'recovery_email_message': recovery_email_message,\n 'recovery_email_activation_message': recovery_email_activation_message,\n 'show_load_all_courses_link': show_load_all_courses_link(user, course_limit, course_enrollments),\n # TODO START: clean up as part of REVEM-199 (START)\n 'course_info': get_dashboard_course_info(user, course_enrollments),\n # TODO START: clean up as part of REVEM-199 (END)\n 'disable_unenrollment': disable_unenrollment,\n 'country_code': country_code,\n # TODO: clean when experiment(Merchandise 2U LOBs - Dashboard) would be stop. [VAN-1097]\n 'is_enterprise_user': is_enterprise_learner(user),\n }\n\n # Include enterprise learner portal metadata and messaging\n enterprise_learner_portal_context = get_enterprise_learner_portal_context(request)\n context.update(enterprise_learner_portal_context)\n\n context_from_plugins = get_plugins_view_context(\n ProjectType.LMS,\n COURSE_DASHBOARD_PLUGIN_VIEW_NAME,\n context\n )\n context.update(context_from_plugins)\n\n notice_url = check_for_unacknowledged_notices(context)\n if notice_url:\n return redirect(notice_url)\n\n course = None\n context.update(\n get_experiment_user_metadata_context(\n course,\n user,\n )\n )\n if ecommerce_service.is_enabled(request.user):\n context.update({\n 'use_ecommerce_payment_flow': True,\n 'ecommerce_payment_page': ecommerce_service.payment_page_url(),\n })\n\n # Gather urls for course card resume buttons.\n resume_button_urls = ['' for entitlement in course_entitlements]\n for url in get_resume_urls_for_enrollments(user, course_enrollments).values():\n resume_button_urls.append(url)\n # There must be enough urls for dashboard.html. Template creates course\n # cards for \"enrollments + entitlements\".\n context.update({\n 'resume_button_urls': resume_button_urls\n })\n\n dashboard_template = 'dashboard.html'\n try:\n # .. filter_implemented_name: DashboardRenderStarted\n # .. filter_type: org.openedx.learning.dashboard.render.started.v1\n context, dashboard_template = DashboardRenderStarted.run_filter(\n context=context, template_name=dashboard_template,\n )\n except DashboardRenderStarted.RenderInvalidDashboard as exc:\n response = render_to_response(exc.dashboard_template, exc.template_context)\n except DashboardRenderStarted.RedirectToPage as exc:\n response = HttpResponseRedirect(exc.redirect_to or reverse('account_settings'))\n except DashboardRenderStarted.RenderCustomResponse as exc:\n response = exc.response\n else:\n response = render_to_response(dashboard_template, context)\n\n if show_account_activation_popup:\n response.delete_cookie(\n settings.SHOW_ACTIVATE_CTA_POPUP_COOKIE_NAME,\n domain=settings.SESSION_COOKIE_DOMAIN,\n path='/',\n )\n\n return response\n","repo_name":"openedx/edx-platform","sub_path":"common/djangoapps/student/views/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":39601,"program_lang":"python","lang":"en","doc_type":"code","stars":6774,"dataset":"github-code","pt":"3"}
+{"seq_id":"24045700912","text":"# Author: \n# Assignment #2 - TextAnalyzer\n# Date due: 2021-03-11\n# I pledge that I have completed this assignment without\n# collaborating with anyone else, in conformance with the\n# NYU School of Engineering Policies and Procedures on\n# Academic Misconduct.\n\n####### DO NOT EDIT FUNCTIONS BELOW ########\n\n#identifying functions\ndef character_is_digit(char):\n \"\"\"Indicates whether the value referenced by char parameter\n is a digit character\n\n :param char: character to check\n :return: True when char is a digit character, False otherwise\n\n >>> test_char = 'b'\n >>> character_is_digit(test_char)\n False\n >>> test_char = '2'\n >>> character_is_digit(test_char)\n True\n \"\"\"\n #true if character is a digit\n return char.isdigit()\n\n\ndef character_is_letter(char):\n \"\"\"Indicates whether the value referenced by char parameter\n is a letter\n\n :param char: character to check\n :return: True when char is a letter, False otherwise\n\n >>> test_char = 'b'\n >>> character_is_letter(test_char)\n True\n >>> test_char = '2'\n >>> character_is_letter(test_char)\n False\n \"\"\"\n #true if character is a letter\n return char.isalpha()\n\n\n####### DO NOT EDIT FUNCTIONS ABOVE ########\n\ndef character_is_whitespace(char):\n \"\"\"Indicates whether the value referenced by char parameter\n is a whitespace character (' ', '\\\\n', '\\\\t')\n\n :param char: character to check\n :return: True when char is space character, False otherwise\n\n >>> test_char = ' '\n >>> character_is_whitespace(test_char)\n True\n >>> test_char = '#'\n >>> character_is_whitespace(test_char)\n False\n >>> test_char = '\\\\n'\n >>> character_is_whitespace(test_char)\n True\n >>> test_char = '\\\\t'\n >>> character_is_whitespace(test_char)\n True\n \"\"\"\n #true if character is a whitespace character\n return char.isspace()\n\n\ndef character_ends_sentence(char):\n \"\"\"Indicates whether the value referenced by char parameter\n is a period, question mark, or exclamation point\n\n :param char: character to check\n :return: True when char ends sentence, False otherwise\n\n >>> test_char = 'k'\n >>> character_ends_sentence(test_char)\n False\n >>> test_char = '.'\n >>> character_ends_sentence(test_char)\n True\n >>> test_char = '?'\n >>> character_ends_sentence(test_char)\n True\n >>> test_char = '!'\n >>> character_ends_sentence(test_char)\n True\n \"\"\"\n #true if the character ends a sentence\n if char.endswith(\".\"):\n return True\n elif char.endswith(\"!\"):\n return True\n elif char.endswith(\"?\"):\n return True\n else:\n return False\n\n\ndef print_results(num_chars, num_spaces, num_digits, num_letters, num_sentences):\n \"\"\"Prints the number of total characters, spaces, digits, letters,\n and sentences identified in the text being analyzed.\n\n :param num_chars: number of total characters in text\n :param num_spaces: number of spaces in text\n :param num_digits: number of digits in text\n :param num_letters: number of letters in text\n :param num_sentences: number of sentences in text\n :return: None\n\n >>> num_chars = 234\n >>> num_spaces = 14\n >>> num_digits = 16\n >>> num_letters = 201\n >>> num_sentences = 21\n >>> print_results(num_chars, num_spaces, num_digits, num_letters, num_sentences)\n \n Count of characters: 234\n Count of spaces: 14\n Count of digits: 16\n Count of letters: 201\n Count of sentences: 21\n \n \"\"\"\n #output the results\n print()\n print('Count of characters:', num_chars)\n print('Count of spaces:', num_spaces)\n print('Count of digits:', num_digits)\n print('Count of letters:', num_letters)\n print('Count of sentences:', num_sentences)\n print()\n\n\ndef analyze_text():\n \"\"\"Calls the functions to compute the number of total characters,\n spaces, digits, letters, and sentences in user-supplied text and to\n output the final counts when text input by user.\n\n :return: True when text provided, False when no text provided\n \"\"\"\n #takes in a string\n txt = input('Please enter text to analyze (press ENTER/return without text to exit): ')\n\n #total variables\n num_letters = 0\n num_digits = 0\n num_spaces = 0\n num_chars = 0\n num_sentences = 0\n\n #loops through every single character in the inputed string\n #for each character it checks it against all of our previously written identifying functions\n #when any of the identifying functions come back as true it adds one to the total variables defined above\n #at the end it increases the iteration variable 'i' in order to move on and check the next character untill the entire string has been worked through\n for i in range(len(txt)):\n if character_is_letter(txt[i]):\n num_letters += 1\n elif character_is_digit(txt[i]):\n num_digits += 1\n elif character_ends_sentence(txt[i]):\n num_sentences += 1\n elif character_is_whitespace(txt[i]):\n num_spaces += 1\n num_chars += 1\n i += 1\n\n #if the inputed string is empty return false\n #else print the results and return true\n if len(txt) == 0:\n return False\n else:\n print_results(num_chars, num_spaces, num_digits, num_letters, num_sentences)\n return True\n\n\ndef run_text_analyzer():\n \"\"\"Runs the Text Analyzer as a repeated sequence of\n prompting the user for input text and outputting the\n character counts computed from the input\n\n :return: None\n \"\"\"\n #displays welcome message\n print('Welcome to the Text Analyzer!')\n print()\n\n #while there continue to be inputs we will analyze the text\n #else the input is empty and we say goodbye and end the program\n while analyze_text():\n continue\n else:\n print()\n print('Goodbye.')\n\n\ndef main():\n \"\"\"Runs a program for analyzing character counts from\n input text\n \"\"\"\n\n # calls run_text_analyzer()\n run_text_analyzer()\n\n\n####### DO NOT REMOVE IF STATEMENT BELOW ########\n\nif __name__ == '__main__':\n # Remove comments for next 4 lines to run doctests\n # print(\"Running doctests...\")\n # import doctest\n # doctest.testmod(verbose=True)\n\n # print(\"\\nRunning program...\\n\")\n\n main()\n","repo_name":"tywenrick3/Calculator_and_TextAnalyzer","sub_path":"text_analyzer.py","file_name":"text_analyzer.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"40429425582","text":"import typing\nimport numpy\nimport matplotlib.pyplot\nimport imgproc.stats.hist._hist\n\nclass Hist:\n \"\"\"[summary]\n \"\"\"\n def __init__(self,\n hist: numpy.ndarray,\n histr: numpy.ndarray,\n histg: numpy.ndarray,\n histb: numpy.ndarray):\n \"\"\"[summary]\n\n Args:\n hist (numpy.ndarray): [description]\n histr (numpy.ndarray): [description]\n histg (numpy.ndarray): [description]\n histb (numpy.ndarray): [description]\n \"\"\"\n self.hist = hist\n self.histr = histr\n self.histg = histg\n self.histb = histb\n def __str__(self) -> str:\n \"\"\"[summary]\n\n Returns:\n str: [description]\n \"\"\"\n return f\"Hist:\\n{self.hist}\\n\" +\\\n f\"Histr:\\n{self.histr}\\n\" +\\\n f\"Histg:\\n{self.histg}\\n\" +\\\n f\"Histb:\\n{self.histb}\\n\"\n def __repr__(self) -> str:\n \"\"\"[summary]\n\n Returns:\n str: [description]\n \"\"\"\n return f\"Hist:\\n{self.hist}\\n\" +\\\n f\"Histr:\\n{self.histr}\\n\" +\\\n f\"Histg:\\n{self.histg}\\n\" +\\\n f\"Histb:\\n{self.histb}\\n\"\n def plot(self, fn: typing.Union[None, str]=None):\n \"\"\"[summary]\n\n Args:\n fn (typing.Union[None, str], optional): [description].\n Defaults to None.\n \"\"\"\n matplotlib.pyplot.clf()\n matplotlib.pyplot.bar(numpy.arange(256), self.hist)\n if (fn):\n matplotlib.pyplot.savefig(fn)\n\n\ndef hist(fn: str) -> Hist:\n \"\"\"[summary]\n\n Args:\n fn (str): [description]\n\n Returns:\n Hist: [description]\n \"\"\"\n hist = numpy.empty(256, dtype=numpy.uintc)\n histr = numpy.empty(256, dtype=numpy.uintc)\n histg = numpy.empty(256, dtype=numpy.uintc)\n histb = numpy.empty(256, dtype=numpy.uintc)\n imgproc.stats.hist._hist.hist_base(fn, hist, histr, histg, histb)\n return Hist(hist, histr, histg, histb)\n","repo_name":"leafyao8621/imgproc","sub_path":"package/imgproc/stats/hist/_hist_wrapper.py","file_name":"_hist_wrapper.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12616907569","text":"\"\"\"\n\nServidor da aplicação Distriduino, \ndesenvolvida na disciplina de Computação Distribuída, 2023.2.\nBrenda Silva Machado\n\n\"\"\"\n\n\nimport socket\nimport pika\n\nHOST = \"127.0.0.1\" # localhost\nPORT = 65432 # Porta para o listen\n\nserver = socket.socket(socket.AF_INET,\n socket.SOCK_STREAM)\nserver.bind((HOST, PORT))\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters(HOST))\nchannel = connection.channel()\nchannel.queue_declare(queue='fila')\n\nserver.listen(1)\n\nprint(\"Calculadora iniciou\")\nprint(\"Esperando pela operacao..\")\n\nclientConnection, clientAddress = server.accept()\nprint(\"Cliente conectado :\", clientAddress)\nmsg = ''\n\ndef callback(ch, method, properties, body):\n while True:\n if body.decode() == \"fim da operação\":\n break\n print(\"Mensagem terminou de ser exibida no mensageiro\")\n channel.stop_consuming()\n return 0\n\n# Recebimento da autenticação\ntoken = clientConnection.recv(1024)\nif token.decode() == \"123456\":\n clientConnection.send(\"1\".encode())\n while True:\n data = clientConnection.recv(1024)\n msg = data.decode()\n if msg == 'q':\n print(\"Conexao encerrada pelo cliente\")\n channel.basic_publish(exchange='',\n routing_key='fila',\n body='fim')\n break\n \n else:\n \n result = 0\n operation_list = msg.split()\n oprnd1 = operation_list[0]\n operation = operation_list[1]\n oprnd2 = operation_list[2]\n \n # Conversao de string para int\n num1 = (int(oprnd1, 2))\n num2 = (int(oprnd2, 2))\n\n # Operacoes básicas\n if operation == \"+\":\n result = bin(num1 + num2)\n elif operation == \"-\":\n result = bin(num1 - num2)\n \n # Conversao para string\n # Envio para o cliente\n output = str(result[2:])\n channel.basic_publish(exchange='',\n routing_key='fila',\n body=output)\n clientConnection.send(output.encode())\n print(\"Resultado enviado para o mensageiro\")\n\n # Limitação: esperar a confirmação que o mensageiro exibiu a mensagem antes de uma nova operação\n # Recebimento da confirmação\n channel.basic_consume(queue='fila', on_message_callback=callback, auto_ack=True)\n\n channel.start_consuming()\n\n clientConnection.send(\"Mensageiro finalizou, pode iniciar nova operação\".encode())\n\n clientConnection.close()\n\n # Destruir a fila\n channel.queue_delete(queue='fila')\nelse:\n clientConnection.send(\"0\".encode())\n clientConnection.close()\n exit()\n","repo_name":"Brenda-Machado/Distriduino","sub_path":"src/servidor.py","file_name":"servidor.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10749361623","text":"import time\n\nara = (u'في حال واجهتك مشكلة راسلني على الخاص')\nara2 = (u'تم الانتهاء من ضغط السيارات بنجاح')\n\nprint(f\"By ! TankOsama#1792\\n {ara}\")\n\n\nprint('Whit 5 Sec...')\ntime.sleep(2.5)\n\n\nprint('Program is run')\n\nimport tkinter as tk\nfrom tkinter import filedialog\n\nroot = tk.Tk()\nroot.withdraw()\nOld_filepath = filedialog.askdirectory()\n\nNew_filePath = filedialog.askdirectory()\n\nimport os\n\narr = os.listdir(rf\"{Old_filepath}\")\nd = 0\n#print(arr)\n#for i in arr:\n # d = d +1\n # b = str(d)\n # os.rename(rf\"C:\\Users\\iosam\\Desktop\\كل ما يتعلف بفايف ام\\marrigecars\\TankFBI{i}\",rf'C:\\Users\\iosam\\Desktop\\كل ما يتعلف بفايف ام\\marrigecars\\TankFBI\\TankCars{i}'+b)\nfd = (fr\"{New_filePath}\\__resource.lua\")\nold = []\nfor j in arr:\n d = d +1\n b = str(d)\n arry=(os.listdir(rf\"{Old_filepath}\\{j}\"))\n for i in arry:\n if i == 'stream' or i == '__resource.lua' or i == 'Stream':\n continue\n os.rename(rf\"{Old_filepath}\\{j}\\{i}\",rf'{New_filePath}\\{b}{i}')\n arryd =(os.listdir(rf\"{Old_filepath}\\{j}\\stream\"))\n for z in arryd:\n try:\n\n os.rename(rf\"{Old_filepath}\\{j}\\stream\\{z}\",rf'{New_filePath}\\stream\\{z}')\n print(f'suuccfule{z}')\n except:\n print(f\"Error{j,z}\")\n\n\n\nf = open(rf\"{New_filePath}\\__resource.lua\", \"a\")\nttd = 0\nf.write(\"\"\"resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'\\n\\n\\n\\n\"\"\")\nf.write(\"files {\")\nfor r in arr:\n ttd = ttd +1\n tt = str(ttd)\n f.write(f\"\"\"\\n '{tt}vehicles.meta',\\n '{tt}carvariations.meta',\\n '{tt}carcols.meta',\\n '{tt}handling.meta',\"\"\")\n # f.write(f\"\"\"'{tt}vehicles.meta',\\n'{tt}carvariations.meta',\\n'{tt}carcols.meta',\\n'{tt}handling.meta' \\n\\n\\n\\n data_file 'HANDLING_FILE' '{tt}handling.meta' \\n\n#data_file 'VEHICLE_METADATA_FILE''{tt}vehicles.meta'\\ndata_file 'CARCOLS_FILE' '{tt}carcols.meta' \\ndata_file 'VEHICLE_VARIATION_FILE' '{tt}carvariations.meta' \"\"\")\nf.write(\"\\n}\")\ntred = 0\nfor q in arr:\n tred = tred +1\n tre = str(tred)\n f.write(f\"\"\"\\n\\n\\ndata_file 'HANDLING_FILE' '{tre}handling.meta' \\ndata_file 'VEHICLE_METADATA_FILE''{tre}vehicles.meta'\\ndata_file 'CARCOLS_FILE' '{tre}carcols.meta' \\ndata_file 'VEHICLE_VARIATION_FILE' '{tre}carvariations.meta'\\n\\n\\n\"\"\")\nf.close()\n\n\nprint(f'----------{ara2}----------')\n\n","repo_name":"TankOsama/FiveM-Merge-cars","sub_path":"MargeCars.py","file_name":"MargeCars.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5879396378","text":"import subprocess\nimport psutil\n\ntry:\n from pynvml import *\n nvmlPY = \"OK\"\nexcept ImportError:\n nvmlPY = None\n\ndef getCpuInfo():\n \"\"\"Returns CPU/s information.\n\n Notes:\n - All values set to zero when called the first time\n - Values stat updating on the second call\n - This can be changed by specifying an interval. In that case the\n calls will be blocking\n \"\"\"\n return {\n 'usage': psutil.cpu_percent(interval=None, percpu=True),\n 'global_usage': psutil.cpu_percent(interval=None),\n 'cpu_times': vars(psutil.cpu_times()),\n }\n\ndef getCudaInfo():\n \"\"\"Returns CUDA device/s information\n \"\"\"\n def get_attribute(att):\n return subprocess.check_output(\n ['nvidia-smi', '--query-gpu={}'.format(att),\n '--format=csv,noheader,nounits'])\n\n mem_used = get_attribute(\"memory.used\")\n mem_total = get_attribute(\"memory.total\")\n mem_per = int(mem_used) * 100 / int(mem_total)\n\n if nvmlPY is not None:\n nvmlInit()\n try:\n handle = nvmlDeviceGetHandleByIndex(0)\n (enc_util, ssize) = nvmlDeviceGetEncoderUtilization(handle)\n except NVMLError as err:\n enc_util = err\n nvmlShutdown()\n else:\n enc_util = \"-1\"\n\n return {\n 'memory.used': mem_used,\n 'memory.free': get_attribute(\"memory.free\"),\n 'memory.total': mem_total,\n 'memory.percent': mem_per,\n 'utilization.perf_state': get_attribute(\"pstate\"),\n 'utilization.gpu': get_attribute(\"utilization.gpu\"),\n 'utilization.enc': enc_util,\n 'utilization.memory': get_attribute(\"utilization.memory\"),\n 'name': get_attribute(\"gpu_name\"),\n }\n\n\ndef getMemoryInfo():\n \"\"\"Returns information of the memory modules in the system\n \"\"\"\n vmem = psutil.virtual_memory()\n swap = psutil.swap_memory()\n vmem = vars(vmem)\n swap = vars(swap)\n\n return {\n 'virtual': vmem,\n 'swap': swap,\n }\n","repo_name":"stitchEm/stitchEm","sub_path":"lib/bindings/samples/server/utils/performance.py","file_name":"performance.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":246,"dataset":"github-code","pt":"3"}
+{"seq_id":"10659962324","text":"#!/usr/bin/env python\r\n__author__ = \"@KaosNeverDied forgettable.eth\"\r\n__copyright__ = \"whatever\"\r\n__credits__ = [\"@kaosNeverdied\"]\r\n__license__ = \"GPL\"\r\n__version__ = \"1.0.1\"\r\n__maintainer__ = \"@KaosNeverdied\"\r\n__status__ = \"Prototype\"\r\n\r\nimport logging\r\nimport time\r\n\r\nfrom seasnake import *\r\n\r\nlogger = logging.getLogger()\r\nlogger.setLevel(logging.DEBUG) #NOTE: minimum logging level - set this to whatever suits your needs\r\n\r\n#config logging\r\nstream_handler = logging.StreamHandler() \r\nformatter = logging.Formatter('%(asctime)s %(levelname)s :: %(message)s')\r\nstream_handler.setFormatter(formatter)\r\nstream_handler.setLevel(logging.INFO) \r\nfile_handler = logging.FileHandler('info.log')\r\nfile_handler.setFormatter(formatter)\r\nfile_handler.setLevel(logging.DEBUG) \r\nlogger.addHandler(stream_handler)\r\nlogger.addHandler(file_handler)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n #NOTE: Basic example of use\r\n asset_contract_address = \"0x06012c8cf97bead5deae237070f9587f8e7a266d\"\r\n token_id = \"1\"\r\n opensea = OpenSea()\r\n asset = opensea.get_asset_single(asset_contract_address=asset_contract_address, token_id=token_id)\r\n print(f'id: {asset.id}')\r\n print(f'token_id: {asset.token_id}')\r\n print(f'background_color: {asset.background_color}')\r\n print(f'img_url: {asset.image_url}')\r\n","repo_name":"kaosneverdied/seasnake","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"42194038771","text":"\ndef suma(num_1:int,num_2:int):\n return num_1+num_2\ndef resta(num_1:int,num_2:int):\n return num_1-num_2\ndef multiplicacion(num_1:int,num_2:int):\n return num_1*num_2\ndef division(num_1:int,num_2:int):\n return num_1/num_2\n\n\ninicio=True\n\nwhile inicio:\n print(\"1. Sumar\")\n print(\"2. Restar\")\n print(\"3. Multiplicar\")\n print(\"4. Dividir\")\n print(\"5. Salir\")\n\n opcion = int(input(\"Seleccione la opción deseada: \"))\n\n if opcion ==1:\n print(\"Ha seleccionado la opcion Sumar\")\n num_1=int(input(\"Seleccione primer numero a sumar: \"))\n num_2=int(input(\"Seleccione segundo numero a sumar: \"))\n print(\"El resultado de la suma es: \", suma(num_1,num_2))\n\n if opcion ==2:\n print(\"Ha seleccionado la opcion Resta\")\n print(\"Ha seleccionado la opcion Resta\")\n num_1=int(input(\"Seleccione primer numero a restar: \"))\n num_2=int(input(\"Seleccione segundo numero a restar: \"))\n print(\"El resultado de la resta es: \", resta(num_1,num_2))\n\n\n\n if opcion ==3:\n print(\"Ha seleccionado la opcion Multiplica\")\n num_1=int(input(\"Seleccione primer numero a multiplicar: \"))\n num_2=int(input(\"Seleccione segundo numero a multiplicar: \"))\n print(\"El resultado de la resta es: \", multiplicacion(num_1,num_2))\n\n\n if opcion ==4:\n print(\"Ha seleccionado la opcion Dividir\")\n num_1=int(input(\"Seleccione primer numero a dividir: \"))\n num_2=int(input(\"Seleccione segundo numero a dividir: \"))\n print(\"El resultado de la resta es: \", division(num_1,num_2))\n\n\n if opcion ==5:\n print(\"Ha seleccionado Salir\")\ninicio=False\n\n\n\n","repo_name":"ClauMurua/funciones","sub_path":"Calculadora.py","file_name":"Calculadora.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70682620883","text":"import win32gui\nimport win32con\nimport time\n #不知道这个咋玩的\ndef exe_is_active():\n while True:\n time.sleep(0.2)\n try:\n # 关闭文件或目录,使用模糊查询\n hld = FindWinHwnd(u\" D:\\Android\")\n if str(hld) != \"0\":\n time.sleep(0.2)\n win32gui.PostMessage(hld, win32con.WM_CLOSE, 0, 0)\n time.sleep(0.1)\n print(\"已关闭txt\")\n\n # 关闭文件或目录,精准查询\n hld = win32gui.FindWindow(None, u\"公用\")\n if str(hld) != \"0\":\n time.sleep(0.2)\n win32gui.PostMessage(hld, win32con.WM_CLOSE, 0, 0)\n time.sleep(0.1)\n print(\"已关闭目录\")\n except:\n print(\"速度过快报错\")\n\n# 模糊查询\ndef FindWinHwnd(title, top=True):\n titles = []\n def foo(hwnd, mouse):\n if top:\n if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):\n if title in win32gui.GetWindowText(hwnd):\n titles.append(hwnd)\n return titles[0]\n else:\n if title in win32gui.GetWindowText(hwnd):\n titles.append(hwnd)\n win32gui.EnumWindows(foo, 0)\n if titles:\n return titles[0]\n else:\n return 0\n\n\nif __name__ == '__main__':\n exe_is_active()","repo_name":"jihaikang/2021-","sub_path":"5_29/wuai_3关闭打开某个程序或目录.py","file_name":"wuai_3关闭打开某个程序或目录.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29039809493","text":"from datetime import datetime\n\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes.generic import GenericForeignKey\n\nfrom ganeti_webmgr.utils import get_rapi\nfrom ganeti_webmgr.utils.client import GanetiApiError\nfrom ganeti_webmgr.clusters.models import CachedClusterObject\n\n\nclass JobManager(models.Manager):\n \"\"\"\n Custom manager for Ganeti Jobs model\n \"\"\"\n def create(self, **kwargs):\n \"\"\" helper method for creating a job with disabled cache \"\"\"\n job = Job(ignore_cache=True, **kwargs)\n job.save(force_insert=True)\n return job\n\n\nclass Job(CachedClusterObject):\n \"\"\"\n model representing a job being run on a ganeti Cluster. This includes\n operations such as creating or delting a virtual machine.\n\n Jobs are a special type of CachedClusterObject. Job's run once then become\n immutable. The lazy cache is modified to become permanent once a complete\n status (success/error) has been detected. The cache can be disabled by\n settning ignore_cache=True.\n \"\"\"\n\n job_id = models.IntegerField()\n content_type = models.ForeignKey(ContentType, related_name=\"+\")\n object_id = models.IntegerField()\n obj = GenericForeignKey('content_type', 'object_id')\n cluster = models.ForeignKey('clusters.Cluster', related_name='jobs',\n editable=False)\n cluster_hash = models.CharField(max_length=40, editable=False)\n\n finished = models.DateTimeField(null=True, blank=True)\n status = models.CharField(max_length=10)\n op = models.CharField(max_length=50)\n\n objects = JobManager()\n\n def save(self, *args, **kwargs):\n \"\"\"\n sets the cluster_hash for newly saved instances\n \"\"\"\n if self.id is None or self.cluster_hash == '':\n self.cluster_hash = self.cluster.hash\n\n super(Job, self).save(*args, **kwargs)\n\n @models.permalink\n def get_absolute_url(self):\n job = '%s/job/(?P\\d+)' % self.cluster\n\n return 'ganeti_web.views.jobs.detail', (), {'job': job}\n\n @property\n def rapi(self):\n return get_rapi(self.cluster_hash, self.cluster_id)\n\n def _refresh(self):\n return self.rapi.GetJobStatus(self.job_id)\n\n def load_info(self):\n \"\"\"\n Load info for class. This will load from ganeti if ignore_cache==True,\n otherwise this will always load from the cache.\n \"\"\"\n if self.id and (self.ignore_cache or self.info is None):\n try:\n self.refresh()\n except GanetiApiError as e:\n # if the Job has been archived then we don't know whether it\n # was successful or not. Mark it as unknown.\n if e.code == 404:\n self.status = 'unknown'\n self.save()\n else:\n # its possible the cluster or crednetials are bad. fail\n # silently\n pass\n\n def refresh(self):\n info = self._refresh()\n valid = self.valid_job(info)\n if valid:\n self.info = info\n self.save()\n # else:\n # Job.objects.get(job_id=self.info['id']).delete()\n\n @classmethod\n def valid_job(cls, info):\n status = info.get('status')\n ops = info.get('ops')\n return not (ops is None and status is None)\n\n @classmethod\n def parse_op(cls, info):\n ops = info['ops']\n op = None\n if ops:\n # Return the most recent operation\n op = ops[-1]['OP_ID']\n return op\n\n @classmethod\n def parse_persistent_info(cls, info):\n \"\"\"\n Parse status and turn off cache bypass flag if job has finished\n \"\"\"\n if not cls.valid_job(info):\n return {}\n op = cls.parse_op(info)\n data = {'status': info['status'], 'op': op}\n if data['status'] in ('error', 'success'):\n data['ignore_cache'] = False\n if info['end_ts']:\n data['finished'] = cls.parse_end_timestamp(info)\n return data\n\n @staticmethod\n def parse_end_timestamp(info):\n sec, micro = info['end_ts']\n return datetime.fromtimestamp(sec + (micro / 1000000.0))\n\n def parse_transient_info(self):\n pass\n\n @property\n def current_operation(self):\n \"\"\"\n Jobs may consist of multiple commands/operations. This helper\n method will return the operation that is currently running or errored\n out, or the last operation if all operations have completed\n\n @returns raw name of the current operation\n \"\"\"\n info = self.info\n index = 0\n for i in range(len(info['opstatus'])):\n if info['opstatus'][i] != 'success':\n index = i\n break\n return info['ops'][index]['OP_ID']\n\n @property\n def operation(self):\n \"\"\"\n Returns the last operation, which is generally the primary operation.\n \"\"\"\n return self.parse_op(self.info)\n\n def __repr__(self):\n return \"\" % (self.id, self.job_id,\n self.status)\n\n __unicode__ = __repr__\n","repo_name":"osuosl/ganeti_webmgr","sub_path":"ganeti_webmgr/jobs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5260,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"3"}
+{"seq_id":"35399260014","text":"#This file reads all our feature sets and assembles \n#a feature set.\n\n#Imports\nimport rasterio\nimport gdal\nimport numpy as np\nimport os\nimport shutil\nimport subprocess\n\n\n#This function returns a dict. with point values and location\ndef return_points(taskID):\n #Get all the files to run\n filenames = os.listdir(taskID + '/individuals')\n\n #Run for each file\n point_data = {} \n for filename in filenames:\n #Open the input raster\n raster = rasterio.open(taskID + '/individuals/' + filename)\n array = raster.read(1)\n\n #Get the index for the min value (the datapoint)\n flat_index = np.argmin(array)\n index = np.unravel_index(flat_index, array.shape)\n \n #Write the data to the dictionary\n key = os.path.splitext(filename)[0]\n point_data[key] = {'index': index, 'value': array[index]}\n\n return point_data\n\n\n#This function returns a dict. with buffer arrays\ndef return_buffers(taskID):\n #Get all the files to run\n filenames = os.listdir(taskID + '/buffers')\n\n #Run for each file\n buffers = {} \n for filename in filenames:\n #Open the input raster\n raster = rasterio.open(taskID + '/buffers/' + filename)\n array = raster.read(1)\n \n #Write the data to the dictionary\n key = os.path.splitext(filename)[0]\n buffers[key] = array\n\n return buffers\n\n\ndef return_topo(taskID):\n \n #Define stack\n arrays = list()\n labels = list()\n\n #Import Elevation\n ##########################\n elev_raster = rasterio.open(taskID + '/topo/elev.tif')\n elev = elev_raster.read(1)\n arrays.append(elev)\n labels.append('Elevation')\n\n #Import Multi-Neighborhood curvatures\n ##########################\n curvlist = os.listdir(taskID + '/topo/curvatures')\n for instance in curvlist:\n curve_raster = rasterio.open(taskID + '/topo/curvatures/' + instance)\n curve = curve_raster.read(1)\n arrays.append(curve)\n labels.append(os.path.splitext(instance)[0])\n\n return arrays #, labels\n\n\ndef template(feature_set, taskID):\n\n #Get template data\n raster_shape = feature_set[0].shape\n raster = gdal.Open(taskID + '/topo/elev.tif')\n geotrans = raster.GetGeoTransform()\n proj = raster.GetProjection()\n\n return raster_shape, geotrans, proj\n\ndef cleanup(taskID):\n if os.path.isfile(taskID + '/rootdata/boundary.shp'):\n subprocess.call('rm ' + taskID + '/rootdata/boundary.*', shell=True)\n if os.path.isfile(taskID + '/rootdata/buffered_boundary.shp'):\n subprocess.call('rm ' + taskID + '/rootdata/buffered_boundary.*', shell=True)\n #if os.path.isfile(taskID + '/topo/elev.tif'):\n #subprocess.call('rm ' + taskID + '/topo/elev.tif', shell=True)\n #if os.path.isdir(taskID + '/topo/curvatures/'):\n #shutil.rmtree(taskID + '/topo/curvatures')\n #subprocess.call('mkdir ' + taskID + '/topo/curvatures/', shell=True)\n if os.path.isdir(taskID + '/buffers/'):\n shutil.rmtree(taskID + '/buffers/')\n subprocess.call('mkdir ' + taskID + '/buffers/', shell=True)\n if os.path.isdir(taskID + '/individuals/'):\n shutil.rmtree(taskID + '/individuals/')\n subprocess.call('mkdir ' + taskID + '/individuals/', shell=True)\n\n\n","repo_name":"jafiecht/soil-docker","sub_path":"server/scripts/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35113186650","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 14 22:23:34 2023\n@author: ayaha\n\"\"\"\nimport os\nimport time\n\nimport joblib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import metrics, svm\nfrom sklearn.model_selection import train_test_split\n\nfrom PSLogger import psLog\nfrom PSUtils import OUT_DIR, get_pics\n\n\ndef psSVM(save=False, kernel=\"linear\", sea=1, shape='ovr', size_img=100, show_cm=False, probability=False):\n \"\"\"\n Higher C decreases the amount of misclassified data points in the trainng set\n but may increase misclassification in test data. C is log\n \"\"\"\n total_time = time.time()\n\n start_time = time.time()\n psLog.debug(\"Loading data...\")\n Y = np.loadtxt(os.path.join(OUT_DIR, 'Y.txt'), dtype=str)\n X = get_pics(size_img)\n\n X_train, X_test, y_train, y_test = train_test_split(\n X, Y, test_size=0.2, shuffle=False)\n psLog.debug(\"Loaded data (%.2fs)\", (time.time()-start_time))\n\n clf = svm.SVC(kernel=kernel, C=sea,\n decision_function_shape=shape, probability=probability)\n psLog.debug(\"Training model...\")\n start_time = time.time()\n clf.fit(X_train, y_train)\n psLog.debug(\"Model trained (%.2fs)\", (time.time()-start_time))\n\n psLog.debug(\"Verifying accuracy...\")\n start_time = time.time()\n predicted = clf.predict(X_test)\n error_rate = 1 - metrics.accuracy_score(y_test, predicted)\n elapsed_time = time.time() - start_time\n\n psLog.debug(\"Classification complete. (%.2fs)\", elapsed_time)\n psLog.debug(f\"Classification error: {error_rate}\")\n\n model_settings = [kernel, sea, shape, size_img]\n if save:\n psLog.debug(\"Saving model...\")\n start_time = time.time()\n joblib.dump((clf, model_settings), 'PSSVMSaved.jbl')\n psLog.debug(\"Model saved (%.2fs)\", (time.time()-start_time))\n\n elapsed_time = time.time() - total_time\n psLog.debug(\"Total time: %.2fs\", time.time()-total_time)\n\n if show_cm:\n disp = metrics.ConfusionMatrixDisplay.from_predictions(\n y_test, predicted)\n disp.figure_.suptitle(\"Confusion Matrix\")\n plt.show()\n\n if probability:\n probabilities = clf.predict_proba(X_test)\n max_probabilities = np.max(probabilities, axis=1)\n confidence = max_probabilities * 100\n labels = clf.classes_[np.argmax(probabilities, axis=1)]\n for conf, label in zip(confidence, labels):\n print(f\"SVM Confidence: {conf:.2f}%, Label: {label}\")\n\n return [model_settings, elapsed_time, error_rate, (clf, model_settings)]\n","repo_name":"ayah-uhhh/ParrotSourML","sub_path":"PSSVM.py","file_name":"PSSVM.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9446936248","text":"import requests\nimport json\nimport influxdb_client\n\ndef getInverterValues(config):\n measurement_points = []\n \n #get config\n debug_output = config[\"global\"][\"debug_output\"]\n hostname = config[\"inverter\"][\"hostname\"]\n measurement = config[\"inverter\"][\"measurement\"]\n\n try:\n #get data from inverter\n url = requests.get(\"http://\" + hostname + \"/solar_api/v1/GetPowerFlowRealtimeData.fcgi\", timeout=10)\n\n try:\n #parse data\n json_data = json.loads(url.text)\n inverter_list = json_data['Body']['Data']['Inverters']\n for inverter_number in inverter_list:\n inverter_data = json_data['Body']['Data']['Inverters'][inverter_number]\n total_kWh = inverter_data['E_Total'] / 1000\n point = influxdb_client.Point(measurement).tag(\"unit\", \"kWh\").field(\"inverter_\" + str(inverter_number), total_kWh)\n measurement_points.append(point)\n if debug_output == \"true\":\n print(\"Total current: \" + str(total_kWh) + \" kWh\")\n\n except:\n if debug_output == \"true\":\n print(\"failed to parse inverter data\")\n\n except:\n if debug_output == \"true\":\n print(\"failed to get inverter data, is server offline?\")\n\n return measurement_points\n","repo_name":"Flipper189/solarflux","sub_path":"inverter.py","file_name":"inverter.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1731572475","text":"from multiprocessing import context\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Q\nfrom .models import Room, Topic, Message\nfrom .forms import RoomForm, UserForm\nfrom django.http import HttpResponse, HttpResponseRedirect\n\n\n#basic views...\ndef home(request):\n rooms = Room.objects.all()\n topics = Topic.objects.all()[0:5]\n comments = Message.objects.all()\n if request.method == 'GET':\n q = request.GET.get('q')\n if q != '' and q != None:\n rooms = Room.objects.filter(\n Q(topic__name__icontains=q) |\n Q(name__icontains=q)|\n Q(description__icontains=q) \n )\n comments = Message.objects.filter(\n Q(room__topic__name__icontains =q)|\n Q(user__username__icontains=q)\n )\n else:\n rooms = Room.objects.all()\n \n room_count = rooms.count()\n \n \n context = {'rooms': rooms, 'topics': topics, 'room_count': room_count, 'comments': comments}\n return render(request, 'IndexApp/home.html', context)\n\ndef rooms(request, pk):\n \n room = Room.objects.get(id =pk)\n comments = room.comments.all().order_by('-created')\n participants = room.participants.all()\n \n if request.method == 'POST':\n comment = Message.objects.create(\n user = request.user,\n room = room,\n body = request.POST.get('body')\n )\n\n comment.save()\n room.participants.add(request.user)\n return redirect('room', pk)\n \n \n \n context ={'room': room, 'comments': comments, 'participants': participants}\n return render(request, 'IndexApp/rooms.html', context)\n\ndef userProfile(request, pk):\n user = User.objects.get(id = pk)\n comments = user.message_set.all()\n rooms = user.room_set.all()\n topics = Topic.objects.all()\n \n \n context = {'comments': comments, 'rooms': rooms, 'topics': topics, 'user': user}\n return render(request, 'IndexApp/userProfile.html', context)\n\n\n@login_required(login_url='loginPage')\ndef room_form(request):\n form = RoomForm()\n topics=Topic.objects.all()\n if request.method == 'POST':\n topic_name = request.POST.get('topic')\n topic, created = Topic.objects.get_or_create(name = topic_name)\n \n Room.objects.create(\n host = request.user,\n topic = topic,\n name = request.POST.get('name'),\n description = request.POST.get('description'),\n )\n # form = RoomForm(request.POST)\n # if form.is_valid():\n # room = form.save(commit=False)\n # room.host = request.User\n # room.save()\n return redirect('home')\n \n \n form = RoomForm()\n context = {'form': form, 'topics': topics}\n return render(request, 'IndexApp/room_form.html', context)\n\n\n\n#Update or edit comments\n@login_required(login_url='loginPage')\ndef updateRoom(request, pk):\n room = Room.objects.get(id=pk)\n form = RoomForm(instance = room)\n topics = Topic.objects.all()\n if (request.user != room.host):\n return HttpResponse('you are not allowed to update this room')\n if request.method == 'POST':\n topic_name = request.POST.get('topic')\n topic, created = Topic.objects.get_or_create(name = topic_name)\n \n room.name = request.POST.get('name')\n room.topic = topic\n room.description = request.POST.get('description')\n room.save()\n \n # form = RoomForm(request.POST, instance=room)\n # if form.is_valid():\n # temp = form.save(commit=False)\n # temp.topic = topic\n return redirect('home') \n \n context = {'form': form, \"topics\":topics, 'room':room}\n \n return render(request, 'IndexApp/room_form.html', context)\n\n@login_required(login_url='loginPage')\ndef deleteRoom(request, pk):\n page = 'room'\n room = Room.objects.get(id=pk)\n \n if (request.user != room.host):\n return HttpResponse('you are not allowed to delete this room')\n \n if request.method == 'POST':\n room.delete()\n return redirect('room', pk)\n \n \n context = {'room': room, 'page': page}\n return render(request, 'IndexApp/deleteRoom.html', context)\n\n\n#Login views\ndef loginPage(request):\n page = 'login'\n if request.user.is_authenticated:\n return redirect('home')\n if request.method == 'POST':\n username = request.POST.get('username').lower()\n password = request.POST.get('password')\n \n \n user = authenticate(username = username, password = password)\n \n if user is not None:\n login(request, user)\n return redirect('home')\n \n else:\n messages.error(request, 'Invalid username or password')\n \n context = {'page': page}\n return render(request, 'IndexApp/login_registration.html', context)\n\n\ndef registerUser(request):\n page = 'register'\n form = UserCreationForm()\n \n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.username = user.username.lower()\n user.save()\n login(request, user)\n return redirect('home')\n \n else:\n messages.error(request, 'There was an error registering the User. Please try again later')\n return redirect('regUser')\n \n \n \n \n context = {'page': page, 'form': form}\n return render(request, 'IndexApp/login_registration.html', context)\n\ndef logoutPage(request):\n logout(request)\n return redirect('loginPage')\n \n#delete comments \n@login_required(login_url='loginPage')\ndef deleteComment(request, pk):\n page = 'comments'\n comment = Message.objects.get(id=pk)\n \n if (request.user != comment.user):\n return HttpResponse('you are not allowed to delete this room')\n \n if request.method == 'POST':\n comment.delete()\n return redirect('room', pk=comment.room.id)\n \n \n context = {'page': page, 'comment' : comment}\n return render(request, 'IndexApp/deleteRoom.html', context)\n\n\n@login_required(login_url='loginPage')\ndef updateUser(request):\n user = request.user\n form = UserForm(instance=user)\n \n if request.method == 'POST':\n form = UserForm(request.POST, instance=user)\n if form.is_valid():\n form.save()\n return redirect('userProfile', pk = request.user.id)\n \n \n \n context = {'form': form}\n return render(request, 'IndexApp/update_user.html', context)\n\ndef topicsPage(request):\n q = request.GET.get('q') if request.GET.get('q') != None else''\n topics = Topic.objects.filter(name__icontains=q)\n \n context = {'topics': topics, 'rooms': rooms}\n return render(request, 'IndexApp/topics.html', context)\n\n\ndef activityPage(request):\n rooms= Room.objects.all()\n comments = Message.objects.all()\n \n context = {'rooms': rooms, 'comments': comments}\n return render(request, 'IndexApp/activity.html', context)\n","repo_name":"Kayphaz007/WeChat","sub_path":"IndexApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21182809231","text":"#!/usr/bin/env python\n\n\"\"\" Histogram of user function run-times (completed & killed).\n\nScript to produce a histogram plot giving a count of user function (sim or\ngen) calls by run-time intervals. Color shows completed versus killed versus\nfailed/exception.\n\nThis plot is produced from the libE_stats.txt file. Status is taken from the\ncalc_status returned by user functions.\n\nThe plot is written to a file.\n\n\"\"\"\n\nimport sys\n\nimport matplotlib\nimport numpy as np\n\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\n# Basic options ---------------------------------------------------------------\n\ninfile = \"libE_stats.txt\"\ntime_key = \"Time:\"\nstatus_key = \"Status:\"\nsim_only = True # Ignore generator times\nmax_bins = 40\nran_ok = [\"Completed\"] # List of OK states\nrun_killed = [\"killed\"] # Searches for this word in status string\nrun_exception = [\"Exception\", \"Failed\"]\n\n# -----------------------------------------------------------------------------\n\n\ndef search_for_keyword(in_list, kw_list):\n for i, val in enumerate(in_list):\n if val.endswith(\":\"):\n break # New key word found\n else:\n if val in kw_list:\n return True\n return False\n\n\ndef append_to_list(mylst, glob_list, found_time):\n # Assumes Time comes first - else have to modify\n if found_time:\n mylst.append(glob_list[-1])\n else:\n print(\"Error Status found before time - exiting\")\n sys.exit()\n\n\nactive_line_count = 0\nin_times = []\nin_times_ran = []\nin_times_kill = []\nin_times_exception = []\n\n\n# Read straight from libEnsemble summary file.\nwith open(infile) as f:\n for line in f:\n lst = line.split()\n found_time = False\n found_status = False\n for i, val in enumerate(lst):\n if val == time_key:\n if sim_only and lst[i - 1] != \"sim\":\n break\n in_times.append(lst[i + 1])\n found_time = True\n if val == status_key:\n if lst[i + 1] in ran_ok:\n append_to_list(in_times_ran, in_times, found_time) # Assumes Time comes first\n elif search_for_keyword(lst[i + 1 : len(lst)], run_killed):\n append_to_list(in_times_kill, in_times, found_time) # Assumes Time comes first\n elif search_for_keyword(lst[i + 1 : len(lst)], run_exception):\n exceptions = True\n append_to_list(in_times_exception, in_times, found_time) # Assumes Time comes first\n else:\n print(f\"Error: Unknown status - rest of line: {lst[i + 1:len(lst)]}\")\n sys.exit()\n found_status = True\n if found_time and found_status:\n active_line_count += 1\n break\n\nprint(f\"Processed {active_line_count} calcs\")\n\ntimes = np.asarray(in_times, dtype=float)\ntimes_ran = np.asarray(in_times_ran, dtype=float)\ntimes_kill = np.asarray(in_times_kill, dtype=float)\ntimes_exc = np.asarray(in_times_exception, dtype=float)\n\nnum_bins = min(active_line_count, max_bins)\nbinwidth = (times.max() - times.min()) / num_bins\nbins = np.arange(min(times), max(times) + binwidth, binwidth)\n\n# Completed is the top segment\nplt_times = [times_kill, times_ran]\nlabels = [\"Killed\", \"Completed\"]\ncolors = [\"#FF7F0e\", \"#1F77B4\"] # Orange, Blue\n\n# Insert at bottom (Dont want label if no exceptions)\nif in_times_exception:\n plt_times.insert(0, times_exc)\n labels.insert(0, \"Except/Failed\")\n colors.insert(0, \"#d62728\") # Red\n\nplt.hist(plt_times, bins, edgecolor=\"black\", linewidth=1.5, stacked=True, label=labels, color=colors)\n\nif sim_only:\n calc = \"sim\"\nelse:\n calc = \"calc\"\n\ntitl = \"Histogram of \" + calc + \" times\" + \" (\" + str(active_line_count) + \" user calcs)\" + str(num_bins) + \" bins\"\n\nplt.title(titl)\nplt.xlabel(\"Calculation run time (sec)\", fontsize=14)\nplt.ylabel(\"Count\", fontsize=14)\nplt.grid(axis=\"y\")\nplt.legend(loc=\"best\", fontsize=14)\n\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\n\n# plt.show()\nplt.savefig(\"hist_completed_v_killed.png\")\n# plt.savefig(\"hist_completed_v_killed.png\", bbox_inches=\"tight\", transparent=True)\n","repo_name":"Libensemble/libensemble","sub_path":"scripts/plot_libe_histogram.py","file_name":"plot_libe_histogram.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"3"}
+{"seq_id":"17503147475","text":"# @Author: Farhan Rehman\n# Purpose: Converts SQLite queries response to JSON\n\n# Imports\nfrom rest_framework.serializers import ModelSerializer, ReadOnlyField\nfrom rest_framework import serializers\n\nfrom .models import CongressTrade, CongressPerson, Ticker, SummaryStat\n\n# Abstraction is integrated due to django within all of these classes\nclass TickerSerializer(serializers.ModelSerializer):\n class Meta:\n # Database table\n model = Ticker\n # Fields to appear on the response\n fields = ('ticker', 'company', 'marketcap', 'sector', 'industry', 'totalTransactions', 'totalVolumeTransactions', 'purchases', 'sales',)\n\nclass CongressPersonSerializer(serializers.ModelSerializer):\n class Meta:\n # Database table\n model = CongressPerson\n # Fields to appear on the response\n fields = ('fullName', 'currentParty', 'currentChamber', 'currentState', 'image', 'totalTransactions', 'totalVolumeTransactions', 'purchases', 'sales',)\n\nclass CongressTradeSerializer(serializers.ModelSerializer):\n # Gets ForignKey field to appear on the response, refer to ERD Diagram to get a better understanding of the connection between the models\n name = ReadOnlyField(source='name.fullName')\n ticker = ReadOnlyField(source='ticker.ticker')\n\n if ticker == None:\n ticker = \"-\"\n\n class Meta:\n # Database table\n model = CongressTrade\n # Fields to appear on the response\n # fields = ('name', 'bioguide','firstName','lastName', 'ticker', 'transactionDate', 'assetType', 'transactionType', 'amount', 'ptrLink')\n fields = ('name', 'ticker', 'transactionDate', 'assetType', 'transactionType', 'amount', 'ptrLink')\n\nclass SummaryStatSerializer(serializers.ModelSerializer):\n class Meta:\n # Database table\n model = SummaryStat\n # Fields to appear on the response\n # __all__ includes all fields in the model in the response\n fields = \"__all__\"\n","repo_name":"InsiderUnlocked/Backend","sub_path":"congress/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"74833671761","text":"# -*- coding: utf-8 -*-\nimport typing\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass CustomComboBox(QtWidgets.QWidget): \n def __init__(self, \n parent: typing.Optional[QtWidgets.QWidget] = ...,\n init: str = \"No Connection\"\n ) -> None: \n super(QtWidgets.QWidget, self).__init__(parent)\n\n self.DOT_STYLE = (\"QWidget {\\n\"\n \"border-radius: 6px;\\n\"\n \"background-color: {OPTION};\\n\"\n \"}\")\n\n self.setupUi(init)\n\n def setupUi(self, initial_text: str = \"No Connection\"):\n\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())\n self.setSizePolicy(sizePolicy)\n self.setMinimumSize(QtCore.QSize(0, 30))\n\n self.setStyleSheet(\"QComboBox {\\n\"\n\"background-color: #FFF;\\n\"\n\"color: #B5BFC6; \\n\"\n\"border-radius: 14px;\\n\"\n\"text-align: center; \\n\"\n\"\\n\"\n\"selection-background-color: #FFF; /*ECECEC*/\\n\"\n\"selection-color: #0F5BCD;\\n\"\n\"outline: 0;\\n\"\n\"padding-left: 8px;\\n\"\n\"}\\n\"\n\"QComboBox:hover {\\n\"\n\" background-color: #F8F9FB; \\n\"\n\"}\\n\"\n\"QComboBox:on { /* shift the text when the popup opens */\\n\"\n\" color: #B5BFC6\\n\"\n\"}\\n\"\n\"QComboBox::drop-down {\\n\"\n\"border: 0px;\\n\"\n\"padding-right: 5px;\\n\"\n\"}\\n\"\n\"QComboBox::down-arrow {\\n\"\n\"/* image: url(:/icons/icons/edit.png); width: 16px; height: 16px; */\\n\"\n\"}\\n\"\n\"\\n\"\n\"QComboBox QListView {\\n\"\n\"background-color: #F8F9FB;\\n\"\n\"color: #B5BFC6; \\n\"\n\"border-radius: 8px;\\n\"\n\"padding: 5px; margin-top: 5px;\\n\"\n\"outline: 1px;\\n\"\n\"}\\n\"\n\"QComboBox QAbstractItemView {\\n\"\n\" selection-background-color: #EDF0F6;\\n\"\n\" selection-color: #4487EB;\\n\"\n\"}\\n\"\n\"\\n\")\n self.setObjectName(\"comboBoxFrame\")\n\n self.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))\n\n #########################\n # Layout #\n #########################\n self.__layout = QtWidgets.QHBoxLayout(self)\n self.__layout.setContentsMargins(12, 0, 0, 0)\n self.__layout.setSpacing(4)\n self.__layout.setObjectName(\"layout\")\n\n #########################\n # Status Dot #\n #########################\n self.__dot = QtWidgets.QWidget(self)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.__dot.sizePolicy().hasHeightForWidth())\n self.__dot.setSizePolicy(sizePolicy)\n self.__dot.setMinimumSize(QtCore.QSize(12, 12))\n self.__dot.setMaximumSize(QtCore.QSize(12, 12))\n self.__dot.setObjectName(\"dot\")\n self.__layout.addWidget(self.__dot)\n self.setStatusIdle()\n \n #########################\n # ComboBox #\n #########################\n self.comboBox = QtWidgets.QComboBox(self)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().hasHeightForWidth())\n self.comboBox.setSizePolicy(sizePolicy)\n self.comboBox.setMinimumSize(QtCore.QSize(0, 30))\n\n font = QtGui.QFont()\n font.setFamily(\"Montserrat SemiBold\")\n font.setPointSize(10)\n font.setBold(False)\n font.setWeight(50)\n self.comboBox.setFont(font)\n\n self.comboBox.addItem(initial_text)\n self.comboBox.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)\n self.comboBox.setObjectName(\"comboBox\")\n self.__layout.addWidget(self.comboBox)\n \n def setStatusIdle(self) -> None: self.__dot.setStyleSheet( \n self.DOT_STYLE.replace('{OPTION}', '#B5BFC6') \n )\n def setStatusConnected(self) -> None: self.__dot.setStyleSheet( \n self.DOT_STYLE.replace('{OPTION}', '#04B56E') \n )\n def setStatusConnecting(self) -> None: self.__dot.setStyleSheet( \n self.DOT_STYLE.replace('{OPTION}', '#F99500') \n )\n def setStatusDisconnected(self) -> None: self.__dot.setStyleSheet( \n self.DOT_STYLE.replace('{OPTION}', '#F25858') \n )\n\n\n def addItem(self, text: str, userData: typing.Any = ...) -> None: \n self.comboBox.addItem(text, userData)\n def addItems(self, texts: typing.Iterable[str]) -> None:\n self.comboBox.addItems(texts)\n def clear(self) -> None: \n self.comboBox.clear()\n\n\nif __name__ == '__main__':\n\n app = QtWidgets.QApplication([])\n \n window = QtWidgets.QWidget()\n window.setStyleSheet(\"QWidget {background-color: #FFF;}\")\n\n layout = QtWidgets.QHBoxLayout(window)\n layout.setContentsMargins(12, 12, 12, 12)\n layout.setSpacing(12)\n layout.setObjectName(\"layout\")\n\n #TUTORIAL ######################################\n statusBox1 = CustomComboBox(window)\n\n statusBox1.addItem(\"Connection A\")\n statusBox1.addItems(\n [\"Connection B\", \"Connection C\"])\n \n statusBox1.comboBox.activated.connect(print) # Print the index after comboBox get clicked\n\n statusBox2 = CustomComboBox(window, init=\"Connecting\")\n statusBox2.setStatusConnecting()\n\n statusBox3 = CustomComboBox(window, init=\"Connected\")\n statusBox3.setStatusConnected()\n\n statusBox4 = CustomComboBox(window, init=\"Error\")\n statusBox4.setStatusDisconnected()\n\n layout.addWidget(statusBox1)\n layout.addWidget(statusBox2)\n layout.addWidget(statusBox3)\n layout.addWidget(statusBox4)\n window.update()\n ################################################\n\n spacer = QtWidgets.QSpacerItem(261, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n layout.addItem(spacer)\n window.show()\n app.exec_()\n","repo_name":"defmylife/Qt-templates","sub_path":"StatusButtons/ComboBox.py","file_name":"ComboBox.py","file_ext":"py","file_size_in_byte":5973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2037490038","text":"import sys\nN = int(sys.stdin.readline())\nwhole_img = []\nres = ''\n\nfor i in range(N):\n line = list(sys.stdin.readline())\n whole_img.append(line)\n\ndef compression(start_row, start_col, length):\n global res\n\n if length == 1:\n res += whole_img[start_row][start_col]\n return\n\n first = ''\n for i in range(start_row, start_row+length):\n for j in range(start_col, start_col+length):\n if i == start_row and j == start_col:\n first = whole_img[i][j]\n continue\n else:\n if whole_img[i][j] != first:\n res += '('\n compression(start_row, start_col, int(length/2))\n compression(start_row, start_col + int(length / 2), int(length / 2))\n compression(start_row + int(length/2), start_col, int(length/2))\n compression(start_row + int(length/2), start_col + int(length/2), int(length/2))\n res += ')'\n return\n\n res += first\n\ncompression(0, 0, N)\n\nprint(res)","repo_name":"kayjayk/Algorithms_py","sub_path":"Exam1992.py","file_name":"Exam1992.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33024404274","text":"import pygame\nfrom pygame.locals import (\n K_w,\n K_a,\n K_s,\n K_d,\n K_q,\n K_e,\n K_ESCAPE,\n KEYDOWN,\n QUIT,\n)\nimport config as CONFIG\n\nclass Hud:\n '''Represents the heads up display elements on the canvs.'''\n\n def __init__(self):\n '''Initialize the robot class'''\n\n # Indicator color (initial shade of gray)\n self.indicator_color = 240\n\n # Create the indicator rectangle\n self.ind_pos = CONFIG.border_pixels/4\n self.ind_size = CONFIG.border_pixels/2\n self.indicator = pygame.Rect(self.ind_pos, self.ind_pos, self.ind_size, self.ind_size)\n\n # Position of pressed key indicators\n self.key_ind_pos = {\n K_w: 1 * (self.ind_size + 2 * self.ind_pos) + self.ind_pos,\n K_a: 2 * (self.ind_size + 2 * self.ind_pos) + self.ind_pos,\n K_s: 3 * (self.ind_size + 2 * self.ind_pos) + self.ind_pos,\n K_d: 4 * (self.ind_size + 2 * self.ind_pos) + self.ind_pos,\n K_q: 5 * (self.ind_size + 2 * self.ind_pos) + self.ind_pos,\n K_e: 6 * (self.ind_size + 2 * self.ind_pos) + self.ind_pos,\n }\n\n # Color of pressed key indicators\n self.key_ind_colors = {\n K_w: (255, 0, 0),\n K_a: (0, 255, 0),\n K_s: (0, 0, 255),\n K_d: (255, 255, 0),\n K_q: (0, 255, 255),\n K_e: (255, 0, 255),\n 'none': (0, 0, 0,)\n }\n\n # Define pressed key indicator rectangles\n self.key_ind = {\n K_w: pygame.Rect(self.ind_pos, self.key_ind_pos[K_w], self.ind_size, self.ind_size),\n K_a: pygame.Rect(self.ind_pos, self.key_ind_pos[K_a], self.ind_size, self.ind_size),\n K_s: pygame.Rect(self.ind_pos, self.key_ind_pos[K_s], self.ind_size, self.ind_size),\n K_d: pygame.Rect(self.ind_pos, self.key_ind_pos[K_d], self.ind_size, self.ind_size),\n K_q: pygame.Rect(self.ind_pos, self.key_ind_pos[K_q], self.ind_size, self.ind_size),\n K_e: pygame.Rect(self.ind_pos, self.key_ind_pos[K_e], self.ind_size, self.ind_size)\n }\n\n # Clock for managing game framerate\n self.clock = pygame.time.Clock()\n\n def check_input(self, events):\n '''Check for keyboard inputs'''\n\n # Look at every event in the queue\n for event in events:\n # Did the user hit a key?\n if event.type == KEYDOWN:\n # Was it the Escape key? If so, stop the loop.\n if event.key == K_ESCAPE:\n return False\n\n # Did the user click the window close button? If so, stop the loop.\n elif event.type == QUIT:\n return False\n\n return True\n\n def draw_frame_indicator(self, canvas):\n '''Draws the HUD frame indicator.'''\n\n # Update the color value\n self.indicator_color -= int(240/CONFIG.frame_rate)\n if self.indicator_color <= 0:\n self.indicator_color = 240\n\n # Create an RGB color tuple\n color_tuple = (self.indicator_color, self.indicator_color, self.indicator_color)\n\n # Draw the indicator on the canvas\n pygame.draw.rect(canvas, color_tuple, self.indicator)\n\n def draw_keys(self, canvas, keypress):\n '''Draws indicators showing the currently pressed wasd-qe keys'''\n\n for [key, value] in self.key_ind.items():\n if keypress[key]:\n pygame.draw.rect(canvas, self.key_ind_colors[key], self.key_ind[key])\n else:\n pygame.draw.rect(canvas, self.key_ind_colors['none'], self.key_ind[key])\n\n def get_exec_time(self):\n '''Gets the frame calculation time'''\n return self.clock.get_rawtime()\n","repo_name":"CherL01/KirB","sub_path":"interface/hud.py","file_name":"hud.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72239739282","text":"'''\n1. 기준 테이터를 설정하고 그 기준보다 큰 데이터와 작은 데이터의 위치를 바꾸는 방법\n2. 병합 정렬과 더불어 일반적인 상황에서 가장 많이 사용된다.\n3. 쉽게 하려면 첫 번째 데이터를 기준으로 선택한다\n4. 왼쪽의 데이터에서 피벗보다 큰 값을 선택하고, 오른쪽에선 작은 값을 선택한다.\n5. 선택이 완료되면 둘을 스왑한다.\n6. start와 end가 엇갈리면 왼쪽 배열의 마지막 값과 피벗을 스왑한다.\n'''\n\n\ndef qsort_pythonic(target):\n if len(target) <= 1:\n return target\n pivot = target[0]\n\n left = [i for i in target if i < pivot]\n mid = [i for i in target if i == pivot]\n right = [i for i in target if i > pivot]\n return qsort_pythonic(left) + mid + qsort_pythonic(right)\n\n\ndef qsort_while(target, start, end):\n # 재귀에서 다루는 배열은 같은 배열임을 생각하자.\n # start, end 포인터만 변경해가면서 정렬을 수행하는 것이다.\n # 따라서 종료조건은 target의 length가 아니라 start와 end의 차이로 지정해야 한다.\n # 여기서 start와 end는 둘다 포함되는 범위이므로 range(start, end)와 다름을 생각하자.\n\n if start >= end:\n return\n pivot = (start + end) // 2 # 피벗도 인덱스로 지정한다. 인덱스와 실제 값을 헷갈리지말자\n target[pivot], target[start] = target[start], target[pivot]\n left = start + 1\n right = end\n # 두 개의 포인터가 교차하면 멈춰야 한다.\n while left <= right:\n # 왼쪽은 피벗보다 큰 숫자를 찾을 때 까지 계속 증가시켜준다.\n while left <= end and target[left] <= target[pivot]:\n left += 1\n # 오른쪽은 피벗보다 작은 숫자를 찾을 때 까지 증가시킨다.\n while right > start and target[right] >= target[pivot]:\n right -= 1\n # 만약 left와 right가 교차했다면 특수한 처리를 해줘야한다.\n # right가 멈춰 선 곳에 위치한 원소는 pivot보다 작거나 같은 원소이므로\n # 제일 첫 번째 원소인 pivot과 스위치해줘도 퀵정렬의 조건과 일치한다.\n if left > right:\n target[right], target[pivot] = target[pivot], target[right]\n # 교차하지 않았다면 left, right를 바꿔주면 된다.\n else:\n target[left], target[right] = target[right], target[left]\n # while문 안에서 피벗을 기준으로 한 정렬이 완료되었다.\n # 따라서 피벗을 제외한 양 옆의 배열을 대상으로 재귀적으로 퀵정렬을 호출해준다.\n # array 자체는 변화하지 않고 start, end인덱스 기준으로 퀵정렬을 수행할 구간을 지정하는 형식이므로\n # 이 형식에 맞게 호출해주어야한다.\n qsort_while(target, start, right - 1)\n qsort_while(target, right + 1, end)\n # partition 함수는 주어진 범위에서 피벗값을 기준으로 작은 값들과 큰 값들을 분리하는 역할을 수행하고, 피벗값의 위치를 반환합니다.\n\n\ndef partition(arr, low, high):\n # 피벗 인덱스를 중간값으로 설정합니다.\n pivot_index = (low + high) // 2\n # 피벗 인덱스의 값을 배열의 마지막 요소와 교환합니다.\n arr[pivot_index], arr[high] = arr[high], arr[pivot_index]\n pivot = arr[high]\n\n # i는 작은 값들을 추적하는 인덱스로 사용됩니다.\n i = low - 1\n\n # low부터 high까지 반복하며 피벗값과 비교합니다.\n for j in range(low, high):\n if arr[j] <= pivot:\n # 작은 값들을 좌측에 유지하고 인덱스 i를 증가시킵니다.\n i += 1\n arr[i], arr[j] = arr[j], arr[i]\n\n # 마지막으로 피벗 값을 올바른 위치로 옮깁니다.\n arr[i + 1], arr[high] = arr[high], arr[i + 1]\n return i + 1\n\n# quick_sort 함수는 재귀적으로 분할 정복 방식으로 정렬을 수행합니다.\n\n\ndef quick_sort(arr, low, high):\n if low < high:\n # 주어진 범위를 분할하여 피벗 인덱스를 얻습니다.\n pivot_index = partition(arr, low, high)\n # 피벗 인덱스를 기준으로 왼쪽 부분 배열을 정렬합니다.\n quick_sort(arr, low, pivot_index - 1)\n # 피벗 인덱스를 기준으로 오른쪽 부분 배열을 정렬합니다.\n quick_sort(arr, pivot_index + 1, high)\n\n\narray = [3, 6, 8, 10, 1, 2, 1, -1]\nprint(\"Original array:\", array)\nquick_sort(array, 0, len(array) - 1)\nprint(\"Sorted array:\", array)\nprint('----------------')\n\narray = [3, 3, 3, 1, 1, 2, 1, 0, -1, -1, 0]\nprint(\"WHILE Original array:\", array)\nqsort_while(array, 0, len(array) - 1)\nprint(\"WHILE Sorted array:\", array)\nprint('----------------')\n\narray = [3, 6, 8, 10, 1, 2, 1, -1]\nprint(\"Original array:\", array)\nprint(\"Sorted array:\", qsort_pythonic(array))\n","repo_name":"atoye1/ThisIsCodingTest","sub_path":"Sorting/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":4920,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43023255394","text":"# 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\nimport pretend\nimport pytest\n\nfrom pyramid.httpexceptions import HTTPBadRequest\n\nfrom warehouse.admin.views import journals as views\n\nfrom ....common.db.accounts import UserFactory\nfrom ....common.db.packaging import JournalEntryFactory, ProjectFactory\n\n\nclass TestProjectList:\n def test_no_query(self, db_request):\n journals = sorted(\n JournalEntryFactory.create_batch(30),\n key=lambda j: (j.submitted_date, j.id),\n reverse=True,\n )\n result = views.journals_list(db_request)\n\n assert result == {\"journals\": journals[:25], \"query\": None}\n\n def test_with_page(self, db_request):\n journals = sorted(\n JournalEntryFactory.create_batch(30),\n key=lambda j: (j.submitted_date, j.id),\n reverse=True,\n )\n db_request.GET[\"page\"] = \"2\"\n result = views.journals_list(db_request)\n\n assert result == {\"journals\": journals[25:], \"query\": None}\n\n def test_with_invalid_page(self):\n request = pretend.stub(params={\"page\": \"not an integer\"})\n\n with pytest.raises(HTTPBadRequest):\n views.journals_list(request)\n\n def test_query_basic(self, db_request):\n project0 = ProjectFactory.create()\n project1 = ProjectFactory.create()\n journals0 = sorted(\n JournalEntryFactory.create_batch(30, name=project0.normalized_name),\n key=lambda j: (j.submitted_date, j.id),\n reverse=True,\n )\n JournalEntryFactory.create_batch(30, name=project1.normalized_name)\n\n db_request.GET[\"q\"] = f\"{project0.name}\"\n result = views.journals_list(db_request)\n\n assert result == {\n \"journals\": journals0[:25],\n \"query\": f\"{project0.name}\",\n }\n\n def test_query_term_project(self, db_request):\n project0 = ProjectFactory.create()\n project1 = ProjectFactory.create()\n journals0 = sorted(\n JournalEntryFactory.create_batch(30, name=project0.normalized_name),\n key=lambda j: (j.submitted_date, j.id),\n reverse=True,\n )\n JournalEntryFactory.create_batch(30, name=project1.normalized_name)\n\n db_request.GET[\"q\"] = f\"project:{project0.name}\"\n result = views.journals_list(db_request)\n\n assert result == {\n \"journals\": journals0[:25],\n \"query\": f\"project:{project0.name}\",\n }\n\n def test_query_term_user(self, db_request):\n user0 = UserFactory.create()\n user1 = UserFactory.create()\n journals0 = sorted(\n JournalEntryFactory.create_batch(30, submitted_by=user0),\n key=lambda j: (j.submitted_date, j.id),\n reverse=True,\n )\n JournalEntryFactory.create_batch(30, submitted_by=user1)\n\n db_request.GET[\"q\"] = f\"user:{user0.username}\"\n result = views.journals_list(db_request)\n\n assert result == {\n \"journals\": journals0[:25],\n \"query\": f\"user:{user0.username}\",\n }\n\n def test_query_term_version(self, db_request):\n journals = JournalEntryFactory.create_batch(10)\n\n db_request.GET[\"q\"] = f\"version:{journals[0].version}\"\n result = views.journals_list(db_request)\n\n assert result == {\n \"journals\": [journals[0]],\n \"query\": f\"version:{journals[0].version}\",\n }\n","repo_name":"pypi/warehouse","sub_path":"tests/unit/admin/views/test_journals.py","file_name":"test_journals.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","stars":3382,"dataset":"github-code","pt":"3"}
+{"seq_id":"35124568046","text":"import warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nimport joblib\nimport numpy as np\nimport pandas as pd\nfrom nbsvm_classifier import NBSVMClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, confusion_matrix, matthews_corrcoef\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\n\n\nclass TrainClassifier:\n def __init__(self, field=\"Summary\", vec_type=\"tfidf\"):\n self.RANDOM_STATE = 42\n self.field = field\n self.vec_type = vec_type\n\n def get_data(self, path):\n df = pd.read_csv(path)\n df = df.drop_duplicates()\n df = df.dropna(subset=[self.field])\n X, y = df[self.field], df[\"Class\"]\n return X, y\n\n def get_splits(self, X, y):\n X_train, X_valid, y_train, y_valid = train_test_split(\n X,\n y,\n test_size=0.2,\n random_state=self.RANDOM_STATE,\n stratify=y,\n )\n return X_train, X_valid, y_train, y_valid\n\n def print_configs(self):\n print(f\"FIELD: {self.field}\")\n print(f\"VECTORIZER: {self.vec_type.upper()}\", end=\"\\n\\n\")\n\n def print_metrics(self, y_true, y_pred):\n acc = accuracy_score(y_true, y_pred)\n mcc = matthews_corrcoef(y_true, y_pred)\n print(f\"ACCURACY: {acc:.3f}\")\n print(f\"MCC: {mcc:.3f}\")\n tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()\n print(f\"TP: {tp}\\tTN: {tn}\\tFP: {fp}\\tFN: {fn}\", end=\"\\n\\n\")\n return acc, mcc, tp, tn, fp, fn\n\n def get_count_vectors(self, X_train, X_valid):\n vec = CountVectorizer()\n train_term_doc = vec.fit_transform(X_train)\n valid_term_doc = vec.transform(X_valid)\n joblib.dump(vec, f\"../pickles/count_vectorizer_{self.field}.joblib\")\n return train_term_doc, valid_term_doc\n\n def get_tfidf_vectors(self, X_train, X_valid):\n vec = TfidfVectorizer()\n train_term_doc = vec.fit_transform(X_train)\n valid_term_doc = vec.transform(X_valid)\n joblib.dump(vec, f\"../pickles/tfidf_vectorizer_{self.field}.joblib\")\n return train_term_doc, valid_term_doc\n\n def train(self, path):\n accs, mccs, tps, tns, fps, fns = [], [], [], [], [], []\n\n # load data\n X, y = self.get_data(path)\n\n # get splits\n X_train, X_valid, y_train, y_valid = self.get_splits(X, y)\n\n # get train & valid vectors\n if self.vec_type == \"tfidf\":\n train_term_doc, valid_term_doc = self.get_tfidf_vectors(X_train, X_valid)\n elif self.vec_type == \"count\":\n train_term_doc, valid_term_doc = self.get_count_vectors(X_train, X_valid)\n\n # iterate over each model\n for model_name in [\"naive_bayes\", \"nbsvm\", \"logistic_regression\"]:\n print(\"*\" * 60)\n print(\" \" * 25 + f\"{model_name.upper()}\")\n print(\"*\" * 60)\n # create an object\n if model_name == \"naive_bayes\":\n model = MultinomialNB()\n elif model_name == \"nbsvm\":\n model = NBSVMClassifier()\n elif model_name == \"logistic_regression\":\n model = LogisticRegression()\n\n # fit the model on training data\n model.fit(train_term_doc, y_train)\n\n # predict on train & validation\n train_preds = model.predict(train_term_doc)\n valid_preds = model.predict(valid_term_doc)\n\n # print & store training metrics\n print(f\"TRAINING METRICS\")\n acc, mcc, tp, tn, fp, fn = self.print_metrics(y_train, train_preds)\n accs.append(acc)\n mccs.append(mcc)\n tps.append(tp)\n tns.append(tn), fps.append(fp), fns.append(fn)\n\n # print & store validation metrics\n print(f\"VALIDATION METRICS\")\n acc, mcc, tp, tn, fp, fn = self.print_metrics(y_valid, valid_preds)\n accs.append(acc)\n mccs.append(mcc)\n tps.append(tp)\n tns.append(tn), fps.append(fp), fns.append(fn)\n print(\"\\n\\n\")\n\n # save model\n joblib.dump(\n model, f\"../models/{model_name}_{self.field}_{self.vec_type}.joblib\"\n )\n index = pd.MultiIndex.from_product(\n [[\"naive_bayes\", \"nbsvm\", \"logistic_regression\"], [\"Train\", \"Valid\"]],\n names=[\"Split\", \"Model\"],\n )\n metric_df = pd.DataFrame.from_dict(\n {\"ACC\": accs, \"MCC\": mccs, \"TP\": tps, \"TN\": tns, \"FP\": fps, \"FN\": fns},\n )\n metric_df.index = index\n print(metric_df.to_markdown())\n\n\nif __name__ == \"__main__\":\n path = \"../data/processed/processed_food_reviews.csv\"\n for vec_type in [\"count\", \"tfidf\"]:\n for field in [\"Summary\", \"Text\"]:\n classifier = TrainClassifier(field=field, vec_type=vec_type)\n classifier.print_configs()\n classifier.train(path)\n print(\"-\" * 80, end=\"\\n\")\n print(\">\" * 80, end=\"\\n\")\n","repo_name":"adimyth/customer_sentiment_analysis","sub_path":"scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22062081462","text":"from setuptools import setup\n\n\nwith open('requirements.txt') as f:\n requirements = f.read().splitlines()\n\n\nwith open('requirements.txt') as f:\n required = f.read().splitlines()\n\nsetup(\n name=\"smaystr-crawling-platform\",\n version=\"0.0.1\",\n install_requires=required,\n packages=[\"app\"],\n url=\"\",\n download_url=\"\",\n description=\"\",\n long_description=\"\",\n license=\"\",\n keywords=\"\",\n classifiers=[\n \"Intended Audience :: Developers\",\n \"Programming Language :: Python\",\n \"Natural Language :: English\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3.7\",\n ],\n)\n\n","repo_name":"smaystr/dtk_modus","sub_path":"data_crawling/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27634908642","text":"import scrapy\n\nfrom pep_parse.items import PepParseItem\nfrom pep_parse.settings import SPIDER_NAME, ALLOWED_DOMAINS, START_URLS\n\n\nclass PepSpider(scrapy.Spider):\n name = SPIDER_NAME\n allowed_domains = ALLOWED_DOMAINS\n start_urls = START_URLS\n\n def parse(self, response):\n rows = response.css('section#numerical-index tbody tr')\n for row in rows:\n pep_link = row.css('a::attr(href)').get()\n yield response.follow(pep_link, callback=self.parse_pep)\n\n def parse_pep(self, response):\n number, name = response.css('h1.page-title::text').get().split(' – ')\n data = {\n 'number': int(number.replace('PEP ', '')),\n 'name': name,\n 'status': response.css('dd abbr::text').get()\n }\n yield PepParseItem(data)\n","repo_name":"bvsvrvb/praktikum-scrapy-parser","sub_path":"pep_parse/spiders/pep.py","file_name":"pep.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"44023319388","text":"from __future__ import print_function\n\nimport argparse\nimport logging\nimport random\nimport time\nimport os\nimport numpy as np\n\nfrom carla.client import make_carla_client\nfrom carla.sensor import Camera, Lidar\nfrom carla.settings import CarlaSettings\nfrom carla.tcp import TCPConnectionError\nfrom carla.util import print_over_same_line\nfrom carla.transform import Transform,Scale\n\n\ndef makeadir(filename):\n dirname = os.path.dirname(filename)\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n\n\n\n\ndef run_carla_client(args):\n # Here we will run 3 episodes with 300 frames each.\n number_of_episodes = 1\n frames_per_episode =600\n\n # We assume the CARLA server is already waiting for a client to connect at\n # host:port. To create a connection we can use the `make_carla_client`\n # context manager, it creates a CARLA client object and starts the\n # connection. It will throw an exception if something goes wrong. The\n # context manager makes sure the connection is always cleaned up on exit.\n with make_carla_client(args.host, args.port) as client:\n print('CarlaClient connected')\n\n for episode in range(0, number_of_episodes):\n # Start a new episode.\n\n\n\n if 1:\n\n # Create a CarlaSettings object. This object is a wrapper around\n # the CarlaSettings.ini file. Here we set the configuration we\n # want for the new episode.\n settings = CarlaSettings()\n settings.set(\n SynchronousMode=True,\n SendNonPlayerAgentsInfo=True,\n NumberOfVehicles=0,\n NumberOfPedestrians=0,\n WeatherId=1,\n QualityLevel='low')\n settings.randomize_seeds()\n\n # Now we want to add a couple of cameras to the player vehicle.\n # We will collect the images produced by these cameras every\n # frame.\n\n\n\n #add camera easily,ver1.0\n Cameralist={}\n Lidarlist={}\n\n\n\n def add_camera(cameraname,pitch,yaw,roll):\n\n def Add_camera(full_name,pitch,yaw,roll,type):\n camera0 = Camera(full_name)\n # Set image resolution in pixels.\n camera0.set_image_size(1024,1024)\n # Set its position relative to the car in meters.\n camera0.set_position(5,0,4)\n camera0.set_rotation(pitch, yaw, roll)\n camera0.set_PostProcessing(type)\n settings.add_sensor(camera0)\n Cameralist[full_name]=camera0\n\n\n Add_camera(os.path.join('RGB',cameraname),pitch,yaw,roll,'None')\n Add_camera(os.path.join('Semantic',cameraname),pitch,yaw,roll,'SemanticSegmentation')\n # Add_camera(os.path.join('Depth',cameraname),pitch,yaw,roll,'Depth')\n\n instrincs_name = args.out_filename_format.format('pose/instrincs/'+cameraname , 0)\n\n cam_instrincs=Cameralist[os.path.join('RGB',cameraname)].get_instrincs()\n makeadir(instrincs_name)\n np.savetxt(instrincs_name, cam_instrincs)\n\n\n add_camera('Camera_F0',0,0,0)\n add_camera('Camera_F1',-90,0,0)\n add_camera('Camera_L0',0,-90,0)\n add_camera('Camera_R0',0,90,0)\n add_camera('Camera_B0',0,180,0)\n # add_camera('Camera_A',0,45,0)\n # add_camera('Camera_B',0,135,0)\n # add_camera('Camera_C',0,-45,0)\n # add_camera('Camera_D',0,-135,0)\n #add_camera('Camera_F1',0,0,0)\n #add_camera('Camera_L1',0,-90, 0)\n #add_camera('Camera_R1',0,90, 0)\n\n\n\n\n\n\n\n\n #\n #\n # # Let's add another camera producing ground-truth depth.\n # camera1 = Camera('CameraDepth', PostProcessing='Depth')\n # camera1.set_image_size(800, 600)\n # camera1.set_position(0.30, 0, 1.30)\n # settings.add_sensor(camera1)\n\n Lidarname='Lidar/Lidar64_0'\n lidar = Lidar(Lidarname)\n lidar.set_position(5,0,4)\n lidar.set_rotation(-80, 0, 0)\n lidar.set(\n Channels=64,\n Range=30,\n PointsPerSecond=2000000,\n RotationFrequency=10,\n UpperFovLimit=30,\n LowerFovLimit=-30)\n settings.add_sensor(lidar)\n Lidarlist[Lidarname]=lidar\n\n\n Lidarname = 'Lidar/Lidar64_1'\n lidar = Lidar(Lidarname)\n lidar.set_position(5, 0, 4) #(5,0,4)\n lidar.set_rotation(0, 0, 0)\n lidar.set(\n Channels=64,\n Range=30,\n PointsPerSecond=2000000,\n RotationFrequency=10,\n UpperFovLimit=30,\n LowerFovLimit=-30)\n settings.add_sensor(lidar)\n Lidarlist[Lidarname] = lidar\n\n\n\n\n else:\n\n # Alternatively, we can load these settings from a file.\n with open(args.settings_filepath, 'r') as fp:\n settings = fp.read()\n\n # Now we load these settings into the server. The server replies\n # with a scene description containing the available start spots for\n # the player. Here we can provide a CarlaSettings object or a\n # CarlaSettings.ini file as string.\n scene = client.load_settings(settings)\n\n # Choose one player start at random.\n number_of_player_starts = len(scene.player_start_spots)\n #player_start = random.randint(0, max(0, number_of_player_starts - 1))\n player_start = 133\n\n # Notify the server that we want to start the episode at the\n # player_start index. This function blocks until the server is ready\n # to start the episode.\n print('Starting new episode at %r...' % scene.map_name)\n client.start_episode(player_start)\n\n\n\n\n \n \n \n # Iterate every frame in the episode.\n for frame in range(0, frames_per_episode):\n\n # Read the data produced by the server this frame.\n measurements, sensor_data = client.read_data()\n\n # Print some of the measurements.\n if frame>=50:\n frame-=50\n posefilename = args.out_filename_format.format('pose/txt/Lidar', frame)\n print_and_save_measurements(measurements,posefilename)\n # Save the images to disk if requested.\n if args.save_images_to_disk:\n for name, measurement in sensor_data.items():\n extrincs_name = args.out_filename_format.format('pose/extrincs/'+name.split('/')[1], frame)\n makeadir(extrincs_name)\n filename = args.out_filename_format.format('Data/'+name, frame)\n\n\n if 'Lidar' in name:\n world_transform = Transform(\n measurements.player_measurements.transform,'l'\n )\n sensor_to_car_transform=Lidarlist[name].get_unreal_transform()\n else:\n world_transform = Transform(\n measurements.player_measurements.transform, 'c'\n )\n sensor_to_car_transform = Cameralist[name].get_unreal_transform()\n\n Camera_extrincs=Transform(Scale(x=-1))*world_transform*sensor_to_car_transform\n np.savetxt(extrincs_name,Camera_extrincs.matrix)\n\n\n if 'Lidar' in name:\n measurement.apply_transform(Camera_extrincs)\n\n\n measurement.save_to_disk(filename)\n\n\n\n\n # We can access the encoded data of a given image as numpy\n # array using its \"data\" property. For instance, to get the\n # depth value (normalized) at pixel X, Y\n #\n # depth_array = sensor_data['CameraDepth'].data\n # value_at_pixel = depth_array[Y, X]\n #\n\n # Now we have to send the instructions to control the vehicle.\n # If we are in synchronous mode the server will pause the\n # simulation until we send this control.\n\n if not args.autopilot:\n\n client.send_control(\n steer=random.uniform(-1.0, 1.0),\n throttle=0.5,\n brake=0.0,\n hand_brake=False,\n reverse=False)\n\n else:\n\n # Together with the measurements, the server has sent the\n # control that the in-game autopilot would do this frame. We\n # can enable autopilot by sending back this control to the\n # server. We can modify it if wanted, here for instance we\n # will add some noise to the steer.\n\n control = measurements.player_measurements.autopilot_control\n #control.steer += random.uniform(-0.1, 0.1)\n control.throttle = 0.4\n client.send_control(control)\n\n\ndef print_and_save_measurements(measurements,filename):\n folder = os.path.dirname(filename)\n if not os.path.isdir(folder):\n os.makedirs(folder)\n\n filename=filename+'.txt'\n with open(filename,'w') as fp:\n\n number_of_agents = len(measurements.non_player_agents)\n player_measurements = measurements.player_measurements\n message = 'Vehicle at ({pos_x:.1f}, {pos_y:.1f}), '\n message += 'rotation:{pitch:.2f},{roll:.2f},{yaw:.2f} '\n message += '{speed:.0f} km/h, '\n message += 'Collision: {{vehicles={col_cars:.0f}, pedestrians={col_ped:.0f}, other={col_other:.0f}}}, '\n message += '{other_lane:.0f}% other lane, {offroad:.0f}% off-road, '\n message += '({agents_num:d} non-player agents in the scene)'\n message = message.format(\n pos_x=-player_measurements.transform.location.x,\n pos_y=player_measurements.transform.location.y,\n pitch=player_measurements.transform.rotation.pitch,\n roll=player_measurements.transform.rotation.roll,\n yaw=player_measurements.transform.rotation.yaw,\n speed=player_measurements.forward_speed * 3.6, # m/s -> km/h\n col_cars=player_measurements.collision_vehicles,\n col_ped=player_measurements.collision_pedestrians,\n col_other=player_measurements.collision_other,\n other_lane=100 * player_measurements.intersection_otherlane,\n offroad=100 * player_measurements.intersection_offroad,\n agents_num=number_of_agents)\n print_over_same_line(message)\n\n\n write_message = 'x:{pos_x:.2f}\\ny:{pos_y:.2f}\\nz:{pos_z:.2f}\\npitch:{pitch:.2f}\\nroll:{roll:.2f}\\nyaw:{yaw:.2f}\\n'\n write_message = write_message.format(\n pos_x=-player_measurements.transform.location.x,\n pos_y=player_measurements.transform.location.y,\n pos_z=player_measurements.transform.location.z,\n pitch=player_measurements.transform.rotation.pitch,\n roll=player_measurements.transform.rotation.roll,\n yaw=player_measurements.transform.rotation.yaw,\n )\n fp.write(write_message)\n\n\ndef main():\n argparser = argparse.ArgumentParser(description=__doc__)\n argparser.add_argument(\n '-v', '--verbose',\n action='store_true',\n dest='debug',\n help='print debug information')\n argparser.add_argument(\n '--host',\n metavar='H',\n default='localhost',\n help='IP of the host server (default: localhost)')\n argparser.add_argument(\n '-p', '--port',\n metavar='P',\n default=2000,\n type=int,\n help='TCP port to listen to (default: 2000)')\n argparser.add_argument(\n '-a', '--autopilot',\n action='store_true',\n help='enable autopilot')\n argparser.add_argument(\n '-l', '--lidar',\n action='store_true',\n help='enable Lidar')\n argparser.add_argument(\n '-q', '--quality-level',\n choices=['Low', 'Epic'],\n type=lambda s: s.title(),\n default='low',\n help='graphics quality level, a lower level makes the simulation run considerably faster.')\n argparser.add_argument(\n '-i', '--images-to-disk',\n action='store_true',\n dest='save_images_to_disk',\n help='save images (and Lidar data if active) to disk')\n argparser.add_argument(\n '-c', '--carla-settings',\n metavar='PATH',\n dest='settings_filepath',\n default='',\n help='Path to a \"CarlaSettings.ini\" file')\n\n args = argparser.parse_args()\n\n log_level = logging.DEBUG if args.debug else logging.INFO\n logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)\n\n logging.info('listening to server %s:%s', args.host, args.port)\n\n args.out_filename_format = 'Data/out_lidar_vedio_test/episode_18/{:s}/{:0>6d}'\n\n while True:\n try:\n\n run_carla_client(args)\n\n print('Done.')\n return\n\n except TCPConnectionError as error:\n logging.error(error)\n time.sleep(1)\n\n\nif __name__ == '__main__':\n\n try:\n main()\n except KeyboardInterrupt:\n print('\\nCancelled by user. Bye!')\n","repo_name":"visg-robox/2.5D-semantic","sub_path":"dataset_scipt/carla_scipt/data_simulate/getmydata.py","file_name":"getmydata.py","file_ext":"py","file_size_in_byte":14137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25335658130","text":"# Runtime: 124 ms, faster than 82.13% of Python3 online submissions for Range Sum Query 2D - Immutable.\r\n# Memory Usage: 16.7 MB, less than 16.67% of Python3 online submissions for Range Sum Query 2D - Immutable.\r\nclass NumMatrix:\r\n\r\n def __init__(self, matrix: List[List[int]]):\r\n if not matrix:\r\n return\r\n len_row, len_col = len(matrix), len(matrix[0])\r\n self.mat = [[0] * (len_col + 1) for _ in range(len_row + 1)]\r\n for row in range(1, len_row + 1):\r\n for col in range(1, len_col + 1):\r\n self.mat[row][col] = matrix[row - 1][col - 1] + self.mat[row][col - 1] + self.mat[row - 1][col] - self.mat[row - 1][col - 1]\r\n\r\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\r\n return self.mat[row2 + 1][col2 + 1] - self.mat[row1][col2 + 1] - self.mat[row2 + 1][col1] + self.mat[row1][col1]\r\n\r\n\r\n# Your NumMatrix object will be instantiated and called as such:\r\n# obj = NumMatrix(matrix)\r\n# param_1 = obj.sumRegion(row1,col1,row2,col2)\r\n","repo_name":"daidai21/Leetcode","sub_path":"Algorithms/Python3.x/304-Range_Sum_Query_2D_-_Immutable.py","file_name":"304-Range_Sum_Query_2D_-_Immutable.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"42811705809","text":"from typing import List\n\n\nclass Solution:\n def isPerfectSquare(self, num: int) -> bool:\n i = 1\n while i <= num // i:\n if i * i == num:\n return True\n i += 1\n return False\n\n\nif __name__ == \"__main__\":\n s = Solution()\n result = s.isPerfectSquare(16)\n print(result)\n","repo_name":"kenwoov/PlayLeetCode","sub_path":"Algorithms/Easy/367. Valid Perfect Square/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36970481015","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 7 17:44:57 2019\n\n@author: robin\n\"\"\"\n\nimport os\nfrom random import sample\nfrom shutil import copy\nimport numpy as np\n\n\ndef partition_title_list(list_in, tronc = 0, is_test_set = False):\n ''' Partition the curves files names into train, test and vaidation sets. Be careful that it shuffles the original list\n list_in (list): The original list of files names to partition\n tronc (int): If positive keep only elements of the list\n is_test_set (bool): whether or not to create a test set\n ------------------------------------------------------------------------\n returns (list of list): list_in partitioned in n random lists\n '''\n assert type(list_in) == list\n \n n = 4 # Split the list in four parts: the first two parts (half of the files names) constitute the training set. The other two parts represent the valid and train set\n \n tronc_list = sample(list_in, tronc) if tronc > 0 else list_in\n while len(tronc_list) % n != 0: # To avoid lists of different size pad the sequences with 'None' strings\n tronc_list.append('None')\n four_splitted_list = [tronc_list[i::n] for i in range(n)] \n files_partition = {}\n if is_test_set:\n files_partition['train'] = four_splitted_list[0] + four_splitted_list[1]\n files_partition['test'] = four_splitted_list[2]\n files_partition['valid'] = four_splitted_list[3]\n else:\n files_partition['train'] = four_splitted_list[0] + four_splitted_list[1] + four_splitted_list[2]\n files_partition['test'] = []\n files_partition['valid'] = four_splitted_list[3]\n return files_partition\n\n \ndef imgs_train_test_valid_split(root_dir, balanced = False, is_test_set = False):\n ''' Split the curves contained in the subdirectory of the into 3 folders: train, test and validation folders\n For the moment, I sample the same number of curves for each class (equal to the lowest umber of curves available)\n root_dir (str): The path to the folder containing the 4 folders: all, train, test and validation set (If everithing is ok root_directory is the 'curves' directory)\n ---------------------------------------------------------------------------------------------------------------\n returns (None): The data rightly split in three sub-datasets stored on hard disk\n '''\n curves_types = [f for f in os.listdir(root_dir + '/all')]\n\n if balanced:\n min_nb_curves = min([len(os.listdir(root_dir + '/all/' + ctype + '/' + cclass)) for ctype in curves_types for cclass in os.listdir(root_dir + '/all/' + ctype)]) \n min_nb_curves -= min_nb_curves % 4 # Ensures that the all the plankton types have the same number of observations\n \n else: # Extract all available curves\n min_nb_curves = 0 #np.inf\n \n for ctype in curves_types:\n print(ctype)\n cluster_classes = [f for f in os.listdir(root_dir + '/all/' + ctype)]\n for cclass in cluster_classes:\n curves_files = [f for f in os.listdir(root_dir + '/all/' + ctype + '/' + cclass)]\n\n files_partition = partition_title_list(curves_files, min_nb_curves, is_test_set)\n for folder, files in files_partition.items():\n for file in files:\n if file != 'None': \n copy(root_dir + '/all/' + ctype + '/' + cclass + '/' + file, root_dir + '/' + folder + '/' + ctype + '/' + cclass + '/' + file)\n \ndef nb_available_imgs(root_dir):\n ''' Compute the number of available images in the folders '''\n # Assuming that all 5 ctypes repos have the same number of observations\n nb_train = np.sum([len(os.listdir(root_dir + '/train/Curvature/' + cclass)) for cclass in os.listdir(root_dir + '/train/Curvature')]) \n nb_test = np.sum([len(os.listdir(root_dir + '/test/Curvature/' + cclass)) for cclass in os.listdir(root_dir + '/test/Curvature')]) \n nb_valid = np.sum([len(os.listdir(root_dir + '/valid/Curvature/' + cclass)) for cclass in os.listdir(root_dir + '/valid/Curvature')]) \n\n return nb_train, nb_test, nb_valid\n\n# Write a spec to ensure ok to fit NN on the curves: Same number of pic in each ctype subfolders ","repo_name":"RobeeF/planktonPipeline","sub_path":"extract_Pulse_curves/cnn_functions.py","file_name":"cnn_functions.py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34550341814","text":"try:\n import gi\n\n gi.require_version('Aravis', '0.4')\n from gi.repository import Aravis\n import numpy as np\n from PIL import Image\n import time\n\nexcept ImportError as importError:\n print(importError)\n\nclass Gige_camera():\n def __init__(self, name=None, camResolution=None, frameRate=15, mode = 'mono8' ):\n '''\n\t\t:param name: datatype: string, optional\n\t\t:param camResolution: datatype: tuple, optional\n\t\t:param frameRate: data type: int, optional\n\t\t'''\n self._name = name if (type(name) == str or name == None) else str(name)\n self._camResolution = camResolution if type(camResolution) == tuple else None\n self._frameRate = frameRate if type(frameRate) == int else int(frameRate)\n self.threshTimeTrigExitDanger =0.0005\n try:\n if name is None:\n self._camera = Aravis.Camera.new()\n\n else:\n self._camera = Aravis.Camera.new(name)\n\n sensorSize = self._camera.get_sensor_size()\n if self._camResolution is None or self._camResolution[0] > sensorSize[0] or self._camResolution[1] > \\\n sensorSize[1]:\n self._camResolution = (sensorSize[0], sensorSize[1])\n print('name: ', name, '\\n', 'cameraResolution: ', self._camResolution[0], 'x', self._camResolution[\n 1], '\\n', 'frameRate: ', frameRate)\n self._CameraInit(self._camera, self._camResolution, frameRate, mode)\n except Exception as error:\n if str(error) == 'constructor returned NULL':\n print('no camera found')\n else:\n print(error)\n\n def _CameraInit(self,a,b,c,d):\n try:\n camResolution=(320,480)\n frameRate=15\n mode='mono8'\n camera=self._camera\n camera.set_region(x=0, y=0, width=camResolution[0], height=camResolution[1])\n camera.set_frame_rate(frameRate)\n if mode == 'mono8':\n try:\n camera.set_pixel_format(Aravis.PIXEL_FORMAT_MONO_8)\n except Exception as error:\n print(error)\n elif mode == 'BRG8':\n try:\n camera.set_pixel_format(Aravis.PIXEL_FORMAT_BAYER_RG_8)\n except Exception as error:\n print(error)\n else:\n pass\n self._payload = camera.get_payload()\n self._stream = camera.create_stream()\n self._stream.push_buffer(Aravis.Buffer.new_allocate(self._payload))\n camera.start_acquisition()\n print(\"Camera vendor : %s\" % (camera.get_vendor_name()))\n except Exception as error:\n print(error)\n\n\n def Capture(self):\n try:\n self._camera.software_trigger()\n tic = time.time()\n print(\"waiting for pop\")\n while True:\n print(\"hi\")\n imageBuffer = self._stream.pop_buffer()\n\n print(imageBuffer)\n if imageBuffer:\n break\n elif (time.time() - tic) > self.threshTimeTrigExitDanger:\n break\n print('pop done')\n if imageBuffer:\n self._stream.push_buffer(imageBuffer)\n dataFromBuffer = imageBuffer.get_data()\n print(dataFromBuffer)\n if imageBuffer:\n print(\"test 1\")\n ImageIpl = Image.frombytes('L', (self._camResolution[0], self._camResolution[1]), dataFromBuffer, 'raw')\n print(ImageIpl)\n imageArray = np.asarray(ImageIpl)\n imgBayer = imageArray\n cv2.imwrite('fkjshfs.jpg', imgBayer)\n print(\"image saved\")\n cv2.waitKey(0)\n return True, imgBayer\n\n else:\n return False, None\n except Exception as error:\n return False, error\n\n\n def SetTriggerMode(self, mode=\"Software\"):\n try:\n if mode == 'software':\n self._camera.set_trigger(\"Software\")\n elif mode == 'external':\n self._camera.set_trigger(\"Line1\")\n else:\n self._camera.set_trigger(\"Any\")\n print ('mode should either \\'software\\' or \\'external\\'.',)\n print ('current Triggering Mode: ', self._camera.get_trigger_source())\n except Exception as error:\n print (error)\n\n\n def SetExposure(self, exposure=None):\n if exposure == None:\n print ('Exposure time: ', self._camera.get_exposure_time())\n return\n try:\n self._camera.set_exposure_time(exposure)\n print ('Exposure time: ', self._camera.get_exposure_time())\n except Exception as error:\n print (error)\ng=Gige_camera()\ng.Capture()\n#\n#name=None, camResolution=None, frameRate=15, mode = 'BRG8'\n\n#\n# camera, camResolution, frameRate, mode\n\n","repo_name":"darshil97/python","sub_path":"gigeCamera.py","file_name":"gigeCamera.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5479148661","text":"#!/usr/bin/env python2.4\n\"\"\"\nReturns all positions of a maf with any pwm score > threshold\nThe positions are projected onto human coordinates\n\"\"\"\n\nimport sys\n\nfrom bx import intervals\nfrom bx.align import maf as align_maf\nfrom bx.pwm.pwm_score_maf import MafMotifScorer\n\n\ndef isnan(x):\n return not x == x\n\n\ndef main():\n if len(sys.argv) < 5:\n print(\"%s bedfile inmaf spec1,spec2,... string [string2,...]\" % sys.argv[0], file=sys.stderr)\n sys.exit(0)\n\n # read in intervals\n regions = {}\n for line in open(sys.argv[1]):\n if line.startswith(\"#\"):\n continue\n fields = line.strip().split()\n chrom, start, end = fields[0], int(fields[1]), int(fields[2])\n try:\n name = fields[3]\n except IndexError:\n name = None\n if chrom not in regions:\n regions[chrom] = intervals.Intersecter()\n regions[chrom].add(start, end, name)\n\n motif_strings = sys.argv[4:]\n if not isinstance(motif_strings, list):\n motif_strings = [motif_strings]\n inmaf = open(sys.argv[2])\n threshold = 0.5\n\n species = []\n\n for sp in sys.argv[3].split(\",\"):\n species.append(sp)\n\n for maf in align_maf.Reader(inmaf):\n mafchrom = maf.components[0].src.split(\".\")[1]\n mafstart = maf.components[0].start\n mafend = maf.components[0].end\n reftext = maf.components[0].text\n r = regions[mafchrom].find(mafstart, mafend)\n if mafchrom not in regions or len(r) == 0:\n continue\n\n # maf block scores for each matrix\n for scoremax, width, headers in MafMotifScorer(species, maf, motif_strings):\n blocklength = width\n mafsrc, mafstart, mafend = headers[0]\n mafchrom = mafsrc.split(\".\")[1]\n\n # lists of scores for each position in scoremax\n for mx_name, mx in scoremax.items():\n for offset in range(blocklength):\n # scan all species with threshold\n for i in range(len(species)):\n if mx[i][offset] > threshold:\n refstart = mafstart + offset - reftext.count(\"-\", 0, offset)\n refend = refstart + len(mx_name)\n\n data = \" \".join([\"%.2f\" % mx[x][offset] for x in range(len(species))])\n # quote the motif\n r = regions[mafchrom].find(refstart, refend)\n if mafchrom in regions and len(r) > 0:\n region_label = r[0].value\n else:\n # region_label = 0\n continue\n v_name = mx_name.replace(\" \", \"_\")\n print(mafchrom, refstart, refend, region_label, v_name, data)\n break\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bxlab/bx-python","sub_path":"lib/bx/pwm/bed_score_aligned_string.py","file_name":"bed_score_aligned_string.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"3"}
+{"seq_id":"334052917","text":"import torch\nimport torch.optim as optim\nimport os\nimport time\nimport utils.evaluate as evaluate\nimport models.resnet as resnet\nfrom scipy.linalg import hadamard\nfrom loguru import logger\nfrom models.adsh_loss import ADSH_Loss\nfrom data.data_loader import sample_dataloader\nfrom utils import AverageMeter\nfrom utils.tools import compute_result, CalcTopMap\nfrom tqdm import tqdm\nimport random\nimport numpy as np\n\n\nclass CSQLoss(torch.nn.Module):\n def __init__(self, args, bit):\n super(CSQLoss, self).__init__()\n self.is_single_label = args.dataset not in {\"nuswide_21\", \"nus-widezs\", \"coco\"}\n print(\"is_single_label\", self.is_single_label)\n if bit == 16 or bit == 32 or bit == 64:\n print(\"use hadamard martrix to generate hash centers\")\n self.hash_targets = self.get_hash_targets(args.num_classes, bit).to(args.device)\n else:\n print(\"use bernoulli distribution to generate hash centers\")\n self.hash_targets = self.get_hash_targets_by_B(args.num_classes, bit).to(args.device)\n self.multi_label_random_center = torch.randint(2, (bit,)).float().to(args.device)\n self.criterion = torch.nn.BCELoss().to(args.device)\n self.lambd = args.lambd\n\n def forward(self, u, y, ind):\n # u = u.tanh()\n hash_center = self.label2center(y)\n center_loss = self.criterion(0.5 * (u + 1), 0.5 * (hash_center + 1))\n\n Q_loss = (u.abs() - 1).pow(2).mean()\n return center_loss + self.lambd * Q_loss\n\n def label2center(self, y):\n if self.is_single_label:\n hash_center = self.hash_targets[y.argmax(axis=1)]\n else:\n # to get sign no need to use mean, use sum here\n center_sum = y @ self.hash_targets\n random_center = self.multi_label_random_center.repeat(center_sum.shape[0], 1)\n center_sum[center_sum == 0] = random_center[center_sum == 0]\n hash_center = 2 * (center_sum > 0).float() - 1\n return hash_center\n\n #通过伯努利分布生成hash center\n def get_hash_targets_by_B(self, n_class, bit):\n\n hash_targets = torch.zeros((n_class, bit))\n for k in range(20):\n for index in range(n_class):\n\n ones = torch.ones(bit)\n # Bernouli distribution\n sa = random.sample(list(range(bit)), bit // 2)\n ones[sa] = -1\n hash_targets[index] = ones\n # to find average/min pairwise distance\n c = []\n for i in range(n_class):\n for j in range(n_class):\n if i < j:\n TF = sum(hash_targets[i] != hash_targets[j])\n c.append(TF)\n c = np.array(c)\n # choose min(c) in the range of K/4 to K/3\n # see in https://github.com/yuanli2333/Hadamard-Matrix-for-hashing/issues/1\n # but it is hard when bit is small\n if c.min() > bit / 4 and c.mean() >= bit / 2:\n print(c.min(), c.mean())\n break\n return hash_targets\n # use algorithm 1 to generate hash centers\n def get_hash_targets(self, n_class, bit):\n H_K = hadamard(bit)\n H_2K = np.concatenate((H_K, -H_K), 0)\n hash_targets = torch.from_numpy(H_2K[:n_class]).float()\n\n if H_2K.shape[0] < n_class:\n hash_targets.resize_(n_class, bit)\n for k in range(20):\n for index in range(H_2K.shape[0], n_class):\n #前2k个hash center通过hadmard matrix生成\n ones = torch.ones(bit)\n # Bernouli distribution\n sa = random.sample(list(range(bit)), bit // 2)\n ones[sa] = -1\n hash_targets[index] = ones\n # to find average/min pairwise distance\n c = []\n for i in range(n_class):\n for j in range(n_class):\n if i < j:\n TF = sum(hash_targets[i] != hash_targets[j])\n c.append(TF)\n c = np.array(c)\n\n # choose min(c) in the range of K/4 to K/3\n # see in https://github.com/yuanli2333/Hadamard-Matrix-for-hashing/issues/1\n # but it is hard when bit is small\n if c.min() > bit / 4 and c.mean() >= bit / 2:\n print(c.min(), c.mean())\n break\n return hash_targets\n\n\n\ndef train(\n test_loader,\n train_loader,\n database_loader,\n query_loader_zs,\n database_loader_zs,\n code_length,\n args,\n):\n \"\"\"\n Training model.\n\n Args\n test_loader, database_loader(torch.utils.data.dataloader.DataLoader): Data loader.\n code_length(int): Hashing code length.\n args.device(torch.args.device): GPU or CPU.\n lr(float): Learning rate.\n Returns\n mAP(float): Mean Average Precision.\n \"\"\"\n # Initialization\n # model = alexnet.load_model(code_length).to(args.device)\n\n\n device = args.device\n args.num_train = len(train_loader.dataset)\n # args.step_continuation = 20\n print(\"csq for zero shot\")\n\n model = resnet.resnet50(pretrained=args.pretrain, num_classes=code_length)\n print('backbone is resnet50')\n\n\n model.to(device)\n if args.optim == 'SGD':\n optimizer = optim.SGD(model.parameters(), lr=args.lr, weight_decay=args.wd, momentum=args.momen, nesterov=args.nesterov)\n elif args.optim == 'Adam':\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd)\n elif args.optim == 'AdamW':\n optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd)\n scheduler = optim.lr_scheduler.MultiStepLR(optimizer, args.lr_step)\n\n criterion = CSQLoss(args, code_length)\n\n losses = AverageMeter()\n start = time.time()\n best_mAP = 0\n corresponding_mAP_all = 0\n corresponding_zs_mAP = 0\n corresponding_zs_mAP_all = 0\n\n\n\n print(\"start training\")#*******************************************wp\n\n for it in range(args.max_iter):\n iter_start = time.time()\n # Sample training data for cnn learning\n train_dataloader, sample_index = sample_dataloader(train_loader, args.num_samples, args.batch_size, args.root, args.dataset)\n\n\n for epoch in range(args.max_epoch):\n # epoch_start = time.time()\n\n # criterion.scale = (epoch // args.step_continuation + 1) ** 0.5\n\n model.train()\n losses.reset()\n pbar = tqdm(enumerate(train_dataloader),total=len(train_dataloader),ncols = 50)\n # print((len(train_dataloader)))\n for batch, (data, targets, index) in pbar:\n # for batch, (data, targets, index) in enumerate(train_dataloader):\n # print(targets.shape)\n data, targets, index = data.to(device), targets.to(device), index.to(device)\n optimizer.zero_grad()\n u = model(data)\n loss = criterion(u, targets.float(), index)\n losses.update(loss.item())\n loss.backward()\n optimizer.step()\n logger.info('[epoch:{}/{}][loss:{:.6f}]'.format(epoch+1, args.max_epoch, losses.avg))\n\n scheduler.step()\n logger.info('[iter:{}/{}][iter_time:{:.2f}]'.format(it+1, args.max_iter,\n time.time()-iter_start))\n if (it < 35 and (it + 1) % args.val_freq == 0) or (it >= 35 and (it + 1) % 1 == 0):\n # if (it + 1) % 1 == 0 :\n\n query_code = generate_code(model, test_loader, code_length, args.device)\n query_targets = test_loader.dataset.get_onehot_targets()\n B = generate_code(model, database_loader, code_length, args.device)\n db_label= database_loader.dataset.get_onehot_targets()\n # if args.num_zs != 0:\n zs_test_binary = generate_code(model, query_loader_zs, code_length, args.device)\n zs_test_label = query_loader_zs.dataset.get_onehot_targets()\n\n zs_db_binary = generate_code(model, database_loader_zs, code_length, args.device)\n zs_db_label = database_loader_zs.dataset.get_onehot_targets()\n\n db_all_binary = torch.cat((B, zs_db_binary), 0)\n db_all_label = torch.cat((db_label, zs_db_label), 0)\n\n mAP = evaluate.mean_average_precision(\n query_code.to(args.device),\n B,\n query_targets[:,:args.num_classes].to(args.device),\n db_label[:,:args.num_classes].to(args.device),\n args.device,\n args.topk,\n )\n # if args.num_zs != 0:\n mAP_all = evaluate.mean_average_precision(\n query_code.to(args.device),\n db_all_binary.to(args.device),\n query_targets.to(args.device),\n db_all_label.to(args.device),\n args.device,\n args.topk,\n )\n zs_mAP_all = evaluate.mean_average_precision(\n zs_test_binary.to(args.device),\n db_all_binary.to(args.device),\n zs_test_label.to(args.device),\n db_all_label.to(args.device),\n args.device,\n args.topk,\n )\n zs_mAP = evaluate.mean_average_precision(\n zs_test_binary.to(args.device),\n zs_db_binary.to(args.device),\n zs_test_label.to(args.device),\n zs_db_label.to(args.device),\n args.device,\n args.topk,\n )\n\n\n if mAP > best_mAP:\n best_mAP = mAP\n corresponding_mAP_all = mAP_all\n corresponding_zs_mAP = zs_mAP\n corresponding_zs_mAP_all = zs_mAP_all\n ret_path = os.path.join('checkpoints', args.info, 'best_mAP',str(code_length))\n if not os.path.exists(ret_path):\n os.makedirs(ret_path)\n torch.save(query_code.cpu(), os.path.join(ret_path, 'query_code.t'))\n torch.save(B.cpu(), os.path.join(ret_path, 'database_code.t'))\n torch.save(query_targets.cpu(), os.path.join(ret_path, 'query_targets.t'))\n torch.save(db_label.cpu(), os.path.join(ret_path, 'database_targets.t'))\n torch.save(zs_test_binary.cpu(), os.path.join(ret_path, 'zs_test_binary.t'))\n torch.save(zs_db_binary.cpu(), os.path.join(ret_path, 'zs_db_binary.t'))\n torch.save(zs_test_label.cpu(), os.path.join(ret_path, 'zs_test_label.t'))\n torch.save(zs_db_label.cpu(), os.path.join(ret_path, 'zs_db_label.t'))\n torch.save(model.state_dict(), os.path.join(ret_path, 'model.pkl'))\n model = model.to(args.device)\n logger.info('[iter:{}/{}][code_length:{}][mAP:{:.5f}][mAP_all:{:.5f}][best_mAP:{:.5f}]'.format(it+1, args.max_iter, code_length, mAP,mAP_all ,best_mAP))\n logger.info('[iter:{}/{}][code_length:{}][zs_mAP:{:.5f}][zs_mAP_all:{:.5f}]'.format(it+1, args.max_iter, code_length, zs_mAP, zs_mAP_all))\n\n\n logger.info('[Training time:{:.2f}]'.format(time.time()-start))\n\n\n return best_mAP, corresponding_mAP_all, corresponding_zs_mAP, corresponding_zs_mAP_all\n\n\ndef generate_code(model, dataloader, code_length, device):\n # query_dataloader wp\n \"\"\"\n Generate hash code\n\n Args\n dataloader(torch.utils.data.DataLoader): Data loader.\n code_length(int): Hash code length.\n device(torch.device): Using gpu or cpu.\n\n Returns\n code(torch.Tensor): Hash code.\n \"\"\"\n\n model.eval()\n with torch.no_grad():\n N = len(dataloader.dataset)\n code = torch.zeros([N, code_length]).to(device)\n for data, _, index in dataloader:\n data = data.to(device)\n hash_code = model(data)\n code[index, :] = hash_code.sign()\n\n model.train()\n return code\n","repo_name":"Kso-Ayaka/DSH_Analysis","sub_path":"csq.py","file_name":"csq.py","file_ext":"py","file_size_in_byte":12082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14481655923","text":"import torch\nfrom torch import nn\nimport math\nimport matplotlib.pyplot as plt\n\n# for replication\ntorch.manual_seed(111)\n\n\nclass Discriminator(nn.Module):\n def __init__(self):\n super().__init__()\n self.model = nn.Sequential(\n nn.Linear(2, 256),\n nn.ReLU(),\n nn.Dropout(0.3),\n nn.Linear(256, 128),\n nn.ReLU(),\n nn.Dropout(0.3),\n nn.Linear(128, 64),\n nn.ReLU(),\n nn.Dropout(0.3),\n nn.Linear(64, 1),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n output = self.model(x)\n return output\n\n\nclass Generator(nn.Module):\n def __init__(self):\n super().__init__()\n self.model = nn.Sequential(\n nn.Linear(2, 16),\n nn.ReLU(),\n nn.Linear(16, 32),\n nn.ReLU(),\n nn.Linear(32, 2),\n )\n\n def forward(self, x):\n output = self.model(x)\n return output\n\n\n# create training data - pairs (x1, x2) so that x2 is the sine of x1\n# where x1 is in the interval from 0 to 2π\ntrain_data_length = 1024\ntrain_data = torch.zeros((train_data_length, 2))\ntrain_data[:, 0] = 2 * math.pi * torch.rand(train_data_length)\ntrain_data[:, 1] = torch.sin(train_data[:, 0])\ntrain_labels = torch.zeros(train_data_length)\ntrain_set = [\n (train_data[i], train_labels[i]) for i in range(train_data_length)\n]\n\n# plot training data\nplt.plot(train_data[:, 0], train_data[:, 1], \".\")\n\n# prepare model\nbatch_size = 32\ntrain_loader = torch.utils.data.DataLoader(\n train_set, batch_size=batch_size, shuffle=True\n)\ndiscriminator = Discriminator()\ngenerator = Generator()\nlr = 0.001\nnum_epochs = 300\nloss_function = nn.BCELoss()\n\noptimizer_discriminator = torch.optim.Adam(discriminator.parameters(), lr=lr)\noptimizer_generator = torch.optim.Adam(generator.parameters(), lr=lr)\n\n# train model\nfor epoch in range(num_epochs):\n for n, (real_samples, _) in enumerate(train_loader):\n # Data for training the discriminator\n real_samples_labels = torch.ones((batch_size, 1))\n latent_space_samples = torch.randn((batch_size, 2))\n generated_samples = generator(latent_space_samples)\n generated_samples_labels = torch.zeros((batch_size, 1))\n all_samples = torch.cat((real_samples, generated_samples))\n all_samples_labels = torch.cat(\n (real_samples_labels, generated_samples_labels)\n )\n\n # Training the discriminator\n discriminator.zero_grad()\n output_discriminator = discriminator(all_samples)\n loss_discriminator = loss_function(\n output_discriminator, all_samples_labels)\n loss_discriminator.backward()\n optimizer_discriminator.step()\n\n # Data for training the generator\n latent_space_samples = torch.randn((batch_size, 2))\n\n # Training the generator\n generator.zero_grad()\n generated_samples = generator(latent_space_samples)\n output_discriminator_generated = discriminator(generated_samples)\n loss_generator = loss_function(\n output_discriminator_generated, real_samples_labels\n )\n loss_generator.backward()\n optimizer_generator.step()\n\n # Show loss\n if epoch % 10 == 0 and n == batch_size - 1:\n print(f\"Epoch: {epoch} Loss D.: {loss_discriminator}\")\n print(f\"Epoch: {epoch} Loss G.: {loss_generator}\")\n\n# generate sample\nlatent_space_samples = torch.randn(100, 2)\ngenerated_samples = generator(latent_space_samples)\ngenerated_samples = generated_samples.detach()\nplt.plot(generated_samples[:, 0], generated_samples[:, 1], \".\")\n\n\n\n# inspired by https://realpython.com/generative-adversarial-networks/","repo_name":"agnedil/Portfolio","sub_path":"01-Generative-AI-Prompt-Engineering/GANs/Simple_GAN_PyTorch.py","file_name":"Simple_GAN_PyTorch.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"12619239803","text":"\"\"\"\nExtension of XBlock Validation class to include information for presentation in Studio.\n\"\"\"\nfrom xblock.validation import Validation, ValidationMessage\n\n\nclass StudioValidationMessage(ValidationMessage):\n \"\"\"\n A message containing validation information about an xblock, extended to provide Studio-specific fields.\n \"\"\"\n\n # A special message type indicating that the xblock is not yet configured. This message may be rendered\n # in a different way within Studio.\n NOT_CONFIGURED = \"not-configured\"\n\n TYPES = [ValidationMessage.WARNING, ValidationMessage.ERROR, NOT_CONFIGURED]\n\n def __init__(self, message_type, message_text, action_label=None, action_class=None, action_runtime_event=None):\n \"\"\"\n Create a new message.\n\n Args:\n message_type (str): The type associated with this message. Most be `WARNING` or `ERROR`.\n message_text (unicode): The textual message.\n action_label (unicode): Text to show on a \"fix-up\" action (optional). If present, either `action_class`\n or `action_runtime_event` should be specified.\n action_class (str): A class to link to the \"fix-up\" action (optional). A click handler must be added\n for this class, unless it is \"edit-button\", \"duplicate-button\", or \"delete-button\" (which are all\n handled in general for xblock instances.\n action_runtime_event (str): An event name to be triggered on the xblock client-side runtime when\n the \"fix-up\" action is clicked (optional).\n \"\"\"\n super().__init__(message_type, message_text)\n if action_label is not None:\n if not isinstance(action_label, str):\n raise TypeError(\"Action label must be unicode.\")\n self.action_label = action_label\n if action_class is not None:\n if not isinstance(action_class, str):\n raise TypeError(\"Action class must be a string.\")\n self.action_class = action_class\n if action_runtime_event is not None:\n if not isinstance(action_runtime_event, str):\n raise TypeError(\"Action runtime event must be a string.\")\n self.action_runtime_event = action_runtime_event\n\n def to_json(self):\n \"\"\"\n Convert to a json-serializable representation.\n\n Returns:\n dict: A dict representation that is json-serializable.\n \"\"\"\n serialized = super().to_json()\n if hasattr(self, \"action_label\"):\n serialized[\"action_label\"] = self.action_label\n if hasattr(self, \"action_class\"):\n serialized[\"action_class\"] = self.action_class\n if hasattr(self, \"action_runtime_event\"):\n serialized[\"action_runtime_event\"] = self.action_runtime_event\n return serialized\n\n\nclass StudioValidation(Validation):\n \"\"\"\n Extends `Validation` to add Studio-specific summary message.\n \"\"\"\n\n @classmethod\n def copy(cls, validation):\n \"\"\"\n Copies the `Validation` object to a `StudioValidation` object. This is a shallow copy.\n\n Args:\n validation (Validation): A `Validation` object to be converted to a `StudioValidation` instance.\n\n Returns:\n StudioValidation: A `StudioValidation` instance populated with the messages from supplied\n `Validation` object\n \"\"\"\n if not isinstance(validation, Validation):\n raise TypeError(\"Copy must be called with a Validation instance\")\n studio_validation = cls(validation.xblock_id)\n studio_validation.messages = validation.messages\n return studio_validation\n\n def __init__(self, xblock_id):\n \"\"\"\n Create a `StudioValidation` instance.\n\n Args:\n xblock_id (object): An identification object that must support conversion to unicode.\n \"\"\"\n super().__init__(xblock_id)\n self.summary = None\n\n def set_summary(self, message):\n \"\"\"\n Sets a summary message on this instance. The summary is optional.\n\n Args:\n message (ValidationMessage): A validation message to set as this instance's summary.\n \"\"\"\n if not isinstance(message, ValidationMessage):\n raise TypeError(\"Argument must of type ValidationMessage\")\n self.summary = message\n\n @property\n def empty(self):\n \"\"\"\n Is this object empty (contains no messages and no summary)?\n\n Returns:\n bool: True iff this instance has no validation issues and therefore has no messages or summary.\n \"\"\"\n return super().empty and not self.summary\n\n def to_json(self):\n \"\"\"\n Convert to a json-serializable representation.\n\n Returns:\n dict: A dict representation that is json-serializable.\n \"\"\"\n serialized = super().to_json()\n if self.summary:\n serialized[\"summary\"] = self.summary.to_json()\n return serialized\n","repo_name":"openedx/edx-platform","sub_path":"xmodule/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","stars":6774,"dataset":"github-code","pt":"3"}
+{"seq_id":"25878879260","text":"from tkinter import *\nimport time\nfrom tkinter import messagebox\nimport random\nimport smtplib\nimport getpass\nimport pyaudio\nimport winsound\nimport sys\nimport wave\nimport pyglet\nfrom PIL import ImageTk, Image\n#all music and sound effects coded by Ian and Siddarth\n#gameOver coded by Jared\ndef gameOver():\n frame4.pack_forget()\n global frame5\n frame5 = Frame(newWindow)\n frame5.pack()\n global dragonHealth,playerHealth, turnNumber, entry\n win = \"Congratulations! You defeated the dragon!\"\n lose = \"The dragon burnt you to a crisp and ate you\"\n if (dragonHealth <= 0):\n gLabel = Label(frame5, text = win)\n if (playerHealth <= 0):\n gLabel = Label(frame5, text = lose)\n gLabel.grid(row = 1)\n emailLabel = Label(frame5, text = \"Enter your email if you want the results of your adventure\")\n emailLabel.grid(row = 2)\n myemail = StringVar()\n entry = Entry(frame5, textvariable = myemail)\n entry.grid(row = 2, column = 1)\n sendButton = Button(frame5, text = \"Send Email\", command = textEmail)\n sendButton.grid(row = 1, column =1)\n endLabel = Label(frame5, text = \"If not, thanks for playing!\")\n endLabel.grid(row = 3)\n endButton = Button(frame5, text = \"Exit\", command = Endgame)\n endButton.grid(row = 3, column = 1)\n#coded by Jared\ndef textEmail():\n global head, chest, legs, weapon, userEmail, turnNumber, playerHealth, dragonHealth, userEmail, entry, gold, emailText\n userEmail = entry.get()\n emailText = \"\"\n turnText= str(turnNumber)\n if(dragonHealth <= 0):\n emailText = \"Congratulations on beating the dragon! In order to defeat the dragon, you used your \" + weapon + \". You were wearing the \" + head + \", the \" + chest + \", and the \" + legs + \". You defeated the dragon in \" + turnText + \" turns. You were able to retire with \" + str(gold) + \" gold. Thanks for playing!\"\n if(playerHealth <= 0):\n emailText = \"The dragon bested you this time. Your \" + weapon + \" was unable to save you. You were wearing the \" + head + \", the \" + chest + \", and the \" + legs + \" before the dragon burnt them all to ash. The dragon defeated you in \" + turnText + \" turns. The dragon adds \" + str(gold) + \" gold to its hoard. Thanks for playing!\"\n if (userEmail != \"\"):\n passwordGet()\n#coded by Jared\ndef passwordGet():\n global frame5, passEntry\n frame5.destroy()\n frame6 = Frame(newWindow)\n frame6.pack()\n passText = StringVar()\n passEntry = Entry(frame6,textvariable = passText, show = \"*\")\n passEntry.grid(row = 1, column = 1)\n passLabel = Label(frame6, text = \"Enter your password: \")\n passLabel.grid(row = 1)\n passButton = Button(frame6, text = \"Send the email\", command = sendEmail)\n passButton.grid(row = 1, column = 2)\n#coded by Jared\ndef sendEmail():\n global passEntry, userEmail, emailText\n password = passEntry.get()\n try:\n gameserver = smtplib.SMTP('smtp.gmail.com',587)\n gameserver.ehlo()\n gameserver.starttls()\n gameserver.login( userEmail, password) # the user sends the results to themselves\n gameserver.sendmail( userEmail, userEmail, emailText)\n gameserver.quit()\n except:\n print(\"There was a problem\")\n Endgame()\n #coded by Jared\ndef Endgame():\n newWindow.destroy()\n player.pause()\n#coded by Jared\ndef bossFight():\n frame3.pack_forget()\n goldLabel.pack_forget()\n global frame4\n frame4 = Frame(newWindow)\n frame4.pack()\n dragonImage = Image.open(\"blueEyes.png\")\n dragonImage2 = ImageTk.PhotoImage(dragonImage)\n dragonLabel = Label(frame4, image = dragonImage2)\n dragonLabel.image = dragonImage2\n dragonLabel.grid(row = 0, columnspan = 4)\n global playerHealth, dragonHealth, actionPoints, turnNumber\n playerHealth = 100\n dragonHealth = 200\n actionPoints = 10\n turnNumber = 1\n global healthAmt, healthLabel\n healthAmt = StringVar()\n healthAmt.set(\"Health: \" + str(playerHealth))\n healthLabel = Label(frame4, textvariable = healthAmt)\n healthLabel.grid(row = 1)\n global apAmt, apLabel\n apAmt = StringVar()\n apAmt.set(\"Action Points: \" + str(actionPoints))\n apLabel = Label(frame4, textvariable = apAmt)\n apLabel.grid(row =1, column =1)\n global dHealthAmt, dHealthLabel\n dHealthAmt = StringVar()\n dHealthAmt.set(\"Dragon Health: \" + str(dragonHealth))\n dHealthLabel = Label(frame4, textvariable = dHealthAmt)\n dHealthLabel.grid(row=1, column = 3)\n global turnCount, turnLabel\n turnCount = StringVar()\n turnCount.set(\"Turn Number: \" + str(turnNumber))\n turnLabel = Label(frame4, textvariable = turnCount)\n turnLabel.grid(row = 1, column = 2)\n wAttack = Button(frame4, text = \"Weak Attack\", command = weakAttack)\n wAttack.grid(row = 2)\n sAttack = Button(frame4, text = \"Strong Attack\", command = strongAttack)\n sAttack.grid(row = 2, column = 1)\n spAttack = Button(frame4, text = \"Special Attack\", command = specialAttack)\n spAttack.grid(row = 2, column = 2)\n dodge = Button(frame4, text = \"Dodge\", command = dodging)\n dodge.grid(row = 2, column = 3)\n fightMusic = pyglet.media.load('bossFight.wav')\n global player\n player.queue(fightMusic)\n player.next_source()\n#coded by Jared\ndef dragonAttack():\n global head, chest, legs, playerHealth, healthAmt, healthLabel\n defenseBonus = 0\n if(head == \"Enchanted Hat\" or head == \"Enchanted Helm\" or head == \"Fire Hat\"):\n defenseBonus = defenseBonus + 1\n if(legs == \"Enchanted Pants\" or legs == \"Enchanted Leggings\" or legs == \"Fire Pants\"):\n defenseBonus = defenseBonus + 1\n if(chest == \"Enchanted Shirt\" or chest == \"Enchanted Chestplate\" or chest == \"FireShirt\"):\n defenseBonus = defenseBonus + 2\n dAttack = [1,2,3,4]\n randomAttack = random.choice(dAttack)\n if (randomAttack == 1 or randomAttack == 4):\n playerHealth = playerHealth - (10 - ( 2 * defenseBonus))\n messagebox.showinfo(\"Tail Attack!\", \"The dragon swipes at you with it's mighty tail!\")\n winsound.PlaySound('whipCrack', winsound.SND_ASYNC)\n if (randomAttack == 2):\n playerHealth = playerHealth - (14 - ( 3 * defenseBonus))\n messagebox.showinfo(\"Claw Attack!\", \"The dragon swipes you with its claws!\")\n winsound.PlaySound('dragonClaw', winsound.SND_ASYNC)\n if (randomAttack == 3):\n playerHealth = playerHealth - (20 - ( 4 * defenseBonus))\n messagebox.showinfo(\"Fire Attack!\", \"The dragon breathes its flames at you!\")\n winsound.PlaySound('fireBreath', winsound.SND_ASYNC)\n healthAmt.set(\"Health: \" + str(playerHealth))\n healthLabel = Label(frame4, textvariable = healthAmt)\n if(playerHealth <=0):\n gameOver()\n#coded by Jared\ndef weakAttack():\n global dragonHealth,frame4,dHealthLabel,dHealthAmt, weapon, turnNumber, turnCount, turnLabel\n attackBonus = 1\n if(weapon == \"Enchanted Bow\" or weapon == \"Enchanted Sword\" or weapon == \"waterstaff\"):\n attackBonus = 1.25\n dragonHealth = dragonHealth - (8 * attackBonus)\n messagebox.showinfo( \"Weak Attack\", \"You hit the dragon using your \" + weapon)\n if (weapon == \"Enchanted Bow\" or weapon == \"Compound Bow\"):\n winsound.PlaySound('rangerSp', winsound.SND_ASYNC)\n if (weapon == \"Enchanted Sword\" or weapon == \"Broadsword\"):\n winsound.PlaySound('warriorSp', winsound.SND_ASYNC)\n if (weapon == \"waterstaff\" or weapon == \"firestaff\"):\n winsound.PlaySound('wizardSp', winsound.SND_ASYNC)\n dHealthAmt.set(\"Dragon Health: \" + str(dragonHealth))\n dHealthLabel = Label(frame4, textvariable = dHealthAmt)\n if (dragonHealth <= 0):\n gameOver()\n else:\n dragonAttack()\n turnNumber = turnNumber + 1\n turnCount.set(\"Turn Number: \" + str(turnNumber))\n turnLabel = Label(frame4, textvariable = turnCount)\n frame4.update_idletasks()\n#coded by Jared\ndef strongAttack():\n global dragonHealth,frame4,dHealthLabel,dHealthAmt, weapon, actionPoints, apAmt, apLabel, turnNumber, turnCount, turnLabel\n attackBonus = 1\n if(weapon == \"Enchanted Bow\" or weapon == \"Enchanted Sword\" or weapon == \"waterstaff\"):\n attackBonus = 1.25\n if(actionPoints < 2.5):\n messagebox.showinfo(\"You missed!\",\"You used too much of your stamina and the dragon easily dodged\")\n if (actionPoints >= 2.5):\n dragonHealth = dragonHealth - (20 * attackBonus)\n actionPoints = actionPoints - 2.5\n messagebox.showinfo( \"Strong Attack\", \"You prepare yourself and hit the dragon with a mighty blow using your \" + weapon)\n if (weapon == \"Enchanted Bow\" or weapon == \"Compound Bow\"):\n winsound.PlaySound('rangerSp', winsound.SND_ASYNC)\n if (weapon == \"Enchanted Sword\" or weapon == \"Broadsword\"):\n winsound.PlaySound('warriorSp', winsound.SND_ASYNC)\n if (weapon == \"waterstaff\" or weapon == \"firestaff\"):\n winsound.PlaySound('wizardSp', winsound.SND_ASYNC)\n dHealthAmt.set(\"Dragon Health: \" + str(dragonHealth))\n dHealthLabel = Label(frame4, textvariable = dHealthAmt)\n apAmt.set(\"Action Points: \" + str(actionPoints))\n apLabel = Label(frame4, textvariable = apAmt)\n if (dragonHealth <= 0):\n gameOver()\n else:\n dragonAttack()\n turnNumber = turnNumber + 1\n turnCount.set(\"Turn Number: \" + str(turnNumber))\n turnLabel = Label(frame4, textvariable = turnCount)\n frame4.update_idletasks()\n#coded by Jared\ndef specialAttack():\n global dragonHealth,frame4,dHealthLabel,dHealthAmt, weapon, actionPoints, apAmt, apLabel, turnNumber, turnCount, turnLabel\n attackBonus = 1\n if(weapon == \"Enchanted Bow\" or weapon == \"Enchanted Sword\" or weapon == \"waterstaff\"):\n attackBonus = 1.25\n if(actionPoints <5):\n messagebox.showinfo(\"You missed!\",\"You used too much of your stamina and the dragon easily dodged\")\n if (actionPoints >= 5):\n dragonHealth = dragonHealth - (40 * attackBonus)\n actionPoints = actionPoints - 5\n if (weapon == \"Enchanted Bow\" or weapon == \"Compound Bow\"):\n messagebox.showinfo( \"Special Attack\", \"You shoot the dragon in the eye! It roars in agony!\")\n winsound.PlaySound('rangerSp', winsound.SND_ASYNC)\n if (weapon == \"Enchanted Sword\" or weapon == \"Broadsword\"):\n messagebox.showinfo(\"Special Attack\", \"You slice off one of the dragons claws! It roars in agony!\")\n winsound.PlaySound('warriorSp', winsound.SND_ASYNC)\n if (weapon == \"waterstaff\" or weapon == \"firestaff\"):\n messagebox.showinfo(\"Special Attack\", \"You charge up your power and blast the dragon with your magic! It roars in agony!\")\n winsound.PlaySound('wizardSp', winsound.SND_ASYNC)\n dHealthAmt.set(\"Dragon Health: \" + str(dragonHealth))\n dHealthLabel = Label(frame4, textvariable = dHealthAmt)\n apAmt.set(\"Action Points: \" + str(actionPoints))\n apLabel = Label(frame4, textvariable = apAmt)\n if (dragonHealth <= 0):\n gameOver()\n else:\n dragonAttack()\n turnNumber = turnNumber + 1\n turnCount.set(\"Turn Number: \" + str(turnNumber))\n turnLabel = Label(frame4, textvariable = turnCount)\n frame4.update_idletasks()\n#coded by Jared\ndef dodging():\n global dragonHealth,frame4,dHealthLabel,dHealthAmt, turnNumber, turnCount, turnLabel\n dodgeChance = [1,2]\n dodgePercent = random.choice(dodgeChance)\n if (dodgePercent == 1):\n dragonHealth = dragonHealth - 10\n dHealthAmt.set(\"Dragon Health: \" + str(dragonHealth))\n dHealthLabel = Label(frame4, textvariable = dHealthAmt)\n messagebox.showinfo(\"You dodged!\",\"You dodge out of the way of the dragon's attack and it injures itself\")\n if (dragonHealth <= 0):\n gameOver()\n if (dodgePercent == 2):\n messagebox.showinfo(\"You were hit!\",\"You tried dodging but the dragon hit you with its attack!\")\n dragonAttack()\n turnNumber = turnNumber + 1\n turnCount.set(\"Turn Number: \" + str(turnNumber))\n turnLabel = Label(frame4, textvariable = turnCount)\n frame4.update_idletasks()\n#showInventory designed by Jared\ndef showInventory():\n global frame3\n frame3 = Frame(newWindow)\n frame3.pack()\n global head, chest, legs, weapon\n hatBonus = \"\"\n chestBonus = \"\"\n legBonus = \"\"\n weaponBonus = \"\"\n if(head == \"Enchanted Hat\" or head == \"Enchanted Helm\" or head == \"Fire Hat\"):\n hatBonus = \" (+ 25 percent protection)\"\n if(chest == \"Enchanted Shirt\" or chest == \"Enchanted Chestplate\" or chest == \"FireShirt\"):\n chestBonus = \" (+ 50 percent protection)\"\n if(legs == \"Enchanted Pants\" or legs == \"Enchanted Leggings\" or legs == \"Fire Pants\"):\n legBonus = \" (+ 25 percent protection)\"\n if(weapon == \"Enchanted Bow\" or weapon == \"Enchanted Sword\" or weapon == \"waterstaff\"):\n weaponBonus = \" (+ 25 percent damage)\"\n hatLabel = Label(frame3, text = \"The headwear you chose was the \" + head + hatBonus)\n hatLabel.pack(side=TOP)\n chestLabel = Label(frame3, text = \"The chestwear you chose was the \" + chest + chestBonus)\n chestLabel.pack(side=TOP)\n legLabel = Label(frame3, text = \"The legwear you chose was the \" + legs + legBonus)\n legLabel.pack(side=TOP)\n weaponLabel = Label(frame3, text = \"The weapon you chose was the \" + weapon + weaponBonus)\n weaponLabel.pack(side=TOP)\n bossButton = Button(frame3, text = \"Ready to fight!\", command = bossFight)\n bossButton.pack(side = BOTTOM)\n#inventory designed by Devon\ndef inventory(item, choose):\n global head, chest, legs, weapon\n if(item == \"staff\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n weapon = \"waterstaff\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n weapon = \"firestaff\"\n if(item == \"wiztop\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n chest = \"FireShirt\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n chest = \"WaterShirt\"\n if(item == \"wizhat\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n head = \"Fire Hat\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n head = \"Water Hat\"\n if(item == \"wizlegs\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n legs = \"Fire Pants\"\n elif(choose ==2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n legs = \"Water Pants\"\n if(item == \"sword\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n weapon = \"Enchanted Sword\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n weapon = \"Broadsword\"\n if(item == \"boots\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n legs = \"Enchanted Leggings\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n legs = \"Armored Leggings\"\n if(item == \"chestplate\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n chest = \"Enchanted Chestplate\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n chest = \"Steel Chestplate\"\n if(item == \"helm\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n head = \"Enchanted Helm\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n head = \"Steel Helm\"\n if(item == \"bow\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n weapon = \"Enchanted Bow\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n weapon = \"Compound Bow\"\n if(item == \"archerhat\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n head = \"Enchanted Hat\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n head = \"Archer's Hat\"\n if(item == \"archerpants\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n legs = \"Enchanted Pants\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n legs = \"Archer's Pants\"\n if(item == \"archershirt\"):\n if(choose == 1):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n chest = \"Enchanted Shirt\"\n elif(choose == 2):\n winsound.PlaySound('equipitem.wav', winsound.SND_ASYNC)\n chest = \"Archer's Shirt\"\n#All gold functions designed by Jared\ndef resetGold(item, choose):\n spentGold()\n reset(item, choose)\ndef spentGold():\n global gold\n gold = gold - 250\n#reset designed by Siddarth\ndef ClearScreen():\n button1.destroy()\n button2.destroy()\n button3.destroy()\n#reset designed by Siddarth and Devon\ndef reset(itemchosen, choose):\n goldLabel.destroy()\n frame2.pack_forget()\n inventory(itemchosen, choose)\n if (numberOfDoors2 == 0):\n showInventory()\n if (choice == 1):\n WizardCreateDoors(numberOfDoors2)\n if (choice == 2):\n WarriorCreateDoors(numberOfDoors2)\n if (choice == 3):\n RangerCreateDoors(numberOfDoors2)\n#createRooms designed by Siddarth and Devon\ndef createRooms(item1, item2, itemChoice):\n global frame2\n frame2 = Frame(newWindow)\n frame2.pack()\n pathToImage1 = Image.open(item1)\n pathToImage2 = Image.open(item2)\n photoImage1 = ImageTk.PhotoImage(pathToImage1)\n photoImage2 = ImageTk.PhotoImage(pathToImage2)\n goldLabel.pack(side = TOP)\n selectedItem = itemChoice\n if gold >= 250:\n button1 = Button(frame2, image = photoImage1, text = \"Gold Price: 250\", compound = BOTTOM, command = lambda: resetGold(selectedItem, 1))\n button1.photoImage1 = photoImage1\n button1.pack(side = RIGHT)\n button2 = Button(frame2, image = photoImage2, text = \"Gold Price: 0\", compound = BOTTOM ,command = lambda: reset(selectedItem, 2))\n button2.photoImage2 = photoImage2\n button2.pack(side = RIGHT)\n\n#Rooms designed by Siddarth and Devon \ndef staffRoom():\n createRooms(\"waterstaff1.jpg\", \"fireStaff1.jpg\", \"staff\")\ndef topRoom():\n createRooms(\"firetop1.jpg\", \"waterRobe1.jpg\", \"wiztop\")\ndef wizardHatRoom():\n createRooms(\"fireHat1.jpg\", \"waterHat1.jpg\",\"wizhat\")\ndef bottomRoom():\n createRooms(\"fireRobe1.jpg\", \"waterBottom1.jpg\",\"wizlegs\")\n\ndef swordRoom():\n createRooms(\"ElementalSword.jpg\",\"MetalSword.jpg\",\"sword\")\ndef legsRoom():\n createRooms(\"ElementalLegs.jpg\",\"MetalLegs.jpg\",\"boots\")\ndef chestRoom():\n createRooms(\"ElementalPlate.jpg\", \"MetalBody.jpg\",\"chestplate\")\ndef helmRoom():\n createRooms(\"ElementalFullHelm.jpg\", \"MetalFullHelm.jpg\",\"helm\")\n\ndef bowRoom():\n createRooms(\"ElementalBow.jpg\", \"Bow.jpg\",\"bow\")\ndef RangerHatRoom():\n createRooms(\"elementalArcherHat.png\", \"robinHoodHat.jpg\",\"archerhat\")\ndef leggingsRoom():\n createRooms(\"elementalArcherLegs.png\",\"archerLegs.png\",\"archerpants\")\ndef torsoRoom():\n createRooms(\"elementalArcherTop.png\", \"ArcherTop.jpg\",\"archershirt\")\n\nrandomArray = [1,2,3,4]\nrandomGold = [1,2,3,4]\n#DoorUpdate Functions Designed by Siddarth\ndef WizardDoorUpdate():\n numberOfDoors1 = numberOfTimesDecremented\n global gold\n global numberOfDoors2\n numberOfDoors2 = numberOfDoors1 - 1\n\n randomNumber = random.choice(randomArray)\n goldFind = random.choice(randomGold)\n\n if randomNumber == 1:\n messagebox.showinfo(\"Staff\",\"You have entered the staff room\")\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n staffRoom()\n if randomNumber == 2:\n messagebox.showinfo(\"Top\",\"You have entered the top room\")\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n topRoom()\n if randomNumber == 3:\n messagebox.showinfo(\"Bottom\",\"You have entered the bottom room\")\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n bottomRoom()\n if randomNumber == 4:\n messagebox.showinfo(\"Hat\",\"You have entered the hat room\")\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n wizardHatRoom()\ndef WarriorDoorUpdate():\n numberOfDoors1 = numberOfTimesDecremented\n global gold\n global numberOfDoors2\n numberOfDoors2 = numberOfDoors1 - 1\n randomNumber = random.choice(randomArray)\n goldFind = random.choice(randomGold)\n if randomNumber == 1:\n messagebox.showinfo(\"Sword\",\"You have entered the sword room\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n swordRoom()\n if randomNumber == 2:\n messagebox.showinfo(\"Chest\",\"You have entered the chest room\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n chestRoom()\n if randomNumber == 3:\n messagebox.showinfo(\"Leggings\",\"You have entered the leggings room\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n legsRoom()\n if randomNumber == 4:\n messagebox.showinfo(\"Helm\",\"You have entered the helm room\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n helmRoom()\ndef RangerDoorUpdate():\n numberOfDoors1 = numberOfTimesDecremented\n global gold\n global numberOfDoors2\n numberOfDoors2 = numberOfDoors1 - 1\n randomNumber = random.choice(randomArray)\n goldFind = random.choice(randomGold)\n if randomNumber == 1:\n messagebox.showinfo(\"Bow\",\"You have entered the bow room\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n bowRoom()\n if randomNumber == 2:\n messagebox.showinfo(\"Torso\",\"You have entered the shirt room\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n torsoRoom()\n if randomNumber == 3:\n messagebox.showinfo(\"Leggings\",\"You have entered the legging's room\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n leggingsRoom()\n if randomNumber == 4:\n messagebox.showinfo(\"Hat\",\"You have entered the hat room\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n if goldFind == 1:\n messagebox.showinfo(\"Gold!!!\",\"You have also found gold in this room\")\n winsound.PlaySound('money.wav', winsound.SND_ASYNC)\n gold = gold + 250\n frame.pack_forget()\n randomArray.remove(randomNumber)\n RangerHatRoom()\n#Door functions designed by Siddarth\ndef WizardDoor():\n ClearScreen()\n global choice\n choice = 1\n messagebox.showinfo(\"wizard door\", \"You have entered the Wizard door! Choose another door and this will lead you to either the hat door, the top door, the robe door, or the staff door.\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n WizardCreateDoors(4)\ndef WarriorDoor():\n ClearScreen()\n global choice\n choice = 2\n messagebox.showinfo(\"warrior door\", \"You have entered the Warrior door! Choose another door and this will lead you to either the helm door, the chest door, the greaves door, or the sword door.\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n WarriorCreateDoors(4)\ndef RangerDoor():\n ClearScreen()\n global choice\n choice = 3\n messagebox.showinfo(\"ranger door\", \"You have entered the Ranger door! Choose another door and this will lead you to either the hat door, the torso door, the leggings door, or the bow door.\")\n winsound.PlaySound('door.wav', winsound.SND_ASYNC)\n RangerCreateDoors(4)\n#Create Doors Functions designed by Siddarth\ndef WizardCreateDoors(numberOfDoors):\n goldamount = StringVar()\n goldamount.set(\"Gold: \" + str(gold))\n global goldLabel\n goldLabel = Label(newWindow, textvariable = goldamount)\n goldLabel.pack(side = TOP)\n global numberOfTimesDecremented\n numberOfTimesDecremented = 0\n img5 = Image.open(\"door5.jpg\")\n img6 = ImageTk.PhotoImage(img1)\n global frame\n frame = Frame(newWindow)\n frame.pack()\n \n while numberOfDoors != 0:\n global labelx\n #labelx = Label(frame, image = img2)\n #labelx.pack(side = RIGHT)\n global wizardButton\n wizardButton = Button(frame, image = img6,command = WizardDoorUpdate)\n wizardButton.img6 = img6\n wizardButton.pack(side = RIGHT)\n numberOfDoors = numberOfDoors - 1\n numberOfTimesDecremented = numberOfTimesDecremented + 1\ndef WarriorCreateDoors(numberOfDoors):\n goldamount = StringVar()\n goldamount.set(\"Gold: \" + str(gold))\n global goldLabel\n goldLabel = Label(newWindow, textvariable = goldamount)\n goldLabel.pack(side = TOP)\n global numberOfTimesDecremented\n numberOfTimesDecremented = 0\n img5 = Image.open(\"door5.jpg\")\n img6 = ImageTk.PhotoImage(img1)\n global frame\n frame = Frame(newWindow)\n frame.pack()\n while numberOfDoors != 0:\n global labelx\n #labelx = Label(frame, image = img2)\n #labelx.pack(side = RIGHT)\n global warriorButton\n warriorButton = Button(frame, image = img6,command = WarriorDoorUpdate)\n warriorButton.img6 = img6\n warriorButton.pack(side = RIGHT)\n numberOfDoors = numberOfDoors - 1\n numberOfTimesDecremented = numberOfTimesDecremented + 1\ndef RangerCreateDoors(numberOfDoors):\n goldamount = StringVar()\n goldamount.set(\"Gold: \" + str(gold))\n global goldLabel\n goldLabel = Label(newWindow, textvariable = goldamount)\n goldLabel.pack(side = TOP)\n global numberOfTimesDecremented\n numberOfTimesDecremented = 0\n img5 = Image.open(\"door5.jpg\")\n img6 = ImageTk.PhotoImage(img1)\n global frame\n frame = Frame(newWindow)\n frame.pack()\n while numberOfDoors != 0:\n global labelx\n #labelx = Label(frame, image = img2)\n #labelx.pack(side = RIGHT)\n global rangerButton\n rangerButton = Button(frame, image = img6, command = RangerDoorUpdate)\n rangerButton.img6 = img6\n rangerButton.pack(side = RIGHT)\n numberOfDoors = numberOfDoors - 1\n numberOfTimesDecremented = numberOfTimesDecremented + 1\n#coded by Siddarth\ncasualBackground = pyglet.media.load('gamemusic.wav')\nglobal player\nplayer = pyglet.media.Player()\nplayer.queue(casualBackground)\nplayer.play()\ndef endMusic():\n newWindow.destroy()\n player.pause()\nnewWindow = Tk()\nnewWindow.protocol(\"WM_DELETE_WINDOW\",endMusic)\nmytext = StringVar()\ngold = 500\ngoldamount = StringVar()\ngoldamount.set(\"Gold: \" + str(gold))\nglobal goldLabel\nmessagebox.showinfo(\"Welcome Adventurer!\", \"There's a nasty dragon at the end of this dungeon that we need you to clear out. Here is 500 gold, you can buy equipment in the rooms beyond to help you with your battle. Better equipment costs more gold. Good luck and remember, we're all counting on you...\")\nwinsound.PlaySound('money.wav', winsound.SND_ASYNC)\ngoldLabel = Label(newWindow, textvariable = goldamount)\nimg1 = Image.open(\"door5.jpg\")\nimg2 = ImageTk.PhotoImage(img1)\nwarriorImg = Image.open(\"fighter.jpg\")\nwarriorImg2 = ImageTk.PhotoImage(warriorImg)\nwizardImg = Image.open(\"wizard.png\")\nwizardImg2 = ImageTk.PhotoImage(wizardImg)\nrangerImg = Image.open(\"ranger.jpg\")\nrangerImg2 = ImageTk.PhotoImage(rangerImg)\nwizardDoorCount = 4\nbutton1 = Button(newWindow, text = \"WIZARD\", image = wizardImg2, compound = BOTTOM ,command = WizardDoor)\nbutton1.wizardImg2 = wizardImg2\nbutton1.pack(side = RIGHT)\nbutton2 = Button(newWindow, text = \"WARRIOR\", image = warriorImg2, compound = BOTTOM, command = WarriorDoor)\nbutton2.warriorImg2 = warriorImg2\nbutton2.pack(side = RIGHT)\nbutton3 = Button(newWindow, text = \"RANGER\", image = rangerImg2, compound = BOTTOM, command = RangerDoor)\nbutton3.rangerImg2 = rangerImg2\nbutton3.pack(side = RIGHT)\n","repo_name":"Devonnair96/CST205P3","sub_path":"FinalTextGame.py","file_name":"FinalTextGame.py","file_ext":"py","file_size_in_byte":30791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38444124883","text":"'''\nProperty List Module\n====================\n\nThe Property List module reads and writes .plist files which are used\nheavily throughout OSX using the PyObjC bridge for NSPropertyListSerialization\n\nSeveral parts of this code have been taken/modified from gneagle's\nFoundationPlist class which is a part of the munki project.\n\nRemember that changes may not be effected immediately, and that you should try to avoid modifying the plist\nof any running process (If using NSPropertyListSerialization).\n\nTODO:\n\n- The write_key/read_key executions should support collections. Operations on selections via command line\nare always a bit clunky, so need to put some thought into this.\n\n:maintainer: Mosen \n:maturity: new\n:depends: objc,Foundation\n:platform: darwin\n'''\n\nimport logging\nimport salt.exceptions\n\nlog = logging.getLogger(__name__) # Start logging\n\nHAS_LIBS = False\ntry:\n import os\n\n from Foundation import NSData, \\\n NSPropertyListSerialization, \\\n NSPropertyListMutableContainers, \\\n NSPropertyListXMLFormat_v1_0, \\\n NSPropertyListBinaryFormat_v1_0, \\\n NSNumber, \\\n NSString, \\\n NSMutableDictionary, \\\n NSMutableArray, \\\n NSMutableData\n\n HAS_LIBS = True\nexcept ImportError:\n log.debug('Error importing dependencies for plist execution module.')\n\n__virtualname__ = 'plist'\n\n\ndef __virtual__():\n '''\n Only load if the platform is correct and we can use PyObjC libs\n '''\n if __grains__.get('kernel') != 'Darwin':\n return False\n\n if not HAS_LIBS:\n return False\n\n return __virtualname__\n\n\ndef _read_plist(filepath):\n \"\"\"\n Read a .plist file from filepath. Return the unpacked root object\n (which is usually a dictionary).\n\n If the file doesn't exist, this returns None\n \"\"\"\n if not os.path.isfile(filepath):\n log.debug('Tried to read non-existent property list at path: {0}'.format(filepath))\n return None\n\n plistData = NSData.dataWithContentsOfFile_(filepath)\n\n dataObject, plistFormat, error = \\\n NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(\n plistData, NSPropertyListMutableContainers, None, None)\n if error:\n error = error.encode('ascii', 'ignore')\n\n raise salt.exceptions.SaltInvocationError(\n 'Error decoding Property List : {}'.format(error)\n )\n else:\n return dataObject\n\n\ndef _write_plist(dataObject, filepath, format=NSPropertyListXMLFormat_v1_0):\n '''\n Write 'rootObject' as a plist to filepath.\n '''\n plistData, error = \\\n NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_(\n dataObject, format, None)\n if error:\n error = error.encode('ascii', 'ignore')\n raise salt.exceptions.SaltInvocationError(\n 'Error encoding Property List: {}'.format(error)\n )\n else:\n if plistData.writeToFile_atomically_(filepath, True):\n return\n else:\n raise salt.exceptions.SaltInvocationError(\n 'Failed to write Property List at path: {}'.format(filepath)\n )\n\n\ndef _generate_plist_string(rootObject, format=NSPropertyListXMLFormat_v1_0):\n '''Return 'rootObject' as a plist-formatted string.'''\n plistData, error = \\\n NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_(\n rootObject, format, None)\n if error:\n error = error.encode('ascii', 'ignore')\n raise salt.exceptions.SaltInvocationError(\n 'Error encoding Property List: {}'.format(error)\n )\n else:\n return str(plistData)\n\n\ndef _value_to_nsobject(value, nstype):\n '''Convert a string with a type specifier to a native Objective-C NSObject (serializable).'''\n return {\n 'string': lambda v: NSString.stringWithUTF8String_(v),\n 'int': lambda v: NSNumber.numberWithInt_(v),\n 'float': lambda v: NSNumber.numberWithFloat_(v),\n 'bool': lambda v: True if v == 'true' else False,\n 'data': lambda v: NSMutableData.dataWithLength_(len(value)).initWithBase64EncodedString_options_(value)\n }[nstype](value)\n\ndef _objects_for_dict(dict, keys, collector):\n \"\"\"Extract a section of a Property List by providing an existing structure (dict) of the keys.\n\n Recursive call traverses the specified keys in the NSDictionary, and retrieves the associated\n object at each 'leaf node', assigning a hierarchy of keys and the found value to the collector.\n\n Args:\n dict (NSDictionary): The current dictionary being operated on\n\n keys: The current dict describing a key or nested key in the dict parameter.\n\n collector: A reference to the current dict which can have value(s) set.\n \"\"\"\n # Stop collecting values if the specified key hierarchy doesn't exist.\n if dict is None:\n collector = None\n return\n\n for key, value in keys.items():\n if type(value) is dict:\n collector[key] = {}\n plist_value = dict.objectForKey_(key)\n _objects_for_dict(plist_value, value, collector[key])\n else:\n\n collector[key] = dict.objectForKey_(key)\n\ndef _set_objects_for_keys(dict, keys, changed=None):\n \"\"\"Set plist values using a given dict.\n\n Recursively finds or creates keys given and sets their values. This can be used to maintain a partial or\n complete override of any given property list file.\n\n Args:\n dict (NSMutableDictionary): The current dictionary being operated on. For a non existent file this will be\n blank.\n\n keys: A dict representing a hierarchy with leaf node values.\n \"\"\"\n if changed is None:\n changed = dict()\n\n for key, value in keys.items():\n existing_value = dict.objectForKey_(key)\n\n if type(value) is dict:\n # Value unavailable, so create structure\n if existing_value is None:\n child = NSMutableDictionary()\n dict.setObject_forKey_(child, key)\n\n changed[key] = {}\n _set_objects_for_keys(child, value, changed[key])\n else:\n if existing_value != value:\n dict.setObject_forKey_(value, key)\n changed[key] = value\n\n\ndef _remove_objects_for_keys(dict, keys, changed=None):\n \"\"\"Remove plist values using a given dict.\n\n Traverse each entry in the keys dict and remove the corresponding key (if it exists).\n If it doesn't exist then the function returns early.\n If the key was removed, the full path to that key is indicated in the changed dict.\n\n Args:\n dict (NSMutableDictionary): The current dictionary being operated on. For a non existent file this will be\n blank.\n\n keys: A dict representing a hierarchy pointing to keys to be removed\n\n changed: A dict used to record changes made\n \"\"\"\n if changed is None:\n changed = dict()\n\n for key, value in keys.items():\n existing_value = dict.objectForKey_(key)\n\n if not existing_value is None: # No need to process removal for non existent keys\n if type(value) is dict:\n changed[key] = {}\n _remove_objects_for_keys(existing_value, value, changed[key]) # Recurse deeper until not a dict\n else:\n dict.removeObjectForKey_(key)\n changed[key] = value\n\n\ndef _object_for_key_list(dict, keys, create=False):\n '''\n Get an object inside a nested NSDictionary structure, using a list of keys to traverse.\n\n If create is true, then missing elements are automatically created as NSMutableDictionary objects.\n '''\n key = keys.pop(0)\n\n # User accidentally supplies zero length key\n if len(key) == 0:\n return dict\n\n if len(keys) > 0:\n value = dict.objectForKey_(key)\n if value is None:\n if create:\n created = NSMutableDictionary()\n dict.setObject_forKey_(created, key)\n return _object_for_key_list(created, keys, create)\n else: # Just return None if path was not found\n log.debug('No key found in Property List: {0}'.format(key))\n return None\n else:\n return _object_for_key_list(dict.objectForKey_(key), keys, create)\n else:\n # TODO: special case for array index notation [x] if current object is NSArray\n # if dict.isKindOfClass_(NSArray.class_()):\n # return\n return dict.objectForKey_(key)\n\n\ndef _set_object_for_key_list(dict, keys, value, create=True, createNSType=NSMutableDictionary):\n '''\n Set the value of an object inside a nested NSDictionary structure, using a list of keys to traverse.\n\n If create is true, then missing elements are automatically created as NSMutableDictionary objects.\n createNSType can be passed a constructor to another possible collection type.\n '''\n key = keys.pop(0)\n\n # User accidentally supplies zero length key\n if len(key) == 0:\n return dict\n\n if len(keys) > 0:\n return _object_for_key_list(dict.objectForKey_(key), keys, create)\n else:\n dict.setObject_forKey_(value, key)\n\n\ndef _addObjectForKeyList(dict, keys, value, create=True):\n '''\n Add an object to an array inside a nested NSDictionary structure, using a list of keys.\n It is assumed that the last key points to an NSArray.\n\n If the create argument is true, non existent keys will be created as NSMutableDictionaries. The last item of the\n keys list will be created as an NSArray, and then the supplied value will be appended as an object\n '''\n key = keys.pop(0)\n\n # User accidentally supplies zero length key\n if len(key) == 0:\n return dict\n\n if len(keys) > 0:\n return _object_for_key_list(dict.objectForKey_(key), keys, create)\n else:\n dict.setObject_forKey_(value, key)\n\n\ndef _remove_object_for_key_list(dict, keys):\n '''\n Remove an object inside a nested NSDictionary structure, using a list of nested keys\n '''\n key = keys.pop(0)\n\n # User accidentally supplies zero length key\n if len(key) == 0:\n return dict\n\n if len(keys) > 0:\n return _object_for_key_list(dict.objectForKey_(key), keys)\n else:\n # TODO: special case for array index notation [x] if current object is NSArray\n # if dict.isKindOfClass_(NSArray.class_()):\n # return\n return dict.removeObjectForKey_(key)\n\n\ndef gen_string(data, format='xml'):\n '''\n Take a python struct (normally a dict) and generate a string representing a property list.\n\n data\n Python data structure (dict)\n\n format (default 'xml')\n Generate format, 'xml' or 'binary'\n '''\n serialization = NSPropertyListXMLFormat_v1_0 if format == 'xml' else NSPropertyListBinaryFormat_v1_0\n plistData, error = \\\n NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_(\n data, serialization, None)\n if error:\n error = error.encode('ascii', 'ignore')\n log.debug('Error writing plist')\n log.debug(error)\n raise NSPropertyListSerializationException(error)\n else:\n return plistData\n\ndef parse_string(data):\n '''\n Take a property list as a string and return a python native representation.\n\n Used by other modules in salt-osx\n '''\n plistData = buffer(data)\n dataObject, plistFormat, error = \\\n NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(\n plistData, NSPropertyListMutableContainers, None, None)\n if error:\n error = error.encode('ascii', 'ignore')\n\n import traceback\n\n log.debug('Error parsing plist from string')\n log.debug(error)\n raise NSPropertyListSerializationException(error)\n else:\n return dataObject\n\ndef read_key(path, key=''):\n '''\n Read the value of a key contained within the Property List file specified\n\n path\n An absolute path to a property list (.plist) file, including the extension\n\n key\n The path specification for the key to modify. A list of keys separated by a colon. eg. 'path:to:name'\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' plist.read [key]\n '''\n dataObject = _read_plist(path)\n\n if dataObject is None:\n return None\n\n keys = key.split(':')\n if type(keys) is str:\n keys = list(keys)\n\n value = _object_for_key_list(dataObject, keys)\n return value\n\n\ndef write_key(path, key, nstype, value):\n '''\n Write the value of a key contained within the Property List file specified.\n If the property list file does not exist, the default behaviour is to create it with the keys/values given.\n\n path\n An absolute path to a property list (.plist) file, including the extension\n\n key\n The path specification for the key to modify. A list of keys separated by a colon.\n\n nstype\n The value type to write, one of 'string', 'int', 'float', 'bool', 'data'\n\n value\n The property value. If not specified it will be set to an empty value.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' plist.write [value]\n '''\n log.debug('Reading original plist for modification at path: %s' % path)\n dataObject = _read_plist(path)\n\n log.debug('Deriving key hierarchy from colon separated string')\n keys = key.split(':')\n if type(keys) is str:\n keys = list(keys)\n\n if dataObject is None:\n dataObject = NSMutableDictionary()\n\n log.debug('Performing string to NSObject conversion')\n nsval = _value_to_nsobject(value, nstype)\n log.debug('Setting object value in hierarchy')\n _set_object_for_key_list(dataObject, keys, nsval)\n log.debug('Writing out plist to original path')\n _write_plist(dataObject, path)\n\n\ndef delete_key(path, key):\n '''\n Delete the key from the property list at the specified path\n\n path\n An absolute path to a property list (.plist) file, including the extension\n\n key\n The specification of the key to modify. A list of keys separated by a colon.\n\n .. code-block:: bash\n\n salt '*' plist.delete [key]\n '''\n dataObject = _read_plist(path)\n\n if dataObject is None:\n return None # None indicating no action was taken.\n\n\n keys = key.split(':')\n if type(keys) is str:\n keys = list(keys)\n\n _remove_object_for_key_list(dataObject, keys)\n _write_plist(dataObject, path)\n\n\ndef append_key(path, key, nstype, value):\n '''\n Append an item to an array within a property list file.\n\n path\n An absolute path to a property list (.plist) file, including the extension\n\n key\n The specification of the key to append an element to. A list of keys separated by a colon.\n\n .. code-block:: bash\n\n salt '*' plist.append_key \n '''\n log.debug('Reading original plist for modification at path: %s' % path)\n root = _read_plist(path)\n\n log.debug('Deriving key hierarchy from colon separated string')\n keys = key.split(':')\n if type(keys) is str:\n keys = list(keys)\n\n if root is None:\n raise salt.exceptions.SaltInvocationError('Tried to append to non existing file, not currently supported.')\n\n log.debug('Performing string to NSObject conversion')\n nsval = _value_to_nsobject(value, nstype)\n log.debug('Setting object value in hierarchy')\n\n if len(keys) > 1:\n parent = _object_for_key_list(root, keys[:-1])\n else:\n parent = root\n\n log.debug('Updating or creating object at key: {}'.format(keys[-1]))\n collection = parent.objectForKey_(keys[-1])\n\n # This is destructive if the key value is already another type\n if collection is None or type(collection) is not NSMutableArray:\n collection = NSMutableArray()\n parent.setObject_forKey_(collection, keys[-1])\n\n collection.addObject_(nsval)\n\n log.debug('Writing out plist to original path')\n\n from pprint import pprint\n pprint(root)\n xml_plist = _generate_plist_string(root, NSPropertyListXMLFormat_v1_0)\n log.debug(xml_plist)\n _write_plist(root, path)\n\n\ndef read(path):\n '''\n Read the entire contents of the property list at the specified path\n\n path\n An absolute path to a property list (.plist) file, including the extension\n\n .. code-block:: bash\n\n salt '*' plist.read \n '''\n dataObject = _read_plist(path)\n return dataObject\n\ndef write(path, contents_dict):\n '''\n (over)write the entire contents of the property list at the specified path\n\n path\n An absolute path to a property list (.plist) file, including the extension\n\n contents_dict\n A python dict containing the objects to be encoded into the plist file.\n '''\n _write_plist(path, contents_dict)\n\n\ndef read_keys(path, keys):\n \"\"\"\n Read values of keys described by a dict.\n Each dict entry is traversed until it has no child dict.\n\n path\n An absolute path to a property list (.plist) file, including the extension\n\n keys\n A dict describing a key or nested keys, with any leaf values used to look up the\n corresponding plist value.\n \"\"\"\n dataObject = _read_plist(path)\n\n collector = {}\n _objects_for_dict(dataObject, keys, collector)\n\n return collector\n\n\ndef write_keys(path, keys, test=False):\n \"\"\"\n Write key structure and its values to the given property list.\n If a key does not exist in the target plist, it is created as a dictionary by default.\n\n path\n An absolute path to a property list (.plist) file, including the extension\n\n keys\n A dict describing a structure and value(s) that should exist inside the target plist\n\n test\n If test is true, no changes will be written, but you will receive a dict containing the changes that\n would have been performed.\n \"\"\"\n dataObject = _read_plist(path)\n\n if dataObject is None:\n dataObject = NSMutableDictionary()\n\n changed = {}\n _set_objects_for_keys(dataObject, keys, changed)\n\n if test == False:\n _write_plist(dataObject, path)\n\n return changed\n\n\ndef delete_keys(path, keys, test=False):\n \"\"\"\n Delete keys indicated by key dict structure.\n The deepest, or leaf node, of each dictionary entry will be removed from the plist.\n\n path\n An absolute path to a property list (.plist) file, including the extension\n\n keys\n A dict describing keys that should NOT exist inside the target plist\n\n test\n If test is true, no changes will be written, but you will receive a dict containing the keys that\n would have been removed.\n \"\"\"\n dataObject = _read_plist(path)\n changed = {}\n\n if dataObject is None:\n return changed # No need to remove anything from non existent property list\n\n _remove_objects_for_keys(dataObject, keys, changed)\n\n if test == False:\n _write_plist(dataObject, path)\n\n return changed\n","repo_name":"mosen/salt-osx","sub_path":"_modules/plist_serialization.py","file_name":"plist_serialization.py","file_ext":"py","file_size_in_byte":19147,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"3"}
+{"seq_id":"39048855712","text":"from pyesgf.search import SearchConnection\nconn = SearchConnection('http://esgf-index1.ceda.ac.uk/esg-search',\n distrib=False)\n\n#%%\nctx = conn.new_context(project='CORDEX', query='temperature')\nprint('Hits:', ctx.hit_count)\nprint('Institute:')\nctx.facet_counts['institute']\n#%%\nfrom pyesgf.logon import LogonManager\nlm = LogonManager()\nlm.logoff()\nlm.is_logged_on()","repo_name":"SebBub/misc_scripts","sub_path":"Download_Scripts/ESGF.py","file_name":"ESGF.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"18132609997","text":"# Дано число A (> 1).\n# Вывести наименьшее из целых чисел K, для которых сумма 1 + 1/2 + ... + 1/K будет больше A, и саму эту сумму.\n\nimport random\n\nA = random.randrange(2, 200)\nprint('A = ', A)\n\nK = 1\nS = 1\nwhile S <= A:\n K += 1\n S += K\nprint(\"K =\", K, \" , S =\", S)\n","repo_name":"galamyan01/Example","sub_path":"PZ_4/PZ_4_9_2.py","file_name":"PZ_4_9_2.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24498373949","text":"import sys\nfrom collections import defaultdict\nimport math\nimport random\nimport os\nimport os.path\n\"\"\"\nCOMS W4705 - Natural Language Processing - Fall 2022 \nProrgramming Homework 1 - Trigram Language Models\nDaniel Bauer\n\"\"\"\n\ndef corpus_reader(corpusfile, lexicon=None): \n with open(corpusfile,'r') as corpus: \n for line in corpus: \n if line.strip():\n sequence = line.lower().strip().split()\n if lexicon: \n yield [word if word in lexicon else \"UNK\" for word in sequence]\n else: \n yield sequence\n\ndef get_lexicon(corpus):\n word_counts = defaultdict(int)\n for sentence in corpus:\n for word in sentence: \n word_counts[word] += 1\n return set(word for word in word_counts if word_counts[word] > 1) \n\n\n\ndef get_ngrams(sequence, n):\n \"\"\"\n COMPLETE THIS FUNCTION (PART 1)\n Given a sequence, this function should return a list of n-grams, where each n-gram is a Python tuple.\n This should work for arbitrary values of 1 <= n < len(sequence).\n \"\"\"\n\n ngrams = []\n\n \n if n is 1:\n ngrams.append(('START',))\n\n \n RangeEnd = (len(sequence)+1)\n for index_word in range(0, RangeEnd):\n tuple_gram = ()\n for index_gram in range(index_word-n+1, index_word+1):\n word = None\n if index_gram < 0:\n word = 'START'\n elif index_gram >= len(sequence):\n word = 'STOP'\n else:\n word = sequence[index_gram]\n if word:\n tuple_gram = tuple_gram + (word,)\n \n ngrams.append(tuple_gram)\n\n return ngrams\n\n\nclass TrigramModel(object):\n \n def __init__(self, corpusfile):\n \n # Iterate through the corpus once to build a lexicon \n generator = corpus_reader(corpusfile)\n self.lexicon = get_lexicon(generator)\n self.lexicon.add(\"UNK\")\n self.lexicon.add(\"START\")\n self.lexicon.add(\"STOP\")\n \n # Now iterate through the corpus again and count ngrams\n generator = corpus_reader(corpusfile, self.lexicon)\n self.count_ngrams(generator)\n\n\n def count_ngrams(self, corpus):\n \"\"\"\n COMPLETE THIS METHOD (PART 2)\n Given a corpus iterator, populate dictionaries of unigram, bigram,\n and trigram counts. \n \"\"\"\n \n self.unigramcounts = {} # might want to use defaultdict or Counter instead\n self.bigramcounts = {} \n self.trigramcounts = {} \n self.totalcount = 0\n\n ##Your code here\n for sequence in corpus: \n for token in get_ngrams(sequence, 1): \n if not token in self.unigramcounts: \n self.unigramcounts[token] = 0 \n self.unigramcounts[token] += 1 \n\n for token in get_ngrams(sequence, 2): \n if not token in self.bigramcounts: \n self.bigramcounts[token] = 0 \n self.bigramcounts[token] += 1 \n\n for token in get_ngrams(sequence, 3): \n if not token in self.trigramcounts: \n self.trigramcounts[token] = 0 \n self.trigramcounts[token] += 1 \n \n self.totalcount += len(sequence) \n\n self.bigramcounts[(\"START\", \"START\")] = self.unigramcounts[(\"START\",)] \n\n return\n\n def raw_trigram_probability(self,trigram):\n \"\"\"\n COMPLETE THIS METHOD (PART 3)\n Returns the raw (unsmoothed) trigram probability\n \"\"\"\n tricount = self.trigramcounts.get(trigram, 0.0)\n bicount = float(self.bigramcounts.get(trigram[:-1], 0.0))\n \n return (tricount/bicount) if bicount != 0 else 0.0\n\n def raw_bigram_probability(self, bigram):\n \"\"\"\n COMPLETE THIS METHOD (PART 3)\n Returns the raw (unsmoothed) bigram probability\n \"\"\"\n bicount = self.bigramcounts.get(bigram, 0.0)\n unicount = float(self.unigramcounts.get(bigram[:-1], 0.0))\n\n return (bicount/unicount) if unicount != 0 else 0.0\n \n def raw_unigram_probability(self, unigram):\n \"\"\"\n COMPLETE THIS METHOD (PART 3)\n Returns the raw (unsmoothed) unigram probability.\n \"\"\"\n unicount = self.unigramcounts.get(unigram, 0.0)\n tricount = float(self.trigramcounts.get(unigram[:-1], 0.0))\n\n return (unicount/tricount) if tricount != 0 else 0.0\n #hint: recomputing the denominator every time the method is called\n # can be slow! You might want to compute the total number of words once, \n # store in the TrigramModel instance, and then re-use it. \n\n def generate_sentence(self,t=20): \n \"\"\"\n COMPLETE THIS METHOD (OPTIONAL)\n Generate a random sentence from the trigram model. t specifies the\n max length, but the sentence may be shorter if STOP is reached.\n \"\"\"\n return \n\n def smoothed_trigram_probability(self, trigram):\n \"\"\"\n COMPLETE THIS METHOD (PART 4)\n Returns the smoothed trigram probability (using linear interpolation). \n \"\"\"\n lambda1 = 1/3.0\n lambda2 = 1/3.0\n lambda3 = 1/3.0\n \n temp_unigram = [] \n temp_unigram.append(trigram[2]) \n p_unigram = self.raw_unigram_probability(tuple(temp_unigram)) \n\n temp_bigram = [] \n temp_bigram.append(trigram[1]) \n temp_bigram.append(trigram[2]) \n p_bigram = self.raw_bigram_probability(tuple(temp_bigram)) \n\n p_trigram = self.raw_trigram_probability(trigram) \n\n return lambda1 * p_trigram + lambda2 * p_bigram + lambda3 * p_unigram \n \n def sentence_logprob(self, sentence):\n \"\"\"\n COMPLETE THIS METHOD (PART 5)\n Returns the log probability of an entire sequence.\n \"\"\"\n trigrams = get_ngrams(sentence, 3)\n\n logprob = 0.0\n for gram in trigrams:\n smoothedprob = self.smoothed_trigram_probability(gram)\n if smoothedprob == 0.0:\n continue\n p = math.log(smoothedprob, 2)\n logprob = logprob + p\n\n\n return float(logprob)\n\n def perplexity(self, corpus):\n \"\"\"\n COMPLETE THIS METHOD (PART 6) \n Returns the log probability of an entire sequence.\n \"\"\"\n sum = 0 \n count = 0 \n for sentence in corpus: \n sum += self.sentence_logprob(sentence) \n count += len(sentence) \n\n sum /= count \n\n return float(2, -sum) \n\n\ndef essay_scoring_experiment(training_file1, training_file2, testdir1, testdir2):\n\n model1 = TrigramModel(training_file1)\n model2 = TrigramModel(training_file2)\n\n total = 0\n correct = 0 \n \n for f in os.listdir(testdir1):\n pp = model1.perplexity(corpus_reader(os.path.join(testdir1, f), model1.lexicon))\n # .. \n \n for f in os.listdir(testdir2):\n pp = model2.perplexity(corpus_reader(os.path.join(testdir2, f), model2.lexicon))\n # .. \n \n return 0.0\n\nif __name__ == \"__main__\":\n\n model = TrigramModel(sys.argv[1]) \n\n # put test code here...\n # or run the script from the command line with \n # $ python -i trigram_model.py [corpus_file]\n # >>> \n #\n # you can then call methods on the model instance in the interactive \n # Python prompt. \n\n # print(get_ngrams([\"natural\", \"language\", \"processing\"],1))\n # print(get_ngrams([\"natural\", \"language\", \"processing\"],2))\n # print(get_ngrams([\"natural\", \"language\", \"processing\"],3))\n #\n # print(len(model.unigramcounts))\n # print(len(model.bigramcounts))\n # print(len(model.trigramcounts))\n #\n # print(model.trigramcounts[('START','START','the')])\n # print(model.bigramcounts[('START','the')])\n # print(model.unigramcounts[('the',)])\n #\n # print(\"Unigram: \" + str(model.raw_unigram_probability(('department',))))\n # print(\"Bigram: \" + str(model.raw_bigram_probability(('highway', 'department'))))\n # print(\"Trigram: \" + str(model.raw_trigram_probability(('state','highway','department'))))\n #\n # print(\"Smoothed Trigram: \" + str(model.smoothed_trigram_probability(('state','highway','department'))))\n # print(\"Sentence Log Probability: \" + str(model.sentence_logprob('The State Highway department')))\n \n \n \n # Testing perplexity: \n # dev_corpus = corpus_reader(sys.argv[2], model.lexicon)\n # pp = model.perplexity(dev_corpus)\n # print(pp)\n\n\n # Essay scoring experiment: \n # acc = essay_scoring_experiment('./hw1_data/ets_toefl_data/train_high.txt', './hw1_data/ets_toefl_data/train_low.txt\", \"./hw1_data/ets_toefl_data/test_high\", \"./hw1_data/ets_toefl_data/test_low\")\n # print(acc)\n\n","repo_name":"ShengzhiLuo/NLP-ngram-Classification","sub_path":"trigram_model.py","file_name":"trigram_model.py","file_ext":"py","file_size_in_byte":8796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}