diff --git "a/314.jsonl" "b/314.jsonl" new file mode 100644--- /dev/null +++ "b/314.jsonl" @@ -0,0 +1,652 @@ +{"seq_id":"631928171","text":"#!/usr/bin/python\n\nimport rospy\nfrom geometry_msgs.msg import Pose\nfrom flexbe_core import EventState, Logger\nfrom flexbe_core.proxy import ProxyActionClient\nfrom robot_module_msgs.msg import JointTrapVelAction,JointTrapVelGoal\nimport tf.transformations as tft\nimport numpy as np\nimport quaternion as qt\n\nfrom kdl_tree_from_urdf_model import *\nimport PyKDl\n\nclass CallActionTFTrapVel(EventState):\n \n '''\n Implements a state that reads Pose() from input and sends them to ns/cart_lin_action_server\n [...] \n\n #< t2_out Data Send TF data\n ># t2_data Pose() Data from target Pose() from mongodb\n -- namespace string namespace of publish topic \n\n <= continue Written successfully\n <= failed Failed\n '''\n\n def __init__(self, namespace, max_vel, max_acl, offset=0, offset_type='local'):\n super(CallActionTFTrapVel, self).__init__(outcomes = ['continue', 'failed'], input_keys = ['t2_data'], output_keys = ['t2_out'])\n \n rospy.loginfo('__init__ callback happened.') \n \n self.ns = namespace\n if offset == 0:\n offset = [0, 0, 0, 0, 0, 0]\n self.offset = np.array(offset)\n self.offset_type = offset_type\n self.H = np.zeros((4, 4))\n self.H[-1, -1] = 1.0\n self.R = np.eye(4)\n # Declaring topic and client\n self._topic = \"/\" + str(self._namespace) + \"/joint_impedance_controller/move_joint_trap\"\n self._client = ProxyActionClient({ self._topic: JointTrapVelAction})\n\n self.max_vel = max_vel\n self.max_acl = max_acl\n\n def on_enter(self, userdata):\n Logger.loginfo(\"Started sending goal...\")\n # create goal\n\n position = np.array([userdata.t2_data[0].position.x,\n userdata.t2_data[0].position.y,\n userdata.t2_data[0].position.z])\n orientation = np.array([userdata.t2_data[0].orientation.x,\n userdata.t2_data[0].orientation.y,\n userdata.t2_data[0].orientation.z,\n userdata.t2_data[0].orientation.w])\n old_position = position\n old_orientation = orientation\n \n Logger.loginfo(\"Offset: {}\".format(self.offset))\n\n ###### GLOBAL OFFSET\n if self.offset_type == 'global':\n position = position + self.offset[0:3]\n orientation = (qt.from_float_array(orientation[[3,0,1,2]]) * \n qt.from_euler_angles(np.deg2rad(self.offset[3:])))\n orientation = qt.as_float_array(orientation)[[1,2,3,0]]\n \n ###### LOCAL OFFSET\n elif self.offset_type == 'local':\n\n orientation = (qt.from_float_array(old_orientation[[3,0,1,2]]) * \n qt.from_euler_angles(np.deg2rad(self.offset[3:])))\n self.R[:3, -1] = self.offset[:3]\n self.H[:3, :3] = qt.as_rotation_matrix(orientation)\n self.H[:3, -1] = old_position\n self.H = self.H.dot(self.R)\n position = self.H[:3, -1]\n orientation = qt.as_float_array(qt.from_rotation_matrix(self.H))[[1,2,3,0]]\n\n eulers = qt.as_euler_angles(qt.from_float_array(orientation[[3,0,1,2]]))\n eulers = np.rad2deg(eulers)\n Logger.loginfo(\"Eulers are: {}\".format(eulers)) \n \n # # Fix rotation if required (NOT REQUIRED CURRENTLY)\n # if self.limit_rotations:\n # if (eulers[2] < -30 or eulers[2] > 70):\n # self.offset[-1] += 180\n # orientation = (qt.from_float_array(old_orientation[[3,0,1,2]]) * \n # qt.from_euler_angles(np.deg2rad(self.offset[3:])))\n # self.R[:3, -1] = self.offset[:3]\n # self.H[:3, :3] = qt.as_rotation_matrix(orientation)\n # self.H[:3, -1] = old_position\n # self.H = self.H.dot(self.R)\n # position = self.H[:3, -1]\n # orientation = qt.as_float_array(qt.from_rotation_matrix(self.H))[[1,2,3,0]]\n # eulers = qt.as_euler_angles(qt.from_float_array(orientation[[3,0,1,2]]))\n # eulers = np.rad2deg(eulers)\n # Logger.loginfo(\"Fixed eulers are: {}\".format(eulers)) \n # else:\n # Logger.loginfo(\"Eulers are fine!\") \n\n goal = CartLinTaskGoal() \n pose = Pose()\n pose.position.x = position[0]\n pose.position.y = position[1]\n pose.position.z = position[2]\n pose.orientation.x = orientation[0]\n pose.orientation.y = orientation[1]\n pose.orientation.z = orientation[2]\n pose.orientation.w = orientation[3]\n \n goal.target_pose = [pose]\n goal.desired_travel_time = self.exe_time \n\n Logger.loginfo(\"Goal created: {}\".format(goal))\n \n try:\n self._client.send_goal(self._topic, goal)\n Logger.loginfo(\"Goal sent: {}\".format(str(goal)))\n except Exception as e:\n Logger.loginfo('Failed to send the goal command:\\n{}'.format(str(e)))\n self._error = True\n return 'failed' \n \n def execute(self, userdata):\n try:\n if self._client.has_result(self._topic):\n self.result = self._client.get_result(self._topic) \n return 'continue'\n else:\n feedback = self._client.get_feedback(self._topic)\n except Exception as e:\n Logger.loginfo(\"No result or server is not active!\")\n return 'failed'\n\n def on_exit(self, userdata):\n userdata.t2_out = self.result\n\n if not self._client.get_result(self._topic):\n self._client.cancel(self._topic)\n Logger.loginfo('Cancelled active action goal.')\n \n Logger.loginfo('Finished sending CartLinTaskGoal.')\n\n\nif __name__ == '__main__':\n print(\"Testing standalone\")\n rospy.init_node('test_node')\n test_state=CallActionTFCartLin(\"test\", 3)\n","sub_path":"reconcycle_flexbe_states/src/reconcycle_flexbe_states/CallAction_TF_TrapVel.py","file_name":"CallAction_TF_TrapVel.py","file_ext":"py","file_size_in_byte":6161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"619134193","text":"from django.shortcuts import render, redirect\nfrom django.views.generic import TemplateView\nfrom django.http import HttpResponse, JsonResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .models import Room, Image_Model, Video_Model, cp_page\nfrom .forms import Image_Form, Video_Form, registration_form\nfrom django.contrib.auth.decorators import login_required\nimport json\nimport sys\n\nimport datetime\nimport calendar\nfrom django.utils.safestring import mark_safe\nfrom .utils import EventCalendar\nfrom django.template import loader\nfrom .models import Santa\n\n# Create your views here.\n\n\n\nclass HomePageView(TemplateView):\n template_name='home.html'\n\nclass AboutPageView(TemplateView):\n template_name = 'about.html'\n\ndef media_index(request):\n\n return render(request, 'media_index.html')\n\ndef register(request):\n if request.method == 'POST':\n form = registration_form(request.POST)\n if form.is_valid():\n user = cp_page(\n username=form.cleaned_data['username'],\n f_name=form.cleaned_data['f_name'],\n l_name=form.cleaned_data['l_name'],\n email=form.cleaned_data['email'],\n wishlist=form.cleaned_data['wishlist'],\n )\n user.save()\n form.save(commit=True)\n return redirect(\"/\")\n else:\n form = registration_form()\n context = {\"form\":form}\n return render(request,\"registration/register.html\",context)\n\n# adapted from https://gearheart.io/blog/creating-a-chat-with-django-channels/\n@login_required(login_url='/login/')\ndef ChatPageView(request):\n \"\"\"\n Root page view. This is essentially a single-page app, if you ignore the\n login and admin parts.\n \"\"\"\n # Get a list of rooms, ordered alphabetically\n rooms = Room.objects.order_by(\"title\")\n\n # Render that in the index template\n return render(request, \"chat.html\", {\n \"rooms\": rooms,\n})\n\n@login_required(login_url='/login/')\ndef image_view(request):\n if request.method == 'POST':\n form = Image_Form(request.POST, request.FILES)\n if form.is_valid():\n images = Image_Model(\n image=form.cleaned_data['image'],\n image_description=form.cleaned_data['image_description'],\n )\n images.save()\n return redirect(\"/\")\n else:\n form = Image_Form()\n context={\n \"form\":form\n }\n return render(request, 'image.html',context)\n\n@login_required(login_url='/login/')\ndef video_view(request):\n if request.method == 'POST':\n form = Video_Form(request.POST, request.FILES)\n if form.is_valid():\n videos = Video_Model(\n video=form.cleaned_data['video_url'],\n video_title=form.cleaned_data['video_title'],\n video_description=form.cleaned_data['video_description']\n )\n videos.save()\n return redirect(\"/\")\n else:\n form = Video_Form()\n context={\n \"form\":form\n }\n return render(request, 'video.html',context)\n\n@login_required(login_url='/login/')\ndef media_view(request):\n if request.method == 'GET':\n video_list = Video_Model.objects.all()\n image_list = Image_Model.objects.all()\n context={\n \"videos\":video_list,\n \"images\":image_list\n }\n return render(request, 'media_index.html', context)\n\n@login_required(login_url='/login/')\ndef cp_view(request):\n if request.method == 'GET':\n user_data = cp_page\n context={\n \"username\":user_data.username,\n \"f_name\":user_data.f_name,\n \"l_name\":user_data.l_name,\n \"email\":user_data.email,\n \"wishlist\":user_data.wishlist,\n }\n return render(request, 'control.html', context)\n\n\n#adapted from https://alexpnt.github.io/2017/07/15/django-calendar/\n@login_required(login_url='/login/')\ndef public_changelist_view(request, extra_context=None):\n after_day = request.GET.get('day__gte', None)\n extra_context = extra_context or {}\n\n if not after_day:\n d = datetime.date.today()\n else:\n try:\n split_after_day = after_day.split('-')\n d = datetime.date(year=int(split_after_day[0]), month=int(split_after_day[1]), day=1)\n except:\n d = datetime.date.today()\n\n previous_month = datetime.date(year=d.year, month=d.month, day=1) # find first day of current month\n previous_month = previous_month - datetime.timedelta(days=1) # backs up a single day\n previous_month = datetime.date(year=previous_month.year, month=previous_month.month,\n day=1) # find first day of previous month\n\n last_day = calendar.monthrange(d.year, d.month)\n next_month = datetime.date(year=d.year, month=d.month, day=last_day[1]) # find last day of current month\n next_month = next_month + datetime.timedelta(days=1) # forward a single day\n next_month = datetime.date(year=next_month.year, month=next_month.month,\n day=1) # find first day of next month\n\n #extra_context['previous_month'] = reverse('admin:events_event_changelist') + '?day__gte=' + str(\n # previous_month)\n #extra_context['next_month'] = reverse('admin:events_event_changelist') + '?day__gte=' + str(next_month)\n\n cal = EventCalendar()\n html_calendar = cal.formatmonth(d.year, d.month, withyear=True)\n html_calendar = html_calendar.replace('= 0 and x <= width and y >= self.height() and y <= height + self.height():\n pass # Item was clicked do not hide popup\n else:\n self.list_widget.setCurrentRow(0)\n super().hidePopup()\n\n def stateChanged(self, state=None):\n # state is unused\n selected_data = []\n count = self.list_widget.count()\n\n for i in range(1, count):\n check_box = self.list_widget.itemWidget(self.list_widget.item(i))\n if check_box.isChecked():\n selected_data.append(check_box.text())\n\n if selected_data:\n self.line_edit.setText(', '.join(selected_data))\n else:\n self.line_edit.clear()\n self.updated.emit()\n\n def addItem(self, text, user_data=None):\n # user_data is unused\n list_widget_item = QListWidgetItem(self.list_widget)\n check_box = QCheckBox(self)\n check_box.setText(text)\n self.list_widget.addItem(list_widget_item)\n self.list_widget.setItemWidget(list_widget_item, check_box)\n check_box.stateChanged.connect(self.stateChanged)\n\n def currentText(self):\n if self.line_edit.text():\n return [_.strip() for _ in self.line_edit.text().split(\",\")]\n return []\n\n def addItems(self, texts: list):\n for s in texts:\n self.addItem(s)\n\n def count(self):\n return max(0, self.list_widget.count() - 1) # Do not count the search bar\n\n def onSearch(self, s):\n for i in range(self.list_widget.count()):\n check_box = self.list_widget.itemWidget(self.list_widget.item(i))\n if s.lower() in check_box.text().lower():\n self.list_widget.item(i).setHidden(False)\n else:\n self.list_widget.item(i).setHidden(True)\n\n def itemClicked(self, index):\n if index != self.search_bar_index:\n check_box = self.list_widget.itemWidget(self.list_widget.item(index))\n check_box.setChecked(not check_box.isChecked())\n\n def setSearchBarPlaceholderText(self, placeholder_text):\n self.search_bar.setPlaceholderText(placeholder_text)\n\n def setPlaceholderText(self, placeholder_text):\n self.line_edit.setPlaceholderText(placeholder_text)\n\n def clear(self):\n self.list_widget.clear()\n current_item = QListWidgetItem(self.list_widget)\n self.search_bar = QLineEdit(self)\n self.search_bar.setPlaceholderText(\"Search...\")\n self.search_bar.setClearButtonEnabled(True)\n self.list_widget.addItem(current_item)\n self.list_widget.setItemWidget(current_item, self.search_bar)\n\n self.search_bar.textChanged.connect(self.onSearch)\n\n def wheelEvent(self, wheel_event):\n pass # Do not handle the wheel event\n\n def eventFilter(self, obj, event):\n if obj is self.line_edit and event.type() == QEvent.MouseButtonRelease:\n self.showPopup()\n return False\n\n def setCurrentText(self, text):\n pass\n\n def setCurrentTexts(self, texts):\n count = self.list_widget.count()\n\n for i in range(1, count):\n check_box = self.list_widget.itemWidget(self.list_widget.item(i))\n check_box_string = check_box.text()\n if check_box_string in texts:\n check_box.setChecked(True)\n\n def ResetSelection(self):\n count = self.list_widget.count()\n\n for i in range(1, count):\n check_box = self.list_widget.itemWidget(self.list_widget.item(i))\n check_box.setChecked(False)\n\n\n# Testing\n# Run \"python -m app.editor.multi_select_combo_box\" from main directory\nif __name__ == '__main__':\n import sys\n from PyQt5.QtWidgets import QApplication, QHBoxLayout, QDialog\n app = QApplication(sys.argv)\n\n class BasicDialog(QDialog):\n def __init__(self, parent=None):\n super().__init__(parent)\n\n layout = QHBoxLayout(self)\n self.setLayout(layout)\n\n widget = MultiSelectComboBox()\n widget.addItem(\"Japan\")\n widget.addItem(\"China\")\n widget.addItem(\"Korea\")\n layout.addWidget(widget)\n\n window = BasicDialog()\n window.show()\n app.exec_()\n","sub_path":"app/extensions/multi_select_combo_box.py","file_name":"multi_select_combo_box.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"375392518","text":"# -*- coding: utf-8 -*-\n# sifter/sifter/sifter.py\n\n'''\n --------------------------------------------------------------\n sifter module.\n \n Jan 2020\n Matt Payne & Mike Alexandersen\n \n This module provides overall access to sifter:\n sifter searches the ITF\n\n\n *WRITE MORE STUFF*\n \n --------------------------------------------------------------\n '''\n\n\n# Import third-party packages\n# --------------------------------------------------------------\nimport sys, os\nimport argparse\n\n\n# Import neighboring packages\n# --------------------------------------------------------------\nfrom . import query # Yay, python3 relative import :-)\n\n# Set default search parameters\n# --------------------------------------------------------------\ndefault_dict = {\n 'cons_arcsecs' : 2.0,\n 'max_residuals_arcsecs' : 500.0,\n 'orbit_file' : 'cheby.json',\n}\n\ndef sifter():\n \n \n # -------- PARSE ANY COMMAND-LINE ARGUMENTS ----------------\n arg_parser = argparse.ArgumentParser()\n\n arg_parser.add_argument('-s', '--screen', dest='print_to_screen', action=\"store_true\",\n help=\"e.g.: sifter.py -s. Prints output to screen. \\\n Default = False.\")\n\n arg_parser.add_argument('-c', '--consistency', dest='cons_arcsecs', default = default_dict['cons_arcsecs'],\n help=\"e.g.: sifter.py -c 1.0 . Sets 'consistency' in arc-seconds. \\\n Default value = default_dict['cons_arcsecs'] = %r .\" % default_dict['cons_arcsecs'])\n\n arg_parser.add_argument('-m', '--maxres', dest='max_residuals_arcsecs', default = default_dict['max_residuals_arcsecs'],\n help=\"e.g.: sifter.py -m 1000.0 . Sets 'maximum residuals' in arc-seconds. \\\n Default value = default_dict['max_residuals_arcsecs'] = %r .\" % default_dict['max_residuals_arcsecs'])\n\n arg_parser.add_argument('-o', '--orbfile', dest='orbit_file', default = default_dict['orbit_file'],\n help=\"e.g.: sifter.py -o K20B12Q.json : Sets name of the input file that contains the orbital information, \\\n N.B. Currently assumes will be JSON format and contain CHEBYSHEV COEFFS. \\\n Default value = default_dict['orbit_file'] = %r .\" % default_dict['orbit_file'])\n\n\n # Add an optional additional argument:\n arg_parser.add_argument('arg', nargs='?', default=None)\n\n # Parse the arguments:\n args = arg_parser.parse_args()\n\n # **DEBUGGING** Print out variable names & values\n for k,v in args.__dict__.items():\n print(k,v)\n\n\n\n # -------- EXECUTE QUERY (TO SEARCH ITF) ----------------\n #\n # (i) Check the input file of cheby-coeffs exists\n # - Could/Should extend this to check its actually a valid file ...\n # asset os.path.isfile( args.orbit_file ), \\\n # 'Could not proceed with query as %r does not appear to exist ... \\n ... perhaps supply a full filepath?' % args.orbit_file\n #\n # (ii) Read the input file of cheby-coeffs into a dictionary\n #with open( args.orbit_file ) as json_file:\n # cheby_dict = json.load(json_file)\n\n # (iii) Run the main sifter-query to see if the input orbit matches anything in the ITF\n #query.query( cheby_dict )\n\n\nif __name__ == '__main__':\n sifter()\n\n\n\n","sub_path":"sifter/sifter.py","file_name":"sifter.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"488312848","text":"# -*- coding: utf-8 -*-\n\n# 2019/1/16 0016 上午 11:11 \n\n__author__ = 'RollingBear'\n\nimport threading\nimport time\n\n\ndef Seeker(cond, name):\n time.sleep(2)\n cond.acquire()\n print('%s close eyes' % name)\n # 1\n cond.notify()\n # 2\n cond.wait()\n for i in range(3):\n print('%s is finding' % name)\n time.sleep(2)\n # 3\n cond.notify()\n cond.release()\n print('%s win' % name)\n\n\ndef Hider(cond, name):\n cond.acquire()\n # 1\n cond.wait()\n for i in range(2):\n print('%s is hiding' % name)\n time.sleep(3)\n print('%s is already hided' % name)\n # 2\n cond.notify()\n # 3\n cond.wait()\n cond.release()\n print('%s has been findes' % name)\n\n\nif __name__ == '__main__':\n cond = threading.Condition()\n seeker = threading.Thread(target=Seeker, args=(cond, 'seeker'))\n hider = threading.Thread(target=Hider, args=(cond, 'hider'))\n seeker.start()\n hider.start()\n","sub_path":"Threading_Condition.py","file_name":"Threading_Condition.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"254362491","text":"from database.database import create_table_database, query_database\nfrom entities.movie import Movie\n\n\ndef create_movies_table():\n query = \"\"\"CREATE TABLE IF NOT EXISTS movies (\n moviesId INTEGER PRIMARY KEY AUTOINCREMENT,\n movie_name TEXT,\n release_date DATE,\n rating REAL,\n genre TEXT,\n studioId INTEGER,\n boxofficeId INTEGER,\n FOREIGN KEY (studioId) REFERENCES studios(studioId),\n FOREIGN KEY (boxofficeId) REFERENCES box_offices(boxofficeId))\"\"\"\n\n create_table_database(query)\n# Isspausdina lentele\n# query_database(\"PRAGMA table_info(movies)\")\n\n# Dropina lentele\n# create_table_database(\"DROP TABLE movies\")\n# create_movies_table()\n\ndef create_movie(Movie):\n query = \"\"\"INSERT INTO movies VALUES (?, ?, ?, ? ,? ,?, ?)\"\"\"\n params = (Movie.moviesId, Movie.movie_name, Movie.release_date, Movie.rating, Movie.genre,\n Movie.studioId, Movie.boxofficeId)\n query_database(query, params)\n\nMovie1 = Movie(None, 'Boratas' , 2008, 8, 'Komedija',\n None, None)\ncreate_movie(Movie1)\n\ndef get_movie(Movie):\n query = \"\"\"SELECT * FROM movies WHERE moviesId = (?) OR movie_name = (?) OR release_date = (?)\n OR rating = (?) OR genre = (?) OR studioId = (?) OR boxofficeId = (?)\"\"\"\n params = (Movie.moviesId, Movie.movie_name, Movie.release_date, Movie.rating, Movie.genre, Movie.studioId,\n Movie.boxofficeId)\n query_database(query, params, True)\n\n# get_movie(Movie1)\n\ndef update_movie(Movie):\n\n query = \"\"\"UPDATE movies SET movie_name = 'Belekas' WHERE movie_name = (?) OR moviesId = (?) OR release_date = (?)\n OR rating = (?) OR genre = (?) OR studioId = (?) OR boxofficeId = (?) = (?)\"\"\"\n parameters = (Movie.moviesId, Movie.movie_name, Movie.release_date, Movie.rating, Movie.genre, Movie.studioId,\n Movie.boxofficeId)\n querry_database(query, parameters, True)\n\n\n# update_movie(Movie1)\n\ndef delete_movie(Movie):\n query = \"\"\"DELETE FROM movies WHERE moviesId = (?) OR movie_name = (?) OR release_date = (?)\n OR rating = (?) OR genre = (?) OR studioId = (?) OR boxofficeId = (?) \"\"\"\n parameters = (Movie.moviesId, Movie.movie_name, Movie.release_date, Movie.rating, Movie.genre, Movie.studioId,\n Movie.boxofficeId)\n querry_database(query, parameters, True)\n\n\n# delete_movie(Movie1)","sub_path":"database/modals/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"404077010","text":"\n# Exercise 9.\n\n# A string is a palindrome if it is identical forward and backward. For example “anna”, “civic”, “level” and “hannah” are all examples of palindromic words. Write a program that reads a string from the user and uses a loop to determines whether or not it is a palindrome. Display the result, including a meaningful output message.\n\ninput_9 = input('Enter a word: ')\nreverse_9 = input_9[-1:-len(input_9)-1:-1]\nif input_9 == reverse_9:\n print('{} equals {}. This is a palindromic word.' .format(input_9, reverse_9))\nelse:\n print('{} does not equal {}. This is not a palindromic word.' .format(input_9, reverse_9))\n\n","sub_path":"4Python/5HomeWork/9hw.py","file_name":"9hw.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"571981228","text":"from flask import Flask, render_template, url_for\nfrom forms import RegistrationForm, LoginForm\napp = Flask(__name__)\n\n# Key is just used for testing and is changed if public version of any webside comes out.\napp.config[\"SECRET_KEY\"] = \"f747ed855cb68bb1c4cb20650823b468\"\n\nposts = [\n {\n \"author\": \"Tex Nevada\",\n \"title\": \"Something title\",\n \"content\": \"HELLOW GUYS. I KNOW WEB CODING NOW\",\n \"date_posted\": \"06/07/2019\",\n },\n {\n \"author\": \"Tex Nevada\",\n \"title\": \"Whoop whoop\",\n \"content\": \"Its the sound of da police\",\n \"date_posted\": \"06/07/2019\",\n },\n]\n\n@app.route(\"/\")\n@app.route(\"/home\")\ndef index():\n return render_template(\"home.html\", posts=posts)\n\n@app.route(\"/about\")\ndef about():\n return render_template(\"about.html\", title=\"About\")\n\n@app.route(\"/nukecodes\")\ndef nukecodes():\n return render_template(\"nukecodes.html\", title=\"Nuke codes\")\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n form = RegistrationForm()\n return render_template(\"register.html\", title=\"Register\", form=form)\n\n@app.route(\"/login\")\ndef login():\n form = LoginForm()\n return render_template(\"login.html\", title=\"Login\", form=form)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"208636723","text":"# Day 13\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[List[int]]\n :type newInterval: List[int]\n :rtype: List[List[int]]\n \"\"\"\n result = []\n \n for i, [x,y] in enumerate(intervals):\n if y < newInterval[0]: #interval is before new\n result.append(intervals[i])\n elif x > newInterval[1]: #interval is after \n result.append(intervals[i])\n else: #interval intersects with new interval\n newInterval[0] = min(x, newInterval[0])\n newInterval[1] = max(y, newInterval[1])\n \n \n result.append(newInterval) \n result.sort()\n \n return result\n","sub_path":"intervalInsert.py","file_name":"intervalInsert.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"384432484","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nimport tensorflow as tf\nimport numpy as np\n\n#创造数据\nX_data = np.random.rand(100).astype(np.float32)\ny_data = X_data * 0.3 + 0.1\n\n#创造结构\nWeights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))\nbiases = tf.Variable(tf.zeros([1]))\n\ny = Weights*X_data + biases\n\nloss = tf.reduce_mean(tf.square(y - y_data))\noptimizer = tf.train.GradientDescentOptimizer(0.5)\ntrain = optimizer.minimize(loss)\n\ninit = tf.global_variables_initializer()\n\n#\nsess = tf.Session()\nsess.run(init)\nfor step in range(200):\n sess.run(train)\n if step % 20 == 0:\n print(step,sess.run(Weights),sess.run(biases))\nsess.close()","sub_path":"tensorflow_study/003.py","file_name":"003.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"101560235","text":"# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n##############################################################################\n\n\nfrom osv import fields, osv\nimport time\n\nclass promo_rec(osv.osv_memory):\n _name = \"promo.rec\"\n\n _columns = {\n 'job_id': fields.many2many('hr.job','jobs_emp_rel','employee_job_comp','job_emps_id', 'Job Name',required=True ),\n 'payroll_id': fields.many2one('hr.salary.scale', 'Salary Scale',required=True ),\n# 'degree': fields.many2one('hr2.degree.names', 'Degree Name',required=True ),\n 'degree': fields.many2one('hr.salary.degree', 'Degree Name',required=True ),\n 'from': fields.date(\"Start Date\", required= True),\n 'year': fields.integer('Year', required=True),\n \n }\n _defaults = {\n 'year': int(time.strftime('%Y')),\n \n }\n \n def print_report(self, cr, uid, ids, context=None):\n datas = {}\n if context is None:\n context = {}\n data = self.read(cr, uid, ids)[0]\n datas = {\n 'ids':[],\n 'model': 'hr.employee',\n 'form': data\n }\n return {\n 'type': 'ir.actions.report.xml',\n 'report_name': 'promo.rec',\n 'datas': datas,\n }\n\npromo_rec()\n","sub_path":"v_7/Dongola/addons_backup/7-1/hr_payroll_custom/wizard1/wizard_promotion_priority_report.py","file_name":"wizard_promotion_priority_report.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"369605532","text":"import getpass\nimport json\nimport os\nimport pathlib\nimport shutil\nimport sys\nimport tkinter as tk\n\nfrom db_logger_gui import MainApp, ScreenRes, check_singleton\nfrom make_db_entry import DBSessionLogger\n\n\ndef validate_config(config):\n keys_non_null = [\n \"database_name\",\n \"database_relpath\",\n \"networkdrive_hostname\",\n \"daq_relpath\",\n ]\n\n for k in keys_non_null:\n if not config.get(k):\n raise ValueError(f\"Config is NOT valid: entry `{k}` is not present or Null.\")\n\n return True\n\ndef main():\n # check singleton\n try:\n sing = check_singleton()\n except OSError as e:\n root = tk.Tk()\n root.title('Error')\n message = \"Only one instance of the NexusLIMS \" + \\\n \"Session Logger can be run at one time. \" + \\\n \"Please close the existing window if \" + \\\n \"you would like to start a new session \" \\\n \"and run the application again.\"\n if sys.platform == 'win32':\n message = message.replace('be run ', 'be run\\n')\n message = message.replace('like to ', 'like to\\n')\n root.withdraw()\n tk.messagebox.showerror(parent=root, title=\"Error\", message=message)\n sys.exit(0)\n\n\n # config\n config_dir = os.path.join(pathlib.Path.home(), \".nexuslims\", \"gui\")\n if not os.path.exists(config_dir):\n os.makedirs(config_dir)\n\n config_fn = os.path.join(config_dir, \"config.json\")\n if not os.path.isfile(config_fn):\n # default config\n default_fn = os.path.abspath(__file__)\n default_fn = default_fn.replace(os.path.basename(__file__), \"config.json\")\n shutil.copy(default_fn, config_fn)\n\n msg = (\"No config file found, the default config is copied to %s. \"\n \"Modify the configuration appropiately and run the application again.\") % config_fn\n root = tk.Tk()\n root.title(\"Error\")\n root.withdraw()\n tk.messagebox.showerror(parent=root, title=\"Error\", message=msg)\n sys.exit(0)\n\n try:\n config = json.loads(open(config_fn).read())\n validate_config(config)\n except Exception as e:\n root = tk.Tk()\n root.title(\"Error\")\n root.withdraw()\n tk.messagebox.showerror(parent=root, title=\"Error\", message=str(e))\n sys.exit(0)\n\n # user\n login = getpass.getuser()\n\n dbdl = DBSessionLogger(config=config, user=login, verbosity=2)\n sres = ScreenRes(dbdl)\n\n root = MainApp(dbdl, screen_res=sres)\n root.protocol(\"WM_DELETE_WINDOW\", root.on_closing)\n root.mainloop()\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/db_logger_gui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"195326058","text":"# coding: utf-8\nimport json\nfrom django.http.response import HttpResponse, JsonResponse\nfrom django.contrib import auth\nfrom commons.django_model_utils import get_or_none\nfrom commons.django_views_utils import ajax_login_required\nfrom core.service import log_svc, globalsettings_svc, url_service\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.datastructures import MultiValueDictKeyError\n\n\ndef dapau(request):\n raise Exception(\"break on purpose\")\n\n\n@csrf_exempt\ndef login(request):\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = auth.authenticate(username=username, password=password)\n user_dict = None\n if user is not None:\n if user.is_active:\n auth.login(request, user)\n log_svc.log_login(request.user)\n user_dict = _user2dict(user)\n return JsonResponse(user_dict, safe=False)\n\n\ndef logout(request):\n if request.method.lower() != \"post\":\n raise Exception(\"Logout only via post\")\n if request.user.is_authenticated:\n log_svc.log_logout(request.user)\n auth.logout(request)\n return HttpResponse(\"{}\", content_type=\"application/json\")\n\n\ndef whoami(request):\n i_am = (\n {\"user\": _user2dict(request.user), \"authenticated\": True,}\n if request.user.is_authenticated\n else {\"authenticated\": False}\n )\n return JsonResponse(i_am)\n\n\ndef settings(request):\n le_settings = globalsettings_svc.list_settings()\n return JsonResponse(le_settings)\n\n\n@ajax_login_required\ndef url(request):\n user = request.user.pk\n if request.method.lower() == \"get\":\n urls = url_service.list_urls(user)\n return JsonResponse(urls, safe=False)\n if request.method.lower() == \"post\":\n try:\n url = url_service.add_url(request.POST[\"url\"], user)\n return JsonResponse(url, safe=False, status=201)\n except MultiValueDictKeyError:\n return JsonResponse({\"message\": \"Bad request\"}, status=400)\n\n\n@ajax_login_required\ndef redirect_url(request, short_url):\n user = request.user.pk\n if request.method.lower() == \"get\" and short_url:\n url = url_service.get_url(short_url)\n if url:\n return JsonResponse(url, safe=False)\n return JsonResponse({\"message\": \"Not Found\"}, status=404)\n return JsonResponse({\"message\": \"Bad request\"}, status=400)\n\n\ndef _user2dict(user):\n d = {\n \"id\": user.id,\n \"name\": user.get_full_name(),\n \"username\": user.username,\n \"first_name\": user.first_name,\n \"last_name\": user.last_name,\n \"email\": user.email,\n \"permissions\": {\"ADMIN\": user.is_superuser, \"STAFF\": user.is_staff,},\n }\n return d\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"265115493","text":"from coffin.shortcuts import render_to_response\nfrom coffin.template import RequestContext\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.mail import send_mail, BadHeaderError\nfrom django.views.decorators.cache import never_cache\nfrom trend import settings\nfrom json import dumps\nfrom django.contrib.auth.hashers import make_password\nfrom django.contrib.auth.models import UserManager\nfrom django.db import connection\nfrom urlparse import urlparse\nimport urlparse\nimport urllib2\nimport urllib\nfrom django.contrib.auth import login, authenticate, logout\nimport os\nimport json\nfrom django.contrib.gis.geoip import GeoIP\n\n\n\ndef o_nama(request, template_name=\"personalna/o_nama.html\"):\n \n return render_to_response(template_name, locals(), context_instance=RequestContext(request))\n\n\n\ndef kontakt(request, template_name=\"personalna/kontakt.html\"):\n \n return render_to_response(template_name, locals(), context_instance=RequestContext(request))\n\n\n\n\ndef contact_us(request):\n try:\n send_mail(request.GET.get('kompanija', ''), request.GET['forma_tekst'] + '\\nOdgovoriti ', request.GET['email'],\n [settings.EMAIL_HOST_USER], fail_silently=False)\n except BadHeaderError: \n return HttpResponse('Invalid header found.Possible attempt of Header Injection') \n \n return HttpResponse('Your message was successfully sent to Homegirl Shopping.com. Thank you for contacting us.')\n\n\n\n\n@never_cache\ndef google_authorizacija(request):\n from trend.google import Google\n a = Google(json = {'scope': 'email profile', 'state': '/profile', 'redirect_uri': 'http://www.homegirlshopping.com/google', 'response_type': 'code', 'client_id': '410445462280-nikhfhf0mcvoua4a31kqdgfkro3t8cqe.apps.googleusercontent.com', 'approval_prompt': 'force'})\n return HttpResponseRedirect(a.generisi_link())\n\n@never_cache\ndef google(request):\n from trend.google import Google\n code = str(request.GET['code'])\n a = Google(json = { 'code': code, 'client_id':'410445462280-nikhfhf0mcvoua4a31kqdgfkro3t8cqe.apps.googleusercontent.com', 'client_secret':'lC3cuD5rUSIMDEQ7PVVBvVxs', 'redirect_uri': 'http://www.homegirlshopping.com/google', 'grant_type': 'authorization_code', 'key': '410445462280-nikhfhf0mcvoua4a31kqdgfkro3t8cqe.apps.googleusercontent.com' })\n a = Google(token=a.token_sesija())\n o = a.google_api()\n konekcija = connection.cursor()\n konekcija.execute('select u.id from auth_user as u inner join personalna_userprofile as up on up.user_id = u.id where up.identifikacija=%s', [o['id']])\n korisnik = konekcija.fetchone()\n if korisnik == None:\n sifra = UserManager().make_random_password(length=12)\n konekcija.execute(\"INSERT INTO auth_user (username, password, first_name, last_name, email, is_staff, is_active, is_superuser, last_login, date_joined) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())\", [o['displayName'], make_password(sifra), o['name']['givenName'], o['name']['familyName'], '', '1', '1', '0'])\n konekcija.execute(\"select u.id from auth_user as u where u.username=%s\", [o['displayName']])\n user_id = konekcija.fetchone()[0]\n try:\n email = o['emails'][0]['value']\n except KeyError:\n email = 'No Available Data' \n try:\n godiste = o['birthday']\n except KeyError:\n godiste = 'None' \n u = urlparse.urlparse(o['image']['url'])\n url_slika = u.scheme + '://' + u.netloc + u.path + '?sz=250' \n avatar = a.string_generator(o['displayName']) \n konekcija.execute(\"INSERT INTO personalna_userprofile (user_id, ime, prezime, email, slika, identifikacija, rodjenje, ip_adresa) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\", [user_id, o['name']['givenName'], o['name']['familyName'], email, avatar + u.path[-4:], o['id'], godiste, request.META.get('REMOTE_ADDR') ])\n \n \n s = urllib2.build_opener().open(url_slika).read()\n f = open('/NoviSajt/trendsajt/static/profili/' + avatar + u.path[-4:], 'wb+')\n f.write(s)\n f.close() \n autentifikacija = authenticate(username=o['displayName'], password=sifra)\n login(request, autentifikacija)\n \n else:\n sifra = UserManager().make_random_password(length=12)\n konekcija.execute(\"UPDATE auth_user SET password=%s WHERE auth_user.username=%s\", [make_password(sifra), o['displayName']])\n konekcija.execute('select up.slika from personalna_userprofile as up where up.identifikacija=%s', [o['id']])\n slika_b = konekcija.fetchone()[0]\n \n os.remove('/NoviSajt/trendsajt/static/profili/%s' % slika_b)\n \n avatar = a.string_generator(o['displayName']) \n u = urlparse.urlparse(o['image']['url'])\n url_slika = u.scheme + '://' + u.netloc + u.path + '?sz=250' \n s = urllib2.build_opener().open(url_slika).read()\n f = open('/NoviSajt/trendsajt/static/profili/' + avatar + u.path[-4:], 'wb+')\n f.write(s)\n f.close() \n \n konekcija.execute(\"UPDATE personalna_userprofile as up SET slika=%s WHERE up.identifikacija=%s\", [avatar + u.path[-4:], o['id']])\n \n \n \n \n autentifikacija = authenticate(username=o['displayName'], password=sifra)\n login(request, autentifikacija)\n \n \n return HttpResponseRedirect(getattr(settings, \"LOGIN_REDIRECT_URL\", \"/\"))\n \n \n \n \n \n \n\ndef login_provjera(request):\n \n if request.user.is_authenticated() == True:\n \n return HttpResponse('OK')\n \n \n else:\n return HttpResponse('No')\n \n \n\n\ndef like_provjera(request):\n from django.db import connection\n konekcija = connection.cursor() \n konekcija.execute('select au.id from auth_user as au inner join personalna_userprofile as uv on uv.user_id = au.id where uv.ip_adresa=%s', [request.META.get('REMOTE_ADDR')]) \n try:\n id = konekcija.fetchone()[0]\n except TypeError:\n id = None \n if request.user.is_authenticated() == False and id == None:\n \n return HttpResponse('LIKE')\n \n \n \n else:\n return HttpResponse('NO-LIKE')\n\n\n\ndef generisi_akaunt(request):\n konekcija = connection.cursor()\n konekcija.execute('select up.ime, up.prezime, up.slika from personalna_userprofile as up inner join auth_user as au on au.id = up.user_id where au.username=%s', [request.user.username])\n profil = konekcija.fetchall()\n rezultat = []\n for n in profil:\n json = {}\n json['ime'] = n[0]\n json['prezime'] = str(n[1])\n json['slika'] = str(n[2])\n rezultat.append(json) \n \n ajax = dumps(rezultat)\n mimetype = 'application/json'\n \n return HttpResponse(ajax, mimetype) \n\n\n\n\n\n\ndef logout_f(request):\n logout(request)\n return HttpResponseRedirect('/')\n \n \n \n \n \n\n\ndef facebook_authorizacija(request):\n argumenti = {'client_id': settings.FACEBOOK_APP_ID, \n 'client_secret': settings.FACEBOOK_APP_SECRET,\n 'scope': settings.FACEBOOK_SCOPE,\n 'redirect_uri': request.build_absolute_uri('/fb-login'),\n }\n return HttpResponseRedirect('https://www.facebook.com/dialog/oauth?' + urllib.urlencode(argumenti)) \n \n \n \n\n\n\n\n\ndef fb_login(request):\n argumenti = {'client_id': settings.FACEBOOK_APP_ID,\n 'client_secret': settings.FACEBOOK_APP_SECRET,\n 'scope': settings.FACEBOOK_SCOPE,\n 'redirect_uri': request.build_absolute_uri('/fb-login'),\n 'code':request.GET['code']\n } \n token = urlparse.parse_qs(urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(argumenti)).read())['access_token'][0]\n fb_profil = json.load(urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % token))\n konekcija = connection.cursor()\n konekcija.execute('select a.id from izdvojeno_amazon as a')\n ids = konekcija.fetchall()\n konekcija.execute('select a.artikal, a.url, a.opis, a.brend, a.slika_1 from izdvojeno_amazon as a where a.id = %s', [rand_artikal(ids)[0]])\n artikal = konekcija.fetchone()\n from trend.google import Facebook\n c = Facebook(token, fb_profil['id'])\n c.fb_objavi(**{'name': artikal[0], 'link': request.build_absolute_uri('/article/' + artikal[1]), 'caption': artikal[0] + ' ' + artikal[3], 'description': artikal[2], 'picture': artikal[4]})\n \n \n \n \n \n konekcija.execute('select u.id from auth_user as u inner join personalna_userprofile as up on up.user_id = u.id where up.identifikacija=%s', [fb_profil['id']])\n korisnik = konekcija.fetchone()\n if korisnik == None:\n sifra = UserManager().make_random_password(length=12)\n konekcija.execute(\"INSERT INTO auth_user (username, password, first_name, last_name, email, is_staff, is_active, is_superuser, last_login, date_joined) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())\", [fb_profil['name'].replace(\" \", \"\").lower(), make_password(sifra), fb_profil['first_name'], fb_profil['last_name'], '', '1', '1', '0'])\n konekcija.execute(\"select u.id from auth_user as u where u.username=%s\", [fb_profil['name'].replace(\" \", \"\").lower()])\n user_id = konekcija.fetchone()[0]\n try:\n email = fb_profil['email']\n except KeyError:\n email = 'No Available Data' \n try:\n godiste = fb_profil['birthday']\n except KeyError:\n godiste = 'None' \n \n \n c = urllib2.Request(\"http://graph.facebook.com/%s/picture?type=large\" % fb_profil['id'])\n cr = urllib2.urlopen(c).geturl()\n format = urlparse.urlparse(cr).path[-4:]\n \n konekcija.execute(\"INSERT INTO personalna_userprofile (user_id, ime, prezime, email, slika, identifikacija, rodjenje, ip_adresa) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\", [user_id, fb_profil['first_name'], fb_profil['last_name'], email, fb_profil['id'] + format, fb_profil['id'], godiste, request.META.get('REMOTE_ADDR') ])\n \n pc = urllib2.urlopen(cr).read()\n f = open('/NoviSajt/trendsajt/static/profili/' + fb_profil['id'] + format, 'wb+')\n f.write(pc)\n f.close() \n autentifikacija = authenticate(username=fb_profil['name'].replace(\" \", \"\").lower(), password=sifra)\n login(request, autentifikacija)\n \n else:\n sifra = UserManager().make_random_password(length=12)\n konekcija.execute(\"SELECT au.username from auth_user AS au inner join personalna_userprofile as pu on pu.user_id = au.id WHERE pu.identifikacija =%s\", [fb_profil['id']])\n user = konekcija.fetchone()[0]\n konekcija.execute(\"UPDATE auth_user SET password=%s WHERE auth_user.username=%s\", [make_password(sifra), user])\n konekcija.execute('select up.slika from personalna_userprofile as up where up.identifikacija=%s', [fb_profil['id']])\n slika_b = konekcija.fetchone()[0]\n try:\n os.remove('/NoviSajt/trendsajt/static/profili/%s' % slika_b)\n except OSError:\n pass\n c = urllib2.Request(\"http://graph.facebook.com/%s/picture?type=large\" % fb_profil['id'])\n cr = urllib2.urlopen(c).geturl() \n format = urlparse.urlparse(cr).path[-4:]\n \n pc = urllib2.urlopen(cr).read()\n f = open('/NoviSajt/trendsajt/static/profili/' + fb_profil['id'] + format, 'wb+')\n f.write(pc)\n f.close() \n \n konekcija.execute(\"UPDATE personalna_userprofile as up SET slika=%s WHERE up.identifikacija=%s\", [fb_profil['id'] + format, fb_profil['id']])\n \n \n \n \n autentifikacija = authenticate(username=user, password=sifra)\n login(request, autentifikacija)\n \n \n return HttpResponseRedirect(\"/profile\") \n \n \n\n\ndef rand_artikal(ids):\n import random\n id = random.sample(set([n[0] for n in ids]), 1)\n return id\n\n\n\n\n\n\n\n@never_cache \ndef profil(request, template_name=\"personalna/profil.html\"):\n konekcija = connection.cursor()\n konekcija.execute('select up.ime, up.prezime, up.slika, up.email, up.rodjenje from personalna_userprofile as up inner join auth_user as au on au.id = up.user_id where au.username=%s', [request.user.username])\n profile = konekcija.fetchone()\n ime_p = profile[0] + \" \" + profile[1]\n ip = GeoIP()\n klijent_drzava = ip.country(request.META.get('REMOTE_ADDR'))['country_name']\n konekcija.execute('SELECT transakcije_drzave.d_logo FROM transakcije_drzave WHERE transakcije_drzave.drzava=%s', [klijent_drzava])\n zastava = konekcija.fetchone()[0]\n \n konekcija.execute('select a.artikal, a.url, a.slika_1 from izdvojeno_amazon as a inner join personalna_userviews as uv on a.id = uv.artikal_id where uv.korisnik_id = %s or uv.ip_adresa = %s order by uv.datum DESC', [request.user.id, request.META.get('REMOTE_ADDR') ])\n views = konekcija.fetchall()[:16]\n \n konekcija.execute('select f.fraza, count(f.fraza) as ponavlja_se from personalna_fraze as f where f.korisnik_id=%s or f.ip_adresa=%s group by f.fraza having count(f.fraza > 1) order by ponavlja_se DESC', [request.user.id, request.META.get('REMOTE_ADDR')])\n fraze = konekcija.fetchall()[:10]\n sql = generisi_sql(fraze)\n konekcija.execute(sql, None)\n sugestije_fraze = konekcija.fetchall()[:8]\n b_sql = generisi_brand_sql(fraze)\n konekcija.execute(b_sql, None)\n sugestije_brand = konekcija.fetchall()[:8]\n \n konekcija.execute('select a.artikal, a.posjecenost, a.url, a.slika_2 from izdvojeno_amazon as a order by a.posjecenost DESC')\n artikli_posjeta = konekcija.fetchall()[:10]\n \n konekcija.execute('select b.brand, b.posjecenost, b.url, b.logo from izdvojeno_brandovi as b order by b.posjecenost DESC')\n brandovi_posjeta = konekcija.fetchall()[:10]\n \n konekcija.execute('select c.artikal, count(*) as ukupno, c.url, c.slika_1 from (select a.artikal, a.slika_1, a.url from izdvojeno_amazon as a inner join transakcije_analitika as ta on ta.produkt_id = a.id union all select a.artikal, a.slika_1, a.url from izdvojeno_amazon as a inner join transakcije_kupovina_po_drzavama as ta on ta.artikal_id = a.id) as c group by c.artikal having count(c.artikal) >= 1 ORDER BY ukupno DESC')\n best_prodaja = konekcija.fetchall()[:20]\n \n konekcija.execute('select distinct a.artikal, a.url, a.slika_1 from izdvojeno_amazon as a inner join personalna_spasi_artikal as sa on sa.artikal_id = a.id where sa.korisnik_id=%s', [request.user.id])\n snimljeno = konekcija.fetchall()\n return render_to_response(template_name, locals(), context_instance=RequestContext(request)) \n\n\ndef gledano_za_mjesec(request):\n import datetime\n godina = datetime.datetime.now().year\n mjesec = request.GET['mjesec']\n konekcija = connection.cursor()\n konekcija.execute('select a.artikal, a.slika_1, a.url from izdvojeno_amazon as a inner join personalna_userviews as uv on uv.artikal_id = a.id where MONTH(datum) = %s and YEAR(datum) = %s and (korisnik_id = %s or ip_adresa = %s ) order by uv.datum DESC', [str(mjesec), str(godina), request.user.id, request.META.get('REMOTE_ADDR')])\n r = konekcija.fetchall()[:16]\n rezultati = []\n for a in r:\n json = {}\n json['artikal'] = a[0]\n json['slika'] = a[1]\n json['url'] = a[2]\n rezultati.append(json) \n ax = dumps(rezultati)\n mimetype = 'application/json'\n return HttpResponse(ax, mimetype)\n\n\n\n\ndef snimljeno_za_mjesec(request):\n import datetime\n godina = datetime.datetime.now().year\n mjesec = request.GET['mjesec']\n konekcija = connection.cursor()\n konekcija.execute('select distinct a.artikal, a.slika_1, a.url from izdvojeno_amazon as a inner join personalna_spasi_artikal as sa on sa.artikal_id = a.id where MONTH(datum) = %s and YEAR(datum) = %s and korisnik_id = %s order by sa.datum DESC', [str(mjesec), str(godina), request.user.id])\n r = konekcija.fetchall()[:16]\n rezultati = []\n for a in r:\n json = {}\n json['artikal'] = a[0]\n json['slika'] = str(a[1])\n json['url'] = a[2]\n rezultati.append(json) \n ax = dumps(rezultati)\n mimetype = 'application/json'\n return HttpResponse(ax, mimetype)\n\n\n\n\n\ndef snimljeno_kupi(request):\n artikal = request.GET['artikal']\n konekcija = connection.cursor()\n konekcija.execute('select a.artikal, a.ponuda_url, a.cijena, a.boja, a.velicina, a.slika_1, a.materijal from izdvojeno_amazon as a where a.url = %s',[artikal])\n r = konekcija.fetchall()\n rezultati = []\n for a in r:\n json = {}\n json['artikal'] = a[0]\n json['ponuda'] = a[1]\n json['cijena'] = str(a[2])\n json['boja'] = a[3]\n json['velicina'] = a[4]\n json['slika'] = a[5]\n json['materijal'] = a[6]\n rezultati.append(json) \n ax = dumps(rezultati)\n mimetype = 'application/json'\n return HttpResponse(ax, mimetype)\n\n\n\n\ndef korisnici_gledano(request):\n url = request.GET['url']\n konekcija = connection.cursor()\n konekcija.execute('select u.id from izdvojeno_amazon as a inner join personalna_userviews as uv on uv.artikal_id = a.id inner join auth_user as u on u.id = uv.korisnik_id where a.url=%s', [url])\n u_ids = konekcija.fetchall()\n sql = 'create view gledano as select a.artikal, a.slika_1, a.url, sgk.id from izdvojeno_amazon as a inner join personalna_userviews as uv on uv.artikal_id = a.id inner join auth_user as u on u.id = uv.korisnik_id inner join izdvojeno_sub_kategorije as sk on sk.id = a.sub_kat_id inner join izdvojeno_sub_glavne_kategorije as sgk on sgk.id = sk.sgl_id where '\n u = ''\n for n in u_ids:\n u += ' u.id = %s or' % n[0]\n \n upit = u[:-2] + ' and uv.korisnik_id != %s' % request.user.id \n konekcija.execute(sql + upit)\n \n konekcija.execute('select sgk.id from izdvojeno_amazon as a inner join izdvojeno_sub_kategorije as sk on sk.id = a.sub_kat_id inner join izdvojeno_sub_glavne_kategorije as sgk on sgk.id = sk.sgl_id where a.url = %s', [url]) \n sgl_id = konekcija.fetchone()\n konekcija.execute('select * from gledano where gledano.url != %s and gledano.id = %s', [url, sgl_id[0]])\n r = konekcija.fetchall()[:12]\n konekcija.execute('drop view gledano')\n rezultati = []\n for a in r:\n json = {}\n json['artikal'] = a[0]\n json['slika'] = a[1]\n json['url'] = a[2]\n rezultati.append(json) \n ax = dumps(rezultati)\n mimetype = 'application/json'\n return HttpResponse(ax, mimetype)\n \n\n\n\n\n\n\n\n\n\n\ndef generisi_sql(fraze):\n if fraze != ():\n sql = \"SELECT a.artikal, a.slika_1, a.url FROM izdvojeno_amazon AS a WHERE 1=1\"\n konektor = ' AND'\n uslov = \"\"\n for n in fraze:\n uslov += \" (a.artikal LIKE \\'%s\\' or a.artikal LIKE \\'%s\\' or a.artikal LIKE \\'%s\\') OR \" % (n[0] + '%', '%' + n[0], '%' + n[0] + '%')\n return sql + konektor + uslov[:-3] + \" order by a.posjecenost DESC\"\n else:\n return \"SELECT a.artikal, a.slika_1, a.url FROM izdvojeno_amazon AS a WHERE 1=1\" \n \n \n \n \n \ndef generisi_brand_sql(fraze):\n if fraze != ():\n sql = \"SELECT b.brand, b.logo, b.url FROM izdvojeno_brandovi AS b WHERE 1=1 and b.logo != NULL\"\n konektor = ' AND'\n uslov = \"\"\n for n in fraze:\n uslov += \" (b.brand LIKE \\'%s\\' or b.brand LIKE \\'%s\\' or b.brand LIKE \\'%s\\') OR \" % (n[0] + '%', '%' + n[0], '%' + n[0] + '%')\n return sql + konektor + uslov[:-3] + \" order by b.posjecenost DESC\"\n else:\n return \"SELECT b.brand, b.logo, b.url FROM izdvojeno_brandovi AS b WHERE 1=1 and b.logo != NULL\" \n \n\n\n\ndef facebook_marketing(request, template_name=\"transakcije/facebook_marketing.html\"):\n return render_to_response(template_name, locals(), context_instance=RequestContext(request))\n\n\n\n\n\n\n\ndef spasi_artikal(request):\n if request.user.is_authenticated() == True:\n a_id = request.GET['artikal_id']\n from django.db import connection\n konekcija = connection.cursor()\n konekcija.execute(\"INSERT INTO personalna_spasi_artikal (korisnik_id, datum, artikal_id) VALUES (%s, NOW(), %s)\", [request.user.id, a_id ]) \n return HttpResponse('OK')\n else:\n return HttpResponse('You have sucessfully saved item to your account.')\n \n ","sub_path":"engine/personalna/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"262187249","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport calendar\nimport time\n\ncal = time.strptime(\"Thu Nov 15 13:57:12 2018\") # 一个时间元组\n\n\ncalendar.calendar(theyear=2018) # 返回某一年的日历\n# calendar.prcal(theyear=2018) # 同上\ncalendar.firstweekday() # 返回当前每周起始日期的设置\ncalendar.isleap(2018) # 是闰年返回True,否则为false\ncalendar.leapdays(2018, 2028) # 返回两个时间点的闰年总和\ncalendar.month(2018, 11) # 返回某年某月的日历\ncalendar.prmonth(2018, 11) # 同上\ncalendar.monthcalendar(2018, 11) # 返回一个证书的单层嵌套列表,每个列表里是一个星期的整数\ncalendar.monthrange(2018, 11) # 返回两个整数。一是该月的星期几的日期码,二是该月的日期码。\ncalendar.setfirstweekday(0) # 设置每周的起始日期码。0(星期一)到6(星期日)。\ncalendar.timegm(cal) # 接受时间元组,返回该时刻的时间辍\ncalendar.weekday(2018, 11, 15) # 返回给定日期的日期码。\n\nprint()\n\n\n\n\n","sub_path":"A_库的分类/时间类_time&datetime/calendar_learn.py","file_name":"calendar_learn.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"385949571","text":"import pandas as pd\nimport numpy as np\nimport nav_connect as nv\nimport pickle\nimport time\nfrom datetime import datetime, timedelta\nfrom dateutil import parser\nimport EGR.EGR_model.utils as utils\n\n#EGR FCs\nEGR_FC = ['SPN2791','SPN2659','SPN3251','SPN3216','SPN3226','SPN4765','SPN4364','SPN637',\n 'SPN102','SPN132','SPN188','SPN1761']\n\n#TSPs\ndf_tsp = pd.read_excel('~/EGR/data/Telematic devices.xlsx')\nTSP = df_tsp.Ameritrak.values\n\n#Get all A26 data\nodbc = nv.odbc()\nq = '''select * from analyticsplayground.a26_vins_with_esn'''\ndf_vins = odbc.read_sql(q)\ndf_vins['model_mjr'] = df_vins.mdl_7_cd.apply(lambda x: x[:2])\nall_vins = list(set(df_vins.vin.values))\n\n#Confirmed EGR Failures\ndf_fails = pd.ExcelFile('~/EGR/data/EGR D.xlsx').parse('Claim comments')\ndf_fails = df_fails[(df_fails['Failure Mode'] == 'Bushing Wear') \n | (df_fails['Failure Mode'] == 'Sticking EGR Valve') \n | (df_fails['Failure Mode'] == 'Pin/Butterfly Broken') \n | (df_fails['Failure Mode'] == 'Broken Pin/Butterfly and High Bushing wear')]\n\n#Fails dictionary\nd_fails = df_fails.set_index('VIN')['Fail Date'].to_dict()\n\n# bad vins\nvins_bad = list(d_fails.keys())\n\n# good vins (All A26 that have DIS<365 and not failed)\ntoday = datetime.now() - timedelta(days=1)\n#today = parser.parse('2020-03-31')\n \ndf_vins['DIS'] = df_vins['trk_build_date'].apply(lambda x: (today - x).days) \ndf_good = df_vins.query('DIS < 365')\nvins_good = list(set(df_good.vin) - set(vins_bad))\n\n#Form strings for DB requests\nvins_str_bad = str(tuple(vins_bad)).replace('\\'','\\\"')\nvins_str_good = str(tuple(vins_good)).replace('\\'','\\\"')\nspn_str = str(tuple(EGR_FC)).replace('\\'','\\\"')\n\n#Get FC data for failed and good vins \ndf_fc_bad = utils.get_fc_data(vins_str_bad, spn_str)\ndf_fc_good = utils.get_fc_data(vins_str_good, spn_str)\n\n#Get time difference (in days) to failure. For good vins, it is time to 'today'.\ndf_fc_bad['t_diff'] = df_fc_bad.apply(lambda r: (parser.parse(r['dtc_date']) - d_fails[r['vin']]).days, axis=1)\ndf_fc_good['t_diff'] = df_fc_good.dtc_date.apply(lambda x: (parser.parse(x) - today).days)\n\n#Make qualitative preselections for good and bad vins\nndays_occ_back = 15\nndays = 90 + ndays_occ_back\ndata_fc_bad_sel = utils.fc_preselections(df_fc_bad, 'Bad', TSP, ndays)\ndata_fc_good_sel = utils.fc_preselections(df_fc_good, 'Good', TSP, ndays)\nprint('len(data_fc_bad_sel), len(data_fc_good_sel)', len(data_fc_bad_sel), len(data_fc_good_sel))\n\n### Get OCC data \n#\ndef get_test_data(vins_str, data_fc_sel, day_min, data_type): \n df_data = utils.get_all_data(vins_str, day_min)\n \n if data_type == 'Bad':\n df_data['t_diff'] = df_data.apply(lambda r: (r['day'] - d_fails[r['vin']]).days, axis=1)\n else:\n df_data['t_diff'] = df_data.apply(lambda r: (r['day'] - today).days, axis=1)\n \n #Keep just OCC data ndays_occ_back\n df_data = df_data.query('t_diff >= {} and t_diff <= {}'.format(-ndays_occ_back, 0))\n \n data_m = pd.merge(df_data, df_vins[['vin',\n 'mdl_7_cd',\n 'model_mjr',\n 'engine_hp',\n 'trans_fwd_gears',\n 'def_tanks_gallons',\n ]], on ='vin')\n \n #Get weighted FC counts for each day of OCC data back in time. \n df_fc, cols_fc = utils.get_fc_counts_by_day(data_fc_sel, data_m)\n #Merge FC and OCC data\n data_mm = pd.merge(data_m, df_fc, on=['vin','day'], how='left')\n #Fill NA FC data with zeros\n data_mm[cols_fc] = data_mm[cols_fc].fillna(value=0)\n\n return data_mm\n \n# \n#Bad vins first\n#\nodbc = nv.odbc()\nt0 = time.time()\ndate_min_bad = \"2020-01-01\"\ndata_bad_mm = get_test_data(vins_str_bad, data_fc_bad_sel, date_min_bad, 'Bad')\nprint('Get all bad data:',time.time() - t0, len(data_bad_mm))\n\n#Store results\ndata_bad_mm.to_csv('EGR/EGR_model/data/data_bad_egr_hist.csv',index=False)\n\n#\n#Now select good vins\n#\nodbc = nv.odbc()\nt0 = time.time()\n#Get good train data\nN_good_train = 2000\ndate_min_good = (datetime.now() - timedelta(days=ndays_occ_back)).strftime(\"%Y-%m-%d\") \n#date_min_good = \"2020-03-01\"\ngood_vins_str = str(tuple(vins_good[:N_good_train])).replace('\\'','\\\"')\ndata_good_mm = get_test_data(good_vins_str, data_fc_good_sel, date_min_good, 'Good')\n\nprint('Get all good data:',time.time() - t0, len(data_good_mm))\n\n#Store results\ndata_good_mm.to_csv('EGR/EGR_model/data/data_good_egr_hist.csv',index=False)\n\n\n#\n#Create Test sample\n#\nvins_test = list(set(all_vins) - set(vins_good) - set(vins_bad))\n\ndate_min_test = \"2020-05-01\"\nn = len(vins_test)\nstep = 1000\nn1 = 0\nn2 = n1+step\ni = 1\nt0 = time.time() \nwhile n2-step < n:\n print(n1, n2)\n odbc = nv.odbc()\n vins_str_test = str(tuple(vins_test[n1:n2])).replace('\\'','\\\"')\n df_fc_test = utils.get_fc_data(vins_str_test, spn_str)\n df_fc_test['t_diff'] = df_fc_test.dtc_date.apply(lambda x: (parser.parse(x) - today).days)\n data_fc_test_sel = utils.fc_preselections(df_fc_test, 'Test', TSP, ndays)\n data_all_mm = get_test_data(vins_str_test, data_fc_test_sel, date_min_test, 'Test')\n print('Get all test data:',time.time() - t0, len(data_all_mm))\n data_all_mm.to_csv('EGR/EGR_model/data/data_all_egr_hist_{}.csv'.format(i), index=False)\n n1, n2 = n2, n2+step\n i += 1 \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":5351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"74600705","text":"\r\n## filtering the protein functionality analysis-annovar file\r\n## This tool modifies the output file\r\n\r\nimport pandas as pd\r\ndf = pd.read_csv('C:\\\\') #enter annovar output file as an input for filtering\r\n\r\n#df=df.rename(columns = {'Otherinfo':'ID'})\r\n\r\n #select specific columns\r\n\r\ndf = df[['Chr', 'Start', 'End', 'Ref', 'Alt', 'Func.refGene', 'Gene.refGene', 'ExonicFunc.refGene', 'AAChange.refGene',\r\n 'Gene_full_name.refGene', 'dbscSNV_ADA_SCORE', 'dbscSNV_RF_SCORE', 'dpsi_max_tissue', 'dpsi_zscore', 'Otherinfo']]\r\n\r\n#, 'dbscSNV_ADA_SCORE', 'dbscSNV_RF_SCORE', 'dpsi_max_tissue', 'dpsi_zscore',\r\nremove_word = ['comment'] ###remove 'comments: ' from string\r\npat = r'\\b(?:{})\\b'.format('|'.join(remove_word))\r\n\r\ndf['ID'] = df['Otherinfo'].str.replace(pat, '') ###column name change to 'ID'\r\ndel df['Otherinfo']\r\n\r\ncols = df.columns.tolist() ### move 'ID' column as a first column\r\ncols = cols[-1:] + cols[:-1]\r\ndf = df[cols]\r\n\r\n\r\ndf.to_csv('C:\\\\', index= False) #produce a modified output file without indexing\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"splice_filter.py","file_name":"splice_filter.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"138065631","text":"from __future__ import absolute_import\n\nfrom celery import shared_task\nfrom data.models import *\nfrom datetime import datetime\n\n@shared_task\ndef make_polygon(x, y, ref_x, ref_y, step):\n def create_point(x, y, ref_x, ref_y):\n reach = 50\n closest_points = []\n while(len(closest_points) < 10):\n closest_points = Location.objects.filter(\n x__lt=x + reach,\n x__gt=x - reach,\n y__lt=y + reach,\n y__gt=y - reach\n )\n reach += 50\n \n sorted_closest_points = sorted(closest_points, key=lambda t: t.distance(x, y))\n total = 0\n for counter, value in enumerate(sorted_closest_points[:10]):\n total += value.altitude\n return_point, created = Point.objects.get_or_create(\n x=x - ref_x,\n y=y - ref_y,\n defaults={\n 'x':x - ref_x,\n 'y':y - ref_y,\n 'z': float(total) / 10.0\n }\n )\n return return_point\n \n p1 = create_point(x, y, ref_x, ref_y)\n p2 = create_point(x + step, y, ref_x, ref_y)\n p3 = create_point(x, y + step, ref_x, ref_y)\n p4 = create_point(x + step, y + step, ref_x, ref_y)\n Polygon.objects.create(p1=p1, p2=p2, p3=p3, p4=p4)\n \n \n","sub_path":"execution/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"474417721","text":"import ast\nimport astor\n\n\ntarget_path = \"./source.py\"\nsource = open(target_path).read()\ntree = ast.parse(source, target_path)\n\n# Replace the first Comparator in the program\n# To simplify this example, we will replace any compare operator with\n# \">=\"\n\n\nvisit_target = 2\nvisit_count = 0\n\nclass RewriteCompare(ast.NodeTransformer):\n def visit_Compare(self, node):\n global visit_count, visit_target\n self.generic_visit(node)\n visit_count = visit_count + 1\n #print(visit_count)\n if (visit_count == visit_target):\n #print(\"Hi\")\n newnode = ast.Compare(left=node.left, ops=[ast.Lt()], comparators=node.comparators)\n return newnode\n else:\n return node\n\ntree = RewriteCompare().visit(tree)\nprint(astor.to_source(tree))\n","sub_path":"rewrite_first_comp.py","file_name":"rewrite_first_comp.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"626852057","text":"import json\nimport os\n\n\ndef wrap_file_to_list(filepath):\n with open(filepath, 'r') as original:\n data = original.read()\n with open(filepath, 'w') as modified:\n modified.write(\"[\\n\" + data)\n modified.write(\"\\n]\")\n original.close()\n modified.close()\n\n\ndef get_list_of_json_files(directory):\n output_list = []\n for i in os.listdir(directory):\n if i.endswith(\".json\"):\n try:\n with open(os.path.join(directory, i), 'r', encoding='utf8') as try_file:\n json.load(try_file)\n output_list.append(i)\n # except json.decoder.JSONDecodeError:\n # wrap_file_to_list((os.path.join(directory, i)))\n # print(\"Wrapped [] around \", i)\n except Exception as e:\n print(i, \"caused error\", e)\n return output_list\n\n\ndef get_list_of_csv_files(directory):\n output_list = []\n for i in os.listdir(directory):\n if i.endswith(\".csv\"):\n output_list.append(i)\n return output_list\n\nfrom functions import config\nprint(get_list_of_csv_files(config.url_list_tester_input))\n","sub_path":"functions/directory.py","file_name":"directory.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"444391649","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nPrzykład banalnej aplikacji WWW zgodnej ze specyfikacją WSGI (Python Web\nServer Gateway Interface).\n\nOryginalna wersja specyfikacji, przeznaczona dla Pythona 2, jest dostępna\npod . Wersja uwzględniająca zmiany\nwprowadzone w Pythonie 3 jest pod .\n\nNajważniejsze informacje:\n- punktem wejścia do aplikacji WSGI może być funkcja (jak w tym przykładzie)\n albo klasa\n- serwer HTTP wywołuje funkcję / konstruktor klasy przekazując jako argumenty\n słownik ze środowiskiem WSGI oraz referencję do funkcji, której wywołanie\n pozwala aplikacji wyspecyfikować nagłówki odpowiedzi\n- właściwą treść odpowiedzi funkcja zwraca jako swój wynik; musi to być obiekt\n pozwalający się iterować (a więc np. tablica), iterowane elementy są jeden\n za drugim odsyłane klientowi HTTP\n- jeśli zapytanie HTTP zawierało dokument/właściwą treść, to jest ona dostępna\n w strumieniu wsgi.input w środowisku WSGI\n\nInformacje specyficzne dla Pythona 3:\n- łańcuchy Pythona są unikodowe, podobnie jak w Javie\n- wg specyfikacji HTTP nagłówki zapytań i odpowiedzi są ciągami bajtów\n w kodowaniu ISO-8859-1, można więc je jednoznacznie skonwertować do/z\n postaci unikodowych łańcuchów (i dla wygody jest to automatycznie robione)\n- treść po nagłówkach może być tekstem w dowolnym kodowaniu albo wręcz danymi\n binarnymi, programista musi je przetwarzać jako ciągi bajtów\n- typ Pythona o nazwie bytes reprezentuje ciągi bajtów / łańcuchy binarne\n- jeśli w zmiennej s jest łańcuch, to można go zamienić na bajty albo przez\n rzutowanie bytes(s, \"UTF-8\"), albo przez s.encode(\"UTF-8\")\n- bajty b konwertujemy na łańcuch przez str(b, \"UTF-8\") lub b.decode(\"UTF-8\")\n- specjalna notacja b\"znaki ASCII\" pozwala wyspecyfikować stałą typu bytes\n\"\"\"\n\ndef hello_app(environment, start_response):\n headers = [\n (\"Content-Type\", \"text/plain; charset=UTF-8\"),\n (\"Server\", \"HelloApp/1.0\"),\n ]\n start_response(\"200 OK\", headers);\n\n envdump = \"Środowisko WSGI:\\n{\\n\"\n for k in sorted(environment.keys()):\n envdump += repr(k) + \": \" + repr(environment[k]) + \",\\n\"\n envdump += \"}\\n\"\n\n return [ b\"Hello, world!\\n\\n\", envdump.encode(\"UTF-8\") ]\n\n# Poniższy fragment pozwala uruchomić zdefiniowaną powyżej aplikację wewnątrz\n# deweloperskiego serwera HTTP/WSGI po wydaniu z linii poleceń komendy\n# python3 hello_webapp.py\n# Jeśli nie chcemy aby środowisko linuksowej powłoki \"przeciekało\" do\n# środowiska WSGI można je wyzerować używając programu env:\n# env -i python3 hello_webapp.py\n#\nif __name__ == \"__main__\":\n from wsgiref.simple_server import make_server\n port = 8000\n httpd = make_server(\"\", port, hello_app)\n print(\"Listening on port %i, press ^C to stop.\" % port)\n httpd.serve_forever()\n","sub_path":"Zestaw9/hello_webapp.py","file_name":"hello_webapp.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"377501755","text":"import os\nimport pyautogui\nfrom pathlib import Path, PureWindowsPath\nfrom bluetooth import *\n\nDESKTOP_PATH = os.path.expanduser(\"~\\Desktop\\screenshot.png\")\nSERVER_SOCK = BluetoothSocket(RFCOMM)\nUUID = \"94f39d29-7d6d-437d-973b-fba39e49d4ee\"\n\ndef takeScreenshot():\n myScreenshot = pyautogui.screenshot()\n print(DESKTOP_PATH)\n myScreenshot.save(DESKTOP_PATH)\n return\n\nSERVER_SOCK.bind((\"\", PORT_ANY))\nSERVER_SOCK.listen(1)\n\nport = SERVER_SOCK.getsockname()[1]\n\nadvertise_service(SERVER_SOCK, \"SampleServer\",\n service_id=UUID,\n service_classes=[UUID, SERIAL_PORT_CLASS],\n profiles=[SERIAL_PORT_PROFILE])\n\nprint(\"Waiting for connection on RFCOMM channel %d\" % port)\nclient_sock, client_info = SERVER_SOCK.accept()\nprint(\"Accepted connection from \", client_info)\n\nwhile True:\n data = client_sock.recv(1024)\n if len(data) == 0:\n break\n print(\"received [%s]\" % data)\n\n # do we need decode?\n stringData = data.decode('utf-8')\n\n if 'command' in stringData:\n if 'screenshot' in stringData:\n takeScreenshot()\n filePath = Path(DESKTOP_PATH)\n client_sock.send(\"screenshot.png\")\n f = open(filePath, 'r')\n while True:\n content = f.read(1024)\n if len(content) != 0:\n client_sock.send(content)\n else:\n break\n f.close()\n elif 'file' in stringData:\n args = stringData.split()\n print(args[1])\n filePath = Path(args[1])\n f = open(filePath, 'r')\n while True:\n content = f.read(1024)\n if len(content) != 0:\n client_sock.send(content)\n else:\n break\n\n f.close()\n elif 'recieve' in stringData:\n # recieve file name\n data = client_sock.recv(1024)\n # f = open(\"guru99.txt\", \"w+\")\n while True:\n data = client_sock.recv(1024)\n if len(data) == 0:\n break\n buffer = data.decode('utf-8')\n # f.write(buffer)\n # f.close()\n elif 'stop' in stringData:\n break\n else:\n print(\"wrong command [%s]\" % stringData)\n\nprint(\"disconnected\")\nclient_sock.close()\nSERVER_SOCK.close()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"304147632","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''此服务器能够接受客户端的信息,返回时在信息前加一个时间戳'''\nfrom socket import *\nfrom time import ctime\n\nhost='localhost'#本地主机名\nport=8888\t\t#端口号\nbufsiz=1024 #设置最大缓冲数\naddr=(host,port)\nudpSerSock=socket(AF_INET,SOCK_DGRAM) #创建服务器套接字\nudpSerSock.bind(addr) #绑定端口\n\nwhile True:\n\tprint('等待消息...')\n\tdata,addr=udpSerSock.recvfrom(bufsiz)\n\tudpSerSock.sendto(('[%s] %s' % (ctime(),data.decode('utf-8'))).encode('utf-8'),addr)\n\tprint('...收到并返回:',addr)\nudpSerSock.close()","sub_path":"python练习/tsUserv.py","file_name":"tsUserv.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"25420741","text":"import pandas as pd\nimport argparse\nimport sys\n\nVARIANT_COUNT_POSTFIX = \"_variant_count\"\nTUMOR_TYPE_COUNT_POSTFIX = \"_tumortype_count\"\n\nGENERAL_POPULATION_F_PREFIX = \"f_\"\nGENERAL_POPULATION_N_PREFIX = \"n_\"\nSIG_PREFIX = \"Sig.\"\n\n\ndef generate_count_list(mutation_row, tumor_types):\n return [\n {\n \"tumor_type\": tumor_type,\n \"tumor_type_count\": mutation_row[tumor_type + TUMOR_TYPE_COUNT_POSTFIX],\n \"variant_count\": mutation_row[tumor_type + VARIANT_COUNT_POSTFIX]\n } for tumor_type in tumor_types\n ]\n\n\ndef generate_stats_by_prefix(mutation_row, col_names, prefix):\n return {\n col_name.replace(prefix, \"\").lower(): mutation_row[col_name] for col_name in col_names\n }\n\n\ndef generate_general_population_stats(mutation_row, count_col_names, freq_col_names):\n # add the lists for count and frequency stats\n return {\n \"counts\": generate_stats_by_prefix(\n mutation_row,\n count_col_names,\n GENERAL_POPULATION_N_PREFIX\n ),\n \"frequencies\": generate_stats_by_prefix(\n mutation_row,\n freq_col_names,\n GENERAL_POPULATION_F_PREFIX\n )\n }\n\n\ndef generate_tumor_type_stats(mutation_row, sig_col_names):\n return {\n \"tumor_type\": mutation_row[\"Proposed_level\"],\n \"n_cancer_type_count\": mutation_row[\"n_cancer_type_count\"],\n \"f_cancer_type_count\": mutation_row[\"f_cancer_type_count\"],\n \"f_biallelic\": mutation_row[\"f_biallelic\"],\n \"age_at_dx\": mutation_row[\"age_at_dx\"],\n \"tmb\": mutation_row[\"tmb\"],\n \"msi_score\": mutation_row[\"msi_score\"],\n \"n_with_sig\": mutation_row[\"n_with_sig\"],\n \"signatures\": generate_stats_by_prefix(mutation_row, sig_col_names, SIG_PREFIX),\n \"hrd_score\": {\n \"lst\": mutation_row[\"lst\"],\n \"ntelomeric_ai\": mutation_row[\"ntelomeric_ai\"],\n \"fraction_loh\": mutation_row[\"fraction_loh\"],\n },\n \"n_germline_homozygous\": mutation_row[\"n_germline_homozygous\"]\n }\n\n\ndef extract_tumor_types_from_col_names(mutations_df):\n # get columns (keys) ending with count postfixes\n count_keys = list(filter(lambda colname: colname.endswith(TUMOR_TYPE_COUNT_POSTFIX) or\n colname.endswith(VARIANT_COUNT_POSTFIX),\n mutations_df.keys()))\n return set([\n count_key.replace(TUMOR_TYPE_COUNT_POSTFIX, \"\").replace(VARIANT_COUNT_POSTFIX, \"\") for count_key in count_keys\n ])\n\n\ndef extract_col_names_by_prefix(mutations_df, stats_prefix):\n # get columns (keys) starting with population stats prefixes\n return list(filter(lambda colname: colname.startswith(stats_prefix), mutations_df.keys()))\n\n\ndef process_data_frame(mutations_df, mutation_status):\n # add the list for tumor type counts\n mutations_df[\"counts_by_tumor_type\"] = mutations_df.apply(\n lambda row: generate_count_list(row, extract_tumor_types_from_col_names(mutations_df)), axis=1\n )\n mutations_df[\"Mutation_Status\"] = mutation_status\n # pick only the columns we need\n df = mutations_df[[\"Hugo_Symbol\",\n \"Chromosome\",\n \"Start_Position\",\n \"End_Position\",\n \"Reference_Allele\",\n \"Alternate_Allele\",\n \"Mutation_Status\",\n \"classifier_pathogenic_final\",\n \"penetrance\",\n \"counts_by_tumor_type\"]]\n # rename columns for JSON format\n df.columns = [\"hugo_gene_symbol\",\n \"chromosome\",\n \"start_position\",\n \"end_position\",\n \"reference_allele\",\n \"variant_allele\",\n \"mutation_status\",\n \"pathogenic\",\n \"penetrance\",\n \"counts_by_tumor_type\"]\n return df\n\n\ndef process_all_variant_freq_df(mutations_df, mutation_status):\n mutations_df[\"Mutation_Status\"] = mutation_status\n mutations_df[\"general_population_stats\"] = mutations_df.apply(\n lambda row: generate_general_population_stats(\n row,\n extract_col_names_by_prefix(mutations_df, GENERAL_POPULATION_N_PREFIX),\n extract_col_names_by_prefix(mutations_df, GENERAL_POPULATION_F_PREFIX),\n ), axis=1\n )\n # pick only the columns we need\n df = mutations_df[[\"Hugo_Symbol\",\n \"Chromosome\",\n \"Start_Position\",\n \"End_Position\",\n \"Reference_Allele\",\n \"Alternate_Allele\",\n \"Mutation_Status\",\n \"general_population_stats\",\n \"n_germline_homozygous\"]]\n # rename columns for JSON format\n df.columns = [\"hugo_gene_symbol\",\n \"chromosome\",\n \"start_position\",\n \"end_position\",\n \"reference_allele\",\n \"variant_allele\",\n \"mutation_status\",\n \"general_population_stats\",\n \"n_germline_homozygous\"]\n return df\n\n\ndef process_variants_by_cancertype_summary_df(mutations_df, mutation_status):\n mutations_df[\"Mutation_Status\"] = mutation_status\n mutations_df[\"stats_by_tumor_type\"] = mutations_df.apply(\n lambda row: generate_tumor_type_stats(\n row,\n extract_col_names_by_prefix(mutations_df, SIG_PREFIX)\n ), axis=1\n )\n # pick only the columns we need\n df = mutations_df[[\"Hugo_Symbol\",\n \"Chromosome\",\n \"Start_Position\",\n \"End_Position\",\n \"Reference_Allele\",\n \"Alternate_Allele\",\n \"Mutation_Status\",\n \"stats_by_tumor_type\"]]\n # rename columns for JSON format\n df.columns = [\"hugo_gene_symbol\",\n \"chromosome\",\n \"start_position\",\n \"end_position\",\n \"reference_allele\",\n \"variant_allele\",\n \"mutation_status\",\n \"stats_by_tumor_type\"]\n return df\n\n\ndef create_variants_by_cancertype_summary_index(mutations_df):\n # all other column names except stats_by_tumor_type\n col_names = list(filter(lambda colname: colname != \"stats_by_tumor_type\", mutations_df.keys()))\n # keep the first for every column except stats_by_tumor_type, they are the same\n aggregator = {col_name: 'first' for col_name in col_names}\n # aggregate stats_by_tumor_type as a list\n aggregator['stats_by_tumor_type'] = lambda s: list(s)\n return mutations_df.groupby('id').agg(aggregator).set_index(\"id\").to_dict('index')\n\n\ndef process_msk_expert_review_df(mutations_df, mutation_status):\n mutations_df[\"Mutation_Status\"] = mutation_status\n mutations_df[\"MSK_Expert_Review\"] = True\n # pick only the columns we need\n df = mutations_df[[\"Hugo_Symbol\",\n \"Chromosome\",\n \"Start_Position\",\n \"End_Position\",\n \"Reference_Allele\",\n \"Alternate_Allele\",\n \"Mutation_Status\",\n \"MSK_Expert_Review\"]]\n # rename columns for JSON format\n df.columns = [\"hugo_gene_symbol\",\n \"chromosome\",\n \"start_position\",\n \"end_position\",\n \"reference_allele\",\n \"variant_allele\",\n \"mutation_status\",\n \"msk_expert_review\"]\n return df\n\n\ndef merge_mutations(germline_mutations_df,\n biallelic_mutations_df,\n qc_pass_mutations_df,\n all_variants_freq_df,\n msk_expert_review_df,\n variants_by_cancertype_summary_df):\n # generate ID for each data frame\n generate_id(germline_mutations_df)\n generate_id(biallelic_mutations_df)\n generate_id(qc_pass_mutations_df)\n generate_id(all_variants_freq_df)\n generate_id(msk_expert_review_df)\n generate_id(variants_by_cancertype_summary_df)\n\n # create a dictionary for germline mutations\n biallelic_mutations_index = biallelic_mutations_df.set_index(\"id\").to_dict('index')\n qc_pass_mutations_index = qc_pass_mutations_df.set_index(\"id\").to_dict('index')\n all_variants_freq_index = all_variants_freq_df.set_index(\"id\").to_dict('index')\n msk_expert_review_index = msk_expert_review_df.set_index(\"id\").drop_duplicates().to_dict('index')\n variants_by_cancertype_summary_index = create_variants_by_cancertype_summary_index(\n variants_by_cancertype_summary_df)\n\n # add data from other sources into the main germline data frame\n add_column_data(germline_mutations_df,\n biallelic_mutations_index,\n \"biallelic_counts_by_tumor_type\",\n \"counts_by_tumor_type\")\n add_column_data(germline_mutations_df,\n qc_pass_mutations_index,\n \"qc_pass_counts_by_tumor_type\",\n \"counts_by_tumor_type\")\n add_column_data(germline_mutations_df,\n all_variants_freq_index,\n \"general_population_stats\",\n \"general_population_stats\")\n add_column_data(germline_mutations_df,\n all_variants_freq_index,\n \"n_germline_homozygous\",\n \"n_germline_homozygous\")\n add_column_data(germline_mutations_df,\n msk_expert_review_index,\n \"msk_expert_review\",\n \"msk_expert_review\",\n default_value=False)\n add_column_data(germline_mutations_df,\n variants_by_cancertype_summary_index,\n \"stats_by_tumor_type\",\n \"stats_by_tumor_type\")\n\n # drop the id columns from the original data frames\n germline_mutations_df.drop(columns=[\"id\"], inplace=True)\n biallelic_mutations_df.drop(columns=[\"id\"], inplace=True)\n qc_pass_mutations_df.drop(columns=[\"id\"], inplace=True)\n all_variants_freq_df.drop(columns=[\"id\"], inplace=True)\n msk_expert_review_df.drop(columns=[\"id\"], inplace=True)\n variants_by_cancertype_summary_df.drop(columns=[\"id\"], inplace=True)\n\n\ndef add_column_data(target_df, source_index, target_col_name, source_col_name, default_value=None):\n target_df[target_col_name] = target_df.apply(\n lambda row: pick_column_from_index(row[\"id\"], source_index, source_col_name, default_value), axis=1\n )\n\n\ndef pick_column_from_index(row_id, source_index, source_col_name, default_value=None):\n try:\n return source_index[row_id][source_col_name]\n except KeyError:\n return default_value\n\n\ndef generate_id(df):\n df[\"id\"] = df[\"chromosome\"].map(str) + \"_\" + \\\n df[\"start_position\"].map(str) + \"_\" + \\\n df[\"end_position\"].map(str) + \"_\" + \\\n df[\"reference_allele\"].map(str) + \"_\" + \\\n df[\"variant_allele\"].map(str)\n\n\n# workaround for mixed NAs and integers\n# see https://stackoverflow.com/questions/39666308/pd-read-csv-by-default-treats-integers-like-floats\ndef fix_na_values(df):\n df[[\"Start_Position\", \"End_Position\"]] = df[[\"Start_Position\", \"End_Position\"]].fillna(-1).astype(int)\n\n\ndef parse_file(input, sep):\n # make sure that chromosome is always parsed as string\n df = pd.read_csv(input, sep=sep, dtype={\"Chromosome\": object})\n fix_na_values(df)\n return df\n\n\ndef main(input_somatic,\n input_germline,\n input_biallelic,\n input_qc_pass,\n input_all_variants_freq,\n input_msk_expert_review,\n input_variants_by_cancertype_summary):\n # parse mutation files\n somatic_mutations_df = parse_file(input_somatic, sep='\\t')\n germline_mutations_df = parse_file(input_germline, sep='\\t')\n biallelic_mutations_df = parse_file(input_biallelic, sep='\\t')\n qc_pass_mutations_df = parse_file(input_qc_pass, sep='\\t')\n all_variants_freq_df = parse_file(input_all_variants_freq, sep='\\t')\n msk_expert_review_df = parse_file(input_msk_expert_review, sep='\\t')\n variants_by_cancertype_summary_df = parse_file(input_variants_by_cancertype_summary, sep='\\t')\n # process original input\n somatic_mutations_df = process_data_frame(somatic_mutations_df, \"somatic\")\n germline_mutations_df = process_data_frame(germline_mutations_df, \"germline\")\n biallelic_mutations_df = process_data_frame(biallelic_mutations_df, \"germline\")\n qc_pass_mutations_df = process_data_frame(qc_pass_mutations_df, \"germline\")\n all_variants_freq_df = process_all_variant_freq_df(all_variants_freq_df, \"germline\")\n msk_expert_review_df = process_msk_expert_review_df(msk_expert_review_df, \"germline\")\n variants_by_cancertype_summary_df = process_variants_by_cancertype_summary_df(variants_by_cancertype_summary_df,\n \"germline\")\n # merge everything into the main germline mutations data frame\n merge_mutations(germline_mutations_df,\n biallelic_mutations_df,\n qc_pass_mutations_df,\n all_variants_freq_df,\n msk_expert_review_df,\n variants_by_cancertype_summary_df)\n # convert processed data frames to JSON format\n somatic_mutations_df.to_json(sys.stdout, orient='records', lines=True)\n germline_mutations_df.to_json(sys.stdout, orient='records', lines=True)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"input_somatic\",\n help=\"signal/somatic_mutations_by_tumortype_merge.txt\")\n parser.add_argument(\"input_germline\",\n help=\"signal/mutations_cnv_by_tumortype_merge.txt\")\n parser.add_argument(\"input_biallelic\",\n help=\"signal/biallelic_by_tumortype_merge.txt\")\n parser.add_argument(\"input_qc_pass\",\n help=\"signal/mutations_QCpass_by_tumortype_merge.txt\")\n parser.add_argument(\"input_all_variants_freq\",\n help=\"signal/signaldb_all_variants_frequencies.txt\")\n parser.add_argument(\"input_msk_expert_review\",\n help=\"signal/signaldb_msk_expert_review_variants.txt\")\n parser.add_argument(\"input_variants_by_cancertype_summary\",\n help=\"signal/signaldb_variants_by_cancertype_summary_statistics.txt\")\n args = parser.parse_args()\n main(args.input_somatic,\n args.input_germline,\n args.input_biallelic,\n args.input_qc_pass,\n args.input_all_variants_freq,\n args.input_msk_expert_review,\n args.input_variants_by_cancertype_summary)\n","sub_path":"scripts/transform_signal_db_mutations.py","file_name":"transform_signal_db_mutations.py","file_ext":"py","file_size_in_byte":14898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"137997119","text":"'''\n\nCopyright (c) 2013-2014 Hypothes.is Project and contributors\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'''\n\n#this is a code reused from hypothesis, adapted and extended to be used for languages\n\n# -*- coding: utf-8 -*-\nimport urllib\n\nfrom pyramid import httpexceptions as exc\nfrom pyramid.view import view_config\nfrom h import i18n\n\nimport models\nimport annotran\n\n\n_ = i18n.TranslationString\n\n\n@view_config(route_name='page_add',\n request_method='POST')\ndef addPage(request):\n if request.authenticated_userid is None:\n raise exc.HTTPNotFound()\n\n name = request.matchdict[\"languageName\"]\n pageid = request.matchdict[\"pageId\"]\n groupubid = request.matchdict[\"groupubid\"]\n\n language = annotran.languages.models.Language.get_by_name(name)\n\n pageid = urllib.unquote(urllib.unquote(pageid))\n page = annotran.pages.models.Page.get_by_uri(pageid)\n if not page:\n page = annotran.pages.models.Page(uri=pageid, language=language)\n request.db.add(page)\n else:\n page.members.append(language)\n request.db.flush()\n\n url = request.route_url('language_read', public_language_id=language.pubid, public_group_id=groupubid)\n return exc.HTTPSeeOther(url)\n\ndef includeme(config):\n config.add_route('page_add', 'pages/{languageName}/{pageId}/{groupubid}/addPage')\n config.scan(__name__)\n","sub_path":"annotran/pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"570641791","text":"from textwrap import wrap\r\nimport sys\r\n\r\ndef key_generation(key):\r\n key_bin = ''\r\n for i in key:\r\n key_bin += '0' * (16 - len(bin(ord(i))[2:])) + bin(ord(i))[2:]\r\n\r\n return key_bin\r\n\r\ndef message_to_bin(message):\r\n message_arr = []\r\n for i in message:\r\n message_arr.append('0' * (16 - len(bin(ord(i))[2:])) + bin(ord(i))[2:])\r\n\r\n #print(message_arr)\r\n\r\n message_binary = ''.join(message_arr)\r\n\r\n return message_binary\r\n\r\ndef bin_array_to_str(bin_message):\r\n message = ''\r\n for i in bin_message:\r\n message += i\r\n\r\n return message\r\n\r\ndef bin_to_hex(message):\r\n message = wrap(message, 4)\r\n message_hex = ''\r\n\r\n for i in message:\r\n message_hex += hex(int(i, 2))[2:]\r\n\r\n return message_hex\r\n\r\ndef hex_to_bin(message_hex):\r\n message = ''\r\n for i in message_hex:\r\n message += '0' * (4 - len(bin(int(i, 16))[2:])) + bin(int(i, 16))[2:]\r\n\r\n return message\r\n\r\ndef bin_to_message(bin_message):\r\n message = ''\r\n bin_message = wrap(bin_message, 16)\r\n for i in bin_message:\r\n message += chr(int(i, 2))\r\n\r\n return message\r\n\r\ndef gamma_generation(message_binary, key_bin):\r\n R1 = list(map(int, key_bin[0:19])) # (18, 17, 16, 13, 0), синхробит - 7\r\n R2 = list(map(int, key_bin[19:41])) # (21, 20, 0), синхробит - 9\r\n R3 = list(map(int, key_bin[41:64])) # (22, 21, 20, 7, 0), синхробит - 9\r\n\r\n #невсекотумасленицазптбудетивеликийпосттчкprint(R1, R2, R3)\r\n\r\n encrypted_message_binary = []\r\n output_bits_array = ''\r\n\r\n for i in message_binary:\r\n output_bit = (R1[18] + R2[21] + R3[22]) % 2\r\n #print('Output bit', output_bit, R1[18], R2[21], R3[22])\r\n output_bits_array = output_bits_array + str(output_bit)\r\n encrypted_message_binary += str((output_bit + int(i)) % 2)\r\n #print('encrypted_message_binary', str((output_bit + int(i)) % 2))\r\n F = R1[7] & R2[9] | R1[7] & R3[9] | R2[9] & R3[9]\r\n #print('F', F, R1[7], R2[9], R3[9])\r\n if R1[7] == F:\r\n for k in range(len(R1)):\r\n R1[len(R1) - k - 1] = R1[len(R1) - k - 2]\r\n R1[0] = (R1[13] + R1[16] + R1[17] + R1[18]) % 2\r\n #print(R1, R1[13], R1[16], R1[17], R1[18])\r\n if R2[9] == F:\r\n for k in range(len(R2)):\r\n R2[len(R2) - k - 1] = R2[len(R2) - k - 2]\r\n R2[0] = (R2[20] + R2[21]) % 2\r\n #print(R2, R2[20], R2[21])\r\n if R3[9] == F:\r\n for k in range(len(R3)):\r\n R3[len(R3) - k - 1] = R3[len(R3) - k - 2]\r\n R3[0] = (R3[7] + R3[20] + R3[21] + R3[22]) % 2\r\n #print(R3, R3[7], R3[20], R3[21], R3[22])\r\n\r\n print('Сгенерированная гамма: ', bin_to_hex(output_bits_array))\r\n\r\n return encrypted_message_binary\r\n\r\nmessage = input(\"Введите сообщение: \")\r\nkey = input('Введите ключ (минимум 4 символа): ')\r\nif len(key) < 4:\r\n print('Длина ключа не соответствует требованиям криптосистемы. Пожалуйста, введите новый ключ.')\r\n sys.exit(0)\r\n\r\nencrypted_message = bin_to_hex(bin_array_to_str(gamma_generation(message_to_bin(message), key_generation(key))))\r\nprint(\"Зашифрованное сообщение:\", encrypted_message)\r\n\r\ndecrypted_message = bin_to_message(bin_array_to_str(gamma_generation(hex_to_bin(encrypted_message), key_generation(key))))\r\nprint('Расшифрованное сообщение: ', decrypted_message)\r\n\r\n","sub_path":"A5(1)/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"86650856","text":"# -*- coding: utf-8 -*-\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime\r\nfrom pathlib import Path\r\nhome = str(Path.home())\r\nPATH = home + \"\\\\Desktop\\\\ee_grad_project\\\\\"\r\n\r\nimport os\r\nos.chdir(PATH)\r\n\r\n#my library\r\nfrom foodDataWeightFromLogV2 import calWeightFromLog\r\n\r\nOUTPUT = PATH + \"dataFile\\\\output_log.xlsx\"\r\nFOOD_DATA = PATH + \"dataFile\\\\food_data.xlsx\"\r\n\r\ndef pick_randomWeight_from_list(food_id_Series,weightSeries):\r\n \"from food_id_list pick food_id with weight\"\r\n food_id = np.random.choice(food_id_Series,1,p=weightSeries)\r\n return food_id\r\n\r\n\r\ndef yes_or_no_loop(data,id_code,weights):\r\n noChoiceList = []\r\n choice = 0\r\n print(\"\\n음식을 추천해드립니다!\\n\")\r\n while(choice == 0):\r\n\r\n if len(noChoiceList) == list(data[\"food_id\"])[-1]:\r\n print(\"더 이상 추천해줄 음식이 없습니다.\")\r\n choice = \"EXIT\"\r\n break\r\n \r\n food_id = pick_randomWeight_from_list(list(weights[\"food_id\"]),list(weights[\"weight\"]))\r\n index = list(data[\"food_id\"].values).index(food_id)\r\n randomFood, pickedCategory = data[\"food\"][index], data[\"category\"][index]\r\n #음식리스트 전부가 마음에 안들경우 출력\r\n \r\n #골랐던 음식이 마음에 안든 경우 이를 제외 추천\r\n if randomFood in noChoiceList:\r\n continue\r\n \r\n print(pickedCategory,\"-\",randomFood)\r\n while(True):\r\n choice = input(\"Yes or No? \")\r\n choice = choice.upper()\r\n if choice in [\"Y\",\"YES\",\"EXIT\"]:\r\n break\r\n elif choice in [\"N\", \"NO\"]:\r\n print()\r\n choice = 0\r\n noChoiceList.append(randomFood)\r\n break\r\n else:\r\n print(\"Wrong Input\")\r\n if choice == \"EXIT\":\r\n randomFood = \"Dump\"\r\n return randomFood, noChoiceList\r\n\r\ndef pick_main(id_code):\r\n food_data = pd.read_excel(FOOD_DATA)\r\n try:\r\n log_data= pd.read_excel(OUTPUT) \r\n except:\r\n log_data = pd.DataFrame(columns=[\"id_code\",\"food_id\",\"choice\",\"time\",\"gps\",\"weather\",\"temp\"])\r\n weights = calWeightFromLog(id_code)[0]\r\n weights[\"weight\"] = weights[\"weight\"] / weights[\"weight\"].sum()\r\n print(weights)\r\n randomFood, noChoiceList = yes_or_no_loop(food_data, id_code,weights)\r\n for food in noChoiceList:\r\n food_id = food_data.loc[food_data[\"food\"]==food][\"food_id\"].values[0]\r\n log_data = log_data.append({\"id_code\":id_code, \"food_id\":food_id, \"choice\":0, \"time\":datetime.datetime.now(), \"gps\":np.nan, \"weather\":np.nan, \"temp\":np.nan},ignore_index=True)\r\n if randomFood == \"Dump\":\r\n pass\r\n else:\r\n food_id = food_data.loc[food_data[\"food\"]==randomFood][\"food_id\"].values[0]\r\n log_data = log_data.append({\"id_code\":id_code, \"food_id\":food_id, \"choice\":1, \"time\":datetime.datetime.now(), \"gps\":np.nan, \"weather\":np.nan, \"temp\":np.nan},ignore_index=True)\r\n #return log_data\r\n log_data.to_excel(OUTPUT, index=None)\r\n #return log_data\r\n \r\n#w = pick_main(1)\r\n","sub_path":"pickFunctionWithWeightV1.py","file_name":"pickFunctionWithWeightV1.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"409253837","text":"from tkinter import *\nfrom tkinter import messagebox\n\nimport LayoutGenerator\nimport random\nimport time\nimport threading\nimport NewRecord\nimport os.path\n\n\nsec = 1 # time in seconds\nw = None\nroot = None\ngenerator = None # instance of LayoutGenerator.py\ncombobox = None # difficulty level combobox\ndifficultyLevel = None # difficulty level\nlayout = None # generated layout\nisSolutionShown = False # whether the correct solution is already shown\ntimer = None # Timer object\ngameTime = False # is the game in progress\ngameOver = False # is the game over\ntimeCount = \"\" # passed since the game was started time\ncheckRec = \"\" # tuple report of the checkRecord() function\n # [[0]isNewRecord, [1]fileName, [2]operation]\n\n\n''' Depending on the difficulty level, loads the best results from a \nrelated to the difficulty level file, and shows either window with the message\nthat there are no results yet or window with best results.'''\ndef showHOF():\n lines = []\n prompt = \"\"\n global difficultyLevel\n if difficultyLevel == \"Beginner\":\n fileName = \"records_list_beginner.txt\"\n elif difficultyLevel == \"Advanced\":\n fileName = \"records_list_advanced.txt\"\n elif difficultyLevel == \"Master\":\n fileName = \"records_list_master.txt\"\n if os.path.isfile(fileName):\n hof = open(fileName, 'r')\n if len(hof.readlines()) > 0:\n hof.seek(0, 0)\n lines = [line.split(\";\") for line in hof.readlines()]\n for line in lines:\n line[3] = int(line[3])\n sortedLines = sorted(lines, key = lambda player: player[3]) # sort by time\n else:\n prompt = \"Oops, no records yet for \" + difficultyLevel + \" level...\"\n hof.close()\n else:\n prompt = \"Oops, no records yet for \" + difficultyLevel + \" level...\"\n # if no records, just show \"prompt\" message\n if prompt != \"\":\n messagebox.showinfo(\"Best results\", prompt)\n else:\n # show best results\n messageWindow(\"Best results\", sortedLines)\n\n\n'''Saves new record to the related to the current difficulty level file.\nCreates new file if it does not exist, adds record if there are less than 5\nrecords, deletes the worst result and adds new record \nif there are already 5 results in the file.'''\ndef processNewRecord(name):\n lines = []\n if name == \"\":\n name = \"Anonymous\"\n newRecordString = name + \";\" + difficultyLevel + \";\" + timeCount + \";\" + str(sec - 1)\n if checkRec[2] == \"new\": # operation = new\n # just add new record\n try:\n hof = open(checkRec[1], \"w\")\n hof.write(newRecordString)\n except FileNotFoundError:\n # create file if it does not exist\n hof = open(checkRec[1], \"w+\")\n hof.write(newRecordString)\n elif checkRec[2] == \"append\": # operation = append\n # append new record to the file\n hof = open(checkRec[1], \"a\")\n hof.write(\"\\n\" + newRecordString)\n elif checkRec[2] == \"rewrite\": # operation = rewrite\n # replace the lowest result with the new record\n lines.append([name, difficultyLevel, timeCount, int(sec - 1)])\n hof = open(checkRec[1], \"r\")\n for line in hof.readlines():\n ls = line.split(\";\")\n ls[3] = int(ls[3])\n lines.append(ls)\n hof.close()\n sortedLines = sorted(lines, key=lambda player: player[3]) # sort by time\n sortedLines.pop()\n hof = open(checkRec[1], \"w+\")\n isFirst = True\n for line in sortedLines:\n if isFirst:\n hof.write(line[0]+\";\"+line[1]+\";\"+line[2]+\";\"+str(line[3]))\n isFirst = False\n else:\n hof.write(\"\\n\" + line[0] + \";\" + line[1] + \";\" + line[2] + \";\" + str(line[3]))\n hof.close()\n\n\n'''Opens related to the current difficulty level file and checks \nif the time of the current game is shorter than those saved in the file.\nReturns report in a tuple of three parameters:\n- Boolean isNewRecord\n- String name of the related to the current difficulty level file\n- String operation type (new, append, rewrite).'''\ndef checkRecord():\n global timeCount, sec, difficultyLevel\n isNewRecord = False\n fileName = \"\"\n operation = \"\"\n # Check if this is a new record\n if difficultyLevel == \"Beginner\":\n fileName = \"records_list_beginner.txt\"\n elif difficultyLevel == \"Advanced\":\n fileName = \"records_list_advanced.txt\"\n elif difficultyLevel == \"Master\":\n fileName = \"records_list_master.txt\"\n if os.path.isfile(fileName):\n hof = open(fileName, 'r')\n hofLen = len(hof.readlines())\n hof.seek(0, 0)\n # less than 5 records\n if 0 <= hofLen < 5:\n isNewRecord = True\n operation = \"append\"\n # 5+ records\n else:\n for line in hof.readlines():\n l = line.split(\";\")\n if int(l[3]) > sec:\n isNewRecord = True\n operation = \"rewrite\"\n # new file\n else:\n isNewRecord = True\n operation = \"new\"\n hof = open(fileName, 'w+')\n hof.close()\n return isNewRecord, fileName, operation\n\n\n'''Requests checkRecord() function to check if it is a new record.\nShows a window with congratulations and offering\nuser to enter his name when a new record is established.'''\ndef congratWinner():\n global timeCount, sec, checkRec\n isNewRecord = False\n checkRec = checkRecord()\n isNewRecord = checkRec[0]\n # it is a new record\n if isNewRecord:\n message = \"Congratulations! \\n\\nYou have established a new record! \\nYour time is \" + timeCount + \"\\n\\nEnter your name:\"\n NewRecord.create_New_record(root, message)\n # not a record\n else:\n messagebox.showinfo(\"Winner\", \"Congratulations! \\n\" +\n \"Your solution is correct. \\n\" +\n \"Your time is \" + timeCount)\n\n\n'''Checks user's solution correctness.\nIf solution is correct, will call function congratWinner().\nIf is incorrect, will show error message.'''\ndef checkSolution():\n global gameTime, w, layout, isSolutionShown\n if isSolutionShown or not layout:\n return\n gameTime = False\n cells = w.getCells()\n n = 0\n isCorrect = True\n for l in layout:\n for i in l:\n if cells[n].get() == \"\" or int(cells[n].get()) != i:\n cells[n].configure({\"foreground\": \"Red\"})\n isCorrect = False\n cells[n].config(state=\"readonly\")\n n += 1\n if isCorrect:\n congratWinner()\n else:\n messagebox.showerror(\"Error\", \"Sorry! \\nYour solution is NOT correct. \\nYour time is {0}\".format(timeCount))\n\n\n'''Stops game and fills in cells with correct numbers.'''\ndef showSolution():\n global isSolutionShown, w, layout, gameTime\n if not layout:\n return\n gameTime = False\n cells = w.getCells()\n n = 0\n for l in layout:\n for i in l:\n cells[n].config(state=\"NORMAL\")\n cells[n].delete(0, END)\n cells[n].insert(0, i)\n cells[n].config(state=\"readonly\")\n n += 1\n isSolutionShown = True\n\n\n'''Starts and shows a timer, counting a time passed since the game was started.'''\ndef timerStart():\n global sec, gameTime, w, timeCount\n sec = 0\n while not gameOver:\n while gameTime:\n hours = sec // 3600\n minutes = (sec // 60) % 60\n seconds = sec % 60\n timeCount = \"\"\n if hours < 10:\n timeCount += \"0\"+str(hours)\n else:\n timeCount += str(hours)\n if minutes < 10:\n timeCount += \":0\"+str(minutes)\n else:\n timeCount += \":\"+str(minutes)\n if seconds < 10:\n timeCount += \":0\"+str(seconds)\n else:\n timeCount += \":\"+str(seconds)\n w.TLabel1.configure(text=timeCount)\n time.sleep(1)\n sec += 1\n\n\n'''Starts a new game. Requests a new layout, fills in cells with these numbers,\n hiding some of the numbers depending of the current difficulty level.\n Starts a timer.'''\ndef startNewGame():\n global w, layout, isSolutionShown, timer, gameTime, sec, difficultyLevel\n isSolutionShown = False\n difficultyLevel = w.level.get()\n cells = w.getCells()\n layout = None\n while not layout:\n layout = generator.generateLayout()\n hn = 0\n if difficultyLevel == \"Beginner\":\n hn = 20\n elif difficultyLevel == \"Advanced\":\n hn = 30\n elif difficultyLevel == \"Master\":\n hn = 40\n hideNums = random.sample(range(1, 81), hn)\n n = 0\n for l in layout:\n for i in l:\n cells[n].config(state=\"NORMAL\")\n cells[n].configure({\"foreground\": \"Black\"})\n if cells[n].get() != \"\":\n cells[n].delete(0, END)\n if n not in hideNums:\n cells[n].insert(0, i)\n cells[n].config(state=\"readonly\")\n n += 1\n gameTime = True\n sec = 0\n if not timer:\n timer = threading.Timer(0, timerStart)\n timer.start()\n\n'''Shows a window with the best results'''\ndef messageWindow(title, sortedLines):\n win = Toplevel()\n win.geometry(\"385x225+500+200\")\n win.title(title)\n Label(win, text=\"Name\").grid(row=0, column=0, ipady=5)\n Label(win, text=\"Difficulty\").grid(row=0, column=1, ipady=5)\n Label(win, text=\"Time\").grid(row=0, column=2, ipady=5)\n n = 1\n for line in sortedLines:\n Label(win, text=line[0]).grid(row=n, column=0, sticky=W, ipadx=40)\n Label(win, text=line[1]).grid(row=n, column=1, ipady=3)\n Label(win, text=line[2]).grid(row=n, column=2, ipadx=50)\n n += 1\n Label(win, text=\" \").grid(row=n)\n Button(win, text='Thanks!', command=win.destroy).grid(row=7, columnspan=3, sticky=S)\n\n\ndef set_Tk_var():\n global combobox\n combobox = StringVar()\n\n\n'''Initializer.'''\ndef init(top, gui, *args, **kwargs):\n global w, top_level, root, generator\n w = gui\n top_level = top\n root = top\n generator = LayoutGenerator.LayoutGenerator()\n set_Tk_var()\n return True\n\n\ndef destroy_window():\n # Function which closes the window.\n global gameTime\n print(\"bye bye\")\n global top_level\n gameTime = False\n top_level.destroy()\n top_level = None\n\n\n","sub_path":"SudokuApp/SudokuController.py","file_name":"SudokuController.py","file_ext":"py","file_size_in_byte":10405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"624856668","text":"import tensorflow as tf\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\n\ndef load_image(image_path):\n \"\"\"\n Load image (float32 conversion and normalization)\n\n :param image_path: path of the image to load, string\n :return:\n - image: Image, ndarray\n \"\"\"\n image = plt.imread(image_path)\n image = image.astype(np.float32)\n image = image / 255.\n\n return image\n\n\ndef load_images(image_folder_path):\n \"\"\"\n Load all images in the defined folder (float32 conversion and normalization)\n\n :param image_folder_path: path of the folder containing images, string\n :return:\n - images: Images of the folder, list of ndarray\n \"\"\"\n\n image_list = []\n for img in os.listdir(image_folder_path):\n image = plt.imread(image_folder_path + img)\n image = image.astype(np.float32)\n image = image / 255.\n image_list.append(image)\n\n return image_list\n\n\ndef preprocess_image(images, image_size=(256, 256)):\n images_list = []\n for image in images:\n image = tf.image.resize(image, image_size)\n images_list.append(image)\n images = np.asarray(images_list)\n tensor = tf.convert_to_tensor(images)\n return tensor\n\n\ndef show_images(images, titles=('',)):\n nb_images = len(images)\n for i in range(nb_images):\n plt.subplot(1, nb_images, i+1)\n plt.imshow(images[i], aspect='equal')\n plt.axis('off')\n plt.title(titles[i] if len(titles) > i else '')\n plt.show()\n\n\ndef postprocess_tensor(tensor, image_size=(256, 256)):\n image = tensor[0]\n image = tf.image.resize(image, image_size)\n return image\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"641137795","text":"import sys\na = sys.argv[1]\nf = open(a,'r')\nwords =[]\nfor string in f:\n\twords+=string.split()\n\nprint(a)\nfor word in words:\n\tprint (word)\nprint (\"Total \"+str(len(words))+\" words\")\n\nf.close()","sub_path":"lesson2/3/1/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"470789211","text":"#!/usr/bin/env python3\n\"\"\"Compatibility shims\n\"\"\"\nimport io\n\ndef zip_stream(file, chunk_size=8192):\n \"\"\"Fix non-seekable zip reading stream in Python < 3.7\n \"\"\"\n if not file.seekable():\n buffer = io.BytesIO()\n while True:\n bytes = file.read(chunk_size)\n if not bytes: break\n buffer.write(bytes)\n file.close()\n file = buffer\n return file\n","sub_path":"webscrapbook/_compat/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"531259443","text":"# Default imports\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import GridSearchCV\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\n\n# load data\ndataset = pd.read_csv('data/loan_clean_data.csv')\n# split data into X and y\nX = dataset.iloc[:, :-1]\ny = dataset.iloc[:, -1]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=9)\n\n# Write your solution here :\ndef xgboost (X_train, X_test, y_train, y_test,**kwargs):\n xgb = XGBClassifier()\n param_grid = {\"max_depth\": [ 2],\n \"min_child_weight\": [ 8],\n \"subsample\": [0.6, .7, .8, .9],\n \"colsample_bytree\": [0.6, .7, .8, .9, 1]\n }\n grid = GridSearchCV(xgb,param_grid,cv = 5)\n grid.fit(X_train,y_train)\n y_pred = grid.predict(X_test)\n accuracy = accuracy_score(y_test,y_pred)\n return accuracy.item()\n","sub_path":"q03_xgboost/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"335979519","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\ndef index(request):\n\tcontext = {\n\t\t'columns': [\n\t\t\t[0, 'duration'],\n\t\t\t[4, 'src_bytes'],\n\t\t\t[5, 'dst_bytes'],\n\t\t\t[7, 'wrong_fragment'],\n\t\t\t[8, 'urgent'],\n\t\t\t[9, 'hot'],\n\t\t\t[10, 'num_failed_logins'],\n\t\t\t[12, 'num_compromised'],\n\t\t\t[13, 'root_shell'],\n\t\t\t[14, 'su_attempted'],\n\t\t\t[15, 'num_root'],\n\t\t\t[16, 'num_file_creations'],\n\t\t\t[17, 'num_shells'],\n\t\t\t[18, 'num_access_files'],\n\t\t\t[19, 'num_outbound_cmds'],\n\t\t\t[22, 'count'],\n\t\t\t[23, 'srv_count'],\n\t\t\t[24, 'serror_rate'],\n\t\t\t[25, 'srv_serror_rate'],\n\t\t\t[26, 'rerror_rate'],\n\t\t\t[27, 'srv_rerror_rate'],\n\t\t\t[28, 'same_srv_rate'],\n\t\t\t[29, 'diff_srv_rate'],\n\t\t\t[30, 'srv_diff_host_rate'],\n\t\t\t[31, 'dst_host_count'],\n\t\t\t[32, 'dst_host_srv_count'],\n\t\t\t[33, 'dst_host_same_srv_rate'],\n\t\t\t[34, 'dst_host_diff_srv_rate'],\n\t\t\t[35, 'dst_host_same_src_port_rate'],\n\t\t\t[36, 'dst_host_srv_diff_host_rate'],\n\t\t\t[37, 'dst_host_serror_rate'],\n\t\t\t[38, 'dst_host_srv_serror_rate'],\n\t\t\t[39, 'dst_host_rerror_rate'],\n\t\t\t[40, 'dst_host_srv_rerror_rate'],\n\t\t]\n\t}\n\treturn render(request, 'kmeans/index.html', context)\n\ndef scatterplot(request):\n\tcolumns = request.POST.getlist('columns[]')\n\tprint(columns)\n\treturn render(request, 'kmeans/index.html')","sub_path":"kmeans/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"546325651","text":"\"\"\"\nThis file is used to configure application settings.\n\nDo not import this file directly.\n\nYou can use the settings API via:\n\n from ferris import settings\n\n mysettings = settings.get(\"mysettings\")\n\nThe settings API will load the \"settings\" dictionary from this file. Anything else\nwill be ignored.\n\nOptionally, you may enable the dynamic settings plugin at the bottom of this file.\n\"\"\"\n\nsettings = {}\n\nsettings['timezone'] = {\n 'local': 'US/Eastern'\n}\n\nsettings['email'] = {\n # Configures what address is in the sender field by default.\n 'sender': 'ocardona@grupodot.com'\n}\n\nsettings['app_config'] = {\n 'webapp2_extras.sessions': {\n # WebApp2 encrypted cookie key\n # You can use a UUID generator like http://www.famkruithof.net/uuid/uuidgen\n 'secret_key': '9a788030-837b-11e1-b0c4-0800200c9a66',\n }\n}\n\nsettings['oauth2'] = {\n # OAuth2 Configuration should be generated from\n # the google cloud console (Credentials for Web Application)\n 'client_id': None, # XXXXXXXXXXXXXXX.apps.googleusercontent.com\n 'client_secret': None,\n 'developer_key': None # Optional\n}\n\nsettings['oauth2_service_account'] = {\n # OAuth2 service account configuration should be generated\n # from the google cloud console (Service Account Credentials)\n 'client_email': None, # XXX@developer.gserviceaccount.com\n 'private_key': None, # Must be in PEM format\n 'developer_key': None # Optional\n}\n\nsettings['upload'] = {\n # Whether to use Cloud Storage (default) or the blobstore to store uploaded files.\n 'use_cloud_storage': True,\n # The Cloud Storage bucket to use. Leave as \"None\" to use the default GCS bucket.\n # See here for info: https://developers.google.com/appengine/docs/python/googlecloudstorageclient/activate#Using_the_Default_GCS_Bucket\n 'bucket': None\n}\n\n# Enables or disables app stats.\n# Note that appstats must also be enabled in app.yaml.\nsettings['appstats'] = {\n 'enabled': False,\n 'enabled_live': False\n}\n\n# Optionally, you may use the settings plugin to dynamically\n# configure your settings via the admin interface. Be sure to\n# also enable the plugin via app/routes.py.\n\n#import plugins.settings\n\n# import any additional dynamic settings classes here.\n\n# import plugins.my_plugin.settings\n\n# Un-comment to enable dynamic settings\n#plugins.settings.activate(settings)\n\n\"\"\"\nCopy these settings to the bottom of app/settings.py\n\"\"\"\n\n# get your own recaptcha keys by registering at http://www.google.com/recaptcha/\nsettings['captcha_public_key'] = \"6LdQTv0SAAAAAHpwmUanuNsZUgQzRoJ7AwQwK8Dm\"\nsettings['captcha_private_key'] = \"6LdQTv0SAAAAAMfLm4-2wM5ShXpGO2vBgHzk5I2t\"\n\n\"\"\"\nCopy the contents of this file into the bottom of `app/settings.py`\n\nModify the settings as needed\n\"\"\"\n\n# This gets used in emails\nsettings['app_name'] = 'FarmaSocial'\n\nsettings['app_config'] = {\n 'webapp2_extras.sessions': {\n # WebApp2 encrypted cookie key\n # You can use a UUID generator like http://www.famkruithof.net/uuid/uuidgen\n 'secret_key': '_PUT_KEY_HERE_YOUR_SECRET_KEY_',\n },\n 'webapp2_extras.auth': {\n 'user_model': 'plugins.custom_auth.models.user.User',\n 'user_attributes': ['email'],\n }\n}\n\n# Password AES Encryption Parameters\n# aes_key must be only 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*) bytes (characters) long.\nsettings['aes_key'] = \"12_24_32_BYTES_KEY_FOR_PASSWORDS\"\nsettings['salt'] = \"_PUT_SALT_HERE_TO_SHA512_PASSWORDS_\"\n\n#Twitter Login\n# get your own consumer key and consumer secret by registering at https://dev.twitter.com/apps\n# callback url must be: http://[YOUR DOMAIN]/login/twitter/complete\nsettings['twitter_consumer_key'] = \"bn4f5vBMQtTxH49Gz8QnXZV0H\"\nsettings['twitter_consumer_secret'] = \"nHuSnZntHnlW8Kl3zLCmGuGHafZr1k7jBFrwLVKt7dVYnj1ppt\"\n\n#Facebook Login\n# get your own consumer key and consumer secret by registering at https://developers.facebook.com/apps\n#Very Important: set the site_url= your domain in the application settings in the facebook app settings page\n# callback url must be: http://[YOUR DOMAIN]/login/facebook/complete\nsettings['fb_api_key'] = '1483155815278222'\nsettings['fb_secret'] = '1d0cfec2dc923832132f5d9346c25686'\n\n#Linkedin Login\n#Get you own api key and secret from https://www.linkedin.com/secure/developer\nsettings['linkedin_api'] = 'LINKEDIN_API'\nsettings['linkedin_secret'] = 'LINKEDIN_SECRET'\n\n# Github login\n# Register apps here: https://github.com/settings/applications/new\nsettings['github_server'] = 'github.com'\nsettings['github_redirect_uri'] = 'http://www.example.com/social_login/github/complete',\nsettings['github_client_id'] = 'GITHUB_CLIENT_ID'\nsettings['github_client_secret'] = 'GITHUB_CLIENT_SECRET'\n\n# Enable Federated login (OpenID and OAuth)\n# Google App Engine Settings must be set to Authentication Options: Federated Login\nsettings['enable_federated_login'] = True\n\n# List of social login providers\n# uri is for OpenID only (not OAuth)\nsettings['social_providers'] = { \n 'google': {'name': 'google', 'label': 'Google', 'uri': 'gmail.com'},\n 'github': {'name': 'github', 'label': 'Github', 'uri': ''},\n 'facebook': {'name': 'facebook', 'label': 'Facebook', 'uri': ''},\n 'linkedin': {'name': 'linkedin', 'label': 'LinkedIn', 'uri': ''},\n #'myopenid': {'name': 'myopenid', 'label': 'MyOpenid', 'uri': 'myopenid.com'},\n 'twitter': {'name': 'twitter', 'label': 'Twitter', 'uri': ''},\n 'yahoo': {'name': 'yahoo', 'label': 'Yahoo!', 'uri': 'yahoo.com'},\n }\n\n# If true, it will write in datastore a log of every email sent\nsettings['log_email'] = False\n\n# If true, it will write in datastore a log of every visit\nsettings['log_visit'] = False\n\nsettings['callback'] = '/mayorista/welcome'","sub_path":"app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"452649362","text":"# -*- coding: utf-8 -*-\n\nfrom collections import namedtuple\n\nmax_edge_list = []\nfor file_id in range(5):\n file_name = './MESH/gd'+str(file_id)\n \n Node = namedtuple(\"Node\",'x,y,marker')\n Elem = namedtuple(\"Elem\",'i,j,k,ei,ej,ek,si,sj,sk,xV,yV,marker')\n Side = namedtuple(\"Side\",'c,d,ea,eb,marker')\n \n nodes = {}\n elems = {}\n sides = {}\n \n node_file = open(file_name+'.n','r')\n for _ in range(int(node_file.readline().split()[0])):\n ln = node_file.readline().split()\n nodes[int(ln[0])] = Node(float(ln[1]),float(ln[2]),int(ln[3]))\n node_file.close()\n \n elem_file = open(file_name+'.e')\n for _ in range(int(elem_file.readline().split()[0])):\n ln = elem_file.readline().split()\n elems[int(ln[0])] = Elem(*([int(x) for x in ln[1:10]] \\\n +[float(x) for x in ln[10:12]]\\\n +[int(ln[12])]))\n elem_file.close()\n \n side_file = open(file_name+'.s')\n for _ in range(int(side_file.readline().split()[0])):\n ln = side_file.readline().split()\n sides[int(ln[0])] = Side(*[int(x) for x in ln[1:]])\n side_file.close()\n \n edge_length_list_x = [nodes[sid.c].x - nodes[sid.d].x for idx,sid in sides.items()]\n edge_length_list_y = [nodes[sid.c].y - nodes[sid.d].y for idx,sid in sides.items()]\n \n edge_length_list = [i**2+j**2 for i,j in zip(edge_length_list_x,edge_length_list_y)]\n \n max_edge_list += [max(edge_length_list)**(1/2)]","sub_path":"addCountMaxEdge.py","file_name":"addCountMaxEdge.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"115434415","text":"import os.path as op\n\nfrom setuptools import setup\n\n\nwith open(op.join(op.dirname(__file__), './README.md')) as fin:\n long_description = fin.read()\n\n\nsetup(\n name='wcpan.drive.google',\n version='3.1.0',\n author='Wei-Cheng Pan',\n author_email='legnaleurc@gmail.com',\n description='Asynchronous Google Drive API.',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/legnaleurc/wcpan.drive.google',\n packages=[\n 'wcpan.drive.google',\n ],\n python_requires='>= 3.7',\n install_requires=[\n 'PyYAML ~= 3.12',\n 'aiohttp ~= 3.3.2',\n 'arrow ~= 0.12.1',\n 'wcpan.logger ~= 1.2.3',\n 'wcpan.worker ~= 4.1.0',\n ],\n classifiers=[\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3.7',\n ])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"516839426","text":"#!/opt/stack/bin/python\n#\n# @SI_Copyright@\n# stacki.com\n# v3.2\n# \n# Copyright (c) 2006 - 2016 StackIQ Inc. All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice unmodified and in its entirety, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided \n# with the distribution.\n# \n# 3. All advertising and press materials, printed or electronic, mentioning\n# features or use of this software must display the following acknowledgement: \n# \n# \t \"This product includes software developed by StackIQ\" \n# \n# 4. Except as permitted for the purposes of acknowledgment in paragraph 3,\n# neither the name or logo of this software nor the names of its\n# authors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY STACKIQ AND CONTRIBUTORS ``AS IS''\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STACKIQ OR CONTRIBUTORS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# @SI_Copyright@\n#\n# @Copyright@\n# \t\t\t\tRocks(r)\n# \t\t www.rocksclusters.org\n# \t\t version 5.4 (Maverick)\n# \n# Copyright (c) 2000 - 2010 The Regents of the University of California.\n# All rights reserved.\t\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice unmodified and in its entirety, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided \n# with the distribution.\n# \n# 3. All advertising and press materials, printed or electronic, mentioning\n# features or use of this software must display the following acknowledgement: \n# \n# \t\"This product includes software developed by the Rocks(r)\n# \tCluster Group at the San Diego Supercomputer Center at the\n# \tUniversity of California, San Diego and its contributors.\"\n# \n# 4. Except as permitted for the purposes of acknowledgment in paragraph 3,\n# neither the name or logo of this software nor the names of its\n# authors may be used to endorse or promote products derived from this\n# software without specific prior written permission. The name of the\n# software includes the following terms, and any derivatives thereof:\n# \"Rocks\", \"Rocks Clusters\", and \"Avalanche Installer\". For licensing of \n# the associated name, interested parties should contact Technology \n# Transfer & Intellectual Property Services, University of California, \n# San Diego, 9500 Gilman Drive, Mail Code 0910, La Jolla, CA 92093-0910, \n# Ph: (858) 534-5815, FAX: (858) 534-7345, E-MAIL:invent@ucsd.edu\n# \n# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# @Copyright@\n\nfrom __future__ import print_function\nimport os\nimport os.path\nimport sys\nimport stack.app\nimport stack.bootable\nimport stack.file\nfrom stack.exception import *\n\n\nclass App(stack.app.Application):\n\tdef __init__(self, argv):\n\t\tstack.app.Application.__init__(self, argv)\n\t\tself.usage_name = 'build-initrd'\n\t\tself.usage_version = '@VERSION@'\n\t\tself.rpmsPath = None\n\n\t\tself.getopt.l.extend([\n\t\t\t('rpms=', 'Path to Local RPMs'),\n\t\t\t('pkgs=', 'RPM packages to add to initrd.img'),\n\t\t\t('update-pkgs=',\n\t\t\t'RPM packages to add to /updates in initrd.img'),\n\t\t\t('build-directory=',\n\t\t\t\t'Directory to apply all RPMs to')\n\t\t])\n\n\tdef parseArg(self, c):\n\t\tif stack.app.Application.parseArg(self, c):\n\t\t\treturn 1\n\t\telif c[0] == '--rpms':\n\t\t\tself.rpmsPath = c[1]\n\t\telif c[0] == '--pkgs':\n\t\t\tself.pkgs = c[1].split()\n\t\telif c[0] == '--update-pkgs':\n\t\t\tself.updatepkgs = c[1].split()\n\t\telif c[0] == '--build-directory':\n\t\t\tself.builddir = c[1]\n\t\treturn 0\n\n\n\tdef overlaypkgs(self, pkgs, update):\n\t\tfor pkg in pkgs:\n\t\t\tRPM = self.boot.findFile(pkg)\n\t\t\tif not RPM:\n\t\t\t\traise CommandError(self, \"Could not find %s rpm\" % (pkg))\n\n\t\t\tprint(\"Applying package %s\" % (pkg))\n\n\t\t\tself.boot.applyRPM(RPM, \n\t\t\t\tos.path.join(os.getcwd(), pkg),\n\t\t\t\t\tflags='--noscripts --excludedocs')\n\n\t\t\t#\n\t\t\t# now 'overlay' the package onto the expanded initrd\n\t\t\t#\n\t\t\tdestdir = '../%s' % self.builddir\n\t\t\tif update == 1:\n\t\t\t\tdestdir = '%s/updates' % destdir\n\n\t\t\tos.system('cd %s ; find . -not -type d | cpio -pdu %s'\n\t\t\t\t% (pkg, destdir))\n\n\n\tdef run(self):\n\t\tprint(\"build-initrd starting...\")\n\n\t\tself.boot = stack.bootable.Bootable(self.rpmsPath, self.builddir)\n\n\t\tprint('updatepkgs: ' , self.updatepkgs)\n\t\tprint('pkgs: ' , self.pkgs)\n\n\t\t#\n\t\t# overlay packages onto the initrd.img\n\t\t#\n\t\tupdate = 1 \n\t\tself.overlaypkgs(self.updatepkgs, update)\n\n\t\tupdate = 0\n\t\tself.overlaypkgs(self.pkgs, update)\n\n\t\tprint(\"build-initrd complete.\")\n\n# Main\napp = App(sys.argv)\napp.parseArgs()\napp.run()\n\n","sub_path":"src/stack/images/build-initrd.py","file_name":"build-initrd.py","file_ext":"py","file_size_in_byte":6524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"242977884","text":"# (C) Copyright 2014 Voyager Search\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Executes a Voyager processing task.\"\"\"\nimport os\nimport collections\nimport json\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), 'tasks'))\nimport tasks\n# from tasks import utils\nfrom tasks.utils import task_utils\n\n\ndef run_task(json_file):\n \"\"\"Main function for running processing tasks.\"\"\"\n with open(json_file) as data_file:\n try:\n request = json.load(data_file)\n __import__(request['task'])\n getattr(sys.modules[request['task']], \"execute\")(request)\n except (ImportError, ValueError) as ex:\n sys.stderr.write(repr(ex))\n sys.exit(1)\n\n\nif __name__ == '__main__':\n if sys.argv[1] == '--info':\n # Metadata GP tools do not work in Python with ArcGIS 10.0\n task_info = collections.defaultdict(list)\n info_dir = os.path.join(os.path.dirname(__file__), 'info')\n for task in tasks.__all__:\n # Validate the .info.json file.\n task_properties = collections.OrderedDict()\n task_properties['name'] = task\n task_properties['available'] = True\n fp = None\n try:\n fp = open(os.path.join(info_dir, '{0}.info.json'.format(task)))\n d = json.load(fp)\n if 'available' in d and not d['available']:\n task_properties['available'] = False\n except ValueError as ve:\n task_properties['available'] = False\n task_properties['JSON syntax error'] = str(ve)\n except IOError:\n continue\n finally:\n if fp:\n fp.close()\n\n # Validate the Python code.\n try:\n __import__(task)\n except task_utils.LicenseError as le:\n task_properties['available'] = False\n task_properties['No LocateXT License'] = str(le)\n except IOError as ioe:\n task_properties['available'] = False\n task_properties['No LocateXT Tool'] = str(ioe)\n except ImportError as ie:\n if 'arcpy' in str(ie):\n task_properties['available'] = False\n task_properties['Import error'] = '{0}. Requires ArcGIS'.format(str(ie))\n else:\n task_properties['available'] = False\n task_properties['Import error'] = str(ie)\n except (RuntimeError, TypeError) as re:\n if 'NotInitialized' in str(re):\n task_properties['available'] = False\n task_properties['License error'] = '{0}. ArcGIS is not licensed.'.format(str(re))\n else:\n task_properties['available'] = False\n task_properties['Error'] = str(re)\n except SyntaxError as se:\n task_properties['available'] = False\n task_properties['Python syntax error'] = str(se)\n\n task_info['tasks'].append(task_properties)\n sys.stdout.write(json.dumps(task_info, indent=2))\n sys.stdout.flush()\n elif sys.argv[1] == '--license':\n import arcpy\n with open(os.path.join(os.path.dirname(__file__), 'supportfiles', 'licenses.json'), 'r') as fp:\n licenses = json.load(fp)\n for product in licenses['product']:\n product['status'] = arcpy.CheckProduct(product['code'])\n for extension in licenses['extension']:\n extension['status'] = arcpy.CheckExtension(extension['code'])\n [licenses['extension'].remove(e) for e in licenses['extension'] if e['status'].startswith('Unrecognized')]\n sys.stdout.write(json.dumps(licenses, indent=2))\n sys.stdout.flush()\n else:\n run_task(sys.argv[1])\n sys.exit(0)\n","sub_path":"processing/VoyagerTaskRunner.py","file_name":"VoyagerTaskRunner.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"604105853","text":"import math\n\ndef load_raw():\n infile = open(\"099_data\",\"r\")\n indata = infile.read()\n infile.close()\n return indata\n\ndef process(d):\n ou = []\n k = []\n hold = \"\"\n for x in d:\n if (x == \",\") or (ord(x) == 10) or (ord(x) == 13):\n if len(hold) != 0:\n k.append(float(hold))\n hold = \"\"\n if x == \",\":\n continue\n # x is a return character\n if len(k) != 0:\n ou.append(k)\n k = []\n else:\n # not a special character\n hold += x\n return ou\n\ndef logify(d):\n ou = []\n for x in d:\n ou.append(math.log10(x[0])*x[1])\n return ou\n\ndef find_max(d):\n max_index = 0\n for i in range(1,len(d)):\n if d[i] > d[max_index]:\n max_index = i\n return max_index + 1 # start counting lines at 1\n\ndef main():\n d = load_raw()\n d = process(d)\n d = logify(d)\n d = find_max(d)\n print(d)\n\nmain()\n","sub_path":"001-100/091-100/099.py","file_name":"099.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"346361338","text":"from django.contrib import messages\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.urls import reverse\nfrom django.views.generic import ListView, View\n\nfrom pretalx.common.mixins.views import (\n ActionFromUrl, Filterable, PermissionRequired, Sortable,\n)\nfrom pretalx.common.views import CreateOrUpdateView\nfrom pretalx.person.forms import SpeakerProfileForm\nfrom pretalx.person.models import SpeakerProfile, User\n\n\nclass SpeakerList(PermissionRequired, Sortable, Filterable, ListView):\n model = SpeakerProfile\n template_name = 'orga/speaker/list.html'\n context_object_name = 'speakers'\n default_filters = ('user__nick__icontains', 'user__email__icontains', 'user__name__icontains')\n sortable_fields = ('user__nick', 'user__email', 'user__name')\n default_sort_field = 'user__name'\n paginate_by = 25\n permission_required = 'orga.view_speakers'\n\n def get_permission_object(self):\n return self.request.event\n\n def get_queryset(self):\n qs = SpeakerProfile.objects.filter(event=self.request.event)\n qs = self.filter_queryset(qs)\n qs = self.sort_queryset(qs)\n return qs\n\n\nclass SpeakerDetail(PermissionRequired, ActionFromUrl, CreateOrUpdateView):\n template_name = 'orga/speaker/form.html'\n form_class = SpeakerProfileForm\n model = User\n permission_required = 'orga.view_speaker'\n write_permission_required = 'orga.change_speaker'\n\n def get_object(self):\n return get_object_or_404(\n User.objects.filter(submissions__in=self.request.event.submissions.all()).order_by('id').distinct(),\n pk=self.kwargs['pk'],\n )\n\n def get_permission_object(self):\n return self.get_object().profiles.filter(event=self.request.event).first()\n\n @property\n def permission_object(self):\n return self.get_permission_object()\n\n def get_success_url(self) -> str:\n return reverse('orga:speakers.view', kwargs={'event': self.request.event.slug, 'pk': self.get_object().pk})\n\n def get_context_data(self, *args, **kwargs):\n ctx = super().get_context_data(*args, **kwargs)\n submissions = self.request.event.submissions.filter(speakers__in=[self.get_object()])\n ctx['submission_count'] = submissions.count()\n ctx['submissions'] = submissions\n return ctx\n\n def form_valid(self, form):\n messages.success(self.request, 'The speaker profile has been updated.')\n if form.has_changed():\n profile = self.get_object().profiles.filter(event=self.request.event).first()\n if profile:\n profile.log_action('pretalx.user.profile.update', person=self.request.user, orga=True)\n return super().form_valid(form)\n\n def get_form_kwargs(self, *args, **kwargs):\n ret = super().get_form_kwargs(*args, **kwargs)\n ret.update({\n 'event': self.request.event,\n 'user': self.get_object(),\n })\n return ret\n\n\nclass SpeakerToggleArrived(PermissionRequired, View):\n permission_required = 'orga.change_speaker'\n\n def get_object(self):\n return get_object_or_404(SpeakerProfile, event=self.request.event, user_id=self.kwargs['pk'])\n\n def dispatch(self, request, event, pk):\n profile = self.get_object()\n profile.has_arrived = not profile.has_arrived\n profile.save()\n action = 'pretalx.speaker.arrived' if profile.has_arrived else 'pretalx.speaker.unarrived'\n profile.user.log_action(action, data={'event': self.request.event.slug}, person=self.request.user, orga=True)\n if request.GET.get('from') == 'list':\n return redirect(reverse('orga:speakers.list', kwargs={'event': self.kwargs['event']}))\n return redirect(reverse(\n 'orga:speakers.view',\n kwargs=self.kwargs,\n ))\n","sub_path":"src/pretalx/orga/views/speaker.py","file_name":"speaker.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"339525618","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport os\nimport sys\nsys.path.append(sys.path[0] + (\"/\" if sys.path[0] else None) + \"..\")\nfrom shared import GMMData\nfrom shared import BAData\nfrom shared import HandData\nfrom shared import LSTMData\nfrom shared import input_utils\nfrom runner.Filepaths import filepath_to_dirname\nfrom runner.Benchmark import run_benchmark\n\n# function printing to stderr\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\ndef main(argv):\n try:\n if (len(argv) < 9):\n eprint(\"usage: PythonRunner test_type module_path input_filepath \" +\\\n \"output_dir minimum_measurable_time nruns_F nruns_J time_limit [-rep]\\n\")\n return 1\n\n test_type = argv[1]\n module_path = os.path.normpath(argv[2])\n input_filepath = os.path.normpath(argv[3])\n output_prefix = os.path.normpath(argv[4])\n minimum_measurable_time = float(argv[5])\n nruns_F = int(argv[6])\n nruns_J = int(argv[7])\n time_limit = float(argv[8])\n\n # read only 1 point and replicate it?\n replicate_point = (len(argv) > 9 and str(argv[9]) == \"-rep\")\n\n # If the given prefix is a directory then add a separator to its end\n # thus we can just use concatenation further\n if os.path.isdir(output_prefix):\n output_prefix += os.path.sep\n\n if test_type == \"GMM\":\n # read gmm input\n _input = input_utils.read_gmm_instance(input_filepath, replicate_point)\n elif test_type == \"BA\":\n # read ba input\n _input = input_utils.read_ba_instance(input_filepath)\n elif test_type == \"HAND\":\n model_dir = os.path.join(filepath_to_dirname(input_filepath), \"model\")\n # read hand input\n _input = input_utils.read_hand_instance(model_dir, input_filepath, False)\n elif test_type == \"HAND-COMPLICATED\":\n model_dir = os.path.join(filepath_to_dirname(input_filepath), \"model\")\n # read hand complicated input\n _input = input_utils.read_hand_instance(model_dir, input_filepath, True)\n elif test_type == \"LSTM\":\n _input = input_utils.read_lstm_instance(input_filepath)\n else:\n raise RuntimeError(\"Python runner doesn't support tests of \" + test_type + \" type\")\n\n run_benchmark(\n module_path,\n input_filepath,\n _input,\n output_prefix,\n minimum_measurable_time,\n nruns_F,\n nruns_J,\n time_limit\n )\n\n except RuntimeError as ex:\n eprint(\"Runtime exception caught: \", ex)\n except Exception as ex:\n eprint(\"An exception caught: \", ex)\n\n return 0\n\nif __name__ == \"__main__\":\n main(sys.argv[:])","sub_path":"src/python/runner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"398870067","text":"# in routing.py\nfrom channels.routing import route,include\nfrom .consumers import *\n\nrouting = [\n\n\troute(\"websocket.connect\", connectSocket , path=r\"^/meeteat/(?P[0-9]+)/$\"),\n\troute(\"websocket.disconnect\", disconnectSocket , path=r\"^/meeteat/(?P[0-9]+)/$\"),\n\troute(\"websocket.receive\", receiveMessage , path=r\"^/meeteat/(?P[0-9]+)/$\"),\n\t\n]\n","sub_path":"Server/meeteat/meeteat/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"223032894","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom elasticsearch import Elasticsearch\nfrom pprint import pprint\n\n\ndef cluster_state(es):\n \"\"\"Get a comprehensive state information of the whole cluster.\n \"\"\"\n pprint(es.cluster.state())\n\n\ndef cluster_stats(es):\n \"\"\"he Cluster Stats API allows to retrieve statistics from a cluster wide\n perspective. The API returns basic index metrics and information about\n the current nodes that form the cluster.\n \"\"\"\n pprint(es.cluster.stats())\n\n\nif __name__ == '__main__':\n es = Elasticsearch(['http://127.0.0.1:9200/'])\n cluster_state(es)\n cluster_stats(es)\n\n\n# references\n# https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch/client/cluster.py#L53","sub_path":"elasticsearch/cluster.state.py","file_name":"cluster.state.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"293923916","text":"# # `datetime` module examples\n#\n# This module will allow you to get the current date/time and calculate deltas, among many functions.\n#\n# If you want to use the current timestamp as a table name suffix in SQL, you'll need to do a bit of string manipulation, as shown in the creation of the `clean_timestamp` variable.\n\nfrom datetime import datetime\n\n# Get the timestamp for right now\nthis_instant = datetime.now()\n\n# Let's inspect this item's type and representation\nprint(type(this_instant))\nthis_instant\n\n# Turn this timestamp into a string and the format as you want\ntimestamp_str = str(this_instant)\nprint(timestamp_str)\n\n# +\n# Extract date and time\nthe_date, the_time = timestamp_str.split(\" \")\nprint(the_date)\nprint(the_time)\n\n# Omit the miliseconds in the time\nthe_time = the_time.split(\".\")[0]\nprint(the_time)\n\n# +\n# Replace unwanted characters in the_time with an underscore\nthe_time = the_time.replace(\":\", \"_\")\n \n# Do the same for the date's dash\nthe_date = the_date.replace(\"-\", \"_\")\n \nclean_timestamp = f\"{the_date}_{the_time}\"\n# -\n\nprint(clean_timestamp)\n","sub_path":"basic/general/pure_python/use_datetime.py","file_name":"use_datetime.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"136898585","text":"# -*- coding: UTF-8 -*-\n\"\"\"\n:Script: plot_arr.py\n:Author: Dan.Patterson@carleton.ca\n:Modified: 2018-08-18\n:Purpose: To plot a 3D array as a graph with each dimension appearing\n: row-wise, instead of down a column. This produces a side-by-side\n: comparison of the data.\n:\n:Functions:\n: - plot_grid\n:Notes:\n: plt is matplotlib.pyplot from import\n: fig = plt.gcf() # get the current figure\n: fig.get_size_inches() # find out its size in inches\n: array([ 9.225, 6.400])\n: fig.bbox_inches\n: Bbox('array([[ 0.000, 0.000],\\n [ 9.225, 6.400]])')\n:References:\n:----------\n: https://matplotlib.org/2.0.0/api/figure_api.html\n:\n\"\"\"\n# ---- imports, formats, constants ----\nimport sys\nimport numpy as np\nfrom textwrap import dedent\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n# import matplotlib.colors as mc\n\n# local import\n\nft = {'bool': lambda x: repr(x.astype('int32')),\n 'float_kind': '{: 0.2f}'.format}\nnp.set_printoptions(edgeitems=3, linewidth=80, precision=2,\n suppress=True, threshold=20,\n formatter=ft)\n\nscript = sys.argv[0]\n\n\n# ---- functions -------------------------------------------------------------\n#\ndef plot_grid(a):\n \"\"\"Emulate a 3D array plotting each dimension sequentially.\n :Requires:\n :---------\n : a - an ndarray. if a.ndim < 3, an extra dimension is prepended to it.\n : The min and max are determined from the input data values.\n : This is used later on for interpolation.\n :Returns:\n : A plot of the array dimensions.\n \"\"\"\n def plot_3d(rows=1, cols=1):\n \"\"\"Set the parameters of the 3D array for plotting\"\"\"\n x = np.arange(cols)\n y = np.arange(rows)\n xg = np.arange(-0.5, cols + 0.5, 1)\n yg = np.arange(-0.5, rows + 0.5, 1)\n return [x, y, xg, yg]\n #\n a = a.squeeze()\n if a.ndim < 3:\n frmt = \"1D and 2D arrays not supported, read the docs\\n{}\"\n print(dedent(frmt).format(plot_grid.__doc__))\n return None\n # proceed with 3D array\n n, rows, cols = a.shape\n x, y, xg, yg = plot_3d(rows, cols)\n w = (cols*n)//2\n h = (rows + 1)//2\n w = max(w, h)\n h = min(w, h)\n fig, axes = plt.subplots(1, n, sharex=True, sharey=True,\n dpi=150, figsize=(w, h))\n fig.set_tight_layout(True)\n fig.set_edgecolor('w')\n fig.set_facecolor('w')\n idx = 0\n for ax in axes:\n m_min = a.min()\n m_max = a.max()\n a_s = a[idx]\n col_lbl = \"Cols: for \" + str(idx)\n ax.set_aspect('equal')\n ax.set_adjustable('box') # box-forced') # deprecated prevents spaces\n ax.set_xticks(xg, minor=True)\n ax.set_yticks(yg, minor=True)\n ax.set_xlabel(col_lbl, labelpad=12)\n ax.xaxis.label_position = 'top'\n ax.xaxis.label.set_fontsize(12)\n if idx == 0:\n ax.set_ylabel(\"Rows\", labelpad=2) # was 12\n ax.yaxis.label.set_fontsize(12)\n ax.grid(which='minor', axis='x', linewidth=1, linestyle='-', color='k')\n ax.grid(which='minor', axis='y', linewidth=1, linestyle='-', color='k')\n t = [[x, y, a_s[y, x]]\n for y in range(rows)\n for x in range(cols)]\n for i, (x_val, y_val, c) in enumerate(t):\n ax.text(x_val, y_val, c, va='center', ha='center', fontsize=12)\n ax.matshow(a[idx], cmap=cm.gray_r, interpolation='nearest',\n vmin=m_min, vmax=m_max, alpha=0.2)\n idx += 1\n # ---- end of script ----------------------------------------------------\n\n\ndef _plt_(a):\n \"\"\"\n :one array shows numbers, the alternate text\n \"\"\"\n plot_grid(a)\n print(\"array... shape {} ndim {}\\n{}\".format(a.shape, a.ndim, a))\n\n\n# ----------------------------------------------------------------------------\nif __name__ == \"__main__\":\n \"\"\" \"\"\"\n# print(\"Script... {}\".format(script))\n d, r, c = [3, 8, 4]\n a = np.arange(d*r*c).reshape(d, r, c)\n b = a * 1.0\n c = np.random.randint(96, size=96).reshape(d, r, c)\n c1 = c * 1.0\n d = np.arange(2*3*3*4).reshape(2, 3, 3, 4)\n e = np.arange(4*5).reshape(4, 5)\n# _plt_(a)\n","sub_path":"arraytools/graphing/plot_arr.py","file_name":"plot_arr.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"599170352","text":"from math import sqrt\ndef sum_for_list(lst):\n pf = set()\n for i in lst:\n if i < 0: i /= -1\n for j in range(2, int(sqrt(i)) + 1):\n while i % j == 0 and i != 1:\n pf.add(j)\n i /= j\n if i is not 1: pf.add(i)\n return [[p, sum(i for i in lst if i % p == 0)] for p in sorted(pf)]\n","sub_path":"codewars/sum_by_factors.py","file_name":"sum_by_factors.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"345663102","text":"\"\"\"\n767\nmedium\nreorganize string\n\"\"\"\n\nfrom heapq import *\nfrom collections import Counter\n\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n\n count = Counter(s)\n res = \"\"\n heap = [(-count[key], key) for key in count]\n heapify(heap)\n while len(heap) >= 2:\n count1, key1 = heappop(heap)\n count2, key2 = heappop(heap)\n res += key1 + key2\n count2 += 1\n count1 += 1\n if count2 != 0:\n heappush(heap, (count2, key2))\n if count1 != 0:\n heappush(heap, (count1, key1))\n\n if heap and heap[0][0] < -1:\n return \"\"\n\n if heap:\n res += heap[0][1]\n\n return res\n\nsol = Solution()\ns1 = \"aaab\"\nprint(sol.reorganizeString(s1))\n\n","sub_path":"Q767.py","file_name":"Q767.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"382383756","text":"def ios_sort(interfaces):\n if isinstance(interfaces, list):\n return sorted(interfaces, key=normalize_ios_interface)\n elif isinstance(interfaces, dict):\n return sorted(interfaces.items(), key=lambda x: normalize_ios_interface(x[0]))\n\ndef normalize_ios_interface(value):\n if isinstance(value, int):\n return value\n\n order = {\n 'Loopback': 0,\n 'Port-channel': 1,\n 'GigabitEthernet': 2,\n }\n\n import re\n x = [order.get(re.match('\\D*', value).group().lower())]\n x.extend(map(int, filter(None, re.split('\\D+', value))))\n return tuple(x)\n\nclass FilterModule(object):\n def filters(self):\n return {\n 'ios_sort': ios_sort,\n }\n","sub_path":"homelab/001_base_templates/filter_plugins/interface_sort.py","file_name":"interface_sort.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"11028934","text":"execfile('src/load.py', globals()) # don't remove this!\n\n#\n# This scripts provides an example of MIB rate analysis for \n# a list of LHC fills\n#\n# SV (viret@in2p3.fr) : 15/11/10 (creation) \n#\n# For more info, have a look at the CMS MIB webpage:\n# \n# http://sviret.web.cern.ch/sviret/Welcome.php?n=CMS.MIB\n#\n\n\n#\n# First give the number of the fills you want to analyze \n# \n# You could find info on the fill on the CMS WBM page:\n#\n# https://cmswbm.web.cern.ch/cmswbm/cmsdb/servlet/FillInfo?FILL=****\n#\n# where **** is the fill number\n\n\nfills = [2083,2085]\n\n\n#\n# Create the list of events to be analyzed, and read the ROOTuple information\n#\n#\n\na = Use(fills)\nb = ReadMIBSummary(processingDir='/afs/cern.ch/user/s/sviret/www/Images/CMS/MIB/Monitor/Rootuples/2011')\n\n# Launch the analysis\n\nprocessors = [a,b]\n\n\n#\n# Do some plots\n#\n\nfor i in range(5): \n processors.append(do_bit_trend_plot(bit=2,pixcut=i,doEps=True))\n processors.append(do_bit_trend_plot(bit=4,pixcut=i,doEps=True))\n processors.append(do_bit_trend_plot(bit=5,pixcut=i,doEps=True))\n\nprocessors.append(do_bunches_trend_plot())\nprocessors.append(do_prescale_trend_plot())\n\n# Add the html page production\nprocessors.append(do_trend_html())\n\n#\n# Go for it!!!\n#\n\nGo(processors)\n\n\n","sub_path":"ProcessData/share/Tucs/macros/MIB_trend_DQ.py","file_name":"MIB_trend_DQ.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"350511690","text":"\nimport sys\nimport gi\nfrom gi.repository import Gtk, GLib, Gio, Handy\nfrom .main_window import MainWindow\n\n\nclass Application(Gtk.Application):\n def __init__(self):\n super().__init__(application_id=\"de.falsei.ueb1news\",\n flags=Gio.ApplicationFlags.FLAGS_NONE)\n Handy.init()\n \n def do_startup(self):\n Gtk.Application.do_startup(self)\n GLib.set_application_name(\"News Agent\")\n GLib.set_prgname(\"News Agent\")\n\n def do_activate(self):\n window = self.props.active_window\n if not window:\n window = MainWindow(application=self)\n window.present()\n\n\ndef main(version):\n app = Application()\n return app.run(sys.argv)\n\n","sub_path":"ueb1/news_agent/src/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"519285751","text":"import time\ndef clusternodes(cluster_centers,r_matrix,min_preference,keys_array,output_type=\"all\"): # find nodes that are connected to the exemplar in the final responsibility matrix\n # construct the sparse array vectors\n # first column contains the exemplar id, all following columns contains the attached nodes.\n eps = 1/100000;\n #print('preference, eps:',preference,eps)\n #r_matrix = r_matrix.multiply(r_matrix > -(min_preference-eps)) # filter out fake zeros\n r_matrix = r_matrix.multiply(r_matrix < 0.)\n ClusterNodes = [] ; # [ {cluster_index1,[node_indices]},{cluster_index2,[node_indices]}...] \n num_exemplars = 0;\n if(output_type==\"all\"):\n for index in cluster_centers:\n # scan r_matrix(index,j) for all j in row, add j to set IF r_matrix(index,j) is non-zero, negative and < preference\n temp_csr = r_matrix.getrow(index);\n temp_csr_indices = temp_csr.indices # indptr indices\n #print(index,temp_csr_indices)\n #cluster_arr=[]\n #cluster_arr.append(int(keys_array.subscriber.values[keys_array.key.values==index][0])) # index\n row_sum = 0.\n exemplar_key = keys_array['subscriber'].get(index)\n if len(temp_csr_indices)>1: # minimum cluster size\n num_exemplars += 1\n for i in range(0,len(temp_csr_indices)): # temp_csr.nnz\n # index, temp_csr[i] forall i\n node_index = temp_csr_indices[i]\n #cluster_arr.append(int(keys_array.subscriber.values[keys_array.key.values==node_index][0]))\n cluster_node = keys_array['subscriber'].get(node_index)\n if(exemplar_key != cluster_node):\n ClusterNodes.append((exemplar_key,cluster_node))\n # map node keys to cluster key\n # row_sum += temp_csr[0,node_index]\n #cluster_arr.append(row_sum)\n #ClusterNodes.append(cluster_arr)\n # use Keys_arrays to map the cluster_centers values and r_matrix values to subscriber keys. \n elif(output_type==\"exemplars_count\"): # no filters..\n for index in cluster_centers:\n temp_csr = r_matrix.getrow(index);\n temp_csr_indices = temp_csr.indices # indptr indices\n row_sum = 0.\n exemplar_key = keys_array['subscriber'].get(index)\n if len(temp_csr_indices)>1: # minimum cluster size\n num_exemplars += 1\n ClusterNodes.append([exemplar_key,len(temp_csr_indices)-1]) \n return ClusterNodes, num_exemplars;","sub_path":"codes/graph_clustering/Affinity_propagation/Python/clusternodes_v2.py","file_name":"clusternodes_v2.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"387492203","text":"import numpy as np\r\n# import matplotlib\r\n# import matplotlib.pyplot as plt\r\nfrom SimWrapper.DataHandler import DataObject\r\nfrom SimWrapper.Enums import ControllerType\r\n\r\nclass Graph:\r\n import numpy as np\r\n\r\n # import matplotlib\r\n # import matplotlib.pyplot as plt\r\n def __init__(self,task,start_time = 0):\r\n self.task=task\r\n if task.controller.control_type == ControllerType.Impedance:\r\n prefix = 'Impedance_'\r\n self.isImpedance = True\r\n else:\r\n prefix = 'Regular_'\r\n self.isImpedance = False\r\n\r\n print(prefix)\r\n self.name_prefix = prefix\r\n self.start_time = start_time\r\n self.dt=self.task.simobj.model.opt.timestep\r\n self.contact_forces()\r\n self.position()\r\n\r\n def position(self):\r\n gripper_desired_pos = self.task.desired_pos\r\n gripper_pos = self.task.gripper_pos\r\n gripper_desired_imp_pos = self.task.desired_pos_imp\r\n if self.isImpedance:\r\n ex = (gripper_desired_imp_pos.x - gripper_pos.x)\r\n ey = (gripper_desired_imp_pos.y - gripper_pos.y)\r\n ez = (gripper_desired_imp_pos.z - gripper_pos.z)\r\n title = 'Position Error - Relative to Impedance'\r\n t = np.arange(0, len(ex) * self.dt, self.dt)\r\n self.plot3(t, ex, ey, ez, 'pos_error_imp', ttl=title, ylbl='Error [mm]')\r\n\r\n ex = (gripper_desired_pos.x - gripper_pos.x)\r\n ey = (gripper_desired_pos.y - gripper_pos.y)\r\n ez = (gripper_desired_pos.z - gripper_pos.z)\r\n title = 'Position Error - Relative to Desired Position'\r\n t = np.arange(0, len(ex) * self.dt, self.dt)\r\n self.plot3(t,ex,ey,ez, 'pos_error', ttl=title, ylbl='Error [mm]')\r\n\r\n\r\n def contact_forces(self):\r\n gripper_force = self.task.gripper_force\r\n fx = gripper_force.x\r\n fy = gripper_force.y\r\n fz = gripper_force.z\r\n t = np.arange(0, len(fx) * self.dt, self.dt)\r\n self.plot(t,fx,'contact_force_x', ttl='Contact Force - X Axis')\r\n self.plot(t,fy,'contact_force_y', ttl='Contact Force - Y Axis')\r\n self.plot(t,fz,'contact_force_z', ttl='Contact Force - Z Axis')\r\n\r\n\r\n def plot(self,x,y,name= [], ttl='', xlbl='Time [sec]', ylbl='Force [N]'):\r\n if len(name) == 0:\r\n name = np.random(1e3)\r\n fig, ax = plt.subplots()\r\n ax.plot(x,y)\r\n ax.grid()\r\n ax.set_xlim(self.start_time)\r\n ax.set_ylim(auto=True)\r\n ax.set(xlabel=xlbl, ylabel=ylbl)\r\n plt.title(ttl)\r\n fig.savefig(self.name_prefix+ name+'.png')\r\n\r\n def plot3(self,x,y1,y2,y3,name= [], ttl='', xlbl='Time [sec]', ylbl='Force [N]'):\r\n if len(name) == 0:\r\n name = np.random(1e3)\r\n fig, ax = plt.subplots()\r\n ax.plot(x,y1)\r\n ax.plot(x,y2)\r\n ax.plot(x,y3)\r\n plt.gca().legend(('X','Y','Z'))\r\n ax.grid()\r\n ax.set_xlim(self.start_time)\r\n ax.set_ylim(-50,50)\r\n ax.set(xlabel=xlbl, ylabel=ylbl)\r\n plt.title(ttl)\r\n fig.savefig(self.name_prefix+ name+'.png')","sub_path":"Projects_2020/Group_2/UR5 RTDE/SimWrapper/Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"425659122","text":"import sounddevice as sd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy import signal as sg\nimport soundfile as sf\nfrom scipy.fftpack import fft\n\n\ndef filter(signal, cutoff_hz, fs):\n nyq_rate = fs/2\n width = 5.0/nyq_rate\n ripple_db = 60.0 # dB\n N, beta = sg.kaiserord(ripple_db, width)\n taps = sg.firwin(N, cutoff_hz/nyq_rate, window=('kaiser', beta))\n\n return(sg.lfilter(taps, 1.0, signal))\n\n\ndef fourier(sinal, fs):\n N = len(sinal)\n T = 1/fs\n if T != 0:\n xf = np.linspace(0.0, 1.0/(2.0*T), N//2)\n yf = fft(sinal)\n return(xf, yf[0:N//2])\n else:\n return 0, 0\n\n\nfs = 44100\nduration = 6\ncutoff_hz = 3000\n\nprint(\"Favor digitar: 1- Ouvir 2- Arquivo \")\nmodo = int(input(\"\"))\n\nif modo == 1:\n # Ouvir audio\n audio = sd.rec(int(duration*fs), fs, channels=1)\n sd.wait()\n print(\"Estou ouvindo\")\n\n y = audio[:, 0]\nelse:\n y, rate1 = sf.read('som1.wav')\n print(\"Peguei arquivo\")\n\n# Fourrier audio recebido\nf, Y = fourier(y, fs)\nplt.plot(f, np.abs(Y), label='audio recebido')\nplt.show()\n\n# Portadora:\n\nfC1 = 5000\nfC2 = 15000\n\nt = np.linspace(0, len(y)/fs, len(y))\n\nc1 = np.sin(2*math.pi*fC1*t)\nc2 = np.sin(2*math.pi*fC2*t)\n\nm1L = y*c1\nf1, Y1 = fourier(m1L, fs)\nplt.plot(f1, np.abs(Y1), label='audio recebido')\n\nm2L = y*c2\nf2, Y2 = fourier(m2L, fs)\nplt.plot(f2, np.abs(Y2), label='audio recebido')\nplt.show()\n\nm1 = filter(m1L, cutoff_hz, fs)\nm2 = filter(m2L, cutoff_hz, fs)\n\n# Fourrier (m1F e m2F)\nm1f, m1y = fourier(m1, fs)\nplt.plot(m1f, np.abs(m1y), label='m1')\n\nm2f, m2y = fourier(m2, fs)\nplt.plot(m2f, np.abs(m2y), label='m2')\nplt.xlim(0, cutoff_hz)\nplt.show()\n\nsf.write('m1r.wav', m1, fs)\nsf.write('m2r.wav', m2*2, fs)\n","sub_path":"Projeto7/receptor.py","file_name":"receptor.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"2349784","text":"import torch.nn as nn\nimport torch\nimport torch.nn.functional as F\n\nfrom Layers import ReSentenceMatrixLayer, SentenceMatrixLayer\nfrom Model.G2E.attention import MultiHeadedAttention\nfrom Model.G2E.gcn.GraphConvolution import GraphConvolution\nfrom .Layer import Decoder, Encoder, InputLayers, PreLayers\n\n\nclass GraphState2eep(nn.Module):\n def __init__(self,vocab_len, in_size=300, g_out_size=300,l_h_size=300, out_size=1,\n dropout=0.3, bi=True,Ec_layer=2):\n super(GraphState2eep, self).__init__()\n self.ELayer_nums = Ec_layer\n self.embedding = nn.Embedding(vocab_len, in_size)\n self.dropout=nn.Dropout(dropout)\n self.lstm = nn.LSTM(in_size, in_size, num_layers=1, batch_first=True,bidirectional=bi)\n self.linear = nn.Linear(in_size*2,in_size*1)\n self.EncoderList = Encoder(in_size*2, g_out_size, in_size*2, dropout=dropout,num_layers=1,bidirectional=bi)\n self.PreLayer = PreLayers(in_size*4, l_h_size, out_size)\n self.gcn =GraphConvolution(in_size*1,in_size*2)\n\n def forward(self, x, adj, trigger, mask=None):\n x = self.embedding(x)\n # for i in range(self.ELayer_nums):\n # x, _ = self.EncoderList[i](x, adj)\n x,_= self.lstm(x)\n x = self.dropout(F.relu(self.linear(x)))\n x = self.gcn(x,adj)\n x,_ = self.EncoderList(x,adj)\n one_hot = F.one_hot(torch.arange(0, trigger.max() + 1), x.shape[1]).to(trigger.device)\n trigger = one_hot[trigger].unsqueeze(-1)\n trigger = trigger.expand(trigger.shape[0], trigger.shape[1], x.shape[-1]).bool()\n # print(\"----------trigger----------------\")\n # print(trigger)\n trigger_x = x.masked_select(trigger).reshape(x.shape[0], 1, x.shape[-1])\n # print(\"----------trigger_x----------------\")\n # print(trigger_x.shape)\n x = self.PreLayer(trigger_x)\n return x.squeeze()\n\n\nif __name__ == \"__main__\":\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n model = GraphState2eep(10).to(device)\n x = torch.rand(4, 5, 10).to(device)\n adj = torch.ones(4, 5, 5).to(device)\n trigger = torch.tensor([1, 2, 3, 4]).to(device)\n mask = torch.ones(4, 5).to(device)\n out = model(x, trigger, adj, mask)\n print(out.shape)\n","sub_path":"Model/G2E/GraphStateEEPemb.py","file_name":"GraphStateEEPemb.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"302886896","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'动态图'\n\n__author__ = '作者'\n\nfrom PIL import Image,ImageSequence\ngif_name = 'gif'\ngif = Image.open('%s.gif'%gif_name)\nfor i, frame in enumerate(ImageSequence.Iterator(gif), 1):\n\t# print(frame)\n frame.convert('RGB').save(\"./tmp/%s%d.jpg\" % (gif_name, i))\n\nimport imageio\nimport os\nframes = []\nfor x in os.listdir('./tmp'):\n\tif os.path.isfile(x) and os.path.splitext(x)[1] == '.jpg':\n\t\tprint(x)\n# print(os.listdir('./tmp'))\n# x for x in os.listdir('./tmp') if os.path.isfile(x) and os.path.splitext(x)[1] == '.jpg' and os.path.splitext(x)[0].index(gif_name) > -1\n# print(os.path.splitext('gif16.jpg')[0].index(gif_name))\n# for x in [x for x in os.listdir('./tmp') if os.path.isfile(x) and ((os.path.splitext(x)[0].index(gif_name) > -1) and os.path.splitext(x)[1] == '.jpg')]:\n# \tframes.append(imageio.imread('./tmp/%s'%x))\n# imageio.mimsave('gif/as_t.gif', frames, 'GIF', duration=0.5)\n","sub_path":"Python/gif/gif.py","file_name":"gif.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"80060544","text":"from . import Handler\nfrom shutil import rmtree\nfrom app import chpc\nfrom app.params import *\nimport re\nfrom numpy import random\nimport numpy\nfrom app import tweak\nimport logging\n\n\nclass MaxMin(Handler):\n TYPE_MIN = 'min'\n TYPE_MAX = 'max'\n\n TYPES = [TYPE_MAX, TYPE_MIN]\n\n def make(self, base=None):\n pass\n\n def submit(self):\n self.make_files()\n self.upload_files()\n self.submit_all_jobs()\n\n self.set_status(self.STATE_SUBMITTED)\n\n def abandon(self):\n self.sample.status = self.STATE_ERROR\n self.sample.has_done = 1\n\n def pull(self):\n logging.info('pulling...')\n jobs = self.fetch_jobs()\n\n if len(jobs) > 0:\n self.describe_jobs(jobs)\n raise self.StillRunning()\n else:\n finished = self.finished_jobs()\n logging.info('meep finished: [%s]' % ', '.join(finished))\n\n if len(finished) < 2:\n if self.sample.retried > 3:\n raise self.FatalError()\n else:\n logging.info('job was interrupted')\n raise self.Interrupted()\n\n def rate(self):\n logging.info('calling matlab')\n self.call_matlab()\n\n loss = {}\n for m_type in ['min', 'max']:\n loss[m_type] = self.fetch_matlab_result(m_type)\n\n if not self.calculate_rating(loss['max'], loss['min']):\n self.sample.status = self.STATE_ERROR\n self.sample.has_done = 1\n logging.info('error')\n else:\n self.sample.status = self.STATE_DONE\n self.sample.has_done = 1\n logging.info('done')\n\n def restart(self):\n logging.info('restarting job')\n finished = self.finished_jobs()\n self.make_files()\n self.upload_files()\n self.restart_failed_jobs(finished)\n\n def restart_failed_jobs(self, finished):\n for m_type in self.TYPES:\n if m_type not in finished:\n self.submit_job(m_type)\n\n self.sample.retried += 1\n\n def set_status(self, status):\n self.sample.status = status\n\n def make_files(self):\n self.make_meep_files()\n self.make_matlab_files()\n self.make_sbatch_files()\n\n def submit_all_jobs(self):\n self.submit_job(self.TYPE_MAX)\n self.submit_job(self.TYPE_MIN)\n\n def make_matlab_files(self):\n self.create_file('matlab.sh', self.template('matlab', {\n '__MATLAB_NAME__': self.config['matlab']\n }))\n self.create_file('xy.py', self.template('xy'))\n\n def make_sbatch_files(self):\n time_cost = self.config['time']\n\n for m_type in self.TYPES:\n content = self.template('sbatch', {\n '__NAME__': '%s-%s' % (self.sample.job_name, m_type),\n '__WORKDIR__': self.remote_sample_folder,\n '__ACCOUNT__': SBATCH_ACCOUNT,\n '__PARTITION__': SBATCH_PARTITION,\n '__MAX_MIN__': m_type,\n '__TIME__': time_cost\n })\n self.create_file('sbatch-%s.sh' % m_type, content)\n\n def make_meep_files(self):\n\n whole_width = self.config['width']\n whole_length = self.config['length']\n\n l_input = self.config['meep_linput']\n l_output = self.config['meep_loutput']\n\n for min_max in self.TYPES:\n header = self.template('meep-%s-header' % min_max, {\n '__PIXEL_LENGTH__': whole_length / 10,\n '__PIXEL_WIDTH__': whole_width / 10,\n '__GRAPH_LENGTH__': self.config['graphene_length'],\n '__RESOLUTION__': RESOLUTION,\n '__LAYOUT_LENGTH__': whole_length,\n '__LAYOUT_WIDTH__': whole_width,\n '__L_INPUT__': l_input,\n '__L_OUTPUT__': l_output,\n '__INPUT_WAVEGUIDE__': self.config['meep_input_waveguide']\n })\n points = []\n\n for part_name, part_points in self.sample.parts.items():\n part_cfg = self.config['parts'][part_name]\n layout = numpy.array(part_points).reshape((part_cfg['width']['size'], part_cfg['length']['size']))\n\n width_offset = part_cfg['width']['offset']\n length_offset = part_cfg['length']['offset']\n\n for r in range(0, len(layout)):\n row = layout[r]\n for c in range(0, len(row)):\n if int(row[c]) == 1:\n points.append(self.template('meep-point', {\n '__LENGTH_OFFSET__': c + 1 + length_offset,\n '__WIDTH_OFFSET__': r + 1 + width_offset,\n }))\n\n points = \"\\n\\n\".join(points)\n footer = self.template('meep-%s-footer' % min_max, {\n '__OUTPUT_WAVEGUIDE__': self.config['meep_output_waveguide'],\n '__EZ__': self.config['meep_ez']\n })\n content = header + points + footer\n self.create_file('meep-' + min_max + '.ctl', content)\n\n def run_matlab(self):\n chpc.remote_shell_file('/'.join([CHPC_WORK_DIR, self.sample.digest, 'matlab.sh']))\n\n def get_loss_value(self, m_type):\n file = '/'.join([CHPC_WORK_DIR, self.sample.digest, 'loss-%s.txt']) % m_type\n out = chpc.remote_cmd('cat %s' % file)\n matched = re.match(\"^\\d+\\.\\d+$\", out)\n if matched is not None:\n return float(matched.group(0))\n else:\n return None\n\n def restart_all(self):\n chpc.remote_cmd('rm -rf %s/%s/*.log' % (CHPC_WORK_DIR, self.sample.digest))\n\n def clean(self):\n rmtree(self.local_sample_folder)\n\n def clean_remote(self):\n chpc.remote_cmd('rm -rf %s/%s' % (CHPC_WORK_DIR, self.sample.digest))\n\n def call_matlab(self):\n chpc.remote_cmd('/bin/bash %s/matlab.sh' % self.remote_sample_folder)\n\n def fetch_all_matlab_results(self):\n losses = {}\n\n for m_type in self.TYPES:\n losses[m_type] = self.fetch_matlab_result(m_type)\n\n return losses\n\n def fetch_matlab_result(self, m_type):\n chpc.remote_cmd('/usr/bin/python %s/xy.py' % self.remote_sample_folder)\n\n out = chpc.remote_cmd('cat %s/loss-%s.txt' % (self.remote_sample_folder, m_type))\n out = str(out).strip()\n matched = re.match('.*\\s*(\\d+\\.\\d+)\\s*.*', out, re.MULTILINE)\n if matched is not None:\n return float(matched.group(1))\n else:\n return None\n\n def finished_jobs(self):\n finished = []\n for m_type in ['min', 'max']:\n if self.is_type_done(m_type):\n finished.append(m_type)\n\n return finished\n\n def is_type_done(self, m_type):\n output = chpc.remote_cmd('ls -l %s/meep-%s-out/hx-000200.00.h5' % (self.remote_sample_folder, m_type))\n if len(output) > 0:\n return 'No such file or directory' not in output\n else:\n return False\n\n def calculate_rating(self, loss_max, loss_min):\n if not loss_max or not loss_min:\n return False\n\n results = {\n 'loss_max': loss_max,\n 'loss_min': loss_min,\n 'depth': (loss_max - loss_min) / (loss_max + loss_min) * 100\n }\n\n loss_min_target = 0.05\n\n if loss_min < loss_min_target:\n g = 0\n else:\n g = ((loss_min_target - loss_min) / loss_min_target) ** 2\n\n self.sample.rating = round(((loss_max - loss_min) / loss_max) ** 2 - g, 5)\n\n self.sample.results = results\n\n return True\n\n def create_parts(self, parent):\n category_params = self.config\n\n new_parts = {}\n for part_name, part_cfg in category_params['parts'].items():\n tweak_module = getattr(tweak, category_params['parts'][part_name]['tweak'])\n tweak_method = getattr(tweak_module, 'tweak')\n\n if part_name in parent.parts:\n old_part = parent.parts[part_name]\n else:\n part_width = part_cfg['width']['size']\n part_length = part_cfg['length']['size']\n old_part = [random.randint(2) for _ in range(part_width * part_length)]\n\n new_parts[part_name] = tweak_method(old_part, part_cfg)\n\n return new_parts\n","sub_path":"app/handlers/maxmin.py","file_name":"maxmin.py","file_ext":"py","file_size_in_byte":8367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"598170651","text":"import socket\n\nHOST = \"www.google.com\"\nPORT = 80\nBUFFER_SIZE = 4096\n\npay_load = \"GET / HTTP/1.0\\r\\nHOST: www.google.com\\r\\n\\r\\n\"\n\ndef connect(address):\n try:\n new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n new_sock.connect(address)\n new_sock.sendall(pay_load.encode())\n new_sock.shutdown(socket.SHUT_WR)\n full_data = new_sock.recv(BUFFER_SIZE)\n print(full_data)\n except Exception as e:\n print(e)\n finally:\n new_sock.close()\n\ndef main():\n connect(('127.0.0.1', 8001))\n \nif __name__==\"__main__\":\n main()\n\n \n","sub_path":"proxy_client.py","file_name":"proxy_client.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"611961232","text":"\"\"\"\n Table 1: Relative contribution of each term in\n the energy budget of the Lamb-Chapygin\n dipole solution.\n\"\"\"\n\nimport h5py\nimport numpy as np\nfrom scipy import integrate\nimport matplotlib.pyplot as plt\n\nfrom astropy.io import ascii\n\nfrom Utils import *\n\nplt.close('all')\n\npathi = \"outputs/lambdipole/\"\npatho = \"../writeup/figs/\"\n\nparams = h5py.File(pathi+\"parameters.h5\",\"r\")\ndiags = h5py.File(pathi+\"diagnostics.h5\")\n\n## get params\nUe, ke = params['dimensional/Ue'][()], params['dimensional/ke'][()]\nTe = params['dimensional/Te'][()]\nUw = params['dimensional/Uw'][()]\n\n## get diagnostics\ntime = diags['time'][:]\nKE_qg = diags['ke_qg'][:]\nPE_niw = diags['pe_niw'][:]\nENS_qg = diags['ens'][:]\ng1 = diags['gamma_r'][:]\ng2 = diags['gamma_a'][:]\nx1 = diags['xi_r'][:]\nx2 = diags['xi_a'][:]\nep_psi = diags['ep_psi'][:]\nchi_phi = diags['chi_phi'][:]\n\n## calculate relative contribution\ni = g1.size\n\nKE, PE = KE_qg[i-1]-KE_qg[0], PE_niw[i-1]-PE_niw[0]\n\nG1, G2 = integrate.simps(y=g1[:i],x=time[:i]), integrate.simps(y=g2[:i],x=time[:i])\nX1 = -integrate.simps(y=x1[:i],x=time[:i])\nX2 = -integrate.simps(y=x2[:i],x=time[:i])\nG1_Pw, G2_Pw = G1/PE, G2/PE\nG1_Ke, G2_Ke, X1_Ke, X2_Ke = G1/KE, G2/KE, X1/KE, X2/KE\nG_Ke = G1_Ke+G2_Ke\nCHI_Pw = integrate.simps(y=chi_phi[:i],x=time[:i])/PE\nEP_Ke = -integrate.simps(y=ep_psi[:i],x=time[:i])/KE\n\nRES_PE = 1-(G1_Pw+G2_Pw+CHI_Pw)\nRES_KE = 1+(G1_Ke+G2_Ke+X1_Ke+X2_Ke+EP_Ke)\n\n## export LaTeX table\nLabels_Pw = np.array(['$\\Gamma_r$','$\\Gamma_a$','$-$','$-$','$\\chi_\\phi$','Res.'])\nLabels_Ke = np.array(['-$\\Gamma_r$','-$\\Gamma_a$','$\\Xi_r$','$\\Xi_a$','$\\epsilon_\\psi$','Res.'])\nfmt = 1e3\nPw_budget = np.round(np.array([G1_Pw, G2_Pw,np.nan, np.nan, CHI_Pw, RES_PE])*fmt)/fmt\nKe_budget = np.round(np.array([G1_Ke, G2_Ke, X1_Ke, X2_Ke, EP_Ke, RES_KE])*fmt)/fmt\n\ndata = np.concatenate([Labels_Pw[:,np.newaxis],Pw_budget[:,np.newaxis],\n Labels_Ke[:,np.newaxis], Ke_budget[:,np.newaxis]], axis=1)\n\ndata[2,1] = \"$-$\"\ndata[3,1] = \"$-$\"\n\nfno = \"../writeup/table1.tex\"\ncaption = \"The time-integrated budget of wave potential energy and quasigeostrophic\\\n kinetic energy of the Lamb-Chaplygin dipole expirement. \\label{table1}\"\nascii.write(data, output=fno, Writer=ascii.Latex, names=['$\\dot{P}_w$ budget',\n 'Rel. contribution ($\\int\\dot{P}_w \\dd t/\\Delta P_w dt$)','$\\dot{K}_e$ budget',\n 'Rel. contribution ($\\int\\dot{K}_e \\dd t/\\Delta K_e$)'],\n overwrite=True, caption=caption,\n latexdict={'preamble': r'\\begin{center}',\n 'tablefoot': r'\\end{center}',\n 'tabletype': 'table'})\n","sub_path":"code/Table1.py","file_name":"Table1.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"82846102","text":"from tensorflow.keras.layers import Layer\nfrom tensorflow.keras import backend as K\nimport tensorflow as tf\n\nimport numpy as np\n\n\nclass PriorBox(Layer):\n def __init__(self, s_min=None, s_max=None,\n feature_map_number=None, num_box=None, **kwargs):\n '''\n\n :param img_size:\n :param s_min:\n :param s_max:\n :param feature_map_number: [1, 2, 3, 4, 5, 6]\n '''\n\n self.default_boxes = []\n self.num_box = num_box\n if s_min <= 0:\n raise Exception('min_size must be positive')\n self.s_min = s_min\n self.s_max = s_max\n self.feature_map_number = feature_map_number\n self.aspect_ratio = [[1., 1 / 1, 2., 1 / 2],\n [1., 1 / 1, 2., 1 / 2],\n [1., 1 / 1, 2., 1 / 2, 3., 1 / 3],\n [1., 1 / 1, 2., 1 / 2, 3., 1 / 3],\n [1., 1 / 1, 2., 1 / 2, 3., 1 / 3],\n [1., 1 / 1, 2., 1 / 2]]\n\n super().__init__(**kwargs)\n\n def build(self, input_shape):\n self.batch_size = input_shape[0]\n self.width = input_shape[2]\n self.height = input_shape[1]\n\n self.s_k = self.get_sk(self.s_max, self.s_min, 6, self.feature_map_number)\n self.s_k1 = self.get_sk(self.s_max, self.s_min, 6, self.feature_map_number + 1)\n\n super(PriorBox, self).build(input_shape)\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[1] * input_shape[2], 4)\n\n @tf.function\n def call(self, x):\n feature_map_ratio = self.aspect_ratio[self.feature_map_number - 1]\n s = 0.0\n\n default_boxes = None\n for eleh in range(self.height):\n center_y = (eleh + 0.5) / float(self.height)\n for elew in range(self.width):\n center_x = (elew + 0.5) / float(self.width)\n for ratio in feature_map_ratio:\n s = self.s_k\n\n if (ratio == 1.0):\n s = np.sqrt(self.s_k * self.s_k1)\n\n box_width = s * np.sqrt(ratio)\n box_height = s / np.sqrt(ratio)\n\n if default_boxes is None:\n default_boxes = np.array([center_x, center_y, box_width, box_height]).reshape(-1, 4)\n else:\n default_boxes = np.concatenate(\n (default_boxes, np.array([[center_x, center_y, box_width, box_height]])), axis=0)\n\n boxes_tensor = np.expand_dims(default_boxes, axis=0)\n boxes_tensor = tf.tile(tf.constant(boxes_tensor, dtype='float32'), (tf.shape(x)[0], 1, 1))\n\n return boxes_tensor\n\n def get_sk(self, s_max, s_min, m, k):\n '''\n :param s_max:\n :param s_min:\n :param m: number of feature map\n :param k: k-th feature map\n :return:\n '''\n sk_value = s_min + ((s_max - s_min) / (m - 1.0)) * (k - 1)\n\n return sk_value","sub_path":"Object Detection/SSD/utils/PriorBox.py","file_name":"PriorBox.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"33442831","text":"N = int(input())\nnums = list(map(int, input().split()))\n\nBASIS_LENGTH = 32\n\n\ndef reduce(num):\n total = 0\n power = 0\n for i in range(BASIS_LENGTH):\n if bad & (1 << i): continue\n total += ((num & (1 << i)) >> i) * pow(2, power)\n power += 1\n return total\n \ndef expand(num):\n total = 0\n power = 0\n for i in range(BASIS_LENGTH):\n if bad & (1 << i):\n continue\n total += ((num & (1 << power)) >> power) * pow(2, i)\n power += 1\n return total\n\nBASIS = [0 for i in range(BASIS_LENGTH)]\nnumsPrime = [reduce(n) for n in nums]\n\n\ndef insertVector(x):\n for i in range(BASIS_LENGTH -1, -1, -1):\n if x & (1 << i) == 0: continue\n if BASIS[i] == 0: BASIS[i] = x; return\n x ^= BASIS[i]\n \nfor x in numsPrime:\n insertVector(x)\n\ndef getSum():\n total = 0\n for el in reversed(BASIS):\n if el == 0: continue\n if el ^ total > total:\n total = el ^ total\n return total\n\nprint(2*expand(getSum()) + bad)\n","sub_path":"AtCoder/Beginner 155/F.py","file_name":"F.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"409207645","text":"\"\"\"\nCode to apply non-linearity correction.\n\"\"\"\nfrom __future__ import print_function\n\nimport copy\n\nimport numpy as np\n\nimport scipy.optimize\nfrom scipy.interpolate import UnivariateSpline\n\nimport astropy.io.fits as fits\n\nfrom lsst.eotest.fitsTools import fitsTableFactory, fitsWriteto\n\n\ndef lin_func(pars, xvals):\n \"\"\"Return a line whose slope is pars[0]\"\"\"\n return pars[0]*xvals\n\ndef chi2_model(pars, xvals, yvals):\n \"\"\"Return the chi2 w.r.t. the model\"\"\"\n return (yvals - lin_func(pars, xvals))/np.sqrt(yvals)\n\ndef make_profile_hist(xbin_edges, xdata, ydata, **kwargs):\n \"\"\"Build a profile historgram\n\n Parameters\n ----------\n xbin_edges : `array`\n The bin edges\n xdata : `array`\n The x-axis data\n ydata : `array`\n The y-axis data\n\n Keywords\n --------\n yerrs : `array`\n The errors on the y-axis points\n\n stderr : `bool`\n Set error bars to standard error instead of RMS\n\n Returns\n -------\n x_vals : `array`\n The x-bin centers\n y_vals : `array`\n The y-bin values\n y_errs : `array`\n The y-bin errors\n \"\"\"\n yerrs = kwargs.get('yerrs', None)\n stderr = kwargs.get('stderr', False)\n\n nx = len(xbin_edges) - 1\n x_vals = (xbin_edges[0:-1] + xbin_edges[1:])/2.\n y_vals = np.ndarray((nx))\n y_errs = np.ndarray((nx))\n\n if yerrs is None:\n weights = np.ones(ydata.shape)\n else:\n weights = 1./(yerrs*yerrs)\n\n y_w = ydata*weights\n\n for i, (xmin, xmax) in enumerate(zip(xbin_edges[0:-1], xbin_edges[1:])):\n mask = (xdata >= xmin) * (xdata < xmax)\n if mask.sum() < 2:\n y_vals[i] = 0.\n y_errs[i] = -1.\n continue\n y_vals[i] = y_w[mask].sum() / weights[mask].sum()\n y_errs[i] = ydata[mask].std()\n if stderr:\n y_errs[i] /= np.sqrt(mask.sum())\n\n return x_vals, y_vals, y_errs\n\n\nclass NonlinearityCorrection:\n \"\"\"Apply a non-linearity correction\n\n The point of this calls is to serve as a callable object that will\n linearize bias-subtracted data\n\n corrected_adu = nlc(amp, uncorrected_adu)\n\n This is implemented as a spline interpolation for each of the 16 amplifiers on a CCD\n \"\"\"\n def __init__(self, prof_x, prof_y, prof_yerr, **kwargs):\n \"\"\"C'tor\n\n Parameters\n ----------\n prof_x : `array`\n Array of 16 x nbins values for the x-axis of the correction function\n prof_y : `array`\n Array of 16 x nbins values for the y-axis of the correction function\n prof_yerr : `array`\n Array of 16 x nbins values for the y-axis of the correction function\n \"\"\"\n self._prof_x = prof_x\n self._prof_y = prof_y\n self._prof_yerr = prof_yerr\n self._nxbins = self._prof_x.shape[1]\n\n self._spline_dict = {}\n for iamp in range(16):\n idx_sort = np.argsort(self._prof_x[iamp])\n profile_x = self._prof_x[iamp][idx_sort]\n profile_y = self._prof_y[iamp][idx_sort]\n if self._prof_yerr is not None:\n profile_yerr = self._prof_yerr[iamp][idx_sort]\n mask = profile_yerr >= 0.\n else:\n mask = np.ones(profile_x.shape)\n self._spline_dict[iamp] = UnivariateSpline(profile_x[mask], profile_y[mask])\n\n def __getitem__(self, amp):\n \"\"\"Get the function that corrects a particular amp\"\"\"\n return self._spline_dict[amp]\n\n def __call__(self, amp, adu):\n \"\"\"Apply the non-linearity correction to a particular amp\"\"\"\n return adu*(1 + self._spline_dict[amp-1](adu))\n\n\n def write_to_fits(self, fits_file):\n \"\"\"Write this object to a FITS file\"\"\"\n output = fits.HDUList()\n output.append(fits.PrimaryHDU())\n\n col_prof_x = fits.Column(name='prof_x', format='%iE' % self._nxbins,\n unit='ADU', array=self._prof_x)\n col_prof_y = fits.Column(name='prof_y_corr', format='%iE' % self._nxbins,\n unit='ADU', array=self._prof_y)\n col_prof_yerr = fits.Column(name='prof_yerr', format='%iE' % self._nxbins,\n unit='ADU', array=self._prof_yerr)\n\n fits_cols = [col_prof_x, col_prof_y, col_prof_yerr]\n hdu = fitsTableFactory(fits_cols)\n hdu.name = 'nonlin'\n output.append(hdu)\n\n fitsWriteto(output, fits_file, overwrite=True)\n\n\n def save_plots(self, plotfile, **kwargs):\n \"\"\"Save plots showing the nonlinearity correction\"\"\"\n import matplotlib.pyplot as plt\n ymin = kwargs.get('ymin', None)\n ymax = kwargs.get('ymax', None)\n\n figsize = kwargs.get('figsize', (15, 10))\n\n fig, axs = plt.subplots(nrows=4, ncols=4, figsize=figsize)\n fig.suptitle(\"Nonlinearity\")\n\n xlabel = r'Mean [ADU]'\n ylabel = r'Frac Resid [$(q - g\\mu)/g\\mu$]'\n for i_row in range(4):\n ax_row = axs[i_row, 0]\n ax_row.set_ylabel(ylabel)\n\n for i_col in range(4):\n ax_col = axs[3, i_col]\n ax_col.set_xlabel(xlabel)\n\n iamp = 0\n for i_row in range(4):\n for i_col in range(4):\n axes = axs[i_row, i_col]\n if ymin is not None or ymax is not None:\n axes.set_ylim(ymin, ymax)\n mask = self._prof_yerr[iamp] >= 0.\n x_masked = self._prof_x[iamp][mask]\n xline = np.linspace(1., x_masked.max(), 1001)\n model = self._spline_dict[iamp](xline)\n axes.errorbar(x_masked, self._prof_y[iamp][mask],\n yerr=self._prof_yerr[iamp][mask], fmt='.')\n axes.plot(xline, model, 'r-')\n iamp += 1\n if plotfile is None:\n fig.show()\n else:\n fig.savefig(plotfile)\n\n\n @classmethod\n def create_from_table(cls, table):\n \"\"\"Create a NonlinearityCorrection object from a fits file\n\n Parameters\n ----------\n table : `Table`\n The table data used to build the nonlinearity correction\n\n Returns\n -------\n nl : `NonlinearityCorrection`\n The requested object\n \"\"\"\n prof_x = table.data['prof_x']\n prof_y = table.data['prof_y_corr']\n prof_yerr = table.data['prof_yerr']\n return cls(prof_x, prof_y, prof_yerr)\n\n @classmethod\n def create_from_fits_file(cls, fits_file, hdu_name='nonlin'):\n \"\"\"Create a NonlinearityCorrection object from a fits file\n\n Parameters\n ----------\n fits_file : `str`\n The file with the data used to build the nonlinearity correction\n\n hdu_name : `str`\n The name of the HDU with the nonlinearity correction data\n\n Returns\n -------\n nl : `NonlinearityCorrection`\n The requested object\n \"\"\"\n hdulist = fits.open(fits_file)\n table = hdulist[hdu_name]\n nl = cls.create_from_table(table)\n hdulist.close()\n return nl\n\n\n @staticmethod\n def _correct_null_point(profile_x, profile_y, profile_yerr, null_point):\n \"\"\"Force the spline to go through zero at a particular x-xvalue\n\n Parameters\n ----------\n profile_x : `array`\n The x-bin centers\n profile_y : `array`\n The b-bin values\n profile_yerr : `array`\n The y-bin errors\n null_point : `float`\n The x-value where the spline should go through zero \n\n Returns\n -------\n y_vals_corr\n The adjusted y-values\n y_errs_corr\n The adjusted y-errors\n \"\"\"\n uni_spline = UnivariateSpline(profile_x, profile_y)\n offset = uni_spline(null_point)\n\n y_vals_corr = ((1 + profile_y) / (1 + offset)) - 1.\n y_errs_corr = profile_yerr\n return y_vals_corr, y_errs_corr\n\n @classmethod\n def create_from_det_response(cls, detresp, gains, **kwargs):\n \"\"\"Create a NonlinearityCorrection object DetectorResponse FITS file\n\n Note that the DetectorResponse files typically store the signal in electrons,\n but we want a correction that works on ADU, so we have to remove the gains.\n\n Parameters\n ----------\n detresp : `DetectorResponse`\n An object with the detector response calculated from flat-pair files\n\n gains : `array` or `None`\n Array with amplifier by amplifer gains\n\n\n Keywords\n --------\n fit_range : `tuple`\n The range over which to define the non-linearity, defaults to (0., 9e4)\n\n nprofile_bins : `int` or `None`\n The number of bins to use in the profile, defaults to 10\n If `None` then this will use all of the data point rather that making\n a profile histogram\n\n null_point : `float` or `None`\n X-value at which the correction should vanish, defaults to 0.\n If `None` then this will simply use the pivot point of the fit to the data \n\n Returns\n -------\n nl : `NonlinearityCorrection`\n The requested object\n \"\"\"\n fit_range = kwargs.get('fit_range', (0., 9e4))\n nprofile_bins = kwargs.get('nprofile_bins', 10)\n null_point = kwargs.get('null_point', 0,)\n\n if nprofile_bins is not None:\n xbins = np.linspace(fit_range[0], fit_range[1], nprofile_bins+1)\n else:\n xbins = None\n nprofile_bins = len(detresp.flux)\n\n prof_x = np.ndarray((16, nprofile_bins))\n prof_y = np.ndarray((16, nprofile_bins))\n prof_yerr = np.ndarray((16, nprofile_bins))\n\n for idx, amp in enumerate(detresp.Ne):\n xdata = copy.copy(detresp.Ne[amp])\n if gains is not None:\n xdata /= gains[idx]\n mask = (fit_range[0] < xdata) * (fit_range[1] > xdata)\n xdata_fit = xdata[mask]\n ydata_fit = detresp.flux[mask]\n mean_slope = (ydata_fit/xdata_fit).mean()\n pars = (mean_slope,)\n results = scipy.optimize.leastsq(chi2_model, pars,\n full_output=1,\n args=(xdata_fit, ydata_fit))\n model_yvals = lin_func(results[0], xdata)\n frac_resid = (detresp.flux - model_yvals)/model_yvals\n frac_resid_err = 1./xdata\n\n if xbins is not None:\n prof_x[idx], prof_y[idx], prof_yerr[idx] = make_profile_hist(xbins, xdata, frac_resid,\n y_errs=frac_resid_err,\n stderr=True)\n else:\n prof_x[idx], prof_y[idx], prof_yerr[idx] = xdata, frac_resid, frac_resid_err\n\n if null_point is not None:\n prof_y[idx], prof_yerr[idx] = cls._correct_null_point(prof_x[idx], prof_y[idx], prof_yerr[idx], null_point) \n\n return cls(prof_x, prof_y, prof_yerr)\n","sub_path":"python/lsst/eotest/sensor/NonlinearityCorrection.py","file_name":"NonlinearityCorrection.py","file_ext":"py","file_size_in_byte":11180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"235659634","text":"import numpy as np\n\n# Check MMSE\ndef MMSE(f,P):\n py = np.ravel(P.sum(axis=0))\n f2 = np.reshape(f,(len(f),1))\n Pxgy = P.dot(np.diag(py**(-1)))\n Efxgy = f2.transpose().dot(Pxgy)\n error = np.tile(f2,(1,P.shape[1]))-np.tile(Efxgy,(P.shape[0],1))\n error = error**2\n mmse = error*P\n return mmse.sum()","sub_path":"Adult/PICmmse.py","file_name":"PICmmse.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"93531511","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport time\nimport tornado\n\n\nclass AsyncMixin(object):\n\n def apply(self, method, *args, **kwargs):\n res = method.delay(*args, **kwargs)\n self.wait_for_result(res, self.reply)\n\n def wait_for_result(self, res, callback, t=10):\n if t > 0:\n if res.ready():\n callback(res.result)\n else:\n tornado.ioloop.IOLoop.instance().add_timeout(time.time() + 0.1,\n lambda: self.wait_for_result(res, callback, t - 0.1))\n else:\n callback(None)\n\n def reply(self, result):\n raise NotImplemented\n","sub_path":"tc/mixin.py","file_name":"mixin.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"470585824","text":"# vim: ts=2:sw=2:tw=80:nowrap\n\nfrom gi.repository import Gtk as gtk\nfrom numpy.random import rand\n\nvar0 = 0.4\nvar1 = 30\nvar2 = dict( a = 100, b = 2000 )\n\nnan = float('nan')\n\nclass func:\n def __init__(self, avg=False, Nextra=8):\n self.avg = avg\n self.ne = Nextra\n\n def onstart(self):\n print('nothing to get ready for!')\n\n def onstop(self):\n print('nothing to clean up!')\n\n def run(self):\n global var0, var1, var2\n xx = var0 * 100\n yy = var1 * 1\n zz0 = var2['a'] * 0.01\n zz1 = var2['b'] * 0.0001\n #f = ( sin((xx/40. + (yy/30.)**2))**2.0) * 100.0\n f = xx**2 + abs(yy-100) * abs(yy+100) + abs(zz0-100) + (zz1+50)**2\n R = list(rand(self.ne))\n if self.avg:\n #return average([ f for i in range(10) ])\n return [average([ poisson( f ) for i in range(10) ])] + R\n else:\n return [f] + R\n\n def extra_data_labels(self):\n return ['rand'] * self.ne\n\n\ndef get_globals():\n return globals()\n\nimport traceback, pprint\nfrom ..executor import Make\n\nmain_settings = dict()\n\ndef main():\n win = gtk.Window()\n e = Make(win, 'func', main_settings)( func(), globals() )\n\n print('e: ', e)\n return e\n try:\n while e(): pass\n except: traceback.print_exc()\n if e.results:\n print('cache length: ', len(e.results))\n print('skipped evals: ', e.skipped_evals)\n #print('results: ')\n #pprint.pprint( e.results )\n","sub_path":"python/arbwave/processor/executor/optimize/tests/manual_executor_test.py","file_name":"manual_executor_test.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"577575561","text":"#!/usr/bin/env python\n\nfrom os.path import join, dirname\n\n\ndef main():\n try:\n from robot.libdoc import libdoc\n except Exception as ex:\n err_msg = \"Robot Framework 2.7 or later required for generating documentation\"\n raise RuntimeError(err_msg) from ex\n\n libdoc(join(dirname(__file__), '..', 'src', 'BrowserMobProxyLibrary'),\n join(dirname(__file__), 'BrowserMobProxyLibrary.html'))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"doc/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"196036463","text":"import cherrypy\nimport subprocess\nimport os, time\nfrom library import doMurfi, endMurfi, doServ, endServ, doStim, doStimPlacebo, makeSession, HOME, SUBJS,makeFakeData,createSubDir,testDisplay, testTrigger,testButton,testBirdSounds,testLetterSounds, testInfoClient_Start, RTSCRIPTSDIR\nimport getpass\nfrom psychopy import data\nclass HelloWorld:\n def __init__(self):\n self.run = '1'\n self.history = \"
  • logged in
\"\n \n def index(self):\n with open(os.path.join(HOME,'index.html')) as fp:\n msg = fp.readlines()\n login = \"\"\"\n
\n
\n\n

Subject:\n

\n

Visit #:\n

\n

\n

\n
\n
\n\"\"\"\n msg+= login\n with open(os.path.join(HOME,'footer.html')) as fp:\n foot = fp.readlines()\n return msg+foot ###end: def index()\n index.exposed = True\n\n def doLogin(self,subject=None,visit=None):\n self.subject = subject\n self.visit = visit\n date = data.getDateStr()[:-5]\n with open(os.path.join(HOME,'index.html')) as fp:\n msg = fp.readlines()\n with open(os.path.join(HOME,'historybar.html')) as fp:\n hist = fp.readlines()\n msg += hist \n ## if no subject/sessiondir exists, create it - also if the mask and study ref exist lets make fakedata\n if not os.path.exists(os.path.join(SUBJS,subject)):\n self.history = createSubDir(subject) + self.history\n if os.path.exists(os.path.join(SUBJS,subject,'mask','%s_roi.nii'%subject)) \\\n and os.path.exists(os.path.join(SUBJS,subject,'xfm','%s_study_ref.nii'%subject))\\\n and not os.path.exists(os.path.join(SUBJS,subject,'run1.nii')):\n pass\n #self.history = makeFakeData(subject) +self.history\n if not os.path.exists(os.path.join(SUBJS,\"%s/session%s/\"%(subject,visit))):\n history = makeSession(subject,visit) # returns history\n self.history = history + self.history\n msg += self.history\n msg += \"\"\"\"\"\"\n subject_info = \"\"\"\n
\n

\n
Subject: %s \n
Visit #: %s \n

\n

\n\n

\n\n

Run #:\n

\n

Tests:\n

\n
\n
\n
\n
\n
\n
\n
\n

\n

Murfi:\n

\n

\n

Fake Data:\n

\n

\n

Stimulus:\n

\n

\n\n

\n\n
\n\n

\n \n

\n\n\n\n\n\"\"\" % (subject, visit, self.run,subject,visit,subject,date,int(self.run),subject,visit,subject,date,int(self.run))\n msg += subject_info\n with open(os.path.join(HOME,'footer.html')) as fp:\n foot = fp.readlines()\n return msg+foot ### end: def doLogin()\n\n doLogin.exposed=True\n\n def formHandler(self,run=None,button=None):\n self.run = run # run number\n if button==\"Start Murfi\":\n return self.doMurfi(run)\n if button==\"End Murfi\":\n return self.endMurfi(run)\n if button==\"Serve\":\n return self.doServ(run)\n if button==\"End Serve\":\n return self.endServ(run)\n if button==\"Stimulus\":\n return self.doStim(run)\n if button==\"Placebo Stimulus\":\n return self.doStimPlacebo(run)\n if button==\"Test Display\":\n history = testDisplay()\n self.history = history + self.history\n return self.doLogin(self.subject,self.visit)\n if button==\"Test Buttons\":\n history = testButton()\n self.history = history + self.history\n return self.doLogin(self.subject,self.visit)\n if button==\"Test Bird Sounds\":\n history = testBirdSounds()\n self.history = history + self.history\n return self.doLogin(self.subject,self.visit)\n if button==\"Test Letter Sounds\":\n history = testLetterSounds()\n self.history = history + self.history\n return self.doLogin(self.subject,self.visit)\n if button==\"Test Scanner Trigger\":\n history = testTrigger()\n self.history = history + self.history\n return self.doLogin(self.subject,self.visit)\n if button==\"Start InfoClient Test\":\n history = \"
  • Started info client, please serve fakedata
\"\n self.history = history + self.history\n self.rt = testInfoClient_Start()\n return self.doLogin(self.subject,self.visit) \n if button==\"Check InfoClient\":\n log = open(\"/home/%s/Desktop/infoClientTest.txt\"%getpass.getuser(),'w') \n self.rt.check()\n log.write(str(self.rt.xml))\n log.close()\n self.history = \"
  • checked infoclient
\" + self.history\n return self.doLogin(self.subject,self.visit)\n if button==\"End InfoClient\":\n self.rt.close()\n return self.doLogin(self.subject,self.visit)\n \n ### end: def formHandler()\n\n formHandler.exposed=True\n\n def doMurfi(self,run=None):\n ###### subprocess stdout/stderr is redirected to useful log files:\n ## self.logbase is set in doMurfi because doMurfi is the first step of every run\n ## -- it includes a timestamp to allow multiple runs and to avoid overwriting.\n ## -- thanks to logbase, servOUT's filename base matches murfOUT's. \n ## self.murfOUT & self.servOUT (in doServ()) are open filehandles to that run's log files\n ## -- close them in endMurfi/endServ.\n\n self.logbase = os.path.join(SUBJS, self.subject, \"session%s\"%self.visit, run + time.strftime(\"_%b%d_%H%M%S_\")) # make new stdout/stderr base\n self.murfOUT = open(self.logbase+\"murfi.log\", 'w') # stdout/stderr go to this file\n\n proc, history = doMurfi(self.subject,self.visit,run,self.murfOUT)\n self.murfi_subprocess = proc\n self.history = history + self.history\n return self.doLogin(self.subject,self.visit)\n \n doMurfi.exposed=True\n\n def endMurfi(self,run=None):\n history = endMurfi(self.murfi_subprocess,self.subject,self.visit,run,self.murfOUT)\n self.history = history + self.history\n return self.doLogin(self.subject,self.visit)\n\n endMurfi.exposed=True\n\n def doServ(self,run=None):\n self.servOUT = open(self.logbase+\"servenii4d.log\", 'w') # stdout/stderr go to this file\n proc, history = doServ(self.subject,self.visit,run,self.servOUT)\n self.serv_subprocess = proc\n self.history = history + self.history \n return self.doLogin(self.subject,self.visit)\n\n doServ.exposed=True \n \n def endServ(self,run=None):\n history = endServ(self.serv_subprocess,self.subject,self.visit,run,self.servOUT)\n self.history = history + self.history\n return self.doLogin(self.subject,self.visit)\n\n endServ.exposed=True\n\n def doStim(self,run=None):\n proc, history = doStim(self.subject,self.visit,run)\n self.history = history + self.history \n return self.doLogin(self.subject,self.visit)\n \n doStim.exposed=True\n\n def doStimPlacebo(self,run=None):\n proc, history = doStimPlacebo(self.subject,self.visit,run)\n self.history = history + self.history \n return self.doLogin(self.subject,self.visit)\n \n doStimPlacebo.exposed=True\n\n\nif __name__ == \"__main__\":\n if (os.getlogin() == 'ss'): ### sasen will use different port\n cherrypy.config.update({'server.socket_host': '18.93.5.27',\n 'server.socket_port': 8090\n })\n config = {'/': {'tools.staticdir.on': True,\n 'tools.staticdir.dir': os.getcwd()},\n '/css': {'tools.staticdir.on': True,\n 'tools.staticdir.dir': os.path.abspath('css/')},\n '/flot': {'tools.staticdir.on': True,\n 'tools.staticdir.dir': os.path.abspath('../flot')},\n '/subjects': {'tools.staticdir.on': True,\n 'tools.staticdir.dir': '/home/%s/subjects'%getpass.getuser()},\n }\n cherrypy.tree.mount(HelloWorld(),'/',config=config)\n cherrypy.engine.start()\n cherrypy.engine.block()\n\n","sub_path":"scripts/cherrypy/cherry.py","file_name":"cherry.py","file_ext":"py","file_size_in_byte":12938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"257012238","text":"# -*- coding: UTF-8 -*-\nimport sys\nimport getopt\nimport logging\nfrom insstar.crawler import insstar_crawler\n\nCONF_FILE = ''\nLOG_FORMAT = '%(levelname)s %(asctime)s %(filename)s %(funcName)s : %(message)s'\n\n\ndef set_log_level(level):\n llevel = logging.INFO if not level else getattr(logging, level.upper())\n logging.basicConfig(format=LOG_FORMAT, level=llevel)\n print(\"log init finished, level:\", level.upper())\n\n\ndef usage():\n \"\"\"\n 使用说明函数\n \"\"\"\n print('Usage:', sys.argv[0], '-c conf_file')\n sys.exit(1)\n\n\ndef parse_command_line() -> CONF_FILE:\n if len(sys.argv) < 3:\n usage()\n ret = ''\n opts, args = getopt.getopt(sys.argv[1:], \"c:\", [])\n for option, value in opts:\n if option == \"-c\":\n ret = value\n return ret\n\n\nif __name__ == '__main__':\n set_log_level(\"debug\")\n insstar_crawler()\n","sub_path":"spider/ImageCrawler/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"368055781","text":"# -*- encoding: utf-8 -*-\n# @File: Singleton.py \n# @Time: 2020-05-22 10:03\n# @Author: ZHANG\n# @Description: Singleton\n\"\"\"\n2.\n单例模式,核心结构中只包含一个被称为单例类的特殊类,类的对象只能存在一个\n三个要点: 某个类只有一个实例; 必须自行创建这个实例; 必须自行向整个系统提供这个实例\n\"\"\"\n\n\nclass Singleton1(object):\n \"\"\"类变量\"\"\"\n\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, '_instance'):\n orig = super(Singleton1, cls)\n cls._instance = orig.__new__(cls)\n return cls._instance\n\n\nclass Myclass(Singleton1):\n a = 1\n\n\none = Myclass()\ntwo = Myclass()\n\nprint(id(one))\nprint(id(two))\nprint(one == two)\nprint(one is two)\n\ntwo.a = 3\nprint(one.a)\n\n\nclass Borg(object):\n \"\"\"共享属性\"\"\"\n _state = {}\n\n def __new__(cls, *args, **kwargs):\n ob = super(Borg, cls).__new__(cls)\n ob.__dict__ = cls._state\n return ob\n\n\nclass Myclass2(Borg):\n a = 1\n\n\nprint(\"=================\")\none = Myclass2()\ntwo = Myclass2()\ntwo.a = 3\nprint(one.a)\nprint(id(one))\nprint(id(two))\nprint(one == two)\nprint(one is two)\nprint(id(one.__dict__))\nprint(id(two.__dict__))\n\n\ndef singleton(cls, *args, **kwargs):\n \"\"\"装饰器\"\"\"\n instances = {}\n\n def getinstance():\n if cls not in instances:\n instances[cls] = cls(*args, **kwargs)\n return instances[cls]\n\n return getinstance\n\n\n@singleton\nclass Myclass3(object):\n a = 1\n\n def __init__(self, x=0):\n self.x = x\n\n\nprint(\"================\")\none = Myclass3()\ntwo = Myclass3()\ntwo.a = 3\nprint(one.a)\nprint(id(one))\nprint(id(two))\nprint(one == two)\nprint(one is two)\none.x = 1\nprint(one.x)\nprint(two.x)\n\n\nfrom target_offer.mysingleton import my_singleton\n\"\"\"import 方法\"\"\"\nmy_singleton.foo()\n","sub_path":"target_offer/Singleton.py","file_name":"Singleton.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"239027840","text":"#!/usr/bin/env python\nimport argparse\nimport re\nimport os\nimport shutil\nimport subprocess\n\nargs = None\ndescr = \"\"\"Setup an opam install\"\"\"\n\nlocal_regex = re.compile(\"src:\\s*\\\"local\")\n\ndef parse_arguments():\n global args\n parser = argparse.ArgumentParser(\n description=descr,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n '--srcdir', dest=\"srcdir\", metavar='S',\n action=\"store\", \n help='directory of the opam repository')\n parser.add_argument(\n '--installdir', dest=\"installdir\", metavar='S',\n action=\"store\", \n help='directory where opam and ocaml will be installed')\n args = parser.parse_args()\n\ndef copy_packages():\n \"\"\"create the packages subdir from the one that need for our platform\"\"\"\n if os.path.exists(\"packages\"):\n shutil.rmtree(\"packages\")\n shutil.copytree(\"x86_64-linux\", \"packages\")\n\ndef replace_urls():\n \"\"\"replace local links to point to current repos\"\"\"\n matches = []\n for root, dirnames, filenames in os.walk('packages'):\n for filename in filenames:\n if filename.endswith(\"opam\"):\n matches.append(os.path.join(root, filename))\n for fn in matches:\n with open(fn, 'r') as f:\n text = f.read()\n text = local_regex.sub(\"src: \\\"\" + args.srcdir , text)\n with open(fn, 'w') as f:\n f.write(text)\n\ndef clean():\n if os.path.exists(args.installdir):\n shutil.rmtree(args.installdir)\n\ndef copy_opam():\n os.mkdir(args.installdir)\n os.mkdir(os.path.join(args.installdir, 'bin'))\n shutil.copyfile(os.path.join(args.srcdir, 'src', 'opam-2.0.3-x86_64-linux'),\n os.path.join(args.installdir, 'bin', 'opam'))\n\ndef opam_init():\n subprocess.call(['opam', 'init', '--bare', '--bypass-checks', '-n', '-y', args.srcdir])\n\ndef opam_switch(arg):\n subprocess.call(['opam', 'switch', 'create', '-y', arg])\n\ndef opam_install(arg):\n subprocess.call(['opam', 'install', '-y', arg])\n\ndef opam_install_deps(arg):\n subprocess.call(['opam', 'install', '-y', '--deps-only', arg])\n\ndef main():\n parse_arguments()\n clean()\n copy_opam()\n os.environ['PATH'] = os.pathsep.join([os.path.join(args.installdir, 'bin'),\n os.environ['PATH']])\n os.environ['OPAMROOT'] = args.installdir\n copy_packages()\n replace_urls()\n opam_init()\n opam_switch('ocaml-system.4.07.1')\n\n opam_install_deps('infer')\n opam_install_deps('alt-ergo')\n opam_install_deps('why3')\n\n\n\nmain()\n","sub_path":"adacore_setup.py","file_name":"adacore_setup.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"189623862","text":"__license__ = 'MIT License '\n__author__ = 'Lucas Theis '\n__docformat__ = 'epytext'\n\nfrom django.contrib import admin\nfrom publications.models import CustomLink, CustomFile, Publication\nfrom publications.admin.forms import PublicationAdminForm\n\nclass CustomLinkInline(admin.StackedInline):\n model = CustomLink\n extra = 1\n max_num = 5\n\n\nclass CustomFileInline(admin.StackedInline):\n model = CustomFile\n extra = 1\n max_num = 5\n\n\nclass PublicationAdmin(admin.ModelAdmin):\n list_display = ('type', 'citekey', 'first_author', 'title', 'type', 'year', 'journal_or_book_title')\n list_display_links = ('title',)\n change_list_template = 'admin/publications/change_list.html'\n search_fields = ('title', 'journal', 'authors', 'keywords', 'year')\n inlines = [CustomLinkInline, CustomFileInline]\n\n def change_view(self, request, object_id, *args, **kwargs):\n # Get the required and optional fields\n t = Publication.objects.get(pk=object_id).type\n required_fields = t.get_bibtex_required_list()\n optional_fields = t.get_bibtex_optional_list()\n\n # Set the fieldsets to optional and required\n self.fieldsets = [\n (None, {'fields':\n ['type', 'title', 'authors', 'year'] + required_fields}),\n ]\n\n if optional_fields:\n self.fieldsets.append((None, {'fields': optional_fields}))\n\n # Ensure that none of the optional-applicable-to-all fields are required\n general_fields = [\n 'citekey', 'keywords', 'url', 'urldate', 'code', 'pdf', 'doi', 'isbn','issn', 'note', 'external']\n general_fields = [k for k in general_fields if k not in required_fields]\n\n self.fieldsets.extend([\n (None, {'fields': general_fields}),\n (None, {'fields': ('abstract',)}),\n (None, {'fields': ('image', 'thumbnail')}),\n (None, {'fields': ('lists',)}),\n ])\n\n # Amended form with required arguments\n self.form = PublicationAdminForm\n self.readonly_fields = ('type',)\n\n return super(PublicationAdmin, self).change_view(request, object_id, *args, **kwargs)\n","sub_path":"publications/admin/publicationadmin.py","file_name":"publicationadmin.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"132929647","text":"from django.conf.urls.defaults import patterns, include, url\nfrom django.conf import settings\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Django admin\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n\nurlpatterns += patterns('apps.front.views',\n url(r'^person/$', 'persons', name='persons'),\n url(r'^person/(?P\\d+)/tagcloud/$', 'tagcloud', name='tagcloud'),\n)\n\nif settings.DEBUG: \n urlpatterns += patterns('django.views.static', \n url(r'static/(?P.*)$', 'serve', {'document_root': settings.STATIC_ROOT}),\n url(r'media/(?P.*)$', 'serve', {'document_root': settings.MEDIA_ROOT}),\n ) \n","sub_path":"frontend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"338671678","text":"import os\nimport json\nfrom dateutil import parser\n\n\nclass Nested:\n def __init__(self, structure):\n self.dict = structure\n\n def __new__(cls, structure):\n self = super(Nested, cls).__new__(cls)\n self.dict = structure\n if type(structure) is dict:\n self.__dict__ = {key: Nested(structure[key]) for key in structure}\n elif type(structure) is list:\n self = [Nested(item) for item in structure]\n else:\n self = structure\n return self\n\n def __str__(self):\n return str(self.dict)\n\n\nConfig = Nested({\n 'start': {\n 'date': None,\n 'district': None,\n 'court': None\n },\n 'search': {\n 'keyword': '*',\n 'type': None,\n 'reason': {\n 'value': '知识产权与竞争纠纷',\n 'level': 2\n },\n 'court:': {\n 'value': None,\n 'level': 0,\n 'indicator': False\n },\n 'district': None\n },\n 'condition': {\n '法院层级': None,\n '案件类型': '民事案件',\n '审判程序': None,\n '文书类型': None,\n },\n 'config': {\n 'max_retry': 10,\n 'proxy': True,\n 'timeout': 60\n }\n})\n\nif os.path.isfile('config.json'):\n with open('config.json', 'r', encoding='utf-8') as f:\n data = json.load(f)\n start_date = data['start']['date']\n if start_date is not None:\n data['start']['date'] = parser.parse(start_date)\n Config = Nested(data)\nelse:\n with open('config.json', 'w', encoding='utf-8') as f:\n json.dump(Config.data, f, ensure_ascii=False, indent=2)\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"425951813","text":"for x in range(2):\n for y in range(2):\n for z in range(2):\n for w in range(2):\n # (x ∨ y) ∧ ¬(y ≡ z) ∧ ¬w\n if ((x or y) and not(y == z) and not w) == 1:\n print(z, y, x, w)\n\n# следование заменяют на <=\n\n# полученные строки можно скопировать в эксель,\n# поставить наименования столбцов xyzw\n# и попереставлять строки и столбики,\n# подгоняя под заданную нам таблицу\n","sub_path":"#2 27399.py","file_name":"#2 27399.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"517828989","text":"inbuilt = ['delay']\n\ndef delay_checker(reply_value):\n if type(reply_value['delay'] == type(1)):\n return \"ok\"\n else:\n return {\"error\":True,\"message\":\"please check the type of delay\"}\n\n\ndef combiner(reply_values,output_values):\n output = []\n index = 0\n for i in reply_values:\n flag = 0\n for j in inbuilt:\n if j in i:\n flag = 1\n output.append(i)\n if flag == 0:\n output.append(output_values[index])\n index = index + 1\n return output","sub_path":"ChatBot code/api/libraries/gentemplateparsers/inbuilt_validations.py","file_name":"inbuilt_validations.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"208114623","text":"import time, datetime\n\n# debug flag\nDEBUG = True\n\n\n#holiday\nHOLIDAYS = [\n \"2018-09-24\", \"2018-10-01\", \"2018-10-02\", \"2018-10-03\", \"2018-10-04\", \"2018-10-05\",\n]\n\n\ndef is_trading_day(tm = time.time()):\n \"\"\"\n trading day: except weekday and holiday\n :param tm:\n :return:\n \"\"\"\n if DEBUG:\n return True\n\n # date time\n dt = datetime.datetime.fromtimestamp(tm)\n\n # check weekday\n if dt.isoweekday() in [6, 7]:\n return False\n\n # check holiday\n if dt.date().strftime('%Y-%m-%d') in HOLIDAYS:\n return False\n\n return True\n\n\ndef is_auction_time(tm = time.time()):\n \"\"\"\n 集合竞价时间,auction time: 9:15~9:25, 14:57~15:00\n :param tm:\n :return:\n \"\"\"\n if DEBUG:\n return True\n\n # check trading day\n if not is_trading_day(tm):\n return False\n\n # check trading time\n dtm = datetime.datetime.fromtimestamp(tm).time()\n\n if (datetime.time(9, 15) < dtm < datetime.time(9, 25)) \\\n or (datetime.time(14, 57) < dtm < datetime.time(15, 00)) :\n return True\n\n return False\n\n\ndef is_trading_time(tm = time.time()):\n \"\"\"\n trading time: 9:30~11:30, 13:00~14:57\n :param tm:\n :return:\n \"\"\"\n if DEBUG:\n return True\n\n # check trading day\n if not is_trading_day(tm):\n return False\n\n # check trading time\n dtm = datetime.datetime.fromtimestamp(tm).time()\n\n if ( datetime.time(9, 30) < dtm < datetime.time(11, 30)) \\\n or (datetime.time(13, 00) < dtm < datetime.time(14, 57)):\n return True\n\n return False\n\n\ndef is_clearing_time(tm = time.time()):\n \"\"\"\n clearing time: trading day's 15:00~15:10\n :param tm:\n :return:\n \"\"\"\n if DEBUG:\n return False\n\n # check trading day\n if not is_trading_day(tm):\n return False\n\n # check clearing time\n dtm = datetime.datetime.fromtimestamp(tm).time()\n\n if datetime.time(15, 00) < dtm < datetime.time(15, 10):\n return True\n\n return False","sub_path":"app/svc/app/aam/trade/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"120367665","text":"# encoding:utf-8\nimport urllib2\n\n\"\"\"\n使用网络上找到的免费的代理\nProxyHandler创建代理的函数,参数是一个字典,键http/https 值ip:port 或者yonghuming:mima@ip:port\n在创建opener的时候将代理对象加入进去 opener = urllib2.build_opener(代理对象) \n\"\"\"\nhttpproxy = urllib2.ProxyHandler({\"http\":\"49.70.64.148:9999\"}) # 无密码验证代理的使用\n# httpproxy = urllib2.ProxyHandler({\"http\":\"wangwei:111111@49.70.64.148:9999\"}) # 带密码的代理使用\n# 出错的一个原因其实就是代理不好使\n\"\"\"\nnohttpproxy = urllib2.ProxyHandler({}) # 空代理的使用\n\nopener = urllib2.build_opener(nohttpproxy) # 创建一个空代理打开器\n\"\"\"\n\nopener = urllib2.build_opener(httpproxy) # 创建一个打开器\n\"\"\"\n注意下面的url链接的完整性ttp://www.baidu.com/ 斜杠\n\"\"\"\nrequest = urllib2.Request(\"https://www.kuaidaili.com/doc/\")\nresponse = opener.open(request) # 打开网页,内置代理服务器\nprint(response.read())","sub_path":"urllib2_test/urllib2_test_11.py","file_name":"urllib2_test_11.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"286661465","text":"#Future Value\n\ndef futureValue():\n investment = int(input(\"How much is being invested? $\"))\n\n time = int(input(\"How many years will it remain invested? \"))\n\n rate = float(input(\"What % is the interest rate? \"))\n\n for i in range(time):\n investment = (investment + investment*(rate/100))\n print(\"Year\", i+1, \"= $\", investment)\n \nfutureValue()\n ","sub_path":"future_value.py","file_name":"future_value.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"361980805","text":"#!/usr/bin/env python\n# ***** BEGIN LICENSE BLOCK *****\n# Version: MPL 1.1/GPL 2.0/LGPL 2.1\n#\n# The contents of this file are subject to the Mozilla Public License Version\n# 1.1 (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n# http://www.mozilla.org/MPL/\n#\n# Software distributed under the License is distributed on an \"AS IS\" basis,\n# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n# for the specific language governing rights and limitations under the\n# License.\n#\n# The Original Code is Mozilla.\n#\n# The Initial Developer of the Original Code is\n# the Mozilla Foundation .\n# Portions created by the Initial Developer are Copyright (C) 2011\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n# Aki Sasaki \n#\n# Alternatively, the contents of this file may be used under the terms of\n# either the GNU General Public License Version 2 or later (the \"GPL\"), or\n# the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n# in which case the provisions of the GPL or the LGPL are applicable instead\n# of those above. If you wish to allow use of your version of this file only\n# under the terms of either the GPL or the LGPL, and not to allow others to\n# use your version of this file under the terms of the MPL, indicate your\n# decision by deleting the provisions above and replace them with the notice\n# and other provisions required by the GPL or the LGPL. If you do not delete\n# the provisions above, a recipient may use your version of this file under\n# the terms of any one of the MPL, the GPL or the LGPL.\n#\n# ***** END LICENSE BLOCK *****\n\"\"\"configtest.py\n\nVerify the .json and .py files in the configs/ directory are well-formed.\n\nFurther tests to verify validity would be desirable.\n\"\"\"\n\nimport os\nimport pprint\nimport sys\ntry:\n import simplejson as json\nexcept ImportError:\n import json\n\nsys.path.insert(1, os.path.dirname(sys.path[0]))\n\nfrom mozharness.base.script import BaseScript\n\n# ConfigTest {{{1\nclass ConfigTest(BaseScript):\n config_options = [[\n [\"--test-file\",],\n {\"action\": \"extend\",\n \"dest\": \"test_files\",\n \"help\": \"Specify which config files to test\"\n }\n ]]\n\n def __init__(self, require_config_file=False):\n self.config_files = []\n BaseScript.__init__(self, config_options=self.config_options,\n all_actions=['list-config-files',\n 'test-json-configs',\n 'test-python-configs',\n ],\n default_actions=['test-json-configs',\n 'test-python-configs'],\n require_config_file=require_config_file)\n\n def query_config_files(self):\n if self.config_files:\n return self.config_files\n c = self.config\n if 'test_files' in c:\n self.config_files = c['test_files']\n return self.config_files\n self.debug(\"No --test-file(s) specified; defaulting to crawling the configs/ directory.\")\n config_files = []\n for root, dirs, files in os.walk(os.path.join(sys.path[0], \"..\",\n \"configs\")):\n for name in files:\n # Hardcode =P\n if name.endswith(\".json\") or name.endswith(\".py\"):\n if not name.startswith(\"test_malformed\"):\n config_files.append(os.path.join(root, name))\n self.config_files = config_files\n return self.config_files\n\n def list_config_files(self):\n config_files = self.query_config_files()\n for config_file in config_files:\n self.info(config_file)\n\n def test_json_configs(self):\n \"\"\" Currently only \"is this well-formed json?\"\n\n \"\"\"\n config_files = self.query_config_files()\n filecount = [0, 0]\n for config_file in config_files:\n if config_file.endswith(\".json\"):\n filecount[0] += 1\n self.info(\"Testing %s.\" % config_file)\n fh = open(config_file)\n try:\n json.load(fh)\n except ValueError:\n self.add_summary(\"%s is invalid json.\" % config_file,\n level=\"error\")\n self.error(pprint.pformat(sys.exc_info()[1]))\n else:\n self.info(\"Good.\")\n filecount[1] += 1\n if filecount[0]:\n self.add_summary(\"%d of %d json config files were good.\" %\n (filecount[1], filecount[0]))\n else:\n self.add_summary(\"No json config files to test.\")\n\n def test_python_configs(self):\n \"\"\"Currently only \"will this give me a config dictionary?\"\n\n \"\"\"\n config_files = self.query_config_files()\n filecount = [0, 0]\n for config_file in config_files:\n if config_file.endswith(\".py\"):\n filecount[0] += 1\n self.info(\"Testing %s.\" % config_file)\n global_dict = {}\n local_dict = {}\n try:\n execfile(config_file, global_dict, local_dict)\n except:\n self.add_summary(\"%s is invalid python.\" % config_file,\n level=\"error\")\n self.error(pprint.pformat(sys.exc_info()[1]))\n else:\n if 'config' in local_dict and isinstance(local_dict['config'], dict):\n self.info(\"Good.\")\n filecount[1] += 1\n else:\n self.add_summary(\"%s is valid python, but doesn't create a config dictionary.\" %\n config_file, level=\"error\")\n if filecount[0]:\n self.add_summary(\"%d of %d python config files were good.\" %\n (filecount[1], filecount[0]))\n else:\n self.add_summary(\"No python config files to test.\")\n\n# __main__ {{{1\nif __name__ == '__main__':\n config_test = ConfigTest()\n config_test.run()\n","sub_path":"scripts/configtest.py","file_name":"configtest.py","file_ext":"py","file_size_in_byte":6347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"305079627","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCheck synchronization between iRODS and Django\n\nThis checks that:\n\n1. every ResourceFile corresponds to an iRODS file\n2. every iRODS file in {short_id}/data/contents corresponds to a ResourceFile\n3. every iRODS directory {short_id} corresponds to a Django resource\n\n* By default, prints errors on stdout.\n* Optional argument --log instead logs output to system log.\n\"\"\"\n\nfrom django.core.management.base import BaseCommand\nfrom hs_core.models import BaseResource\nfrom hs_core.management.utils import ingest_irods_files\n\nimport logging\n\n\nclass Command(BaseCommand):\n help = \"Check synchronization between iRODS and Django.\"\n\n def add_arguments(self, parser):\n\n # a list of resource id's, or none to check all resources\n parser.add_argument('resource_ids', nargs='*', type=str)\n\n # Named (optional) arguments\n parser.add_argument(\n '--log',\n action='store_true', # True for presence, False for absence\n dest='log', # value is options['log']\n help='log errors to system log',\n )\n\n def handle(self, *args, **options):\n\n if len(options['resource_ids']) > 0: # an array of resource short_id to check.\n for rid in options['resource_ids']:\n try:\n res = BaseResource.objects.get(short_id=rid)\n except BaseResource.DoesNotExist:\n msg = \"Resource with id {} not found in Django Resources\".format(rid)\n print(msg)\n\n resource = res.get_content_model()\n\n print(\"REPAIRING RESOURCE {}\".format(rid))\n resource.check_irods_files(stop_on_error=False,\n echo_errors=True,\n log_errors=False,\n return_errors=False,\n clean_irods=False,\n clean_django=True,\n sync_ispublic=True)\n if resource.resource_type == 'CompositeResource' or \\\n resource.resource_type == 'GenericResource' or \\\n resource.resource_type == 'ModelInstanceResource' or \\\n resource.resource_type == 'ModelProgramResource':\n logger = logging.getLogger(__name__)\n ingest_irods_files(resource,\n logger,\n stop_on_error=False,\n echo_errors=True,\n log_errors=False,\n return_errors=False)\n\n if resource.resource_type == 'CompositeResource':\n for res_file in resource.files.all():\n if not res_file.has_logical_file:\n print(\"Logical file missing for file {}\".format(res_file.short_path))\n resource.set_default_logical_file()\n\n else: # check all resources\n print(\"REPAIRING ALL RESOURCES\")\n for r in BaseResource.objects.all():\n resource = r.get_content_model()\n\n # first clean up Django references to non-existent iRODS files\n resource.check_irods_files(stop_on_error=False,\n echo_errors=True,\n log_errors=False,\n return_errors=False,\n clean_irods=False,\n clean_django=True,\n sync_ispublic=True)\n\n # now ingest any dangling iRODS files that you can\n if resource.resource_type == 'CompositeResource' or \\\n resource.resource_type == 'GenericResource' or \\\n resource.resource_type == 'ModelInstanceResource' or \\\n resource.resource_type == 'ModelProgramResource':\n logger = logging.getLogger(__name__)\n ingest_irods_files(resource,\n logger,\n stop_on_error=False,\n echo_errors=True,\n log_errors=False,\n return_errors=False)\n\n if resource.resource_type == 'CompositeResource':\n for res_file in resource.files.all():\n if not res_file.has_logical_file:\n print(\"Logical file missing for file {}\".format(res_file.short_path))\n resource.set_default_logical_file()\n","sub_path":"hs_core/management/commands/repair_resource.py","file_name":"repair_resource.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"308303527","text":"import ctypes\nimport threading\n\nfrom common import KEYS\n\nuser32 = ctypes.WinDLL(\"User32.dll\")\n\n\nclass State:\n def __init__(self, queue):\n self.q = queue\n self.thread = threading.Thread(target=self.watcher)\n self.thread.start()\n\n def watcher(self):\n old_state = -1\n while True:\n new_state = State.get_locks_state()\n if old_state != new_state:\n self.q.put(new_state)\n old_state = new_state\n\n @staticmethod\n def get_locks_state():\n status = 0\n for i, key in enumerate(KEYS):\n status |= (1 if user32.GetKeyState(key['keycode']) else 0) << i\n return status\n","sub_path":"state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"159327803","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef loadDataSet():\n datamat = []\n labelmat = []\n fr = open('/home/plutolove/testSet.txt')\n for line in fr.readlines():\n str = line.split()\n datamat.append([1.0, float(str[0]), float(str[1])])\n labelmat.append(int(str[2]))\n return datamat, labelmat\n\n\ndef sigmoid(inX):\n return 1.0/(1.0 + np.exp(-inX))\n\n\ndef gradAscent(datamat, labelmat):\n dataset = np.mat(datamat)\n labels = np.mat(labelmat).transpose()\n m, n = np.shape(dataset)\n alpha = 0.001\n iters = 500\n weights = np.ones((n, 1))\n for i in range(iters):\n h = sigmoid(dataset * weights)\n error = (labels - h)\n weights = weights + alpha * dataset.transpose() * error\n return weights\n\n\ndef plotBestFit(wei):\n weights = wei.getA()\n data, label = loadDataSet()\n dataArr = np.array(data)\n n = np.shape(data)[0]\n x1 = []\n y1 = []\n x2 = []\n y2 = []\n for i in range(n):\n if(label[i] == 1):\n x1.append(dataArr[i, 1])\n y1.append(dataArr[i, 2])\n else:\n x2.append(dataArr[i, 1])\n y2.append(dataArr[i, 2])\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(x1, y1, s=30, c='red', marker='s')\n ax.scatter(x2, y2, s=30, c='green')\n x = np.arange(-3.0, 3.0, 0.1)\n y = (-weights[0] - weights[1] * x)/weights[2]\n ax.plot(x, y)\n plt.xlabel('X1')\n plt.ylabel('X2')\n plt.show()\n\n\ndef classify(inX, weights):\n prob = sigmoid(sum(inX * weights))\n if(prob > 0.5):\n return 1\n else:\n return 0\n\n'''\ndata, label = loadDataSet()\nweights = gradAscent(data, label)\nplotBestFit(weights)\n'''","sub_path":"Logistic/logRegres.py","file_name":"logRegres.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"77996441","text":"\"\"\"\nImplementing basic feed forward NNet for the MNIST dataset.\n*Also from Sentdex tutorial*\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# Import MNIST data\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True )\n\n# Define number of nudes per layer\nnNodesH1 = 500\nnNodesH2 = 500\nnNodesH3 = 500\n\n# Define number of distinct targets.\nnClasses = 10\nbatchSize = 100\n\n# Define input data (No height, but 28*28 width, or 784 width\nx = tf.placeholder('float',[None, 784])\n\n# Define output data\ny = tf.placeholder('float')\n\ndef neuralNetworkModel(data):\n \"\"\" Set up computation graph for neural network\n\n This network will only have three hidden layers and then an output layer.\n\n Args:\n data (df): Data for the model to be trained on.\n\n Returns:\n output (tensor): The output tensor from the neural network.\n\n \"\"\"\n\n hiddenLayer1 = {'weights':tf.Variable(tf.random_normal([784, nNodesH1])),\n 'biases': tf.Variable(tf.random_normal([nNodesH1]))}\n\n hiddenLayer2 = {'weights':tf.Variable(tf.random_normal([nNodesH1, nNodesH2])),\n 'biases': tf.Variable(tf.random_normal([nNodesH2]))}\n\n hiddenLayer3 = {'weights':tf.Variable(tf.random_normal([nNodesH2, nNodesH3])),\n 'biases': tf.Variable(tf.random_normal([nNodesH3]))}\n\n outputLayer = {'weights':tf.Variable(tf.random_normal([nNodesH3, nClasses])),\n 'biases': tf.Variable(tf.random_normal([nClasses]))}\n\n layer1 = tf.add(tf.matmul(data,hiddenLayer1['weights']), hiddenLayer1['biases'])\n layer1 = tf.nn.relu(layer1)\n\n layer2 = tf.add(tf.matmul(layer1, hiddenLayer2['weights']), hiddenLayer2['biases'])\n layer2 = tf.nn.relu(layer2)\n\n layer3 = tf.add(tf.matmul(layer2, hiddenLayer3['weights']), hiddenLayer3['biases'])\n layer3 = tf.nn.relu(layer3)\n\n output = tf.add(tf.matmul(layer3, outputLayer['weights']), outputLayer['biases'])\n\n return output\n\ndef trainNeuralNet(x):\n # Return one hot array from NNet.\n prediction = neuralNetworkModel(x)\n\n # Cost function.\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))\n\n # Optimizer\n optimizer = tf.train.AdamOptimizer().minimize(cost)\n\n # State number of epochs (cycles of feed forward and backprop)\n numEpochs = 10\n\n with tf.Session() as sess:\n sess.run(tf.initialize_all_variables())\n\n for epoch in range(numEpochs):\n epochLoss = 0\n for _ in range(int(mnist.train.num_examples/batchSize)):\n epochX, epochy = mnist.train.next_batch(batchSize)\n # Update cost with x and y with backprop\n _, c = sess.run([optimizer, cost], feed_dict={x: epochX, y: epochy})\n epochLoss += c # Update cost\n print('Epoch', epoch, 'completed out of', numEpochs, 'loss:', epochLoss)\n \n correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1)) # Checks to see if the prediction == actual\n accuracy = tf.reduce_mean(tf.cast(correct, 'float')) # Cast accuracy to a float.\n print('Accuracy:', accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))\n\n \ntrainNeuralNet(x)\n","sub_path":"Day3/DeepNNetIntro.py","file_name":"DeepNNetIntro.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"84599178","text":"\"\"\"\nWordpress Watcher\nAutomating WPscan to scan and report vulnerable Wordpress sites\n\nDISCLAIMER - USE AT YOUR OWN RISK.\n\"\"\"\nimport shlex\nimport os \nimport traceback\nimport subprocess\nfrom subprocess import CalledProcessError\nfrom wpwatcher import log\nfrom wpwatcher.utils import safe_log_wpscan_args, oneline\n# WPScan helper class -----------\nclass WPScanWrapper():\n\n def __init__(self, path):\n self.path=path\n # List of current WPScan processes\n self.processes=[]\n\n # Helper method: actually wraps wpscan\n def wpscan(self, *args):\n (exit_code, output)=(0,\"\")\n # WPScan arguments\n cmd=shlex.split(self.path) + list(args)\n # Log wpscan command without api token\n log.debug(\"Running WPScan command: %s\" % ' '.join(safe_log_wpscan_args(cmd)) )\n # Run wpscan -------------------------------------------------------------------\n try:\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=open(os.devnull,'w') )\n # Append process to current process list and launch\n self.processes.append(process)\n wpscan_output, _ = process.communicate()\n self.processes.remove(process)\n try: wpscan_output=wpscan_output.decode(\"utf-8\")\n except UnicodeDecodeError: wpscan_output=wpscan_output.decode(\"latin1\")\n # Error when wpscan failed, except exit code 5: means the target has at least one vulnerability.\n # See https://github.com/wpscanteam/CMSScanner/blob/master/lib/cms_scanner/exit_code.rb\n if process.returncode not in [0,5]:\n # Handle error\n err_string=\"WPScan command '%s' failed with exit code %s %s\" % (' '.join(safe_log_wpscan_args(cmd)) ,str(process.returncode), \". WPScan output: %s\"%wpscan_output if wpscan_output else '')\n log.error(oneline(err_string))\n else :\n # WPScan comamnd success\n log.debug(\"WPScan raw output:\\n\"+wpscan_output)\n (exit_code, output)=(process.returncode, wpscan_output)\n except (CalledProcessError) as err:\n # Handle error --------------------------------------------------\n wpscan_output=str(err.output)\n err_string=\"WPScan command '%s' failed with exit code %s %s\\nError:\\n%s\" % (' '.join(safe_log_wpscan_args(cmd)) ,str(process.returncode), \". WPScan output: %s\"%wpscan_output if wpscan_output else '', traceback.format_exc())\n\n log.error(oneline(err_string))\n (exit_code, output)=(err.returncode, wpscan_output)\n except FileNotFoundError as err:\n err_string=\"Could not find wpscan executable. \\nError:\\n%s\" % (traceback.format_exc())\n log.error(oneline(err_string))\n (exit_code, output)=(-1, \"\")\n return((exit_code, output))\n \n # Check if WPScan is installed\n def is_wpscan_installed(self):\n exit_code, _ = self.wpscan(\"--version\")\n if exit_code!=0: return False\n else: return True\n\n # Update WPScan database\n def update_wpscan(self):\n log.info(\"Updating WPScan\")\n exit_code, _ = self.wpscan(\"--update\")\n if exit_code!=0: \n log.error(\"Error updating WPScan\")\n exit(-1)\n","sub_path":"wpwatcher/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"204341334","text":"# coding=utf-8\nimport json\n\nfrom commons.exception import BatchUploadError\nfrom commons.utils import time_util, to_dict\nfrom core.framework.plugin import execute_plugin\nfrom data.manager import WageMgr, WageRawDataMgr, CrewMgr\nfrom data.manager.proj import ProjOfferMgr\n\n\ndef create_wage_raw_data(proj_id, lines):\n line_index = 0\n data = {'errors': []}\n for line in lines:\n line_index += 1\n crew_id = CrewMgr.get_crew_id_by_account(line['crew_account'])\n if not crew_id:\n data['errors'].append(BatchUploadError(line_index, '该员工没有录入系统').to_dict())\n continue\n wage_time = time_util.dateString2timestampCommon(line['wage_time'])\n record = {\n 'proj_id': proj_id,\n 'crew_id': crew_id,\n 'bill_id': '%d%d%d' % (proj_id, wage_time, crew_id),\n 'wage_time': wage_time\n }\n records = []\n for key, value in line.items():\n if key.endswith('量') and float(value) > 0:\n record['position'] = key.replace('量', '')\n record['work_amount'] = value\n records.append(record.copy())\n for record in records:\n record['work_hours'] = float(line['work_hours']) / len(records)\n WageRawDataMgr.create_override_if_exist(record)\n return data\n\n\ndef calculate(proj_id, date):\n offers = ProjOfferMgr.query({'proj_id': proj_id, 'is_del': 0})\n date_timestamp = time_util.dateString2timestampCommon(date)\n raw_datas = WageRawDataMgr.query({'proj_id': proj_id, 'wage_time': date_timestamp, 'is_del': 0})\n calculated_datas = []\n for offer in offers:\n if offer.position != '所有':\n data = {'offer': to_dict(offer), 'raw_datas': to_dict(raw_datas), 'calculated_datas': []}\n result = execute_plugin('offer', offer.id, 'on_position_calculate', {}, data)\n calculated_datas.extend(result['data']['calculated_datas'])\n\n wage_maps = {}\n for data in calculated_datas:\n key = '%s_%s_%s' % (data['supplier_id'], data['offer_type'], data['crew_id'])\n if key in wage_maps:\n wage_maps[key]['amount'] += data['amount']\n wage_maps[key]['work_rate'] += data['work_rate']\n else:\n wage_maps[key] = data\n for offer in offers:\n if offer.position == '所有':\n data = {'offer': to_dict(offer), 'wage_datas': wage_maps.values()}\n result = execute_plugin('offer', offer.id, 'on_position_agregate_calculate', {}, data)\n for item in result['data']['wage_datas']:\n WageMgr.create_override_if_exist(item)\n","sub_path":"service/wage_service.py","file_name":"wage_service.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"306854234","text":"import argparse\nimport os\nfrom pathlib import Path\n\nfrom detr_models.detr.config import DefaultDETRConfig\nfrom detr_models.detr.train import init_training\n\nconfig = DefaultDETRConfig()\n\n\ndef get_args_parser():\n parser = argparse.ArgumentParser(add_help=False)\n parser.add_argument(\n \"-sp\", \"--storage_path\", help=\"Path to data storage\", type=str, required=True\n )\n parser.add_argument(\n \"-o\",\n \"--output_dir\",\n help=\"Path to store weights and losses\",\n default=os.path.join(os.getcwd(), \"training_results\"),\n type=str,\n )\n\n parser.add_argument(\"-bs\", \"--batch_size\", default=config.batch_size, type=int)\n parser.add_argument(\"-e\", \"--epochs\", default=config.epochs, type=int)\n\n parser.add_argument(\n \"-masks\",\n \"--train_masks\",\n help=\"Flag to indicate trainining of segmentation masks\",\n default=config.train_masks,\n action=\"store_true\",\n )\n\n parser.add_argument(\n \"-up\", \"--use_pretrained\", help=\"Path to pre-trained model weights.\", type=str\n )\n\n parser.add_argument(\n \"-gpu\",\n \"--use_gpu\",\n help=\"Flag to indicate training on a GPU\",\n action=\"store_true\",\n )\n\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n help=\"Flag to indicate additional logging\",\n action=\"store_true\",\n )\n return parser\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n \"DETR training script\", parents=[get_args_parser()]\n )\n args = parser.parse_args()\n\n if args.output_dir:\n Path(args.output_dir).mkdir(parents=True, exist_ok=True)\n\n training_config = {\n \"storage_path\": args.storage_path,\n \"output_dir\": args.output_dir,\n \"batch_size\": args.batch_size,\n \"epochs\": args.epochs,\n \"train_masks\": args.train_masks,\n \"use_pretrained\": args.use_pretrained,\n \"use_gpu\": args.use_gpu,\n \"verbose\": args.verbose,\n }\n\n init_training(training_config)\n","sub_path":"detr_models/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"125358346","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\n\n\ndef main():\n if len(sys.argv) != 5:\n sys.stdout.write('Invalid number of arguments')\n return\n\n mthd = sys.argv[1]\n rf = sys.argv[2]\n n = sys.argv[3]\n ow = sys.argv[4] == '+'\n rfstr = rf.replace('/', '')\n owstr = '_ow' if ow else ''\n file = open('data_{mthd}_{rf}_{n}{ow}'.format(mthd=mthd, rf=rfstr, n=n, ow=owstr), 'w')\n\n if mthd == 'PUTGET':\n N = int(int(n) / 2)\n ow_n_times = 2 if ow else 1\n N = int(N / 2) if ow else N\n for i in range(0, N):\n ID = i\n for j in range(0, ow_n_times):\n mthd = 'PUT'\n tag = '{mthd}_{rf}'.format(mthd=mthd, rf=rf)\n body = '||hello!! yandex-tank load test!!! gfsdgwergiwj4ofrgjoi4jgedfghweiorh'\n file.write('{m}||/v0/entity?id={id}&replicas={rf}||{tag}{body}\\n'.format(m=mthd, id=ID, rf=rf, tag=tag, body=body))\n mthd = 'GET'\n tag = '{mthd}_{rf}'.format(mthd=mthd, rf=rf)\n body = ''\n file.write('{m}||/v0/entity?id={id}&replicas={rf}||{tag}{body}\\n'.format(m=mthd, id=ID, rf=rf, tag=tag, body=body))\n return\n\n tag = '{mthd}_{rf}'.format(mthd=mthd, rf=rf)\n N = int(n)\n ow_n_times = 2 if ow else 1\n N = int(N / 2) if ow else N\n for i in range(0, N):\n ID = i\n for j in range(0, ow_n_times):\n if mthd == 'PUT':\n body = '||hello!! yandex-tank load test!!! gfsdgwergiwj4ofrgjoi4jgedfghweiorh'\n else:\n body = ''\n file.write('{m}||/v0/entity?id={id}&replicas={rf}||{tag}{body}\\n'.format(m=mthd, id=ID, rf=rf, tag=tag, body=body))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"yandex-tank/ammo_gens/gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"529155142","text":"import os\nimport re\nimport logging\nimport certifi\nimport time\nimport pygsheets\nimport pandas as pd\nimport ssl as ssl_lib\nfrom flask import Flask\nfrom fuzzywuzzy import fuzz\nfrom slack import WebClient\nfrom nltk.corpus import stopwords\nfrom slackeventsapi import SlackEventAdapter\nimport requests\n\n\n# The bot id, so we can remove this from the response text\nbot_id = '<@U012HNV5J2D>'\n\n# Initialize a Flask app to host the events adapter\napp = Flask(__name__)\nslack_events_adapter = SlackEventAdapter(os.environ[\"SLACK_SIGNING_SECRET\"], \"/slack/events\", app)\n\n# Initialize a Web API client\nslack_web_client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])\n\ndef get_data():\n r = requests.get('https://api.covid19india.org/data.json')\n body = r.json()\n return body\n\ndef get_message_payload(channel_id, welcome_block):\n return {\n \"channel\": channel_id,\n \"blocks\": [\n welcome_block,\n ],\n }\n\n\ndef prepareAllAnswer(body, index, statename):\n statewise = body['statewise']\n statedata = statewise[index]\n data = statename\n data += \"\\nConfirmed: \" + statedata['confirmed']\n if int(statedata['deltaconfirmed']) > 0 :\n if int(statedata['deltaconfirmed']) > 1:\n data += ' (' + statedata['deltaconfirmed'] + ' new cases)'\n else:\n data += ' (' + statedata['deltaconfirmed'] + ' new case)'\n\n data += \"\\nActive: \" + statedata['active']\n data += \"\\nRecovered: \" + statedata['recovered']\n if int(statedata['deltarecovered']) > 0:\n if int(statedata['deltarecovered']) > 1:\n data += ' (' + statedata['deltarecovered'] + ' new recoveries)'\n else:\n data += ' (' + statedata['deltarecovered'] + ' new recovery)'\n\n data += \"\\nDeaths: \" + statedata['deaths']\n if int(statedata['deltadeaths']) > 0 :\n if int(statedata['deltadeaths']) > 1 :\n data += ' (' + statedata['deltadeaths'] + ' new deaths)'\n else:\n data += ' (' + statedata['deltadeaths'] + ' new death)'\n return data\n\n\ndef prepareStatesData(body):\n statewise = body['statewise']\n index = 0\n #data = \"My\"\n data = 'Top 15 states with most cases'\n for object in statewise:\n if index > 15:\n break\n else:\n data += '\\n' + object['state'] + ': ' + object['confirmed']\n #print(data)\n if int(object['deltaconfirmed']) > 0:\n data += ' (+' + object['deltaconfirmed'] + ') '\n #print(data)\n index = index + 1\n return data\n\n\n# Post message to slack using WebClient\ndef post_message_to_slack(channel: str, slack_message):\n response = slack_web_client.chat_postMessage(channel=channel, text=slack_message)\n\ndef preprocess_raw_text(text):\n stop_words = [bot_id]\n # Remove stopword and punctuation\n text = ' '.join([word for word in text.split() if word not in stop_words])\n text = ' '.join([re.sub(r'[^A-Za-z0-9]+', \"\", word) for word in text.split()])\n # print(\"Processed text in fun\" + text)\n return text\n\n\n# Subscribe to only the message events that mention your app or bot eg. @covid-bot all/states\n@slack_events_adapter.on(\"app_mention\")\ndef message(payload):\n global company_index\n # Extract the payload contents\n start_time = time.time()\n event = payload.get(\"event\", {})\n print(event)\n channel_id = event.get(\"channel\")\n command = preprocess_raw_text(event.get(\"text\"))\n body = get_data()\n if command.lower() == \"all\":\n allData = prepareAllAnswer(body, 0, \"All States in India\")\n print(allData)\n post_message_to_slack(channel_id, allData)\n elif command.lower() == \"states\":\n stateData = prepareStatesData(body)\n print(stateData)\n post_message_to_slack(channel_id, stateData)\n else:\n print(\"Please enter 'all' or 'states'\")\n post_message_to_slack(channel_id, \"Please enter 'all' or 'states'\")\n\nif __name__ == \"__main__\":\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n logger.addHandler(logging.StreamHandler())\n ssl_context = ssl_lib.create_default_context(cafile=certifi.where())\n app.run(port=3000)","sub_path":"covid-bot.py","file_name":"covid-bot.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"592168407","text":"i = 0\nwhile i < 3:\n\tprint('Hello World')\n\ti = i + 1\nprint('After while')\n\n#피보나치 \na, b = 0, 1\nwhile b < 1000:\n\tprint(\"Hello World \"+str(b))\n\ta, b = b, a + b\n\n#컨테이너\nmembers = ['cho', 'jung', 'ha']\ni = 0\nwhile i < len(members):\n\tprint(members[i])\n\ti = i + 1\n\nfor member in members:\n\tprint(member)\n\nfor item in range(5, 11):\n\tprint(item)","sub_path":"practice/basic/loof/loof.py","file_name":"loof.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"196733867","text":"import numpy as np\nimport cv2\nimport dlib\nfrom skimage import io\nfrom sets import Set\nimport os\nimport inspect\n\nclass Mole_Tracker(object):\n\t\"\"\"\n\tArgs:\n\t\tfilename1 (str): first image's path \n\t\tfilename2 (str): second image's path \n\t\tmoles1 (array of (x,y) tuples): first image's moles coordinates \n\t\tmoles2 (array of (x,y) tuples): second image's moles coordinates \n\t\"\"\"\n\tdef __init__(self, filename1, filename2, moles1, moles2):\n\t\tsuper(Mole_Tracker, self).__init__()\n\t\timage1 = cv2.imread(filename1)\n\t\tself.gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)\n\t\timage2 = cv2.imread(filename2)\n\t\tself.gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)\n\t\tself.moles1 = moles1\n\t\tself.moles2 = moles2\n\n\tdef rect_to_bb(self, rect):\n\t\t# take a bounding predicted by dlib and convert it\n\t\t# to the format (x, y, w, h) as we would normally do\n\t\t# with OpenCV\n\t\tx = rect.left()\n\t\ty = rect.top()\n\t\tw = rect.right() - x\n\t\th = rect.bottom() - y\n\t \n\t\t# return a tuple of (x, y, w, h)\n\t\treturn (x, y, w, h)\n\n\tdef shape_to_np(self, shape, dtype=\"int\"):\n\t\t# initialize the list of (x, y)-coordinates\n\t\tcoords = np.zeros((68, 2), dtype=dtype)\n\t \n\t\t# loop over the 68 facial landmarks and convert them\n\t\t# to a 2-tuple of (x, y)-coordinates\n\t\tfor i in range(0, 68):\n\t\t\tcoords[i] = (shape.part(i).x, shape.part(i).y)\n\t \n\t\t# return the list of (x, y)-coordinates\n\t\treturn coords\n\n\tdef get_landmarks(self, gray):\n\n\t\trects = self.detector(gray, 1)\n\n\t\t# loop over the face detections\n\t\tfor (i, rect) in enumerate(rects):\n\t\t\t# determine the facial landmarks for the face region, then\n\t\t\t# convert the facial landmark (x, y)-coordinates to a NumPy\n\t\t\t# array\n\t\t\tshape = self.predictor(gray, rect)\n\t\t\tshape = self.shape_to_np(shape)\n\t\t\treturn shape\n\n\tdef get_distance(self, shape, moles):\n\t\t\n\t\tdistances = {}\n\t\t# Store and return four distance between mole and landmarks\n\t\tfor i in xrange(len(moles)):\n\t\t\tdist_40 = np.sqrt((moles[i][0] - shape[40][0])**2 + (moles[i][1] - shape[40][1])**2)\n\t\t\tdist_43 = np.sqrt((moles[i][0] - shape[43][0])**2 + (moles[i][1] - shape[43][1])**2)\n\t\t\tdistances[moles[i]] = [dist_40, dist_43]\n\t\tprint(distances)\n\t\treturn distances\n\n\tdef match(self, distances1, distances2, ratio):\n\t\tmole_pairs = {}\n\t\tfor mole1, dist1 in distances1.iteritems():\n\t\t\tfor mole2, dist2 in distances2.iteritems():\n\t\t\t\t\n\t\t\t\tprint(mole1)\n\t\t\t\tprint(mole2)\n\t\t\t\t\n\t\t\t\tprint(dist2)\n\t\t\t\tdist1 = [dist1[0] * ratio, dist1[1] * ratio]\n\t\t\t\tprint(dist1)\n\t\t\t\t# print(dist2)\n\t\t\t\tif np.isclose(dist1, dist2, atol=10).all():\n\t\t\t\t\tmole_pairs[mole1] = mole2\n\t\t\t\t\tdel(distances2[mole2])\n\t\t\t\t\tbreak\n\t\treturn mole_pairs\n\n\tdef track(self):\n\t\tself.detector = dlib.get_frontal_face_detector()\n\t\tself.predictor = dlib.shape_predictor(\"./shape_predictor_68_face_landmarks.dat\")\n\t\tshape1 = self.get_landmarks(self.gray1)\n\t\tshape2 = self.get_landmarks(self.gray2)\n\t\tdistances1 = self.get_distance(shape1, self.moles1)\n\t\tdistances2 = self.get_distance(shape2, self.moles2)\n\t\tland_mark_dist1 = np.sqrt((shape1[40][0] - shape1[43][0])**2 + (shape1[40][1] - shape1[43][1])**2)\n\t\tland_mark_dist2 = np.sqrt((shape2[40][0] - shape2[43][0])**2 + (shape2[40][1] - shape2[43][1])**2)\n\t\tratio = land_mark_dist1 / land_mark_dist2\n\t\tmole_pairs = self.match(distances1, distances2, ratio)\n\t\treturn mole_pairs\n\n''' Example to use the code '''\n'''\nmoles1 = [(608, 508), (652, 568), (806, 517)]\nmoles2 = [(565, 498), (605, 557), (756, 508)]\ntracker = Mole_Tracker(\"./../log/test1.png\", \"./../log/test2.png\", moles1, moles2)\n\nmole_pairs = tracker.track()\nprint(mole_pairs)\ncolor = 255\nfor m1, m2 in mole_pairs.iteritems():\n\tcv2.circle(tracker.gray1, (m1[0], m1[1]), 1, (0, 0, color), -1)\n\tcv2.circle(tracker.gray2, (m2[0], m2[1]), 1, (0, 0, color), -1)\n\tcolor -= 85\ncv2.imshow(\"Output1\", tracker.gray1)\ncv2.imwrite('output1.png', tracker.gray1)\ncv2.imshow(\"Output2\", tracker.gray2)\ncv2.imwrite('output2.png', tracker.gray2)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n'''\n\n\n\n\n\n","sub_path":"modules/MMM-Mole/code/Calibrate.py","file_name":"Calibrate.py","file_ext":"py","file_size_in_byte":3904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"264010147","text":"import glob\nfrom multiprocessing import Process, Manager, Value, Semaphore\nimport os\nimport pysam\nfrom random import random\nimport sys\n\nfrom reference_vntr import load_unique_vntrs_data\nfrom sam_utils import get_id_of_reads_mapped_to_vntr_in_samfile\nfrom vntr_finder import VNTRFinder\n\n\ndef clean_up_tmp():\n os.system('rm -rf /tmp/*.sam')\n os.system('rm -rf /tmp/*.fasta')\n\n\ndef bowtie_alignment(fasta_file, output, param):\n os.system('bowtie2 -x hg19_chromosomes/hg19_bt2_idx --end-to-end -f %s -S %s --threads 24 --score-min L,-0.6,%s' % (fasta_file, output, param))\n\n\ndef bwa_alignment(fasta_file, output, param):\n os.system('bwa mem -T %s -t 24 hg19_chromosomes/CombinedHG19_Reference.fa %s > %s' % (param, fasta_file, output))\n\n\ndef save_reads_stat(file_name, reads):\n with open(file_name, 'w') as out:\n for read in reads:\n alignment_score = None\n for key, value in read.tags:\n if key == 'AS':\n alignment_score = value\n out.write('%s %s\\n' % (read.qname, alignment_score))\n\n\ndef get_positive_and_fn_reads_from_samfile(sam_file, reference_vntr, true_reads, read_length=150):\n alignment_file = pysam.AlignmentFile(sam_file, 'r', ignore_truncation=True)\n start = reference_vntr.start_point\n end = reference_vntr.start_point + reference_vntr.get_length()\n positive_reads = []\n false_negative_reads = []\n try:\n for read in alignment_file.fetch(until_eof=True):\n if read.is_unmapped:\n if read.qname in true_reads:\n false_negative_reads.append(read)\n continue\n # if read.is_supplementary:\n # continue\n # if read.is_secondary:\n # continue\n if reference_vntr.chromosome == read.reference_name:\n if start - read_length < read.reference_start < end:\n positive_reads.append(read)\n continue\n if read.qname in true_reads:\n false_negative_reads.append(read)\n except IOError as err:\n print('Catched IOError: ', err)\n print('positive len:', len(positive_reads))\n return positive_reads, false_negative_reads\n\n\ndef write_hmm_scores(simulated_samfile, true_reads_hmm_scores, false_reads_hmm_scores, ref_vntr, true_reads):\n vntr_finder = VNTRFinder(ref_vntr)\n hmm = vntr_finder.get_vntr_matcher_hmm(150)\n\n manager = Manager()\n false_scores = manager.list()\n true_scores = manager.list()\n\n process_list = []\n sema = Semaphore(16)\n samfile = pysam.AlignmentFile(simulated_samfile, 'r', ignore_truncation=True)\n for read in samfile.fetch(until_eof=True):\n if read.seq.count('N') > 0:\n continue\n if True:\n if read.qname in true_reads:\n sema.acquire()\n p = Process(target=VNTRFinder.add_hmm_score_to_list, args=(sema, hmm, read, true_scores))\n else:\n if random() > 0.001:\n continue\n sema.acquire()\n p = Process(target=VNTRFinder.add_hmm_score_to_list, args=(sema, hmm, read, false_scores))\n process_list.append(p)\n p.start()\n else:\n if vntr_finder.is_true_read(read):\n sema.acquire()\n p = Process(target=VNTRFinder.add_hmm_score_to_list, args=(sema, hmm, read, true_scores))\n else:\n if random() > 0.001:\n continue\n sema.acquire()\n p = Process(target=VNTRFinder.add_hmm_score_to_list, args=(sema, hmm, read, false_scores))\n process_list.append(p)\n p.start()\n for p in process_list:\n p.join()\n\n with open(true_reads_hmm_scores, 'w') as out:\n for score in true_scores:\n out.write('%s\\n' % score)\n with open(false_reads_hmm_scores, 'w') as out:\n for score in false_scores:\n out.write('%s\\n' % score)\n\n\ndef find_info_by_mapping(sim_dir='simulation_data/', dir_index=0):\n reference_vntrs = load_unique_vntrs_data()\n id_to_gene = {119: 'DRD4', 1220: 'GP1BA', 1221: 'CSTB', 1214: 'MAOA', 1219: 'IL1RN'}\n gene_to_length = {'DRD4': 528, 'GP1BA': 39, 'CSTB': 168, 'MAOA': 30}\n clean_up_tmp()\n dirs = glob.glob(sim_dir+'/*')\n simulation_dir = dirs[dir_index]\n files = glob.glob(simulation_dir + '/*')\n for fasta_file in files:\n if fasta_file.endswith('WGS_30x.fasta'):\n gene_name = simulation_dir.split('/')[-1].split('_')[0]\n vntr_id = None\n for vid, gname in id_to_gene.items():\n if gname == gene_name:\n vntr_id = vid\n ref_vntr = reference_vntrs[vntr_id]\n\n true_reads_file = fasta_file[:-6] + '_true_reads.txt'\n simulated_sam_file = fasta_file[:-6] + '.sam'\n if not os.path.exists(true_reads_file):\n region = [ref_vntr.start_point, ref_vntr.start_point + gene_to_length[gene_name]]\n true_reads = get_id_of_reads_mapped_to_vntr_in_samfile(simulated_sam_file, ref_vntr, region=region)\n with open(true_reads_file, 'w') as out:\n for true_read in true_reads:\n out.write('%s\\n' % true_read)\n else:\n with open(true_reads_file) as input:\n lines = input.readlines()\n true_reads = [line.strip() for line in lines if line.strip() != '']\n\n true_reads_hmm_scores = fasta_file[:-6] + '_t_reads_hmm_score.txt'\n false_reads_hmm_scores = fasta_file[:-6] + '_f_reads_hmm_score.txt'\n if not os.path.exists(true_reads_hmm_scores):\n write_hmm_scores(simulated_sam_file, true_reads_hmm_scores, false_reads_hmm_scores, ref_vntr, true_reads)\n\n for i, parameter in enumerate([10]):\n positive_file = fasta_file[:-6] + '_bwa_%s_positive_supplementary_reads.txt' % abs(parameter)\n false_negative_file = fasta_file[:-6] + '_bwa_%s_fn_supplementary_reads.txt' % abs(parameter)\n if os.path.exists(positive_file) and os.path.exists(false_negative_file):\n continue\n bwa_alignment_file = '/tmp/_gene%s_' % dir_index + 'bwa_alignment_%s.sam' % i\n bwa_alignment(fasta_file, bwa_alignment_file, parameter)\n positive_reads, fn_reads = get_positive_and_fn_reads_from_samfile(bwa_alignment_file, ref_vntr, true_reads)\n save_reads_stat(positive_file, positive_reads)\n save_reads_stat(false_negative_file, fn_reads)\n\n clean_up_tmp()\n\n for i, parameter in enumerate([-0.6, -2]):\n if i == 0:\n continue\n positive_file = fasta_file[:-6] + '_bowtie_%s_positive_supplementary_reads.txt' % abs(parameter)\n false_negative_file = fasta_file[:-6] + '_bowtie_%s_fn_supplementary_reads.txt' % abs(parameter)\n if os.path.exists(positive_file) and os.path.exists(false_negative_file):\n continue\n bowtie_alignment_file = '/tmp/_gene%s_' % dir_index + 'bowtie_alignment_%s.sam' % i\n bowtie_alignment(fasta_file, bowtie_alignment_file, parameter)\n positive_reads, fn_reads = get_positive_and_fn_reads_from_samfile(bowtie_alignment_file, ref_vntr, true_reads)\n save_reads_stat(positive_file, positive_reads)\n save_reads_stat(false_negative_file, fn_reads)\n if gene_name == 'MAOA':\n os.system('cp %s /pedigree2/projects/VeNTeR/bowtie_alignment_%s.sam' % (bowtie_alignment_file, i))\n\n clean_up_tmp()\n\n\n\nfind_info_by_mapping('simulation_data/', int(sys.argv[1]))\n","sub_path":"src/compare_read_mapping_sensitivity.py","file_name":"compare_read_mapping_sensitivity.py","file_ext":"py","file_size_in_byte":7831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"260665952","text":"inputfile = \"C:\\\\Users\\\\jkearns\\\\Documents\\\\GitHub\\\\advent-of-code-2017\\\\04\\\\input04.txt\"\nwith open(inputfile) as f:\n phrases = f.readlines()\ntotal = len(phrases)\nvalid = 0\ninvalid = 0\nfor phrase in phrases:\n cleanphrase = phrase.strip('\\n')\n usedwords = []\n thisvalid = True\n for word in cleanphrase.split(' '):\n if word in usedwords:\n thisvalid = False\n usedwords.append(word)\n if thisvalid:\n valid += 1\n else:\n invalid += 1\n \nprint (\"{0} valid\".format(valid))\nprint (\"{0} invalid\".format(invalid))\nprint (\"{0} total\".format(total))","sub_path":"04/04a.py","file_name":"04a.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"111499778","text":"#import statements from ATT model\n\nfrom collections import defaultdict\nimport re\n\nfrom bs4 import BeautifulSoup\n\nimport sys\nimport os\n\nfrom bs4 import BeautifulSoup\n\nimport sys\nimport os\nos.environ['KERAS_BACKEND']='tensorflow'\n\nfrom tensorflow.keras.preprocessing.text import Tokenizer, text_to_word_sequence\n\nfrom tensorflow.keras import utils\nfrom tensorflow.keras.utils import to_categorical\n\nfrom tensorflow.keras.layers import Embedding\nfrom tensorflow.keras.layers import Dense, Input, Flatten\nfrom tensorflow.keras.layers import Conv1D, MaxPooling1D, Embedding, Concatenate, Dropout, LSTM, GRU, Bidirectional, TimeDistributed\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Attention\n\nfrom tensorflow.keras import backend as K\n\nfrom tensorflow.keras.layers import Layer, InputSpec\nfrom tensorflow.keras import initializers\n\n#import from OGmodel\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport tensorflow_datasets as tfds\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.utils import Sequence\nfrom sklearn.metrics import roc_curve, auc\nimport matplotlib.pyplot as plt\n\nMAX_SENT_LENGTH = 100\nMAX_NB_WORDS = 20000\nEMBEDDING_DIM = 100\nVALIDATION_SPLIT = 0.2\n\nwith open('data/y_train.pickle', 'rb') as handle:\n Y_train = pickle.load(handle)\nwith open('data/y_test.pickle', 'rb') as handle:\n Y_test = pickle.load(handle)\nwith open('data/y_valid.pickle', 'rb') as handle:\n Y_valid = pickle.load(handle)\n\nwith open('data/x_train.pickle', 'rb') as handle:\n X_train = pickle.load(handle)\nwith open('data/x_test.pickle', 'rb') as handle:\n X_test = pickle.load(handle)\nwith open('data/x_valid.pickle', 'rb') as handle:\n X_valid = pickle.load(handle)\nwith open('data/vocab_set.pickle', 'rb') as handle:\n vocabulary_set = pickle.load(handle)\nX_train = X_train[:500000]\nY_train = Y_train[:500000]\nX_test = X_test[:250000]\nY_test = Y_test[:250000]\nX_valid = X_valid[:250000]\nY_valid = Y_valid[:250000]\n\n# Encode training, valid and test instances\nencoder = tfds.features.text.TokenTextEncoder(vocabulary_set)\n\n# Model Definition\n\n\nclass AttLayer(Layer):\n def __init__(self, attention_dim):\n self.init = initializers.get('normal')\n self.supports_masking = True\n self.attention_dim = attention_dim\n super(AttLayer, self).__init__()\n\n def build(self, input_shape):\n assert len(input_shape) == 3\n self.W = K.variable(self.init((input_shape[-1], self.attention_dim)), name='W')\n self.b = K.variable(self.init((self.attention_dim, )), name='b')\n self.u = K.variable(self.init((self.attention_dim, 1)), name='u')\n self.tw = [self.W, self.b, self.u]\n super(AttLayer, self).build(input_shape)\n\n def compute_mask(self, inputs, mask=None):\n return None\n\n def call(self, x, mask=None):\n # size of x :[batch_size, sel_len, attention_dim]\n # size of u :[batch_size, attention_dim]\n # uit = tanh(xW+b)\n uit = K.tanh(K.bias_add(K.dot(x, self.W), self.b))\n ait = K.dot(uit, self.u)\n ait = K.squeeze(ait, -1)\n\n ait = K.exp(ait)\n\n if mask is not None:\n # Cast the mask to floatX to avoid float64 upcasting in theano\n ait *= K.cast(mask, K.floatx())\n ait /= K.cast(K.sum(ait, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n ait = K.expand_dims(ait)\n weighted_input = x * ait\n output = K.sum(weighted_input, axis=1)\n\n return output\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[-1])\n\ninputs = Input(shape=(None,), dtype='int32')\nembedding = Embedding(encoder.vocab_size, 128)(inputs)\nl_lstm = Bidirectional(LSTM(64, return_sequences=True))(embedding)\natt = Attention()([embedding,l_lstm])\nl_lstm2 = Bidirectional(LSTM(64))(embedding)\npreds = Dense(1, activation='sigmoid')(l_lstm2)\nmodel = Model(inputs, preds)\n\n#model = tf.keras.Sequential([\n# tf.keras.layers.Embedding(encoder.vocab_size, 64),\n# tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)),\n# tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n# tf.keras.layers.Dense(64, activation='relu'),\n# tf.keras.layers.Dropout(0.5),\n# tf.keras.layers.Dense(1, activation='sigmoid')\n#])\n\nmodel.compile(loss='binary_crossentropy',\n optimizer=tf.keras.optimizers.Adam(1e-4),\n metrics=['acc'])\n\nmodel.summary()\nbatch_size = 16\n\n# Building generators\nclass CustomGenerator(Sequence):\n def __init__(self, text, labels, batch_size, num_steps=None):\n self.text, self.labels = text, labels\n self.batch_size = batch_size\n self.len = np.ceil(len(self.text) / float(self.batch_size)).astype(np.int64)\n if num_steps:\n self.len = min(num_steps, self.len)\n def __len__(self):\n return self.len\n def __getitem__(self, idx):\n batch_x = self.text[idx * self.batch_size:(idx + 1) * self.batch_size]\n batch_y = self.labels[idx * self.batch_size:(idx + 1) * self.batch_size]\n return batch_x, batch_y\n\n\ntrain_gen = CustomGenerator(X_train, Y_train, batch_size)\nvalid_gen = CustomGenerator(X_valid, Y_valid, batch_size)\ntest_gen = CustomGenerator(X_test, Y_test, batch_size)\n\n\n\n\n# Training the model\ncheckpointer = ModelCheckpoint('data/models/model-{epoch:02d}-{val_loss:.5f}.hdf5',\n monitor='val_loss',\n verbose=1,\n save_best_only=True,\n mode='min')\n\ncallback_list = [checkpointer] #, , reduce_lr\nhis1 = model.fit_generator(\n generator=train_gen,\n epochs=1,\n validation_data=valid_gen)\n \n \n \n \npredIdxs = model.predict_generator(test_gen, verbose=1)\n\nfpr, tpr, _ = roc_curve(Y_test, predIdxs)\nroc_auc = auc(fpr, tpr)\n\nplt.figure()\nlw = 2\nplt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\n\nplt.savefig('auc_model.png')\n","sub_path":"ATT_train_and_test.py","file_name":"ATT_train_and_test.py","file_ext":"py","file_size_in_byte":6456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"21643691","text":"class Inference():\n\n # Variables to fill-in\n # nodes = None # dict of dicts\n # adjacency = None # dict of lists\n\n # graph = None\n\n partition_field = None\n\n c_label = None\n c_hat_label = None\n p_hat_label = None\n\n # collective = None\n # relational = None\n\n def __init__(self, graph, collective, relational):\n '''\n :param collective: the collective inference method to use\n :param relational: the relational classifer to use\n '''\n # print len(graph.vs)\n self.graph = graph.copy()\n\n # Add node ids\n # if 'id' not in self.graph.vs.attributes():\n self.graph.vs['id'] = range(self.graph.vcount())\n\n self.collective = collective\n self.relational = relational\n\n # def _update_nodes(self, update):\n # for u in update:\n # self.nodes[u[nid]] = u\n\n def learn(self, partition):\n # print partition\n # print len(self.graph.vs)\n nodes_p = self.graph.vs(partition_eq=partition)\n\n # Learning step\n # update = collective.learn(nodes_p, relational)\n # _update_nodes(update)\n\n self.collective.learn(self.graph, nodes_p, self.relational)\n\n def predict(self, partition):\n nodes_p = self.graph.vs(partition_eq=partition)\n\n # Prediction step\n # update = collective.predict(nodes_p, relational)\n # _update_nodes(update)\n\n self.collective.predict(self.graph, nodes_p, self.relational)\n","sub_path":"components/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"282416377","text":"import functools\nfrom typing import Callable, Dict, Any, Optional, TYPE_CHECKING\n\nfrom ray._private import signature\nfrom ray.workflow import serialization_context\nfrom ray.workflow.common import (\n Workflow,\n WorkflowData,\n StepType,\n WorkflowStepRuntimeOptions,\n validate_user_metadata,\n)\nfrom ray.workflow import workflow_context\nfrom ray.util.annotations import PublicAPI\n\nif TYPE_CHECKING:\n from ray.workflow.common import CheckpointModeType\n\n\ndef _inherit_checkpoint_option(checkpoint: \"Optional[CheckpointModeType]\"):\n # If checkpoint option is not specified, inherit checkpoint\n # options from context (i.e. checkpoint options of the outer\n # step). If it is still not specified, it's True by default.\n context = workflow_context.get_workflow_step_context()\n if checkpoint is None:\n if context is not None:\n return context.checkpoint_context.checkpoint\n if checkpoint is None:\n return True\n return checkpoint\n\n\nclass WorkflowStepFunction:\n \"\"\"This class represents a workflow step.\"\"\"\n\n def __init__(\n self,\n func: Callable,\n *,\n step_options: \"WorkflowStepRuntimeOptions\" = None,\n name: Optional[str] = None,\n metadata: Optional[Dict[str, Any]] = None,\n ):\n validate_user_metadata(metadata)\n self._func = func\n self._step_options = step_options\n self._func_signature = signature.extract_signature(func)\n self._name = name or \"\"\n self._user_metadata = metadata or {}\n\n # Override signature and docstring\n @functools.wraps(func)\n def _build_workflow(*args, **kwargs) -> Workflow:\n flattened_args = signature.flatten_args(self._func_signature, args, kwargs)\n\n def prepare_inputs():\n from ray.workflow.api import _ensure_workflow_initialized\n\n _ensure_workflow_initialized()\n return serialization_context.make_workflow_inputs(flattened_args)\n\n nonlocal step_options\n if step_options is None:\n step_options = WorkflowStepRuntimeOptions.make(\n step_type=StepType.FUNCTION\n )\n # We could have \"checkpoint=None\" when we use @workflow.step\n # with arguments. Avoid this by updating it here.\n step_options.checkpoint = _inherit_checkpoint_option(\n step_options.checkpoint\n )\n\n workflow_data = WorkflowData(\n func_body=self._func,\n inputs=None,\n step_options=step_options,\n name=self._name,\n user_metadata=self._user_metadata,\n )\n return Workflow(workflow_data, prepare_inputs)\n\n self.step = _build_workflow\n\n def __call__(self, *args, **kwargs):\n raise TypeError(\n \"Workflow steps cannot be called directly. Instead \"\n f\"of running '{self.step.__name__}()', \"\n f\"try '{self.step.__name__}.step()'.\"\n )\n\n @PublicAPI(stability=\"beta\")\n def options(\n self,\n *,\n max_retries: int = None,\n catch_exceptions: bool = None,\n name: str = None,\n metadata: Dict[str, Any] = None,\n allow_inplace: bool = None,\n checkpoint: \"Optional[CheckpointModeType]\" = None,\n **ray_options,\n ) -> \"WorkflowStepFunction\":\n \"\"\"This function set how the step function is going to be executed.\n\n Args:\n max_retries: num of retries the step for an application\n level error.\n catch_exceptions: Whether the user want to take care of the\n failure mannually.\n If it's set to be true, (Optional[R], Optional[E]) will be\n returned.\n If it's false, the normal result will be returned.\n name: The name of this step, which will be used to\n generate the step_id of the step. The name will be used\n directly as the step id if possible, otherwise deduplicated by\n appending .N suffixes.\n metadata: metadata to add to the step.\n allow_inplace: Execute the workflow step inplace.\n checkpoint: The option for checkpointing.\n **ray_options: All parameters in this fields will be passed\n to ray remote function options.\n\n Returns:\n The step function itself.\n \"\"\"\n validate_user_metadata(metadata)\n name = name if name is not None else self._name\n metadata = {**self._user_metadata, **(metadata if metadata is not None else {})}\n step_options = WorkflowStepRuntimeOptions.make(\n step_type=StepType.FUNCTION,\n catch_exceptions=catch_exceptions\n if catch_exceptions is not None\n else self._step_options.catch_exceptions,\n max_retries=max_retries\n if max_retries is not None\n else self._step_options.max_retries,\n allow_inplace=allow_inplace\n if allow_inplace is not None\n else self._step_options.allow_inplace,\n checkpoint=_inherit_checkpoint_option(checkpoint),\n ray_options={\n **self._step_options.ray_options,\n **(ray_options if ray_options is not None else {}),\n },\n )\n return WorkflowStepFunction(\n self._func, step_options=step_options, name=name, metadata=metadata\n )\n","sub_path":"python/ray/workflow/step_function.py","file_name":"step_function.py","file_ext":"py","file_size_in_byte":5520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"553670898","text":"import argparse\nimport numpy as np\nfrom pathlib import Path\n\nimport torch\nfrom torch import nn\n\nfrom model import CharRNN\nfrom common import one_hot_encode\n\n\n# Defining method to make mini-batches for training\ndef get_batches(arr, batch_size, seq_length):\n '''Create a generator that returns batches of size\n batch_size x seq_length from arr.\n\n Arguments\n ---------\n arr: Array you want to make batches from\n batch_size: Batch size, the number of sequences per batch\n seq_length: Number of encoded chars in a sequence\n '''\n\n batch_size_total = batch_size * seq_length\n\n # total number of batches we can make\n n_batches = len(arr) // batch_size_total\n\n # Keep only enough characters to make full batches\n arr = arr[:n_batches * batch_size_total]\n\n # Reshape into batch_size rows\n arr = arr.reshape((batch_size, -1))\n\n # iterate through the array, one sequence at a time\n for n in range(0, arr.shape[1], seq_length):\n\n # The features\n x = arr[:, n:n + seq_length]\n\n # The targets, shifted by one\n y = np.zeros_like(x)\n try:\n y[:, :-1], y[:, -1] = x[:, 1:], arr[:, n + seq_length]\n except IndexError:\n y[:, :-1], y[:, -1] = x[:, 1:], arr[:, 0]\n yield x, y\n\n\n# Declaring the train method\ndef train(net, data, epochs=10, batch_size=10, seq_length=50, lr=0.001, clip=5, val_frac=0.1, print_every=10):\n ''' Training a network \n\n Arguments\n ---------\n\n net: CharRNN network\n data: text data to train the network\n epochs: Number of epochs to train\n batch_size: Number of mini-sequences per mini-batch, aka batch size\n seq_length: Number of character steps per mini-batch\n lr: learning rate\n clip: gradient clipping\n val_frac: Fraction of data to hold out for validation\n print_every: Number of steps for printing training and validation loss\n\n '''\n net.train()\n\n opt = torch.optim.Adam(net.parameters(), lr=lr)\n criterion = nn.CrossEntropyLoss()\n\n # create training and validation data\n val_idx = int(len(data) * (1 - val_frac))\n data, val_data = data[:val_idx], data[val_idx:]\n\n if torch.cuda.is_available():\n net.cuda()\n\n counter = 0\n n_chars = len(net.chars)\n for e in range(epochs):\n\n # initialize hidden state\n h = net.init_hidden(batch_size)\n\n for x, y in get_batches(data, batch_size, seq_length):\n counter += 1\n\n # One-hot encode our data and make them Torch tensors\n x = one_hot_encode(x, n_chars)\n inputs, targets = torch.from_numpy(x), torch.from_numpy(y)\n\n if torch.cuda.is_available():\n inputs, targets = inputs.cuda(), targets.cuda()\n\n # Creating new variables for the hidden state, otherwise\n # we'd backprop through the entire training history\n h = tuple([each.data for each in h])\n\n # zero accumulated gradients\n net.zero_grad()\n\n # get the output from the model\n output, h = net(inputs, h)\n\n # calculate the loss and perform backprop\n loss = criterion(output, targets.view(batch_size * seq_length).long())\n loss.backward()\n\n # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.\n nn.utils.clip_grad_norm_(net.parameters(), clip)\n opt.step()\n\n # loss stats\n if counter % print_every == 0:\n\n # Get validation loss\n val_h = net.init_hidden(batch_size)\n val_losses = []\n net.eval()\n for x, y in get_batches(val_data, batch_size, seq_length):\n\n # One-hot encode our data and make them Torch tensors\n x = one_hot_encode(x, n_chars)\n x, y = torch.from_numpy(x), torch.from_numpy(y)\n\n # Creating new variables for the hidden state, otherwise\n # we'd backprop through the entire training history\n val_h = tuple([each.data for each in val_h])\n\n inputs, targets = x, y\n if torch.cuda.is_available():\n inputs, targets = inputs.cuda(), targets.cuda()\n\n output, val_h = net(inputs, val_h)\n val_loss = criterion(output, targets.view(batch_size * seq_length).long())\n\n val_losses.append(val_loss.item())\n\n net.train() # reset to train mode after iterationg through validation data\n\n print(\"Epoch: {}/{}...\".format(e + 1, epochs),\n \"Step: {}...\".format(counter),\n \"Loss: {:.4f}...\".format(loss.item()),\n \"Val Loss: {:.4f}\".format(np.mean(val_losses)))\n\n\nif __name__ == \"__main__\":\n\n # Parse command line arguments\n argparser = argparse.ArgumentParser()\n argparser.add_argument('corpus_path', type=Path)\n argparser.add_argument('--n_hidden', type=int, default=512)\n argparser.add_argument('--n_layers', type=int, default=2)\n argparser.add_argument('--batch_size', type=int, default=128)\n argparser.add_argument('--seq_length', type=int, default=100)\n argparser.add_argument('--n_epochs', type=int, default=2)\n args = argparser.parse_args()\n\n # read train corpus\n text = args.corpus_path.read_text(encoding=\"utf-8\")\n\n # encoding the text and map each character to an integer and vice versa\n # We create two dictionaries:\n # 1. int2char, which maps integers to characters\n # 2. char2int, which maps characters to integers\n chars = tuple(set(text))\n int2char = dict(enumerate(chars))\n char2int = {ch: ii for ii, ch in int2char.items()}\n\n # encode the text\n encoded = np.array([char2int[ch] for ch in text])\n\n # init model\n n_hidden = args.n_hidden\n n_layers = args.n_layers\n net = CharRNN(chars, n_hidden, n_layers)\n\n # declaring the hyperparameters\n batch_size = args.batch_size\n seq_length = args.seq_length\n n_epochs = args.n_epochs\n\n # train the model\n train(net, encoded, epochs=n_epochs, batch_size=batch_size, seq_length=seq_length, lr=0.001, print_every=50)\n\n # Saving the model\n model_name = f'rnn_{n_epochs}_epoch.net'\n\n checkpoint = {'n_hidden': net.n_hidden,\n 'n_layers': net.n_layers,\n 'state_dict': net.state_dict(),\n 'tokens': net.chars}\n\n with open(model_name, 'wb') as f:\n torch.save(checkpoint, f)\n","sub_path":"server/ml/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"530103678","text":"# Immutable Data Structures: Tuples #\nimport collections\nfrom pprint import pprint\n\nScientist = collections.namedtuple('Scientist', [\n 'name',\n 'field',\n 'born',\n 'nobel',\n])\n\nscientists = (\n Scientist(name='Ada Lovelace', field='math', born=1815, nobel=False),\n Scientist(name='Emmy Noether', field='math', born=1882, nobel=False),\n Scientist(name='Marie Curie', field='math', born=1867, nobel=True),\n Scientist(name='Tu Youyou', field='physics', born=1930, nobel=True),\n Scientist(name='Ada Yonath', field='chemistry', born=1939, nobel=True),\n Scientist(name='Vera Rubin', field='chemistry', born=1928, nobel=False),\n Scientist(name='Sally Ride', field='physics', born=1951, nobel=False),\n)\n\nname_and_age = tuple(map(\n lambda x: {\"name\": x.name, 'birth': x.born},\n scientists\n))\n\npprint(name_and_age)\npprint(tuple({'name': x.name, 'born': x.born} for x in scientists))\n","sub_path":"FREE/map2.py","file_name":"map2.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"324138669","text":"import media\nimport fresh_tomatoes\n\n# Declare lion_king instance\nlion_king = media.Movie(\"Lion King\",\n \"https://upload.wikimedia.org/wikipedia/en/\"\n \"3/3d/The_Lion_King_poster.jpg\",\n \"https://www.youtube.com/watch?v=4sj1MT05lAA\")\n\n# Declare toy story instance\ntoy_story = media.Movie(\"Toy Story\",\n \"https://upload.wikimedia.org/wikipedia/en/\"\n \"1/13/Toy_Story.jpg\",\n \"https://www.youtube.com/watch?v=KYz2wyBy3kc\")\n# Declare avatar instance\navatar = media.Movie(\"Avatar\",\n \"https://upload.wikimedia.org/wikipedia/en/\"\n \"b/b0/Avatar-Teaser-Poster.jpg\",\n \"https://www.youtube.com/watch?v=d1_JBMrrYw8\")\n\n# Declare school of rock instance\nschool_of_rock = media.Movie(\"School of Rock\",\n \"https://upload.wikimedia.org/wikipedia/en/\"\n \"1/11/School_of_Rock_Poster.jpg\",\n \"https://www.youtube.com/watch?v=XCwy6lW5Ixc\")\n\n# Declare wall e instance\nwall_e = media.Movie(\"Wall E\",\n \"https://upload.wikimedia.org/wikipedia/en/\"\n \"c/c2/WALL-Eposter.jpg\",\n \"https://www.youtube.com/watch?v=8-_9n5DtKOc\")\n\n# Declare ai instance\nai = media.Movie(\"AI\",\n \"https://upload.wikimedia.org/wikipedia/en/\"\n \"e/e6/AI_Poster.jpg\",\n \"https://www.youtube.com/watch?v=_19pRsZRiz4\")\n\n# Make movie list to be displayed\nmovies = [lion_king, toy_story, avatar, school_of_rock, wall_e, ai]\n\n# make a movies web page\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"204833470","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ___\n# \n# \n# ___\n\n# # NumPy Exercises \n# \n# Now that we've learned about NumPy let's test your knowledge. We'll start off with a few simple tasks, and then you'll be asked some more complicated questions.\n\n# #### Import NumPy as np\n\n# In[3]:\n\n\nimport numpy as np\n\n\n# #### Create an array of 10 zeros \n\n# In[3]:\n\n\nnp.zeros(10)\n\n\n# #### Create an array of 10 ones\n\n# In[4]:\n\n\nnp.ones(10)\n\n\n# #### Create an array of 10 fives\n\n# In[8]:\n\n\nnp.repeat(5, 10)\n\n\n# #### Create an array of the integers from 10 to 50\n\n# In[9]:\n\n\nnp.arange(10, 51)\n\n\n# #### Create an array of all the even integers from 10 to 50\n\n# In[13]:\n\n\nnp.arange(10, 51, 2)\n\n\n# #### Create a 3x3 matrix with values ranging from 0 to 8\n\n# In[18]:\n\n\narr1 = np.matrix([[0,1,2],[3,4,5],[6,7,8]])\narr1\n\n\n# #### Create a 3x3 identity matrix\n\n# In[19]:\n\n\nnp.eye(3, 3)\n\n\n# #### Use NumPy to generate a random number between 0 and 1\n\n# In[5]:\n\n\nrandom = np.random.rand(1)\nrandom\n\n\n# #### Use NumPy to generate an array of 25 random numbers sampled from a standard normal distribution\n\n# In[6]:\n\n\nnp.random.randn(25)\n\n\n# #### Create the following matrix:\n\n# In[7]:\n\n\nmatrix = np.arange(1,101)/100\nreshaped_matrix = matrix.reshape(10, 10)\nreshaped_matrix\n\n\n# #### Create an array of 20 linearly spaced points between 0 and 1:\n\n# In[42]:\n\n\nnp.linspace(0,1,20)\n\n\n# ## Numpy Indexing and Selection\n# \n# Now you will be given a few matrices, and be asked to replicate the resulting matrix outputs:\n\n# In[11]:\n\n\nmat = np.arange(1,26).reshape(5,5)\nmat\n\n\n# In[12]:\n\n\nmat[2:, 1:]\n\n\n# In[13]:\n\n\nmat[2:, 1:]\n\n\n# In[51]:\n\n\nmat[3][4]\n\n\n# In[67]:\n\n\nmat[3][4]\n\n\n# In[53]:\n\n\nmat[0:3, 1].reshape(3, 1)\n\n\n# In[69]:\n\n\nmat[0:3, 1].reshape(3, 1)\n\n\n# In[60]:\n\n\nmat[4]\n\n\n# In[70]:\n\n\nmat[4]\n\n\n# In[62]:\n\n\nmat[3:5]\n\n\n# In[71]:\n\n\nmat[3:5]\n\n\n# ### Now do the following\n\n# #### Get the sum of all the values in mat\n\n# In[14]:\n\n\nmat.sum()\n\n\n# #### Get the standard deviation of the values in mat\n\n# In[15]:\n\n\nmat.std()\n\n\n# #### Get the sum of all the columns in mat\n\n# In[16]:\n\n\nmat.sum(axis=0)\n\n\n# # Great Job!\n","sub_path":"Rajiv_Nair_Assignment2.py","file_name":"Rajiv_Nair_Assignment2.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"528250417","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Author: Dongdong Tian @ USTC\n#\n# Revision History:\n# 2014-09-03 Dongdong Tian Initial Coding\n# 2014-10-05 Dongdong Tian Fix bugs:\n# - handle datas with more than 2000000 points\n# - delimite components code with commas\n# 2014-11-01 Dongdong Tian Modify to fit new version of request script\n# 2015-03-21 Dongdong Tian Fix a bug when dirname contains underscore\n# 2015-05-18 Dongdong Tian Keep endian of SAC data same as current machine\n# 2015-06-05 Dongdong Tian Fix a bug with code 0103A and 0402A\n\n\"\"\"Extract SAC data files from NIED Hi-net WIN32 files\n\nUsage:\n rdhinet.py DIRNAME [-C ] [-D ] [-S ] [-P ]\n rdhinet.py -h\n\nOptions:\n -h Show this help.\n -C Components to extract, delimited using commas.\n Avaiable components are U, N, E, X, Y et. al.\n Default to extract all components.\n -D Output directory for SAC files.\n -S Suffix of output SAC files. Default: no suffix.\n -P Parallel using multiple processes.\n Set number of CPUs to if equals 0. [default: 0]\n\"\"\"\n\nimport os\nimport glob\nimport subprocess\nimport multiprocessing\n\nfrom docopt import docopt\n\n# external tools from Hi-net\nwin2sac = \"win2sac_32\"\n\n\ndef win_prm(chfile, prmfile=\"win.prm\"):\n \"\"\"four line parameters file\"\"\"\n\n with open(prmfile, \"w\") as f:\n f.write(\".\\n\")\n f.write(chfile + \"\\n\")\n f.write(\".\\n\")\n f.write(\".\\n\")\n\n\ndef get_chno(chfile, comps):\n \"\"\" read channel no list from channel table\"\"\"\n\n chno = []\n with open(chfile, \"r\") as f:\n for line in f:\n if line[0] == '#':\n continue\n\n items = line.split()\n no, comp = items[0], items[4]\n if comps is None or comp in comps:\n chno.append(no)\n\n print(\"Total %d channels\" % len(chno))\n return chno\n\n\ndef _extract_channel(tup):\n \"\"\"extract only one channel for one time\"\"\"\n\n winfile, chno, outdir, prmfile, pmax = tup\n # print(winfile, chno, outdir, prmfile, pmax)\n subprocess.call([win2sac,\n winfile,\n chno,\n \"SAC\",\n outdir,\n '-e',\n '-p'+prmfile,\n '-m'+str(pmax)\n ],\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL)\n\n\ndef win32_sac(winfile, ch_no, outdir=\".\", prmfile=\"win.prm\", pmax=2000000):\n\n tuple_list = []\n for ch in chno:\n t = winfile, ch, outdir, prmfile, pmax\n tuple_list.append(t)\n\n procs = int(arguments['-P'])\n\n if procs == 1:\n for t in tuple_list:\n _extract_channel(t)\n else:\n if procs == 0:\n procs = multiprocessing.cpu_count()\n else:\n procs = min(multiprocessing.cpu_count(), procs)\n\n pool = multiprocessing.Pool(processes=procs)\n pool.map(_extract_channel, tuple_list)\n\n\ndef rename_sac(dirname, outdir, sacfile=None):\n for file in glob.glob(os.path.join(dirname, \"*.SAC\")):\n dir, base = os.path.split(file)\n filename = os.path.splitext(base)[0]\n if sacfile:\n filename += \".\" + sacfile\n dest = os.path.join(outdir, filename)\n os.rename(file, dest)\n\n\nif __name__ == \"__main__\":\n arguments = docopt(__doc__)\n dirname = arguments['DIRNAME']\n\n chfile = glob.glob(os.path.join(dirname, \"*_????????.ch\"))[0]\n cntfile = glob.glob(os.path.join(dirname, \"*_????????????_*.cnt\"))[0]\n basename = os.path.basename(cntfile)\n span = int(os.path.splitext(basename)[0].split(\"_\")[2])\n\n # generate win32 paramerter file\n prmfile = os.path.join(dirname, \"win.prm\")\n win_prm(chfile, prmfile=prmfile)\n\n # get channel NO. lists for channel table\n comps = None\n if arguments['-C']:\n comps = arguments['-C'].split(\",\")\n chno = get_chno(chfile, comps)\n\n # maximum number of points\n pmax = span * 60 * 100 # assume data sample rate = 0.01\n # extrac sac files to dirname\n win32_sac(cntfile, chno, outdir=dirname, prmfile=prmfile, pmax=pmax)\n os.unlink(prmfile)\n\n # rename SAC files and move to outdir\n outdir = dirname\n if arguments['-D']:\n outdir = arguments['-D']\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n rename_sac(dirname, outdir, arguments['-S'])\n","sub_path":"rdhinet.py","file_name":"rdhinet.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"286283119","text":"from typing import IO, Any, Optional\n\nfrom .._protocol import ExtParams\nfrom .._util import assert_env_param_type, assert_opt_env_param_type, assert_param_type\nfrom .base import (\n ExtBlobStoreMessageWriter,\n ExtBlobStoreMessageWriterChannel,\n)\n\n\nclass ExtS3MessageWriter(ExtBlobStoreMessageWriter):\n # client is a boto3.client(\"s3\") object\n def __init__(self, client: Any, *, interval: float = 10):\n super().__init__(interval=interval)\n self._interval = assert_param_type(interval, float, self.__class__.__name__, \"interval\")\n # Not checking client type for now because it's a boto3.client object and we don't want to\n # depend on boto3.\n self._client = client\n\n def make_channel(\n self,\n params: ExtParams,\n ) -> \"ExtS3MessageChannel\":\n bucket = assert_env_param_type(params, \"bucket\", str, self.__class__)\n key_prefix = assert_opt_env_param_type(params, \"key_prefix\", str, self.__class__)\n return ExtS3MessageChannel(\n client=self._client,\n bucket=bucket,\n key_prefix=key_prefix,\n interval=self._interval,\n )\n\n\nclass ExtS3MessageChannel(ExtBlobStoreMessageWriterChannel):\n # client is a boto3.client(\"s3\") object\n def __init__(\n self, client: Any, bucket: str, key_prefix: Optional[str], *, interval: float = 10\n ):\n super().__init__(interval=interval)\n self._client = client\n self._bucket = bucket\n self._key_prefix = key_prefix\n\n def upload_messages_chunk(self, payload: IO, index: int) -> None:\n key = f\"{self._key_prefix}/{index}.json\" if self._key_prefix else f\"{index}.json\"\n self._client.put_object(\n Body=payload.read(),\n Bucket=self._bucket,\n Key=key,\n )\n","sub_path":"python_modules/dagster-ext/dagster_ext/_io/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"467391239","text":"#!/usr/bin/python3\n# pylint: disable=no-name-in-module\n\nimport numpy as np\nimport argparse\nfrom cv2 import circle, imread, imshow, waitKey, destroyAllWindows\nfrom numba import njit\n\n\ndef show(img, normalize=False, title='DEFAULT', delay=0):\n ''' Function for image display.\n TODO: Display accumulator option.\n '''\n\n imshow(title, img)\n waitKey(delay)\n destroyAllWindows()\n\n\ndef constructIndices(edges):\n ''' This function returns the indices of the non zero edges \n '''\n args = np.argwhere(edges > 0)\n I = args[:, 1]\n J = args[:, 0]\n return I, J\n\n\ndef findMaxima(hSpace, numOfMaxima, delta):\n ''' This function returns the local maximas of the accumulator.\n :param accum: The accumulator for the query image.\n :param delta: The radius around the local maxima to set to zero.\n :rtype: list(tuple) \n '''\n maxs = []\n\n for _ in range(numOfMaxima):\n\n mx = np.argwhere(hSpace == np.max(hSpace))[0]\n y, x = mx[0], mx[1]\n maxs.append((x, y))\n hSpace[y - delta: y + delta, x - delta: x + delta] = 0\n\n return maxs\n\n\n@njit\ndef checkBelongs(I, J, x_c, y_c, R):\n ''' This function find the indices that a point belongs to a circle.\n :param I: int[:] // Indicis of possible circle point \n :param x_c: int // x coordinates of the circle.\n :param R: int // radius of the circle.\n :rtype: int[:]\n\n '''\n d = (I - x_c) ** 2 + (J - y_c) ** 2\n return np.where(np.abs(d - R ** 2) < 1e-3, 1, 0)\n\n\n@njit(cache=True)\ndef constructAccum(I, J, R, shape):\n ''' This function construct the accumulator for a circle with radius R.\n :param shape: \n '''\n m, n = shape\n accum = np.zeros((m, n))\n for i in range(m):\n for j in range(n):\n accum[i, j] += np.sum(checkBelongs(I, J, j, i, R))\n return accum\n\n\ndef load_image(query_name):\n ''' Loads and displays query_image\n :params query_image: Path to the query image.\n '''\n query = imread(query_name, 0)\n\n if query is None:\n print(\"Can't find query image\")\n exit()\n\n img = 255 - query\n\n show(img, title='Query')\n\n return img\n\ndef search_for_circle(query_image, numOfObjects):\n ''' Loads the query_image, build the accumulator and finds local maxima.\n :params query_image: The query image.\n '''\n \n I, J = constructIndices(query_image)\n\n A = constructAccum(I, J, 58, query_image.shape)\n\n maxs = findMaxima(A, numOfObjects, 5)\n\n for mx in maxs:\n circle(query_image, mx, 58, (255, 255, 255), 3)\n\n show(query_image, title='Result')\n\n\n# We fix the radius to 58\ndef main():\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-i\", \"--input\", required = True, help = \"Path to the image\")\n ap.add_argument(\"-n\", \"--nmax\", required = True, help = \"Number of maximas\")\n\n args = vars(ap.parse_args())\n img = load_image(args['input'])\n search_for_circle(img, int(args['nmax']))\n\nif __name__ == \"__main__\":\n main()","sub_path":"circleHT/CircleHT.py","file_name":"CircleHT.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"509148812","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom setuptools import setup\nimport pkg_resources\nimport codecs\nimport fsaipe\n\n\nwith codecs.open('README.rst', encoding='utf-8') as f:\n long_description = f.read()\n\nwith open(\"requirements.txt\", \"r\") as f:\n install_requires = [str(req) for req in pkg_resources.parse_requirements(f)]\n\nsetup(\n name='saipe',\n version=fsaipe.__version__,\n license=\"Apache\",\n description='Flask SqlAlchemy In Place Editor',\n long_description=long_description,\n author='Gustavo vargas',\n author_email='xgvargas@gmail.com',\n url='https://github.com/xgvargas/saipe',\n # py_modules = ['saipe'],\n packages = ['fsaipe'],\n install_requires=install_requires,\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"451381687","text":"import math\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nprint(\"hello\")\n\n# read file 1\ndata_obs = open(\"observations.txt\")\nlines = data_obs.readlines()\ndata_obs.close()\n\nline1 = lines[0]\nline1 = line1.strip()\nline1 = line1.split()\nNumberNodes = int(line1[3])\nprint(NumberNodes)\n\n# read file 2\ndata_res = open(\"log_nodeResults.txt\")\nlines = data_res.readlines()\ndata_res.close()\n\nxs = []\nys = []\nfor i in range(NumberNodes):\n\txs.append([])\n\tys.append([])\n\n#IerationIDs = []\n#NodeIDs = []\n#nxs = []\n#nys = []\n#phases = []\ncounter = 0\nfor line in lines:\n\tline = line.strip()\n\teles = line.split()\n\tprint(eles)\n\n\tfor i in range(NumberNodes):\n\t\tID = i\n\t\txID = 0 + 2*i\n\t\tyID = 1 + 2*i\n\t\tx = float(eles[xID])\n\t\ty = float(eles[yID])\n\n\t\txs[ID].append(x)\n\t\tys[ID].append(y)\n\tcounter += 1\n\nprint(xs)\nprint()\nprint(ys)\n\nplt.plot(xs[0], ys[0], marker='o', mec='r', mfc='w',label='Iterations')\nplt.plot(xs[0][-1], ys[0][-1], marker='+', mec='r', mfc='w',label='Convergence Point')\nplt.plot(-57.24, 2.58, marker='v', mec='r', mfc='w',label='Ground Truth')\nplt.legend()\nplt.xlabel('X')\nplt.ylabel(\"Y\")\nplt.xlim(-65,-10)\nplt.ylim(-20,20)\nplt.title('Iteration Results')\n\nplt.savefig('test.png', format='png', bbox_inches='tight', transparent=True, dpi=600)\nplt.show()\n\n","sub_path":"ssl_rssi_2D_mapAndObstacles/analysis-attenuationAndPathLossExponent/analysis-nodes.py","file_name":"analysis-nodes.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"76921461","text":"import uavcan\nfrom contextlib import closing\nfrom MountControl import MountControl\nfrom utils import Tools \nimport cv2 as cv\nimport threading\nimport time \n\n'''\nshould handle timeout, when uav move route after 90s\n'''\n\n\nif __name__ == '__main__':\n\ttools = Tools('/home/mmc/tx2logs', usecam=False)\n\tuavcan.load_dsdl()\n\tnode_info = uavcan.protocol.GetNodeInfo.Response()\n\tnode_info.name = 'com.mmc.tx2'\n\t\t\n\tdirection = [[1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1], [0,-1], [1,-1]]\t\n\n\twith closing(uavcan.make_node('/dev/ttyACM0', node_id=20, bitrate=1000000, node_info=node_info)) as node:\n\t\t# init mount, task\n\t\tmount = MountControl(node)\n\n\t\tdef publisNodeInfo():\n\t\t\t# publish the uavcan node info\n\t\t\tmsg = uavcan.protocol.NodeStatus()\n\t\t\tnode.broadcast(msg)\n\t\t\n\t\tdef taskStart():\n\t\t\t# set num 3, if not detect the nodes, it will try three times\n\t\t\tnum = 3\n\t\t\twhile num != 0:\n\t\t\t\tnodes = tools.detect()\n\t\t\t\tcenterX, centerY = tools.getImgSize()\n\t\t\t\tcenterX = centerX / 2\n\t\t\t\tcenterY = centerY / 2\n\t\t\t\ttools.log('detect node length {}'.format(len(nodes)))\n\t\t\t\tif len(nodes) == 0:\n\t\t\t\t\tnum -= 1\n\t\t\t\t\tcontinue\n\t\t\t\telif len(nodes) > 0:\n\t\t\t\t\tconvNodes = tools.conversionCoordinates(nodes, centerX, centerY)\n\t\t\t\t\tfor one in convNodes:\n\t\t\t\t\t\tmount.mountPointMoveCtrl(one[0], one[1])()\n\t\t\t\t\t\tmount.waitForControlOver()\n\t\t\t\t\t\tmount.mountTakePicCtrl()\n\t\t\t\t\t\t# mount.takePhotoByZoom(zoom=4)\n\t\t\t\t\t\tmount.waitForControlOver()\n\t\t\t\t\t\tmount.mountPointMoveCtrl(-1*one[0], -1*one[1])()\n\t\t\t\t\t\tmount.waitForControlOver()\n\t\t\t\t\tbreak\n\t\tdef handleTx2Commond(event):\n\t\t\t# use the global parametet arrive, working\n\t\t\t# handle the tx2command request\n\t\t\t# if working reponse not ok, else response ok\n\t\t\tif event.request.magic_number != event.request.MAGIC_NUMBER or tools.isWorking():\n\t\t\t\treturn uavcan.thirdparty.mmc.Tx2Command.Response(ok=False)\n\t\t\telse:\n\t\t\t\t# if uav arrive, set arrive true and start work, then if uav arrive and working response not ok, if uav arrive and not working, response ok\n\t\t\t\tif event.request.cmd and not tools.isArrive():\n\t\t\t\t\ttools.setArrive(True)\n\t\t\t\t\ttools.setWorking(True)\n\t\t\t\t\t# start node detection right now\n\t\t\t\t\t# should edit !!!!\n\t\t\t\t\ttaskThread = threading.Thread(target=taskStart)\n\t\t\t\t\ttaskThread.start()\n\t\t\t\t\treturn uavcan.thirdparty.mmc.Tx2Command.Response(ok=True)\n\t\t\t\telif event.request.cmd and tools.isArrive():\n\t\t\t\t\tif tools.isWorking():\n\t\t\t\t\t\treturn uavcan.thirdparty.mmc.Tx2Command.Response(ok=False)\n\t\t\t\t\telse:\n\t\t\t\t\t\ttools.setArrive(False)\n\t\t\t\t\t\treturn uavcan.thirdparty.mmc.Tx2Command.Response(ok=True)\n\n\t\tnode.add_handler(uavcan.thirdparty.mmc.Tx2Command, handleTx2Commond)\n\t\tnode.add_handler(uavcan.thirdparty.mmc.Broadcast, mount.listenMountInfo)\n\t\t# every 0.5 second publish node info to all nodes\n\t\tnode.periodic(0.5, publisNodeInfo)\n\t\twhile True:\n\t\t\tnode.spin(0)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"138867373","text":"import time\nimport tensorflow as tf\nimport logging\nfrom v5 import config as cfg\nfrom v5.model import read_rec\nimport numpy as np\n# from tensorflow.contrib.rnn import LayerNormBasicLSTMCell, BasicRNNCell, GridLSTMCell, GRUCell, BasicLSTMCell\nfrom v5.model.bnlstm import BNLSTMCell\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%b %d %Y %H:%M:%S')\n\n\nclass LstmModel:\n def __init__(self, session):\n self.session = session\n self.right = 0\n self.samples = 0\n self.right_list = np.zeros([5])\n self.samples_list = np.zeros([5])\n self.w = {'fc_weight_1':\n tf.Variable(tf.truncated_normal([cfg.time_step * cfg.state_size, cfg.class_num], stddev=0.01, dtype=tf.float32), name='fc_weight_1'),\n }\n self.b = {'fc_bias_1':\n tf.Variable(tf.constant(0.01, dtype=tf.float32, shape=[cfg.class_num]), name='fc_bias_1'),\n }\n\n def build_graph(self):\n self.batch_data, self.batch_label = read_rec.read_and_decode(cfg.rec_file)\n self.rnn_keep_prop = cfg.rnn_keep_prop\n\n # multi_cell = tf.contrib.rnn.MultiRNNCell([BasicLSTMCell(cfg.state_size)] * cfg.hidden_layers)\n # cell = tf.contrib.rnn.DropoutWrapper(cell, input_keep_prob=1.0, output_keep_prob=self.rnn_keep_prop)\n multi_cell = tf.contrib.rnn.MultiRNNCell(\n [BNLSTMCell(cfg.state_size, training=True) for _ in range(cfg.hidden_layers)])\n state_init = multi_cell.zero_state(cfg.batch_size, dtype=tf.float32)\n val, self.states = tf.nn.dynamic_rnn(multi_cell, self.batch_data, initial_state=state_init, dtype=tf.float32)\n\n \"\"\"reshape the RNN output\"\"\"\n # val = tf.transpose(val, [1, 0, 2])\n # self.val = tf.gather(val, val.get_shape()[0] - 1)\n dim = cfg.time_step * cfg.state_size\n self.val = tf.reshape(val, [-1, dim])\n\n\n self.logits = tf.nn.xw_plus_b(self.val, self.w['fc_weight_1'], self.b['fc_bias_1'])\n\n self.cross_entropy = tf.reduce_mean(\n tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.logits, labels=self.batch_label, name=\"cross_entropy\"))\n\n \"\"\"Loss function and Optimizer\"\"\"\n global_step = tf.get_variable('global_step', shape=[], dtype=tf.int64,\n initializer=tf.zeros_initializer(),\n trainable=False)\n self.poly_decay_lr = tf.train.polynomial_decay(learning_rate=cfg.learning_rate,\n global_step=global_step,\n decay_steps=cfg.decay_steps,\n end_learning_rate=0.0002,\n power=cfg.power)\n weight = [v for _, v in self.w.items()]\n norm = tf.add_n([tf.nn.l2_loss(i) for i in weight])\n self.minimize = tf.train.MomentumOptimizer(\n learning_rate=self.poly_decay_lr, momentum=cfg.momentum).\\\n minimize(self.cross_entropy + cfg.weght_decay * norm, global_step=global_step)\n\n \"\"\"saver\"\"\"\n self.saver = tf.train.Saver()\n\n def save_model(self):\n save_time = time.strftime(\"%Y-%m-%d-%H-%M\", time.localtime())\n self.saver.save(self.session, \"../log/train/%s.ckpt\" % save_time)\n logging.info(\"save file time: %s\", save_time)\n\n def train_model(self):\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=self.session, coord=coord)\n for i in range(cfg.iter_num):\n _, logits, labels = self.session.run([self.minimize, self.logits, self.batch_label])\n # print(logits)\n self.acc_dist(logits, labels, i)\n if (i + 1) % 20 == 0:\n ce, lr = self.session.run([self.cross_entropy, self.poly_decay_lr])\n logging.info(\"%d th iter, cross_entropy == %s, learning rate == %s\", i, ce, lr)\n logging.info('accuracy == %s', self.right_list / self.samples_list)\n logging.info('samples distribute == %s', self.samples_list)\n self.right_list = np.zeros([5])\n self.samples_list = np.zeros([5])\n if (i + 1) % 5000 == 0:\n self.save_model()\n\n # self.save_model()\n coord.request_stop()\n coord.join(threads=threads)\n\n def acc(self, logits, label, gs):\n max_idx = np.argmax(logits, axis=1)\n # if (gs + 1) % 20 == 0:\n # print(np.count_nonzero(max_idx == 1))\n # print(np.count_nonzero(label == 1))\n # print('--------------')\n equal = np.sum(np.equal(max_idx, label).astype(int))\n self.right += equal\n self.samples += cfg.batch_size\n\n def acc_dist(self, logits, labels, gs):\n max_idx = np.argmax(logits, axis=1)\n if (gs + 1) % 20 == 0:\n print(np.count_nonzero(max_idx))\n print(np.count_nonzero(labels))\n print('--------------')\n threshold = np.arange(0.5, 1, 0.1)\n max = np.max(logits, axis=1, keepdims=True)\n prob = np.exp(logits - max) / np.sum(np.exp(logits - max), axis=1, keepdims=True)\n b_labels = labels.astype(bool)[:, np.newaxis]\n b_idx = np.concatenate((~b_labels, b_labels), axis=1)\n target = b_idx.astype(int)\n for i, t in enumerate(threshold):\n bool_index = prob > t\n self.samples_list[i] += np.count_nonzero(bool_index)\n self.right_list[i] += np.count_nonzero(target[bool_index])\n\n\n\ndef run():\n with tf.Graph().as_default(), tf.Session() as session:\n lstmModel = LstmModel(session)\n lstmModel.build_graph()\n \"\"\"init variables\"\"\"\n if cfg.ckpt_file is None:\n logging.info(\"init all variables by random\")\n lstmModel.session.run(tf.global_variables_initializer())\n else:\n logging.info(\"init all variables by previous file\")\n lstmModel.saver.restore(lstmModel.session, cfg.ckpt_file)\n lstmModel.train_model()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"v5/model/model_val.py","file_name":"model_val.py","file_ext":"py","file_size_in_byte":6230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"475337770","text":"import falcon\nfrom trex.handlers.abstract_handler import AbstractHandler\n\n\nclass Authentication(object):\n \"\"\"\n Authentication middleware used for authenticating individual requests.\n \"\"\"\n\n def process_resource(self, req, resp, resource):\n \"\"\"\n Authenticates the request by retrieving the authentication service off of the resource.\n\n :param req: The request object\n :type req: falcon.Request\n\n :param resp: The response object\n :type resp: falcon.Response\n \"\"\"\n assert isinstance(req, falcon.Request)\n assert isinstance(resp, falcon.Response)\n\n if req.method != 'OPTIONS':\n if resource:\n assert isinstance(resource, AbstractHandler), type(resource)\n resource.authenticate(req)\n else:\n assert resource is None\n raise falcon.HTTPNotFound()\n else:\n assert req.method == 'OPTIONS'\n","sub_path":"trex/system/middleware/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"555226025","text":"import statistics\r\nimport csv\r\n\r\nGENDER = 0\r\nHEIGHT = 1\r\nWEIGHT = 2\r\n\r\ndef readnumbertxt(n_file):\r\n\tfile = open(n_file, 'r')\r\n\tnumbers = []\r\n\tfor x in file:\r\n\t\tnumbers.append(int(x))\r\n\t\tfile.close()\r\n\treturn numbers\r\n\r\ndef variance(numbers):\r\n\tmean = statistics.mean(numbers)\r\n\ttotal = 0\r\n\tfor y in numbers:\r\n\t\ttotal+=((y-mean)**2)\r\n\treturn total/len(numbers)\r\n\r\ndef standard_deviation(var):\r\n\treturn var ** 0.5\r\n\r\ndef weightheight(wh_file):\r\n\twith open(wh_file,'r') as f:\r\n\t\treader = csv.reader(f)\r\n\t\tnext(reader)\r\n\t\twh = []\r\n\t\tfor x in reader:\r\n\t\t\twh.append(x)\r\n\treturn wh\r\n\r\ndef get_gwh(data):\r\n\tgender = []\r\n\theight = []\r\n\tweight = []\r\n\tfor d in data:\r\n\t\theight.append(float(d[HEIGHT]))\r\n\t\tweight.append(float(d[WEIGHT]))\r\n\t\tgender.append(d[GENDER])\r\n\r\n\treturn gender, height, weight\r\n\r\n\r\ndata = weightheight(\"weight-height.csv\")\r\n\r\ng, h, w = get_gwh(data)\r\n\r\nmean_h = statistics.mean(h)\r\nmean_w = statistics.mean(w)\r\nstd_h = standard_deviation(variance(h))\r\nstd_w = standard_deviation(variance(w))\r\n\r\ncounter = 0\r\n\r\ndef report(counter, stats):\r\n\tif anoms[0] == None:\r\n\t\tprint(\"ANOMALY! (%s) > weight: %f\" % (','.join(data[counter]),anoms[1]))\r\n\telif anoms[1] == None:\r\n\t\tprint(\"ANOMALY! (%s) > height: %f\" % (','.join(data[counter]),anoms[0]))\r\n\telse:\r\n\t\tprint(\"ANOMALY! (%s) > height: %f, weight: %f\" % (','.join(data[counter]),anoms[1],anoms[0]))\r\n\r\nfor d in data:\r\n\tweight = float(d[WEIGHT])\r\n\theight = float(d[HEIGHT])\r\n\tanoms = [None,None]\r\n\r\n\tif weight > mean_w + (2.5 * std_w) or weight < mean_w - (2.5 * std_w):\r\n\t\tanoms[1]=weight\r\n\r\n\tif height > mean_h + (2.5 * std_h) or height < mean_h - (2.5 * std_h):\r\n\t\tanoms[0]=height\r\n\r\n\tif anoms[0] or anoms[1]:\r\n\t\treport(counter,anoms)\r\n\r\n\t\tcounter = counter + 1\r\n\r\n\r\n\r\n# ANOMALY! (MALE, 76.4, 122.3) > height: 122.3\r\n# ANOMALY! (MALE, 76.4, 122.3) > weight: 76.4,\r\n# ANOMALY! (MALE, 76.4, 122.3) > weight: 76.4, height: 122.3","sub_path":"python_7.py","file_name":"python_7.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"373136820","text":"from __future__ import absolute_import, unicode_literals\n\nimport os.path\nimport os\nimport unittest\n\nfrom betamax import Betamax\nfrom betamax_serializers import pretty_json\nimport github3\n\nfrom mozvcssync.github_pr import GitHubPR\n\nHERE = os.path.abspath(os.path.dirname(__file__))\nAUTH_TOKEN = os.environ.get('GH_AUTH_TOKEN', 'x' * 20)\n\n\nBetamax.register_serializer(pretty_json.PrettyJSONSerializer)\nwith Betamax.configure() as config:\n config.cassette_library_dir = os.path.join(HERE, 'cassettes')\n config.default_cassette_options['serialize_with'] = 'prettyjson'\n config.define_cassette_placeholder(b'', AUTH_TOKEN)\n config.default_cassette_options['record_mode'] = os.environ.get(\n 'BETMAX_RECORD_MODE', 'once')\n\n\nclass TestGithubPR(unittest.TestCase):\n def setUp(self):\n self.github = github3.GitHub()\n self.session = self.github._session\n self.configure_session(self.session)\n self.recorder = Betamax(self.session)\n with self.recorder.use_cassette('github-pr-initialization'):\n self.ghpr = GitHubPR(\n AUTH_TOKEN, 'servo/servo', '', github=self.github)\n\n def configure_session(self, session):\n \"\"\"Configure a requests session for testing.\"\"\"\n session.headers.update({'Accept-Encoding': 'identity'})\n\n def test_upstream_repo_missing(self):\n self.ghpr.upstream_user = \"auserwhichdoesntexist\"\n self.ghpr.repo_name = \"arepowhichdoesntexist\"\n\n with self.recorder.use_cassette('github-pr-upstream-no-repo'):\n with self.assertRaises(Exception) as context:\n self.ghpr.upstream_repo()\n\n self.assertTrue(\n b'failed to find github repo' in str(context.exception))\n\n def test_upstream_repo_exists(self):\n with self.recorder.use_cassette('github-pr-upstream-repo'):\n upstream = self.ghpr.upstream_repo()\n\n assert upstream.full_name == 'servo/servo'\n","sub_path":"vcssync/tests/test-github-pr.py","file_name":"test-github-pr.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"265558957","text":"from ..models.buyer import *\nfrom catalog.serializers.category import serialize_categories\nfrom catalog.serializers.product import serialize_product\nfrom address.serializers.state import serialize_state\nfrom .businesstype import serialize_business_type\nimport time\nimport jwt as JsonWebToken\nimport settings\nfrom scripts.utils import getTimeStamp\n\ndef serialize_buyer(buyer_entry, parameters = {}):\n\n\tbuyer = {}\n\n\tbuyer[\"buyerID\"] = buyer_entry.id\n\tbuyer[\"name\"] = buyer_entry.name\n\tbuyer[\"whatsapp_contact_name\"] = buyer_entry.whatsapp_contact_name\n\tbuyer[\"company_name\"] = buyer_entry.company_name\n\tbuyer[\"mobile_number\"] = buyer_entry.mobile_number\n\tbuyer[\"whatsapp_number\"] = buyer_entry.whatsapp_number\n\tif buyer_entry.email == None:\n\t\tbuyer[\"email\"] = \"\"\n\telse:\n\t\tbuyer[\"email\"] = buyer_entry.email\n\tbuyer[\"alternate_phone_number\"] = buyer_entry.alternate_phone_number\n\tbuyer[\"mobile_verification\"] = buyer_entry.mobile_verification\n\tbuyer[\"email_verification\"] = buyer_entry.email_verification\n\tbuyer[\"whatsapp_sharing_active\"] = buyer_entry.whatsapp_sharing_active\n\tbuyer[\"gender\"] = buyer_entry.gender\n\tbuyer[\"created_at\"] = buyer_entry.created_at\n\tbuyer[\"updated_at\"] = buyer_entry.updated_at\n\tbuyer[\"buyer_panel_url\"] = str(buyer_entry.id) + \"-\" + str(int(time.mktime(buyer_entry.created_at.timetuple())))\n\tbuyer[\"store_url\"] = buyer_entry.store_url\n\tbuyer[\"store_global_margin\"] = buyer_entry.store_global_margin\n\t\n\tif \"buyer_details_details\" in parameters and parameters[\"buyer_details_details\"] == 1 and hasattr(buyer_entry,'buyerdetails'):\n\t\tbuyer_details = {}\n\t\tbuyer_details[\"detailsID\"] = buyer_entry.buyerdetails.id\n\t\tbuyer_details[\"vat_tin\"] = buyer_entry.buyerdetails.vat_tin\n\t\tbuyer_details[\"cst\"] = buyer_entry.buyerdetails.cst\n\t\tbuyer_details[\"customer_type\"] = buyer_entry.buyerdetails.customer_type\n\t\tbuyer_details[\"buying_capacity\"] = buyer_entry.buyerdetails.buying_capacity\n\t\tbuyer_details[\"purchase_duration\"] = buyer_entry.buyerdetails.purchase_duration\n\t\tif hasattr(buyer_entry.buyerdetails, \"buyer_type\") and buyer_entry.buyerdetails.buyer_type != None:\n\t\t\tbuyer_details[\"buyer_type\"] = serialize_business_type(buyer_entry.buyerdetails.buyer_type)\n\t\telse:\n\t\t\tbuyer_details[\"buyer_type\"] = {}\n\n\t\tbuyer[\"details\"] = buyer_details\n\n\tif \"buyer_interest_details\" in parameters and parameters[\"buyer_interest_details\"] == 1:\n\t\tbuyerInterestQuerySet = filterBuyerInterest(parameters)\n\t\tbuyerInterestQuerySet = buyerInterestQuerySet.filter(buyer_id = buyer_entry.id)\n\t\tbuyer[\"buyer_interests\"] = parse_buyer_interest(buyerInterestQuerySet,parameters)\n\n\tif \"buyer_product_details\" in parameters and parameters[\"buyer_product_details\"] == 1:\n\t\ttempParameters = parameters.copy()\n\t\ttempParameters[\"buyer_interest_active\"] = True\n\t\ttempParameters[\"buyer_product_delete_status\"] = False\n\t\ttempParameters[\"buyer_product_is_active\"] = True\n\t\ttempParameters[\"responded\"] = 0\n\t\ttempParameters[\"buyer_product_shared_on_whatsapp\"] = False\n\t\tbuyerProductQuerySet = filterBuyerProducts(tempParameters)\n\t\tbuyerProductQuerySet = buyerProductQuerySet.filter(buyer_id = buyer_entry.id)\n\t\tbuyerProductQuerySet = buyerProductQuerySet[:parameters[\"buyer_product_count\"]]\n\t\tbuyer[\"buyer_products\"] = parse_buyer_product(buyerProductQuerySet,parameters)\n\n\tif \"buyer_address_details\" in parameters and parameters[\"buyer_address_details\"] == 1:\n\t\tbuyer_addresses_queryset = BuyerAddress.objects.filter(buyer_id = buyer_entry.id)\n\t\tbuyer_addresses = parse_buyer_address(buyer_addresses_queryset, parameters)\n\t\tbuyer[\"address\"] = buyer_addresses\n\n\tif \"buyer_purchasing_state_details\" in parameters and parameters[\"buyer_purchasing_state_details\"] == 1:\n\t\tbuyer_purchasing_state_queryset = filterBuyerPurchasingState(parameters)\n\t\tbuyer_purchasing_state_queryset = buyer_purchasing_state_queryset.filter(buyer_id=buyer_entry.id)\n\t\tbuyer_purchasing_state = parse_buyer_purchasing_state(buyer_purchasing_state_queryset, parameters)\n\t\tbuyer[\"purchasing_states\"] = buyer_purchasing_state\n\n\tif \"buyer_buys_from_details\" in parameters and parameters[\"buyer_buys_from_details\"] == 1:\n\t\tbuyer_buys_from_queryset = filterBuyerBuysFrom(parameters)\n\t\tbuyer_buys_from_queryset = buyer_buys_from_queryset.filter(buyer_id=buyer_entry.id)\n\t\tbuyer_buys_from = parse_buyer_buys_from(buyer_buys_from_queryset, parameters)\n\t\tbuyer[\"buys_from\"] = buyer_buys_from\n\n\treturn buyer\n\ndef serialize_buyer_registration(buyer_registration_entry, parameters = {}):\n\n\tbuyer_registration = {}\n\n\ttokenPayload = {\n\t\t\"exp\": buyer_registration_entry.getExpiryTimeStamp(),\n\t\t\"iat\": getTimeStamp(buyer_registration_entry.created_at),\n\t\t\"sub\":\"buyer registration\",\n\t\t\"jti\": buyer_registration_entry.id\n\t}\n\n\tencoded = JsonWebToken.encode(tokenPayload, settings.SECRET_KEY, algorithm='HS256')\n\t\n\tbuyer_registration[\"registration_token\"] = encoded\n\n\treturn buyer_registration\n\ndef serialize_buyer_refresh_token(buyer_refresh_token_entry, parameters = {}):\n\n\ttokenPayload = {\n\t\t\"exp\": buyer_refresh_token_entry.getExpiryTimeStamp(),\n\t\t\"iat\": getTimeStamp(buyer_refresh_token_entry.created_at),\n\t\t\"sub\":\"buyer refresh token\",\n\t\t\"jti\": buyer_refresh_token_entry.id,\n\t\t\"user\":\"buyer\",\n\t\t\"buyerID\":buyer_refresh_token_entry.buyer_id,\n\t}\n\n\tencoded = JsonWebToken.encode(tokenPayload, settings.SECRET_KEY, algorithm='HS256')\n\n\treturn encoded\n\ndef serialize_buyer_forgot_password_token(buyer_forgot_password_token_entry, parameters = {}):\n\n\tbuyer_forgot_password = {}\n\n\ttokenPayload = {\n\t\t\"exp\": buyer_forgot_password_token_entry.getExpiryTimeStamp(),\n\t\t\"iat\": getTimeStamp(buyer_forgot_password_token_entry.created_at),\n\t\t\"sub\":\"buyer forgot password\",\n\t\t\"jti\": buyer_forgot_password_token_entry.id,\n\t\t\"user\":\"buyer\",\n\t}\n\n\tencoded = JsonWebToken.encode(tokenPayload, settings.SECRET_KEY, algorithm='HS256')\n\n\tbuyer_forgot_password[\"forgot_password_token\"] = encoded\n\n\treturn buyer_forgot_password\n\ndef serialize_buyer_access_token(buyer_access_token_entry, parameters = {}):\n\n\ttokenPayload = {\n\t\t\"exp\": buyer_access_token_entry.getExpiryTimeStamp(),\n\t\t\"iat\": getTimeStamp(buyer_access_token_entry.created_at),\n\t\t\"sub\":\"buyer access token\",\n\t\t\"jti\": buyer_access_token_entry.id,\n\t\t\"buyerID\":buyer_access_token_entry.buyer_id,\n\t\t\"user\":\"buyer\"\n\t}\n\n\tencoded = JsonWebToken.encode(tokenPayload, settings.SECRET_KEY, algorithm='HS256')\n\n\treturn encoded\n\ndef parse_buyer_address(buyer_addresses_queryset, parameters = {}):\n\n\tbuyer_addresses =[]\n\n\tfor buyer_address in buyer_addresses_queryset:\n\n\t\tbuyer_address_entry = serialize_buyer_address(buyer_address, parameters)\n\t\tbuyer_addresses.append(buyer_address_entry)\n\n\treturn buyer_addresses\n\ndef serialize_buyer_address(buyer_address, parameters = {}):\n\tbuyer_address_entry = {\n\t\t\"addressID\" : buyer_address.id,\n\t\t\"buyerID\" : buyer_address.buyer_id,\n\t\t\"address\" : buyer_address.address_line,\n\t\t\"landmark\" : buyer_address.landmark,\n\t\t\"city\" : buyer_address.city_name,\n\t\t\"state\" : buyer_address.state_name,\n\t\t\"country\" : buyer_address.country_name,\n\t\t\"contact_number\" : buyer_address.contact_number,\n\t\t\"pincode\" : buyer_address.pincode_number,\n\t\t\"priority\" : buyer_address.priority,\n\t\t\"pincodeID\":buyer_address.pincode_id,\n\t\t\"alias\":buyer_address.alias,\n\t\t\"client_id\":buyer_address.client_id,\n\t\t\"created_at\":buyer_address.created_at,\n\t\t\"updated_at\":buyer_address.updated_at\n\t}\n\treturn buyer_address_entry\n\ndef parse_buyer(buyers_queryset, parameters = {}):\n\n\tbuyers = []\n\n\tfor buyer in buyers_queryset:\n\t\tbuyer_entry = serialize_buyer(buyer, parameters)\n\t\tbuyers.append(buyer_entry)\n\n\treturn buyers\n\ndef parse_buyer_shared_product_id(buyers_queryset, parameters = {}):\n\n\tbuyers = []\n\n\tfor buyer in buyers_queryset:\n\t\tbuyer_entry = serialize_buyer_shared_product_id(buyer, parameters)\n\t\tbuyers.append(buyer_entry)\n\n\treturn buyers\n\ndef serialize_buyer_shared_product_id(buyer_shared_product_id_entry, parameters = {}):\n\tbuyer_shared_product_id = {}\n\n\tbuyer_shared_product_id[\"buyersharedproductID\"] = buyer_shared_product_id_entry.id\n\tbuyer_shared_product_id[\"buyerID\"] = buyer_shared_product_id_entry.buyer_id\n\tbuyer_shared_product_id[\"productID\"] = buyer_shared_product_id_entry.productid_filter_text\n\tbuyer_shared_product_id[\"created_at\"] = buyer_shared_product_id_entry.created_at\n\tbuyer_shared_product_id[\"updated_at\"] = buyer_shared_product_id_entry.updated_at\n\tbuyer_shared_product_id[\"delete_status\"] = buyer_shared_product_id_entry.delete_status\n\n\treturn buyer_shared_product_id\n\n\ndef parse_buyer_interest(buyer_interests_queryset, parameters = {}):\n\n\tbuyer_interests = []\n\n\tfor buyer_interest in buyer_interests_queryset:\n\t\tbuyer_interest_entry = serialize_buyer_interest(buyer_interest, parameters)\n\t\tbuyer_interests.append(buyer_interest_entry)\n\n\treturn buyer_interests\n\ndef serialize_buyer_interest(buyer_interest_entry, parameters = {}):\n\n\tbuyer_interest = {}\n\n\tbuyer_interest[\"buyerinterestID\"] = buyer_interest_entry.id\n\tbuyer_interest[\"categoryID\"] = buyer_interest_entry.category_id\n\tbuyer_interest[\"scale\"] = buyer_interest_entry.scale\n\tbuyer_interest[\"price_filter_applied\"] = buyer_interest_entry.price_filter_applied\n\tbuyer_interest[\"min_price_per_unit\"] = buyer_interest_entry.min_price_per_unit\n\tbuyer_interest[\"max_price_per_unit\"] = buyer_interest_entry.max_price_per_unit\n\tbuyer_interest[\"fabric_filter_text\"] = buyer_interest_entry.fabric_filter_text\n\tbuyer_interest[\"productid_filter_text\"] = buyer_interest_entry.productid_filter_text\n\tbuyer_interest[\"is_active\"] = bool(buyer_interest_entry.is_active)\n\tbuyer_interest[\"created_at\"] = buyer_interest_entry.created_at\n\tbuyer_interest[\"updated_at\"] = buyer_interest_entry.updated_at\n\n\tif not (\"category_details_details\" in parameters and parameters[\"category_details_details\"] == 1):\n\t\tbuyer_interest[\"category\"] = serialize_categories(buyer_interest_entry.category)\n\n\treturn buyer_interest\n\ndef parse_buyer_product(buyer_products_queryset, parameters = {}):\n\n\tbuyer_products = []\n\n\tfor buyer_product in buyer_products_queryset:\n\t\tbuyer_product_entry = serialize_buyer_product(buyer_product, parameters)\n\t\tbuyer_products.append(buyer_product_entry)\n\n\treturn buyer_products\n\ndef parse_buyer_product_response(buyer_products_queryset, parameters = {}):\n\n\tbuyer_products = []\n\n\tfor buyer_product in buyer_products_queryset:\n\t\tbuyer_product_entry = serialize_buyer_product_response(buyer_product, parameters)\n\t\tbuyer_products.append(buyer_product_entry)\n\n\treturn buyer_products\n\ndef serialize_buyer_product(buyer_product_entry, parameters = {}):\n\n\tbuyer_product = {}\n\n\tbuyer_product[\"buyerproductID\"] = buyer_product_entry.id\n\tbuyer_product[\"buyerID\"] = buyer_product_entry.buyer_id\n\tif hasattr(buyer_product_entry,\"buyer_interest\"):\n\t\tbuyer_product[\"buyerinterestID\"] = buyer_product_entry.buyer_interest_id\n\tbuyer_product[\"is_active\"] = bool(buyer_product_entry.is_active)\n\tbuyer_product[\"responded\"] = buyer_product_entry.responded\n\tbuyer_product[\"created_at\"] = buyer_product_entry.created_at\n\tbuyer_product[\"updated_at\"] = buyer_product_entry.updated_at\n\t\n\tif \"product_details\" in parameters and parameters[\"product_details\"] == 1:\n\t\tbuyer_product[\"product\"] = serialize_product(buyer_product_entry.product, parameters)\n\telse:\n\t\tproduct = {}\n\t\tproduct[\"productID\"] = buyer_product_entry.product.id\n\t\tproduct[\"display_name\"] = buyer_product_entry.product.display_name\n\t\tproduct[\"min_price_per_unit\"] = buyer_product_entry.product.min_price_per_unit\n\t\tbuyer_product[\"product\"] = product\n\n\treturn buyer_product\n\ndef serialize_buyer_product_response(buyer_product_entry, parameters = {}):\n\n\tbuyer_product = {}\n\n\tbuyer_product[\"buyerproductresponseID\"] = buyer_product_entry.id\n\tbuyer_product[\"buyerID\"] = buyer_product_entry.buyer_id\n\tbuyer_product[\"buyerproductID\"] = buyer_product_entry.buyer_product_id\n\tbuyer_product[\"response_code\"] = buyer_product_entry.response_code\n\tbuyer_product[\"has_swiped\"] = int(buyer_product_entry.has_swiped)\n\tbuyer_product[\"responded_from\"] = buyer_product_entry.responded_from\n\tbuyer_product[\"created_at\"] = buyer_product_entry.created_at\n\tbuyer_product[\"updated_at\"] = buyer_product_entry.updated_at\n\tbuyer_product[\"store_margin\"] = buyer_product_entry.store_margin\n\t\n\tif \"product_details\" in parameters and parameters[\"product_details\"] == 1:\n\t\tbuyer_product[\"product\"] = serialize_product(buyer_product_entry.product, parameters)\n\telse:\n\t\tproduct = {}\n\t\tproduct[\"productID\"] = buyer_product_entry.product.id\n\t\tproduct[\"display_name\"] = buyer_product_entry.product.display_name\n\t\tproduct[\"min_price_per_unit\"] = buyer_product_entry.product.min_price_per_unit\n\t\tbuyer_product[\"product\"] = product\n\n\treturn buyer_product\n\ndef parse_buyer_purchasing_state(buyer_purchasing_states_queryset, parameters = {}):\n\n\tbuyer_purchasing_states =[]\n\n\tfor buyer_purchasing_state in buyer_purchasing_states_queryset:\n\n\t\tbuyer_purchasing_state_entry = serialize_buyer_purchasing_state(buyer_purchasing_state, parameters)\n\t\tbuyer_purchasing_states.append(buyer_purchasing_state_entry)\n\n\treturn buyer_purchasing_states\n\ndef serialize_buyer_purchasing_state(buyer_purchasing_state_entry, parameters = {}):\n\n\tbuyer_purchasing_state = {}\n\tbuyer_purchasing_state[\"buyerpurchasingstateID\"] = buyer_purchasing_state_entry.id\n\tbuyer_purchasing_state[\"buyerID\"] = buyer_purchasing_state_entry.buyer_id\n\tbuyer_purchasing_state[\"created_at\"] = buyer_purchasing_state_entry.created_at\n\tbuyer_purchasing_state[\"updated_at\"] = buyer_purchasing_state_entry.updated_at\n\tbuyer_purchasing_state[\"delete_status\"] = buyer_purchasing_state_entry.delete_status\n\n\tbuyer_purchasing_state[\"state\"] = serialize_state(buyer_purchasing_state_entry.state)\n\n\treturn buyer_purchasing_state\n\ndef parse_buyer_buys_from(buyer_buys_from_entry, parameters = {}):\n\n\tbuyer_buys_froms =[]\n\n\tfor buyer_buys_from in buyer_buys_from_entry:\n\n\t\tbuyer_buys_from_entry = serialize_buyer_buys_from(buyer_buys_from, parameters)\n\t\tbuyer_buys_froms.append(buyer_buys_from_entry)\n\n\treturn buyer_buys_froms\n\ndef serialize_buyer_buys_from(buyer_buys_from_entry, parameters = {}):\n\n\tbuyer_buys_from = {}\n\tbuyer_buys_from[\"buyerbuysfromID\"] = buyer_buys_from_entry.id\n\tbuyer_buys_from[\"buyerID\"] = buyer_buys_from_entry.buyer_id\n\tbuyer_buys_from[\"created_at\"] = buyer_buys_from_entry.created_at\n\tbuyer_buys_from[\"updated_at\"] = buyer_buys_from_entry.updated_at\n\n\tbuyer_buys_from[\"business_type\"] = serialize_business_type(buyer_buys_from_entry.business_type)\n\n\treturn buyer_buys_from\n\ndef parse_buyer_store_lead(buyer_store_leads_queryset, parameters = {}):\n\n\tbuyer_store_leads = []\n\n\tfor buyer_store_lead in buyer_store_leads_queryset:\n\t\tbuyer_store_lead_entry = serialize_buyer_store_lead(buyer_store_lead, parameters)\n\t\tbuyer_store_leads.append(buyer_store_lead_entry)\n\n\treturn buyer_store_leads\n\ndef serialize_buyer_store_lead(buyer_store_lead_entry, parameters = {}):\n\n\tbuyer_store_lead = {}\n\tbuyer_store_lead[\"buyerstoreleadID\"] = buyer_store_lead_entry.id\n\tbuyer_store_lead[\"buyerID\"] = buyer_store_lead_entry.buyer_id\n\tbuyer_store_lead[\"name\"] = buyer_store_lead_entry.name\n\tbuyer_store_lead[\"mobile_number\"] = buyer_store_lead_entry.mobile_number\n\tbuyer_store_lead[\"email\"] = buyer_store_lead_entry.email\n\tbuyer_store_lead[\"status\"] = buyer_store_lead_entry.status\n\tbuyer_store_lead[\"sizes\"] = buyer_store_lead_entry.sizes\n\tbuyer_store_lead[\"quantity\"] = buyer_store_lead_entry.quantity\n\tbuyer_store_lead[\"product_link\"] = buyer_store_lead_entry.get_product_link()\n\t\n\tbuyer_store_lead[\"product\"] = serialize_product(buyer_store_lead_entry.product, parameters)\n\n\treturn buyer_store_lead","sub_path":"users/serializers/buyer.py","file_name":"buyer.py","file_ext":"py","file_size_in_byte":15422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"646793427","text":"#!/usr/bin/python3\n\"\"\" show status \"\"\"\nfrom api.v1.views import app_views\nfrom flask import jsonify, abort, request, make_response\nfrom models import storage\nfrom models.place import Place\nfrom models.city import City\nfrom models.user import User\n\n\n@app_views.route('/cities//places', methods=['GET', 'POST'],\n strict_slashes=False)\ndef places_of_city(city_id):\n \"\"\"\n Route for handle http methods for requested place by city\n city_id: Is the id of the searched city\n \"\"\"\n city = storage.get(City, city_id)\n\n if not city:\n abort(404)\n\n info_city = []\n for info in city.places:\n info_city.append(info.to_dict())\n if request.method == 'GET':\n return jsonify(info_city)\n\n if request.method == 'POST':\n data = request.get_json()\n if not data:\n abort(400, 'Not a JSON')\n if \"user_id\" not in data:\n abort(400, 'Missing user_id')\n if storage.get(User, data[\"user_id\"]) is None:\n abort(404)\n if \"name\" not in data:\n abort(400, 'Missing name')\n\n data['city_id'] = city_id\n new_place = Place(**data)\n new_place.save()\n storage.save()\n return jsonify(new_place.to_dict()), 201\n\n\n@app_views.route('/places/', methods=['GET', 'DELETE', 'PUT'],\n strict_slashes=False)\ndef places_by_id(place_id):\n \"\"\"\n Route for a city that handle http methods\n place_id: is the id of the searched place\n \"\"\"\n place = storage.get(Place, place_id)\n\n if not place:\n abort(404)\n\n if request.method == 'GET':\n return jsonify(place.to_dict())\n\n if request.method == 'DELETE':\n storage.delete(place)\n storage.save()\n return jsonify({}), 200\n\n if request.method == 'PUT':\n info = request.get_json()\n if not info:\n abort(400, \"Not a JSON\")\n dont = ['id', 'created_at', 'updated_at', 'user_id', 'city_id']\n for key, value in info.items():\n if key in dont:\n pass\n else:\n setattr(place, key, value)\n place.save()\n return jsonify(place.to_dict()), 200\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"402113802","text":"#!/usr/bin/env python\n\n\n'''\n# Team ID: VD#0565\n# Theme: Vitarana Drone\n# Author List: Mrinal Pathak, Mrinal Pathak, Ayush Kumar Jha, Aditya Kumar Garg\n# Filename: Task_6_VD_0565_attitude_controller.py\n# Functions: init, imu_callback(), drone_command_callback(), roll_set_pid(), pitch_set_pid(), yaw_set_pid(), has_reached_callback(), pid(), main\n# Global variables: e_drone, r\n'''\n\n\n'''\nThis python file runs a ROS-node of name attitude_control which controls the roll pitch and yaw angles of the eDrone.\nThis node publishes and subsribes the following topics:\n\t\tPUBLICATIONS SUBSCRIPTIONS\n\t\t/roll_error /pid_tuning_yaw\n\t\t/pitch_error /pid_tuning_pitch\n\t\t/yaw_error /pid_tuning_roll\n\t\t/edrone/pwm /edrone/imu/data\n\t\t\t\t\t\t\t\t/edrone/drone_command\n\nRather than using different variables, use list. eg : self.setpoint = [1,2,3], where index corresponds to x,y,z ...rather than defining self.x_setpoint = 1, self.y_setpoint = 2\nCODE MODULARITY AND TECHNIQUES MENTIONED LIKE THIS WILL HELP YOU GAINING MORE MARKS WHILE CODE EVALUATION.\n'''\n\n# Importing the required libraries\n\nfrom vitarana_drone.msg import *\nfrom pid_tune.msg import PidTune\nfrom sensor_msgs.msg import Imu\nfrom std_msgs.msg import Float32\nimport rospy\nimport time\nimport tf\n\n\nclass Edrone():\n\t\"\"\"docstring for Edrone\"\"\"\n\t# Function Name: init\n\t# Inputs: None\n\t# Outputs: None\n\t# Purpose: To initialise all the variables used in the class, and all other initialisations.\n\tdef __init__(self):\n\t\trospy.init_node('dummy_controller',anonymous = True) # initializing ros node with name drone_control\n\n\t\t# This corresponds to your current orientation of eDrone in quaternion format. This value must be updated each time in your imu callback\n\t\t# [x,y,z,w]\n\t\tself.drone_orientation_quaternion = [0.0, 0.0, 0.0, 0.0]\n\n\t\t# This corresponds to your current orientation of eDrone converted in euler angles form.\n\t\t# [r,p,y]\n\t\tself.drone_orientation_euler = [0.0, 0.0, 0.0]\n\n\t\t# This is the setpoint that will be received from the drone_command in the range from 1000 to 2000\n\t\t# [r_setpoint, p_setpoint, y_setpoint]\n\t\tself.setpoint_cmd = [1500,1500,1500,1000]\n\n\t\t# The setpoint of orientation in euler angles at which you want to stabilize the drone\n\t\t# [r_setpoint, p_psetpoint, y_setpoint]\n\t\tself.setpoint_euler = [0.0,0.0,0.0]\n\n\t\t# Declaring pwm_cmd of message type prop_speed and initializing values\n\t\t# Hint: To see the message structure of prop_speed type the following command in the terminal\n\t\t# rosmsg show vitarana_drone/prop_speed\n\n\t\tself.pwm_cmd = prop_speed()\n\t\tself.pwm_cmd.prop1 = 0.0\n\t\tself.pwm_cmd.prop2 = 0.0\n\t\tself.pwm_cmd.prop3 = 0.0\n\t\tself.pwm_cmd.prop4 = 0.0\n\n\t\t# initial setting of Kp, Kd and ki for [roll, pitch, yaw]. eg: self.Kp[2] corresponds to Kp value in yaw axis\n\t\t# after tuning and computing corresponding PID parameters, change the parameters\n\t\tself.Kp = [28.8,28.8,0.6]\n\t\tself.Ki = [0.0,0.0,0.0]\n\t\tself.Kd = [281.7,281.7,0]\n\t\t# -----------------------Add other required variables for pid here ----------------------------------------------\n\t\tself.min_values = [0, 0, 0, 0]\n\t\tself.max_values = [1024, 1024, 1024, 1024]\n\n\t\tself.prev_error = [0,0,0]\n\t\tself.error = [0,0,0]\n\t\tself.differential_error = [0,0,0]\n\t\tself.sum_Iterm = [0,0,0]\n\t\tself.has_reached = 0\n\t\t# Hint : Add variables for storing previous errors in each axis, like self.prev_values = [0,0,0] where corresponds to [roll, pitch, yaw]\n\t\t# Add variables for limiting the values like self.max_values = [1024, 1024, 1024, 1024] corresponding to [prop1, prop2, prop3, prop4]\n\t\t# self.min_values = [0, 0, 0, 0] corresponding to [prop1, prop2, prop3, prop4]\n\t\t#\n\t\t# ----------------------------------------------------------------------------------------------------------\n\n\t\t# # This is the sample time in which you need to run pid. Choose any time which you seem fit. Remember the stimulation step time is 50 ms\n\t\tself.sample_time = 0.060 # in seconds\n\n\t\t# Publishing /edrone/pwm, /roll_error, /pitch_error, /yaw_error\n\t\tself.pwm_pub = rospy.Publisher('/edrone/pwm', prop_speed, queue_size=10)\n\n\t\t# ------------------------Add other ROS Publishers here-----------------------------------------------------\n\t\tself.roll_pub = rospy.Publisher('/roll_error', Float32, queue_size=10)\n\t\tself.pitch_pub = rospy.Publisher('/pitch_error', Float32, queue_size=10)\n\t\tself.yaw_pub = rospy.Publisher('/yaw_error', Float32, queue_size=10)\n\t\tself.zero_pub = rospy.Publisher('/zero_error', Float32, queue_size=10)\n\t\t# -----------------------------------------------------------------------------------------------------------\n\n\t\t# Subscribing to /drone_command, imu/data, /pid_tuning_roll, /pid_tuning_pitch, /pid_tuning_yaw\n\t\trospy.Subscriber('/drone_command', edrone_cmd, self.drone_command_callback)\n\t\trospy.Subscriber('/edrone/imu/data', Imu, self.imu_callback)\n\t\t#rospy.Subscriber('/pid_tuning_roll', PidTune, self.roll_set_pid)\n\t\t#rospy.Subscriber('/pid_tuning_pitch', PidTune, self.pitch_set_pid)\n\t\t#rospy.Subscriber('/pid_tuning_yaw', PidTune, self.yaw_set_pid)\n\t\trospy.Subscriber('/reached', Float32, self.has_reached_callback)\n\n\t# Imu callback function\n\t# The function gets executed each time when imu publishes /edrone/imu/data\n\n\t# Note: The imu publishes various kind of data viz angular velocity, linear acceleration, magnetometer reading (if present),\n\t# but here we are interested in the orientation which can be calculated by a complex algorithm called filtering which is not in the scope of this task,\n\t# so for your ease, we have the orientation published directly BUT in quaternion format and not in euler angles.\n\t# We need to convert the quaternion format to euler angles format to understand the orienataion of the edrone in an easy manner.\n\t# Hint: To know the message structure of sensor_msgs/Imu, execute the following command in the terminal\n\t# rosmsg show sensor_msgs/Imu\n\n\tdef imu_callback(self, msg):\n\n\t\t'''\n\t\tPurpose:\n\t\t---\n\t\tCallback function for imu\n\n\t\tInput Arguments:\n\t\t---\n\t\tmsg` : Imu\n\t\t the pose and Imu details of the edrone\n\n\t\tReturns: None\n\n\t\tExample call:\n\t\t---\n\t\tN/A\n\t\t'''\n\n\n\t\tself.drone_orientation_quaternion = [msg.orientation.x, msg.orientation.y, msg.orientation.z, msg.orientation.w]\n\n\t\t# --------------------Set the remaining co-ordinates of the drone from msg----------------------------------------------\n\n\tdef drone_command_callback(self, msg):\n\n\t\t'''\n\t\tPurpose:\n\t\t---\n\t\tCallback function for drone_command topic\n\n\t\tInput Arguments:\n\t\t---\n\t\tmsg` : edrone_cmd\n\t\t the roll, pitch, yaw and throttle values\n\n\t\tReturns: None\n\n\t\tExample call:\n\t\t---\n\t\tN/A\n\t\t'''\n\n\t\tself.setpoint_cmd = [msg.rcRoll, msg.rcPitch, msg.rcYaw, msg.rcThrottle]\n\t\tprint(msg)\n\n\t\t# ---------------------------------------------------------------------------------------------------------------\n\n\t# Callback function for /pid_tuning_roll\n\t# This function gets executed each time when /tune_pid publishes /pid_tuning_roll\n\tdef roll_set_pid(self,msg):\n\n\t\t'''\n\t\tPurpose:\n\t\t---\n\t\tCallback function for Roll PID tuning\n\n\t\tInput Arguments:\n\t\t---\n\t\tmsg` : PidTune\n\t\t the values received from PidTuner\n\n\t\tReturns: None\n\n\t\tExample call:\n\t\t---\n\t\tN/A\n\t\t'''\n\n\t\tself.Kp[0] = msg.Kp * 0.06 # This is just for an example. You can change the ratio/fraction value accordingly\n\t\tself.Ki[0] = msg.Ki * 0.008\n\t\tself.Kd[0] = msg.Kd * 0.3\n \n\t# ----------------------------Define callback function like roll_set_pid to tune pitch, yaw--------------\n\tdef pitch_set_pid(self,msg):\n\n\t\t'''\n\t\tPurpose:\n\t\t---\n\t\tCallback function for Pitch PID tuning\n\n\t\tInput Arguments:\n\t\t---\n\t\tmsg` : PidTune\n\t\t the values received from PidTuner\n\n\t\tReturns: None\n\n\t\tExample call:\n\t\t---\n\t\tN/A\n\t\t'''\n\n\t\tself.Kp[1] = msg.Kp * 0.06\n\t\tself.Ki[1] = msg.Ki * 0.008\n\t\tself.Kd[1] = msg.Kd * 0.3\n\n\tdef yaw_set_pid(self,msg):\n\n\t\t'''\n\t\tPurpose:\n\t\t---\n\t\tCallback function for Yaw PID tuning\n\n\t\tInput Arguments:\n\t\t---\n\t\tmsg` : PidTune\n\t\t the values received from PidTuner\n\n\t\tReturns: None\n\n\t\tExample call:\n\t\t---\n\t\tN/A\n\t\t'''\n\n\t\tself.Kp[2] = msg.Kp * 0.06\n\t\tself.Ki[2] = msg.Ki * 0.008\n\t\tself.Kd[2] = msg.Kd * 0.3\n\n\tdef has_reached_callback(self,msg):\n\n\t\t'''\n\t\tPurpose:\n\t\t---\n\t\tCallback function for receiving info when edrone has reached its final position to turn off.\n\n\t\tInput Arguments:\n\t\t---\n\t\tmsg` : Boolean\n\t\t True when the edrone has finished the task\n\n\t\tReturns: None\n\n\t\tExample call:\n\t\t---\n\t\tN/A\n\t\t'''\n\n\t\tself.has_reached = msg.data\n\n\t# ----------------------------------------------------------------------------------------------------------------------\n\n\tdef pid(self):\n\n\t\t'''\n\t\tPurpose:\n\t\t---\n\t\tTo implement PID control to maintain the attitude of the edrone while flying.\n\n\t\tInput Arguments:\n\t\t---\n\t\tNone\n\n\t\tReturns: None\n\n\t\tExample call:\n\t\t---\n\t\tobject.pid()\n\t\t'''\n\n\t\t# -----------------------------Write the PID algorithm here--------------------------------------------------------------\n\n\t\t# Steps:\n\t\t# 1. Convert the quaternion format of orientation to euler angles\n\t\t(self.drone_orientation_euler[0], self.drone_orientation_euler[1], self.drone_orientation_euler[2]) = tf.transformations.euler_from_quaternion([self.drone_orientation_quaternion[0], self.drone_orientation_quaternion[1], self.drone_orientation_quaternion[2], self.drone_orientation_quaternion[3]])\n\n\t\t# 2. Convert the setpoint that is in the range of 1000 to 2000 into angles with the limit from -10 degree to 10 degree in euler angles\n\t\tself.setpoint_euler = [i * 0.02 - 30 for i in self.setpoint_cmd[0:3]]\n\n\t\t# 3. Compute error in each axis. eg: error[0] = self.setpoint_euler[0] - self.drone_orientation_euler[0], where error[0] corresponds to error in roll...\n\t\tself.error = [x1-x2 for (x1,x2) in zip(self.setpoint_euler, self.drone_orientation_euler)]\n\t\tself.error[2]=self.error[2]*10000\n\t\t# 4. Compute the error (for proportional), change in error (for derivative) and sum of errors (for integral) in each axis. Refer \"Understanding PID.pdf\" to understand PID equation.\n\t\tself.differential_error = [x1-x2 for (x1,x2) in zip(self.error,self.prev_error)]\n\n\t\t# 5. Calculate the pid output required for each axis. For eg: calcuate self.out_roll, self.out_pitch, etc.\n\t\tself.out_roll = float(self.error[0] * self.Kp[0] + self.sum_Iterm[0] * self.Ki[0] + self.differential_error[0] * self.Kd[0])\n\t\tself.out_pitch = float(self.error[1] * self.Kp[1] + self.sum_Iterm[1] * self.Ki[1] + self.differential_error[1] * self.Kd[1])\n\t\tself.out_yaw = float(self.error[2] * self.Kp[2] + self.sum_Iterm[2] * self.Ki[2] + self.differential_error[2] * self.Kd[2])\n\t\tprint(\"roll \",self.out_roll)\n\t\tprint(\"pitch \",self.out_pitch)\n\t\tprint(\"yaw\",self.out_yaw)\n\t\t\n\t\t# Also convert the range of 1000 to 2000 to 0 to 1024 for throttle here itslef\n\t\tthrottle_val =self.setpoint_cmd[3] * 1.024 - 1024\n\t\tprint(\"throttle \",throttle_val)\n\n\t\t# 6. Use this computed output value in the equations to compute the pwm for each propeller. LOOK OUT FOR SIGN (+ or -). EXPERIMENT AND FIND THE CORRECT SIGN\n\t\tself.pwm_cmd.prop1 = throttle_val + self.out_roll - self.out_pitch - self.out_yaw \n\t\tself.pwm_cmd.prop2 = throttle_val - self.out_roll - self.out_pitch + self.out_yaw\n\t\tself.pwm_cmd.prop3 = throttle_val - self.out_roll + self.out_pitch - self.out_yaw\n\t\tself.pwm_cmd.prop4 = throttle_val + self.out_roll + self.out_pitch + self.out_yaw\n\t\t\n\t\t# 7. Don't run the pid continously. Run the pid only at the a sample time. self.sampletime defined above is for this purpose. THIS IS VERY IMPORTANT.\n\t\t\n\t\t# 8. Limit the output value and the final command value between the maximum(0) and minimum(1024)range before publishing. For eg : if self.pwm_cmd.prop1 > self.max_values[1]:\n\t\tif self.pwm_cmd.prop1 > self.max_values[0]:\n\t\t\tself.pwm_cmd.prop1 = self.max_values[0]\n\n\t\tif self.pwm_cmd.prop1 < self.min_values[0]:\n\t\t\tself.pwm_cmd.prop1 = self.min_values[0]\n\n\t\tif self.pwm_cmd.prop2 > self.max_values[1]:\n\t\t\tself.pwm_cmd.prop2 = self.max_values[1]\n\n\t\tif self.pwm_cmd.prop2 < self.min_values[1]:\n\t\t\tself.pwm_cmd.prop2 = self.min_values[1]\n\n\t\tif self.pwm_cmd.prop3 > self.max_values[2]:\n\t\t\tself.pwm_cmd.prop3 = self.max_values[2]\n\n\t\tif self.pwm_cmd.prop3 < self.min_values[2]:\n\t\t\tself.pwm_cmd.prop3 = self.min_values[2]\n\n\t\tif self.pwm_cmd.prop4 > self.max_values[3]:\n\t\t\tself.pwm_cmd.prop4 = self.max_values[3]\n\n\t\tif self.pwm_cmd.prop4 < self.min_values[3]:\n\t\t\tself.pwm_cmd.prop4 = self.min_values[3] \n\t\t\n\t\t# 8. Update previous errors.eg: self.prev_error[1] = error[1] where index 1 corresponds to that of pitch (eg)\n\t\tself.prev_error = self.error\n\t\t# 9. Add error_sum to use for integral component\n\t\tself.sum_Iterm = [x1+x2 for (x1,x2) in zip(self.sum_Iterm,self.error)]\n\n\t\t# publish topics\n\t\tself.pwm_pub.publish(self.pwm_cmd)\n\t\tself.roll_pub.publish(self.error[0])\n\t\tself.pitch_pub.publish(self.error[1])\n\t\tself.yaw_pub.publish(self.error[2])\n\t\tself.zero_pub.publish(self.error[0]-self.error[0])\n\n# Function Name: main (built in)\n# Inputs: None\n# Outputs: None\n# Purpose: To create an object of class Edrone and call the pid method of it at a rate of 16.67 Hz\nif __name__ == '__main__':\n\n\te_drone = Edrone() # object of class Edrone\n\tr = rospy.Rate(1/e_drone.sample_time) # specify rate in Hz based upon your desired PID sampling time, i.e. if desired sample time is 33ms specify rate as 30Hz\n\twhile not rospy.is_shutdown():\n\t\tif(e_drone.has_reached):\n\t\t\tbreak\n\t\te_drone.pid()\n\t\tr.sleep()\n","sub_path":"scripts/attitude_controller.py","file_name":"attitude_controller.py","file_ext":"py","file_size_in_byte":13615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"463121500","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nimport random\nimport math\nfrom opensimplex import OpenSimplex\n\n\ngen = OpenSimplex(seed=int(random.random()*1000))\n\n\ndef noise(nx, ny):\n # Rescale from -1.0:+1.0 to 0.0:1.0\n return gen.noise2d(nx, ny) / 2.0 + 0.5\n\n\nclass Env:\n \"\"\"Represents the entire environment\"\"\"\n CMAP = colors.ListedColormap(['blue', 'green', 'brown'])\n\n def __init__(self, size: int = 16, max_height: int = 2, ocean_depth: float = .2, creature_count: int = 10):\n self.size = size\n self.max_height = max_height\n self.ocean_depth = ocean_depth\n self.creature_count = creature_count\n\n # make grid with noise\n self.grid = np.zeros(shape=(size, size))\n for y in range(size):\n for x in range(size):\n nx = x/size - 0.5\n ny = y/size - 0.5\n self.grid[y][x] = math.pow(1 * noise(nx, ny) + 0.5 * noise(2 * nx, 2 * ny) + 0.25 * noise(4 * nx, 2 * ny), max_height)\n\n # validate depths\n if max_height <= ocean_depth:\n raise Exception(\"Max height must be greater than ocean depth\")\n\n self.creature_height = max_height + 10\n self.bounds = [0, ocean_depth, max_height, self.creature_height]\n\n # add the creatures to the map in valid starting locations\n self.creatures = []\n while len(self.creatures) < self.creature_count:\n possible_location = (random.randint(0, self.size - 1), random.randint(0, self.size - 1))\n if self.valid_location(possible_location) and possible_location not in self.creatures:\n self.creatures.append(possible_location)\n\n print(self.creatures)\n\n # initial image\n self.fig = plt.figure()\n self.norm = colors.BoundaryNorm(self.bounds, self.CMAP.N)\n self.im = plt.imshow(self.grid, cmap=self.CMAP, interpolation='none', origin='lower', norm=self.norm)\n\n def initial_plot(self):\n # put the creature on the map\n a = self.im.get_array()\n for c in self.creatures:\n a[c[0]][c[1]] = self.creature_height\n self.im.set_array(a)\n return [self.im]\n\n def valid_location(self, location, ocean_okay=False) -> bool:\n \"\"\"check if the new location breaks the rules\"\"\"\n gt_size = any([i > self.size - 1 for i in location])\n lt_zero = any([i < 0 for i in location])\n if gt_size or lt_zero:\n return False\n\n in_ocean = (self.grid[location[0]][location[1]] <= self.ocean_depth) or ocean_okay\n if in_ocean:\n return False\n\n return True\n\n def creature_move(self, array):\n \"\"\"Moves the creature one square in a random, valid direction\"\"\"\n\n for index, c in enumerate(self.creatures):\n # pick a direction that's allowed\n while True:\n x_or_y = random.randint(0, 1)\n direction = 1 if random.random() < 0.5 else -1\n if x_or_y:\n new_location = (c[0], c[1] + direction)\n else:\n new_location = (c[0] + direction, c[1])\n\n # check if the new location breaks the rules\n if self.valid_location(new_location):\n break\n\n array[c[0]][c[1]] = self.grid[c[0]][c[1]]\n self.creatures[index] = new_location\n print(self.creatures)\n array[new_location[0]][new_location[1]] = self.creature_height\n\n return array\n\n def animate(self, index):\n \"\"\"animate it\"\"\"\n a = self.im.get_array()\n\n a = self.creature_move(a)\n\n self.im.set_array(a)\n\n return [self.im]\n","sub_path":"environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"188937346","text":"# !python3\n# coding: utf-8\n# author: sis-flag\n\nimport os\nimport time\nimport shutil\nimport pickle\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom my_act import act_dict\n\n# %% parameters\nR = {}\n\nR[\"seed\"] = 0\n\nR[\"size_it\"] = 1000\nR[\"size_bd\"] = 100\n\nR[\"penalty\"] = 1e3\n\nR[\"act_name\"] = (\"sin\",) * 3\nR[\"hidden_units\"] = (180,) * 3\nR[\"learning_rate\"] = 1e-4\nR[\"lr_decay\"] = 5e-7\n\nR[\"varcoe\"] = 0.5\n\nR[\"total_step\"] = 5000\nR[\"resamp_epoch\"] = 1\nR[\"plot_epoch\"] = 500\n\nR[\"record_path\"] = os.path.join(\"..\", \"exp\", \"sin_N\")\n\n# %% generate data in domain\n\nR[\"dimension\"] = dim = 1\nR[\"area_it\"] = 2\nR[\"area_bd\"] = 1\n\n# interior data\ndef rand_it(size):\n x_it = np.random.rand(size, dim) * 2 - 1\n return x_it.astype(np.float32)\n\n\n# boundary data\ndef rand_bd(size):\n\n x_bd = np.random.rand(size, dim) * 2 - 1\n ind = np.random.randint(dim, size=size)\n x01 = np.random.randint(2, size=size) * 2 - 1\n for ii in range(size):\n x_bd[ii, ind[ii]] = x01[ii]\n\n return x_bd.astype(np.float32)\n\n\n# %% PDE problem\n# - (a(x) u'(x))' + c(x) u(x) = f(x)\nR[\"mu\"] = mu = 6 * np.pi\n\n\ndef u(x):\n u = np.sin(mu * x)\n return u.astype(np.float32).reshape((-1, 1))\n\n\ndef a(x):\n a = np.ones((x.shape[0], 1))\n return a.astype(np.float32).reshape((-1, 1))\n\n\ndef c(x):\n c = np.zeros((x.shape[0], 1))\n return c.astype(np.float32).reshape((-1, 1))\n\n\ndef f(x):\n f = mu * mu * np.sin(mu * x)\n return f.astype(np.float32).reshape((-1, 1))\n\n\n# %% save parameters\n\n# prepare folder\nif not os.path.isdir(R[\"record_path\"]):\n os.mkdir(R[\"record_path\"])\n\n# save current code\nsave_file = os.path.join(R[\"record_path\"], \"code.py\")\nshutil.copyfile(__file__, save_file)\n\n# %% set seed\ntf.set_random_seed(R[\"seed\"])\ntf.random.set_random_seed(R[\"seed\"])\nnp.random.seed(R[\"seed\"])\n\n# %% get test points\nx_test = np.linspace(-1, 1, 200 +1).reshape((-1, 1))\n\nR[\"x_test\"] = x_test.astype(np.float32)\nR[\"u_test_true\"] = u(R[\"x_test\"])\n\n# %% get sample points\nx_samp = np.linspace(-1, 1, 200 +1).reshape((-1, 1))\n\nR[\"x_samp\"] = x_samp.astype(np.float32)\nR[\"u_samp_true\"] = u(R[\"x_samp\"])\n\n# %% normal neural network\nunits = (dim,) + R[\"hidden_units\"] + (1,)\n\n\ndef neural_net(x):\n with tf.variable_scope(\"vscope\", reuse=tf.AUTO_REUSE):\n\n y = x\n\n for i in range(len(units) - 2):\n init_W = np.random.randn(units[i], units[i + 1]).astype(np.float32)\n init_W = init_W * (2 / (units[i] + units[i + 1]) ** R[\"varcoe\"])\n init_b = np.random.randn(units[i + 1]).astype(np.float32)\n init_b = init_b * (2 / (units[i] + units[i + 1]) ** R[\"varcoe\"])\n\n W = tf.get_variable(name=\"W\" + str(i), initializer=init_W)\n b = tf.get_variable(name=\"b\" + str(i), initializer=init_b)\n\n y = act_dict[R[\"act_name\"][i]](tf.matmul(y, W) + b)\n\n init_W = np.random.randn(units[-2], units[-1]).astype(np.float32)\n init_W = init_W * (2 / (units[i] + units[i + 1]) ** R[\"varcoe\"])\n init_b = np.random.randn(units[-1]).astype(np.float32)\n init_b = init_b * (2 / (units[i] + units[i + 1]) ** R[\"varcoe\"])\n\n W = tf.get_variable(name=\"W\" + str(len(units) - 1), initializer=init_W)\n b = tf.get_variable(name=\"b\" + str(len(units) - 1), initializer=init_b)\n\n y = tf.matmul(y, W) + b\n\n return y\n\n\n# %% loss and optimizer (\"V\" for variable)\nwith tf.variable_scope(\"vscope\", reuse=tf.AUTO_REUSE):\n\n Vx_it = tf.placeholder(tf.float32, shape=(None, dim))\n Vx_bd = tf.placeholder(tf.float32, shape=(None, dim))\n\n Va_it = tf.placeholder(tf.float32, shape=(None, 1))\n Vc_it = tf.placeholder(tf.float32, shape=(None, 1))\n Vf_it = tf.placeholder(tf.float32, shape=(None, 1))\n\n Vu_true_bd = tf.placeholder(tf.float32, shape=(None, 1))\n\n Vu_it = neural_net(Vx_it)\n Vu_bd = neural_net(Vx_bd)\n\n Vdu_it = tf.gradients(Vu_it, Vx_it)[0]\n\n Vloss_it = R[\"area_it\"] * tf.reduce_mean(\n 1 / 2 * Va_it * tf.reduce_sum(tf.square(Vdu_it), axis=1, keepdims=True)\n + 1 / 2 * Vc_it * tf.square(Vu_it)\n - Vf_it * Vu_it\n )\n Vloss_bd = R[\"area_bd\"] * tf.reduce_mean(tf.square(Vu_bd - Vu_true_bd))\n\n Vloss = Vloss_it + R[\"penalty\"] * Vloss_bd\n\n learning_rate = tf.placeholder_with_default(input=1e-3, shape=[], name=\"lr\")\n optimizer = tf.train.AdamOptimizer(learning_rate)\n train_op = optimizer.minimize(Vloss)\n\n# %% train model\nt0 = time.time()\nloss, loss_bd = [], []\nerror = []\nlr = 1 * R[\"learning_rate\"]\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nwith tf.Session(config=config) as sess:\n\n sess.run(tf.global_variables_initializer())\n\n for epoch in range(R[\"total_step\"] + 1):\n\n # generate new data (\"N\" for number)\n if epoch % R[\"resamp_epoch\"] == 0:\n\n Nx_it = rand_it(R[\"size_it\"])\n Nx_bd = rand_bd(R[\"size_bd\"])\n\n Na_it = a(Nx_it)\n Nc_it = c(Nx_it)\n Nf_it = f(Nx_it)\n\n Nu_bd = u(Nx_bd)\n\n # train neural network\n lr = (1 - R[\"lr_decay\"]) * lr\n\n _, Nloss, Nloss_bd = sess.run(\n [train_op, Vloss, Vloss_bd],\n feed_dict={\n Vx_it: Nx_it,\n Vx_bd: Nx_bd,\n Va_it: Na_it,\n Vc_it: Nc_it,\n Vf_it: Nf_it,\n Vu_true_bd: Nu_bd,\n learning_rate: lr,\n },\n )\n\n # get test error\n R[\"u_test\"] = sess.run(Vu_it, feed_dict={Vx_it: R[\"x_test\"]})\n Nerror = R[\"area_it\"] * np.mean((R[\"u_test\"] - R[\"u_test_true\"]) ** 2)\n\n loss.append(Nloss)\n loss_bd.append(Nloss_bd)\n error.append(Nerror)\n\n # show current state\n if epoch % R[\"plot_epoch\"] == 0:\n\n print(\"epoch %d, time %.3f\" % (epoch, time.time() - t0))\n print(\"total loss %f, boundary loss %f\" % (Nloss, Nloss_bd))\n print(\"interior error %f\" % (Nerror))\n\n R[\"time\"] = time.time() - t0\n R[\"loss\"] = np.array(loss)\n R[\"loss_bd\"] = np.array(loss_bd)\n R[\"error\"] = np.array(error)\n\n u_samp = sess.run(Vu_it, feed_dict={Vx_it: R[\"x_samp\"]})\n R[\"u_samp_\" + str(epoch)] = u_samp\n\n # %% save data\n data_dir = os.path.join(R[\"record_path\"], \"data.pkl\")\n with open(data_dir, \"wb\") as file:\n pickle.dump(R, file)\n\n# %% save data\ndata_dir = os.path.join(R[\"record_path\"], \"data.pkl\")\nwith open(data_dir, \"wb\") as file:\n pickle.dump(R, file)\n","sub_path":"exp/sin_N/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":6510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"427869634","text":"from dsk.maya.helper.lib.base_criteria import CriteriaExpression\n# factory base\n\nclass MakeExpressionCr(CriteriaExpression):\n Property = 'expressionUndefined'\n Value = \"\"\n def __init__(self):\n super(MakeExpressionCr,self).__init__(self.Value)\n\n\ndef makeExpression(propertyname,expression=\"x\",doc=None):\n assert isinstance(propertyname,basestring)\n assert expression != \"\"\n assert isinstance(expression,basestring)\n\n doc = doc if doc != None else \"return True %s was found\" % expression\n return type(propertyname+\"Cr\",\n (MakeExpressionCr,),\n {'Property':propertyname, # class attribute\n 'Value':expression,\n '__doc__':doc,\n '__slots__':()\n })\n\nsig = \"%r,expression=%r,doc=%r\"\ndef buildCall(aclass):\n assert aclass.Value != None\n return sig % (aclass.Property,\n aclass.Value,\n aclass.__doc__)\n\n__api__ = [(makeExpression,buildCall)]\n__criteria__ = []","sub_path":"dsk/maya/helper/lib/criteria/crExpression.py","file_name":"crExpression.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"408213113","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom functools import partial\n\nfrom se3cnn.blocks import GatedBlock\nfrom se3cnn import basis_kernels\n\n\nclass network(nn.Module):\n\n def __init__(self, output_size, filter_size=5):\n super(network, self).__init__()\n\n features = [(1,),\n (4, 4, 4, 4),\n (4, 4, 4, 4),\n (4, 4, 4, 4),\n (output_size,)]\n\n common_block_params = {\n 'size': filter_size,\n 'padding': filter_size//2,\n 'stride': 1,\n 'normalization': 'instance',\n 'radial_window': partial(\n basis_kernels.gaussian_window_fct_convenience_wrapper,\n mode='compromise', border_dist=0, sigma=0.6),\n }\n\n block_params = [\n {'activation': (F.relu, F.sigmoid)},\n {'activation': (F.relu, F.sigmoid)},\n {'activation': (F.relu, F.sigmoid)},\n {'activation': None},\n ]\n\n assert len(block_params) + 1 == len(features)\n\n blocks = [GatedBlock(features[i], features[i + 1],\n **common_block_params, **block_params[i])\n for i in range(len(block_params))]\n\n self.layers = torch.nn.Sequential(\n *blocks,\n )\n\n def forward(self, x):\n out = self.layers(x)\n return out\n\n","sub_path":"examples/image/cath/scripts/to_ignore/MRI/networks/MICCAI2012/SE3BasicModel/SE3BasicModel.py","file_name":"SE3BasicModel.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"87703315","text":"from subprocess import Popen, PIPE\nimport sys\nimport logging\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\nclass ExecuteR(object):\n\n def worm_cat_fun(self, file_name, out_dir, title=\"rgs\", annotation_type=\"straight\", input_type=\"Sequence ID\"):\n\n ret_val = self.run(self.worm_cat_function, file_name, title, out_dir, \"False\", annotation_type, input_type)\n\n return ret_val\n\n worm_cat_function = ('./worm_cat.R',\n '--file', 0,\n '--title', 1,\n '--out_dir', 2,\n '--rm_dir', 3,\n '--annotation_type',4,\n '--input_type', 5\n )\n\n def run(self, arg_list, *args):\n try:\n processed_args = self.process_args(arg_list, *args)\n process = Popen(processed_args, stdout=PIPE)\n out, err = process.communicate()\n out = str(out, 'utf-8')\n if not out:\n out = '{}'\n sys.stderr.write(\"run: out={} err={}\\n\".format(out,err))\n return out\n except Exception as e:\n sys.stderr.write(\"ERROR: command line error %s\\n\" % args)\n sys.stderr.write(\"ERROR: %s\\n\" % e)\n sys.exit(-1)\n\n def process_args(self, arg_tuple, *args):\n # process the arg\n arg_list = list(arg_tuple)\n for index in range(0, len(arg_list)):\n if type(arg_list[index]) == int:\n # substitue for args passed in\n if arg_list[index] < len(args):\n arg_list[index] = args[arg_list[index]]\n # if we have more substitutions than args passed delete the extras\n else:\n del arg_list[index - 1:]\n break\n return arg_list\n","sub_path":"worm_cat/utils/execute_r.py","file_name":"execute_r.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"55499962","text":"# coding:utf-8\nimport pymysql.cursors\n# import os\n# os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'\n\n# mysql_info = {\"host\": '10.10.11.94',\n# \"port\": 3306,\n# \"user\": 'root',\n# \"passwd\": 'root$2016',\n# \"db\": 'credit',\n# \"charset\": 'utf8'}\nmysql_info = {\"host\": '10.12.11.86',\n \"port\": 3306,\n \"user\": 'store_rw',\n \"passwd\": 'Spts$201708',\n \"db\": 'GiveU_Store',\n \"charset\": 'utf8'}\nclass MysqlUtiltwo():\n '''\n mysql数据库相关操作\n 连接数据库信息:mysql_info\n 创建游标:mysql_execute\n 查询某个字段对应的字符串:mysql_getstring\n 查询一组数据:mysql_getrows\n 关闭mysql连接:mysql_close\n '''\n def __init__(self,mysql_info=mysql_info):\n self.db_info = mysql_info\n u'''连接池方式'''\n self.conn = MysqlUtiltwo.__getConnect(self.db_info)\n\n @staticmethod\n def __getConnect(db_info):\n '''静态方法,从连接池中取出连接'''\n try:\n conn = pymysql.connect(host=db_info['host'],\n port=db_info['port'],\n user=db_info['user'],\n passwd=db_info['passwd'],\n db=db_info['db'],\n charset=db_info['charset'])\n return conn\n except Exception as a:\n print(\"数据库连接异常:%s\"%a)\n\n def mysql_execute(self, sql):\n '''执行sql语句'''\n cur = self.conn.cursor()\n try:\n cur.execute(sql)\n except Exception as a:\n self.conn.rollback() # sql执行异常后回滚\n print(\"执行SQL语句出现异常:%s\"%a)\n else:\n cur.close()\n self.conn.commit() # sql无异常时提交\n\n def mysql_getrows(self, sql):\n ''' 返回查询结果'''\n self.conn.commit() #当有动态的新增数据时,需要先提交, 否则无法查询到\n cur = self.conn.cursor()\n try:\n cur.execute(sql)\n except Exception as a:\n print(\"执行SQL语句出现异常:%s\"%a)\n else:\n rows = cur.fetchall()\n cur.close()\n return rows\n\n def mysql_getstring(self, sql):\n '''查询某个字段的对应值'''\n rows = self.mysql_getrows(sql)\n if rows != None:\n for row in rows:\n for i in row:\n return i\n\n def mysql_Update(self, sql, data=''):\n \"\"\"\n 插入数据\n :param sql: SQL语句\n :param data: 插入字段的值,根据表字段顺序填写。设定空值是为了解放sql,不受固定形式限制\n :usage:\n sql = \"UPDATE trade SET saving = '%.2f' WHERE account = '%s' \"\n data = (8888, '13512345678')\n :return:\n \"\"\"\n cur = self.conn.cursor()\n if data == '':\n cur.execute(sql)\n else:\n cur.execute(sql % data)\n self.conn.commit()\n self.conn.commit()\n print('成功修改 %s 条数据' % cur.rowcount)\n\n def mysql_close(self):\n ''' 关闭 close mysql'''\n try:\n self.conn.close()\n except Exception as a:\n print(\"数据库关闭时异常:%s\"%a)\n\n\n\n\n\n# MySQLdb.connect() 建立数据库连接\n# cur = conn.cursor() #通过获取到的数据库连接conn下的cursor()方法来创建游标。\n# cur.execute() #过游标cur 操作execute()方法可以写入纯sql语句。通过execute()方法中写如sql语句来对数据进行操作。\n# cur.close() # cur.close() 关闭游标\n# conn.commit() # conn.commit()方法在提交事物,在向数据库插入(或update)一条数据时必须要有这个方法,否则数据不会被真正的插入。\n# conn.rollback() # 发生错误时候回滚\n# conn.close() # Conn.close()关闭数据库连接\n\nif __name__ == \"__main__\":\n A = MysqlUtiltwo()\n # sql = \"SELECT *FROM notify_request t where TEMPLATE_ID LIKE '16091%' ORDER BY t.REQUEST_TIME DESC limit 0,1\"\n sql = \"SELECT t.sms_code FROM (SELECT * FROM sms_verify_info WHERE phone = '13300000000' ORDER BY sent_time DESC) t LIMIT 1\"\n sql2 = \"SELECT t.con_name FROM (SELECT * FROM mobiletest_mobiledata WHERE con_name LIKE '自动化%' ORDER BY create_time DESC) t LIMIT 1\"\n # # A.mysql_execute(sql)\n # b=A.mysql_getrows(sql)\n # print (b)\n # con_name='自动化邞蚦'\n # x = A.mysql_getrows(\"select contract_no from cs_credit where id_person=(select id from cs_person where name ='%s')\"%(con_name))\n # print(x)\n # print (A.mysql_getstring(sql2))\n # A.mysql_close()\n sql = \"select id_person from t_user where login_name=15400110001 limit 1;\"\n\n for i in range(0,10):\n print (A.mysql_getstring(sql))\n\n\n","sub_path":"atp3/apps/project_01/case/mysql_pubtwo.py","file_name":"mysql_pubtwo.py","file_ext":"py","file_size_in_byte":4953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"424580127","text":"#!/usr/bin/python3\n\"\"\" create a web application that listen in port 5000\n\"\"\"\n\n\nfrom flask import Flask, escape, render_template\nfrom models import storage\nimport shlex\n\napp = Flask(__name__)\n# condition strict_slashes=False\napp.url_map.strict_slashes = False\n\n\n@app.route('/')\ndef hello():\n \"\"\" print this message\n \"\"\"\n return (\"Hello HBNB!\")\n\n\n@app.route('/hbnb')\ndef no_hello():\n \"\"\" print another message\n \"\"\"\n return (\"HBNB\")\n\n\n@app.route('/c/')\ndef C_coment(text='hola'):\n \"\"\" print a comment related to C\n \"\"\"\n text = text.replace('_', ' ')\n return (\"C {}\".format(escape(text)))\n\n\n@app.route('/python')\n@app.route('/python/')\ndef python(text='is cool'):\n \"\"\" commentary for python\n \"\"\"\n text = text.replace('_', ' ')\n return (\"Python {}\".format(escape(text)))\n\n\n@app.route('/number/')\ndef integer(n):\n \"\"\" print a integer number\n \"\"\"\n return (\"{} is a number\".format(n))\n\n\n@app.route('/number_template/')\ndef render(n):\n \"\"\" first render html, by default it search in templates folder\n \"\"\"\n return (render_template('5-number.html', n=n))\n\n\n@app.route('/number_odd_or_even/')\ndef second_render(n):\n \"\"\" even or odd render\n \"\"\"\n return (render_template('6-number_odd_or_even.html', n=n))\n\n\n@app.route('/states_list')\ndef call_States():\n \"\"\" call the states created\n \"\"\"\n lista = []\n dic = storage.all(\"State\")\n for elem in dic:\n var = dic[elem].name + \"/\" + dic[elem].id\n lista.append(var)\n lista.sort()\n # list of ordered tuples\n lista2 = []\n for elem in lista:\n elem = elem.replace('/', ' ')\n elem = shlex.split(elem)\n lista2.append((elem[0], elem[1]))\n return (render_template('7-states_list.html', tupla=lista2))\n\n\n@app.route('/cities_by_states')\ndef cities_per_State():\n \"\"\" cities per states\n \"\"\"\n lista = []\n dic = storage.all(\"State\")\n for elem in dic:\n lista.append((dic[elem].id, dic[elem].name))\n lista = sorted(lista, key=lambda x: x[1])\n # list of cities\n cities = []\n for state in dic:\n aux = dic[state].cities\n for city in aux:\n cities.append((dic[state].name, city.id, city.name))\n cities = sorted(cities, key=lambda x: x[2])\n return (render_template('8-cities_by_states.html', S=lista, C=cities))\n\n\n@app.route('/states')\ndef only_states():\n \"\"\" send all states\n \"\"\"\n lista = []\n dic = storage.all('State')\n for elem in dic:\n lista.append((dic[elem].id, dic[elem].name))\n lista = sorted(lista, key=lambda x: x[1])\n return (render_template('9-states.html', S=lista, C=None, F=3))\n\n\n@app.route('/states/')\ndef city_of_state_id(id):\n \"\"\" cities of state id\n \"\"\"\n lista = []\n flag = 0\n dic = storage.all('State')\n for key in dic:\n if (id == dic[key].id):\n flag = 1\n lista.append((dic[key].id, dic[key].name))\n if (flag == 0):\n return (render_template('9-states.html', S=None, C=None, F=0))\n dic = storage.all('City')\n cities = []\n for elem in dic:\n if (dic[elem].state_id == lista[0][0]):\n cities.append((dic[elem].id, dic[elem].name))\n cities = sorted(cities, key=lambda x: x[1])\n return (render_template('9-states.html', S=lista, C=cities, F=1))\n\n\n@app.route('/hbnb_filters')\ndef hbnb ():\n \"\"\" using static web page created before\n \"\"\"\n states, S = [], []\n cities, C = [], []\n amenities, A = [], []\n dic = storage.all('State')\n for elem in dic:\n states.append((dic[elem].id, dic[elem].name))\n S = sorted(states, key=lambda x: x[1])\n dic = storage.all('City')\n for el in dic:\n cities.append((dic[el].id, dic[el].name, dic[el].state_id))\n C = sorted(cities, key=lambda x: x[1])\n dic = storage.all('Amenity')\n for elem in dic:\n amenities.append((dic[elem].id, dic[elem].name))\n A = sorted(amenities, key=lambda x: x[1])\n return render_template('10-hbnb_filters.html', S=S, C=C, A=A)\n\n\n@app.teardown_appcontext\ndef close(var=None):\n \"\"\" realizae this, when the process finishes\n \"\"\"\n storage.close()\n\n\nif __name__ == \"__main__\":\n # config the run\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"web_flask/10-hbnb_filters.py","file_name":"10-hbnb_filters.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"59507942","text":"from premalifescience.settings import STATICFILES_DIRS, STATIC_URL\nfrom django.contrib import admin\nfrom django.urls import path,include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom . import views\n\n \nadmin.site.site_header=\"prema life sciences\"\nadmin.site.site_title=\"welcome to our Dashboard\"\nadmin.site.index_title=\"welcome to this portal\"\nurlpatterns = [\n path('',views.Home, name='Home'),\n path('AboutUS',views.AboutUS, name='AboutUS'),\n path('Contact',views.Contact, name='Contact'),\n path('products/',views.PRODUCTS, name='PRODUCTS'),\n path('products',views.PRODUCTSHOME, name='PRODUCTSHOME'),\n path('covid',views.COVID19SOLUTIONSHOME, name='COVID19SOLUTIONSHOME'),\n \n path('covid/',views.COVID19SOLUTIONS, name='COVID19SOLUTIONS'),\n path('media',views.MEDIA, name='MEDIA'),\n path('career',views.CAREER, name='CAREER'),\n path('terms-conditions',views.Terms,name='Terms'),\n path('policies',views.Policies,name='Policies')\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"premalifescience/Home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"191650006","text":"import vk\nimport time\nimport winsound\n\n\nsession = vk.Session(access_token='enter here your token')\napi = vk.API(session, v='5.74')\n\ni = 0\nwhile 1:\n if(i == 3):\n break;\n api.messages.send(peer_id=list_of_groups[i], message='Echo test');\n #api.wall.post(message='Test');\n #api.messages.createChat(user_ids='427270575', title='Test');\n #api.messages.send(domain='daynichnemnogo', random_id=i, message='Test');\n winsound.Beep(3000, 650)\n print('Done!');\n i = i + 1;\n print('Цикл ' + str(i));\n time.sleep(5);\n","sub_path":"First.py","file_name":"First.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"632429609","text":"################################################### You MIGHT need this import.\nfrom net import Net\nimport theano.tensor as T\nimport theano\nimport lasagne\nimport numpy as np\nimport cv2\n\nclass Tester(object):\n def __init__(self, snapshot_path):\n # The original Girshick's code requires this field to exist.\n self.name = ''\n\n ###################################################### Your code goes here.\n # Load your network into, say, self.net.\n self.net = Net(snapshot_path)\n self.image_w = self.net.image_w\n\n def preprocess(self, img):\n img = img.astype('float32')\n resized_image = np.zeros(shape = (1, 3, self.image_w, self.image_w))\n resized_image[0,2,:,:] = cv2.resize(img[2,:,:], (self.image_w, self.image_w))\n resized_image[0,1,:,:] = cv2.resize(img[1,:,:], (self.image_w, self.image_w)) \n resized_image[0,0,:,:] = cv2.resize(img[0,:,:], (self.image_w, self.image_w)) \n return resized_image.astype('float32')\n \n \n def forward(self, data, rois):\n \"\"\"Performs a forward pass through the neural network.\n\n Arguments:\n data (ndarray): tensor containing the whole scenes (images)\n rois (ndarray): tensor containg ROIs; rois[:, 0] are indices of scenes \n in data, the rest are (left, top, bottom, right) \n coordinates\n\n Returns:\n output (dict): a dictionary with a single key 'cls_prob' holding\n probability distributions produced by the network\n \"\"\"\n\n ###################################################### Your code goes here.\n # You should have the following line:\n \n input_X = T.tensor4()\n output_layer = self.net.prediction\n \n prediction = lasagne.layers.get_output(output_layer, input_X, deterministic=True)\n \n pred_fun = theano.function([input_X], prediction)\n input_data = np.zeros(shape = (len(rois[:,0]), 3, self.image_w, self.image_w))\n for i in range(len(rois[:,0])):\n img = data[rois[:, 0][i].astype('int')]\n img = img[:, rois[i,2].astype('int'):rois[i,4].astype('int'), rois[i,1].astype('int'):rois[i,3].astype('int')]\n input_data[i, :, :, :] = self.preprocess(img)\n \n batch_size = 128\n start = 0\n net_output = pred_fun(input_data[0:batch_size].astype('float32'))\n for start in range(batch_size, len(rois[:,0]), batch_size):\n end = min(start+batch_size, len(rois[:,0]))\n a = pred_fun(input_data[start:end].astype('float32'))\n net_output = np.concatenate((net_output, a), axis = 0)\n \n output = {'cls_prob': net_output}\n\n return output\n","sub_path":"HW6 RCNN/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"501485654","text":"'''\nExercise 1: [wordlist2]\n\nWrite a program that reads the words in words.txt and stores them as keys in a dictionary. \nIt doesn't matter what the values are. \nThen you can use the in operator as a fast way to check whether a string is in the dictionary.\n\n'''\n\nword_list = dict()\nfile = open('words.txt')\nfor word in file:\n item = word.strip()\n #count = (word_list.get(word,-99))\n word_list[item] = True\n #vals = list(word_list())\n\nprint(word_list)\n#vals = list(word_list())\n\ncheck_word = input('Type in a word to check if in dictionary:',)\n\nif check_word in word_list:\n#if check_word in vals:\n print(check_word + ' is in dictionary')\nelse:\n print(check_word + ' is not in dictionary')\n\n\n#'Day' in word_list\n#print(word_list['Apple']) \n\n\n#list_lenght = len(word_list)\n#print(list_lenght)\n#word_list.sort()\n#print(word_list)\n","sub_path":"chapter_9/ch_9_ex_1.py","file_name":"ch_9_ex_1.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"181157742","text":"import csv\n\nr_fileTSV = 'data_promesse.tsv'\n\nw_fileTSV = '/root/Documents/Faustine/data_promesse_avec_sommes.tsv'\n\ntitres=[\"Auteur\",\"Titre\",\"Date\",\"Genre\",\"Citation\",\"parjure\",\"serment\",\"promesse\",\"engagement\",\"pacte\",\"gage\",\"foi\",\"voeu\",\"parole\",\"traitre\",\"alliance\",\"caution\",\"garantie\",\"contrat\",\"traite\"]\n\nwith open(\"data_promesse.tsv\") as fd:\n rd = csv.reader(fd, delimiter=\"\\t\", quotechar='\"')\n for row in rd:\n print(row)\n","sub_path":"sommation_colonnes.py","file_name":"sommation_colonnes.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"1000121","text":"from google.colab import files\n\nuploaded = files.upload()\nfor fn in uploaded.keys():\n text = uploaded[fn].decode()\n \n \nimport random\nfrom textblob import TextBlob\n\nimport nltk\nnltk.download('punkt')\nnltk.download('averaged_perceptron_tagger')\n\nwith open('skyrim32.txt', 'r') as file:\n text = file.read()\n\nblob = TextBlob(text)\n\nadjectives = []\nnouns = []\nverbs = []\nadverbs = []\npropernouns = []\nprep = []\nperpro = []\nconj = []\ninter = []\npresverb = []\n\nfor word,pos in blob.tags:\n if (pos == 'JJ'):\n adjectives.append(word)\n if (pos == 'NN'):\n nouns.append(word)\n if (pos == 'VBG'):\n verbs.append(word)\n if (pos == 'RB'):\n adverbs.append(word)\n if (pos == 'NNP'):\n propernouns.append(word)\n if (pos == 'IN'):\n prep.append(word)\n if (pos == 'PRP'):\n perpro.append(word) \n if (pos == 'CC'):\n conj.append(word)\n if (pos == 'UH'):\n inter.append(word)\n if (pos == 'VBP'):\n presverb.append(word)\n \nfor i in range(3):\n a = random.choice(adjectives)\n b = random.choice(nouns)\n b2 = random.choice(nouns)\n c = random.choice(verbs)\n d = random.choice(adverbs)\n e = random.choice(propernouns)\n f = random.choice(prep)\n g = random.choice(conj)\n g2 = random.choice(conj)\n e2 = random.choice(propernouns)\n h = random.choice(inter)\n i = random.choice(perpro) \n j = random.choice(presverb)\n \n print(e,'and',e2,c)\n print(e,c,b)\n print(e2,c,b2)\n","sub_path":"poem/SkyrimPoem.py","file_name":"SkyrimPoem.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"455999059","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^login$', views.login),\n url(r'^register/$', views.register),\n url(r'^process$', views.register_user),\n url(r'^logging$', views.logging),\n]\n","sub_path":"Python/django/belt_exam/apps/login/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"447697389","text":"# intake system list from EVE ESI, pull values in to dictionary, sort dictionary by npc kills, show top 10\n# add options for more data retrieval later\n\n#imports\nimport requests\nimport sqlite3\nimport json\nimport operator\nimport itertools\nimport pandas as pd\nfrom operator import itemgetter\n###############################################################################\n#Master Variables that the user can change\n#System to start routing from (must appear exactly as it does in game):\norigin = \"Jita\"\n##############################################################################\n\n#in case of unexpected CCP URL change fix this\nbase_system_url = \"https://esi.evetech.net/latest/universe/system_kills/?datasource=tranquility\"\n\n#eve sde connect boilerplate - assumes SQLITE SDE is in same directory as this python script\n#if not you should fix that cause I'm not changing this\n#download latest EVE SDE from https://www.fuzzwork.co.uk/dump/sqlite-latest.sqlite.bz2 \nprint(\"\\nConnecting to local database and requesting/parsing EVE ESI data...\")\ndatabase = r\"sqlite-latest.sqlite\"\nconn = sqlite3.connect(database)\ncur = conn.cursor()\n\ncur.execute(\"SELECT solarSystemID FROM mapSolarSystems WHERE solarSystemName=?\", (origin,))\noriginID = cur.fetchone()\noriginID = originID[0]\n\nprint(\"Getting system data json...\")\nsystem_data = requests.get(base_system_url)\nsystems_json = system_data.json()\n\n\n#make 2 lists at the same time in the same for loop that we can then convert to a dict of key value pairs\n#where the key is the systemID and the value is the npc kills\nsys_id = []\nnpc_kills = []\n\ni = 0\nfor system in systems_json:\n name = systems_json[i][\"system_id\"]\n cur.execute(\"SELECT solarSystemName FROM mapSolarSystems WHERE solarSystemID=?\", (name,))\n name = cur.fetchone() \n sys_id.append(name[0])\n npc_kills.append(systems_json[i][\"npc_kills\"])\n i += 1\nprint(\"Looped through system ids, creating dictionary...\")\nmaster_dict = {sys_id[i]: npc_kills[i] for i in range(len(sys_id))} \n\n#playing with pandas instead of attempting to sort dicts seems smart here\ndf = pd.Series(master_dict)\ndf.index.name = 'System'\nregion_list = []\nprint(\"Creating region name list...\")\nfor key in master_dict:\n cur.execute(\"SELECT regionID FROM mapSolarSystems WHERE solarSystemName=?\", (key,))\n regionID = cur.fetchone()\n cur.execute(\"SELECT regionName FROM mapRegions WHERE regionID=?\", (regionID[0],))\n regionName = cur.fetchone()\n region_list.append(regionName[0])\n\nprint(\"Creating presorted master dataframe...\")\npddata = { 'Region': region_list, 'System': sys_id, 'Kills': npc_kills, }\n\ndf1 = pd.DataFrame(pddata)\n\njumps = []\nregion = []\nsystem = []\nnpcs = []\nprint(\"Sorting by kills and obtaining routing data from origin system specified to top 30 systems...\")\ndf1.sort_values(by=['Kills'], ascending=False, inplace=True)\nfor item in df1.head(30).itertuples():\n region.append(item.Region)\n system.append(item.System)\n npcs.append(item.Kills)\n sys = item.System\n cur.execute(\"SELECT solarSystemID FROM mapSolarSystems WHERE solarSystemName=?\", (sys,))\n destiID = cur.fetchone()\n URLstring = \"https://esi.evetech.net/latest/route/\" + str(originID) + \"/\" + str(destiID[0]) + \"/?datasource=tranquility&flag=shortest\"\n get_route_json = requests.get(URLstring)\n load_route_json = get_route_json.json()\n i = len(load_route_json)\n jumps.append(i)\n\n\nfinaldata = { \"Region\": region, \"System\": system, \"NPC Kills\": npcs, \"Jumps\": jumps, }\nprint(\"Inserting jump data to short dataframe...\")\nnewframe = pd.DataFrame(finaldata)\nnewframe.assign(region=region)\nnewframe.assign(system=system)\nnewframe.assign(kills=npcs)\nnewframe.assign(jumps=jumps)\nnewframe.reset_index()\n\nprint(\"\\n\\n\\nSorted by npc kills:\")\nprint(newframe.to_string(index=False))\nnewframe.sort_values(by='Jumps', ascending=True, inplace=True)\nprint(\"\\n\\nSorted by jumps from origin system:\")\nprint(newframe.to_string(index=False))\n","sub_path":"activewhere.py","file_name":"activewhere.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"19927856","text":"from tkinter import *\nimport sys,copy,tkinter.messagebox\nfrom numpy import *\n\ntree=Tk()\ntree.title('continuous-time branching process')\ntop=Frame(tree)\ntop.pack(side=TOP)\n\nbframe=Frame(tree)\nbframe.pack(side=LEFT)\n\nclass bcanvas: \n def __init__(self,root,width,height):\n self.root=root\n self.width=width\n self.height=height\n try:\n self.canvas = Canvas(self.root, width=self.width, height=self.height, bg = 'white')\n self.canvas.pack()\n self.clear()\n except:\n print ('An error has occured in init!')\n\n def clear(self):\n try:\n self.canvas.create_rectangle(0,0,self.width,self.height,fill='white')\n except:\n print ('An error has occured in clear!')\n\n def drawb(self,t,y): \n r=0.015*self.height\n self.canvas.create_oval(self.width*t-r,self.height*y-r,self.width*t+r,self.height*y+r,outline='black', fill='blue')\n\n def drawd(self,t,y): \n r=0.015*self.height\n self.canvas.create_oval(self.width*t-r,self.height*y-r,self.width*t+r,self.height*y+r,outline='black', fill='red')\n\n\n def drawl(self,x,dx,v):\n for y in v:\n self.canvas.create_line((self.width*x,self.height*y),(self.width*x+self.width*dx,self.height*y),width=2,fill='blue')\n\n def drawv(self,t,y1,y2):\n self.canvas.create_line((self.width*t,self.height*y1),(self.width*t,self.height*y2),width=2,fill='blue')\n\nonoff=False\ndef toggle(event):\n global onoff\n if onoff:\n onoff=False\n else:\n onoff=True\n\nb=0.2\nd=0.1\ntmax=15.0\ndt=tmax/1000.0\n\n# Runs the animation when button is pressed\ndef run():\n global onoff \n tmax=tm.get()\n b=pbor.get()\n d=pdie.get()\n error=StringVar() \n\n n=n1.get()#int(input)\n print ('===start run===')\n cg.clear()\n\n v=[] # list of living individuals; stores a vertical position for each\n if n==1:v=[0.5] # start with one\n if n==2:v=[0.3,0.6]\n if n==3:v=[0.25,0.5,0.75]\n if n==4:v=[0.2,0.4,0.6,0.8]\n\n t=0\n while t<=tmax and len(v)>0:\n t+=dt\n rate = b*len(v)\n urv=random.random()\n if urv < rate*dt:\n print (urv,b*len(v),d*len(v))\n if len(v)==1:\n vnow=sum(v)\n v=[0.5*vnow,0.5*(1+vnow)]\n print (v)\n cg.drawb(t/tmax,v[0])\n cg.drawb(t/tmax,v[1])\n cg.drawv(t/tmax,v[0],v[1])\n else:\n i=random.randint(len(v))\n vm1=v[i]\n if i==0:\n newv=(0.05+vm1)/2\n else:\n vm2=v[i-1]\n newv=vm1+(vm2-vm1)/3.0\n v[i]=newv\n if i==len(v)-1:\n pairv=(0.95+vm1)/2\n else:\n vm2=v[i+1]\n pairv=vm1+(vm2-vm1)/3.0\n v.append(pairv)\n cg.drawv(t/tmax,newv,pairv)\n cg.drawb(t/tmax,newv)\n cg.drawb(t/tmax,pairv)\n v.sort()\n print (t,len(v))\n else:\n rate = (b+d)*len(v)\n if urv',toggle)\nbut.pack(side=TOP)\ntm=Scale(top, orient=HORIZONTAL, length=184, from_=0.0, to=20.0, tickinterval=5, resolution=5,label='maximum time')\ntm.set(tmax)\ntm.pack(side=LEFT)\n\n# Now the sliders (in a frame called sframe)\npbor=Scale(top, orient=HORIZONTAL, length=214, from_=0., to=1.2, tickinterval=.5, resolution=0.1,label='birth')\npbor.set(b)\npbor.pack(side=LEFT)\npdie=Scale(top, orient=HORIZONTAL, length=214, from_=0., to=1.2, tickinterval=.5, resolution=0.1,label='death')\npdie.set(d)\npdie.pack(side=LEFT)\n\nn1=Scale(top, orient=HORIZONTAL, length=184, from_=0, to=4, tickinterval=1, resolution=1,label='Starting number of cells')\nn1.set(1)\nn1.pack(side=LEFT)\n\ntotalwidth=1200\ntotalheight=300\ncg=bcanvas(tree,totalwidth,totalheight)\n\ntree.mainloop()\n","sub_path":"Continuous Time Branching Process python 3.py","file_name":"Continuous Time Branching Process python 3.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"306014724","text":"from tkinter import *\r\n\r\nclass Interface(Frame):\r\n \"\"\"Fenêtre principale. Tous les widgets sont stockés comme \r\n attributs de cette fenêtre. La classe hérite d'un cadre \r\n (frame)\"\"\"\r\n \r\n def __init__(self, fenetre, **kwargs):\r\n Frame.__init__(self, fenetre, width=768, height=576, \r\n **kwargs)\r\n \"\"\"On appel le constructeur de la classe Frame\"\"\"\r\n self.pack(fill=BOTH)\r\n self.nb_clic = 0\r\n \r\n # Création de nos widgets\r\n # Message\r\n self.message = Label(self, text=\"Vous n'avez pas cliqué\")\r\n self.message.pack()\r\n \r\n # Bouton quitter\r\n self.bouton_quitter = Button(self, text=\"Quitter\", \r\n command=self.quit)\r\n self.bouton_quitter.pack(side=\"left\")\r\n \r\n # Bouton cliquer\r\n self.bouton_cliquer = Button(self, text=\"Cliquez ici\", \r\n fg=\"red\", command=self.cliquer)\r\n \"\"\"Prend en commande la fonction 'cliquer' \"\"\"\r\n self.bouton_cliquer.pack(side=\"right\")\r\n \r\n def cliquer(self):\r\n \"\"\"Il y a eu un clic sur le bouton. On change la valeur du \r\n label message\"\"\"\r\n \r\n self.nb_clic += 1\r\n self.message[\"text\"] = \"Vous avez cliqué {} fois.\".format(\r\n self.nb_clic)\r\n\r\nfenetre = Tk() # Création de la fenêtre Tkinter\r\ninterface = Interface(fenetre)\r\n\r\ninterface.mainloop() # Interompe la boucle à la fermeture\r\ninterface.destroy() # Détruit la fenêtre\r\n \r\n","sub_path":"Classe.py","file_name":"Classe.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"47426469","text":"from opengever.base.sentry import log_msg_to_sentry\nfrom Products.PortalTransforms.data import datastream\nfrom Products.PortalTransforms.transforms.safe_html import SafeHTML\nfrom zope.globalrequest import getRequest\n\n\n# These are the HTML tags that are supported by sablon\n# Value is 1 if they have a closing part (e.g.

...

) and 0 for empty\n# tags (like
).\nVALID_TAGS = {\n 'b' : 1,\n# trix delivers html5 and not xhtml, so we we use 1 here to force
\n 'br' : 1,\n 'div' : 1,\n 'em' : 1,\n 'i' : 1,\n 'li' : 1,\n 'ol' : 1,\n 'p' : 1,\n 'strong' : 1,\n 'u' : 1,\n 'ul' : 1,\n}\n\n\nSERVER_SIDE_STRING_MAX_LENGTH = 2**14\n\n\n_transform = SafeHTML(name='trix_to_sablon', valid_tags=VALID_TAGS)\n\n\ndef convert(markup):\n \"\"\"Use this function to transform markup from trix to markup that can\n be processed by sablon.\n\n This converter is expected to do nothing since trix markup is already valid\n for sablon. It is just a safeguard against malicious markup injection or\n against changes in trix.\n\n Thus we also log to sentry whenever we actually have to convert markup.\n\n \"\"\"\n data = _transform.convert(markup, data=datastream('trix_to_sablon'))\n converted = data.getData()\n if converted != markup:\n _log_unexpected_conversion_to_sentry(converted, markup)\n return converted\n\n\ndef _log_unexpected_conversion_to_sentry(converted, markup):\n request = getRequest()\n\n extra = {\n 'converted_html': converted,\n 'source_html': markup\n }\n\n log_msg_to_sentry(\n 'Unexpected html during trix/sablon conversion',\n request=request,\n url=request.get('ACTUAL_URL', ''),\n extra=extra,\n string_max_length=SERVER_SIDE_STRING_MAX_LENGTH)\n","sub_path":"opengever/base/transforms/trix2sablon.py","file_name":"trix2sablon.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"493546371","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /c/Users/byk/Documents/Projects/sentry/sentry/src/sentry/testutils/helpers/options.py\n# Compiled at: 2019-08-16 17:27:46\nfrom __future__ import absolute_import\n__all__ = ['override_options']\nfrom django.test.utils import override_settings\nfrom contextlib import contextmanager\nfrom mock import patch\n\n@contextmanager\ndef override_options(options):\n \"\"\"\n A context manager for overriding specific configuration\n Options.\n \"\"\"\n from django.conf import settings\n from sentry.options import default_manager\n wrapped = default_manager.store.get\n\n def new_get(key, **kwargs):\n try:\n return options[key.name]\n except KeyError:\n return wrapped(key, **kwargs)\n\n new_options = settings.SENTRY_OPTIONS.copy()\n new_options.update(options)\n with override_settings(SENTRY_OPTIONS=new_options):\n with patch.object(default_manager.store, 'get', side_effect=new_get):\n yield","sub_path":"pycfiles/sentry-10.0.0-py27-none-any/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"638214385","text":"import sys\n\nimport tensorflow as tf\n\nDataset = tf.data.Dataset\nmnist = tf.keras.datasets.mnist\n\n# Add InjectTF2 to python path.\ninject_tf2_path = \"../\"\n\nif inject_tf2_path not in sys.path:\n sys.path.append(inject_tf2_path)\n\nfrom inject_tf2 import InjectTF2\n\n\n# Prepare data set\n(_, _), (x_test, y_test) = mnist.load_data()\nx_test = x_test / 255.0\n\n# Add a channels dimension\nx_test = x_test[..., tf.newaxis].astype(\"float32\")\ntest_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test))\n\n\nmodel = tf.keras.models.load_model(\"mnist_model.h5\") \n\nmodel.summary()\n\nitf2 = InjectTF2(model, \"./example_config.yml\", test_ds, 32, \"INFO\")\n\nitf2.evaluate_layer_with_injections()\n","sub_path":"example/inject_example_random_bit.py","file_name":"inject_example_random_bit.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"168655987","text":"from panda3d.core import NodePath, Vec4, TextNode, CardMaker, TransparencyAttrib\n\nfrom direct.interval.IntervalGlobal import LerpColorScaleInterval, Sequence, Func, Wait, Parallel\n\nfrom toontown.achievements import Achievements\nfrom toontown.toonbase import ToontownGlobals\nfrom toontown.toonbase import TTLocalizer\n\n\nachievementModel = loader.loadModel('phase_3.5/models/gui/achievement_set.bam')\nachievementSfx = base.loadSfx('phase_3.5/audio/sfx/poof_in.ogg')\nlockTexture = loader.loadTexture('phase_3.5/maps/achievement_lock.png')\n\nCategoryModels = {\n Achievements.BRONZE: achievementModel.find('**/achievement1'),\n Achievements.SILVER: achievementModel.find('**/achievement2'),\n Achievements.GOLD: achievementModel.find('**/achievement3'),\n Achievements.PLATINUM: achievementModel.find('**/achievement4')\n}\n\n\nclass AchievementNode(NodePath):\n def __init__(self, achievementId, faded=False, locked=False):\n NodePath.__init__(self, hidden.attachNewNode('achievement-%s-%s' % (achievementId, id(self))))\n\n self.achievementId = achievementId\n self.category = Achievements.getAchievementCategory(self.achievementId)\n\n CategoryModels[self.category].copyTo(self)\n\n if not faded:\n self.generateAchievementInfo()\n\n if locked:\n cm = CardMaker('lock')\n lock = self.attachNewNode(cm.generate())\n lock.setTransparency(TransparencyAttrib.MAlpha)\n lock.setTexture(lockTexture)\n lock.setScale(0.35)\n lock.setPos(1.5, 0, -0.025)\n lock.setColorScale(0, 0, 0, 0.6)\n\n if faded:\n self.setColorScale(0, 0, 0, 0.1)\n\n self.flattenStrong()\n\n def generateAchievementInfo(self):\n acievementInfo = TTLocalizer.getAchievementInfo(self.achievementId)\n\n title = TextNode('title')\n title.setText(acievementInfo[0])\n title.setFont(ToontownGlobals.getSignFont())\n title.setTextColor(1, 1, 1, 1)\n title.setAlign(TextNode.ACenter)\n\n titleNode = self.attachNewNode(title)\n titleNode.setScale(0.2)\n titleNode.setZ(0.2)\n\n description = TextNode('description')\n description.setText(acievementInfo[1])\n description.setFont(ToontownGlobals.getSignFont())\n description.setTextColor(1, 1, 1, 1)\n description.setAlign(TextNode.ACenter)\n\n descriptionNode = self.attachNewNode(description)\n descriptionNode.setScale(0.15)\n descriptionNode.setZ(-0.14)\n\n\nclass AchievementPopup(NodePath):\n def __init__(self, achievementId):\n NodePath.__init__(self, hidden.attachNewNode('achievement-popup-%s' % id(self)))\n\n AchievementNode(achievementId).reparentTo(self)\n\n self.reparentTo(base.a2dTopCenter, 4000)\n self.stash()\n\n self.setScale(0.3)\n self.setZ(-0.18)\n\n self.callback = None\n\n def setCallback(self, callback):\n self.callback = callback\n\n def doCallback(self):\n if self.callback is not None:\n self.callback()\n\n def cleanup(self):\n self.removeNode()\n\n def play(self):\n Sequence(\n Parallel(\n Sequence(\n Func(self.unstash),\n Func(self.setTransparency, 1),\n LerpColorScaleInterval(self, 1.2, Vec4(1, 1, 1, 1), startColorScale=Vec4(1, 1, 1, 0)),\n Func(self.clearColorScale),\n Func(self.clearTransparency)\n ),\n Func(base.playSfx, achievementSfx)\n ),\n Wait(2.5),\n Sequence(\n Func(self.setTransparency, 1),\n LerpColorScaleInterval(self, 0.4, Vec4(1, 1, 1, 0), startColorScale=Vec4(1, 1, 1, 1)),\n Func(self.clearColorScale),\n Func(self.clearTransparency),\n Func(self.stash)\n ),\n Func(self.cleanup),\n Func(self.doCallback)\n ).start()\n\n\nclass AchievementsGUI:\n def __init__(self):\n self.queue = []\n self.playing = False\n\n def showAchievement(self, achievementId):\n popup = AchievementPopup(achievementId)\n self.queue.append(popup)\n\n if self.playing is False:\n self.playing = True\n self.showNext()\n\n def showNext(self):\n if len(self.queue) == 0:\n self.playing = False\n return\n\n popup = self.queue.pop(0)\n popup.setCallback(self.showNext)\n popup.play()\n","sub_path":"src/toontown/achievements/AchievementsGUI.py","file_name":"AchievementsGUI.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"429836873","text":"# test_reader.py\nimport unittest\nfrom reader import Reader\nimport warnings\n\nclass TestReader(unittest.TestCase):\n\n def setUp(self):\n self.reader = Reader(\"role\", None)\n warnings.filterwarnings(\"ignore\", category=ResourceWarning, message=\"unclosed.*\") \n\n def test_get_roles(self):\n roles = self.reader.get_roles()\n self.assertIsNotNone(roles)\n\n def test_get_unused_role_permissions(self):\n roles = self.reader.get_roles()\n unused = self.reader.get_unused_role_permissions(roles[1])\n self.assertIsNotNone(roles)\n self.assertIsNotNone(unused)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"iamunused/test_reader.py","file_name":"test_reader.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"358056718","text":"from flask import *\r\nimport textsummary\r\nimport audiosummary\r\nimport video\r\n\r\napp=Flask(__name__)\r\n\r\n\r\n@app.route(\"/\")\r\ndef demo():\r\n return render_template(\"index.html\")\r\n\r\n@app.route(\"/upload\")\r\ndef upload():\r\n return render_template(\"file_upload1.html\")\r\n\r\n@app.route(\"/upload1\")\r\ndef upload1():\r\n return render_template(\"file_upload2.html\")\r\n\r\n@app.route(\"/upload2\")\r\ndef upload2():\r\n return render_template(\"file_upload3.html\")\r\n\r\n@app.route(\"/summarize\",methods=[\"POST\"])\r\ndef summarize():\r\n global file\r\n f=request.files['file']\r\n file=f.filename\r\n f.save(file)\r\n textsummary.generate_summary(file)\r\n filename=file.split(\".\")[0]+\"summary.txt\"\r\n return send_file(filename,as_attachment=True, cache_timeout=0)\r\n \r\n\r\n@app.route(\"/audiosummarize\",methods=[\"POST\"])\r\ndef audiosummarize():\r\n global file\r\n f=request.files['file']\r\n file=f.filename\r\n f.save(file)\r\n audiosummary.get_large_audio_transcription(file)\r\n filename=\"audiosummary.txt\"\r\n return send_file(filename,as_attachment=True, cache_timeout=0)\r\n\r\n@app.route(\"/audiotextsummarize\",methods=[\"POST\"])\r\ndef audio():\r\n filename=\"audio.txt\"\r\n return send_file(filename,as_attachment=True, cache_timeout=0)\r\n \r\n@app.route(\"/videosummarize\",methods=[\"POST\"])\r\ndef videosummarize():\r\n global file\r\n f=request.files['file']\r\n file=f.filename\r\n f.save(file)\r\n video.videosummary(file)\r\n filename=\"videosummary.txt\"\r\n return send_file(filename,as_attachment=True, cache_timeout=0)\r\n\r\n@app.route(\"/videotextsummarize\",methods=[\"POST\"])\r\ndef video1():\r\n filename=\"video.txt\"\r\n return send_file(filename,as_attachment=True, cache_timeout=0)\r\n \r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"285698637","text":"#!/usr/bin/python\n\nfrom Tkinter import *\nimport math\n\nkey_list = ['7','8','9','+',\n\t\t\t'4','5','6','-',\n\t\t\t'1','2','3','*',\n\t\t\t'0','.','%','/']\n\ntop = Tk()\ntop.geometry('320x280')\ntop.resizable(False, False) \ndef button(root,text,row,col,command = None):\n bt = Button(root,text = text,width = 10,height = 2,command = command)\n bt.grid(row = row,column = col)\n return bt\ndisplay = StringVar()\n\n\ndef colc(event):\n try:\n display.set(eval(display.get()))\n except:\n display.set('ERROR!')\n\nLabel(top,textvariable = display,bg = 'white',anchor = E,width = 44,height = 2).grid(columnspan = 20)\n\nKey = enumerate(key_list)\nfor index,i in Key:\n row = index / 4 + 1\n col = index % 4\n button(top,i,row,col,lambda d = display,s = i:d.set(d.get() + s))\n\nKeys = enumerate(['CLR','^','&','='])\nfor x,y in Keys:\n row = x / 4 + 5\n col = x % 4\n if(y == 'CLR'):\n button(top,y,row,col,lambda d = display:d.set(''))\n elif(y == '^'):\n button(top,y,row,col,lambda d = display:d.set(d.get() + '**'))\n elif(y == '&'):\n button(top,y,row,col,lambda d = display:d.set((math.sqrt(float(d.get()))))) \n elif(y == '='):\n bt = button(top,y,row,col)\n bt.bind('',colc)\ntop.mainloop()\n\n","sub_path":"py/cal.py","file_name":"cal.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"241660738","text":"import csv\n\ndef csv_readlist(file, file_path):\n ## csv read as list\n csv_list = []\n full_path = file_path + file\n with open(full_path) as f:\n reader = csv.DictReader(f)\n for i in reader:\n csv_list.append(i)\n return csv_list\n\ndef csv_writelist(file, file_path, data):\n ## csv write list\n full_path = file_path + file\n field = data[0].keys()\n \n with open(full_path, 'wb') as f:\n writer = csv.DictWriter(f, field)\n writer.writeheader()\n writer.writerows(data)\n \n \nif __name__ == \"__main__\":\n file_path = '/srv/www/idehe.com/store2/stock_data/'\n file = 'ETF.csv'\n test_data = [{'aa':'BB'}]\n csv_writelist(file, file_path, test_data)\n #print csv_readlist(file, file_path)","sub_path":"csv_handle.py","file_name":"csv_handle.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"573300460","text":"import logging\nfrom rasa_core import config\nfrom rasa_core import utils\nfrom rasa_core.channels.slack import SlackInput\nfrom rasa_core.agent import Agent\nfrom rasa_core.interpreter import RasaNLUInterpreter\nfrom rasa_core.utils import EndpointConfig\n\n\nlogfile = 'dialogue_model.log'\n\n\ndef train_core(domain_file, model_path, training_data_file, policy_config):\n logging.basicConfig(filename=logfile, level=logging.DEBUG)\n agent = Agent(domain_file, policies=config.load(policy_config))\n training_data = agent.load_data(training_data_file)\n agent.train(training_data)\n agent.persist(model_path)\n return agent\n\n\ndef run_core(core_model_path, nlu_model_path, action_endpoint_url, slack_token):\n logging.basicConfig(filename=logfile, level=logging.DEBUG)\n nlu_interpreter = RasaNLUInterpreter(nlu_model_path)\n action_endpoint = EndpointConfig(url=action_endpoint_url)\n agent = Agent.load(core_model_path, interpreter=nlu_interpreter, action_endpoint=action_endpoint)\n input_channel = SlackInput(slack_token)\n agent.handle_channels([input_channel], 5004, serve_forever=True)\n\n print(\"Your bot is ready to talk! Type your messages here or send 'stop'\")\n while True:\n a = input()\n if a == 'stop':\n break\n responses = agent.handle_text(a)\n for response in responses:\n print(response[\"text\"])\n return agent\n\n\nif __name__ == '__main__':\n actionConfig = utils.read_yaml_file('endpoints.yml')\n slackConfig = utils.read_yaml_file('credentials.yml')\n train_core('domain.yml', './models/current/dialogue', './data/stories.md', 'policy.yml')\n run_core('./models/current/dialogue', './models/current/nlu',\n actionConfig[\"action_endpoint\"][\"url\"], slackConfig[\"slack\"][\"slack_token\"])\n","sub_path":"rasa_gstack/dialogue_model.py","file_name":"dialogue_model.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"312103669","text":"import qwiic_button\nimport time\nimport board\nimport busio\nimport digitalio\nimport subprocess\nfrom PIL import Image, ImageDraw, ImageFont\nimport adafruit_mpr121\nimport adafruit_rgb_display.st7789 as st7789\nimport webcolors\n\n\n# Configuration for CS and DC pins (these are FeatherWing defaults on M0/M4):\ncs_pin = digitalio.DigitalInOut(board.CE0)\ndc_pin = digitalio.DigitalInOut(board.D25)\nreset_pin = None\n# Config for display baudrate (default max is 24mhz):\nBAUDRATE = 64000000\n# Setup SPI bus using hardware SPI:\nspi = board.SPI()\n# Create the ST7789 display:\ndisp = st7789.ST7789(\n spi,\n cs=cs_pin,\n dc=dc_pin,\n rst=reset_pin,\n baudrate=BAUDRATE,\n width=135,\n height=240,\n x_offset=53,\n y_offset=40,\n)\n# Create blank image for drawing.\n# Make sure to create image with mode 'RGB' for full color.\nheight = disp.width # we swap height/width to rotate it to landscape!\nwidth = disp.height\nimage = Image.new(\"RGB\", (width, height))\nrotation = 90\n# Get drawing object to draw on image.\ndraw = ImageDraw.Draw(image)\n# Draw a black filled box to clear the image.\ndraw.rectangle((0, 0, width, height), outline=0, fill=(0, 0, 0))\ndisp.image(image, rotation)\n# Draw some shapes.\n# First define some constants to allow easy resizing of shapes.\npadding = -2\ntop = padding\nbottom = height - padding\n# Move left to right keeping track of the current x position for drawing shapes.\nx = 0\n# Alternatively load a TTF font. Make sure the .ttf font file is in the\n# same directory as the python script!\n# Some other nice fonts to try: http://www.dafont.com/bitmap.php\nfont = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf\", 20)\n# Turn on the backlight\nbacklight = digitalio.DigitalInOut(board.D22)\nbacklight.switch_to_output()\nbacklight.value = True\n\nmy_button = qwiic_button.QwiicButton()\n\nstate = 0\nwhile True:\n draw.rectangle((0, 0, width, height), outline=0, fill=0)\n if state == 0:\n clocktime = time.strftime(\"%A, %B %e, %Y\")\n draw.text((x,top), clocktime, font=font, fill=\"#03cafc\")\n clocktime2 = time.strftime(\"%H:%M:%S\")\n y = top + font.getsize(clocktime)[1]\n draw.text((x, y), clocktime2, font=font, fill=\"#1303fc\")\n disp.image(image, rotation)\n time.sleep(1)\n elif state == 1:\n clocktime = time.strftime(\"%A, %B %e, %Y\")\n draw.text((x,top), clocktime, font=font, fill=\"#03cafc\")\n clocktime2 = time.strftime(\"%I:%M:%S\")\n y = top + font.getsize(clocktime)[1]\n draw.text((x,y), clocktime2, font=font, fill=\"#7703fc\")\n disp.image(image, rotation)\n time.sleep(1) \n if state == 0 and my_button.is_button_pressed()==True:\n state = 1\n elif state == 1 and my_button.is_button_pressed()==True:\n state = 0\n","sub_path":"Lab 4/timer_button.py","file_name":"timer_button.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"403029402","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nimport json\nfrom controller.model import Model\nfrom controller import helper as h\nfrom controller import validate as v\n\n\nclass Page(Model):\n primary = 'name'\n collection = 'page'\n layouts = ['上下一栏', '上下两栏', '上下三栏', '左右两栏'] # 图片的版面结构\n fields = {\n 'name': {'name': '页编码'},\n 'width': {'name': '宽度'},\n 'height': {'name': '高度'},\n 'source': {'name': '数据分类'},\n 'layout': {'name': '页面结构', 'input_type': 'radio', 'options': layouts},\n 'page_code': {'name': '对齐编码'},\n 'book_page': {'name': '原书页码'},\n 'uni_sutra_code': {'name': '统一经编码'},\n 'sutra_code': {'name': '经编码'},\n 'reel_code': {'name': '卷编码'},\n 'blocks': {'name': '栏框数据'},\n 'columns': {'name': '列框数据'},\n 'chars': {'name': '字框数据'},\n 'images': {'name': '图框数据'},\n 'user_links': {'name': '用户序线'},\n 'ocr_chr': {'name': '字框OCR'},\n 'ocr_col': {'name': '列框OCR'},\n 'cmp_txt': {'name': '比对文本'},\n 'txt': {'name': '校对文本'},\n 'nor_txt': {'name': '正字文本'},\n 'txt_match': {'name': '文本匹配'},\n 'has_gen_chars': {'name': '是否已生成字数据'},\n 'tasks': {'name': '任务状态'},\n 'remark_box': {'name': '切分备注'},\n 'remark_txt': {'name': '文本备注'},\n 'create_time': {'name': '创建时间'},\n 'updated_time': {'name': '更新时间'},\n }\n rules = [(v.not_empty, 'name'), (v.is_page, 'name')]\n search_fields = ['name', 'source']\n\n @classmethod\n def metadata(cls):\n return dict(name='', width='', height='', source='', layout='', page_code='', sutra_code='',\n uni_sutra_code='', reel_code='', reel_page_no='', blocks=[], columns=[], chars=[],\n ocr='', ocr_col='', txt='')\n\n @classmethod\n def insert_many(cls, db, file_stream=None, layout=None):\n \"\"\" 插入新页面\n :param db 数据库连接\n :param file_stream 已打开的文件流。\n :param layout 页面的版面结构。\n :return {status: 'success'/'failed', code: '', message: '...', errors:[]}\n \"\"\"\n result = json.load(file_stream)\n page_names = [r.split('.')[0] for r in result]\n name2suffix = {r.split('.')[0]: r.split('.')[1] if '.' in r else None for r in result}\n # 检查���复时,仅仅检查页码,不检查后缀\n existed_pages = list(db.page.find({'name': {'$in': page_names}}, {'name': 1}))\n new_names = set(page_names) - set([p['name'] for p in existed_pages])\n pages = []\n for page_name in new_names:\n page = cls.metadata()\n s = page_name.split('.')\n page['name'] = s[0]\n page['layout'] = layout\n page['page_code'] = h.align_code(s[0])\n page['img_suffix'] = name2suffix.get(page_name)\n pages.append(page)\n if pages:\n r = db.page.insert_many(pages)\n message = '导入page,总共%s条记录,插入%s条,%s条旧数据。' % (len(page_names), len(pages), len(existed_pages))\n return dict(status='success', message=message, inserted_ids=r.inserted_ids if pages else [])\n\n @classmethod\n def get_page_search_condition(cls, request_query):\n request_query = re.sub('[?&]?from=.*$', '', request_query)\n condition, params = dict(), dict()\n q = h.get_url_param('q', request_query)\n if q and cls.search_fields:\n m = len(q) > 1 and q[0] == '='\n condition['$or'] = [{k: q[1:] if m else {'$regex': q}} for k in cls.search_fields]\n for field in ['name', 'source', 'txt', 'remark_box', 'remark_txt']:\n value = h.get_url_param(field, request_query)\n if value:\n params[field] = value\n condition.update({field: value[1:] if len(value) > 1 and value[0] == '=' else {'$regex': value}})\n task_type = h.get_url_param('task_type', request_query)\n if task_type:\n params['task_type'] = task_type\n task_status = h.get_url_param('task_status', request_query)\n if task_status:\n params['task_status'] = task_status\n num = h.get_url_param('num', request_query) or 1\n params['num'] = num\n if task_type and task_status:\n condition.update({'tasks.%s.%s' % (task_type, num): None if task_status == 'un_published' else task_status})\n match_field = h.get_url_param('match_field', request_query)\n if match_field:\n params['match_field'] = match_field\n match_status = h.get_url_param('match_status', request_query)\n if match_status not in [None, '']:\n params['match_status'] = match_status\n if match_field and match_status not in [None, '']:\n condition.update({'txt_match.%s.status' % match_field: match_status})\n return condition, params\n","sub_path":"controller/page/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"298818359","text":"import Tkinter as tk\nfrom Tkinter import *\nimport tkMessageBox\n\nfrom guiflows import flows\n\ndef skypevar():\n\t# tkMessageBox.showinfo(\"Selection\", \"You have chosen the Skype plan!\")\n\tflows(1)\n\ndef streamingvar():\n\t# tkMessageBox.showinfo(\"Selection\", \"You have chosen the Netflix plan!\")\n\tflows(2)\n\ndef gamevar():\n\t# tkMessageBox.showinfo(\"Selection\", \"You have chosen the Gaming plan!\")\n\tflows(3)\n## Create window to place canvas and widgets\nroot = tk.Tk()\nroot.title(\"Select your service\")\nbgimage= tk.PhotoImage(file='background_1.png')\nw = bgimage.width()\nh = bgimage.height()\nroot.geometry(\"%dx%d+50+30\" % (w,h))\n## Create canvas for background image\ncv = tk.Canvas(width=w, height=h)\ncv.pack(side='top', fill='both', expand='yes')\ncv.create_image(0, 0, image=bgimage, anchor='nw')\n\n## Create buttons\nskype_img = tk.PhotoImage(file='skype.png')\nskype = tk.Button(cv, image=skype_img, command=skypevar)\nskype.place(anchor='nw', x=120, y=250)\n\nstreaming_img = tk.PhotoImage(file='streaming.png')\nstreaming = tk.Button(cv, image=streaming_img, command=streamingvar)\nstreaming.place(anchor='nw', x=420, y=250)\n\ngame_img = tk.PhotoImage(file='gaming.png')\ngame = tk.Button(cv, image=game_img, command=gamevar)\ngame.place(anchor='nw', x=720, y=250)\n\n\nroot.mainloop()\n\n\n","sub_path":"gui_1.py","file_name":"gui_1.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"546576937","text":"\"\"\"\nPackage of plots to make about sky subtraction.\nCalled from command line, the first argument is\nname of a MiniskyPC file output from sky_pca, and\nsecond argument is the name for a multipage pdf of\ndiagnostic plots.\n\"\"\"\nimport numpy as np\nimport pylab as pl\nfrom pixcorrect import skyinfo\n\ncmap = 'cubehelix'\n\ndef showMini(mini, vrange=None):\n \"\"\"\n Make a 2d plot of a mini-sky image.\n Use percentiles of the valid pixels to set the\n color scale if no limit is given.\n \"\"\"\n if vrange is None:\n vmin = np.percentile(mini.vector(), 1.)\n vmax = np.percentile(mini.vector(), 99.)\n else:\n vmin = -vrange\n vmax = vrange\n pl.imshow(mini.data, interpolation='nearest', origin='lower', aspect='equal',\n vmin=vmin, vmax=vmax, cmap=cmap)\n pl.colorbar()\n\ndef showPCA(pcfile):\n \"\"\"\n Plot all principal components in a row(s)\n \"\"\"\n pca = skyinfo.MiniskyPC.load(pcfile)\n npc = pca.U.shape[1]\n nrows = int((npc - 1) / 4) + 1\n ncols = min(npc, 4)\n fig, axx = pl.subplots(nrows, ncols, squeeze=True)\n fig.set_size_inches(2 * ncols, 2 * nrows)\n for ipc in range(npc):\n irow = int(ipc / 4)\n icol = ipc % 4\n fig.sca(axx[irow, icol])\n pl.axis('off')\n pc = pca.get_pc(ipc)\n vmin = np.percentile(pc.vector(), 1.)\n vmax = np.percentile(pc.vector(), 99.)\n pl.imshow(pc.data, interpolation='nearest', origin='lower', aspect='equal',\n vmin=vmin, vmax=vmax, cmap=cmap)\n pl.text(10, 200, 'PC{:d}'.format(ipc), color='white')\n\ndef rmsVsPc(pcfile):\n \"\"\"\n Plot the variance (actually RMS) vs PC number\n \"\"\"\n rms = skyinfo.MiniskyPC.get_pc_rms(pcfile)\n pl.semilogy(range(len(rms)), rms, 'ro')\n pl.xlim(-0.5, len(rms) + 0.5)\n pl.xlabel('PC Number')\n pl.ylabel('RMS signal')\n pl.grid()\n pl.title('RMS vs PC for ' + pcfile)\n\ndef showResids2(m, model, mask, sh):\n \"\"\"\n Make an image of residuals in the first 100 frames\n \"\"\"\n out = np.ones(((sh[0] + 2) * 10, (sh[1] + 2) * 10), dtype=float) * -1\n img = np.ones(sh, dtype=float) * -1\n for i in range(10):\n x0 = i * (sh[1] + 2)\n for j in range(10):\n y0 = j * (sh[0] + 2)\n img[mask] = m[:, 10 * i + j] - model[:, 10 * i + j]\n print(sh, img.shape, x0, y0)\n out[y0:y0 + sh[0], x0:x0 + sh[1]] = img\n return out\n\n\ndef pcaReport(pcafile, pdffile):\n \"\"\"\n Make a set of plots for quality control on a PCA output\n pcafile is the output of sky_pca\n pdffile is output plots of this routine.\n \"\"\"\n from matplotlib.backends.backend_pdf import PdfPages\n pp = PdfPages(pdffile)\n rmsVsPc(pcafile)\n pp.savefig()\n pl.clf()\n showPCA(pcafile)\n pp.savefig()\n pp.close()\n","sub_path":"python/pixcorrect/skyplot.py","file_name":"skyplot.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"645089840","text":"#!/usr/bin/python3\n\n\"\"\"\ndivide_data.py: Runs the split_mass program from halld_sim over a set of AmpTools ROOT files to divide it into mass bins.\n Run it without arguments for a more detailed description of its inputs.\n\nAuthor: Nathaniel Dene Hoffman - Carnegie Mellon University - GlueX Collaboration\nCreation Date: 5 July 2021\n\"\"\"\n\nimport argparse\nimport errno\nimport sys\nimport os\nimport numpy as np\nfrom pathlib import Path\nparser = argparse.ArgumentParser(description=\"Splits up an AmpTools tree into mass bins (invariant mass of all final state particles, ignoring beam and recoil proton)\")\nparser.add_argument(\"--low\", type=float, help=\"low bin in GeV\")\nparser.add_argument(\"--high\", type=float, help=\"high bin in GeV\")\nparser.add_argument(\"-n\", default=0, type=int, help=\"number of bins (run without this argument for ~40 MeV bins)\")\nparser.add_argument(\"-g\", \"--generated\", help=\"path to the generated Monte Carlo AmpTools ROOT file\")\nparser.add_argument(\"-a\", \"--accepted\", help=\"path to the accepted Monte Carlo AmpTools ROOT file\")\nparser.add_argument(\"-d\", \"--data\", help=\"path to the data AmpTools ROOT file\")\nparser.add_argument(\"-b\", \"--background\", help=\"path to the background AmpTools ROOT file\")\nparser.add_argument(\"-t\", \"--tree\", help=\"optionally specify the input tree name\", default='kin')\nparser.add_argument(\"-o\", \"--output\", help=\"path to the output folder\")\nparser.add_argument(\"-c\", \"--config\", help=\"path to a template amptools config file (keywords are @DATAFILE, @GENFILE, @ACCFILE, and @NIFILE)\", required=True)\n\n# Handle argument errors\nif len(sys.argv) == 1: # If no arguments are provided, print the help string and exit\n parser.print_help(sys.stderr)\n sys.exit(1)\nargs = parser.parse_args()\nif args.high <= args.low: # high bin must be >= low bin\n print(\"The high bin value must be greater than the low bin value!\")\n sys.exit(1)\nif args.n == 0: # If no bin number is specified (or if 0 is chosen), set it to create ~40 MeV bins (as close as possible)\n span = args.high - args.low\n args.n = int(span / 0.040)\n\n# Check to see if all the files actually exist:\nconfig_path = Path(args.config).resolve()\nif config_path.is_file():\n print(f\"AmpTools Config Template: {config_path}\")\nelse:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), args.config)\n\nif args.generated != None:\n generated_path = Path(args.generated).resolve()\n if generated_path.is_file():\n print(f\"Generated file: {generated_path}\")\n else:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), args.generated)\nif args.accepted != None:\n accepted_path = Path(args.accepted).resolve()\n if accepted_path.is_file():\n print(f\"Accepted file: {accepted_path}\")\n else:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), args.accepted)\nif args.data != None:\n data_path = Path(args.data).resolve()\n if data_path.is_file():\n print(f\"Data file: {data_path}\")\n else:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), args.data)\nif args.background != None:\n background_path = Path(args.background).resolve()\n if background_path.is_file():\n print(f\"Background file: {background_path}\")\n else:\n raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), args.background)\nif args.output != None:\n output_dir = Path(args.output).resolve()\n if output_dir.is_dir():\n print(f\"Output_Folder: {output_dir}\")\n else:\n output_dir.mkdir(parents=True)\n print(f\"Output_Folder: {output_dir}\")\n\n\n# removed for now, it seems the split_mass program sets a value by default and you can't set this\n# AND set an optional tree name\n#max_events = 1e9 # Maximum number of events to process, this may need to be modified in the future\n\noutput_dirs = [output_dir / f\"{bin_num}\" for bin_num in np.arange(args.n)]\nfor bin_dir in output_dirs:\n bin_dir.mkdir(exist_ok=True) # create subdirectories for each bin\n\nbin_info_file = output_dir / \"bin_info.txt\"\nwith open(bin_info_file, 'w') as bin_info_writer:\n bin_content = np.linspace(args.low, args.high, args.n)\n lines_to_write = [\"bin\\tmass\\n\"]\n for i, bin_c in enumerate(bin_content):\n lines_to_write.append(f\"{i}\\t{bin_c}\\n\")\n bin_info_writer.writelines(lines_to_write) # write a tab-separated file containing the masses of each bin\n\n# Process Generated\nif args.generated != None:\n print(\"Splitting Generated Monte Carlo\")\n os.system(f\"split_mass {generated_path} {generated_path.stem + '_GEN_'} {args.low} {args.high} {args.n} -T {args.tree}:kin\")\n\n# Process Accepted\nif args.accepted != None:\n print(\"Splitting Accepted Monte Carlo\")\n os.system(f\"split_mass {accepted_path} {accepted_path.stem + '_ACCEPT_'} {args.low} {args.high} {args.n} -T {args.tree}:kin\")\n\n# Process Data\nif args.data != None:\n print(\"Splitting Data\")\n os.system(f\"split_mass {data_path} {data_path.stem + '_DATA_'} {args.low} {args.high} {args.n} -T {args.tree}:kin\")\n\n\n# Process Background\nif args.background != None:\n print(\"Splitting Background\")\n os.system(f\"split_mass {background_path} {background_path.stem + '_BKG_'} {args.low} {args.high} {args.n} -T {args.tree}:kin\")\n\n# Copy in a template config file to each bin and change the @TAG file paths inside to point to the proper files\nfor bin_num in np.arange(args.n):\n bin_files = Path('.').glob(f\"*_{bin_num}.root\")\n for bin_file in bin_files:\n destination = output_dir / str(bin_num) / bin_file.name\n bin_file.replace(destination)\n with open(config_path) as config:\n config_text = config.read()\n if args.generated != None:\n config_text = config_text.replace(\"@GENFILE\", generated_path.stem + \"_GEN_\" + f\"_{bin_num}.root\")\n if args.accepted != None:\n config_text = config_text.replace(\"@ACCFILE\", accepted_path.stem + \"_ACCEPT_\" + f\"_{bin_num}.root\")\n if args.data != None:\n config_text = config_text.replace(\"@DATAFILE\", data_path.stem + \"_DATA_\" + f\"_{bin_num}.root\")\n if args.background != None:\n config_text = config_text.replace(\"@BKGFILE\", background_path.stem + \"_BKG_\" + f\"_{bin_num}.root\")\n config_text = config_text.replace(\"@NIFILE\", f\"{bin_num}_ni.txt\")\n config_bin_name = config_path.stem + f\"_{bin_num}.cfg\"\n with open(output_dir / str(bin_num) / config_bin_name, 'w') as config_bin:\n config_bin.write(config_text)\n","sub_path":"divide_data.py","file_name":"divide_data.py","file_ext":"py","file_size_in_byte":6509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"108392028","text":"# 根据图形形成词云\n# 图形背景是白色的\n\nimport jieba\nimport wordcloud\nfrom scipy.misc import imread\n\nmask = imread('china.jpg')\nwith open('gaige.txt') as f:\n\tt = f.read()\nls = jieba.lcut(t)\ntxt = ' '.join(ls)\nw = wordcloud.WordCloud(font_path='msyh.ttc',mask=mask,\\\n\twidth = 1000,height=700,background_color='white')\nw.generate(txt)\nw.to_file('Output.jpg')","sub_path":"python学习示例/python基础/wordcloud_Py/ChinaMap.py","file_name":"ChinaMap.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"181815525","text":"import json\n\n\ndef get_users():\n return {\n \"firstName\": \"Jane\",\n \"lastName\": \"Doe\",\n \"hobbies\": [\"running\", \"sky diving\", \"singing\"],\n \"age\": 35,\n \"children\": [\n {\n \"firstName\": \"Alice\",\n \"age\": 6\n },\n {\n \"firstName\": \"Bob\",\n \"age\": 8\n }\n ]\n }\n\n\n\nif __name__ == '__main__':\n dict_str = json.dumps(get_users())\n print(dict_str)\n\n dictData = { \"ID\" : 210450,\n \"login\" : \"admin\",\n \"name\" : \"John Smith\",\n \"password\" : \"root\",\n \"phone\" : 5550505,\n \"email\" : \"smith@mail.com\",\n \"online\" : True }\n jsonData = json.dumps(dictData)\n with open(\"data.json\", \"w\") as file:\n file.write(jsonData)\n\n with open(\"data.json\", \"r\") as file:\n json_str = file.read()\n json_dict = json.loads(json_str)\n print(json_dict[\"name\"])","sub_path":"ua/univer/lesson05/example_dict/example_json.py","file_name":"example_json.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"562847858","text":"\"\"\"\n* This is the main script\n\n\"\"\"\nimport RPi.GPIO as GPIO\nimport threading\nimport time\n\nfrom timing import Timing\n\nfrom detectors.TE_detector import TE_detect\nfrom detectors.limit import Limit\n\nfrom devices.boom import Boom\nfrom devices.lock import Lock\nfrom devices.ricoh import Ricoh\nfrom devices.rf_experiment.rf import RF\nfrom devices.arducam import ArduCam\n\nNUM_EXT = Timing.EXTEND_TIME / Timing.EXTEND_PERIOD\t# The number of RF datapoints taken\n\nimport config.pins\nGPIO.setmode(GPIO.BCM)\nconfig.pins.setup()\n\nprint('Initializing...')\n\n# Initializing detects\nte1 = TE_detect()\nlimit = Limit()\n\n# Initializing devices\nboom = Boom()\nlock = Lock()\nricoh = Ricoh()\nrf = RF()\narduCam = ArduCam()\n\n# Setting up threads\nrf_setup = threading.Thread(target=rf.setup)\nrf_deactivate = threading.Thread(target=rf.deactivate)\n\narduCam.activate()\n\n# Setting up\nrf_setup.start()\nrf_setup.join()\n\nprint('Setup Complete')\nprint('Waiting for TE...')\n\n#te1.wait_for_detect()\n# =============== Main ===============\nricoh.activate()\n\n# Extend boom and take rf measurements\nextension = 0\nprint('Extending boom...')\n\nwhile extension < NUM_EXT:\n rf_activate = threading.Thread(target=rf.activate)\n rf_activate.daemon = True\n rf_activate.start()\n\n boom.activate()\n extension += 1\n\n\nprint('Holding boom at extension...')\n\ntime.sleep(Timing.TIME_AT_EXTENSION)\n\n\n# Retract and take measurements\nprint('Retracting boom...')\n\nwhile not limit.doorShut():\n rf_activate = threading.Thread(target=rf.activate)\n rf_activate.daemon = True\n rf_activate.start()\n boom.deactivate()\n extension -= 1\n\n\n#=============== Cleanup ==================\nlock.activate()\nboom.shutdown()\nricoh.deactivate()\nrf_deactivate.start()\n\n\n\n\nGPIO.cleanup()\t\t# Resets all output pins to input to avoid issues\n\nprint('Success')\n\n","sub_path":"mission_control/mission_control.py","file_name":"mission_control.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"414472066","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 23 23:02:52 2020\n\n@author: nialb\n\"\"\"\nimport os\nimport shutil\n\nimport numpy as np\nimport pandas as pd\n\nimport cv2\nfrom keras.preprocessing.image import ImageDataGenerator\n\neqh_dir = 'equalized_ds'\neqh_train_dir = eqh_dir + '\\\\train'\neqh_val_dir = eqh_dir + '\\\\val'\neqh_test_dir = eqh_dir + '\\\\test'\n\nif(os.path.exists(eqh_dir)):\n shutil.rmtree(eqh_dir)\n \nos.makedirs(eqh_dir)\nos.makedirs(eqh_train_dir)\nos.makedirs(eqh_val_dir)\nos.makedirs(eqh_test_dir)\n\ndef clahe_prep(img): \n img_crp = img[40:738, 40:738]\n img_sized = cv2.resize(img_crp, (768,768))\n clahe = cv2.createCLAHE(clipLimit=3, tileGridSize=(8,8))\n lab = cv2.cvtColor(img_sized, cv2.COLOR_BGR2LAB)\n l, a, b = cv2.split(lab)\n\n cl = clahe.apply(l)\n limg = cv2.merge((cl,a,b))\n\n img = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n\n return np.uint8(img)\n\nmetadata_base = pd.read_csv('metadata_augmented.csv')\nmetadata_base['eqh_file_path'] = ''\n\nfor i in range(0, len(metadata_base)):\n file_name = metadata_base.iloc[i].loc['X_ray_image_name']\n base_path = metadata_base.iloc[i].loc['augmented_file_path']\n ds_type = metadata_base.iloc[i].loc['Dataset_type']\n base_img = cv2.imread(base_path)\n enh_img = clahe_prep(base_img)\n \n if ds_type == 'train':\n save_path = os.path.join(eqh_train_dir, file_name)\n elif ds_type == 'val': \n save_path = os.path.join(eqh_val_dir, file_name)\n elif ds_type == 'test': \n save_path = os.path.join(eqh_test_dir, file_name)\n else:\n save_path = os.path.join(eqh_dir, file_name)\n \n metadata_base['eqh_file_path'].iloc[i] = save_path\n cv2.imwrite(save_path, enh_img)\n \nmetadata_eqh = metadata_base.drop(['augmented_file_path'], axis=1)\nmetadata_eqh.to_csv('metadata_eqh.csv', index=False)\n","sub_path":"equalize_histogram_images.py","file_name":"equalize_histogram_images.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"324139493","text":"import sys\nsys.path.append(\"../../../src/raven-doc\")\n\nimport io\nfrom raven.parser.doc_parser import DocParser \n\ndef main():\n\tparser = DocParser()\n\t#try:\n\tfile = open(\"sample.js\", \"r\")\n\tinput = file.read()\n\tfile.close()\n\tparser.parser(input)\n\tprint(\"Files were parsed successfuly.\")\n\t#except Exception as ex:\n\t#\tprint(\"File 'Sample.js', line 1\\n {1}\\nError: {0}\".format(ex, parser.get_error()))\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"test/raven-doc/parser/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"544276221","text":"import logging\nfrom typing import List, Union\nfrom .registrations_version import RegistrationsVersion\nfrom .registrations_version import RegistrationsVersionConfig\nimport nuget.request_wrapper\n\nclass CatalogEntry:\n def __init__(self, json):\n self.url = json[\"@id\"] # type: str\n self.id = json[\"id\"] # type: str\n self.version = json[\"version\"] # type: str\n \n self.authors = json.get(\"authors\") # type: Union[string,List[string]] \n self.depracation = json.get(\"deprecation\")\n self.description = json.get(\"description\") # type: str\n self.licenseUrl = json.get(\"licenseUrl\") # type: str\n self.licenseExpression = json.get(\"licenseExpression\") # type: str\n self.listed = json.get(\"listed\") # type: bool\n self.minClientVersion = json.get(\"minClientVersion\") # type: str\n self.projectUrl = json.get(\"projectUrl\") # type: str\n self.published = json.get(\"published\") # type: str\n self.requireLicenseAcceptance = json.get(\"requireLicenseAcceptance\") # type: bool\n self.summary = json.get(\"summary\") # type: str\n self.tags = json.get(\"tags\") # type: Union[string,List[string]]\n self.title = json.get(\"title\") # type: str\n\n self.dependencyGroups = json.get(\"dependencyGroups\") \n\nclass RegistrationLeaf: \n def __init__(self, json):\n self.url = json[\"@id\"] # type: str\n self.packageContent = json[\"@id\"] # type: str\n self.catalogEntry = CatalogEntry(json[\"catalogEntry\"])\n self.commitTimeStamp = json.get(\"commitTimeStamp\") # type: str\n\nclass RegistrationPage: \n def __init__(self, json): \n self.url = json[\"@id\"] # type: str\n self.count = json[\"count\"] #type: int \n self.lower = json[\"lower\"] # type: str\n self.parent = json.get(\"parent\") # type: str\n self.upper = json[\"upper\"] # type: str\n self.commitTimeStamp = json.get(\"commitTimeStamp\") # type: str\n self.__set_items(json) \n\n def items(self) -> List[RegistrationLeaf]:\n \"\"\"\n Gets or fetches every RegistrationLeaf for this page. This will require a Server API call to self.url if the items were not included originally.\n \"\"\"\n if not self.__items: \n self.__set_items(nuget.request_wrapper.get_request(self.url)) \n \n return self.__items\n\n def __set_items(self,json):\n self.__items = []\n if json.get(\"items\"): \n for i in json[\"items\"]:\n self.__items.append(RegistrationLeaf(i)) \n\nclass RegistrationsIndex:\n \"\"\"\n Represents the Registration index resource.\n https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index\n\n \"\"\" \n def __init__(self, json: dict, url: str):\n super().__init__()\n assert isinstance(json, dict), \":param json must be a dict\"\n assert isinstance(url, str), \":param url must be a str\"\n self.url = url\n self.count = json[\"count\"] #type: int\n self.items = [] #type: List[RegistrationPage]\n self.commitTimeStamp = json.get(\"commitTimeStamp\") # type: str\n for i in json[\"items\"]:\n self.items.append(RegistrationPage(i))\n\nclass Registrations:\n \"\"\"\n This class can be used to access nuget package registration data from the Server API.\n https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource\n \"\"\"\n\n def __init__(self, service_index_json: dict):\n \"\"\" \n :param service_index_json The json response from the nuget service index endpoint.\n https://docs.microsoft.com/en-us/nuget/api/service-index\n \"\"\" \n self._version_config = RegistrationsVersionConfig(service_index_json) \n \n def index(self, package_id: str, service_version: RegistrationsVersion = RegistrationsVersion.RELEASE) -> RegistrationsIndex:\n assert isinstance(package_id, str), \":param package_id must be a str\"\n url = f'{self._version_config.get_base_url(service_version)}{package_id.lower()}/index.json'\n index_data = nuget.request_wrapper.get_request(url)\n return RegistrationsIndex(index_data, url) if index_data else None","sub_path":"nuget/registrations.py","file_name":"registrations.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"561704582","text":"name = input(\"Como te llamas? \\n\")\nprint(\"Hola, \", name)\nage = int(input(\"Cual es tu edad? \\n\"))\ndate = int(input('En que año estamos? \\n'))\ncumplidos = input('Cumpliste año ya este año? [S/N] \\n')\n\nif cumplidos == 'S':\n nac = date - age\nelse:#cualquier cosa entra aqui\n nac = date - age -1\n\n\nprint(age)\nprint(name,', Naciste en el año: ', nac)\n","sub_path":"Modulo0/p04.py","file_name":"p04.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"253576329","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='EmployeeRecords',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('EName', models.CharField(max_length=60)),\n ('HiringDate', models.DateField(help_text=b'date published')),\n ('emailID', models.CharField(max_length=60)),\n ('upload', models.FileField(upload_to=b'photos/')),\n ],\n ),\n ]\n","sub_path":"CreateRecords/Employee/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"591964097","text":"import requests\nimport os\nimport csv\nfrom bs4 import BeautifulSoup\nimport random\nfrom requests.exceptions import ConnectionError\n\n\ncsv_header = [['NAME', 'ADDRESS', 'PHONE NUMBER', 'IP ADDRESS', 'ESTIMATED INCOME', 'OCCUPATION', 'AGE']]\n\n\ndef write_direct_csv(lines, filename):\n with open('output/%s' % filename, 'a', encoding=\"utf-8\", newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n writer.writerows(lines)\n csv_file.close()\n\n\ndef write_csv(lines, filename):\n if not os.path.isdir('output'):\n os.mkdir('output')\n if not os.path.isfile('output/%s' % filename):\n write_direct_csv(lines=csv_header, filename=filename)\n write_direct_csv(lines=lines, filename=filename)\n\n\ndef write_success_phones(lines):\n filename = 'success_phones.csv'\n with open('output/%s' % filename, 'a', encoding=\"utf-8\", newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n writer.writerows(lines)\n csv_file.close()\n\n\ndef read_success_phones():\n file = 'output/success_phones.csv'\n phone = []\n with open(file=file, encoding='utf-8') as reader:\n rows = reader.readlines()\n for row in rows:\n phone.append(row.strip())\n return phone\n\n\ndef phones():\n path = 'AZ_29k_25_05.txt'\n f = open(path, \"r+\")\n p_numbers = f.readlines()\n f.close()\n return p_numbers\n\n\ndef get_proxies():\n url = \"http://list.didsoft.com/get?email=developer61510@gmail.com&pass=mv3asy&pid=http3000&showcountry=no\"\n res = requests.get(url=url).text.split('\\n')\n return res\n\n\ndef check_ip(rand):\n url = 'https://httpbin.org/ip'\n print(url)\n proxy = {\n 'http': 'http://{}'.format(rand),\n 'https': 'https://{}'.format(rand)\n }\n try:\n response = requests.get(url=url, proxies=proxy)\n print('This is response url: ', response.text.strip())\n return proxy\n except ConnectionError as e:\n print(e, 'Trying another proxy')\n return None\n\n\ndef request(number):\n # proxies = get_proxies()\n # while True:\n # rand = random.choice(proxies)\n # check = check_ip('176.110.154.59:53499')\n # print('here: ', check)\n # if check is not None:\n # break\n name, address, ip, income, occupation, age = '', '', '', '', '', ''\n results = []\n req_number = '{}-{}-{}'.format(number[1:4], number[4:7], number[7:11])\n url = 'https://thatsthem.com/phone/{}'.format(req_number)\n response = requests.get(url=url)\n if response.url == 'https://thatsthem.com/?rl=true':\n print('Proxy Terminated')\n exit()\n soup = BeautifulSoup(response.text, 'html5lib')\n cards = soup.find_all(attrs={'class': 'ThatsThem-record'})\n for card in cards:\n if card.find(attrs={'itemprop': \"name\"}):\n name = card.find(attrs={'itemprop': \"name\"}).text.strip()\n if card.find(attrs={'itemprop': \"address\"}):\n address = card.find(attrs={'itemprop': \"address\"}).text.strip()\n if card.find('dt', text=\"Occupation\"):\n occupation = card.find('dt', text=\"Occupation\").find_next('dd').text.strip()\n if card.find('dt', text=\"Estimated Income\"):\n income = card.find('dt', text=\"Estimated Income\").find_next('dd').text.strip()\n if card.find('dt', text=\"IP Address\"):\n ip = card.find('dt', text=\"IP Address\").find_next('dd').text.strip()\n if card.find(attrs={'class': 'ThatsThem-record-age'}) and card.find(attrs={'class': 'ThatsThem-record-age'}).find('span', {'class': 'active'}):\n age = card.find(attrs={'class': 'ThatsThem-record-age'}).find('span', {'class': 'active'}).text.strip()\n row = [name, address, number, ip, income, occupation, age]\n results.append(row)\n return results\n\n\ndef main():\n success_numbers = read_success_phones()\n phone_numbers = phones()\n for p in phone_numbers:\n phone_number = p.strip()\n if phone_number in success_numbers:\n print('Exist')\n continue\n response = request(number=phone_number)\n write_success_phones([[phone_number]])\n if response:\n write_csv(lines=response, filename='Result.csv')\n print(response)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"thatsthem/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"84075372","text":"standUser = \"Josuke Higashikata\"\nstandName = \"Crazy Diamond\"\n\nunformattedString = standUser + \"'s stand is called \" + standName + \".\"\nformattedString = f\"{standUser}'s stand is called {standName}.\"\n\nprint(\"unformatted: \" + unformattedString)\nprint(\"formatted: \" + formattedString)\n\n# outputs the same thing, but one is easier to edit and understand in the code\n","sub_path":"PythonTut/StringFormatting.py","file_name":"StringFormatting.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"30636990","text":"from sys import argv\r\nimport os\r\n\r\ndef solve_sheep(in_file):\r\n inp = open(in_file)\r\n root, ext = os.path.splitext(in_file)\r\n out = open(root + \".out\", 'w')\r\n n_cases = int(inp.readline())\r\n for case in range(n_cases):\r\n sheep_number = sheep(int(inp.readline()))\r\n out.write(\"Case #{}: {}\\n\".format(case + 1, sheep_number))\r\n\r\n\r\ndef sheep(n):\r\n if n == 0:\r\n return \"INSOMNIA\"\r\n\r\n seen = set(str(n))\r\n num = n\r\n while len(seen) < 10:\r\n num += n\r\n seen = seen.union(list(str(num)))\r\n\r\n return num\r\n\r\n\r\nif __name__ == \"__main__\":\r\n solve_sheep(argv[1])","sub_path":"codes/CodeJamCrawler/16_0_1/kokasih/sheep.py","file_name":"sheep.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"636137979","text":"from main.settings.base import *\nimport os\n\nDEBUG = True\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': os.environ['DB_NAME'],\n 'USER': os.environ['DB_USER'],\n 'PASSWORD': os.environ['DB_PASSWORD'],\n 'HOST': os.environ['DB_HOST'],\n 'PORT': os.environ['DB_PORT'],\n }\n}\n\nCELERY_BROKER_URL = \"amqp://mq\"\nCELERY_RESULT_BACKEND = 'amqp://mq'\nCELERY_ACCEPT_CONTENT = ['application/json']\nCELERY_RESULT_SERIALIZER = 'json'\nCELERY_TASK_SERIALIZER = 'json'\nCELERY_TIMEZONE = 'Africa/Nairobi'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'main/static'),\n)\n\nMEDIA_ROOT = BASE_DIR\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder',\n)\n\n# Compress Settings\nCOMPRESS_ROOT = BASE_DIR + '/static/'\nCOMPRESS_ENABLED = True\nCOMPRESS_OFFLINE_CONTEXT = {\n 'STATIC_URL': 'STATIC_URL',\n}\n\nCOMPRESS_CSS_FILTERS = [\n 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter']\nCOMPRESS_JS_FILTERS = ['compressor.filters.jsmin.JSMinFilter']\nCOMPRESS_REBUILD_TIMEOUT = 5400\n","sub_path":"main/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"596863138","text":"from __future__ import print_function, division\nfrom batch import *\nfrom data import *\nfrom models import *\nfrom resnet3d import *\nimport sys\n\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\n\n\n\ndef main():\n use_cuda = torch.cuda.is_available()\n\n torch.manual_seed(1)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n\n inputDir = [sys.argv[1] + '/1200/source', sys.argv[1] + '/3000/source']\n targetDir = [sys.argv[1] + '/1200/target', sys.argv[1] + '/3000/target']\n segDir = sys.argv[1] + '/SLANT'\n\n train_loss_file = sys.argv[2] + '/train_loss.txt'\n\n if int(sys.argv[3]) == -1:\n f = open(train_loss_file, 'w')\n f.close()\n\n train_dataset = dataset(inputDir, targetDir, segDir)\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=10000, shuffle=False, **kwargs)\n\n model_file = sys.argv[2] + '/epoch_{}'\n #model = UNet().to(device)\n model = resnet10(sample_size=1, sample_duration=1).to(device)\n\n start_epoch = 1\n if int(sys.argv[3]) != -1:\n model.load_state_dict(torch.load(model_file.format(sys.argv[3])))\n start_epoch = int(sys.argv[3]) + 1\n\n lr = 0.0001\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n\n\n for epoch in range(start_epoch, 31):\n print('\\nEpoch {}: '.format(epoch))\n\n train_loss = train(model, device, train_loader, optimizer)\n\n with open(train_loss_file, \"a\") as file:\n file.write(str(train_loss))\n file.write('\\n')\n\n if epoch%3==0:\n with open(model_file.format(epoch), 'wb') as f:\n torch.save(model.state_dict(), f)\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"SIMPLE_SLANT_pytorch_src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"230260931","text":"from beginner.msg import MsgFlystate, MsgTrajectory\nimport rospy, sys\nfrom std_msgs.msg import String\nfrom params import parameters\n# modules\n# ------------------------------------------------------------------------------\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom worldGen import WorldGen\n\ndef callback( data):\n \"\"\" Returns Wing Beat Amplitude Difference from received data\"\"\"\n global x,y,frame\n x[frame]=data.position.x\n y[frame]=data.position.y\n\n return x,y\n\n\ndef listener():\n \"\"\" Listens to Kinefly Flystate topic\"\"\"\n rospy.Subscriber(\"/trajectory\", MsgTrajectory, callback)\n\n\ndef initPlot():\n plt.axis([0,255,0,255])\n # if parameters['loadOdour']:\n # from world import odourFieldGen, plumeStripGen\n # odourFieldGen()\n initPlot=WorldGen()\n initPlot.initPositions()\n initPlot.plotPositions()\n\n\n\nrospy.init_node('plot')\ndur=200000\ndt=30/165.\nx=np.zeros(dur)\ny=np.zeros(dur)\nframe=0\n\nlistener()\nplt.close('all') # close all previous plots\nfig = plt.figure(1)\nax = plt.axes(xlim=(0, 255), ylim=(0, 255))\nscat = ax.scatter([], [], s=.1)\n\n\ndef press(event):\n global x,y\n print('press', event.key)\n sys.stdout.flush()\n if event.key == 'c':\n\n x = np.zeros(dur)\n y = np.zeros(dur)\n\n if event.key == 'x':\n global play\n play=False\n plt.close()\n\ndef init():\n initPlot()\n scat.set_offsets([])\n return scat,\n\ndef animate(i):\n global frame\n frame=i\n data = np.hstack((x[:i,np.newaxis], y[:i, np.newaxis]))\n scat.set_offsets(data)\n return scat,\n\nfig.canvas.mpl_connect('key_press_event', press)\n\nanim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x)+1,\n interval=dt, blit=True, repeat=False)\n\n\nplt.show()\n\n","sub_path":"realTimePlotter.py","file_name":"realTimePlotter.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"219189959","text":"from __future__ import print_function\nimport geopandas as gpd\nimport pandas as pd\nimport json\nfrom bokeh.io import output_notebook, show, output_file, save\nfrom bokeh.plotting import figure\nfrom bokeh.models import GeoJSONDataSource, LinearColorMapper, ColorBar\nfrom bokeh.palettes import brewer\nfrom bokeh.io import curdoc, output_notebook\nfrom bokeh.models import Slider, HoverTool,TableColumn, DataTable, Slider,ColumnDataSource,CustomJS,Title\n\nfrom bokeh.layouts import widgetbox, row, column\nfrom bokeh.plotting import figure\nfrom bokeh.models.widgets import Select\n\nfrom bokeh.embed import components\n\nfrom bokeh.embed import json_item\nfrom bokeh.resources import CDN as CDN\nfrom bokeh.sampledata.iris import flowers\nimport copy\nfrom flask import Flask, render_template, request\n\nfrom jinja2 import Template\nfrom flask_bootstrap import Bootstrap\n\nfrom datetime import date\n\n\n\n\n\n\napp = Flask(__name__)\n\ndashboard = \"/Users/Aditya/Desktop/project/\"\n\n\n\n\n\n\ndef createDataTables():\n\tpd.options.display.float_format = '{:,.0f}'.format\n\n\n\tdatafile = '/Users/Aditya/Desktop/project/output.csv'\n\n\tdfDataTable = pd.read_csv(datafile, names = ['Country','Deaths','Deaths /1M pop','New Deaths','Tests','EstimatedCases','Confirmed Cases',\n\t\t'Confirmed Case/Fatality Rate','Confirmed Cases/1M pop','Seasonal Flu Deaths (CDC/WHO 2017)'], skiprows = 2)\n\n\tdfDataTable.fillna('No data', inplace = True)\n\n\n\ttable1 = dfDataTable[[\"Country\",\"Tests\",\"Confirmed Cases\"]].copy()\n\ttable2 = dfDataTable[[\"Country\",\"Deaths\",\"Seasonal Flu Deaths (CDC/WHO 2017)\"]].copy()\n\ttable2.rename(columns={ table2.columns[2]: \"Flu Deaths 2017\" }, inplace = True)\n\ttable1.rename(columns={ table1.columns[2]: \"Cases\" }, inplace = True)\n\ttable2.rename(columns={ table2.columns[1]: \"COVID-19 Deaths\" }, inplace = True)\n\n\ttable1Html = table1.to_html(index = False, justify = 'center', classes =[\"table\",\"text-left\"], border = 0)\n\ttable2Html = table2.to_html(index = False, justify = 'center', classes =[\"table\",\"text-left\"],border = 0)\n\t\n\n\treturn table1Html,table2Html\n\n\n\n\n\n\n\n\ndef createMap():\n\t#pd.options.display.float_format = '{:,.0f}'.format\n\tshapefile = '/Users/Aditya/Desktop/project/geoData/ne_110m_admin_0_countries.shp'\n\tdatafile = '/Users/Aditya/Desktop/project/output.csv'\n\n\n\n\t#Read shapefile using Geopandas\n\tgdf = gpd.read_file(shapefile)[['ADMIN', 'ADM0_A3', 'geometry']]\n\t#Rename columns.\n\tgdf.columns = ['country', 'country_code', 'geometry']\n\t#Drop row corresponding to 'Antarctica'\n\t#gdf.at[43, 'country'] = \"French Guiana\"\n\t#drop antartica, takes too much space\n\tgdf = gdf.drop(gdf.index[159])\n\n\n\n\t#Read csv file using pandas\n\n\t\n\n\n\tdf = pd.read_csv(datafile, names = ['Country','Deaths','Deaths /1M pop','New Deaths','Tests','Confirmed Cases','Confirmed Case/Fatality Rate',\n\t\t'Confirmed Cases/1M pop','EstimatedCases','Seasonal Flu Deaths1(CDC/WHO 2017)'], skiprows = 2)\n\tmerged = gdf.merge(df, left_on = 'country', right_on = 'Country', how = 'left')\n\tmerged['Deaths /1M pop'].fillna(\"No Data\", inplace = True)\n\tmerged.round({'Deaths /1M pop': 2})\n\t#print(merged.head(merged['Deaths /1M pop']))\n\n\t#Read data to json.\n\tmerged_json = json.loads(merged.to_json())\n\t#Convert to String like object.\n\n\tjson_data = json.dumps(merged_json)\n\n\n\t#Input GeoJSON source that contains features for plotting.\n\tgeosource = GeoJSONDataSource(geojson = json_data)\n\n\t#Define a sequential multi-hue color palette.\n\tpalette = brewer['YlOrRd'][7]\n\n\t#Reverse color order so that dark blue is highest obesity.\n\tpalette = palette[::-1]\n\n\t#Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors.\n\tcolor_mapper = LinearColorMapper(palette = palette, low = 0, high = 350, nan_color = '#d9d9d9')\n\n\t#Define custom tick labels for color bar.\n\ttick_labels = {'0': '0', '50': '50', '100':'100', '150':'150', '200':'200', '250':'250', '300':'300','350':'>350'}\n\n\t#Add hover tool\n\n\n\tTOOLTIPS = \"\"\"\n
\n
\n Country: @country \n
\n
\n Deaths /1M: @{Deaths /1M pop}{0.00 a} \n \n
\n
\n\n\"\"\"\n\n\thover = HoverTool(tooltips = TOOLTIPS)\n\t#Create color bar. \n\tcolor_bar = ColorBar(color_mapper=color_mapper, label_standoff=9,width = 20, height = 555,\n\tborder_line_color=None,location = (0,-10), orientation = 'vertical', major_label_overrides = tick_labels, background_fill_color = \"#1e1e2f\" ,\n\tmajor_label_text_color = \"white\")\n\n\t#Create figure object.\n\tp = figure(title = 'Deaths per Million', plot_height = 610 , plot_width = 1100, toolbar_location = None, tools = [hover])\n\tp.title.text_color = \"white\"\n\tp.xgrid.grid_line_color = None\n\tp.ygrid.grid_line_color = None\n\tp.background_fill_color = \"#3690c0\"\n\tp.border_fill_color = \"#1e1e2f\"\n\tp.axis.visible = False\n\ttoday = date.today()\n\n\td2 = today.strftime(\"%B %d, %Y\")\n\ttitle = \"Data is from https://www.realclearpolitics.com/coronavirus. Last updated %s\"%d2\n\n\tp.add_layout(Title(text=title, align=\"left\",text_color = \"white\"), \"below\")\n\n\n\t#Add patch renderer to figure. \n\tp.patches('xs','ys', source = geosource,fill_color = {'field' :'Deaths /1M pop', 'transform' : color_mapper},\n\t line_color = 'black', line_width = 0.25, fill_alpha = 1)\n\n\t#Specify figure layout.\n\tp.add_layout(color_bar, 'right')\n\n\tscript, div = components(p)\n\n\t#Display figure.\n\tsave(p)\n\treturn p\n\ndef getGlobalNums(datafile):\n\n\tglobalDF = pd.read_csv(datafile, names = ['Country','Deaths','Deaths /1M pop','New Deaths','Tests','Confirmed Cases',\n\t\t'Confirmed Case/Fatality Rate','Confirmed Cases/1M pop','EstimatedCases','Seasonal Flu Deaths1(CDC/WHO 2017)'],nrows=2)\n\tglobalDF.fillna('No data', inplace = True)\n\tdata = globalDF.iloc[1]\n\tglobalNums = []\n\tfor x in data:\n\t\tif x != \"No data\" and (x != 'Total Global Deaths'):\n\t\t\tnum = int(float((x)))\n\t\t\tglobalNums.append(f\"{num:,d}\")\n\treturn globalNums\n\n@app.route('/')\ndef index():\n\n\tdatafile = '/Users/Aditya/Desktop/project/output.csv'\n\n\tplot = createMap()\n\ttable1, table2 = createDataTables()\n\tscript, div = components(plot)\n\tglobalNums = getGlobalNums(datafile)\n\n\t\n\n\treturn render_template(\"index.html\", script=script, div=div,globalD=globalNums[0],globalC = globalNums[1],\n\t\ttable1 = table1, table2=table2)\n\nif __name__== \"__main__\":\n\n\tapp.run()\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"547023901","text":"from pyspark.ml.classification import LogisticRegression\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\nfrom pyspark.ml.feature import StringIndexer, VectorAssembler, IndexToString\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import StructType, StructField, DoubleType, StringType\n\n\ndef build_spark_session():\n return SparkSession.builder.appName(\"Logistic Regression\").getOrCreate()\n\n\nspark = build_spark_session()\n\n\n# Schema for iris dataset\ndef get_iris_schema():\n iris_schema = StructType([\n StructField(\"sepal_length\", DoubleType()),\n StructField(\"sepal_width\", DoubleType()),\n StructField(\"petal_length\", DoubleType()),\n StructField(\"petal_width\", DoubleType()),\n StructField(\"class\", StringType())\n ])\n return iris_schema\n\n\ndef read_iris_data_frame(input_file=\"iris.data\"):\n iris_df = spark.read.schema(get_iris_schema()).csv(input_file)\n return iris_df\n\n\n# to convert the string classes to double type\ndef string_to_index(data, input_col=\"class\", output_col=\"indexed_class\"):\n # iris_data = read_iris_data_frame()\n indexer = StringIndexer(inputCol=input_col, outputCol=output_col).fit(data)\n indexed_data = indexer.transform(data)\n return indexed_data\n\n\n# converts to feature vetor\ndef convert_to_vector():\n vectorizer = VectorAssembler(\n inputCols=[\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\"],\n outputCol=\"features\"\n )\n return vectorizer\n\n\n# converts the converted class indexes to index\ndef index_to_string(data, input_col=\"prediction\", output_col=\"class\"):\n # indexed_data could be broad casted, had some issues in my local spark, so reading the data frame again\n indexed_data = string_to_index(read_iris_data_frame(), \"class\", \"labels\").select([\"class\", \"labels\"]).distinct()\n result = data.join(indexed_data, data.prediction == indexed_data.labels)\n result.select(\"class\").show()\n return result.select(\"class\")\n\n\n# for cleansing the data to the standard format\ndef data_cleanse(data):\n iris_data = string_to_index(data, \"class\", \"indexed_class\")\n # iris_data.show(5)\n iris_df_assembler = convert_to_vector()\n iris_data = iris_df_assembler.transform(iris_data)\n iris_data = iris_data.select([\"features\", \"indexed_class\"])\n return iris_data\n\n\n# model and model parameters\ndef build_model(data):\n model_df = data\n train_data, test_data = model_df.randomSplit([0.80, 0.20])\n log_reg_model = LogisticRegression(labelCol=\"indexed_class\") \\\n .setParams(tol=0.0001, regParam=0.0, maxIter=100, fitIntercept=True) \\\n .fit(train_data)\n return train_data, test_data, log_reg_model\n\n\n# test data frame\ndef create_test_data():\n pred_data = build_spark_session().createDataFrame(\n [(5.1, 3.5, 1.4, 0.2),\n (6.2, 3.4, 5.4, 2.3)],\n [\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\"])\n return pred_data\n\n\n# evaluate the results\ndef evaluation_metrics(predicted_results):\n evaluator = MulticlassClassificationEvaluator() \\\n .setLabelCol(\"indexed_class\") \\\n .setPredictionCol(\"prediction\") \\\n .setMetricName(\"accuracy\")\n\n accuracy = evaluator.evaluate(predicted_results)\n print(\"Accuracy: \" + str(accuracy))\n\n\n# predict the test results\ndef predict_test_results(lr_model, pred_data):\n pred_data = pred_data\n pred_df_assembler = convert_to_vector()\n pred_data = pred_df_assembler.transform(pred_data)\n pred_data = pred_data.select(\"features\")\n model = lr_model.transform(pred_data)\n result = index_to_string(model)\n return result\n\n\ndef write_to_csv(result):\n result.repartition(1).write. \\\n format(\"csv\"). \\\n option(\"header\", \"true\"). \\\n mode(saveMode=\"Overwrite\"). \\\n save(\"out/out_3_2.txt\")\n\n\ndef main():\n iris_data = read_iris_data_frame(\"iris.data\")\n iris_data = data_cleanse(iris_data)\n train_data, test_data, log_reg_model = build_model(iris_data)\n pred_data = create_test_data()\n predicted_results = log_reg_model.transform(test_data)\n evaluation_metrics(predicted_results)\n prediction = predict_test_results(log_reg_model, pred_data)\n write_to_csv(prediction)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/main/scala/Task3/Task3_2.py","file_name":"Task3_2.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"218503986","text":"from django import template\nfrom django.conf import settings\nfrom django.urls import reverse\n\nimport re\nfrom urllib.parse import urlencode\nfrom urllib.parse import urlparse, urlunparse, parse_qsl\n\nfrom portal.constants import URL_PARAMETERS_KEPT\nfrom portal.templatetags.restaurant_info import get_image_path\n\nregister = template.Library()\n\n@register.simple_tag(takes_context=True)\ndef add_parameters(context, url):\n \"\"\"\n add get parameters from current url to internal links\n for example if the page is loaded with embedded=true\n all internal links should contain embedded=true\n\n the parameters that should be taken from the current url\n are kept in constants.URL_PARAMETERS_KEPT\n\n \"\"\"\n get_params = context['request'].GET\n # params of the request that have to be passed over to url\n params = {}\n for p in get_params:\n if p in URL_PARAMETERS_KEPT:\n params[p] = get_params[p]\n\n # add the params form the request to url\n url_parts = list(urlparse(url))\n query = dict(parse_qsl(url_parts[4]))\n query.update(params)\n\n url_parts[4] = urlencode(query)\n\n return urlunparse(url_parts)\n\n@register.simple_tag(takes_context=True)\ndef link_to_restaurant(context, restaurant):\n base_url = reverse('restaurant', args=[restaurant['slug']])\n return add_parameters(context, base_url)\n\n@register.filter\ndef external_link(url):\n \"\"\"\n add http:// if not already present\n\n \"\"\"\n if re.match('\\s*^https?://', url):\n return url\n else:\n return 'http://' + url\n\n@register.simple_tag(takes_context = True)\ndef set_language_link(context, language):\n path = context['request'].path\n # return add_parameters( context, chlocale(path, language) )\n return add_parameters( context, path )\n","sub_path":"portal/templatetags/links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"417306467","text":"from django.conf.urls.defaults import *\n\nurlpatterns = patterns('service.views', \n (r'^(?P.+)/treeview/(?P.+)/$', 'treeview'),\n (r'^(?P.+)/treeview/$', 'treeview'), \n (r'^(?P.+)/(?P.+)/(?P.+)/$', 'status'), \n (r'^(?P\\w+)/(?Pjson)$', 'main'),\n (r'^(?Pjson)$', 'main'),\n (r'^(?P\\w+)/$', 'main'),\n (r'^$', 'main'),\n)\n","sub_path":"gstat-web/tags/R_1_0_7/apps/service/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"318416448","text":"from typing import TypeVar, List, Tuple, Sequence, Iterable\n\nT = TypeVar('T')\n\n\ndef copy_list(sequence: Iterable[Tuple[str, T]]) -> List[T]:\n new_list: List[T] = []\n for elem in sequence:\n new_list.append(elem[1])\n return new_list\n\n\ntest_data = [\n ('1', 10),\n ('1', 10),\n ('1', '1'),\n]\n\ntest_value0 = copy_list(test_data)\n# test_value1 = copy_list([1, 2, 3])\n# test_value2 = copy_list([1, 2, 9])\n# test_value3 = copy_list([1.3, 2.1, 3])\n# test_value4 = copy_list([\"srt\", \"rts\", \"str\"])\n# test_value5 = copy_list((\"srt\", \"rts\", \"str\"))\n# test_value6 = copy_list({\"srt\", \"rts\", \"str\"})\n","sub_path":"070_oop/001_classes/examples/ITVDN_Python_Advanced/006_Типизированный Python/example6.py","file_name":"example6.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"7786688","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 6 19:13:01 2018\n\n@author: romai\n\"\"\"\n\nimport sys\nsys.path.append('../utils')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport haardetection as hd\nimport fourier as four\nimport masks\nimport opencv_utils as mycv2\n\nimport yaml\nPATHS = yaml.load(open(\"../config/paths.yaml\"))\n\nface_cascade = mycv2.loadCascadeCassifier(PATHS[\"haarcascade\"][\"frontalface\"])\n\nimage = mycv2.loadImage(PATHS[\"data\"][\"images\"][0])\ngray = mycv2.cvtGray(image)\n\ngrayface = hd.getDetection(gray, hd.track(gray, face_cascade))[0] #Getting the first detected face in the image\n\nfouriertransform = four.getFourierMagnitude(grayface) #Getting the fourier Magnitude\n\nMasks = masks.getRadiusMasks(fouriertransform.shape[0]) #Getting masks\n\n#Plotting the image and its fourier transformation\nplt.figure(figsize = (8, 12))\nplt.subplot(221),plt.imshow(grayface, cmap = 'gray')\nplt.title('Input Image'), plt.xticks([]), plt.yticks([])\nplt.subplot(222),plt.imshow(fouriertransform, cmap = 'gray')\nplt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])\nplt.show()\n\n#Plotting the masked images and their fourier transformation\nplt.figure(figsize = (8, 12))\nfor i in np.arange(len(Masks)):\n mask = Masks[i]\n plt.subplot(len(Masks) * 100 + 20 + 2*i + 1),plt.imshow(grayface * mask, cmap = 'gray')\n plt.title('Input Image'), plt.xticks([]), plt.yticks([])\n plt.subplot(len(Masks) * 100 + 20 + 2*i + 2),plt.imshow(four.getFourierMagnitude(grayface * mask), cmap = 'gray')\n plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])\nplt.show()\n","sub_path":"code/tests/fouriertransform.py","file_name":"fouriertransform.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"102737979","text":"#!/usr/bin/python3\n\n# access a windows domain controller via ldaps\n\nimport ldap\nimport sys\n\nfrom pprint import pprint\n\nldap_uri = 'ldaps://dc1.acme.local:636'\nbind_dn = 'ACME\\\\sam'\nbind_pw = 'Secret123'\nbase_dn = 'CN=users,DC=acme,DC=local'\n\nscope = ldap.SCOPE_SUBTREE\nattributes = ['displayName', 'mail']\nsearch_filter = '(&(objectClass=person)(sAMAccountName=rm))'\n\ntry:\n ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)\n l = ldap.initialize(ldap_uri)\n l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)\n l.simple_bind_s(bind_dn, bind_pw)\n rst = l.search_s(base_dn, scope, search_filter, attributes)\n pprint(rst)\n print('mail: {}'.format(rst[0][1]['mail'][0].decode('UTF-8')))\nexcept (KeyError, IndexError, ldap.LDAPError) as e:\n print(e)\n sys.exit(1)\n","sub_path":"languages/python/module-ldap-ad.py","file_name":"module-ldap-ad.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"258953312","text":"from .utils import *\n\ndef standardGlobalAlignment(textA, textB, match, mismatch, gap, isTable):\n sizeA = len(textA) + 1\n sizeB = len(textB) + 1\n largestNumber = \"\"\n matrix = [[ [] for j in range(sizeB)] for i in range(sizeA)]\n matrix[0][0].append(0)\n for i in range(1, sizeA):\n gapValue = i * gap\n strGapValue = str(gapValue)\n if len(strGapValue) > len(largestNumber):\n largestNumber = strGapValue\n matrix[i][0].append(gapValue)\n matrix[i][0].append(\"U\")\n for j in range(1, sizeB):\n gapValue = j * gap\n if len(strGapValue) > len(largestNumber):\n largestNumber = strGapValue\n matrix[0][j].append(gapValue)\n matrix[0][j].append(\"L\")\n \n #necessary for make the table looks better, it can also have a minus\n\n for i in range(sizeA):\n for j in range(sizeB):\n if(i > 0 and j > 0):\n upGap = matrix[i-1][j][0] + gap\n leftGap = matrix[i][j-1][0] + gap\n comparisonValue = comparison(textA[i-1],\n textB[j-1], match, mismatch, matrix[i-1][j-1][0])\n maxValue = max(upGap, leftGap, comparisonValue)\n matrix[i][j].append(maxValue)\n \n maxValueString = str(maxValue)\n if len(maxValueString) > len(largestNumber):\n largestNumber = maxValueString\n\n if(upGap == maxValue):\n matrix[i][j].append(\"U\")\n if(leftGap == maxValue):\n matrix[i][j].append(\"L\")\n if(comparisonValue == maxValue):\n matrix[i][j].append(\"D\")\n \n score = matrix[sizeA - 1][sizeB - 1][0]\n alignment = getGlobalAlignments(textA, textB, matrix)\n result = []\n result.append(score)\n result.append(alignment)\n if isTable:\n table = getTable(matrix,largestNumber, textA, textB)\n result.append(table)\n return result\n\ndef getGlobalAlignments(textA, textB, matrix):\n resultA = \"\"\n resultB = \"\"\n\n i = len(textA)\n j = len(textB)\n\n while i > 0 and j > 0 and len(matrix[i][j]) > 1:\n if matrix[i][j][1] == \"D\":\n resultA = textA[i-1] + resultA\n resultB = textB[j-1] + resultB\n i = i - 1\n j = j - 1\n elif matrix[i][j][1] == \"U\":\n resultA = textA[i-1] + resultA\n resultB = \"-\" + resultB\n i = i - 1\n elif matrix[i][j][1] == \"L\":\n resultA = \"-\" + resultA\n resultB = textB[j-1] + resultB\n j = j - 1\n \n return resultA + '\\n' + resultB\n\ndef AffineGapAlignment(textA, textB, match, mismatch, openGapPenalty, gapExtensionPenalty,\n isTable):\n sizeA = len(textA) + 1\n sizeB = len(textB) + 1\n largestNumber = \"\"\n matrix = [[[] for j in range(sizeB)] for i in range(sizeA)]\n uppertable = [[0 for j in range(sizeB)] for i in range(sizeA)]\n lowertable = [[0 for j in range(sizeB)] for i in range(sizeA)]\n matrix[0][0].append(0)\n matrix[0][1].append(-openGapPenalty)\n matrix[0][1].append(\"L\")\n matrix[1][0].append(-openGapPenalty)\n matrix[1][0].append(\"U\")\n for i in range(2,len(matrix)):\n matrix[i][0].append(matrix[i-1][0][0] + gapExtensionPenalty)\n matrix[i][0].append(\"U\")\n\n for j in range(2, len(matrix[0])):\n matrix[0][j].append(matrix[0][j-1][0] + gapExtensionPenalty)\n matrix[0][j].append(\"L\") \n\n #Edges means gap extension in textA\n uppertable[0][1] = -openGapPenalty\n for i in range(len(uppertable)):\n uppertable[i][0] = (sizeA - 1) * -openGapPenalty * 10000 #this is our infinite \n for j in range(2, len(uppertable[0])):\n uppertable[0][j] = uppertable[0][j-1] + gapExtensionPenalty \n\n #Edges means gap extension in textB\n lowertable[1][0] = -openGapPenalty\n for j in range(len(lowertable[0])):\n lowertable[0][j] = (sizeB - 1) * -openGapPenalty * 10000 #this is our infinite \n for i in range(2, len(lowertable)):\n lowertable[i][0] = lowertable[i-1][0] + gapExtensionPenalty \n\n for i in range(1, len(matrix)):\n for j in range(1, len(matrix[i])):\n lowertable[i][j] = max(lowertable[i-1][j] + gapExtensionPenalty, matrix[i-1][j][0] - openGapPenalty)\n uppertable[i][j] = max(uppertable[i][j-1] + gapExtensionPenalty, matrix[i][j-1][0] - openGapPenalty)\n score1 = matrix[i-1][j-1][0]\n w1 = mismatch\n if textA[i-1] == textB[j-1]:\n w1 = match\n matrix[i][j].append(max(score1 + w1, lowertable[i][j],uppertable[i][j]))\n\n decision = max(score1 + w1, lowertable[i][j],uppertable[i][j])\n decisionString = str(decision)\n if len(decisionString) > len(largestNumber):\n largestNumber = decisionString\n if decision == score1 + w1:\n matrix[i][j].append(\"D\")\n elif decision == lowertable[i][j]:\n matrix[i][j].append(\"U\")\n else:\n matrix[i][j].append(\"L\")\n \n result = []\n score = matrix[sizeA - 1][sizeB - 1][0]\n result.append(score)\n alignment = getGlobalAlignments(textA, textB, matrix)\n result.append(alignment)\n if isTable:\n table = getTable(matrix, largestNumber, textA, textB)\n result.append(table)\n return result\n\ndef gapPenalty(textA, textB, match, mismatch, gap_one, gap_two, isTable):\n sizeA = len(textA) + 1\n sizeB = len(textB) + 1\n largestNumber = \"\"\n matrix = [[[] for j in range(sizeB)] for i in range(sizeA)]\n\n matrix[0][0].append(0)\n for i in range(1, sizeA):\n matrix[i][0].append(i * gap_one)\n matrix[i][0].append(\"U\")\n for j in range(1, sizeB):\n matrix[0][j].append(j * gap_two)\n matrix[0][j].append(\"L\")\n \n for i in range(1, sizeA):\n for j in range(1, sizeB):\n comparisonValue = comparison(textA[i-1], textB[j-1], match,\n mismatch, matrix[i-1][j-1][0])\n upGap = matrix[i-1][j][0] + gap_one\n leftGap = matrix[i][j-1][0] + gap_two\n maxValue = max(comparisonValue, upGap, leftGap)\n maxValueString = str(maxValue)\n if len(maxValueString) > len(largestNumber):\n largestNumber = maxValueString\n matrix[i][j].append(maxValue)\n if maxValue == comparisonValue:\n matrix[i][j].append(\"D\")\n if maxValue == upGap:\n matrix[i][j].append(\"U\")\n if maxValue == leftGap:\n matrix[i][j].append(\"L\")\n result = []\n score = matrix[sizeA - 1][sizeB - 1][0]\n result.append(score)\n alignment = getGlobalAlignments(textA, textB, matrix)\n result.append(alignment)\n if isTable:\n table = getTable(matrix, largestNumber, textA, textB)\n result.append(table)\n return result\n\ndef globalAlignmentWithKBand(textA, textB, match, mismatch, gap, k, isTable):\n sizeA = len(textA) + 1\n sizeB = len(textB) + 1\n largestNumber = \"\"\n greaterSize = sizeA\n greaterText = textA\n lowerSize = sizeB\n lowerText = textB\n if sizeA < sizeB:\n greaterSize = sizeB\n greaterText = textB\n lowerSize = sizeA\n lowerText = textA\n\n matrix = [[[0] for j in range(lowerSize)] for i in range(greaterSize)]\n for i in range(1,greaterSize):\n if i < k:\n valueGap = i * gap\n valueGapString = str(valueGap)\n if len(valueGapString) > len(largestNumber):\n largestNumber = valueGapString\n matrix[i][0][0] = valueGap\n matrix[i][0].append(\"U\")\n for j in range(1,lowerSize):\n if j < k:\n valueGap = j * gap\n valueGapString = str(valueGap)\n if len(valueGapString) > len(largestNumber):\n largestNumber = valueGapString\n matrix[0][j][0] = valueGap\n matrix[0][j].append(\"L\")\n for i in range(1, greaterSize):\n for d in range(-k, k):\n j = i + d\n if 1 <= j and j <= (lowerSize - 1):\n upGap = matrix[i-1][j][0] + gap\n leftGap = matrix[i][j-1][0] + gap\n comparisonValue = comparison(greaterText[i-1],lowerText[j-1],match,\n mismatch, matrix[i-1][j-1][0])\n matrix[i][j][0] = comparisonValue\n if insideStrip(i - 1, j, k):\n maxValue = max(matrix[i][j][0], upGap)\n matrix[i][j][0] = maxValue\n if insideStrip(i, j - 1, k):\n maxValue = max(matrix[i][j][0], leftGap)\n matrix[i][j][0] = maxValue\n if matrix[i][j][0] == upGap:\n matrix[i][j].append(\"U\")\n if matrix[i][j][0] == comparisonValue:\n matrix[i][j].append(\"D\")\n if matrix[i][j][0] == leftGap:\n matrix[i][j].append(\"L\")\n maxValueString = str(matrix[i][j][0])\n if len(maxValueString) > len(largestNumber):\n largestNumber = maxValueString\n result = []\n score = matrix[greaterSize - 1][lowerSize - 1][0]\n result.append(score)\n alignment = getGlobalAlignments(greaterText, lowerText, matrix)\n result.append(alignment)\n if isTable:\n table = getTableKband(matrix, largestNumber)\n result.append(table)\n return result","sub_path":"BMC_Proyecto_1_Alineamientos-master/principalApp/algoritmos/Global.py","file_name":"Global.py","file_ext":"py","file_size_in_byte":9460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"570471782","text":"#!/usr/bin/python\n\nimport math\n\n\ndef recipe_batches(recipe, ingredients):\n l = []\n\n for ingredient, qty in recipe.items():\n if not ingredients.get(ingredient):\n return 0\n\n l.append(ingredients[ingredient] // qty)\n\n minimum = min(l)\n\n if minimum < 1:\n return 0\n\n return min(l)\n\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test\n # your implementation with different inputs\n recipe = {'milk': 100, 'butter': 50, 'flour': 5}\n ingredients = {'milk': 132, 'butter': 48, 'flour': 51}\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(\n batches=recipe_batches(recipe, ingredients), ingredients=ingredients))\n","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"482722839","text":"#!/usr/bin/env python3\n# coding: utf8\n\nimport tagbook.meta\nimport logging\nimport pytest\n\nlog = logging.getLogger(__name__)\nNOTEXISTINGFILE = 'anuistenarusetnarustinarist.epub'\nEXISTINGFILE = 'test.epub'\n\n\n@pytest.fixture()\ndef createBook(request):\n \"\"\"\n Create an empty eBook\n \"\"\"\n import epub\n book = epub.open_epub(EXISTINGFILE, 'w')\n book.close()\n\n def deleteBook():\n import os\n os.remove(EXISTINGFILE)\n request.addfinalizer(deleteBook)\n\n\n@pytest.fixture()\ndef addContributor():\n metaTest = tagbook.meta.MetaData(EXISTINGFILE)\n metaTest.addContributor('Little Author', 'author', 'Author, Little')\n\n\n@pytest.fixture()\ndef bookMultipleContributors():\n metaTest = tagbook.meta.MetaData(EXISTINGFILE)\n metaTest.addContributor('Little Author', 'author', 'Author, Little')\n metaTest.addContributor('Little Publisher', 'publisher',\n 'Publisher, Little')\n\n\nclass TestMetaContributor:\n def test_contributors(self, createBook):\n m = tagbook.meta.MetaData(EXISTINGFILE)\n log.debug(m.getContributors())\n assert m.meta.contributors == m.getContributors()\n m.cleanContributors()\n log.debug(m.getContributors())\n assert m.getContributors() == []\n assert m.getContributorsNumber() == 0\n m.addContributor('Great Author', 'author', 'Author, Great')\n assert m.getContributorsNumber() == 1\n assert m.getContributors() == [('Great Author', 'author',\n 'Author, Great')]\n assert m.getContributor(0) == ('Great Author', 'author',\n 'Author, Great')\n with pytest.raises(IndexError):\n m.getContributor(1)\n assert m.getRoleContributors('author') == [('Great Author',\n 'Author, Great')]\n assert m.getRoleContributors('publisher') == []\n assert m.getFileAsContributors('Author, Great') == [('Great Author',\n 'author')]\n assert m.getFileAsContributors('') == []\n\n m.addContributor('Great Publisher', 'publisher')\n assert m.getContributorsNumber() == 2\n assert m.getContributors() == [('Great Author', 'author',\n 'Author, Great'),\n ('Great Publisher', 'publisher', '')]\n assert m.getContributor(0) == ('Great Author', 'author',\n 'Author, Great')\n assert m.getContributor(1) == ('Great Publisher', 'publisher', '')\n with pytest.raises(IndexError):\n m.getContributor(2)\n assert m.getRoleContributors('author') == [('Great Author',\n 'Author, Great')]\n assert m.getRoleContributors('publisher') == [('Great Publisher', '')]\n assert m.getFileAsContributors('Author, Great') == [('Great Author',\n 'author')]\n assert m.getFileAsContributors('') == [('Great Publisher',\n 'publisher')]\n\n m.addContributor('Great Other')\n assert m.getContributorsNumber() == 3\n assert m.getContributors() == [('Great Author', 'author',\n 'Author, Great'),\n ('Great Publisher', 'publisher', ''),\n ('Great Other', '', '')]\n assert m.getContributor(0) == ('Great Author', 'author',\n 'Author, Great')\n assert m.getContributor(1) == ('Great Publisher', 'publisher', '')\n assert m.getContributor(2) == ('Great Other', '', '')\n with pytest.raises(IndexError):\n m.getContributor(3)\n assert m.getRoleContributors('author') == [('Great Author',\n 'Author, Great')]\n assert m.getRoleContributors('publisher') == [('Great Publisher', '')]\n assert m.getRoleContributors('') == [('Great Other', '')]\n assert m.getFileAsContributors('Author, Great') == [('Great Author',\n 'author')]\n assert m.getFileAsContributors('') == [('Great Publisher',\n 'publisher'),\n ('Great Other', '')]\n\n m.addContributor('Author2', 'author')\n m.removeContributorByName('Great Other')\n assert m.getContributorsNumber() == 3\n assert m.getContributors() == [('Great Author', 'author',\n 'Author, Great'),\n ('Great Publisher', 'publisher', ''),\n ('Author2', 'author', '')]\n assert m.getContributor(0) == ('Great Author', 'author',\n 'Author, Great')\n assert m.getContributor(1) == ('Great Publisher', 'publisher', '')\n assert m.getContributor(2) == ('Author2', 'author', '')\n with pytest.raises(IndexError):\n m.getContributor(3)\n assert m.getRoleContributors('author') == [('Great Author',\n 'Author, Great'),\n ('Author2', '')]\n assert m.getRoleContributors('publisher') == [('Great Publisher', '')]\n assert m.getFileAsContributors('Author, Great') == [('Great Author',\n 'author')]\n assert m.getFileAsContributors('') == [('Great Publisher',\n 'publisher'),\n ('Author2', 'author')]\n\n m.removeContributorByIndex(0)\n assert m.getContributorsNumber() == 2\n assert m.getContributors() == [('Great Publisher', 'publisher', ''),\n ('Author2', 'author', '')]\n assert m.getContributor(0) == ('Great Publisher', 'publisher', '')\n assert m.getContributor(1) == ('Author2', 'author', '')\n with pytest.raises(IndexError):\n m.getContributor(2)\n assert m.getRoleContributors('author') == [('Author2', '')]\n assert m.getRoleContributors('publisher') == [('Great Publisher', '')]\n assert m.getFileAsContributors('Author, Great') == []\n assert m.getFileAsContributors('') == [('Great Publisher',\n 'publisher'),\n ('Author2', 'author')]\n\n m.addContributor('Publisher2', 'publisher')\n assert m.getContributorsNumber() == 3\n m.removeContributorByRole('publisher')\n assert m.getContributorsNumber() == 1\n assert m.getContributors() == [('Author2', 'author', '')]\n assert m.getContributor(0) == ('Author2', 'author', '')\n with pytest.raises(IndexError):\n m.getContributor(1)\n assert m.getRoleContributors('author') == [('Author2', '')]\n assert m.getRoleContributors('publisher') == []\n assert m.getFileAsContributors('Author, Great') == []\n assert m.getFileAsContributors('') == [('Author2', 'author')]\n\n m.addContributor('Little New One', '', 'One, Little New')\n m.addContributor('Test')\n assert m.getContributorsNumber() == 3\n m.removeContributorByFileas('')\n assert m.getContributorsNumber() == 1\n assert m.getContributors() == [('Little New One', '',\n 'One, Little New')]\n assert m.getContributor(0) == ('Little New One', '', 'One, Little New')\n with pytest.raises(IndexError):\n m.getContributor(1)\n assert m.getRoleContributors('author') == []\n assert m.getRoleContributors('publisher') == []\n assert m.getRoleContributors('') == [('Little New One',\n 'One, Little New')]\n assert m.getFileAsContributors('One, Little New') == [\n ('Little New One', '')\n ]\n assert m.getFileAsContributors('') == []\n\n def test_newContributors(self, createBook, addContributor):\n m = tagbook.meta.MetaData(EXISTINGFILE)\n assert m.getContributorsNumber() == 1\n assert m.getContributors() == [('Little Author',\n 'author',\n 'Author, Little')]\n assert m.getContributor(0) == ('Little Author',\n 'author',\n 'Author, Little')\n assert m.getRoleContributors('author') == [('Little Author',\n 'Author, Little')]\n assert m.getFileAsContributors('Author, Little') == [('Little Author',\n 'author')]\n with pytest.raises(IndexError):\n m.getContributor(1)\n\n def _subtest_openEpubAndRemoveOneContributor(self):\n m = tagbook.meta.MetaData(EXISTINGFILE)\n assert m.getContributorsNumber() == 2\n m.removeContributorByIndex(1)\n\n def test_removeExistingTitles(self, createBook, bookMultipleContributors):\n self._subtest_openEpubAndRemoveOneContributor()\n m = tagbook.meta.MetaData(EXISTINGFILE)\n assert m.getContributorsNumber() == 1\n","sub_path":"src/tagbook/tests/test_contributors.py","file_name":"test_contributors.py","file_ext":"py","file_size_in_byte":9554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"488308106","text":"# @brief Example to test the fracture boundary recovery\n# @author github/PedroLima92\n# @date november 2020\n\nimport subprocess\n# import math\nimport os,sys,inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0,parentdir) \n\nimport animtools\n\n\n\n\n\n\n\n\n\n# ../dfnMesh/\nvtkfile = \"vtkmesh\"\n# where to save vtk files?\ndestination = \"documentation/animations/boundary/ex2/\"\n# ../examples/\nexample = destination+\"boundary2.txt\"\n# ../examples/\nmsh = \"no-msh-file\"\n\n\n\n\n\n\n# grid origin\norigin = [ 0.0, 0.0, 0.0]\n# domain dimensions\ndomain = [ 4.0, 4.0, 4.0]\n# mesh partitions\neltype = \"EHexahedral\"\npartitions = [2, 2, 2]\n\n# preamble\npreamble = \"\"\nif(msh == \"no-msh-file\"):\n preamble += \"Origin\\n\"+str(origin[0])+' '+str(origin[1])+' '+str(origin[2])+' '+\"\\n\\n\"\n preamble += \"Domain\\n\"+str(domain[0])+' '+str(domain[1])+' '+str(domain[2])+' '+\"\\n\\n\"\n preamble += \"Mesh\\n\"+eltype+\"\\n\"+str(partitions[0])+' '+str(partitions[1])+' '+str(partitions[2])+' '+\"\\n\\n\"\nelse:\n preamble += \"Mesh\\n\\\"\"+msh+\"\\\"\"\n\npreamble += \"\\n\\n\"\n\n# Fractures\nfracture0 = \"Fracture 0\\n\"\nfracture0 += \"Limit Erecovered\\n\"\n# p0 = [[ 0.1, 0.8, 0.8, 0.1],\n# [ 7.0, -0.1, -0.1, 7.0],\n# [ -1.0, -1.0, 1.0, 1.0]]\n# for i in range(3):\n# for j in range(len(p0[0])):\n# if(p0[i][j] >= 0.0): fracture0 += ' '\n# fracture0 += str(p0[i][j])+' '\n# fracture0 += \"\\n\"\n\nfracture1 = \"Fracture 1\\n\"\nfracture1 += \"Limit Erecovered\\n\"\n# p0 = [[ 7.0, -0.1, -0.1, 7.0],\n# [ 0.1, 0.8, 0.8, 0.1],\n# [ -1.0, -1.0, 1.0, 1.0]]\n# for i in range(3):\n# for j in range(len(p0[0])):\n# if(p0[i][j] >= 0.0): fracture1 += ' '\n# fracture1 += str(p0[i][j])+' '\n# fracture1 += \"\\n\"\n\n\nx0 = \"\\n-1.50 5.00 5.00 -1.50\"\nz0 = \"\\n-0.50 -0.50 5.00 5.00\"\nx1 = \"\\n 1.50 5.00 5.00 1.50\"\nz1 = \"\\n 1.50 1.50 5.00 5.00\"\n\ntoldist = 0.4\nstep = 0.07\n# steps = 0\nstarty0 = -0.1\nyfinal = 5.0\nsteps = int((yfinal-starty0)/step)\nsteps += 1\n\nfor i in range(steps):\n# for i in range(12,13):\n y0 = starty0 + i*step\n f = open(example,\"w+\")\n f.write(preamble)\n # f.write(\"\\n\\nFracture 0 4\")\n # f.write(x0)\n if y0 < 0 :\n y = (\"\\n%.2f %.2f %.2f %.2f\" % (y0,y0,y0,y0))\n else:\n y = (\"\\n %.2f %.2f %.2f %.2f\" % (y0,y0,y0,y0))\n # f.write(y)\n # f.write(z0)\n f.write(fracture0)\n f.write(y)\n f.write(x0)\n f.write(z0)\n f.write(\"\\n\\n\")\n f.write(fracture1)\n f.write(x1)\n f.write(y)\n f.write(z1)\n f.close()\n # run dfnMesh\n print(y0)\n dfnMesh = [\"build/src/dfnTest\"\n ,example\n ,\"-m\"\n ,msh\n ,\"-td\"\n ,str(toldist)]\n subprocess.call(dfnMesh)\n # @todo exception handler to stop loop could go in here\n rename = [\"cp\"\n , vtkfile+\".vtk\"\n , destination+vtkfile+\".\"+str(i)+\".vtk\"]\n subprocess.call(rename)\n\n\n# for i in range(steps):","sub_path":"documentation/animations/boundary/boundary2.py","file_name":"boundary2.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"383482574","text":"import itertools\nimport time\nimport random\nimport math\n\ndef go(times = 1, recursiveTimes=18):\n\tavailableChoices = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49]\n\t\n\t#13983816 -- ALL\n\t#13596115\n\t#12972701\n\t#6234550\n\t#1944511 - 3 excluded \n\t#1245568 - 7 excluded\n\t# 261503 - 14 excluded\n\tcomb = list(itertools.combinations(availableChoices,6))\n\t\n\tunfortuneNumbers = [7, 18 , 19 , 32 , 37 , 49, 6 , 13 , 18 , 31 , 39 , 40]\n\tfinalResult = []\n\t\n\tprint(len(comb))\n\tfor i in range(0, len(comb)):\n\t\tif i % 100000 == 0:\n\t\t\tprint(i)\n\t\tif IsAllRed(comb[i]) == True:\n\t\t\tcontinue\n\t\tif IsAllBlue(comb[i]) == True:\n\t\t\tcontinue\n\t\tif IsAllGreen(comb[i]) == True:\n\t\t\tcontinue\n\t\tif IsAllEven(comb[i]) == True:\n\t\t\tcontinue\n\t\tif IsAllOdd(comb[i]) == True:\n\t\t\tcontinue\n\t\tif IsThreeContinuousNumber(comb[i]) == True:\n\t\t\tcontinue\n\t\tif DoNotHaveOrMoreThanTwoTwoContinuousNumber(comb[i]) == True:\n\t\t\tcontinue\n\t\tif DoNotEmptyOneDoor(comb[i]) == True:\n\t\t\tcontinue\n\t\tif IncludeUnfortuneNumber(comb[i], unfortuneNumbers) == True:\n\t\t\tcontinue\n\t\t\n\t\tfinalResult.append(comb[i])\n\tprint(len(finalResult))\n\t\n\tfor t in range(0,times):\n\t\tprint(t)\n\t\ttemp = halve(finalResult, recursiveTimes)\n\t\tfor i in temp:\n\t\t\tprint(i)\n\t\ndef IsAllRed(daList):\n\tredBall = [1,2,7,8,12,13,18,19,23,24,29,30,34,35,40,45,46]\n\treturn set(daList) < set(redBall)\n\ndef IsAllBlue(daList):\n\tblueBall = [3,4,9,10,14,15,20,25,26,31,32,36,37,41,42,47,48]\n\treturn set(daList) < set(blueBall)\n\t\ndef IsAllGreen(daList):\n\tgreenBall = [5,6,11,16,17,21,22,27,28,32,33,38,39,43,44,49]\n\treturn set(daList) < set(greenBall)\n\t\ndef IsThreeContinuousNumber(daList):\n\tfor j in range(0, len(daList)):\n\t\tif j + 2 < len(daList):\n\t\t\tif daList[j] + 1 == daList[j+1]:\n\t\t\t\tif daList[j+1] +1 == daList[j+2]:\n\t\t\t\t\treturn True\n\treturn False\n\ndef DoNotHaveOrMoreThanTwoTwoContinuousNumber(daList):\n\tcnt = 0\n\tfor j in range(0, len(daList)):\n\t\tif j + 1 < len(daList):\n\t\t\tif daList[j] + 1 == daList[j+1]:\n\t\t\t\tcnt = cnt + 1\n\treturn cnt != 1\n\ndef DoNotEmptyOneDoor(daList):\n\temptyDoorCnt = 0\n\t\n\tset0 = [1,2,3,4,5,6,7,8,9]\n\tset1 = [10,11,12,13,14,15,16,17,18,19]\n\tset2 = [20,21,22,23,24,25,26,27,28,29]\n\tset3 = [30,31,32,33,34,35,36,37,38,39]\n\tset4 = [40,41,42,43,44,45,46,47,48,49]\n\t\n\tif len(set(daList) & set(set0)) == 0:\n\t\temptyDoorCnt = emptyDoorCnt+1\n\tif len(set(daList) & set(set1)) == 0:\n\t\temptyDoorCnt = emptyDoorCnt+1\n\tif len(set(daList) & set(set2)) == 0:\n\t\temptyDoorCnt = emptyDoorCnt+1\n\tif len(set(daList) & set(set3)) == 0:\n\t\temptyDoorCnt = emptyDoorCnt+1\n\tif len(set(daList) & set(set4)) == 0:\n\t\temptyDoorCnt = emptyDoorCnt+1\n\t\n\treturn emptyDoorCnt != 1\n\ndef IsAllGreen(daList):\n\tgreenBall = [5,6,11,16,17,21,22,27,28,32,33,38,39,43,44,49]\n\treturn set(daList) < set(greenBall)\n\t\ndef IsAllEven(daList):\n\tfor j in range(0, len(daList)):\n\t\tif daList[j] % 2 > 0:\n\t\t\treturn False\n\treturn True\n\ndef IsAllOdd(daList):\n\tfor j in range(0, len(daList)):\n\t\tif daList[j] % 2 == 0:\n\t\t\treturn False\n\treturn True\n\t\ndef IncludeUnfortuneNumber(daList, unfortuneNumbers):\n\tfor j in range(0, len(daList)):\n\t\tif daList[j] in unfortuneNumbers:\n\t\t\treturn True;\n\treturn False\n\ndef halve(daList, recursiveTimes=3):\n\tgetVar = lambda searchList, ind: [searchList[i] for i in ind]\n\t\n\tside = random.randint(0,1)\n\tmiddle = math.ceil(len(daList)/2)\n\t\n\tcnt = recursiveTimes\n\tselected = list(daList)\n\t\n\tif side == 0:\n\t\tselected[middle:len(selected)] = []\n\telse:\n\t\tselected[0:middle-1] = []\n\t\n\tcnt = cnt - 1\n\tif cnt == 0:\n\t\treturn selected\n\telse:\n\t\treturn halve(selected, cnt)","sub_path":"script/elimination-plus.py","file_name":"elimination-plus.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"136000601","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\n\nfrom accounts.forms import UserCreationForm, UserUpdateForm, ProfileUpdateForm\nfrom accounts.models import User, UserProfile, Log\n\n\ndef register(request, *args, **kwargs):\n title = 'User Registration'\n form = UserCreationForm(request.POST or None)\n if form.is_valid():\n form.save()\n email = form.cleaned_data.get('email')\n user = User.objects.get(email=email)\n Log.objects.create(user=user.get_full_name(), subject='Registration', detail='User Registration Complete')\n return redirect('login')\n context = {\n 'title': title,\n 'form': form\n }\n return render(request, \"accounts/register.html\", context)\n\n\n@login_required\ndef profile(request):\n title = 'User Profile'\n user = request.user\n try:\n profile = UserProfile.objects.get(user=user)\n context = {\n 'user': user,\n 'title': title\n }\n return render(request, 'dashboard/profile.html', context)\n except:\n profile = UserProfile.objects.create(user=user)\n context = {\n 'user': user,\n 'title': title\n }\n return render(request, 'dashboard/profile.html', context)\n\n\n@login_required\ndef edit_profile(request):\n if request.method == 'POST':\n u_form = UserUpdateForm(request.POST, instance=request.user)\n p_form = ProfileUpdateForm(request.POST,\n request.FILES,\n instance=request.user.userprofile)\n if u_form.is_valid() and p_form.is_valid():\n u_form.save()\n p_form.save()\n messages.success(request, 'Your profile has been updated!')\n return redirect('profile')\n\n else:\n u_form = UserUpdateForm(instance=request.user)\n p_form = ProfileUpdateForm(instance=request.user.userprofile)\n\n context = {\n 'user_form': u_form,\n 'profile_form': p_form\n }\n\n return render(request, 'dashboard/edit_profile.html', context)\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"515020080","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n@author: zhangjianshen\n@file: auto_init_class\n@time: 2018/10/22\n'''\nimport inspect\n\n\n# f_args = inspect.getargspec(barplot)\n# dict(f_args._asdict())\n\ndef fn_auto_init_class(auto_class, input_dict):\n assert isinstance(input_dict, dict), ValueError('input_dict must be a dict')\n f = auto_class.__init__\n f_args = inspect.getargspec(f)\n if f_args.defaults is not None:\n f_args_tuple = list(zip(f_args.args[-len(f_args.defaults):], f_args.defaults))\n f_args_tuple.extend(\n list(zip(f_args.args[1:-len(f_args.defaults)], [None] * int(len(f_args.args[1:-len(f_args.defaults)])))))\n else:\n f_args_tuple = list(zip(f_args.args[1:], [None] * int(len(f_args.args[1:]))))\n f_args_dict = dict(f_args_tuple)\n f_args_dict_key = f_args_dict.keys()\n mid_input_dict = {key: input_dict.get(key, f_args_dict.get(key)) for key in f_args_dict_key}\n f_args_dict.update(mid_input_dict)\n return auto_class(**f_args_dict)\n","sub_path":"longgb/Scripts/PyCode/auto_init_class.py","file_name":"auto_init_class.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"163723096","text":"from coolorange.tools import *\n\ndef twin_t_match(model, data, result, col_names, core_only=False):\n \"\"\" calculateif twin_t_match\n\n Parameters: model (model object) - the prediction model obj\n data (DataFrame) - the data load from ETL methods\n result (dict) - a dictionary of real result,\n can be extracted from ETL method: extract_missing_result()\n o/w, need to follow the format {race_id:list/array of first 3 places}\n col_names (array-like) - the column names in order that matches with the model dimension\n core_only (boo) - if we only bet on position (i.e. first 3 places)\n optional, default is False, i.e. bet on twin-t, not position\n\n Returns: (dict) - dictionary contains the match result\n \"\"\"\n\n def single_race_twin_t(model, separated, col_names, id_, result, core_only=False):\n \"\"\" single race result match with twin-t method\n \"\"\"\n cal_result = model.predict_proba(separated[id_][col_names].values)[:,1]\n sorted_cal_result = np.argsort(cal_result)[::-1] + 1\n\n real_result = [int(i) for i in result[id_]]\n\n core_win = [sorted_cal_result[i] in real_result for i in [0,1,2]]\n rest_win = not bool(len(set(real_result) - set(sorted_cal_result[:8])))\n\n if core_only:\n return core_win\n else:\n prediction_result = np.array(core_win) * np.array(rest_win)\n return prediction_result\n\n file_name = data.file_name.unique()[0]\n unique_sheet_name = data.sheet_name.unique()\n separated = {'_'.join(format_date_race(file_name, i)):data[data.sheet_name == i] for i in unique_sheet_name}\n\n all_prediction_result = {i:single_race_twin_t(model, separated, col_names, i, result, core_only) for i in separated}\n return all_prediction_result\n","sub_path":"ETL/coolorange/result_ver.py","file_name":"result_ver.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"305953345","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport _init_paths\n\nimport os\nimport cv2\nimport pandas as pd\nfrom src.lib.opts_mayank_multitask import opts\nfrom src.lib.detectors.detector_factory import detector_factory\nfrom src.lib.datasets.dataset_factory import dataset_factory\n\nimage_ext = ['jpg', 'jpeg', 'png', 'webp']\nvideo_ext = ['mp4', 'mov', 'avi', 'mkv']\ntime_stats = ['tot', 'load', 'pre', 'net', 'dec', 'post', 'merge']\nclass_name = [\"person\", \"rider\", \"car\", \"bus\", \"truck\", \"bike\", \"motor\", \"traffic light\", \"traffic sign\", \"train\"]\n\n\ndef demo(opt):\n\n os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpus_str\n bblabel=[]\n # opt.debug = max(opt.debug, 1)\n\n Dataset = dataset_factory[opt.dataset]\n opt = opts().update_dataset_info_and_set_heads(opt, Dataset)\n\n Detector = detector_factory[opt.task]\n detector = Detector(opt)\n\n if opt.demo == 'webcam' or \\\n opt.demo[opt.demo.rfind('.') + 1:].lower() in video_ext:\n cam = cv2.VideoCapture(0 if opt.demo == 'webcam' else opt.demo)\n detector.pause = False\n while True:\n _, img = cam.read()\n cv2.imshow('input', img)\n ret = detector.run(img)\n time_str = ''\n for stat in time_stats:\n time_str = time_str + '{} {:.3f}s |'.format(stat, ret[stat])\n # print(time_str)\n if cv2.waitKey(1) == 27:\n return # esc to quit\n else:\n if os.path.isdir(opt.demo):\n image_names = []\n ls = os.listdir(opt.demo)\n for file_name in sorted(ls):\n ext = file_name[file_name.rfind('.') + 1:].lower()\n if ext in image_ext:\n image_names.append(os.path.join(opt.demo, file_name))\n else:\n image_names = [opt.demo]\n for index,(image_name) in enumerate(image_names):\n\n ret = detector.run(image_name)\n # if index > 50:\n # break\n\n\n #################################################################33\n resu = ret['results']\n for data in resu:\n # print(resu[data])\n for arr in resu[data]:\n # print(arr)\n # print(data)\n\n # $$$$$$$$$$$$$$$$$$$$$$\n xmin = int(arr[0])\n ymin = int(arr[1])\n xmax = int(arr[2])\n ymax = int(arr[3])\n score = float(arr[4])\n width = 1\n height = 1\n # coordinate = [xmin, ymin, xmax, ymax, class_num]\n # object_name=object_name+\"_\"+light_color\n # object_name = \"traffic_light\"\n # print(data)\n object_name = class_name[data-1]\n data_label = [image_name, width, height, object_name, xmin, ymin, xmax, ymax,score]\n # data_label = [file_name, width, height, object_name, xmin, ymin, xmax, ymax]\n if not ((xmin == xmax) and (ymin == ymax)):\n bblabel.append(data_label)\n # print(file_name)\n # print()\n else:\n 1\n # print(\"file_name\")\n\n\n\n\n\n ############################## #############################################333\n time_str = ''\n for stat in time_stats:\n time_str = time_str + '{} {:.3f}s |'.format(stat, ret[stat])\n print(time_str)\n\n columns = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax','score']\n df = pd.DataFrame(bblabel, columns=columns)\n df.to_csv('centernet_multitask.csv', index=False)\n\nif __name__ == '__main__':\n # opt = opts().init()\n opt = opts().parse()\n demo(opt)\n","sub_path":"src/demo_mayank_multitask.py","file_name":"demo_mayank_multitask.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"198720759","text":"# Interactions\nSERVICES = {} # various services\nNODES = {} # nodes that can be used for listing\nSECTIONS = {} # sections supported by section module\nPLUGINS = {} # config for services / plugins\n\n# Files\nDB_FILE = None\nMETADATA_FILE = None\nDATA_PATH = None\n\n# Misc\nBASE_URL = None\nMETADATA_CACHE_TIME = 60*60*24*30\nPHANTOMJS_PORT = 41044","sub_path":"apiserver/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"165574748","text":"import os\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.python.framework import graph_util\n\nimport transform\nimport utils\n\n\npretrained_style_file = 'pretrained_styles/rain_princess.ckpt'\nbatch_size = 1\nimage_max_size = 400\ncontent_img_path = '../../test_data/me.jpeg'\n\ncontent_img = utils.read_image(content_img_path, preprocess_flag=True, max_size=image_max_size)\n\n\ng = tf.Graph()\nsoft_config = tf.ConfigProto(allow_soft_placement=True)\nwith g.as_default(), tf.Session(config=soft_config) as sess:\n img_placeholder = tf.placeholder(tf.float32, shape=(batch_size, image_max_size, image_max_size, 3),\n name='img_placeholder')\n preds = transform.net(img_placeholder)\n saver = tf.train.Saver()\n\n saver.restore(sess, pretrained_style_file)\n\n output_node_names = ['Tanh']\n output_graph_def = tf.graph_util.convert_variables_to_constants(\n sess, # The session is used to retrieve the weights\n tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes\n output_node_names # The output node names are used to select the usefull nodes\n )\n with tf.gfile.GFile('test/aa.pb', \"wb\") as f:\n f.write(output_graph_def.SerializeToString())\n","sub_path":"ImageStyle/feedward/test_pb.py","file_name":"test_pb.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"83778780","text":"import unittest\nfrom special_relativity import Vector3D\nimport numpy as np\nimport pandas as pd\n\n\nclass TestVector3D(unittest.TestCase):\n\n def setUp(self):\n self.df = pd.DataFrame([[1, 2, 3, 4],\n [2, 4, 5, 6],\n [3, 3, 1, 7]])\n self.x = Vector3D(self.df[0], self.df[1], self.df[2])\n self.y = self.df[3]\n\n @unittest.skip(\"We will fix the product things later...\")\n def test__mul__forInnerProduct(self):\n \"\"\"Verify the multiplication in Vector3D * Vector3D (= Number)\"\"\"\n np.testing.assert_allclose(\n self.x * self.x, self.df[0]**2 + self.df[1]**2 + self.df[2]**2)\n\n @unittest.skip(\"We will fix the product things later...\")\n def test__mul__forScalarProduct(self):\n \"\"\"Verify the multiplication in Vector3D * Number (= Vector3D)\"\"\"\n self.assertTrue(self.x * self.y == Vector3D(\n self.df[0] * self.df[3], self.df[1] * self.df[3], self.df[2] * self.df[3]))\n self.assertTrue(self.x.__mul__(self.y) == Vector3D(\n self.df[0] * self.df[3], self.df[1] * self.df[3], self.df[2] * self.df[3]))\n\n @unittest.skip(\"We will fix the product things later...\")\n def test__rmul__(self):\n \"\"\"Verify the multiplication in Number * Vector3D (= Vector3D)\"\"\"\n self.assertTrue(self.y * self.x == Vector3D(self.df[0] * self.df[3], self.df[1] * self.df[3], self.df[2]* self.df[3]))\n\n def tearDown(self):\n self.df = None\n self.x = None\n self.y = None\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_Vector3D.py","file_name":"test_Vector3D.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"54283320","text":"from socket import *\nfrom multiprocessing import Process\n\nserver_socket = socket(AF_INET, SOCK_STREAM)\nserver_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\nserver_socket.bind((\"\", 5000))\nserver_socket.listen(4)\n\ndef deal_client(client_socket):\n data = client_socket.recv(1024)\n # print(type(data)) #byte\n # print(data)\n start_line = \"HTTP/1.1 200 OK\\r\\n\"\n headers = \"Server: Lisuple server\\r\\n\"\n body = \"Welcome!\\r\\n\"\n response = start_line + headers + \"\\r\\n\" + body\n client_socket.send(bytes(response, \"utf-8\")) # must be bytes\n client_socket.close()\n \n\nwhile True:\n client_socket, client_info = server_socket.accept()\n print(\"%s on line\" %(client_info,))\n p = Process(target=deal_client, args=(client_socket,))\n p.start()\n client_socket.close()\n","sub_path":"python/httpServer/01-static_web_server.py","file_name":"01-static_web_server.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"264523334","text":"# Copyright 2016 - Nokia\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nimport re\nimport six\n\nfrom oslo_log import log\nfrom voluptuous import All\nfrom voluptuous import Any\nfrom voluptuous import Error\nfrom voluptuous import Invalid\nfrom voluptuous import Required\nfrom voluptuous import Schema\n\nfrom vitrage.common.constants import edge_labels\nfrom vitrage.common.constants import entities_categories\nfrom vitrage.evaluator.actions.base import action_types\nfrom vitrage.evaluator.template_fields import TemplateFields\nfrom vitrage.evaluator.template_validation.base import Result\nfrom vitrage.evaluator.template_validation.error_messages import error_msgs\n\nLOG = log.getLogger(__name__)\n\n\nRESULT_DESCRIPTION = 'Template syntax validation'\nCORRECT_RESULT_MESSAGE = 'Template syntax is OK'\n\n\ndef syntax_validation(template_conf):\n\n result = validate_template_sections(template_conf)\n\n if result.is_valid:\n metadata = template_conf[TemplateFields.METADATA]\n result = validate_metadata_section(metadata)\n\n if result.is_valid:\n definitions = template_conf[TemplateFields.DEFINITIONS]\n result = validate_definitions_section(definitions)\n\n if result.is_valid:\n scenarios = template_conf[TemplateFields.SCENARIOS]\n result = validate_scenarios_section(scenarios)\n\n return result\n\n\ndef validate_template_sections(template_conf):\n\n schema = Schema({\n Required(TemplateFields.DEFINITIONS, msg=error_msgs[21]): dict,\n Required(TemplateFields.METADATA, msg=error_msgs[62]): dict,\n Required(TemplateFields.SCENARIOS, msg=error_msgs[80]): list\n })\n return _validate_dict_schema(schema, template_conf)\n\n\ndef validate_metadata_section(metadata):\n\n any_str = Any(str, six.text_type)\n\n schema = Schema({\n Required(TemplateFields.ID, msg=error_msgs[60]): any_str,\n TemplateFields.DESCRIPTION: any_str\n })\n return _validate_dict_schema(schema, metadata)\n\n\ndef validate_definitions_section(definitions):\n\n schema = Schema({\n Required(TemplateFields.ENTITIES, error_msgs[20]): list,\n TemplateFields.RELATIONSHIPS: list\n })\n result = _validate_dict_schema(schema, definitions)\n\n if result.is_valid:\n result = validate_entities(definitions[TemplateFields.ENTITIES])\n\n relationships = definitions.get(TemplateFields.RELATIONSHIPS, None)\n if result.is_valid and relationships:\n return validate_relationships(relationships)\n\n return result\n\n\ndef validate_entities(entities):\n\n if not entities:\n LOG.error(error_msgs[43])\n return _get_fault_result(error_msgs[43])\n\n for entity in entities:\n\n schema = Schema({\n Required(TemplateFields.ENTITY, msg=error_msgs[46]): dict,\n })\n result = _validate_dict_schema(schema, entity)\n\n if result.is_valid:\n result = validate_entity_dict(entity[TemplateFields.ENTITY])\n\n if not result.is_valid:\n return result\n\n return result\n\n\ndef validate_entity_dict(entity_dict):\n\n any_str = Any(str, six.text_type)\n schema = Schema({\n Required(TemplateFields.CATEGORY, msg=error_msgs[42]):\n All(_validate_category_field()),\n TemplateFields.TYPE: any_str,\n Required(TemplateFields.TEMPLATE_ID, msg=error_msgs[41]):\n All(_validate_template_id_value())\n }, extra=True)\n\n return _validate_dict_schema(schema, entity_dict)\n\n\ndef validate_relationships(relationships):\n\n for relationship in relationships:\n\n schema = Schema({\n Required(TemplateFields.RELATIONSHIP, msg=error_msgs[101]): dict,\n })\n result = _validate_dict_schema(schema, relationship)\n\n if result.is_valid:\n relationship_dict = relationship[TemplateFields.RELATIONSHIP]\n result = validate_relationship_dict(relationship_dict)\n\n if not result.is_valid:\n return result\n return result\n\n\ndef validate_relationship_dict(relationship_dict):\n\n any_str = Any(str, six.text_type)\n schema = Schema({\n Required(TemplateFields.SOURCE, msg=error_msgs[102]): any_str,\n Required(TemplateFields.TARGET, msg=error_msgs[103]): any_str,\n TemplateFields.RELATIONSHIP_TYPE: _validate_relationship_type_field(),\n Required(TemplateFields.TEMPLATE_ID, msg=error_msgs[104]):\n All(_validate_template_id_value())\n })\n return _validate_dict_schema(schema, relationship_dict)\n\n\ndef validate_scenarios_section(scenarios):\n\n if not scenarios:\n LOG.error(error_msgs[81])\n return _get_fault_result(error_msgs[81])\n\n for scenario in scenarios:\n\n schema = Schema({\n Required(TemplateFields.SCENARIO, msg=error_msgs[82]): dict,\n })\n result = _validate_dict_schema(schema, scenario)\n\n if result.is_valid:\n result = validate_scenario(scenario[TemplateFields.SCENARIO])\n\n if not result.is_valid:\n return result\n\n return result\n\n\ndef validate_scenario(scenario):\n\n any_str = Any(str, six.text_type)\n schema = Schema({\n Required(TemplateFields.CONDITION, msg=error_msgs[83]): any_str,\n Required(TemplateFields.ACTIONS, msg=error_msgs[84]): list\n })\n result = _validate_dict_schema(schema, scenario)\n\n if result.is_valid:\n return validate_actions_schema(scenario[TemplateFields.ACTIONS])\n\n return result\n\n\ndef validate_actions_schema(actions):\n\n if not actions:\n LOG.error(error_msgs[121])\n return _get_fault_result(error_msgs[121])\n\n for action in actions:\n\n schema = Schema({\n Required(TemplateFields.ACTION, msg=error_msgs[122]): dict,\n })\n result = _validate_dict_schema(schema, action)\n\n if result.is_valid:\n result = validate_action_schema(action[TemplateFields.ACTION])\n\n if not result.is_valid:\n return result\n\n return result\n\n\ndef validate_action_schema(action):\n\n schema = Schema({\n Required(TemplateFields.ACTION_TYPE, msg=error_msgs[123]):\n _validate_action_type_field(),\n TemplateFields.PROPERTIES: dict,\n Required(TemplateFields.ACTION_TARGET, msg=error_msgs[124]): dict\n })\n return _validate_dict_schema(schema, action)\n\n\ndef _validate_dict_schema(schema, value):\n\n try:\n schema(value)\n except Error as e:\n LOG.error(e)\n return _get_fault_result(e)\n\n return _get_correct_result()\n\n\ndef _get_fault_result(comment):\n return Result(RESULT_DESCRIPTION, False, comment)\n\n\ndef _get_correct_result():\n return Result(RESULT_DESCRIPTION, True, 'Template syntax is OK')\n\n\ndef _validate_template_id_value(msg=None):\n def f(v):\n if re.match(\"_*[a-zA-Z]+\\\\w*\", str(v)):\n return str(v)\n else:\n raise Invalid(msg or error_msgs[1])\n return f\n\n\ndef _validate_category_field(msg=None):\n def f(v):\n if str(v) in entities_categories:\n return str(v)\n else:\n raise Invalid(msg or error_msgs[45])\n return f\n\n\ndef _validate_relationship_type_field(msg=None):\n def f(v):\n if str(v) in edge_labels:\n return str(v)\n else:\n raise Invalid(msg or error_msgs[100])\n return f\n\n\ndef _validate_action_type_field(msg=None):\n def f(v):\n if str(v) in action_types:\n return str(v)\n else:\n raise Invalid(msg or error_msgs[120])\n return f\n","sub_path":"vitrage/evaluator/template_validation/template_syntax_validator.py","file_name":"template_syntax_validator.py","file_ext":"py","file_size_in_byte":7961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"285722258","text":"\n\nfrom xai.brain.wordbase.nouns._scanner import _SCANNER\n\n#calss header\nclass _SCANNERS(_SCANNER, ):\n\tdef __init__(self,): \n\t\t_SCANNER.__init__(self)\n\t\tself.name = \"SCANNERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"scanner\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_scanners.py","file_name":"_scanners.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"201885563","text":"from django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group\nfrom notifications.signals import notify\n\nfrom django.conf import settings\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom simple_history.models import HistoricalRecords\n\nfrom smallissue.models import BaseModel\nfrom smallissue.utils import get_or_none_if_pk_is_none\n\n\nclass Project(BaseModel):\n key = models.CharField(max_length=5)\n name = models.CharField(max_length=128)\n leader = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='projects_leading')\n users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='projects', through='Participation')\n order = models.PositiveSmallIntegerField(null=True)\n\n def __str__(self):\n return '{}#{}'.format(self.name, self.id)\n\n\ndef add_project_leader_to_leader_group(sender, instance: Project, created, **kwargs):\n if created:\n group = Group.objects.get(name='project_leader')\n instance.leader.groups.add(group)\n\n\npost_save.connect(add_project_leader_to_leader_group, sender=Project)\n\n\nclass Participation(models.Model):\n project = models.ForeignKey(Project, on_delete=models.CASCADE)\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n job_title = models.CharField(max_length=80, null=True, blank=True)\n date_joined = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return '{} - {}'.format(self.project, self.user.username)\n\n\nclass Team(models.Model):\n project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='teams')\n users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='project_teams', blank=True)\n name = models.CharField(max_length=128)\n\n def __str__(self):\n return '{} {}'.format(self.project, self.name)\n\n\nclass Issue(BaseModel):\n class STATUS(models.IntegerChoices):\n TODO = 0\n DOING = 1\n DONE = 2\n HOLD = 3\n\n key = models.CharField(max_length=20, null=True)\n title = models.CharField(max_length=128)\n body = models.TextField(null=True, blank=True)\n author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n assignee = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='assigned_issues',\n null=True)\n subscribers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='subscribed_issues',\n through='IssueSubscription', blank=True)\n status = models.SmallIntegerField(choices=STATUS.choices, default=STATUS.TODO)\n project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='issues')\n order = models.PositiveSmallIntegerField(null=True)\n tags = models.ManyToManyField('issue.Tag', related_name='issues', through='IssueTagging',\n through_fields=('issue', 'tag'))\n history = HistoricalRecords()\n\n def __str__(self):\n return '#{}: {}'.format(self.id, self.title)\n\n\ndef generate_key(sender, instance, created, **kwargs):\n if created:\n key_num = Issue.objects.filter(project=instance.project).count()\n instance.key = instance.project.key + '-' + str(key_num)\n instance.save()\n\n\ndef subscribe_author_when_created(sender, instance: Issue, created, **kwargs):\n if created:\n instance.subscribers.add(instance.author)\n\n\npost_save.connect(generate_key, sender=Issue)\npost_save.connect(subscribe_author_when_created, sender=Issue)\n\n\nclass IssueSubscription(models.Model):\n issue = models.ForeignKey(Issue, on_delete=models.CASCADE)\n subscriber = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n\n def __str__(self):\n return '{} to issue#{}({})'.format(self.subscriber.username, self.issue.id, self.issue.title)\n\n\nclass Comment(BaseModel):\n content = models.TextField()\n issue = models.ForeignKey(Issue, on_delete=models.CASCADE, related_name='comments')\n author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='issue_comments')\n\n\nclass Tag(models.Model):\n name = models.CharField(max_length=30)\n\n\nclass IssueTagging(models.Model):\n tag = models.ForeignKey(Tag, on_delete=models.CASCADE)\n issue = models.ForeignKey(Issue, on_delete=models.CASCADE)\n history = HistoricalRecords()\n\n\nclass IssueHistory(models.Model):\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n history_id = models.PositiveIntegerField()\n issue_id = models.PositiveIntegerField(blank=True, null=True)\n history = GenericForeignKey('content_type', 'history_id')\n history_date = models.DateTimeField(null=True)\n\n class Meta:\n ordering = ['-history_date']\n\n\ndef get_change_from_histories(histories):\n User = get_user_model()\n result = []\n for issue_history in histories:\n history = issue_history.history\n if history.__class__ == Issue.history.model:\n if history.prev_record:\n delta = history.diff_against(history.prev_record, excluded_fields=['order', 'project', ])\n for change in delta.changes:\n if change.field == 'key':\n continue\n\n data = {\n 'field': change.field,\n 'user': {'id': history.history_user.id, 'username': history.history_user.username},\n 'type': history.history_type,\n 'date': history.history_date,\n }\n if change.field == 'assignee':\n old_assignee = get_or_none_if_pk_is_none(User, change.old)\n new_assignee = get_or_none_if_pk_is_none(User, change.new)\n data['old_value'] = {'id': change.old,\n 'username': old_assignee.username if old_assignee else None}\n data['new_value'] = {'id': change.new,\n 'username': new_assignee.username if new_assignee else None}\n else:\n data['old_value'] = change.old\n data['new_value'] = change.new\n\n result.append(data)\n else:\n result.append({\n 'field': None,\n 'old_value': None,\n 'new_value': None,\n 'user': {'id': history.history_user.id, 'username': history.history_user.username},\n 'type': history.history_type,\n 'date': history.history_date,\n })\n elif history.__class__ == IssueTagging.history.model:\n result.append({\n 'field': 'tags',\n 'old_value': None,\n 'new_value': history.tag.name,\n 'user': {'id': history.history_user.id, 'username': history.history_user.username},\n 'type': history.history_type,\n 'date': history.history_date\n })\n else:\n raise TypeError('이슈와 이슈태깅 히스토리컬 모델이 아닙니다.')\n\n return result\n\n\ndef notify_issue_changes(sender, instance, created, **kwargs):\n issue = Issue.objects.get(id=instance.issue_id)\n actor = instance.history.history_user\n issue_subscribers = issue.subscribers.exclude(id=actor.id)\n\n if not issue_subscribers.exists():\n return\n\n # change = get_change_from_histories([instance])[0]\n\n h = instance.history\n if h.__class__ == Issue.history.model: # HistoricalIssue\n if h.history_type == \"+\":\n description = \"이슈를 생성했습니다.\"\n verb = \"생성\"\n elif h.history_type == \"-\":\n description = \"이슈를 삭제했습니다.\"\n verb = \"삭제\"\n else: # h.history_type == \"~\"\n description = \"이슈를 업데이트헀습니다.\"\n verb = \"업데이트\"\n else: # HistoricalIssueTagging, 태그는 추가, 삭제 모두 이슈 업데이트로 알림.\n description = \"이슈를 업데이트했습니다.\"\n verb = \"업데이트\"\n\n # issue_data = {'id': issue.id, 'key': issue.key, 'title': issue.title, 'project_id': issue.project.id, 'change': change}\n\n notify.send(actor, recipient=issue_subscribers, verb=verb, target=instance,\n description=description)\n\n\npost_save.connect(notify_issue_changes, sender=IssueHistory)\n\n\ndef create_issue_history(sender, instance, created, **kwargs):\n content_type = ContentType.objects.get_for_model(instance)\n\n if sender == Issue.history.model:\n issue_id = instance.id\n elif sender == IssueTagging.history.model:\n issue_id = instance.issue_id\n else:\n raise TypeError('이슈와 이슈태깅 히스토리컬 모델이 아닙니다.')\n\n try:\n issue_history = IssueHistory.objects.get(\n content_type=content_type,\n history_id=instance.history_id,\n issue_id=issue_id\n )\n except IssueHistory.DoesNotExist:\n issue_history = IssueHistory(\n content_type=content_type,\n history_id=instance.history_id,\n issue_id=issue_id\n )\n\n issue_history.history_date = instance.history_date\n issue_history.save()\n\n\npost_save.connect(create_issue_history, sender=Issue.history.model)\npost_save.connect(create_issue_history, sender=IssueTagging.history.model)\n\n\ndef attachment_directory_path(instance, filename):\n return 'attachment/{0}/{1}'.format(instance.project.name, filename)\n\n\nclass Attachment(models.Model):\n file = models.FileField(upload_to=attachment_directory_path, blank=True, null=True)\n author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, blank=True, null=True)\n project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='attachments')\n uploaded_at = models.DateTimeField(auto_now_add=True)\n content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n content_id = models.PositiveIntegerField()\n content = GenericForeignKey('content_type', 'content_id')\n\n def __str__(self):\n return self.title\n\n @property\n def filename(self):\n return self.file.name.split('/')[-1:][0]\n","sub_path":"issue/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"177111384","text":"#phrase=input(\"Entrez une phrase\")#simplement pour tester\ndef noaccent(data):\n \"\"\" supprime les accents du texte data \"\"\"\n data2=\"\"#il FAUT créer la nouvelle phrase(vide)\n accents = { 'a': ['à', 'ã', 'á', 'â'],\n 'e': ['é', 'è', 'ê', 'ë'],\n 'i': ['î', 'ï'],\n 'u': ['ù', 'ü', 'û'],\n 'o': ['ô', 'ö'],\n 'c': ['ç']\n }\n for lettre in data:#inspecte chaque lettre de la phrase data\n for cle,defi in accents.items():#navigue a travers les clé\n for valeur in defi:#permet de tester TOUTE les definition d'une clé\n if lettre==valeur:#Test\n lettre=cle#Si test ok, alors prend la valeur de la clé(a,e,i,o,u ou c)\n data2=data2+lettre#recréer la phrase de départ sans la ponctuation\n #print(data2)\n return data2\n#print(noaccent(phrase))#simplement pour tester","sub_path":"noaccent.py","file_name":"noaccent.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"505860992","text":"\"\"\"Routines to render a metamodel.\n\n\"\"\"\n\nimport textx\nimport arpeggio\nimport markdown\nfrom .render_utils import print_obj, get_match_examples, doc_from_class, render_regex, as_regex, SPECIAL_REGEXES, str_sequence_doc, render_arpeggio_sequence, CHARS_AS_READABLE\nfrom .render_arpeggio import render_arpeggio_sequence_as_str\n\n\nclass ParsingSequence:\n\n def __init__(self, peg_rule):\n self.sequence = render_arpeggio_sequence(peg_rule)\n self.sequence_repr = tuple(render_arpeggio_sequence_as_str(peg_rule))\n\n def as_markdown(self):\n \"\"\"Yield mkd lines describing self sequence tuple representing the grammar\"\"\"\n yield ''\n yield '

' + markdown.markdown(' '.join(self.sequence_repr)) + '

'\n yield ''\n to_add = []\n for item in self.sequence:\n type_line, *sublines = ParsingSequence.item_repr(item)\n if type_line:\n # print('LINER:', type_line, f'\\t({len(sublines)} sublines)')\n yield '- Type ' + type_line\n for line in sublines:\n head = ' ' if line.startswith(' ') else ' - '\n yield head + line\n\n @staticmethod\n def item_repr(item) -> [str]:\n while len(item) == 1: item, = item\n if not item:\n pass # nothing to do\n elif item[0] == 'regex':\n yield f'anything matching regex {render_regex(item[1])}'\n elif item[0] == 'special regex':\n yield f'anything matching standard regex {item[1].upper()}'\n elif len(item) == 3 and item[0] in {'0..*', '1..*'}:\n _, objname, sep = item\n sep = CHARS_AS_READABLE.get(sep, \"\\'\" + str(sep) + \"\\'\")\n if item[0] == '0..*':\n yield f'zero or any number of [{objname}](#{objname.lower()}) separated by {sep}'\n else:\n yield f'at least one [{objname}](#{objname.lower()}) separated by {sep}'\n elif len(item) == 2 and item[0] == '0..1':\n _, sub = item\n while len(sub) == 1: sub, = sub\n first, *lasts = ParsingSequence.item_repr(sub)\n yield f'optionally ' + first\n yield from lasts\n elif len(item) == 2 and item[0] is str:\n yield f'the string `{item[1]}`'\n elif item[0] == 'choice':\n # In order to avoid a sublist, the following machinery avoid having\n # a sublist when there is few elements, all described by a single line.\n assert len(item) == 2\n lines = []\n inline = len(item[1]) < 4 # if True, push the content in a single line\n # NOTE: be based on the final length instead of the number of item would be more robust.\n for sub in item[1]:\n first, *nexts = ParsingSequence.item_repr(sub)\n lines.append(first)\n for next_ in nexts:\n lines.append(' - ' + next_)\n inline = False # we can't put it into a single line\n if inline:\n yield 'either ' + ' or '.join(lines)\n else: # multiple lines\n yield 'one of the following:'\n yield from lines\n elif isinstance(item, tuple): # this is a composed object\n yield 'in this order:'\n for sub in item:\n yield from ParsingSequence.item_repr(sub)\n else: # Unexpected object\n print('WOOT:', item)\n yield item\n\n\nclass DocSection:\n \"\"\"\n\n TODO:\n - tooltips on class names and abstract rules: https://www.w3schools.com/howto/howto_css_tooltip.asp\n\n \"\"\"\n\n def __init__(self, name:str, names_in_parents:set=set(), raw_doc:str='', sequence:tuple=()):\n self.name = str(name)\n self.names_in_parents = frozenset(names_in_parents)\n self.raw_doc = str(raw_doc or '')\n self.sequence = ParsingSequence(sequence) if sequence else None\n\n def as_markdown(self):\n yield '# ' + self.name\n if self.raw_doc:\n yield self.raw_doc\n if self.sequence:\n yield ''\n yield from self.sequence.as_markdown()\n\n def as_html(self) -> str:\n return markdown.markdown('\\n'.join(self.as_markdown()))\n\n @staticmethod\n def from_textx_class(textx_class) -> (str, object):\n \"\"\"Build and return an instance from given textx class\"\"\"\n cls, kwargs = DocSection, {'names_in_parents': set(), 'raw_doc': doc_from_class(textx_class)}\n if hasattr(textx_class, '__name__'):\n kwargs['name'] = textx_class.__name__\n # print_obj(textx_class)\n assert hasattr(textx_class, '__name__'), textx_class\n if not hasattr(textx_class, '_tx_attrs'):\n return\n regex = as_regex(textx_class)\n if regex:\n cls = DocRegexSection\n kwargs['regex'] = regex\n elif textx_class.__name__ in SPECIAL_REGEXES:\n return textx_class.__name__ # don't need more, since these are autogenerated in another way\n elif isinstance(textx_class, textx.metamodel.MetaAttr): # it's a ?=, += or *=\n cls = DocSelectionSection\n kwargs['selection'], kwargs['target'] = textx_class.mult, textx_class.cls\n elif not textx_class._tx_attrs and textx_class._tx_inh_by: # it's a raw choice\n cls = DocChoiceSection\n kwargs['choice'] = tuple(textx_class._tx_inh_by)\n else: # it's a \"regular\" rule\n kwargs['sequence'] = textx_class._tx_peg_rule\n return cls(**kwargs)\n\n\nclass DocChoiceSection(DocSection):\n def __init__(self, choices:tuple, **kwargs):\n self.choices = tuple(choices)\n super().__init__(**kwargs)\n\n def as_markdown(self):\n yield from super().as_markdown()\n yield ''\n for choice in self.choices:\n yield '- ' + str(choice)\n\nclass DocSelectionSection(DocSection):\n def __init__(self, selection:str, target:object, **kwargs):\n self.target = str(target)\n self.selection = str(selection)\n super().__init__(**kwargs)\n\n def as_markdown(self):\n yield from super().as_markdown()\n yield ''\n print('SELECTION:', self.target)\n if self.selection == '0..1':\n yield 'Optionally, type a ' + str(self.target)\n elif self.selection == '1..*':\n yield 'Type at least one ' + str(self.target)\n elif self.selection == '0..*':\n yield 'Type zero or any number of ' + str(self.target)\n\nclass DocRegexSection(DocSection):\n def __init__(self, regex:str, **kwargs):\n self.regex = str(regex)\n super().__init__(**kwargs)\n\n def as_markdown(self):\n yield from super().as_markdown()\n examples = get_match_examples(self.regex, amount=4)\n render = render_regex(self.regex, get_match_examples(self.regex, amount=0))\n yield f'{self.name.title()} is a *regex rule*, detecting anything matched by {render}, such as:'\n yield ''\n for example in examples:\n yield f'-
{example}
'\n yield ''\n\n\nif __name__ == '__main__':\n classes = [METAMODEL.rootcls] + list(METAMODEL.user_classes.values())\n print('CLASSES:', classes)\n with open('out.html', 'w') as fd:\n for cls in classes:\n out = DocSection.from_textx_class(cls)\n if out:\n fd.write(out.as_html())\n fd.write('

\\n')\n","sub_path":"textx_dsldoc/render_metamodel.py","file_name":"render_metamodel.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"235620647","text":"# -*- coding: utf-8 -*-\nimport re\nimport nltk\nimport sys\nsub = 'Simple Approaches to Tokenization'\nprint('\\n' + sub + '='*(80 - len(sub)))\nraw = \"\"\"'When I'M a Duchess,' she said to herself, (not in a very hopeful tone\nthough), 'I won't have any pepper in my kitchen AT ALL. Soup does very\nwell without--Maybe it's always pepper that makes people hot-tempered,'...\"\"\"\nprint(re.split(r' ', raw))\nprint(re.split(r'[ \\t\\n]+', raw))\nprint(re.split(r'\\s+', raw))\nprint(re.split(r'\\W+', raw))\nprint(re.findall(r'\\w+|\\S\\w*', raw))\nprint(re.findall(r\"\\w+(?:[-']\\w+)*|'|[-.(]+|\\S\\w*\", raw))\n\nsub = 'NLTK\\'s Regular Expression Tokenizer'\nprint('\\n' + sub + '='*(80 - len(sub)))\ntext = 'That U.S.A. poster-print costs $12.40...'\npattern = r'''(?x)\n ([A-Z]\\.)+\n| \\w+(-\\w+)*\n| \\$?\\d+(\\.\\d+)?%?\n| \\.\\.\\.\n| [][.,;\"'?():-_`]\n'''\n#tokens = nltk.regexp_tokenize(text, pattern)\ntokens = re.findall(pattern, text)\nprint(tokens)","sub_path":"References/nltk/III.7.RegExp4TokenizingText.py","file_name":"III.7.RegExp4TokenizingText.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"492987824","text":"from __future__ import absolute_import # For 'redis'\n\nimport redis\n\nfrom ..job import Job\nfrom .. import app_settings\n\nclass RedisBackend(object):\n def __init__(self):\n self.client = redis.Redis(\n host=app_settings.REDIS_HOST,\n port=app_settings.REDIS_PORT,\n )\n\n def enqueue(self, job, queue):\n self.client.rpush(self._key(queue), job.to_json())\n\n def dequeue(self, queue, timeout):\n try:\n _, data = self.client.blpop(self._key(queue), timeout)\n\n return Job.from_json(data)\n except TypeError:\n pass\n\n def _key(self, queue):\n if app_settings.REDIS_PREFIX:\n return '%s:django_lightweight_queue:%s' % (\n app_settings.REDIS_PREFIX,\n queue,\n )\n\n return 'django_lightweight_queue:%s' % queue\n","sub_path":"django_lightweight_queue/backends/redis.py","file_name":"redis.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"244101632","text":"#!/usr/bin/env python3\nimport os\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom multiprocessing import Pool\n\nBD = \"/raid/triples/\"\nBDSEG = \"/raid/triplesseg/\"\n\ndef transform(im):\n im = im.crop((0, 308, 5784, 308+592))\n # (5784/1248) = 4.63461538462\n im = im.resize((1248, 128))\n return im\n\n\ndef get_seg_frames(fn):\n im = Image.open(BDSEG+fn)\n im = transform(im)\n print(fn)\n im.save(\"segs/\"+fn)\n\ndef get_frames(fn):\n im = Image.open(BD+fn)\n im = transform(im)\n print(fn)\n im.save(\"imgs/\"+fn)\n\ntici_f_focal_length = 2648.0\n\nif __name__ == \"__main__\":\n segs = sorted(os.listdir(BD))\n p = Pool(64)\n\n \"\"\"\n arr = [\"comma3 %s\" % fn.split(\".\")[0] for fn in segs]\n with open(\"train.txt\", \"w\") as f:\n f.write('\\n'.join(arr))\n\n fl = tici_f_focal_length / 4.63461538462\n dx = (1928/2) / 4.63461538462\n dy = ((1208/2)-400) / 4.63461538462\n istr = \"%f,0.0,%f,0.0,%f,%f,0.0,0.0,1.0\" % (fl, dx, fl, dy)\n print(istr)\n\n for s in segs:\n with open(\"/raid/depth/comma3/\"+s.replace(\".png\", \"_cam.txt\"), \"w\") as f:\n f.write(istr)\n \"\"\"\n\n for x in tqdm(p.imap_unordered(get_seg_frames, segs)):\n pass\n\n #for x in tqdm(p.imap_unordered(get_frames, segs)):\n # pass\n","sub_path":"make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"85661361","text":"import os\nimport runpy\nfrom pathlib import Path\n\nimport pytest\nfrom qtpy import API_NAME\n\nimport napari\nfrom napari._qt.qt_main_window import Window\nfrom napari.utils.notifications import notification_manager\n\n# not testing these examples\nskip = [\n 'surface_timeseries.py', # needs nilearn\n '3d_kymograph.py', # needs tqdm\n 'live_tiffs.py', # requires files\n 'tiled-rendering-2d.py', # too slow\n 'live_tiffs_generator.py',\n 'points-over-time.py', # too resource hungry\n 'embed_ipython.py', # fails without monkeypatch\n 'custom_key_bindings.py', # breaks EXPECTED_NUMBER_OF_VIEWER_METHODS later\n 'new_theme.py', # testing theme is extremely slow on CI\n 'dynamic-projections-dask.py', # extremely slow / does not finish\n]\n\n\nif os.environ.get('MIN_REQ', '') == '1':\n skip.extend(['spheres.py', 'clipping_planes_interactive.py'])\n\nEXAMPLE_DIR = Path(napari.__file__).parent.parent / 'examples'\n# using f.name here and re-joining at `run_path()` for test key presentation\n# (works even if the examples list is empty, as opposed to using an ids lambda)\nexamples = [f.name for f in EXAMPLE_DIR.glob(\"*.py\") if f.name not in skip]\n\n# still some CI segfaults, but only on windows with pyqt5\nif os.getenv(\"CI\") and os.name == 'nt' and API_NAME == 'PyQt5':\n examples = []\n\nif os.getenv(\"CI\") and os.name == 'nt' and 'to_screenshot.py' in examples:\n examples.remove('to_screenshot.py')\n\n\n@pytest.mark.filterwarnings(\"ignore\")\n@pytest.mark.skipif(not examples, reason=\"No examples were found.\")\n@pytest.mark.parametrize(\"fname\", examples)\ndef test_examples(fname, monkeypatch):\n \"\"\"Test that all of our examples are still working without warnings.\"\"\"\n\n # hide viewer window\n monkeypatch.setattr(Window, 'show', lambda *a: None)\n # prevent running the event loop\n monkeypatch.setattr(napari, 'run', lambda *a, **k: None)\n\n # make sure our sys.excepthook override doesn't hide errors\n def raise_errors(etype, value, tb):\n raise value\n\n monkeypatch.setattr(notification_manager, 'receive_error', raise_errors)\n\n # run the example!\n try:\n runpy.run_path(str(EXAMPLE_DIR / fname))\n except SystemExit as e:\n # we use sys.exit(0) to gracefully exit from examples\n if e.code != 0:\n raise\n finally:\n napari.Viewer.close_all()\n","sub_path":"napari/_tests/test_examples.py","file_name":"test_examples.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"360391940","text":"from tkinter import *\nimport pandas\nfrom random import choice\n\nBACKGROUND_COLOR = \"#B1DDC6\"\ncurrent_card = {}\nto_learn = {}\ntry:\n data = pandas.read_csv(\"data/words_to_learn.csv\")\nexcept FileNotFoundError:\n original_data = pandas.read_csv(\"data/french_words.csv\")\n to_learn = original_data.to_dict(orient=\"records\")\nelse:\n to_learn = data.to_dict(orient=\"records\")\n\n\ndef next_card():\n global current_card, flip_timer\n window.after_cancel(flip_timer)\n current_card = choice(to_learn)\n canvas.itemconfig(canvas_image, image=card_front_img)\n canvas.itemconfig(title_text, text=\"French\", fill=\"black\")\n canvas.itemconfig(word, text=f\"{current_card['French']}\", fill=\"black\")\n flip_timer = window.after(3000, flip_card)\n\n\ndef flip_card():\n canvas.itemconfig(canvas_image, image=card_back_img)\n canvas.itemconfig(title_text, fill=\"white\", text=\"English\")\n canvas.itemconfig(word, fill=\"white\", text=f\"{current_card['English']}\")\n\n\ndef is_know():\n to_learn.remove(current_card)\n data_file = pandas.DataFrame(to_learn)\n data_file.to_csv(\"data/words_to_learn.csv\", index=False)\n next_card()\n\n\nwindow = Tk()\nwindow.title(\"Flashy\")\nwindow.config(padx=50, pady=50, bg=BACKGROUND_COLOR)\nflip_timer = window.after(3000, next_card)\n\ncanvas = Canvas(width=800, height=526, bg=BACKGROUND_COLOR, highlightthickness=0)\ncard_front_img = PhotoImage(file=\"images/card_front.png\")\ncard_back_img = PhotoImage(file=\"images/card_back.png\")\ncanvas_image = canvas.create_image(400, 263, image=card_front_img)\ntitle_text = canvas.create_text(400, 150, text=\"\", font=(\"Ariel\", 40, \"italic\"))\nword = canvas.create_text(400, 263, text=\"\", font=(\"Ariel\", 60, \"bold\"))\ncanvas.grid(column=0, row=0, columnspan=2)\n\nwrong_img = PhotoImage(file=\"images/wrong.png\")\nwrong_button = Button(image=wrong_img, highlightthickness=0, command=next_card)\nwrong_button.grid(column=0, row=1)\nright_img = PhotoImage(file=\"images/right.png\")\nright_button = Button(image=right_img, highlightthickness=0, command=is_know)\nright_button.grid(column=1, row=1)\nnext_card()\n\nwindow.mainloop()\n","sub_path":"Day_31/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"213641823","text":"# Copyright (c) 2018 Santosh Philip\n# =======================================================================\n# Distributed under the MIT License.\n# (See accompanying file LICENSE or copy at\n# http://opensource.org/licenses/MIT)\n# =======================================================================\n\n\"\"\"py.test for idf_helpers.easyopen\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport os\nimport pytest\n\nfrom eppy import modeleditor\nimport eppy.easyopen as easyopen\nfrom eppy.pytest_helpers import do_integration_tests\nimport eppy.runner.run_functions as run_functions\n\nfrom six import StringIO\nfrom six.moves import reload_module as reload\n\ndef latestidd():\n \"\"\"extract the latest idd installed\"\"\"\n pth, _ = run_functions.install_paths(version='8.8.0') # works with any value in version\n dirpth = os.path.dirname(pth)\n dirpth = os.path.dirname(dirpth)\n alldirs = os.listdir(dirpth)\n eplusdirs = [dir for dir in alldirs if dir.startswith('EnergyPlus')]\n maxapp = max(eplusdirs)\n ver = folder2ver(maxapp)\n return ver\n \ndef folder2ver(folder):\n \"\"\"get the version number from the E+ install folder\"\"\"\n ver = folder.split('EnergyPlus')[-1]\n ver = ver[1:]\n splitapp = ver.split('-')\n ver = '.'.join(splitapp)\n return ver\n \ndef test_folder2ver():\n \"\"\"py.test for folder2ver\"\"\"\n data = (\n ('EnergyPlus-8-8-0', '8.8.0'), # folder, expected\n ('EnergyPlusV8-8-0', '8.8.0'), # folder, expected\n ) \n for folder, expected in data:\n result = folder2ver(folder) \n assert result == expected\n \ndef test_cleanupversion():\n \"\"\"py.test for cleanupversion\"\"\"\n data = (\n ('8.8.0', '8.8.0'), # ver, expected\n ('8.8.1', '8.8.0'), # ver, expected\n ('8.8', '8.8.0'), # ver, expected\n ('8', '8.0.0'), # ver, expected\n ('', '.0.0'), # ver, expected\n ) \n for ver, expected in data:\n result = easyopen.cleanupversion(ver)\n assert result == expected\n \n\n@pytest.mark.skipif(\n not do_integration_tests(), reason=\"$EPPY_INTEGRATION env var not set\")\ndef test_easyopen():\n \"\"\"py.test for easyopen\"\"\"\n ver = latestidd()\n txt, result = (\" Version,{};\".format(ver), '{}'.format(ver))\n fhandle = StringIO(txt)\n reload(modeleditor)\n reload(easyopen)\n idf = easyopen.easyopen(fhandle)\n versions = idf.idfobjects['version'.upper()]\n version = versions[0]\n ver = version.Version_Identifier\n assert result == ver\n # test with epw=weatherfile\n fhandle = StringIO(txt)\n epwname = 'weatherfile.epw'\n idf = easyopen.easyopen(fhandle, epw=epwname)\n assert idf.epw == epwname\n\n@pytest.mark.skipif(\n not do_integration_tests(), reason=\"$EPPY_INTEGRATION env var not set\")\ndef test_easyopen_withidd():\n \"\"\"py.test for easyopen\"\"\"\n ver = latestidd()\n iddfile = easyopen.getiddfile(ver)\n txt, result = (\" Version,{};\".format(ver), '{}'.format(ver))\n fhandle = StringIO(txt)\n reload(modeleditor)\n reload(easyopen)\n idf = easyopen.easyopen(fhandle, idd=iddfile)\n versions = idf.idfobjects['version'.upper()]\n version = versions[0]\n ver = version.Version_Identifier\n assert result == ver\n # test with epw=weatherfile\n fhandle = StringIO(txt)\n epwname = 'weatherfile.epw'\n idf = easyopen.easyopen(fhandle, idd=iddfile, epw=epwname)\n assert idf.epw == epwname\n ","sub_path":"eppy/tests/test_easyopen.py","file_name":"test_easyopen.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"354581661","text":"import asyncio\n\nfrom asynctest import TestCase\n\nfrom asyncworker import App, RouteTypes\nfrom asyncworker.connections import AMQPConnection\n\nconsume_callback_shoud_not_be_called = False\nhandler_with_requeue_called = 0\nhandler_without_requeue_called = 0\nsuccessful_message_value_is_equal = False\n\n\nclass RabbitMQConsumerTest(TestCase):\n async def setUp(self):\n self.queue_name = \"test\"\n self.connection = AMQPConnection(\n hostname=\"127.0.0.1\", username=\"guest\", password=\"guest\", prefetch=1\n )\n self.app = App(connections=[self.connection])\n\n async def tearDown(self):\n await self.app.connections.with_type(RouteTypes.AMQP_RABBITMQ)[0][\n \"/\"\n ].connection.channel.queue_delete(self.queue_name)\n handler_without_requeue_called = 0\n handler_with_requeue_called = 0\n\n async def test_process_one_successful_message(self):\n \"\"\"\n Um worker com dois handlers um que publica e outro que lê a mensagem\n No final um ack() é chamado\n \"\"\"\n message = {\"key\": \"value\"}\n\n @self.app.route([self.queue_name], type=RouteTypes.AMQP_RABBITMQ)\n async def handler(messages):\n global successful_message_value_is_equal\n successful_message_value_is_equal = (\n messages[0].body[\"key\"] == message[\"key\"]\n )\n\n await self.app.startup()\n queue = self.connection[\"/\"]\n await queue.connection._connect()\n await queue.connection.channel.queue_declare(self.queue_name)\n\n await queue.put(routing_key=self.queue_name, data=message)\n await asyncio.sleep(1)\n self.assertTrue(successful_message_value_is_equal)\n await self.app.shutdown()\n\n async def test_process_message_reject_with_requeue(self):\n \"\"\"\n Causamos um erro no handler para que a mensagem seja rejeitada e\n recolocada na fila.\n O handler confirmará a mensagem na segunda tentativa (`msg.ack()`)\n \"\"\"\n\n @self.app.route([self.queue_name], type=RouteTypes.AMQP_RABBITMQ)\n async def other_handler(messages):\n global handler_with_requeue_called\n if handler_with_requeue_called > 0:\n messages[0].accept()\n else:\n handler_with_requeue_called += 1\n value = messages[0].field # AttributeError\n\n await self.app.startup()\n queue = self.connection[\"/\"]\n await queue.connection._connect()\n await queue.connection.channel.queue_declare(self.queue_name)\n\n await queue.put(\n routing_key=self.queue_name,\n data={\"key\": \"handler_with_requeue_then_ack\"},\n )\n await asyncio.sleep(2)\n self.assertEqual(1, handler_with_requeue_called)\n await self.app.shutdown()\n\n async def test_process_message_reject_without_requeue(self):\n \"\"\"\n Adicionamos um handler que causa uma falha mas que joga a mensagem fora.\n Temos que conferir que o handler foi chamado\n \"\"\"\n\n @self.app.route([self.queue_name], type=RouteTypes.AMQP_RABBITMQ)\n async def other_handler(messages):\n global handler_without_requeue_called\n handler_without_requeue_called += 1\n messages[0].reject(requeue=False)\n value = messages[0].field # AttributeError\n\n await self.app.startup()\n queue = self.connection[\"/\"]\n await queue.connection._connect()\n await queue.connection.channel.queue_declare(self.queue_name)\n\n await queue.put(\n routing_key=self.queue_name, data={\"key\": \"handler_without_requeue\"}\n )\n await asyncio.sleep(2)\n self.assertEqual(1, handler_without_requeue_called)\n\n await self.app.shutdown()\n await queue.connection.close()\n\n async def callback(*args, **kwargs):\n global consume_callback_shoud_not_be_called\n consume_callback_shoud_not_be_called = True\n\n queue = self.connection[\"/\"]\n await queue.connection._connect()\n await queue.connection.channel.basic_consume(\n callback, queue_name=self.queue_name\n )\n await asyncio.sleep(5)\n self.assertFalse(consume_callback_shoud_not_be_called)\n","sub_path":"itests/test_rabbitmq_consumer.py","file_name":"test_rabbitmq_consumer.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"207754848","text":"import sys\r\nfrom core import create_file, create_folder, get_list, delete_file, copy_file, save_info\r\n\r\nsave_info('Старт')\r\n\r\ncommand = sys.argv[1]\r\n\r\nif command == 'list':\r\n get_list()\r\nelif command == 'create_file':\r\n try:\r\n name = sys.argv[2]\r\n except IndexError:\r\n print('Отсутствует название файла')\r\n else:\r\n create_file(name)\r\nelif command == 'create_folder':\r\n try:\r\n name = sys.argv[2]\r\n except IndexError:\r\n print('Отсутствует название папки')\r\n else:\r\n create_folder(name)\r\nelif command == 'delete':\r\n try:\r\n name = sys.argv[2]\r\n except IndexError:\r\n print('Отсутствует название удаляемого объекта')\r\n else:\r\n delete_file(name)\r\nelif command == 'copy':\r\n name = sys.argv[2]\r\n new_name = sys.argv[3]\r\n copy_file(name, new_name)\r\nelif command == 'help':\r\n print('list - список файлов и папок')\r\n print('create_file - создание файла')\r\n print('create_folder - создание файла')\r\n print('delete - удаление файла или папки')\r\n print('copy - копирование файла или папки')\r\n\r\nsave_info('Конец')\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"130058295","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport datetime\nimport os.path\nfrom collections import OrderedDict\n\nfrom django.db import models\nfrom django.contrib.sites.models import Site\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.timezone import now\n\nfrom events.utils import slugify\n\n\n# In which grade does a high school student graduate?\nGRADUATION_GRADE = 4\n\n\n@python_2_unicode_compatible\nclass School(models.Model):\n abbreviation = models.CharField(max_length=100,\n blank=True,\n verbose_name=\"skratka\",\n help_text=\"Sktatka názvu školy.\")\n verbose_name = models.CharField(max_length=100,\n verbose_name=\"celý názov\")\n addr_name = models.CharField(max_length=100, blank=True)\n street = models.CharField(max_length=100, blank=True)\n city = models.CharField(max_length=100, blank=True)\n zip_code = models.CharField(max_length=10, blank=True)\n\n class Meta:\n verbose_name = \"škola\"\n verbose_name_plural = \"školy\"\n ordering = (\"city\", \"street\", \"verbose_name\")\n\n def __str__(self):\n result = \"\"\n if self.abbreviation:\n result += self.abbreviation + \", \"\n result += self.verbose_name\n if self.street:\n result += \", \" + self.street\n if self.city or self.zip_code:\n result += \", \"\n if self.zip_code:\n result += self.zip_code\n if self.city:\n result += \" \" + self.city\n return result\n\n\n@python_2_unicode_compatible\nclass AdditionalUserDetails(models.Model):\n user = models.OneToOneField('auth.User',\n related_name='additional_events_details')\n school = models.ForeignKey(School, default=1, verbose_name=\"škola\",\n help_text='Do políčka napíšte skratku, '\n 'časť názvu alebo adresy školy a následne '\n 'vyberte správnu možnosť zo zoznamu. '\n 'Pokiaľ vaša škola nie je '\n 'v zozname, vyberte \"Gymnázium iné\" '\n 'a pošlite nám e-mail.')\n is_teacher = models.BooleanField(verbose_name=\"som učiteľ\",\n help_text='Učitelia vedia hromadne '\n 'prihlasovať školy na akcie.')\n graduation = models.IntegerField(blank=True, null=True,\n verbose_name=\"rok maturity\",\n help_text=\"Povinné pre žiakov.\")\n want_news = models.BooleanField(verbose_name=\"pozvánky e-mailom\",\n help_text=\"Mám záujem dostávať \"\n \"e-mailom pozvánky na ďalšie akcie.\")\n\n class Meta:\n verbose_name = \"dodatočné údaje o užívateľoch\"\n verbose_name_plural = \"dodatočné údaje o užívateľoch\"\n\n def __str__(self):\n return \"%s\" % (self.user,)\n\n def get_grade(self, date=None):\n \"\"\"\n Returns the school grade based on graduation_year and the provided\n date. If no date is provided, today is used.\n \"\"\"\n if self.graduation is None:\n return None\n if date is None:\n date = datetime.date.today()\n # Normalize the given date's year to the one in which the closest\n # following graduation happens.\n # For simplicity, we assume graduation happens every year on the\n # first day of July.\n if date.month >= 7:\n date = date.replace(year=date.year + 1)\n years_to_graduation = self.graduation - date.year\n return GRADUATION_GRADE - years_to_graduation\n\n\ndef choose_invitation_filename(instance, original):\n return \"%s/invitation-%s.pdf\" % (instance.date.isoformat(),\n slugify(unicode(instance))[:74])\n\n\n@python_2_unicode_compatible\nclass Event(models.Model):\n name = models.CharField(max_length=100,\n help_text=\"Názov akcie, napr. Klub Trojstenu \"\n \"po Náboji FKS\")\n date = models.DateField(unique=True)\n deadline = models.DateTimeField(help_text=\"Deadline na prihlasovanie\")\n invitation = models.FileField(upload_to=choose_invitation_filename,\n blank=True,\n help_text=\"PDF s pozvánkou, keď bude \"\n \"hotová.\")\n sites = models.ManyToManyField(Site)\n poll_begin = models.DateTimeField(blank=True, null=True,\n help_text=\"Spustenie ankety\")\n poll_end = models.DateTimeField(blank=True, null=True,\n help_text=\"Ukončenie ankety\")\n poll = models.ForeignKey('polls.Poll', blank=True, null=True,\n related_name=\"events\",\n help_text=\"Anketa\")\n\n class Meta:\n verbose_name = \"akcia\"\n verbose_name_plural = \"akcie\"\n ordering = (\"-date\",)\n\n def __str__(self):\n return \"%s %s\" % (self.name, self.date.year)\n\n @models.permalink\n def get_absolute_url(self):\n # We need to check if the event is the latest for this page and we\n # don't have access to the request to just call get_latest_event.\n if Event.objects.filter(sites__id__in=self.sites.all(),\n date__gt=self.date).count() > 0:\n # There are newer relevant events, generate a general URL.\n return (\"event_detail\", (), {\n 'year': self.date.strftime('%Y'),\n 'month': self.date.strftime('%m'),\n 'day': self.date.strftime('%d'),\n })\n # Else just return the link to the latest event.\n return (\"event_latest\",)\n\n @models.permalink\n def get_attendance_url(self):\n return (\"event_attendance\", (), {\n 'year': self.date.strftime('%Y'),\n 'month': self.date.strftime('%m'),\n 'day': self.date.strftime('%d'),\n })\n\n @models.permalink\n def get_poll_url(self):\n return (\"event_poll\", (), {\n 'year': self.date.strftime('%Y'),\n 'month': self.date.strftime('%m'),\n 'day': self.date.strftime('%d'),\n })\n\n @models.permalink\n def get_poll_results_url(self):\n return (\"event_poll_results\", (), {\n 'year': self.date.strftime('%Y'),\n 'month': self.date.strftime('%m'),\n 'day': self.date.strftime('%d'),\n })\n\n def get_grouped_lectures(self):\n \"\"\"\n Returns the lectures for this event in an OrderedDict mapping\n times to lists of lectures sorted by their rooms.\n \"\"\"\n try:\n return self._grouped_lectures_cache\n except AttributeError:\n result = OrderedDict()\n for lecture in self.lectures.order_by(\"time\", \"room\"):\n result.setdefault(lecture.time, []).append(lecture)\n self._grouped_lectures_cache = result\n return result\n\n def is_in_future(self):\n return now().date() <= self.date\n\n def signup_period_open(self):\n return now() < self.deadline\n\n def poll_is_active(self):\n now_ = now()\n return (self.poll and self.poll_begin and\n self.poll_begin <= now_ and\n (not self.poll_end or self.poll_end >= now_))\n\n\ndef choose_lecture_materials_filename(instance, original):\n extension = os.path.splitext(original)[1]\n lecture_slug = slugify(unicode(instance))[:74]\n return \"%s/%s%s\" % (instance.event.date.isoformat(),\n lecture_slug, extension)\n\n\n@python_2_unicode_compatible\nclass Lecture(models.Model):\n event = models.ForeignKey(Event, verbose_name=\"akcia\",\n related_name=\"lectures\")\n lecturer = models.CharField(max_length=100, blank=True,\n verbose_name=\"prednášajúci\")\n title = models.CharField(max_length=147, verbose_name=\"názov prednášky\")\n abstract = models.TextField(blank=True, verbose_name=\"abstrakt\")\n room = models.CharField(max_length=20, verbose_name=\"miestnosť\")\n time = models.TimeField(verbose_name=\"čas\")\n field = models.CharField(max_length=47, blank=True,\n verbose_name=\"odbor\")\n video_url = models.URLField(blank=True, verbose_name=\"URL videa\")\n materials = models.FileField(upload_to=choose_lecture_materials_filename,\n blank=True,\n verbose_name=\"materiály\",\n help_text=\"Materiály od prednášajúceho, \"\n \"napr. slidy v PDF alebo ZIP obsahujúci \"\n \"všetky obrázky a videá.\")\n poll = models.ForeignKey('polls.Poll', blank=True, null=True,\n related_name=\"lectures\",\n help_text=\"Anketa\")\n\n class Meta:\n verbose_name = \"bod programu (napr. prednáška)\"\n verbose_name_plural = \"body programu (napr. prednášky)\"\n ordering = (\"event\", \"time\")\n\n def __str__(self):\n return \"%s: %s\" % (self.lecturer, self.title)\n\n\ndef get_latest_event(request):\n \"\"\"\n Returns the latest event relevant for the current site.\n \"\"\"\n site = get_current_site(request)\n return Event.objects.filter(sites__id__exact=site.pk).order_by('-date')[0]\n\n\n@python_2_unicode_compatible\nclass IndividualSignup(models.Model):\n event = models.ForeignKey(Event, verbose_name=\"akcia\",\n related_name=\"individual_signups\")\n user = models.ForeignKey('auth.User')\n lunch = models.BooleanField(verbose_name=\"obed\",\n help_text=\"Mám záujem o obed po akcii\")\n\n class Meta:\n verbose_name = \"prihláška jednotlivca\"\n verbose_name_plural = \"prihlášky jednotlivcov\"\n\n def __str__(self):\n return \"%s, %s\" % (self.user, self.event)\n\n\nclass IndividualOvernightSignup(IndividualSignup):\n sleepover = models.BooleanField(verbose_name=\"chcem prespať\",\n help_text=\"Prespávanie bude v lodenici \"\n \"alebo v telocvični za poplatok, ktorý \"\n \"určí na mieste doc. Potočný. Viac v \"\n 'organizačných'\n \" pokynoch.\")\n sleeping_bag = models.BooleanField(verbose_name=\"spacák\",\n help_text=\"Mám záujem požičať si \"\n \"spacák. Spacákov je obmedzené \"\n \"množstvo, takže pokiaľ môžete, \"\n \"radšej si doneste vlastné.\")\n sleeping_pad = models.BooleanField(verbose_name=\"karimatka\",\n help_text=\"Mám záujem požičať si \"\n \"karimatku. Karimatiek je obmedzené \"\n \"množstvo, takže pokiaľ môžete, \"\n \"radšej si doneste vlastné.\")\n game_participation = models.BooleanField(verbose_name=\"zúčastním sa hry\",\n help_text=\"Pre viac detailov \"\n \"o tom, kedy sa bude konať \"\n \"hra, sledujte novinky.\")\n\n class Meta:\n verbose_name = \"prihláška jednotlivca s možnosťou prespať\"\n verbose_name_plural = \"prihlášky jednotlivcov s možnosťou prespať\"\n\n\nclass SchoolSignup(models.Model):\n event = models.ForeignKey(Event, verbose_name=\"akcia\",\n related_name=\"school_signups\")\n user = models.ForeignKey('auth.User')\n students1 = models.PositiveSmallIntegerField(default=0,\n verbose_name=\"počet prvákov\")\n students2 = models.PositiveSmallIntegerField(default=0,\n verbose_name=\"počet druhákov\")\n students3 = models.PositiveSmallIntegerField(default=0,\n verbose_name=\"počet tretiakov\")\n students4 = models.PositiveSmallIntegerField(default=0,\n verbose_name=\"počet štvrtákov\")\n lunches = models.PositiveSmallIntegerField(default=0,\n verbose_name=\"počet obedov\")\n\n class Meta:\n verbose_name = \"hromadná prihláška\"\n verbose_name_plural = \"hromadné prihlášky\"\n\n def get_total_students(self):\n return self.students1 + self.students2 + self.students3 + self.students4\n\n\ndef get_signup_model(request):\n \"\"\"\n Returns the signup model relevant to current site and the logged in\n user's settings.\n \"\"\"\n try:\n return request._akademia_events_signup_model\n except AttributeError:\n if get_current_site(request).domain == 'akademia.trojsten.sk':\n if request.user.additional_events_details.is_teacher:\n model = SchoolSignup\n else:\n model = IndividualSignup\n else:\n model = IndividualOvernightSignup\n request._akademia_events_signup_model = model\n return model\n","sub_path":"events/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"458524694","text":"from django.shortcuts import render_to_response, redirect\nfrom django.template.context import RequestContext\nfrom src.models import Programmer, Pair\n\ndef create_pair():\n programmers = list(Programmer.objects.all())\n while programmers:\n first_member = programmers.pop()\n for programmer in programmers:\n Pair(first_programmer=first_member, second_programmer=programmer, count=0).save()\n\n\ndef create_stair(request):\n if( request.method == 'POST' ):\n Programmer.objects.all().delete()\n programmer_names = request.POST['programmer_names'].split(',')\n for name in programmer_names:\n Programmer(name = name.strip()).save()\n if len(programmer_names) > 1:\n create_pair()\n return redirect(view_stair)\n return render_to_response('create_stair.html', RequestContext(request))\n\n\ndef view_stair(request):\n programmers = list(Programmer.objects.all())\n pairs = Pair.objects.all()\n return render_to_response('view_pair_stair.html',\n RequestContext(request,{'programmers_column':programmers[0:-1],\n 'programmers_row': programmers[1:],\n 'pairs': pairs}))\n\n\ndef increment_count(request, first_programmer_id, second_programmer_id):\n pair = Pair.objects.get(first_programmer=first_programmer_id,\n second_programmer=second_programmer_id)\n pair.count += 1\n pair.save()\n return view_stair(request)","sub_path":"src/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"116484049","text":"\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.http import HttpResponse\nfrom .models import User\nfrom asesorias.models import Asesoria, Curso, Seccion, FactTable, Cita\nfrom django.http import JsonResponse\nimport json\n# Create your views here.\n\n\n\n\ndef mostrarCursos(request):\n agregar = 1\n tipo = 0\n curso = Curso.objects.all().order_by('id')\n\n return render(request, 'agregarAsesoria.html', locals())\n\n\n\ndef listarAsesoria(request):\n tipo = 0\n agregar = 0\n factTable = FactTable.objects.all().order_by(\"id\")\n arreglo=[]\n\n for x in factTable:\n print(5)\n x_info = {}\n\n #CURSO\n curso= Curso.objects.filter(id=x.curso_id)\n for y in curso:\n x_info['curso'] = y.nombre\n\n #PROFESOR\n profesor=User.objects.filter(id=x.profesor_id)\n for y in profesor:\n x_info['profesor'] = y.first_name\n\n #ASESORIA\n asesoria=Asesoria.objects.filter(id=x.asesoria_id)\n for y in asesoria:\n x_info['id'] = y.id\n x_info['horario'] = y.horario\n x_info['dia'] = y.dia\n x_info['lugar'] = y.lugar\n\n #Seccion\n seccion=Seccion.objects.filter(id=x.seccion_id)\n for y in seccion:\n x_info['seccion'] = y.codigo\n\n arreglo.append(x_info)\n print(arreglo)\n\n return render(request, 'listarAsesoria.html', locals())\n\ndef eliminarAsesoria(request):\n tipo = 0\n agregar = 0\n id=request.POST.get('id_asesoria', False)\n asesoria=Asesoria.objects.filter(id=id)\n FactTable.objects.filter(asesoria=asesoria)\n asesoria.delete()\n return redirect('/listarAsesoria')\n\ndef editarAsesoria(request):\n id = int(request.GET.get('id'))\n tipo= 1\n agregar= 0\n listado = Asesoria.objects.all().order_by(\"id\")\n return render(request, 'listarAsesoria.html', locals())\n\ndef guardarCambios(request):\n tipo = 0\n agregar = 0\n id=request.POST.get('id_asesoria', False)\n curso=request.POST['curso']\n profesor=request.POST['profesor']\n horario=request.POST['horario']\n lugar=request.POST['lugar']\n dia=request.POST['dia']\n asesoria= Asesoria.objects.get(id=id)\n asesoria.curso = curso\n asesoria.profesor = profesor\n asesoria.horario = horario\n asesoria.lugar = lugar\n asesoria.dia=dia\n asesoria.save()\n return redirect('/listarAsesoria')\n\ndef guardarAsesoria(request):\n tipo = 0\n agregar = 0\n curso=request.POST['curso']\n sv=request.POST['seccion']\n profesor=request.POST['profesor']\n horario=request.POST['horario']\n seccion=request.POST['seccion']\n dia=request.POST['dia']\n lugar=request.POST['lugar']\n #buscarProfesor=User.objects.filter(first_name__iexact=busqueda)\n #buscarSeccion=Seccion.objects.filter(codigo__iexact=busqueda)\n #codigo = models.AutoField()\n #dia\n #horario\n #lugar\n #seccion\n \n objCurso= Curso.objects.get(nombre=curso)\n arrProf=profesor.split(\" \")\n objProf= User.objects.get(first_name=arrProf[0])\n objProf2= User.objects.get(last_name=arrProf[1])\n if objProf.id==objProf2.id:\n objSeccion=Seccion.objects.get(profesor=objProf.id,curso=objCurso.id,codigo=int(seccion))\n print(objCurso.id)\n print(profesor)\n print(objProf.id)\n print(objSeccion.id)\n print(lugar)\n\n asesoria = Asesoria.objects.create(dia=dia, horario=horario, lugar=lugar, seccion=objSeccion)\n\n asesoria.save()\n newAsesoria=asesoria\n print(newAsesoria)\n fact=FactTable.objects.create(curso=objCurso,profesor=objProf,asesoria=newAsesoria,seccion=objSeccion)\n fact.save()\n return redirect('/listarAsesoria')\n\ndef cancelar(request):\n tipo = 0\n agregar = 0\n return redirect('/listarAsesoria')\n\ndef salir(request):\n tipo = 0\n agregar = 0\n return render(request, 'registration/login.html')\n\ndef logout(request):\n request.session['id'] = ''\n return render(request, 'registration/login.html')\n","sub_path":"asesorias/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"559107260","text":"#!/usr/bin/env python\n\nimport sys\nimport argparse\nimport string\nimport time\nimport random\nimport numpy\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description=\"Preprocess training data\")\n\tparser.add_argument('--input_path', metavar='path', type=str, help='Input file path')\n\tparser.add_argument('--output_path', metavar='path', type=str, help='Output file path')\n\tparser.add_argument('--training_sample_size', metavar='int', type=int, help='Number of sample to retrieve from file')\n\tparser.add_argument('--starting_sample_location', metavar='int', type=int, help='From which sample to start with')\n\targs = parser.parse_args()\n\t\n\toutput_fh = open (args.output_path, 'w')\n\tsample_count = 1\n\tread_count = 1\n\ttemp_seq = ''\n\t# rewrites the training data into a format which the mapper takes in\n\twith open(args.input_path, 'r') as input_fh:\n\t\tinput_fh.readline() # read off initial title of dna seq.\n\t\twhile True:\n\t\t\tinput_str = input_fh.readline()\n\t\t\tif len(input_str) == 0: break\n\t\t\tinput_str = input_str.strip().upper()\n\n\t\t\tif '>' in input_str:\n\t\t\t\tif (sample_count >= args.starting_sample_location):\n\t\t\t\t\tif (read_count <= args.training_sample_size): #using two-thirds data for training\n\t\t\t\t\t\toutput_fh.write (temp_seq + '\\n')\n\t\t\t\t\tread_count += 1\n\t\t\t\tsample_count += 1\n\t\t\telse:\n\t\t\t\ttemp_seq = input_str\n\n","sub_path":"preprocess_classify.py","file_name":"preprocess_classify.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"645408585","text":"import cv2 as cv\nimport numpy as np\nimport tkinter as tk\nfrom PIL import ImageTk, Image\nimport os\nimport json\n\n\ndef add_images(img1, img2, size):\n alpha1 = img1[:, :, 3] / 255.0\n alpha2 = 1.0 - alpha1\n out = np.zeros((size, size, 4), np.uint8)\n for c in range(0, 4):\n out[:, :, c] = (alpha1 * img1[:, :, c] + alpha2 * img2[:, :, c])\n return out\n\n\ndef do_save(img, token, circleMeta, out_path):\n print(f\"Saving Token '{out_path}'...\", end=\" \")\n try:\n bg = token[\"bg\"]\n except KeyError:\n bg = None\n img = img[\"cv\"]\n token = token[\"cv\"]\n\n # resize image (We assume token is a square image)\n out_size = token.shape[0] - token.shape[0] % 2\n r = out_size // 2\n img = cv.copyMakeBorder(img, r, r, r, r, cv.BORDER_CONSTANT, value=(0, 0, 0, 0))\n scale = out_size / (circleMeta[\"r\"] * 2)\n resized = cv.resize(img, (int(scale * img.shape[1]), int(scale * img.shape[0])), interpolation=cv.INTER_AREA)\n center = [int((circleMeta[\"y\"] + r) * scale), int((circleMeta[\"x\"] + r) * scale)]\n\n # crop images to size\n cropped_img = resized[center[0] - r:center[0] + r, center[1] - r:center[1] + r]\n cropped_token = token[out_size - 2 * r:out_size, out_size - 2 * r:out_size]\n\n # add the background\n if bg is not None:\n if type(bg) is tuple:\n background = np.zeros((out_size, out_size, 4), np.uint8)\n background[:] = (bg[2], bg[1], bg[0], 255)\n else:\n background = cv.imread(bg, -1)\n if background.shape[2] != 4:\n background = cv.cvtColor(background, cv.COLOR_RGB2RGBA)\n cropped_img = add_images(cropped_img, background, out_size)\n\n # mask original image\n mask = np.zeros((out_size, out_size), np.uint8)\n cv.circle(mask, (r, r), r - 10, (255, 255, 255), -1)\n masked = cv.bitwise_and(cropped_img, cropped_img, mask=mask)\n\n # add token border to image\n out = add_images(cropped_token, masked, out_size)\n\n cv.imwrite(out_path, out)\n print(\"Done.\", end=\"\\n\")\n\n\ndef save_meta(path, to_save, meta):\n try:\n obj = meta[path[0]]\n except KeyError:\n meta[path[0]] = dict()\n obj = meta[path[0]]\n try:\n obj = obj[path[1]]\n except KeyError:\n obj[path[1]] = dict()\n obj = obj[path[1]]\n obj[\"meta\"] = to_save\n with open(META, \"w\") as f:\n json.dump(meta, f, indent=2, separators=(',', ': '), )\n\n\ndef exit_ui(root):\n root.destroy()\n\n\ndef init_ui(img, tokens, out_path, meta):\n root = tk.Tk()\n root.title(img[\"url\"])\n root.focus_force()\n\n frame = tk.Frame(root, height=100, width=img[\"w\"])\n frame.pack()\n\n def onRadio():\n v = radio.get()\n for i in range(4):\n if i != v:\n try:\n canvas.delete(tokens[i][\"canvas\"])\n except KeyError:\n pass\n if circleMeta[\"r\"] != 0:\n t = Image.open(tokens[v][\"url\"]).resize((int(2 * circleMeta[\"r\"]), int(2 * circleMeta[\"r\"])),\n Image.ANTIALIAS)\n tokens[v][\"tk\"] = ImageTk.PhotoImage(t)\n tokens[v][\"canvas\"] = canvas.create_image(circleMeta[\"x\"], circleMeta[\"y\"], image=tokens[v][\"tk\"],\n anchor=\"c\")\n\n radio = tk.IntVar()\n tk.Radiobutton(frame, anchor=\"e\", variable=radio, value=0, text=\"1x1 Token\", command=onRadio).pack()\n tk.Radiobutton(frame, anchor=\"e\", variable=radio, value=1, text=\"2x2 Token\", command=onRadio).pack()\n tk.Radiobutton(frame, anchor=\"e\", variable=radio, value=2, text=\"3x3 Token\", command=onRadio).pack()\n tk.Radiobutton(frame, anchor=\"e\", variable=radio, value=3, text=\"4x4 Token\", command=onRadio).pack()\n radio.set(0)\n try:\n s = img[\"meta\"][\"size\"]\n radio.set(s - 1)\n except KeyError:\n pass\n\n label_text = \"\"\"Click+Drag to create and move token border.\n Right click to unset token border.\n Press \"S\" to save as token; \"W\" to exit.\"\"\"\n tk.Label(frame, text=label_text).pack()\n\n canvas = tk.Canvas(root, height=img[\"h\"], width=img[\"w\"])\n canvas.pack(fill=\"both\")\n img[\"tk\"] = ImageTk.PhotoImage(Image.open(img[\"url\"]))\n img[\"canvas\"] = canvas.create_image(0, 0, image=img[\"tk\"], anchor=\"nw\")\n circleMeta = {\"x\": 0, \"y\": 0, \"r\": 0, \"circle\": None, \"released\": False}\n\n def onClick(evt):\n circleMeta[\"released\"] = False\n circleMeta[\"x\"] = int(evt.x)\n circleMeta[\"y\"] = int(evt.y)\n circleMeta[\"r\"] = 10\n circleMeta[\"circle\"] = canvas.create_oval(circleMeta[\"x\"] - circleMeta[\"r\"], circleMeta[\"y\"] - circleMeta[\"r\"],\n circleMeta[\"x\"] + circleMeta[\"r\"], circleMeta[\"y\"] + circleMeta[\"r\"])\n\n def onDrag(evt):\n if not circleMeta[\"circle\"]:\n circleMeta[\"circle\"] = canvas.create_oval(circleMeta[\"x\"] - circleMeta[\"r\"],\n circleMeta[\"y\"] - circleMeta[\"r\"],\n circleMeta[\"x\"] + circleMeta[\"r\"],\n circleMeta[\"y\"] + circleMeta[\"r\"])\n if not circleMeta[\"released\"]:\n circleMeta[\"r\"] = int(\n np.linalg.norm(np.array([circleMeta[\"x\"], circleMeta[\"y\"]]) - np.array([evt.x, evt.y])))\n else:\n circleMeta[\"x\"] = int(evt.x)\n circleMeta[\"y\"] = int(evt.y)\n\n canvas.coords(circleMeta[\"circle\"], circleMeta[\"x\"] - circleMeta[\"r\"], circleMeta[\"y\"] - circleMeta[\"r\"],\n circleMeta[\"x\"] + circleMeta[\"r\"], circleMeta[\"y\"] + circleMeta[\"r\"])\n\n def onRelease(evt):\n if circleMeta[\"circle\"]:\n canvas.delete(circleMeta[\"circle\"])\n circleMeta[\"circle\"] = None\n circleMeta[\"released\"] = True\n canvas.unbind(\"\")\n t = Image.open(tokens[radio.get()][\"url\"]).resize((int(2 * circleMeta[\"r\"]), int(2 * circleMeta[\"r\"])),\n Image.ANTIALIAS)\n tokens[radio.get()][\"tk\"] = ImageTk.PhotoImage(t)\n tokens[radio.get()][\"canvas\"] = canvas.create_image(circleMeta[\"x\"], circleMeta[\"y\"],\n image=tokens[radio.get()][\"tk\"], anchor=\"c\")\n\n def onRightClick(evt):\n if circleMeta[\"circle\"]:\n canvas.delete(circleMeta[\"circle\"])\n circleMeta[\"circle\"] = None\n try:\n canvas.delete(tokens[radio.get()][\"canvas\"])\n except KeyError:\n pass\n canvas.unbind(\"\")\n canvas.bind(\"\", onClick)\n\n def onKey(evt):\n char = evt.char.lower()\n if char == \"s\":\n if circleMeta[\"r\"] == 0:\n raise Exception(\"You need to select an area first.\")\n else:\n path = [img[\"url\"].split(\"\\\\\")[-2], img[\"url\"].split(\"\\\\\")[-1].split(\".\")[0]]\n to_save = {\"x\": circleMeta[\"x\"], \"y\": circleMeta[\"y\"], \"r\": circleMeta[\"r\"], \"size\": radio.get() + 1}\n save_meta(path, to_save, meta)\n do_save(img, tokens[radio.get()], circleMeta, out_path)\n exit_ui(root)\n elif char == \"w\" or char == \"q\":\n print(f\"Closing '{img['url']}'. No token created.\")\n exit_ui(root)\n\n canvas.bind(\"\", onClick)\n canvas.bind(\"\", onRightClick)\n canvas.bind(\"\", onDrag)\n canvas.bind(\"\", onRelease)\n root.bind(\"\", onKey)\n\n return root\n\n\ndef get_image(url):\n img_cv = cv.imread(url, -1)\n imgHeight, imgWidth, channels = img_cv.shape\n # creating an alpha channel\n if channels != 4:\n img_cv = cv.cvtColor(img_cv, cv.COLOR_RGB2RGBA)\n\n return {\"url\": url, \"cv\": img_cv, \"h\": imgHeight, \"w\": imgWidth, \"tk\": None}\n\n\ndef get_token_images():\n out = []\n for i in range(len(TOKEN_FILES)):\n token = get_image(TOKEN_FILES[i])\n token[\"bg\"] = TOKEN_BG[i]\n out.append(token)\n return out\n\n\ndef main():\n try:\n with open(META, \"r\") as m:\n meta = json.load(m)\n except FileNotFoundError:\n meta = dict()\n tokens = get_token_images()\n for subdir, _, files in os.walk(INPATH):\n for file in files:\n filename, extension = os.path.splitext(file)\n if extension in IMAGE_EXTENSIONS:\n image = get_image(os.path.join(subdir, file))\n try:\n image[\"meta\"] = meta[subdir.split(\"\\\\\")[-1]][filename][\"meta\"]\n except KeyError:\n image[\"meta\"] = {\"x\": 0, \"y\": 0, \"r\": 0, \"size\": 1}\n\n out_folder = subdir.replace(INPATH, OUTPATH)\n if not os.path.exists(out_folder):\n os.makedirs(out_folder)\n if image[\"meta\"][\"x\"] and image[\"meta\"][\"y\"] and image[\"meta\"][\"r\"]:\n token_idx = 0\n if image[\"meta\"][\"size\"]:\n token_idx = image[\"meta\"][\"size\"] - 1\n do_save(image, tokens[token_idx],\n {\"x\": image[\"meta\"][\"x\"], \"y\": image[\"meta\"][\"y\"], \"r\": image[\"meta\"][\"r\"]},\n os.path.join(out_folder, file))\n else:\n ui = init_ui(image, tokens, os.path.join(out_folder, file), meta)\n ui.mainloop()\n\n\n# CONFIG ###############################################################################################################\nMETA = \"meta.json\"\nTOKEN_FILES = [\"token/1x1.png\", \"token/2x2.png\", \"token/3x3.png\", \"token/4x4.png\"]\nTOKEN_BG = [\"token/bg1x1.png\", \"token/bg2x2.png\", \"token/bg3x3.png\", \"token/bg4x4.png\"]\n# TOKEN_BG = [None, None, None, None] # Uncomment this line for transparent backgrounds\n# TOKEN_BG = [(94, 0, 0), (94, 0, 0), (94, 0, 0), (94, 0, 0)] # Uncomment this line for solid color (R,G,B) backgrounds\nINPATH = \"input\"\nOUTPATH = \"output\"\nIMAGE_EXTENSIONS = [\".png\", \".jpg\"]\n########################################################################################################################\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"generate-tokens.py","file_name":"generate-tokens.py","file_ext":"py","file_size_in_byte":10267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"293494882","text":"from django.urls import path;\nfrom chossen import views;\n#select_subject\nurlpatterns = [\n path(\"\",views.home,name=\"home\"),\n path('student/group/',views.select_group,name=\"group\"),\n path(\"student/groups/data\",views.display_info,name=\"groups_info\"),\n path('student/group/subjects/',views.select_subjects,name=\"subjects\"),\n path(\"student/subscription/data\",views.student_data,name=\"student\"),\n];\n","sub_path":"task/chossen/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"452778577","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 ('training', '0064_auto_20150916_1413'),\n ('profiles', '0012_auto_20150905_1915'),\n ('feedback', '0016_auto_20150915_1205'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='FeedbackSummary',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('best', models.TextField(max_length=1000, null=True, verbose_name=b'Favourite aspect of module', blank=True)),\n ('worst', models.TextField(max_length=1000, null=True, verbose_name=b'Least favourite aspect of module', blank=True)),\n ('general', models.TextField(max_length=1000, null=True, verbose_name=b'Comments in general', blank=True)),\n ('module', models.ForeignKey(to='training.Module')),\n ('researcher', models.ForeignKey(blank=True, to='profiles.Researcher', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"feedback/migrations/0017_feedbacksummary.py","file_name":"0017_feedbacksummary.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"377178067","text":"#! python3\r\n# chap8madlibs.py - Takes a text file and lets user add their own text whenever the words\r\n# ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file and replaces them.\r\n\r\nimport re\r\n\r\n# Get the file name\r\nmadLibs = input('Enter the .txt filename that you want to Mad Lib: \\n')\r\n\r\n# Try to open the file, then put the words into a list\r\ntry:\r\n with open(madLibs + '.txt') as madLibFile:\r\n madLibCont = madLibFile.read()\r\n madLibWords = list(madLibCont.split())\r\n\r\n # Create the regex for each replaceable term\r\n adjRegex = re.compile(r'ADJECTIVE')\r\n nounRegex = re.compile(r'NOUN')\r\n verbRegex = re.compile(r'VERB')\r\n adverbRegex = re.compile(r'ADVERB')\r\n\r\n # print the replacement prompts and get user input\r\n for i in range(len(madLibWords)):\r\n if adjRegex.match(madLibWords[i]):\r\n sub = input('Enter an adjective:\\n')\r\n madLibWords[i] = sub\r\n elif nounRegex.match(madLibWords[i]):\r\n sub = input('Enter a noun:\\n')\r\n madLibWords[i] = sub\r\n elif verbRegex.match(madLibWords[i]):\r\n sub = input('Enter a verb:\\n')\r\n madLibWords[i] = sub\r\n elif adverbRegex.match(madLibWords[i]):\r\n sub = input('Enter an adverb:\\n')\r\n madLibWords[i] = sub\r\n else:\r\n continue\r\n\r\n # Write new text file with replacement prompts to the text and print results to screen\r\n joinWordsList = ' '\r\n newString = joinWordsList.join(madLibWords)\r\n with open(madLibs + 'New.txt', 'w') as newMadLibsFile:\r\n newMadLibsFile.write(newString)\r\n print(newString)\r\n\r\nexcept FileNotFoundError:\r\n print('No such file: %s' % (madLibs + '.txt'))\r\n","sub_path":"chap8madlibs.py","file_name":"chap8madlibs.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"273158900","text":"# import cv2\n# import math\n\n# This is a comment\n# print(\"Hello world\")\n# print(math.gcd(3,6))\n'''\nThis is a multi line comment\n\n'''\n# This is also a comment\n# print(5+8)\n# if(age<18):\n# print(\"hello\")\n\n\na = 34\nb = \"Harry\"\nc = 45.32\nd = 3\n\n# print(a + d)\n# print(a - d)\n# print(a * d)\n# print(a / d)\n\n# Quiz: Try these operators:\n# 1. ** Exponentiation operator\n# 2. // Floor division operator\n# 3. % Modulo operator\n\n# Wrong syntax\n# harry project = 45\n# Rules for creating variables\n\n# 1. variable should start wioth a letter or an underscore\n# 2. variable cannot start with a number\n# 3. It can only contain alpha numeric characters\n# 4. Variable names are case sensitive. Harry and harry are two different variables\n\n# typeA = type(a)\n# typeB = type(b)\n# print(typeB)\ne = \"31\"\ne = float(e)\n# e = str(455)\n# e = int(\"34\")\n# e = 3.14\n# print(type(e))\n# print(e+2)\n\n\nname = \"Harry, Shubham, vikrant\"\n# print(name[2:5])\n# print(name)\n# print(name.strip())\n# print(len(name))\nvar = name.lower()\nvar = name.upper()\nvar = name.replace(\"ar\", \"t\")\nvar = name.replace(\", \", '\\n')\n# print(var)\n\nstri = \"This is a \"\nname1 = \"Harry\"\nname2 = \"Rohan\"\nstri2 = \"This is not a\"\n# print(stri + name)\n# temp = \"This is a {1} and he is a good boy named {0}\".format(name1, name2)\ntemp = f\"this is a {name2} and he is a good boy {name1}\"\n# print(temp)\n\n'''\nPython Collections:\n1. List\n2. Tuple\n3. Set\n4. Dictionary\n\n'''\n# List\nlst = [61,2,3,4,6,41]\n# var = type(lst)\n# lst[2] = 45\n# var = lst[2]\n# lst.append(100)\n# lst.insert(1,100)\n# lst.remove(61)\n# lst.pop()\n# del lst[3]\n# del lst\nlst.clear()\nvar = lst\n# var = len(lst)\n# var = lst[1:4]\n# print(var)\n\n\n# Tuple\na = (\"Harry\", \"Shubh\", \"Rohan\")\n# var = a\na = list(a)\nvar = type(a)\n\n# Cannot do this\na[0] = \"Vikrant\"\n# print(var)\n\n# Set\ns1 = {23,2,2,2,2,2,7,3,2,1,2,2,12,7,6,3,12,}\n# s1.add(44444)\n# s1.update([12,12,423,3423,634,123,432,23])\n# print(len(s1))\n# s1.remove(1666)\n# Like list you can use: .pop, .clear, del\n# and.. intersection, union\n# s1.discard(1666)\n# print(s1)\n\nharryDict = {\n \"Name\": \"Harry\",\n \"Class\": \"4th\",\n \"Marks\": 34.34,\n \"Hours In School\": 6\n}\nharryDict[\"Marks\"] = 34\n# print(harryDict[\"Marks\"])\nharryDict.pop(\"Marks\")\n# del, clear, pop, update\n# print(harryDict)\n\n# age = 34\n# age = input(\"Enter Your Age\\n\")\n# age = int(age)\n# # print(type(age))\n# if(age>18):\n# print(\"You can drive a car\")\n\n# elif(age==18):\n# print(\"You are an awesome teen\")\n\n# else:\n# print(\"You cannot drive\")\n\n\n# Loops:\n# Scenario: you have to print numbers between 1 to 1000\n# for i in range(0, 1000):\n# print(i)\n\n# li = [1, 432, \"this\"]\n# for item in li:\n# print(item)\n# # Quiz: Use for loop to iterate dictionary, set and tuples\n# i = 0\n# while(i<100):\n# i = i + 1\n# if i == 78:\n# continue\n# print(i+1)\n\n# Functions:\n# def greet():\n# print(\"Good morning sir\")\n# print(\"Good morning mam\")\n# print(\"Good morning Uncle\")\n\n# greet()\n\n# def sum(a, b):\n# print(\"Running sum\")\n# c = a + b\n# return c\n\n# d = sum(34, 45)\n# print(d)\n\nclass Employee:\n def __init__(self, gname, gsalary):\n self.name = gname\n self.salary = gsalary\n\nharry = Employee(\"harry\", 34)\nprint(harry.name)\nprint(harry.salary)\n","sub_path":"basic_python_.py","file_name":"basic_python_.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"552682578","text":"import os\nimport glob\nfrom logger import log_error\nfrom dateUtil import get_current_short_date_str, get_seconds_cut, get_time, convert_seconds_to_minutes, str_to_date_time, add_seconds_to_date, get_date_str, add_days_to_date, str_to_date, convert_path_to_str_date, rest_seconds_to_date\nfrom os.path import basename\nfrom picamera import PiCamera\nfrom dbUtil import get_config_value\nimport base64\nimport subprocess\n\nPATH_VIDEO_LOCALIZATION = ''\nPATH_CONCAT_VIDEOS = ''\nTIME_RECORDING_VIDEO = 0\nTIME_BEFORE = 0\nTIME_AFTER = 0\n\n# Constantes de la base de datos\ndef update_variables():\n global PATH_VIDEO_LOCALIZATION\n global PATH_CONCAT_VIDEOS\n global TIME_RECORDING_VIDEO\n global TIME_BEFORE\n global TIME_AFTER\n PATH_VIDEO_LOCALIZATION = get_config_value(\"VIDEO_LOCALIZATION_PATH\")\n PATH_CONCAT_VIDEOS = get_config_value(\"CONCAT_VIDEOS_PATH\")\n TIME_RECORDING_VIDEO = int(get_config_value(\"TIME_RECORDING_VIDEO\"))\n TIME_AFTER = int(get_config_value(\"TIME_AFTER_RECORD\"))\n TIME_BEFORE = int(get_config_value(\"TIME_BEFORE_RECORD\"))\n\n\n# Ejemplo de llamada:\n# get_mp4_between_dates('/home/pi/ViviFutbolLocal/Videos/2017-07-15/mp4/', '2017-07-15 14:35:00', '2017-07-15 14:38:00')\ndef get_mp4_between_dates(folder_path, start_date, finish_date):\n try:\n file_list = []\n result = subprocess.Popen('find ' + folder_path +' -name \"*.mp4\" -type f -newermt \"' + start_date + '\" ! -newermt \"' + finish_date + '\" -exec ls -lt --time-style=long-iso {} +', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (stdout,stderr) = result.communicate()\n files = stdout.decode().split()\n if len(files) > 0:\n i=7\n while i < len(files):\n file_list.append(files[i])\n i+=8\n file_list.sort()\n \n return file_list\n \n except Exception as e:\n print(str(e))\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_mp4_between_dates()', str(e))\n\n\ndef get_concat_file_name(file_name):\n try:\n update_variables()\n file_name_split = file_name.split('/')\n file_only_name = file_name_split[len(file_name_split)-1]\n file_without_extension = file_only_name.split('.')[0]\n video_path = PATH_VIDEO_LOCALIZATION + get_current_short_date_str()\n return video_path + PATH_CONCAT_VIDEOS + file_without_extension + '.mp4'\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_concat_file_name()', str(e))\n\n \ndef get_h264_files_in_directory(directory):\n try:\n return glob.glob(directory+'/*.h264')\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_h264_files_in_directory()', str(e))\n\n\ndef get_mp4_files_in_directory(directory):\n try:\n files = glob.glob(directory+'/*.mp4')\n files.sort(key=lambda x: os.path.getmtime(x))\n files.sort()\n return files\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_mp4_files_in_directory()', str(e))\n\n\ndef get_jpg_files_in_directory(directory):\n try:\n return glob.glob(directory+'/*.jpg')\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_jpg_files_in_directory()', str(e))\n\n\ndef get_wav_files_in_directory(directory):\n try:\n files = glob.glob(directory+'/*.wav')\n files.sort(key=lambda x: os.path.getmtime(x))\n return files\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_wav_files_in_directory()', str(e))\n\n \ndef delete_file(file_path):\n try:\n os.system('rm '+ file_path)\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - delete_file()', str(e))\n\n\ndef newest_h264_in_directory(directory):\n try:\n file_array = get_h264_files_in_directory(directory)\n if len(file_array) > 0:\n return max(glob.iglob(directory+'*.h264'), key=os.path.getctime)\n else:\n return []\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - newest_h264_in_directory()', str(e))\n\n\ndef newest_wav_in_directory(directory):\n try:\n file_array = get_h264_files_in_directory(directory)\n if len(file_array) > 0:\n return max(glob.iglob(directory+'*.wav'), key=os.path.getctime)\n else:\n return []\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - newest_wav_in_directory()', str(e))\n\n \ndef newest_h264_in_directory(directory):\n try:\n file_array = get_h264_files_in_directory(directory)\n if len(file_array) > 0:\n return max(glob.iglob(directory+'*.h264'), key=os.path.getctime)\n else:\n return []\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - newest_h264_in_directory()', str(e))\n\n\ndef newest_MP4_in_directory(directory):\n try:\n file_array = get_mp4_files_in_directory(directory)\n if len(file_array) > 0:\n return max(glob.iglob(directory+'*.mp4'), key=os.path.getctime)\n else:\n return []\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - newest_MP4_in_directory()', str(e))\n\n \ndef oldest_MP4_in_directory(directory):\n try:\n file_array = get_mp4_files_in_directory(directory)\n if len(file_array) > 0:\n return min(glob.iglob(directory+'*.mp4'), key=os.path.getctime)\n else:\n return []\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - oldest_MP4_in_directory()', str(e))\n\n\ndef get_file_name_without_extension(name):\n try:\n filename, file_extension = os.path.splitext(name)\n return os.path.basename(filename)\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_file_name_without_extension()', str(e))\n\n\ndef get_file_name(file_path):\n try:\n head, tail = os.path.split(file_path)\n file_name = get_file_name_without_extension(tail)\n return file_name\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_file_name()', str(e))\n\n\ndef image_monitor_device(directory, picture_path):\n try:\n # Obtengo el video que se esta grabando para obtener el ultimo frame\n newest_h264_file = newest_h264_in_directory(directory + \"/\")\n picture_file = ''\n \n if len(newest_h264_file) > 0 :\n # Si se esta grabando un video obtengo el frame\n time_last_frame = get_time_last_frame(newest_h264_file, picture_path)\n get_last_frame_from_current_video(newest_h264_file, picture_path, time_last_frame)\n else:\n # Si la camara no esta grabando, saco una foto\n try:\n PiCamera().close()\n except OSError:\n pass\n camera = PiCamera()\n camera.capture(picture_path)\n camera.close()\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - image_monitor_device()', str(e))\n\n\n#Obtiene el ultimo frame del video que se esta filmando\ndef get_last_frame_from_current_video(h264_file, picture_path, time_last_frame):\n try:\n os.system('avconv -ss ' + time_last_frame + ' -r 30 -i ' + h264_file + ' -t 1 ' + picture_path)\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_last_frame_from_current_video()', str(e))\n\n\n#Obtiene la fecha del ultimo frame\ndef get_time_last_frame(newest_h264_file, picture_path):\n try:\n h264_name = get_file_name(newest_h264_file)\n h264_time = get_time(h264_name)\n picture_name = get_file_name(picture_path)\n picture_time = get_time(picture_name)\n difference_time = get_seconds_cut(h264_time, picture_time)\n time_last_frame = convert_seconds_to_minutes(difference_time)\n return time_last_frame\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_time_last_frame()', str(e))\n\n\n# Obtiene el siguiente video filmado de otro video\ndef get_next_video(video_path):\n try:\n update_variables()\n video_str_date = convert_path_to_str_date(video_path)\n video_date = str_to_date_time(video_str_date)\n video_str_date = video_str_date.split('_')[0]\n new_video_date = add_seconds_to_date(video_date, TIME_RECORDING_VIDEO)\n video_path = PATH_VIDEO_LOCALIZATION + video_str_date + '/mp4'\n new_video_path = PATH_VIDEO_LOCALIZATION + video_str_date + '/mp4/'+ get_date_str(new_video_date) + \".mp4\"\n\n # Pregunto si existe el video asi no tengo que recorrer todos los videos\n if not os.path.exists(new_video_path):\n new_video_path = ''\n mp4_files = get_mp4_files_in_directory(video_path)\n \n # Obtengo el final de la marca para ver si entra en el video a consultar\n new_mark_date = add_seconds_to_date(video_date, TIME_RECORDING_VIDEO + TIME_AFTER)\n \n # Para cada video mp4 pregunto si el final de la marca pertenece al video\n for video in mp4_files:\n video_str_date = convert_path_to_str_date(video)\n video_date = str_to_date_time(video_str_date)\n finish_time = add_seconds_to_date(video_date, TIME_RECORDING_VIDEO)\n \n if video_contains_mark(video_date, new_mark_date):\n return video\n elif finish_time > new_mark_date:\n # Si el video termina despues de la marca pero no pertenecia a ningun video termino la iteracion\n break\n \n return new_video_path \n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_next_video()', str(e))\n\n\n# Retorna si una marca fue creada durante ese video\ndef video_contains_mark(video_date, mark):\n try:\n update_variables()\n finish_time = add_seconds_to_date(video_date, TIME_RECORDING_VIDEO)\n if (video_date <= mark and finish_time >= mark):\n return True\n else:\n return False\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - video_contains_mark()', str(e))\n\n\n# Retorna true si el video se encuentra entre las marcas\ndef video_between_marks(video_start_date, start, finish):\n try:\n update_variables()\n video_end_date = add_seconds_to_date(video_start_date, TIME_RECORDING_VIDEO)\n start_date = str_to_date_time(start)\n finish_date = str_to_date_time(finish)\n\n if (video_start_date < start_date and video_end_date < finish_date) or (video_start_date > start_date and video_end_date < finish_date) or (video_start_date < finish_date and video_end_date > finish_date):\n return True\n else:\n return False\n except Exception as e:\n print(str(e))\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - video_between_marks()', str(e))\n\n\n# Convierte una imagen a base64\ndef convert_image_to_base64(picture_path):\n try:\n encoded_string = ''\n with open(picture_path, \"rb\") as image_file:\n encoded_string = base64.b64encode(image_file.read())\n return str(encoded_string)\n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - convert_image_to_base64()', str(e))\n\n\n# Obtiene el video anterior de otro video filmado\ndef get_previous_video(video_path):\n try:\n update_variables()\n video_str_date = convert_path_to_str_date(video_path)\n video_date = str_to_date_time(video_str_date)\n video_str_date = video_str_date.split('_')[0]\n new_video_date = rest_seconds_to_date(video_date, TIME_RECORDING_VIDEO)\n video_path = PATH_VIDEO_LOCALIZATION + video_str_date + '/mp4'\n new_video_path = PATH_VIDEO_LOCALIZATION + video_str_date + '/mp4/'+ get_date_str(new_video_date) + \".mp4\"\n \n if not os.path.exists(new_video_path):\n new_video_path = ''\n mp4_files = get_mp4_files_in_directory(video_path)\n \n # Obtengo el final de la marca para ver si entra en el video a consultar\n new_mark_date = rest_seconds_to_date(video_date, TIME_BEFORE)\n \n # Para cada video mp4 pregunto si el final de la marca pertenece al video\n for video in mp4_files:\n video_str_date = convert_path_to_str_date(video)\n video_date = str_to_date_time(video_str_date)\n \n if video_contains_mark(video_date, new_mark_date):\n return video\n elif video_date > new_mark_date:\n # Si el video empieza despues de la marca pero no pertenecia a ningun video termino la iteracion\n break\n\n return new_video_path \n except Exception as e:\n log_error('SYSTEM', 'SYSTEM', 'fileUtil.py - get_previous_video()', str(e))\n\n","sub_path":"Scripts/fileUtil.py","file_name":"fileUtil.py","file_ext":"py","file_size_in_byte":12954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"57275875","text":"from django.contrib.auth import views as auth_views\nfrom django.urls import path,include\nfrom apps.core.views import frontpage\nfrom . import views\n\nurlpatterns = [\n path('become-vendor/', views.become_vendor, name='become_vendor'),\n path('vendor-admin/', views.vendor_admin, name='vendor_admin'),\n path('add-product/', views.add_product, name='add_product'),\n path('edit-vendor/', views.edit_vendor, name='edit_vendor'),\n path('edit-customer/', views.edit_customer, name='edit_customer'),\n path('edit-product//', views.edit_product, name='edit_product'),\n path('delete-product//', views.delete_product, name='delete_product'),\n # path('', frontpage, name='frontpage'),\n path('logout/', views.user_logout, name='user_logout'),\n # path('login/', auth_views.LoginView.as_view(template_name='vendor/login.html'), name='login'),\n path('login/', views.user_login, name='user_login'),\n path('', views.vendors, name='vendors'),\n path('/', views.vendor, name='vendor'),\n path('vendor-admin/home/', frontpage, name='frontpage'),\n path('vendor-kyc/', views.vendor_kyc, name='vendor_kyc'),\n\n\n\n #path('', include('apps.core.urls')),\n\n]","sub_path":"Interiorshop/interiorshop-main/interiorshop-main/apps/vendor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"550625298","text":"import apache_beam as beam\nimport logging\n\nfrom craigslist.crawler import Apartments\n\nclass GetPosts(beam.DoFn):\n def process(self, element):\n apartments = Apartments()\n links = apartments.get_posts(test=True)\n return links\n\nclass GetPostDetails(beam.DoFn):\n def process(self, element):\n apartments = Apartments() \n post = apartments.get_post(element) \n yield post\n\nclass CleanTimestamp(beam.DoFn):\n def process(self, element):\n timestamp_fields = ['posted_date']\n for field in timestamp_fields:\n timestamp = element[field]\n timestamp = timestamp[:-2] + \":\" + timestamp[-2:]\n element[field] = timestamp\n yield element ","sub_path":"pipeline/dofn.py","file_name":"dofn.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"64518544","text":"\"\"\"\nProject Euler #48\nMan why ask such question???\n\"\"\"\nup = 1000\nmy_sum = 0\nfor i in range( 1, up + 1 ):\n my_sum += i**i\n \ns = str(my_sum)\nprint(s[len(s)-10:])\n","sub_path":"Competitive Programming/project_euler/48.py","file_name":"48.py","file_ext":"py","file_size_in_byte":166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"266321824","text":"import datetime\n\nfrom titus_isolate import log\nfrom titus_isolate.config.constants import ALLOCATOR_KEY, CPU_ALLOCATORS, DEFAULT_ALLOCATOR, \\\n CPU_ALLOCATOR_A, CPU_ALLOCATOR_B, AB_TEST, EC2_INSTANCE_ID, CPU_ALLOCATOR_NAME_TO_CLASS_MAP\nfrom titus_isolate.docker.constants import BURST, STATIC\n\nBUCKETS = [\"A\", \"B\"]\n\n\ndef get_burst_workloads(workloads):\n return get_workloads_by_type(workloads, BURST)\n\n\ndef get_static_workloads(workloads):\n return get_workloads_by_type(workloads, STATIC)\n\n\ndef get_workloads_by_type(workloads, workload_type):\n return [w for w in workloads if w.get_type() == workload_type]\n\n\ndef get_allocator_class(config_manager, hour=None):\n if hour is None:\n hour = datetime.datetime.utcnow().hour\n\n alloc_str = config_manager.get(ALLOCATOR_KEY)\n\n if alloc_str == AB_TEST:\n return __get_ab_allocator_class(config_manager, hour)\n else:\n return __get_allocator_class(alloc_str)\n\n\ndef __get_allocator_class(allocator_str):\n if allocator_str not in CPU_ALLOCATORS:\n log.error(\"Unexpected CPU allocator specified: '{}', falling back to default: '{}'\".format(allocator_str, DEFAULT_ALLOCATOR))\n allocator_str = DEFAULT_ALLOCATOR\n\n return CPU_ALLOCATOR_NAME_TO_CLASS_MAP[allocator_str]\n\n\ndef __get_ab_allocator_class(config_manager, hour):\n a_allocator_str = config_manager.get(CPU_ALLOCATOR_A)\n b_allocator_str = config_manager.get(CPU_ALLOCATOR_B)\n\n a_allocator_class = __get_allocator_class(a_allocator_str)\n b_allocator_class = __get_allocator_class(b_allocator_str)\n\n bucket = get_ab_bucket(config_manager, hour)\n\n if bucket not in BUCKETS:\n log.error(\"Unexpected A/B bucket specified: '{}', falling back to default: '{}'\".format(bucket, DEFAULT_ALLOCATOR))\n return __get_allocator_class(\"UNDEFINED_AB_BUCKET\")\n\n return {\n \"A\": a_allocator_class,\n \"B\": b_allocator_class,\n }[bucket]\n\n\ndef get_ab_bucket(config_manager, hour):\n\n instance_id = config_manager.get(EC2_INSTANCE_ID)\n if instance_id is None:\n log.error(\"Failed to find: '{}' in config manager, is the environment variable set?\".format(EC2_INSTANCE_ID))\n return \"UNDEFINED\"\n\n # Take the last character of an instance id turn it into a number and determine whether it's odd or even.\n # An instance id looks like this: i-0cfefd19c9a8db976\n char = instance_id[-1]\n bucket = _get_ab_bucket_int(char, hour)\n if bucket == 0:\n return \"A\"\n else:\n return \"B\"\n\n\ndef _get_ab_bucket_int(char, hour):\n instance_int = ord(char)\n hour = int(hour / 6)\n int_bucket = (instance_int + (hour % 2)) % 2\n return int_bucket\n","sub_path":"titus_isolate/isolate/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"590952268","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nfrom skimage import feature\n\n\n# Get source region and target region and init confidence\ndef load_image(image1, image2):\n image = cv2.imread(image1)\n RGBimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n mask = cv2.imread(image2)\n mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)\n confidence = (mask == 255).astype('float')\n return image, RGBimage, mask, confidence\n\n# Use edge detection to get front fill Delta Omega from mask image\ndef get_front_fill(mask):\n ff = (feature.canny(mask)).astype(float)\n itemindex = np.where(ff==1)\n return itemindex\n\n# Use point axis and window_size to get the range of patch psi P(2X2 array)\ndef patch(image,point, window_size):\n iy,ix = image.shape\n size = window_size[0]//2\n x, y = point\n patch_range = [(max(x - size, 0), max(y - size, 0)),\n (min(x + size, ix - 1), min(y + size, iy - 1))]\n patch_size = (patch_range[1][1]-patch_range[0][1]+1, patch_range[1][0]-patch_range[0][0]+1)\n return patch_range, patch_size\n\n# compute point p confidence\ndef compute_confidence(confidence, point, mask, window_size):\n psiP,_ = patch(mask, point, window_size)\n x_1, y_1 = psiP[0]\n x_2, y_2 = psiP[1]\n area = (x_2-x_1+1) * (y_2-y_1+1)\n t_sum = 0\n for i in range(y_1, y_2 + 1):\n for j in range(x_1, x_2 + 1):\n if mask[i, j] != 0:\n t_sum += confidence[i, j]\n return t_sum / area\n\n# Get the gradient of isophote around the patch\ndef compute_gradient(image,mask):\n alpha = 255\n gx = (cv2.Scharr(image, cv2.CV_64F, 1, 0))/alpha\n gy = (cv2.Scharr(image, cv2.CV_64F, 0, 1))/alpha\n gx[mask==1]=0\n gy[mask==1]=0\n return gx,gy\n\n# Get the unit vector of the normal on front fill\ndef compute_normal(front_fill,mask):\n gx = cv2.Scharr(mask, cv2.CV_64F, 1, 0)\n gy = cv2.Scharr(mask, cv2.CV_64F, 0, 1)\n normal = []\n for i in range(len(front_fill[0])):\n x,y = front_fill[1][i], front_fill[0][i]\n norm = np.sqrt(gx[y,x]**2 + gy[y,x]**2)\n if norm != 0:\n normal.append([gy[y,x]/norm,-gx[y,x]/norm])\n else:\n normal.append([gy[y,x],-gx[y,x]])\n return normal\n\n# Compute data term by equation\ndef compute_data(nalba_Ip, normal, point, point_num):\n x,y = point\n alpha = 255\n data = (np.sqrt((nalba_Ip[0][y,x] * normal[point_num][0])**2 + (nalba_Ip[1][y,x] * normal[point_num][1])**2)) / alpha\n return data\n\n# Compute priority for point P\ndef compute_priority(confidence, data):\n priority = confidence * data\n return priority\n\n# Get the data in patch Psi\ndef get_patch_data(psi, image):\n startX = psi[0][0]\n endX = psi[1][0]\n startY = psi[0][1]\n endY = psi[1][1]\n return image[startY:endY+1, startX:endX+1]\n\n\n# Compute the sum of squared differences (SSD) of the already filled pixels in\n# the two patches psiP and psiQ\ndef SSD(psiP, psiQ, rgbimage, source_mask):\n channels = rgbimage.shape[2]\n psiP_data = get_patch_data(psiP, rgbimage)\n psiQ_data = get_patch_data(psiQ, rgbimage)\n ssd = 0\n for i in range(channels):\n difference = psiP_data[:,:,i] - psiQ_data[:,:,i]\n ssd += np.sum(np.square(difference[source_mask]))\n return ssd\n\n# Get the patch data of psi Q\ndef get_patch_q(q, mask, patch_size):\n ysize = patch_size[0]//2\n xsize = patch_size[1]//2\n startX = q[0] - xsize\n startY = q[1] - ysize\n if patch_size[1] %2 != 0:\n endX = q[0] + xsize\n else:\n endX = q[0] + xsize - 1\n if patch_size[0] %2 != 0:\n endY = q[1] + ysize\n else:\n endY = q[1] + ysize - 1\n mask_xy = [np.repeat(np.arange(startY, endY+1),patch_size[1]), np.tile(np.arange(startX, endX+1), patch_size[0])]\n if mask[mask_xy].sum() == patch_size[0]*patch_size[1]*0:\n return np.array([[startX, startY],[endX, endY]])\n else: \n return None\n\n# Find the best match patch psi q hat\ndef best_match_patch(rgbimage, mask, psiP, patch_size):\n h,w,_ = rgbimage.shape\n ysize = patch_size[0]//2\n xsize = patch_size[1]//2\n ssd = []\n psiQ_hat = []\n psiP_mask_data = get_patch_data(psiP, mask)\n source_index = np.argwhere(psiP_mask_data != 255)\n source_mask = [source_index[:, 0],source_index[:,1]]\n if patch_size[1] %2 != 0:\n endX = w-xsize-1\n else:\n endX = w-xsize\n if patch_size[0] %2 != 0:\n endY = h-ysize-1\n else:\n endY = h-ysize\n for i in range(xsize, endX):\n for j in range(ysize, endY):\n psiQ = get_patch_q((i, j), mask, patch_size)\n if type(psiQ) == np.ndarray:\n ssd.append(SSD(psiP, psiQ, rgbimage, source_mask))\n psiQ_hat.append(psiQ)\n index = np.argmin(ssd)\n return psiQ_hat[index]\n\n# Fill the empty pixels in sai P with the value of corresponding pixels in sai q hat.\ndef fill_image(RGBimage, mask, psiP, psiQ_hat):\n psiP_mask_data = get_patch_data(psiP, mask)\n target_index = np.argwhere(psiP_mask_data != 0)\n target_mask = [target_index[:, 0],target_index[:,1]]\n channels = RGBimage.shape[2]\n psiP_data = get_patch_data(psiP, RGBimage)\n psiQ_hat_data = get_patch_data(psiQ_hat, RGBimage)\n for i in range(channels):\n psiP_data[:,:,i][target_mask] = psiQ_hat_data[:,:,i][target_mask]\n psiP_mask_data[target_mask] = 0\n\n return RGBimage, mask\n\n# Update confidence in intersection aera of sai P_hat and omega with C(P_hat)\ndef update_confidence(confidence, saiP_hat, P_hat):\n px,py = P_hat\n curr = confidence[py,px]\n x_1, y_1 = saiP_hat[0]\n x_2, y_2 = saiP_hat[1]\n for i in range(x_1, x_2 + 1):\n for j in range(y_1, y_2 + 1):\n if confidence[j,i] == 0:\n confidence[j,i] = curr\n return confidence\n\n# Inpainting function\n# type image1: string\n# param image1: the name of the orignal image. s.t 'xxx.png'\n# type image2: string\n# param image2 the name of the mask image. s.t 'xxx_mask.png'\n# type window_size: tuple\n# param window_size: a tuple contains the height and width of the patch window(usually h = w). s.t (x,x)\n# return: Nothing. The inpainted image will be saved as 'xxx_result.png' under the same directory of this function file\n\ndef inpainting(image1, image2, window_size):\n image, RGBimage, mask, confidence = load_image(image1,image2)\n window_size = window_size\n while(not np.all(mask == 0)):\n front_fill = get_front_fill(mask)\n nalba_Ip = compute_gradient(image,mask)\n normal = compute_normal(front_fill,mask)\n ff_priority = []\n for i in range(len(front_fill[0])):\n curr = (front_fill[1][i],front_fill[0][i])\n curr_confidence = compute_confidence(confidence,curr,mask,window_size)\n confidence[curr[1], curr[0]] = curr_confidence\n curr_data = compute_data(nalba_Ip,normal,curr,i)\n ff_priority.append(compute_priority(curr_confidence,curr_data))\n curr_max = np.argmax(ff_priority)\n curr_idx = (front_fill[1][curr_max],front_fill[0][curr_max])\n psiP, patch_size = patch(image, curr_idx, window_size)\n psiQ_hat = best_match_patch(RGBimage, mask, psiP, patch_size)\n RGBimage, mask = fill_image(RGBimage, mask, psiP, psiQ_hat)\n update_confidence(confidence, psiP, curr_idx)\n # print(ff_priority)\n plt.imshow(RGBimage)\n plt.show()\n fig = plt.figure()\n plt.imshow(RGBimage)\n index = image1.find(\".\")\n image3 = image1[:index]+\"_result\" + image1[index:]\n plt.savefig(image3, dpi=fig.dpi)\n\n\nif __name__ == \"__main__\":\n image1 = \"air.png\"\n image2 = \"air_mask.png\"\n inpainting(image1, image2, (7,7))\n","sub_path":"Inpainting.py","file_name":"Inpainting.py","file_ext":"py","file_size_in_byte":7303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"109891680","text":"from util.parser import Parser\n\n\nclass SgsnInfoParser(Parser):\n def __init__(self):\n super(SgsnInfoParser, self).__init__()\n\n def parse(self, data):\n node_data = {}\n for line in data.split('\\n'):\n if line.startswith('hw'):\n node_data['hw'] = line.split()[2]\n elif line.startswith('swl'):\n node_data['swl'] = line.split()[2]\n elif line.startswith('type'):\n node_data['nodeType'] = line.split()[2]\n return node_data\n\n\nclass EpgHwParser(Parser):\n def __init__(self):\n super(EpgHwParser, self).__init__()\n\n def parse(self, data):\n node_data = {}\n for line in data.split(\"\\r\\n\"):\n if line.startswith(\"Current platform is\"):\n node_data['hw'] = line.split(\"is\")[1].strip()\n return node_data\n\n\nclass EpgSwParser(Parser):\n def __init__(self):\n super(EpgSwParser, self).__init__()\n\n def parse(self, data):\n node_data = {}\n for line in data.split('\\r\\n'):\n if line.startswith('EPG application version'):\n node_data['swl'] = line.split(':')[1].strip()\n return node_data\n","sub_path":"epc_oam_apps_160930/target/worker/nodeManagement/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"5198369","text":"import whitehat\nfrom whitehat.utilities import get_ip\n\nip = whitehat.ip(\"ip address\")\n\nweb_ip = get_ip(\"example.com\")\nip_location = ip.location\nip_info = ip.get_all_info() # already including location\n\nprint(web_ip)\nprint(ip_location)\nprint(ip_info)","sub_path":"examples/ip.py","file_name":"ip.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"137152342","text":"\"\"\"\nWorks with the legacy version of caDNAno SQ\nWorks with even numbered helices, assumed they go all into one direction.\nThis simplifies the binding of the scaffold and binding of the staples\n\"\"\"\nMAX_ROWS = 20\nMAX_COLS = 30\nMAX_HELICES = MAX_ROWS * MAX_COLS\n\n\ndef generate_even_helix_position_sq(rows=MAX_ROWS, cols=MAX_COLS):\n \"\"\"Iterator to generate the next even helix position on a square lattice.\n :param rows: number of rows in the lattice\n :param cols: number of columns in the lattice\n :return (row, col): tuple consisting of helix coordinates on the lattice\n \"\"\"\n n_rows = rows * 2 # as the step is 2 we have to have double the number of rows\n for i in range(0, cols, 1):\n for j in range(0, n_rows, 2):\n m = 0 if i % 2 == 0 else 1 # to accommodate for the row shift at odd columns\n yield (i, j + m)\n\n\ndef vhelix(num=0, column=0, row=0, overhang=0, segment_length=26, displayed_length=126):\n \"\"\" Create a virtual helix.\n :param num: helix number\n :param column: helix column coordinate on square grid\n :param row: helix row coordinate on square grid\n :param overhang: length of the overhang\n :param segment_length: length of scaffold and staple strands on this segment\n :param displayed_length: displayed length in caDNAno\n :return: dictionary, containing virtual helix definition\n \"\"\"\n return {\n \"num\": num,\n \"col\": column,\n \"row\": row,\n \"loop\": [0 for i in range(displayed_length)],\n \"skip\": [0 for i in range(displayed_length)],\n \"stapLoop\": [],\n \"scafLoop\": [],\n \"stap\": __staple(num=num, overhang=overhang, length=segment_length, displayed_length=displayed_length),\n \"scaf\": __scaffold(num=num, overhang=overhang, length=segment_length, displayed_length=displayed_length),\n \"stap_colors\": []\n }\n\n\ndef __scaffold(length=26, overhang=1, num=0, displayed_length=126):\n \"\"\"Constructs scaffold segment for virtual helix.\n :param length: length of scaffold strand\n :param overhang: length of the overhang\n :param num: helix number\n :param displayed_length: displayed length in caDNAno\n :return: list containing scaffold base definitions\n \"\"\"\n s = [[-1, -1, -1, -1] for i in range(overhang)] # shift scaffold position overhang bases to the right\n s.append([-1, -1, num, overhang + 1]) # start base [-1,-1, num, base_number]\n s.extend([num, i - 1, num, i + 1]\n for i in range(overhang + 1, length + 2 * overhang - 1)) # construct scaffold path\n s.append([num, length + 2 * overhang + 2, -1, -1]) # last base [num, base_number, -1, -1]\n s.extend([[-1, -1, -1, -1]\n for i in range(displayed_length - length - 2 * overhang)]) # fill up displayed length\n return s\n\n\ndef __staple(length=26, overhang=1, num=0, displayed_length=126):\n \"\"\"Constructs staple segment for virtual helix.\n :param length: length of staple strand on this segment\n :param overhang: length of the overhang\n :param num: helix number\n :param displayed_length: displayed length in caDNAno\n :return: list containing scaffold base definitions\n \"\"\"\n s = [[num, 1, -1, -1]] # start base, inverse as scaffold\n s.extend([num, i + 1, num, i - 1]\n for i in range(1, length - 1 + overhang)) # construct staple path\n s.append([-1, -1, num, length - 2 + overhang]) # end base\n s.extend([[-1, -1, -1, -1]\n for i in range(displayed_length - length - overhang)]) # fill up displayed length\n return s\n\n\ndef interconnect_helices(helices):\n \"\"\"Interconnect scaffold path of helices in list.\n :param helices: list of helices\n \"\"\"\n\n def bind_helix(h1, h2):\n \"\"\"scaffold binding\"\"\"\n b1, b2 = None, None\n for b in h1[\"scaf\"][::-1]:\n if b != [-1, -1, -1, -1]:\n b1 = b\n break\n for b in h2[\"scaf\"]:\n if b != [-1, -1, -1, -1]:\n b2 = b\n break\n b1[2] = b2[2]\n b1[3] = b2[3] - 1 # don't ask me why ? ...\n b2[0] = b1[0]\n b2[1] = b1[1]\n\n for i in range(len(helices) - 1):\n bind_helix(helices[i], helices[i + 1])\n\n\ndef interconnect_staples(helices, connection_pairs):\n \"\"\"Interconnect staple path, for given list of helices.\n :param helices: list of helices\n :param connection_pairs: list of (helix number, helix number) which have to be connected\n \"\"\"\n\n def connect_staples(h1, h2):\n \"\"\"0->4 direction\"\"\"\n s1 = h1[\"stap\"]\n s2 = h2[\"stap\"]\n b1, b2 = None, None\n # b1 is always the first base\n b1 = s1[0]\n # b2 we have to search\n for b in s2[::-1]:\n if b != [-1, -1, -1, -1]:\n b2 = b\n break\n b1[2] = b2[2]\n b1[3] = b2[3] + 1 # don't ask me why ? ...\n b2[0] = b1[0]\n b2[1] = b1[1]\n\n # generate numbered dictionary\n helix_by_number = {}\n for h in helices:\n helix_by_number[h[\"num\"]] = h\n for helix_numbers in connection_pairs:\n connect_staples(helix_by_number[helix_numbers[0]], helix_by_number[helix_numbers[1]])\n\n\ndef break_staple(helix, position=10):\n \"\"\"Break a staple at given position.\n :param helix: location of the staple\n :param position: base position to place the nick\n \"\"\"\n staple = helix[\"stap\"]\n # staples start from 0, so position is the position of the nick\n b1 = staple[position]\n b2 = staple[position + 1]\n b1[0], b1[1] = -1, -1\n b2[2], b2[3] = -1, -1\n\n\nCOLOR_PALETTE = {\n \"pink\": 12060252,\n \"black\": 3355443,\n \"gray\": 8947848,\n \"dark_red\": 13369344,\n \"light_red\": 16204552,\n \"orange\": 16225054,\n \"light_green\": 11184640,\n \"green\": 5749504,\n \"dark_green\": 29184,\n \"light_blue\": 243362,\n \"dark_blue\": 1507550,\n \"purple\": 7536862,\n}\n\ndef get_staple_ends(helix):\n \"\"\"Provided a helix we get all the staple ends on that helix.\n :param helix: virtual helix\n :return: list of staple ends\n \"\"\"\n stap = helix[\"stap\"]\n ends = []\n for i, base in enumerate(stap):\n l, r = base[:2], base[2:4]\n if l == [-1, -1] and r != [-1, -1]:\n ends.append(i)\n return ends\n\ndef color_staple(staple_end, color, helix):\n \"\"\"Color staple with corresponding color.\n :param staple_end: the start of the staple (5' end)\n :param color: color of the staple\n :param helix: location of staple end\n \"\"\"\n helix[\"stap_colors\"].append(\n [staple_end, color]\n )\n\n","sub_path":"util/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":6537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"423551479","text":"import numpy as np\nimport pytest\nfrom sklearn.datasets import load_iris\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, classification_report\n\nfrom fedot.core.data.data import InputData\nfrom fedot.core.data.data_split import train_test_data_setup\nfrom fedot.core.operations.model import Model\nfrom fedot.core.pipelines.node import PrimaryNode, SecondaryNode\nfrom fedot.core.repository.dataset_types import DataTypesEnum\nfrom fedot.core.repository.tasks import Task, TaskTypesEnum\n\n\n@pytest.fixture()\ndef data_setup() -> InputData:\n predictors, response = load_iris(return_X_y=True)\n np.random.seed(1)\n np.random.shuffle(predictors)\n np.random.shuffle(response)\n predictors = predictors[:100]\n response = response[:100]\n data = InputData(features=predictors, target=response, idx=np.arange(0, 100),\n task=Task(TaskTypesEnum.classification),\n data_type=DataTypesEnum.table)\n return data\n\n\ndef model_metrics_info(class_name, y_true, y_pred):\n print('\\n', f'#test_eval_strategy_{class_name}')\n print(classification_report(y_true, y_pred))\n print('Test model accuracy: ', accuracy_score(y_true, y_pred))\n\n\ndef test_node_factory_log_reg_correct(data_setup):\n model_type = 'logit'\n node = PrimaryNode(operation_type=model_type)\n\n expected_model = Model(operation_type=model_type).__class__\n actual_model = node.operation.__class__\n\n assert node.__class__ == PrimaryNode\n assert expected_model == actual_model\n\n\ndef test_eval_strategy_logreg(data_setup):\n data_set = data_setup\n train, test = train_test_data_setup(data=data_set)\n test_skl_model = LogisticRegression(C=10., random_state=1,\n solver='liblinear',\n max_iter=10000, verbose=0)\n test_skl_model.fit(train.features, train.target)\n expected_result = test_skl_model.predict(test.features)\n\n test_model_node = PrimaryNode(operation_type='logit')\n test_model_node.fit(input_data=train)\n actual_result = test_model_node.predict(input_data=test)\n\n assert len(actual_result.predict) == len(expected_result)\n\n\ndef test_node_str():\n # given\n operation_type = 'logit'\n test_model_node = PrimaryNode(operation_type=operation_type)\n expected_node_description = operation_type\n\n # when\n actual_node_description = str(test_model_node)\n\n # then\n assert actual_node_description == expected_node_description\n\n\ndef test_node_repr():\n # given\n operation_type = 'logit'\n test_model_node = PrimaryNode(operation_type=operation_type)\n expected_node_description = operation_type\n\n # when\n actual_node_description = repr(test_model_node)\n\n # then\n assert actual_node_description == expected_node_description\n\n\ndef test_ordered_subnodes_hierarchy():\n first_node = PrimaryNode('knn')\n second_node = PrimaryNode('knn')\n third_node = SecondaryNode('lda', nodes_from=[first_node, second_node])\n root = SecondaryNode('logit', nodes_from=[third_node])\n\n ordered_nodes = root.ordered_subnodes_hierarchy()\n\n assert len(ordered_nodes) == 4\n\n\ndef test_distance_to_primary_level():\n first_node = PrimaryNode('knn')\n second_node = PrimaryNode('knn')\n third_node = SecondaryNode('lda', nodes_from=[first_node, second_node])\n root = SecondaryNode('logit', nodes_from=[third_node])\n\n distance = root.distance_to_primary_level\n\n assert distance == 2\n","sub_path":"test/unit/pipelines/test_node.py","file_name":"test_node.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"356528034","text":"def calculadora():\n print(\"########## Calculadora de horas ##########\")\n x = 0\n while x == 0:\n x = int(input(\"\"\"Escolha uma opçao\n 1. Horas em Minutos\n 2. Minutos em Horas \"\"\"))\n if x == 1:\n horas = int(input(\"Horas\"))\n minutos = int(input(\"Minutos\"))\n conversor = (horas * 60 + minutos)\n print(\"Total de minutos:\", conversor)\n break\n if x == 2:\n minutos = int((input(\"Quanto Minutos?\")))\n horas_inteiro = minutos // 60\n horas_resto = minutos % 60\n print(minutos, \" são %s:%s horas\" % (horas_inteiro, horas_resto))\n break\n else:\n print(\"opcao invalida, digite 1 ou 2\")\n x = 0\n\n\ndef main():\n calculadora()\n\n\nmain()\n","sub_path":"Calculadora_minutos.py","file_name":"Calculadora_minutos.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"241456962","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nThis experiment was created using PsychoPy2 Experiment Builder (v1.73.06), August 23, 2012, at 12:58\nIf you publish work using this script please cite the relevant PsychoPy publications\n Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of Neuroscience Methods, 162(1-2), 8-13.\n Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy. Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008\n\"\"\"\n\nfrom __future__ import division #so that 1/3=0.333 instead of 1/3=0\nfrom psychopy import visual, core, data, event, logging, gui, sound\nfrom psychopy.constants import * #things like STARTED, FINISHED\nimport numpy as np # whole numpy lib is available, pre-pend 'np.'\nfrom numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray\nfrom numpy.random import random, randint, normal, shuffle\nimport os #handy system and path functions\n\"\"\"\n#store info about the experiment session\nexpName='None'#from the Builder filename that created this script\nexpInfo={'participant':'', 'session':'001'}\ndlg=gui.DlgFromDict(dictionary=expInfo,title=expName)\nif dlg.OK==False: core.quit() #user pressed cancel\nexpInfo['date']=data.getDateStr()#add a simple timestamp\nexpInfo['expName']=expName\n#setup files for saving\nif not os.path.isdir('data'):\n os.makedirs('data') #if this fails (e.g. permissions) we will get error\nfilename='data' + os.path.sep + '%s_%s' %(expInfo['participant'], expInfo['date'])\nlogFile=logging.LogFile(filename+'.log', level=logging.EXP)\nlogging.console.setLevel(logging.WARNING)#this outputs to the screen, not a file\n\"\"\"\n#setup the Window\nwin = visual.Window(size=(1280, 1024), fullscr=True, screen=0, allowGUI=False, allowStencil=False,\n monitor='testMonitor', color=[0,0,0], colorSpace='rgb')\n\n#Initialise components for routine:trial\ntrialClock=core.Clock()\ntext=visual.TextStim(win=win, ori=0, name='text',\n text='Testing Sounds ',\n font='Arial',\n pos=[0, 0], height=0.1,wrapWidth=None,\n color='white', colorSpace='rgb', opacity=1,\n depth=0.0)\nsound_1=sound.Sound('A',)\nsound_1.setVolume(1)\n\n#set up handler to look after randomisation of conditions etc\ntrials=data.TrialHandler(nReps=10, method='sequential', originPath=None,\n trialList=data.importConditions('test_sounds_bird.xlsx'),\n seed=1)\nthisTrial=trials.trialList[0]#so we can initialise stimuli with some values\n#abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb)\nif thisTrial!=None:\n for paramName in thisTrial.keys():\n exec(paramName+'=thisTrial.'+paramName)\n\nfor thisTrial in trials:\n currentLoop = trials\n #abbrieviate parameter names if possible (e.g. rgb=thisTrial.rgb)\n if thisTrial!=None:\n for paramName in thisTrial.keys():\n exec(paramName+'=thisTrial.'+paramName)\n \n #Start of routine trial\n t=0; trialClock.reset()\n frameN=-1\n \n #update component parameters for each repeat\n sound_1.setSound(sound)\n key_resp = event.BuilderKeyResponse() #create an object of type KeyResponse\n key_resp.status=NOT_STARTED\n #keep track of which have finished\n trialComponents=[]#to keep track of which have finished\n trialComponents.append(text)\n trialComponents.append(sound_1)\n trialComponents.append(key_resp)\n for thisComponent in trialComponents:\n if hasattr(thisComponent,'status'): thisComponent.status = NOT_STARTED\n #start the Routine\n continueRoutine=True\n while continueRoutine:\n #get current time\n t=trialClock.getTime()\n frameN=frameN+1#number of completed frames (so 0 in first frame)\n #update/draw components on each frame\n \n #*text* updates\n if t>=0.0 and text.status==NOT_STARTED:\n #keep track of start time/frame for later\n text.tStart=t#underestimates by a little under one frame\n text.frameNStart=frameN#exact frame index\n text.setAutoDraw(True)\n #start/stop sound_1\n if t>=0.0 and sound_1.status==NOT_STARTED:\n #keep track of start time/frame for later\n sound_1.tStart=t#underestimates by a little under one frame\n sound_1.frameNStart=frameN#exact frame index\n sound_1.play()#start the sound (it finishes automatically)\n \n #*key_resp* updates\n if t>=0.0 and key_resp.status==NOT_STARTED:\n #keep track of start time/frame for later\n key_resp.tStart=t#underestimates by a little under one frame\n key_resp.frameNStart=frameN#exact frame index\n key_resp.status=STARTED\n #keyboard checking is just starting\n key_resp.clock.reset() # now t=0\n event.clearEvents()\n if key_resp.status==STARTED:#only update if being drawn\n theseKeys = event.getKeys(keyList=['space'])\n if len(theseKeys)>0:#at least one key was pressed\n key_resp.keys=theseKeys[-1]#just the last key pressed\n key_resp.rt = key_resp.clock.getTime()\n #abort routine on response\n continueRoutine=False\n \n #check if all components have finished\n if not continueRoutine:\n break # lets a component forceEndRoutine\n continueRoutine=False#will revert to True if at least one component still running\n for thisComponent in trialComponents:\n if hasattr(thisComponent,\"status\") and thisComponent.status!=FINISHED:\n continueRoutine=True; break#at least one component has not yet finished\n \n #check for quit (the [Esc] key)\n if event.getKeys([\"escape\"]): core.quit()\n #refresh the screen\n if continueRoutine:#don't flip if this routine is over or we'll get a blank screen\n win.flip()\n \n #end of routine trial\n for thisComponent in trialComponents:\n if hasattr(thisComponent,\"setAutoDraw\"): thisComponent.setAutoDraw(False)\n #check responses\n if len(key_resp.keys)==0: #No response was made\n key_resp.keys=None\n #store data for trials (TrialHandler)\n trials.addData('key_resp.keys',key_resp.keys)\n if key_resp.keys != None:#we had a response\n trials.addData('key_resp.rt',key_resp.rt)\n\n#completed 10 repeats of 'trials'\n\n#get names of stimulus parameters\nif trials.trialList in ([], [None], None): params=[]\nelse: params = trials.trialList[0].keys()\n#save data for this loop\ntrials.saveAsPickle(filename+'trials')\ntrials.saveAsExcel(filename+'.xlsx', sheetName='trials',\n stimOut=params,\n dataOut=['n','all_mean','all_std', 'all_raw'])\n\n#Shutting down:\nwin.close()\ncore.quit()\n","sub_path":"localXfer/SoundTest_Bird.py","file_name":"SoundTest_Bird.py","file_ext":"py","file_size_in_byte":6689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"59250466","text":"import time\nimport os\nimport numpy\nimport torch\n\nimport nmt.all_constants as ac\nimport nmt.utils as ut\nfrom nmt.model import Model\nimport nmt.configurations as configurations\nfrom nmt.validator import Validator\n\n\nclass Trainer(object):\n \"\"\"Trainer\"\"\"\n def __init__(self, args):\n super(Trainer, self).__init__()\n self.config = configurations.get_config(args.proto, getattr(configurations, args.proto), args.config_overrides)\n self.num_preload = args.num_preload\n self.lr = self.config['lr']\n\n ut.remove_files_in_dir(self.config['save_to'])\n\n self.logger = ut.get_logger(self.config['log_file'])\n\n self.train_smooth_perps = []\n self.train_true_perps = []\n\n # For logging\n self.log_freq = self.config['log_freq'] # log train stat every this-many batches\n self.log_train_loss = []\n self.log_nll_loss = []\n self.log_train_weights = []\n self.log_grad_norms = []\n self.total_batches = 0 # number of batches done for the whole training\n self.epoch_loss = 0. # total train loss for whole epoch\n self.epoch_nll_loss = 0. # total train loss for whole epoch\n self.epoch_weights = 0. # total train weights (# target words) for whole epoch\n self.epoch_time = 0. # total exec time for whole epoch, sounds like that tabloid\n \n # get model\n device = ut.get_device()\n self.model = Model(self.config).to(device)\n self.validator = Validator(self.config, self.model)\n\n self.validate_freq = self.config['validate_freq']\n if self.validate_freq == 1:\n self.logger.info('Evaluate every ' + ('epoch' if self.config['val_per_epoch'] else 'batch'))\n else:\n self.logger.info(f'Evaluate every {self.validate_freq:,} ' + ('epochs' if self.config['val_per_epoch'] else 'batches'))\n\n # Estimated number of batches per epoch\n self.est_batches = max(self.model.data_manager.training_tok_counts) // self.config['batch_size']\n self.logger.info(f'Guessing around {self.est_batches:,} batches per epoch')\n\n\n param_count = sum([numpy.prod(p.size()) for p in self.model.parameters()])\n self.logger.info(f'Model has {int(param_count):,} parameters')\n\n # Set up parameter-specific options\n params = []\n for p in self.model.parameters():\n ptr = p.data_ptr()\n d = {'params': [p]}\n if ptr in self.model.parameter_attrs:\n attrs = self.model.parameter_attrs[ptr]\n for k in attrs:\n d[k] = attrs[k]\n params.append(d)\n \n self.optimizer = torch.optim.Adam(params, lr=self.lr, betas=(self.config['beta1'], self.config['beta2']), eps=self.config['epsilon'])\n\n def report_epoch(self, epoch, batches):\n\n self.logger.info(f'Finished epoch {epoch}')\n self.logger.info(f' Took {ut.format_time(self.epoch_time)}')\n self.logger.info(f' avg words/sec {self.epoch_weights / self.epoch_time:.2f}')\n self.logger.info(f' avg sec/batch {self.epoch_time / batches:.2f}')\n self.logger.info(f' {batches} batches')\n\n if self.epoch_weights:\n train_smooth_perp = self.epoch_loss / self.epoch_weights\n train_true_perp = self.epoch_nll_loss / self.epoch_weights\n else:\n train_smooth_perp = float('inf')\n train_true_perp = float('inf')\n\n self.est_batches = batches\n self.epoch_time = 0.\n self.epoch_nll_loss = 0.\n self.epoch_loss = 0.\n self.epoch_weights = 0.\n self.log_train_loss = []\n self.log_nll_loss = []\n self.log_train_weights = []\n self.log_grad_norms = []\n\n train_smooth_perp = numpy.exp(train_smooth_perp) if train_smooth_perp < 300 else float('inf')\n self.train_smooth_perps.append(train_smooth_perp)\n train_true_perp = numpy.exp(train_true_perp) if train_true_perp < 300 else float('inf')\n self.train_true_perps.append(train_true_perp)\n\n self.logger.info(f' smooth, true perp: {float(train_smooth_perp):.2f}, {float(train_true_perp):.2f}')\n\n\n def clip_grad_values(self):\n \"\"\"\n Adapted from https://pytorch.org/docs/stable/_modules/torch/nn/utils/clip_grad.html#clip_grad_value_\n This is the same as torch.nn.utils.clip_grad_value_, except is also sets nan gradients to 0.0\n \"\"\"\n parameters = self.model.parameters()\n clip_value = float(self.config['grad_clamp'])\n if isinstance(parameters, torch.Tensor):\n parameters = [parameters]\n for p in filter(lambda p: p.grad is not None, parameters):\n p.grad.data.clamp_(min=-clip_value, max=clip_value)\n p.grad.data[torch.isnan(p.grad.data)] = 0.0\n\n def get_params(self, pe=False):\n for n, p in self.model.named_parameters():\n if (n in self.model.struct_params) == pe:\n yield p\n\n def run_log(self, batch, epoch, batch_data):\n #with torch.autograd.detect_anomaly(): # throws exception when any forward computation produces nan\n start = time.time()\n _, src_toks, src_structs, trg_toks, targets = batch_data\n\n # zero grad\n self.optimizer.zero_grad()\n\n # get loss\n ret = self.model(src_toks, src_structs, trg_toks, targets, batch, epoch)\n loss = ret['loss']\n nll_loss = ret['nll_loss']\n\n if self.config['normalize_loss'] == ac.LOSS_TOK:\n opt_loss = loss / (targets != ac.PAD_ID).sum()\n elif self.config['normalize_loss'] == ac.LOSS_BATCH:\n opt_loss = loss / targets.size()[0]\n else:\n opt_loss = loss\n\n opt_loss.backward()\n # clip gradient\n if self.config['grad_clamp']: self.clip_grad_values()\n if self.config['grad_clip_pe']:\n pms = list(self.get_params(True))\n if pms: torch.nn.utils.clip_grad_norm_(pms, self.config['grad_clip_pe'])\n pms = self.get_params()\n else:\n pms = self.model.parameters()\n grad_norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.config['grad_clip']).detach()\n \n # update\n self.adjust_lr()\n self.optimizer.step()\n\n # update training stats\n num_words = (targets != ac.PAD_ID).detach().sum()\n\n loss = loss.detach()\n nll_loss = nll_loss.detach()\n self.total_batches += 1\n self.log_train_loss.append(loss)\n self.log_nll_loss.append(nll_loss)\n self.log_train_weights.append(num_words)\n self.log_grad_norms.append(grad_norm)\n self.epoch_time += time.time() - start\n\n if self.total_batches % self.log_freq == 0:\n \n log_train_loss = torch.tensor(0.0)\n log_nll_loss = torch.tensor(0.0)\n log_train_weights = torch.tensor(0.0)\n log_all_weights = torch.tensor(0.0)\n for smooth, nll, weight in zip(self.log_train_loss, self.log_nll_loss, self.log_train_weights):\n if not self.config['grad_clamp'] or (torch.isfinite(smooth) and torch.isfinite(nll)):\n log_train_loss += smooth\n log_nll_loss += nll\n log_train_weights += weight\n log_all_weights += weight\n #log_train_loss = sum(x for x in self.log_train_loss).item()\n #log_nll_loss = sum(x for x in self.log_nll_loss).item()\n #log_train_weights = sum(x for x in self.log_train_weights).item()\n avg_smooth_perp = log_train_loss / log_train_weights\n avg_smooth_perp = numpy.exp(avg_smooth_perp) if avg_smooth_perp < 300 else float('inf')\n avg_true_perp = log_nll_loss / log_train_weights\n avg_true_perp = numpy.exp(avg_true_perp) if avg_true_perp < 300 else float('inf')\n\n self.epoch_loss += log_train_loss\n self.epoch_nll_loss += log_nll_loss\n self.epoch_weights += log_all_weights\n \n acc_speed_word = self.epoch_weights / self.epoch_time\n acc_speed_time = self.epoch_time / batch\n\n avg_grad_norm = sum(self.log_grad_norms) / len(self.log_grad_norms)\n #median_grad_norm = sorted(self.log_grad_norms)[len(self.log_grad_norms)//2]\n\n est_percent = int(100 * batch / self.est_batches)\n epoch_len = max(5, ut.get_num_digits(self.config['max_epochs']))\n batch_len = max(5, ut.get_num_digits(self.est_batches))\n if batch > self.est_batches: remaining = '?'\n else: remaining = ut.format_time(acc_speed_time * (self.est_batches - batch))\n\n self.log_train_loss = []\n self.log_nll_loss = []\n self.log_train_weights = []\n self.log_grad_norms = []\n cells = [f'{epoch:{epoch_len}}',\n f'{batch:{batch_len}}',\n f'{est_percent:3}%',\n f'{remaining:>9}',\n f'{acc_speed_word:#10.4g}',\n f'{acc_speed_time:#6.4g}s',\n f'{avg_smooth_perp:#11.4g}',\n f'{avg_true_perp:#9.4g}',\n f'{avg_grad_norm:#9.4g}']\n self.logger.info(' '.join(cells))\n\n def adjust_lr(self):\n if self.config['warmup_style'] == ac.ORG_WARMUP:\n step = self.total_batches + 1.0\n if step < self.config['warmup_steps']:\n lr = self.config['embed_dim'] ** (-0.5) * step * self.config['warmup_steps'] ** (-1.5)\n else:\n lr = max(self.config['embed_dim'] ** (-0.5) * step ** (-0.5), self.config['min_lr'])\n for p in self.optimizer.param_groups:\n p['lr'] = lr\n elif self.config['warmup_style'] == ac.FIXED_WARMUP:\n warmup_steps = self.config['warmup_steps']\n step = self.total_batches + 1.0\n start_lr = self.config['start_lr']\n peak_lr = self.config['lr']\n min_lr = self.config['min_lr']\n if step < warmup_steps:\n lr = start_lr + (peak_lr - start_lr) * step / warmup_steps\n else:\n lr = max(min_lr, peak_lr * warmup_steps ** (0.5) * step ** (-0.5))\n for p in self.optimizer.param_groups:\n p['lr'] = lr\n elif self.config['warmup_style'] == ac.UPFLAT_WARMUP:\n warmup_steps = self.config['warmup_steps']\n step = self.total_batches + 1.0\n start_lr = self.config['start_lr']\n peak_lr = self.config['lr']\n min_lr = self.config['min_lr']\n if step < warmup_steps:\n lr = start_lr + (peak_lr - start_lr) * step / warmup_steps\n for p in self.optimizer.param_groups:\n p['lr'] = lr\n else:\n pass\n\n def train(self):\n self.model.train()\n stop_early = False\n \n early_stop_msg_num = self.config['early_stop_patience'] * self.validate_freq\n early_stop_msg_metric = 'epochs' if self.config['val_by_bleu'] else 'batches'\n early_stop_msg = f'No improvement for last {early_stop_msg_num} {early_stop_msg_metric}; stopping early!'\n for epoch in range(1, self.config['max_epochs'] + 1):\n batch = 0\n for batch_data in self.model.data_manager.get_batches(mode=ac.TRAINING, num_preload=self.num_preload):\n if batch == 0:\n self.logger.info(f'Begin epoch {epoch}')\n epoch_str = ' ' * max(0, ut.get_num_digits(self.config['max_epochs']) - 5) + 'epoch'\n batch_str = ' ' * max(0, ut.get_num_digits(self.est_batches) - 5) + 'batch'\n self.logger.info(' '.join([epoch_str, batch_str, 'est%', 'remaining', 'trg word/s', 's/batch', 'smooth perp', 'true perp', 'grad norm']))\n batch += 1\n self.run_log(batch, epoch, batch_data)\n if not self.config['val_per_epoch']:\n stop_early = self.maybe_validate()\n if stop_early:\n self.logger.info(early_stop_msg)\n break\n if stop_early:\n break\n self.report_epoch(epoch, batch)\n if self.config['val_per_epoch'] and epoch % self.validate_freq == 0:\n stop_early = self.maybe_validate(just_validate=True)\n if stop_early:\n self.logger.info(early_stop_msg)\n break\n\n if not self.config['val_by_bleu'] and not stop_early:\n # validate 1 last time\n self.maybe_validate(just_validate=True)\n\n self.logger.info('Training finished')\n self.logger.info('Train smooth perps:')\n self.logger.info(', '.join([f'{x:.2f}' for x in self.train_smooth_perps]))\n self.logger.info('Train true perps:')\n self.logger.info(', '.join([f'{x:.2f}' for x in self.train_true_perps]))\n numpy.save(os.path.join(self.config['save_to'], 'train_smooth_perps.npy'), self.train_smooth_perps)\n numpy.save(os.path.join(self.config['save_to'], 'train_true_perps.npy'), self.train_true_perps)\n\n self.model.save()\n\n # Evaluate test\n test_file = self.model.data_manager.data_files[ac.TESTING][self.model.data_manager.src_lang]\n dev_file = self.model.data_manager.data_files[ac.VALIDATING][self.model.data_manager.src_lang]\n if os.path.exists(test_file):\n self.logger.info('Evaluate test')\n self.restart_to_best_checkpoint()\n self.model.save()\n self.validator.translate(test_file, to_ids=True)\n self.logger.info('Translate dev set')\n self.validator.translate(dev_file, to_ids=True)\n\n def restart_to_best_checkpoint(self):\n if self.config['val_by_bleu']:\n best_bleu = numpy.max(self.validator.best_bleus)\n best_cpkt_path = self.validator.get_cpkt_path(best_bleu)\n else:\n best_perp = numpy.min(self.validator.best_perps)\n best_cpkt_path = self.validator.get_cpkt_path(best_perp)\n\n self.logger.info(f'Restore best cpkt from {best_cpkt_path}')\n self.model.load_state_dict(torch.load(best_cpkt_path))\n\n def is_patience_exhausted(self, patience, if_worst=False):\n '''\n if_worst=False (default) -> check if last patience epochs have failed to improve dev score\n if_worst=True -> check if last epoch was WORSE than the patience epochs before it\n '''\n curve = self.validator.bleu_curve if self.config['val_by_bleu'] else self.validator.perp_curve\n best_worse = max if self.config['val_by_bleu'] is not if_worst else min\n return patience and len(curve) > patience and curve[-1 if if_worst else -1-patience] == best_worse(curve[-1-patience:])\n\n def maybe_validate(self, just_validate=False):\n if self.total_batches % self.validate_freq == 0 or just_validate:\n self.model.save()\n self.validator.validate_and_save()\n\n # if doing annealing\n step = self.total_batches + 1.0\n warmup_steps = self.config['warmup_steps']\n\n if self.config['warmup_style'] == ac.NO_WARMUP \\\n or (self.config['warmup_style'] == ac.UPFLAT_WARMUP and step >= warmup_steps) \\\n and self.config['lr_decay'] > 0:\n\n if self.is_patience_exhausted(self.config['lr_decay_patience'], if_worst=True):\n if self.config['val_by_bleu']:\n metric = 'bleu'\n scores = self.validator.bleu_curve\n else:\n metric = 'perp'\n scores = self.validator.perp_curve\n scores = ', '.join([str(x) for x in scores[-1 - self.config['lr_decay_patience']:]])\n\n self.logger.info(f'Past {metric} scores are {scores}')\n # when don't use warmup, decay lr if dev not improve\n if self.lr * self.config['lr_decay'] >= self.config['min_lr']:\n new_lr = self.lr * self.config['lr_decay']\n self.logger.info(f'Anneal the learning rate from {self.lr} to {new_lr}')\n self.lr = new_lr\n for p in self.optimizer.param_groups:\n p['lr'] = self.lr\n return self.is_patience_exhausted(self.config['early_stop_patience'])\n","sub_path":"nmt/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":16540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"499759522","text":"import sqlite3\r\nimport io\r\n\r\nclass BancoDeDados:\r\n def __init__(self):\r\n ##conectando ao banco\r\n self.conn = sqlite3.connect('CryptoCoins.db')\r\n #cursor que executará os comandos sql\r\n self.cursor = self.conn.cursor()\r\n \r\n def criar(self):\r\n #criando a tabela Historico\r\n self.cursor.execute(\"\"\"\r\n CREATE TABLE IF NOT EXISTS historico(\r\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n day TEXT NOT NULL,\r\n coin TEXT NOT NULL,\r\n amount REAL NOT NULL);\"\"\")\r\n\r\n self.cursor.execute(\"\"\"\r\n CREATE TABLE IF NOT EXISTS market(\r\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n coin TEXT NOT NULL,\r\n last REAL NOT NULL,\r\n lowestAsk REAL NOT NULL,\r\n highestBid REAL NOT NULL,\r\n high24hr REAL NOT NULL,\r\n low24hr REAL NOT NULL,\r\n volume REAL NOT NULL,\r\n day TEXT NOT NULL);\"\"\") \r\n print('Tabelas com sucesso!')\r\n\r\n #inserir dados na tabela\r\n def insert(self, *args):#moeda, valor\r\n pass\r\n\t\t\r\n #visualizar dados da tabela\r\n def select(self,*args):\r\n pass\r\n\r\n def __backup(self):\r\n with io.open('CryptoCoins_Backup.sql','w') as bkp:\r\n #(iterdump)exporta a estrutura do banco e os dados para um arquivo externo\r\n for linha in self.conn.iterdump():\r\n bkp.write('%s\\n' % linha)\r\n print('Backup realizado com sucesso!')\r\n print('Salvo no diretório atual como CryptoCoins_Backup.sql')\r\n\r\n def __restoreBackup(self):\r\n self.rest = io.open('CryptoCoins_Backup.sql','r')\r\n self.sql = self.rest.read()\r\n self.cursor.executescript(self.sql)\r\n print('Banco de Dados recuperado com sucesso!')\r\n \r\n","sub_path":"DataBase.py","file_name":"DataBase.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"366530432","text":"import tkinter as tk\n\ntoor = tk.Tk()\n \ndef func(event):\n print(\"You hit return.\")\n entrytext=entry.get()\n while entrytext==\"\":\n super() #random piece of code that does not work but gets the job done\n open('participant.txt','w').write(entry.get())\n toor.destroy()\ntoor.bind('', func)\n\ndef onclick():\n print(\"You clicked the button\")\n entrytext=entry.get()\n while entrytext==\"\":\n super() #random piece of code that does not work but gets the job done\n open('participant.txt','w').write(entry.get())\n toor.destroy()\n\nlabel = tk.Label(toor, text=\"Enter participant number:\", font=(\"Verdana\", 25))\nlabel.pack(pady=10,padx=10)\n\nentry = tk.Entry(toor)\nentry.pack()\nbutton = tk.Button(toor,text='submit',command=onclick)\nbutton.pack()\n\nwindowWidth = toor.winfo_reqwidth()\nwindowHeight = toor.winfo_reqheight()\n \n# Gets both half the screen width/height and window width/height\npositionRight = int(toor.winfo_screenwidth()/2 - windowWidth/2)\npositionDown = int(toor.winfo_screenheight()/2 - windowHeight/2)\n\ntoor.title(\"Enter Participant Number\")\ntoor.geometry(\"+{}+{}\".format(positionRight, positionDown))\ntoor.mainloop()\n","sub_path":"MelodyRepetitionTask/getinput.py","file_name":"getinput.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"385057462","text":"from matplotlib.widgets import Slider, RadioButtons\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\n\nx_val = 90\ny_val = 90\nz_val = 90\n\nLINK_1 = 60\nLINK_2 = 120\nLINK_3 = 110\n\n\nfig = plt.figure(\"FK\")\nax = plt.axes([0.05, 0.2, 0.90, 0.75], projection=\"3d\")\naxe = plt.axes([0.25, 0.85, 0.001, 0.001])\n\naxxval = plt.axes([0.35, 0.1, 0.45, 0.03])\na0_val = Slider(axxval, \"Theta 1\", 0, 180, valinit=x_val)\n\naxyval = plt.axes([0.35, 0.0575, 0.45, 0.03])\na1_val = Slider(axyval, \"Theta 2\", 0, 180, valinit=y_val)\n\naxzval = plt.axes([0.35, 0.015, 0.45, 0.03])\na2_val = Slider(axzval, \"Theta 3\", 0, 180, valinit=z_val)\n\n\n\ndef getFKFrame(theta_1, theta_2, theta_3):\n T01 = np.array(\n [\n [ math.cos(theta_1), -math.sin(theta_1), 0, 0], \n [ math.sin(theta_1), math.cos(theta_1), 0, 0 ], \n [ 0, 0, 1, 0], \n [ 0, 0, 0, 1]\n ] \n )\n\n T02 = np.array(\n [\n [math.cos(theta_2), -math.sin(theta_2), 0, LINK_1],\n [0, 0, -1, 0],\n [math.sin(theta_2), math.cos(theta_2), 0, 0],\n [0, 0, 0, 1]\n ]\n )\n\n T03 = np.array(\n [\n [math.cos(theta_3), -math.sin(theta_3), 0, LINK_2],\n [math.sin(theta_3), math.cos(theta_3), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ]\n )\n\n T04 = np.array(\n [\n [1, 0, 0, LINK_3],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ]\n )\n\n T10 = np.dot(T01, T02)\n T20 = np.dot(T10, T03)\n T30 = np.dot(T20, T04)\n\n return [T10, T20, T30]\n \n\ndef plotFrame( theta_1, theta_2, theta_3, pltObj ):\n frame = ( getFKFrame(\n np.radians(theta_1), \n np.radians(theta_2 ), \n np.radians(theta_3 )) )\n print(frame[2][0][3], frame[2][1][3], frame[2][2][3])\n pltObj.cla() \n pltObj.plot( \n [0, frame[0][0][3], frame[1][0][3],frame[2][0][3]], \n [0, frame[0][1][3], frame[1][1][3],frame[2][1][3]], \n [0, frame[0][2][3], frame[1][2][3],frame[2][2][3]], \n \"o-\", \n markerSize=5, \n markerFacecolor=\"orange\", \n linewidth=5, \n color=\"blue\" \n )\n \n pltObj.set_xlim3d(-200, 200)\n pltObj.set_ylim3d(-200, 200)\n pltObj.set_zlim3d(-100, 200)\n pltObj.set_xlabel(\"X-axis\")\n pltObj.set_ylabel(\"Y-axis\")\n pltObj.set_zlabel(\"Z-axis\")\n pltObj.set_axisbelow(True)\n\ndef update_a0_val(val):\n global x_val , y_val, z_val\n x_val = val\n plotFrame(x_val, y_val, z_val, ax)\n\ndef update_a1_val(val):\n global x_val, y_val, z_val\n y_val = val\n plotFrame(x_val, y_val, z_val, ax)\n\ndef update_a2_val(val):\n global x_val, y_val, z_val\n z_val = val\n plotFrame(x_val, y_val, z_val, ax)\n\n\na0_val.on_changed( update_a0_val )\na1_val.on_changed( update_a1_val )\na2_val.on_changed( update_a2_val )\n\n\nplotFrame(x_val, y_val, z_val, ax)\nplt.show()\n\n\n\n\n","sub_path":"FK.py","file_name":"FK.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"507191628","text":"import argparse\r\nimport json\r\n\r\nfrom torch.utils.data import DataLoader\r\nimport cv2\r\nfrom models import *\r\nfrom utils.datasets import *\r\nfrom utils.utils import *\r\nfrom torchvision import transforms\r\nfrom matplotlib import pyplot as plt\r\nfrom torch.autograd import Variable\r\nimport time\r\ntransform = transforms.ToTensor()\r\n\r\ndef test(cfg,\r\n data,\r\n weights=None,\r\n batch_size=16,\r\n imgsz=416,\r\n conf_thres=0.001,\r\n iou_thres=0.6, # for nms\r\n save_json=False,\r\n single_cls=False,\r\n augment=False,\r\n model=None,\r\n dataloader=None,\r\n multi_label=True):\r\n # Initialize/load model and set device\r\n if model is None:\r\n is_training = False\r\n device = torch_utils.select_device(opt.device, batch_size=batch_size)\r\n verbose = opt.task == 'test'\r\n\r\n model = Darknet(cfg, imgsz, verbose=True)\r\n\r\n print('model -->', model)\r\n\r\n if weights.endswith('.pt'): # pytorch format\r\n model.load_state_dict(torch.load(weights, map_location=device)['model'])\r\n\r\n # model.fuse()\r\n model.to(device)\r\n model.eval()\r\n\r\n Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor\r\n\r\n image = cv2.imread('./dog.jpg',cv2.IMREAD_COLOR)\r\n image = cv2.resize(image, (int(imgsz),int(imgsz)), interpolation=cv2.INTER_AREA) \r\n source_image = image.copy()\r\n # image = image.astype(np.float32)\r\n image = image / 255.0 \r\n image = transform(image)\r\n image = image.unsqueeze(0) \r\n image = image.to(device)\r\n image = Variable(image.type(Tensor), requires_grad=False)\r\n print('image size :', image.size(), ':', image.dtype)\r\n\r\n\r\n with torch.no_grad():\r\n # inf_out, train_out = model(torch.zeros((1, 3, imgsz, imgsz), device=device), verbose=True) \r\n start_time = time.time()\r\n \r\n inf_out, train_out = model(image, verbose=True)\r\n print('use time :', (time.time() - start_time))\r\n print('inf out size :', inf_out.size())\r\n print('train out size :', train_out[0].size(), train_out[1].size())\r\n\r\n print('out class :', inf_out.size())\r\n output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, multi_label=multi_label)\r\n # output = np.array(output[0])\r\n # print('out put:', output.shape)\r\n\r\n for si, pred in enumerate(output):\r\n clip_coords(pred, (imgsz, imgsz))\r\n boxes = pred[:, :4].clone().tolist()\r\n score = pred[:,4].clone().tolist()\r\n classID = pred[:,5].clone().tolist()\r\n\r\n for bitem in boxes:\r\n x0,y0,x1,y1 = bitem\r\n x0 = int(x0)\r\n y0 = int(y0)\r\n x1 = int(x1)\r\n y1 = int(y1)\r\n cv2.rectangle(source_image, (x0,y0), (x1, y1), (0, 255, 0), 5) \r\n\r\n print(f'si {si} --->', boxes, ' scores: ', score, 'classID :', classID)\r\n\r\n plt.imshow(source_image)\r\n plt.show()\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(prog='test.py')\r\n parser.add_argument('--cfg', type=str, default='cfg/yolov3-tiny-old.cfg', help='*.cfg path')\r\n parser.add_argument('--data', type=str, default='data/coco2014.data', help='*.data path')\r\n parser.add_argument('--weights', type=str, default=r'D:\\PROJECT_TW\\git\\data\\qrdetect\\weights\\yolov3-tiny.pt', help='weights path')\r\n parser.add_argument('--batch-size', type=int, default=16, help='size of each image batch')\r\n parser.add_argument('--img-size', type=int, default=416, help='inference size (pixels)')\r\n parser.add_argument('--conf-thres', type=float, default=0.5, help='object confidence threshold')\r\n parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS')\r\n parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')\r\n parser.add_argument('--task', default='test', help=\"'test', 'study', 'benchmark'\")\r\n parser.add_argument('--device', default='cpu', help='device id (i.e. 0 or 0,1) or cpu')\r\n parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')\r\n parser.add_argument('--augment', action='store_true', help='augmented inference')\r\n opt = parser.parse_args()\r\n # opt.save_json = opt.save_json or any([x in opt.data for x in ['coco.data', 'coco2014.data', 'coco2017.data']])\r\n opt.cfg = check_file(opt.cfg) # check file\r\n # opt.data = check_file(opt.data) # check file\r\n print(opt)\r\n\r\n\r\n test(opt.cfg,\r\n opt.data,\r\n opt.weights,\r\n opt.batch_size,\r\n opt.img_size,\r\n opt.conf_thres,\r\n opt.iou_thres,\r\n opt.save_json,\r\n opt.single_cls,\r\n opt.augment)","sub_path":"object detect/lib/yolo/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"549053206","text":"import numpy as np\nimport astropy.io.fits as pyfits\nimport astropy.wcs as pywcs\nimport os\nfrom soxs.utils import mylog, parse_value, get_rot_mat, \\\n downsample\nfrom soxs.instrument_registry import instrument_registry\nfrom tqdm import tqdm\n\n\ndef wcs_from_event_file(f):\n h = f[\"EVENTS\"].header\n w = pywcs.WCS(naxis=2)\n w.wcs.crval = [h[\"TCRVL2\"], h[\"TCRVL3\"]]\n w.wcs.crpix = [h[\"TCRPX2\"], h[\"TCRPX3\"]]\n w.wcs.cdelt = [h[\"TCDLT2\"], h[\"TCDLT3\"]]\n w.wcs.ctype = [h[\"TCTYP2\"], h[\"TCTYP3\"]]\n w.wcs.cunit = [h[\"TCUNI2\"], h[\"TCUNI3\"]]\n return w\n\n\ndef write_event_file(events, parameters, filename, overwrite=False):\n from astropy.time import Time, TimeDelta\n mylog.info(\"Writing events to file %s.\" % filename)\n\n t_begin = Time.now()\n dt = TimeDelta(parameters[\"exposure_time\"], format='sec')\n t_end = t_begin + dt\n\n col_x = pyfits.Column(name='X', format='D', unit='pixel', array=events[\"xpix\"])\n col_y = pyfits.Column(name='Y', format='D', unit='pixel', array=events[\"ypix\"])\n col_e = pyfits.Column(name='ENERGY', format='E', unit='eV', array=events[\"energy\"]*1000.)\n col_dx = pyfits.Column(name='DETX', format='D', unit='pixel', array=events[\"detx\"])\n col_dy = pyfits.Column(name='DETY', format='D', unit='pixel', array=events[\"dety\"])\n col_id = pyfits.Column(name='CCD_ID', format='D', unit='pixel', array=events[\"ccd_id\"])\n\n chantype = parameters[\"channel_type\"]\n if chantype == \"PHA\":\n cunit = \"adu\"\n elif chantype == \"PI\":\n cunit = \"Chan\"\n col_ch = pyfits.Column(name=chantype.upper(), format='1J', unit=cunit, array=events[chantype])\n\n col_t = pyfits.Column(name=\"TIME\", format='1D', unit='s', array=events['time'])\n\n cols = [col_e, col_x, col_y, col_ch, col_t, col_dx, col_dy, col_id]\n\n coldefs = pyfits.ColDefs(cols)\n tbhdu = pyfits.BinTableHDU.from_columns(coldefs)\n tbhdu.name = \"EVENTS\"\n\n tbhdu.header[\"MTYPE1\"] = \"sky\"\n tbhdu.header[\"MFORM1\"] = \"x,y\"\n tbhdu.header[\"MTYPE2\"] = \"EQPOS\"\n tbhdu.header[\"MFORM2\"] = \"RA,DEC\"\n tbhdu.header[\"TCTYP2\"] = \"RA---TAN\"\n tbhdu.header[\"TCTYP3\"] = \"DEC--TAN\"\n tbhdu.header[\"TCRVL2\"] = parameters[\"sky_center\"][0]\n tbhdu.header[\"TCRVL3\"] = parameters[\"sky_center\"][1]\n tbhdu.header[\"TCDLT2\"] = -parameters[\"plate_scale\"]\n tbhdu.header[\"TCDLT3\"] = parameters[\"plate_scale\"]\n tbhdu.header[\"TCRPX2\"] = parameters[\"pix_center\"][0]\n tbhdu.header[\"TCRPX3\"] = parameters[\"pix_center\"][1]\n tbhdu.header[\"TCUNI2\"] = \"deg\"\n tbhdu.header[\"TCUNI3\"] = \"deg\"\n tbhdu.header[\"TLMIN2\"] = 0.5\n tbhdu.header[\"TLMIN3\"] = 0.5\n tbhdu.header[\"TLMAX2\"] = 2.0*parameters[\"num_pixels\"]+0.5\n tbhdu.header[\"TLMAX3\"] = 2.0*parameters[\"num_pixels\"]+0.5\n tbhdu.header[\"TLMIN4\"] = parameters[\"chan_lim\"][0]\n tbhdu.header[\"TLMAX4\"] = parameters[\"chan_lim\"][1]\n tbhdu.header[\"TLMIN6\"] = -0.5*parameters[\"num_pixels\"]\n tbhdu.header[\"TLMAX6\"] = 0.5*parameters[\"num_pixels\"]\n tbhdu.header[\"TLMIN7\"] = -0.5*parameters[\"num_pixels\"]\n tbhdu.header[\"TLMAX7\"] = 0.5*parameters[\"num_pixels\"]\n tbhdu.header[\"EXPOSURE\"] = parameters[\"exposure_time\"]\n tbhdu.header[\"TSTART\"] = 0.0\n tbhdu.header[\"TSTOP\"] = parameters[\"exposure_time\"]\n tbhdu.header[\"HDUVERS\"] = \"1.1.0\"\n tbhdu.header[\"RADECSYS\"] = \"FK5\"\n tbhdu.header[\"EQUINOX\"] = 2000.0\n tbhdu.header[\"HDUCLASS\"] = \"OGIP\"\n tbhdu.header[\"HDUCLAS1\"] = \"EVENTS\"\n tbhdu.header[\"HDUCLAS2\"] = \"ACCEPTED\"\n tbhdu.header[\"DATE\"] = t_begin.tt.isot\n tbhdu.header[\"DATE-OBS\"] = t_begin.tt.isot\n tbhdu.header[\"DATE-END\"] = t_end.tt.isot\n tbhdu.header[\"RESPFILE\"] = os.path.split(parameters[\"rmf\"])[-1]\n tbhdu.header[\"PHA_BINS\"] = parameters[\"nchan\"]\n tbhdu.header[\"ANCRFILE\"] = os.path.split(parameters[\"arf\"])[-1]\n tbhdu.header[\"CHANTYPE\"] = parameters[\"channel_type\"]\n tbhdu.header[\"MISSION\"] = parameters[\"mission\"]\n tbhdu.header[\"TELESCOP\"] = parameters[\"telescope\"]\n tbhdu.header[\"INSTRUME\"] = parameters[\"instrument\"]\n tbhdu.header[\"RA_PNT\"] = parameters[\"sky_center\"][0]\n tbhdu.header[\"DEC_PNT\"] = parameters[\"sky_center\"][1]\n tbhdu.header[\"ROLL_PNT\"] = parameters[\"roll_angle\"]\n tbhdu.header[\"AIMPT_X\"] = parameters[\"aimpt_coords\"][0]\n tbhdu.header[\"AIMPT_Y\"] = parameters[\"aimpt_coords\"][1]\n if parameters[\"dither_params\"][\"dither_on\"]:\n tbhdu.header[\"DITHXAMP\"] = parameters[\"dither_params\"][\"x_amp\"]\n tbhdu.header[\"DITHYAMP\"] = parameters[\"dither_params\"][\"y_amp\"]\n tbhdu.header[\"DITHXPER\"] = parameters[\"dither_params\"][\"x_period\"]\n tbhdu.header[\"DITHYPER\"] = parameters[\"dither_params\"][\"y_period\"]\n\n start = pyfits.Column(name='START', format='1D', unit='s',\n array=np.array([0.0]))\n stop = pyfits.Column(name='STOP', format='1D', unit='s',\n array=np.array([parameters[\"exposure_time\"]]))\n\n tbhdu_gti = pyfits.BinTableHDU.from_columns([start,stop])\n tbhdu_gti.name = \"STDGTI\"\n tbhdu_gti.header[\"TSTART\"] = 0.0\n tbhdu_gti.header[\"TSTOP\"] = parameters[\"exposure_time\"]\n tbhdu_gti.header[\"HDUCLASS\"] = \"OGIP\"\n tbhdu_gti.header[\"HDUCLAS1\"] = \"GTI\"\n tbhdu_gti.header[\"HDUCLAS2\"] = \"STANDARD\"\n tbhdu_gti.header[\"RADECSYS\"] = \"FK5\"\n tbhdu_gti.header[\"EQUINOX\"] = 2000.0\n tbhdu_gti.header[\"DATE\"] = t_begin.tt.isot\n tbhdu_gti.header[\"DATE-OBS\"] = t_begin.tt.isot\n tbhdu_gti.header[\"DATE-END\"] = t_end.tt.isot\n\n hdulist = [pyfits.PrimaryHDU(), tbhdu, tbhdu_gti]\n\n pyfits.HDUList(hdulist).writeto(filename, overwrite=overwrite)\n\n\ndef parse_region_args(rtype, args, dx, dy):\n if rtype == \"Box\":\n xctr, yctr, xw, yw = args\n new_args = [xctr + dx, yctr + dy, xw, yw]\n elif rtype == \"Circle\":\n xctr, yctr, radius = args\n new_args = [xctr + dx, yctr + dx, radius]\n elif rtype == \"Polygon\":\n new_args = [[x + dx for x in args[0]],\n [y + dy for y in args[1]]]\n else:\n raise NotImplementedError\n return new_args\n\n\ndef make_exposure_map(event_file, expmap_file, energy, weights=None,\n asol_file=None, normalize=True, overwrite=False,\n reblock=1, nhistx=16, nhisty=16, order=1):\n \"\"\"\n Make an exposure map for a SOXS event file, and optionally write\n an aspect solution file. The exposure map will be created by\n binning an aspect histogram over the range of the aspect solution.\n\n Parameters\n ----------\n event_file : string\n The path to the event file to use for making the exposure map.\n expmap_file : string\n The path to write the exposure map file to.\n energy : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, or NumPy array\n The energy in keV to use when computing the exposure map, or \n a set of energies to be used with the *weights* parameter. If\n providing a set, it must be in keV.\n weights : array-like, optional\n The weights to use with a set of energies given in the\n *energy* parameter. Used to create a more accurate exposure\n map weighted by a range of energies. Default: None\n asol_file : string, optional\n The path to write the aspect solution file to, if desired.\n Default: None\n normalize : boolean, optional\n If True, the exposure map will be divided by the exposure time\n so that the map's units are cm**2. Default: True\n overwrite : boolean, optional\n Whether or not to overwrite an existing file. Default: False\n reblock : integer, optional\n Supply an integer power of 2 here to make an exposure map \n with a different binning. Default: 1\n nhistx : integer, optional\n The number of bins in the aspect histogram in the DETX\n direction. Default: 16\n nhisty : integer, optional\n The number of bins in the aspect histogram in the DETY\n direction. Default: 16\n order : integer, optional\n The interpolation order to use when making the exposure map. \n Default: 1\n \"\"\"\n import pyregion._region_filter as rfilter\n from scipy.ndimage.interpolation import rotate, shift\n from soxs.instrument import AuxiliaryResponseFile, perform_dither\n if isinstance(energy, np.ndarray) and weights is None:\n raise RuntimeError(\"Must supply a single value for the energy if \"\n \"you do not supply weights!\")\n if not isinstance(energy, np.ndarray):\n energy = parse_value(energy, \"keV\")\n f_evt = pyfits.open(event_file)\n hdu = f_evt[\"EVENTS\"]\n arf = AuxiliaryResponseFile(hdu.header[\"ANCRFILE\"])\n exp_time = hdu.header[\"EXPOSURE\"]\n nx = int(hdu.header[\"TLMAX2\"]-0.5)//2\n ny = int(hdu.header[\"TLMAX3\"]-0.5)//2\n ra0 = hdu.header[\"TCRVL2\"]\n dec0 = hdu.header[\"TCRVL3\"]\n xdel = hdu.header[\"TCDLT2\"]\n ydel = hdu.header[\"TCDLT3\"]\n x0 = hdu.header[\"TCRPX2\"]\n y0 = hdu.header[\"TCRPX3\"]\n xdet0 = 0.5*(2*nx+1)\n ydet0 = 0.5*(2*ny+1)\n xaim = hdu.header.get(\"AIMPT_X\", 0.0)\n yaim = hdu.header.get(\"AIMPT_Y\", 0.0)\n roll = hdu.header[\"ROLL_PNT\"]\n instr = instrument_registry[hdu.header[\"INSTRUME\"].lower()]\n dither_params = {}\n if \"DITHXAMP\" in hdu.header:\n dither_params[\"x_amp\"] = hdu.header[\"DITHXAMP\"]\n dither_params[\"y_amp\"] = hdu.header[\"DITHYAMP\"]\n dither_params[\"x_period\"] = hdu.header[\"DITHXPER\"]\n dither_params[\"y_period\"] = hdu.header[\"DITHYPER\"]\n dither_params[\"plate_scale\"] = ydel*3600.0\n dither_params[\"dither_on\"] = True\n else:\n dither_params[\"dither_on\"] = False\n f_evt.close()\n\n # Create time array for aspect solution\n dt = 1.0 # Seconds\n t = np.arange(0.0, exp_time+dt, dt)\n\n # Construct WCS\n w = pywcs.WCS(naxis=2)\n w.wcs.crval = [ra0, dec0]\n w.wcs.crpix = [x0, y0]\n w.wcs.cdelt = [xdel, ydel]\n w.wcs.ctype = [\"RA---TAN\",\"DEC--TAN\"]\n w.wcs.cunit = [\"deg\"]*2\n\n # Create aspect solution if we had dithering.\n # otherwise just set the offsets to zero\n if dither_params[\"dither_on\"]:\n x_off, y_off = perform_dither(t, dither_params)\n # Make the aspect histogram\n x_amp = dither_params[\"x_amp\"]/dither_params[\"plate_scale\"]\n y_amp = dither_params[\"y_amp\"]/dither_params[\"plate_scale\"]\n x_edges = np.linspace(-x_amp, x_amp, nhistx+1, endpoint=True)\n y_edges = np.linspace(-y_amp, y_amp, nhisty+1, endpoint=True)\n asphist = np.histogram2d(x_off, y_off, (x_edges, y_edges))[0]\n asphist *= dt\n x_mid = 0.5*(x_edges[1:]+x_edges[:-1])/reblock\n y_mid = 0.5*(y_edges[1:]+y_edges[:-1])/reblock\n\n # Determine the effective area\n eff_area = arf.interpolate_area(energy).value\n if weights is not None:\n eff_area = np.average(eff_area, weights=weights)\n\n if instr[\"chips\"] is None:\n rtypes = [\"Box\"]\n args = [[0.0, 0.0, instr[\"num_pixels\"], instr[\"num_pixels\"]]]\n else:\n rtypes = []\n args = []\n for i, chip in enumerate(instr[\"chips\"]):\n rtypes.append(chip[0])\n args.append(np.array(chip[1:]))\n\n tmpmap = np.zeros((2*nx, 2*ny))\n\n for rtype, arg in zip(rtypes, args):\n rfunc = getattr(rfilter, rtype)\n new_args = parse_region_args(rtype, arg, xdet0-xaim-1.0, ydet0-yaim-1.0)\n r = rfunc(*new_args)\n tmpmap += r.mask(tmpmap).astype(\"float64\")\n\n tmpmap = downsample(tmpmap, reblock)\n\n if dither_params[\"dither_on\"]:\n expmap = np.zeros(tmpmap.shape)\n niter = nhistx*nhisty\n pbar = tqdm(leave=True, total=niter, desc=\"Creating exposure map \")\n for i in range(nhistx):\n for j in range(nhisty):\n expmap += shift(tmpmap, (x_mid[i], y_mid[j]), order=order)*asphist[i, j]\n pbar.update(nhisty)\n pbar.close()\n else:\n expmap = tmpmap*exp_time\n\n expmap *= eff_area\n if normalize:\n expmap /= exp_time\n\n if roll != 0.0:\n rotate(expmap, roll, output=expmap, reshape=False)\n\n expmap[expmap < 0.0] = 0.0\n\n map_header = {\"EXPOSURE\": exp_time,\n \"MTYPE1\": \"EQPOS\",\n \"MFORM1\": \"RA,DEC\",\n \"CTYPE1\": \"RA---TAN\",\n \"CTYPE2\": \"DEC--TAN\",\n \"CRVAL1\": ra0,\n \"CRVAL2\": dec0,\n \"CUNIT1\": \"deg\",\n \"CUNIT2\": \"deg\",\n \"CDELT1\": xdel*reblock,\n \"CDELT2\": ydel*reblock,\n \"CRPIX1\": 0.5*(2.0*nx//reblock+1),\n \"CRPIX2\": 0.5*(2.0*ny//reblock+1)}\n\n map_hdu = pyfits.ImageHDU(expmap, header=pyfits.Header(map_header))\n map_hdu.name = \"EXPMAP\"\n map_hdu.writeto(expmap_file, overwrite=overwrite)\n\n if asol_file is not None:\n\n if dither_params[\"dither_on\"]:\n\n det = np.array([x_off, y_off])\n\n pix = np.dot(get_rot_mat(roll).T, det)\n\n ra, dec = w.wcs_pix2world(pix[0,:]+x0, pix[1,:]+y0, 1)\n\n col_t = pyfits.Column(name='time', format='D', unit='s', array=t)\n col_ra = pyfits.Column(name='ra', format='D', unit='deg', array=ra)\n col_dec = pyfits.Column(name='dec', format='D', unit='deg', array=dec)\n\n coldefs = pyfits.ColDefs([col_t, col_ra, col_dec])\n tbhdu = pyfits.BinTableHDU.from_columns(coldefs)\n tbhdu.name = \"ASPSOL\"\n tbhdu.header[\"EXPOSURE\"] = exp_time\n\n hdulist = [pyfits.PrimaryHDU(), tbhdu]\n\n pyfits.HDUList(hdulist).writeto(asol_file, overwrite=overwrite)\n\n else:\n\n mylog.warning(\"Refusing to write an aspect solution file because \"\n \"there was no dithering.\")\n\n\ndef _write_spectrum(bins, spec, exp_time, spectype, parameters,\n specfile, overwrite=False):\n\n col1 = pyfits.Column(name='CHANNEL', format='1J', array=bins)\n col2 = pyfits.Column(name=spectype.upper(), format='1D', array=bins.astype(\"float64\"))\n col3 = pyfits.Column(name='COUNTS', format='1J', array=spec.astype(\"int32\"))\n col4 = pyfits.Column(name='COUNT_RATE', format='1D', array=spec/exp_time)\n\n coldefs = pyfits.ColDefs([col1, col2, col3, col4])\n\n tbhdu = pyfits.BinTableHDU.from_columns(coldefs)\n tbhdu.name = \"SPECTRUM\"\n\n tbhdu.header[\"DETCHANS\"] = spec.size\n tbhdu.header[\"TOTCTS\"] = spec.sum()\n tbhdu.header[\"EXPOSURE\"] = exp_time\n tbhdu.header[\"LIVETIME\"] = exp_time\n tbhdu.header[\"CONTENT\"] = spectype\n tbhdu.header[\"HDUCLASS\"] = \"OGIP\"\n tbhdu.header[\"HDUCLAS1\"] = \"SPECTRUM\"\n tbhdu.header[\"HDUCLAS2\"] = \"TOTAL\"\n tbhdu.header[\"HDUCLAS3\"] = \"TYPE:I\"\n tbhdu.header[\"HDUCLAS4\"] = \"COUNT\"\n tbhdu.header[\"HDUVERS\"] = \"1.1.0\"\n tbhdu.header[\"HDUVERS1\"] = \"1.1.0\"\n tbhdu.header[\"CHANTYPE\"] = spectype\n tbhdu.header[\"BACKFILE\"] = \"none\"\n tbhdu.header[\"CORRFILE\"] = \"none\"\n tbhdu.header[\"POISSERR\"] = True\n for key in [\"RESPFILE\", \"ANCRFILE\", \"MISSION\", \"TELESCOP\", \"INSTRUME\"]:\n tbhdu.header[key] = parameters[key]\n tbhdu.header[\"AREASCAL\"] = 1.0\n tbhdu.header[\"CORRSCAL\"] = 0.0\n tbhdu.header[\"BACKSCAL\"] = 1.0\n\n hdulist = pyfits.HDUList([pyfits.PrimaryHDU(), tbhdu])\n\n hdulist.writeto(specfile, overwrite=overwrite)\n\n\ndef write_spectrum(evtfile, specfile, overwrite=False):\n r\"\"\"\n Bin event energies into a spectrum and write it to \n a FITS binary table. Does not do any grouping of \n channels, and will automatically determine PI or PHA. \n\n Parameters\n ----------\n evtfile : string\n The name of the event file to read the events from. \n specfile : string\n The name of the spectrum file to be written.\n overwrite : boolean, optional\n Whether or not to overwrite an existing file with \n the same name. Default: False\n \"\"\"\n from soxs.instrument import RedistributionMatrixFile\n parameters = {}\n if isinstance(evtfile, str):\n f = pyfits.open(evtfile)\n spectype = f[\"EVENTS\"].header[\"CHANTYPE\"]\n rmf = f[\"EVENTS\"].header[\"RESPFILE\"]\n p = f[\"EVENTS\"].data[spectype]\n exp_time = f[\"EVENTS\"].header[\"EXPOSURE\"]\n for key in [\"RESPFILE\", \"ANCRFILE\", \"MISSION\", \"TELESCOP\", \"INSTRUME\"]:\n parameters[key] = f[\"EVENTS\"].header[key]\n f.close()\n else:\n rmf = evtfile[\"rmf\"]\n spectype = evtfile[\"channel_type\"]\n p = evtfile[spectype]\n parameters[\"RESPFILE\"] = os.path.split(rmf)[-1]\n parameters[\"ANCRFILE\"] = os.path.split(evtfile[\"arf\"])[-1]\n parameters[\"TELESCOP\"] = evtfile[\"telescope\"] \n parameters[\"INSTRUME\"] = evtfile[\"instrument\"]\n parameters[\"MISSION\"] = evtfile[\"mission\"] \n exp_time = evtfile[\"exposure_time\"]\n\n rmf = RedistributionMatrixFile(rmf)\n minlength = rmf.n_ch\n if rmf.cmin == 1:\n minlength += 1\n spec = np.bincount(p, minlength=minlength)\n if rmf.cmin == 1:\n spec = spec[1:]\n bins = (np.arange(rmf.n_ch)+rmf.cmin).astype(\"int32\")\n\n _write_spectrum(bins, spec, exp_time, spectype, parameters,\n specfile, overwrite=overwrite)\n\n\ndef write_radial_profile(evt_file, out_file, ctr, rmin,\n rmax, nbins, ctr_type=\"celestial\",\n emin=None, emax=None, expmap_file=None,\n overwrite=False):\n r\"\"\"\n Bin up events into a radial profile and write them to a FITS\n table. \n\n Parameters\n ----------\n evt_file : string\n Input event file.\n out_file : string\n The output file to write the profile to. \n ctr : array-like\n The central coordinate of the profile. Can either be in \n celestial coordinates (the default) or \"physical\" pixel \n coordinates. If the former, the ``ctr_type`` keyword \n argument must be explicity set to \"physical\".\n rmin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`\n The minimum radius of the profile, in arcseconds. \n rmax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`\n The maximum radius of the profile, in arcseconds.\n nbins : integer\n The number of bins in the profile.\n ctr_type : string, optional\n The type of center coordinate. Either \"celestial\" for \n (RA, Dec) coordinates (the default), or \"physical\" for \n pixel coordinates.\n emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional\n The minimum energy of the events to be binned in keV. \n Default is the lowest energy available.\n emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional\n The maximum energy of the events to be binned in keV. \n Default is the highest energy available.\n overwrite : boolean, optional\n Whether or not to overwrite an existing file with the \n same name. Default: False\n expmap_file : string, optional\n Supply an exposure map file to determine fluxes. \n Default: None\n \"\"\"\n import astropy.wcs as pywcs\n rmin = parse_value(rmin, \"arcsec\")\n rmax = parse_value(rmax, \"arcsec\")\n f = pyfits.open(evt_file)\n hdu = f[\"EVENTS\"]\n orig_dx = hdu.header[\"TCDLT3\"]\n e = hdu.data[\"ENERGY\"]\n if emin is None:\n emin = e.min()\n else:\n emin = parse_value(emin, \"keV\")\n emin *= 1000.\n if emax is None:\n emax = e.max()\n else:\n emax = parse_value(emax, \"keV\")\n emax *= 1000.\n idxs = np.logical_and(e > emin, e < emax)\n x = hdu.data[\"X\"][idxs]\n y = hdu.data[\"Y\"][idxs]\n exp_time = hdu.header[\"EXPOSURE\"]\n w = wcs_from_event_file(f)\n dtheta = np.abs(w.wcs.cdelt[1])*3600.0\n f.close()\n\n if ctr_type == \"celestial\":\n ctr = w.all_world2pix(ctr[0], ctr[1], 1)\n\n r = np.sqrt((x-ctr[0])**2+(y-ctr[1])**2)\n rr = np.linspace(rmin/dtheta, rmax/dtheta, nbins+1)\n C = np.histogram(r, bins=rr)[0]\n rbin = rr*dtheta\n rmid = 0.5*(rbin[1:]+rbin[:-1])\n\n A = np.pi*(rbin[1:]**2-rbin[:-1]**2)\n\n Cerr = np.sqrt(C)\n\n R = C/exp_time\n Rerr = Cerr/exp_time\n\n S = R/A\n Serr = Rerr/A\n\n col1 = pyfits.Column(name='RLO', format='D', unit='arcsec', array=rbin[:-1])\n col2 = pyfits.Column(name='RHI', format='D', unit='arcsec', array=rbin[1:])\n col3 = pyfits.Column(name='RMID', format='D', unit='arcsec', array=rmid)\n col4 = pyfits.Column(name='AREA', format='D', unit='arcsec**2', array=A)\n col5 = pyfits.Column(name='NET_COUNTS', format='D', unit='count', array=C)\n col6 = pyfits.Column(name='NET_ERR', format='D', unit='count', array=Cerr)\n col7 = pyfits.Column(name='NET_RATE', format='D', unit='count/s', array=R)\n col8 = pyfits.Column(name='ERR_RATE', format='D', unit='count/s', array=Rerr)\n col9 = pyfits.Column(name='SUR_BRI', format='D', unit='count/s/arcsec**2', array=S)\n col10 = pyfits.Column(name='SUR_BRI_ERR', format='1D', unit='count/s/arcsec**2', array=Serr)\n\n coldefs = [col1, col2, col3, col4, col5, col6, col7, col8, col9, col10]\n\n if expmap_file is not None:\n f = pyfits.open(expmap_file)\n ehdu = f[\"EXPMAP\"]\n wexp = pywcs.WCS(header=ehdu.header)\n cel = w.all_pix2world(ctr[0], ctr[1], 1)\n ectr = wexp.all_world2pix(cel[0], cel[1], 1)\n exp = ehdu.data[:,:]\n nx, ny = exp.shape\n reblock = ehdu.header[\"CDELT2\"]/orig_dx\n x, y = np.mgrid[1:nx+1,1:ny+1]\n r = np.sqrt((x-ectr[0])**2 + (y-ectr[1])**2)\n f.close()\n E = np.histogram(r, bins=rr/reblock, weights=exp)[0] / np.histogram(r, bins=rr/reblock)[0]\n with np.errstate(invalid='ignore', divide='ignore'):\n F = R/E\n Ferr = Rerr/E\n SF = F/A\n SFerr = Ferr/A\n col11 = pyfits.Column(name='MEAN_SRC_EXP', format='D', unit='cm**2', array=E)\n col12 = pyfits.Column(name='NET_FLUX', format='D', unit='count/s/cm**2', array=F)\n col13 = pyfits.Column(name='NET_FLUX_ERR', format='D', unit='count/s/cm**2', array=Ferr)\n col14 = pyfits.Column(name='SUR_FLUX', format='D', unit='count/s/cm**2/arcsec**2', array=SF)\n col15 = pyfits.Column(name='SUR_FLUX_ERR', format='D', unit='count/s/cm**2/arcsec**2', array=SFerr)\n coldefs += [col11, col12, col13, col14, col15]\n\n tbhdu = pyfits.BinTableHDU.from_columns(pyfits.ColDefs(coldefs))\n tbhdu.name = \"PROFILE\"\n\n hdulist = pyfits.HDUList([pyfits.PrimaryHDU(), tbhdu])\n\n hdulist.writeto(out_file, overwrite=overwrite)\n\ncoord_types = {\"sky\": (\"X\", \"Y\", 2, 3),\n \"det\": (\"DETX\", \"DETY\", 6, 7)}\n\n\ndef write_image(evt_file, out_file, coord_type='sky', emin=None, emax=None,\n overwrite=False, expmap_file=None, reblock=1):\n r\"\"\"\n Generate a image by binning X-ray counts and write \n it to a FITS file.\n\n Parameters\n ----------\n evt_file : string\n The name of the input event file to read.\n out_file : string\n The name of the image file to write.\n coord_type : string, optional\n The type of coordinate to bin into an image. \n Can be \"sky\" or \"det\". Default: \"sky\"\n emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional\n The minimum energy of the photons to put in the \n image, in keV.\n emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional\n The maximum energy of the photons to put in the \n image, in keV.\n overwrite : boolean, optional\n Whether or not to overwrite an existing file with \n the same name. Default: False\n expmap_file : string, optional\n Supply an exposure map file to divide this image by\n to get a flux map. Default: None\n reblock : integer, optional\n Change this value to reblock the image to larger \n pixel sizes (reblock >= 1). Only supported for\n sky coordinates. Default: 1\n \"\"\"\n if coord_type == \"det\" and reblock > 1:\n raise RuntimeError(\"Reblocking images is not supported \"\n \"for detector coordinates!\")\n f = pyfits.open(evt_file)\n e = f[\"EVENTS\"].data[\"ENERGY\"]\n if emin is None:\n emin = e.min()\n else:\n emin = parse_value(emin, \"keV\")\n emin *= 1000.\n if emax is None:\n emax = e.max()\n else:\n emax = parse_value(emax, \"keV\")\n emax *= 1000.\n idxs = np.logical_and(e > emin, e < emax)\n xcoord, ycoord, xcol, ycol = coord_types[coord_type]\n x = f[\"EVENTS\"].data[xcoord][idxs]\n y = f[\"EVENTS\"].data[ycoord][idxs]\n exp_time = f[\"EVENTS\"].header[\"EXPOSURE\"]\n xmin = f[\"EVENTS\"].header[\"TLMIN%d\" % xcol]\n ymin = f[\"EVENTS\"].header[\"TLMIN%d\" % ycol]\n xmax = f[\"EVENTS\"].header[\"TLMAX%d\" % xcol]\n ymax = f[\"EVENTS\"].header[\"TLMAX%d\" % ycol]\n if coord_type == 'sky':\n xctr = f[\"EVENTS\"].header[\"TCRVL%d\" % xcol]\n yctr = f[\"EVENTS\"].header[\"TCRVL%d\" % ycol]\n xdel = f[\"EVENTS\"].header[\"TCDLT%d\" % xcol]*reblock\n ydel = f[\"EVENTS\"].header[\"TCDLT%d\" % ycol]*reblock\n f.close()\n\n nx = int(xmax-xmin)//reblock\n ny = int(ymax-ymin)//reblock\n\n xbins = np.linspace(xmin, xmax, nx+1, endpoint=True)\n ybins = np.linspace(ymin, ymax, ny+1, endpoint=True)\n\n H, xedges, yedges = np.histogram2d(x, y, bins=[xbins, ybins])\n\n if expmap_file is not None:\n if coord_type == \"det\":\n raise RuntimeError(\"Cannot divide by an exposure map for images \"\n \"binned in detector coordinates!\")\n f = pyfits.open(expmap_file)\n if f[\"EXPMAP\"].shape != (nx, ny):\n raise RuntimeError(\"Exposure map and image do not have the same shape!!\")\n with np.errstate(invalid='ignore', divide='ignore'):\n H /= f[\"EXPMAP\"].data.T\n H[np.isinf(H)] = 0.0\n H = np.nan_to_num(H)\n H[H < 0.0] = 0.0\n f.close()\n\n hdu = pyfits.PrimaryHDU(H.T)\n\n if coord_type == 'sky':\n hdu.header[\"MTYPE1\"] = \"EQPOS\"\n hdu.header[\"MFORM1\"] = \"RA,DEC\"\n hdu.header[\"CTYPE1\"] = \"RA---TAN\"\n hdu.header[\"CTYPE2\"] = \"DEC--TAN\"\n hdu.header[\"CRVAL1\"] = xctr\n hdu.header[\"CRVAL2\"] = yctr\n hdu.header[\"CUNIT1\"] = \"deg\"\n hdu.header[\"CUNIT2\"] = \"deg\"\n hdu.header[\"CDELT1\"] = xdel\n hdu.header[\"CDELT2\"] = ydel\n hdu.header[\"CRPIX1\"] = 0.5*(nx+1)\n hdu.header[\"CRPIX2\"] = 0.5*(ny+1)\n else:\n hdu.header[\"CUNIT1\"] = \"pixel\"\n hdu.header[\"CUNIT2\"] = \"pixel\"\n\n hdu.header[\"EXPOSURE\"] = exp_time\n\n hdu.writeto(out_file, overwrite=overwrite)\n\n\ndef plot_spectrum(specfile, plot_energy=True, lw=2, xmin=None, xmax=None,\n ymin=None, ymax=None, xscale=None, yscale=None, \n label=None, fontsize=18, fig=None, ax=None, \n plot_counts=False, **kwargs):\n \"\"\"\n Make a quick Matplotlib plot of a convolved spectrum\n from a file. A Matplotlib figure and axis is returned.\n\n Parameters\n ----------\n specfile : string\n The file to be opened for plotting.\n figsize : tuple of integers, optional\n The size of the figure on both sides in inches.\n Default: (10,10)\n plot_energy : boolean, optional\n Whether to plot in energy or channel space. Default is\n to plot in energy, unless the RMF for the spectrum\n cannot be found. \n lw : float, optional\n The width of the lines in the plots. Default: 2.0 px.\n xmin : float, optional\n The left-most energy (in keV) or channel to plot. Default is the \n minimum value in the spectrum. \n xmax : float, optional\n The right-most energy (in keV) or channel to plot. Default is the \n maximum value in the spectrum. \n ymin : float, optional\n The lower extent of the y-axis. By default it is set automatically.\n ymax : float, optional\n The upper extent of the y-axis. By default it is set automatically.\n xscale : string, optional\n The scaling of the x-axis of the plot. Default: \"log\"\n yscale : string, optional\n The scaling of the y-axis of the plot. Default: \"log\"\n label : string, optional\n The label of the spectrum. Default: None\n fontsize : int\n Font size for labels and axes. Default: 18\n fig : :class:`~matplotlib.figure.Figure`, optional\n A Figure instance to plot in. Default: None, one will be\n created if not provided.\n ax : :class:`~matplotlib.axes.Axes`, optional\n An Axes instance to plot in. Default: None, one will be\n created if not provided.\n plot_counts : boolean, optional\n If set to True, the counts instead of the count rate will\n be plotted. Default: False\n\n Returns\n -------\n A tuple of the :class:`~matplotlib.figure.Figure` and the :class:`~matplotlib.axes.Axes` objects.\n \"\"\"\n import matplotlib.pyplot as plt\n from soxs.instrument import RedistributionMatrixFile\n f = pyfits.open(specfile)\n hdu = f[\"SPECTRUM\"]\n chantype = hdu.header[\"CHANTYPE\"]\n rmf = hdu.header.get(\"RESPFILE\", None)\n xerr = None\n if plot_energy:\n if rmf is not None:\n rmf = RedistributionMatrixFile(rmf)\n x = 0.5*(rmf.ebounds_data[\"E_MIN\"]+rmf.ebounds_data[\"E_MAX\"])\n xerr = 0.5*(rmf.ebounds_data[\"E_MAX\"]-rmf.ebounds_data[\"E_MIN\"])\n xlabel = \"Energy (keV)\"\n else:\n raise RuntimeError(\"Cannot find the RMF associated with this \"\n \"spectrum, so I cannot plot in energy!\")\n else:\n x = hdu.data[chantype]\n xlabel = \"Channel (%s)\" % chantype\n if plot_counts:\n y = hdu.data[\"COUNTS\"].astype(\"float64\")\n yerr = np.sqrt(y)\n else:\n if \"COUNT_RATE\" in hdu.columns.names:\n y = hdu.data[\"COUNT_RATE\"]\n else:\n y = hdu.data[\"COUNTS\"]/hdu.header[\"EXPOSURE\"]\n yerr = np.sqrt(hdu.data[\"COUNTS\"])/hdu.header[\"EXPOSURE\"]\n if plot_energy:\n yunit = \"keV\"\n y /= 2.0*xerr\n yerr /= 2.0*xerr\n else:\n yunit = \"bin\"\n f.close()\n if fig is None:\n fig = plt.figure(figsize=(10, 10))\n if xscale is None:\n if ax is None:\n xscale = \"log\"\n else:\n xscale = ax.get_xscale()\n if yscale is None:\n if ax is None:\n yscale = \"log\"\n else:\n yscale = ax.get_yscale()\n if ax is None:\n ax = fig.add_subplot(111)\n ax.errorbar(x, y, yerr=yerr, xerr=xerr, lw=lw, label=label, **kwargs)\n ax.set_xscale(xscale)\n ax.set_yscale(yscale)\n ax.set_xlim(xmin, xmax)\n ax.set_ylim(ymin, ymax)\n ax.set_xlabel(xlabel, fontsize=fontsize)\n if plot_counts:\n ylabel = \"Counts (counts/%s)\"\n else:\n ylabel = \"Count Rate (counts/s/%s)\"\n ax.set_ylabel(ylabel % yunit, fontsize=fontsize)\n ax.tick_params(axis='both', labelsize=fontsize)\n return fig, ax","sub_path":"soxs/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":30786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"443196413","text":"from __future__ import absolute_import, unicode_literals, print_function\n\nimport re\nimport json\nimport scrapy\n\n#from babel.numbers import parse_number\n#from scraper.items import HomeListing\nfrom zillow.items import HomeListing\n\nimport sys\n#import psycopg2\n\nBASE_URL = \"http://zillow.com\"\n#https://www.zillow.com/cincinnati-oh/sold/\n\ndbname = \"scrapinghub\"\nuser = \"postgres\"\nhost = \"localhost\"\npassword = \"postgres\"\nportno = \"5432\"\n\nclass ZillowScraper(scrapy.Spider):\n name = 'zillow_sold'\n\n def __init__(self, *args, **kwargs):\n super(ZillowScraper, self).__init__(*args, **kwargs)\n #city = kwargs.get('city')\n # self.city = 'cincinnati'\n # self.state= 'oh'\n # self.pincode= '45243'\n uscity = str(self.city)\n regionstate = str(self.state)\n if not uscity:\n raise ValueError('city parameter not defined')\n if not regionstate:\n raise ValueError('state parameter not defined')\n self.city = uscity.lower()\n self.regionstate = regionstate.lower()\n self.searchurl = ''\n \n # def dbconnect():\n # self.connect_str = \"dbname='\"+dbname+\"' user='\"+user+\"' host='\"+host+\"' password='\"+password+\"' port='\"+portno+\"'\"\n # self.conn = psycopg2.connect(self.connect_str)\n # self.cursor = self.conn.cursor()\n # return self.conn,self.cursor\n\n def start_requests(self):\n uscity = self.city\n regionstate = self.regionstate\n self.url = str(BASE_URL)+\"/\"+str(uscity)+\"-\"+str(regionstate)+\"/sold/\" \n #self.url = \"https://www.zillow.com/homes/\"+str(self.pincode)+\"_rb/\"\n self.url = \"https://www.zillow.com/homes/recently_sold/\"+str(self.pincode)+\"/house,condo,apartment_duplex,mobile,townhouse_type/\"\n #self.url = \"https://www.zillow.com/homes/recently_sold/45243/house,condo,apartment_duplex,mobile,townhouse_type/\"\n self.searchurl = self.url\n yield scrapy.Request(self.url, self.parse)\n\n def parse(self, response):\n mylist = []\n i = 1\n for atag in response.xpath('//div[@id=\"search-results\"]/ul/li'):\n mydict = {}\n mydict['zpid'] = atag.xpath('.//article/@data-zpid').extract_first()\n for x in atag.xpath('.//article/div[1]'):\n # Tag A\n # Each li represents a Property..\n street = x.xpath('.//span[1]/span[1]/text()').extract_first()\n city = x.xpath('.//span[1]/span[2]/text()').extract_first()\n state = x.xpath('.//span[1]/span[3]/text()').extract_first()\n postalcode = x.xpath('.//span[1]/span[4]/text()').extract_first()\n mydict['street'] = street\n mydict['city'] = city\n mydict['state'] = state\n mydict['postalcode'] = postalcode\n mydict['sold'] = x.xpath('.//div[1]/h4/span/text()').extract_first()\n mydict['path'] = BASE_URL + x.xpath('.//a[1]/@href').extract_first()\n mydict['date'] = x.xpath('.//div[2]/ul/li/text()').extract_first()\n #..bedroom bathroom,sqft data...\n sqftdata = x.xpath('.//div[1]/p/span/text()').extract()\n mydict['pricesqft'] = ''\n mydict['bed'] = ''\n mydict['bath'] = ''\n mydict['sqft'] = ''\n # to check List index outof range \n if (0 < len(sqftdata) and sqftdata[0] is not None):\n try:\n mydict['pricesqft'] = str(sqftdata[0]).strip().split()[1]\n except Exception as e:\n mydict['pricesqft'] = None\n if (1 < len(sqftdata) and sqftdata[1] is not None):\n try:\n mydict['bed'] = str(sqftdata[1]).strip().split()[0]\n except Exception as e:\n mydict['bed'] = None\n if (2 < len(sqftdata) and sqftdata[2] is not None):\n try:\n mydict['bath'] = str(sqftdata[2]).strip().split()[0]\n except Exception as e:\n mydict['bath'] = None \n if (3 < len(sqftdata) and sqftdata[3] is not None):\n try:\n mydict['sqft'] = str(sqftdata[3]).strip().split()[0]\n except Exception as e:\n mydict['sqft'] = None \n \n # sql=\"insert into scrapinghub (zpid,path,street,city,state) VALUES (%s,%s,%s,%s,%s)\".format(mydict['zpid'],mydict['path'],mydict['street'],mydict['city'],mydict['state'])\n # self.cursor.execute(sql)\n # self.conn.commit()\n \n # yield scrapy.Request(mydict['path'], callback=self.detailpage_parse,meta={'item':mydict})\n \n yield mydict\n \n i = i + 1\n \n pagecount = 1\n next_pagelink = ''\n nextpage = response.xpath('//div[@id=\"search-pagination-wrapper\"]/ol')\n mydict = {}\n total_pagecount = nextpage.xpath('.//li[@class=\"zsg-pagination-ellipsis\"]/following-sibling::li[1]/a/text()').extract_first()\n if total_pagecount is not None:\n total_pagecount = int(total_pagecount)\n total_pagecount = total_pagecount + 1\n for var in list(range(2,total_pagecount)): \n i = str(var)\n next_pagelink = self.searchurl+i+\"_p/\"\n pagecount = pagecount + 1\n yield scrapy.Request(next_pagelink, callback=self.parse)\n \n def detailpage_parse(self, response):\n item = response.meta['item']\n for atag in response.xpath('//div[@class=\"zsg-layout-content\"]'): \n #item={}\n for element in atag.xpath('.//div[@id=\"hdp-content\"]/div[2]'): \n # element.xpath('.//section[1]/@class').extract_first()\n # o/p - zsg-content-section\n # .......................... \n # divpath = './/section[1]/div[@class=\"hdp-facts zsg-content-component z-moreless\"]/div[1]/p/text()' \n # item['test1'] = element.xpath(divpath).extract_first() \n # o/p -- Facts & Features\n # ............................Don't Delete Above Links................\n features = './/section[1]/div[@class=\"hdp-facts zsg-content-component z-moreless\"]/div[1]/' \n typepath = features+'div[1]/div[1]/div/div[2]/div/text()'\n yearbuiltpath = features+'div[1]/div[2]/div/div[2]/div/text()'\n lotpath = features+'div[1]/div[6]/div/div[2]/div/text()'\n item['type'] = element.xpath(typepath).extract_first()\n item['yearbuilt'] = element.xpath(yearbuiltpath).extract_first()\n item['lot'] = element.xpath(lotpath).extract_first()\n \n features2 = './/section[2]/div[@class=\"zsg-content-component\"]/div[1]/'\n last30days = features2+'div/div/div[1]/div[2]/div[2]/div/div[2]/text()'\n last30days_per= features2+'div/div/div[1]/div[2]/div[2]/div/div[2]/span/text()'\n oneyearforecast= features2+'div/div/div[1]/div[2]/div[3]/div/div[2]/text()'\n oneyrforecast_per= features2+'div/div/div[1]/div[2]/div[3]/div/div[2]/span/text()'\n \n item['zestimate'] = response.xpath('//div[@class=\"primary-zestimate-item\"]/div[2]/div/text()').extract_first()\n item['zestimate_range'] = response.xpath('//div[@class=\"secondary-wrapper\"][1]/div[2]/text()').extract_first()\n item['last30days'] = response.xpath('//div[@class=\"secondary-wrapper\"][2]/div[2]/text()').extract_first()\n item['last30days_per'] = response.xpath('//div[@class=\"secondary-wrapper\"][2]/div[2]/text()').extract_first()\n item['oneyearforecast'] = response.xpath('//div[@class=\"secondary-wrapper\"][3]/div[2]/text()').extract_first()\n item['oneyrforecast_per'] = response.xpath('//div[@class=\"secondary-wrapper\"][3]/div[2]/text()').extract_first()\n r=1\n for tableprice in response.xpath('//table[@class=\"zsg-table yui3-toggle-content-minimized\"][1]/tbody/tr'):\n item['p_date'+r] = tableprice.xpath('.//td[1]/text()').extract_first()\n item['p_event'+r] = tableprice.xpath('.//td[2]/text()').extract_first()\n item['p_price'+r] = tableprice.xpath('.//td[3]/span[1]/text()').extract_first()\n item['p_priceper'+r] = tableprice.xpath('.//td[3]/span[2]/span/span/text()').extract_first()\n item['p_agents'+r] = tableprice.xpath('.//td[4]/text()').extract_first()\n r=r+1\n\n \n return item ","sub_path":"scrapinghub_zilllow_spider/build/lib/zillow/spiders/zillow.py","file_name":"zillow.py","file_ext":"py","file_size_in_byte":8876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"45632695","text":"\"\"\"Currency service for fetching a currency.\"\"\"\n\nfrom core.models import Currency\n\n\nclass CurrencyService:\n \"\"\"CurrencyService class.\"\"\"\n\n API_URL = 'https://free.currencyconverterapi.com/api/v6/convert'\n\n def __init__(self, request_service):\n \"\"\"Construct a CurrencyService object.\n\n Args:\n request_service: An object to make external requests.\n \"\"\"\n self._request_service = request_service\n\n def fetch(self, code):\n \"\"\"Fetch a currency code from an external source.\n\n Args:\n code: The currency code to fetch.\n\n Returns:\n Currency object.\n \"\"\"\n data = self._request_service.get(\n \"{}?q=GBP_{}&compact=y\".format(self.API_URL, code)\n ).json()\n\n return Currency(\n code=code,\n rate=data['GBP_{}'.format(code)]['val']\n )\n","sub_path":"app/core/services/currency_service.py","file_name":"currency_service.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"232206414","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2016 matsumotoyasuyuki\n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\n\n\"\"\"\nfrom django import forms\n\n\nclass TalkForm(forms.Form):\n log = forms.CharField(\n label='会話',\n widget=forms.TextInput(attrs={'class': 'form-control'})\n )\n","sub_path":"pylove/noby/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"333732968","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import Select\nimport config\nimport time\nimport os\nfrom glob import glob\nfrom datetime import date\nfrom datetime import datetime\nimport pyexcel as p\nimport pymysql\nfrom openpyxl import load_workbook\nfrom tqdm import tqdm\nimport dateutil.relativedelta\nimport re\nfrom openpyxl import Workbook\nfrom slacker import Slacker\nimport requests\nimport json\nfrom pyvirtualdisplay import Display\n\ndisplay = Display(visible=0, size=(1200, 900))\ndisplay.start()\n\n\ndef replacedate(text):\n if text is None:\n return\n else:\n text = text[0:10]\n return text.strip()\n\n\ndef replacenone(text):\n if text is None:\n return\n else:\n text = str(text)\n return text.strip()\n\ndef replaceTextToInt(text):\n if text is None:\n return\n else:\n text = str(text)\n a = text.split(\",\")\n b = \"\".join(a)\n text = int(b)\n return text\n\n\ndef replaceint(text):\n if text is None:\n return\n else:\n text = int(text)\n return text\n\n\ndef countSleep(sleep, total):\n for count in range(1, total):\n print(count)\n time.sleep(sleep)\n\n\ndef findSelect(xpath, value):\n el = Select(driver.find_element_by_xpath(xpath))\n el.select_by_value(value)\n\n# DB\ndb = pymysql.connect(\n host=config.DATABASE_CONFIG['host'],\n user=config.DATABASE_CONFIG['user'],\n password=config.DATABASE_CONFIG['password'],\n db=config.DATABASE_CONFIG['db'],\n charset=config.DATABASE_CONFIG['charset'],\n autocommit=True)\ncursor = db.cursor()\n# 슬랙 인증\nslack = Slacker(config.SLACK_API['token'])\n\n# f코드 정규\nrex = re.compile('_F[0-9]+')\nrexSpace = re.compile('_F[0-9]+')\n# 날짜 모듈\nmakeToday = datetime.today()\nnow = makeToday.strftime(\"%m%d_%H%M\")\nnowTime = makeToday.strftime(\"%H_%M\")\ntotalNow = makeToday.strftime(\"%Y-%m-%d\")\nmakeLastMonth = makeToday - dateutil.relativedelta.relativedelta(months=1)\nendNow = makeLastMonth.strftime(\"%Y-%m-%d\")\n\ndef changeFileToXlsx(originalName, resultName):\n stOriExcel = config.ST_LOGIN['excelPath'] + originalName\n stResultExcel = config.ST_LOGIN['excelPath'] + resultName + now + '.xls'\n stResultXlsx = config.ST_LOGIN['excelPath'] + resultName + now + '.xlsx'\n\n os.rename(stOriExcel, stResultExcel)\n\n p.save_book_as(file_name=stResultExcel, dest_file_name=stResultXlsx)\n return stResultXlsx\n\n# 셀레니움 셋\noptions = Options()\n# options.add_argument('--headless')\noptions.add_argument(\"disable-gpu\")\nprefs = {\n \"download.default_directory\": config.ST_LOGIN['excelPath'],\n \"directory_upgrade\": True\n}\noptions.add_experimental_option(\"prefs\", prefs)\ndriver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options=options)\n\n# 지마켓 시작\ndriver.switch_to.window(driver.window_handles[0])\ndriver.get('https://www.esmplus.com/Member/SignIn/LogOn')\ndriver.find_element_by_xpath('//*[@id=\"rdoSiteSelect\" and @value=\"GMKT\"]').click()\ndriver.find_element_by_xpath('//*[@id=\"SiteId\"]').send_keys(config.ESM_LOGIN['id'])\ndriver.find_element_by_xpath('//*[@id=\"SitePassword\"]').send_keys(config.ESM_LOGIN['password'])\ndriver.find_element_by_xpath('//*[@id=\"btnSiteLogOn\"]').click()\ncountSleep(1, 3)\nprint('로그인')\n\nwindowLists = driver.window_handles\nfor windowList in windowLists[1:]:\n driver.switch_to.window(driver.window_handles[-1])\n driver.close()\n\ndriver.switch_to.window(driver.window_handles[0])\ncountSleep(1, 3)\nprint('팝업 제거')\ndriver.get('https://www.esmplus.com/Escrow/Claim/ReturnRequestManagement?menuCode=TDM118')\ncountSleep(1, 3)\nprint('메뉴 이동')\ndriver.find_element_by_xpath('//*[@id=\"divSearch\"]/div/div[1]/table/tbody/tr[1]/td[1]/span[5]/a').click()\ndriver.find_element_by_xpath('//*[@id=\"btnSearch\"]').click()\ncountSleep(1, 5)\nprint('검색 결과')\ndriver.find_element_by_xpath('//*[@id=\"contents\"]/div[1]/form/div[4]/span/span/a').click()\ncountSleep(1, 5)\nprint('엑셀 다운')\nalert = driver.switch_to.alert\nalert.accept()\ncountSleep(1, 10)\nprint('엑셀 다운 완료')\n\nfindEbayFile = glob(config.ST_LOGIN['excelPath'] + \"ReturnRequest_*.xls\")\nprint(findEbayFile)\nfileResult = max(findEbayFile).split(\"/\")\nprint(fileResult)\nebayReturnFileName = fileResult[-1]\nprint(ebayReturnFileName)\n\nebayResult = changeFileToXlsx(ebayReturnFileName, 'ebayRetuneRequst_')\n\nprint('파일 변경 완료')\n\ndelOrder = '''DELETE From `bflow`.`channel_returns` where channel in (\"gmarket\",\"auction\",\"g9\")'''\ncursor.execute(delOrder)\n\n\nchannelSql = '''\n INSERT INTO `bflow`.`channel_returns` (\n order_number,\n order_number_line,\n return_number,\n channel,\n security_refund,\n security_refund_at,\n return_request_at,\n return_complete_at,\n return_delivery_case,\n return_delivery_fees,\n return_request_case,\n channel_delivery_fees,\n return_respons,\n payment_case,\n return_qty,\n refund_state,\n product_name,\n product_option,\n fcode,\n claim_state,\n delivery_company,\n delivery_code,\n return_delivery_arrive_at,\n return_hold_at,\n return_delivery_complete_at\n ) VALUES (\n %s, %s, %s, %s, %s,\n %s, %s, %s, %s, %s,\n %s, %s, %s, %s, %s,\n %s, %s, %s, %s, %s,\n %s, %s, %s, %s, %s\n )\n ON DUPLICATE KEY UPDATE \n security_refund = %s,\n security_refund_at = %s,\n return_request_at = %s,\n return_complete_at = %s,\n return_delivery_case = %s,\n return_delivery_fees = %s,\n return_request_case = %s,\n channel_delivery_fees = %s,\n return_respons = %s,\n payment_case = %s,\n return_qty = %s,\n refund_state = %s,\n delivery_company = %s,\n delivery_code = %s,\n return_delivery_arrive_at = %s,\n return_hold_at = %s,\n return_delivery_complete_at = %s,\n fcode = %s,\n claim_state = %s\n '''\n\npath = ebayResult\n\nwb = load_workbook(path)\n\nws = wb.active\n\nmaxRow = ws.max_row\n\nfor idx, row in enumerate(ws.iter_rows(min_row=2, max_row=maxRow )):\n print(idx, \"/\" , maxRow)\n order_number = replacenone(row[3].value)\n order_number_line = None\n return_number = None\n mallId = replacenone(row[1].value)\n searchMall = mallId.split()\n if searchMall[1] == '(brich_07)':\n channel = 'gmarket'\n elif searchMall[1] == '(brich)':\n channel = 'auction'\n elif searchMall[1] == '(brichmall)':\n channel = 'g9'\n security = replacenone(row[0].value)\n if security == 'Y':\n security_refund = '빠른환불'\n else:\n security_refund = None\n security_refund_at = None\n return_request_at = row[11].value\n return_complete_at = row[12].value\n return_delivery_case = replacenone(row[30].value)\n return_delivery_fees = replaceTextToInt(row[8].value)\n return_request_case = None\n channel_delivery_fees = None\n return_respons = replacenone(row[5].value)\n payment_case = replacenone(row[9].value)\n return_qty = replaceint(row[23].value)\n refund_state = replacenone(row[2].value)\n product_name = replacenone(row[19].value)\n product_option = replacenone(row[24].value)\n detailCode = replacenone(row[49].value)\n if detailCode is not None:\n changeCode = \"_\" + detailCode + \"_\"\n makeCode = rex.search(changeCode)\n if makeCode is None:\n fcode = None\n else:\n fcode = makeCode.group()\n\n delivery_company = replacenone(row[9].value)\n delivery_code = replacenone(row[10].value)\n return_delivery_arrive_at = row[11].value\n return_hold_at = row[17].value\n return_delivery_complete_at = None\n claim_state = '반품'\n\n values = (\n order_number,\n order_number_line,\n return_number,\n channel,\n security_refund,\n security_refund_at,\n return_request_at,\n return_complete_at,\n return_delivery_case,\n return_delivery_fees,\n return_request_case,\n channel_delivery_fees,\n return_respons,\n payment_case,\n return_qty,\n refund_state,\n product_name,\n product_option,\n fcode,\n claim_state,\n delivery_company,\n delivery_code,\n return_delivery_arrive_at,\n return_hold_at,\n return_delivery_complete_at,\n security_refund,\n security_refund_at,\n return_request_at,\n return_complete_at,\n return_delivery_case,\n return_delivery_fees,\n return_request_case,\n channel_delivery_fees,\n return_respons,\n payment_case,\n return_qty,\n refund_state,\n delivery_company,\n delivery_code,\n return_delivery_arrive_at,\n return_hold_at,\n return_delivery_complete_at,\n fcode,\n claim_state\n )\n print(channelSql, values)\n cursor.execute(channelSql, values)\nos.remove(ebayResult)\ndb.close()\ndisplay.stop()\ndriver.quit()\n# returnUrl = 'https://www.esmplus.com/Escrow/Claim/ReturnManagementSearch'\n# returnParms = {\n# 'page': '1',\n# 'limit': '200',\n# 'siteGbn': '1',\n# 'searchAccount': 'TA^278815',\n# 'searchDateType': 'ODD',\n# 'searchSDT': '2019-08-27',\n# 'searchEDT': '2019-11-27',\n# 'searchType': 'RR',\n# 'searchKey': 'ON',\n# 'searchKeyword':'', \n# 'orderByType': '',\n# 'excelInfo': '',\n# 'searchStatus': 'RR',\n# 'searchAllYn': 'N',\n# 'tabGbn': '1',\n# 'SortFeild': 'PayDate',\n# 'SortType': 'Desc',\n# 'start': '0',\n# 'searchDistrType': 'AL',\n# 'searchRewardStatus': 'NN',\n# 'searchFastRefundYn': '',\n# }\n# returnHeader = {'Content-Type' : 'application/x-www-form-urlencoded',\n# 'Referer': 'https://www.esmplus.com/Escrow/Claim/ReturnRequestManagement?menuCode=TDM118',\n# 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}\n# returnCookies = {'ESM_AUTH': 'B044D833077F80351AC6DCE532CFB728D47244CB65B62B3F34030FF8E03C1AE2C23398EB38289CC329DFD6A993367ED223EF303D71393DFD43995312D0446B28992A1E68EF0FBC13874B36E64981384B128058B1CE46A65998FD479E669941142039F898C85EB8100AD2FCADD11D721598FC6D45'}\n# returnRequest = requests.get(returnUrl, params=returnParms, headers=returnHeader)\n\n# returnToJson = returnRequest.json\n# print(returnRequest.url)\n# print(returnRequest.request)\n# print(returnRequest.text)\n# print(returnRequest.content)\n# print(returnRequest.request)\n# print(returnToJson)\n\n# https://www.esmplus.com/Escrow/Claim/ReturnRequestManagement?menuCode=TDM118","sub_path":"ebayReturnCheck.py","file_name":"ebayReturnCheck.py","file_ext":"py","file_size_in_byte":10727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"242889276","text":"# coding=utf-8\n\n\"\"\"\nCollects data from an arbitrary set of files.\n\nConfiguration is nested, and allows for per-file options. The default parsing\nmode for a file is yaml, which also supports JSON. For YAML/JSON files, the\nformat is simple key:value, where value is parseable as a float. The following\nfiles would be considered valid:\n\n\nFile1:\n---\nmetric1: 123\nmetric2: 456\n\nFile2:\n{\n \"metric1\": 123,\n \"metric2\": 456\n}\n\nThe current valid options are:\n\n* service - The specific name of the service that data is being collected for.\n\nGiven a directory structure as follows:\n\n/tmp\n├── service1\n│   ├── data1.yaml\n│   └── data2.yaml\n├── service2.yaml\n\nThe following configuration would record stats from /tmp/service1/data1.yaml\nand /tmp/service1/data2.yaml under \"service1\" and stats for from\n/tmp/service2.yaml under service2:\n\n[files]\n [[/tmp/service1]]\n service = service1\n [[/tmp/service2.yaml]]\n service = service2\n\"\"\"\n\nimport diamond.collector\nimport yaml\nimport os\n\n\nclass MultiFilesCollector(diamond.collector.Collector):\n\n def get_default_config_help(self):\n config_help = super(MultiFilesCollector, self).get_default_config_help()\n config_help.update({\n 'files': 'A dictionary of files or paths to collect data from.'\n })\n return config_help\n\n def get_default_config(self):\n \"\"\"\n Returns default collector settings.\n \"\"\"\n config = super(MultiFilesCollector, self).get_default_config()\n config.update({\n 'files': []\n })\n return config\n\n def collect(self):\n paths = self._expand_paths(self.config.get('files', {}))\n self.log.debug('Collecting from files: %s', paths.keys())\n for path, options in paths.items():\n try:\n service = options.get('service')\n with open(path, 'r') as f:\n data = yaml.safe_load(f)\n for k, v in (data or {}).items():\n try:\n value = float(v)\n except ValueError:\n value = None\n self.publish(k, value, service=service)\n except:\n self.log.exception('Unable to process file: %s', path)\n\n def _expand_paths(self, config):\n all_paths = {}\n for path, options in config.items():\n if os.path.exists(path):\n if os.path.isfile(path):\n all_paths[path] = options\n else:\n for fn in os.listdir(path):\n fp = os.path.join(path, fn)\n if os.path.isfile(fp):\n all_paths[fp] = options\n else:\n self.log.warn('Unable to find file or directory at: %s', path)\n\n return all_paths\n","sub_path":"src/collectors/multifiles/multifiles.py","file_name":"multifiles.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"137138517","text":"from array import array\n \nUP = 10 ** 4 + 30\n \ngraph = [[] for _ in range(UP)]\nsieve = [1 for _ in range(UP)]\nprimes = []\n \nfor i in range(2, UP):\n if sieve[i]:\n primes.append(i)\n for j in range(2,UP // i):\n sieve[i * j] = 0\n \nfor prime in primes:\n if 10 ** 4 > prime > 10 ** 3:\n p = str(prime)\n for casa in range(4):\n for alg in range(int(casa == 0), 10):\n n = int(p[:casa] + str(alg) + p[casa+1:])\n # if n < 1000:\n # print(p, n, casa, alg, p[:casa], str(alg), p[casa+1:])\n if sieve[n]:\n graph[prime].append(n)\n \ndef bfs(n1, n2):\n ans = 0\n fila = [n1]\n marcados = array(\"i\", (0,)) * UP\n comeco = 0\n fim = 1\n while True:\n fim = len(fila)\n if comeco == fim:\n break\n for i in range(comeco, fim):\n atual = fila[i]\n if not marcados[atual]:\n marcados[atual] = 1\n if atual == n2:\n return ans\n for viz in graph[atual]:\n if not marcados[viz]:\n fila.append(viz)\n comeco = fim\n ans += 1\n return ans\n \nn = int(input())\nfor _ in range(n):\n a, b = map(int, input().split())\n # print(graph[a])\n print(bfs(a, b)) \n","sub_path":"PPATH.py","file_name":"PPATH.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"388473894","text":"import os\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nfrom ._modules.realtime_saliency import SaliencyModel\n\n\nclass RealTimeSaliency(nn.Module):\n def __init__(self, net, model_confidence=0, device=None):\n super().__init__()\n import copy\n self.net = copy.deepcopy(net).to(device)\n\n model = SaliencyModel(self.net, 5, 64, 3, 64, fix_encoder=True,\n use_simple_activation=False, allow_selector=True)\n model.minimialistic_restore(os.path.join(\n os.path.dirname(__file__), '_modules', 'realtime_saliency',\n 'minsaliency'))\n model.train(False)\n self.model = model.to(device)\n\n self.model_confidence = model_confidence\n\n def forward(self, x, target_cls=None, sec_ord=False):\n if target_cls == None:\n target_cls = self.net(x.detach())[-1].max(1)[1]\n\n masks = self.model(x * 2, target_cls,\n model_confidence=self.model_confidence)[0]\n sal = F.interpolate(masks, x.size(\n 2), mode='bilinear', align_corners=False)\n accu = self._predict(x)\n return sal, accu\n\n def _predict(self, x):\n return F.softmax(self.net(x)[-1], 1)\n","sub_path":"models/saliency/optim_methods/realtime_saliency.py","file_name":"realtime_saliency.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"363581253","text":"import os\nimport webbrowser\n\nos.environ[\"PATH\"] = \"/Users/seddon/Anaconda3/anaconda/bin/:\" + os.environ[\"PATH\"]\nos.system(\"coverage run --branch code_to_be_analyzed_1.py\")\nos.system(\"coverage annotate\")\nos.system(\"/bin/cat code_to_be_analyzed_2.py,cover\")\nos.system(\"coverage html\")\n\nfilename = 'htmlcov/index.html'\nfrom urllib.request import pathname2url\nurl = 'file://{}'.format(pathname2url(os.path.abspath(filename)))\nprint(url)\nwebbrowser.open_new(url)\n","sub_path":"Python3/src/14 Testing/Code Coverage/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"151317336","text":"#!/usr/bin/python\nimport os\nimport re\nimport sys\n\nlog = os.popen(\"tail -1000 /var/log/\"+sys.argv[1]+\"/modsecurity/debug.log\").readlines()\ndebug_parse = open(\"debug_parse_\"+sys.argv[1]+\".log\",\"w\")\nfor line in log:\n\tsplit_line = line.split(\"] \")\n\tfor term in split_line:\n\t\tif re.search(r'id \\\"',term):\n\t\t\tdebug_parse.write(split_line[0]+\"]\" + term + \"]\" + split_line[5])","sub_path":"debug_parse.py","file_name":"debug_parse.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"366630846","text":"# Copyright 2021 Google LLC. All Rights Reserved.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom connector import channel\nfrom google3.cloud.graphite.mmv2.services.google.compute import snapshot_pb2\nfrom google3.cloud.graphite.mmv2.services.google.compute import snapshot_pb2_grpc\n\nfrom typing import List\n\n\nclass Snapshot(object):\n def __init__(\n self,\n name: str = None,\n description: str = None,\n source_disk: str = None,\n disk_size_gb: int = None,\n storage_bytes: int = None,\n license: list = None,\n snapshot_encryption_key: dict = None,\n source_disk_encryption_key: dict = None,\n self_link: str = None,\n labels: dict = None,\n project: str = None,\n zone: str = None,\n id: int = None,\n service_account_file: str = \"\",\n ):\n\n channel.initialize()\n self.name = name\n self.description = description\n self.source_disk = source_disk\n self.snapshot_encryption_key = snapshot_encryption_key\n self.source_disk_encryption_key = source_disk_encryption_key\n self.labels = labels\n self.project = project\n self.zone = zone\n self.service_account_file = service_account_file\n\n def apply(self):\n stub = snapshot_pb2_grpc.ComputeSnapshotServiceStub(channel.Channel())\n request = snapshot_pb2.ApplyComputeSnapshotRequest()\n if Primitive.to_proto(self.name):\n request.resource.name = Primitive.to_proto(self.name)\n\n if Primitive.to_proto(self.description):\n request.resource.description = Primitive.to_proto(self.description)\n\n if Primitive.to_proto(self.source_disk):\n request.resource.source_disk = Primitive.to_proto(self.source_disk)\n\n if SnapshotSnapshotEncryptionKey.to_proto(self.snapshot_encryption_key):\n request.resource.snapshot_encryption_key.CopyFrom(\n SnapshotSnapshotEncryptionKey.to_proto(self.snapshot_encryption_key)\n )\n else:\n request.resource.ClearField(\"snapshot_encryption_key\")\n if SnapshotSourceDiskEncryptionKey.to_proto(self.source_disk_encryption_key):\n request.resource.source_disk_encryption_key.CopyFrom(\n SnapshotSourceDiskEncryptionKey.to_proto(\n self.source_disk_encryption_key\n )\n )\n else:\n request.resource.ClearField(\"source_disk_encryption_key\")\n if Primitive.to_proto(self.labels):\n request.resource.labels = Primitive.to_proto(self.labels)\n\n if Primitive.to_proto(self.project):\n request.resource.project = Primitive.to_proto(self.project)\n\n if Primitive.to_proto(self.zone):\n request.resource.zone = Primitive.to_proto(self.zone)\n\n request.service_account_file = self.service_account_file\n\n response = stub.ApplyComputeSnapshot(request)\n self.name = Primitive.from_proto(response.name)\n self.description = Primitive.from_proto(response.description)\n self.source_disk = Primitive.from_proto(response.source_disk)\n self.disk_size_gb = Primitive.from_proto(response.disk_size_gb)\n self.storage_bytes = Primitive.from_proto(response.storage_bytes)\n self.license = Primitive.from_proto(response.license)\n self.snapshot_encryption_key = SnapshotSnapshotEncryptionKey.from_proto(\n response.snapshot_encryption_key\n )\n self.source_disk_encryption_key = SnapshotSourceDiskEncryptionKey.from_proto(\n response.source_disk_encryption_key\n )\n self.self_link = Primitive.from_proto(response.self_link)\n self.labels = Primitive.from_proto(response.labels)\n self.project = Primitive.from_proto(response.project)\n self.zone = Primitive.from_proto(response.zone)\n self.id = Primitive.from_proto(response.id)\n\n def delete(self):\n stub = snapshot_pb2_grpc.ComputeSnapshotServiceStub(channel.Channel())\n request = snapshot_pb2.DeleteComputeSnapshotRequest()\n request.service_account_file = self.service_account_file\n if Primitive.to_proto(self.name):\n request.resource.name = Primitive.to_proto(self.name)\n\n if Primitive.to_proto(self.description):\n request.resource.description = Primitive.to_proto(self.description)\n\n if Primitive.to_proto(self.source_disk):\n request.resource.source_disk = Primitive.to_proto(self.source_disk)\n\n if SnapshotSnapshotEncryptionKey.to_proto(self.snapshot_encryption_key):\n request.resource.snapshot_encryption_key.CopyFrom(\n SnapshotSnapshotEncryptionKey.to_proto(self.snapshot_encryption_key)\n )\n else:\n request.resource.ClearField(\"snapshot_encryption_key\")\n if SnapshotSourceDiskEncryptionKey.to_proto(self.source_disk_encryption_key):\n request.resource.source_disk_encryption_key.CopyFrom(\n SnapshotSourceDiskEncryptionKey.to_proto(\n self.source_disk_encryption_key\n )\n )\n else:\n request.resource.ClearField(\"source_disk_encryption_key\")\n if Primitive.to_proto(self.labels):\n request.resource.labels = Primitive.to_proto(self.labels)\n\n if Primitive.to_proto(self.project):\n request.resource.project = Primitive.to_proto(self.project)\n\n if Primitive.to_proto(self.zone):\n request.resource.zone = Primitive.to_proto(self.zone)\n\n response = stub.DeleteComputeSnapshot(request)\n\n @classmethod\n def list(self, project, service_account_file=\"\"):\n stub = snapshot_pb2_grpc.ComputeSnapshotServiceStub(channel.Channel())\n request = snapshot_pb2.ListComputeSnapshotRequest()\n request.service_account_file = service_account_file\n request.Project = project\n\n return stub.ListComputeSnapshot(request).items\n\n def to_proto(self):\n resource = snapshot_pb2.ComputeSnapshot()\n if Primitive.to_proto(self.name):\n resource.name = Primitive.to_proto(self.name)\n if Primitive.to_proto(self.description):\n resource.description = Primitive.to_proto(self.description)\n if Primitive.to_proto(self.source_disk):\n resource.source_disk = Primitive.to_proto(self.source_disk)\n if SnapshotSnapshotEncryptionKey.to_proto(self.snapshot_encryption_key):\n resource.snapshot_encryption_key.CopyFrom(\n SnapshotSnapshotEncryptionKey.to_proto(self.snapshot_encryption_key)\n )\n else:\n resource.ClearField(\"snapshot_encryption_key\")\n if SnapshotSourceDiskEncryptionKey.to_proto(self.source_disk_encryption_key):\n resource.source_disk_encryption_key.CopyFrom(\n SnapshotSourceDiskEncryptionKey.to_proto(\n self.source_disk_encryption_key\n )\n )\n else:\n resource.ClearField(\"source_disk_encryption_key\")\n if Primitive.to_proto(self.labels):\n resource.labels = Primitive.to_proto(self.labels)\n if Primitive.to_proto(self.project):\n resource.project = Primitive.to_proto(self.project)\n if Primitive.to_proto(self.zone):\n resource.zone = Primitive.to_proto(self.zone)\n return resource\n\n\nclass SnapshotSnapshotEncryptionKey(object):\n def __init__(self, raw_key: str = None, sha256: str = None):\n self.raw_key = raw_key\n self.sha256 = sha256\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = snapshot_pb2.ComputeSnapshotSnapshotEncryptionKey()\n if Primitive.to_proto(resource.raw_key):\n res.raw_key = Primitive.to_proto(resource.raw_key)\n if Primitive.to_proto(resource.sha256):\n res.sha256 = Primitive.to_proto(resource.sha256)\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return SnapshotSnapshotEncryptionKey(\n raw_key=Primitive.from_proto(resource.raw_key),\n sha256=Primitive.from_proto(resource.sha256),\n )\n\n\nclass SnapshotSnapshotEncryptionKeyArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [SnapshotSnapshotEncryptionKey.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [SnapshotSnapshotEncryptionKey.from_proto(i) for i in resources]\n\n\nclass SnapshotSourceDiskEncryptionKey(object):\n def __init__(self, raw_key: str = None):\n self.raw_key = raw_key\n\n @classmethod\n def to_proto(self, resource):\n if not resource:\n return None\n\n res = snapshot_pb2.ComputeSnapshotSourceDiskEncryptionKey()\n if Primitive.to_proto(resource.raw_key):\n res.raw_key = Primitive.to_proto(resource.raw_key)\n return res\n\n @classmethod\n def from_proto(self, resource):\n if not resource:\n return None\n\n return SnapshotSourceDiskEncryptionKey(\n raw_key=Primitive.from_proto(resource.raw_key),\n )\n\n\nclass SnapshotSourceDiskEncryptionKeyArray(object):\n @classmethod\n def to_proto(self, resources):\n if not resources:\n return resources\n return [SnapshotSourceDiskEncryptionKey.to_proto(i) for i in resources]\n\n @classmethod\n def from_proto(self, resources):\n return [SnapshotSourceDiskEncryptionKey.from_proto(i) for i in resources]\n\n\nclass Primitive(object):\n @classmethod\n def to_proto(self, s):\n if not s:\n return \"\"\n return s\n\n @classmethod\n def from_proto(self, s):\n return s\n","sub_path":"python/services/compute/snapshot.py","file_name":"snapshot.py","file_ext":"py","file_size_in_byte":10357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"553972435","text":"'''\nfirst cut: 1 to 3\nsecond cut: first cut + (1 to 3)\nthird cut: second cut + (1 to 3)\n\ncut => check valid => terminate recursion / continute dfs\n'''\nclass Solution:\n def restoreIpAddresses(self, s):\n res = []\n\n # dfs fn,\n # cuts: cuts we left\n # acc: accumulated cut string\n # rest_s: string to be cut\n def dfs(cuts, acc, rest_s):\n # terminate condition\n if cuts == 0 and not rest_s:\n res.append('.'.join(acc))\n\n if cuts == 0 or not rest_s:\n return\n\n for i in range(1, min(4, 1 + len(rest_s))):\n if int(rest_s[:i]) <= 255:\n dfs(cuts - 1, [*acc, rest_s[:i]], rest_s[i:])\n if rest_s[0] == '0':\n break\n\n # start dfs with initial setups\n dfs(4, [], s)\n\n return res\n\n\n\n# DFS\nclass Solution:\n def restoreIpAddresses(self, s):\n res = []\n\n def dfs(rest, rest_n, path):\n if rest_n == 0 and not rest:\n res.append('.'.join(path))\n\n if rest_n == 0 or not rest:\n return\n\n for i, ch in enumerate(rest[:3]):\n if int(rest[:i + 1]) < 256:\n dfs(rest[i + 1:], rest_n - 1, path + [rest[:i + 1]])\n if ch == '0' and i == 0:\n break\n\n dfs(s, 4, [])\n return res\n","sub_path":"leetcode/py/93.py","file_name":"93.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"114530664","text":"import pytest\nimport requests\n\n#conftest.py 共享 test_fix_conftest\n\n\ndef test_get_allbook(getToken):\n r=requests.get(\n url='http://127.0.0.1:5000/v1/api/books',headers={'Authorization':'JWT {0}'.format(getToken)}\n )\n print(r.json())\n","sub_path":"pyTest/basic/test_fix_conftest1.py","file_name":"test_fix_conftest1.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"405145029","text":"import numpy as np\nimport sys\nfrom .warp import functional_warp, functional_scale\nfrom scipy.optimize import minimize\n\n\ndef best_warp(func1,\n func2,\n period,\n warp_func,\n scale_func,\n generate_warp_func,\n generate_scale_func,\n num_knots=4,\n optimization_kwargs={},\n starting_weights=None,\n evaluation_points=None,\n distance_cost=None,\n warp_cost=None,\n warp_constraints=None,\n return_type='joint_function'):\n \"\"\"\n params\n ---\n func1: function to be warped\n func2: function that func1 will be warped to try to match\n period: the period over which the distortions will be applied\n warp_func: the function that warps the target function\n scale_func: the function that scales the target function\n num_knots: the number of breakpoints in the distortion functions\n optimization_kwargs: kwargs that get passed into scipy's minimize function\n starting_weights: a dictionary containing the weights at which to start the\n minimization function. should have keys 'warp' and 'scale'\n evaluation_points: the points at which functions are evaluated to compute\n their cost. defaults to np.linspace(0, period, 20)\n distance_cost: a function that gets passed two arrays of the two functions\n evaluated at the to_evaluate points, and computes some cost between\n them\n warp_cost: a function that gets passed the warp_weights and scale_weights,\n and computes their cost (e.g. warping further from diagonal is less\n likely). also passed knot points for context\n warp_constraitns: a function that gets passed the warp_weights and\n scale_weights, and returns True if they are 'allowed' and false\n otherwise. Also passed knot_points for context.\n return_type: either 'joint_function' or 'independent_functions'. If the\n former, this function returns an optimal distortion function. If the\n later, this function returns the warp and scale functions that must be\n applied in that order to achieve the optimal warp.\n \"\"\"\n\n valid_returns = ('joint_function', 'independent_functions', 'weights')\n if return_type not in valid_returns:\n raise ValueError('Invalid return type provided - must be in {}'\n .format(valid_returns))\n\n # define default cost functions\n if distance_cost is None:\n\n def distance_cost(x, y):\n return np.sum((x - y)**2)\n\n if warp_constraints is None:\n\n def warp_constraints(warp_weights, scale_weights, knot_points):\n return True\n\n if warp_cost is None:\n\n def warp_cost(warp_weights, scale_weights, knot_points):\n return 0\n\n if evaluation_points is None:\n evaluation_points = np.linspace(0, period, 20)\n\n knot_points = np.linspace(0, 1, num_knots)\n\n def distance(params):\n warp_weights, scale_weights = np.split(params, [num_knots - 2])\n if not warp_constraints(warp_weights, scale_weights, knot_points):\n return sys.maxsize\n\n warped = warp_func(func1, knot_points[1:-1], warp_weights, period)\n warped_scaled = scale_func(warped, knot_points[1:-1], scale_weights,\n period)\n\n warped_scaled_evaluated = warped_scaled(evaluation_points).flatten()\n func2_evaluated = func2(evaluation_points).flatten()\n cost = distance_cost(warped_scaled_evaluated, func2_evaluated)\n cost += warp_cost(warp_weights, scale_weights, knot_points)\n return cost\n\n if starting_weights is None:\n starting_weights = {\n 'warp': knot_points[1:-1],\n 'scale': np.ones(num_knots)\n }\n\n x0 = np.concatenate((starting_weights['warp'], starting_weights['scale']))\n\n optimal = minimize(distance, x0, **optimization_kwargs)\n\n assert optimal.success, 'Optimization failed'\n\n warp_weights, scale_weights = np.split(optimal.x, [num_knots - 2])\n\n if return_type == 'weights':\n return {'warp': warp_weights, 'scale': scale_weights}\n\n warp_func = generate_warp_func(knot_points[1:-1], warp_weights)\n scale_func = generate_scale_func(knot_points[1:-1], scale_weights)\n\n if return_type == 'joint_function':\n warped = functional_warp(func1, warp_func, period)\n return functional_scale(warped, scale_func, period)\n\n if return_type == 'independent_functions':\n return {'warp': warp_func, 'scale': scale_func}\n","sub_path":"fwarp/best_warp.py","file_name":"best_warp.py","file_ext":"py","file_size_in_byte":4579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"261980950","text":"class Community:\n pop = 10\n name = \"barbarians\"\n agr = 0\n status = \"Exist\"\n culture = 10\n\n def __init__(self, population=10, name=\"barbarians\"):\n self.pop = population\n self.name = name\n if name != \"barbarians\":\n print(self.name, \"is formed\")\n\n def agriculture(self):\n self.agr = 10\n self.pop = self.pop * self.agr\n\n def enslavetion(self, part):\n self.pop = self.pop - self.pop // part\n if self.pop == 0:\n self.crash()\n\n def reorganise(self, child):\n self.status = \"is reorganised\"\n print(self.name, self.status, \"to\", child.name, \"(\", child.culture, \")\")\n\n def crash(self):\n self.status = \"is exterminated\"\n print(self.name, \"(\", self.culture, \")\", self.status)\n self.pop = 0\n\n def attack(self, enemy):\n self.pop = self.pop + 1 * self.agr\n self.culture = self.culture + enemy.culture\n print(self.name, \"(\", self.culture, \")\", \"attack\", enemy.name)\n enemy.crash()\n\n def conquested(self):\n self.status = \"is conquested\"\n\n\nclass Civilisation(Community):\n agr = 10\n\n def __init__(self, parent, part=1, name=\"Precursors\"):\n self.pop = parent.pop // part\n self.culture = parent.culture * 5 // part\n self.name = name\n parent.pop = parent.pop - self.pop\n if parent.pop == 0:\n parent.reorganise(self)\n else:\n print(self.name, \"(\", self.culture, \")\", \"formed from\", parent.name)\n\n def attack(self, enemy, part=1):\n self.pop = self.pop + enemy.pop // part\n enemy.enslavetion(part)\n if self.culture < enemy.culture:\n self.culture = self.culture + enemy.culture\n print(self.name, \"(\", self.culture, \")\", \"attack\", enemy.name)\n\n def colonise(self):\n self.pop = self.pop * 10\n self.culture = self.culture * 10\n\n\nclass Empire(Civilisation):\n\n def __init__(self, parent):\n self.name = parent.name\n self.pop = parent.pop\n self.culture = parent.culture * 2\n\n def conquest(self, victim):\n victim.conquested()\n self.pop = self.pop + victim.pop\n self.culture = self.culture + victim.culture\n print(self.name, \"(\", self.culture, \")\", \"conquest\", victim.name)\n\n\nclass State(Empire):\n economics = 0\n industrialIndex = 0\n\n def __init__(self, parent, part, name):\n self.pop = parent.pop // part\n self.culture = parent.culture // part\n self.name = name\n self.economics = self.pop * self.culture\n parent.pop = parent.pop - self.pop\n parent.culture = parent.culture - self.culture\n if parent.pop == 0:\n parent.reorganise(self)\n else:\n print(self.name, \"(\", self.culture, \"/\", self.economics, \")\", \"formed from\", parent.name)\n\n def conquest(self, victim, part=1):\n self.pop = self.pop + victim.pop // (part + 1)\n self.culture = self.culture + victim.culture // (part + 10)\n self.economics = self.pop * self.culture\n victim.pop = victim.pop - victim.pop // part\n victim.culture = victim.culture - victim.culture // part\n if victim.pop == 0:\n print(self.name, \"(\", self.culture, \"/\", self.economics, \")\", \"conquest\", victim.name)\n else:\n print(self.name, \"(\", self.culture, \"/\", self.economics, \")\", \"conquest part of\", victim.name)\n\n def attack(self, enemy):\n self.culture = self.culture + enemy.culture // 9 - self.culture // 10\n enemy.culture = enemy.culture - enemy.culture // 7\n self.economics = self.culture * self.pop\n print(self.name, \"(\", self.culture, \"/\", self.economics, \") win against\", enemy.name, \"(\", enemy.culture, \")\")\n if enemy.culture == 0:\n enemy.crash()\n\n def crash(self):\n self.culture = 0\n self.status = \"is bankrupt\"\n print(self.name, self.status)\n\n def help(self, partner):\n partner.culture = partner.culture + self.culture // 10\n self.culture = self.culture - self.culture // 100\n self.economics = self.pop * self.culture\n if partner.status == \"is bankrupt\":\n partner.status == \"is debtor\"\n print(self.name, \"(\", self.culture, \"/\", self.economics, \")\", \"send help to\", partner.name)\n\n def industrialization(self):\n self.culture = self.culture * 10\n self.pop = self.pop * 10\n self.economics = self.culture * self.pop\n if self.industrialIndex == 0:\n print(self.name, \"is industrialized\")\n self.industrialIndex = 1\n\n\nclass Coalition(State):\n\n def __init__(self, name, organizer):\n self.name = name\n self.pop = organizer.pop\n self.culture = organizer.culture\n self.economics = self.pop * self.culture\n print(self.name, \"(\", self.culture, \"/\", self.economics, \")\", \"formed by\", organizer.name)\n\n def accept(self, member):\n self.pop = self.pop + member.pop\n self.culture = self.culture + member.culture\n self.economics = self.pop * self.culture\n print(member.name, \"join\", self.name, \"(\", self.culture, \"/\", self.economics, \")\")\n\n def economicsAttack(self, enemy):\n enemy.crash()\n\n def crash(self):\n self.status = \"broke up\"\n print(self.name, self.status)\n\n def help(self, partner):\n partner.culture = partner.culture + self.culture // 10\n self.culture = self.culture + self.culture // 100\n self.economics = self.pop * self.culture\n if partner.status == \"is bankrupt\":\n partner.status = \"is debtor\"\n print(self.name, \"(\", self.culture, \"/\", self.economics, \")\", \"send help to\", partner.name)\n\n def GreatWar(self, enemy):\n enemy.crash()\n self.status = \"is bankrupt\"\n self.culture = 0\n print(self.name, self.status)\n\n\nIndoEuropeans = Community(10, \"Indo-Europeans\")\nSemitic = Community()\nAfroAsian = Community()\nAfroAsian.agriculture()\nIndoEuropeans.agriculture()\nSumerians = Civilisation(AfroAsian, 10, \"Sumerians\")\nEgypt = Civilisation(AfroAsian, 2, \"Egypt\")\nIVC = Civilisation(AfroAsian, 10)\nMinoans = Civilisation(AfroAsian, 10)\nMinoans.colonise()\nSemitic.agriculture()\nIndoEuropeans.attack(IVC)\nAkkad = Civilisation(Semitic, 4, \"Akkad\")\nPhoenicia = Civilisation(Semitic, 3, \"Phoenicia\")\nAkkad = Empire(Akkad)\nAkkad.conquest(Sumerians)\nPhoenicia.colonise()\nEgypt.attack(Semitic, 10)\nHittites = Civilisation(IndoEuropeans, 10, \"Nesili\")\nAssyria = Civilisation(Semitic, 2, \"Assyria\")\nHittites.attack(Egypt, 10)\nEgypt.attack(Hittites, 10)\nSemitic.attack(Hittites)\nIndoEuropeans.attack(Minoans)\nGreeks = Civilisation(IndoEuropeans, 10, \"Hellenes\")\nEtruscans = Civilisation(AfroAsian, 1, \"Etruscans\")\nGreeks.colonise()\nEtruscans.colonise()\nAssyria = Empire(Assyria)\nAssyria.conquest(Akkad)\nCarthage = Civilisation(Phoenicia, 2, \"Carthage\")\nAssyria.conquest(Phoenicia)\nPersia = Civilisation(IndoEuropeans, 10, \"Persia\")\nPersia = Empire(Persia)\nPersia.conquest(Assyria)\nPersia.conquest(Egypt)\nRomans = Civilisation(IndoEuropeans, 10, \"Romans\")\nPersia.attack(Greeks, 10)\nGreeks.attack(Persia, 10)\nGreeks = Empire(Greeks)\nGreeks.conquest(Persia)\nRomans.attack(Greeks, 10)\nRomans = Empire(Romans)\nRomans.conquest(Etruscans)\nRomans.conquest(Greeks)\nRomans.attack(Semitic, 4)\nRomans.attack(IndoEuropeans, 4)\nTurks = Community(10, \"Turks\")\nEuropeans = Civilisation(IndoEuropeans, 1, \"Europeans\")\nFrancs = State(Europeans, 6, \"Francs\")\nIberians = State(Europeans, 5, \"Iberians\")\nIberians.conquest(Romans, 6)\nFrancs.conquest(Romans, 5)\nGermans = State(Europeans, 4, \"Germans\")\nItalians = State(Romans, 4, \"Italians\")\nRomans = State(Romans, 1, \"Byzantium\")\nRomans.help(Italians)\nArabs = State(Semitic, 1, \"Umayyads\")\nArabs.conquest(Romans, 2)\nArabs.conquest(Iberians)\nArabs = State(Arabs, 1, \"Abbasids\")\nFrancs.attack(Arabs)\nFrance = Empire(Francs)\nFrance.conquest(Germans)\nFrance.conquest(Italians)\nGermans = State(France, 2, \"Germans\")\nItalians = State(Germans, 3, \"Italians\")\nFrance = State(France, 1, \"France\")\nScandinavians = Civilisation(Europeans, 1, \"Vikings\")\nRussians = State(Scandinavians, 2, \"Russians\")\nScandinavians.attack(France, 10)\nScandinavians.attack(Germans, 10)\nRussians.attack(Romans)\nScandinavia = State(Scandinavians, 1, \"Scandinavia\")\nScandinavia.conquest(Germans, 3)\nScandinavia.colonise()\nTurks = Civilisation(Turks, 1, \"Seljuqs\")\nTurks = Empire(Turks)\nTurks.attack(Romans, 2)\nFrance.attack(Turks)\nFrance.conquest(Scandinavia, 7)\nIberians = State(Arabs, 10, \"Iberians\")\nTurks.conquest(Arabs)\nGermans.attack(Scandinavia)\nGermans.attack(Russians)\nFrance.attack(Turks)\nBritain = State(France, 3, \"Britain\")\nBritain.attack(Turks)\nRomans.help(Italians)\nItalians.attack(Romans)\nBritain.attack(France)\nBritain.attack(France)\nFrance.attack(Britain)\nFrance.attack(Britain)\nFrance.attack(Britain)\nTurks = State(Turks, 1, \"Ottomans\")\nTurks.conquest(Romans)\nTurks.attack(Italians)\nTurks.attack(Italians)\nSpain = State(Iberians, 1, \"Spain\")\nSpain.conquest(Germans)\nSpain.colonise()\nSpain.colonise()\nBritain.industrialization()\nGermans = State(Spain, 20, \"Germans\")\nSpain.colonise()\nGermans.industrialization()\nFrance.industrialization()\nFrance.industrialization()\nFrance.colonise()\nFrance.attack(Spain)\nBritain.attack(Spain)\nGermans.attack(Turks)\nRussia = State(Russians, 1, \"Russia\")\nRussia.attack(Scandinavia)\nRussia.conquest(Scandinavia, 6)\nRussia.colonise()\nRussia.attack(Turks)\nRussia.colonise()\nGermans.attack(France)\nBritain.attack(France)\nBritain.conquest(France, 10)\nUSA = State(Britain, 9, \"USA\")\nBritain.colonise()\nFrance.industrialization()\nFrance.conquest(Germans, 1)\nFrance.attack(Spain)\nFrance.attack(Turks)\nRussia.attack(France)\nGermans = State(France, 2, \"Germans\")\nBritain.attack(France)\nBritain.colonise()\nFrance.colonise()\nBritain.conquest(Germans, 10)\nBritain.colonise()\nUSA.industrialization()\nUSA.colonise()\nEntente = Coalition(\"Entente\", France)\nEntente.accept(Britain)\nEntente.attack(Russia)\nUSA.industrialization()\nRussia.industrialization()\nGermans.attack(Entente)\nGermans.conquest(Entente, 10)\nGermany = State(Germans, 1, \"Germany\")\nEntente.accept(Russia)\nItaly = State(Italians, 1, \"Italy\")\nItaly.industrialization()\nItaly.colonise()\nEntente.colonise()\nUSA.industrialization()\nGermany.help(Turks)\nfor i in range(0, 5):\n Germany.attack(Entente)\n Entente.attack(Germany)\nRSFSR = State(Entente, 4, \"RSFSR\")\nUSA.attack(Germany)\nEntente.attack(RSFSR)\nRSFSR.attack(Entente)\nRSFSR.industrialization()\nEntente.GreatWar(Germany)\nUSSR = Coalition(\"USSR\", RSFSR)\nUSSR.industrialization()\nUSA.industrialization()\nUSA.help(Entente)\nUSA.help(Germany)\nUSSR.industrialization()\nUSA.industrialization()\nEntente.industrialization()\nGermany.industrialization()\nGermany.colonise()\nGermany.conquest(Entente, 3)\nEntente.attack(Germany)\nGermany.attack(USSR)\nUSSR.attack(Germany)\nUSA.attack(Germany)\nEntente.GreatWar(Germany)\nUSA.help(Entente)\nEntente.conquest(Germany, 2)\nUSSR.conquest(Germany, 1)\nEntente.industrialization()\nUSA.industrialization()\nNATO = Coalition(\"NATO\", USA)\nNATO.accept(Entente)\nNATO.economicsAttack(USSR)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"129736558","text":"import tweepy\r\nimport random\r\nimport itertools\r\nfrom tmdbv3api import TMDb, Movie, Discover\r\nimport collections\r\nimport time\r\nimport re\r\nfrom config import create_api, create_tmdb\r\n\r\n# Genre ID cache\r\ndict = {'28':'Action' , '12':'Adventure' , '16':'Animation' , '35':'Comedy' , '80':'Crime' , '99':'Documentary' , '18':'Drama' , '10751':'Family' , \\\r\n '14':'Fantasy' , '36':'History' , '27':'Horror' , '10402':'Music' , '9648':'Mystery' , '10749':'Romance' , '878':'Science Fiction' , \\\r\n '10770':'TV Movie' , '53':'Thriller' , '10752':'War' , '37':'Western'}\r\n\r\ndef post_movie(api, cgi = '27'):\r\n # Choose Genre\r\n cgi = random.choice(list(dict.keys()))\r\n \r\n # Create recommendation\r\n discover = Discover()\r\n movie = discover.discover_movies({'with_genres': cgi, 'with_original_language': 'en', 'release_date.lte': '2020-02-02', \\\r\n 'vote_average.gte': '7', 'vote_count.gte': '100', 'page': str(random.randint(1, 5))})\r\n rec = random.choice(movie)\r\n \r\n # Get IMDB ID\r\n movieimd = Movie()\r\n imd = movieimd.details(rec.id)\r\n \r\n # Create hashtags\r\n namehash = '#' + re.sub(r'\\W+', '', rec.title)\r\n genhash = '#' + re.sub(r'\\W+', '', dict[str(rec.genre_ids[0])])\r\n \r\n # Create post string\r\n tweet = '𝗧𝗶𝘁𝗹𝗲: ' + rec.title + '\\n𝗚𝗲𝗻𝗿𝗲: ' + dict[str(rec.genre_ids[0])] + '\\n𝗬𝗲𝗮𝗿: ' + rec.release_date[0:4] + \\\r\n '\\n𝗦𝗰𝗼𝗿𝗲: ' + str(int(rec.vote_average*10)) + \"%\" + '\\n\\nWas it worth the watch? ' + namehash + ' ' + genhash + \\\r\n '\\nhttps://www.imdb.com/title/' + imd.imdb_id \r\n \r\n return tweet\r\n\r\ndef main():\r\n # Create tmdb object\r\n tmdb = create_tmdb()\r\n # Create API object\r\n api = create_api()\r\n while True:\r\n # Post tweet\r\n api.update_status(post_movie(api))\r\n # Wait for next post\r\n time.sleep(10800)\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"bots/postmovie.py","file_name":"postmovie.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"628334745","text":"import sys\ntest_cases = open(sys.argv[1], 'r')\n# test_cases = open('data.txt', 'r')\nfor test in test_cases:\n if test == '':\n continue\n\n rows = test.split('|')\n best =[int(s) for s in rows[0].strip().split(' ')]\n\n for row in rows:\n cols =[int(s) for s in row.strip().split(' ')]\n for i in range(0, len(cols) ):\n if cols[i] > best[i]:\n best[i] = cols[i]\n\n print(\" \".join(map(str, best)))\ntest_cases.close()\n","sub_path":"python/find_the_highest_score/find_the_highest_score.py","file_name":"find_the_highest_score.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"421046800","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,JsonResponse,HttpResponseNotFound\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom elasticsearch import Elasticsearch\nimport json\nimport logging\nimport traceback\n\n#Connection to ElasticSearch server.\nes = Elasticsearch([{'host': 'localhost', 'port': 9200}])\n\n#home page with a search box to search keywords\ndef home(request):\n if request.method == 'GET':\n search_query = request.GET.get('search_box', None)\n return render(request,'wordsearch/index.html')\n\n#method for doing partial searches using query language\n@csrf_exempt\ndef partial_search(request):\n try:\n if request.method == \"GET\":\n\n # if query parameter word not in url\n if 'word' not in request.GET:\n return HttpResponseNotFound('

Page Not Found

') \n\n #if query parameter word in url\n word=request.GET.get('word')\n keyWord = str('*'+word+'*')\n\n #query to search index\n q1={\n 'bool':{\n 'should':[\n {\n 'term':{\n 'word':word\n }\n },\n {\n 'query_string':{\n 'query':keyWord,\n 'fields':['word',]\n }\n },\n ]\n }\n }\n\n #search in index\n t = es.search(index=[\"word_list\"],body={\"from\":0,\"size\":10000,\"query\":q1})\n \n #getting data from index\n temp_word = {}\n for k in t['hits']['hits']:\n words = k['_source']['word']\n score = k['_source']['usage_frequency']\n temp_dict = {words:score}\n if temp_dict not in temp_word.items():\n temp_word.update(temp_dict)\n \n #making list of usage frequency and sorting in descending order\n temp = []\n for k in temp_word:\n temp.append(temp_word[k])\n temp.sort(reverse=True)\n\n #making a new list of words according to thier usage frequecy\n temp1 =[]\n for i in temp:\n for k in temp_word:\n if i == temp_word[k]:\n temp1.append(k)\n \n #swapping the position of word searched with first element of list\n for i in range(0,len(temp1)):\n if word == temp1[i]:\n a=temp1[0]\n temp1[0]=temp1[i]\n temp1[i]=a\n break\n \n #getting top 25 values from list and sorting them according to thier length\n temp1=sorted(temp1[:25],key=len)\n\n return JsonResponse({'data':temp1})\n #return JsonResponse(temp1,safe=False)\n\n except Exception as e:\n logging.error(\"Exception Occured during login\",exc_info=True)\n traceback.print_exc()\n return JsonResponse({'Error':'BadRequest'})\n","sub_path":"wordsearch/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"456015008","text":"import cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimg = cv2.imread('C:/Users/Adarsh Gupta/Desktop/Car Image 11.png')\r\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\nimg0 = cv2.GaussianBlur(gray,(3,3),10)\r\nimg1 = cv2.Sobel(img0,cv2.CV_64F,1,0,ksize=5)\r\n#img.create(rows, cols, CV_8UC1); \r\n#img = imread(Capture.png, CV_8UC1);\r\n\r\n#dst = cv2.bilateralFilter(gray,6,75,75)\r\n#equal_histogram = cv2.equalizeHist(dst)\r\nequalised = cv2.equalizeHist(gray)\r\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT,(10,10))\r\nkernel1 = np.ones((9,9), np.uint8)\r\n#morph_image = cv2.morphologyEx(equalised,cv2.MORPH_OPEN,kernel,iterations=2)\r\nsub_morp_image = cv2.morphologyEx(equalised,cv2.MORPH_TOPHAT,kernel1)\r\n#gaussian_blur = cv2.GaussianBlur(morph_image,(3,3),10)\r\n#sub_morp_image = cv2.subtract(img0,morph_image)\r\nret,binary_car_image01 = cv2.threshold(sub_morp_image,0,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\r\n#th2 = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)\r\n#binary_car_image0 = cv2.adaptiveThreshold(sub_morp_image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)\r\n#laplacian = cv2.Laplacian(sub_morp_image,cv2.CV_64F)\r\n#laplacian = np.array(laplacian, dtype=np.uint8)\r\n#laplacian = cv2.cvtColor(laplacian, cv2.COLOR_BGR2GRAY)\r\n#ret,laplacian = cv2.threshold(laplacian,0,255, cv2.THRESH_OTSU)\r\ncanny_image = cv2.Canny(binary_car_image01,100,150)\r\nbinary_car_image = canny_image\r\n#kernel = np.ones((5,5), np.uint8)\r\n#kernel2 = np.ones((5,5), np.uint8)\r\n#binary_car_image01 = cv2.dilate(binary_car_image01,kernel,iterations=1)\r\n#binary_car_image01 = cv2.erode(binary_car_image01,kernel,iterations=2)\r\n#contours, hierarchy = cv2.findContours(canny_image ,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\r\n#cont = cv2.drawContours(binary_car_image01, contours, -1, (0,255,0), 3)\r\n#contours,h\r\n#kernel = np.ones((3,3), np.uint8)\r\n#binary_car_image0 = cv2.dilate(canny_image,kernel,iterations=1)\r\n#binary_car_image = cv2.erode(binary_car_image0,kernel,iterations=1)\r\n#binary_car_image = cv2.convertScaleAbs(canny_image)\r\n#binary_car_image = laplacian\r\n#binary_car_image = ~binary_car_image\r\ntitles = ['Original Image', 'Global Thresholding (v = 127)' , 'Adaptive Thresh_Mean' , 'Adaptive Thresh_Gaussian']\r\nimages = [gray, binary_car_image01, binary_car_image, img1]\r\n\r\nfor i in range(4):\r\n plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')\r\n plt.title(titles[i])\r\n plt.xticks([]),plt.yticks([])\r\nplt.show()\r\n\r\n\r\nfrom skimage import measure\r\nfrom skimage.measure import regionprops\r\nimport matplotlib.patches as patches\r\n'''import localization as lp\r\nfrom .geoProject import *\r\nfrom .methods import *\r\nfrom .find_centroid import maxPol\r\nimport shapely as shx'''\r\n\r\n# this gets all the connected regions and groups them together\r\nkernel = np.ones((3,3), np.uint8)\r\nbinary_car_image0 = cv2.erode(binary_car_image,kernel,iterations=1)\r\nlabel_image = measure.label(binary_car_image01)\r\n\r\n# getting the maximum width, height and minimum width and height that a license plate can be\r\nplate_dimensions = (0.08*label_image.shape[0], 0.2*label_image.shape[0], 0.15*label_image.shape[1], 0.6*label_image.shape[1])\r\nmin_height, max_height, min_width, max_width = plate_dimensions\r\nplate_objects_cordinates = []\r\nplate_like_objects = []\r\nfig, (ax1) = plt.subplots(1)\r\nax1.imshow(gray, cmap=\"gray\");\r\n\r\na = 0\r\ni = 0\r\nfor region in regionprops(label_image):\r\n if region.area < 50 or region.area > 2000 :\r\n continue\r\n a = a + region.area\r\n i = i + 1\r\nmaximum = 0\r\n# regionprops creates a list of properties of all the labelled regions\r\nfor region in regionprops(label_image):\r\n if region.area < 50 or region.area > 2000 :\r\n #if the region is so small then it's likely not a license plate\r\n continue\r\n \r\n # the bounding box coordinates\r\n min_row, min_col, max_row, max_col = region.bbox\r\n region_height = max_row - min_row\r\n region_width = max_col - min_col\r\n #print(region)\r\n #print(n_white_pix, \" \" , n_black_pix)\r\n # ensuring that the region identified satisfies the condition of a typical license plate\r\n if region_width/region_height <= 6.5 and region_width/region_height >= 2.5 and region.area >= (a/i) and np.sum(binary_car_image01[min_row:max_row,min_col:max_col] == 255) > np.sum(binary_car_image01[min_row:max_row,min_col:max_col] == 0):\r\n sobelx = cv2.Sobel(gray[min_row:max_row,min_col:max_col],cv2.CV_64F,1,0,ksize=5)\r\n label_image2 = measure.label(sobelx)\r\n j = 0\r\n for region in regionprops(label_image2):\r\n j = j + 1\r\n if j > maximum :\r\n maximum = j\r\n min_row2 = min_row\r\n min_col2 = min_col\r\n max_row2 = max_row\r\n max_col2 = max_col\r\nplate_like_objects.append(binary_car_image[min_row2:max_row2,min_col2:max_col2])\r\nplate_objects_cordinates.append((min_row2, min_col2,max_row2, max_col2))\r\nrectBorder = patches.Rectangle((min_col2, min_row2), max_col2-min_col2, max_row2-min_row2, edgecolor=\"red\", linewidth=2, fill=False)\r\nax1.add_patch(rectBorder)\r\nprint(rectBorder)\r\ncv2.imshow(\"Orignal Image\",gray[min_row2:max_row2,min_col2:max_col2])\r\n \r\n # let's draw a red rectangle over those regions\r\nplt.show()\r\n\r\n#ret1,th2 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\r\n#blur = cv2.GaussianBlur(gray,(5,5),0)\r\n#th3 = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)\r\n#th5 = cv2.adaptiveThreshold(dst,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)\r\n#ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\r\n\r\n\r\n'''titles = ['Original Image', 'Global Thresholding (v = 127)' , 'Adaptive Thresh_Mean' , 'Adaptive Thresh_Gaussian']\r\nimages = [gray, binary_car_image, binary_car_image0, img1]\r\n\r\nfor i in range(4):\r\n plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')\r\n plt.title(titles[i])\r\n plt.xticks([]),plt.yticks([])\r\nplt.show()'''\r\n","sub_path":"LocalizationApproach2.py","file_name":"LocalizationApproach2.py","file_ext":"py","file_size_in_byte":5947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"598810916","text":"# Create a function that returns the sum of the two lowest positive numbers\n# given an array of minimum 4 integers. No floats or empty arrays will be passed.\n\n\ndef sum_two_smallest_numbers(numbers):\n \"\"\" Return the sum of the 2 smallest integers from array \"\"\"\n\n first = min(numbers)\n numbers.remove(first)\n second = min(numbers)\n\n return first + second","sub_path":"sum_two_smallest.py","file_name":"sum_two_smallest.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"257776501","text":"from sgl.gui.widget import Widget\nfrom sgl.gui.enums import Align\n\nclass Label(Widget):\n\tdef __init__(self, text='', align = Align.MIDDLECENTER):\n\t\tsuper(Label, self).__init__()\n\t\tself.text = text\n\t\tself.align = align\n\t\t\n\tdef __repr__(self):\n\t\treturn self.text\n\n\tdef get_text(self):\n\t\treturn self._text\n\t\t\n\tdef set_text(self, v):\n\t\tself._text = str(v or '')\n\t\tif v:\n\t\t\tself.texture = self.theme.font.render(v)\n\t\t\tself.requestedSize = self.texture.size\n\t\telse:\n\t\t\tself.texture = None\n\t\t\tself.requestedSize = 0, 0\n\t\t\t\n\ttext = property(get_text, set_text)\n","sub_path":"sgl/gui/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"239280601","text":"def main():\n # get inputs\n first = [int(x) for x in input().strip()]\n last = [int(x) for x in input().strip()]\n\n # create boolean arrays for tracking fall outs.\n arr1 = [True for x in first]\n arr2 = [True for x in last]\n\n # larger number keeps all numbers past length of shorter.\n if len(arr1) < len(arr2):\n shorter = arr1\n else:\n shorter = arr2\n \n # reverse lists to 'right-align' them.\n num1 = first[::-1]\n num2 = last[::-1]\n\n # iterate through flipping booleans of fall through values.\n for i in range(len(shorter)):\n if num1[i] < num2[i]:\n arr1[i] = False\n elif num1[i] == num2[i]:\n continue\n else:\n arr2[i] = False\n\n # reverse boolean arrays to match with initial numbers.\n arr1 = arr1[::-1]\n arr2 = arr2[::-1]\n \n new_first = ''\n new_last = ''\n \n # generate new numbers\n for i in range(len(arr1)):\n if arr1[i]:\n new_first += str(first[i])\n\n for i in range(len(arr2)):\n if arr2[i]:\n new_last += str(last[i])\n\n if len(new_first) == 0:\n new_first = 'YODA'\n \n if len(new_last) == 0:\n new_last = 'YODA'\n \n zeros = 0\n for i in range(len(new_first)):\n if new_first[i] != '0':\n break\n else:\n zeros += 1\n if zeros == len(new_first):\n new_first = '0'\n break\n \n zeros = 0\n for i in range(len(new_last)):\n if new_last[i] != '0':\n break\n else:\n zeros += 1\n if zeros == len(new_last):\n new_last = '0'\n break\n\n print(new_first)\n print(new_last)\n\nif __name__ == '__main__':\n main()\n ","sub_path":"Python/yoda/yoda.py","file_name":"yoda.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"463100465","text":"import numpy as np\nfrom scipy import sparse\nfrom scipy import optimize\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.decomposition import PCA\n\n\ndef pca(vec, dim=1, **pca_params):\n return PCA(n_components=dim, **pca_params).fit_transform(vec)\n\n\ndef get_semi_space(\n vec,\n anchor_vec,\n labels,\n label_order=None,\n dim=1,\n mode=\"lda\",\n centering=True,\n **params\n):\n\n if label_order is None:\n class_labels, class_ids = np.unique(labels, return_inverse=True)\n n_class = len(class_labels)\n else:\n label2cids = {l: i for i, l in enumerate(label_order)}\n class_ids = np.array([label2cids[l] for l in labels])\n n_class = len(label2cids)\n\n if mode == \"simple\":\n left_center = np.mean(anchor_vec[class_ids == 0, :], axis=0)\n right_center = np.mean(anchor_vec[class_ids == 1, :], axis=0)\n vr = right_center - left_center\n denom = np.linalg.norm(vec, axis=1) * np.linalg.norm(vr)\n denom = 1 / np.maximum(denom, 1e-20)\n ret_vec = sparse.diags(denom) @ (vec @ vr.T)\n\n denom = np.linalg.norm(anchor_vec, axis=1) * np.linalg.norm(vr)\n denom = 1 / np.maximum(denom, 1e-20)\n anch_vec = sparse.diags(denom) @ (anchor_vec @ vr.T)\n elif mode == \"lda\":\n lda = LinearDiscriminantAnalysis(n_components=dim, **params)\n lda.fit(anchor_vec, class_ids)\n ret_vec = lda.transform(vec)\n anch_vec = lda.transform(anchor_vec)\n\n if centering:\n class_centers = np.zeros((n_class, dim))\n for cid in range(n_class):\n class_centers[cid, :] = (\n np.mean(anch_vec[class_ids == cid, :], axis=0)\n if dim > 1\n else np.mean(anch_vec[class_ids == cid, :])\n )\n ret_vec -= np.mean(class_centers, axis=0) if dim > 1 else np.mean(class_centers)\n return ret_vec\n\n\ndef save_semi_axis(filename, vec_all, anchor_points, labels):\n anchor_vec = vec_all[anchor_points, :]\n np.savez(filename, anchor_vec=anchor_vec, labels=labels)\n\n\ndef calc_semi_axis_from_file(\n filename, vec, label_order=None, dim=1, mode=\"simple\", **params\n):\n data = np.load(filename)\n anchor_vec = data[\"anchor_vec\"]\n labels = data[\"labels\"]\n return calc_semi_axis(\n vec, anchor_vec, labels, label_order=label_order, dim=dim, mode=mode, **params\n )\n","sub_path":"libs/network_embedding/network_embedding/projection.py","file_name":"projection.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"32307971","text":"import re\nimport logging\nimport socket\nfrom urllib import request, error, parse\n\nregex_ip = re.compile(\n r\"\\D*(\"\n + r\"(?:1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.\"\n + r\"(?:1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.\"\n + r\"(?:1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.\"\n + r\"(?:1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\"\n + r\")\\D*\")\n\ndef get_ip():\n return (get_ip_by_azure())\n \ndef get_ip_by_azure():\n url = 'http://42.159.252.221:55555/'\n try:\n resp = request.urlopen(url=url, timeout=10).read()\n return regex_ip.match(resp.decode(\"utf-8\")).group(1)\n except Exception as e:\n logging.warning(\"get_ip_by_ipip FAILED, error: %s\", str(e))\n return None\n \nif __name__ == '__main__':\n print(get_ip())\n","sub_path":"get_ip.py","file_name":"get_ip.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"52017056","text":"#!/usr/bin/env python3\n# --------------------( LICENSE )--------------------\n# Copyright (c) 2014-2021 Beartype authors.\n# See \"LICENSE\" for further details.\n\n'''\n**Beartype PEP-agnostic type hint tester utilities** (i.e., callables\nvalidating arbitrary objects to be PEP-agnostic type hints).\n\nThis private submodule is *not* intended for importation by downstream callers.\n'''\n\n# ....................{ IMPORTS }....................\nfrom beartype.roar import (\n BeartypeDecorHintTypeException,\n BeartypeDecorHintForwardRefException,\n)\nfrom beartype._util.cache.utilcachecall import callable_cached\nfrom beartype._util.cls.utilclstest import (\n die_unless_type, is_type_isinstanceable)\nfrom beartype._util.hint.nonpep.utilhintnonpeptest import (\n die_unless_hint_nonpep,\n is_hint_nonpep,\n)\nfrom beartype._util.hint.pep.utilhintpeptest import (\n die_if_hint_pep_unsupported,\n is_hint_pep,\n is_hint_pep_supported,\n)\nfrom beartype._util.hint.data.utilhintdata import (\n HINT_BASES_FORWARDREF,\n HINTS_IGNORABLE_SHALLOW,\n)\nfrom typing import Type\n\n# See the \"beartype.cave\" submodule for further commentary.\n__all__ = ['STAR_IMPORTS_CONSIDERED_HARMFUL']\n\n# ....................{ VALIDATORS }....................\ndef die_unless_hint(\n # Mandatory parameters.\n hint: object,\n\n # Optional parameters.\n hint_label: str = 'Annotated',\n) -> None:\n '''\n Raise an exception unless the passed object is a **supported type hint**\n (i.e., object supported by the :func:`beartype.beartype` decorator as a\n valid type hint annotating callable parameters and return values).\n\n Specifically, this function raises an exception if this object is neither:\n\n * A **supported PEP-compliant type hint** (i.e., :mod:`beartype`-agnostic\n annotation compliant with annotation-centric PEPs currently supported\n by the :func:`beartype.beartype` decorator).\n * A **PEP-noncompliant type hint** (i.e., :mod:`beartype`-specific\n annotation intentionally *not* compliant with annotation-centric PEPs).\n\n Efficiency\n ----------\n This validator is effectively (but technically *not*) memoized. Since the\n passed ``hint_label`` parameter is typically unique to each call to this\n validator, memoizing this validator would uselessly consume excess space\n *without* improving time efficiency. Instead, this validator first calls\n the memoized :func:`is_hint_pep` tester. If that tester returns ``True``,\n this validator immediately returns ``True`` and is thus effectively\n memoized; else, this validator inefficiently raises a human-readable\n exception without memoization. Since efficiency is largely irrelevant in\n exception handling, this validator thus remains effectively memoized.\n\n Parameters\n ----------\n hint : object\n Object to be validated.\n hint_label : Optional[str]\n Human-readable label prefixing this object's representation in the\n exception message raised by this function. Defaults to ``\"Annotated\"``.\n\n Raises\n ----------\n BeartypeDecorHintPepUnsupportedException\n If this object is a PEP-compliant type hint currently unsupported by\n the :func:`beartype.beartype` decorator.\n BeartypeDecorHintNonPepException\n If this object is neither:\n\n * A PEP-noncompliant type hint.\n * A supported PEP-compliant type hint.\n '''\n\n # If this object is a supported type hint, reduce to a noop.\n if is_hint(hint):\n return\n # Else, this object is *NOT* a supported type hint. In this case,\n # subsequent logic raises an exception specific to the passed parameters.\n\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # BEGIN: Synchronize changes here with is_hint() below.\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n # If this hint is PEP-compliant, raise an exception only if this hint is\n # currently unsupported by @beartype.\n if is_hint_pep(hint):\n die_if_hint_pep_unsupported(hint=hint, hint_label=hint_label)\n\n # Else, this hint is *NOT* PEP-compliant. In this case, raise an exception\n # only if this hint is also *NOT* PEP-noncompliant. By definition, all\n # PEP-noncompliant type hints are supported by @beartype.\n die_unless_hint_nonpep(hint=hint, hint_label=hint_label)\n\n# ....................{ VALIDATORS ~ class }....................\n#FIXME: Unit test us up, please.\ndef die_unless_hint_type_isinstanceable(\n # Mandatory parameters.\n hint: object,\n\n # Optional parameters.\n hint_label: str = 'Annotated',\n exception_cls: Type[Exception] = BeartypeDecorHintTypeException,\n) -> None:\n '''\n Raise an exception unless the passed object is an **isinstanceable class**\n (i.e., class whose metaclass does *not* define an ``__instancecheck__()``\n dunder method that raises an exception).\n\n Classes that are *not* isinstanceable include most PEP-compliant type\n hints, notably:\n\n * **Generic aliases** (i.e., subscriptable classes overriding the\n ``__class_getitem__()`` class dunder method standardized by `PEP 560`_\n subscripted by an arbitrary object) under Python >= 3.9, whose\n metaclasses define an ``__instancecheck__()`` dunder method to\n unconditionally raise an exception. Generic aliases include:\n\n * `PEP 484`_-compliant **subscripted generics.**\n * `PEP 585`_-compliant type hints.\n\n * User-defined classes whose metaclasses define an ``__instancecheck__()``\n dunder method to unconditionally raise an exception, including:\n\n * `PEP 544`_-compliant protocols *not* decorated by the\n :func:`typing.runtime_checkable` decorator.\n\n Motivation\n ----------\n When a class whose metaclass defines an ``__instancecheck__()`` dunder\n method is passed as the second parameter to the :func:`isinstance` builtin,\n that builtin defers to that method rather than testing whether the first\n parameter passed to that builtin is an instance of that class. If that\n method raises an exception, that builtin raises the same exception,\n preventing callers from deciding whether arbitrary objects are instances\n of that class. For brevity, we refer to that class as \"non-isinstanceable.\"\n\n Most classes are isinstanceable, because deciding whether arbitrary objects\n are instances of those classes is a core prerequisite for object-oriented\n programming. Most classes that are also PEP-compliant type hints, however,\n are *not* isinstanceable, because they're *never* intended to be\n instantiated into objects (and typically prohibit instantiation in various\n ways); they're only intended to be referenced as type hints annotating\n callables, an arguably crude form of callable markup.\n\n :mod:`beartype`-decorated callables typically check the types of arbitrary\n objects at runtime by passing those objects and types as the first and\n second parameters to the :func:`isinstance` builtin. If those types are\n non-isinstanceable, those type-checks will typically raise\n non-human-readable exceptions (e.g., ``\"TypeError: isinstance() argument 2\n cannot be a parameterized generic\"`` for `PEP 585`_-compliant type hints).\n This is non-ideal both because those exceptions are non-human-readable\n *and* because those exceptions are raised at call rather than decoration\n time, where users expect the :mod:`beartype.beartype` decorator to raise\n exceptions for erroneous type hints.\n\n Thus the existence of this function, which the :mod:`beartype.beartype`\n decorator calls to validate the usability of type hints that are classes\n *before* checking objects against those classes at call time.\n\n Parameters\n ----------\n hint : object\n Object to be validated.\n hint_label : str\n Human-readable label prefixing this hint's representation in the\n exception message raised by this function. Defaults to ``\"Annotated\"``.\n exception_cls : Type[Exception]\n Type of exception to be raised. Defaults to\n :exc:`BeartypeDecorHintTypeException`.\n\n Raises\n ----------\n BeartypeDecorHintTypeException\n If this hint is *not* an isinstanceable class.\n\n .. _PEP 544:\n https://www.python.org/dev/peps/pep-0544\n .. _PEP 585:\n https://www.python.org/dev/peps/pep-0585\n '''\n\n # # Avoid circular import dependencies.\n # from beartype._util.hint.pep.proposal.utilhintpep544 import (\n # is_hint_pep544_protocol)\n\n # If this hint is *NOT* a class, raise an exception.\n die_unless_type(cls=hint, exception_cls=exception_cls)\n # Else, this hint is a class.\n\n # If this class is *NOT* isinstanceable, raise an exception. For\n # efficiency, this test is split into two passes (in order of decreasing\n # efficiency):\n #\n # 1. Test whether this class is isinstanceable with the memoized\n # is_type_isinstanceable() tester. This is crucial, as this test can\n # *ONLY* be implemented via inefficient EAFP-style exception handling.\n # 2. If that tester reports this class to be non-isinstanceable, raise a\n # human-readable exception chained onto the non-human-readable exception\n # raised by explicitly passing that class as the second parameter to the\n # isinstance() builtin.\n if not is_type_isinstanceable(hint):\n assert isinstance(exception_cls, type), (\n 'f{repr(exception_cls)} not exception class.')\n\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # CAUTION: Synchronize with the is_type_isinstanceable() tester.\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n try:\n isinstance(None, hint) # type: ignore[arg-type]\n except Exception as exception:\n #FIXME: Uncomment after we uncover why doing so triggers an\n #infinite circular exception chain when \"hint\" is a \"GenericAlias\".\n # # Human-readable exception message to be raised as either...\n # exception_message = (\n # # If this class is a PEP 544-compliant protocol, a message\n # # documenting this exact issue and how to resolve it;\n # (\n # f'{hint_label} PEP 544 protocol {hint} '\n # f'uncheckable at runtime (i.e., '\n # f'not decorated by @typing.runtime_checkable).'\n # )\n # if is_hint_pep544_protocol(hint) else\n # # Else, a fallback message documenting this general issue.\n # (\n # f'{hint_label} type {hint} uncheckable at runtime (i.e., '\n # f'not passable as second parameter to isinstance() '\n # f'due to raising \"{exception}\" from metaclass '\n # f'__instancecheck__() method).'\n # )\n # )\n\n # Human-readable exception message to be raised.\n exception_message = (\n f'{hint_label} type {hint} uncheckable at runtime (i.e., '\n f'not passable as second parameter to isinstance() '\n f'due to raising \"{exception}\" from metaclass '\n f'__instancecheck__() method).'\n )\n\n # Raise this high-level exception with this human-readable message\n # chained onto this low-level exception with a typically\n # non-human-readable message.\n raise exception_cls(exception_message) from exception\n\n# ....................{ VALIDATORS ~ forwardref }....................\ndef die_unless_hint_forwardref(hint: object) -> None:\n '''\n Raise an exception unless the passed object is a **forward reference type\n hint** (i.e., object indirectly referring to a user-defined class that\n typically has yet to be defined).\n\n Parameters\n ----------\n hint : object\n Object to be validated.\n\n Raises\n ----------\n BeartypeDecorHintForwardRefException\n If this object is *not* a forward reference type hint.\n '''\n\n # If this is *NOT* a forward reference type hint, raise an exception.\n if not is_hint_forwardref(hint):\n raise BeartypeDecorHintForwardRefException(\n f'Type hint {repr(hint)} not forward reference.')\n\n# ....................{ TESTERS }....................\n@callable_cached\ndef is_hint(hint: object) -> bool:\n '''\n ``True`` only if the passed object is a **supported type hint** (i.e.,\n object supported by the :func:`beartype.beartype` decorator as a valid type\n hint annotating callable parameters and return values).\n\n This tester function is memoized for efficiency.\n\n Parameters\n ----------\n hint : object\n Object to be validated.\n\n Returns\n ----------\n bool\n ``True`` only if this object is either:\n\n * A **PEP-compliant type hint** (i.e., :mod:`beartype`-agnostic\n annotation compliant with annotation-centric PEPs).\n * A **PEP-noncompliant type hint** (i.e., :mod:`beartype`-specific\n annotation intentionally *not* compliant with annotation-centric\n PEPs).\n\n Raises\n ----------\n TypeError\n If this object is **unhashable** (i.e., *not* hashable by the builtin\n :func:`hash` function and thus unusable in hash-based containers like\n dictionaries and sets). All supported type hints are hashable.\n '''\n\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # BEGIN: Synchronize changes here with die_unless_hint() above.\n #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n # Return true only if...\n return (\n # This is a PEP-compliant type hint supported by @beartype *OR*...\n is_hint_pep_supported(hint) if is_hint_pep(hint) else\n # This is a PEP-noncompliant type hint, which by definition is\n # necessarily supported by @beartype.\n is_hint_nonpep(hint)\n )\n\n# ....................{ TESTERS ~ ignorable }....................\n@callable_cached\ndef is_hint_ignorable(hint: object) -> bool:\n '''\n ``True`` only if the passed object is an **ignorable type hint.**\n\n This tester function is memoized for efficiency.\n\n Parameters\n ----------\n hint : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is an ignorable type hint.\n\n Raises\n ----------\n TypeError\n If this object is **unhashable** (i.e., *not* hashable by the builtin\n :func:`hash` function and thus unusable in hash-based containers like\n dictionaries and sets). All supported type hints are hashable.\n '''\n\n # Attempt to...\n try:\n # If this hint is shallowly ignorable, return true.\n if hint in HINTS_IGNORABLE_SHALLOW:\n return True\n # Else, this hint is *NOT* shallowly ignorable.\n # If this hint is unhashable, hint is *NOT* shallowly ignorable.\n except TypeError:\n pass\n\n # If this hint is PEP-compliant...\n if is_hint_pep(hint):\n # Avoid circular import dependencies.\n from beartype._util.hint.pep.utilhintpeptest import (\n is_hint_pep_ignorable)\n\n # Defer to the function testing whether this hint is an ignorable\n # PEP-compliant type hint.\n return is_hint_pep_ignorable(hint)\n\n # Else, this hint is PEP-noncompliant and thus *NOT* deeply ignorable.\n # Since this hint is also *NOT* shallowly ignorable, this hint is\n # unignorable. In this case, return false.\n return False\n\n# ....................{ TESTERS ~ forwardref }....................\ndef is_hint_forwardref(hint: object) -> bool:\n '''\n ``True`` only if the passed object is a **forward reference type hint**\n (i.e., object indirectly referring to a user-defined class that typically\n has yet to be defined).\n\n Specifically, this tester returns ``True`` only if this object is either:\n\n * A string whose value is the syntactically valid name of a class.\n * An instance of the :class:`typing.ForwardRef` class. The :mod:`typing`\n module implicitly replaces all strings subscripting :mod:`typing` objects\n (e.g., the ``MuhType`` in ``List['MuhType']``) with\n :class:`typing.ForwardRef` instances containing those strings as instance\n variables, for nebulous reasons that make little justifiable sense but\n what you gonna do 'cause this is 2020. *Fight me.*\n\n This tester is intentionally *not* memoized (e.g., by the\n :func:`callable_cached` decorator), as the implementation trivially reduces\n to an efficient one-liner.\n\n Parameters\n ----------\n hint : object\n Object to be inspected.\n\n Returns\n ----------\n bool\n ``True`` only if this object is a forward reference type hint.\n '''\n\n # Return true only if this hint is an instance of a PEP-compliant forward\n # reference superclass.\n return isinstance(hint, HINT_BASES_FORWARDREF)\n","sub_path":"beartype/_util/hint/utilhinttest.py","file_name":"utilhinttest.py","file_ext":"py","file_size_in_byte":17209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"373144569","text":"from preprocess_frame import *\n\n\ndef stack_frames(stacked_frames, state, is_new_episode, stack_size=4):\n # Arguments:\n # stacked_frames: A deque containing four frames\n # state: Current frame\n # is_new_episode: A boolean value which determines if we're stacking frames from a newly created episode or not\n # stack_size: Determines the stack size. By default is 4.\n # Returns:\n # stacked_state: a 84*84*4 deque containing the last 4 states(frames).\n # Implements:\n # Calls the preprocess function on each new frame and then stacks #stack_size of frames together in a deque.\n\n # preprocess the frame\n frame = preprocess_frame(state)\n # if we're in a new episode create a new deque and stack four of the first frames in it. if not just add it to\n # the stack\n if is_new_episode:\n for i in range(stack_size):\n stacked_frames[:, :, i] = frame\n\n else:\n stacked_frames[:, :, -1] = frame\n\n return stacked_frames\n","sub_path":"Agent Architectures/A2C/stack_frames.py","file_name":"stack_frames.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"530650900","text":"import os\nimport logging\nimport soundfile as sf\nimport tensorflow as tf\nimport numpy as np\nfrom recognize_command import RecognizeCommands, RecognizeResult\nfrom streaming_accuracy_utils import StreamingAccuracyStats\nfrom figure_utils import *\nimport time\nimport wave\nimport matplotlib.pyplot as plt\n# Reads a model graph definition from disk, and creates a default graph object\n\ndef load_graph(mode_file):\n graph = tf.Graph()\n with graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(mode_file, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n return graph\n\n\n# Takes a file name, and loads a list of labels from it, one per line, and\n# returns a vector of strings.\n\ndef read_label_file(file_name):\n label_list = []\n with open(file_name, 'r') as f:\n lines = f.readlines()\n for line in lines:\n label_list.append(line.strip())\n return label_list\n\n# Takes a file name, loads a piece of wav from it, and return sample_rate and numpy data of np.float64\n\ndef read_wav_file(file_name):\n data, sample_rate = sf.read(file_name, dtype='float32')\n return sample_rate, data\n\n\n\ndef main():\n wav_file = r\"E:\\converted\\chouchun\\180804_1841.wav\"\n logging.basicConfig(level=logging.INFO)\n\n ground_truth_file = r'E:\\1.txt'\n\n label_file = r\"E:\\tmp\\speech_commands_train\\conv_labels.txt\"\n model_file = r'E:\\2frozen_graph.pb'\n\n # ops = tf.get_default_graph().get_operations()\n # all_tensor_names = {output.name for op in ops for output in op.outputs}\n input_data_name = \"decoded_sample_data:0\"\n input_rate_name = \"decoded_sample_data:1\"\n output_softmax_label_name = 'labels_softmax:0'\n\n clip_duration_ms = 300\n clip_stride_ms = 10\n\n average_window_duration_ms = 200\n detection_threshold = 0.3\n suppression_ms = 1500\n time_tolerance_ms = 100\n verbose = True\n\n label_list = read_label_file(label_file)\n sample_rate, data = read_wav_file(wav_file)\n channel_count = 1\n\n recognize_commands = RecognizeCommands(labels=label_list,\n average_window_duration_ms=average_window_duration_ms,\n detection_threshold=detection_threshold,\n suppression_ms=suppression_ms,\n minimum_count=4)\n\n stats = StreamingAccuracyStats()\n stats.read_ground_truth_file(ground_truth_file)\n recognize_element = RecognizeResult()\n all_found_words = []\n\n\n sample_count = data.shape[0]\n clip_duration_samples = int(clip_duration_ms * sample_rate / 1000)\n clip_stride_samples = int(clip_stride_ms * sample_rate / 1000)\n audio_data_end = sample_count - clip_duration_samples\n\n # load model and create a tf session to process audio pieces\n log_file_path = r'E:\\result2.txt'\n recognize_graph = load_graph(model_file)\n\n #if exists, clear log path contents\n if os.path.exists(log_file_path):\n os.remove(log_file_path)\n\n with recognize_graph.as_default():\n with tf.Session() as sess:\n # Get input and output tensor\n audio_data_tensor = tf.get_default_graph().get_tensor_by_name(input_data_name)\n audio_sample_rate_tensor = tf.get_default_graph().get_tensor_by_name(input_rate_name)\n output_softmax_label_tensor = tf.get_default_graph().get_tensor_by_name(output_softmax_label_name)\n\n for audio_data_offset in range(0, audio_data_end, clip_stride_samples):\n input_start = audio_data_offset\n input_end = audio_data_offset + clip_duration_samples\n outputs = sess.run(output_softmax_label_tensor,\n feed_dict={audio_data_tensor: np.expand_dims(data[input_start:input_end], axis=-1),\n audio_sample_rate_tensor: sample_rate})\n\n outputs = np.squeeze(outputs)\n current_time_ms = int(audio_data_offset * 1000 / sample_rate)\n try:\n recognize_commands.process_latest_result(outputs, current_time_ms, recognize_element)\n except Exception as e:\n logging.error(\"Recognition processing failed: \" + str(e))\n return\n\n #if recognize_element.is_new_command and recognize_element.found_command != '_silence_':\n if True:\n all_found_words.append([recognize_element.found_command, current_time_ms])\n\n if verbose:\n stats.calculate_accuracy_stats(all_found_words, current_time_ms, time_tolerance_ms)\n try:\n recognition_state = stats.delta()\n except Exception as e:\n logging.error(\"Statistics delta computing failed: \" + str(e))\n else:\n\n logging.info(str(current_time_ms) + \"ms: \" + recognize_element.found_command + \": \" +\n str(recognize_element.score) + recognition_state)\n\n f = open(log_file_path, 'a')\n write_str = str(current_time_ms) + ':' + recognize_element.found_command + '\\n'\n f.write(write_str)\n f.close()\n stats.print_accuracy_stats()\n\n stats.calculate_accuracy_stats(all_found_words, -1, time_tolerance_ms)\n stats.print_accuracy_stats()\n\n #show the recognized field in different colors\n show_recognized(wav_file, log_file_path)\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"test_streaming_accuracy.py","file_name":"test_streaming_accuracy.py","file_ext":"py","file_size_in_byte":5807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"192456561","text":"\"\"\"\nMagnetic data from Rio de Janeiro\n=================================\n\nWe provide sample total-field magnetic anomaly data from an airborne survey of\nRio de Janeiro, Brazil, from the 1970s. The data are made available by the\nGeological Survey of Brazil (CPRM) through their `GEOSGB portal\n`__. See the documentation for\n:func:`verde.datasets.fetch_rio_magnetic_anomaly` for more details.\n\"\"\"\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nimport numpy as np\nimport verde as vd\n\n# The data are in a pandas.DataFrame\ndata = vd.datasets.fetch_rio_magnetic_anomaly()\nprint(data.head())\n\n# Make a Mercator plot of the data using Cartopy\nplt.figure(figsize=(7, 5))\nax = plt.axes(projection=ccrs.Mercator())\nax.set_title('Total-field Magnetic Anomaly of Rio de Janeiro', pad=25)\n# Since the data is diverging (going from negative to positive)\n# we need to center our colorbar on 0. To do this, we calculate\n# the maximum absolute value of the data to set vmin and vmax.\nmaxabs = np.max(np.abs([data.total_field_anomaly_nt.min(),\n data.total_field_anomaly_nt.max()]))\n# Cartopy requires setting the projection of the original data through the\n# transform argument. Use PlateCarree for geographic data.\nplt.scatter(data.longitude, data.latitude, c=data.total_field_anomaly_nt,\n s=1, cmap='seismic', vmin=-maxabs, vmax=maxabs,\n transform=ccrs.PlateCarree())\ncb = plt.colorbar(pad=0.1)\ncb.set_label('nT')\nax.gridlines(draw_labels=True)\n# Set the extent of the plot to the limits of the data\nax.set_extent(vd.get_region(data.longitude, data.latitude))\nplt.tight_layout()\nplt.show()\n","sub_path":"examples/data/sample_rio_magnetic_anomaly.py","file_name":"sample_rio_magnetic_anomaly.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"220726773","text":"\"\"\"\r\nauthor - Mohit.\r\n\"\"\"\r\n\r\nfrom flask import Flask, request, redirect, render_template\r\nimport io\r\nimport PyPDF2\r\nimport os\r\nimport pymongo\r\nfrom pymongo import MongoClient\r\n\r\napp = Flask(__name__)\r\nroot = os.getcwd()\r\n\r\n\r\nfile = \"m\"\r\n\r\n\r\n@app.route('/')\r\ndef first_page():\r\n return render_template('first.html')\r\n\r\n\r\n@app.route('/redirect', methods=['GET', 'POST'])\r\ndef redirect():\r\n return render_template('Frontend.html')\r\n\r\n\r\n@app.route('/re', methods=['GET', 'POST'])\r\ndef re():\r\n return render_template('adminfp.html')\r\n\r\n\r\n@app.route('/send', methods=['GET', 'POST'])\r\ndef send():\r\n\r\n if request.method == 'POST':\r\n file = request.form['id']\r\n path = root\r\n path = path+\"\\\\\" + file\r\n if os.path.isdir(path):\r\n os.chdir(path)\r\n else:\r\n os.mkdir(path)\r\n os.chdir(path)\r\n\r\n return render_template('upload_page.html')\r\n return render_template('Frontend.html')\r\n\r\n\r\n@app.route('/pdf_upload', methods=['GET', 'POST'])\r\ndef pdf_upload():\r\n client = pymongo.MongoClient(\r\n \"mongodb+srv://mohit13:vitsucks13@m13-kpbkz.mongodb.net/test?retryWrites=true&w=majority\")\r\n db = client.trail\r\n coll = db.test\r\n doc =[]\r\n if request.method == 'POST':\r\n files = request.files.getlist('file')\r\n for fileup in files:\r\n content = fileup.read()\r\n\r\n pdf = PyPDF2.PdfFileReader(io.BytesIO(content))\r\n count = 0\r\n text = \"\"\r\n num_pages = pdf.numPages\r\n name = fileup.filename\r\n while count < num_pages:\r\n pageObj = pdf.getPage(count)\r\n count += 1\r\n text += pageObj.extractText()\r\n\r\n name = name[:-4]\r\n \r\n doc.append(text)\r\n # ON Device.................................................\r\n # if os.path.isfile(name):\r\n # f = open(name + \".txt\", \"a\")\r\n # else:\r\n # f = open(name + \".txt\", \"w+\")\r\n\r\n # f.write(text)\r\n # f.close()\r\n\r\n # path = root\r\n # return render_template('uploadedpdf.html', file=text)\r\n # os.rmdir(path)\r\n def insertdoc(pt):\r\n data ={\r\n \"_id\":file,\r\n \"docs\": pt\r\n }\r\n coll.insert_one(data)\r\n insertdoc(doc)\r\n return render_template('upload_page.html')\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","sub_path":"finalproj.py","file_name":"finalproj.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"253972355","text":"#! /usr/bin/env python\n#\n# Usage: ingest-nerdm-res.py [-VqsU] [-M URL] NERD_FILE_OR_DIR [...]\n# See help details via: ingest-nerdm-res.py -h\n#\n# Load NERDm JSON files into the RMM\n#\nimport os, sys, errno, json, re, warnings, shutil\nfrom argparse import ArgumentParser\n\nbasedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\noarpypath = os.path.join(basedir, \"python\")\nif 'OAR_HOME' in os.environ:\n basedir = os.environ['OAR_HOME']\n oarpypath = os.path.join(basedir, \"lib\", \"python\") +\":\"+ \\\n os.path.join(basedir, \"python\")\nschemadir = os.path.join(basedir, \"etc\", \"schemas\")\nif not os.path.exists(schemadir):\n sdir = os.path.join(basedir, \"model\")\n if os.path.exists(sdir):\n schemadir = sdir\n \nif 'OAR_PYTHONPATH' in os.environ:\n oarpypath = os.environ['OAR_PYTHONPATH']\n\nsys.path.extend(oarpypath.split(os.pathsep))\ntry:\n import nistoar\nexcept ImportError as e:\n nistoardir = os.path.join(basedir, \"python\")\n sys.path.append(nistoardir)\n import nistoar\n\nfrom nistoar.rmm.mongo.nerdm import (NERDmLoader, LoadLog, RecordIngestError,\n JSONEncodingError)\n\ndescription = \\\n\"\"\"ingest NERDm resource data into the RMM.\n\nFiles or directories can be listed on the command-line. When a directory is\nlisted, this script will search the directory (and its subdirectories) for files\nwith the '.json' extension and attempt to load them as NERDm files. \n\"\"\"\n\nepilog = None\n\ndef define_opts(progname=None):\n parser = ArgumentParser(progname, None, description, epilog)\n parser.add_argument('nerdfile', metavar='NERDFILEDIR', type=str, nargs='+',\n help=\"a file or directory containing the resource data\")\n parser.add_argument('-V', '--skip-validate', dest='validate', default=True,\n action=\"store_false\",\n help=\"do not attempt to validate the records before \"+\n \"ingesting them\")\n parser.add_argument('-A', '--archive-records', dest='archdir', metavar=\"DIR\",\n action='store', default=None,\n help=\"after successfully loading each record, move the \"+\n \"record file to the archive directory DIR\")\n parser.add_argument('-q', '--quiet', dest='quiet', default=False,\n action=\"store_true\",\n help=\"do not print non-fatal status messages\")\n parser.add_argument('-s', '--silent', dest='silent', default=False,\n action=\"store_true\", help=\"print no messages at all\")\n parser.add_argument('-U', '--warn-update', dest='warn', default=False,\n action=\"store_true\", help=\"print a warning message if \"+\n \"one or more records overwrite/update previous \"+\n \"existing records\")\n parser.add_argument('-M', '--mongodb-url', metavar='URL',type=str,dest='url',\n action='store', default=\"mongodb://mongodb:3333/TestDB\",\n help=\"the URL to the MongoDB database to load into (in \"+\n \"the form 'mongodb://HOST:PORT/DBNAME')\")\n\n return parser\n\ndef main(args):\n parser = define_opts()\n opts = parser.parse_args(args)\n if opts.silent:\n opts.quiet = True\n if opts.archdir and (not os.path.isdir(opts.archdir) or not os.access(opts.archdir, os.W_OK)):\n print(\"{0}: {1}: not a directory with write permission\".format(parser.prog, opts.archdir),\n file=sys.stderr)\n return 3\n\n stat = 0\n loader = NERDmLoader(opts.url, schemadir)\n if opts.warn and not opts.quiet:\n loader.onupdate = 'warn'\n warnings.simplefilter(\"once\")\n totres = LoadLog()\n\n for nerdpath in opts.nerdfile:\n validate = opts.validate\n\n if os.path.isdir(nerdpath):\n res = load_from_dir(nerdpath, loader, validate, opts.archdir)\n elif os.path.isfile(nerdpath):\n res = load_from_file(nerdpath, loader, validate, opts.archdir)\n elif not os.path.exists(nerdpath):\n res = LoadLog().add(nerdpath, [ \"File not found.\" ])\n else:\n res = LoadLog().add(nerdpath, [ \"Filepath not loadable.\" ])\n\n totres.merge(res)\n\n if not opts.silent and res.failure_count > 0:\n if not opts.quiet:\n print(\"{0}: The following records failed to load:\"\n .format(parser.prog), file=sys.stderr)\n for f in res.failures():\n why = (isinstance(f.errs[0], RecordIngestError) and \\\n \"Ingest error\") or \"Validation errors\"\n why += \": \"+fmterrs(f.errs)\n print(\"\\t{0}: \\t{1}\".format(str(f.key), why))\n else:\n print(\"{0}: {1}: {2} out of {3} records failed to load\"\n .format(parser.prog, fldfile, res.failure_count,\n res.attempt_count))\n\n if not opts.quiet:\n print(\"Ingested {0} out of {1} records\".format(totres.success_count,\n totres.attempt_count))\n\n if totres.failure_count > 0:\n stat = 2\n return stat\n\ndef load_from_dir(dirpath, loader, validate=True, archdir=None):\n results = LoadLog()\n\n for root, dirs, files in os.walk(dirpath):\n # don't look in .directorys\n for i in range(len(dirs)-1, -1, -1):\n if dirs[i].startswith('.'):\n del dirs[i]\n\n for f in files:\n if f.startswith('.') or not f.endswith('.json'):\n continue\n f = os.path.join(root, f) \n load_from_file(f, loader, validate, archdir, results)\n \n return results\n\ndef load_from_file(filepath, loader, validate=True, archdir=None, results=None):\n with open(filepath) as fd:\n try:\n data = json.load(fd)\n except ValueError as ex:\n ex = JSONEncodingError(ex)\n return LoadLog().add(filepath, ex)\n\n out = loader.load(data, validate=validate, results=results, id=filepath)\n\n if archdir and out.failure_count == 0:\n recid = re.sub(r'/.*$', '', re.sub(r'ark:/\\d+/', '', data.get('@id','')))\n if not recid:\n # should not happen\n recid = filepath\n ver = data.get('version', '1.0.0').replace('.', '_')\n outfile = os.path.join(archdir, \"%s-v%s.json\" % (os.path.basename(recid), ver))\n\n # this should not raise errors, but if it does, let it bubble up\n shutil.move(filepath, outfile)\n \n return out\n\n\n\ndef fmterrs(errs):\n msgs = str(errs[0]).split(\"\\n\")\n out = msgs[0]\n if len(errs) > 1 or len(msgs) > 1:\n out += \"...\"\n return out\n \n \nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","sub_path":"scripts/ingest-nerdm-res.py","file_name":"ingest-nerdm-res.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"123186952","text":"import os\nimport csv\nimport sys\nimport logging\nfrom threading import RLock, Thread\n\ndef pick_projects(directory):\n \"\"\"\n Finds all subdirectories in directory containing a .json file\n :param directory: string containing directory of subdirectories to search\n :return: list projects found under the given directory\n \"\"\"\n ext = '.json'\n subs = [x[0] for x in os.walk(directory,followlinks=True)]\n projects = []\n\n for sub in subs:\n files = []\n for f in os.listdir(sub):\n if f.endswith(ext):\n files.append(f)\n if len(files) > 0:\n sizes = [os.stat(os.path.join(sub, pick)).st_size for pick in files]\n max_size = max(sizes)\n index = sizes.index(max_size)\n projects.append(os.path.join(sub, files[index]))\n return projects\n\ndef pick_zipped_projects(directory):\n \"\"\"\n Finds all subdirectories in directory containing a .json file\n :param directory: string containing directory of subdirectories to search\n :return: list projects found under the given directory\n \"\"\"\n ext = '.tgz'\n subs = [x[0] for x in os.walk(directory)]\n projects = []\n\n for sub in subs:\n for f in os.listdir(sub):\n if f.endswith(ext):\n projects.append(os.path.join(sub,f))\n return projects\n\nclass BatchProcessor:\n\n def __init__(self, completeFile, itemsToProcess, threads=1):\n self.completefile = completeFile if completeFile is not None else str(os.getpid()) + '.txt'\n self.itemsToProcess = itemsToProcess\n self.threads=threads\n self.count = 0\n self.lock = RLock()\n\n def _thread_worker(self, total, func_to_run,done_file,error_writer):\n while not self.q.empty():\n try:\n item_to_process = self.q.get_nowait()\n if item_to_process is None:\n break\n item_id = item_to_process[0] if isinstance(item_to_process,tuple) else item_to_process\n logging.getLogger('maskgen').info('Project updating: ' + str(item_id))\n errors = func_to_run(item_to_process)\n if errors is not None:\n for error in errors:\n if type(error) == tuple:\n error_writer.writerow((str(item_id),) + error)\n else:\n error_writer.writerow((str(item_id), error))\n with self.lock:\n self.count += 1\n logging.getLogger('maskgen').info(\n 'Project updated [' + str(self.count) + '/' + str(total) + '] ' + str(item_id))\n\n done_file.write(item_id + '\\n')\n done_file.flush()\n except Exception as e:\n logging.getLogger('maskgen').error(str(e))\n logging.getLogger('maskgen').error('Project skipped: ' + str(item_id))\n\n def process(self, func):\n from Queue import Queue\n from functools import partial\n skips = []\n if os.path.exists(self.completefile):\n with open(self.completefile, 'r') as skip:\n skips = skip.readlines()\n skips = [x.strip() for x in skips]\n count = 0\n total = len(self.itemsToProcess)\n logging.getLogger('maskgen').info('Processing {} projects'.format(total))\n name=0\n threads=[]\n self.q = Queue()\n for item_to_process in self.itemsToProcess:\n if item_to_process not in skips:\n self.q.put(item_to_process)\n with open(self.completefile, 'a') as done_file:\n with open(os.path.join('ErrorReport_' + str(os.getpid()) + '.csv'), 'w') as csvfile:\n error_writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n thread_func = partial(self._thread_worker, total, func, done_file, error_writer)\n for i in range(int(self.threads)):\n name += 1\n t = Thread(target=thread_func, name=str(name))\n threads.append(t)\n t.start()\n for thread in threads:\n thread.join()\n return self.count\n","sub_path":"maskgen/batch/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"381702450","text":"import pyperclip\n\na = [\"a\", 440.00]\na_s = [\"a#\", \"bb\", 466.16]\nb = [\"b\", \"cb\", 493.88]\nc = [\"c\", \"b#\", 523.25]\nc_s = [\"c#\", \"db\", 554.37]\nd = [\"d\", 587.33]\nd_s = [\"d#\", 622.25]\ne = [\"e\", \"fb\", 329.63]\nf = [\"f\", \"e#\", 349.23]\nf_s = [\"f#\", 369.99]\ng = [\"g\", 392.00]\ng_s = [\"g#\", \"ab\", 415.30]\n\nlist_of_tone_values = [a, a_s, b, c, c_s, d, d_s, e, f, f_s, g, g_s]\nnote_string = input(\"Type in every note with a space between each one:\\n\").lower()\nnote_list = note_string.split()\nlength_string = \"Type in every note length with a space between each one (quarter = 0.25, half = 0.5, whole = 1, etc.):\"\nlength_list = length_string.split()\nfor i in range(len(length_list)):\n length_list[i] = float(length_list[i])\npin_var = input(\"Type in the variable name of the pin you will be using:\\n\")\nfinal_string = \"\"\n\nfor i in range(len(note_list)):\n for o in range(len(list_of_tone_values)):\n if note_list[i] in list_of_tone_values[o]:\n final_string += (\n \"tone(\"\n + pin_var\n + \", \"\n + str(list_of_tone_values[o][-1])\n + \", \"\n + str(length_list[o] * 2000)\n + \");\\ndelay(\"\n + str((length_list[o] * 2000) + 50)\n + \");\\n\"\n )\n\nprint(final_string)\npyperclip.copy(final_string)\n","sub_path":"computer-technology/labs/speaker/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"269166129","text":"# 自己实现的,基于leetcode-300,写的比较复杂,1432 ms, 在所有 Python 提交中击败了8.06%\nclass Solution(object):\n def findNumberOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n n = len(nums)\n # dp[i]的值代表以nums[i]结尾的最长上升子序列的长度\n dp = [1] * n\n # combination[i]的值代表以nums[i]结尾的最长上升子序列的个数\n # 注意:1.初始化的时候combination[1...n]要初始化为0,否则后面有可能会多1\n combination = [1] + [0] * (n - 1)\n for i in range(1, n):\n\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\n\n flag = False\n for j in range(i):\n if nums[i] > nums[j] and dp[j] + 1 == dp[i]:\n flag = True\n # 注意:2.不是加1,而是加combination[j],一开始写错了\n # combination[i] += 1\n combination[i] += combination[j]\n # 注意3:flag为False代表nums[0..i-1]中数都大于nums[i],所以以nums[i]结尾的最长上升子序列就是其本身,当然,只有一个\n if not flag:\n combination[i] = 1\n # print(dp)\n # print(combination)\n return sum(combination[i] for i in range(n) if dp[i] == max(dp))\n\n\n# 852 ms, 在所有 Python 提交中击败了35.48%的用户\nclass Solution(object):\n def findNumberOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n n = len(nums)\n # length[i]的值代表以nums[i]结尾的最长上升子序列的长度\n # count[i]的值代表以nums[i]结尾的最长上升子序列的个数\n length, count = [1] * n, [1] * n\n for i in range(1, n):\n for j in range(i):\n if nums[i] > nums[j]:\n if length[i] < length[j] + 1:\n length[i] = length[j] + 1\n count[i] = count[j]\n elif length[i] == length[j] + 1:\n count[i] += count[j]\n # 直接最后一步根据length数组和count数组计算最长递增子序列的个数\n return sum(count[i] for i in range(n) if length[i] == max(length))\n\n\n# 572 ms, 在所有 Python 提交中击败了88.71%的用户\nclass Solution(object):\n def findNumberOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n n = len(nums)\n # 注意:下面的i是从1开始进行迭代的,所以,这里的初始应该为1,而不是0\n res = max_len = 1\n # length[i]的值代表以nums[i]结尾的最长上升子序列的长度\n # count[i]的值代表以nums[i]结尾的最长上升子序列的个数\n length, count = [1] * n, [1] * n\n for i in range(1, n):\n for j in range(i):\n if nums[i] > nums[j]:\n if length[i] == length[j] + 1:\n count[i] += count[j]\n elif length[i] < length[j] + 1:\n length[i] = length[j] + 1\n count[i] = count[j]\n if max_len == length[i]:\n res += count[i]\n elif max_len < length[i]:\n max_len = length[i]\n res = count[i]\n return res\n","sub_path":"题目分类/动态规划/number_of_longest_increasing_subsequence_673.py","file_name":"number_of_longest_increasing_subsequence_673.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"454673306","text":"from .Architecture import Architecture\nfrom ..Log import Log\nfrom ...observer import Observable, Status\nimport tensorflow as tf\nimport sys\n\n\nclass Brain(metaclass=Observable):\n _m_arc: Architecture\n _m_weights = []\n _m_biases = []\n _m_model = None\n _m_session = None\n _m_activation_function = None\n\n _m_status = Status()\n\n def __init__(self, architecture: Architecture):\n super().__init__()\n self._m_arc = architecture\n self.x = tf.placeholder('float32', shape=(1, architecture.input_number))\n self.y = tf.placeholder('float32', shape=(1, architecture.output_number))\n\n def run_session(self, functions):\n with tf.Session() as sess:\n self._define_model()\n self._define_model_cost_optimize()\n self._m_session = sess\n init = tf.global_variables_initializer()\n self._m_session.run(init)\n result = []\n for f in functions:\n result.append(f())\n self._m_session = None\n return result\n\n def feed_with_zeros(self):\n self._m_weights = 0\n self._m_biases = 0\n\n def feed_with_ones(self):\n self._m_weights = 1\n self._m_biases = 1\n\n def feed_with_aleatory_entropy(self,w: float,b: float):\n self._m_weights = w\n self._m_biases = b\n\n def feed_with(self, weights, biases, have_to_check=True):\n self._m_status.fct = 'feed_with'\n if have_to_check:\n self._check_feed(weights, biases)\n self._m_biases = biases\n self._m_weights = weights\n\n def train(self, batch_x, batch_y, number_of_epoch, have_to_check=True):\n if have_to_check:\n self._check_batch(batch_x, batch_y)\n\n if self._m_session is None:\n Log.e(\"Train method had to be called as run_session([partial(function_to_call),parameters])\")\n\n self._m_status.fct = 'train'\n self._m_status.iteration_n = number_of_epoch\n sess = self._m_session\n cost = self.cost\n optimizer = self.optimizer\n variables_names = [v.name for v in tf.trainable_variables()]\n\n number_of_batch = len(batch_x)\n best_var = any\n best_loss = float('inf')\n for epoch in range(number_of_epoch):\n self._m_status.iteration_i = epoch\n total_loss = 0\n for i in range(number_of_batch):\n a, c = sess.run([optimizer, cost], feed_dict={self.x: [batch_x[i]], self.y: [batch_y[i]]})\n total_loss += c\n\n total_loss = total_loss / number_of_batch\n if total_loss < best_loss:\n self._m_status.option = str(total_loss)\n best_loss = total_loss\n values = sess.run(variables_names)\n best_var = zip(variables_names, values)\n\n i = 0\n weights = []\n biases = []\n for k, v in zip(variables_names, best_var):\n if i % 2 == 0:\n weights.append(v[1].tolist())\n else:\n biases.append(v[1].tolist())\n i += 1\n return {'weights': weights, 'biases': biases}\n\n def calc_accuracy(self, inputs_x, inputs_y):\n if self._m_session is None:\n Log.e(\"Train method had to be called as run_session([partial(function_to_call),parameters])\")\n\n self._m_status.fct = 'calc_accuracy'\n acc = 0\n number_of_batch = len(inputs_x)\n self._m_status.iteration_n = number_of_batch\n for i in range(number_of_batch):\n self._m_status.iteration_i = i\n correct_prediction = tf.equal(tf.argmax(self._m_model, 1), tf.argmax(self.y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n acc += accuracy.eval({self.x: [inputs_x[i]], self.y: [inputs_y[i]]})\n return 100 * acc / number_of_batch\n\n def calc_value(self, input_x):\n if self._m_session is None:\n Log.e(\"Train method had to be called as run_session([partial(function_to_call),parameters])\")\n sess = self._m_session\n return sess.run(tf.argmax(self._m_model, 1), {self.x: [input_x]})\n\n def calc_values(self, inputs_x):\n if self._m_session is None:\n Log.e(\"Train method had to be called as run_session([partial(function_to_call),parameters])\")\n\n self._m_status.fct = 'calc_values'\n self._m_status.iteration_n = len(inputs_x)\n sess = self._m_session\n output = []\n index = 0\n for input_x in inputs_x:\n self._m_status.iteration_n = index\n output.append(sess.run(tf.argmax(self._m_model, 1), {self.x: [input_x]})[0])\n index += 1\n return output\n\n def set_activation_function(self, f):\n if f == 'sigmoid':\n self._m_activation_function = tf.sigmoid\n elif f == 'relu':\n self._m_activation_function = tf.nn.relu\n elif f == 'relu6':\n self._m_activation_function = tf.nn.relu6\n elif f == 'tanh':\n self._m_activation_function = tf.nn.tanh\n else:\n print('RTFD')\n sys.exit(-1)\n\n def _define_model(self):\n self._m_model = self._create_model()\n\n def _define_model_cost_optimize(self):\n self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self._m_model, labels=self.y))\n self.optimizer = tf.train.AdamOptimizer().minimize(self.cost)\n\n def _check_feed_biases(self, biases):\n for index in range(0, len(biases)-2):\n bias = biases[index][0]\n if len(bias) != self._m_arc.hidden_layers[index]:\n Log.e('biases['+str(index)+'] should be shape '\n '(' + str(self._m_arc.hidden_layers[index]) + ')'\n ' and is (' + str(len(bias)) + ')')\n\n bias = biases[-1][0]\n if len(bias) != self._m_arc.output_number:\n Log.e('biases[-1] should be shape '\n '(' + str(self._m_arc.output_number) + ')'\n ' and is (' + str(len(bias)) + ')')\n\n def _check_feed_weights(self, input_weights, hidden_weights, output_weights):\n if len(self._m_arc.hidden_layers) == 0:\n next_layer_size = self._m_arc.output_number\n else:\n next_layer_size = self._m_arc.hidden_layers[0]\n\n if len(input_weights) != self._m_arc.input_number:\n Log.e('weights[0] should be shape '\n '(' + str(self._m_arc.input_number) + ',' + str(next_layer_size) + ')'\n ' and is (' + str(len(input_weights)) + ',)')\n for input_weight in input_weights:\n if len(input_weight) != next_layer_size:\n Log.e('weights[0] should be shape '\n '(' + str(self._m_arc.input_number) + ',' + str(next_layer_size) + ')'\n ' and is (' + str(len(input_weight)) + ',)')\n\n index = 0\n next_layer_size = self._m_arc.input_number\n for hidden_weight in hidden_weights:\n if index == 0:\n index += 1\n next_layer_size = self._m_arc.hidden_layers[index]\n continue\n if len(hidden_weight) != self._m_arc.hidden_layers[index]:\n Log.e('weights[' + str(index+1) +'] should be shape '\n '(' + str(self._m_arc.hidden_layers[index]) + ',' + str(next_layer_size) + ')'\n ' and is (' + str(len(hidden_weight)) +',)')\n for hidden_weight_n in hidden_weight:\n if len(hidden_weight_n) != next_layer_size:\n Log.e('weights[' + str(index+1) +'] should be shape '\n '(' + str(self._m_arc.hidden_layers[index]) + ',' + str(next_layer_size) + ')'\n ' and is (' + str(len(hidden_weight)) +',' + str(len(hidden_weight_n)) +')')\n index += 1\n next_layer_size = self._m_arc.hidden_layers[index]\n\n if len(output_weights) != next_layer_size:\n Log.e('weights[-1] should be shape '\n '(' + str(next_layer_size) +',' + str(self._m_arc.output_number) + ')'\n ' and is (' + str(len(output_weights)) +',)')\n for output_weight in output_weights:\n if len(output_weight) != self._m_arc.output_number:\n Log.e('weights[-1] should be shape '\n '(' + str(next_layer_size) +',' + str(self._m_arc.output_number) + ')'\n ' and is (' + str(len(output_weights)) +',' + str(len(output_weight)) +')')\n\n def _check_feed(self, weights, biases):\n if len(weights) != len(biases):\n Log.e('length weights should be ' + str(len(self._m_arc.hidden_layers) + 1))\n if len(weights) != (len(self._m_arc.hidden_layers)+1):\n Log.e('length weights should be ' + str(len(self._m_arc.hidden_layers) + 1))\n \n input_w = weights[0]\n hidden_w = [weights[i] for i in range(1, len(weights)-1)]\n output_w = weights[-1]\n self._check_feed_weights(input_weights=input_w, hidden_weights=hidden_w, output_weights=output_w)\n self._check_feed_biases(biases)\n\n def _check_batch(self, batch_x, batch_y):\n if len(batch_x)!=len(batch_y):\n Log.e('batch_x and batch_y does not have the same length')\n for index in range(len(batch_x)):\n if len(batch_x[index]) != self._m_arc.input_number:\n Log.e('batch_x[' + str(index) +'] should be shape(' + self._m_arc.input_number + ')')\n if len(batch_y[index]) != self._m_arc.output_number:\n Log.e('batch_y[' + str(index) +'] should be shape(' + self._m_arc.output_number + ')')\n\n def _biases(self, i, size):\n if self._m_biases == 1:\n return tf.ones([1, size], tf.float32)\n if self._m_biases == 0:\n return tf.zeros([1, size], tf.float32)\n if isinstance(self._m_biases, float):\n return tf.random_normal([1, size],stddev=self._m_biases)\n elif len(self._m_biases) != 0:\n return self._m_biases[i]\n return tf.random_normal([1, size])\n\n def _weights(self, i, size_x, size_y):\n if self._m_weights == 1:\n return tf.ones([size_x, size_y], tf.float32)\n if self._m_weights == 0:\n return tf.zeros([size_x, size_y], tf.float32)\n if isinstance(self._m_weights, float):\n return tf.random_normal([size_x, size_y],stddev=self._m_weights)\n elif len(self._m_weights) != 0:\n return self._m_weights[i]\n return tf.random_normal([size_x, size_y])\n\n def _create_model(self):\n data = self.x\n number_of_layer = len(self._m_arc.hidden_layers)\n if number_of_layer >= 1:\n last_layer = self._m_arc.input_number\n last_layer_calc = data\n index = 0\n for hidden_layer in self._m_arc.hidden_layers:\n hidden_layer_temp = {\n 'weights': tf.Variable(self._weights(index, size_x=last_layer, size_y=hidden_layer)),\n 'biases': tf.Variable(self._biases(index, size=hidden_layer))}\n last_layer_calc = tf.add(tf.matmul(last_layer_calc, hidden_layer_temp['weights']), hidden_layer_temp['biases'])\n last_layer_calc = self._activation_function(last_layer_calc)\n\n last_layer = hidden_layer\n index += 1\n\n output_layer = {\n 'weights': tf.Variable(self._weights(index, size_x=last_layer, size_y=self._m_arc.output_number)),\n 'biases': tf.Variable(self._biases(index, size=self._m_arc.output_number))}\n\n output = tf.add(tf.matmul(last_layer_calc, output_layer['weights']), output_layer['biases'])\n\n else:\n layer = {'weights': tf.Variable(tf.random_normal([self._m_arc.input_number, self._m_arc.output_number])),\n 'biases': tf.Variable(tf.random_normal([1, self._m_arc.output_number]))}\n\n output = tf.add(tf.matmul(data, layer['weights']), layer['biases'])\n\n output = self._activation_function(output)\n return output\n\n def _activation_function(self, v):\n if self._m_activation_function is None:\n return tf.nn.relu(v)\n else:\n return self._m_activation_function(v)\n\n def _o_get_status(self):\n return self._m_status\n","sub_path":"oh_my_brain/neural_network/Perceptron/Brain.py","file_name":"Brain.py","file_ext":"py","file_size_in_byte":12372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"199008526","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nlist_of_names = ['Roger', 'Mary', 'Luisa', 'Elvis']\nlist_of_ages = [23, 24, 19, 86]\nlist_of_heights_cm = [175, 162, 178, 182]\n\n#[A]\nprint('\\nA')\nfor name in list_of_names:\n print(\"The name {:} is {:} letters long\".format(name, len(name)))\n\n#[B]\nprint('\\n\\nB')\nnewlist=[len(x) for x in list_of_names]\nprint('lenght of names:')\nprint(newlist)\n#[E]\nimport person\n\npeople={list_of_names[i]:person.person(list_of_names[i],list_of_ages[i],list_of_heights_cm[i])for i in range(0,len(list_of_names))}\nprint('\\n\\nE')\nprint (people) \n\n#[F]\na=np.array(list_of_ages)\n\nb=np.array(list_of_heights_cm)\n\n#[G]\nmean_of_ages=np.mean(a)\nprint('\\n\\nG')\nprint(f\"The mean of ages of the people is {mean_of_ages}\")\n\n#[H]\nplt.scatter(list_of_ages,list_of_heights_cm)\nplt.xlabel(\"age\")\nplt.ylabel(\"height\")\nplt.grid(axis='both')\nplt.title(\"Scatter Plot of Age and Height\")","sub_path":"hw1_python_basics/hw1p1.py","file_name":"hw1p1.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"29027646","text":"# -*- coding: utf-8 -*-\nimport os\nimport requests\nfrom lxml import etree\n\n\ns = requests.Session()\n\n\ndef get_platid():\n response = s.get('http://www.xiaohulu.com/anchor2/')\n html = etree.HTML(response.content)\n nodes = html.xpath('//li[@class=\"gameplat\"] | //li[@class=\"recreationplat\"]')\n for node in nodes:\n yield (node.get('data-platid'), node.findtext('h5'))\n\n\ndef get_rooms(platid=2):\n base_url = \"http://www.xiaohulu.com/anchor2/ajax_index_hulu\"\n params = {'time': '60m',\n 'platstr': str(platid),\n 'at': 'hulu_dms',\n 'day': 'week&w=1',\n 'classstr': ''\n }\n response = s.get(base_url, params=params)\n try:\n rooms = response.json().get('data')\n fname = \"./data/rooms/platid_\" + platid\n fdir = os.path.split(fname)[0]\n if not os.path.isdir(fdir):\n os.makedirs(fdir)\n if os.path.exists(fname):\n os.remove(fname)\n with open(fname, \"a\") as f:\n f.writelines('\\n'.join([room.get('source_link') for room in rooms]))\n except AttributeError:\n return\n\n\nif __name__ == '__main__':\n for platid, plat_name in get_platid():\n print('Fetching %s live rooms' % (plat_name,))\n get_rooms(platid)\n","sub_path":"fetch_rooms.py","file_name":"fetch_rooms.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"178711865","text":"\"\"\"\n\nDense Basis SED fitting code.\n\n\n\"\"\"\n\n\nimport numpy as np\nfrom numpy import linalg as LA\nimport scipy.io as sio\nimport random as rn\nimport os\nimport warnings\nimport random\nimport sys\nimport time\n\n\"\"\"\n\npython script to run dense basis SED fitting on the CANDELS catalog on CALIBURN.\n\nneeds the following functions\n\nimport catalog\nsplit catalog among nodes\ngenerate SFH basis\nsplit SFH basis among processes within a node\nfit SEDs available with basis SFHs available\npoll for minimum chi^2. (or avoid this step if statistics allow)\ncompute uncertainties on reconstructed SFH\ncompress and store results\n\n\"\"\"\n\n# Dependencies: Write code to check if installed\n\nfrom tqdm import tqdm\nimport fsps\nfrom astropy.cosmology import FlatLambdaCDM\n#import ipyparallel as ipp\n\n# used for goodrun\n#catalog_path = 'catalogs_full/cs_z'\ncatalog_path = 'vac/phot/cs_z'\n\n#redshift = float(sys.argv[1])\n#dustval = int(sys.argv[2])\n#metallicity = int(sys.argv[3])\nredshift = 0.5\n#redshift = temp.astype(np.float)\n#print('fitting catalog at redshift: '+ str(redshift))\n\n\ncosmo = FlatLambdaCDM(H0=70, Om0=0.3)\nageuniv = cosmo.age(redshift).value\n\nsfh_data = sio.loadmat('data/basis.mat')\nnewtime = np.array(sfh_data['newtime'])\n\n\ndef run_DB_now_single(redshift):\n\t#if len(input_arr) == 3:\n\tprint('init DB.')\t\n\t\n\ttemp = RunDenseBasis(redshift,Av=0,Zv=6)\n\tdel temp\n\treturn\n\n\ndef run_DB_now(input_arr):\n\n\ttemparr = np.array(input_arr)\n\tredshift = temparr[0]\n\tZv = int(temparr[1])\n\tAv = int(temparr[2])\n\tprint('init DB.')\t\n\t\n\ttemp = RunDenseBasis(redshift,Av,Zv)\n\tdel temp\n\treturn\n\nclass RunDenseBasis:\n\n\tdef __init__(self, redshift,Av = 0, Zv = 6, nep=1, catalog_path = 'vac/phot/cs_z', vb = False):\n\n\t\trun_title = 'trials'\n\t\tfh = 'log_files/'+run_title+'_z_'+str(redshift)+'_Z_'+str(Zv)+'_Av_'+str(Av)+'_nep_'+str(nep)+'.log'\n\t\tlogfile_handle = open(fh, 'w+')\n\n\t\tt_init = time.time()\n\t\t\n\t\tlogfile_handle.write('-------------------------------------------------------- \\n')\n\t\tlogfile_handle.write('----------Initializing Dense Basis SED fitting---------- \\n')\n\t\tlogfile_handle.write('-------------------------------------------------------- \\n \\n')\n\n\t\tlogfile_handle.write('>> Preparing to fit catalog at redshift: '+ str(redshift)+'\\n')\n\n\t\t# code to initialize a stellar population\n\n\t\tself.redshift = redshift\n\n\t\tmocksp = fsps.StellarPopulation(compute_vega_mags=False, zcontinuous=1,sfh=0, imf_type=1, logzsol=0.0, dust_type=2, dust2=0.0, add_neb_emission=True)\n\t\t[lam,temp] = mocksp.get_spectrum(tage = 5.9)\n\t\tself.mocksp = mocksp\n\t\tself.lam = lam\n\t\tself.temp = temp\n\n\t\t#Av = 5\n\t\t#Zv = 6\n\n\t\t# initialize a cosmology to determine luminosity distances and ages of the universe at different redshifts\n\n\t\tcosmo = FlatLambdaCDM(H0=70, Om0=0.3)\n\t\tageuniv = cosmo.age(redshift).value\n\t\tself.cosmo = cosmo\n\t\tself.ageuniv = ageuniv\n\t\tlogfile_handle.write('The age of the universe at this redshift is '+str(ageuniv) + ' Gyr. \\n')\n\n\t\t# centers of the 17 CANDELS filters\n\n\t\tcenters = np.array([3734,3722,4317,5918,7693,8047,9055,9851,10550,12486,15370,21605,21463,35508,44960,57245,78840])\n\t\tself.centers = centers\n\n\n\n\t\tlogfile_handle.write('>> Importing Catalog to fit: \\n')\n\t\tsed_fits, sed_err, tpu = self.import_catalog(redshift)\n\t\tlogfile_handle.write('>> Size of imported catalog: '+ str(sed_fits.shape[1]) +'\\n')\n\n\n\t\tlogfile_handle.write('>> Importing filter curves at redshift '+str(redshift)+'\\n')\n\t\t#used for goodrun\n\t\t#kitname = 'fkilt/codex_filter_val_kit_fsps_'+str(redshift)+'.mat'\n\t\tkitname = 'vac/fkilt/codex_filter_val_kit_fsps_'+str(redshift)+'.mat'\n\t\tfilt_data = sio.loadmat(kitname)\n\t\tlam_z = np.array(filt_data['lambda_z'])\n\t\tlam_z_lores = np.array(filt_data['lambda_z_lores'])\n\t\tfilcurves = np.array(filt_data['filtercurve'])\n\n\n\t\t# add code to check which Nbands must be true depending on redshift\n\t\t# lambda = rest frame PAH *(1+z) should not be in filter\n\t\tNbands = [True,True,True,True,True,True,True,True,True,True,True,True,True,True,True,False,False]\n\t\tgalid = 1\n\n\t\t#tau = np.power(10,np.linspace(-1,2,10))\n\t\t#t0 = np.linspace(0,ageuniv,30)\n\n\n\t\t\"\"\" Needs parallelization here: try splitting along basis,\n\t\t\tor each dust and metallicity (easier for now) - done as wrapper\n\n\t\t\"\"\"\n\n\t\t#logfile_handle.write('>> Initializing default linexp SFH basis. \\n')\n\t\t#tau, t0, newtime, default_basis, params = self.generate_basis(ageuniv)\n\n\t\tlogfile_handle.write('>> Initializing pruned 3-family SFH basis. \\n')\n\t\tnewtime, default_basis, params = self.load_pruned_basis(ageuniv)\n\n\t\tprint(newtime.shape, default_basis.shape, params.shape)\n\t\t\n\n\t\t# can use dview.push, dview.scatter, dview.gather, dview.pull for transfers\n\n\t\tlogfile_handle.write('>> Generating Spectra, SEDs \\n')\n\t\tspectra, seds, lam = self.generate_spectra(default_basis , mocksp, lam, lam_z, lam_z_lores, filcurves, redshift = redshift, dustval = Av, metallicity = Zv)\n\n\t\tlogfile_handle.write('>> Making N component basis \\n')\n\t\ttemp_sed, temp_sfh, temp_param = self.make_N_component_basis(seds.T, default_basis.T, params, dubl_brst= nep)\n\t\tflatbasis, flatnormbasis = self.make_flatbasis(temp_sed.T)\n\n\t\tlogfile_handle.write('>> Basis shapes | SEDs = '+ str(temp_sed.shape)+' SFHs = '+str(temp_sfh.shape)+' params: '+ str(temp_param.shape)+'\\n')\n\t\t\n\t\t#print('>> Fitting a single galaxy SED')\n\t\t#bfval, bfin, c2srf, mf, nb_new = self.fit_single_SED(temp_sed,sed_fits[0:,galid],tpu.ravel(),sed_err[0:,galid],Nbands)\n\t\t#print('>> Fit with chi2 = '+str(bfval))\n\t\t#print('>> Calculating uncertainties for a single SEDfit')\n\t\t#rec_median_sfh, rec_std_sfh, rec_prct_uppr, rec_prct_lowr = self.get_uncertainties(c2srf,mf,temp_sfh)\n\t\t#print(c2srf.shape)\n\t\t#print(mf.shape)\n\n\t\tt1 = time.time()\n\t\tlogfile_handle.write('>> Finished prep. Time elapsed: '+str(t1-t_init)+' sec. \\n \\n')\n\n\t\tlogfile_handle.write('>> Fitting entire catalog, with ' + str(sed_fits.shape[1]) + ' galaxies. \\n')\n\n\t\trec_chi2, rec_index, rec_mf, rec_c2s, rec_massfac, rec_Nbands = self.fit_catalog(temp_sed,sed_fits,tpu.ravel(),sed_err[0:,galid],Nbands)\n\n\t\tt2 = time.time()\n\t\tlogfile_handle.write('>> Finished fitting catalog in '+str(t2-t1)+' sec. \\n \\n')\n\n\n\n\t\t#rec_median_sfh = np.zeros((len(newtime.T),len(rec_chi2) ))\n\t\t#rec_std_sfh = np.zeros((len(newtime.T),len(rec_chi2) ))\n\t\t#rec_prct_uppr = np.zeros((len(newtime.T),len(rec_chi2) ))\n\t\t#rec_prct_lowr = np.zeros((len(newtime.T),len(rec_chi2) ))\n\t\t#for i in tqdm(range(len(rec_chi2))):\n\t\t#\ttemp = rec_massfac[0:,galid]\n\t\t#\ttemp.shape = (len(rec_c2s[0:,galid]),1)\n\t\t#\ttempa, tempb, tempc, tempd = self.get_uncertainties(rec_c2s[0:,galid].ravel(),temp,temp_sfh)\n\t\t#\trec_median_sfh[0:,galid] = tempa.ravel()\n\t\t#\trec_std_sfh[0:,galid] = tempb.ravel()\n\t\t#\trec_prct_uppr[0:,galid] = tempc.ravel()\n\t\t#\trec_prct_lowr[0:,galid] = tempd.ravel()\n\n\t\t#t3 = time.time()\n\t\t#logfile_handle.write('>> Finished computing uncertainties in '+str(t3-t2)+' sec. \\n \\n')\n\n\t\tlogfile_handle.write('>> Saving files to disk \\n')\n\t\tself.save_outputs(rec_chi2, rec_index, rec_mf, rec_c2s, rec_massfac, rec_Nbands, output_path = 'outputs/trials', z=redshift, Z=Zv, Av =Av, nep = 1)\n\t\t#self.save_outputs(rec_chi2, rec_index, rec_mf, rec_median_sfh, rec_std_sfh, rec_prct_lowr, rec_prct_uppr, rec_Nbands, output_path = 'outputs/trials', z=redshift, Z=Zv, Av =Av, nep = nep)\n\n\t\ttfinal = time.time()\n\t\tlogfile_handle.write('Finished run in '+str(tfinal-t_init)+ ' sec')\n\n\t\tlogfile_handle.close()\n\t\t\t\n\t\tdel rec_chi2, rec_index, rec_mf, rec_c2s, rec_massfac, rec_Nbands, run_title, logfile_handle, fh, redshift, t_init, t1, t2, spectra, seds, lam, temp_sed, temp_sfh, temp_param, mocksp, flatbasis, flatnormbasis\n\n\t\treturn\n\t\t#return mocksp, ageuniv, filcurves, lam_z, lam_z_lores\n\n#-----------------------------custom code for fitting a single SED----------------------------------------------------\n\n\tdef custom_SED_fit(custom_SED, custom_err, redshift,Av = 0, Zv = 6, nep=1, vb = False):\n\t\tt_init = time.time()\n\t\t\n\t\tprint('--------------------------------------------------------')\n\t\tprint('----------Initializing Dense Basis SED fitting----------')\n\t\tprint('-------------------------------------------------------- \\n')\n\n\t\tprint('>> Preparing to fit catalog at redshift: '+ str(redshift))\n\n\t\t# code to initialize a stellar population\n\n\t\t#self.redshift = redshift\n\n\t\tmocksp = fsps.StellarPopulation(compute_vega_mags=False, zcontinuous=1,sfh=0, imf_type=1, logzsol=0.0, dust_type=2, dust2=0.0, add_neb_emission=True)\n\t\t[lam,temp] = mocksp.get_spectrum(tage = 5.9)\n\t\t#self.mocksp = mocksp\n\t\t#self.lam = lam\n\t\t#self.temp = temp\n\n\t\t#Av = 5\n\t\t#Zv = 6\n\n\t\t# initialize a cosmology to determine luminosity distances and ages of the universe at different redshifts\n\n\t\tcosmo = FlatLambdaCDM(H0=70, Om0=0.3)\n\t\tageuniv = cosmo.age(redshift).value\n\t\t#self.cosmo = cosmo\n\t\t#self.ageuniv = ageuniv\n\t\tprint('The age of the universe at this redshift is '+str(ageuniv) + ' Gyr.')\n\n\t\t# centers of the 17 CANDELS filters\n\n\t\tcenters = np.array([3734,3722,4317,5918,7693,8047,9055,9851,10550,12486,15370,21605,21463,35508,44960,57245,78840])\n\t\t#self.centers = centers\n\n\t\tprint('>> Importing Median photometric uncertainties at redshift '+str(redshift))\n\t\t#sed_fits, sed_err, tpu = self.import_catalog(redshift)\n\t\ttemp1, temp2, tpu = self.import_catalog(redshift)\n\t\t#logfile_handle.write('>> Size of imported catalog: '+ str(sed_fits.shape[1]) +'\\n')\n\t\tsed_fits = custom_SED\n\t\tsed_err = custom_err\n\n\n\t\tprint('>> Importing filter curves at redshift '+str(redshift)+'\\n')\n\t\t#used for goodrun\n\t\t#kitname = 'fkilt/codex_filter_val_kit_fsps_'+str(redshift)+'.mat'\n\t\tkitname = 'vac/fkilt/codex_filter_val_kit_fsps_'+str(redshift)+'.mat'\n\t\tfilt_data = sio.loadmat(kitname)\n\t\tlam_z = np.array(filt_data['lambda_z'])\n\t\tlam_z_lores = np.array(filt_data['lambda_z_lores'])\n\t\tfilcurves = np.array(filt_data['filtercurve'])\n\n\n\t\t# add code to check which Nbands must be true depending on redshift\n\t\t# lambda = rest frame PAH *(1+z) should not be in filter\n\t\tNbands = [True,True,True,True,True,True,True,True,True,True,True,True,True,True,True,False,False]\n\t\tgalid = 1\n\n\t\t#tau = np.power(10,np.linspace(-1,2,10))\n\t\t#t0 = np.linspace(0,ageuniv,30)\n\n\n\t\t\"\"\" Needs parallelization here: try splitting along basis,\n\t\t\tor each dust and metallicity (easier for now) - done as wrapper\n\n\t\t\"\"\"\n\n\t\t#logfile_handle.write('>> Initializing default linexp SFH basis. \\n')\n\t\t#tau, t0, newtime, default_basis, params = self.generate_basis(ageuniv)\n\n\t\tprint('>> Initializing pruned 3-family SFH basis. \\n')\n\t\tnewtime, default_basis, params = self.load_pruned_basis(ageuniv)\n\n\t\tprint(newtime.shape, default_basis.shape, params.shape)\n\t\t\n\n\t\t# can use dview.push, dview.scatter, dview.gather, dview.pull for transfers\n\n\t\tprint('>> Generating Spectra, SEDs \\n')\n\t\tspectra, seds, lam = self.generate_spectra(default_basis , mocksp, lam, lam_z, lam_z_lores, filcurves, redshift = redshift, dustval = Av, metallicity = Zv)\n\n\t\tprint('>> Making N component basis \\n')\n\t\ttemp_sed, temp_sfh, temp_param = self.make_N_component_basis(seds.T, default_basis.T, params, dubl_brst= nep)\n\t\tflatbasis, flatnormbasis = self.make_flatbasis(temp_sed.T)\n\n\t\tprint('>> Basis shapes | SEDs = '+ str(temp_sed.shape)+' SFHs = '+str(temp_sfh.shape)+' params: '+ str(temp_param.shape)+'\\n')\n\t\t\n\t\t#print('>> Fitting a single galaxy SED')\n\t\t#bfval, bfin, c2srf, mf, nb_new = self.fit_single_SED(temp_sed,sed_fits[0:,galid],tpu.ravel(),sed_err[0:,galid],Nbands)\n\t\t#print('>> Fit with chi2 = '+str(bfval))\n\t\t#print('>> Calculating uncertainties for a single SEDfit')\n\t\t#rec_median_sfh, rec_std_sfh, rec_prct_uppr, rec_prct_lowr = self.get_uncertainties(c2srf,mf,temp_sfh)\n\t\t#print(c2srf.shape)\n\t\t#print(mf.shape)\n\n\t\tt1 = time.time()\n\t\tprint('>> Finished prep. Time elapsed: '+str(t1-t_init)+' sec. \\n \\n')\n\n\t\tprint('>> Fitting entire catalog, with ' + str(sed_fits.shape[1]) + ' galaxies. \\n')\n\n\t\trec_chi2, rec_index, rec_mf, rec_c2s, rec_massfac, rec_Nbands = self.fit_catalog(temp_sed,sed_fits,tpu.ravel(),sed_err[0:,galid],Nbands)\n\n\t\tt2 = time.time()\n\t\tprint('>> Finished fitting catalog in '+str(t2-t1)+' sec. \\n \\n')\n\n\n\n\t\t#rec_median_sfh = np.zeros((len(newtime.T),len(rec_chi2) ))\n\t\t#rec_std_sfh = np.zeros((len(newtime.T),len(rec_chi2) ))\n\t\t#rec_prct_uppr = np.zeros((len(newtime.T),len(rec_chi2) ))\n\t\t#rec_prct_lowr = np.zeros((len(newtime.T),len(rec_chi2) ))\n\t\t#for i in tqdm(range(len(rec_chi2))):\n\t\t#\ttemp = rec_massfac[0:,galid]\n\t\t#\ttemp.shape = (len(rec_c2s[0:,galid]),1)\n\t\t#\ttempa, tempb, tempc, tempd = self.get_uncertainties(rec_c2s[0:,galid].ravel(),temp,temp_sfh)\n\t\t#\trec_median_sfh[0:,galid] = tempa.ravel()\n\t\t#\trec_std_sfh[0:,galid] = tempb.ravel()\n\t\t#\trec_prct_uppr[0:,galid] = tempc.ravel()\n\t\t#\trec_prct_lowr[0:,galid] = tempd.ravel()\n\n\t\t#t3 = time.time()\n\t\t#logfile_handle.write('>> Finished computing uncertainties in '+str(t3-t2)+' sec. \\n \\n')\n\n\t\t#logfile_handle.write('>> Saving files to disk \\n')\n\t\t#self.save_outputs(rec_chi2, rec_index, rec_mf, rec_c2s, rec_massfac, rec_Nbands, output_path = 'outputs/trials', z=redshift, Z=Zv, Av =Av, nep = 1)\n\t\t#self.save_outputs(rec_chi2, rec_index, rec_mf, rec_median_sfh, rec_std_sfh, rec_prct_lowr, rec_prct_uppr, rec_Nbands, output_path = 'outputs/trials', z=redshift, Z=Zv, Av =Av, nep = nep)\n\n\t\ttfinal = time.time()\n\t\tprint('Finished run in '+str(tfinal-t_init)+ ' sec')\n\n\t\t#logfile_handle.close()\n\t\t\t\n\t\t#del rec_chi2, rec_index, rec_mf, rec_c2s, rec_massfac, rec_Nbands, run_title, logfile_handle, fh, redshift, t_init, t1, t2, spectra, seds, lam, temp_sed, temp_sfh, temp_param, mocksp, flatbasis, flatnormbasis\n\n\t\t#return\n\t\t#return mocksp, ageuniv, filcurves, lam_z, lam_z_lores\n\t\treturn rec_chi2, rec_index, rec_mf, rec_c2s, rec_massfac, rec_Nbands\n\n\n\n\n#----------------------------------------------------------------------------------------------\n#--------------------------Validated Functions-------------------------------------------------\n#----------------------------------------------------------------------------------------------\n\n\n\n\n\n\t# do i need this here?\n\t#@dview.remote(block=True)\n\tdef gen_linexp(self, mass, tau, t0, newtime):\n\t\timport numpy as np\n\t\t#tarr = np.linspace(1e-3,5.9010,5901)\n\t\ttarr = np.arange(1e-3,np.amax(newtime),1e-3)\n\t\tsfh = np.zeros((len(tarr),))\n\t\tif tau == 0:\n\t\t\tprint('tau is zero!?')\n\t\tsfh = ((tarr)/tau)*np.exp(-((tarr)/tau))\n\t\ttind = np.argmin(np.absolute(tarr-(np.amax(newtime)-t0) ))\n\t\tif tind == 0:\n\t\t\ttind = 1\n\t\ttemp = sfh[0:tind]\n\t\tsfh = np.zeros((len(tarr),))\n\t\tsfh[-1-len(temp):-1] = temp\n\t\tsfh[-1] = temp[-1]\n\t\tmassfh = np.sum(sfh*1e5)\n\t\tsfh = sfh*mass/massfh\n\t\tsfh_interp = np.interp(newtime,tarr,sfh)\n\t\treturn sfh_interp.T\n\n\n\tdef gen_gaussian(self,mass, mu, sigma, newtime):\n\t import numpy as np\n\t tarr = np.arange(1e-3,np.amax(newtime),1e-3)\n\t sfh = np.zeros((len(tarr),))\n\t #sfh = ((tarr)/tau2)*np.exp(-((tarr)/tau2))\n\t sfh = np.exp(-((tarr-mu)*(tarr-mu)/(2*sigma*sigma)))\n\t tind = np.argmin(np.absolute(tarr-(5.9010) ))\n\t temp = sfh[0:tind]\n\t sfh = np.zeros((len(tarr),))\n\t sfh[-1-len(temp):-1] = temp\n\t sfh[-1] = temp[-1]\n\t massfh = np.sum(sfh*1e5)\n\t sfh = sfh*mass/massfh\n\t sfh_interp = np.interp(newtime,tarr,sfh)\n\t return sfh_interp.T\n\n\tdef gen_lognormal(self,mass, mu, sigma, newtime):\n\t import numpy as np\n\t tarr = np.arange(1e-3,np.amax(newtime),1e-3)\n\t sfh = np.zeros((len(tarr),))\n\t #sfh = ((tarr)/tau2)*np.exp(-((tarr)/tau2))\n\t #sfh = np.exp(-((tarr-t02)*(tarr-t02)/(2*tau2*tau2)))\n\t sfh = (1/tarr)*np.exp(-(np.log(tarr)-mu)*(np.log(tarr)-mu)/(2*sigma*sigma))\n\t tind = np.argmin(np.absolute(tarr-(5.9010-mu) ))\n\t temp = sfh[0:tind]\n\t sfh = np.zeros((len(tarr),))\n\t sfh[-1-len(temp):-1] = temp\n\t sfh[-1] = temp[-1]\n\t massfh = np.sum(sfh*1e5)\n\t sfh = sfh*mass/massfh\n\t sfh_interp = np.interp(newtime,tarr,sfh)\n\t return sfh_interp.T\n\n\tdef load_pruned_basis(self, ageuniv):\n\n\t\timport scipy.io as sio\n\t\timport numpy as np\n\n\t\tsfh_handle = sio.loadmat('data/basis.mat')\n\t\tsfhs = sfh_handle['sfh_basis_final']\n\t\ttemp = sfh_handle['newtime']\n\t\tnewtime = temp*ageuniv/np.amax(temp)\n\t\tparams = sfh_handle['params_final']\n\n\t\treturn newtime.T, sfhs.T, params.T\n\n\tdef generate_basis(self, ageuniv, tau_start = -1,tau_end = 2,tau_num = 10,t0_start = 0, t0_num = 30,sfh_family = 'linexp',vb = False):\n\n\t\t# function to generate a basis of a given parameteric family of curves\n\t\t# currently supported families: linexp, besselexp, gaussian\n\t\timport numpy as np\n\t\t# take tau range, t0 range for each SFH family. (currently linexp, expand to all families)\n\n\t\tt0_end = ageuniv\n\n\t\ttau = np.power(10,np.linspace(tau_start,tau_end,tau_num))\n\t\tt0 = np.linspace(t0_start, t0_end, t0_num)\n\n\t\tif vb == True:\n\t\t\tprint('generating basis')\n\t\t\n\t\t\tprint('tau start is: '+str(tau_start))\n\t\t\tprint('tau end is: '+str(tau_end))\n\t\t\tprint('tau num is: '+ str(tau_num))\n\t\t\t\n\t\t\tprint('Tau Array:')\n\t\t\tprint(tau)\n\t\t\tprint('t0 Array:')\n\t\t\tprint(t0)\t\t\n\n\t\tsfh_data = sio.loadmat('data/sfh_newtime.mat')\n\t\ttages = np.array(sfh_data['tage'])\n\t\tnewtime = np.array(sfh_data['newtime'])\n\t\tnewtime = newtime*ageuniv/np.amax(newtime)\n\n\n\t\tindexarray = np.zeros((10*30,1))\n\t\tindexvals = np.zeros((10*30,2))\n\t\tcounter = 0\n\t\tfor i in range(len(tau)):\n\t\t\tfor j in range(len(t0)):\n\t\t\t\tindexarray[counter] = counter\n\t\t\t\tindexvals[counter,:] = [tau[i],t0[j]]\n\t\t\t\tcounter = counter + 1\n\n\n\t\t#@dview.remote(block=True)\n\t\t#def makesmallbasis(newtime, indexvals,indexarray):\n\n\t\tsfh_set = np.zeros((len(newtime.T),len(indexarray)))\n\t\tfor i in range(len(indexarray)-1):\n\t\t\ttv = int(indexarray[i])\n\t\t\tgsfh = self.gen_linexp(1e9,indexvals[tv,0],indexvals[tv,1],newtime)\n\t\t\tsfh_set[0:,i] = gsfh.ravel()\n\t\tprint('>> SFH basis size: '+ str(sfh_set.shape))\n\t\treturn tau, t0, newtime, sfh_set.T, indexvals.T\n\n\n\n\tdef import_catalog(self, redshift = redshift, catalog_path = catalog_path):\n\n\t\t# function to import the segment of the CANDELS catalog at the given redshift\n\t\t# return summary statistics - number of SEDs, median photometric uncertainties\n\t\tprint('filename: '+ catalog_path +str(redshift)+'.mat')\n\t\tfile_handle = sio.loadmat(catalog_path+str(redshift)+'.mat')\n\t\tsed_fits = np.array(file_handle['subcat'])\n\t\tsed_err = np.array(file_handle['subcat_err'])\n\t\ttpu = np.array(file_handle['tpu'])\n\n\t\treturn sed_fits, sed_err, tpu\n\n\tdef save_outputs(self, rec_chi2, rec_index, rec_mf, rec_c2s, rec_mfs, rec_Nbands, output_path = 'outputs/default_', z=0, Z = 0, Av = 0, nep = 1):\n\n\t\t# function to import the segment of the CANDELS catalog at the given redshift\n\t\t# return summary statistics - number of SEDs, median photometric uncertainties\n\t\tfname = output_path + '_z_' +str(z)+'_Z_'+str(Z)+'_Av_'+str(Av)+'_Nep_'+str(nep)+'.mat'\n\t\tprint('saving file: '+ fname)\n\t\tsio.savemat(fname,mdict = {'rec_chi2':rec_chi2, 'rec_index':rec_index, 'rec_mf':rec_mf, 'rec_c2s':rec_c2s, 'rec_mfs':rec_mfs, 'rec_Nbands':rec_Nbands})\n\n\t\treturn\n\n\n\tdef save_outputs_alt(self, rec_chi2, rec_index, rec_mf, rec_median_sfh, rec_std_sfh, rec_prct_lowr, rec_prct_uppr, rec_Nbands, output_path = 'outputs/default_', z=0, Z = 0, Av = 0, nep = 1):\n\n\t\t# this one is with uncertainties\n\t\t# function to import the segment of the CANDELS catalog at the given redshift\n\t\t# return summary statistics - number of SEDs, median photometric uncertainties\n\t\tfname = output_path + '_z_' +str(z)+'_Z_'+str(Z)+'_Av_'+str(Av)+'_Nep_'+str(nep)+'.mat'\n\t\tprint('saving file: '+ fname)\n\t\tsio.savemat(fname,mdict = {'rec_chi2':rec_chi2, 'rec_index':rec_index, 'rec_mf':rec_mf, 'rec_median_sfh':rec_median_sfh, 'rec_std_sfh':rec_std_sfh, 'rec_prct_lowr':rec_prct_lowr, 'rec_prct_uppr':rec_prct_uppr, 'rec_Nbands':rec_Nbands})\n\n\t\treturn\n\n\n\tdef generate_spectra(self, sfhs ,sp, lam, lam_z, lam_z_lores, filcurves ,newtime = newtime, cosmo = cosmo,redshift = redshift, dustval = 0, metallicity = 0, vb = False):\n\n\t\t# function to generate spectra using FSPS corresponding to a given SFH (single or set of SFHs)\n\n\t\tdustbins = np.linspace(0.0,2,21)\n\t\tlogZbins = np.linspace(-1.5,0.5,9)\n\t \n\t\tageuniv = cosmo.age(redshift).value\n\t\tags = newtime.T\n\t\tags = ags*ageuniv/np.amax(ags)\n\t\tsfhs = sfhs.T\n\n\t\tprint('dust= '+str(dustbins[dustval]) + ' and metallicity = '+str(logZbins[metallicity]))\n\n\t\tif vb == True:\n\t\t\tprint(str(ageuniv)+' Gyr at redshift '+str(redshift))\n\t\t\tprint('have dust, metval, and inputs')\n\t\t\tprint(sfhs.shape)\n\t\t\tprint('imported stellarpopulation')\n\t\t\t[lam,temp] = sp.get_spectrum(tage = ageuniv)\n\t\t\t\n\t \n\t\tsp.params[\"dust2\"] = dustbins[dustval]\n\t\tsp.params[\"logzsol\"] = logZbins[metallicity]\n\t\tsp.params[\"sfh\"] = 3\n\t\tsp.params[\"add_igm_absorption\"] = True\n\t\tsp.params[\"zred\"] = redshift\n\t\t\n\t\tspectra = np.zeros((len(lam),sfhs.shape[1]))\n\t\tseds = np.zeros((17,sfhs.shape[1]))\n\t \n\t\tfor i in (range(sfhs.shape[1])):\n\t\t\t#tempsfh = np.flipud(sfhs[0:,i])\n\t\t\ttempsfh = (sfhs[0:,i])\n\t\t\tsp.set_tabular_sfh(ags, tempsfh)\n\t\t\t[lam,spectra[0:,i]] = sp.get_spectrum(tage = ageuniv)\n\t\t\t#seds[0:,i] = filvals_fsps_fnu(spectra[0:,i],1,lam)\n\t\t\ttemp2 = self.convert_to_microjansky(spectra[0:,i],redshift,cosmo)\n\t\t\tseds[0:,i] = self.generate_SEDs(temp2,redshift,lam,lam_z,lam_z_lores,filcurves)\n\t\t\n\t \n\t\treturn spectra.T, seds.T, lam\n\n\n\tdef convert_to_microjansky(self, spec, z ,cosmo):\n\t\t# 1e6 for Jansky to microJansky\n\t\t# 3.48e33 for solar luminosity in ergs/s\n\t\t# 3.086e+24 for Mpc to cm in dL\n\t\ttemp = spec *1e6 * 1e23*3.48e33*(1+z)/(4*np.pi*3.086e+24*3.086e+24*cosmo.luminosity_distance(z).value*cosmo.luminosity_distance(z).value)\n\t\treturn temp\n\n\tdef generate_SEDs(self, spec ,z ,lam ,lam_z ,lam_z_lores, filcurves):\n\n\t\t# function to multiply a spectrum (or set of spectra) with the CANDELS filter curves\n\t\t# in appropriate units to generate an SED in microJansky\n\n\t\tlam_z_input = lam*(1+z)\n\t\tnu = 3e18/lam_z\n\t\t# change this to appropriate normalisation. see documentation.\n\t\tfnuspec = spec\n\n\t\tfilvals = np.zeros((filcurves.shape[1],))\n\t\tfor tindex in range(filcurves.shape[1]):\n\t\t\tmask = filcurves[0:,tindex]>0\n\t\t\ttemp1 = filcurves[mask,tindex]\n\t\t\ttemp2 = fnuspec[mask]\n\t\t\t#print(str(temp1.shape)+' and '+str(temp2.shape))\n\t\t\tfilvals[tindex] = np.sum(temp1*temp2)/np.sum(filcurves[0:,tindex])\n\n\t\treturn filvals\n\n\n\tdef make_flatbasis(self, temp_sed):\n\n\t\t# make a 1-D array for the SFH/SED basis\n\n\t\tflatbasis = np.zeros((temp_sed.T.shape))\n\t\tflatnormbasis = np.zeros((temp_sed.T.shape))\n\t\tfor i in range(len(temp_sed[1,0:])):\n\t\t\tif sum(flatbasis[0:,i]) > 0:\n\t\t\t\tflatbasis[0:,i] = temp_sed.T[0:,i]\n\t\t\t\tflatnormbasis[0:,i] = temp_sed.T[0:,i]/np.linalg.norm(temp_sed.T[0:,i])\n\n\t\treturn flatbasis, flatnormbasis\n\n\n\n\tdef make_N_component_basis(self,temp_sed,temp_sfh,temp_param,dubl_brst):\n\n\t\t# something about the number of elements it returns seems slightly off..... check this\n\t\t# eg. for 2 component it returned 90601 instead of 90000\n\n\n\t\tif dubl_brst == 1:\n\n\t\t\t#---------1 component data-------------------------------------\n\t\t\tep1_basis_sed = temp_sed\n\t\t\tep1_finesfh = temp_sfh\n\t\t\t#ep1_spectra =temp_spec\n\t\t\tep1_param = temp_param\n\t\t\tparam = temp_param\n\t\t\t#ep1_dusty_sed = add_dust(ep1_basis_sed,ep1_spectra,lam)\n\t\t\tprint('Returned '+str(dubl_brst)+' component basis with '+str(len(ep1_basis_sed.T))+' elements')\n\t\t\treturn ep1_basis_sed, ep1_finesfh, ep1_param\n\n\t\telif dubl_brst == 2:\n\n\t\t\t#---------2 component data-------------------------------------\n\t\t\tcg = 1\n\t\t\tif cg > 1:\n\t\t\t\ttl = round(len(temp_sed.T)/cg+1)\n\t\t\telse:\n\t\t\t\ttl = len(temp_sed.T)\n\t\t\tep2_basis_sed = np.zeros((17,tl,tl))\n\t\t\tep2_finesfh = np.zeros((len(temp_sfh),tl,tl))\n\t\t\tep2_param = np.zeros((4,tl,tl))\n\t\t\t#ep2_spectra = np.zeros((len(temp_spec),tl,tl))\n\t\t\tfor dbarr1 in range(0,len(temp_sed.T),cg):\n\t\t\t\tfor dbarr2 in range(0,len(temp_sed.T),cg):\n\t\t\t\t\t#tempexpl = temp_sed[0:,dbarr1] + temp_sed[0:,dbarr2]\n\t\t\t\t\t#print(str(dbarr1) + ' ' + str(dbarr2) + str(ep2_basis_sed.shape))\n\t\t\t\t\tep2_basis_sed[0:,round(dbarr1/cg),round(dbarr2/cg)] = (temp_sed[0:,dbarr1] + temp_sed[0:,dbarr2])/2\n\t\t\t\t\tep2_finesfh[0:,round(dbarr1/cg),round(dbarr2/cg)] = (temp_sfh[0:,dbarr1] + temp_sfh[0:,dbarr2])/2\n\t\t\t\t\tep2_param[0:,round(dbarr1/cg),round(dbarr2/cg)] = np.append(temp_param[0:,dbarr1],temp_param[0:,dbarr2])\n\t\t\t\t#ep2_spectra[0:,round(dbarr1/cg),round(dbarr2/cg)] = (temp_spec[0:,dbarr1] + temp_spec[0:,dbarr2])/2\n\t\t\t\t#ep2_spectra.shape = (len(temp_spec),tl*tl)\n\t\t\tep2_basis_sed.shape = (17,tl*tl)\n\t\t\tep2_finesfh.shape = (len(temp_sfh),tl*tl)\n\t\t\tep2_param.shape = (4,tl*tl)\n\t\t\t#ep2_dusty_sed = add_dust(ep2_basis_sed,ep2_spectra,lam)\n\t\t\tprint('Returned '+str(dubl_brst)+' component basis with '+str(len(ep2_basis_sed.T))+' elements')\n\t\t\treturn ep2_basis_sed, ep2_finesfh, ep2_param\n\n\t\telif dubl_brst == 3:\n\n\t\t\t#---------3 component data-------------------------------------\n\t\t\tcg = 2\n\t\t\ttl = round(len(temp_sed.T)/cg +1)\n\t\t\tep3_basis_sed = np.zeros((17,tl,tl,tl))\n\t\t\tep3_finesfh = np.zeros((len(temp_sfh),tl,tl,tl))\n\t\t\tep3_param = np.zeros((6,tl,tl,tl))\n\t\t\t#ep3_spectra = np.zeros((len(temp_spec),tl,tl,tl))\n\t\t\tfor dbarr1 in range(0,len(temp_sed.T),cg):\n\t\t\t\tfor dbarr2 in range(0,len(temp_sed.T),cg):\n\t\t\t\t\tfor dbarr3 in range(0,len(temp_sed.T),cg):\n\t\t\t\t\t\tep3_basis_sed[0:,round(dbarr1/cg),round(dbarr2/cg),round(dbarr3/cg)] = (temp_sed[0:,dbarr1]+temp_sed[0:,dbarr2]+temp_sed[0:,dbarr3])/3\n\t\t\t\t\t\tep3_finesfh[0:,round(dbarr1/cg),round(dbarr2/cg),round(dbarr3/cg)] = (temp_sfh[0:,dbarr1]+temp_sfh[0:,dbarr2]+temp_sfh[0:,dbarr3])/3\n\t\t\t\t\t\tep3_param[0:,round(dbarr1/cg),round(dbarr2/cg),round(dbarr3/cg)] = np.append(np.append(temp_param[0:,dbarr1],temp_param[0:,dbarr2]),temp_param[0:,dbarr3])\n\t\t\t\t\t\t#ep3_spectra[0:,round(dbarr1/cg),round(dbarr2/cg),round(dbarr3/cg)] = (temp_spec[0:,dbarr1] + temp_spec[0:,dbarr2] + temp_spec[0:,dbarr3])/3\n\t\t\t#ep3_spectra.shape = (len(temp_spec),tl*tl*tl)\n\t\t\tep3_basis_sed.shape = (17,tl*tl*tl)\n\t\t\tep3_finesfh.shape = (len(temp_sfh),tl*tl*tl)\n\t\t\tep3_param.shape = (6,tl*tl*tl)\n\t\t\t#ep3_dusty_sed = add_dust(ep3_basis_sed,ep3_spectra,lam)\n\t\t\tprint('Returned '+str(dubl_brst)+' component basis with '+str(len(ep3_basis_sed.T))+' elements')\n\t\t\treturn ep3_basis_sed, ep3_finesfh, ep3_param\n\n\n\n\n\tdef chi2(self,RSnoise,basis,mass,sigma_i,Nbands):\n\t\t\n\t\t#return goodness-of-fit parameter, assume 5%error in all bands\n\t\t#systemic error equivalent?\n\t\t#meanval = np.mean(mass*basis)\n\t\t#diff = np.power((RSnoise-mass*basis +0.005*meanval),2)\n\t\t\n\t\tchi = np.power((RSnoise-mass*basis),2)/np.power((sigma_i),2)\n\t\t#print(chi)\n\t\tchitwo = sum(chi)/len(Nbands)\n\t\treturn chitwo\n\n\n\tdef get_uncertainties(self,c2s,mf,finesfh,timear=0,vb = False):\n\n\t\t# Use best-fit information to generate uncertainties on the reconstructed SFH locally \n\t\t#print(mf)\n\t\t#print('mf has shape: '+str(mf.shape))\n\t\tmfgood = np.nan_to_num(mf)\n\t\t#print('mfgood has shape: '+str(mfgood.shape))\n\t\tbestfit_in = np.argmin(c2s)\n\t\tbestfit_val = np.amin(c2s)\n\t\tc2s_rescaled = c2s/bestfit_val\n\t\t#c2s_good_in = np.array(np.where(c2s_rescaled < 11)).T\n\t\ttemp = np.arange(len(c2s_rescaled))\n\t\tmask = c2s_rescaled < 11\n\t\t#print(temp.shape)\n\t\t#print(mask.shape)\n\t\tc2s_good_in = temp[mask.ravel()]\n\t\tif vb == True:\n\t\t\tprint(c2s_good_in.shape)\n\t\t\tprint(str(len((c2s_good_in)))+' good SFHs considered for median')\n\t\tsfh_rescaled = np.zeros((len(finesfh),len(finesfh.T)))\n\t\tfor bi in (c2s_good_in):\n\t\t\t#print('bi is: '+str(bi)+ ' for mfgood of shape '+str(mfgood.shape))\n\t\t\tif vb == True:\n\t\t\t\tprint('mass factors: ' + str(mfgood[bi])+ ' at '+str(bi))\n\t\t\t#print(bi, sfh_rescaled.shape, finesfh.shape, mfgood.shape)\n\t\t\tsfh_rescaled[0:,bi] = finesfh[0:,bi]*mfgood[bi]\n\t\tmedian_sfh = np.zeros((len(finesfh),1))\n\t\tstd_sfh = np.zeros((len(finesfh),1))\n\t\tmedian_sfh2 = np.zeros((len(finesfh),1))\n\t\tstd_sfh2 = np.zeros((len(finesfh),1))\n\t\tprct_uppr_sfh2 = np.zeros((len(finesfh),1))\n\t\tprct_lowr_sfh2 = np.zeros((len(finesfh),1))\n\t\tfor ti in range(len(finesfh)):\n\t\t\tmedian_sfh[ti] = np.nanmedian(sfh_rescaled[ti,c2s_good_in])\n\t\t\tstd_sfh[ti] = np.nanstd(finesfh[ti,c2s_good_in])\n\t\tisoutlier = np.zeros((len(c2s_good_in),1)) + 1\n\t\tcounter = 0\n\t\tfor bi in c2s_good_in:\n\t\t\tif np.amax(sfh_rescaled[0:,bi] - median_sfh) < 5:\n\t\t\t\tisoutlier[counter] = 0\n\t\t\tcounter = counter + 1\n\t\tc2s_nooutlier_in = c2s_good_in[np.array(np.where(isoutlier <1)[0])]\n\t\tif vb == True: \n\t\t\tprint(str(len((c2s_nooutlier_in)))+' good SFHs considered for uncertainties after outlier clipping')\n\t\t\tprint(str((c2s_nooutlier_in)))\n\t\tfor ti in range(len(finesfh)):\n\t\t\tmedian_sfh2[ti] = np.nanmedian(sfh_rescaled[ti,c2s_nooutlier_in])\n\t\t\tstd_sfh2[ti] = np.nanstd(sfh_rescaled[ti,c2s_nooutlier_in])\n\t\t\tprct_uppr_sfh2[ti] = np.percentile(sfh_rescaled[ti,c2s_nooutlier_in],84)\n\t\t\tprct_lowr_sfh2[ti] = np.percentile(sfh_rescaled[ti,c2s_nooutlier_in],16)\n\t\ttemp2 = median_sfh2 - std_sfh2\n\t\ttemp2[temp2 < 0] = 0\n\n\n\t\treturn median_sfh2, std_sfh2, prct_uppr_sfh2, prct_lowr_sfh2\n\n\n\tdef fit_single_SED(self,basis_sed,obs_sed,mpu,errorvals,Nbands):\n\n\t\t# Fit a single SED from the catalog with the basis to get a best fit SFH\n\t\t# not useful in the long run, but useful for diagnostics\n\n\t\t#print(basis_sed[Nbands,1].shape)\n\t\t#print(obs_sed[Nbands].shape)\n\t\t#print(mpu.shape)\n\t\t#print(errorvals.shape)\n\t\t#print(Nbands)\n\n\t\tNb_new = obs_sed > 0\n\t\tNbands_use = Nbands & Nb_new\n\n\t\tmassfac = np.zeros((len(basis_sed.T),1)) \n\t\tchi2surf = np.zeros((len(basis_sed.T),1)) + 100\n\t\tfor i in range(len(basis_sed.T)):\n\t\t\tif (LA.norm(basis_sed[Nbands_use,i]) > 0):\n\t\t\t\tmassfac[i] = LA.norm(obs_sed[Nbands_use])/LA.norm(basis_sed[Nbands_use,i])\n\n\t\t\t\t# this is what I want while using mock galaxy catalogs\n\t\t\t\t#sigma_i = (obs_sed[Nbands]*errorvals[Nbands]) + mpu[Nbands]\n\n\t\t\t\t# for real data, \n\t\t\t\tsigma_i = errorvals[Nbands_use]\n\n\t\t\t\tchi2surf[i] = self.chi2(obs_sed[Nbands_use],basis_sed[Nbands_use,i],massfac[i],sigma_i,Nbands_use)\n\t\t\tbestfit_in = np.argmin(chi2surf)\n\t\t\tbestfit_val = np.amin(chi2surf)\n\n\t\treturn bestfit_val, bestfit_in, chi2surf, massfac, Nbands_use\n\n\n\tdef fit_catalog(self,basis_sed,mock_seds,mpu,errorvals,Nbands):\n\n\t\t# Fit a subsection of the local catalog using the locally generated SFH/SED basis\n\n\t\tfrom tqdm import tqdm\n\n\t\tchi2_gal = np.zeros((len(mock_seds.T),1))\n\t\tindex_gal = np.zeros((len(mock_seds.T),1))\n\t\tmf_gal = np.zeros((len(mock_seds.T),1))\n\t\tc2s_gal = np.zeros((len(basis_sed.T),len(mock_seds.T)))\n\t\tmassfac_gal = np.zeros((len(basis_sed.T),len(mock_seds.T)))\n\t\tNbands_gal = np.zeros((mock_seds.shape))\n\t\tfor galid in tqdm(range(len(mock_seds.T))):\n\t\t\tchi2_gal[galid], index_gal[galid], temp1, temp2, Nbands_gal[0:,galid] = self.fit_single_SED(basis_sed,mock_seds[0:,galid],np.array(mpu),np.array(errorvals),Nbands)\n\t\t\tc2s_gal[0:,galid] = temp1.ravel()\n\t\t\tmassfac_gal[0:,galid] = temp2.ravel()\n\t\t\tmf_gal[galid] = massfac_gal[int(index_gal[galid]),galid]\n\t\treturn chi2_gal, index_gal, mf_gal, c2s_gal, massfac_gal, Nbands_gal\n\n\n\n#----------------------------------------------------------------------------------------------\n#--------------------------Functions Still Under Testing---------------------------------------\n#----------------------------------------------------------------------------------------------\n\n\n\t\n\t\t\n\t\t\n","sub_path":"fitting_script_simple.py","file_name":"fitting_script_simple.py","file_ext":"py","file_size_in_byte":30776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"129255676","text":"##############################################\n# now variables to plot\n# Include also variables to be plotted\n\nres_cuts = [ c for c in cuts if 'res' in c]\nboost_cuts = [ c for c in cuts if 'boost' in c]\n\n\nvariables['events'] = { 'name': '1', \n 'range' : (1,0,2), \n 'xaxis' : 'events', \n 'fold' : 3\n }\n\n########################\n\nvariables['DNNoutput_res_bins1'] = {\n 'name': 'DNNoutput',\n 'range': (15,0.,1),\n 'xaxis': 'DNN output, resolved',\n 'fold': 3 ,\n 'cuts': res_cuts,\n 'blind': { c:[0.7,1] for c in cuts if \"_sig_\" in c},\n}\n\nvariables['DNNoutput_res_bins2'] = {\n 'name': 'DNNoutput',\n 'range': (25,0.,1),\n 'xaxis': 'DNN output, resolved',\n 'fold': 3 ,\n 'cuts': res_cuts,\n 'blind': { c:[0.7,1] for c in cuts if \"_sig_\" in c},\n}\n\nvariables['DNNoutput_res_bins3'] = {\n 'name': 'DNNoutput',\n 'range': (30,0.,1),\n 'xaxis': 'DNN output, resolved',\n 'fold': 3 ,\n 'cuts': res_cuts,\n 'blind': { c:[0.7,1] for c in cuts if \"_sig_\" in c},\n}\n\n\n##################### \n\nvariables['DNNoutput_boost_bins1'] = {\n 'name': 'DNNoutput_boosted',\n 'range': (20,0.,1),\n 'xaxis': 'DNN output, boosted',\n 'fold': 3 ,\n 'cuts': boost_cuts,\n 'blind': { c:[0.7,1] for c in cuts if \"_sig_\" in c} ,\n}\n\nvariables['DNNoutput_boost_bins2'] = {\n 'name': 'DNNoutput_boosted',\n 'range': ([0.05, 0.1, 0.15, 0.20, 0.25, 0.3, 0.35, 0.4, 0.55, 0.7, 0.85, 1.],),\n 'xaxis': 'DNN output, boosted',\n 'fold': 3 ,\n 'cuts': boost_cuts,\n 'blind': { c:[0.7,1] for c in cuts if \"_sig_\" in c} ,\n}\n\n\n#####################\n#Fit variables\n\nvariables['fit_bins_res'] ={ 'name' : 'w_lep_pt',\n 'range' : ([0,100,200,300,400,500,700],),\n 'xaxis' : 'W leptonic Pt', \n 'fold' : 3,\n 'cuts': res_cuts\n} \n\nvariables['fit_bins_boost'] ={ 'name' : 'w_lep_pt',\n 'range' : ([0,75,150,250,400,700],),\n 'xaxis' : 'W leptonic Pt', \n 'fold' : 3,\n 'cuts': boost_cuts\n} \n\n######################\n\nvariables['w_lep_pt'] = { 'name': 'w_lep_pt', \n 'range' : (50,0,700), \n 'xaxis' : 'Pt W leptonic', \n 'fold' : 3\n }\n\nvariables['whad_pt_boost'] = { 'name': \"w_had_pt\",\n 'range': (30, 200, 900),\n 'xaxis': 'W hadronic Pt',\n 'fold': 3 ,\n 'cuts': boost_cuts\n }\n\n\nvariables['deltaeta_vbs'] = { 'name': 'deltaeta_vbs', \n 'range' : (20,2.5,8.5), \n 'xaxis' : '#Delta#eta VBS jets', \n 'fold' : 3,\n } \n\nvariables['mjj_vjet'] = { 'name': 'mjj_vjet', \n 'range' : (60,40,250), \n 'xaxis' : 'Whad reco mass', \n 'fold' : 3\n }\n\nvariables['mjj_vbs_boost'] = { 'name': 'mjj_vbs', \n 'range' : (30,250,2500) , \n 'xaxis' : 'M_{jj} VBS', \n 'fold' : 3,\n 'blind': [1500,2500],\n 'cuts': boost_cuts\n }\n\n\nvariables['mjj_vbs_res'] = { 'name': 'mjj_vbs', \n 'range' : (40,250,4000) , \n 'xaxis' : 'M_{jj} VBS', \n 'fold' : 3,\n 'blind': [1500,4000],\n 'cuts': res_cuts\n }","sub_path":"Configurations/VBSjjlnu/Full2016v7/conf_fit_v4/variables_fit.py","file_name":"variables_fit.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"259302864","text":"import numpy as np\n\n\ndef r_s(M):\n \"schwardzchild radius\"\n # Units of c^2/G\n return 2*M\n\n\ndef Phi_g(M, r):\n \"Gravitational potential\"\n rs = r_s(M)\n phi = -rs/np.linalg.norm(r, axis=1) # , keepdims=True)\n phi[phi < -1] = -1\n return phi\n\n\ndef angle_rowwise(A, B):\n p1 = np.einsum('ij,ij->i', A, B)\n p2 = np.einsum('ij,ij->i', A, A)\n p3 = np.einsum('ij,ij->i', B, B)\n p4 = p1 / np.sqrt(p2*p3)\n return np.arccos(np.clip(p4, -1.0, 1.0))\n\n\ndef ray_equation(S, Phi):\n r = S[:, 0:3]\n k = S[:, 3:6]\n dxdy = np.zeros(S.shape)\n\n psi = angle_rowwise(r, k)\n\n rnorm = np.linalg.norm(r, axis=1)\n knorm = np.linalg.norm(k, axis=1)\n\n y11 = 2*knorm*Phi/rnorm*(1 + Phi)*np.cos(psi)\n y12 = 2*(1 + Phi)\n y21 = knorm**2 * Phi / rnorm**2 * (1 + (3 + 4*Phi)*np.cos(psi)**2)\n y22 = -y11\n\n g1 = y11*r.T + y12*k.T\n g2 = y21*r.T + y22*k.T\n dxdy[:, 0:3] = g1.T\n dxdy[:, 3:6] = g2.T\n\n return dxdy\n\n\ndef RK4F(func, S, h, Phi):\n\n s1 = h*func(S, Phi)\n s2 = h*func(S + s1/2.0 + h/2, Phi)\n s3 = h*func(S + s2/2.0 + h/2, Phi)\n s4 = h*func(S + s3 + h, Phi)\n\n return S + s1/6 + s2/3 + s3/3 + s4/6\n\n\ndef sqrnorm(vec):\n return np.einsum('...i,...i', vec, vec)\n\n\ndef norm(vec):\n # you might not believe it, but this is the fastest way of doing this\n # there's a stackexchange answer about this\n return np.sqrt(np.einsum('...i,...i', vec, vec))\n\n\ndef blendcolors(cb, balpha, ca, aalpha):\n\n return ca + cb * (balpha*(1.-aalpha))[:, np.newaxis]\n\n\n# this is for the final alpha channel after blending\ndef blendalpha(balpha, aalpha):\n return aalpha + balpha*(1.-aalpha)\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"411419523","text":"from socket import *\n\nHOST = 'localhost'\nPORT = 12456\nBUF_SIZE = 1024\nADDR = (HOST, PORT)\n\nudpClientSock = socket(AF_INET, SOCK_DGRAM)\n\nwhile True:\n data = input('> ')\n if not data:\n break\n udpClientSock.sendto(data.encode(),ADDR)\n data, ADDR = udpClientSock.recvfrom(BUF_SIZE)\n data = data.decode()\n if not data:\n break\n print(data)\n\nudpClientSock.close()","sub_path":"python3/socket/testUDPClient.py","file_name":"testUDPClient.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"634620629","text":"#!/usr/bin/env python\n# labor.py\t\nimport mdl_class as mdl\n\nimport numpy as np\nimport matplotlib as mpl\nimport sys, time\n\n#mpl.rcParams['backend'] = 'GTKAgg'\nmpl.rcParams['figure.frameon'] = False\nmpl.rcParams['toolbar'] = 'None'\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider, Button\n\nplt.close(\"all\")\n\n# Set up\nmm = mdl.MacroModel()\n\n## Set up figure\nfig, axs = plt.subplots(1, 2)\nfig.subplots_adjust(bottom=0.25, left=0.1)\nfig.patch.set_facecolor('white')\n\nax1 = axs[0]\nax2 = axs[1]\nax2.set_visible(False)\n\nlnwidth = 4.0\nmksize = 12.0\n\n# Production plot\nprod, = ax1.plot(mm.curves['N'], mm.curves['Y'], 'b', linewidth=lnwidth)\nprod_fix, = ax1.plot(mm.curves['N'], mm.curves['Y'], 'r', linewidth=lnwidth)\n\nax1.set_xlabel('Labor (N)')\nax1.set_ylabel('Output (Y)')\nax1.set_autoscale_on(False)\nax1.set_xlim(0, mm.const['N_disp_max'])\nax1.set_ylim(0, mm.const['Y_disp_max'])\n\nax1.spines['right'].set_color(\"none\")\nax1.spines['top'].set_color(\"none\")\nax1.tick_params(axis='x', which='both', top='off')\nax1.tick_params(axis='y', which='both', right='off')\nax1.get_xaxis().set_ticks([])\nax1.get_yaxis().set_ticks([])\n\n\n# Labor Market Plot\nax2.set_visible(True)\n\nax2.set_xlabel('Labor (N)')\nax2.set_ylabel('Wage ($\\omega$)')\nax2.set_autoscale_on(False)\nax2.set_xlim(0, mm.const['N_disp_max'])\nax2.set_ylim([0, mm.const['omega_disp_max']])\nax2.spines['right'].set_color(\"none\")\nax2.spines['top'].set_color(\"none\")\nax2.get_xaxis().set_ticks([])\nax2.get_yaxis().set_ticks([])\n\nlabor_d, = ax2.plot(mm.curves['N'], mm.curves['omega_d'], 'b', linewidth=lnwidth)\nlabor_d_fix, = ax2.plot(mm.curves['N'], mm.curves['omega_d'], 'r', linewidth=lnwidth)\n\nlabor_s, = ax2.plot(mm.curves['N'], mm.curves['omega_s'], 'b', linewidth=lnwidth)\nlabor_s_fix, = ax2.plot(mm.curves['N'], mm.curves['omega_s'], 'r', linewidth=lnwidth)\n\nprod_pt, = ax1.plot(mm.en['N'], mm.en['Y'], 'bo', markersize=mksize)\nprod_pt_fx, = ax1.plot(mm.en['N'], mm.en['Y'], 'ro', markersize=mksize)\n\nlabor_pt, = ax2.plot(mm.en['N'], mm.en['omega'], 'bo', markersize=mksize)\nlabor_pt_fix, = ax2.plot(mm.en['N'], mm.en['omega'], 'ro', markersize=mksize)\n\n\n# Sliders\n# Slider functions\ndef redraw_plots(mm, prod, prod_pt, labor_d, labor_s, labor_pt):\n\tprod.set_ydata(mm.curves['Y'])\n\tprod_pt.set_xdata(mm.en['N'])\n\tprod_pt.set_ydata(mm.en['Y'])\n\n\tlabor_d.set_ydata(mm.curves['omega_d'])\n\tlabor_s.set_ydata(mm.curves['omega_s'])\n\tlabor_pt.set_xdata(mm.en['N'])\n\tlabor_pt.set_ydata(mm.en['omega'])\n\ndef on_tech_change(A_0):\n\tmm.set_exog('A', A_0)\n\tredraw_plots(mm, prod, prod_pt, labor_d, labor_s, labor_pt)\n\ndef on_z_ls_change(z_ls_0):\n\tmm.set_exog('z_ls', z_ls_0)\n\tredraw_plots(mm, prod, prod_pt, labor_d, labor_s, labor_pt)\n\ndef on_z_ld_change(z_ld_0):\n\tmm.set_exog('z_ld', z_ld_0)\n\tredraw_plots(mm, prod, prod_pt, labor_d, labor_s, labor_pt)\n\ndef reset_click(clicked):\n\t# k_slider.set_val(1)\n\tA_slider.set_val(1)\n\tz_ls_slider.set_val(0)\n\tz_ld_slider.set_val(0)\n\t# redraw_plots(mm, prod, prod_pt, labor_d, labor_s, labor_pt)\n\n# Slider definitions\ninit_width = 8\n\nA_slider_ax = plt.axes([0.15, 0.11, 0.25, 0.02])\nA_slider = Slider(A_slider_ax, \"Production\", 0, mm.const['A_max'], valinit=mm.ex['A'], color='#0000FF')\nA_slider.on_changed(on_tech_change)\nA_slider.valtext.set_visible(False)\nA_slider.vline.set_linewidth(init_width)\n\nz_ld_slider_ax = plt.axes([0.65, 0.15, 0.25, 0.02])\nz_ld_slider = Slider(z_ld_slider_ax, \"Labor Demand\", mm.const['z_ld_min'], mm.const['z_ld_max'], valinit=mm.ex['z_ld'], color='#0000FF')\nz_ld_slider.on_changed(on_z_ld_change)\nz_ld_slider.valtext.set_visible(False)\nz_ld_slider.vline.set_linewidth(init_width)\n\nz_ls_slider_ax = plt.axes([0.65, 0.11, 0.25, 0.02])\nz_ls_slider = Slider(z_ls_slider_ax, \"Labor Supply\", mm.const['z_ls_min'], mm.const['z_ls_max'], valinit=mm.ex['z_ls'], color='#0000FF')\nz_ls_slider.on_changed(on_z_ls_change)\nz_ls_slider.valtext.set_visible(False)\nz_ls_slider.vline.set_linewidth(init_width)\n\n\nreset_botton_ax = plt.axes([0.45, 0.03, 0.1, 0.04])\nreset_button = Button(reset_botton_ax, \"Reset\")\nreset_button.on_clicked(reset_click)\n\n# Show the figure\nfig.show()\n","sub_path":"labor.py","file_name":"labor.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"434837057","text":"from time import sleep\nfrom machine import Pin, I2C\nfrom essentials import do_connect, http_get, do_deepsleep, blink, local_time\nfrom bme280 import ESP_BME280\ngc.collect()\nfrom AS3935 import ESP_AS3935\ngc.collect()\nimport usyslog\n\ndomo1_url = 'http://192.168.178.201:8080/json.htm?type=command¶m=udevice&idx='\ndomo2_url = 'http://192.168.178.202:8080/json.htm?type=command¶m=udevice&idx='\n\ndo_connect(ESSID, PWD)\nblink(2)\nlocal_time()\ngc.collect()\n\nlog=usyslog.UDPClient(ip='192.168.178.200')\n\np_irq = Pin(13, Pin.IN) # create input pin on GPIO13\ni2c1 = I2C(scl=Pin(5), sda=Pin(4), freq=50000)\nsensor = ESP_AS3935(i2c=i2c1, indoors=True, noise_floor=0)\n\nprint('Config: Indoors {0:s}, Noiselevel {1:d}, Min_Strikes {2:d}'.format(str(sensor.get_indoors()), sensor.get_noise_floor(), sensor.get_min_strikes()))\nlog.notice('Env: Finished Init ..entering loop {0:s}'.format(local_time()))\nprint('Finished Init ..entering loop {0:s}'.format(local_time()))\nj=1\nwhile True:\n del sensor\n del i2c1\n gc.collect()\n\n i2c = I2C(scl=Pin(14, Pin.OUT), sda=Pin(12, Pin.OUT))\n bme = ESP_BME280(i2c=i2c)\n altitude = 482.25\n\n blink(2)\n t=bme.read_compensated_data()[0]/100\n p=bme.read_compensated_data()[1]/256/100\n psea = p / pow(1 - altitude/44330.0, 5.255)\n r=bme.read_compensated_data()[2]/1024\n print(\"{0:7.2f} hPa p, {1:7.2f} hPa MSL, {2:5.2f} rH, {3:5.2f} C\".format(p, psea, r, t))\n\n try:\n http_get('{0:s}72&nvalue=0&svalue={1:4.1f};{2:4.1f};0;{3:6.1f};0'.format(domo1_url, t,r,psea))\n except:\n print('e:Bs1')\n try:\n http_get('{0:s}72&nvalue=0&svalue={1:4.1f};{2:4.1f};0;{3:6.1f};0'.format(domo2_url, t,r,psea))\n except:\n print('e:Bs2')\n\n del bme\n del i2c\n gc.collect()\n i2c1 = I2C(scl=Pin(5), sda=Pin(4), freq=50000)\n sensor = ESP_AS3935(i2c=i2c1, indoors=True, noise_floor=0, on_init=False)\n if j==1:\n print('Config: Indoors {0:s}, Noiselevel {1:d}, Min_Strikes {2:d}'.format(str(sensor.get_indoors()), sensor.get_noise_floor(), sensor.get_min_strikes()))\n\n #sleep(1)\n for inner_step in range(1,60):\n blink(1)\n# print(inner_step)\n inter = p_irq.value()\n sleep(0.5)\n reason = sensor.get_interrupt()\n\n if (inter == 1):\n print('Interrup detected: {0:s} {1:d} {2:d}'.format(local_time(), inter, reason))\n\n if reason == 0x01:\n print('Noise high - adjusting {0:s} {1:d}'.format(local_time(), inter))\n sensor.raise_noise_floor()\n continue\n elif reason == 0x04:\n print('Disturber - masking {0:s} {1:d}'.format(local_time(), inter))\n sensor.set_mask_disturber(True)\n continue\n elif reason == 0x08:\n distance = sensor.get_distance()\n energy = sensor.get_energy()\n log.alert('Lightning! - {0:s}, {0:4d} km away. E: {1:d}'.format(local_time(), distance, energy))\n print('Lightning! - {0:s}, {0:4d} km away. E: {1:d}'.format(local_time(), distance, energy))\n try:\n http_get('{0:s}73&nvalue=0&svalue={1:d}'.format(domo1_url, distance))\n except:\n print('e:As1')\n try:\n http_get('{0:s}73&nvalue=0&svalue={1:d}'.format(domo2_url, distance))\n except:\n print('e:As2')\n\n sleep(5)\n\n if j == 4:\n# log.notice('..running at {0:s}'.format(local_time()))\n print('..running at {0:s}'.format(local_time()))\n j=0\n else:\n j=j+1\n# print('outer end')\n# sleep(15*60)\n\n#import http_server_ssl\n#http_server_ssl.run()\n\n\n# check if the device woke from a deep sleep\n#if machine.reset_cause() == machine.DEEPSLEEP_RESET:\n# print('woke from a deep sleep')\n\n# put the device to sleep in seconds\n#do_deepsleep(5*60)\n","sub_path":"MicroPython/esp8266/esp8266-bme280/main_ori.py","file_name":"main_ori.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"313103403","text":"from flask import request\nfrom flask import jsonify\nfrom flask import Flask\nfrom flask import render_template\nimport datetime as d\n\nimport flask\n\n\n\napp = Flask(__name__)\n@app.route(\"/dict_dir\")\ndef dictDir():\n return (str(request.__dict__) + \"\\n\" + str(request.__dir__))\n\n\n@app.route(\"/index\", methods=[\"GET\"])\ndef get_my_ip():\n # return render_template('template.html', ip_address=(jsonify({'ip_address': request.remote_addr}), 200))\n # print((jsonify({'ip_address': request.remote_addr}), 200))\n # return jsonify({'ip_address': request.remote_addr}), 200\n var_brow = request.user_agent.browser\n var_nav = request.headers.get('User-Agent')\n var_os = request.user_agent.platform\n var_ip = request.environ.get('ip_address', request.remote_addr)\n our_date = d.datetime.now().strftime(\"%A %d %B %Y %H %M\")\n with open(\"journal.co\", \"a\") as fo:\n writing = \"--date : \" + our_date + \"\\n\" + \"--informations = \" + \"\\n\" + \"--browser : \" + str(var_brow) + \"\\n\" + \"--navigateur : \" + str(var_nav) + \"\\n\" + \"--os : \" + str(var_os) + \"\\n\" + \"--adresse_ip : \" + str(var_ip)\n fo.write(str(writing))\n return render_template('template.html', ip_address = var_ip, nav = var_nav, brow = var_brow, oos = var_os)\n\n@app.route(\"/journal\")\ndef printInfos():\n with open(\"journal.co\", \"r\") as f:\n return render_template('template.html', lines = f)\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"ipp.py","file_name":"ipp.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"565154406","text":"fin = open(\"bm.txt\", \"r\") # Results from running tsp 10 times for each instance\nfout = open(\"results.txt\", \"w+\") # Output file\nftarget = open(\"target.txt\", \"r\") # Target average results\nfsummary = open(\"summary.txt\", \"w+\") # Results summary, looking at off percentage\n\nisFirst = True\nflag = 0 # 0 is cost 1 is time\n\nfor line in fin.readlines():\n\n #Treating read line\n no_endl = line.split(\"\\n\")\n my_list = no_endl[0].split()\n \n if len(my_list) == 1: # Line is an instance's name\n\n instance_name = my_list[0]\n \n if isFirst == False: # There's no cost or time data at the first name\n avg_cost = sum_cost/10\n avg_time = sum_time/10\n\n off_pct = ( (avg_cost - target) / target ) * 100\n\n # Verbose - Writes info to results.txt\n fout.write(\"\\nAvg cost: \")\n fout.write(str(avg_cost))\n fout.write(\"\\nAvg time: \")\n fout.write(str(avg_time))\n fout.write(\"\\nOff percentage: \")\n fout.write(str(off_pct))\n fout.write(\"\\n\\n\")\n\n # Summary - Writes info to summary.txt\n fsummary.write(\" --- \")\n if off_pct == 0:\n fsummary.write(\"Optimal!\")\n elif off_pct <= 0.5:\n fsummary.write(\"Good\")\n else:\n fsummary.write(\"Needs improvement\")\n fsummary.write(\"\\n\")\n\n fout.write(instance_name)\n fsummary.write(instance_name)\n\n # Gets target value from target.txt for given instance\n # so the error % can be calculated later.\n for tgt in ftarget.readlines():\n \n #Treating read line\n tgt_list = tgt.split(\":\")\n tgt_name = tgt_list[0]\n\n if instance_name == tgt_name:\n \n # Continue treating the line (after if to save resources)\n tgt_value_endl = tgt_list[1]\n tgt_value_list = tgt_value_endl.split(\"\\n\")\n tgt_value = tgt_value_list[0]\n \n target = float(tgt_value)\n\n ftarget.seek(0,0)\n\n break\n\n #Reset total cost and time\n sum_cost = 0\n sum_time = 0\n\n\n\n else: # Else line is cost or time\n num = my_list[1]\n \n if flag == 0:\n sum_cost += int(num)\n flag = 1\n elif flag == 1:\n sum_time += float(num)\n flag = 0\n \n isFirst = False\n\n\nfin.close()\nfout.close()\nftarget.close()\nfsummary.close()","sub_path":"benchmark/bm.py","file_name":"bm.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"4590133","text":"import os, time, datetime, traceback, psutil\r\n\r\npython = (\"python3\", \"python\")[os.name == \"nt\"]\r\n\r\n\r\ndef delete(f):\r\n while f in os.listdir():\r\n try:\r\n os.remove(f)\r\n break\r\n except:\r\n print(traceback.format_exc())\r\n time.sleep(1)\r\n\r\nsd = \"shutdown.json\"\r\nrs = \"restart.json\"\r\nhb = \"heartbeat.json\"\r\n\r\ndelete(sd)\r\ndelete(rs)\r\ndelete(hb)\r\n\r\nwhile not sd in os.listdir():\r\n delete(rs)\r\n delete(hb)\r\n proc = psutil.Popen([python, \"bot.py\"], shell=True)\r\n print(\"Bot started with PID \" + str(proc.pid) + \".\")\r\n time.sleep(8)\r\n try:\r\n print(\"Heartbeat started.\")\r\n alive = True\r\n while alive:\r\n f = open(hb, \"wb\")\r\n f.close()\r\n print(\r\n \"Heartbeat at \"\r\n + str(datetime.datetime.now())\r\n + \".\"\r\n )\r\n for i in range(16):\r\n time.sleep(0.5)\r\n ld = os.listdir()\r\n if rs in ld or sd in ld:\r\n alive = False\r\n break\r\n if not alive or hb in os.listdir():\r\n alive = False\r\n break\r\n found = True\r\n while found:\r\n found = False\r\n try:\r\n for child in proc.children():\r\n child.kill()\r\n found = True\r\n except psutil.NoSuchProcess:\r\n break\r\n while True:\r\n try:\r\n proc.kill()\r\n except psutil.NoSuchProcess:\r\n break\r\n print(\"Bot closed without shutdown signal, restarting...\")\r\n except KeyboardInterrupt:\r\n raise\r\n except:\r\n print(traceback.format_exc())\r\n time.sleep(0.5)\r\n \r\ndelete(hb)\r\ndelete(rs)\r\ndelete(sd)\r\n \r\nprint(\"Shutdown signal confirmed. Press [ENTER] to close.\")\r\ninput()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"331118050","text":"import random\r\n\r\nimport telebot\r\nfrom khayyam import JalaliDate\r\nfrom gtts import gTTS\r\n#import qrcode\r\n\r\nmybot = telebot.TeleBot('2039927554:AAFrqwyUmMSrd3F_Q6n3LA9s0piw8ZknSvs')\r\n\r\n@mybot.message_handler(commands= ['start'])\r\ndef send_welcome(message):\r\n mybot.reply_to(message, f'Hi {message.from_user.first_name}, Welcome to my bot.')\r\n mybot.send_message(message.chat.id, 'Please send /help if you need help.')\r\n\r\n@mybot.message_handler(commands= ['game'])\r\ndef play_game(message):\r\n mybot.reply_to(message, 'guess number between 0-20')\r\n mybot.register_next_step_handler(message, game) \r\n\r\nmybot.number = random.randint(0, 20)\r\n\r\ndef game(message):\r\n if message.text.startswith(\"/\"):\r\n mybot.send_message(message.chat.id, 'agein send your command.')\r\n else:\r\n mymarkup = telebot.types.ReplyKeyboardMarkup(row_width= 1)\r\n btn1 = telebot.types.KeyboardButton('New Game')\r\n mymarkup.add(btn1)\r\n if message.text == 'New Game':\r\n mybot.number = random.randint(0, 20)\r\n mes = mybot.send_message(message.chat.id, 'guess new number between 0-20', reply_markup= telebot.types.ReplyKeyboardRemove(selective=True))\r\n mybot.register_next_step_handler(mes, game)\r\n elif int(message.text) == mybot.number:\r\n mybot.reply_to(message, 'Yesss. You Win! ')\r\n mybot.number = random.randint(0, 20)\r\n mes = mybot.send_message(message.chat.id, 'if want new game press New Game', reply_markup = mymarkup )\r\n mybot.register_next_step_handler(mes, game)\r\n elif int(message.text) < mybot.number:\r\n mes = mybot.reply_to(message, 'No! guess higher.')\r\n mybot.register_next_step_handler(mes, game)\r\n elif int(message.text) > mybot.number:\r\n mes = mybot.reply_to(message, 'No! guess lower. ')\r\n mybot.register_next_step_handler(mes, game)\r\n else:\r\n mybot.reply_to(message, 'Are you okey?! what are you saying?! ')\r\n \r\n \r\n@mybot.message_handler(commands= ['age'])\r\ndef show_age(message):\r\n mybot.reply_to(message, 'Tell me your date of birth (yyyy/mm/dd) to tell you how old are you.')\r\n mybot.register_next_step_handler(message, ages)\r\n\r\ndef ages(message):\r\n date = message.text.split('/')\r\n difference = JalaliDate.today() - JalaliDate(int(date[0]), int(date[1]), int(date[2]))\r\n age = {}\r\n age[0] = difference.days // 365\r\n if 1 <= int(date[1]) <= 6:\r\n age[1] = (difference.days % 365 ) // 33\r\n age[2] = (difference.days % 365) % 33 - 5\r\n elif 7 <= int(date[1]) <= 11:\r\n age[1] = (difference.days % 365 ) // 31\r\n age[2] = (difference.days % 365) % 31 + 1\r\n elif int(date[1]) == 12:\r\n age[1] = (difference.days % 365 ) // 30\r\n age[2] = (difference.days % 365) % 30\r\n\r\n mybot.send_message(message.chat.id, f'you are {age[0]} year {age[1]} month {age[2]} day')\r\n\r\n@mybot.message_handler(commands= ['voice'])\r\ndef play_voice(message):\r\n mybot.reply_to(message, 'Type a sentence so I can send it to you as a voice.')\r\n mybot.register_next_step_handler(message, voice)\r\n\r\ndef voice(message):\r\n mytext = message.text\r\n language = 'en'\r\n myobj = gTTS(text= mytext, lang= language, slow= False)\r\n myobj.save('voice.mp3')\r\n voice = open('voice.mp3','rb')\r\n mybot.send_voice(message.chat.id, voice= voice)\r\n\r\n@mybot.message_handler(commands= ['max'])\r\ndef show_max(message):\r\n mybot.reply_to(message, 'Enter a list of numbers (n1,n2,...) to say the largest number. ')\r\n mybot.register_next_step_handler(message, max_num)\r\n\r\ndef max_num(message):\r\n mytext = message.text.split(',')\r\n nums = []\r\n for i in mytext:\r\n nums.append(int(i))\r\n mybot.send_message(message.chat.id, f'Maximum num in your list is : {max(nums)}')\r\n\r\n@mybot.message_handler(commands= ['argmax'])\r\ndef show_arg_max(message):\r\n mybot.reply_to(message, 'Enter a list of numbers (n1,n2,...) to say the argument of the largest number. ')\r\n mybot.register_next_step_handler(message, arg_max_num)\r\n\r\ndef arg_max_num(message):\r\n mytext = message.text.split(',')\r\n nums = []\r\n for i in mytext:\r\n nums.append(int(i))\r\n mybot.send_message(message.chat.id, f'Arg of the max num in your list is : {nums.index(max(nums))}')\r\n\r\n# @mybot.message_handler(commands= ['qrcode'])\r\n# def send_qrcode(message):\r\n# mybot.reply_to(message, 'Enter a sentence so l can make the qrcode ')\r\n# mybot.register_next_step_handler(message, make_qrcode)\r\n\r\n# def make_qrcode(message):\r\n #img = qrcode.make(message.text)\r\n #img.save('qrcode.png')\r\n # image = open('qrcode.png', 'rb')\r\n # mybot.send_photo(message.chat.id, image)\r\n\r\n@mybot.message_handler(commands= ['help'])\r\ndef show_max(message):\r\n mybot.reply_to(message, 'Plese send:\\n/game if you want help\\n/age if you wanna know your age.\\n/voice if you want to change your sentence to voice\\n/max if you want to the largest number\\n/argmax if you want to argument of the largest number')\r\n\r\nmybot.polling()\r\n","sub_path":"Telegram-bot.py","file_name":"Telegram-bot.py","file_ext":"py","file_size_in_byte":5059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"511780109","text":"import BOOK\nimport MEMBER\nimport ISSUE\ndef MenuBook():\n while True:\n BOOK.clrscreen()\n print(\"\\t\\t\\tBook Record Management\\n\")\n print(\"===================================================================\")\n print(\"1.Add Book Record\")\n print(\"2.Display Book Records\")\n print(\"3.Search Book Record\")\n print(\"4.Delete Book Record\")\n print(\"5.Update Book Record\")\n print(\"6.Return to Main Menu \")\n print(\"===================================================================\")\n choice=int(input(\"Enter Choice between 1 to 5------------->:\"))\n if choice==1:\n BOOK.insertData()\n elif choice==2:\n BOOK.display()\n elif choice==3:\n BOOK.SearchBookRec()\n elif choice==4:\n BOOK.deleteBook()\n elif choice==5:\n print(\"no such function\")\n elif choice==6:\n return\n else:\n print(\"wrong choice.......enter your choice again\")\n x=input(\"enter any key to continue\")\ndef MenuMember():\n while True:\n BOOK.clrscreen() \n print('\\t\\t\\tMember Record Management\\n')\n print(\"============================================================\") \n print(\"1.add member record\")\n print(\"2.display member records\")\n print(\"3.search member record\") \n print(\"4.delete member record\") \n print(\"5.update book record\") \n print(\"6.return to mainmenu\") \n print(\"=============================================================\")\n choice=int(input(\"enter choice between 1 to 5-------->\")) \n if choice==1:\n MEMBER.insertMember()\n elif choice==2:\n MEMBER.display()\n elif choice==3:\n MEMBER.SearchMember()\n elif choice==4:\n MEMBER.deleteMember()\n elif choice==5:\n print(\"no such function\")\n elif choice==6:\n return\n else:\n print(\"wrong choice.........enter your choice again\")\n x=input(\"enter any key to continue\")\n#---------------------------------------------------------------------\ndef MenuIssueReturn():\n while True:\n BOOK.clrscreen()\n print(\"\\t\\t\\t Member record management\\n\")\n print(\"============================================================\") \n print(\"1.issuebook\")\n print(\"2.display issued book records\")\n print(\"3.return issued book\")\n print(\"4.return to main menu\")\n print(\"============================================================\") \n choice=int(input(\"Enter Choice between 1 to 4------------->:\"))\n if choice==1:\n ISSUE.issueBook()\n elif choice==2:\n ISSUE.ShowIssuedBooks() \n elif choice==3:\n ISSUE.returnBook() \n elif choice==4:\n return\n else:\n print(\"wrong choice.........enter your choice again\")\n x=input(\"enter any key to continue\")\n \n \n\n \n\n","sub_path":"MENULIB.py","file_name":"MENULIB.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"599163859","text":"#-----------------------------------------------------------------------------\n# University of Leeds, School of Computing\n# Client application to be used in Coursework 1 of COMP3011 2020-2021\n# Written by Najmuddin Dost, 2019\n# Najmuddin is an Alumnus of the University of Leeds\n# Currently, he works as a Software Engineer at Sage (sage.com)\n# Edited by Ammar Alsalka, University of Leeds, 2021\n#------------------------------------------------------------------------------\nimport requests\nimport json\nimport re\nimport datetime\n\n#-------------------------------------------------------------------------------\n# This is the client class which interacts with different news agencies and\n# provides the user with various API call options.\n#-------------------------------------------------------------------------------\nclass Client():\n #Init function to set required class variables\n def __init__(self):\n self.s = requests.Session()\n self.url=\"None\"\n self.status=\"None\"\n\n\n #Login the user to a news agency if username, url, and password are valid\n def login(self, username, password):\n print(\"\\nLoggin In....\")\n payload = {'username': username, 'password': password}\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n\t\t\n try:\n r = self.s.post(self.url+\"api/login/\", data=payload, headers=headers, timeout=4)\n print(r.text)\n print(\"Status Code is %s\" % r.status_code)\n if(r.status_code==200):\n self.status=\"(\"+username+\") \"\n else:\n self.url = \"None\"\n except requests.exceptions.RequestException:\n print(\"Error! Failed to establish connection to:\", self.url)\n self.url=\"None\"\n\n\n #Logs the user out from current session if its active\n def logout(self):\n print(\"\\nLoggin out....\")\n try:\n r = self.s.post(self.url+\"api/logout/\",timeout=10)\n print(r.text)\n print(\"Status Code is %s\"%r.status_code)\n if(r.status_code==200):\n self.status=\"None\"\n except requests.exceptions.RequestException:\n print(\"Error! Failed to logout from \",self.url)\n\n\n #Sends a post request to add a news story to a news agency\n def postStory(self, headline, category, region, details):\n print(\"\\nPosting Story....\")\n headers = {'content-type': 'application/json'}\n payload = {'headline': headline, 'category': category, 'region':region, 'details': details}\n\n try:\n r = self.s.post(self.url+\"api/poststory/\",data=json.dumps(payload), headers=headers, timeout=10)\n print(r.text)\n print(\"Status Code is %s\" % r.status_code)\n except requests.exceptions.RequestException:\n print(\"Error! Failed to post to \", self.url)\n\n\n # gets news stories from a single news agency\n def getSingleStories(self, params, agency=None): # params: 0=id 1=cat 2=reg 3=date\n# headers = {'content-type': 'application/json'}\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n payload = {'story_cat': params[1], 'story_region': params[2], 'story_date':params[3]}\n\n if(agency==None):\n agency=self.getAgency(params[0])\n if(agency==\"Not Found\"):\n print(\"Error! Could not find agency with unique code \", params[0])\n return\n\n url=agency[\"url\"]\n if not url.startswith(\"http://\"):\n url = \"http://\"+url\n if not url.endswith(\"/\"):\n url = url+\"/\"\n\n try:\n r = self.s.get(url+\"api/getstories/\",data=json.dumps(payload), headers=headers, timeout=10)\n print(\"\\nRetrieving News Stories from \",agency[\"agency_name\"],\"....\")\n\n if(r.status_code==200):\n stories=json.loads(r.text)\n i=1\n for story in stories[\"stories\"]:\n print(\"\\nStory \",i)\n print(\"Key: \".ljust(20),story[\"key\"])\n print(\"Headline: \".ljust(20), story[\"headline\"])\n print(\"Category: \".ljust(20), story[\"story_cat\"])\n print(\"Region: \".ljust(20), story[\"story_region\"])\n print(\"Author Name: \".ljust(20), story[\"author\"])\n print(\"Date Published: \".ljust(20), story[\"story_date\"])\n print(\"Details: \".ljust(20), story[\"story_details\"])\n i+=1\n else:\n print(\"\\nError! Failed to retrieve stories from \", url)\n if(len(r.text)<=500):\n print(r.text)\n print(\"Status Code is %s\" % r.status_code)\n except Exception:\n print(\"\\nError! Failed to retrieve stories from \", url)\n\n\n #Gets news stories from all news agencies registered in the directory\n def getAllStories(self, params):\n print(\"\\nGetting News Stories From All Agencies....\")\n r = self.s.get('http://directory.pythonanywhere.com/api/list/', timeout=4)\n\n if(r.status_code==200):\n agencies=json.loads(r.text)\n for agency in agencies[\"agency_list\"]:\n self.getSingleStories(params, agency=agency)\n else:\n print(r.text)\n print(\"Status Code is %s\" % r.status_code)\n\n\n #Attempts to delete a story from a news agency\n def deleteStory(self, key):\n print(\"\\nDeleting Story With Key:\",key,\"....\")\n headers = {'content-type': 'application/json'}\n payload = {'story_key': key}\n\n try:\n r = self.s.post(self.url+\"api/deletestory/\",data=json.dumps(payload), headers=headers, timeout=10)\n print(r.text)\n print(\"Status Code is %s\" % r.status_code)\n except requests.exceptions.RequestException:\n print(\"Error! Failed to delete story with key \", key)\n\n\n # initially, this should be used once to register your agency in the directory\n\t# insert your service details before calling this function\n\t# -------------------------------------------------------------------\n def registerService(self):\n print(\"\\nRegistering Service....\")\n headers = {'content-type': 'application/json'}\n payload = {\"agency_name\": \"Enter your agency name here\",\n \"url\": \"http://???.pythonanywhere.com/\",\n \"agency_code\":\"???\"}\n\n r = self.s.post('http://directory.pythonanywhere.com/api/register/',\n data=json.dumps(payload), headers=headers, timeout=10)\n print(r.text)\n print(\"Status Code is %s\" % r.status_code)\n\n\n #Lists all agencies registered in the directory\n def listAgencies(self):\n print(\"\\nListing all agencies in the directory....\")\n r = self.s.get('http://directory.pythonanywhere.com/api/list/', timeout=10)\n\n if(r.status_code==200):\n agencies=json.loads(r.text)\n i=1\n for agency in agencies[\"agency_list\"]:\n print(\"\\nAgency \",i)\n print(\"Name: \".ljust(35),agency[\"agency_name\"])\n print(\"URL: \".ljust(35), agency[\"url\"])\n print(\"Unique Code: \".ljust(35), agency[\"agency_code\"])\n i+=1\n else:\n if(len(r.text)<=500):\n print(r.text)\n print(\"Status Code is %s\" % r.status_code)\n\n\n #Given the 3 letter agency code, will find and return the agency object\n def getAgency(self, code):\n r = self.s.get('http://directory.pythonanywhere.com/api/list/', timeout=10)\n\n if(r.status_code==200):\n agencies=json.loads(r.text)\n for agency in agencies[\"agency_list\"]:\n if(agency[\"agency_code\"]==code):\n return agency\n return \"Not Found\"\n\n #Prints out some welcome information\n def displayWelcome(self):\n print(\"\\n\\t\\tWelcome To Amazing Client! Please enter your commands\")\n print(\"Do not append to the url the api address e.g. api/login, this is automatically added\")\n print(\"-------------------------------------------------------------------------------------\")\n print(\"--) register (use once only to register your service) \")\n print(\"--) login url -\")\n print(\"--) logout -\")\n print(\"--) post -\")\n print(\"--) news [id def=*] [cat def=*] [reg def=*] [date def=*] -\")\n print(\"--) list -\")\n print(\"--) delete story_key -\")\n print(\"----exit (to stop client) -\")\n print(\"----show (to display available commands) -\")\n print(\"-------------------------------------------------------------------------------------\")\n\n\n #Client interface which processes the user's inputs\n def runClient(self):\n self.displayWelcome()\n while(True):\n if(self.status!=\"None\"):\n prompt=self.status+\">>>\"\n else:\n prompt = \">>>\"\n command=input(prompt).strip().split()\n\n if not command: # empty\n continue\n if(command[0]== \"register\"):\n self.registerService ()\t\t\t\t\n elif(command[0]==\"login\" and len(command)==2): # login\n username = input(\"Please enter your username: \").strip()\n password = input(\"Please enter your password: \").strip()\n self.setURL(command[1])\n self.login(username, password)\n elif(command[0]==\"logout\" and len(command)==1): # logout\n if(self.url==\"None\"):\n print(\"Error! current session is not active, please login to a url for logout to work!\")\n else:\n self.logout()\n elif(command[0] == \"post\" and len(command) == 1): # post\n if(self.url == \"None\"):\n print(\"Error! not logged in, please login first using the login command\")\n continue\n self.processPostInput(command)\n elif(command[0] == \"news\"): # news\n self.processNewsInput(command)\n elif(command[0]==\"list\" and len(command)==1): # list\n self.listAgencies()\n elif(command[0]==\"delete\" and len(command)==2 and command[1].isdigit()==True): # delete\n if(self.url == \"None\"):\n print(\"Error! not logged into any server, please login to a server using [login url]\")\n continue\n self.deleteStory(command[1])\n elif(command[0] == \"exit\"): # exit\n break\n elif(command[0]==\"show\" and len(command)==1): # show\n self.displayWelcome()\n\n\n #Processes the post input from user and calls relevant class function\n def processPostInput(self, command):\n headline=input(\"Headline: \")\n category=\"\"\n while(not (category==\"pol\" or category==\"art\" or category==\"trivia\" or category==\"tech\")):\n category=input(\"Category (pol, art, trivia, tech)\")\n\n region=\"\"\n while(not (region==\"eu\" or region==\"w\" or region==\"uk\")):\n region=input(\"Region (eu, w, uk)\")\n details=input(\"Details: \")\n self.postStory(headline, category, region, details)\n\n\n #Processes the news input and calls relevant class functions\n def processNewsInput(self, command):\n params = [\"*\", \"*\", \"*\", \"*\"] # 0=id 1=cat 2=reg 3=date\n for cmd in command[1:]:\n if(len(cmd) == 3 and cmd != \"pol\" and cmd != \"art\" and cmd.isalpha()):\n params[0] = cmd\n elif(cmd == \"pol\" or cmd == \"art\" or cmd == \"tech\" or cmd == \"trivia\"):\n params[1] = cmd\n elif(cmd == \"uk\" or cmd == \"w\" or cmd == \"eu\"):\n params[2] = cmd\n elif(len(cmd)==10):\n m = bool(re.match('^\\d\\d/\\d\\d/\\d{4}$', cmd)) # dd/mm/yyyy\n if(self.checkDateIsValid(cmd) == True and m == True):\n params[3] = cmd\n else:\n return\n\n print(\"Final news: \", params)\n if(params[0]!=\"*\"):\n self.getSingleStories(params)\n elif(params[0]==\"*\"):\n self.getAllStories(params)\n\n #Checks if the date provided is a valid date\n def checkDateIsValid(self, cmd):\n day, month, year = cmd.split('/')\n try:\n d=datetime.datetime(int(year), int(month), int(day))\n return True\n except ValueError:\n print(\"Error! date is not a valid date, plz try again\")\n\n return False\n\n #Checks and corrects the url from the user and updates the class variable\n def setURL(self, url):\n if not url.startswith(\"http://\"):\n url = \"http://\"+url\n if not url.endswith(\"/\"):\n url = url+\"/\"\n print(\"final url: \", url)\n self.url=url\n\n#Main function which simply creates a client and starts the interface\nif __name__ == \"__main__\":\n c = Client()\n c.runClient()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":13673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"72535853","text":"from django.shortcuts import render\nfrom api.models import Flower, Shipping, Comment\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, permission_classes\nfrom api.serializers import FlowerSerilizer, ShippingSerializer, CommentSerializer\nfrom rest_framework.views import status, APIView\nfrom rest_framework.permissions import IsAuthenticated\n\n\n@api_view(['GET', 'POST'])\ndef flower_list(request):\n if request.method == 'GET':\n try:\n flowers = Flower.objects.all()\n serializer = FlowerSerilizer(flowers, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except:\n return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n if request.method == 'POST':\n flower = Flower.objects.create(\n name = request.data['name'],\n price = request.data['price'],\n description = request.data['description'],\n image = request.data['image'],\n light = request.data['light'],\n temp = request.data['temp'],\n humidity = request.data['humidity'],\n watering = request.data['watering'],\n fertilizer = request.data['fertilizer'],\n transplantatio = request.data['transplantatio'],\n )\n\n return Response({\"flower\":\"atbbe\"}, status=status.HTTP_200_OK)\n\n@api_view(['GET'])\ndef flower_detailed(request, flower_id):\n try:\n flower = Flower.objects.get(id=flower_id)\n except:\n return Response({\"\": \"\"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n if request.method == 'GET':\n serializer = FlowerSerilizer(flower)\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n@permission_classes(IsAuthenticated, ) \n@api_view(['PUT', 'DELETE'])\ndef flower_admin(request, flower_id):\n try:\n flower = Flower.objects.get(id=flower_id)\n except:\n return Response({\"\": \"\"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n if request.method =='PUT':\n flower.name = request.data['name']\n flower.price = request.data['price']\n flower.description = request.data['description']\n flower.image = request.data['image']\n flower.light = request.data['light']\n flower.temp = request.data['temp']\n flower.humidity = request.data['humidity']\n flower.watering = request.data['watering']\n flower.fertilizer = request.data['fertilizer']\n flower.transplantatio = request.data['transplantatio']\n flower.save()\n return Response({\"flower\": \"aaaaaaa\"}, status=status.HTTP_200_OK)\n if request.method =='DELETE':\n flower.delete()\n return Response({\"serializer.data\": \"a\"}, status=status.HTTP_200_OK)\n\nclass ShippingView(APIView):\n def post(self, request):\n flower = Flower.objects.get(id=request.data['flower'])\n Shipping.objects.create(\n name = request.data['name'],\n phone = request.data['phone'],\n flower = flower\n )\n return Response({\"fff\": 'fff'}, status=status.HTTP_200_OK)\n \n def get(self, request):\n try:\n ships = Shipping.objects.all()\n serializer = ShippingSerializer(ships, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except:\n return Response({\"\": \"\"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\nclass CommentView(APIView):\n def post(self, request):\n flower = Flower.objects.get(id=request.data['id'])\n Comment.objects.create(\n name = request.data['name'],\n text = request.data['text'],\n flower = flower\n )\n return Response({\"fff\": 'fff'}, status=status.HTTP_200_OK)\n\n def get(self, request):\n try:\n comments = Comment.objects.all()\n serializer = CommentSerializer(comments, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except:\n return Response({\"\": \"\"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"380027141","text":"import CONFIG\nimport mysql.connector\n\n\n# 元类\nclass Mysqlservermetaclass(type):\n def __new__(mcs, name, bases, attrs):\n attrs['DBSERVER'] = CONFIG.MYSQLDBSERVER\n return type.__new__(mcs, name, bases, attrs)\n\n\nclass MysqlDBmetaclass(Mysqlservermetaclass):\n def __new__(mcs, name, bases, attrs):\n attrs['db_name'] = name\n attrs['dbconn'] = {'database': name}\n return type.__new__(mcs, name, bases, attrs)\n\n\nclass MysqlTableMetaclass(MysqlDBmetaclass):\n def __new__(mcs, name, bases, attrs):\n attrs['table_name'] = name\n return type.__new__(mcs, name, bases, attrs)\n\n\n# 基类\nclass MysqlserverBase(metaclass=Mysqlservermetaclass):\n @classmethod\n def __getconn(cls):\n conn = mysql.connector.connect(**cls.DBSERVER)\n return conn\n\n @classmethod\n def databases(cls):\n conn = cls.__getconn()\n cr = conn.cursor()\n sql = 'show databases;'\n cr.execute(sql)\n t = cr.fetchall()\n __databases = []\n for tp in t:\n __databases.append(tp[0])\n return __databases\n\n\nclass MysqlDBBase(metaclass=MysqlDBmetaclass):\n @classmethod\n def __getconn(cls):\n LOCAL_DB = dict(cls.DBSERVER, **cls.dbconn)\n conn = mysql.connector.connect(**LOCAL_DB)\n return conn\n\n @classmethod\n def getdata(cls, sql):\n conn = cls.__getconn()\n cr = conn.cursor()\n cr.execute(sql)\n t = cr.fetchall()\n return t\n\n @classmethod\n def changedata(cls, sql):\n conn = cls.__getconn()\n cr = conn.cursor()\n cr.execute(sql)\n conn.commit()\n\n @classmethod\n def tables(cls):\n conn = cls.__getconn()\n cr = conn.cursor()\n sql = 'show tables;'\n cr.execute(sql)\n t = cr.fetchall()\n __tables = []\n for tp in t:\n __tables.append(tp[0])\n return __tables\n\n\nclass MysqlTableBase(metaclass=MysqlTableMetaclass):\n @classmethod\n def desc(cls):\n t0 = ('Field', 'Type', 'Null', 'Key', 'Default', 'Extra')\n sql = 'desc %s;' % cls.table_name\n __desc = cls.getdata(sql)\n __desc.insert(0, t0)\n return __desc\n\n # 获取列名\n @classmethod\n def colnames(cls):\n sql = 'desc %s;' % cls.table_name\n t = cls.getdata(sql)\n __colnames = []\n for tp in t:\n __colnames.append(tp[0])\n return __colnames\n\n # 增删改查\n @classmethod\n def select(cls, DISTINCT='', COLNAMES='', TABLES='', WHERE='', LIMIT='', ORDER_BY=''):\n __SELECT = \"select {} {} from {} {} {} {};\".format(DISTINCT, COLNAMES, TABLES, WHERE, LIMIT, ORDER_BY)\n return __SELECT\n\n @classmethod\n def insert(cls, TABLES='', COLNAMES='', VALUES=''):\n __INSERT = \"insert into {} {} values {};\".format(TABLES, COLNAMES, VALUES)\n return __INSERT\n\n @classmethod\n def update(cls, TABLES='', KEYWORDS='', WHERE=''):\n __UPDATE = \"update {} set {} {};\".format(TABLES, KEYWORDS, WHERE)\n return __UPDATE\n\n @classmethod\n def delete(cls, TABLES='', WHERE=''):\n __DELECT = \"delete from {} {};\".format(TABLES, WHERE)\n return __DELECT\n\n # 列出表内总数\n @classmethod\n def fetchall(cls, NUM=0):\n if NUM == 0:\n __SQL = cls.select(COLNAMES='*', TABLES=cls.table_name)\n else:\n __SQL = cls.select(COLNAMES='*', TABLES=cls.table_name, LIMIT='LIMIT {}'.format(NUM))\n return cls.getdata(__SQL)\n\n @classmethod\n def colnum(cls):\n __SQL = cls.select(COLNAMES='count(*)', TABLES=cls.table_name)\n print(__SQL)\n __NUM = cls.getdata(__SQL)\n return __NUM[0][0]\n\n\n# 类\nclass Mysqlserver(MysqlserverBase):\n pass\n\n\nclass MysqlDB(MysqlDBBase):\n pass\n\n\nclass MysqlTable(MysqlTableBase):\n def __init__(self, **kw):\n for key in kw:\n assert key in self.colnames(), \"当前表中没有->{}<-列\".format(key)\n self.info = kw\n\n def count(self):\n __condition = 'where'\n for key in self.info:\n __condition = __condition + ' {}=\\'{}\\' and'.format(key, self.info[key])\n __condition = __condition[:-4]\n __SQL = self.select(COLNAMES='count(*)', TABLES=self.table_name, WHERE=__condition)\n __NUM = self.getdata(__SQL)\n return __NUM[0][0]\n\n def search(self, NUM=0):\n __condition = 'where'\n for key in self.info:\n if self.info[key]=='':\n pass\n else:\n __condition = __condition + ' {}=\\'{}\\' and'.format(key, self.info[key])\n if len(__condition)<=6:\n return []\n else:\n __condition = __condition[:-4]\n if NUM == 0:\n __SQL = self.select(COLNAMES='*', TABLES=self.table_name, WHERE=__condition)\n else:\n __SQL = self.select(COLNAMES='*', TABLES=self.table_name, WHERE=__condition, LIMIT='LIMIT {}'.format(NUM))\n return self.getdata(__SQL)\n\n def save(self):\n __COLNAME='( '\n __VALUES='( '\n for key in self.info:\n if self.info[key]=='':\n pass\n else:\n __COLNAME=__COLNAME+key+','\n __VALUES=__VALUES+'\\''+self.info[key]+'\\''+','\n __COLNAME=__COLNAME[:-1]+')'\n __VALUES=__VALUES[:-1]+')'\n __SQL=self.insert(TABLES=self.table_name,COLNAMES=__COLNAME,VALUES=__VALUES)\n print(__SQL)\n try:\n self.changedata(__SQL)\n return True\n except Exception as e:\n print(e)\n return False\n\n\n pass\n\n # 辅助功能\n\n\nif __name__ == '__main__':\n class DBserver(Mysqlserver):\n pass\n\n\n class Groupdata1(MysqlDB, DBserver):\n pass\n\n\n class Group10(MysqlTable, Groupdata1):\n pass\n\n\n db = DBserver()\n l = Group10(**{'QunNum': 900002})\n print(l.info)\n print(db.databases())\n print(l.DBSERVER)\n print(l.db_name)\n print(l.table_name)\n print(l.databases())\n print(l.tables())\n print(l.colnames())\n print(l.desc())\n print(l.count())\n print(l.search())\n","sub_path":"test__mysqlmetaclass.py","file_name":"test__mysqlmetaclass.py","file_ext":"py","file_size_in_byte":6141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"75860149","text":"import numpy as np\nfrom vgg16.vgg16 import load_vgg16_features\nfrom roicap.roicap import load_roicap_features\nfrom keras.preprocessing.sequence import pad_sequences\n\n\ndef len_cap_data_generator(image_ids, batch_size, caption_lengths, shuffle=False):\n \"\"\"\n Generates data for LenCap model.\n :param image_ids: image ids\n :type image_ids: numpy.array\n :param batch_size: batch size\n :type batch_size: int\n :param caption_lengths:\n :type caption_lengths: pandas.DataFrame\n :param shuffle: shuffle the data if true\n :type shuffle: bool\n \"\"\"\n b = 0\n image_index = -1\n image_id = 0\n output_size = 2\n batch_image_features, batch_caption_length = None, None\n while True:\n try:\n image_index = (image_index + 1) % len(image_ids)\n if shuffle and image_index == 0:\n np.random.shuffle(image_ids)\n image_id = image_ids[image_index]\n image_features = load_vgg16_features(image_id)\n caption_length = np.zeros(output_size)\n pos = caption_lengths.loc[image_id].values[1]\n caption_length[pos] = 1\n if b == 0:\n batch_image_features = np.zeros((batch_size,) + image_features.shape, dtype=image_features.dtype)\n batch_caption_length = np.zeros((batch_size,) + caption_length.shape, dtype=caption_length.dtype)\n batch_image_features[b] = image_features\n batch_caption_length[b] = caption_length\n b += 1\n if b >= batch_size:\n yield batch_image_features, batch_caption_length\n b = 0\n except:\n raise Exception('An error occurred while processing image ' + str(image_id))\n\n\ndef med_cap_data_generator(sequences, config, features_type, fc, shuffle=False):\n \"\"\"\n Generates data for MedCap model.\n :param sequences: word sequences\n :type sequences: list(list)\n :param config: model configurations\n :type config: Config\n :param features_type: type of the image features\n :type features_type: str\n :param fc: use features from fully connected layer if true\n :type fc: bool\n :param shuffle: shuffle the data if true\n :type shuffle: bool\n \"\"\"\n assert features_type in ('vgg16', 'roicap')\n b = 0\n sequence_index = -1\n sequence_id = 0\n sequence_ids = np.array([i for i in range(len(sequences))])\n prev_im_id = -1\n prev_img_features = None\n batch_size = config.BATCH_SIZE\n while True:\n try:\n sequence_index = (sequence_index + 1) % len(sequence_ids)\n if shuffle and sequence_index == 0:\n np.random.shuffle(sequence_ids)\n sequence_id = sequence_ids[sequence_index]\n image_id = sequences[sequence_id][0]\n prev_words = sequences[sequence_id][1]\n next_word = sequences[sequence_id][2]\n prev_word_features = pad_sequences([prev_words], config.PADDING_SIZE)[0]\n if prev_im_id == image_id:\n img_features = prev_img_features\n else:\n if features_type == 'vgg16':\n img_features = load_vgg16_features(image_id, fc)\n else:\n img_features = load_roicap_features(image_id)\n prev_img_features = img_features\n prev_im_id = image_id\n next_word_feature = np.zeros(config.VOCABULARY_SIZE)\n next_word_feature[next_word] = 1\n if b == 0:\n batch_image_features = np.zeros((batch_size,) + img_features.shape, dtype=img_features.dtype)\n batch_prev_words = np.zeros((batch_size,) + prev_word_features.shape, dtype=prev_word_features.dtype)\n batch_next_word = np.zeros((batch_size,) + next_word_feature.shape, dtype=next_word_feature.dtype)\n batch_image_features[b] = img_features\n batch_prev_words[b] = prev_word_features\n batch_next_word[b] = next_word_feature\n b += 1\n if b >= batch_size:\n yield [batch_image_features, batch_prev_words], batch_next_word\n b = 0\n except:\n raise Exception('An error occurred while processing sequence ' + str(sequence_id))\n","sub_path":"data_generators.py","file_name":"data_generators.py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"84287475","text":"import pickle\r\nimport json\r\nimport registers\r\nimport TUI as tui\r\n\r\n\r\nclass Library:\r\n def __init__(self):\r\n self.authors = registers.AuthorRegister()\r\n self.books = registers.BookRegister()\r\n\r\n # ==================================== Search ==================================== #\r\n\r\n def search_author(self, first_name, last_name):\r\n author_list = self.authors.search_by_name(first_name, last_name)\r\n if author_list:\r\n tui.print_list_of_items(f\"Search result for author: {first_name} {last_name}\",\r\n author_list)\r\n user_answer = input('Do you want to choose existing record [index]/[N]? ')\r\n try:\r\n user_answer = int(user_answer)\r\n author = author_list[user_answer - 1]\r\n except KeyError:\r\n print(f\"There is no author with such index: {user_answer}\")\r\n author = None\r\n except ValueError:\r\n print(f\"Adding a new record for {first_name} {last_name}\")\r\n author = None\r\n else:\r\n author = None\r\n print(f'There is no author {first_name} {last_name} in the Register')\r\n return author\r\n\r\n def search_books_by_author(self, first_name='?', last_name='?'):\r\n author = self.search_author(first_name, last_name)\r\n if author:\r\n list_of_results = []\r\n book_list = self.books.search_by_author_id(author.id)\r\n for book in book_list:\r\n list_of_results.append([book.id, book.title, author.first_name + ' ' + author.last_name])\r\n if book_list:\r\n tui.print_list_of_items(f\"Search results for books by {first_name} {last_name}\",\r\n list_of_results)\r\n return author, book_list\r\n else:\r\n print(f\"There is no books of {first_name} {last_name} in the Registry\")\r\n\r\n # ================================= Add / Delete ================================= #\r\n\r\n def add_book(self, title, first_name, last_name):\r\n # Select or add new author:\r\n author = self.add_author(first_name, last_name)\r\n _ = self.books.add(title, author.id)\r\n\r\n def add_author(self, first_name, last_name):\r\n # Get the list of existing authors:\r\n author = self.search_author(first_name, last_name)\r\n if not author:\r\n author = self.authors.add(first_name, last_name)\r\n else:\r\n print(f\"Selected {author.first_name} {author.last_name}, ID: {author.id}\")\r\n return author\r\n\r\n def remove_author(self, first_name, last_name):\r\n try:\r\n author, book_list = self.search_books_by_author(first_name, last_name)\r\n user_input = input(f'Do you really want to delete all records '\r\n f'for {first_name} {last_name}? [Y]/[N]: ')\r\n if user_input.lower() == 'y':\r\n for book in book_list:\r\n del self.books.register[book.id]\r\n del self.authors.register[author.id]\r\n except TypeError:\r\n pass\r\n\r\n # ===================================== I/O ====================================== #\r\n\r\n def save_library(self):\r\n with open('library_manager.pkl', 'wb') as file:\r\n pickle.dump((self.authors, self.books), file)\r\n print('Library was successfully saved on disk')\r\n\r\n def load_library(self):\r\n try:\r\n with open('library_manager.pkl', 'rb') as file:\r\n self.authors, self.books = pickle.load(file)\r\n print('Library data was restored successfully')\r\n except IOError:\r\n print('No previous records were found...')\r\n\r\n def export_library(self):\r\n library_records = {}\r\n for _, book in self.books.register.items():\r\n author = self.authors.register[book.author_id]\r\n\r\n if not library_records.get(author.id, False):\r\n library_records[author.id] = {'first_name': author.first_name,\r\n 'last_name': author.last_name,\r\n 'books': []}\r\n\r\n library_records[author.id]['books'].append((book.id, book.title))\r\n with open('library_export.json', 'w') as json_file:\r\n json.dump(library_records, json_file)\r\n print('All the records were exported successfully!')\r\n","sub_path":"!Projects/MP_Library/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":4487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"305772440","text":"import json\nfrom glob import glob\n\nimport numpy as np\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Json to LaTex (Lightly)\")\nparser.add_argument(\"--exname\", default=\"AFS\", help=\"exname to generate json\")\nparser.add_argument(\"--data\", default=\"best\", choices=[\n \"best\", \"mean\", \"std\"], help=\"best: best accuracy, mean: mean accuracy, std: std of acc\")\nparser.add_argument(\"--epoch\", default=\"first epoch\",\n choices=[\"first epoch\", \"best\"], help=\"which epoch to load.\")\nparser.add_argument(\"--output\", default=\"latex.txt\", help=\"output filename\")\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n # 1. LOAD ALL JSON FILE\n json_file_list = glob(\"results/{}*.json\".format(args.exname))\n\n json_file = {}\n for fn in json_file_list:\n with open(fn, \"r\") as fp:\n key = fn.split(\"/\")[1]\n json_file[key] = json.load(fp)\n\n # 2. GENERATE TABLE\n optimizer = []\n learning_rate = []\n network = []\n activation = []\n\n for k, v in json_file.items():\n k = str(k)\n k = k.replace(\"1e-05\", \"0.00001\")\n ks = k.split(\"-\")\n optimizer.append(ks[2])\n network.append(ks[1])\n learning_rate.append(ks[3].replace(\".json\", \"\"))\n\n for kk, vv in v.items():\n kk = str(kk)\n if kk.startswith(\"best\"):\n activation.append(kk.split(\" \")[1])\n\n optimizer = sorted(set(optimizer))\n learning_rate = sorted(set(learning_rate))\n learning_rate.reverse()\n network = sorted(set(network))\n activation = sorted(set(activation))\n\n # 3. CREATE LATEX CODE\n # first row: learning rate\n # second row: Net. Optim\n # total col: 1 + num_leanring_rate \\times num_net \\times num_optim\n total_col = 1 + len(learning_rate) * len(network) * len(optimizer)\n\n latex = open(args.output, \"w\")\n # 1. first row\n line = [[lr] * len(network) * len(optimizer) for lr in learning_rate]\n line = np.array(line).reshape(-1)\n latex.write(\"Learing Rate & \" + \"&\".join(line) + '\\\\\\\\ \\n')\n # 2. second row\n latex.write(\"Net. Optim & \" + \"&\".join([\"{}. {}\".format(net, optim)\n for net in network for optim in optimizer] * len(learning_rate)) + \"\\\\\\\\ \\n\")\n\n # 3. write data\n for act in activation:\n line = \"{}\".format(act)\n\n for lr in learning_rate:\n if lr == \"0.00001\":\n lr = \"1e-05\"\n for net in network:\n for optim in optimizer:\n jf = \"{}-{}-{}.json\".format(net, optim, lr)\n for k, v in json_file.items():\n if jf in k:\n it = \"{} {} {}\".format(args.epoch, act, args.data)\n line += \"& {:.2f}\".format(v[it])\n break\n latex.write(line + \"\\\\\\\\ \\n\")\n\n latex.close()\n","sub_path":"json_to_latex.py","file_name":"json_to_latex.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"412771202","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\nfrom socketserver import BaseRequestHandler, ThreadingTCPServer\nimport time\nimport v2server\n'''\n@Author : npist\n@License : (C) Copyright 2018, npist.com\n@Contact : npist35@gmail.com\n@File : v2rayMS_Server.py\n@Time : 2018.8.20\n@Ver : 0.2\n'''\n\nHOST = '0.0.0.0'\nPORT = 8854\n\nBUFSIZE = 4096\n\n\n# 多线程数据读取处理\nclass Handler(BaseRequestHandler):\n def handle(self):\n # 初始化数据库\n self.conn_sql = v2server.sqlconn()\n while True:\n try:\n # 接收数据\n data = self.accept_data()\n # 无连接时\n if data is None:\n break\n proc_data = data.decode().split('#')\n # client拉取配置信息\n if proc_data[0] == 'pull_list':\n msg = self.conn_sql.pull_user()\n if msg is not None:\n self.send_data(msg) # 分段发送\n else:\n self.request.sendall(b'error')\n except Exception as e:\n print(e)\n break\n # 结束处理\n print(\"close:\", self.request.getpeername())\n # 关闭sql连接\n self.conn_sql.conn.close()\n # 关闭socket连接\n # self.server.shutdown()\n self.request.close()\n\n # 发送数据\n def send_data(self, data):\n # 判断数据长度 并发送长度\n data_len = len(data)\n self.request.sendall(str(data_len).encode())\n time.sleep(0.1)\n if self.request.recv(BUFSIZE) == b'!#%':\n # 发送数据\n self.request.sendall(data.encode())\n\n # 接收数据\n def accept_data(self):\n # 接收长度信息\n data_size = self.request.recv(BUFSIZE)\n if data_size == b'':\n return None\n # 回复已接受\n self.request.sendall(b'!#%')\n # 初始化长度变量, 字符串\n recevied_size = 0\n recevied_data = b''\n # 数据未接收全的情况进行循环监听\n while recevied_size < int(data_size.decode()):\n data_res = self.request.recv(BUFSIZE)\n recevied_size += len(data_res)\n recevied_data += data_res\n return recevied_data\n\n\ndef main():\n ADDR = (HOST, PORT)\n server = ThreadingTCPServer(ADDR, Handler)\n print('listening')\n server.serve_forever() # 监听\n print(server)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"v2rayMS_Server.py","file_name":"v2rayMS_Server.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"529950466","text":"import sqlite3\n\nclass StudentScore:\n def __init__(self, dbname, table_name):\n self.dbname = dbname\n self.tablename = table_name\n self.num_of_stu = 0\n\n @classmethod\n def defaultFn(cls):\n print(\"1, 2, 3, 4 번 중 하나의 숫자를 입력하세요\")\n\n def getMenu(self):\n print(\"메인 메뉴)\\n\\t1. 입력\\n\\t2. 출력\\n\\t3. 종료\")\n try:\n number = int(input(\"번호를 입력하세요: \"))\n menu = {1:self.getInput,\n 2:self.printOut,\n 3:self.exit}\n menu.get(number, self.defaultFn)()\n except:\n print(\"숫자를 입력하세요\")\n\n def _createTable(self):\n try:\n conn = sqlite3.connect(self.dbname)\n sql = 'create table if not exists {}(name var(20), ' \\\n 'korean int, english int, math int, total int, avg float)'.format(self.tablename)\n conn.execute(sql)\n print(\"테이블 생성 성공\")\n except Exception as err:\n print(err)\n conn.close()\n return conn\n\n def _insertTable(self, conn, data):\n command = f\"insert into {self.tablename} values(?,?,?,?,?,?)\"\n try :\n conn.execute(command, data)\n conn.commit()\n except Exception as err:\n print(err)\n\n def _selectTable(self):\n sql = f\"select * from {self.tablename}\"\n try:\n conn = sqlite3.connect(self.dbname)\n cur = conn.cursor()\n cur.execute(sql)\n dt = cur.fetchall()\n except Exception as err:\n print(err)\n conn.close()\n return dt\n\n def getInput(self):\n # 1. 입력\n conn = self._createTable()\n\n isContinue = True\n while isContinue:\n name = input(\"이름: \")\n korean = int(input(\"국어: \"))\n english = int(input(\"영어: \"))\n math = int(input(\"수학: \"))\n sum = korean + english + math\n data = (name, korean, english, math, sum, round(sum / 3, 2))\n self._insertInput(conn, data)\n while 1:\n tmp = input(\"게속 입력하시겠습니까?(y/n) \")\n print(tmp)\n if tmp == 'n' or tmp == 'y': break\n print(\"y, n 중 하나의 정답을 입력흐세요. \")\n isContinue = True if tmp == 'y' else False\n\n conn.close()\n self.getMenu()\n\n def _title(self):\n print(\"-\"*30)\n print(\"이름\\t국어\\t영어\\t수학\\t총점\\t평균\")\n print(\"-\"*30)\n\n def printOut(self):\n # 2. 출력\n total_score_list = []\n self._title()\n\n dt = self._selectTable()\n for s in dt:\n for k in s:\n print(\"{}\".format(k), end='\\t')\n print()\n print(\"-\"*30)\n\n\n def __del__(self):\n pass\n\n def exit(self):\n # 4. 종료\n self.__del__()\n\nif __name__ == \"__main__\":\n obj = StudentScore(\"score.db\", \"grade\")\n obj.getMenu()\n","sub_path":"python/sqlite/13.database_ex.py","file_name":"13.database_ex.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"336218579","text":"from playsound import playsound\r\nimport sys\r\nimport speech_recognition as sr\r\nimport time\r\nimport webbrowser\r\nimport os.path\r\nimport os\r\n\r\ndef amadeus_command():\r\n\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print('한국어로 말하세요')\r\n audio = r.listen(source)\r\n try:\r\n print(\"당신은 말했습니다.\" + r.recognize_google(audio, language=\"ko-KR\"))\r\n\r\n if '안녕' or '좋은 아침' in r.recognize_google(audio, language=\"ko-KR\"):\r\n print (\"하로-\")\r\n playsound('./aa\\hello.mp3')\r\n\r\n elif \"무엇을 할 수 있\" in r.recognize_google(audio, language=\"ko-KR\"):\r\n print (\"무엇이든 물어봐 주세요. 가능한 범위에서 대답해드릴테니까요.\")\r\n playsound('./aa\\askmewhatever.mp3')\r\n\r\n elif \"나무위키\" in r.recognize_google(audio, language=\"ko-KR\"):\r\n print (\"나무위키에 접속합니다.\")\r\n webbrowser.open('https://namu.wiki')\r\n playsound('./aa\\you_sure.mp3')\r\n \r\n elif \"크롬\" or \"Chrome\" in r.recognize_google(audio, language=\"ko-KR\"):\r\n chromepath = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'\r\n if os.path.isfile(chromepath):\r\n print(\"크롬을 실행합니다.\")\r\n playsound('./aa\\you_sure.mp3')\r\n os.startfile(chromepath)\r\n \r\n else :\r\n print('크롬 브라우저가 설치되지 않았거나 지정된 경로에 없습니다.')\r\n playsound('./aa\\sorry.mp3')\r\n\r\n else:\r\n webbrowser.open(\"http://www.google.com/search?q=\" + r.recognize_google(audio, language=\"ko-KR\"))\r\n \r\n except sr.UnknownValueError:\r\n print(\"질문을 이해할 수 없습니다.\")\r\n playsound('./aa\\sorry.mp3')\r\n\r\n\r\n","sub_path":"command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"557981156","text":"import numpy as np\nimport os\nimport glob\n\nFILE = 'ratg13.clustal'\nSC2 = 'NC_045512.2_21563-25384'\n#EXCLUDE = ['NC_019843.3_21456-25517.mfe', 'NC_004718.3_21492-25259.mfe', 'NC_014470.1_21391-25170.mfe']\nEXCLUDE = []\nLIST_OF_FILES = glob.glob(\"*.mfe\")\nSEQS = len(LIST_OF_FILES)\nMOD = SEQS + 2\nMTX_PATH = \"mtx_%s.npy\" % (SEQS)\n\ndef load_file():\n f = open(FILE, 'r')\n return f.readlines()\n\ndef make_dict(lines):\n seqs_dict = {}\n arr = [[] for i in range(SEQS)]\n for i in range(3, len(lines)):\n if (i - 3) % MOD < SEQS:\n cline = lines[i].split()\n if cline[0] not in seqs_dict:\n seqs_dict[cline[0]] = (i-3) % MOD\n arr[(i-3) % MOD] += list(cline[1])\n\n for key in seqs_dict.keys():\n idx = seqs_dict[key]\n sequence = \"\"\n for char in arr[idx]:\n sequence += char\n seqs_dict[key] = sequence.replace('T', 'U')\n\n np.save(MTX_PATH, arr)\n return np.array(arr), seqs_dict\n\ndef make_dist(mtx):\n dist = {}\n mtx = np.transpose(mtx)\n for i in range(mtx.shape[0]):\n key = \"\"\n for char in mtx[i]:\n key += char\n if key in dist:\n dist[key] += 1\n else:\n dist[key] = 1\n\n return dist\n\ndef insert_gaps(seqs_dict):\n list_of_files = LIST_OF_FILES\n dbs_w_gaps = {}\n\n for f in list_of_files:\n mfe_file = open(f, 'r')\n lines = mfe_file.readlines()\n dot_bracket = lines[len(lines)-1].split()[0]\n seq_w_gaps = seqs_dict[f[0:len(f)-4]]\n db_w_gaps = \"\"\n db_counter = 0\n\n for i in range(len(seq_w_gaps)):\n if seq_w_gaps[i] != \"-\":\n db_w_gaps += dot_bracket[db_counter]\n db_counter += 1\n else:\n db_w_gaps += \"-\"\n dbs_w_gaps[f[0:len(f)-4]] = db_w_gaps\n\n return dbs_w_gaps\n\n'''\nMN996532.1_21545-25354 RatG13\nNC_004718.3_21492-25259 SARS\nNC_014470.1_21391-25170 Bat BM48-31\nNC_019843.3_21456-25517 MERS\nNC_045512.2_21563-25384 SC2\n'''\ndef make_db_array(dbs_w_gaps):\n l = [[] for i in range(SEQS)]\n \n for i, species in enumerate(dbs_w_gaps.keys()):\n print(species)\n l[i] = list(dbs_w_gaps[species])\n #print('\\n\\n')\n #print(l[i])\n\n arr = np.array(l)\n return arr\n\n'''\nMN996532.1_21545-25354 RatG13\nNC_004718.3_21492-25259 SARS\nNC_014470.1_21391-25170 Bat BM48-31\nNC_019843.3_21456-25517 MERS\nNC_045512.2_21563-25384 SC2\n'''\ndef compare2(seqs_dict, dbs_w_gaps, threshold=20):\n input_mtx = make_db_array(dbs_w_gaps)\n mtx = np.transpose(input_mtx)\n streaks = []\n cstreak = 0\n sites = []\n start_site = 0\n end_site = 0\n for i in range(mtx.shape[0]):\n site = mtx[i]\n if site[0] == site[SEQS-1]:\n if cstreak == 0:\n start_site = i\n cstreak += 1\n elif cstreak != 0:\n if cstreak >= threshold:\n streaks.append(cstreak)\n end_site = i\n sites.append((start_site, end_site))\n cstreak = 0\n print(streaks)\n print(sites)\n print(\"max: \", max(streaks))\n print(\"total more than %d: %d\" % (threshold, len(streaks)))\n print_conserved(mtx, dbs_w_gaps, seqs_dict, sites, [0, SEQS-1])\n\ndef print_conserved(db, dbs_w_gaps, seqs_dict, sites, species_list):\n keys = list(dbs_w_gaps.keys())\n for j in species_list:\n f = open('%s_cons.txt' % (keys[j]), 'w')\n for loc in sites:\n f.write('> ' + str(loc) + ' ' + keys[j] + '\\n')\n line1 = seqs_dict[keys[j]][loc[0]:loc[1]]\n line2 = dbs_w_gaps[keys[j]][loc[0]:loc[1]]\n #line2 = ''\n #for i in range(loc[0], loc[1]):\n #line2 += db[i][j]\n f.write(line1 + '\\n')\n f.write(line2 + '\\n')\n f.close()\n\ndef count_all_same(db_dist):\n counts = np.zeros(SEQS)\n for entry in db_dist.keys():\n count = db_dist[entry]\n counts[len(set(entry))-1] += count\n \n print(\"[all same, 4 same, 3 same, 2 same, all diff]\")\n print(counts)\n\ndef translate(entry, sc2_idx):\n translation = ['x', 'q', 'w', 'y', 'z']\n entrylist = list(entry)\n x = entrylist[sc2_idx]\n new_entry = []\n seen = [0]\n for i in range(SEQS):\n if entrylist[i] == x:\n new_entry.append(0)\n elif entrylist[i] in seen:\n new_entry.append(seen.index(entrylist[i]))\n else:\n new_entry.append(len(seen))\n seen.append(entrylist[i])\n ne = ''\n for j in range(SEQS): \n ne += translation[new_entry[j]]\n\n return ne\n\ndef collapse(distribution, sc2_idx):\n new_d = {}\n total = 0\n for entry in distribution:\n ne = translate(entry, sc2_idx) \n if ne in new_d:\n new_d[ne] += distribution[entry]\n total += distribution[entry]\n else:\n new_d[ne] = distribution[entry]\n total += distribution[entry]\n\n return new_d\n\ndef standardize(seqs_dict, dbs_w_gaps, threshold=0):\n files = LIST_OF_FILES\n seqs_mtx = [[] for i in range(SEQS)]\n dbs_mtx = [[] for i in range(SEQS)]\n keys = []\n for i, f in enumerate(files):\n key = f[0:len(f)-4]\n keys.append(key)\n seqs_mtx[i] = list(seqs_dict[key])\n dbs_mtx[i] = list(dbs_w_gaps[key])\n\n seqs = np.array(seqs_mtx)\n dbs = np.array(dbs_mtx)\n dist = make_dist(seqs)\n sites = np.transpose(seqs)\n # now onto the stack:\n covid = keys.index(SC2)\n # FLAG\n collapsed_dist = collapse(dist, covid)\n #collapsed_dist = dist\n covid_seq = seqs[covid]\n covid_db = dbs[covid]\n #print(dbs_w_gaps[SC2][617:691])\n #print('\\n')\n covid_db_nogaps = dbs_w_gaps[SC2].replace('-', '')\n #print(covid_db_nogaps[471:516])\n #print(covid_db_nogaps[517:666])\n #print(covid_db_nogaps[666:701])\n dim = seqs.shape[1]\n stack = []\n streaks = []\n locs = []\n cstreak = 0\n start = 0\n end = 0\n i = 0\n while i < dim:\n dot_brac = covid_db[i]\n site = sites[i]\n entry = ''\n for char in site:\n entry += char\n te = translate(entry, covid)\n if dot_brac == '(':\n stack.append((te, i))\n elif dot_brac == ')':\n #print('stack on loc %d:' % (i))\n #print(stack)\n check = stack.pop()\n if te == check[0]:\n if covid_db[i+1] != ')':\n end = i\n cstreak = end - check[1]\n if cstreak >= threshold:\n streaks.append(cstreak)\n locs.append((check[1], end))\n #cstreak = 0\n #start = i\n else:\n prev_stack = check[1]\n j = 0\n while j < len(stack):\n if stack[-1][1] - prev_stack == 1:\n prev_stack = stack[-1][1]\n stack.pop()\n i += 1\n else:\n j = len(stack)\n i += 1\n #cons(locs, seqs_dict[SC2], dbs_w_gaps[SC2])\n return streaks, locs, collapsed_dist, sites, covid, seqs_dict[SC2].replace('-', '')\n\ndef cons(locs, seq, db):\n f = open('ratg13_cons_no_gaps.txt', 'w')\n for loc in locs:\n f.write('> ' + str(loc[0]) + '-' + str(loc[1]) + ' log likelihood: ' + str(loc[2]) + 'random seq of same size log likelihood: ' + str(loc[3]) + '\\n')\n line1 = seq[loc[0]:loc[1]+1]\n line2 = db[loc[0]:loc[1]+1]\n f.write(line1 + '\\n')\n f.write(line2 + '\\n\\n')\n f.close()\n\ndef find(seqs, locs):\n no_gaps = seqs[SC2].replace('-', '')\n seq = seqs[SC2]\n ans = []\n for loc in locs:\n find = seq[loc[0]:loc[1]+1].replace('-', '')\n start = no_gaps.index(find)\n end = start + len(find)\n ans.append((start, end))\n \n starts = []\n ends = []\n for loc in ans:\n starts.append(loc[0])\n ends.append(loc[1])\n fans = []\n for i in range(len(ans)):\n cloc = ans[i]\n if cloc[0] - 1 in starts and cloc[1] + 1 in ends and starts.index(cloc[0] - 1) == ends.index(cloc[1] + 1):\n pass\n else:\n fans.append(cloc)\n\n return fans\n\ndef getnum(blist):\n current_num = 0\n for i in range(len(blist)):\n if blist[i] == ')' and blist[i-1] != ')':\n current_num += 1\n return current_num\n\ndef nest(newlocs, cov_db_nogaps):\n #print(cov_db_nogaps[7:3220])\n final_locs = []\n current_stretch = newlocs.pop()\n blist = list(cov_db_nogaps[current_stretch[0]:current_stretch[1]+1])\n current_num = getnum(blist)\n track = 1\n i = 0\n size = len(newlocs)\n while i < size:\n check = newlocs.pop()\n blist = list(cov_db_nogaps[check[0]: check[1]+1])\n #print(current_stretch[0])\n #print(check[0])\n if current_stretch[0] < check[0]:\n if current_num - getnum(blist) == track:\n track += 1\n else:\n current_stretch = check\n current_num = getnum(blist)\n track = 1\n #print(\"nested!\")\n #current_num -= 1\n else:\n #print(current_num)\n if current_num - track == 0:\n final_locs.append(current_stretch)\n current_stretch = check\n current_num = getnum(blist)\n track = 1\n if i == size - 1 and current_num - track == 0:\n final_locs.append(current_stretch)\n i += 1\n #print(current_num)\n return final_locs\n\ndef tack_on(loc, cov_db_nogaps, sites):\n start = loc[0]\n end = loc[1]\n before = start - 1\n entry = \"\"\n for char in sites[before]:\n entry += char\n e = translate(entry, covid)\n addone = False\n while before >= 0 and cov_db_nogaps[before] == '.':\n centry = \"\"\n for char in sites[before]:\n centry += char\n ce = translate(centry, covid)\n if ce == e and cov_db_nogaps[before-1] == '.':\n before -= 1\n else:\n break\n if before == start - 1:\n before += 1\n \n after = end\n #print(cov_db_nogaps[after])\n entry = \"\"\n for char in sites[after]:\n entry += char\n e = translate(entry, covid)\n while after < sites.shape[0] and cov_db_nogaps[after] == '.':\n centry = \"\"\n for char in sites[after]:\n centry += char\n ce = translate(centry, covid)\n if ce == e:\n after += 1\n else:\n #after -= 1\n break\n \n laced_loc = (before, after-1)\n\n return laced_loc\n\ndef lace(flocs, cov_db_nogaps, sites, cdist, covid):\n intsarr = []\n for i in range(sites.shape[0]):\n if sites[i][covid] == '-':\n intsarr.append(i)\n sites = np.delete(sites, intsarr, axis=0)\n final_dist = make_dist(np.transpose(sites))\n tot = 0\n final_dist = collapse(final_dist, covid)\n for item in final_dist:\n tot += final_dist[item]\n\n laced_locs = []\n for i in range(len(flocs)):\n loc = flocs.pop()\n laced_locs.append(tack_on(loc, cov_db_nogaps, sites))\n \n fin = []\n for i in range(len(laced_locs)-1):\n c = laced_locs[i]\n cn = laced_locs[i+1]\n if cn[0] - c[1] <= 1:\n fin.append((c[0], cn[1]))\n else:\n if len(fin) == 0:\n fin.append(c)\n elif fin[-1][1] != c[1]:\n fin.append(c)\n if fin[-1][1] != laced_locs[-1][1]:\n fin.append(laced_locs[-1])\n fin2 = []\n for i in range(len(fin)-1):\n c = fin[i]\n cn = fin[i+1]\n if cn[0] <= c[1]:\n fin2.append((c[0], cn[1]))\n else:\n if len(fin2) == 0:\n fin2.append(c)\n elif fin2[-1][1] != c[1]:\n fin2.append(c)\n if fin2[-1][1] != fin[-1][1]:\n fin2.append(fin[-1])\n fin3 = []\n for i in range(len(fin2)-1):\n c = fin2[i]\n cn = fin2[i+1]\n if cn[0] <= c[1]:\n fin3.append((c[0], cn[1]))\n else:\n if len(fin3) == 0:\n fin3.append(c)\n elif fin3[-1][1] != c[1]:\n fin3.append(c)\n if fin3[-1][1] != fin2[-1][1]:\n fin3.append(fin2[-1])\n return fin3, final_dist, tot, sites\n\n\ndef probs(laced_flocs, fd, tot, final_sites, covid):\n s_gene_probs = []\n str_sites = []\n for site in final_sites:\n entry = \"\"\n for char in site:\n entry += char\n s_gene_probs.append(fd[translate(entry, covid)] / tot)\n str_sites.append(translate(entry, covid))\n s_gene_probs = np.log(s_gene_probs)\n sigma = np.var(s_gene_probs)\n mu = np.mean(s_gene_probs) \n # np.random.normal(mu, sigma, length of seq)\n fprobs = []\n samplesarray = []\n for loc in laced_flocs:\n samples = (loc[1]+1) - loc[0]\n samplesarray.append(samples)\n prob = 0\n for i in range(loc[0], loc[1]+1):\n prob += s_gene_probs[i]\n draw = np.random.normal(mu, sigma, samples)\n fprobs.append((loc[0], loc[1], prob, np.sum(draw)))\n print(max(samplesarray))\n return fprobs\n\nif __name__ == '__main__':\n lines = load_file()\n _, seqs_dict = make_dict(lines)\n for item in EXCLUDE:\n LIST_OF_FILES.remove(item)\n del seqs_dict[item[0:len(item)-4]]\n SEQS = len(LIST_OF_FILES)\n dbs_w_gaps = insert_gaps(seqs_dict)\n streaks, locs, cdist, sites, covid, sd = standardize(seqs_dict, dbs_w_gaps)\n #print(\"num of locs from stand: \", len(locs))\n newlocs = find(seqs_dict, locs)\n #print(\"num of newlocs from find: \", len(newlocs))\n cov_db_nogaps = dbs_w_gaps[SC2].replace('-', '')\n #print(\"NEW LOCS: \", newlocs)\n #print(\"look at new locs:\\n\")\n '''\n for loc in newlocs:\n print(str(loc))\n print(cov_db_nogaps[loc[0]:loc[1]])\n print('\\n')\n '''\n flocs = nest(newlocs, cov_db_nogaps)\n #print(\"FINAL LOCS: \", flocs)\n #print(\"look at final locs:\\n\")\n '''\n for loc in flocs:\n print(str(loc))\n print(cov_db_nogaps[loc[0]:loc[1]])\n print('\\n')\n '''\n laced_flocs, fd, tot, final_sites = lace(flocs, cov_db_nogaps, sites, cdist, covid)\n attached_probs = probs(laced_flocs, fd, tot, final_sites, covid)\n #print('-' * 80)\n #print(\"LACED FINAL LOCS: \", laced_flocs)\n #print(\"557-581\")\n #print(cov_db_nogaps[557:582])\n cons(attached_probs, sd, cov_db_nogaps)\n print(len(attached_probs))\n\n #for loc in attached_probs:\n #print(str(loc))\n #print(cov_db_nogaps[loc[0]:loc[1]+1])\n #print(\"This sequence had probability: %f. A random one of similar size had prob: %f\" % (loc[2], loc[3]))\n #print('\\n')\n #nest(newlocs)\n # when SEQS=5:\n # mtx[0] = NC_019843, mtx[1] = MN996532, mtx[2] = NC_045512, mtx[3] = NC_004718, mtx[4] = NC_014470\n # 0 = MERS, 1 = RaTG13, 2 = SC2, 3 = SARS, 4 = Bat BM48-31\n #compare2(seqs_dict, dbs_w_gaps)\n #print(db_mtx)\n #print(np.transpose(db_mtx))\n #db_dist = make_dist(db_mtx)\n #count_all_same(db_dist)\n #make_dist(mtx)\n","sub_path":"Interspecies_Dataset/conserved/sc2_and_RaTG13/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":15114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"426536714","text":"# Convert a number of seconds into days, with an interation to always as for\n# a nem number until the user inputs a negative one.\n\nnumber = int(input('Cyclical day calculator\\nWrite a number of seconds\\n(A negative number stops the execution)\\n? '))\n\nwhile number > -1:\n days = number / (3600 * 24)\n print('The equivalent number of days is:', days)\n\n # Ask again for a number\n number = int(input('Write a number of seconds\\n(A negative number stops the execution)\\n? '))\n","sub_path":"cap2/ex9.py","file_name":"ex9.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"572118759","text":"#coding: utf-8\nfrom datetime import date\n\nfrom django.contrib.auth.models import User, Permission\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.test import TestCase\n\nfrom interface.models import LogMeta\nfrom mgr.models import Region, Store, Company, Employee\nfrom views import query_employee, query_regions, query_companies, query_stores\nfrom ajax import AdminFilter, UserPermittedFilter, UserUnpermittedFilter\nfrom ajax import available_levels, titles_for_org_stat\n\n\ndef _equal(emp_qs, emp_arr):\n qs_dict = {}\n for emp in emp_qs:\n qs_dict[emp.username] = emp\n\n arr_dict = {}\n for emp in emp_arr:\n arr_dict[emp.username] = emp\n\n return qs_dict == arr_dict\n\n\nclass TestEmployeeView(TestCase):\n\n def setUp(self):\n self.region = Region(name='region')\n self.region.save()\n\n self.company1 = Company(name='compnay1', region=self.region)\n self.company1.save()\n self.store1 = Store(code='1', name='test_1', company=self.company1)\n self.store1.save()\n self.emp = Employee(username='test_emp', organization=self.company1)\n self.emp.save()\n\n self.company2 = Company(code='2',name='company2', region=self.region)\n self.company2.save()\n self.store2 = Store(code='2', name='test_2', company=self.company2)\n self.store2.save()\n self.store3 = Store(code='3', name='test_3', company=self.company2)\n self.store3.save()\n self.store4 = Store(code='4', name='test_4', company=self.company2)\n self.store4.save()\n self.emp2 = Employee(username='test_emp2', organization=self.store2)\n self.emp2.save()\n self.emp3 = Employee(username='test_emp3', organization=self.store2)\n self.emp3.save()\n\n self.admin = User(username='admin', is_staff=True)\n self.admin.save()\n\n\n def test_query_employee(self):\n emps = query_employee(self.emp, None)\n self.assertTrue(len(emps) == 0)\n\n emps = query_employee(self.admin, self.company2)\n self.assertTrue(_equal(emps, [self.emp2, self.emp3]))\n\n emps = query_employee(self.emp, self.company1)\n self.assertTrue(_equal(emps, [self.emp]))\n\n emps = query_employee(self.emp, self.company2)\n self.assertTrue(len(emps) == 0)\n \n\nclass TestQueryRegions(TestCase):\n def setUp(self):\n log_type = ContentType.objects.get_for_model(LogMeta)\n permission = Permission.objects.get(content_type=log_type, \n codename='view_organization_statistics')\n\n self.admin = User(username='admin', is_staff=True)\n self.admin.save()\n self.region1 = Region(name='region1')\n self.region1.save()\n self.emp = Employee(username='test_emp', organization=self.region1)\n self.emp.save()\n self.emp.user_permissions=[permission]\n\n self.region2 = Region(name='region2')\n self.region2.save()\n\n self.emp_no_perm = Employee(username='test_emp_no_perm', organization=self.region1)\n self.emp_no_perm.save()\n\n def test_query_regions(self):\n regions = query_regions(self.admin)\n self.assertItemsEqual(regions, Region.objects.all())\n\n regions = query_regions(self.emp_no_perm)\n self.assertTrue(len(regions) == 0)\n\n regions = query_regions(self.emp)\n self.assertItemsEqual(regions, [self.region1])\n\n\nclass TestQueryCompanies(TestCase):\n def setUp(self):\n log_type = ContentType.objects.get_for_model(LogMeta)\n permission = Permission.objects.get(content_type=log_type, \n codename='view_organization_statistics')\n\n self.admin = User(username='admin', is_staff=True)\n self.admin.save()\n\n self.region1 = Region(name='region1')\n self.region1.save()\n self.emp_region1_1 = Employee(username='test_emp', organization=self.region1)\n self.emp_region1_1.save()\n self.emp_region1_1.user_permissions = [permission]\n\n self.emp_no_perm = Employee(username='test_emp_no_perm', organization=self.region1)\n self.emp_no_perm.save()\n\n self.company = Company(code='1001', name='company1', region = self.region1)\n self.company.save()\n\n self.store = Store(code='10011001', name='store1', company=self.company)\n self.store.save()\n self.emp_store = Employee(username='test_emp2', organization=self.store)\n self.emp_store.save()\n self.emp_store.user_permissions = [permission]\n\n def test_query_companies(self):\n companies = query_companies(self.admin, \"\")\n self.assertTrue(len(companies) == 0)\n\n companies = query_companies(self.emp_no_perm, self.region1.pk)\n self.assertTrue(len(companies) == 0)\n\n companies = query_companies(self.admin, self.region1.pk)\n self.assertItemsEqual(companies, [self.company])\n\n companies = query_companies(self.emp_region1_1, self.region1.pk)\n self.assertItemsEqual(companies, [self.company])\n\n companies = query_companies(self.emp_store, self.region1.pk)\n self.assertTrue(len(companies) == 0)\n\n\nclass TestQueryStores(TestCase):\n def setUp(self):\n log_type = ContentType.objects.get_for_model(LogMeta)\n permission = Permission.objects.get(content_type=log_type, \n codename='view_organization_statistics')\n\n self.admin = User(username='admin', is_staff=True)\n self.admin.save()\n\n self.region1 = Region(name='region1')\n self.region1.save()\n self.emp_region1_1 = Employee(username='test_emp', organization=self.region1)\n self.emp_region1_1.save()\n self.emp_region1_1.user_permissions = [permission]\n\n self.emp_no_perm = Employee(username='test_emp_no_perm', organization=self.region1)\n self.emp_no_perm.save()\n\n self.company = Company(code='1001', name='company1', region = self.region1)\n self.company.save()\n self.emp_company = Employee(username='test_emp_company', organization=self.company)\n self.emp_company.save()\n self.emp_company.user_permissions = [permission]\n\n self.store = Store(code='10011001', name='store1', company=self.company)\n self.store.save()\n self.emp_store = Employee(username='test_emp2', organization=self.store)\n self.emp_store.save()\n self.emp_store.user_permissions = [permission]\n\n def test_query_stores(self):\n stores = query_stores(self.admin, \"\")\n self.assertTrue(len(stores) == 0)\n\n stores = query_stores(self.admin, self.company.pk)\n self.assertItemsEqual(stores, [self.store])\n\n stores = query_companies(self.emp_no_perm, self.company.pk)\n self.assertTrue(len(stores) == 0)\n\n stores = query_stores(self.emp_company, self.company.pk)\n self.assertItemsEqual(stores, [self.store])\n\n stores = query_stores(self.emp_store, self.company.pk)\n self.assertTrue(len(stores) == 0)\n\n\nclass TestUserFilter(TestCase):\n def setUp(self):\n self.region = Region(name='region')\n self.region.save()\n self.company = Company(code='1001', name='company', region=self.region)\n self.company.save()\n self.store = Store(code='10011001', name='store', company=self.company)\n self.store.save()\n\n self.emp_region = Employee(username='emp_region', organization=self.region)\n self.emp_region.save()\n self.emp_company = Employee(username='emp_company', organization=self.company)\n self.emp_company.save()\n self.emp_store = Employee(username='emp_store', organization=self.store)\n self.emp_store.save()\n self.empid_not_exists = 31415926\n\n package = 'com.tiantian.ttclock'\n appid = 10000\n\n d = date(year=2013, month=12, day=1)\n self.log1 = LogMeta(date=d, uid=self.emp_region.pk, appID=appid, appPkg=package)\n self.log1.save()\n self.log2 = LogMeta(date=d, uid=self.emp_company.pk, appID=appid, appPkg=package)\n self.log2.save()\n self.log3 = LogMeta(date=d, uid=self.emp_store.pk, appID=appid, appPkg=package)\n self.log3.save()\n self.logs = LogMeta.objects.all()\n\n def test_admin_filter(self):\n filter = AdminFilter(self.logs, None, self.company.pk, None, None)\n logs = filter.filter()\n self.assertItemsEqual([self.log2, self.log3], logs)\n\n filter = AdminFilter(self.logs, None, None, None, self.emp_store.pk)\n logs = filter.filter()\n self.assertItemsEqual([self.log3], logs)\n\n filter = AdminFilter(self.logs, None, None, None, None)\n logs = filter.filter()\n self.assertItemsEqual(logs, logs)\n\n def test_user_permitted_filter(self):\n filter = UserPermittedFilter(self.emp_company, self.logs, \n None, None, None, self.emp_company.pk)\n logs = filter.filter()\n self.assertItemsEqual([self.log2], logs)\n\n filter = UserPermittedFilter(self.emp_company, self.logs, \n None, None, None, self.emp_region.pk)\n logs = filter.filter()\n self.assertTrue(len(logs) == 0)\n\n filter = UserPermittedFilter(self.emp_company, self.logs,\n None, None, self.store.pk, None)\n logs = filter.filter()\n self.assertItemsEqual([self.log3], logs)\n\n filter = UserPermittedFilter(self.emp_company, self.logs, \n self.emp_region.pk, None, None, None)\n logs = filter.filter()\n self.assertTrue(len(logs) == 0)\n\n filter = UserPermittedFilter(self.emp_company, self.logs, \n None, None, None, None)\n logs = filter.filter()\n self.assertItemsEqual([self.log2, self.log3], logs)\n\n\n def test_user_unpermitted_filter(self):\n filter = UserUnpermittedFilter(self.logs, self.emp_store.pk)\n logs = filter.filter()\n self.assertItemsEqual([self.log3], logs)\n\n\nclass TestLevels(TestCase):\n\n def test_available_levels(self):\n self.assertItemsEqual(['region', 'company'], available_levels('region', 'company'))\n self.assertItemsEqual(['company', 'store', 'emp'], available_levels('company', 'emp'))\n\n\nclass TestTitlesForOrgStat(TestCase):\n \n def test_titles_for_org_stat(self):\n expected = [u'大区', u'公司编码', u'公司名称', u'机器台数', u'推广数', u'安装总数']\n self.assertItemsEqual(expected, titles_for_org_stat('region', 'company'))\n\n","sub_path":"statistics/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":10612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"182125798","text":"from flask import Blueprint, redirect, render_template, abort, request, url_for\nfrom jinja2 import TemplateNotFound\n\nfrom CTFAlgBlog.models.models import Post\n\nblog = Blueprint(\"blog\", __name__, template_folder=\"../templates\")\n\n\n@blog.route(\"/\", methods=[\"GET\"])\ndef blog_main_page():\n return render_template(\"blog_main_page.html\")\n\n\n@blog.route(\"/post\", methods=[\"GET\"])\ndef show_post():\n try:\n post_id = int(request.args.get('id'))\n needed_post = Post.query.filter_by(id=post_id).first()\n if needed_post is None:\n abort(404)\n return render_template(\"post_template\", post=needed_post)\n except ValueError as e:\n print(e)\n return abort(403)\n except TypeError:\n return redirect(url_for(\"blog.blog_main_page\"))\n except TemplateNotFound as e:\n print(e)\n abort(404)\n","sub_path":"CTFAlgBlog/blueprints/blog/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"202009710","text":"from django.shortcuts import render, get_object_or_404, get_list_or_404\nfrom django.http import HttpResponse\n\nfrom .models import Question,Answer\n\ndef index(request):\n\n\treturn render(request,'QNA/index.html',[])\n\ndef show_all(request):\n\n\tquestions = Question.objects.all()\n\tqa_dict = {}\n\tfor que in questions:\n\t\tans = que.answer_set.order_by('likes')[0]\n\n\t\tqa_dict[que] = ans\n\t\t#print(que.question_text+ans.answer_text)\n\t\t\n\tcontext = {\n\t\t'qa_dict': qa_dict, \n\t}\n\t\n\treturn render(request,'QNA/show_all.html',context)\n\n\ndef detail(request, search_text):\n\n\tquestion = get_object_or_404(Question, question_text=search_text)\n\t\n\tcontext = {\n\t\t'question': question,\n\t}\n\treturn render(request, 'QNA/detail.html', context)\n\n\ndef show_course(request, course):\n\t\n\tquestions = get_list_or_404(Question, course_name=course)\n\n\tprint(questions)\n\tcontext = {\n\t\t'questions': questions,\n\t\t'course': course,\n\t}\n\treturn render(request, 'QNA/show_course.html', context)","sub_path":"QNA/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"538041663","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport cv2\nimport threading\n\nclass WebcamVideoStream:\n stream = None\n out = None\n frame = None\n save = False\n\n def __init__(self, src, width, height):\n # initialize the video camera stream and read the first frame\n self.stream = cv2.VideoCapture(src)\n if not self.stream.isOpened():\n # camera failed\n raise IOError((\"Couldn't open video file or webcam.\"))\n self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, width)\n self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n (self.grabbed, self.frame) = self.stream.read()\n # initialize the variable used to indicate if the thread should\n # check camera stream shape\n real_width = int(self.stream.get(3))\n real_height = int(self.stream.get(4))\n print(\"Start video stream with shape: {},{}\".format(real_width, real_height))\n self.cols = real_width\n self.rows = real_height\n self.running = True\n\n def __del__(self):\n if self.stream.isOpened():\n self.stream.release()\n return\n\n def start(self):\n # start the thread to read frames from the video stream\n t = threading.Thread(target=self.update, args=())\n t.setDaemon(True)\n t.start()\n return self\n\n def update(self):\n try:\n # keep looping infinitely until the stream is closed\n while self.running:\n # otherwise, read the next frame from the stream\n (self.grabbed, self.frame) = self.stream.read()\n except:\n import traceback\n traceback.print_exc()\n self.running = False\n finally:\n # if the thread indicator variable is set, stop the thread\n self.stream.release()\n return\n\n def read(self):\n # return the frame most recently read\n return self.frame\n\n def stop(self):\n self.running = False\n","sub_path":"level5_demo_streaming/pc_server/lib/webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"158819630","text":"import os\r\nimport click\r\nimport pickle\r\n\r\nimport pandas as pd\r\nfrom sklearn.linear_model import LogisticRegression\r\n\r\n\r\n@click.command(\"train\")\r\n@click.option(\"--train-path\")\r\n@click.option(\"--model-path\")\r\ndef train_model(train_path: str, model_path: str) -> None:\r\n \"\"\"\r\n Train and save the model\r\n :param train_path:\r\n :param model_path:\r\n :return:\r\n \"\"\"\r\n model = LogisticRegression(random_state=13, max_iter=1000)\r\n dataframe = pd.read_csv(os.path.join(train_path, \"train.csv\"), index_col=0)\r\n y_train = dataframe.target.values\r\n X_train = dataframe.drop([\"target\"], axis=1).values\r\n model.fit(X_train, y_train)\r\n\r\n os.makedirs(model_path, exist_ok=True)\r\n with open(os.path.join(model_path, \"model.pkl\"), \"wb\") as handler:\r\n pickle.dump(model, handler)\r\n\r\nif __name__ == \"__main__\":\r\n train_model()\r\n\r\n","sub_path":"airflow_ml_dags/images/airflow-train/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"61119567","text":"\"\"\"\nQuestion 17\nQuestion:\nWrite a program that computes the net amount of a bank account based a transaction log\nfrom console input. The transaction log format is shown as following:\n\nD 100\nW 200\n\nD means deposit while W means withdrawal.\n\nSuppose the following input is supplied to the program:\n\nD 300\nD 300\nW 200\nD 100\n\nThen, the output should be:\n\n500\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\n\"\"\"\n\n'''Solution by: leonedott'''\nlst = []\nwhile True:\n x = input()\n if len(x) == 0:\n break\n lst.append(x)\n\nbalance = 0\nfor item in lst:\n if 'D' in item:\n balance += int(item.strip('D '))\n if 'W' in item:\n balance -= int(item.strip('W '))\nprint(balance)\n\n\n\n\n\n\n","sub_path":"Python-Files/Day-5/Question-17-alternative-solution-1.py","file_name":"Question-17-alternative-solution-1.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"495165178","text":"import pymongo\nfrom collections import Counter\nimport re\nimport csv\n\n# Connection to MongoDB\nmyclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\nmydb = myclient[\"indonesia\"]\nmycol = mydb[\"tweetsanalyticsfix\"]\n# mysave = mydb[\"tweetsJul-Aug\"]\n\nemotion = []\ntest = []\n\nif __name__ == \"__main__\":\n\n # Looping for Selecting Coloumn we Needed\n print(\"Start\")\n test3 = \"test\"\n # f = open(\"tesct.csv\", \"w\")\n for tweet in mycol.find({\"text\" : { \"$regex\": 'psbb.*' },\"text_emotion\": \"Tidak Bahagia\", \"place_object.country_code\": \"ID\", \"locations\" : \"Jawa Barat\"}):\n # for tweet in mycol.find(\n # {\"created_at\": {\"$regex\": 'Sep 02.*'}, \"text_emotion\": \"Tidak Bahagia\", \"place_object.country_code\": \"ID\", \"language\":\"in\", \"text\": {\"$regex\": 'duka.*'}}):\n #\n # text = tweet[\"text\"]\n # print(text)\n\n tweets = {\n \"id\": tweet[\"id\"],\n \"created_at\": tweet[\"created_at\"],\n \"text\": tweet[\"text\"]\n }\n\n label = tweet[\"text_emotion\"]\n emotion.append(label)\n print(tweets)\n # test2 = test3\n # test.append(test2)\n\n countEmotion = Counter(emotion)\n print(\"Jumlah Emosi :\", countEmotion)\n print(\"End\")\n\n","sub_path":"SelectData/selectDataMaps.py","file_name":"selectDataMaps.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"451599127","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 30 16:11:01 2017\n\n@author: timothee\n\"\"\"\nfrom torchvision import transforms as T\nfrom PIL import Image\nimport numpy as np\nimport torch\n\n\n#usual cuda check\nuse_cuda = torch.cuda.is_available()\nFloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor\n\n\n#T.Compose creates a succession of torch vision transforms. All of them can take either an image or numpy array in. T.ToTensor will ouput a tensor \nctrCrop = T.Compose([T.CenterCrop(128),T.Scale(120),T.ToTensor()]) #ctrCrop wil involve taking a square of 128 in the middle followed \n#by a scaling to 64X64\noverallCrop = T.Compose([T.CenterCrop(240),T.Scale(120),T.ToTensor()]) #similar,but takes a square overall crop.\n# 240 is the height of the screen, smaller dimension than the width\n\n\n\n\ndef grayscale(original):#Tested, works\n #Check if input is already numpy\n if type(original) is np.ndarray :\n \n new = adaptShape(original)#necessary for the dot operation to work, the RGB dim must be in first position\n new = np.dot(new[...,:3], [0.299, 0.587, 0.114])\n new = np.ascontiguousarray(new, dtype = np.int8)\n return new#Using previous technique from Catch\n \n else:#make it numpy and convert back to image\n \n new = np.asarray(original)\n new = adaptShape(new)\n new = np.dot(new[...,:3], [0.299, 0.587, 0.114])\n new = np.ascontiguousarray(new, dtype = np.int8)\n \n return Image.fromarray(new)\n\n\ndef doCenter(original):#Tested,works\n if type(original) is np.ndarray :\n \n new = Image.fromarray(adaptShape(original))\n \n \n return ctrCrop(grayscale(new)).type(FloatTensor)/255\n\ndef doOverall(original):#Tested, works\n\n if type(original) is np.ndarray :\n\n new = Image.fromarray(adaptShape(original))\n \n return overallCrop(grayscale(new)).type(FloatTensor) /255 \n \n \n\n\n \ndef show(im):#Only for troubleshooting\n \n if type(im) is np.ndarray :\n \n Image.fromarray(im).show()\n \n else:\n im.show()\n \ndef adaptShape(original):#necessary to put the RGB dimension in first position like in Catch\n \n return np.moveaxis(original, 0, -1)#shift all the axis -by -1 > the axis 0 will find itself in position -1\n\n","sub_path":"graphics.py","file_name":"graphics.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"349609824","text":"# Q6 Implementing Neural network using Max likelihood (cross entropy) loss using softmax\n\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom random import seed\n\n\n\n# Function importing Dataset\ndef importdata():\n global train_data\n train_data = pd.read_csv(\n 'train_wine.csv', sep =',', header=None)\n print(train_data.shape)\n test_data = pd.read_csv(\n 'test_wine.csv', sep =',', header=None)\n print(test_data.shape)\n return train_data.values, test_data.values\n\n\n# Function to split the dataset\ndef splitdataset(data):\n # Seperating the target variable\n x = data[:, 1:data.shape[1]]\n y = data[:, 0]\n # print(np.shape(x), np.shape(y))\n return x, y\n\ndef feature_normalization(x):\n mu = np.mean(x,axis=0)\n sigma = np.std(x,axis=0)\n return mu, sigma\n\ndef normalization(x,mu,sigma):\n x = np.subtract(x, mu)\n x = np.divide(x, sigma)\n return x\n\ndef dense_to_one_hot(labels_dense, num_classes=3):\n labels_dense = np.subtract(labels_dense,1)\n labels_one_hot = tf.one_hot(labels_dense,depth=3)\n return labels_one_hot.eval()\n\n\n\ndef evaluate_model(X_train, X_test, y_train, y_test, epochs, batch_size):\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n # Initialize the variables (i.e. assign their default value)\n sess.run(init)\n for epoch in range(epochs):\n avg_cost = 0.0\n total_batch = int(len(X_train) / batch_size)\n x_batches = np.array_split(X_train, total_batch)\n y_batches = np.array_split(y_train, total_batch)\n for i in range(total_batch):\n batch_x, batch_y = x_batches[i], y_batches[i]\n batch_y = dense_to_one_hot(y_batches[i])\n _, c = sess.run([optimizer, loss], feed_dict={ input_layer: batch_x, real_output: batch_y})\n avg_cost += c / total_batch\n if epoch % 100 == 0:\n print(\"Epoch:\", '%04d' % (epoch + 1), \"loss=\",\"{:.9f}\".format(avg_cost))\n\n print(\"\\nTraining complete!\")\n\n # #prediction on test set\n predict = tf.argmax(output_layer, 1)\n pred = predict.eval({input_layer: X_test.reshape(-1, num_input)})\n print(pred)\n correct_prediction = np.add(pred,1)\n print(correct_prediction)\n\n pred_temp = tf.equal(tf.argmax(output_layer, 1), tf.argmax(real_output, 1))\n accuracy = tf.reduce_mean(tf.cast(pred_temp, \"float\"))\n print(\"Test Accuracy:\", accuracy.eval({input_layer: X_test.reshape(-1, num_input), real_output: dense_to_one_hot(y_test)}))\n\n\n\nif __name__ == '__main__':\n # To stop potential randomness\n seed = 128\n rng = np.random.RandomState(seed)\n\n #get dataset\n trainset, testset = importdata()\n\n #split features, label\n X_train, y_train = splitdataset(trainset)\n X_test, y_test = splitdataset(testset)\n\n #feature normalization\n mu, sigma = feature_normalization(X_train)\n X_train = normalization(X_train, mu, sigma)\n X_test = normalization(X_test, mu, sigma)\n\n # Network Parameters\n num_input = X_train.shape[1] #features 12\n num_hidden = 5\n num_output = 3\n\n # define placeholders\n input_layer = tf.placeholder(tf.float32, [None, num_input])\n real_output = tf.placeholder(tf.float32, [None, num_output])\n\n # Training Parameters\n learning_rate = 0.01\n epochs = 1000\n batch_size = 50\n\n # define weights and biases of the neural network\n hidden_layer_weights = tf.Variable(tf.random_normal([num_input, num_hidden], seed = seed))\n hidden_layer_biases = tf.Variable(tf.random_normal([num_hidden],seed = seed))\n output_layer_weights = tf.Variable(tf.random_normal([num_hidden, num_output],seed = seed))\n output_layer_biases = tf.Variable(tf.random_normal([num_output],seed = seed))\n\n\n # create our neural networks computational graph\n hidden_layer = tf.add(tf.matmul(input_layer, hidden_layer_weights), hidden_layer_biases)\n hidden_layer = tf.nn.relu(hidden_layer)\n output_layer = tf.matmul(hidden_layer, output_layer_weights) + output_layer_biases\n\n\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=output_layer,labels=real_output)) # used in maximum likelihood\n #our backpropogation algorithm | ADAM is variant of Gradient Descent algorithm\n optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(loss)\n\n # #training\n evaluate_model(X_train, X_test, y_train, y_test, epochs, batch_size)","sub_path":"MLE_tf.py","file_name":"MLE_tf.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"577982337","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# author: wangzq \n\nimport requests\nfrom flask import (\n Blueprint,\n render_template,\n request,\n url_for,\n session,\n redirect\n)\n\nbp = Blueprint('index', __name__)\n\n\n@bp.route('/')\ndef index():\n if session.get('rtx_id') == None:\n return redirect(url_for('index.login'))\n return render_template('index.html', pageTitle=u'首页')\n\n\n@bp.route('/healthcheck.html')\ndef healthcheckff():\n \"\"\" 添加域名,需要加健康检查\n \"\"\"\n return render_template('healthcheck.html')\n\n\n# QSSO LOGIN\n@bp.route('/login/', methods=['GET', 'POST'])\ndef login():\n # try:\n # if (request.method == 'POST'):\n # token = request.form.get('token')\n # api_response = requests.get(\n # 'http://qsso.corp.qunar.com/api/verifytoken.php?token=%s'\n # % token\n # ).json()\n # if api_response['ret'] == True:\n # session.permanent = True\n # session['rtx_id'] = api_response['userId']\n # if request.args.get('ret'):\n # return redirect(request.args.get('ret'))\n # else:\n # return redirect(url_for('index.index'))\n # return render_template('login.html', pageTitle=\"LOGIN\")\n # except:\n # # 显示一个错误页面\n # return render_template('login.html', pageTitle=\"LOGIN\")\n return render_template('index.html', pageTitle=\"LOGIN\")\n\n\n# LOGOUT\n@bp.route(\"/logout/\")\ndef logout():\n if(session.get('rtx_id')):\n session.clear()\n if request.args.get('ret') != None:\n return redirect(request.args.get('ret'))\n return redirect(url_for('index.login'))\n","sub_path":"itdblib/frontend/views/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"585133612","text":"import os\nimport sys\nimport argparse\n\nfrom numpy.lib.type_check import imag\nimport utils\n\n\ndef main(args):\n\n classes = args.classes\n print('classes: ' + str(classes))\n img_count = 0\n for sub in args.sub_dir:\n \n path = os.path.join(args.root_dir, sub)\n print(path)\n # remove existing txt files for annotation\n utils.remove_annot_files(path)\n \n \n \n \n \n walk_path = os.path.join(path, 'Annotations')\n \n for _, _, f in os.walk(walk_path):\n for file in f:\n if not file.endswith(('.json','.xml')):\n continue\n if '.json' in file:\n filename = file.replace('.json', '')\n if args.dataset_name == 'coco': \n utils.convert_annotation(path, filename, classes)\n if args.dataset_name == 'taco':\n \n print(file)\n utils.convert_annotation_taco(path, filename, classes)\n\n if '.xml' in file:\n filename = file.replace('.xml', '')\n # print(file)\n utils.convert_annotation_x(path, filename, classes)\n img_count += 1\n print('image count: ', img_count)\n\ndef parse_arguments(argv):\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--root_dir', type=str,\n help='root of VOC development kit', default='/home/husan/projects/domestic_waste/yolov5-train/datasets/')\n parser.add_argument('--sub_dir', action='append', type=str, help='root of VOC development kit')\n parser.add_argument('--dataset_name', default='coco', type=str, help='dataset name, for example: coco, taco')\n parser.add_argument('--classes', action='append', type=str,\n help='list of classes for subset', default =\n [\n # 'bus', 'moto',\n # '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', 'A', 'B', 'G', 'M','N'\n '01', '02', '03', '04', '05', '06', '07'\n # 'rnplate',\n # 'rnplate00_01',\n # 'rnplate00_02',\n # 'rnplate00_03',\n # 'rnplate00_04',\n # 'rnplate00_05',\n # 'rnplate00_06',\n # 'rnplate00_07',\n # 'rnplate00_08',\n # 'rnplate00_09',\n # 'rnplate00_10',\n # 'aeroplane',\n # 'bicycle',\n # 'bird',\n # 'boat',\n # 'bottle',\n # 'bus',\n # 'car',\n # 'cat',\n # 'chair',\n # 'cow',\n # 'diningtable',\n # 'dog',\n # 'horse',\n # 'motorbike',\n # 'person',\n # 'pottedplant',\n # 'sheep',\n # 'sofa',\n # 'train',\n # 'tvmonitor'\n ])\n return parser.parse_args(argv)\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n","sub_path":"voc_json_or_xml_to_txt.py","file_name":"voc_json_or_xml_to_txt.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"356815372","text":"version = '1'\nbatch_size = 64 # batch size\nvocab_threshold = 5 # minimum word count threshold\nvocab_from_file = True # if True, load existing vocab file\nembed_size = 512 # dimensionality of image and word embeddings\nhidden_size = 512 # number of features in hidden state of the RNN decoder\nnum_epochs = 1 # number of training epochs\nsave_every = 1 # determines frequency of saving model weights\nprint_every = 100 # determines window for printing average loss\nlog_file = f'training_log_v{version}.txt' # name of file with saved training loss and perplexity\n\n# Optimizer\noptimizer_params = dict() #dict(betas=(0.9, 0.99), weight_decay=1e-2, lr=3e-4)\nuseScheduler = False\n","sub_path":"hyperparameters.py","file_name":"hyperparameters.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"490709424","text":"# import the necessary libraries\nimport cv2\nimport numpy\nimport os\nimport time\n\n# declare the paths of the test dataset and models\nimages_path = '../test_images/'\nprototxt_path = 'models/deploy.prototxt.txt'\nmodel_path = 'models/res10_300x300_ssd_iter_140000.caffemodel'\n\n# load the model\nmodel = cv2.dnn.readNetFromCaffe(prototxt_path, model_path)\n\nimage_files = sorted(os.listdir(images_path)) # get the test images name\ntimings = [] # initialise a list to store time complexities of the model on each and every image\n\n# initialise a loop to process each and every image once\nfor image_name in image_files:\n image = cv2.imread(os.path.join(images_path, image_name)) # read the image\n height, width = image.shape[:2] # store the height and width of the image\n initial_time = time.time() # record time before detecting faces\n\n # detect the faces in the image using the face detector model\n blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (500, 500), (104.0, 177.0, 123.0))\n model.setInput(blob)\n faces = model.forward()\n\n final_time = time.time() # record time after detecting faces\n timings.append(final_time - initial_time) # store the time complexity of the image\n\n # initialise a nested loop to process all the detected faces individually\n for i in range(0, faces.shape[2]):\n # process the each face individually, check for the confidence value,\n # retrieve the coordinates of the bounding boxes and draw them\n confidence = faces[0, 0, i, 2]\n if confidence > 0.6:\n box = faces[0, 0, i, 3:7] * numpy.array([width, height, width, height])\n (x1, y1, x2, y2) = box.astype(\"int\")\n cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 3)\n\n cv2.imshow('DNN face detector: {}'.format(image_name), image) # display the resultant image\n cv2.imwrite('image_results/{}_result.jpg'.format(image_name.split('.')[0]), image) # save the resultant image\n cv2.waitKey(0) # wait for the user to press any key\n cv2.destroyWindow('DNN face detector: {}'.format(image_name)) # destroy the current image window\n\ncv2.destroyAllWindows() # destroy all the image windows\n\nprint(timings) # print the time complexities of the images\n","sub_path":"DNN_Face_Detector/DNN_Face_Detector_Code.py","file_name":"DNN_Face_Detector_Code.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"537514253","text":"#! /usr/bin/env python\nimport requests\n\ndef main():\n version = requests.get('https://www.howsmyssl.com/a/check').json()['tls_version']\n if version < \"TLS 1.2\":\n url = \"http://pyfound.blogspot.com/2017/01/time-to-upgrade-your-python-tls-v12.html\"\n print(f\"Error: The Stripe API requires TLS version 1.2, you are running {version}\"\n f\"\\n\\nPlease see {url} for instructions to update your environment.\")\n exit(1)\n print(\"TLS 1.2 supported, no action required.\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"verify_tls.py","file_name":"verify_tls.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"409760703","text":"from django.shortcuts import render, redirect\nfrom forms import UploadFileForm\nfrom models import Vendas\nfrom django.db.models import Sum\n\ndef file_upload(request):\n\t''' Cuida do upload do arquivo para que o mesmo\n\tseja posteriormente carregado na base de dados '''\n\n\tif request.method == 'POST':\n\t\tform = UploadFileForm(request.POST, request.FILES)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\thandle_uploaded_file(request.FILES['file'])\n\t\t\treturn redirect('/success/')\n\telse:\n\t\tform = UploadFileForm()\n\treturn render(request, \"file_upload/upload.html\", {'form': form})\n\n\ndef handle_uploaded_file(mfile):\n\t''' Realiza a carga do arquivo na base de dados. '''\n\n\tfilename = mfile.name\n\tresult=[record.split('\\t') for record in file(\"desafio_myfreecomm/media/uploads/\" + filename, 'r').readlines()]\n\tdata = result[1:]\n\n\tfor column in data:\n\t\trow = Vendas(purchaser_name = column[0], item_description = column[1], item_price = column[2], purchase_count = column[3], merchant_address = column[4], merchant_name = column[5])\n\t\trow.save()\n\n\ndef success(request):\n\t''' Pagina de retorno para quando o arquivo eh carregado com sucesso! '''\n\n\tgp = Vendas.objects.extra(select = {'total': 'SUM(item_price * purchase_count)'},)\n\treturn render(request, \"file_upload/success.html\", locals())","sub_path":"desafio_myfreecomm/file_upload/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"479511108","text":"def binarysearch(arr, n):\n low = 0\n high = len(arr) - 1\n mid = 0\n while low <= high:\n mid = (high + low) // 2\n if arr[mid] < n:\n low = mid + 1\n elif arr[mid] > n:\n high = mid - 1\n else:\n return mid\n return \"doesnt exist!\"\n\n\nif __name__ == \"__main__\":\n print(\n binarysearch(\n input(\"enter the list: \").split(\",\"), input(\"you want to search for: \")\n )\n )\n","sub_path":"Python-Programs/binarysearch.py","file_name":"binarysearch.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"446905191","text":"from keras import backend as K\nimport tensorflow as tf\n\n\ndef normalized_class_frequencies(x):\n \"\"\"\n x should be a one-hot tensor\n \"\"\"\n class_frequencies = tf.reduce_sum(x, list(range(x.shape.ndims - 1)))\n denominator = tf.cast(tf.reduce_prod(tf.shape(x)[:-1]), x.dtype)\n return class_frequencies / denominator\n\n\ndef balanced_categorical_crossentropy(y_true, y_pred):\n \"\"\"\n Calculates a weighted version of categorical_crossentropy, where the\n individual pixel losses are weighted according to 1-normalized_frequency.\n This has the effect of balancing classes. Importantly, the weights are calculated\n batchwise.\n\n Inspired by:\n https://gist.github.com/wassname/ce364fddfc8a025bfab4348cf5de852d\n \"\"\"\n\n weights = normalized_class_frequencies(y_true)\n y_pred /= K.sum(y_pred, axis=-1, keepdims=True)\n y_pred = K.clip(y_pred, K.epsilon(), 1 - K.epsilon())\n loss = y_true * K.log(y_pred) * weights\n return -K.sum(loss, -1)\n","sub_path":"src/dvpy/tf/balanced_categorical_crossentropy.py","file_name":"balanced_categorical_crossentropy.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"88655655","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"Ntupler\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\n# NOTE: the pick the right global tag!\n# for Spring15 25ns MC: global tag is 'auto:run2_mc'\n# for Run 2 data: global tag is 'auto:run2_data'\n# as a rule, find the \"auto\" global tag in $CMSSW_RELEASE_BASE/src/Configuration/AlCa/python/autoCond.py\n# This auto global tag will look up the \"proper\" global tag\n# that is typically found in the DAS under the Configs for given dataset\n# (although it can be \"overridden\" by requirements of a given release)\nfrom Configuration.AlCa.GlobalTag import GlobalTag\n#process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:phase1_2017_realistic', '')\nprocess.GlobalTag = GlobalTag(process.GlobalTag, '94X_mc2017_realistic_v12', '')\n\n#\n# Define input data to read\n#\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )\n\ninputFilesAOD = cms.untracked.vstring(\n # AOD test files from /DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/RunIISummer17MiniAOD-92X_upgrade2017_realistic_v10_ext1-v1/AODSIM\n # ... files are missing ...\n ) \n\ninputFilesMiniAOD = cms.untracked.vstring(\n # MiniAOD test files from /DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/RunIISummer17MiniAOD-92X_upgrade2017_realistic_v10_ext1-v1/MINIAODSIM\n '/store/mc/RunIIFall17MiniAOD/DYJetsToLL_M-50_TuneCP5_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/94X_mc2017_realistic_v10-v1/00000/005DC030-D3F4-E711-889A-02163E01A62D.root',\n )\n\n#\n# You can list here either AOD or miniAOD files, but not both types mixed\n#\nuseAOD = True\nif useAOD == True :\n inputFiles = inputFilesAOD\n outputFile = \"electron_ntuple.root\"\n pileupProductName = \"addPileupInfo\"\n print(\"AOD input files are used\")\nelse :\n inputFiles = inputFilesMiniAOD\n outputFile = \"electron_ntuple_mini.root\"\n pileupProductName = \"slimmedAddPileupInfo\"\n print(\"MiniAOD input files are used\")\nprocess.source = cms.Source (\"PoolSource\", fileNames = inputFiles ) \n\n#\n# Configure the ntupler module\n#\n\nprocess.ntupler = cms.EDAnalyzer('SimpleElectronNtupler',\n # The module automatically detects AOD vs miniAOD, so we configure both\n #\n # Common to all formats objects\n #\n pileup = cms.InputTag( pileupProductName ),\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\"),\n beamSpot = cms.InputTag('offlineBeamSpot'),\n genEventInfoProduct = cms.InputTag('generator'),\n #\n # Objects specific to AOD format\n #\n electrons = cms.InputTag(\"gedGsfElectrons\"),\n genParticles = cms.InputTag(\"genParticles\"),\n vertices = cms.InputTag(\"offlinePrimaryVertices\"),\n conversions = cms.InputTag('allConversions'),\n #\n # Objects specific to MiniAOD format\n #\n electronsMiniAOD = cms.InputTag(\"slimmedElectrons\"),\n genParticlesMiniAOD = cms.InputTag(\"prunedGenParticles\"),\n verticesMiniAOD = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n conversionsMiniAOD = cms.InputTag('reducedEgamma:reducedConversions'),\n # Effective areas for computing PU correction for isolations\n effAreasConfigFile = cms.FileInPath(\"EgammaWork/ElectronNtupler/data/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_94X.txt\")\n )\n\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string( outputFile )\n )\n\n\nprocess.p = cms.Path(process.ntupler)\n","sub_path":"ElectronNtupler/test/runElectrons_AOD.py","file_name":"runElectrons_AOD.py","file_ext":"py","file_size_in_byte":4278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"579597888","text":"from unittest import TestCase\n\nimport jsonpatch\nfrom core.utils import format_patch\n\n\nclass FormatPatchTestCase(TestCase):\n def setUp(self):\n self.initial = {\"foo\": 1, \"bar\": \"bar\", \"list\": [\"baz\", \"baz\"]}\n\n def test_format_simple_change(self):\n\n b = self.initial.copy()\n b[\"foo\"] = 2\n # b['bar'] = 'rab'\n # b['list'] = reversed(b['list'])\n\n patch = jsonpatch.JsonPatch.from_diff(self.initial, b)\n formatted = format_patch(patch)\n self.assertIsInstance(formatted, basestring)\n self.assertEqual(formatted, \"Changed foo to 2\")\n","sub_path":"cla_backend/apps/call_centre/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"142470794","text":"from rest_framework import routers\nfrom rest_registration.api.urls import login, logout, profile\nfrom django.urls import path, include\nfrom .views import sync_sitec, StudentSitecDataViewSet\n\nrouter = routers.DefaultRouter()\nrouter.register('students-sitec-data', StudentSitecDataViewSet)\n\napp_name = 'api-v1'\nurlpatterns = router.urls\n\nurlpatterns += [\n path('accounts/login/', login, name='login'),\n path('accounts/logout/', logout, name='logout'),\n path('accounts/profile/', profile, name='profile'),\n path('sync-sitec/', sync_sitec, name='sync-sitec')\n]","sub_path":"sitec/api/v1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"448400438","text":"# 继承 封装 多态\n\nfrom mClass import People\n\n\nclass Student(People):\n sum = 0\n\n def __init__(self, name, age) -> None:\n # super().__init__(name)\n super(Student, self).__init__(name)\n self.age = age\n self.__score = 0\n self.__class__.sum = 1\n\n def do_homework(self):\n super().eat(\"Student\", self.name, \"大米\")\n print(\"do_homework\")\n\n\nstudent = Student('hjn', 30)\nstudent.do_homework()\nstudent.eat(\"Student\", \"lsm\", \"屎球球\")\nprint(student.name)\n","sub_path":"开发相关/Python/Basic/basic/16.class/mClass1.py","file_name":"mClass1.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"565034826","text":"\nfrom __future__ import print_function\nimport sage.question as question\ndef test_option_question_with_default_style():\n q = question.OptionQuestion(\"test\", [\"t1\", \"t2\", \"t3\"])\n rpr = \"test\\n\\n[1] t1\\n[2] t2\\n[3] t3\"\n print(rpr)\n repr(q)\n assert rpr == q.__repr__()\n\n\n\n# q = BinaryQuestion(\"Tu eh ladrao?\", default_option=True)\n# q.ask()\n#\n#\n# print(q.answer)\n","sub_path":"tests/question_test.py","file_name":"question_test.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"295059443","text":"import control as co\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG1 = co.tf([2,5],[1,2,3]) # 2s + 5 / s^2 + 2s + 3 --- Provided only the coeficients\n\nG2 = 5*co.tf(np.poly([-2,-5]), np.poly([-4,-5,-9])) # Provided the 'zeros' and the 'poles' of the function\n\nt = np.linspace(0, 10, 1000)\nt1, y1 = co.impulse_response(G1, t)\n\nplt.plot(t1,y1)\nplt.xlabel('time (s)')\nplt.ylabel('amplitude')\nplt.grid()\n","sub_path":"examples/ImpulseResponse.py","file_name":"ImpulseResponse.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"356872043","text":"from tkinter import *\r\nfrom solver import SudokuSolver\r\nimport time\r\nimport threading as th\r\n\r\ndef fill_sudoku():\r\n\r\n\tdef fill_sudoku_th():\r\n\t\tsudoku = [[] for _ in range(9)]\r\n\r\n\t\tfor k in range(81):\r\n\t\t\tfield = fields[k].get() \r\n\t\t\tif field.isdigit() and (0 < int(field) <= 9):\r\n\t\t\t\tsudoku[k//9].append(int(field))\r\n\t\t\telif not field:\r\n\t\t\t\tsudoku[k//9].append(0)\r\n\t\t\telse:\r\n\t\t\t\tlbl.config(text='Wrong format!',fg='red')\r\n\t\t\t\ttime.sleep(1)\r\n\t\t\t\tlbl.config(text='Enter valid sudoku',fg='black')\r\n\t\t\t\treturn\r\n\r\n\t\tsolver = SudokuSolver(sudoku)\r\n\t\tsolver.solve_sudoku()\r\n\t\tif not solver.sudoku_is_correct:\r\n\t\t\tlbl.config(text='Sudoku is incorrect!',fg='red')\r\n\t\t\ttime.sleep(1)\r\n\t\t\tlbl.config(text='Enter valid sudoku',fg='black')\r\n\r\n\t\tsolved_sudoku = solver.finished_sudoku\r\n\t\ttry:\r\n\t\t\tfor k in range(81):\r\n\t\t\t\tfields[k].delete(0,END)\r\n\t\t\t\tfields[k].insert(0,str(solved_sudoku[k//9][k%9]))\r\n\t\texcept: pass\r\n\r\n\tthread1 = th.Thread(target=fill_sudoku_th)\r\n\tthread1.start()\r\n\r\n\r\ndef clear():\r\n\tfor field in fields:\r\n\t\tfield.delete(0,END)\r\n\r\ndef get_from_txt():\r\n\r\n\tdef get_from_txt_th():\r\n\t\tfor field in fields:\r\n\t\t\tfield.delete(0,END)\r\n\t\tsudoku = []\r\n\t\ttry:\r\n\t\t\twith open(filename_field.get()) as file:\r\n\t\t\t\tfor line in file:\r\n\t\t\t\t\ta = [int(x) for x in line.rsplit()]\r\n\t\t\t\t\tsudoku.append(a)\r\n\t\texcept:\r\n\t\t\tlbl.config(text='No such file here!',fg='red')\r\n\t\t\ttime.sleep(1)\r\n\t\t\tlbl.config(text='Enter valid sudoku',fg='black')\r\n\t\t\treturn\r\n\t\tfor k in range(81):\r\n\t\t\tnum = sudoku[k//9][k%9]\r\n\t\t\tif num != 0:\r\n\t\t\t\tfields[k].insert(0,str(num))\r\n\r\n\tthread2 = th.Thread(target=get_from_txt_th)\r\n\tthread2.start()\r\n\r\n\r\n\r\n\t\r\n\r\n\r\nwindow = Tk()\r\nwindow.geometry('395x670')\r\nwindow.resizable(width=False,height=False)\r\nwindow.title('SudokuSolver')\r\nwindow.config(bg='#70d9ff')\r\n\r\nfields = [Entry(window, width=2, font='Times 30', justify=CENTER) for k in range(81)]\r\nfor k in range(81):\r\n\tfields[k].grid(column=(k%9),row=(k//9))\t\r\n\r\nlbl = Label(window, text='Enter valid sudoku', font='Times 18',bg='#70d9ff')\r\nlbl.grid(column=2, row=11, columnspan=5, pady=20)\r\n\r\nsolve_button = Button(window, text=\"Solve!\", font='Times 18', width=8, command=fill_sudoku, bg='#abe9ff', activebackground='#86c4db')\r\nsolve_button.grid(column=1, row=12, columnspan=3, pady=10)\r\n\r\nclear_button = Button(window, text=\"Clear\", font='Times 18',width=8,command=clear, bg='#abe9ff', activebackground='#86c4db')\r\nclear_button.grid(column=5, row=12, columnspan=3, pady=10)\r\n\r\nget_button = Button(window,text=\"From .txt\", font='Times 18',width=8,command=get_from_txt, bg='#abe9ff', activebackground='#86c4db')\r\nget_button.grid(column=0, row=13, columnspan=5, pady=10)\r\n\r\nfilename_field = Entry(window,font='Times 16',width=12)\r\nfilename_field.grid(column=4 ,row=13, columnspan=5,padx=40)\r\nfilename_field.insert(0,'Enter filename')\r\n\r\nwindow.mainloop()","sub_path":"front.py","file_name":"front.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"373845212","text":"# coding=utf-8\r\n\r\nimport datetime\r\n\r\nimport gl\r\n\r\nfrom flask import redirect, render_template, session, request\r\n# from sqlalchemy import text\r\n\r\nfrom admin import app\r\n\r\n\r\n@app.route('/article/append', methods=['GET', 'POST'])\r\ndef article_append():\r\n if 'user' not in session:\r\n return redirect('/login')\r\n if request.method == 'POST':\r\n sql = '''\r\ninsert into news\r\n (news_title, news_type,\r\n news_content,\r\n news_time, news_source, news_level, news_desc)\r\nvalues\r\n (\\'%(news_title)s\\', %(news_type)s,\r\n \\'%(news_content)s\\',\r\n \\'%(news_time)s\\', \\'%(news_source)s\\', %(news_level)s, \\'%(news_desc)s\\')\r\n '''\r\n param = {\r\n 'news_title': request.form['news_title'],\r\n 'news_type': request.form['news_type'],\r\n 'news_content': request.form['news_content'],\r\n 'news_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\r\n 'news_source': request.form['news_source'],\r\n 'news_level': request.form['news_level'],\r\n 'news_desc': request.form['news_desc']\r\n }\r\n sql = sql % param\r\n cnx, cursor = gl.db()\r\n cursor.execute(sql)\r\n cursor.commit()\r\n gl.close(cursor, cnx)\r\n return redirect('/article/append')\r\n\r\n sql = '''\r\nselect *\r\nfrom news_type\r\n '''\r\n cnx, cursor = gl.db()\r\n data = cursor.execute(sql).fetchall()\r\n gl.close(cursor, cnx)\r\n for d in data:\r\n d.news_type_value = d.news_type_value.decode('gbk')\r\n return render_template(\r\n 'article/append.html',\r\n User=session['user'],\r\n types=data)\r\n\r\n\r\n@app.route('/article/list')\r\ndef article_list():\r\n return redirect('/article/list/1')\r\n\r\n\r\n@app.route('/article/list/')\r\ndef article_list_1(page):\r\n if 'user' not in session:\r\n return redirect('/login')\r\n\r\n offset = 0\r\n if int(page) >= 1:\r\n offset = app.config['ENTRY_PER_PAGE'] * (int(page) - 1)\r\n sql = gl.SQL_ARTICLE_LIST % (\r\n app.config['ENTRY_PER_PAGE'],\r\n offset)\r\n# sql = '''\r\n# select top 2 *\r\n# from news\r\n# left join news_type\r\n# on news.news_type=news_type.news_type_id\r\n# where news.news_id not in (\r\n# select top 2 news_id\r\n# from news\r\n# )\r\n# order by news.news_time desc\r\n# '''\r\n # print(sql)\r\n cnx, cursor = gl.db()\r\n data = cursor.execute(sql).fetchall()\r\n gl.close(cursor, cnx)\r\n for d in data:\r\n d.news_title = d.news_title.decode('gbk')\r\n d.news_type_value = d.news_type_value.decode('gbk')\r\n return render_template(\r\n 'article/list.html',\r\n User = session['user'],\r\n article = data,\r\n page = int(page))\r\n\r\n\r\n@app.route('/article/', methods=['GET', 'POST'])\r\ndef article(news_id):\r\n if 'user' not in session:\r\n return redirect('/login')\r\n\r\n if request.method == 'POST':\r\n sql = '''\r\nupdate news\r\nset news_title=\\'%(news_title)s\\', news_type=%(news_type)s,\r\n news_content=\\'%(news_content)s\\', news_source=\\'%(news_source)s\\',\r\n news_level=%(news_level)s, news_desc=\\'%(news_desc)s\\'\r\nwhere news_id=%(news_id)s\r\n '''\r\n param = {\r\n 'news_title': request.form['news_title'],\r\n 'news_type': request.form['news_type'],\r\n 'news_content': request.form['news_content'],\r\n 'news_source': request.form['news_source'],\r\n 'news_level': request.form['news_level'],\r\n 'news_desc': request.form['news_desc'],\r\n 'news_id': news_id\r\n }\r\n sql = sql % param\r\n # print(sql)\r\n cnx, cursor = gl.db()\r\n cursor.execute(sql)\r\n cursor.commit()\r\n gl.close(cursor, cnx)\r\n return redirect('/article/%s' % news_id)\r\n\r\n sql = '''\r\nselect *\r\nfrom news\r\nwhere news_id=%(id)s\r\n '''\r\n param = {'id': news_id}\r\n sql = sql % param\r\n cnx, cursor = gl.db()\r\n data = cursor.execute(sql).fetchone()\r\n sql = '''\r\nselect *\r\nfrom news_type\r\n '''\r\n news_type = cursor.execute(sql).fetchall()\r\n gl.close(cursor, cnx)\r\n for n in news_type:\r\n n.news_type_value = n.news_type_value.decode('gbk')\r\n data.news_title = data.news_title.decode('gbk')\r\n data.news_content = data.news_content.decode('gbk')\r\n data.news_source = data.news_source.decode('gbk')\r\n data.news_desc = data.news_desc.decode('gbk')\r\n\r\n return render_template(\r\n 'article/article.html',\r\n User = session['user'],\r\n news_type = news_type,\r\n article = data)\r\n\r\n\r\n@app.route('/article/filter', methods=['POST'])\r\ndef article_filter():\r\n if 'user' not in session:\r\n return redirect('/login')\r\n\r\n sql = '''\r\nselect *\r\nfrom news\r\nleft join news_type\r\n on news.news_type=news_type.news_type_id\r\nwhere news.news_id>0\r\n '''\r\n if request.form['g_news_title']:\r\n sql = '%s\\n%s' % (\r\n sql,\r\n 'and charindex(\\'%(title)s\\', news.news_title)>0')\r\n if request.form['g_news_time']:\r\n sql = '%s\\n%s' % (\r\n sql,\r\n 'and datediff(day, \\'%(time)s\\', news.news_time)=0')\r\n param = {\r\n 'title': request.form['g_news_title'],\r\n 'time': request.form['g_news_time']\r\n }\r\n sql = sql % param\r\n # print(sql)\r\n cnx, cursor = gl.db()\r\n data = cursor.execute(sql).fetchall()\r\n gl.close(cursor, cnx)\r\n for d in data:\r\n d.news_title = d.news_title.decode('gbk')\r\n d.news_type_value = d.news_type_value.decode('gbk')\r\n return render_template(\r\n 'article/filter.html',\r\n User = session['user'],\r\n article = data)\r\n\r\n\r\n@app.route('/article//delete')\r\ndef article_delete(nid):\r\n if 'user' not in session:\r\n return redirect('/login')\r\n sql = '''\r\ndelete from\r\n news\r\nwhere\r\n news_id=%(news_id)s'''\r\n param = {'news_id': nid}\r\n sql = sql % param\r\n cnx, cursor = gl.db()\r\n cursor.execute(sql)\r\n cursor.commit()\r\n gl.close(cursor, cnx)\r\n return redirect('/article/list')\r\n","sub_path":"admin/admin/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":6012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"363041365","text":"import geopandas as gpd\nfrom shapely import geometry\nimport rtree\nimport pandas as pd\nimport numpy as np\nfrom scipy.spatial import distance\nimport re\n\nOPENMATE_WGS = \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0\"\nOPENMATE_KATECH = \"+proj=tmerc +lat_0=38 +lon_0=128 +k=0.9999 +x_0=400000 +y_0=600000 +ellps=bessel +towgs84=-115.8,474.99,674.11,1.16,-2.31,-1.63,6.43 +units=m +no_defs\"\n\nosrm_road = gpd.read_file('C:/Users/openmate/Dropbox (오픈메이트)/오픈메이트의 팀 폴더/고객사/KAIA/2017 건설기술연구사업/과제1. 과적/2차년도_2019/분석/201903_data_processing/DTG_Mapmatching/data/road/south-korea-latest-free.shp/gis_osm_roads_free_1.shp', encoding = 'utf-8')\nosrm_road.crs = {'proj' : 'longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0'}\nosrm_road_katech = osrm_road.to_crs(OPENMATE_KATECH)\nsum([x is None for x in osrm_road.name.tolist()])\n\n\"\"\"\nroad maaping table\n\nroad_name |||| linked_name\na b\na c\nb a\nc a\n\n\"\"\"\n\n\"\"\"\npandas DF의 iloc, loc, ix 의 차이\n iloc | loc | ix\ninteger 0 x 0\nlabel x 0 0\n\nix는 label이 숫자일경우 label-based만 됨\n\"\"\"\n\nosrm_road_data = osrm_road_katech[['osm_id','geometry']]\nroad_relation = pd.DataFrame(columns = ['osm_id_left', 'osm_id_right'])\n\nosrm_road_data_centroid = osrm_road_data.centroid\nosrm_road_data_centroid_x = osrm_road_data_centroid.x\nosrm_road_data_centroid_y = osrm_road_data_centroid.y\n\nptr_array = pd.concat([osrm_road_data_centroid_x, osrm_road_data_centroid_y], axis=1).as_matrix()\n\n\"\"\"\ncdist : 서로다른 행렬의 거리\npdist : 같은행렬에서의 pair-wise 거리\n\"\"\"\n\nsave_path = \"C:/Users/openmate/Dropbox (오픈메이트)/오픈메이트의 팀 폴더/고객사/KAIA/2017 건설기술연구사업/과제1. 과적/2차년도_2019/분석/201903_data_processing/DTG_Mapmatching/road_relationship/\"\n\nlen(osrm_road_katech.osm_id)\nlen(set(osrm_road_katech.osm_id.to_list()))\nfor i in range(0, (osrm_road_katech.shape[0]-1) ) :\n print( \"index {} is running\".format(i) )\n target = osrm_road_katech[osrm_road_katech.index.isin([i])][['osm_id','geometry']]\n ptr_bounds = target.bounds\n\n target_array = pd.concat([target.centroid.x, target.centroid.y], axis=1).as_matrix()\n\n closest_idx = distance.cdist(target_array, ptr_array) < 5000 # 중심점 5km 거리연산 수행\n # pandas filtering 해줄때는 -1,1 로 reshape 필수\n osrm_road_katech_which= osrm_road_data[closest_idx.reshape(-1, 1)]\n\n target_join = gpd.sjoin(target, osrm_road_katech_which, op = 'intersects')\n target_df = target_join[['osm_id_left', 'osm_id_right']]\n target_df = target_df[target_df.osm_id_left != target_df.osm_id_right]\n id = str(set(target_df.osm_id_left.to_list()))[2:-2]\n\n layer = save_path + \"id_\" + id + \"_result.csv\"\n target_df.to_csv(layer)\n","sub_path":"mapMatching/src/get_road_relationship.py","file_name":"get_road_relationship.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"49265176","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Alien(Sprite):\n '''表示单个外星人的类'''\n \n def __init__(self,ai_settings,screen):\n '''初始化外星人并设置起始位置'''\n super(Alien, self).__init__()\n self.screen = screen\n self.ai_settings = ai_settings\n screen_rect = self.screen.get_rect()\n #加载外星人图像\n self.image = pygame.image.load('images/UFO.bmp')#surface对象\n self.rect = self.image.get_rect() #rect对象\n \n #每个外星人最初都在屏幕左上角附近\n self.rect.x = self.rect.width\n self.rect.y = self.rect.height\n #我们将每个外星人的左边距都设置为外星人的宽度,\n #并将上边距设置为外星人的高度\n \n #储存外星人的准确位置\n self.x=float(self.rect.x)\n \n def blitme(self):\n '''在指定位置绘制外星人'''\n self.screen.blit(self.image,self.rect)#blit绘制图像draw绘制精灵\n \n def check_edges(self,ai_settings):\n '''如果外星人位于屏幕边缘,就返回True'''#这种带函数调用值不能用于条件判断,必须赋值\n screen_rect = self.screen.get_rect()\n if self.rect.right >= screen_rect.right:\n\n return True\n elif self.rect.left <= 0:\n return True \n \n def update(self):\n '''向右移动外星人'''\n self.x += (self.ai_settings.alien_speed_factor *#可储存小数值\n self.ai_settings.fleet_direction)\n self.rect.x = self.x\n \n \n","sub_path":"alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"28107975","text":"import json\nfrom pathlib import Path\n\nfrom etl.src import match_records\n\n\ndef test_transform() -> None:\n basepath = Path(__file__).parent\n with open(basepath / \"test_record_raw.json\") as f, open(basepath / \"test_record_transformed.json\") as e:\n raw = json.load(f)\n expected = json.load(e)\n\n transformed = match_records.MatchRecords.transform_record(raw)\n assert transformed == expected, \"transformed and expected values do not \"\n","sub_path":"tests/etl/match_records_test.py","file_name":"match_records_test.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378098400","text":"import cv2\nimport numpy as np\nimport math\n\ndef detectarDiana(frame):\n\n opcion = 1\n #precision de la diana\n max_distancia = 30\n #cv2.imshow('frame entrada',frame)\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n \n #cv2.imshow('imagen gray',gray)\n\n image = cv2.Canny(gray,100,500)\n #retval, image = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\n \n # cv2.imshow('canny',image)\n \n kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5))\n #image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)\n image = cv2.dilate(image, kernel)\n \n #cv2.imshow('binary',image)\n\n centro = False\n centro_x = 0\n centro_y = 0\n \n #inicialiamos la variable que detecta si la diana esta apuntada\n locked = False\n \n if opcion == 1:\n # Busca los contornos\n contours, hierarchy = cv2.findContours(image,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\n \n true_centers = []\n centers = []\n radii = []\n pt1 = []\n pt2 = []\n fill = []\n areas = []\n \n detectado = False\n # Miramos los contornos detectados\n for contour in contours:\n \n area = cv2.contourArea(contour)\n # Comprovar el area que ocupa\n if area < 200:\n continue\n \n detectado = True\n fill.append(contour)\n areas.append(area)\n \n br = cv2.boundingRect(contour) \n \n # Guardar puntos para recrear el overlay\n pt1.append((br[0], br[1]))\n pt2.append((br[0]+br[2], br[1]+br[3]))\n \n radii.append(min(br[2], br[3])/2) \n \n true_centers.append((br[0]+ (int)(br[2]/2), br[1]+ (int)(br[3]/2)))\n \n m = cv2.moments(contour)\n center = (int(m['m10'] / m['m00']), int(m['m01'] / m['m00']))\n centers.append(center)\n \n\n if detectado:\n maxV = 0\n maxIndex = 0\n maxIndex2 = 0\n \n for i in range(len(areas)):\n if areas[i] > maxV:\n maxV = areas[i]\n maxIndex2 = maxIndex\n maxIndex = i\n if maxIndex != 0:\n fill[maxIndex] = None\n \n overlay = frame.copy()\n \n # Buscamos los centros\n if(len(centers)):\n for n in range(len(centers)): \n if n != maxIndex2:\n continue \n centro = True\n centro_x = true_centers[n][0]\n centro_y = true_centers[n][1]\n ellip = cv2.fitEllipse(fill[n]) \n cv2.drawContours(frame, fill, maxIndex2, (255, 255, 255), 1)\n cv2.ellipse(overlay, ellip, (125, 125, 0), -1)\n cv2.rectangle(frame, pt1[n], pt2[n], (0, 0, 255), 1, 8, 0)\n cv2.circle(frame, true_centers[n], 3, (0, 0, 0), -1)\n cv2.circle(frame, centers[n], 3, (255, 0, 0), -1)\n cv2.addWeighted(overlay, 0.5, frame, 0.5, 0, frame) \n cv2.circle(frame, (centro_x, centro_y), 10 ,(0, 0, 0), 2)\n \n \n if opcion == 2:\n circles\t= cv2.HoughCircles(image,cv2.HOUGH_GRADIENT,1,120,param1=100,param2=30,minRadius=50,maxRadius=92)\n if circles is not None:\n centro = True\n overlay = frame.copy()\n\n circles\t= np.uint16(np.around(circles))\n for\ti in circles[0,:]:\n \t\t#\tdraw\tthe\touter\tcircle\n cv2.circle(frame,(i[0],i[1]),i[2],(0,255,0),6)\n \t\t#\tdraw\tthe\tcenter\tof\tthe\tcircle\n cv2.circle(frame,(i[0],i[1]),2,(0,0,255),3)\n centro_x = i[0]\n centro_y = i[1]\n cv2.circle(frame, (centro_x, centro_y), 10 ,(0, 0, 255), 2)\n\n if centro:\n height, width, _ = frame.shape\n \n centro_x = centro_x-(width/2)\n centro_y = centro_y-(height/2)\n distancia = math.sqrt((centro_x**2)+(centro_y**2))\n \n color = (0, 0, 255)\n if distancia < max_distancia:\n locked = True\n color = (0, 255, 0)\n \n cv2.circle(frame, (int(width/2), int(height/2)), int(max_distancia) , color, 2) \n\n \n return [frame, centro, centro_x, centro_y, locked]\n\n","sub_path":"Aplicacion/IdentificarDiana.py","file_name":"IdentificarDiana.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"62662665","text":"# -*- coding: utf-8 -*-\n#################################################################################\n# Author : Acespritech Solutions Pvt. Ltd. ()\n# Copyright(c): 2012-Present Acespritech Solutions Pvt. Ltd.\n# All Rights Reserved.\n#\n# This program is copyright property of the author mentioned above.\n# You can`t redistribute it and/or modify it.\n#\n#################################################################################\n\n\nimport xlwt\nimport base64\nfrom io import BytesIO\nfrom datetime import date, timedelta\nfrom dateutil.relativedelta import relativedelta\nfrom odoo.tools.misc import xlwt\nfrom odoo.exceptions import Warning\nfrom odoo import models, fields, api, _\n\n\nclass ResConfigSettings(models.TransientModel):\n _inherit = \"res.config.settings\"\n\n @api.multi\n def set_values(self):\n super(ResConfigSettings, self).set_values()\n ICPSudo = self.env['ir.config_parameter'].sudo()\n ICPSudo.set_param(\"stock.module_product_expiry\", self.module_product_expiry)\n\n @api.model\n def get_values(self):\n res = super(ResConfigSettings, self).get_values()\n ICPSudo = self.env['ir.config_parameter'].sudo()\n module_product_expiry = ICPSudo.get_param('stock.module_product_expiry')\n res.update(module_product_expiry=module_product_expiry)\n return res\n\n\nclass ProductExpiryReport(models.Model):\n _name = \"product.expiry.report\"\n _description = \"Print Product Expiry Report\"\n\n num_expiry_days = fields.Integer(string=\"Product Expiry In Next\")\n location_ids = fields.Many2many('stock.location', string=\"Location\",\n domain=[('usage', '=', 'internal')])\n category_ids = fields.Many2many('product.category', string=\"Category\")\n group_by = fields.Selection([('location', 'Location'), ('category', 'Category')], string=\"Group By\",\n default=\"location\")\n\n @api.multi\n def print_pdf_report(self):\n if self.env['ir.config_parameter'].sudo().get_param('stock.module_product_expiry'):\n return self.print_product_expiry_report('pdf')\n\n else:\n raise Warning(_('Please enable \"Expiration Dates\" from Inventory-->Settings-->Traceability'))\n\n @api.multi\n def print_xls_report(self):\n if not self.env['ir.config_parameter'].sudo().get_param('stock.module_product_expiry'):\n raise Warning(_('Please enable \"Expiration Dates\" from Inventory-->Settings-->Traceability'))\n else:\n return self.print_product_expiry_report('xls')\n\n @api.multi\n def print_product_expiry_report(self, report_type):\n if self.num_expiry_days <= 0:\n raise Warning(_('Number Of Expiry Days should be greater then 0'))\n location_ids = self.location_ids.ids or self.env['stock.location'].search([('usage', '=', 'internal')]).ids\n category_ids = self.category_ids.ids or self.env['product.category'].search([]).ids\n SQL1 = '''SELECT sq.location_id,sl.usage,spl.product_id,spl.id,spl.life_date,spl.name,pc.name as product_category,\n pp.default_code,pt.name as product_name \n FROM stock_production_lot spl\n LEFT JOIN stock_quant sq on sq.lot_id = spl.id\n LEFT JOIN stock_location sl on sq.location_id = sl.id\n LEFT JOIN product_product pp on spl.product_id = pp.id\n LEFT JOIN product_template pt on pp.product_tmpl_id = pt.id\n LEFT JOIN product_category pc on pt.categ_id = pc.id\n WHERE spl.life_date AT TIME ZONE 'GMT' <= '%s' AND\n spl.life_date AT TIME ZONE 'GMT' >= '%s' AND\n pc.id IN %s order by pp.default_code''' % (\n (date.today() + timedelta(days=self.num_expiry_days)),\n date.today(),\n \"(%s)\" % ','.join(map(str, category_ids)))\n self.env.cr.execute(SQL1)\n res1 = self.env.cr.dictfetchall()\n\n temp_res = []\n for each in res1:\n if each.get('usage') in ['internal',None]:\n temp_res.append(each)\n SQL = '''SELECT sq.location_id,sl.usage,spl.product_id,spl.id,spl.life_date,spl.name,pc.name as product_category,\n pp.default_code,pt.name as product_name FROM stock_quant sq\n LEFT JOIN stock_location sl on sq.location_id = sl.id\n LEFT JOIN stock_production_lot spl on sq.lot_id = spl.id\n LEFT JOIN product_product pp on spl.product_id = pp.id\n LEFT JOIN product_template pt on pp.product_tmpl_id = pt.id\n LEFT JOIN product_category pc on pt.categ_id = pc.id\n WHERE spl.life_date AT TIME ZONE 'GMT' <= '%s' AND\n spl.life_date AT TIME ZONE 'GMT' >= '%s' AND\n pc.id IN %s AND\n sq.location_id IN %s order by pp.default_code''' % (\n (date.today() + timedelta(days=self.num_expiry_days)),\n date.today(),\n \"(%s)\" % ','.join(map(str, category_ids)),\n \"(%s)\" % ','.join(map(str, location_ids)))\n self.env.cr.execute(SQL)\n res = self.env.cr.dictfetchall()\n if not self.location_ids:\n res = res + temp_res\n res = [dict(t) for t in {tuple(d.items()) for d in res}]\n if len(res) == 0:\n raise Warning(_('No such record found for product expiry.'))\n else:\n if self.group_by == 'category':\n vals = {}\n for each in res:\n if each.get('location_id') == None:\n location_name = \"--\"\n else:\n location_name = self.env['stock.location'].browse(\n each.get('location_id')).display_name\n if each['product_category'] not in vals:\n vals[each.get('product_category')] = [\n {'name': each.get('name'),\n 'product_id': each.get('product_name'),\n 'location_name': location_name,\n 'default_code': each.get('default_code') or '--------',\n 'life_date': each.get('life_date').strftime('%Y-%m-%d'),\n 'remaining_days': relativedelta(each.get('life_date'), date.today()).days,\n 'available_qty': self.env['stock.production.lot'].browse(each.get('id')).product_qty if each.get('id') else False,}]\n else:\n vals[each.get('product_category')].append(\n {'name': each.get('name'),\n 'product_id': each.get('product_name'),\n 'location_name': location_name,\n 'default_code': each.get('default_code') or '--------',\n 'life_date': each.get('life_date').strftime('%Y-%m-%d'),\n 'remaining_days': relativedelta(each.get('life_date'), date.today()).days,\n 'available_qty': self.env['stock.production.lot'].browse(each.get('id')).product_qty if each.get('id') else False,})\n else:\n vals = {}\n for each in res:\n if each.get('location_id') == None:\n location_name = \"--\"\n else:\n location_name = self.env['stock.location'].browse(\n each.get('location_id')).display_name\n if location_name not in vals:\n vals[location_name] = [\n {'name': each.get('name'),\n 'product_id': each.get('product_name'),\n 'product_category': each.get('product_category'),\n 'default_code': each.get('default_code') or '--------',\n 'life_date': each.get('life_date').strftime('%Y-%m-%d'),\n 'remaining_days': relativedelta(each.get('life_date'), date.today()).days,\n 'available_qty': self.env['stock.production.lot'].browse(each.get('id')).product_qty if each.get('id') else False,}]\n else:\n vals[location_name].append(\n {'name': each.get('name'),\n 'product_id': each.get('product_name'),\n 'product_category': each.get('product_category'),\n 'default_code': each.get('default_code') or '--------',\n 'life_date': each.get('life_date').strftime('%Y-%m-%d'),\n 'remaining_days': relativedelta(each.get('life_date'), date.today()).days,\n 'available_qty': self.env['stock.production.lot'].browse(each.get('id')).product_qty if each.get('id') else False,})\n vals.update(\n {'group_by': self.group_by, 'num_days': self.num_expiry_days, 'today_date': date.today()})\n vals_new = {}\n vals_new.update({'stock': vals})\n if report_type == 'pdf':\n return self.env.ref('flexipharmacy_ee.product_expiry_report').report_action(self,\n data=vals_new)\n elif report_type == 'xls':\n return self.print_xls_product_report(vals)\n\n @api.multi\n def print_xls_product_report(self, vals):\n stylePC = xlwt.XFStyle()\n bold = xlwt.easyxf(\"font: bold on; pattern: pattern solid, fore_colour gray25;\")\n alignment = xlwt.Alignment()\n alignment.horz = xlwt.Alignment.HORZ_CENTER\n stylePC.alignment = alignment\n alignment = xlwt.Alignment()\n alignment.horz = xlwt.Alignment.HORZ_CENTER\n font = xlwt.Font()\n borders = xlwt.Borders()\n borders.bottom = xlwt.Borders.THIN\n font.bold = True\n font.height = 500\n stylePC.font = font\n stylePC.alignment = alignment\n pattern = xlwt.Pattern()\n pattern.pattern = xlwt.Pattern.SOLID_PATTERN\n pattern.pattern_fore_colour = xlwt.Style.colour_map['gray25']\n stylePC.pattern = pattern\n workbook = xlwt.Workbook()\n worksheet = workbook.add_sheet('Stock Expiry Report')\n for j in range(0, 7):\n worksheet.col(j).width = 5600\n j += 1\n worksheet.write_merge(1, 2, 0, 6, 'Product Expiry Report', style=stylePC)\n worksheet.write(4, 0, \"Product Expiry In Next\", bold)\n worksheet.write(4, 1, str(vals.get('num_days'))+' Days')\n worksheet.write(4, 4, \"Date\", bold)\n worksheet.write(4, 5, str(vals.get('today_date')))\n i = 6\n for key, value in vals.items():\n if vals.get('group_by') and key not in ['group_by', 'num_days', 'today_date']:\n if vals.get('group_by') == 'location':\n worksheet.write(i, 0, \"Location\", bold)\n elif vals.get('group_by') == 'category':\n worksheet.write(i, 0, \"Category\", bold)\n worksheet.write(i, 1, key)\n i += 2\n if value not in [vals.get('num_day'), vals.get('today_date')]:\n worksheet.write(i, 0, \"Lot/Serial number\", bold)\n worksheet.write(i, 1, \"Product\", bold)\n if vals.get('group_by') == 'location':\n worksheet.write(i, 2, \"Category\", bold)\n elif vals.get('group_by') == 'category':\n worksheet.write(i, 2, \"Location\", bold)\n worksheet.write(i, 3, \"Internal Ref\", bold)\n worksheet.write(i, 4, \"Expiry Date\", bold)\n worksheet.write(i, 5, \"Remaining Days\", bold)\n worksheet.write(i, 6, \"Available Quantity\", bold)\n i += 1\n for each in value:\n count = 0\n for key, val in each.items():\n worksheet.write(i, count, val)\n count += 1\n i += 1\n i += 1\n file_data = BytesIO()\n workbook.save(file_data)\n report_id = self.env['report.download.wizard'].create({\n 'data': base64.encodestring(file_data.getvalue()),\n 'name': 'Product Expiry Report.xls'\n })\n return {\n 'name': 'Download Excel Report',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'report.download.wizard',\n 'target': 'new',\n 'res_id': report_id.id,\n 'type': 'ir.actions.act_window'\n }\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"flexipharmacy_ee/models/product_expiry_report.py","file_name":"product_expiry_report.py","file_ext":"py","file_size_in_byte":13351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"140843975","text":"import urllib.request\nimport urllib.parse\nimport re\nimport pymysql\nimport csv\n\n\nclass MoYan(object):\n def __init__(self, url):\n self.url = url\n self.heads = {\n 'Referer': 'https://maoyan.com/board/4?offset=0',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',\n }\n\n\n self.conn = pymysql.connect(host=\"localhost\", user=\"root\",\n password=\"123456\", database=\"maoyan\",\n charset=\"utf8\")\n\n self.cursor = self.conn.cursor()\n self.scv_f = open('电影排行榜.csv','a')\n self.scv_head = ['pic','name','actor','time','brking','peiming']\n self.write = csv.DictWriter(self.scv_f,self.scv_head)\n def send_request(self,page):\n print('正在发送请求')\n request = self.parse()\n response = urllib.request.urlopen(request)\n # self.write_file(response.read())\n self.write_file(response.read(),page)\n\n def parse(self):\n print(\"正在对路由进行编译\")\n canshu = urllib.parse.urlencode(self.kw)\n full_url = urllib.request.Request(url=self.url + canshu, headers=self.heads)\n return full_url\n def write_csv(self,content):\n self.write.writerow(content)\n def write_file(self, content,page):\n print('正在保存文件')\n with open('猫眼榜单{}.html'.format(page), 'wb') as f:\n f.write(content)\n f.close()\n self.get_data()\n\n def get_data(self):\n print(\"正在使用正则获取指定数据\")\n with open('猫眼榜单1.html', 'r+') as f:\n data = f.readlines()\n data1 = ''.join(data)\n f.close()\n pattern = re.compile(\n r'
.*?(.*?)<.*?(.*?)<.*?

(.*?)<.*?

(.*?)<.*?

(.*?)(.*?)<.*?

',\n re.S)\n result = pattern.findall(data1)\n for i in result:\n mv = {\n 'pic': i[1],\n 'name': i[2],\n 'actor': i[3],\n 'time': i[4],\n 'brking': i[5] + i[6],\n 'peiming': i[0]\n }\n # self.write_sql(mv,)\n self.write_csv(mv)\n def write_sql(self, data):\n # 连接数据库\n print('data的数据有', data)\n conn = pymysql.connect(host=\"localhost\", user=\"root\",\n password=\"123456\", database=\"maoyan\",\n charset=\"utf8\")\n\n sql = 'insert into db_move(%s) values(%s)' % (\n ','.join([key for key in data.keys()]), ','.join(['%s'] * (len(data)))\n )\n self.cursor.execute(sql,[values for values in data.values()])\n self.conn.commit()\n\n def start(self):\n\n for i in range(1, 11):\n\n self.kw = {\n 'offset': (i-1)*10\n }\n self.send_request(i)\n\n # self.get_data()\n\n\nif __name__ == '__main__':\n # https://maoyan.com/board/4?offset=10\n moyan = MoYan('https://maoyan.com/board/4?')\n moyan.start()\n\n\n\n","sub_path":"自己自学的爬虫/02_day/爬取猫眼电影榜单.py","file_name":"爬取猫眼电影榜单.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"562142679","text":"from tensorflow_probability import distributions as tfpd\nimport tensorflow.keras.layers as tfkl\nimport tensorflow.keras as keras\nimport tensorflow as tf\nimport numpy as np\n\n\nclass SequentialVAE(tf.keras.Model):\n\n def __init__(self, task, hidden_size=64, latent_size=256,\n activation='relu', kernel_size=3, num_blocks=4):\n\n super(SequentialVAE, self).__init__()\n\n input_shape = task.input_shape\n shape_before_flat = [input_shape[0] // (\n 2 ** (num_blocks - 1)), hidden_size]\n\n \"\"\"\n\n DEFINE AN ENCODER MODEL THAT DOWNSAMPLES\n\n \"\"\"\n\n # the input layer of a keras model\n x = input_layer = keras.Input(shape=input_shape)\n\n # build a model with an input layer and optional embedding\n x = tfkl.Embedding(task.num_classes, hidden_size)(x)\n\n # the exponent of a positional embedding\n inverse_frequency = 1.0 / (10000.0 ** (tf.range(\n 0.0, hidden_size, 2.0) / hidden_size))[tf.newaxis]\n\n # calculate a positional embedding to break symmetry\n pos = tf.range(0.0, tf.shape(x)[1], 1.0)[:, tf.newaxis]\n positional_embedding = tf.concat([\n tf.math.sin(pos * inverse_frequency),\n tf.math.cos(pos * inverse_frequency)], axis=1)[tf.newaxis]\n\n # add the positional encoding\n x = tfkl.Add()([x, positional_embedding])\n x = tfkl.LayerNormalization()(x)\n\n # add several residual blocks to the model\n for i in range(num_blocks):\n\n if i > 0:\n # downsample the input sequence by 2\n x = tf.keras.layers.AveragePooling1D(pool_size=2,\n padding='same')(x)\n\n # first convolution layer in a residual block\n h = tfkl.Conv1D(hidden_size, kernel_size,\n padding='same', activation=None)(x)\n h = tfkl.LayerNormalization()(h)\n h = tfkl.Activation(activation)(h)\n\n # second convolution layer in a residual block\n h = tfkl.Conv1D(hidden_size, kernel_size,\n padding='same', activation=None)(h)\n h = tfkl.LayerNormalization()(h)\n h = tfkl.Activation(activation)(h)\n\n # add a residual connection to the model\n x = tfkl.Add()([x, h])\n\n # flatten the result and predict the params of a gaussian\n flattened_x = tfkl.Flatten()(x)\n latent_mean = tfkl.Dense(latent_size)(flattened_x)\n latent_standard_dev = tfkl.Dense(\n latent_size, activation=tf.exp)(flattened_x)\n\n # save the encoder as a keras model\n self.encoder_cnn = keras.Model(\n inputs=input_layer,\n outputs=[latent_mean, latent_standard_dev])\n\n \"\"\"\n\n DEFINE A DECODER THAT UPSAMPLES\n\n \"\"\"\n\n # the input layer of a keras model\n x = input_layer = keras.Input(shape=[latent_size])\n x = tfkl.Dense(np.prod(shape_before_flat))(x)\n x = tfkl.Reshape(shape_before_flat)(x)\n\n # add several residual blocks to the model\n for i in reversed(range(num_blocks)):\n\n if i > 0:\n # up-sample the sequence and handle\n x = tf.pad(tf.repeat(x, 2, axis=1), [[0, 0], [\n 0,\n (input_shape[0] // (2 ** (i - 1))) % 2\n ], [0, 0]], mode=\"SYMMETRIC\")\n\n # the exponent of a positional embedding\n inverse_frequency = 1.0 / (10000.0 ** (tf.range(\n 0.0, hidden_size, 2.0) / hidden_size))[tf.newaxis]\n\n # calculate a positional embedding to break symmetry\n pos = tf.range(0.0, tf.shape(x)[1], 1.0)[:, tf.newaxis]\n positional_embedding = tf.concat([\n tf.math.sin(pos * inverse_frequency),\n tf.math.cos(pos * inverse_frequency)], axis=1)[tf.newaxis]\n\n # add the positional encoding\n h = tfkl.Add()([x, positional_embedding])\n h = tfkl.LayerNormalization()(h)\n\n # first convolution layer in a residual block\n h = tfkl.Conv1D(hidden_size, kernel_size,\n padding='same', activation=None)(h)\n h = tfkl.LayerNormalization()(h)\n h = tfkl.Activation(activation)(h)\n\n # second convolution layer in a residual block\n h = tfkl.Conv1D(hidden_size, kernel_size,\n padding='same', activation=None)(h)\n h = tfkl.LayerNormalization()(h)\n h = tfkl.Activation(activation)(h)\n\n # add a residual connection to the model\n x = tfkl.Add()([x, h])\n\n # flatten the result and predict the params of a gaussian\n logits = tfkl.Dense(task.num_classes)(x)\n\n # save the encoder as a keras model\n self.decoder_cnn = keras.Model(\n inputs=input_layer, outputs=logits)\n\n def encode(self, x_batch, training=False):\n mean, standard_dev = self.encoder_cnn(x_batch, training=training)\n return tfpd.MultivariateNormalDiag(loc=mean, scale_diag=standard_dev)\n\n def decode(self, z, training=False):\n logits = self.decoder_cnn(z, training=training)\n return tfpd.Categorical(logits=logits)\n\n def generate(self, z, training=False):\n logits = self.decoder_cnn(z, training=training)\n return tf.argmax(logits, axis=2, output_type=tf.int32)\n\n\nclass ForwardModel(tf.keras.Sequential):\n \"\"\"A Fully Connected Network with 2 trainable layers\"\"\"\n\n distribution = tfpd.Normal\n\n def __init__(self, input_shape, hidden_size=50,\n num_layers=1, initial_max_std=1.5, initial_min_std=0.5):\n \"\"\"Create a fully connected architecture using keras that can process\n designs and predict a gaussian distribution over scores\n\n Args:\n\n task: StaticGraphTask\n a model-based optimization task\n embedding_size: int\n the size of the embedding matrix for discrete tasks\n hidden_size: int\n the global hidden size of the neural network\n num_layers: int\n the number of hidden layers\n initial_max_std: float\n the starting upper bound of the standard deviation\n initial_min_std: float\n the starting lower bound of the standard deviation\n\n \"\"\"\n\n self.max_logstd = tf.Variable(tf.fill([1, 1], np.log(\n initial_max_std).astype(np.float32)), trainable=True)\n self.min_logstd = tf.Variable(tf.fill([1, 1], np.log(\n initial_min_std).astype(np.float32)), trainable=True)\n\n layers = []\n layers.append(tfkl.Flatten(input_shape=input_shape)\n if len(layers) == 0 else tfkl.Flatten())\n for i in range(num_layers):\n layers.extend([tfkl.Dense(hidden_size), tfkl.LeakyReLU()])\n\n layers.append(tfkl.Dense(2))\n super(ForwardModel, self).__init__(layers)\n\n def get_params(self, inputs, **kwargs):\n \"\"\"Return a dictionary of parameters for a particular distribution\n family such as the mean and variance of a gaussian\n\n Args:\n\n inputs: tf.Tensor\n a batch of training inputs shaped like [batch_size, channels]\n\n Returns:\n\n parameters: dict\n a dictionary that contains 'loc' and 'scale_diag' keys\n \"\"\"\n\n prediction = super(ForwardModel, self).__call__(inputs, **kwargs)\n mean, logstd = tf.split(prediction, 2, axis=-1)\n logstd = self.max_logstd - tf.nn.softplus(self.max_logstd - logstd)\n logstd = self.min_logstd + tf.nn.softplus(logstd - self.min_logstd)\n return {\"loc\": mean, \"scale\": tf.math.exp(logstd)}\n\n def get_distribution(self, inputs, **kwargs):\n \"\"\"Return a distribution over the outputs of this model, for example\n a Multivariate Gaussian Distribution\n\n Args:\n\n inputs: tf.Tensor\n a batch of training inputs shaped like [batch_size, channels]\n\n Returns:\n\n distribution: tfp.distribution.Distribution\n a tensorflow probability distribution over outputs of the model\n \"\"\"\n\n return self.distribution(**self.get_params(inputs, **kwargs))\n","sub_path":"design_baselines/bo_qei/nets.py","file_name":"nets.py","file_ext":"py","file_size_in_byte":8256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"320616531","text":"\n\n\n##############\n# code snips from \"6 differenty ways of implimenting vae with tensorflow 2\"\n# https://towardsdatascience.com/6-different-ways-of-implementing-vae-with-tensorflow-2-and-tensorflow-probability-9fe34a8ab981\n# \n##################\n\n##################\n# generic architecture from https://www.tensorflow.org/tutorials/generative/cvae\n##################\n\nimport glob\nimport imageio\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport PIL\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport time\n\nclass CVAE(tf.keras.Model):\n \"\"\"Convolutional variational autoencoder.\"\"\"\n\n def __init__(self, latent_dim):\n super(CVAE, self).__init__()\n self.latent_dim = latent_dim\n self.encoder = tf.keras.Sequential(\n [\n tf.keras.layers.InputLayer(input_shape=(28, 28, 1)),\n tf.keras.layers.Conv2D(\n filters=32, kernel_size=3, strides=(2, 2), activation='relu'),\n tf.keras.layers.Conv2D(\n filters=64, kernel_size=3, strides=(2, 2), activation='relu'),\n tf.keras.layers.Flatten(),\n # No activation\n tf.keras.layers.Dense(latent_dim + latent_dim),\n ]\n )\n\n self.decoder = tf.keras.Sequential(\n [\n tf.keras.layers.InputLayer(input_shape=(latent_dim,)),\n tf.keras.layers.Dense(units=7*7*32, activation=tf.nn.relu),\n tf.keras.layers.Reshape(target_shape=(7, 7, 32)),\n tf.keras.layers.Conv2DTranspose(\n filters=64, kernel_size=3, strides=2, padding='same',\n activation='relu'),\n tf.keras.layers.Conv2DTranspose(\n filters=32, kernel_size=3, strides=2, padding='same',\n activation='relu'),\n # No activation\n tf.keras.layers.Conv2DTranspose(\n filters=1, kernel_size=3, strides=1, padding='same'),\n ]\n )\n\n @tf.function\n def sample(self, eps=None):\n if eps is None:\n eps = tf.random.normal(shape=(100, self.latent_dim))\n return self.decode(eps, apply_sigmoid=True)\n\n def encode(self, x):\n mean, logvar = tf.split(self.encoder(x), num_or_size_splits=2, axis=1)\n return mean, logvar\n\n def reparameterize(self, mean, logvar):\n eps = tf.random.normal(shape=mean.shape)\n return eps * tf.exp(logvar * .5) + mean\n\n def decode(self, z, apply_sigmoid=False):\n logits = self.decoder(z)\n if apply_sigmoid:\n probs = tf.sigmoid(logits)\n return probs\n return logits\n\noptimizer = tf.keras.optimizers.Adam(1e-4)\n\n\ndef log_normal_pdf(sample, mean, logvar, raxis=1):\n log2pi = tf.math.log(2. * np.pi)\n return tf.reduce_sum(\n -.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi),\n axis=raxis)\n\n\ndef compute_loss(model, x):\n mean, logvar = model.encode(x)\n z = model.reparameterize(mean, logvar)\n x_logit = model.decode(z)\n cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=x_logit, labels=x)\n logpx_z = -tf.reduce_sum(cross_ent, axis=[1, 2, 3])\n logpz = log_normal_pdf(z, 0., 0.)\n logqz_x = log_normal_pdf(z, mean, logvar)\n return -tf.reduce_mean(logpx_z + logpz - logqz_x)\n\n\n@tf.function\ndef train_step(model, x, optimizer):\n \"\"\"Executes one training step and returns the loss.\n\n This function computes the loss and gradients, and uses the latter to\n update the model's parameters.\n \"\"\"\n with tf.GradientTape() as tape:\n loss = compute_loss(model, x)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n\n\n##################\n# version a\n##################\n# vae cost function as negative ELBO\ndef vae_cost(x_true, model, analytic_kl=True, kl_weight=1):\n z_sample, mu, sd = model.encode(x_true)\n x_recons_logits = model.decoder(z_sample)\n # compute cross entropy loss for each dimension of every datapoint\n raw_cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=x_true,\n logits=x_recons_logits) # shape=(batch_size, 28, 28, 1)\n # compute cross entropy loss for all instances in mini-batch; shape=(batch_size,)\n neg_log_likelihood = tf.math.reduce_sum(raw_cross_entropy, axis=[1, 2, 3])\n # compute reverse KL divergence, either analytically \n # or through MC approximation with one sample\n if analytic_kl:\n kl_divergence = - 0.5 * tf.math.reduce_sum(\n 1 + tf.math.log(tf.math.square(sd)) - tf.math.square(mu) - tf.math.square(sd),\n axis=1) # shape=(batch_size, )\n else:\n logpz = normal_log_pdf(z_sample, 0., 1.) # shape=(batch_size,)\n logqz_x = normal_log_pdf(z_sample, mu, tf.math.square(sd)) # shape=(batch_size,)\n kl_divergence = logqz_x - logpz\n elbo = tf.math.reduce_mean(-kl_weight * kl_divergence - neg_log_likelihood) # shape=()\n return -elbo\n\n\n@tf.function\ndef train_step(x_true, model, optimizer, analytic_kl=True, kl_weight=1):\n with tf.GradientTape() as tape:\n cost_mini_batch = vae_cost(x_true, model, analytic_kl, kl_weight)\n gradients = tape.gradient(cost_mini_batch, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n\n\n## KL divergence snippet\nprior_dist = tfd.MultivariateNormalDiag(loc=tf.zeros((batch_size, latent_dim)), scale_diag=tf.ones((batch_size, latent_dim)))\nvar_post_dist = tfd.MultivariateNormalDiag(loc=mu, scale_diag=sd)\nkl_divergence = tfd.kl_divergence(distribution_a=var_post_dist, distribution_b=prior_dist)\n\n\n\n##################\n# version b\n##################\nclass VAE_MNIST:\n \n def __init__(self, dim_z, kl_weight, learning_rate):\n self.dim_x = (28, 28, 1)\n self.dim_z = dim_z\n self.kl_weight = kl_weight\n self.learning_rate = learning_rate\n\n # Sequential API encoder\n def encoder_z(self):\n # define prior distribution for the code, which is an isotropic Gaussian\n prior = tfd.Independent(tfd.Normal(loc=tf.zeros(self.dim_z), scale=1.), \n reinterpreted_batch_ndims=1)\n # build layers argument for tfk.Sequential()\n input_shape = self.dim_x\n layers = [tfkl.InputLayer(input_shape=input_shape)]\n layers.append(tfkl.Conv2D(filters=32, kernel_size=3, strides=(2,2), \n padding='valid', activation='relu'))\n layers.append(tfkl.Conv2D(filters=64, kernel_size=3, strides=(2,2), \n padding='valid', activation='relu'))\n layers.append(tfkl.Flatten())\n # the following two lines set the output to be a probabilistic distribution\n layers.append(tfkl.Dense(tfpl.IndependentNormal.params_size(self.dim_z), \n activation=None, name='z_params'))\n layers.append(tfpl.IndependentNormal(self.dim_z, \n convert_to_tensor_fn=tfd.Distribution.sample, \n activity_regularizer=tfpl.KLDivergenceRegularizer(prior, weight=self.kl_weight), \n name='z_layer'))\n return tfk.Sequential(layers, name='encoder')\n \n # Sequential API decoder\n def decoder_x(self):\n layers = [tfkl.InputLayer(input_shape=self.dim_z)]\n layers.append(tfkl.Dense(7*7*32, activation=None))\n layers.append(tfkl.Reshape((7,7,32)))\n layers.append(tfkl.Conv2DTranspose(filters=64, kernel_size=3, strides=2, \n padding='same', activation='relu'))\n layers.append(tfkl.Conv2DTranspose(filters=32, kernel_size=3, strides=2, \n padding='same', activation='relu'))\n layers.append(tfkl.Conv2DTranspose(filters=1, kernel_size=3, strides=1, \n padding='same'))\n layers.append(tfkl.Flatten(name='x_params'))\n # note that here we don't need \n # `tfkl.Dense(tfpl.IndependentBernoulli.params_size(self.dim_x))` because \n # we've restored the desired input shape with the last Conv2DTranspose layer\n layers.append(tfpl.IndependentBernoulli(self.dim_x, name='x_layer'))\n return tfk.Sequential(layers, name='decoder')\n \n def build_vae_keras_model(self):\n x_input = tfk.Input(shape=self.dim_x)\n encoder = self.encoder_z()\n decoder = self.decoder_x()\n z = encoder(x_input)\n\n # compile VAE model\n model = tfk.Model(inputs=x_input, outputs=decoder(z))\n model.compile(loss=negative_log_likelihood, \n optimizer=tfk.optimizers.Adam(self.learning_rate))\n return model\n\n# the negative of log-likelihood for probabilistic output\nnegative_log_likelihood = lambda x, rv_x: -rv_x.log_prob(x)\n\n\n\n\n\n##################\n# version c (a with custom loss)\n##################\ndef custom_sigmoid_cross_entropy_loss_with_logits(x_true, x_recons_logits):\n raw_cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=x_true, \n logits=x_recons_logits)\n neg_log_likelihood = tf.math.reduce_sum(raw_cross_entropy, axis=[1, 2, 3])\n return tf.math.reduce_mean(neg_log_likelihood)\n\n\nmodel.compile(loss=custom_sigmoid_cross_entropy_loss_with_logits, optimizer=tfk.optimizers.Adam(learning_rate))\n\n\n##################\n# version d (b with custom loss)\n##################\n\ndef custom_binary_cross_entropy_loss(x_true, x_recons_dist):\n x_recons_mean = x_recons_dist.mean()\n raw_cross_entropy = tfk.losses.BinaryCrossentropy(\n reduction=tfk.losses.Reduction.NONE)(x_true, x_recons_mean)\n neg_log_likelihood = tf.math.reduce_sum(raw_cross_entropy, axis=[1, 2])\n return tf.math.reduce_mean(neg_log_likelihood)\n\n\n\n##################\n# version e (a with custom loss)\n##################\n\nclass VAE_MNIST(tfk.Model):\n \n def __init__(self, dim_z, kl_weight=1, name=\"autoencoder\", **kwargs):\n super(VAE_MNIST, self).__init__(name=name, **kwargs)\n self.dim_x = (28, 28, 1)\n self.dim_z = dim_z\n self.encoder = self.encoder_z()\n self.decoder = self.decoder_x()\n self.kl_weight = kl_weight\n \n # Sequential API encoder\n def encoder_z(self):\n layers = [tfkl.InputLayer(input_shape=self.dim_x)]\n layers.append(tfkl.Conv2D(filters=32, kernel_size=3, strides=(2,2), \n padding='valid', activation='relu'))\n layers.append(tfkl.Conv2D(filters=64, kernel_size=3, strides=(2,2), \n padding='valid', activation='relu'))\n layers.append(tfkl.Flatten())\n # *2 because number of parameters for both mean and (raw) standard deviation\n layers.append(tfkl.Dense(self.dim_z*2, activation=None))\n return tfk.Sequential(layers)\n \n def encode(self, x_input):\n mu, rho = tf.split(self.encoder(x_input), num_or_size_splits=2, axis=1)\n sd = tf.math.log(1+tf.math.exp(rho))\n z_sample = mu + sd * tf.random.normal(shape=(self.dim_z,))\n return z_sample, mu, sd\n \n # Sequential API decoder\n def decoder_x(self):\n layers = [tfkl.InputLayer(input_shape=self.dim_z)]\n layers.append(tfkl.Dense(7*7*32, activation=None))\n layers.append(tfkl.Reshape((7,7,32)))\n layers.append(tfkl.Conv2DTranspose(filters=64, kernel_size=3, strides=2, \n padding='same', activation='relu'))\n layers.append(tfkl.Conv2DTranspose(filters=32, kernel_size=3, strides=2, \n padding='same', activation='relu'))\n layers.append(tfkl.Conv2DTranspose(filters=1, kernel_size=3, strides=1, \n padding='same'))\n return tfk.Sequential(layers, name='decoder')\n \n def call(self, x_input):\n z_sample, mu, sd = self.encode(x_input)\n kl_divergence = tf.math.reduce_mean(- 0.5 * \n tf.math.reduce_sum(1+tf.math.log(\n tf.math.square(sd))-tf.math.square(mu)-tf.math.square(sd), axis=1))\n x_logits = self.decoder(z_sample)\n # VAE_MNIST is inherited from tfk.Model, thus have class method add_loss()\n self.add_loss(self.kl_weight * kl_divergence)\n return x_logits\n \n# custom loss function with tf.nn.sigmoid_cross_entropy_with_logits\ndef custom_sigmoid_cross_entropy_loss_with_logits(x_true, x_recons_logits):\n raw_cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=x_true, logits=x_recons_logits)\n neg_log_likelihood = tf.math.reduce_sum(raw_cross_entropy, axis=[1, 2, 3])\n return tf.math.reduce_mean(neg_log_likelihood)\n\n \n#################### The following code shows how to train the model ####################\n# set hyperparameters\nepochs = 10\nbatch_size = 32\nlr = 0.0001\nlatent_dim=16\nkl_w=3\n# compile and train tfk.Model\nvae = VAE_MNIST(dim_z=latent_dim, kl_weight=kl_w)\nvae.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr), \n loss=custom_sigmoid_cross_entropy_loss_with_logits)\n \ntrain_history = vae.fit(x=train_images, y=train_images, batch_size=batch_size, epochs=epochs, \n verbose=1, validation_data=(test_images, test_images), shuffle=True)\n\n\n\n\n##################\n# version f (No Keras)\n##################\nclass Sampler_Z(tfk.layers.Layer):\n \n def call(self, inputs):\n mu, rho = inputs\n sd = tf.math.log(1+tf.math.exp(rho))\n batch_size = tf.shape(mu)[0]\n dim_z = tf.shape(mu)[1]\n z_sample = mu + sd * tf.random.normal(shape=(batch_size, dim_z))\n return z_sample, sd\n\nclass Encoder_Z(tfk.layers.Layer):\n \n def __init__(self, dim_z, name=\"encoder\", **kwargs):\n super(Encoder_Z, self).__init__(name=name, **kwargs)\n self.dim_x = (28, 28, 1)\n self.dim_z = dim_z\n self.conv_layer_1 = tfkl.Conv2D(filters=32, kernel_size=3, strides=(2,2), \n padding='valid', activation='relu')\n self.conv_layer_2 = tfkl.Conv2D(filters=64, kernel_size=3, strides=(2,2), \n padding='valid', activation='relu')\n self.flatten_layer = tfkl.Flatten()\n self.dense_mean = tfkl.Dense(self.dim_z, activation=None, name='z_mean')\n self.dense_raw_stddev = tfkl.Dense(self.dim_z, activation=None, name='z_raw_stddev')\n self.sampler_z = Sampler_Z()\n \n # Functional\n def call(self, x_input):\n z = self.conv_layer_1(x_input)\n z = self.conv_layer_2(z)\n z = self.flatten_layer(z)\n mu = self.dense_mean(z)\n rho = self.dense_raw_stddev(z)\n z_sample, sd = self.sampler_z((mu,rho))\n return z_sample, mu, sd\n \nclass Decoder_X(tfk.layers.Layer):\n \n def __init__(self, dim_z, name=\"decoder\", **kwargs):\n super(Decoder_X, self).__init__(name=name, **kwargs)\n self.dim_z = dim_z\n self.dense_z_input = tfkl.Dense(7*7*32, activation=None)\n self.reshape_layer = tfkl.Reshape((7,7,32))\n self.conv_transpose_layer_1 = tfkl.Conv2DTranspose(filters=64, kernel_size=3, strides=2, \n padding='same', activation='relu')\n self.conv_transpose_layer_2 = tfkl.Conv2DTranspose(filters=32, kernel_size=3, strides=2, \n padding='same', activation='relu')\n self.conv_transpose_layer_3 = tfkl.Conv2DTranspose(filters=1, kernel_size=3, strides=1, \n padding='same')\n \n # Functional\n def call(self, z):\n x_output = self.dense_z_input(z)\n x_output = self.reshape_layer(x_output)\n x_output = self.conv_transpose_layer_1(x_output)\n x_output = self.conv_transpose_layer_2(x_output)\n x_output = self.conv_transpose_layer_3(x_output)\n return x_output\n \nclass VAE_MNIST(tfk.Model):\n \n def __init__(self, dim_z, learning_rate, kl_weight=1, name=\"autoencoder\", **kwargs):\n super(VAE_MNIST, self).__init__(name=name, **kwargs)\n self.dim_x = (28, 28, 1)\n self.dim_z = dim_z\n self.learning_rate = learning_rate\n self.encoder = Encoder_Z(dim_z=self.dim_z)\n self.decoder = Decoder_X(dim_z=self.dim_z)\n self.kl_weight = kl_weight\n \n # def encode_and_decode(self, x_input):\n def call(self, x_input):\n z_sample, mu, sd = self.encoder(x_input)\n x_recons_logits = self.decoder(z_sample)\n \n kl_divergence = - 0.5 * tf.math.reduce_sum(1+tf.math.log(\n tf.math.square(sd))-tf.math.square(mu)-tf.math.square(sd), axis=1)\n kl_divergence = tf.math.reduce_mean(kl_divergence)\n # self.add_loss(lambda: self.kl_weight * kl_divergence)\n self.add_loss(self.kl_weight * kl_divergence)\n return x_recons_logits\n \n \n# vae loss function -- only the negative log-likelihood part, \n# since we use add_loss for the KL divergence part\ndef partial_vae_loss(x_true, model):\n # x_recons_logits = model.encode_and_decode(x_true)\n x_recons_logits = model(x_true)\n # compute cross entropy loss for each dimension of every datapoint\n raw_cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=x_true, logits=x_recons_logits)\n neg_log_likelihood = tf.math.reduce_sum(raw_cross_entropy, axis=[1, 2, 3])\n return tf.math.reduce_mean(neg_log_likelihood)\n\n@tf.function\ndef train_step(x_true, model, optimizer, loss_metric):\n with tf.GradientTape() as tape:\n neg_log_lik = partial_vae_loss(x_true, model)\n # kl_loss = model.losses[-1]\n kl_loss = tf.math.reduce_sum(model.losses) # vae.losses is a list\n total_vae_loss = neg_log_lik + kl_loss\n gradients = tape.gradient(total_vae_loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n loss_metric(total_vae_loss)\n \n#################### The following code shows how to train the model ####################\n# set hyperparameters\ntrain_size = 60000\nbatch_size = 64\ntest_size = 10000\nlatent_dim=16\nlr = 0.0005\nkl_w = 3\nepochs = 10\nnum_examples_to_generate = 16\ntrain_dataset = (tf.data.Dataset.from_tensor_slices(train_images)\n .shuffle(train_size).batch(batch_size))\ntest_dataset = (tf.data.Dataset.from_tensor_slices(test_images)\n .shuffle(test_size).batch(batch_size))\n# model training\nvae = VAE_MNIST(dim_z=latent_dim, learning_rate=lr, analytic_kl=True, kl_weight=kl_w)\nloss_metric = tf.keras.metrics.Mean()\nopt = tfk.optimizers.Adam(vae.learning_rate)\n\nfor epoch in range(epochs):\n start_time = time.time()\n for train_x in tqdm(train_dataset):\n train_step(train_x, vae, opt, loss_metric)\n end_time = time.time()\n elbo = -loss_metric.result()\n #display.clear_output(wait=False)\n print('Epoch: {}, Train set ELBO: {}, time elapse for current epoch: {}'.format(\n epoch, elbo, end_time - start_time))\n generate_images(vae, test_sample)","sub_path":"beta-vae/archive/vae_6_ways.py","file_name":"vae_6_ways.py","file_ext":"py","file_size_in_byte":19061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"133818849","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ContainerServiceServicePrincipalProfile(Model):\n \"\"\"Information about a service principal identity for the cluster to use for\n manipulating Azure APIs. Either secret or keyVaultSecretRef must be\n specified.\n\n All required parameters must be populated in order to send to Azure.\n\n :param client_id: Required. The ID for the service principal.\n :type client_id: str\n :param secret: The secret password associated with the service principal\n in plain text.\n :type secret: str\n :param key_vault_secret_ref: Reference to a secret stored in Azure Key\n Vault.\n :type key_vault_secret_ref:\n ~azure.mgmt.containerservice.models.KeyVaultSecretRef\n \"\"\"\n\n _validation = {\n 'client_id': {'required': True},\n }\n\n _attribute_map = {\n 'client_id': {'key': 'clientId', 'type': 'str'},\n 'secret': {'key': 'secret', 'type': 'str'},\n 'key_vault_secret_ref': {'key': 'keyVaultSecretRef', 'type': 'KeyVaultSecretRef'},\n }\n\n def __init__(self, **kwargs):\n super(ContainerServiceServicePrincipalProfile, self).__init__(**kwargs)\n self.client_id = kwargs.get('client_id', None)\n self.secret = kwargs.get('secret', None)\n self.key_vault_secret_ref = kwargs.get('key_vault_secret_ref', None)\n","sub_path":"src/aks-preview/azext_aks_preview/vendored_sdks/azure_mgmt_aks/models/container_service_service_principal_profile.py","file_name":"container_service_service_principal_profile.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"630461539","text":"#import the modules\nimport time\nfrom SimpleCV import Image\nfrom SimpleCV import Color\n\ncar_in_lot = Image(\"parking-car.png\")\ncar_not_in_lot = Image(\"parking-no-car.png\")\n\ncar = car_in_lot.crop(470,200,200,200)\nwin = car.show()\ntime.sleep(1)\nwin.quit()\n\nyellow_car = car.colorDistance(Color.YELLOW)\nwin = yellow_car.show()\ntime.sleep(1)\nwin.quit()\n\nonly_car = car - yellow_car\nwin = only_car.show()\ntime.sleep(1)\nwin.quit()\n\nprint('resultados primera comparacion:')\nR = only_car.meanColor()[2]\nprint('R: ' + str(R))\nG = only_car.meanColor()[1]\nprint('G: ' + str(G))\nB = only_car.meanColor()[0]\nprint('B: ' + str(B))\n\ncar_not_in_lot = Image(\"parking-no-car.png\")\nno_car = car_not_in_lot.crop(470,200,200,200)\n\nyellow_car = no_car.colorDistance(Color.YELLOW)\nwin = yellow_car.show()\ntime.sleep(1)\nwin.quit()\n\nonly_car = car - yellow_car\nprint('resultados segunda comparacion:')\nR = only_car.meanColor()[2]\nprint('R: ' + str(R))\nG = only_car.meanColor()[1]\nprint('G: ' + str(G))\nB = only_car.meanColor()[0]\nprint('B: ' + str(B))\n\nif (R > 15 and G > 10):\n print('Car is in the lot!!')\nelse:\n print('Car is not in the lot!!')\n","sub_path":"detect_object.py","file_name":"detect_object.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"22586892","text":"import os\r\n\r\nfrom nltk import SnowballStemmer\r\nimport codecs\r\nfrom unicodedata import normalize\r\n\r\n\r\ndef remove_accents(txt):\r\n return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII')\r\n\r\n\r\nst = SnowballStemmer('portuguese')\r\ns = codecs.open('keys.txt', 'r', encoding='latin-1')\r\nword = s.read()\r\nspace = \" \";\r\npalavras = word.split()\r\ns.close()\r\n\r\nos.remove('keys.txt')\r\n\r\nfor i in palavras:\r\n word = st.stem(i)\r\n with codecs.open('keys.txt', 'a+', encoding='latin-1') as f:\r\n f.write(word)\r\n f.write(space)","sub_path":"Stemmer.py","file_name":"Stemmer.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"197356952","text":"import numpy as np\nfrom jr.stats import circ_mean, circ_std\n\n\ndef cardinality(angles):\n return 4 * np.abs((angles / np.pi) % 1 - .5) - 1\n\n\ndef ambiguity(angles):\n return np.abs(cardinality(angles))\n\n\ndef prior(y, regressor, past):\n mean = np.mean if regressor is not 'angles' else circ_mean\n return _meanstd_prior(y, regressor, past, mean)\n\n\ndef prior_precision(y, regressor, past):\n std = np.std if regressor is not 'angles' else circ_std\n return _meanstd_prior(y, regressor, past, std)\n\n\ndef _meanstd_prior(y, regressor, past, f):\n y_prior = np.nan * np.zeros_like(y)\n for ii in range(1, y.shape[1]):\n this_range = range(ii - past, ii) if past is not None else range(ii)\n y_prior[:, ii] = f(y[:, this_range], axis=1)\n return y_prior\n\n\ndef prediction_error(y, regressor, past):\n return np.abs(signed_prediction_error(y, regressor, past))\n\n\ndef signed_prediction_error(y, regressor, past):\n y_prior = prior(y, regressor, past)\n spe = y - y_prior\n if regressor is 'angles':\n spe = (spe + np.pi) % (2 * np.pi) - np.pi\n else:\n spe = spe\n return spe\n\n\ndef test_regressors():\n from numpy.testing import assert_almost_equal, assert_equal\n\n y1 = np.linspace(0, 2, 8 + 1)[:-1] * np.pi\n # cardinality\n assert_almost_equal(cardinality(y1), [1., 0, -1., 0., 1., 0., -1., 0.])\n # ambiguity\n assert_almost_equal(ambiguity(y1), [1., 0., 1., 0., 1., 0., 1., 0.])\n # prior\n y2 = (y1 - 1.) % (2 * np.pi)\n y3 = (y1 - np.pi) % (2 * np.pi)\n y4 = (y1 + np.pi) % (2 * np.pi)\n y5 = (y1 - .75 * np.pi) % (2 * np.pi)\n y6 = (y1 + (2 * (np.arange(8) % 2) - 1.)) % (2 * np.pi)\n y123 = np.vstack((y1, y2, y3, y4, y5)).T\n # -- prior first position is nan\n assert_equal(sum(np.isnan(prior(y123, 'angles', 1)[:, 0])), 8)\n # -- prior second position is y1\n assert_almost_equal(prior(y123, 'angles', 1)[:, 1], y1)\n assert_almost_equal(prior(y123, 'angles', 1)[:, 2], y2)\n # -- prior second position with n=2 is mean y1, y2\n assert_almost_equal(prior(y123, 'angles', 2)[:, 2],\n circ_mean(y123[:, :2], axis=1))\n # prediction_error\n pe = prediction_error(y123, 'angles', 1)\n assert_almost_equal(pe[:, 1], np.ones(8))\n\n def pe(y1, y2):\n return prediction_error(np.vstack((y1, y2)).T, 'angles', 1)[:, 1]\n\n assert_almost_equal(pe(y1, y6), np.ones(8))\n assert_almost_equal(pe(y1, y3), np.ones(8) * np.pi)\n assert_almost_equal(pe(y1, y4), np.ones(8) * np.pi)\n assert_almost_equal(pe(y1, y5), np.ones(8) * .75 * np.pi)\n\n # signed prediction_error\n\n def spe(y1, y2):\n return signed_prediction_error(\n np.vstack((y1, y2)).T, 'angles', 1)[:, 1]\n\n assert_almost_equal(spe(y1, y2), -np.ones(8))\n assert_almost_equal(spe(y1, y6), [-1, 1, -1, 1, -1, 1, -1, 1])\n\n # prior_precision\n assert_almost_equal(prior_precision(y123, 'angles', 2)[:, 2],\n circ_std(y123[:, :2], axis=1))\n # TODO\n # # first item has infinite precision\n # assert_false(sum(~np.isnan(_y_prec[:, 0])))\n # # second item has precision = 1\n # assert_almost_equal(_y_prec[:, 1], np.ones(n_trials / n_pos))\n # # the mean second item always has a better precision than the\n # # mean last item\n # assert_almost_equal(y['sequ_prior_prec_angles'][y['position'] == 1],\n # np.ones(n_trials / n_pos))\n","sub_path":"regressors.py","file_name":"regressors.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"252033613","text":"from django.views.decorators.cache import cache_page\nfrom django.shortcuts import render\nfrom.models import zhilian\nfrom .db import *\n\nimport json\n\n\n@cache_page(24*3600)\ndef index(request):\n data=index_data()\n\n # 地图数据\n map_data=data[0]\n\n # 右侧上部柱状图数据\n ringt_top_data=data[1]\n\n # 右侧下部数据\n right_bottom_data=data[2]\n\n return render(request, 'myapp/index.html',context={\n 'map_data':map_data,\n 'ringt_top_data':ringt_top_data,\n 'right_bottom_data':right_bottom_data,\n })\n\n@cache_page(24*3600)\ndef detail(request,page):\n '''\n 详情页视图函数\n :param request:\n :return:\n '''\n\n # 筛选地图数据\n mapData=get_map_data(page)\n\n # 各城市职位排名\n rightTop=top100_city_data(page)\n\n # 各城市职位数所占比重\n rightBottom=to5LevelCityPie(page)\n\n # 词云\n wordCloudData=wordCloud(page)\n\n # Top5职位柱状图\n top5JobNum=getTop5JobNum(page)\n\n # 工作年限与薪资\n salary_exp=exp_salary(page)\n\n # 学历与薪资\n salary_level=level_salary(page)\n\n\n return render(request,'myapp/detail_page.html',{\n 'map_data':mapData,\n 'right_top':rightTop,\n 'right_bottom':rightBottom,\n 'word_cloud_data':wordCloudData,\n 'top5JobNum':top5JobNum,\n 'salary_exp':salary_exp,\n 'salary_level':salary_level\n })\n\n\ndef monitor(request):\n data=crawl_monitor_page()\n context={\"jobData\":data}\n return render(request,\"myapp/monitor_page.html\",context)\n\n\ndef test(request):\n keys=list()\n with open('./myapp/static/myapp/keywords.json','r',encoding='utf-8') as f:\n keys=json.loads(f.read())\n sum = 0\n for key in keys[0]['Job_keywords']:\n result = zhilian.objects(jobType__icontains=key).count()\n sum += result\n\n job_data_all = zhilian.objects.values_list('city')\n data=job_data_all.count()\n\n return render(request,'myapp/test.html')\n\n","sub_path":"myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"6948273","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import redirect, render\nfrom helper.util import *\nfrom helper.lagform import *\nfrom default.views.authen import check_login\nfrom default.config.config_menu import ScreenName\nfrom default.config.config_role import ModuleName, UserRightType\nfrom default.config.common_config import *\nfrom default.logic.userlogic import *\nfrom default.logic.testcontentlogic import *\n\n\n@check_login\ndef master(request):\n\n # check view privilege\n logging_user = LoginUser.get_login_user(request)\n\n if request.method == 'POST':\n params = request.POST\n else:\n params = request.GET\n\n course_id = params.get('course_id', '')\n if course_id and course_id.isdigit():\n course_id = int(course_id)\n else:\n course_id = -1\n level_id = params.get('level_id', '')\n if level_id and level_id.isdigit():\n level_id = int(level_id)\n else:\n level_id = -1\n\n type_form = GacoiForm('master', '/master/', 'POST')\n keu_form = LagForm()\n keu_form.set_title(\"Master\")\n type_form.set_view(\"id,name,order,updated_datetime\")\n type_form.set_key(\"id\")\n type_form.set_required('name, content')\n type_form.set_type('updated_datetime', GacoiFormFieldType.DateTime)\n # type_form.set_hidden('course_id', course_id)\n type_form.get_field('id').set_link('?course_id=[id]&tab_index=1')\n type_form.set_search('name, content')\n type_form.set_order('id,name, content,order,updated_datetime')\n type_form.set_update('name, content')\n type_form.set_insert('name, content')\n type_form.set_option_deletable(True)\n type_form.init(request)\n # data = Course.objects.all().values_list('id',flat=False)\n data = Course.objects.all()\n\n # Order\n if type_form.order_field:\n if type_form.order_type == 'desc':\n data = data.order_by(\"-\" + type_form.order_field)\n else:\n data = data.order_by(type_form.order_field)\n\n # Search user_name,login_name\n search = type_form.get_field(\"name\").get_search_value()\n if search is not None and search != '':\n data = data.filter(name__contains=search)\n\n type_form.set_form_data(data)\n # type_form.set_form_model(Course)\n type_form.set_caption([\"id,name,order,updated_datetime\",\n \"ID,Course Name,Order,Updated Datetime\"])\n\n period_form = None\n fiscal_term = None\n if type_form.is_action(GacoiFormAction.DeleteDone):\n delete_course = Course.objects.get(pk=type_form.get_key_value(\"id\"))\n delete_course.delete()\n\n elif type_form.is_action(GacoiFormAction.InsertDone):\n new_course = Course()\n new_course.name = type_form.get_field('name').get_value_blank2none()\n new_course.updated_datetime = datetime.datetime.today()\n new_course.created_datetime = datetime.datetime.today()\n course_orders = TestContentLogic.get_course_order()\n new_course_order = 1\n if len(course_orders) != 0:\n new_course_order = course_orders[len(course_orders)-1] + 1\n new_course.order = new_course_order\n new_course.save()\n elif type_form.is_action(GacoiFormAction.UpdateDone):\n update_course = Course.objects.get(pk=type_form.get_key_value(\"id\"))\n update_course.name = type_form.get_field('name').get_value_blank2none()\n update_course.updated_datetime = datetime.datetime.today()\n update_course.save()\n\n tab_index = params.get(\"tab_index\", '')\n tab_active1 = 'active'\n tab_active2 = ''\n tab_active3 = ''\n if tab_index == '1':\n tab_active2 = 'active'\n tab_active1 = ''\n tab_active3 = ''\n if tab_index == '2':\n tab_active2 = ''\n tab_active1 = ''\n tab_active3 = 'active'\n\n level_form = None\n if course_id > 0:\n try:\n fiscal_term = Course.objects.get(id=course_id)\n except ObjectDoesNotExist:\n fiscal_term = None\n level_form = GacoiForm('manage_statisticalxxx', '/master/', 'POST')\n level_form.set_view(\"id,name,order,updated_datetime\")\n level_form.set_key(\"id\")\n\n level_form.set_required('name')\n level_form.set_type('updated_datetime', GacoiFormFieldType.DateTime)\n level_form.set_type('created_datetime', GacoiFormFieldType.DateTime)\n level_form.set_hidden('course_id', course_id)\n level_form.get_field('id').set_link('?course_id={0}&level_id=[id]&tab_index=2'.format(course_id))\n level_form.set_search('name')\n level_form.set_order('id,user_name')\n level_form.set_update('name')\n level_form.set_insert('name')\n level_form.set_option_deletable(True)\n level_form.init(request)\n if level_form.is_action(GacoiFormAction.DeleteDone):\n delete_level = Level.objects.get(pk=level_form.get_key_value(\"id\"))\n delete_level.delete()\n\n elif level_form.is_action(GacoiFormAction.InsertDone):\n new_level = Level()\n new_level.name = level_form.get_field('name').get_value_blank2none()\n new_level.updated_datetime = datetime.datetime.today()\n new_level.created_datetime = datetime.datetime.today()\n new_level.course = Course.objects.get(pk=course_id)\n level_orders = TestContentLogic.get_level_order(course_id)\n new_level_order = 1\n if len(level_orders) != 0:\n new_level_order = level_orders[len(level_orders) - 1] + 1\n new_level.order = new_level_order\n new_level.save()\n\n elif level_form.is_action(GacoiFormAction.UpdateDone):\n update_level = Level.objects.get(pk=level_form.get_key_value(\"id\"))\n update_level.name = level_form.get_field('name').get_value_blank2none()\n update_level.updated_datetime = datetime.datetime.today()\n update_level.save()\n # data = Level.objects.filter(course_id=course_id).values_list('id',flat=False)\n data = Level.objects.filter(course_id=course_id)\n\n if level_form.order_field:\n if level_form.order_type == 'desc':\n data = data.order_by(\"-\" + level_form.order_field)\n else:\n data = data.order_by(level_form.order_field)\n\n # Search user_name,login_name\n search = level_form.get_field(\"name\").get_search_value()\n if search is not None and search != '':\n data = data.filter(name__contains=search)\n level_form.set_form_data(data)\n # level_form.set_form_model(Level)\n level_form.set_caption([\"id,name,order,updated_datetime\",\n \"ID,Level Name,Order,Updated Datetime\"])\n\n level_form.set_form_data(data)\n tab_active2 = 'active'\n tab_active3 = ''\n tab_active1 = ''\n\n level = None\n lesson_form = None\n if level_id > 0:\n try:\n level = Level.objects.get(id=level_id)\n except ObjectDoesNotExist:\n level = None\n lesson_form = GacoiForm('manage_statisticalxx', '/master/', 'POST')\n lesson_form.set_view(\"id,name,order,updated_datetime\")\n lesson_form.set_key(\"id\")\n\n lesson_form.set_required('name')\n lesson_form.set_type('updated_datetime', GacoiFormFieldType.DateTime)\n lesson_form.set_type('created_datetime', GacoiFormFieldType.DateTime)\n\n lesson_form.set_hidden('level_id', level_id)\n lesson_form.set_hidden('course_id', course_id)\n lesson_form.set_search('name')\n lesson_form.set_order('id,user_name')\n lesson_form.set_update('name')\n lesson_form.set_insert('name')\n lesson_form.set_option_deletable(True)\n lesson_form.init(request)\n\n if lesson_form.is_action(GacoiFormAction.DeleteDone):\n delete_level = Lesson.objects.get(pk=lesson_form.get_key_value(\"id\"))\n delete_level.delete()\n\n elif lesson_form.is_action(GacoiFormAction.InsertDone):\n new_lesson = Lesson()\n new_lesson.name = lesson_form.get_field('name').get_value_blank2none()\n new_lesson.updated_datetime = datetime.datetime.today()\n new_lesson.created_datetime = datetime.datetime.today()\n new_lesson.level = Level.objects.get(pk=level_id)\n\n level_orders = TestContentLogic.get_lesson_order(level_id)\n new_lesson_order = 1\n if len(level_orders) != 0:\n new_lesson_order = level_orders[len(level_orders) - 1] + 1\n new_lesson.order = new_lesson_order\n new_lesson.save()\n\n elif lesson_form.is_action(GacoiFormAction.UpdateDone):\n update_lesson = Lesson.objects.get(pk=lesson_form.get_key_value(\"id\"))\n update_lesson.name = lesson_form.get_field('name').get_value_blank2none()\n update_lesson.updated_datetime = datetime.datetime.today()\n update_lesson.save()\n\n # data = Lesson.objects.filter(level_id=level_id).values_list('id',flat=False)\n data = Lesson.objects.filter(level_id=level_id)\n if lesson_form.order_field:\n if lesson_form.order_type == 'desc':\n data = data.order_by(\"-\" + lesson_form.order_field)\n else:\n data = data.order_by(lesson_form.order_field)\n\n # Search user_name,login_name\n search = lesson_form.get_field(\"name\").get_search_value()\n if search is not None and search != '':\n data = data.filter(name__contains=search)\n\n lesson_form.set_form_data(data)\n # lesson_form.set_form_model(Lesson)\n lesson_form.set_caption([\"id,name,order,updated_datetime\",\n \"ID,Lesson Name,Order,Updated Datetime\"])\n\n lesson_form.set_form_data(data)\n tab_active2 = ''\n tab_active3 = 'active'\n tab_active1 = ''\n\n\n context = {\n 'user': logging_user,\n 'screen_name': ScreenName.Master,\n 'fiscal_term': fiscal_term,\n 'term_form': type_form,\n 'period_form': level_form,\n 'lesson_form': lesson_form,\n 'level': level,\n 'tab1': tab_active1,\n 'tab2': tab_active2,\n 'tab3': tab_active3,\n }\n\n return render(request, 'master.html', context)\n","sub_path":"Source/remi/default/views/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":10236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"338019405","text":"#!/usr/bin/env python2.7\nimport re\nimport sys\nfrom collections import defaultdict\nfrom Bio import SeqIO\nimport argparse\n\nfrom utils.cigar import expandCigar, compressCigar\n\n\ndef modifyCig(cig):\n \"\"\"\n convert all leading and trailing I and D's into M. \n the parseClusteringOut has does not distinguish and \n will blindly fill all + - in with some type of base.\n For now, we will just make all Is and Ds int Ms \n \"\"\"\n cig = list(cig)\n for idx in xrange(len(cig)):\n if cig[idx] == 'M':\n break\n cig[idx] = 'M'\n #print \"\".join(cig)\n cig = cig[::-1]\n for idx in xrange(len(cig)):\n if cig[idx] == 'M':\n break\n cig[idx] = 'M'\n cig = cig[::-1]\n #print \"\".join(cig)\n return \"\".join(cig) \n\n\ndef updateCigar(child, childstrand, newcentroid, centroidstrand, iterNum, newCigar, seqConsCigar, outputfile, singlestr = \"\"):\n process = [ [iterNum, child, s, idx, False, newCigar, False if(childstrand != '-') else True, newcentroid,] for idx, s in enumerate(seqConsCigar[iterNum][child])]\n while process:\n iNum, ident, info, idx, isNewCentroid, newCigar, isreverse, newparent = process.pop(0)\n if info[0] == newparent:\n continue\n myCigar = info[1]\n orignewcig = newCigar \n if isreverse:\n myCigar = info[1][::-1]\n posCigar = 0\n posRef = 0\n posRead = 0\n newCig = \"\"\n while posRef < len(newCigar) and posRead < len(myCigar):\n if newCigar[posRef] == 'I':\n newCig += 'I'\n posRef += 1\n elif newCigar[posRef] == 'D':\n # if we come across a 'D' in the new cigar, we need to keep it\n newCig += 'D'\n posRef += 1\n elif myCigar[posRead] == 'I':\n newCig += 'I'\n posRead += 1\n posRef += 1\n else: \n newCig += 'M'\n posRef += 1\n posRead += 1\n while posRef < len(newCigar):\n newCig += \"I\"\n posRef += 1\n if isreverse and not isNewCentroid:\n if seqConsCigar[iNum][ident][idx][2] == '+':\n seqConsCigar[iNum][ident][idx][2] = '-'\n info[2] = '-'\n else:\n seqConsCigar[iNum][ident][idx][2] = '+'\n info[2] = '+'\n\n seqConsCigar[iNum][ident][idx][3] = '+'\n info[3] = '+'\n seqConsCigar[iNum][ident][idx][1] = newCig\n\n print >> outputfile, \"%s\\t%s\\t%s\\t%s\\t%s\\t*\"%(info[0], newparent, compressCigar(newCig), info[2], info[3])\n info[1] = newCig\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-i1', '--input1', required = True, help = \"output of muso _1\" )\n parser.add_argument('-i2', '--input2', required = True, help = \"output of muso _2\" )\n parser.add_argument('-o', '--output', required = True, help = \"output file\")\n args = parser.parse_args()\n seqConsCigar = {}\n\n iterNum = 0\n fileName = args.input1\n seqConsCigar[iterNum] = defaultdict(list)\n for line in open(fileName, 'r'):\n # each line is:: s1 s2 cigar strand_s1 strand_s2\n data = line.strip().split()\n seqConsCigar[iterNum][data[1]].append([data[0], expandCigar(data[2]), data[3], data[4]])\n\n iterNum = 1\n fileName = args.input2\n\n with open(args.output, \"w\") as o:\n seqConsCigar[iterNum] = defaultdict(list)\n for line in open(fileName, 'r'):\n # each line is:: s1 s2 cigar strand_s1 strand_s2\n data = line.strip().split()\n if seqConsCigar[iterNum-1].has_key(data[0]): # we are intersted in the sequence that hit against the new centroid\n updateCigar(data[0], data[3], data[1], data[4], iterNum-1, expandCigar(data[2]), seqConsCigar, o) \n","sub_path":"scripts/trackOverlaps.py","file_name":"trackOverlaps.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"65968200","text":"# -*- coding: UTF-8 -*-\n\n'''\nCreated on 5 de dez de 2015\n URI Online Judge \n Acima da Média - 1214\n\nSabe-se que 90% dos calouros tem sempre a expectativa de serem acima da média no início de \nsuas graduações. Você deve checar a realidade para ver se isso procede.\n\nEntrada\n\nA entrada contém muitos casos de teste. A primeira linha da entrada contém um inteiro C, \nindicando o número de casos de teste. Seguem C casos de teste ou instâncias. Cada caso de \nteste inicia com um inteiro N, que é o número de pessoas de uma turma (1 ≤ N ≤ 1000). Seguem \nN inteiros, separados por espaços, cada um indicando a média final (um inteiro entre 0 e 100) \nde cada um dos estudantes desta turma.\n\nSaída\n\nPara cada caso de teste imprima uma linha dando o percentual de estudantes que estão acima da \nmédia da turma, com o valor arredondado e com 3 casas decimais.\n\n\n@author: Gilvonaldo\n'''\n# Número de casos de testes\nC = int(input())\n\nN = \"\"\ncont = 0\nresult = 0\nacimaDaMedia = 0\nfor i in range(C):\n # Número de pessoas de uma turma\n N = input()\n for i in N:\n if N[cont] != ' ': \n result += int(N[cont])\n #cont+=cont\n cont+=cont\n \n if int([i]) >= 70:\n acimaDaMedia += acimaDaMedia\n \n print(len(N) * acimaDaMedia / 100)\n\n\n\n\n\n","sub_path":"POP_EXEMPLOS/nivel2/AcimaDaMedia.py","file_name":"AcimaDaMedia.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"519011992","text":"import numpy as np\n\nfrom my_objects import Vertex\n\n\ndef scale(vertices):\n max = 0\n scaled_vertices = []\n\n for vertex in vertices:\n for coordinate in vertex.as_array():\n if coordinate > max:\n max = coordinate\n\n m = np.matrix([[1 / max, 0, 0, 0],\n [0, 1 / max, 0, 0],\n [0, 0, 1 / max, 0],\n [0, 0, 0, 1]\n ])\n\n for v in vertices:\n res = np.dot(m, np.transpose(v.as_array()))\n v_list = np.asarray(res.T).flatten().tolist()\n scaled_vertices.append(Vertex(v_list))\n\n return scaled_vertices\n\n\ndef move_to_center(vertices):\n [xmin, ymin, zmin,_] = [xmax, ymax, zmax,_] = vertices[0].as_array()\n\n for v in vertices:\n if v.x > xmax: xmax = v.x\n if v.x < xmin: xmin = v.x\n if v.y > ymax: ymax = v.y\n if v.y < ymin: ymin = v.y\n if v.z > zmax: zmax = v.z\n if v.z < zmin: zmin = v.z\n\n center_x = (xmax + xmin) / 2\n center_y = (ymax + ymin) / 2\n center_z = (zmax + zmin) / 2\n\n translated_vertices = []\n for v in vertices:\n v.x = v.x - center_x\n v.y = v.y - center_y\n v.z = v.z - center_z\n translated_vertices.append(v)\n\n return translated_vertices\n\n\ndef set_z_to_zero(vertices):\n for v in vertices: v.z = 0\n","sub_path":"icg/py/lab5/my_transformations.py","file_name":"my_transformations.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"262197579","text":"import numpy as np\r\nimport pandas as pd\r\nimport scipy.sparse as ss\r\n\r\ndef read_data_file_as_coo_matrix(filename='soc-pokec-relationships.txt'):\r\n \"Read data file and return sparse matrix in coordinate format.\"\r\n data = pd.read_csv(filename, sep='\\t', header=None, dtype=np.uint32)\r\n rows = data[0] # Not a copy, just a reference.\r\n cols = data[1]\r\n for i in range(rows.size):\r\n rows[i] = rows[i] - 1\r\n for i in range(cols.size):\r\n cols[i] = cols[i] - 1\r\n ones = np.ones(len(rows), np.uint32)\r\n matrix = ss.coo_matrix((ones, (rows, cols)))\r\n matrix = matrix.todok()\r\n for i in range(1632803):\r\n matrix[i,i] = 1\r\n matrix = matrix.tocoo()\r\n return matrix\r\n\r\n\r\n\r\ndef save_csr_matrix(filename, matrix):\r\n \"\"\"Save compressed sparse row (csr) matrix to file.\r\n\r\n Based on http://stackoverflow.com/a/8980156/232571\r\n\r\n \"\"\"\r\n assert filename.endswith('.npz')\r\n attributes = {\r\n 'data': matrix.data,\r\n 'indices': matrix.indices,\r\n 'indptr': matrix.indptr,\r\n 'shape': matrix.shape,\r\n }\r\n np.savez(filename, **attributes)\r\n \r\ndef load_csr_matrix(filename):\r\n \"\"\"Load compressed sparse row (csr) matrix from file.\r\n\r\n Based on http://stackoverflow.com/a/8980156/232571\r\n\r\n \"\"\"\r\n assert filename.endswith('.npz')\r\n loader = np.load(filename)\r\n args = (loader['data'], loader['indices'], loader['indptr'])\r\n matrix = ss.csr_matrix(args, shape=loader['shape'])\r\n return matrix\r\n\r\ndef test():\r\n \"Test data file parsing and matrix serialization.\"\r\n coo_matrix = read_data_file_as_coo_matrix()\r\n csr_matrix = coo_matrix.tocsr()\r\n save_csr_matrix('edges.npz', csr_matrix)\r\n loaded_csr_matrix = load_csr_matrix('edges.npz')\r\n # Comparison based on http://stackoverflow.com/a/30685839/232571\r\n #assert (csr_matrix != loaded_csr_matrix).nnz == 0\r\n\r\nif __name__ == '__main__':\r\n test()\r\n","sub_path":"csr.py","file_name":"csr.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"235713753","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 22 17:05:50 2019\r\n\r\n@author: MG\r\n\"\"\"\r\n\r\nimport os\r\nfrom PyQt5.QtGui import QPixmap, QColor, QImage\r\nfrom PyQt5 import QtCore\r\nfrom numpy import *\r\nimport numpy as np\r\nimport xml.etree.ElementTree as ET\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib.path import Path\r\n#from PIL import Image, ImageDraw\r\n\r\n\"\"\"Class Image_Converter \r\nConverts Slic3r SVG file into stack of images \r\nrepresenting each layer of STL/CAD model to print\r\n\"\"\"\r\n\r\nclass Image_Converter():\r\n def __init__(self):\r\n super().__init__()\r\n \r\n self.file_type =0 # 0 no file , 1 svg file type, for later more than 1 file type.\r\n self.file_path =''\r\n self.image_height = 0\r\n self.image_width =0\r\n self.dpiY = 185\r\n self.dpiX = 329 # 77 microns in X axis motion\r\n self.layers = []\r\n self.bedpreview = []\r\n self.layers_data = []\r\n self.layer_info = []\r\n \r\n def setdpiX(self,dpX):\r\n self.dpiX = dpX\r\n def setdpiY(self,dpY):\r\n self.dpiY = dpY\r\n def openfile(self,temp_file_path):\r\n \"try to open a file if success return 1 , if fail return 0\"\r\n temp_success =0 # if file is successfully opened or not , 0 not 1 opened\r\n self.layers =[]\r\n self.layers_data =[]\r\n if(str(temp_file_path)==\"\"):\r\n self.file_type =0\r\n print(\"File Directory is not given\")\r\n return 0;\r\n if(os.path.exists(str(temp_file_path)) ==False):\r\n print(\"The File directory doesn't exist\")\r\n return 0;\r\n else:\r\n self.file_path = temp_file_path\r\n filename,file_extension = os.path.splitext(temp_file_path)\r\n if(file_extension.lower() != \".svg\"):\r\n print(\"File type/extension is not compatible NOT an SVG File from Slic3r Program\")\r\n return 0\r\n \r\n if(file_extension.lower() == \".svg\"):\r\n self.file_type =1\r\n try:\r\n with open(self.file_path) as file_object:\r\n self.vector_file = file_object.read()\r\n temp_success =1\r\n except:\r\n nothing =0\r\n if(temp_success ==1):\r\n print(\"file opened\")\r\n # print(self.vector_file)\r\n self.SVG2data(self.file_path)\r\n return 1\r\n #self.SVG_getdata()\r\n \r\n def get_model_layers(self):\r\n return self.layers\r\n \r\n def get_model_layers_numb(self):\r\n return len(self.layers)\r\n \r\n def Bed_image(self):\r\n bed_height = math.floor(150 * (self.dpiX/25.4)) #150mm * 200 dpi/25.4 inch>mm\r\n bed_width = math.floor(150 * (self.dpiY/25.4))\r\n bed_image = zeros((bed_height,bed_width))\r\n return bed_image\r\n \r\n def SVG2data(self,filename):\r\n et = ET.ElementTree(file = filename)\r\n self.height = float(et.getroot().get('height'))\r\n self.width = float(et.getroot().get('width'))\r\n # self.height = int((self.height)* (self.dpi/25.4)) +1\r\n # self.width = int((self.width)* (self.dpi/25.4)) +1\r\n self.height = int((self.height)* (self.dpiY/25.4)) +1 # was 360/25.4\r\n if(self.height % 128 !=0):\r\n print(\"height0 %d\",(self.height))\r\n self.height = 128 * math.ceil(self.height/128)\r\n print(\"height %d\",(self.height))\r\n # self.width = int((self.width)* (339/25.4)) +1 #old resolution = 185 , adjust dpi in polygonarray as well\r\n self.width = math.ceil((self.width)* (self.dpiX/25.4)) #was 339/25.4\r\n self.image_height = self.height\r\n self.image_width = self.width\r\n image = zeros((self.height,self.width) )\r\n \r\n print(self.height,self.width)\r\n total_layers = 0\r\n #print( len(et.getroot()[1]))\r\n for i in et.findall(\"{http://www.w3.org/2000/svg}g\"):\r\n total_layers= total_layers+1\r\n print(total_layers)\r\n \r\n # image0 = zeros(self.image_height,self.image_width)\r\n for j in range(0,total_layers-1): #total_layers\r\n imagex = zeros((self.height,self.width) )\r\n total_bedpreview = []\r\n self.layer_info = []\r\n # imagex =self.Bed_image()\r\n for i in range(0,len(et.getroot()[j])):\r\n first_g = et.getroot()[j][i].get('points')\r\n \r\n first_g =first_g.replace(' ',',')\r\n first_g2 = np.fromstring(first_g,sep=',').reshape(-1,2)\r\n total_bedpreview.extend(first_g2)\r\n imagex =imagex +self.polygon2img(imagex,first_g2)\r\n# \r\n \r\n #imagex = zeros((self.height,self.width) )\r\n #imagex =self.polygon2img(imagex,first_g2)\r\n \r\n #bed_image = bed_image + imagex\r\n self.layers_data.append(self.layer_info)\r\n \r\n self.bedpreview.append(total_bedpreview)\r\n self.layers.append(imagex)\r\n \r\n #self.showlayers(self.layers)\r\n #print(len(self.layers)) \r\n print((self.bedpreview[0][0][0]))\r\n \r\n def polygon2img(self,img,polygonarraypoints):\r\n nr, nc = img.shape\r\n ygrid, xgrid = np.mgrid[:nr, :nc]\r\n xypix = np.vstack((xgrid.ravel(), ygrid.ravel())).T\r\n # print(xypix)\r\n # polygonarraypoints = polygonarraypoints * (self.dpi/25.4)\r\n self.layer_info.append(polygonarraypoints.astype(int))\r\n polygonarraypoints[:,0] = polygonarraypoints[:,0] * (self.dpiX/25.4) #was 339/25.4\r\n \r\n polygonarraypoints[:,1] = polygonarraypoints[:,1] * (self.dpiY/25.4) #was 360/25.4\r\n #self.layer_info.append(polygonarraypoints.astype(int))\r\n \r\n #print(polygonarraypoints)\r\n pth = Path(polygonarraypoints)\r\n mask = pth.contains_points(xypix)\r\n mask = mask.reshape(img.shape)\r\n return mask\r\n \r\n \r\n def showlayers(self,layers):\r\n for l in range(len(layers)):\r\n \r\n data = layers[l]\r\n #print(data)\r\n \r\n #plt.ion()\r\n #plt.figure()\r\n plt.imshow(data, cmap=plt.cm.gray) #interpolation='nearest'\r\n plt.show()\r\n # input(\"press any key to continue\")\r\n # plt.close()\r\n def img_getheight(self):\r\n return self.image_height\r\n \r\n def img_getWidth(self):\r\n return self.image_width\r\n \r\n def getlayer(self,layer_required):\r\n if(len(self.layers) <1):\r\n return (\"no layers were found\")\r\n else:\r\n return self.layers[layer_required]\r\n \r\n def getlayer_data(self,layerinfo_required):\r\n if(len(self.layers_data) <1):\r\n return (\"no layers were found\")\r\n else:\r\n return self.layers_data[layerinfo_required]\r\n \r\n# if __name__.endswith('__main__'):\r\n # im = Image_Converter()\r\n # # ret = im.openfile('../../../ExampleSVGfiles\\sphere.svg')\r\n \r\n # ret = im.openfile(r'C:\\Users\\Jimmy\\Desktop\\3D Printing research\\Silcers\\Slic3r\\STL SAMPLES\\spheresmaller5x.svg')\r\n # print(ret)\r\n # #print(im.Bed_image())\r\n # im.showlayers(im.get_model_layers() )\r\n # #test = im.getlayer(10)\r\n ","sub_path":"subfolder/Image_Converter.py","file_name":"Image_Converter.py","file_ext":"py","file_size_in_byte":7279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"624184473","text":"from django.shortcuts import render,redirect\nfrom .forms import RegistrationForm\nfrom .models import RegistrationData\nimport time\nimport requests\nfrom requests.compat import quote_plus\nfrom bs4 import BeautifulSoup\n\n# Create your views here.\n\n\ndef home(request):\n\n return render(request, 'base.html')\n\ndef download_page(request):\n\n select1 = request.POST.get('search1')\n print(select1)\n\n context = {\n 'form':RegistrationForm,\n 'search1':select1,\n\n\n\n }\n\n return render(request, 'download page.html',context)\n\ndef addUser(request):\n register = RegistrationForm(request.POST)\n\n if register.is_valid():\n myregister = RegistrationData(full_name = register.cleaned_data['full_name'],\n password=register.cleaned_data['password'],\n Email=register.cleaned_data['Email'],\n Phone_number=register.cleaned_data['phone_number'],\n name_of_subject=register.cleaned_data['name_of_subject'],\n )\n myregister.save()\n\n\n return redirect('interjection page')\n\ndef interjection_page(request):\n import time\n import sys\n hey =\"verifing payment:\"\n print(hey)\n\n # animation = [\"10%\", \"20%\", \"30%\", \"40%\", \"50%\", \"60%\", \"70%\", \"80%\", \"90%\", \"100%\"]\n animation = [\"[■□□□□□□□□□]\", \"[■■□□□□□□□□]\", \"[■■■□□□□□□□]\", \"[■■■■□□□□□□]\", \"[■■■■■□□□□□]\", \"[■■■■■■□□□□]\",\n \"[■■■■■■■□□□]\", \"[■■■■■■■■□□]\", \"[■■■■■■■■■□]\", \"[■■■■■■■■■■]\"]\n\n for i in range(len(animation)):\n time.sleep(60)\n sys.stdout.write(\"\\r\" + animation[i % len(animation)])\n sys.stdout.flush()\n\n print(\"\\n\")\n\n select1 = request.POST.get('search1')\n print(select1)\n\n\n context = {\n 'search1': select1,\n 'heyyo':hey\n\n }\n\n return render(request, 'interjection page.html',context)\n\n\n\n","sub_path":"favflamz_pdf/pdf_website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"308355157","text":"import sys\n# 1. 각 위치별로 양 끝점으로 갈때의 min, max값 구함\n# 2. 각 점의 min, max에 대해 max값을 구하면 min에 대한 max값은 min, max에 대한 max값은 max\ndef main():\n num_test_case = int(sys.stdin.readline())\n min_times = []\n max_times = []\n for i in range(num_test_case):\n l,n = map(int, sys.stdin.readline().split())\n k = [int(sys.stdin.readline()) for _ in range(n)]\n \n mintime=0\n maxtime=0\n for i in range(n):\n mini = min(k[i],l-k[i])\n maxi = max(k[i],l-k[i])\n\n mintime = max(mintime, mini)\n maxtime = max(maxtime, maxi)\n \n min_times.append(mintime)\n max_times.append(maxtime)\n\n for i in range(num_test_case):\n print(min_times[i], max_times[i])\n\nmain()","sub_path":"algorithm/Baekjoon/단계별로 풀어보기2/.ipynb_checkpoints/개미(4307)-checkpoint.py","file_name":"개미(4307)-checkpoint.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"204139411","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 22 20:37:42 2021\n\n@author: IRDC Lab\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport classifier_utils as ut\n\n\n\n########## Data Simulation ##############\ndata_1_array,data_2_array = ut.data_2_class_simulation(\nclass_1 = (-4,3),class_2 = (3,-4),\nclass_1_var = 3,class_2_var = 3,\ndata_1_count = 40, data_2_count = 55)\n\n########## Data Simulation ##############\ndata_3_array,data_4_array = ut.data_2_class_simulation(\nclass_1 = (-4,-5),class_2 = (3,4),\nclass_1_var = 3,class_2_var = 2,\ndata_1_count = 40, data_2_count = 55)\n########## Data Simulation Ends ##############\n########## Data Simulation Ends ##############\n\n\nx1_ax =np.arange(-7,8,1)\n#print(x2)\n\nplt.figure(2, figsize=(8, 8))\n\nplt.scatter(data_1_array[0,:],data_1_array[1,:], c=\"r\", marker ='^',\n cmap=plt.cm.Set1, edgecolor='k')\nplt.scatter(data_2_array[0,:],data_2_array[1,:], c=\"g\", marker ='o', \n cmap=plt.cm.Set1, edgecolor='k')\n\nplt.scatter(data_3_array[0,:],data_3_array[1,:], c=\"b\", marker =',', \n cmap=plt.cm.Set1, edgecolor='k')\nplt.scatter(data_4_array[0,:],data_4_array[1,:], c=\"y\", marker ='<',\n cmap=plt.cm.Set1, edgecolor='k')\n\n\n\n\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.legend([\"class 1\",\"class 2\",\"class 3\", \"class 4\"])\nplt.title(\"Multi Classes Data\" )\n\n\n#x_min, x_max = min(x1) - 1, max(x1) + 1\n#y_min, y_max = min(x2) - 1, max(x2) + 1\n\nplt.xlim(-7, 7)\nplt.ylim(-7, 7)\n\nplt.xticks((x1_ax))\nplt.yticks((x1_ax))\nplt.grid()\nplt.show()\n\n#print(\"hyper-line Equation y=mx +c, where m is {} & c is {}\".format(slope_of_hyper_line,ch))\n\n\n\n","sub_path":"data_classifier_02_multi_class_data.py","file_name":"data_classifier_02_multi_class_data.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"8985399","text":"# The MIT License\n#\n# Copyright (c) 2011 Wyss Institute at Harvard University\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# http://www.opensource.org/licenses/mit-license.php\n\n\n\"\"\"\nslicegraphicsitem.py\n\nCreated by Nick Conway on 2010-06-15.\n\"\"\"\n\nfrom exceptions import NotImplementedError\nfrom heapq import *\nfrom views.pathview.handles.activeslicehandle import ActiveSliceHandle\nfrom model.enum import LatticeType, Parity, StrandType\nfrom .slicehelix import SliceHelix\nfrom views import styles\n\nimport util\n# import Qt stuff into the module namespace with PySide, PyQt4 independence\nutil.qtWrapImport('QtCore', globals(), ['QRectF', 'QPointF', 'QEvent', 'Qt', \\\n 'pyqtSignal', 'pyqtSlot', 'QObject'])\nutil.qtWrapImport('QtGui', globals(), [ 'QGraphicsItem', 'QBrush', \\\n 'QPainterPath', 'QPen'])\n\n\nclass SliceGraphicsItem(QGraphicsItem):\n \"\"\"\n SliceGraphicsItem is an abstract class to be inherited by\n HoneycombSliceGraphicsItem or SquareSliceGraphicsItem. SliceGraphicsItem\n is the parent of all SliceHelix items, and is responsible for spawning\n and positioning them according to the part dimensions.\n \"\"\"\n radius = styles.SLICE_HELIX_RADIUS\n \n def __init__(self, part, controller=None, parent=None):\n super(SliceGraphicsItem, self).__init__()\n # data related\n self._part = None\n self.sliceController = controller\n self.parent = parent\n self.setParentItem(parent)\n self.setZValue(100)\n\n # The deselector grabs mouse events that missed a slice\n # and clears the selection when it gets one\n self.deselector = SliceGraphicsItem.Deselector(self)\n self.deselector.setParentItem(self)\n self.deselector.setFlag(QGraphicsItem.ItemStacksBehindParent)\n self.deselector.setZValue(-1)\n\n # Invariant: keys in _helixhash = range(_nrows) x range(_ncols)\n # where x is the cartesian product\n self._helixhash = {}\n self._nrows, self._ncols = 0, 0\n self._rect = QRectF(0, 0, 0, 0)\n self.setPart(part)\n\n # Cache of VHs that were active as of last call to activeSliceChanged\n # If None, all slices will be redrawn and the cache will be filled.\n self._previouslyActiveVHs = None\n # Connect destructor. This is for removing a part from scenes.\n self._part.partRemoved.connect(self.destroy)\n # end def\n\n def destroy(self):\n self._part.partRemoved.disconnect(self.destroy)\n self.scene().removeItem(self)\n self.setPart(None)\n # end def\n\n ############################ Private Methods ############################\n def _upperLeftCornerForCoords(self, row, col):\n pass # subclass\n\n def _updateGeometry(self, newCols, newRows):\n pass # subclass\n\n def _spawnSliceAt(self, row, column):\n ul = QPointF(*self._upperLeftCornerForCoords(row, column))\n helix = SliceHelix(row, column, self)\n helix.setFlag(QGraphicsItem.ItemStacksBehindParent, True)\n helix.setPos(ul)\n self._helixhash[(row, column)] = helix\n\n def _killSliceAt(row, column):\n s = self._helixhash[(row, column)]\n s.scene().removeItem(s)\n del self._helixhash[(row, column)]\n\n def _setDimensions(self, newDims):\n \"\"\"A private method used to change the number of rows,\n cols in response to a change in the dimensions of the\n part represented by the receiver\"\"\"\n newRows, newCols, ignore = newDims\n if self._nrows > newRows:\n for r in range(newRows, self._nrows):\n for c in range(self._ncols):\n self._killSliceAt(r, c)\n elif newRows > self._nrows:\n for r in range(self._nrows, newRows):\n for c in range(self._ncols):\n self._spawnSliceAt(r, c)\n self._nrows = newRows\n # We now have the right number of rows\n if self._ncols > newCols:\n for c in range(newCol, self._ncols):\n for r in range(self._nrows):\n self._killSliceAt(r, c)\n elif newCols > self._ncols:\n for c in range(self._ncols, newCols):\n for r in range(self._nrows):\n self._spawnSliceAt(r, c)\n self._ncols = newCols\n self._updateGeometry(newCols, newRows)\n self.prepareGeometryChange()\n # the Deselector copies our rect so it changes too\n self.deselector.prepareGeometryChange()\n self.zoomToFit()\n\n ############################# Public Methods #############################\n def mousePressEvent(self, event):\n # self.createOrAddBasesToVirtualHelix()\n QGraphicsItem.mousePressEvent(self, event)\n\n def boundingRect(self):\n return self._rect\n\n def paint(self, painter, option, widget=None):\n pass\n\n def zoomToFit(self):\n thescene = self.scene()\n theview = thescene.views()[0]\n theview.zoomToFit()\n\n def part(self):\n return self._part\n\n def setPart(self, newPart):\n if self._part:\n self._part.dimensionsWillChange.disconnect(self._setDimensions)\n self._part.selectionWillChange.disconnect(self.selectionWillChange)\n self._part.activeSliceWillChange.disconnect(self.activeSliceChanged)\n self._part.virtualHelixAtCoordsChanged.disconnect(self.vhAtCoordsChanged)\n if newPart != None:\n self._setDimensions(newPart.dimensions())\n newPart.dimensionsWillChange.connect(self._setDimensions)\n newPart.selectionWillChange.connect(self.selectionWillChange)\n newPart.activeSliceWillChange.connect(self.activeSliceChanged)\n newPart.virtualHelixAtCoordsChanged.connect(self.vhAtCoordsChanged)\n self._part = newPart\n\n def getSliceHelixByCoord(self, row, column):\n if (row, column) in self._helixhash:\n return self._helixhash[(row, column)]\n else:\n return None\n\n def selectionWillChange(self, newSel):\n if self.part() == None:\n return\n if self.part().selectAllBehavior():\n return\n for sh in self._helixhash.itervalues():\n sh.setSelected(sh.virtualHelix() in newSel)\n\n def activeSliceChanged(self, newActiveSliceZIndex):\n newlyActiveVHs = set()\n part = self.part()\n activeSlice = part.activeSlice()\n if self._previouslyActiveVHs:\n for vh in part.getVirtualHelices():\n isActiveNow = vh.hasBaseAt(StrandType.Scaffold, activeSlice)\n if isActiveNow != (vh in self._previouslyActiveVHs):\n self._helixhash[vh.coords()].update()\n if isActiveNow:\n newlyActiveVHs.add(vh)\n else:\n for vh in part.getVirtualHelices():\n isActiveNow = vh.hasBaseAt(StrandType.Scaffold, activeSlice)\n if isActiveNow:\n newlyActiveVHs.add(vh)\n self.update()\n\n def vhAtCoordsChanged(self, row, col):\n self._helixhash[(row, col)].update()\n\n class Deselector(QGraphicsItem):\n \"\"\"The deselector lives behind all the slices and observes mouse press\n events that miss slices, emptying the selection when they do\"\"\"\n def __init__(self, parentHGI):\n super(SliceGraphicsItem.Deselector, self).__init__()\n self.parentHGI = parentHGI\n def mousePressEvent(self, event):\n self.parentHGI.part().setSelection(())\n super(SliceGraphicsItem.Deselector, self).mousePressEvent(event)\n def boundingRect(self):\n return self.parentHGI.boundingRect()\n def paint(self, painter, option, widget=None):\n pass\n","sub_path":"views/sliceview/slicegraphicsitem.py","file_name":"slicegraphicsitem.py","file_ext":"py","file_size_in_byte":8830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"437947667","text":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.\ndf_products = pd.read_csv(\"../input/train.csv\")\ndf_products.head()\ndf_y = df_products[\"target\"]\ndf_y.head()\ndf_X = df_products.drop('id', axis=1).drop('target', axis=1)\ndf_X.head()\ndf_X.to_csv(\"train_X.csv\", header=True, index=False)\ndf_y.to_csv(\"train_y.csv\", header=True, index=False)\npd.read_csv(\"train_X.csv\")\nX = df_X.values\nX\ny = df_y.values\ny = y.reshape(-1)\nprint(\"y shape:\", y.shape)\nX.shape\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\nprint(\"X train:\", X_train.shape)\nprint(\"y train:\", y_train.shape)\nprint()\nprint(\"X test: \", X_test.shape)\nprint(\"y test: \", y_test.shape)\n\nmodel = LogisticRegression(random_state=42)\nmodel.fit(X_train, y_train)\nLogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=45, solver='liblinear', tol=0.0001, verbose=0, warm_start=False)\ny_train_pred = model.predict(X_train)\ny_test_pred = model.predict(X_test)\naccuracy_train = accuracy_score(y_train, y_train_pred)\naccuracy_test = accuracy_score(y_test, y_test_pred)\nprint(\"Training accuracy: {0:.3f}%\".format(accuracy_train * 100))\nprint(\"Test accuracy: {0:.3f}%\".format(accuracy_test * 100))\n","sub_path":"kaggle/otto-group-product-classification-challenge/script_19.py","file_name":"script_19.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"449270886","text":"# 웹 뉴스 정보로 워드 임베딩 하여 유사 단어 파악하기 \n\n\nfrom konlpy.tag import Okt \nimport pandas as pd \n\nokt = Okt()\n\n# daum news \n\nwith open('daumnews.txt', mode = 'r', encoding='utf8') as f :\n #print(f.read())\n lines = f.read().split('\\n') #줄단위로 자르기\n \n print(len(lines))\n \nwordDic = {}\n\nfor line in lines: \n datas = okt.pos(line)\n #print(datas)\n for word in datas:\n if word[1] == 'Noun': \n #print(word[0])\n #print(word[0] in wordDic)\n if not(word[0] in wordDic): # dictionry 안에 같은값이 있을경우 0\n wordDic[word[0]]= 0 \n wordDic[word[0]] += 1 \nprint(wordDic) \n\nkeys = sorted(wordDic.items(), key= lambda x:x[1], reverse=True) #단어의 갯수가 많은순부터 내림차순 정렬\nprint(keys)\n\n# df 에 담기 \n\nwordList = []\ncountList = []\n\nfor word, count in keys[:20]:\n wordList.append(word)\n countList.append(count)\n \n#print(wordList)\n#print(countList)\n\ndf = pd.DataFrame()\n\ndf['word'] = wordList\ndf['count'] = countList\n\nprint(df.head(3))\n\nprint('-------------------------------------------')\n\nresults = []\nwith open('daumnews.txt',mode='r',encoding='utf8') as fr : \n lines = fr.read().split('\\n')\n \n for line in lines:\n datas = okt.pos(line,stem = True)\n #print(datas)\n imsi = [] \n for word in datas: \n #print(word)\n if word[1] in ['Noun'] : #명사말고 제외\n imsi.append(word[0]) \n \n \n imsi2 = (\" \".join(imsi)).strip()\n results.append(imsi2)\n \n#print(results)\n\n\n#file 로 저장\nfileName = 'daumnews2.txt'\nwith open(fileName,mode='w',encoding ='utf8') as fw:\n fw.write('\\n'.join(results))\n print('저장성공')\n\n# word embeddig 중 Word2vec\n\nfrom gensim.models import word2vec\n\n#간단한 예 -----\nsentence = [['python','language','program','computer','say']]\nmodel = word2vec.Word2Vec(sentence , min_count= 1)\nprint(model.wv.most_similar('python')) # 절대 값 1 에 가까울수록 친밀\n\n\nprint()\n# 저장된 문서 daumnews2.txt 를 읽어 유사 단어 파악 \ngenObj = word2vec.LineSentence(fileName)\nprint(genObj) # word2vec.LineSentence object\nmodel = word2vec.Word2Vec(genObj, size = 100 , window = 10, min_count=2 , sg=1) # sg=1 분석방법론은 skip-Gram 사용\nprint(model)\nmodel.init_sims(replace=True) #필요 없는 메모리 해제\n\n\n# 모델 저장 후 사용 \ntry: \n model.save('daum_model.model')\n \nexcept Exception as e:\n print('err :', e)\n\n# 모델 읽기\nmodel = word2vec.Word2Vec.load('daum_model.model')\n\n#단어별 유사도 확인\nprint(model.wv.most_similar(positive='마스크'))\nprint(model.wv.most_similar(positive=['마스크'],topn=3))\nprint(model.wv.most_similar(positive=['마스크','차단'],negative=['가격']))\n\n\n\n \n\n \n \n \n \n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pandas/konelpy-wordcloud/konelpy3word.py","file_name":"konelpy3word.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"579456994","text":"import numpy as np\n\nfrom lns.common.preprocess import Preprocessor\nfrom lns.yolo.train import YoloTrainer\nfrom lns.common import evaluation\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"2\"\n\ntrainer = YoloTrainer(\"new_dataset_ac_21\")\ndataset = Preprocessor.preprocess(\"ScaleLights_New_Youtube\")\n# dataset = dataset.merge_classes({\n# \"green\": [\"goLeft\", \"Green\", \"GreenLeft\", \"GreenStraightRight\", \"go\", \"GreenStraightLeft\", \"GreenRight\", \"GreenStraight\", \"3-green\", \"4-green\", \"5-green\"],\n# \"yellow\": [\"warning\", \"Yellow\", \"warningLeft\", \"3-yellow\", \"4-yellow\", \"5-yellow\"],\n# \"red\": [\"stop\", \"stopLeft\", \"RedStraightLeft\", \"Red\", \"RedLeft\", \"RedStraight\", \"RedRight\", \"3-red\", \"4-red\", \"5-red\", \"4-red-green\", \"5-red-green\", \"5-red-yellow\"],\n# \"off\": [\"OFF\", \"off\", \"3-off\", \"3-other\", \"4-off\", \"4-other\", \"5-off\", \"5-other\"]\n# })\ndataset = dataset.merge_classes({\n \"green\": [\"goLeft\", \"Green\", \"GreenLeft\", \"GreenStraightRight\", \"go\", \"GreenStraightLeft\", \"GreenRight\", \"GreenStraight\", \"3-green\", \"4-green\", \"5-green\"],\n \"yellow\": [\"warning\", \"Yellow\", \"warningLeft\", \"3-yellow\", \"4-yellow\", \"5-yellow\"],\n \"red\": [\"stop\", \"stopLeft\", \"RedStraightLeft\", \"Red\", \"RedLeft\", \"RedStraight\", \"RedRight\", \"3-red\", \"4-red\", \"5-red\"],\n \"off\": [\"OFF\", \"off\", \"3-off\", \"3-other\", \"4-off\", \"4-other\", \"5-off\", \"5-other\"]\n})\nprint(dataset.classes)\nprint(trainer.dataset.classes)\n\nclass_mapping = {trainer.dataset.classes.index(name): dataset.classes.index(name) for name in dataset.classes}\nprint(class_mapping)\n\nmodel = trainer.model\nclass_mapping_fn = lambda x: class_mapping[x]\n\nmats = evaluation.confusion(\n model, dataset,\n class_mapping=class_mapping_fn,\n num_to_sample=2000,\n iou_threshold=0.05,\n score_threshold=np.linspace(0., 1., 21),\n)\n\nmetrics = []\nfor mat in mats:\n metrics.append(evaluation.metrics(mat))\n\nnp.save(\"output.npy\", metrics)\n\n# latency = evaluation.latency(trainer.model, dataset, num_to_sample=100)\n# print(np.median(latency))\n","sub_path":"scripts/eval_helen.py","file_name":"eval_helen.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"140960193","text":"from visitatie.form import Form\n\n\ndef make_message(name, email, file):\n return {\n \"send_from\": \"visitatiecommissiealkmaar@gmail.com\",\n \"send_to\": [email],\n \"subject\": \"Feedback Visitatie 2018/2019\",\n \"text\": \"Beste \"\n + name\n + \",\\n\\nIn de bijlage vindt u de resultaten van de afgelopen visitatie ronde.\\n\\n\"\n + \"Vriendelijke groeten,\\n\\nDivera Twisk\\n\"\n + \"Voorzitter Commissie Visitatie Rug-netwerk\",\n \"files\": [file],\n }\n\n","sub_path":"visitatie/email/make_message.py","file_name":"make_message.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"20961067","text":"import socket\nimport tdl\nimport threading\nimport json\n\nUDP_IP = \"127.0.0.1\"\nUDP_PORT = 5005\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n# Set rendered font\ntdl.setFont('assets/arial_16x16.png')\n\n# Create console window\nwindow = tdl.init(50, 30, \"Network Client\")\n\ndef listener():\n\tglobal window\n\trecvSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\trecvSock.bind((\"127.0.0.1\", 5006))\n\trecvSock.setblocking(0)\n\twhile (1):\n\t\tdataIn = None\n\t\ttry:\n\t\t\tdataIn = recvSock.recv(10000).decode('utf-8')\n\t\texcept:\n\t\t\tpass\n\t\t\t\n\t\tif dataIn != None:\n\t\t\twindow.clear()\n\t\t\tdata = json.loads(dataIn)\n\t\t\tfor entity in data[\"entities\"]:\n\t\t\t\twindow.drawChar(entity[\"x\"], entity[\"y\"], entity[\"char\"])\n\t\t\ttdl.flush()\n\nt = threading.Thread(target=listener)\nt.start()\n\nwhile (1):\n\tfor event in tdl.event.get():\n\t\tif event.type == 'KEYDOWN':\n\t\t\tif event.keychar != 'TEXT':\n\t\t\t\tmsgBytes = \"{0}~{1}\".format(\"KEYDOWN\", event.keychar).encode('utf-8')\n\t\t\t\tsock.sendto(msgBytes, (UDP_IP, UDP_PORT))\n\t\telif event.type == 'KEYUP':\n\t\t\tif event.keychar != 'TEXT':\n\t\t\t\tmsgBytes = \"{0}~{1}\".format(\"KEYUP\", event.keychar).encode('utf-8')\n\t\t\t\tsock.sendto(msgBytes, (UDP_IP, UDP_PORT))\n\n","sub_path":"testClient.py","file_name":"testClient.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"280852725","text":"'''\n Creado por Jonathan Felipe Vargas Arias\n\n'''\nprint('\\n---------Bienvenido al sistema de porcentaje de ayuda de la Universidad Colombiana---------\\n')\nnames= input('Ingrese su nombres -> ')\nlastName = input('Ingrese apellidos -> ')\nedad = int(input('Ingrese su edad en años el interesado debe tener como minimo 15 años -> '))\npuntajePrueba = int(input('Ingrese el puntaje obtenido en el examen -> '))\nnumeroSalarios = int(input('Ingrese el número decimal de salarios mínimos mensuales que tiene de ingreso familiar \\n ejemplo 1,2 salarios minimos -> '))\nporcentajeApoyo = 0\n\n#Se calcula el porcentaje dependiento de la edad que proporciona el usuario\ndef descuentoPorEdad (edad):\n if(edad>=15 and edad <= 18):\n return 25\n elif(edad>=19 and edad <= 21):\n return 15\n elif(edad>=22 and edad <= 25):\n return 10\n elif (edad >=26):\n return 0\n\n#Se calcula el porcentaje dependiento de la salarios que proporciona el usuario\ndef descuentoPorIngreso (numeroSalarios):\n if(numeroSalarios <= 1):\n return 30\n elif(numeroSalarios >1 and numeroSalarios <=2):\n return 20\n elif(numeroSalarios >2 and numeroSalarios <=3):\n return 10\n elif(numeroSalarios >3 and numeroSalarios <=4):\n return 5\n else:\n return 0\n\n#Se calcula el porcentaje dependiento de la puntaje prueba que proporciona el usuario\ndef descuentoPuntajePorExamen(puntajePrueba):\n if(puntajePrueba >=80 and puntajePrueba < 86):\n return 30\n elif(puntajePrueba >= 86 and puntajePrueba <91):\n return 35\n elif(puntajePrueba >= 91 and puntajePrueba < 96):\n return 40\n elif(puntajePrueba >= 96 and puntajePrueba<=100):\n return 45\n elif(puntajePrueba < 80):\n return 0\n\n#Se calcula el porcentaje total de descuento\ndef calcularPorcentajeApoyo( edad, numeroSalarios,puntajePrueba):\n porcentajeApoyo = descuentoPorEdad(edad)\n porcentajeApoyo = porcentajeApoyo + descuentoPorIngreso(numeroSalarios)\n return porcentajeApoyo + descuentoPuntajePorExamen(puntajePrueba)\n\ndef ejecutarPrograma():\n print('\\nUsuario : ',names,' ', lastName,'\\n')\n print('El descuento recibido por edad = ',descuentoPorEdad(edad),'%\\n')\n print('El descuento recibido por el ingreso familiar = ', descuentoPorIngreso(numeroSalarios),'%\\n')\n print('El descuento recibido por el puntaje del examen = ', descuentoPuntajePorExamen(puntajePrueba),'%\\n')\n print('El descuento total que recibirá sobre el valor de la matrícula = ', calcularPorcentajeApoyo(edad, numeroSalarios,puntajePrueba),'%\\n')\n\nejecutarPrograma()\n","sub_path":"esquemaAyudaDescuento.py","file_name":"esquemaAyudaDescuento.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"163962264","text":"import sqlite3\nfrom sqlite3 import Error\n\ndef create_connection(db_file):\n \"\"\" create a database connection to a SQLite database \"\"\"\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n print(sqlite3.version)\n except Error as e:\n print(e)\n finally:\n if conn:\n conn.close()\n\n#create_connection(r\"D:\\SQLite\\db\\employees.db\")\n\ncreate_projects_table_sql = \"\"\" CREATE TABLE IF NOT EXISTS empList (\n id integer PRIMARY KEY,\n name text NOT NULL,\n avatar text,\n createdAt text\n ); \"\"\"\n\ndef create_table(db_file, create_table_sql):\n conn = sqlite3.connect(db_file)\n try:\n c = conn.cursor()\n c.execute(create_table_sql)\n except Error as e:\n print(e)\n\n#create_table(r\"D:\\SQLite\\db\\employees.db\", create_projects_table_sql)\n\ndef create_employee():\n conn = sqlite3.connect(r\"D:\\SQLite\\db\\employees.db\")\n sql = ''' INSERT INTO empList(id,name, avatar, createdAt)\n VALUES(?,?,?,?) '''\n cur = conn.cursor()\n cur.execute(sql, (4, \"Mayank\", \"No Avatar\", \"Today\"))\n conn.commit()\n return cur.lastrowid\n\n#create_employee()\n\ndef select_all_tasks():\n conn = sqlite3.connect(r\"D:\\SQLite\\db\\employees.db\")\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM empList\")\n\n rows = cur.fetchall()\n\n for row in rows:\n print(row)\n\n#select_all_tasks()\n\ndef delete_task():\n conn = sqlite3.connect(r\"D:\\SQLite\\db\\employees.db\")\n sql = 'DELETE FROM empList WHERE id=2'\n cur = conn.cursor()\n cur.execute(sql)\n conn.commit()\n\ndelete_task()\n\nselect_all_tasks()\n\ndef update_task():\n conn = sqlite3.connect(r\"D:\\SQLite\\db\\employees.db\")\n sql = ''' UPDATE empList\n SET name = ? \n WHERE id = ?'''\n cur = conn.cursor()\n cur.execute(sql, (\"Anshul\", 1))\n conn.commit()\n\n#update_task()\n\n#select_all_tasks()\n\n#create_employee()\n\n#sql_create_projects_table = \"\"\" CREATE TABLE IF NOT EXISTS empList (\n# id integer PRIMARY KEY,\n# name text NOT NULL,\n# avatar text,\n# createdAt text\n# ); \"\"\"\n#\n#create_table(r\"D:\\SQLite\\db\\employees.db\", sql_create_projects_table)","sub_path":"Python_Training/SAMPLE/workingWithNumbers.py","file_name":"workingWithNumbers.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"595465887","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Ubuntu Linux ~ Bugtraq II-Black Widow\nCreated on Fri Jun 20 14:18:35 2014\n\n@author: Waiyaki ~ #Spyder\n\"\"\"\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\n\nfrom random import randint\nimport sqlite3\nimport string\nimport time\nimport sys\nimport os\n\nclass Student(object):\n \"\"\"\n Class contains all the necessary methods to let kids learn maths, \n especially integer multiplication, all on their own.\n \"\"\" \n def __init__(self, name):\n self.name = name\n \n def connect(self):\n \"\"\"\n Method connects to the database if it exists, creates one and\n the necessary tables/columns in it otherwise.\n \"\"\"\n db_name = 'students.db'\n create = not os.path.exists(db_name)\n \n connection = sqlite3.connect(db_name)\n \n if create:\n c = connection.cursor()\n c.execute(\"CREATE TABLE student (\"\n \"id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, \"\n \"name TEXT UNIQUE NOT NULL, \"\n \"time_spent FLOAT DEFAULT 0.0, \"\n \"maths_time FLOAT DEFAULT 0.0, \"\n \"practice_time FLOAT DEFAULT 0.0, \"\n \"points FLOAT DEFAULT 0.0, \"\n \"exercises INTEGER DEFAULT 0, \"\n \"practices INTEGER DEFAULT 0, \"\n \"highest_score FLOAT DEFAULT 0.0, \"\n \"lowest_score FLOAT DEFAULT 100.0)\")\n connection.commit()\n return connection\n \n def user(self, repeat):\n \"\"\"\n Method reads in a name, corrects it, checks whether the name is in \n the database, if not, it registers the new user, otherwise, it uses\n the username already in the database.\n \"\"\"\n connection = self.connect()\n c = connection.cursor()\n \n usr_name = self.name\n self.name_exit(usr_name)\n usr_name = self.check_name(usr_name)\n \n c.execute(\"SELECT name FROM student\")\n names = []\n for row in c.fetchall():\n names.append(row)\n loop = True\n while loop: \n if len(names) != 0: \n for name in names:\n name = str(name)\n name = name[3:]\n name = name.strip(\"(',)\")\n if usr_name in name:\n geek_print(\"\\nIs your name {} (yes or no)?\".format(name))\n ans = raw_input(\"> \")\n ans = ans.lower()\n if ans in 'yes':\n usr_name = name\n loop = False # Will discontinue while loop\n break # Out of for\n elif repeat:\n # In case user is repeating with a different username\n geek_print(\"\\nWhat is your name?\")\n usr_name = raw_input(\"> \")\n usr_name = self.check_name(usr_name)\n repeat = False # Prevents this elif from another execution\n break # Out of the for loop, so that the loop can start\n # over at the while loop so that the new name can be\n # evaluated\n else:\n geek_print(\"\"\"\n You must be a new user.\n To register, please enter your full name\n or enter 'exit' or 'quit' to finish\n \"\"\")\n new_user = raw_input(\"> \")\n new_user = self.check_name(new_user)\n usr_name = self.register(new_user)\n loop = False\n else:\n geek_print(\"\"\"\n You must be a new user.\n To register, please enter your full name\n or enter 'exit' or 'quit' to finish\n \"\"\")\n new_user = raw_input(\"> \")\n new_user = self.check_name(new_user)\n usr_name = self.register(new_user)\n loop = False\n \n connection.commit()\n return usr_name\n \n def check_reg_name(self, name):\n \"\"\"\n Method checks the registration name.\n Name has to be at least 2 strings to increase chances of\n uniqueness, see e.g in the print statement.\n \"\"\"\n name = name.split(' ')\n while len(name) <= 2 or len(name) > 4:\n geek_print(\"\"\" \n Please enter your full name:\n e.g Janet Lagat Kiplagat \"\"\")\n name = raw_input(\"> \")\n name = name.split(' ')\n \n name = ' '.join(name)\n name = self.check_name(name) \n return name\n \n def register(self, name):\n \"\"\"\n Method registers a new user\n \"\"\"\n try:\n connection = self.connect()\n c = connection.cursor()\n \n name = self.check_reg_name(name)\n c.execute(\"INSERT INTO student (name) VALUES (?)\", (name,))\n \n connection.commit()\n return name\n except:\n output = \"\"\"\n \\n\\n{0} is already in the database. I am going to assume \\n{0} is your name.\n \"\"\".format(name)\n geek_print(output)\n return name\n \n def check_name_length(self, name):\n \"\"\"\n Method checks the length of the name.\n Name length has to be not less than 3.\n \"\"\" \n while True:\n # Name has to be 3 or more characters long.\n if len(name) >= 3:\n self.name_exit(name)\n break\n else:\n geek_print(\"Please enter your full name:\")\n name = raw_input(\"> \")\n return name\n \n def check_name(self, name):\n \"\"\"\n Method checks name, strips excess whitespace, capitalizes\n as needed.\n \"\"\"\n #Check length\n name = self.check_name_length(name)\n \n #Strip whitespace (When the user hits spacebar twice?)\n word = ''\n results = []\n whitespace = string.whitespace\n for char in name:\n if char in whitespace:\n if word:\n results.append(word)\n word = ''\n else:\n word += char\n if word:\n results.append(word)\n name = ' '.join(results)\n \n #Capitalize\n name = name.lower()\n name = name.split(' ')\n for i in xrange(len(name)):\n name[i] = name[i][0].upper()+name[i][1:]\n \n name = ' '.join(name)\n \n return name\n \n def name_exit(self, text):\n \"\"\"\n Method checks whether the user wants to quit, from their\n name input.\n \"\"\"\n text = text.lower()\n exit_statements = [\"\\nProgram will now exit.\",\n \"\\n\\nIt was nice having you around...\",\n \"\\n\\nI hope to see you some time again soon...\"\n \"\\n\\nGOODBYE!\\n\"\n ]\n time_delay = 1\n while len(text) > 1:\n if text in 'exitquit':\n for i in xrange(len(exit_statements)):\n for char in exit_statements[i]:\n print(char, end='')\n time.sleep(0.02)\n time_delay -= 0.25\n time.sleep(time_delay)\n sys.exit()\n else:\n pass\n break\n \n def load_stats(self, name):\n \"\"\"\n Method loads the user's data from the database\n \"\"\"\n time_spent = []\n maths_time = []\n practice_time = []\n points = []\n exercises = []\n practices = []\n highest_score = []\n lowest_score = []\n \n connection = self.connect()\n c = connection.cursor()\n \n rows = [time_spent, maths_time, practice_time, points, \n exercises, practices, highest_score, lowest_score]\n columns = ['time_spent', 'maths_time', 'practice_time', 'points', \n 'exercises', 'practices','highest_score', 'lowest_score']\n #try:\n for i in range(len(columns)):\n sql = '''SELECT ''' + columns[i] + ''' FROM student WHERE name=\"{}\"'''.format(name)\n c.execute(sql)\n for row in c.fetchone():\n rows[i].append(row)\n return rows\n #except TypeError:\n #pass\n #print(\"\\nNo prior records for {} found.\\n\".format(name))\n \n def view_stats(self, name):\n \"\"\"\n Method prints out the user's performance, given the user's name.\n \"\"\"\n rows = self.load_stats(name)\n time_spent = rows[0][0]\n total_time = (time_spent)/60\n string = \"\"\"\n Results for:\n {}:\n Points accumulated so far : {:<5.2f} points\n Number of math exercises done so far : {:<5d} exercises\n Number of practice exercises done so far: {:<5d} practice exercises\n Highest score (in percentage) : {:<5.2f} %\n Lowest score : {:<5.2f} %\n Total time spent in class : {:<5.2f} minutes\n \\n\n \"\"\".format(name, rows[3][0], rows[4][0], rows[5][0], rows[6][0],\n rows[7][0], total_time)\n \n geek_print(string)\n \n def update_data(self, name, column, value):\n \"\"\"\n Method updates the database.\n \"\"\"\n connection = self.connect()\n c = connection.cursor()\n c.execute(\"UPDATE student SET {}={} WHERE name='{}'\".format(\n column, value, name))\n connection.commit()\n \n def get_level(self):\n \"\"\"\n Method gets the class level of the user.\n \"\"\"\n output = \"\\nPlease choose your class:\"\n geek_print(output)\n print(\"\"\"\n Exercise Questions\n ___________________\n 1. Level 1: (Class 2 - 3)\n 2. Level 2: (Class 3 - 4)\n 3. Level 3: (Class 4 - 5)\n \n Practice Multiplication Questions\n ___________________\n 4. Class 2 - 3\n 5. Class 4 - 5\n \"\"\")\n levels = \"1,2,3,4,5\"\n levels = levels.split(',')\n \n level = raw_input(\"> \")\n while True:\n if level not in levels:\n self.name_exit(level)\n print(\"Please enter your correct level:\")\n level = raw_input(\"> \")\n else:\n break \n return level\n \n def practice_pref(self, level):\n \"\"\"\n Method similar to self.limits(level), but for the practice\n method.\n \"\"\"\n level = str(level)\n if level == '4':\n numbers = 11\n elements = [i for i in xrange(2, 11)]\n elif level == '5':\n numbers = 16\n elements = [i for i in xrange(9, 21)]\n return numbers, elements\n \n def get_operation(self):\n \"\"\"\n Method gets the preferred choice of maths from the user.\n \"\"\"\n output = \"\\nPlease select the maths you want to do: \"\n geek_print(output)\n print(\"\"\"\n Exercises.\n ______________\n 1. Multiplication\n 2. Addition\n 3. Subtraction\n 4. Division\n \"\"\")\n pref_op = raw_input(\"> \")\n self.name_exit(pref_op)\n \n return pref_op\n \n def limits(self, level):\n \"\"\"\n Method determines the max and min limits within which \n mathematical questions should be bound, according to the user's\n class level.\n \"\"\"\n level = str(level)\n if level == '1':\n lim1 = 2\n lim2 = 16\n return lim1, lim2\n elif level == '2':\n lim1 = 2\n lim2 = 100\n return lim1, lim2\n elif level == '3':\n lim1 = 2\n lim2 = 1000\n return lim1, lim2\n elif level == '4' or level == '5':\n # These are practice levels\n pass\n \n def check_level_pref(self, value):\n \"\"\"\n Checks validity of users input to prevent errors.\n Checks level and practice preference inputs\n \"\"\"\n while True:\n while len(value) < 1:\n geek_print(\"Please choose the maths you want to do: \")\n value = raw_input(\"> \")\n self.name_exit(value)\n \n while True:\n try:\n value = int(value)\n while value > 5:\n geek_print(\"Error. Please choose another exercise.\")\n value = eval(raw_input(\"> \"))\n break\n except (NameError, ValueError):\n geek_print(\"Please enter a number 1, 2, 3, or 4: \")\n value = raw_input(\"> \")\n self.name_exit(value)\n break\n return value\n\n \n def resolve_sign(self, v1, v2, sign):\n \"\"\"\n Method resolves the sign given and executes the appropriate type\n of computation.\n \"\"\"\n if sign == '*' or sign == 'x':\n return v1 * v2\n elif sign == '+':\n return v1 + v2\n elif sign == '-':\n return v1 - v2\n elif sign == '/':\n return v1 / v2\n \n def verify(self, trial, v1, v2, sign, count, fail):\n \"\"\"\n Method checks the validity of users input to avoid errors.\n \"\"\" \n while len(trial) < 1:\n # Case where the user hits \"Enter\" without first giving the answer.\n geek_print(\"Please try again:\\n\")\n trial = raw_input(\"{:2d}. {:2d} {} {:2d} = \".format(count, v1,\n sign, v2))\n while True:\n try:\n trial = int(trial) # convert the input from a str to an int\n break\n except ValueError:\n self.check_exit(trial, count, fail)\n #Case when the users input can't be converted to int\n geek_print(\"Incorrect answer. Please enter a number:\\n\")\n trial = raw_input(\"{:2d}. {:2d} {} {:2d} = \".format(count, v1, \n sign, v2))\n self.check_exit(trial, count, fail)\n return trial\n \n def check_exit(self, trial, count, fail):\n \"\"\"\n Method checks whether the user wishes to exit from their\n input.\n \"\"\"\n trial = str(trial)\n trial = trial.lower()\n while len(trial) > 1:\n if trial in 'exitquit':\n output = \"\"\"\n Out of the {} questions you attempted, you scored {} and\n failed {}.\n You did not finish this level.\\n\\n\n \"\"\".format(count, (count) - fail, fail)\n geek_print(output)\n exit_statements = [\"\\n\\nPlease wait...\", \n \"\\n\\nCleaning up......\",\n \"\\n\\nIt was nice having you around. Hope to see you soon...\",\n \"\\n\\nPreparing to exit......\",\n \"\\n\\nProgram will now exit.\",\n \"\\n\\nGOODBYE!\\n\\n\"]\n delay = 1\n for i in xrange(len(exit_statements)):\n for char in exit_statements[i]:\n print(char, end='')\n time.sleep(0.02)\n delay -= 0.15\n time.sleep(delay)\n sys.exit()\n else:\n break\n else:\n pass\n \n def process_levels_prefs(self, level, pref):\n \"\"\"\n Method processes the level and preferences of the user to adjust the\n limits according to the level the user is in.\n \"\"\"\n lim1, lim2 = self.limits(level) \n if pref == 1:\n lev = 'Multiplication Exercise: Level ' + str(level)\n sign = 'x'\n return (lim1, lim2, lev, sign)\n elif pref == 2:\n lev = 'Addition Exercise: Level ' + str(level)\n sign = '+'\n return (lim1, lim2, lev, sign)\n elif pref == 3:\n lev = 'Subtraction Exercise: Level ' + str(level)\n sign = '-'\n return (lim1, lim2, lev, sign)\n elif pref == 4:\n lev = 'Division Exercise: Level ' + str(level)\n sign = '/'\n return (lim1, lim2, lev, sign)\n \n def Maths(self, name, level, pref, q=2):\n '''\n Gives the student an exercise of mathematics questions, checks them\n and computes the percentage score.\n '''\n t1 = time.time()\n lim1, lim2, lev, sign = self.process_levels_prefs(level, pref)\n print(\"\\n{}\\n\".format(lev))\n geek_print(\"Please type in the correct answers to the given question\\n\"\\\n \"or type 'exit' or 'quit' to finish.\\n\")\n count = 0\n fail = 0\n rows = self.load_stats(name)\n \n while count <= q:\n count += 1\n if (level == 1 or level == 2) and sign == '/':\n # Increase the upper limit when the operation is a division\n lim2 = 100\n v1 = randint(lim1, lim2)\n # The divisor should always be between lim1 and 10 for this level\n v2 = randint(lim1, 10) \n else:\n v1 = randint(lim1, lim2)\n v2 = randint(lim1, lim2)\n if sign == '/':\n # Ensure that the question involves numbers that are perfectly\n # divisible\n if level == 1 or level == 2:\n v1, v2 = is_divisible(v1, v2, lim1, 10)\n else:\n v1, v2 = is_divisible(v1, v2, lim1, lim2)\n elif sign == '-':\n while v1 < v2:\n v1 = randint(lim1, lim2)\n elif sign == '*' or 'x':\n v1 = randint(lim1, 13)\n v2 = randint(lim1, 10)\n \n ans = self.resolve_sign(v1, v2, sign)\n trial = raw_input(\"{:2d}. {:2d} {} {:2d} = \".format(count, v1, \n sign, v2))\n \n trial = self.verify(trial, v1, v2, sign, count, fail) \n \n if trial != ans:\n fail += 1\n while trial != ans:\n geek_print(\"{} is not the correct answer. Please try again.\\n\".format(trial))\n trial = raw_input(\"{:2d}. {:2d} {} {:2d} = \".format(count, v1,\n sign, v2))\n trial = self.verify(trial, v1, v2, sign, count, fail) \n print(\" Correct!\\n\")\n score = count - fail\n percent = (score/count)*100\n points = percent * 0.2 # 100% = 20 points\n geek_print(\"You got {} out of {} and failed {}.\".format(score, count, fail))\n geek_print(\"Your percentage score is {:.2f} %\".format(percent))\n geek_print(\"\\nCongratulations! You have added {:.2f} points!\".format(points))\n \n #Gather the data to update the database\n maths_time = time.time() - t1\n time_spent = rows[0][0] + maths_time\n time_in_maths = rows[1][0] + maths_time\n points_in_db = rows[3][0] + points\n exercises = rows[4][0] + 1\n highest_score = rows[6][0]\n lowest_score = rows[7][0]\n if percent > highest_score:\n self.update_data(name, 'highest_score', percent)\n if percent < lowest_score:\n self.update_data(name, 'lowest_score', percent)\n updates = ['time_spent', 'maths_time', 'points', 'exercises']\n update_values = [time_spent, time_in_maths, points_in_db, exercises]\n #Update the database\n for i in xrange(len(updates)):\n self.update_data(name, updates[i], update_values[i])\n \n def practice(self, name, level):\n \"\"\"\n Gives the user a practice exercise that teaches the user multiplication.\n \"\"\"\n t1 = time.time()\n lev = 'Multiplication Practice Questions: Level ' + str(level)\n geek_print(lev)\n count = 0\n fail = 0\n numbers, elements = self.practice_pref(level)\n \n geek_print(\"\\nYou are in Multiplication Practice, level {}\\n\".format(level))\n geek_print(\"\"\"\n Please type in the correct answers to the given question\\n\n or type 'exit' to finish.\n \"\"\")\n cont = 'yes'\n for element in elements:\n cont = cont.lower()\n if cont in ['yes', 'y']:\n for i in xrange(2, numbers):\n ans = element * i\n \n if element % 2 == 0:\n trial = raw_input(\"{:20d}. {:2d} x {:2d} = \".format(count,\n element, i))\n else:\n trial = raw_input(\"{:2d}. {:2d} x {:2d} = \".format(count,\n element, i))\n \n trial = self.verify(trial, element, i, 'x', count, fail)\n \n if trial != ans:\n fail += 1\n while trial != ans:\n if element % 2 == 0:\n print(\"{:22d} is not the correct answer. Please try again:\\n\".format(trial))\n trial = raw_input(\"{:20d}. {:2d} x {:2d} = \".format(count, element, i))\n else:\n print(\"{:2d} is not the correct answer. Please try again:\\n\".format(trial))\n trial = raw_input(\"{:2d}. {:2d} x {:2d} = \".format(count, element, i))\n trial = self.verify(trial, element, i, 'x', count, fail)\n count += 1\n if element % 3 == 0:\n geek_print(\"\\nDo you want to continue with practice (yes or no)?\")\n cont = raw_input(\"> \")\n while True:\n if len(cont) < 1 or cont not in ['yes', 'no', 'y', 'n']:\n geek_print(\"Do you want to continue with practice (yes or no)?\")\n cont = raw_input(\"> \")\n else:\n break\n else:\n break\n count = count - 1\n score = count - fail\n geek_print(\"You scored {} out of {} and failed {}.\".format(score, count, fail))\n geek_print(\"Your percentage score is {:.2f} %\".format((score/count)*100))\n prac_time = time.time() - t1\n connection = self.connect()\n # Update database\n c = connection.cursor()\n c.execute(\"SELECT time_spent, practice_time, practices FROM student WHERE name=?\",(name,))\n rows = []\n for row in c.fetchall():\n rows.append(row)\n total_time = rows[0][0] + prac_time\n practice_time = rows[0][1] + prac_time\n practices = rows[0][2] + 1\n columns = [\"time_spent\", \"practice_time\", \"practices\"]\n values = [total_time, practice_time, practices]\n for i in xrange(len(columns)):\n self.update_data(name, columns[i], values[i])\n \ndef is_divisible(v1, v2, lim1, lim2):\n while True:\n # Count - try to avoid infinite loop? Maybe the number (v2) is prime?\n count = 1\n while v1 % v2 != 0 or v1 == v2:\n count += 1\n v2 = randint(lim1, lim2)\n if count % 10 == 0:\n v1 = randint(lim1, lim2)\n break\n return v1, v2\n\ndef geek_print(string):\n \"\"\"\n Function renders output in a way that attracts the eyes\n of the user.\n \"\"\"\n for char in string:\n print(char, end='')\n time.sleep(0.02)\n if char == '\\n':\n time.sleep(0.01)\n print(\"\\n\")\n\ndef main(name, repeat=False):\n \"\"\"\n Function initializes execution\n \"\"\"\n student = Student(name)\n name = student.user(repeat)\n #Read database, get statistics, print them?\n geek_print(\"\\nDo you want to view your performance so far (yes or no)?\")\n view = raw_input(\"> \")\n view = view.lower()\n if view in 'yes':\n student.view_stats(name)\n else:\n geek_print(\"\\n\\n------> Program will not show performance. <------\\n\\n\")\n time.sleep(0.5)\n \n #Get the user's class, choice of math operations, check them\n level = student.get_level()\n if level == '4' or level == '5':\n level = student.check_level_pref(level)\n student.practice(name, level)\n else:\n level = student.check_level_pref(level)\n pref_op = student.get_operation() #preferred mathematical operation\n pref_op = student.check_level_pref(pref_op)\n \n #Call up the Maths method, process user's level and preference, execute\n #the necessary computations.\n student.Maths(name, level, pref_op)\n return name\n \nif __name__ == '__main__':\n geek_print(\"\"\"\n WELCOME TO THE MATHEMATICS LESSON.\n \n Please start by entering your name below:\n \n \"\"\")\n #Get name, process it.\n geek_print(\"What is your name? \\n\")\n name = raw_input(\"> \")\n name = main(name)\n \n while True:\n print(\"\\n\\nDo you want to start over (yes or no)? \")\n repeat = raw_input(\"> \")\n while not repeat.isalpha():\n print(\"\\nPlease enter the correct choice.\\nDo you want to\"\\\n \" start over (yes or no)? \") \n repeat = raw_input(\"> \")\n \n repeat = repeat.lower()\n if repeat in 'yes':\n rep = True # Is repeating?\n name = main(name, rep)\n else:\n geek_print(\"\"\"\n Congratulations for your efforts.\n It was nice having you around.\n Hope to see you soon.\n \\n\\n{0}GOODBYE!{0}\n \"\"\".format('.'*20))\n sys.exit()\n","sub_path":"AIMath/AI_Math_DB.py","file_name":"AI_Math_DB.py","file_ext":"py","file_size_in_byte":26465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"392205412","text":"import numpy\nfrom skimage.data import camera\nfrom skimage.util import random_noise\n\nfrom dexp.processing.deconvolution.admm_deconvolution import admm_deconvolution\nfrom dexp.processing.filters.fft_convolve import fft_convolve\nfrom dexp.processing.filters.kernels.gaussian import gaussian_kernel_nd\nfrom dexp.utils.backends import Backend, CupyBackend, NumpyBackend\n\n\ndef test_admm_deconvolution_numpy():\n with NumpyBackend():\n _test_admm_deconvolution()\n\n\ndef test_admm_deconvolution_cupy():\n try:\n with CupyBackend():\n _test_admm_deconvolution()\n except ModuleNotFoundError:\n print(\"Cupy module not found! Test passes nevertheless!\")\n\n\ndef _test_admm_deconvolution():\n xp = Backend.get_xp_module()\n\n image = camera().astype(numpy.float32) / 255\n noisy = random_noise(image, mode=\"gaussian\", var=0.005, seed=0, clip=False)\n noisy = random_noise(noisy, mode=\"s&p\", amount=0.03, seed=0, clip=False)\n\n psf = gaussian_kernel_nd(size=9, ndim=2, sigma=2, dtype=numpy.float32)\n\n image = Backend.to_backend(image)\n noisy = Backend.to_backend(noisy)\n psf = Backend.to_backend(psf)\n\n blurry = fft_convolve(image, psf)\n\n deconvolved = admm_deconvolution(blurry, psf)\n\n error = xp.linalg.norm(deconvolved - image, ord=1) / image.size\n\n print(f\"Error = {error}\")\n\n assert error < 0.001\n\n\nif __name__ == \"__main__\":\n test_admm_deconvolution_numpy()\n","sub_path":"dexp/processing/deconvolution/_test/test_admm_deconvolution.py","file_name":"test_admm_deconvolution.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"98398841","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\n\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n#with open(path.join(here, 'README.rst').encoding='utf-8') as f:\n # long_description = f.read()\n\nsetup(\n name = 'epiktube',\n \n version = '1.0.0',\n description = 'A webapp to download media from sites',\n long_description = __doc__,\n url = 'https://github.com/epikapa/epiktube',\n author = 'Epikapa',\n author_email = 'epikapa@epikex.com',\n license = 'MIT',\n classifiers = [\n 'Development Status :: 4',\n 'Intended Audience :: Testers',\n 'Topic :: Webapp :: Media',\n 'Programming Language :: Python :: 3.5'\n ],\n keywords = 'epiktube',\n zip_safe = False,\n include_package_data = True,\n packages = find_packages(exclude=['contrib', 'docs', 'tests']),\n install_requires=['youtube-dl', 'flask']\n )\n\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"641876775","text":"\nfrom random import randint\n\nlength = int(input(f\"Введите длину массива: \"))\narray = []\n\nfor item in range(length):\n number = randint(-100, 100)\n array.append(number)\n\nprint(array)\n\ndef max_item_and_index_of_list(array):\n max = array[0]\n max_index = 0\n index = 0\n while index < len(array):\n if array[index] > max:\n max = array[index]\n max_index = index\n index += 1\n return {\n \"maximum\": max,\n \"max_index\": max_index\n }\n\nprint(max_item_and_index_of_list(array))","sub_path":"hw_alg_6/Max_item_and_index_of_list.py","file_name":"Max_item_and_index_of_list.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"146671238","text":"N = int(input())\nA = list(map(int, input().split()))\nim, m = 0, 0\nfor i,a in enumerate(A):\n if abs(a)>abs(m):\n m = a\n im = i\n\noperations = []\nfor i in range(N):\n if i==im: continue\n operations.append((im+1, i+1))\n A[i] += A[im]\n\nif m>=0:\n for i in range(N-1):\n operations.append((i+1, i+2))\n A[i+1] += A[i]\n\nelse:\n for i in range(N-1, 0, -1):\n operations.append((i+1, i))\n A[i-1] += A[i]\n\nprint(len(operations))\nfor x, y in operations:\n print(x,y)","sub_path":"Python_codes/p03496/s457968381.py","file_name":"s457968381.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"228942108","text":"from prefect import Flow, Task\n\nclass AddTask(Task):\n\n def __init__(self, default: int, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.default= default\n\n def run(self, x: int, y: int=None) -> int:\n if y is None:\n y = self.default\n print(x + y)\n return x + y\n\nadd = AddTask(default=1)\n\nwith Flow(\"oppcode?\") as f:\n first_result = add(1, y=2)\n second_result = add(x=first_result, y=100)\n\nf.register(\"Demo\")","sub_path":"addopcode.py","file_name":"addopcode.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"479975647","text":"from skriil.errors import InvalidDataError, PredictionError\nfrom skriil.basic_methods import mean\nfrom sklearn.preprocessing import StandardScaler\nimport numpy as np\n\n\nclass LinearRegression:\n def __init__(self):\n self.scaler = StandardScaler()\n self.x = []\n self.y = []\n self.a = 0\n self.b = 0\n\n @staticmethod\n def throw_exceptions(x, y):\n if len(x) == 0 or len(y) == 0:\n raise InvalidDataError(\"x or y parameter is missing!\")\n if len(x) != len(y):\n raise InvalidDataError(\"length of x and y has to be the same!\")\n\n @staticmethod\n def f(a, b, x):\n return a * x + b\n\n @staticmethod\n def j(a, b, x, y):\n return mean((y - (a * x + b)) ** 2)\n\n @staticmethod\n def j_ableitung_a(a, b, x, y):\n return mean(-2 * x * (-a * x - b + y))\n\n @staticmethod\n def j_ableitung_b(a, b, x, y):\n return mean(-2 * (-a * x - b + y))\n\n def scale_data(self, x):\n x = self.scaler.transform(x)\n return x\n\n def undo_scale(self, x):\n x = self.scaler.inverse_transform(x)\n return x\n\n def train(self, x, y):\n #self.throw_exceptions(x=x, y=y)\n self.scaler.fit(x)\n x = self.scale_data(x=x)\n a = 1\n b = 1\n rate = 0.005\n for i in range(0, 500):\n da = self.j_ableitung_a(a, b, x, y)\n db = self.j_ableitung_b(a, b, x, y)\n a -= rate * da\n b -= rate * db\n self.a = a\n self.b = b\n\n def predict(self, xl):\n xl = self.scale_data(x=xl)\n predicted = []\n for x in xl:\n predicted.append(self.a * x + self.b)\n return predicted\n\n def score(self, xs, ys):\n y_avg = mean(ys)\n sum_pred = 0\n sum_avg = 0\n for i in range(0, len(xs)):\n sum_pred += (ys[i] - self.predict([xs[i]])[0]) ** 2\n sum_avg += (ys[i] - y_avg) ** 2\n r2 = 1 - sum_pred / sum_avg\n return r2\n\n\n","sub_path":"skriil/linear_model.py","file_name":"linear_model.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"361115083","text":"from random import randrange\n\n\ndef dead_state(width, height):\n board = [[0] * height for i in range(width)]\n\n for h in range(height):\n for w in range(width):\n print(board[w][h], end=\"\")\n print()\n\n return board\n\n\ndef random_state(width, height):\n board = [[randrange(1)] * height for i in range(width)]\n\n for h in range(height):\n for w in range(width):\n print(board[w][h], end=\"\")\n print()\n\n\ndead_state(5, 5)\n\nrandom_state(5, 5)\n","sub_path":"Python/game_of_life/gameoflife.py","file_name":"gameoflife.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"385881526","text":"from datetime import datetime\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom dateutil import parser\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.core.paginator import Paginator\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import Http404, get_object_or_404, render_to_response\nfrom django.template import RequestContext\nfrom django.utils.http import urlquote as django_urlquote\n\nfrom DDR import elasticsearch\nfrom ui import faceting, models\n\n\n# helpers --------------------------------------------------------------\n\n\n# views ----------------------------------------------------------------\n\ndef index( request ):\n return render_to_response(\n 'ui/search/index.html',\n {},\n context_instance=RequestContext(request, processors=[])\n )\n\ndef results( request ):\n \"\"\"Results of a search query.\n \"\"\"\n # prep query for elasticsearch\n model = request.GET.get('model', None)\n q = django_urlquote(request.GET.get('query', ''))\n filters = {}\n fields = models.all_list_fields()\n sort = {'record_created': request.GET.get('record_created', ''),\n 'record_lastmod': request.GET.get('record_lastmod', ''),}\n # do the query\n results = elasticsearch.query(settings.ELASTICSEARCH_HOST_PORT, settings.DOCUMENT_INDEX,\n query=q, filters=filters,\n fields=fields, sort=sort)\n hits = models.massage_query_results(results)\n paginator = Paginator(hits, settings.RESULTS_PER_PAGE)\n page = paginator.page(request.GET.get('page', 1))\n return render_to_response(\n 'ui/search/results.html',\n {'paginator': paginator,\n 'page': page,\n 'query': q,\n 'filters': filters,\n 'sort': sort,},\n context_instance=RequestContext(request, processors=[])\n )\n\ndef term_query( request, field, term ):\n \"\"\"Results of a search query.\n \"\"\"\n # prep query for elasticsearch\n terms_display = {'field':field, 'term':term}\n terms = {field:term}\n facet = faceting.get_facet(field)\n for t in facet['terms']:\n if t['id'] == term:\n try:\n terms_display['term'] = t['title_display']\n except:\n terms_display['term'] = t['title']\n break\n filters = {}\n fields = models.all_list_fields()\n sort = {'record_created': request.GET.get('record_created', ''),\n 'record_lastmod': request.GET.get('record_lastmod', ''),}\n # do the query\n results = elasticsearch.query(settings.ELASTICSEARCH_HOST_PORT, settings.DOCUMENT_INDEX,\n term=terms, filters=filters,\n fields=fields, sort=sort)\n hits = models.massage_query_results(results)\n paginator = Paginator(hits, settings.RESULTS_PER_PAGE)\n page = paginator.page(request.GET.get('page', 1))\n return render_to_response(\n 'ui/search/results.html',\n {'paginator': paginator,\n 'page': page,\n 'terms': terms_display,\n 'filters': filters,\n 'sort': sort,},\n context_instance=RequestContext(request, processors=[])\n )\n","sub_path":"ddrpublic/ui/views/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"312026868","text":"# ------------------------------------------------------------\n# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.\n#\n# Licensed under the BSD 2-Clause License.\n# You should have received a copy of the BSD 2-Clause License\n# along with the software. If not, See,\n#\n# \n#\n# ------------------------------------------------------------\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom dragon.vm.torch.autograd.anchor_pool import APool\n\n# We simply use INC-UID to hash expressions,\n# As Python supports BigInteger\n_EXPRESSION_UID = 0\n\n\ndef _get_uid():\n global _EXPRESSION_UID\n _EXPRESSION_UID += 1\n return _EXPRESSION_UID - 1\n\n\nclass Expression(object):\n def __init__(self):\n self._ops = dict()\n\n def merge(self, expressions):\n for e in expressions:\n if e: self._ops.update(e._ops)\n\n def append(self, op):\n uid = _get_uid()\n op_name = APool.get(op.type)\n self._ops[uid] = op\n self._ops[uid].name = op_name\n return op_name\n\n def debug_str(self, name=''):\n external_inputs = set()\n ordered_ops = sorted(self._ops.items(), key=lambda d: d[0])\n outputs = set()\n buffer0 = '-------------------Expressions-------------------\\n'\n buffer1 = ''\n buffer2 = 'Inputs: ['\n for k, v in ordered_ops:\n buffer1 = buffer1 + '>>> ' + str(k) + '. ('\n for input in v.input:\n if input not in outputs:\n external_inputs.add(input)\n buffer1 = buffer1 + input + ', '\n buffer1 = buffer1 + 'None, ' if len(v.input) == 0 else buffer1\n buffer1 = buffer1[0:-2] + ') -> ' + v.type + ' -> ('\n for output in v.output:\n outputs.add(output)\n buffer1 = buffer1 + output + ', '\n buffer1 = buffer1[0:-2] + ') \\n'\n\n buffer1 = buffer1 + 'Target: ' + name + '\\n'\n for ex_input in external_inputs:\n buffer2 = buffer2 + ex_input + ', '\n buffer2 = buffer2 + ']\\n'\n return buffer0 + buffer2 + buffer1 + buffer0","sub_path":"Dragon/python/dragon/vm/torch/autograd/expression.py","file_name":"expression.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"219204550","text":"\"\"\"\r\nThis is server demo for PML\r\nThis is for a very simple multi-player game\r\nThis demo may be copied, but it is illegal to copy PML\r\n\r\n--IF YOU COPY THIS THEN THE FBI WILL COME :: FBI WARNING NP5--\r\n\r\nDemo made by: Peter Gutkovich\r\n-- Contact Info --\r\nEmail: peter.mty8@gmail.com\r\nPhone Number: 347-623-8734\r\n\"\"\"\r\n\r\n# import json for packing and unpacking json dict strings\r\nfrom json import loads, dumps\r\n# import the amazing pml library\r\nimport pml\r\n# import random\r\nfrom random import randint\r\n\r\n# create game server\r\ngame_server = pml.Server(1234, 2)\r\n\r\n\r\n# create command for handling the \"get_game_info\" client command\r\ndef get_game_info_command_handler(client):\r\n non_included_player_dict = game_server.game_data.copy()\r\n non_included_player_dict.pop(player_msg['player'])\r\n game_server.send(dumps(non_included_player_dict), client)\r\n\r\n\r\n# function to update game data\r\ndef update_coordinates_to_game(client, update_x, update_y, player):\r\n # what to send to client\r\n send_back = \"\"\r\n\r\n # try updating to the game data\r\n try:\r\n # change the game's player's data\r\n game_server.setup_player_data(player=player, data={'x': update_x,\r\n 'y': update_y})\r\n send_back = \"OK\"\r\n except ValueError:\r\n send_back = \"ERROR\"\r\n print(\"THERE WAS AN ERROR\")\r\n\r\n # send response\r\n game_server.send(data=send_back, client=client)\r\n\r\n\r\n# put server socket into listening mode\r\ngame_server.put_server_into_listening()\r\n\r\n# handle incoming player connections and set players their game values\r\nfor i in range(game_server.player_amount):\r\n game_server.handle_player_connections()\r\n\r\nfor player in game_server.players:\r\n game_server.setup_player_data(player=player, data={'x': randint(0, 400),\r\n 'y': randint(0, 400)})\r\n\r\n\r\n# game loop\r\nwhile True:\r\n # collect from each player in game\r\n for i in game_server.players_addr:\r\n # get info from player\r\n player_msg = game_server.receive(1024, i)\r\n player_msg = loads(player_msg)\r\n # get the command name that the player called\r\n fun = player_msg['function']\r\n # get the actual data that the player sent for the server to analyze\r\n client_data = loads(player_msg['data'])\r\n # get the player id of the player who send the data\r\n player = player_msg['player']\r\n\r\n # if command is \"get_game_info\" then call function\r\n if fun == \"get_game_info\":\r\n get_game_info_command_handler(client=i)\r\n\r\n # if the command is \"update_coordinates\" then call function\r\n if fun == \"update_coordinates\":\r\n update_coordinates_to_game(client=i, update_x=client_data['new_x'], update_y=client_data['new_y'], player=player)\r\n\r\n if fun == \"get_FULL_game\":\r\n game_server.send(client=i, data=dumps(game_server.game_data))\r\n","sub_path":"pml_server.py","file_name":"pml_server.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"345001961","text":"import tensorflow as tf\nimport os, sys\nfrom PIL import Image\n\nimage_path = '/Users/hangeulbae/Desktop/test2.jpg'\n\nsize = (299, 299)\n\ninfile = image_path\noutfile = os.path.splitext(infile)[0] + '_resized.jpg'\ntry:\n im = Image.open(infile)\n im.thumbnail(size, Image.ANTIALIAS)\n old_im_size = im.size\n\n ## By default, black colour would be used as the background for padding!\n new_im = Image.new(\"RGB\", size)\n\n new_im.paste(im, ((size[0] - old_im_size[0]) // 2,\n (size[1] - old_im_size[1]) // 2))\n\n new_im.save(outfile, \"JPEG\")\nexcept IOError:\n print\n \"Cannot resize '%s'\" % infile\n\n# Read in the image_data\nimage_data = tf.gfile.FastGFile(outfile, 'rb').read()\n\n# Loads label file, strips off carriage return\nlabel_lines = [line.rstrip() for line\n in tf.gfile.GFile(\"/Users/hangeulbae/Desktop/output_labels.txt\")]\n\n# Unpersists graph from file\nwith tf.gfile.FastGFile(\"/Users/hangeulbae/Desktop/output_graph.pb\", 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n _ = tf.import_graph_def(graph_def, name='')\n\ninit_ops = tf.global_variables_initializer()\nwith tf.Session() as sess:\n sess.run(init_ops)\n # Feed the image_data as input to the graph and get first prediction\n softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')\n\n predictions = sess.run(softmax_tensor, \\\n {'DecodeJpeg/contents:0': image_data})\n\n # Sort to show labels of first prediction in order of confidence\n top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]\n\n for node_id in top_k:\n human_string = label_lines[node_id]\n score = predictions[0][node_id]\n print('%s (score = %.5f)' % (human_string, score))\nos.remove(outfile)","sub_path":"classify_le_gi.py","file_name":"classify_le_gi.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"421223397","text":"import unittest\nimport section8_66\n\n\nclass TestSection8(unittest.TestCase):\n\n def test_one(self):\n bal = 1000\n result = section8_66.BankAccount(\"Pranav\", 100).deposit(bal)\n self.assertEqual(result, 'Available Balance {}'.format(1100))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"section8_66_test.py","file_name":"section8_66_test.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"568979228","text":"# TODO: Code commenting and RST parallel\r\n\r\nimport numpy as np\r\nimport openmdao.api as om\r\nfrom wisdem.floatingse import FloatingSE\r\nfrom wisdem.commonse import fileIO\r\n\r\nplot_flag = False # True\r\nopt_flag = False\r\n\r\nnpts = 5\r\nnsection = npts - 1\r\n\r\nopt = {}\r\nopt[\"platform\"] = {}\r\nopt[\"platform\"][\"columns\"] = {}\r\nopt[\"platform\"][\"columns\"][\"main\"] = {}\r\nopt[\"platform\"][\"columns\"][\"offset\"] = {}\r\nopt[\"platform\"][\"columns\"][\"main\"][\"n_height\"] = npts\r\nopt[\"platform\"][\"columns\"][\"main\"][\"n_layers\"] = 1\r\nopt[\"platform\"][\"columns\"][\"main\"][\"n_bulkhead\"] = 4\r\nopt[\"platform\"][\"columns\"][\"main\"][\"buckling_length\"] = 30.0\r\nopt[\"platform\"][\"columns\"][\"offset\"][\"n_height\"] = npts\r\nopt[\"platform\"][\"columns\"][\"offset\"][\"n_layers\"] = 1\r\nopt[\"platform\"][\"columns\"][\"offset\"][\"n_bulkhead\"] = 4\r\nopt[\"platform\"][\"columns\"][\"offset\"][\"buckling_length\"] = 30.0\r\nopt[\"platform\"][\"tower\"] = {}\r\nopt[\"platform\"][\"tower\"][\"buckling_length\"] = 30.0\r\nopt[\"platform\"][\"frame3dd\"] = {}\r\nopt[\"platform\"][\"frame3dd\"][\"shear\"] = True\r\nopt[\"platform\"][\"frame3dd\"][\"geom\"] = False\r\nopt[\"platform\"][\"frame3dd\"][\"dx\"] = -1\r\n# opt['platform']['frame3dd']['nM'] = 2\r\nopt[\"platform\"][\"frame3dd\"][\"Mmethod\"] = 1\r\nopt[\"platform\"][\"frame3dd\"][\"lump\"] = 0\r\nopt[\"platform\"][\"frame3dd\"][\"tol\"] = 1e-6\r\n# opt['platform']['frame3dd']['shift'] = 0.0\r\nopt[\"platform\"][\"gamma_f\"] = 1.35 # Safety factor on loads\r\nopt[\"platform\"][\"gamma_m\"] = 1.3 # Safety factor on materials\r\nopt[\"platform\"][\"gamma_n\"] = 1.0 # Safety factor on consequence of failure\r\nopt[\"platform\"][\"gamma_b\"] = 1.1 # Safety factor on buckling\r\nopt[\"platform\"][\"gamma_fatigue\"] = 1.755 # Not used\r\nopt[\"platform\"][\"run_modal\"] = True # Not used\r\n\r\nopt[\"flags\"] = {}\r\nopt[\"flags\"][\"monopile\"] = False\r\n\r\nopt[\"TowerSE\"] = {}\r\nopt[\"TowerSE\"][\"n_height_tower\"] = npts\r\nopt[\"TowerSE\"][\"n_layers_tower\"] = 1\r\nopt[\"materials\"] = {}\r\nopt[\"materials\"][\"n_mat\"] = 1\r\n\r\n# Initialize OpenMDAO problem and FloatingSE Group\r\nprob = om.Problem()\r\nprob.model = FloatingSE(modeling_options=opt)\r\nprob.setup()\r\n\r\n# Mooring parameters\r\nprob[\"number_of_mooring_connections\"] = 3 # Evenly spaced around structure\r\nprob[\"mooring_lines_per_connection\"] = 1 # Evenly spaced around structure\r\nprob[\"mooring_type\"] = \"nylon\" # Options are chain, nylon, polyester, fiber, or iwrc\r\nprob[\"anchor_type\"] = \"suctionpile\" # Options are SUCTIONPILE or DRAGEMBEDMENT\r\n\r\n# Remove all offset columns\r\nprob[\"number_of_offset_columns\"] = 0\r\nprob[\"cross_attachment_pontoons_int\"] = 0\r\nprob[\"lower_attachment_pontoons_int\"] = 0\r\nprob[\"upper_attachment_pontoons_int\"] = 0\r\nprob[\"lower_ring_pontoons_int\"] = 0\r\nprob[\"upper_ring_pontoons_int\"] = 0\r\nprob[\"outer_cross_pontoons_int\"] = 0\r\n\r\n# Set environment to that used in OC3 testing campaign\r\nprob[\"water_depth\"] = 320.0 # Distance to sea floor [m]\r\nprob[\"hsig_wave\"] = 10.8 # Significant wave height [m]\r\nprob[\"Tsig_wave\"] = 9.8 # Wave period [s]\r\nprob[\"Uref\"] = 11.0 # Wind reference speed [m/s]\r\nprob[\"zref\"] = 119.0 # Wind reference height [m]\r\n\r\n# Column geometry\r\nprob[\"main.permanent_ballast_height\"] = 5.0 # Height above keel for permanent ballast [m]\r\nprob[\"main_freeboard\"] = 8.0 # Height extension above waterline [m]\r\nprob[\"main.height\"] = np.sum([10.0, 20.0, 10.0, 8.0])\r\nprob[\"main.s\"] = np.cumsum([0.0, 10.0, 20.0, 10.0, 5.0]) / prob[\"main.height\"]\r\nprob[\"main.outer_diameter_in\"] = 14.0 * np.ones(nsection + 1)\r\nprob[\"main.layer_thickness\"] = 0.04 * np.ones((1, nsection))\r\nprob[\"main.bulkhead_thickness\"] = 0.05 * np.ones(4)\r\nprob[\"main.bulkhead_locations\"] = np.array([0.0, 0.25, 0.9, 1.0])\r\n\r\n# Column ring stiffener parameters\r\nprob[\"main.stiffener_web_height\"] = 0.10 * np.ones(nsection) # (by section) [m]\r\nprob[\"main.stiffener_web_thickness\"] = 0.04 * np.ones(nsection) # (by section) [m]\r\nprob[\"main.stiffener_flange_width\"] = 0.10 * np.ones(nsection) # (by section) [m]\r\nprob[\"main.stiffener_flange_thickness\"] = 0.02 * np.ones(nsection) # (by section) [m]\r\nprob[\"main.stiffener_spacing\"] = 0.40 * np.ones(nsection) # (by section) [m]\r\n\r\n# Mooring parameters\r\nprob[\"mooring_diameter\"] = 0.5 # Diameter of mooring line/chain [m]\r\nprob[\"fairlead\"] = 40.0 # Distance below waterline for attachment [m]\r\nprob[\"fairlead_offset_from_shell\"] = 30.0 # Offset from shell surface for mooring attachment [m]\r\nprob[\"mooring_line_length\"] = 250.0 # Unstretched mooring line length\r\nprob[\"anchor_radius\"] = 50.0 # Distance from centerline to sea floor landing [m]\r\nprob[\"fairlead_support_outer_diameter\"] = 5.0 # Diameter of all fairlead support elements [m]\r\nprob[\"fairlead_support_wall_thickness\"] = 0.05 # Thickness of all fairlead support elements [m]\r\n\r\n# Other variables to avoid divide by zeros, even though it won't matter\r\nprob[\"radius_to_offset_column\"] = 15.0\r\nprob[\"offset_freeboard\"] = 0.1\r\nprob[\"off.height\"] = 1.0\r\nprob[\"off.s\"] = np.linspace(0, 1, nsection + 1)\r\nprob[\"off.outer_diameter_in\"] = 5.0 * np.ones(nsection + 1)\r\nprob[\"off.layer_thickness\"] = 0.1 * np.ones((1, nsection))\r\nprob[\"off.permanent_ballast_height\"] = 0.1\r\nprob[\"off.stiffener_web_height\"] = 0.1 * np.ones(nsection)\r\nprob[\"off.stiffener_web_thickness\"] = 0.1 * np.ones(nsection)\r\nprob[\"off.stiffener_flange_width\"] = 0.1 * np.ones(nsection)\r\nprob[\"off.stiffener_flange_thickness\"] = 0.1 * np.ones(nsection)\r\nprob[\"off.stiffener_spacing\"] = 0.1 * np.ones(nsection)\r\nprob[\"pontoon_outer_diameter\"] = 1.0\r\nprob[\"pontoon_wall_thickness\"] = 0.1\r\n\r\n\r\n### Variables common to these spar, semi, TLP examples ###\r\n# Set environment to that used in OC4 testing campaign\r\nprob[\"shearExp\"] = 0.11 # Shear exponent in wind power law\r\nprob[\"cm\"] = 2.0 # Added mass coefficient\r\nprob[\"Uc\"] = 0.0 # Mean current speed\r\nprob[\"wind_z0\"] = 0.0 # Water line\r\nprob[\"yaw\"] = 0.0 # Turbine yaw angle\r\nprob[\"beta_wind\"] = prob[\"beta_wave\"] = 0.0 # Wind/water beta angle\r\nprob[\"cd_usr\"] = -1.0 # Compute drag coefficient\r\n\r\n# Wind and water properties\r\nprob[\"rho_air\"] = 1.226 # Density of air [kg/m^3]\r\nprob[\"mu_air\"] = 1.78e-5 # Viscosity of air [kg/m/s]\r\nprob[\"rho_water\"] = 1025.0 # Density of water [kg/m^3]\r\nprob[\"mu_water\"] = 1.08e-3 # Viscosity of water [kg/m/s]\r\n\r\n# Material properties\r\nprob[\"rho_mat\"] = np.array([7850.0]) # Steel [kg/m^3]\r\nprob[\"E_mat\"] = 200e9 * np.ones((1, 3)) # Young's modulus [N/m^2]\r\nprob[\"G_mat\"] = 79.3e9 * np.ones((1, 3)) # Shear modulus [N/m^2]\r\nprob[\"sigma_y_mat\"] = np.array([3.45e8]) # Elastic yield stress [N/m^2]\r\nprob[\"permanent_ballast_density\"] = 4492.0 # [kg/m^3]\r\n\r\n# Mass and cost scaling factors\r\nprob[\"outfitting_factor\"] = 0.06 # Fraction of additional outfitting mass for each column\r\nprob[\"ballast_cost_rate\"] = 0.1 # Cost factor for ballast mass [$/kg]\r\nprob[\"unit_cost_mat\"] = np.array([1.1]) # Cost factor for column mass [$/kg]\r\nprob[\"labor_cost_rate\"] = 1.0 # Cost factor for labor time [$/min]\r\nprob[\"painting_cost_rate\"] = 14.4 # Cost factor for column surface finishing [$/m^2]\r\nprob[\"outfitting_cost_rate\"] = 1.5 * 1.1 # Cost factor for outfitting mass [$/kg]\r\nprob[\"mooring_cost_factor\"] = 1.1 # Cost factor for mooring mass [$/kg]\r\n\r\n# Mooring parameters\r\nprob[\"number_of_mooring_connections\"] = 3 # Evenly spaced around structure\r\nprob[\"mooring_lines_per_connection\"] = 1 # Evenly spaced around structure\r\n\r\n# Porperties of turbine tower\r\nnTower = prob.model.options[\"modeling_options\"][\"TowerSE\"][\"n_height_tower\"] - 1\r\nprob[\"tower_height\"] = prob[\"hub_height\"] = 77.6\r\nprob[\"tower_s\"] = np.linspace(0.0, 1.0, nTower + 1)\r\nprob[\"tower_outer_diameter_in\"] = np.linspace(8.0, 3.87, nTower + 1)\r\nprob[\"tower_layer_thickness\"] = np.linspace(0.04, 0.02, nTower).reshape((1, nTower))\r\nprob[\"tower_outfitting_factor\"] = 1.07\r\n\r\n# Materials\r\nprob[\"material_names\"] = [\"steel\"]\r\nprob[\"main.layer_materials\"] = prob[\"off.layer_materials\"] = prob[\"tow.tower_layer_materials\"] = [\"steel\"]\r\n\r\n# Properties of rotor-nacelle-assembly (RNA)\r\nprob[\"rna_mass\"] = 350e3\r\nprob[\"rna_I\"] = 1e5 * np.array([1149.307, 220.354, 187.597, 0, 5.037, 0])\r\nprob[\"rna_cg\"] = np.array([-1.132, 0, 0.509])\r\nprob[\"rna_force\"] = np.array([1284744.196, 0, -112400.5527])\r\nprob[\"rna_moment\"] = np.array([3963732.762, 896380.8464, -346781.682])\r\n\r\n# Mooring constraints\r\nprob[\"max_draft\"] = 150.0 # Max surge/sway offset [m]\r\nprob[\"max_offset\"] = 100.0 # Max surge/sway offset [m]\r\nprob[\"operational_heel\"] = 10.0 # Max heel (pitching) angle [deg]\r\n\r\n# Design constraints\r\nprob[\"connection_ratio_max\"] = 0.25 # For welding pontoons to columns\r\n\r\n# API 2U flag\r\nprob[\"loading\"] = \"hydrostatic\"\r\n\r\n\r\n# Use FD and run optimization\r\nprob.run_model()\r\nprob.model.list_outputs(values=True, units=True)\r\n\r\n# Visualize with mayavi, which can be difficult to install\r\nif plot_flag:\r\n import wisdem.floatingse.visualize as viz\r\n\r\n vizobj = viz.Visualize(prob)\r\n vizobj.draw_spar()\r\n","sub_path":"examples/09_floating/tlp_example.py","file_name":"tlp_example.py","file_ext":"py","file_size_in_byte":8790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"615247375","text":"import numpy as np\nfrom edges_io import io\n\n\ndef impedance2gamma(Z, Z0):\n return (Z - Z0) / (Z + Z0)\n\n\ndef gamma2impedance(r, Z0):\n return Z0 * (1 + r) / (1 - r)\n\n\ndef gamma_de_embed(s11, s12s21, s22, rp):\n return (rp - s11) / (s22 * (rp - s11) + s12s21)\n\n\ndef gamma_shifted(s11, s12s21, s22, r):\n return s11 + (s12s21 * r / (1 - s22 * r))\n\n\ndef s2p_read(path_filename):\n\n # loading data\n d, flag = io.S1P._get_kind(path_filename)\n f = d[:, 0]\n\n if flag == \"DB\":\n r = 10 ** (d[:, 1] / 20) * (\n np.cos((np.pi / 180) * d[:, 2]) + 1j * np.sin((np.pi / 180) * d[:, 2])\n )\n if flag == \"MA\":\n r = d[:, 1] * (\n np.cos((np.pi / 180) * d[:, 2]) + 1j * np.sin((np.pi / 180) * d[:, 2])\n )\n if flag == \"RI\":\n r = d[:, 1] + 1j * d[:, 2]\n r1 = d[:, 3] + 1j * d[:, 4]\n r2 = d[:, 5] + 1j * d[:, 6]\n r3 = d[:, 7] + 1j * d[:, 8]\n return r, r1, r2, r3, f\n\n\ndef de_embed(r1a, r2a, r3a, r1m, r2m, r3m, rp):\n # This only works with 1D arrays, where each point in the array is\n # a value at a given frequency\n\n # The output is also a 1D array\n\n s11 = np.zeros(len(r1a)) + 0j # 0j added to make array complex\n s12s21 = np.zeros(len(r1a)) + 0j\n s22 = np.zeros(len(r1a)) + 0j\n\n for i in range(len(r1a)):\n b = np.array([r1m[i], r2m[i], r3m[i]]) # .reshape(-1,1)\n A = np.array(\n [\n [1, r1a[i], r1a[i] * r1m[i]],\n [1, r2a[i], r2a[i] * r2m[i]],\n [1, r3a[i], r3a[i] * r3m[i]],\n ]\n )\n x = np.linalg.lstsq(A, b, rcond=None)[0]\n s11[i] = x[0]\n s12s21[i] = x[1] + x[0] * x[2]\n s22[i] = x[2]\n\n r = gamma_de_embed(s11, s12s21, s22, rp)\n\n return r, s11, s12s21, s22\n\n\ndef fiducial_parameters_85033E(R, md=1, md_value_ps=38):\n # Parameters of open\n open_off_Zo = 50\n open_off_delay = 29.243e-12\n open_off_loss = 2.2 * 1e9\n open_C0 = 49.43e-15\n open_C1 = -310.1e-27\n open_C2 = 23.17e-36\n open_C3 = -0.1597e-45\n\n op = np.array(\n [open_off_Zo, open_off_delay, open_off_loss, open_C0, open_C1, open_C2, open_C3]\n )\n\n # Parameters of short\n short_off_Zo = 50\n short_off_delay = 31.785e-12\n short_off_loss = 2.36 * 1e9\n short_L0 = 2.077e-12\n short_L1 = -108.5e-24\n short_L2 = 2.171e-33\n short_L3 = -0.01e-42\n\n sp = np.array(\n [\n short_off_Zo,\n short_off_delay,\n short_off_loss,\n short_L0,\n short_L1,\n short_L2,\n short_L3,\n ]\n )\n\n # Parameters of match\n match_off_Zo = 50\n\n if md == 0:\n match_off_delay = 0\n elif md == 1:\n match_off_delay = md_value_ps * 1e-12 # 38 ps, from Monsalve et al. (2016)\n match_off_loss = 2.3 * 1e9\n match_R = R\n\n mp = np.array([match_off_Zo, match_off_delay, match_off_loss, match_R])\n\n return (op, sp, mp)\n\n\ndef standard_open(f, par):\n \"\"\"\n frequency in Hz\n \"\"\"\n\n offset_Zo = par[0]\n offset_delay = par[1]\n offset_loss = par[2]\n C0 = par[3]\n C1 = par[4]\n C2 = par[5]\n C3 = par[6]\n\n # Termination\n Ct_open = C0 + C1 * f + C2 * f ** 2 + C3 * f ** 3\n Zt_open = 0 - 1j / (2 * np.pi * f * Ct_open)\n Rt_open = impedance2gamma(Zt_open, 50)\n\n # Transmission line\n Zc_open = (\n offset_Zo + (offset_loss / (2 * 2 * np.pi * f)) * np.sqrt(f / 1e9)\n ) - 1j * (offset_loss / (2 * 2 * np.pi * f)) * np.sqrt(f / 1e9)\n temp = ((offset_loss * offset_delay) / (2 * offset_Zo)) * np.sqrt(f / 1e9)\n gl_open = temp + 1j * ((2 * np.pi * f) * offset_delay + temp)\n\n # Combined reflection coefficient\n R1 = impedance2gamma(Zc_open, 50)\n ex = np.exp(-2 * gl_open)\n Rt = Rt_open\n Ri_open = (R1 * (1 - ex - R1 * Rt) + ex * Rt) / (1 - R1 * (ex * R1 + Rt * (1 - ex)))\n\n return Ri_open\n\n\ndef standard_short(f, par):\n \"\"\"\n frequency in Hz\n \"\"\"\n\n offset_Zo = par[0]\n offset_delay = par[1]\n offset_loss = par[2]\n L0 = par[3]\n L1 = par[4]\n L2 = par[5]\n L3 = par[6]\n\n # Termination\n Lt_short = L0 + L1 * f + L2 * f ** 2 + L3 * f ** 3\n Zt_short = 0 + 1j * 2 * np.pi * f * Lt_short\n Rt_short = impedance2gamma(Zt_short, 50)\n\n # Transmission line %%%%\n Zc_short = (\n offset_Zo + (offset_loss / (2 * 2 * np.pi * f)) * np.sqrt(f / 1e9)\n ) - 1j * (offset_loss / (2 * 2 * np.pi * f)) * np.sqrt(f / 1e9)\n temp = ((offset_loss * offset_delay) / (2 * offset_Zo)) * np.sqrt(f / 1e9)\n gl_short = temp + 1j * ((2 * np.pi * f) * offset_delay + temp)\n\n # Combined reflection coefficient %%%%\n R1 = impedance2gamma(Zc_short, 50)\n ex = np.exp(-2 * gl_short)\n Rt = Rt_short\n Ri_short = (R1 * (1 - ex - R1 * Rt) + ex * Rt) / (\n 1 - R1 * (ex * R1 + Rt * (1 - ex))\n )\n\n return Ri_short\n\n\ndef standard_match(f, par):\n \"\"\"\n frequency in Hz\n \"\"\"\n\n offset_Zo = par[0]\n offset_delay = par[1]\n offset_loss = par[2]\n Resistance = par[3]\n\n # Termination\n Zt_match = Resistance\n Rt_match = impedance2gamma(Zt_match, 50)\n\n # Transmission line\n Zc_match = (\n offset_Zo + (offset_loss / (2 * 2 * np.pi * f)) * np.sqrt(f / 1e9)\n ) - 1j * (offset_loss / (2 * 2 * np.pi * f)) * np.sqrt(f / 1e9)\n temp = ((offset_loss * offset_delay) / (2 * offset_Zo)) * np.sqrt(f / 1e9)\n gl_match = temp + 1j * ((2 * np.pi * f) * offset_delay + temp)\n\n # combined reflection coefficient %%%%\n R1 = impedance2gamma(Zc_match, 50)\n ex = np.exp(-2 * gl_match)\n Rt = Rt_match\n Ri_match = (R1 * (1 - ex - R1 * Rt) + ex * Rt) / (\n 1 - R1 * (ex * R1 + Rt * (1 - ex))\n )\n\n return Ri_match\n\n\ndef agilent_85033E(f, resistance_of_match, m=1, md_value_ps=38):\n \"\"\"\n frequency in Hz\n \"\"\"\n\n op, sp, mp = fiducial_parameters_85033E(\n resistance_of_match, md=m, md_value_ps=md_value_ps\n )\n o = standard_open(f, op)\n s = standard_short(f, sp)\n m = standard_match(f, mp)\n\n return (o, s, m)\n\n\ndef input_impedance_transmission_line(Z0, gamma, length, Zload):\n \"\"\"\n Z0: complex characteristic impedance\n gamma: propagation constant\n length: length of transmission line\n Zload: impedance of termination\n \"\"\"\n\n Zin = (\n Z0\n * (Zload + Z0 * np.tanh(gamma * length))\n / (Zload * np.tanh(gamma * length) + Z0)\n )\n\n return Zin\n","sub_path":"src/edges_cal/reflection_coefficient.py","file_name":"reflection_coefficient.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"414827502","text":"def __init__(self, attrs, module):\n self._attributes = attrs\n self._module = module\n self.attr_names = frozenset(self._attributes.keys())\n self._has_key = False\n for (name, attr) in iteritems(self._attributes):\n if attr.get('read_from'):\n spec = self._module.argument_spec.get(attr['read_from'])\n if (not spec):\n raise ValueError(('argument_spec %s does not exist' % attr['read_from']))\n for (key, value) in iteritems(spec):\n if (key not in attr):\n attr[key] = value\n if attr.get('key'):\n if self._has_key:\n raise ValueError('only one key value can be specified')\n self_has_key = True\n attr['required'] = True","sub_path":"Data Set/bug-fixing-5/38775c53637e9c7ddad6c72b6323fd6c4f442386-<__init__>-bug.py","file_name":"38775c53637e9c7ddad6c72b6323fd6c4f442386-<__init__>-bug.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"570436674","text":"import pprint\n\n\nN = 6\nDP = [[0]*N for _ in range(N)]\ni = 1\nfor j in range(1,N):\n x = j\n y = 0\n while x < N and y < N:\n DP[y][x] = i\n i += 1\n x += 1 \n y += 1\npprint.pprint(DP)","sub_path":"10월/1011/연습장.py","file_name":"연습장.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"117712973","text":"\"\"\"\n正则表达式\n\"\"\"\nimport re\n# print(dir(re))\n# pattern = \"py1811\"\n# restr = \"py1811hellopy1811 hi py1811\"\n# result = re.match(pattern,restr)\n# result = re.search(pattern,restr)\n# result = re.fullmatch(pattern,restr)\n# print(result.group())\n# result = re.findall(pattern,restr)\n# result = re.split(pattern,restr)\n\n# result = re.sub(pattern,\"python1811\",restr,2)\n\n# result = re.finditer(pattern,restr)\n# print(result)\n# for r in result:\n# print(r.group())\n\n# print(result)\n\n# pattern = re.compile(\"py1811\")\n# result = pattern.findall(restr)\n# print(result)\n\n\n\n\"\"\"\n得到Match对象可以使用group方法\nmatch从头匹配\nsearch匹配第一个\nfullmatch从头匹配到尾\n\nfinditer 返回迭代器,迭代器中每一个元素都是Math对象都有group方法\n\n得到列表列表项\nfindall 可以匹配到所有内容\nsplit 使用正则切割字符串\n\n返回字符串\nsub 用新字符替换能够被正则匹配到的内容\n\n\ncompile可以得到一个pattern模型 进而通过模型调用响应方法\n\n\"\"\"\n\n\n# result = re.findall(\"\\W\",\"Py({[181 1he5ll oP\\tY1.8+*11\")\n# print(result)\n\n\"\"\"\nre.I 忽略大小写\nre.S 单行模式,在单行模式下 .符号可以匹配\\n\n\"\"\"\n\n\n\"\"\" 8\n.可以匹配任意字符\n[]可以匹配其中一个 -代表范围\n\\d 数字 \\D非数字\n\\s 空格或制表符 \\S非空格.��表符\n\\w 匹配字母[0-9a-zA-Z] \\W匹配非字母\n\"\"\"\n\n\".*?\"\n\n# result = re.findall(\"\\Wello\", \"hello aello5ello_ello .ello ^ello\")\n# print(result)\n# result = re.findall(\"hi{1,2}\", \"hi china hello chiiina\")\n# print(result)\n\"\"\"\n*可以匹配》=0\n+可以匹配》=1\n?可以匹配0、1\n{m} 出现m次\n{m,} 出现》=m次\n{m,n}出现m-n次\n\"\"\"\n\n# result = re.findall(\"\\\\bhello\\\\b\", \"ahellohihhh_h_ hello\")\n# print(result)\n\"\"\"\n^开头\n$结尾\n\\b单词边界\n\\B非单词边界\n\"\"\"\n\n# result = re.findall(\"hello.world\",\"hello\\nworld\",re.S)\n# print(result)\n\n# result = re.match(r\"(abc)aaabbc\\1\",\"abcaaabbcabc\")\n# print(result.group(),result.group(1))\n\n# result = re.match(r\"(?Phello) world (?P=hname)\", \"hello world hello china\")\n# print(result.group(), result.group(\"hname\"))\n\n# result = re.findall(\"e$\",\"abcde\\nabcd\",re.M)\n# print(result)\n\nimport requests\ndef getinfo2():\n response = requests.get(\"http://quote.stockstar.com/stock/ranklist_a_3_1_1.html\")\n content = response.text\n result = re.findall(\n '(\\d{6})(.*?)',\n content)\n return result\n\ndef getinfo():\n with open(\"content.txt\", \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n # print(content)\n result = re.findall(\n '(\\d{6})(.*?)',\n content)\n return result\n\ndef writefile():\n # print(getinfo())\n with open(\"result.txt\", \"w\", encoding=\"utf-8\") as f:\n for r in getinfo2():\n f.write(r[0]+\"\\t\"+r[1])\n f.write(\"\\n\")\n\n\n\nif __name__ == \"__main__\":\n writefile()\n\n\n\n\n","sub_path":"PythonAdvance/day0222/demo47.py","file_name":"demo47.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"517188826","text":"import numpy as np\nfrom gunpowder import Array, BatchFilter\nfrom scipy import ndimage\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass FusionAugment(BatchFilter):\n \"\"\"Combine foreground of two volumes.\n \n Fusion process details:\n The whole \"base\" volume is kept un-modified, we simply add the\n \"add\" volume to it. To avoid changing the noise profile of the background\n and to minimize the impact of our fusion on the true data, we use\n the \"add\" labels which are assumed to be rough estimates of the signal\n location, covering a relatively large area surrounding the desired signal.\n Denote this smoothed labelling as alpha, then the output fused array is\n simply base + alpha * add.\n We end up with a fused volume with a smooth transitions between true image\n data and fused image data.\n Note: if the true \"base\" signal exactly overlaps with\n the true \"add\" signal, there will be excessively bright voxels, thus it\n is important to guarantee that the signals do not exactly overlap. This can\n be achieved by using the \"GetNeuronPair\" node.\n Note: if the \"base\" labels overlap with the \"add\" labels which will often\n occur if you want the true signals to be close, the overlapping areas will\n be given a label of -1 in the fused_labels array.\n\n Args:\n raw_base (:class:``ArrayKey``):\n\n The intensity array for \"base\" volume.\n\n raw_add (:class:``ArrayKey``):\n\n The intensity array for \"add\" volume.\n\n labels_base (:class:``ArrayKey``):\n\n The labeled array for \"base\" volume.\n\n labels_add (:class:``ArrayKey``):\n\n The labeled array for \"add\" volume.\n\n raw_fused (:class:``ArrayKey``):\n\n The intensity array for \"fused\" volume.\n\n labels_fused (:class:``ArrayKey``):\n\n The labeled array for \"fused\" volume.\n\n blend_mode(``string``, optional):\n\n One of \"labels_mask\" or \"intensities\". If \"labels_mask\" (the default),\n alpha blending is applied to the labels mask of \"add\" volume. If\n \"intensities\", raw intensities of \"add\" volume are used.\n\n blend_smoothness (``float``, optional):\n\n Set sigma for gaussian smoothing of labels mask of \"add\" volume.\n \"\"\"\n\n def __init__(\n self,\n raw_base,\n raw_add,\n labels_base,\n labels_add,\n raw_fused,\n labels_fused,\n blend_mode=\"labels_mask\",\n blend_smoothness=3,\n num_blended_objects=0,\n ):\n\n self.raw_base = raw_base\n self.raw_add = raw_add\n self.labels_base = labels_base\n self.labels_add = labels_add\n self.raw_fused = raw_fused\n self.labels_fused = labels_fused\n self.blend_mode = blend_mode\n self.blend_smoothness = blend_smoothness\n self.num_blended_objects = num_blended_objects\n\n assert self.blend_mode in [\"intensity\", \"labels_mask\"], (\n \"Unknown blend mode %s.\" % self.blend_mode\n )\n\n def setup(self):\n\n self.provides(self.raw_fused, self.spec[self.raw_base].copy())\n self.provides(self.labels_fused, self.spec[self.labels_base].copy())\n\n def prepare(self, request):\n\n # add \"base\" and \"add\" volume to request\n request[self.raw_base] = request[self.raw_fused].copy()\n request[self.raw_add] = request[self.raw_fused].copy()\n\n # enlarge roi for labels to be the same size as the raw data for mask generation\n request[self.labels_base] = request[self.raw_fused].copy()\n request[self.labels_add] = request[self.raw_fused].copy()\n\n def process(self, batch, request):\n\n # Get base arrays\n raw_base_array = batch[self.raw_base].data\n labels_base_array = batch[self.labels_base].data\n\n # Get add arrays\n raw_add_array = batch[self.raw_add].data\n labels_add_array = batch[self.labels_add].data\n\n # fuse labels\n fused_labels_array = self._relabel(labels_base_array.astype(np.int32))\n next_label_id = np.max(fused_labels_array) + 1\n\n add_mask = np.zeros_like(fused_labels_array, dtype=bool)\n for label in np.unique(labels_add_array):\n if label == 0:\n continue\n label_mask = labels_add_array == label\n add_mask[label_mask] = True\n fused_labels_array[label_mask] = next_label_id\n next_label_id += 1\n # handle overlap\n overlap = np.logical_and(fused_labels_array, label_mask)\n fused_labels_array[overlap] = -1\n\n # fuse raw\n if self.blend_mode == \"intensity\":\n\n add_mask = raw_add_array.astype(np.float32) / np.max(raw_add_array)\n raw_fused_array = add_mask * raw_add_array + (1 - add_mask) * raw_base_array\n\n elif self.blend_mode == \"labels_mask\":\n\n soft_mask = np.zeros_like(add_mask, dtype=\"float32\")\n ndimage.gaussian_filter(\n add_mask.astype(\"float32\"),\n sigma=self.blend_smoothness,\n output=soft_mask,\n mode=\"nearest\",\n )\n soft_mask /= np.max(soft_mask)\n soft_mask = np.clip((soft_mask * 2), 0, 1)\n\n raw_fused_array = soft_mask * raw_add_array + raw_base_array\n\n else:\n raise NotImplementedError(\"Unknown blend mode %s.\" % self.blend_mode)\n\n # load specs\n labels_add_spec = batch[self.labels_add].spec.copy()\n labels_fused_spec = request[self.labels_fused].copy()\n raw_base_spec = batch[self.raw_base].spec.copy()\n\n # return raw and labels for \"fused\" volume\n batch.arrays[self.raw_fused] = Array(\n data=raw_fused_array.astype(raw_base_spec.dtype), spec=raw_base_spec\n )\n batch.arrays[self.labels_fused] = Array(\n data=labels_base_array.astype(labels_fused_spec.dtype), spec=labels_add_spec\n ).crop(labels_fused_spec.roi)\n\n return batch\n\n def _relabel(self, a):\n\n labels = list(np.unique(a))\n if 0 in labels:\n labels.remove(0)\n\n old_values = np.asarray(labels, dtype=np.int32)\n new_values = np.arange(1, len(labels) + 1, dtype=np.int32)\n\n values_map = np.arange(int(a.max() + 1), dtype=new_values.dtype)\n values_map[old_values] = new_values\n\n return values_map[a.copy()]\n","sub_path":"neurolight/gunpowder/fusion_augment.py","file_name":"fusion_augment.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"404554817","text":"import random\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtGui import QFont, QPixmap\n\nSHELF_SIZE = 50\nT = 0\nV = 1\nA = 1\nX_V = 1\nfrom PyQt5.QtCore import QTimer\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\n\n\ndef make_w():\n window1 = QMainWindow()\n window1.showFullScreen()\n window1.setStyleSheet(\"background-color: #FF9E73\")\n\n window1.show()\n\n\ndef move_clock(clock):\n x = clock.x()\n y = clock.y()\n\n\ndef jump_to_down(starting_cordinate_hero, hero):\n global T, V, A\n start_y = starting_cordinate_hero[0]\n Y = (V - 2) * T + A * T * T / 2\n hero.move(hero.x() + (Y * 0.1), start_y + (Y * 0.8))\n T = T + 0.7\n hero.resize(hero.width() + 3, hero.height() + 3)\n if hero.x() >= window.width() // 2 - hero.width() // 2 or hero.y() >= window.height() // 2 - hero.height() // 2:\n hero.timer.stop()\n\n\nroot = QApplication([])\nwindow = QMainWindow()\nbg_new = 'background-color: rgb(%d,%d,%d);' % (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))\n\nwindow.setStyleSheet(bg_new)\nwindow.resize(900, 600)\n#\n# quit = QAction(\"Quit\", window)\n# quit.triggered.connect(lambda: make_w())\n\nclock = QtWidgets.QLabel(window)\nclock.setFont(QFont(\"setItalic\", 20))\nclock.setText('Label Example')\nbg_new = 'background-color: rgb(%d,%d,%d);' % (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255))\nclock.setStyleSheet(bg_new)\nclock.move(0, 0)\nwindow.layout().addWidget(clock)\nwindow.clock = clock\n\nclock.timer = QTimer()\ntimer = window.clock.timer\nstarting_cordinate_hero = [window.clock.y(), window.clock.x()]\ntimer.timeout.connect(lambda: jump_to_down(starting_cordinate_hero, window.clock))\ntimer.start(30)\n\nwindow.show()\nroot.exec()\n","sub_path":"coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"490386910","text":"def triangleNumber(n):\n '''Calculates the triangle number'''\n\n tn = 0\n \n for i in range(n, 0, -1):\n tn = tn + i \n\n return tn\n\nn = int(input(\"Enter the number: \"))\n\ni = 1\ncount = n + 1\n\nprint(\"n\", '\\t', \"Triangle number\")\nprint(\"-\", '\\t', \"---------------\")\n \nfor i in range(count):\n print(i, '\\t', triangleNumber(i))\n","sub_path":"python/basics/triangle_number.py","file_name":"triangle_number.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"203566145","text":"# -*- coding:utf-8 -*-\n# @author :adolf\nimport cv2\nimport json\nfrom flask import Flask\nfrom flask import request\nimport traceback\nfrom flask_cors import CORS\nfrom NAP.guanshui import one_page\nimport pdfplumber\nimport base64\nimport uuid\n\n\"\"\"\nsupport ocr服务\n\"\"\"\napp = Flask(__name__)\nCORS(app, resources=r'/*')\n\n\n@app.route('/NAP_ocr_service/', methods=[\"post\", \"get\"], strict_slashes=False)\ndef service_main():\n try:\n in_json = request.get_data()\n if in_json is not None:\n in_dict = json.loads(in_json.decode(\"utf-8\"))\n pdf_with_base64 = in_dict['image']\n\n uid_pdf = uuid.uuid4()\n with open(\"{}.pdf\".format(uid_pdf), \"wb\") as fw:\n fw.write(base64.b64decode(pdf_with_base64))\n\n pdf = pdfplumber.open(\"{}.pdf\".format(uid_pdf))\n\n result_dict = dict()\n for page in pdf.pages:\n res_page = one_page(page)\n # result_dict['result'] = res_page[\"result\"]\n for i in range(len(res_page[\"填发日期\"])):\n # print(i)\n tmp_dict = dict()\n for key in res_page:\n tmp_dict[key] = res_page[key][i]\n result_dict[str(i)] = tmp_dict\n\n print(result_dict.keys())\n return json.dumps(result_dict, ensure_ascii=False)\n else:\n return json.dumps({\"error_msg\": \"data is None\", \"status\": 1}, ensure_ascii=False)\n except Exception as e:\n traceback.print_exc()\n return json.dumps({\"error_msg\": \"unknown error:\" + repr(e), \"status\": 1}, ensure_ascii=False)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=2003, debug=True)\n","sub_path":"NAP/nap_service.py","file_name":"nap_service.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"432618728","text":"#!/bin/python3\r\n\"\"\"Hangman version 1\r\n Python 3.7.2\"\"\"\r\n\r\n\r\nimport random\r\n\r\n\r\ndef hang_man():\r\n \"\"\"Hangman game\"\"\"\r\n word_list = ['it', 'crime', 'stone', 'member', 'reports', 'cry',\r\n 'badge', 'dude', 'hang', 'man']\r\n word = random.choice(word_list)\r\n letter_list = list(word)\r\n count = 0\r\n guesses = []\r\n incorrect_letters = []\r\n\r\n for count in range(len(letter_list * 3)):\r\n guess_letter = input('Guess a letter. ')\r\n\r\n if guess_letter in letter_list:\r\n guesses.append(guess_letter)\r\n locate = letter_list.index(guess_letter)\r\n print(f'There is a {guess_letter} at {locate}.')\r\n print(guesses)\r\n\r\n count += 1\r\n while count >= 1:\r\n guess_word = input('Guess the word, y/n? ')\r\n if guess_word == 'y':\r\n guess = input('What is the word? ')\r\n elif guess_word == 'n':\r\n break\r\n elif guess in word:\r\n print('You avoided death!')\r\n raise SystemExit\r\n else:\r\n print('Wrong!')\r\n break\r\n else:\r\n incorrect_letters.append(guess_letter)\r\n if guess_letter in incorrect_letters:\r\n if len(incorrect_letters) > 1:\r\n print('You already guessed that letter!')\r\n print(f'There is no {guess_letter}.')\r\n else:\r\n print(f'You\\'re hung! The word was {word}.')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n hang_man()\r\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"318814410","text":"#coding=utf-8\n\"\"\"\n将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中\n\"\"\"\nfrom lxml import etree\nimport xlrd\nroot=etree.Element('root')\ncity_xml=etree.ElementTree(root)\n\n\n\ndef openxls():\n excel=xlrd.open_workbook('citys.xls')\n test1=excel.sheet_by_name('test1')\n return test1\n\ncitys={}\ntest1 = openxls()\nfor row_index in range(test1.nrows):\n citys[test1.cell(rowx=row_index,colx=0).value]=test1.cell(rowx=row_index,colx=1).value\ncity = etree.SubElement(root, \"citys\")\ncity.append(etree.Comment('城市信息'))\ncity.text=str(citys)\nwith open('city.xml', 'w', encoding='utf-8') as output:\n output.write(etree.tounicode(city_xml))\n\n#output.write(etree.tostring(city_xml, encoding='utf-8').decode(encoding=\"utf-8\")) 也可,但两种方法都必须进行解码\n\n\n","sub_path":"py0018/converxlstoxml.py","file_name":"converxlstoxml.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"65054273","text":"\"\"\"\r\nThis code pulls data from the ECMWF's ERA5 dataset. \r\n\r\nAuthor: Anthony Baum\r\n\"\"\"\r\n#-----------------------------------------------------------------------------------\r\n\r\n# Module imports\r\nimport netCDF4 as nc\r\nimport cdsapi\r\nfrom shutil import copyfile\r\nimport time\r\nfrom datetime import datetime, timedelta\r\nimport sys\r\n\r\n\r\ndef write_file_to_data_folder(output_filename):\r\n src = r'C:\\Users\\wxbau/data.nc'\r\n dest = r'C:\\Users\\wxbau\\thesis_work\\testing\\data/' + output_filename + '.nc'\r\n copyfile(src, dest)\r\n\r\n\r\ndef generate_datetime_arrays(start_datetime, end_datetime):\r\n hours = []\r\n days = []\r\n months = []\r\n years = []\r\n\r\n # Function will count through time hour by hour, populating arrays above\r\n time_counter = start_datetime\r\n while time_counter < end_datetime:\r\n # Hour\r\n hour = time_counter.hour\r\n if hour < 10:\r\n hour_string = '0' + str(hour) + ':00'\r\n else:\r\n hour_string = str(hour) + ':00'\r\n \r\n if hour_string not in hours:\r\n hours.append(hour_string)\r\n \r\n # Day\r\n day = time_counter.day\r\n day_string = str(day)\r\n if day_string not in days:\r\n days.append(day_string)\r\n\r\n # Month\r\n month = time_counter.month\r\n month_string = str(month)\r\n if month_string not in months:\r\n months.append(month_string)\r\n\r\n # Year\r\n year = time_counter.year\r\n year_string = str(year)\r\n if year_string not in years:\r\n years.append(year_string)\r\n \r\n time_counter = time_counter + timedelta(hours=1)\r\n\r\n return hours, days, months, years\r\n\r\n\r\ndef get_era5_data(start_datetime, end_datetime, pressure_level=None, variable=None, sfc_data=False): # datetime format: dd-mm-yyyy hh\r\n \r\n start_datetime = datetime.strptime(start_datetime, r'%d-%m-%Y-%H')\r\n end_datetime = datetime.strptime(end_datetime, r'%d-%m-%Y-%H')\r\n if sfc_data == True:\r\n pressure_level = 'sfc'\r\n\r\n # Error handling\r\n if start_datetime > end_datetime:\r\n sys.exit('Provided start datetime is after the provided end datetime')\r\n\r\n hours, days, months, years = generate_datetime_arrays(start_datetime, end_datetime)\r\n\r\n # API call \r\n c = cdsapi.Client() \r\n\r\n if sfc_data == True:\r\n c.retrieve('reanalysis-era5-single-levels', {\r\n 'product_type': 'reanalysis',\r\n 'format': 'netcdf',\r\n 'area': '40.00/-103.00/34.00/-94.00',\r\n 'variable': variable,\r\n 'year': years,\r\n 'month': months, \r\n 'day': days,\r\n 'time': hours\r\n }, 'data.nc')\r\n\r\n else:\r\n c.retrieve('reanalysis-era5-pressure-levels', {\r\n 'product_type': 'reanalysis',\r\n 'format': 'netcdf',\r\n 'area': '40.00/-103.00/34.00/-94.00',\r\n 'variable': variable,\r\n 'pressure_level': pressure_level,\r\n 'year': years,\r\n 'month': months,\r\n 'day': days,\r\n 'time': hours\r\n }, 'data.nc')\r\n\r\n dataset_min_date = str(min(days)) + '-' + str(min(months)) + '-' + str(min(years))\r\n dataset_max_date = str(max(days)) + '-' + str(max(months)) + '-' + str(max(years))\r\n filename_string = dataset_min_date + '_' + dataset_max_date + '_' + pressure_level + '_' + variable\r\n write_file_to_data_folder(filename_string)\r\n\r\n return None\r\n\r\n\r\n# get_era5_data(start_datetime='01-01-2018-00', end_datetime='01-01-2018-01', pressure_level='850', variable='temperature')\r\n\r\ndef run_staggered_api_pull(start_datetime, end_datetime, pressure_levels_array=None, variables_array=None, sfc_data=False): # datetime format: dd-mm-yyyy hh\r\n\r\n for variable in variables_array:\r\n if sfc_data == True:\r\n print('Fetching ' + variable + ' sfc')\r\n get_era5_data(start_datetime, end_datetime, variable=variable, sfc_data=True)\r\n time.sleep(5)\r\n else:\r\n for pressure in pressure_levels_array:\r\n # For reference, get_era5_data params are (start_datetime, end_datetime, pressure_level, variable)\r\n print('Fetching ' + variable + ' for pressure level ' + pressure)\r\n get_era5_data(start_datetime, end_datetime, pressure_level=pressure, variable=variable)\r\n time.sleep(5)\r\n\r\n return None\r\n\r\n\r\nua_pressures = ['850', '700', '500', '300']\r\nua_variables = ['temperature', 'geopotential', 'relative_humidity','u_component_of_wind','v_component_of_wind']\r\nsfc_variables = ['10m_u_component_of_wind','10m_v_component_of_wind','2m_dewpoint_temperature', '2m_temperature','mean_sea_level_pressure']\r\n\r\n# Run api call function for upper air\r\n#run_staggered_api_pull(start_datetime='25-04-2011-00', end_datetime='29-04-2011-00', pressure_levels_array=ua_pressures, variables_array=ua_variables)\r\n\r\n# Run api call function for surface data\r\nrun_staggered_api_pull(start_datetime='25-04-2011-00', end_datetime='29-04-2011-00', variables_array=sfc_variables, sfc_data=True)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"era5_access.py","file_name":"era5_access.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"225170975","text":"import simulator\nimport matplotlib.pyplot as plt\n\nenvironment= simulator.Simulator()\n\nfor i in range(100):\n environment.step(environment.uniform_sample())\n print(i)\nresult=environment.gethistory()\nplt.plot(result)\nplt.show()\n\n\n","sub_path":"random_train.py","file_name":"random_train.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"63584731","text":"import turtle\r\nimport math\r\n\r\nSCREEN_WIDTH = 800\r\nSCREEN_HEIGHT = 600\r\n\r\nwn = turtle.Screen()\r\nwn.setup(SCREEN_WIDTH, SCREEN_HEIGHT)\r\nwn.title(\"Space Arena!\")\r\nwn.bgcolor(\"black\")\r\nwn.tracer(0)\r\n\r\npen = turtle.Turtle()\r\npen.speed(0)\r\npen.shape(\"square\")\r\npen.color(\"white\")\r\npen.penup()\r\npen.hideturtle()\r\n\r\nclass Game():\r\n def __init__(self,width,height):\r\n self.width = width\r\n self.height = height\r\n\r\n\r\n def render_border(self,pen):\r\n pen.color(\"white\")\r\n pen.width(3)\r\n pen.penup()\r\n\r\n left = -self.width/2.0\r\n right = self.width/2.0\r\n top = self.height/2.0\r\n bottom = -self.height/2.0\r\n\r\n pen.goto(left, top)\r\n pen.pendown()\r\n pen.goto(right, top)\r\n pen.goto(right, bottom)\r\n pen.goto(left, bottom)\r\n pen.goto(left, top)\r\n pen.penup()\r\n\r\nclass Sprite():\r\n # Constructor\r\n def __init__(self, x, y, shape, color):\r\n self.x = x\r\n self.y = y\r\n self.shape = shape\r\n self.color = color\r\n self.dx = 0\r\n self.dy = 0\r\n self.heading = 0\r\n self.da = 0\r\n self.thrust = 0.0\r\n self.acceleration = 0.003\r\n self.health = 100\r\n self.max_health = 100\r\n self.width = 20\r\n self.height = 20\r\n\r\n def is_collision(self, other):\r\n if self.x < other.x + other.width and\\\r\n self.x + self.width > other.x and\\\r\n self.y < other.y + other.height and\\\r\n self.y + self.height > other.y:\r\n return True\r\n else:\r\n return False\r\n \r\n def update(self):\r\n self.heading += self.da\r\n self.heading %= 360\r\n \r\n self.dx += math.cos(math.radians(self.heading)) * self.thrust\r\n self.dy += math.sin(math.radians(self.heading)) * self.thrust\r\n \r\n self.x += self.dx\r\n self.y += self.dy\r\n\r\n self.border_check()\r\n \r\n def border_check(self):\r\n if self.x > game.width/2.0 - 10:\r\n self.x = game.width/2.0 - 10\r\n self.dx *= -1\r\n\r\n elif self.x <- game.width/2.0 + 10:\r\n self.x = -game.width/2.0 + 10\r\n self.dx *= -1\r\n\r\n elif self.y > game.height/2.0 - 10:\r\n self.y = game.height/2.0 - 10\r\n self.dy *= -1\r\n\r\n elif self.y <- game.height/2.0 + 10:\r\n self.y = -game.height/2.0 + 10\r\n self.dy *= -1\r\n\r\n def render(self, pen):\r\n pen.goto(self.x, self.y)\r\n pen.setheading(self.heading)\r\n pen.shape(self.shape)\r\n pen.color(self.color)\r\n pen.stamp()\r\n \r\n self.render_health_meter(pen)\r\n \r\n def render_health_meter(self, pen):\r\n # Draw health meter\r\n pen.goto(self.x - 10, self.y + 20)\r\n pen.width(3)\r\n pen.pendown()\r\n pen.setheading(0)\r\n \r\n if self.health/self.max_health < 0.3:\r\n pen.color(\"red\")\r\n elif self.health/self.max_health < 0.7:\r\n pen.color(\"yellow\")\r\n else:\r\n pen.color(\"green\")\r\n\r\n pen.fd(20.0 * (self.health/self.max_health))\r\n \r\n if self.health != self.max_health:\r\n pen.color(\"grey\")\r\n pen.fd(20.0 * ((self.max_health-self.health)/self.max_health))\r\n \r\n pen.penup()\r\n \r\nclass Player(Sprite):\r\n def __init__(self, x, y, shape, color):\r\n Sprite.__init__(self, 0, 0, shape, color)\r\n self.lives = 3\r\n self.score = 0\r\n self.heading = 90\r\n self.da = 0\r\n \r\n def rotate_left(self):\r\n self.da = 5\r\n \r\n def rotate_right(self):\r\n self.da = -5\r\n \r\n def stop_rotation(self):\r\n self.da = 0\r\n \r\n def accelerate(self):\r\n self.thrust += self.acceleration\r\n \r\n def decelerate(self):\r\n self.thrust = 0.0\r\n\r\n def fire(self):\r\n missile.fire(self.x, self.y, self.heading, self.dx, self.dy)\r\n \r\n def render(self, pen):\r\n pen.shapesize(0.5, 1.0, None)\r\n pen.goto(self.x, self.y)\r\n pen.setheading(self.heading)\r\n pen.shape(self.shape)\r\n pen.color(self.color)\r\n pen.stamp()\r\n \r\n pen.shapesize(1.0, 1.0, None)\r\n \r\n self.render_health_meter(pen)\r\n\r\nclass Missile(Sprite):\r\n def __init__(self, x, y, shape, color):\r\n Sprite.__init__(self, 0, 0, shape, color)\r\n self.state = \"ready\"\r\n self.fuel = 100\r\n self.thrust = 1.0\r\n self.max_fuel = 200\r\n self.fuel =self.max_fuel\r\n self.height = 4\r\n self.width = 4\r\n\r\n def fire(self, x, y, heading, dx, dy):\r\n if self.state == \"ready\" :\r\n self.state = \"active\"\r\n self.x = x\r\n self.y = y\r\n self.heading = heading\r\n self.dx = dx\r\n self.dy = dy\r\n\r\n self.dx += math.cos(math.radians(self.heading)) * self.thrust\r\n self.dy += math.sin(math.radians(self.heading)) * self.thrust\r\n\r\n def update(self):\r\n if self.state == \"active\":\r\n self.fuel -= self.thrust\r\n if self.fuel <=0:\r\n self.reset()\r\n \r\n self.heading += self.da\r\n self.heading %= 360\r\n \r\n self.x += self.dx\r\n self.y += self.dy\r\n\r\n self.border_check()\r\n\r\n def reset(self):\r\n self.fuel = self.max_fuel\r\n self.dx = 0\r\n self.dy = 0\r\n self.state = \"ready\"\r\n\r\n def render(self, pen):\r\n if self.state == \"active\":\r\n pen.shapesize(0.2, 0.2, None)\r\n pen.goto(self.x, self.y)\r\n pen.setheading(self.heading)\r\n pen.shape(self.shape)\r\n pen.color(self.color)\r\n pen.stamp()\r\n \r\n pen.shapesize(1.0, 1.0, None)\r\n\r\n\r\nclass Enemy(Sprite):\r\n def __init__(self, x, y, shape, color):\r\n Sprite.__init__(self, x, y, shape, color)\r\n\r\nclass Powerup(Sprite):\r\n def __init__(self, x, y, shape, color):\r\n Sprite.__init__(self, x, y, shape, color)\r\n \r\n#create game object\r\ngame=Game(1000, 300)\r\n\r\n# Create player sprite\r\nplayer = Player(0, 0, \"triangle\", \"white\")\r\n\r\n\r\n#create missil object\r\nmissile = Missile(0, 100, \"circle\", \"yellow\")\r\n\r\nenemy = Enemy(0, 100, \"square\", \"red\")\r\nenemy.dx = -0.1\r\nenemy.dy = -0.03\r\n\r\nenemy2 = Enemy(-100, 100, \"square\", \"red\")\r\nenemy2.dx = 0.1\r\nenemy2.dy = 0.03\r\n\r\npowerup = Powerup(0, -100, \"circle\", \"blue\")\r\npowerup.dy = 0.1\r\npowerup.dx = 0.01\r\n\r\npowerup2 = Powerup(-100, -100, \"circle\", \"blue\")\r\npowerup2.dy = -0.1\r\npowerup2.dx = -0.01\r\n\r\n# Sprites list\r\nsprites = []\r\nsprites.append(player)\r\nsprites.append(enemy)\r\nsprites.append(powerup)\r\nsprites.append(missile)\r\nsprites.append(enemy2)\r\nsprites.append(powerup2)\r\n\r\n# Keyboard bindings\r\nwn.listen()\r\nwn.onkeypress(player.rotate_left, \"Left\")\r\nwn.onkeypress(player.rotate_right, \"Right\")\r\n\r\nwn.onkeyrelease(player.stop_rotation, \"Left\")\r\nwn.onkeyrelease(player.stop_rotation, \"Right\")\r\n\r\nwn.onkeypress(player.accelerate, \"Up\")\r\nwn.onkeyrelease(player.decelerate, \"Up\")\r\n\r\nwn.onkeypress(player.fire, \"space\")\r\n\r\n# Main Loop\r\nwhile True:\r\n # Clear screen\r\n pen.clear()\r\n \r\n # Do game stuff\r\n # Update sprites\r\n for sprite in sprites:\r\n sprite.update()\r\n\r\n #check for collisions\r\n for sprite in sprites:\r\n if isinstance(sprite ,Enemy):\r\n if player.is_collision(sprite):\r\n player.x = 0\r\n player.y = 0\r\n\r\n if missile.state == \"active\" and missile.is_collision(sprite):\r\n sprite.x = -100\r\n sprite.y = -100\r\n missile.reset()\r\n\r\n if isinstance(sprite, Powerup):\r\n if player.is_collision(sprite):\r\n sprite.x = 100\r\n sprite.y = 100\r\n\r\n if missile.state == \"active\" and missile.is_collision(sprite):\r\n sprite.x = +100\r\n sprite.y = +100\r\n missile.reset()\r\n\r\n # Render sprites\r\n for sprite in sprites:\r\n sprite.render(pen)\r\n\r\n game.render_border(pen)\r\n \r\n # Update the screen\r\n wn.update()\r\n","sub_path":"space arena.py","file_name":"space arena.py","file_ext":"py","file_size_in_byte":8182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"429012042","text":"N = int(input())\nqueue = []\n\ndef push(x): # 정수를 큐에 넣음\n queue.append(x)\n\ndef pop(): # 가장 앞에 있는 수를 빼고 출력. 수가 없으면 -1 출력\n if len(queue) == 0:\n print(-1)\n else:\n print(queue.pop(0))\n\ndef size(): # 들어있는 정수의 갯수 출력\n print(len(queue))\n\ndef empty(): # 비어있으면 1, 아니면 0 출력\n print(int(not bool(len(queue))))\n\ndef front(): # 큐 가장 앞에있는 수를 출력\n if len(queue) == 0:\n print(-1)\n else:\n print(queue[0])\n\ndef back(): # 큐 가장 뒤에 있는 수를 출력\n if len(queue) == 0:\n print(-1)\n else:\n print(queue[-1])\n\nfunc_lst = [pop,size,empty,front,back]\nfunc_str = ['pop','size','empty','front','back']\nfor i in range(N):\n f = input().split(' ')\n if len(f) == 2:\n push(int(f[1]))\n else:\n func_lst[func_str.index(f[0])]()\n","sub_path":"박상우/Data Structure 1/큐.py","file_name":"큐.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"391145639","text":"\"\"\"\n-----------------------------------------------------------------------------------------\nextract_eyetraces.py\n-----------------------------------------------------------------------------------------\nGoal of the script:\nExtract eye traces from edf file and arrange them well for later treatment\n-----------------------------------------------------------------------------------------\nInput(s):\nsys.argv[1]: subject number (sub-01)\nsys.argv[2]: task (EyeMov)\n-----------------------------------------------------------------------------------------\nOutput(s):\nh5 files with loads of data on eye traces across runs\n-----------------------------------------------------------------------------------------\nTo run:\ncd /Users/martin/Dropbox/Experiments/pMFexp/stats/\npython behav_analysis/extract_eyetraces.py sub-01 EyeMov\n-----------------------------------------------------------------------------------------\n\"\"\"\n\n# Stop warnings\n# -------------\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# General imports\n# ---------------\nimport os\nimport sys\nimport platform\nimport numpy as np\nimport ipdb\nimport json\nimport h5py\nimport scipy.io\ndeb = ipdb.set_trace\n\n# Get inputs\n# ----------\nsubject = sys.argv[1]\ntask = sys.argv[2]\n\n# Define analysis parameters\n# --------------------------\nwith open('behavior_settings.json') as f:\n\tjson_s = f.read()\n\tanalysis_info = json.loads(json_s)\n\n# Get eyelink data\n# ----------------\nif platform.system() == 'Darwin':\n\tmain_dir = analysis_info['main_dir_mac']\n\tedf2asc_dir = analysis_info['edf2asc_dir_mac']\n\tend_file = ''\n \nelif platform.system() == 'Windows':\n\tmain_dir = analysis_info['main_dir_pc']\n\tedf2asc_dir = analysis_info['edf2asc_dir_win']\n\tend_file ='.exe'\n \n\n# Define file list\n# ----------------\nfile_dir = '{exp_dir}/data/{sub}'.format(exp_dir = main_dir, sub = subject)\nlist_filename = ['{sub}_task-{task}_run-01'.format(sub = subject, task = task),\n\t\t\t\t '{sub}_task-{task}_run-02'.format(sub = subject, task = task),\n\t\t\t\t '{sub}_task-{task}_run-03'.format(sub = subject, task = task),\n\t\t\t\t '{sub}_task-{task}_run-04'.format(sub = subject, task = task),\n\t\t\t\t '{sub}_task-{task}_run-05'.format(sub = subject, task = task),\n\t\t\t\t '{sub}_task-{task}_run-06'.format(sub = subject, task = task),\n\t\t\t\t '{sub}_task-{task}_run-07'.format(sub = subject, task = task),\n\t\t\t \t '{sub}_task-{task}_run-08'.format(sub = subject, task = task),\n\t\t\t\t '{sub}_task-{task}_run-09'.format(sub = subject, task = task),\n\t\t\t\t '{sub}_task-{task}_run-10'.format(sub = subject, task = task)]\n\n\n# Define experiments details\n# --------------------------\nnum_run = analysis_info['num_run']\nnum_seq = analysis_info['num_seq']\nseq_trs = analysis_info['seq_trs']\neye_mov_seq = analysis_info['eye_mov_seq']\nrads = analysis_info['rads']\npursuits_tr = np.arange(0,seq_trs,2)\nsaccades_tr = np.arange(1,seq_trs,2)\n\n\n# Exctract data\n# -------------\neye_data_runs = [];\ntime_last_run_eye = 0;\ntime_start_eye = np.zeros((1,num_run))\ntime_end_eye = np.zeros((1,num_run))\ntime_start_seq = np.zeros((num_seq,num_run))\ntime_end_seq = np.zeros((num_seq,num_run))\ntime_start_trial = np.zeros((seq_trs,num_seq,num_run))\ntime_end_trial = np.zeros((seq_trs,num_seq,num_run))\nfor t_run in np.arange(0,num_run,1):\n\n\tedf_filename = '{file_dir}/func/{filename}_eyeData'.format(file_dir = file_dir,filename = list_filename[t_run]);\n\tmat_filename = '{file_dir}/add/{filename}_matFile.mat'.format(file_dir = file_dir,filename = list_filename[t_run]);\n\n\t# get .msg and .dat file\n\tif not os.path.exists('{}.dat'.format(edf_filename)) or not os.path.exists('{}.msg'.format(edf_filename)):\n\t\tos.system('{edf2asc_dir}/edf2asc{end_file} {edf_filename}.edf -e -y'.format(edf2asc_dir = edf2asc_dir,\n\t\t end_file = end_file,\n\t\t edf_filename = edf_filename))\n\t\tos.rename('{}.asc'.format(edf_filename),'{}.msg'.format(edf_filename))\n\n\t\tos.system('{edf2asc_dir}/edf2asc{end_file} {edf_filename}.edf -s -miss -1.0 -y'.format( edf2asc_dir = edf2asc_dir,\n\t\t end_file = end_file,\n\t\t edf_filename = edf_filename))\n\t\tos.rename('{}.asc'.format(edf_filename),'{}.dat'.format(edf_filename))\n\n\t# get first and last time pf each run\n\tmsgfid = open('{}.msg'.format(edf_filename)) \n\tfirst_last_time = False\n\tfirst_time = False\n\tlast_time = False \n\tseq_num = 0\n\twhile not first_last_time:\n\t\tline_read = msgfid.readline()\n\t\tif not line_read == '':\n\t\t\tla = line_read.split()\n\n\t\tif len(la) > 6:\n\t\t\tif la[2] == 'sequence' and la[3]=='1' and la[4]=='started' and not first_time: \n\t\t\t\ttime_start_eye[0,t_run] = float(la[1])\n\t\t\t\tfirst_time = True\n\t\t\t \n\t\t\tif la[2] == 'sequence' and la[3]=='9' and la[4]=='stopped' and not last_time: \n\t\t\t\ttime_end_eye[0,t_run] = float(la[1])\n\t\t\t\tlast_time = True\n\t\t\t \n\t\t\tif la[2] == 'sequence' and la[4]=='started':\n\t\t\t\ttime_start_seq[seq_num,t_run] = float(la[1])\n\t\t\t\ttrial_num = 0\n\t\t\t \n\t\t\tif la[2] == 'sequence' and la[4]=='stopped':\n\t\t\t\ttime_end_seq[seq_num,t_run] = float(la[1])\n\t\t\t\tseq_num += 1\n\t\t\t \n\t\t\tif la[4] == 'trial' and la[6]=='onset':\n\t\t\t\ttime_start_trial[trial_num,seq_num,t_run] = float(la[1])\n\t\t\t \n\t\t\tif la[4] == 'trial' and la[6]=='offset':\n\t\t\t\ttime_end_trial[trial_num,seq_num,t_run] = float(la[1])\n\t\t\t\ttrial_num += 1 \n \n\t\tif first_time == True and last_time == True:\n\t\t\tfirst_last_time = True\n\t\t\tmsgfid.close();\n\n \n\t# load eye coord data\n\teye_dat = np.genfromtxt('{}.dat'.format(edf_filename),usecols=(0, 1, 2))\n\teye_data_run = eye_dat[np.logical_and(eye_dat[:,0]>=time_start_eye[0,t_run],eye_dat[:,0]<=time_end_eye[0,t_run])]\n\n\t# add run number\n\teye_data_run = np.concatenate((eye_data_run,np.ones((eye_data_run.shape[0],1))*(t_run)),axis = 1) \n\t# col 0 = time\n\t# col 2 = eye x coord\n\t# col 3 = eye y coord\n\t# col 4 = run number\n\n\tif t_run == 0:\n\t\teye_data_runs = eye_data_run\n\telse:\n\t\teye_data_runs = np.concatenate((eye_data_runs,eye_data_run), axis=0)\n\n\t# remove msg and dat\n\tos.remove('{}.msg'.format(edf_filename))\n\tos.remove('{}.dat'.format(edf_filename))\n\n\n\n# delete blink time\nblinkNum = 0;\nblink_start = False;\nfor tTime in np.arange(0,eye_data_runs.shape[0],1):\n\tif not blink_start:\n\t\tif eye_data_runs[tTime,1] == -1:\n\t\t\tblinkNum += 1\n\t\t\ttimeBlinkOnset = eye_data_runs[tTime,0]\n\t\t\tblink_start = True\n\t\t\tif blinkNum == 1:\n\t\t\t\tblink_onset_offset = np.matrix([timeBlinkOnset,np.nan])\n\t\t\telse:\n\t\t\t\tblink_onset_offset = np.vstack((blink_onset_offset,[timeBlinkOnset,np.nan]))\n\n\tif blink_start:\n\t\tif eye_data_runs[tTime,1] != -1:\n\t\t\ttimeBlinkOffset = eye_data_runs[tTime,0]\n\t\t\tblink_start = 0\n\t\t\tblink_onset_offset[blinkNum-1,1] = timeBlinkOffset\n\n# nan record around detected blinks\nbefDurBlink = 300; # duration before blink\naftDurBlink = 300; # duration after blink\neye_data_runs_no_blink = np.copy(eye_data_runs)\n\nfor tBlink in np.arange(0,blinkNum,1):\n\tblink_onset_offset[tBlink,0] = blink_onset_offset[tBlink,0]-befDurBlink\n\tblink_onset_offset[tBlink,1] = blink_onset_offset[tBlink,1]+aftDurBlink\n\n\teye_data_runs_no_blink[np.logical_and(eye_data_runs_no_blink[:,0] >= blink_onset_offset[tBlink,0],eye_data_runs_no_blink[:,0] <= blink_onset_offset[tBlink,1]),1] = np.nan\n\teye_data_runs_no_blink[np.logical_and(eye_data_runs_no_blink[:,0] >= blink_onset_offset[tBlink,0],eye_data_runs_no_blink[:,0] <= blink_onset_offset[tBlink,1]),2] = np.nan\n\n\n# put eye coordinates in deg from center (flip y axis)\nmatfile = scipy.io.loadmat(mat_filename)\nscr_sizeX = matfile['config']['scr'][0,0]['scr_sizeX'][0][0][0][0]\nscr_sizeY = matfile['config']['scr'][0,0]['scr_sizeY'][0][0][0][0]\nscreen_size = np.array([scr_sizeX,scr_sizeY])\nppd = matfile['config']['const'][0,0]['ppd'][0][0][0][0]\n\n\neye_data_runs[:,1] = (eye_data_runs[:,1] - (screen_size[0]/2))/ppd;\neye_data_runs[:,2] = -1.0*((eye_data_runs[:,2] - (screen_size[1]/2))/ppd);\neye_data_runs_no_blink[:,1] = (eye_data_runs_no_blink[:,1] - (screen_size[0]/2))/ppd;\neye_data_runs_no_blink[:,2] = -1.0*((eye_data_runs_no_blink[:,2] - (screen_size[1]/2))/ppd);\namp_sequence = matfile['config']['expDes'][0,0]['amp_sequence'][0][0]\n\n# Save all\n# --------\nh5_file = \"{file_dir}/add/{sub}_task-{task}_eyedata.h5\".format(file_dir = file_dir, sub = subject, task = task)\nfolder_alias = 'eye_traces'\n\ntry: os.system('rm {h5_file}'.format(h5_file = h5_file))\nexcept: pass\n\nh5file = h5py.File(h5_file, \"a\")\ntry:h5file.create_group(folder_alias)\nexcept:None\n\nh5file.create_dataset( '{folder_alias}/eye_data_runs'.format(folder_alias = folder_alias),\n data = eye_data_runs,dtype ='float32')\nh5file.create_dataset( '{folder_alias}/eye_data_runs_no_blink'.format(folder_alias = folder_alias),\n data = eye_data_runs_no_blink,dtype ='float32')\n\nh5file.create_dataset( '{folder_alias}/time_start_eye'.format(folder_alias = folder_alias),\n data = time_start_eye,dtype ='float32')\nh5file.create_dataset( '{folder_alias}/time_end_eye'.format(folder_alias = folder_alias),\n data = time_end_eye,dtype ='float32')\n\nh5file.create_dataset( '{folder_alias}/time_start_seq'.format(folder_alias = folder_alias),\n data = time_start_seq,dtype ='float32')\nh5file.create_dataset( '{folder_alias}/time_end_seq'.format(folder_alias = folder_alias),\n data = time_end_seq,dtype ='float32')\n\nh5file.create_dataset( '{folder_alias}/time_start_trial'.format(folder_alias = folder_alias),\n data = time_start_trial,dtype ='float32')\nh5file.create_dataset( '{folder_alias}/time_end_trial'.format(folder_alias = folder_alias),\n data = time_end_trial,dtype ='float32')\n\nh5file.create_dataset( '{folder_alias}/amp_sequence'.format(folder_alias = folder_alias),\n data = amp_sequence,dtype ='float32')\n\n","sub_path":"stats/behav_analysis/.ipynb_checkpoints/extract_eyetraces-checkpoint.py","file_name":"extract_eyetraces-checkpoint.py","file_ext":"py","file_size_in_byte":10046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"383100590","text":"from __future__ import print_function\nfrom __future__ import division\n\nimport cv2\nimport os\nimport pickle\nimport tensorflow as tf\nimport numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\nimport sklearn\nfrom sklearn.ensemble import RandomForestClassifier\n# from tensorflow.examples.tutorials.mnist import input_data\nimport pandas as pd\nimport tifffile\nfrom sklearn.preprocessing import OneHotEncoder\nfrom skimage.color import rgb2gray\n# mnist = input_data.read_data_sets(\"/tmp/data\",one_hot=True)\nfrom skimage.transform import resize\nfrom tqdm import tqdm\nfrom keras.preprocessing.image import ImageDataGenerator\n\n\nbatch_size = 128\nn_classes = 4\nkeep_rate = 0.8\nkeep_prob = tf.placeholder(tf.float32)\nfcNumNeurons = 128\nfcNumNeurons2 = 512\nfcNumNeurons3 = 512\n\nGPU_Num = '1'\n\nhm_epochs = 5\nRandomForestNumEstimators = 100\ndownsample = 4\n\nHEIGHT = 240\nWIDTH = 320\n\nHEIGHT2 = int(240/downsample)\nWIDTH2 = int(320/downsample)\n\nDirectory = '/media/groot/Seagate Backup Plus Drive/dataset/new/BloodCell_Images/blood-cells/dataset2-master/images/'\n\n\ntf.logging.set_verbosity(tf.logging.INFO)\nnum_classes = 10\nbatch_size = 128\nimSz = [28,28]\n\ndef LoadingListOfFiles():\n\n mode = 'train'\n subClasses = os.listdir(Directory + mode)\n for mode in ['train', 'test']:\n\n Data = []\n Label = []\n Label_Tag = []\n for i in range(len(subClasses)):\n dirr = Directory + mode + '/' + subClasses[i] + '/'\n files2 = os.listdir(dirr)\n # for f in tqdm(range(int(len(files2)))):\n for f in range(int(len(files2))):\n le = len(files2[f])\n if files2[f][le-4:] == 'jpeg':\n Data.append(Directory + mode + '/' + subClasses[i] + '/' + files2[f])\n Label_Tag.append(subClasses[i])\n Label.append(i)\n\n Data = np.asarray(Data)\n Label = np.asarray(Label,dtype=np.int32)\n Label_Tag = np.asarray(Label_Tag)\n\n indexesRandomized = np.random.permutation(Data.shape[0])\n\n Data = Data[indexesRandomized]\n Label = Label[indexesRandomized]\n Label_Tag = Label_Tag[indexesRandomized]\n\n Label = OneHotEncoder(n_values=n_classes).fit_transform(Label.reshape(-1, 1)).toarray()\n\n if mode == 'train':\n FilesAddress = {'train_data':Data,'train_label':Label,'train_label_tag':Label_Tag}\n else:\n FilesAddress['test_data'] = Data\n FilesAddress['test_label'] = Label\n FilesAddress['test_label_tag'] = Label_Tag\n\n # TrainPercentage = 0.8\n # L = int( TrainPercentage*Data.shape[0] )\n # FilesAddress = {'train_data':Data[:L,...],'train_label':Label[:L,...],'train_label_tag':Label_Tag[:L,...]}\n # FilesAddress['test_data'] = Data[L:,...]\n # FilesAddress['test_label'] = Label[L:,...]\n # FilesAddress['test_label_tag'] = Label_Tag[L:,...]\n\n\n # FilesAddress = {'train_data':Data,'train_label':Label,'train_label_tag':Label_Tag}\n\n # FilesAddress['test_data'] = Data\n # FilesAddress['test_label'] = Label\n # FilesAddress['test_label_tag'] = Label_Tag\n\n return FilesAddress\n\nimagesDirects = LoadingListOfFiles()\n\ndatagen = ImageDataGenerator(\n featurewise_center=False, # set input mean to 0 over the dataset\n samplewise_center=False, # set each sample mean to 0\n featurewise_std_normalization=False, # divide inputs by std of the dataset\n samplewise_std_normalization=False, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)\n width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)\n height_shift_range=0.1, # randomly shift images vertically (fraction of total height)\n horizontal_flip=True, # randomly flip images\n vertical_flip=False) # randomly flip images\n\ndef Batch(List,ind,mode):\n\n a1 = int(List[ind])\n a2 = int(List[ind+1])\n\n dataAddress = imagesDirects[mode + '_data'][a1:a2]\n label = imagesDirects[mode + '_label'][a1:a2]\n\n for i in range(dataAddress.shape[0]):\n\n im = cv2.imread(dataAddress[i])\n if downsample != 1:\n im2 = scipy.misc.imresize(arr=im, size=(HEIGHT2,WIDTH2 , 3))\n im = np.asarray(im2)\n # im2 = np.zeros((HEIGHT2,WIDTH2,3))\n # for d in range(im.shape[2]):\n # im2[:,:,d] = cv2.resize(im[:,:,d], dsize=(WIDTH2,HEIGHT2))\n\n\n if i == 0:\n data = np.zeros((1,HEIGHT2,WIDTH2,3))\n data[0,...] = im\n else:\n data = np.concatenate((data,im[np.newaxis,...]), axis=0)\n\n data = np.array(data/255.0)\n\n a = datagen.flow(data,label, batch_size=data.shape[0])\n\n data = a[0][0]\n label = a[0][1]\n\n return data, label\n\ndef plotHistogram(a):\n \"\"\"\n Plot histogram of RGB Pixel Intensities\n \"\"\"\n plt.figure(figsize=(10,5))\n plt.subplot(1,2,1)\n plt.imshow(a)\n plt.axis('off')\n histo = plt.subplot(1,2,2)\n histo.set_ylabel('Count')\n histo.set_xlabel('Pixel Intensity')\n n_bins = 30\n plt.hist(a[:,:,0].flatten(), bins= n_bins, lw = 0, color='r', alpha=0.5);\n plt.hist(a[:,:,1].flatten(), bins= n_bins, lw = 0, color='g', alpha=0.5);\n plt.hist(a[:,:,2].flatten(), bins= n_bins, lw = 0, color='b', alpha=0.5);\n\n\ndef BatchesList(mode,batch_size):\n\n data = imagesDirects[mode + '_data']\n num_TrainData = data.shape[0]\n\n NumBatches = int(num_TrainData/batch_size)\n List = []\n for ind in range(0,NumBatches+1):\n List = np.append(List,np.array(batch_size)*ind)\n\n if num_TrainData > batch_size*NumBatches:\n List = np.append(List,np.array(num_TrainData-1))\n\n return List\n\nBatchesEndPointsTrain = BatchesList('train',batch_size)\nBatchesEndPointsTest = BatchesList('test',batch_size)\n\ndataA, labelA = Batch(BatchesEndPointsTrain,0,'train')\n\nplotHistogram(dataA[1])\n\n\ndef cnn_model_fn(features, labels, mode):\n\n input_layer = tf.reshape(features[\"x\"], [-1, imSz[0], imSz[1], 1])\n\n conv1 = tf.layers.conv2d(\n inputs = input_layer,\n filters = 32,\n kernel_size=[5, 5],\n padding=\"same\",\n activation = tf.nn.relu)\n\n pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2,2], strides=2)\n\n conv2 = tf.layers.conv2d(\n inputs = pool1,\n filters=64,\n kernel_size=[5,5],\n padding=\"same\",\n activation=tf.nn.relu)\n\n pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2,2], strides=2)\n\n pool2_flat = tf.reshape(pool2, [-1,int(imSz[0]/4)*int(imSz[1]/4)*64])\n\n dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)\n\n dropout = tf.layers.dropout(inputs=dense, rate = 0.4, training = mode == tf.estimator.ModeKeys.TRAIN)\n\n logits = tf.layers.dense(inputs=dropout, units=num_classes)\n\n predictions = {\n # Generate predictions (for PREDICT and EVAL mode)\n \"classes\": tf.argmax(input=logits, axis=1),\n # Add `softmax_tensor` to the graph. It is used for PREDICT and by the\n # `logging_hook`.\n \"probabilities\": tf.nn.softmax(logits, name=\"softmax_tensor\")}\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) # , config=tf.contrib.learn.RunConfig(session_config=config)) # , config=config\n\n # Calculate Loss (for both TRAIN and EVAL modes)\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n # Configure the Training Op (for TRAIN mode)\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)\n train_op = optimizer.minimize(\n loss=loss,\n global_step=tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) # , config=tf.contrib.learn.RunConfig(session_config=config)) # , config=config\n\n # Add evaluation metrics (for EVAL mode)\n eval_metric_ops = {\n \"accuracy\": tf.metrics.accuracy(\n labels=labels, predictions=predictions[\"classes\"])}\n A = tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops) # , config=tf.contrib.learn.RunConfig(session_config=config))\n return A\n\ndef main(unused_argv):\n\n # with tf.device('/device:GPU:0'):\n # load training and eval data\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n train_data = mnist.train.images\n train_labels = np.asarray(mnist.train.labels, dtype=np.int32)\n eval_data = mnist.test.images\n eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)\n\n mnist_classifier = tf.estimator.Estimator(\n model_fn = cnn_model_fn, model_dir=\"/media/groot/Seagate Backup Plus Drive/code/CNN_MNIST\") # , config=tf.contrib.learn.RunConfig(session_config=config)) #, config=config \"/tmp/mnist_convnet_model\")\n\n tensors_to_log = {\"probabilities\": \"softmax_tensor\"}\n\n # Train the model\n train_input_fn = tf.estimator.inputs.numpy_input_fn(\n x = {\"x\": train_data},\n y = train_labels,\n batch_size = batch_size,\n num_epochs = None,\n shuffle = True)\n\n mnist_classifier.train(\n input_fn = train_input_fn,\n steps = 20000,\n # hooks = [logging_hook]\n )\n\n # Evaluate the model and prints results\n eval_input_fn = tf.estimator.inputs.numpy_input_fn(\n x = {\"x\": eval_data},\n y = eval_labels,\n num_epochs=1,\n shuffle = False)\n\n eval_results = mnist_classifier.evaluate(input_fn = eval_input_fn)\n print(eval_results)\n\n\nconfig = tf.ConfigProto(log_device_placement=True)\nconfig.gpu_options.allow_growth = True\n\n#sess = tf.Session() # config=config) # , graph=myGraph.as_default())\n#sess.run(main(1))\nApp = tf.app.run()\n","sub_path":"Workshop_Nvidia_DLI/ImageBased/Blood_Cell_Classification/main_BloodCell_Classification_MNIST.py","file_name":"main_BloodCell_Classification_MNIST.py","file_ext":"py","file_size_in_byte":9742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"536276495","text":"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport copy\n\nimport torch\nimport torch.nn as nn\n\nfrom nemo.collections.common.parts import form_attention_mask\nfrom nemo.collections.nlp.modules.common.transformer.transformer_modules import MultiHeadAttention, PositionWiseFF\n\n__all__ = [\"TransformerEncoder\"]\n\n\nclass TransformerEncoderBlock(nn.Module):\n \"\"\"\n Building block of Transformer encoder.\n\n Args:\n hidden_size: size of the embeddings in the model, also known as d_model\n inner_size: number of neurons in the intermediate part of feed-forward\n net, usually is (4-8 x hidden_size) in the papers\n num_attention_heads: number of heads in multi-head attention\n attn_score_dropout: probability of dropout applied to attention scores\n attn_layer_dropout: probability of dropout applied to the output of the\n attention layers, but before layer normalization\n ffn_dropout: probability of dropout applied to FFN output\n hidden_act: activation function used between two linear layers in FFN\n \"\"\"\n\n def __init__(\n self,\n hidden_size: int,\n inner_size: int,\n num_attention_heads: int = 1,\n attn_score_dropout: float = 0.0,\n attn_layer_dropout: float = 0.0,\n ffn_dropout: float = 0.0,\n hidden_act: str = \"relu\",\n pre_ln: bool = False,\n ):\n super().__init__()\n self.pre_ln = pre_ln\n self.layer_norm_1 = nn.LayerNorm(hidden_size, eps=1e-5)\n self.first_sub_layer = MultiHeadAttention(\n hidden_size, num_attention_heads, attn_score_dropout, attn_layer_dropout\n )\n self.layer_norm_2 = nn.LayerNorm(hidden_size, eps=1e-5)\n self.second_sub_layer = PositionWiseFF(hidden_size, inner_size, ffn_dropout, hidden_act)\n\n def forward_preln(self, encoder_query, encoder_mask, encoder_keys):\n \"\"\"\n Pre-LayerNorm block\n Order of operations: LN -> Self-Attn -> Residual -> LN -> Cross-Attn -> Residual -> LN -> FFN\n \"\"\"\n residual = encoder_query\n encoder_query = self.layer_norm_1(encoder_query)\n encoder_keys = self.layer_norm_1(encoder_keys)\n self_attn_output = self.first_sub_layer(encoder_query, encoder_keys, encoder_keys, encoder_mask)\n self_attn_output += residual\n\n residual = self_attn_output\n self_attn_output = self.layer_norm_2(self_attn_output)\n output_states = self.second_sub_layer(self_attn_output)\n output_states += residual\n\n return output_states\n\n def forward_postln(self, encoder_query, encoder_mask, encoder_keys):\n \"\"\"\n Post-LayerNorm block\n Order of operations: Self-Attn -> Residual -> LN -> Cross-Attn -> Residual -> LN -> FFN -> Residual -> LN\n \"\"\"\n self_attn_output = self.first_sub_layer(encoder_query, encoder_keys, encoder_keys, encoder_mask)\n self_attn_output += encoder_query\n self_attn_output = self.layer_norm_1(self_attn_output)\n\n output_states = self.second_sub_layer(self_attn_output)\n output_states += self_attn_output\n output_states = self.layer_norm_2(output_states)\n\n return output_states\n\n def forward(self, encoder_query, encoder_mask, encoder_keys):\n if self.pre_ln:\n return self.forward_preln(encoder_query, encoder_mask, encoder_keys)\n else:\n return self.forward_postln(encoder_query, encoder_mask, encoder_keys)\n\n\nclass TransformerEncoder(nn.Module):\n def __init__(\n self,\n num_layers: int,\n hidden_size: int,\n inner_size: int,\n mask_future: bool = False,\n num_attention_heads: int = 1,\n attn_score_dropout: float = 0.0,\n attn_layer_dropout: float = 0.0,\n ffn_dropout: float = 0.0,\n hidden_act: str = \"relu\",\n pre_ln: bool = False,\n pre_ln_final_layer_norm: bool = True,\n ):\n super().__init__()\n\n if pre_ln and pre_ln_final_layer_norm:\n self.final_layer_norm = nn.LayerNorm(hidden_size, eps=1e-5)\n else:\n self.final_layer_norm = None\n\n layer = TransformerEncoderBlock(\n hidden_size,\n inner_size,\n num_attention_heads,\n attn_score_dropout,\n attn_layer_dropout,\n ffn_dropout,\n hidden_act,\n pre_ln,\n )\n self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)])\n self.diag = 0 if mask_future else None\n\n def _get_memory_states(self, encoder_states, encoder_mems_list=None, i=0):\n if encoder_mems_list is not None:\n memory_states = torch.cat((encoder_mems_list[i], encoder_states), dim=1)\n else:\n memory_states = encoder_states\n return memory_states\n\n def forward(self, encoder_states, encoder_mask, encoder_mems_list=None, return_mems=False):\n \"\"\"\n Args:\n encoder_states: output of the embedding_layer (B x L_enc x H)\n encoder_mask: encoder inputs mask (B x L_enc)\n encoder_mems_list: list of the cached encoder hidden states\n for fast autoregressive generation which will be used instead\n of encoder_states as keys and values if not None\n return_mems: bool, whether to return outputs of all encoder layers\n or the last layer only\n \"\"\"\n\n encoder_attn_mask = form_attention_mask(encoder_mask, self.diag)\n\n memory_states = self._get_memory_states(encoder_states, encoder_mems_list, 0)\n cached_mems_list = [memory_states]\n\n for i, layer in enumerate(self.layers):\n encoder_states = layer(encoder_states, encoder_attn_mask, memory_states)\n memory_states = self._get_memory_states(encoder_states, encoder_mems_list, i + 1)\n cached_mems_list.append(memory_states)\n\n if self.final_layer_norm is not None:\n encoder_states = self.final_layer_norm(encoder_states)\n memory_states = self._get_memory_states(encoder_states, encoder_mems_list, i + 1)\n cached_mems_list.append(memory_states)\n\n if return_mems:\n return cached_mems_list\n else:\n return cached_mems_list[-1]\n","sub_path":"nemo/collections/nlp/modules/common/transformer/transformer_encoders.py","file_name":"transformer_encoders.py","file_ext":"py","file_size_in_byte":6836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"302758502","text":"from flask import Flask, render_template, url_for, request, session, redirect, flash\r\nfrom flask_bootstrap import Bootstrap\r\nfrom flask_wtf import FlaskForm\r\nfrom wtforms import StringField, PasswordField, BooleanField, validators, IntegerField\r\nfrom wtforms.validators import InputRequired, Email, Length, ValidationError, Regexp\r\nfrom flask_pymongo import PyMongo\r\nimport bcrypt\r\nimport pickle\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nimport numpy\r\nimport os\r\n\r\napp = Flask(__name__, static_folder='static')\r\n\r\napp.config[\"SECRET_KEY\"] = \"ursecretkey\"\r\nENV = 'dev'\r\n\r\nif ENV == 'dev':\r\n app.debug = True\r\n app.config[\"MONGO_URI\"] = \"your mongo uri\"\r\nelse:\r\n app.debug = False\r\n# app.config['MONGO_URI'] = ''\r\n\r\napp.config[\"MONGO_DBNAME\"] = 'your database'\r\nBootstrap(app)\r\nmongo = PyMongo(app)\r\n\r\n\r\nclass LoginForm(FlaskForm):\r\n username = StringField(validators=[\r\n InputRequired(), Length(min=4, max=15)])\r\n password = PasswordField('Password', validators=[\r\n InputRequired(), Length(min=8, max=50)])\r\n\r\n\r\nclass RegistrationForm(FlaskForm):\r\n username = StringField('Username', validators=[\r\n InputRequired(), Length(min=4, max=15)], render_kw={\"placeholder\": \"Length 4 to 15 characters\"})\r\n password = PasswordField('Password', validators=[\r\n InputRequired(), Length(min=8, max=50)], render_kw={\"placeholder\": \"Length 8 to 50 characters\"})\r\n email = StringField('Email', validators=[InputRequired(), Email(\r\n message=\"INVALID EMAIL\"), Length(max=50)], render_kw={\"placeholder\": \"example@email.com\"})\r\n name = StringField('Name', validators=[\r\n InputRequired(), Length(min=2, max=50)], render_kw={\"placeholder\": \"Length 2 to 50 characters\"})\r\n phone = StringField('Phone number', validators=[Regexp(\r\n \"^[0-9]{10}$\", message=\"Enter valid phone number of 10 digits\")], render_kw={\"placeholder\": \"Length 10 digits\"})\r\n\r\n\r\nclass SmsSpamForm(FlaskForm):\r\n ip = StringField('Enter Message', validators=[\r\n InputRequired(), Length(max=1000000)], render_kw={\"placeholder\": \"Example: Hello How are you,long time no see.\"})\r\n\r\n\r\nclass EmailSpamForm(FlaskForm):\r\n ipe = StringField('Enter Email', validators=[\r\n InputRequired(), Length(max=1000000)], render_kw={\"placeholder\": \"Example: Subject:Regarding the newspaper Advertisement Good Morning sir...message continues..\"})\r\n\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef login():\r\n form = LoginForm()\r\n error = None\r\n if form.validate_on_submit():\r\n users = mongo.db.userinfo\r\n login_user = users.find_one({'username': request.form['username']})\r\n if login_user:\r\n if bcrypt.hashpw(request.form['password'].encode('utf-8'), login_user['password']) == login_user['password']:\r\n session['username'] = request.form['username']\r\n return redirect(url_for('dash'))\r\n else:\r\n error = 'Invalid username/password combination'\r\n flash('Invalid username/password combination')\r\n return render_template('login.html', form=form)\r\n\r\n\r\n@app.route('/signup', methods=['GET', 'POST'])\r\ndef signup():\r\n form = RegistrationForm()\r\n error = None\r\n if form.validate_on_submit() and request.method == 'POST':\r\n users = mongo.db.userinfo\r\n existuser = users.find_one({'username': request.form['username']})\r\n if existuser is None:\r\n hashpass = bcrypt.hashpw(\r\n request.form['password'].encode('utf-8'), bcrypt.gensalt())\r\n users.insert({'username': request.form['username'], 'password': hashpass,\r\n 'email': request.form['email'], 'name': request.form['name'], 'phone': request.form['phone']})\r\n return redirect(url_for('login'))\r\n else:\r\n error = 'That username already exists!'\r\n flash('That username already exists!')\r\n return render_template('signup.html', form=form)\r\n\r\n\r\n@app.route('/dash')\r\ndef dash():\r\n if 'username' in session:\r\n return render_template('dash3.html')\r\n else:\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/logout')\r\ndef logout():\r\n session.pop('username', None)\r\n return redirect('/')\r\n\r\n\r\n@app.route('/spamsmsdetect', methods=['GET', 'POST'])\r\ndef spamsmsdetect():\r\n if 'username' in session:\r\n form = SmsSpamForm()\r\n p = \"\"\r\n if form.validate_on_submit():\r\n print(\"Submitted\")\r\n cv = CountVectorizer()\r\n model = pickle.load(open('model/modeldec.pkl', 'rb'))\r\n model2 = pickle.load(open('model/vec.pkl', 'rb'))\r\n ii = request.form['ip']\r\n f = [str(ii)]\r\n print(f)\r\n final = model2.transform(f).toarray()\r\n if(model.predict(final) == 0):\r\n p = \"Not Spam\"\r\n else:\r\n p = \"Spam\"\r\n smspred = mongo.db.smsprediction\r\n smspred.insert_one(\r\n {'username': session['username'], 'ipstring': ii, 'Prediction': p})\r\n return render_template('smsspam.html', form=form, p=p)\r\n else:\r\n return render_template('index.html')\r\n\r\n@app.route('/api_pred_sms', methods=['GET', 'POST'])\r\ndef api_pred_sms():\r\n if 'username' in session:\r\n form = SmsSpamForm()\r\n p = \"\"\r\n if form.validate_on_submit():\r\n print(\"Submitted\")\r\n cv = CountVectorizer()\r\n model = pickle.load(open('model/modeldec.pkl', 'rb'))\r\n model2 = pickle.load(open('model/vec.pkl', 'rb'))\r\n ii = request.form['ip']\r\n f = [str(ii)]\r\n print(f)\r\n final = model2.transform(f).toarray()\r\n if(model.predict(final) == 0):\r\n p = \"Not Spam\"\r\n else:\r\n p = \"Spam\"\r\n smspred = mongo.db.smsprediction\r\n smspred.insert_one(\r\n {'username': session['username'], 'ipstring': ii, 'Prediction': p})\r\n return p\r\n else:\r\n return render_template('index.html')\r\n\r\n\r\n\r\n\r\n@app.route('/spamemaildetect', methods=['GET', 'POST'])\r\ndef spamemaildetect():\r\n if 'username' in session:\r\n form = EmailSpamForm()\r\n p = \"\"\r\n if form.validate_on_submit():\r\n print(\"Submitted\")\r\n cv = CountVectorizer()\r\n model = pickle.load(open('model/emmodeldec.pkl', 'rb'))\r\n model2 = pickle.load(open('model/emvec.pkl', 'rb'))\r\n ii = request.form['ipe']\r\n f = [str(ii)]\r\n print(f)\r\n final = model2.transform(f).toarray()\r\n if(model.predict(final) == 0):\r\n p = \"Not Spam\"\r\n else:\r\n p = \"Spam\"\r\n empred = mongo.db.emprediction\r\n empred.insert_one(\r\n {'username': session['username'], 'ipstring': ii, 'Prediction': p})\r\n return render_template('emailspam.html', form=form, p=p)\r\n else:\r\n return render_template('index.html')\r\n\r\n@app.route('/api_pred_em', methods=['GET', 'POST'])\r\ndef api_pred_em():\r\n if 'username' in session:\r\n form = EmailSpamForm()\r\n p = \"\"\r\n if form.validate_on_submit():\r\n print(\"Submitted\")\r\n cv = CountVectorizer()\r\n model = pickle.load(open('model/emmodeldec.pkl', 'rb'))\r\n model2 = pickle.load(open('model/emvec.pkl', 'rb'))\r\n ii = request.form['ipe']\r\n f = [str(ii)]\r\n print(f)\r\n final = model2.transform(f).toarray()\r\n if(model.predict(final) == 0):\r\n p = \"Not Spam\"\r\n else:\r\n p = \"Spam\"\r\n empred = mongo.db.emprediction\r\n empred.insert_one(\r\n {'username': session['username'], 'ipstring': ii, 'Prediction': p})\r\n return p\r\n else:\r\n return render_template('index.html')\r\n@app.route('/aboutus')\r\ndef aboutus():\r\n if 'username' in session:\r\n return render_template('aboutus.html')\r\n else:\r\n return render_template('index.html')\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"350922637","text":"from __future__ import absolute_import, division, print_function\nimport numpy as np\nimport cv2\nimport tensorflow as tf\nfrom nets.arcface import Arcface\n# from nets.facenet import Facenet\nfrom nn_search import FaissNN\nimport pickle\n\nimages = []\nfor string_record in tf.python_io.tf_record_iterator('./data/targets_rgb.tfrecords'):\n example = tf.train.Example()\n example.ParseFromString(string_record)\n\n images.append(cv2.imdecode(np.fromstring(\n example.features.feature['image'].bytes_list.value[0], np.uint8), 1))\n\n# embeds = pickle.load(open('./data/targets_embeds.pkl', 'rb'))[:, 1:]\nfnn = FaissNN(pre_embeds_file='./data/targets_embeds.pkl', dim=512)\n\nconfig = tf.ConfigProto()\nconfig.intra_op_parallelism_threads = 4\nconfig.inter_op_parallelism_threads = 4\nsession = tf.Session(config=config)\nnet = Arcface(session, is_training=False)\n\nind = np.random.randint(0, len(images))\nimg = images[ind]\n\nemb = net.forward(np.expand_dims(img, 0))\n\n# dist = 1 - np.dot(emb, embeds.T)\n# topk = np.argsort(dist, axis=1)[:, :25]\ntopk = fnn.search_idx(emb, k=25)\n\nsims = np.zeros((5 * 112, 5 * 112, 3), dtype=np.uint8)\nfor i in range(5):\n for j in range(5):\n sims[i * 112:(i + 1) * 112, j * 112:(j + 1) *\n 112, :] = images[topk[0, i * 5 + j]]\n\ncv2.imshow('target', cv2.cvtColor(img, cv2.COLOR_RGB2BGR))\ncv2.imshow('sims', cv2.cvtColor(sims, cv2.COLOR_RGB2BGR))\ncv2.waitKey(0)\n","sub_path":"python/top_similars.py","file_name":"top_similars.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"537966690","text":"\nfrom zope.interface import Interface\nfrom zope.schema import TextLine,Object,Set,Field,Int,List,Bool, Field\nfrom zope.schema.interfaces import IField\nfrom zope.i18nmessageid import MessageFactory\n\nfrom oship.openehr.rm.datatypes.quantity.interfaces import IDvInterval\nfrom oship.openehr.am.archetype.assertion.interfaces import IAssertion\nfrom oship.openehr.am.archetype.constraint_model.interfaces.ICAttribute import ICAttribute\nfrom oship.openehr.am.archetype.constraint_model.primitive.interfaces import ICPrimitive\nfrom oship.openehr.am.archetype.constraint_model.interfaces.ICComplexObject import ICComplexObject\n\n_ = MessageFactory('oship')\n\n\n\nclass IArchetypeConstraint(Interface):\n \"\"\"\n Archetype equivalent to Locatable class in the Common package of the reference model.\n \"\"\"\n\n def isSubsetOf(other):\n u\"\"\"True if constraints are narrower than this node.\"\"\"\n\n def isValid():\n u\"\"\"True if this node and sub-nodes are valid for its type.\"\"\"\n\n def path():\n \"\"\"\n Return a string containt the path of this node relative to the archetype root.\n \"\"\"\n\n def hasPath(aPath):\n \"\"\"\n Return True if the relative path (aPath) exists at this node.\n \"\"\"\n\n\nclass ICObject(Interface):\n \"\"\"\n Abstract model of constraint on any kind of object node.\n \"\"\"\n\n rmTypeName=TextLine(\n title=_(u\"RM Type Name\"),\n description=_(u\"Reference model type that this node corresponds to.\"),\n required = True,\n )\n\n occurrences=Int(\n title=_(u\"Occurrences\"),\n description=_(u\"Occurrences of this object node in the data.\"),\n required = True\n )\n\n nodeId=TextLine(\n title=_(u\"Node Id\"),\n description=_(u\"Semantic id of this node.\"),\n required = True,\n )\n\n\n parent=Object(\n schema=ICAttribute,\n title=_(u\"Parent\"),\n description=_(u\"CAttribute that owns the CObject.\"),\n required=False,\n )\n\n\nclass ICReferenceObject(Interface):\n \"\"\"\n Abstract parent of CObject subtypes that are defined by reference.\n \"\"\"\n pass\n\n\nclass ICDefinedObject(Interface):\n \"\"\"\n Abstract parent of CObject subtypes that are defined by this value.\n \"\"\"\n\n assumedValue=Field(\n title=_(u\"Assumed Value\"),\n description=_(u\"Value to be assumed if none sent in data. Any Type.\"),\n required=False,\n )\n\n def hasAssumedValue():\n \"\"\"\n Return True if assumedValue is not equal to None.\n \"\"\"\n\n\nclass ICSingleAttribute(Interface):\n \"\"\"\n Concrete model of constraint on a single valued attribute.\n \"\"\"\n\n alternatives=List(\n title=_(u\"Alternatives\"),\n description=_(u\"A list of alternative constraints for the single child of this attribute.\"),\n value_type=Object(schema=ICObject),\n required=False,\n )\n\n\nclass ICMultipleAttribute(Interface):\n \"\"\"\n Abstract model of constraint on any kind of attribute node.\n \"\"\"\n\n cardinality=Object(\n schema = IField, # this must be checked in the implementation as a Cardinality instance.\n title=_(u\"Cardinality\"),\n description=_(u\"Cardinality of this attribute constraint.\"),\n\n )\n\n def members(cobj):\n \"\"\"\n List of constraints representing members of the container value of this attribute.\n \"\"\"\n\n\nclass ICardinality(Interface):\n \"\"\"\n Expresses constraints on the cardinality of container classes.\n \"\"\"\n\n isOrdered=Bool(\n title=_(u\"Ordered\"),\n description=_(u\"True if members are ordered.\"),\n required = True,\n )\n\n isUnique=Bool(\n title=_(u\"Unique\"),\n description=_(u\"True if members are unique.\"),\n required = True,\n )\n\n interval=Object(\n schema=IDvInterval,\n title=_(u\"Interval\"),\n description=_(u\"Interval of this cardinality.\"),\n required = True,\n )\n\n def isBag():\n \"\"\"\n Return True if this cardinality represents an unordered set.\n \"\"\"\n\n def isList():\n \"\"\"\n Return True if this cardinality represents an ordered, non-unique membership.\n \"\"\"\n\n def isSet():\n \"\"\"\n Return True if this cardinality represents an unordered, non-unique membership.\n \"\"\"\n\n\nclass IArchetypeInternalRef(Interface):\n \"\"\"\n See the AOM reference document.\n \"\"\"\n\n targetPath=TextLine(\n title=_(u\"Target Path\"),\n description=_(u\"Reference to an object node using archetype path notation.\"),\n\n )\n\n\nclass IConstraintRef(Interface):\n \"\"\"\n Reference to a constraint described in the same archetype.\n \"\"\"\n\n reference=TextLine(\n title=_(u\"Reference\"),\n description=_(u\"Reference to a constraint in the archetype ontology.\"),\n\n )\n\n\nclass IArchetypeSlot(Interface):\n \"\"\"\n Constraint describing a slot where other archetypes can occur.\n \"\"\"\n\n includes=Set(\n title=_(u\"Includes\"),\n description=_(u\"List of constraints defining other archetypes that can be included here.\"),\n required=False,\n value_type=Object(schema=IAssertion),\n )\n\n excludes=Set(\n title=_(u\"Excludes\"),\n description=_(u\"List of constraints defining archetypes that cannot be include here.\"),\n required=False,\n value_type=Object(schema=IAssertion),\n )\n\n\nclass ICPrimitiveObject(Interface):\n \"\"\"\n Constraint on a primitive object.\n \"\"\"\n\n item=Object(\n schema=ICPrimitive,\n title=_(u\"Item\"),\n description=_(u\"Object actually defining the constraint.\"),\n required=False,\n )\n\n\nclass ICDomainType(Interface):\n \"\"\"\n Abstract parent of domain specific constrainer types.\n \"\"\"\n\n standardEquivalent=Object(\n schema=ICComplexObject,\n title=_(u\"Standard Equivalent\"),\n description=_(u\"Standard form of constraint.\"))\n\n\n","sub_path":"src/oship.openehr.am/src/oship/openehr/am/archetype/constraint_model/interfaces/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"282846686","text":"#!/usr/bin/env python\n\nimport json\n\nfrom convert import BOUNDS\n\n\ndef geojson_feature(feature_type, coordinates, properties=None, **kwargs):\n properties = properties or {}\n properties.update(kwargs)\n return {\n 'type': 'Feature',\n 'properties': properties,\n 'geometry': {\n 'type': feature_type,\n 'coordinates': coordinates\n }\n }\n\n\ndef geojson_bounds(bounds, properties=None, **kwargs):\n '''Convert a tuple of (sw, ne)-corners to a geojson polygon'''\n\n sw_lng, sw_lat = bounds[0]\n ne_lng, ne_lat = bounds[1]\n return geojson_feature('Polygon', [\n [\n bounds[0],\n (sw_lng, ne_lat),\n bounds[1],\n (ne_lng, sw_lat)\n ]\n ], properties, **kwargs)\n\nif __name__ == '__main__':\n all_bounds = []\n for key, bounds in BOUNDS.items():\n bounds = geojson_bounds(bounds, name=key)\n all_bounds.append(bounds)\n\n with open('{}.geojson'.format(key), 'w') as out:\n json.dump(bounds, out, indent=2)\n\n with open('harm36_bounds.geojson', 'w') as out:\n json.dump({\n 'type': 'FeatureCollection',\n 'features': all_bounds\n }, out, indent=2)\n\n\n print('Wrote bounds to .geojson files')\n","sub_path":"bounds.py","file_name":"bounds.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"274793646","text":"import unittest\nfrom copy import copy, deepcopy\n\nfrom delira.training import Parameters\nfrom delira.utils import LookupConfig\n\n\nclass ParametersTest(unittest.TestCase):\n def test_parameters(self):\n def to_lookup_config(dictionary):\n tmp = LookupConfig()\n tmp.update(dictionary)\n return tmp\n\n test_cases = [\n (\n {\"a\": 1, \"b\": [1, 2], \"c\": {\"d\": 3, \"e\": 56}},\n {\"f\": 1, \"g\": {\"h\": {\"i\": {\"a\": 3}}}},\n {\"j\": 1, \"k\": 2},\n {},\n \"e\",\n 56,\n \"a\",\n \"q\"\n )\n ]\n\n for case in test_cases:\n with self.subTest(case=case):\n fixed_model_params, variable_model_params, \\\n fixed_training_params, variable_training_params, \\\n valid_nested_key, valid_nested_value, doubled_key, \\\n invalid_key = case\n\n fixed_model_params = to_lookup_config(fixed_model_params)\n variable_model_params = to_lookup_config(variable_model_params)\n fixed_training_params = to_lookup_config(fixed_training_params)\n variable_training_params = to_lookup_config(\n variable_training_params)\n\n params = Parameters(\n fixed_params={\n \"model\": fixed_model_params,\n \"training\": fixed_training_params\n },\n variable_params={\n \"model\": variable_model_params,\n \"training\": variable_training_params\n }\n )\n\n self.assertFalse(params.training_on_top)\n self.assertTrue(params.variability_on_top)\n self.assertEqual(params.fixed, to_lookup_config({\n \"model\": fixed_model_params,\n \"training\": fixed_training_params\n }))\n\n self.assertEqual(params.variable, to_lookup_config({\n \"model\": variable_model_params,\n \"training\": variable_training_params\n }))\n\n params = params.permute_training_on_top()\n\n self.assertFalse(params.variability_on_top)\n self.assertTrue(params.training_on_top)\n\n self.assertEqual(params.model, to_lookup_config({\n \"fixed\": fixed_model_params,\n \"variable\": variable_model_params\n }))\n\n self.assertEqual(params.training, to_lookup_config({\n \"fixed\": fixed_training_params,\n \"variable\": variable_training_params\n }))\n\n params_copy = params.deepcopy()\n params = params.permute_variability_on_top(\n ).permute_training_on_top()\n self.assertEqual(params_copy, params)\n\n self.assertEqual(params.nested_get(\n valid_nested_key), valid_nested_value)\n\n with self.assertRaises(KeyError):\n params.nested_get(doubled_key)\n\n with self.assertRaises(KeyError):\n params.nested_get(invalid_key)\n\n self.assertEqual(\"default\", params.nested_get(\n invalid_key, \"default\"))\n self.assertEqual(\"default\", params.nested_get(\n invalid_key, default=\"default\"))\n\n params_shallow = copy(params.permute_training_on_top())\n self.assertEqual(params.training_on_top,\n params_shallow.training_on_top)\n params_shallow[\"model.fixed.a\"] += 1\n self.assertNotEqual(params_shallow[\"model.fixed.a\"],\n params[\"model.fixed.a\"])\n\n params_shallow2 = copy(params.permute_variability_on_top())\n self.assertEqual(params.variability_on_top,\n params_shallow2.variability_on_top)\n\n params_deep = deepcopy(params.permute_training_on_top())\n self.assertEqual(params.training_on_top,\n params_deep.training_on_top)\n params_deep[\"model.fixed.a\"] += 1\n self.assertNotEqual(params_deep[\"model.fixed.a\"],\n params[\"model.fixed.a\"])\n\n params_deep2 = deepcopy(params.permute_variability_on_top())\n self.assertEqual(params.variability_on_top,\n params_deep2.variability_on_top)\n\n params.permute_training_on_top()\n params_deep.permute_variability_on_top()\n params.update(params_deep)\n self.assertTrue(params.training_on_top)\n self.assertTrue(params_deep.variability_on_top)\n\n with self.assertRaises(RuntimeError):\n params.update({\"a\": 1})\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/training/test_parameters.py","file_name":"test_parameters.py","file_ext":"py","file_size_in_byte":5106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"154339896","text":"from random import shuffle\nimport numpy as np\n\n\nclass Quick:\n\n def __init__(self):\n pass\n\n @classmethod\n def partition(cls, arr, lo, hi):\n item = arr[lo]\n i = lo\n j = hi+1\n while True:\n while True:\n i += 1\n if not (i < hi and arr[i] < item):\n break\n while True:\n j -= 1\n if not (j > lo and arr[j] > item):\n break\n if i >= j:\n break\n arr[i], arr[j] = arr[j], arr[i]\n\n arr[lo], arr[j] = arr[j], arr[lo]\n return j\n\n @classmethod\n def quicksort(cls, arr, lo, hi):\n if lo >= hi:\n return\n j = cls.partition(arr, lo, hi)\n cls.quicksort(arr, lo, j - 1)\n cls.quicksort(arr, j + 1, hi)\n return arr\n\n @classmethod\n def sort(cls, arr):\n return cls.quicksort(arr, 0, len(arr) - 1)\n\n @classmethod\n def is_sorted(cls, arr):\n N = len(arr)\n\n for i in range(N - 1):\n if arr[i] > arr[i + 1]:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n # items = [5, 5, 4, 3, 1, 2, 9, 6, 7, 10, 11, 13, 8, 0]\n # items = ['a', 'B', 'f', 'c', 'e', 'd', 'D']\n items = np.random.randint(0, 100, 24)\n print(' items: ', items)\n print(Quick.is_sorted(items))\n print('sort items: ', Quick.sort(items))\n print(' items: ', items)\n print(Quick.is_sorted(items))\n","sub_path":"algs4_sorts/quick.py","file_name":"quick.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"545810285","text":"from keras import Sequential\r\nfrom keras.layers import Conv2D, Flatten, Dense\r\nfrom keras.optimizers import Adam\r\n\r\nfrom models.my_model import MyModel\r\n\r\n\r\nclass Simple(MyModel):\r\n\r\n def __init__(self) -> None:\r\n self.INPUT_SHAPE = (224, 224, 3)\r\n\r\n def get_image_size(self):\r\n return self.INPUT_SHAPE[:2]\r\n\r\n def get_factory(self):\r\n \"\"\"\r\n A very simple model for unit test and verify code.\r\n :return: the model.\r\n \"\"\"\r\n model = Sequential()\r\n layers = [\r\n Conv2D(2, kernel_size=(3, 3), strides=1, padding='same', activation='relu', input_shape=self.INPUT_SHAPE),\r\n Flatten(),\r\n Dense(4, activation='relu'),\r\n Dense(2, activation='softmax'),\r\n ]\r\n\r\n for layer in layers:\r\n model.add(layer)\r\n\r\n model.compile(loss='categorical_crossentropy', optimizer=Adam(epsilon=1e-08), metrics=['accuracy'])\r\n return model\r\n","sub_path":"models/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"95737906","text":"#!/usr/bin/env python3\n\n# pylint: disable=C0111 # docstrings are always outdated and wrong\n# pylint: disable=W0511 # todo is encouraged\n# pylint: disable=C0301 # line too long\n# pylint: disable=R0902 # too many instance attributes\n# pylint: disable=C0302 # too many lines in module\n# pylint: disable=C0103 # single letter var names, func name too descriptive\n# pylint: disable=R0911 # too many return statements\n# pylint: disable=R0912 # too many branches\n# pylint: disable=R0915 # too many statements\n# pylint: disable=R0913 # too many arguments\n# pylint: disable=R1702 # too many nested blocks\n# pylint: disable=R0914 # too many local variables\n# pylint: disable=R0903 # too few public methods\n# pylint: disable=E1101 # no member for base\n# pylint: disable=W0201 # attribute defined outside __init__\n# pylint: disable=R0916 # Too many boolean expressions in if statement\n\n\nimport errno\nimport os\nimport signal\nimport sys\nimport time\n#from datetime import datetime\nfrom decimal import Decimal\nfrom decimal import InvalidOperation\n#from functools import wraps\nfrom pathlib import Path\n\nimport click\n#from asserttool import icr\n#import dateparser\nfrom asserttool import eprint\nfrom asserttool import ic\nfrom asserttool import maxone\nfrom asserttool import nevd\nfrom asserttool import verify\nfrom enumerate_input import enumerate_input\nfrom timetool import human_date_to_timestamp\nfrom timetool import timestamp_to_human_date\n#from humanize import naturaldelta\n#from humanize import naturaltime\nfrom unitcalc import convert\n\n\ndef is_before(*,\n timestamp: Decimal,\n before: Decimal,\n inclusive: bool,\n verbose: bool,\n debug: bool,\n ):\n acceptable_results = [Decimal('-1')]\n if inclusive:\n acceptable_results.append(Decimal('0'))\n if debug:\n ic(acceptable_results)\n result = timestamp.compare(before)\n if debug:\n ic(result)\n if result not in acceptable_results:\n return False\n return True\n\n\ndef is_after(*,\n timestamp: Decimal,\n after: Decimal,\n inclusive: bool,\n verbose: bool,\n debug: bool,\n ):\n acceptable_results = [Decimal('1')]\n if inclusive:\n acceptable_results.append(Decimal('0'))\n if debug:\n ic(acceptable_results)\n result = timestamp.compare(after)\n if debug:\n ic(result)\n if result not in acceptable_results:\n return False\n return True\n\n\ndef print_result(*,\n timestamp,\n human: bool,\n end: str,\n verbose: bool,\n debug: bool,\n ):\n if human:\n human_date = timestamp_to_human_date(timestamp)\n if verbose:\n print(timestamp, human_date, end=end)\n else:\n print(human_date, end=end)\n else:\n print(timestamp, end=end)\n\n\n@click.command()\n@click.argument(\"timestamps\", type=str, nargs=-1)\n@click.option('--verbose', is_flag=True)\n@click.option('--debug', is_flag=True)\n@click.option('--before', type=str)\n@click.option('--after', type=str)\n@click.option('--around', type=str)\n@click.option('--within', type=str)\n@click.option('--oldest', is_flag=True)\n@click.option('--newest', is_flag=True)\n@click.option(\"--inclusive\", is_flag=True)\n@click.option(\"--human\", is_flag=True)\n@click.option(\"--exit-after-matches\", type=int)\n@click.option(\"--printn\", is_flag=True)\n@click.pass_context\ndef cli(ctx,\n *,\n timestamps,\n before: str,\n after: str,\n around: str,\n within: str,\n inclusive: bool,\n verbose: bool,\n debug: bool,\n oldest: bool,\n newest: bool,\n human: bool,\n printn: bool,\n exit_after_matches: int,\n ):\n\n null, end, verbose, debug = nevd(ctx=ctx,\n ipython=False,\n verbose=verbose,\n printn=False,\n debug=debug,)\n\n if verbose:\n ic(before, after)\n\n if within is not None:\n maxone([before, after, around], msg='--within requires one of --before/--after/--around')\n\n if around is not None:\n if within is None:\n raise ValueError('--around requires --within')\n if (before is not None) or (after is not None):\n raise ValueError('--around can not be used with --before/--after')\n\n if before is not None:\n try:\n before = Decimal(before)\n except InvalidOperation:\n before = human_date_to_timestamp(before)\n\n if after is not None:\n try:\n after = Decimal(after)\n except InvalidOperation:\n after = human_date_to_timestamp(after)\n\n if around is not None:\n try:\n around = Decimal(around)\n except InvalidOperation:\n around = human_date_to_timestamp(around)\n\n if within is not None:\n try:\n within = Decimal(within)\n except InvalidOperation:\n within_converted = convert(human_input_units=within,\n human_output_unit=\"seconds\",\n verbose=verbose,\n debug=debug,)\n ic(within_converted)\n within = Decimal(within_converted.magnitude)\n ic(within)\n\n # at this point, before and after need to be configured\n assert before is None\n assert after is None\n\n after = around - within\n before = around + within\n ic(after, before)\n\n now = Decimal(time.time())\n\n if (before or after or within):\n ic(before, after, within, now)\n\n match_count = 0\n\n current_newest = None\n current_oldest = None\n for index, timestamp in enumerate_input(iterator=timestamps,\n null=null,\n skip=None,\n head=None,\n tail=None,\n debug=debug,\n verbose=verbose):\n\n try:\n timestamp = Decimal(timestamp)\n except InvalidOperation as e:\n ic(e)\n ic(index, timestamp)\n #import IPython; IPython.embed()\n if timestamp == '':\n continue\n raise e\n\n if debug:\n ic(index, timestamp)\n\n if after:\n if not is_after(timestamp=timestamp,\n after=after,\n inclusive=inclusive,\n verbose=verbose,\n debug=debug,):\n continue\n\n if before:\n if not is_before(timestamp=timestamp,\n before=before,\n inclusive=inclusive,\n verbose=verbose,\n debug=debug,):\n continue\n\n if newest:\n if not current_newest:\n current_newest = timestamp\n if verbose:\n current_newest_human = timestamp_to_human_date(current_newest)\n ic(current_newest, current_newest_human)\n else:\n if is_after(timestamp=timestamp,\n after=current_newest,\n inclusive=False,\n verbose=verbose,\n debug=debug,):\n current_newest = timestamp\n if verbose:\n current_newest_human = timestamp_to_human_date(current_newest)\n ic(current_newest, current_newest_human)\n\n if oldest:\n if not current_oldest:\n current_oldest = timestamp\n if verbose:\n current_oldest_human = timestamp_to_human_date(current_oldest)\n ic(current_oldest, current_oldest_human)\n else:\n if is_before(timestamp=timestamp,\n before=current_oldest,\n inclusive=False,\n verbose=verbose,\n debug=debug,):\n current_oldest = timestamp\n if verbose:\n current_oldest_human = timestamp_to_human_date(current_oldest)\n ic(current_oldest, current_oldest_human)\n\n if not (newest or oldest):\n print_result(timestamp=timestamp,\n human=human,\n end=end,\n verbose=verbose,\n debug=debug,)\n\n match_count += 1\n if exit_after_matches:\n if match_count >= exit_after_matches:\n sys.exit(0)\n\n if (newest or oldest):\n if newest:\n print_result(timestamp=current_newest,\n human=human,\n end=end,\n verbose=verbose,\n debug=debug,)\n if oldest:\n print_result(timestamp=current_oldest,\n human=human,\n end=end,\n verbose=verbose,\n debug=debug,)\n\n","sub_path":"epochfilter/epochfilter.py","file_name":"epochfilter.py","file_ext":"py","file_size_in_byte":9474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"213313282","text":"\"\"\"\nGiven a positive integer `N`, find the smallest number of steps it will take to reach `1`.\n\nThere are two kinds of permitted steps:\n- You may decrement `N` to `N - 1`.\n- If `a * b = N`, you may decrement `N` to the larger of `a` and `b`.\n\nFor example, given `100`, you can reach `1` in five steps with the following route: `100 -> 10 -> 9 -> 3 -> 2 -> 1`.\n\n--\ndict to store best\nfor each, iterate\n\"\"\"\nimport collections\nimport math\n\n\ndef steps_to_1(N):\n queue = collections.deque()\n queue.append((N, 0))\n found = dict()\n found[N] = 0\n while queue:\n val, count = queue.popleft()\n if val == 1:\n return count\n queue.append((val - 1, count + 1))\n for a in range(2, math.floor(math.sqrt(val)) + 1):\n b = val // a\n if a * b == val:\n if b in found:\n continue\n found[b] = count + 1\n queue.append((b, count + 1))\n\n\nif __name__ == \"__main__\":\n assert steps_to_1(100) == 5\n # with the following route: `100 -> 10 -> 9 -> 3 -> 2 -> 1\n","sub_path":"old/dcp_series/dcp_321.py","file_name":"dcp_321.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"188269601","text":"import re\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\npage_number = 1\ndata = []\nlen_previous_total_product = 0\nlen_previous_page = 0\ncheck = True\n#x= 0\n\n\n\ndef get_star(product_position):\n #Find all script json\n list_script = soup.find_all('script',{'type':'application/ld+json'})\n\n #pattern will remove the tag SCRIPT in json\n pattern = r'[^<\\sscript type=\\\"application/ld+json\\\">](.*)[^]'\n\n # Convert nontype to string to modify\n a = str(list_script[product_position])\n #print(re.find(pattern, a))\n\n # Find all string that match with pattern and store it to variable abc\n abc = re.findall(pattern,a)\n #check type of abc\n #print(abc)\n\n #split string where it has comma, and it will create a list \n list_abc =abc[0].split(',')\n\n #Because the json structure in this web has format like dict, so we convert it to dict to get info \n d = {}\n\n #We pass each element of list_abc and remove junk components by using regex\n for i in list_abc:\n component = re.sub(r'(.*{)|(}.*)|\"','',i).split(':')\n d[component[0]] = component[1]\n #print(component)\n\n # Test the result\n return d\n\n\n \n\n\nwhile(check):\n\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}\n\n r = requests.get(f'https://tiki.vn/laptop-may-vi-tinh/c1846?page={page_number}', headers=headers)\n\n # r.text is a HTML file so we will use html.parser\n soup = BeautifulSoup(r.text, 'html.parser')\n \n products = soup.find_all('div', {'class':'product-item'})\n\n product_position = 1\n \n data_check = []\n \n for product in products:\n\n # Each product is dictionary containing the required information\n d = {'product_id':'', 'seller_id':'', 'title':'', 'price':'', 'image_url':'', 'product_page_url':'', 'tiki-now':'', 'freeship':'', 'number-review':'','percentage-star':'', 'badge-under-price':'', 'discount-percentage':'', 'shocking-price':'', 'installment':'' , 'free-gift':''}\n\n # We use the try-except blocks to handle errors\n d['product_id'] = product['product-sku']\n d['seller_id'] = product['data-seller-product-id']\n d['title'] = product['data-title']\n d['price'] = product['data-price']\n\n # There are some articles without img tag...\n if product.img:\n d['image_url'] = product.img['src']\n \n #URL PAGE\n d['product_page_url'] = product.a['href']\n\n #TIKI NOW\n try:\n if (product.find('div',{'class':'badge-service'}).img['src']):\n d['tiki-now'] = product.find('div',{'class':'badge-service'}).img['src']\n except:\n d['tiki-now']='NO'\n #print(1)\n \n #FREE SHIP OR SHOCKING PRICE\n if product.find('p', {'class':'service-text'}):\n if product.find('p', {'class':'service-text'}).text == \" Freeship \":\n d['freeship'] = product.find('p', {'class':'service-text'}).text\n else:\n d['shocking-price'] = product.find('p', {'class':'service-text'}).text \n #print(2)\n\n #NUMBERS OF REVIEWS\n if product.find('p', {'class':'review'}):\n d['number-review'] = product.find('p', {'class':'review'}).text\n\n #print(3)\n \n #STARS/ PERCENTAGE OF STARS\n try:\n if (get_star(product_position)['ratingValue']):\n d['percentage-star'] = (get_star(product_position)['ratingValue'])\n product_position +=1\n except:\n d['percentage-star'] = ''\n\n #print(4)\n \n #BADGE UNDER PRICE\n if product.find('div', {'class':'badge-under_price'}):\n d['badge-under-price'] = 'Badge under price'\n if product.find('div', {'class':'badge-under-price'}):\n d['badge-under-price'] = 'Badge under price'\n\n #print(5)\n \n #DISCOUNT PERCENTAGE \n if product.find('span', {'class':'sale-tag'}):\n d['discount-percentage'] = (product.find('span', {'class':'sale-tag'}).text)\n \n #print(6)\n #INSTALLMENTS\n if product.find('p', {'class':'installment'}):\n d['installment'] = (product.find('p', {'class':'installment'}).text)\n if product.find('div', {'badge-benefits'}):\n d['installment'] = (product.find('div', {'badge-benefits'}).text)\n #print(7)\n\n if product.find('div',{'class':'freegift-list'}):\n d['free-gift'] = product.find('div',{'class':'freegift-list'}).text\n # Append the dictionary to data list\n data_check.append(d)\n data.append(d)\n \n\n if page_number == 1:\n data_page_previous = len(data)\n len_previous_total_product = len(data)\n\n\n if len(data) > len_previous_total_product or (len(data) == len_previous_total_product and page_number == 1):\n if len(data_check) < data_page_previous:\n check = False\n break\n page_number += 1\n data_page_previous = len(data_check)\n len_previous_total_product = len(data)\n #x+=1\n #print(len(data))\n #print(data[-1])\n \n \n\n #total_data.extend(data)\n #print(len(total_data))\n''' \nimport pandas as pd\n\nproducts = pd.DataFrame(data = data, columns = data[0].keys())\nprint(products)\n\n\nproducts.to_pickle(\"./result.pkl\")\nunpickled_result = pd.read_pickle(\"./result.pkl\")\nunpickled_result\n\nproducts.to_csv(\"./result.csv\", index=False)\n\n'''","sub_path":"web-scraping.py","file_name":"web-scraping.py","file_ext":"py","file_size_in_byte":5479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"230054358","text":"#!/usr/bin/python3\n\n# eoqcqiwlkbnshkdcuciftsdokbjxjsymisqitsfmrvhv\n\ncipher = input(\"Type the encrypted text: \")\nkey = input(\"Type the key: \")\n\ncipher_len = len(cipher)\nkey_len = len(key)\n\nkey_string = \"\"\n\nfor x in range(0, int(cipher_len / key_len)):\n key_string += key\n\nfor index in range(0, cipher_len % key_len):\n key_string += key[index]\n\n\nalpha_index = {}\ni = 0\nfor x in range(97, 123):\n alpha_index[chr(x)] = i\n i += 1\n\ndecipher = \"\"\nfor position in range(0, cipher_len):\n decipher += chr(97 + (alpha_index[cipher[position]] - alpha_index[key_string[position]])%26 )\n\nprint(decipher)","sub_path":"vigener.py","file_name":"vigener.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"487551620","text":"from collections import deque\n\n\ndef bfs():\n queue = deque()\n queue.append((1, 0, 0))\n visit[1][0] = 1\n while queue:\n s, clip, time = queue.popleft()\n if s == n:\n return time\n \n if visit[s][s] == 0:\n visit[s][s] = 1\n queue.append((s, s, time + 1))\n if s + clip <= n and visit[s + clip][clip] == 0:\n visit[s + clip][clip] = 1\n queue.append((s + clip, clip, time + 1))\n if s - 1 >= 0 and visit[s - 1][clip] == 0:\n visit[s - 1][clip] = 1\n queue.append((s - 1, clip, time + 1))\n\n\nn = int(input())\nvisit = [[0 for _ in range(n + 1)] for _ in range(n + 1)]\n\nprint(bfs())","sub_path":"BOJ/BOJ Python/PY14226_이모티콘.py","file_name":"PY14226_이모티콘.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"31590771","text":"import logging\nimport socket\nfrom urllib.parse import urlparse\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.signals import user_logged_in\nfrom django.db import DatabaseError\nfrom netifaces import interfaces, ifaddresses, AF_INET\n\nfrom .settings import app_settings\n\nlogger = logging.getLogger(__name__)\n\n\nCONVERSION_SERVER_HOST = urlparse(app_settings['CONVERSION_SERVER']).hostname\nCAPTURE_SERVER_HOST = urlparse(app_settings['CAPTURE_SERVER']).hostname\nAUTOLOGIN_IPS = [\n socket.gethostbyname(CONVERSION_SERVER_HOST),\n socket.gethostbyname(CAPTURE_SERVER_HOST),\n]\nfor interface in interfaces():\n for link in ifaddresses(interface).get(AF_INET, []):\n AUTOLOGIN_IPS.append(link['addr'])\n\n\ndef get_internal_user():\n if not hasattr(get_internal_user, 'instance'):\n username = app_settings['INTERNAL_USER']\n User = get_user_model()\n\n internal_user, created = User.objects.get_or_create(\n username=username,\n defaults={'password': settings.SECRET_KEY,\n 'is_active': True,\n 'is_staff': False}\n )\n\n get_internal_user.instance = internal_user\n return get_internal_user.instance\n\n\ndef clear_internal_user_cache():\n if hasattr(get_internal_user, 'instance'):\n del get_internal_user.instance\n\n\nclass AutoLoginMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n if \"HTTP_X_FORWARDED_FOR\" in request.META:\n request.META[\"HTTP_X_PROXY_REMOTE_ADDR\"] = request.META[\"REMOTE_ADDR\"]\n parts = request.META[\"HTTP_X_FORWARDED_FOR\"].split(\",\", 1)\n request.META[\"REMOTE_ADDR\"] = parts[0]\n\n useragent = request.META.get('HTTP_USER_AGENT', '')\n if useragent:\n request.META['HTTP_USER_AGENT'] = useragent.replace('FrontendTest', '')\n is_running_tests = ('FrontendTest' in useragent or getattr(settings, 'TEST', False))\n\n user = getattr(request, 'user', None)\n\n if user and user.is_anonymous and not is_running_tests:\n remoteip = request.META.get('REMOTE_ADDR')\n if remoteip in AUTOLOGIN_IPS:\n user = get_internal_user()\n try:\n user_logged_in.send(self, user=user, request=request)\n except DatabaseError as exc:\n print(exc)\n request.user = user\n\n return self.get_response(request)\n","sub_path":"mapentity/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"388603468","text":"import bpy \n\n#locations of where the head will be\nlocations = [(3.0, 3.0, 3.0), (4.0, 4.0, 4.0), (5.0, 5.0, 5.0), (6.0, 6.0, 6.0)]\n\n#initial locations\ninit_vertices = [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)]\ninit_edges = [[0, 1], [1, 2]]\n\n#contextual objects\nSCENE = bpy.context.scene \t\t\t\t\t#grab the active scene\nFRAME_NUM = 0\nSCENE.frame_start = FRAME_NUM\t\t\t\t#begin animation at 0\n\n#names\nmesh_name = \"PLSWORKMESH\"\nobj_name = \"PLSWORKOBJ\"\n\n\n\n\n\n\n\n\n#initialize a new mesh and object for the vector\nmesh = bpy.data.meshes.new(mesh_name)\nmesh.from_pydata(init_vertices, init_edges, [])\nmesh.update()\nbpy.data.objects.new(obj_name, mesh)\n\n#grab the object\nvector = bpy.data.objects[obj_name]\n\n#Link mesh to object and object to scene\nvector.data = mesh \t\t\t\t\t\t\t#mesh to object\nbpy.context.scene.objects.link(vector) \t\t#object to scene\nbpy.context.scene.objects.active = vector\n\n#grab the VCG vector's head coordinates property\nVCG_head = bpy.data.objects[obj_name].data.vertices[2]\n\n#set the first keyframe\nVCG_head.keyframe_insert(data_path=\"co\")\n\nfor location in locations:\n\tFRAME_NUM+= 10\n\tbpy.context.scene.frame_set(FRAME_NUM)\n\n\tVCG_head.co = location \n\tVCG_head.keyframe_insert(data_path=\"co\")\n\nSCENE.frame_end = FRAME_NUM \n","sub_path":"VCGPathScript_v1.py","file_name":"VCGPathScript_v1.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"338833264","text":"def minNumofHops(array):\n if len(array) == 1:\n return 0\n hops = 0\n maxReach = array[0]\n steps = array[0]\n for i in range(1, len(array)-1):\n maxReach = max(maxReach, i+array[i])\n steps -= 1\n if steps == 0:\n hops += 1\n steps = maxReach-i\n\n return hops + 1\n\n\narray = []\nfor i in range(11):\n val = int(input())\n array.append(val)\n\nprint(minNumofHops(array))\n","sub_path":"ladder.py","file_name":"ladder.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"397114827","text":"string = input('Enter your string = ')\n\nstring = string.lower()\n\nalphabate = 'abcdefghijklmnopqrstuvwxyz'\n\nlt_ct = {}\n\nfor char in string:\n if char in alphabate:\n if char in lt_ct:\n lt_ct[char] = lt_ct[char] + 1\n else:\n lt_ct[char] = 1\n\nkeys = lt_ct.keys()\n\nfor char in sorted(keys):\n print(char, lt_ct[char])\n\n","sub_path":"CharacterCount.py","file_name":"CharacterCount.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"81526883","text":"import torch\nfrom torch import nn\n\nclass DomainTokeinzer(torch.nn.Module):\n def __init__(self, config):\n super().__init__()\n\n self.config = config\n self.pad_index = 0\n self.total_subdomian_domain_elements = 1\n\n self.SubdomianDomain2index = {'pad':self.pad_index}\n self.define_SubdomianDomain2index()\n\n self.subdomain2domain = {}\n self.define_subdomain2domain_dict()\n\n def get_SubdomianDomain2index_len(self):\n return len(self.SubdomianDomain2index)\n\n def define_SubdomianDomain2index(self):\n\n for domain in self.config.domain2parts.keys():\n self.SubdomianDomain2index[domain] = self.total_subdomian_domain_elements\n self.total_subdomian_domain_elements += 1\n\n for domain_parts_list_name in self.config.domain2parts:\n for subdomian_type in self.config.domain2parts[domain_parts_list_name]:\n self.SubdomianDomain2index[subdomian_type] = self.total_subdomian_domain_elements\n self.total_subdomian_domain_elements += 1\n\n def define_subdomain2domain_dict(self):\n for domain_parts_list_name in self.config.domain2parts:\n for subdomian_type in self.config.domain2parts[domain_parts_list_name]:\n self.subdomain2domain[subdomian_type] = domain_parts_list_name\n\n def get_batch_tokenized(self, token_list):\n return torch.stack([self.__call__(token) for token in token_list])\n\n def __call__(self, subdomain, need_random_subdomain = None):\n tokenized_DomainSubdomian_element = []\n domain = self.subdomain2domain.get(subdomain)\n if domain:\n domain_index = self.SubdomianDomain2index[domain]\n tokenized_DomainSubdomian_element.append(domain_index)\n\n subdomain_index = self.SubdomianDomain2index[subdomain]\n tokenized_DomainSubdomian_element.append(subdomain_index)\n tokenized_DomainSubdomian_element += [self.pad_index] * (self.get_SubdomianDomain2index_len() - len(tokenized_DomainSubdomian_element))\n else:\n for token_index in range(len(self.SubdomianDomain2index)):\n tokenized_DomainSubdomian_element.append(token_index)\n\n # tokenized_DomainSubdomian_list.append(tokenized_DomainSubdomian_element)\n # return torch.tensor(tokenized_DomainSubdomian_list)\n if need_random_subdomain == True:\n return torch.tensor(tokenized_DomainSubdomian_element), [0]\n else:\n return torch.tensor(tokenized_DomainSubdomian_element)\n\nclass DomainEmdeddings(torch.nn.Module):\n def __init__(self, config, domain_indexes_number):\n super().__init__()\n\n self.config = config\n\n self.domain_embeddings = nn.Embedding(num_embeddings=domain_indexes_number,\n embedding_dim=self.config.model_dim)\n\n self.apply(self.init_weights)\n\n def init_weights(self, module):\n if isinstance(module, (nn.Embedding,)):\n module.weight.data.uniform_(-self.config.init_range, self.config.init_range)\n\n def forward(self, DomaiSubdomain_tokens_batch):\n embeddings = self.domain_embeddings(DomaiSubdomain_tokens_batch)\n return embeddings","sub_path":"conditional_model/model/c_4/domain_c4.py","file_name":"domain_c4.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"365377084","text":"#!/usr/bin/env python\n\n# Task: Calculate total number of viewers by show for ABC given shows/station, show/viewers.\n# join1_mapper.py provides the map() function for Map/Reduce\n\n# map() inputs: 6 total files (3 gennum, 3 genchan)\n# join2_gennum*.txt consist of (A TV show title and the number of viewers)\n# join2_genchan*.txt consists of (A TV show title and the channel it was on) \n\nimport sys \n \nfor line in sys.stdin:\n\tline = line.strip() #strip out carriage return\n\tkey_value = line.split(\",\") #split line, into key and value, returns a list\n\tkey_in = key_value[0] #key is first item in list\n\tvalue_in = key_value[1] #value is 2nd item \n\tif value_in == \"ABC\" or value_in.isdigit():\n\t\tprint(key_in,'\\t',value_in)","sub_path":"join2_mapper.py","file_name":"join2_mapper.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"625682116","text":"import re\nimport os\nimport time\nfrom docx import Document\n# 修改段前 段后间距\nfrom docx.shared import Pt\n# 居中\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\n# 修改字体\nfrom docx.oxml.ns import qn\n\nclass SJK_CONTENT:\n\tdef remove_label(self,text_content):\n\t\t\"\"\"\n\t\t过滤文本\n\t\t:params text_content:待替换文本列表\n\t\t:return :list\n\t\t\"\"\"\n\t\t# 取出图片链接\n\t\timg_regular = re.compile(r\"\"\".*?src=['\"](.*?)['\"].*?\"\"\")\n\t\t# 去除转义字符,\\n \\a \\t\n\t\tescape_regular = re.compile(r\"[\\a\\b\\f\\n\\t\\r\\v\\\\]\")\n\t\t# 去除html标签\n\t\thtml_regular = re.compile(r\"<[^>]+>\",re.S)\n\t\t# 去除utf编码保存文件导致出现的\\ufeff\n\t\tbom_regular = re.compile(u\"[\\ufeff]+\",re.S)\n\n\t\tres = []\n\t\tfor text in text_content:\n\t\t\t# 匹配src链接\n\t\t\tif \"src\" in text and \"img\" in text:\n\t\t\t\timg = re.findall(img_regular,text.replace(\" \",\"\"))\n\t\t\t\tfor i in img:\n\t\t\t\t\tres.append(i)\n\t\t\t# 去除转义字符\n\t\t\ttext = re.sub(escape_regular,\"\",text)\n\t\t\t# 去除html标签\n\t\t\ttext = re.sub(html_regular,\"\",text)\n\t\t\t# 去除utf编码保存文件导致出现的\\ufeff\n\t\t\ttext = re.sub(bom_regular,\"\",text)\n\t\t\tif text != \"\":\n\t\t\t\tres.append(text)\n\n\t\treturn res\n\n\tdef write_docx(self,section_name,docx_path,new_text_content):\n\t\t\"\"\"\n\t\t章节文档写入docx\n\t\t:params docx_path: docx存储路径\n\t\t:params new_text_content: 过滤过的内容\n\t\t:return : None\n\t\t\"\"\"\n\t\t# 解决了写入标题都是同一个标题的Bug\n\t\tdocument = Document()\n\t\t# 添加标题0,居中\n\t\thead = document.add_heading(section_name,0)\n\t\thead.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER\n\n\t\t# 更改Normal样式,正文\n\t\tdocument.styles['Normal'].font.name = u'仿宋'\n\t\tdocument.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋')\n\n\t\tfor _ in new_text_content:\n\t\t\tparagraph = document.add_paragraph(_,'Normal')\n\t\t\tparagraph.paragraph_format.space_before = Pt(20)\n\t\tdocument.save(docx_path)\n\t\tprint(docx_path,\"下载完成\")\n\t\ttime.sleep(1)\n\n\tdef main(self,section_name,docx_path,text_content):\n\t\t# 先正则过滤,再写入\n\t\t# 不存在则进行SC流程\n\t\tif os.path.exists(docx_path):\n\t\t\tprint(docx_path,\"已存在\")\n\t\t\treturn\n\n\t\tnew_text_content = self.remove_label(text_content)\n\t\tself.write_docx(section_name,docx_path,new_text_content)","sub_path":"sjk_content.py","file_name":"sjk_content.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"567826896","text":"# -*- coding: UTF-8 -*-\n#build DNN model by tensorflow\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport keras\nimport numpy as np\nnp.random.seed(1337) # for reproducibility\n\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.optimizers import RMSprop\nfrom keras.utils import np_utils\n\ndef build_model(X_train, Y_train, X_test, Y_test, nb_classes = 3, nb_epoch = 20, batch_size = 8, hidden_unit = [512,512]):\n #convert class vectors to binary class matrices\n #to_categorical(y, nb_classes=None\n #将类别向量(从0到nb_classes的整数向量)映射为二值类别矩阵, 用于应用到以categorical_crossentropy为目标函数的模型中\n #y: 类别向量; nb_classes:总共类别数\n X_train= np.transpose(X_train)\n X_test= np.transpose(X_test)\n print('X_train.shape'+str(X_train.shape))\n print('X_test.shape'+str(X_test.shape))\n train_m = X_train.shape[0]\n train_input = X_train.shape[1]\n Y_train = np_utils.to_categorical(Y_train, nb_classes)\n Y_test = np_utils.to_categorical(Y_test, nb_classes)\n # Dense层:即全连��层\n # keras.layers.core.Dense(output_dim, init='glorot_uniform', activation='linear', weights=None, W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, input_dim=None)\n # 激活函数可以通过设置单独的激活层实现,也可以在构造层对象时通过传递activation参数实现。\n model = Sequential()\n model.add(Dense(hidden_unit[0], input_shape=(train_input,)))\n model.add(Activation('relu'))\n model.add(Dropout(0.2))\n # 以下两行等价于:model.add(Dense(#hidden_unit,activation='relu'))\n model.add(Dense(hidden_unit[1]))\n model.add(Activation('relu'))\n\n # Dropout 需要断开的连接的比例\n model.add(Dropout(0.2))\n model.add(Dense(nb_classes))\n model.add(Activation('softmax'))\n\n # 打印出模型概况\n print('model.summary:')\n model.summary()\n # 在训练模型之前,通过compile来对学习过程进行配置\n # 编译模型以供训练\n # 包含评估模型在训练和测试时的性能的指标,典型用法是metrics=['accuracy']\n # 如果要在多输出模型中为不同的输出指定不同的指标,可像该参数传递一个字典,例如metrics={'ouput_a': 'accuracy'}\n model.compile(loss='categorical_crossentropy',\n optimizer=RMSprop(lr=0.003, rho=0.9, epsilon=1e-08, decay=0.2),\n metrics=['accuracy'])\n\n # 训练模型\n # Keras以Numpy数组作为输入数据和标签的数据类型\n # fit(self, x, y, batch_size=32, nb_epoch=10, verbose=1, callbacks=[], validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None)\n # nb_epoch:整数,训练的轮数,训练数据将会被遍历nb_epoch次。Keras中nb开头的变量均为\"number of\"的意思\n # verbose:日志显示,0为不在标准输出流输出日志信息,1为输出进度条记录,2为每个epoch输出一行记录\n # shuffle:布尔值,表示是否在训练过程中每个epoch前随机打乱输入样本的顺序。\n\n # fit函数返回一个History的对象,其History.history属性记录了损失函数和其他指标的数值随epoch变化的情况,如果有验证集的话,也包含了验证集的这些指标变化情况\n history = model.fit(X_train, Y_train,\n batch_size=batch_size, epochs=nb_epoch,\n verbose=1, validation_data=(X_test, Y_test),\n shuffle = True)\n # 按batch计算在某些输入数据上模型的误差\n print('-------evaluate--------')\n score = model.evaluate(X_test, Y_test, verbose=1)\n print('Test score:', score[0])\n print('Test accuracy:', score[1])\n\ndef predict(classifier,new_samples):\n return []\n\n","sub_path":"test/xears/models/DNN.py","file_name":"DNN.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"213422804","text":"from pandas.plotting import table\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n\ndef cast_seconds(v):\n list_ = v.split(':')\n hours, minutes, seconds = int(list_[0]), int(list_[1]), int(list_[2])\n return hours * 60 * 60 + minutes * 60 + seconds\n\n\ndef read_plot_table(path):\n df = pd.read_csv(path, index_col=False, error_bad_lines=False)\n column_name = df.columns[0]\n columns = ['VarName', 'TimeString', 'VarValue', 'Validity', 'Time_ms']\n df = df[column_name].str.split(';', expand=True)\n df.columns = columns\n df = df.iloc[:-1, :]\n df['time'] = df.TimeString.str.split(' ', expand=True).iloc[:, 1].apply(lambda x: x.replace('\"', ''))\n df.time = df.time.apply(lambda x: cast_seconds(x))\n idx = []\n min_ = 0\n for i in df.time.index:\n if df.time.loc[i] >= min_:\n idx.append(i)\n min_ = df.time.loc[i]\n\n df = df.loc[idx]\n return df.time.values, df.VarValue.values.astype('float')\n\n\ndef read_customer_data(path):\n df = pd.read_csv(path, sep=';')\n df.columns = [col.strip() for col in df.columns]\n columns = ['Client', 'Order', 'N_serial', 'Dim1', 'Dim2']\n return df[columns].replace(np.nan, 0), df.Note.values[0]\n\n\ndef save_table_image(df, path):\n ax = plt.subplot(111, frame_on=False)\n ax.xaxis.set_visible(0)\n ax.yaxis.set_visible(0)\n table(ax, df, loc='upper center')\n plt.savefig(path)\n\n\ndef table_to_string(df):\n s = ''\n for c in df.columns:\n s += c\n s += ': '\n s += str(df[c].values[0])\n s += ' ' * 5\n return s\n\n\ndef step_data_reader(path):\n df = pd.read_csv(path, usecols=[0], skiprows=0)\n df.rename(columns={'List separator=;Decimal symbol=':\n 'split_'},\n inplace=True)\n df = df.split_.str.split(';', expand=True)\n df.rename(columns={0: 'name',\n 1: 'step'},\n inplace=True)\n return df\n\n\ndef cast_order(data, order):\n col_names = [x.split('_')[3:] for x in data.columns]\n data.columns = ['_'.join(name) for name in col_names]\n return data[order]\n\n\ndef aggregate_step_data(data, keys, order):\n table = pd.DataFrame()\n for key in keys:\n step = data.loc[data.name.apply(lambda x: key in x)]\n step = step.set_index('name').T\n step = cast_order(step, order)\n step.index = [key]\n\n table = pd.concat([table, step], axis=0)\n\n table.amp = table.amp.astype('float')\n table.temp_lav = table.temp_lav.astype('float')\n\n table.amp = table.amp / 10\n\n table.temp_lav = table.temp_lav / 10\n\n table.amp = table.amp.astype('str')\n table.temp_lav = table.temp_lav.astype('str')\n print(table.temp_lav.values)\n print(table.amp.values)\n\n table.mod_crom = table.mod_crom.apply(lambda x: 'crome' if x == 0 else 'etching')\n matches = {'0': 'Start from previous',\n '1': 'Start from max',\n '2': 'Start from min'}\n\n table.replace({'start_da': matches}, inplace=True)\n\n table.volt = table.volt.astype('float') / 10\n table.volt = table.volt.astype('str')\n return table\n","sub_path":"utils/table_helpers.py","file_name":"table_helpers.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"380552028","text":"\nfrom django.conf.urls import url, include\nfrom appStudent.views import viewStudentAccount as studentAccountViews\nfrom appStudent.views import viewPdfStudentDetail\n\nfrom appStudent.views import viewMoveStudent as moveStudentViews\n\nfrom appStudent.views import viewAdmission as admissionViews\n\nstudentAccount = [\n url(r'^$', studentAccountViews.vwfnStudentAccountIndex, name='student-account-index'),\n url(r'^edit/(?P\\d+)', studentAccountViews.vwfnStudentAccountEdit, name='student-account-edit'),\n url(r'^delete/(?P\\d+)',studentAccountViews.vwfnStudentAccountDelete, name='student-account-delete'),\n url(r'^delete-image/(?P\\d+)',studentAccountViews.vwfnStudentAccountDeleteImage, name='student-account-delete-image')\n]\n\nstudenPDF = [\n\n]\n\nurlpatterns = [\n url(r'^student-account/', include(studentAccount, namespace='student-account')),\n url(r'^pdf---student-detail$', viewPdfStudentDetail.vwfnPdfStudentAccountIndex, name='student-detail-index'),\n url(r'^pdf---student-detail/pdf', viewPdfStudentDetail.vwfnPdfStudentAccountPrint, name='student-detail-pdf'),\n\n # Move-Student\n url(r'^move-student$', moveStudentViews.vwfnMoveStudentIndex, name='move-student'),\n\n # admission\n url(r'^admission$', admissionViews.vwfnAdmissionIndex, name='admission'),\n url(r'^admission/create', admissionViews.vwfnAdmissionCreate, name='admission-create'),\n url(r'^admission/edit/(?P\\d+)', admissionViews.vwfnAdmissionEdit, name='admission-edit'),\n url(r'^admission/delete/(?P\\d+)', admissionViews.vwfnAdmissionDelete, name='admission-delete'),\n url(r'^admission/move-students', admissionViews.vwfnAdmissionMoveStudent, name='admission-move-students'),\n]\n\n\n'''Route::get('load-student-data', 'loaddata\\School\\Controllers\\StudentDataController@index');\nRoute::post('load-student-data', 'loaddata\\School\\Controllers\\StudentDataController@store');\n\nRoute::get('admission', 'School\\Controllers\\AdmissionController@index');\nRoute::get('admission/create', 'School\\Controllers\\AdmissionController@create');\nRoute::post('admission/create', 'School\\Controllers\\AdmissionController@store');\nRoute::get('admission/edit/{id}', 'School\\Controllers\\AdmissionController@edit');\nRoute::post('admission/edit/{id}', 'School\\Controllers\\AdmissionController@update');\nRoute::get('admission/delete/{id}', 'School\\Controllers\\AdmissionController@destroy');\nRoute::post('admission/move-students', 'School\\Controllers\\AdmissionController@moveStudents');\n\nRoute::get('move-student', 'School\\Controllers\\MoveStudentController@index');\nRoute::post('move-student', 'School\\Controllers\\MoveStudentController@move');\n\n\nRoute::get('pdf---student', 'reports\\School\\Controllers\\OneStudentController@index');\nRoute::get('pdf---student/pdf', 'reports\\School\\Controllers\\OneStudentController@report');\n\nRoute::get('pdf---dice', 'reports\\School\\Controllers\\DICEController@index');\nRoute::get('pdf---dice/pdf', 'reports\\School\\Controllers\\DICEController@report');\nRoute::get('pdf---dice/csv', 'reports\\School\\Controllers\\DICEController@csv');'''\n","sub_path":"appStudent/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"646819488","text":"from models import create_classes\nimport os\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect)\n\napp = Flask(__name__)\n\nfrom flask_sqlalchemy import SQLAlchemy\nengine = create_engine(\"sqlite:///nsBorder.sqlite\")\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n\n\nprint(Base.classes.keys())\n\nnorthPorts = Base.classes.northPorts\nsouthPorts = Base.classes.southPorts\nnorthStates = Base.classes.northStates\nsouthStates = Base.classes.southStates\n\n@app.route(\"/\")\ndef index():\n return render_template(\"north_ports.html\")\n\n@app.route(\"/south_ports\")\ndef south_port_page():\n return render_template(\"south_ports.html\")\n\n@app.route(\"/north_states\")\ndef north_states_page():\n return render_template(\"north_states.html\")\n\n@app.route(\"/south_states\")\ndef south_states_page():\n return render_template(\"south_states.html\")\n\n\n@app.route(\"/north_port\")\ndef north_port_entrydata():\n session = Session(engine)\n north_port_results = session.query(northPorts.A, northPorts.PortName, northPorts.Date, northPorts.Value).all()\n north_port_info = []\n for result in north_port_results:\n north_port_entry_info = {\n \"id\": result.A,\n \"PortName\": result.PortName,\n \"Date\": result.Date,\n \"Value\": result.Value\n\n }\n\n north_port_info.append(north_port_entry_info)\n\n return jsonify(north_port_info)\n\n@app.route(\"/south_port\") \ndef south_port_entrydata():\n session = Session(engine)\n south_port_results = session.query(southPorts.A, southPorts.PortName, southPorts.Date, southPorts.Value).all()\n south_port_info = []\n for result in south_port_results:\n south_port_entry_info = {\n \"id\": result.A,\n \"PortName\": result.PortName,\n \"Date\": result.Date,\n \"Value\": result.Value,\n\n }\n\n south_port_info.append(south_port_entry_info)\n\n return jsonify(south_port_info)\n\n@app.route(\"/north_state\")\ndef north_state_entrydata():\n session = Session(engine)\n north_state_results = session.query(northStates.A, northStates.State, northStates.Date, northStates.Value).all()\n north_state_info = []\n for result in north_state_results:\n north_state_entry_info = {\n \"id\": result.A,\n \"State\": result.State,\n \"Date\": result.Date,\n \"Value\": result.Value,\n\n }\n \n north_state_info.append(north_state_entry_info)\n \n return jsonify(north_state_info)\n \n@app.route(\"/south_state\")\ndef south_state_entrydata(): \n session = Session(engine)\n south_state_results = session.query(southStates.A, southStates.State, southStates.Date, southStates.Value).all()\n south_state_info = []\n for result in south_state_results:\n south_state_entry_info = {\n \"id\": result.A,\n \"State\": result.State,\n \"Date\": result.Date,\n \"Value\": result.Value\n\n }\n\n \n\n south_state_info.append(south_state_entry_info)\n\n return jsonify(south_state_info)\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"env/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"446634311","text":"import unittest\nimport reader, printer, evaluator, utilities\nfrom scheme_objects import *\nimport scheme_exceptions.reader_exceptions as readerEx\n\n\nclass ReaderQuoteTestCase(unittest.TestCase):\n def setUp(self):\n self.stream = utilities.StringStream()\n self.output_stream = utilities.StringStream()\n\n def test_simple_quote(self):\n self.stream.set_stream(\"'(a b c d e f g)\")\n result = reader.read_from_stream(self.stream)\n printer.print_scheme_object(result, self.output_stream)\n self.assertEqual(self.output_stream.get_stream(), \"(quote (a b c d e f g))\")\n\n def test_nested_quote(self):\n self.stream.set_stream(\"(x (a '(a b c d e f g)))\")\n result = reader.read_from_stream(self.stream)\n printer.print_scheme_object(result, self.output_stream)\n self.assertEqual(self.output_stream.get_stream(), \"(x (a (quote (a b c d e f g))))\")\n\n def test_malformed_quoted_list(self):\n with self.assertRaises(readerEx.MalformedListException) as cm:\n self.stream.set_stream('10 123)')\n reader.read_from_stream(self.stream)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_07_reader_quote.py","file_name":"test_07_reader_quote.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"186303227","text":"from flask import Flask, flash, render_template, redirect, url_for, session, logging, request, send_from_directory, jsonify, make_response, json\nfrom functools import wraps\nimport os\nimport json\nfrom os import environ as env\nimport jwt\nimport datetime\nfrom dotenv import load_dotenv, find_dotenv\nfrom datetime import timedelta\nfrom redis import Redis\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.datastructures import CallbackDict\nfrom flask.sessions import SessionInterface, SessionMixin\nimport pickle\nimport redis\nfrom authlib.flask.client import OAuth\nfrom six.moves.urllib.parse import urlencode\n\nimport constants\n\nENV_FILE = find_dotenv()\nif ENV_FILE:\n load_dotenv(ENV_FILE)\n\nAUTH0_CALLBACK_URL = constants.AUTH0_CALLBACK_URL\nAUTH0_CLIENT_ID = constants.AUTH0_CLIENT_ID\nAUTH0_CLIENT_SECRET = constants.AUTH0_CLIENT_SECRET\nAUTH0_DOMAIN = constants.AUTH0_DOMAIN\n\nAUTH0_BASE_URL = 'https://' + AUTH0_DOMAIN\nAUTH0_AUDIENCE = constants.AUTH0_AUDIENCE\nif AUTH0_AUDIENCE is '':\n AUTH0_AUDIENCE = AUTH0_BASE_URL + '/userinfo'\n\napp = Flask(__name__)\n\nimport redis\nfrom uuid import uuid4\napp.secret_key=constants.SECRET_KEY\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\nAPP_FILES = APP_ROOT + \"/../dl/\"\n\n#Auth0\noauth = OAuth(app)\n\nauth0 = oauth.register(\n 'auth0',\n client_id=AUTH0_CLIENT_ID,\n client_secret=AUTH0_CLIENT_SECRET,\n api_base_url=AUTH0_BASE_URL,\n access_token_url=AUTH0_BASE_URL + '/oauth/token',\n authorize_url=AUTH0_BASE_URL + '/authorize',\n client_kwargs={\n 'scope': 'openid profile',\n },\n)\n\n#FUNCTIONS\ndef convertUrlDownloadsToList():\n target = os.path.join(APP_FILES, 'urlKeysAndFilePaths.txt')\n listOfUrlDownloads = []\n listOfUrlDownloads.append([])\n f=open(target,'r')\n i = 0\n for line in f:\n # Each record of listOfUrlDownloads is [urlKey,filename]\n partsOfFile = line.split(' ')\n listOfUrlDownloads[i].append(partsOfFile[0])\n filepath = partsOfFile[1].rstrip()\n partsOfFilepath = filepath.split('/')\n listOfUrlDownloads[i].append(partsOfFilepath[1])\n i += 1\n listOfUrlDownloads.append([])\n return listOfUrlDownloads\n\n#REDIS CONFIGURATION\ndef generate_sid():\n return str(uuid4())\n\ndef openSession(username):\n #r = redis.StrictRedis(host='localhost', port=6379, db=0)\n r = redis.StrictRedis(host='localhost', port=6379, password=\"\", decode_responses=True)\n\n sid1 = str(uuid4())\n key1 = 'ostrowm4:session:'+sid1\n sid2 = str(uuid4())\n key2 = 'ostrowm4:session:'+sid2\n value1 = username\n r.set(key1, value1)\n r.set(key2, \"true\")\n return sid1, sid2\n\ndef closeSession(sid1, sid2):\n #r = redis.StrictRedis(host='localhost', port=6379, db=0)\n r = redis.StrictRedis(host='localhost', port=6379, password=\"\", decode_responses=True)\n key1='ostrowm4:session:'+sid1.rstrip()\n key2='ostrowm4:session:'+sid2.rstrip()\n r.delete(key1)\n r.delete(key2)\n\ndef getLogin(sid):\n #r = redis.StrictRedis(host='localhost', port=6379, db=0)\n r = redis.StrictRedis(host='localhost', port=6379, password=\"\", decode_responses=True)\n key = 'ostrowm4:session:'+sid.rstrip()\n #TESTY: zapytanie redis get key w konsoli zwróci przechowywaną wartość, poniższy kod nie.\n return r.get(key) #.decode('ascii')\n\n#saving sid's in file\ndef saveSid(sid):\n f = open(\"sid.txt\", \"a\")\n f.write(sid + \"\\n\")\n f.close()\n#getting sid from file, first line = username, second line = \"true\"\ndef getSid(num):\n with open('sid.txt', \"r\") as f:\n lines=f.readlines()\n return lines[num - 1]\n\n#application\n\n@app.route('/ostrowm4/app/')\ndef index():\n return render_template('index.html')\n\ndef check_if_login(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if getLogin(getSid(2)) == \"true\":\n return f(*args, **kwargs)\n else:\n return redirect(url_for('login'))\n return wrap\n\n#If redis is not required:\n'''\ndef requires_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n if constants.PROFILE_KEY not in session:\n return redirect('/login')\n return f(*args, **kwargs)\n return decorated\n'''\n\n@app.route('/ostrowm4/app/login/')\ndef login():\n return render_template('login.html')\n\n@app.route('/ostrowm4/app/loginLogic/')\ndef loginLogic():\n return auth0.authorize_redirect(redirect_uri=AUTH0_CALLBACK_URL, audience=AUTH0_AUDIENCE)\n\n@app.route('/ostrowm4/app/callback')\ndef callback_handling():\n auth0.authorize_access_token()\n resp = auth0.get('userinfo')\n userinfo = resp.json()\n username = userinfo['name']\n\n session[constants.JWT_PAYLOAD] = userinfo\n session[constants.PROFILE_KEY] = {\n 'user_id': userinfo['sub'],\n 'name': userinfo['name'],\n 'picture': userinfo['picture']\n }\n\n sessionSid1, sessionSid2 = openSession(username)\n saveSid(sessionSid1)\n saveSid(sessionSid2)\n flash('You are now logged in', 'success')\n app.config['token'] = jwt.encode({'user' : username, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=3)}, app.config['SECRET_KEY'])\n\n return redirect(url_for('fileSubmitter'))\n\n@app.route('/ostrowm4/app/logout/')\n@check_if_login\ndef logout():\n closeSession(getSid(1), getSid(2))\n open('sid.txt', 'w').close()\n session.clear()\n params = {'returnTo': url_for('login', _external=True), 'client_id': AUTH0_CLIENT_ID}\n return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params))\n #return redirect(url_for('login'))\n\n@app.route('/ostrowm4/app/fileSubmitter/')\n@check_if_login\ndef fileSubmitter():\n target = os.path.join(APP_FILES, getLogin(getSid(1)) + 'Files')\n userFiles = os.listdir(target)\n dowloadUrlsList = convertUrlDownloadsToList()\n return render_template('fieSubmitter.html', files=userFiles, target=target, token=app.config['token'], username=getLogin(getSid(1)), isLog = getLogin(getSid(2)), dowloadUrls = dowloadUrlsList)\n\nif __name__ == '__main__':\n #app.config['SESSION_COOKIE_SECURE'] = True\n #app.config['REMEMBER_COOKIE_SECURE'] = True\n #app.config['SESSION_COOKIE_HTTPONLY'] = True\n #app.config['REMEMBER_COOKIE_HTTPONLY'] = True\n #app.run(port = '443')\n app.run(debug=True, port=5000) #to delete on pi server\n","sub_path":"webapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"521389970","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom Field import Field\n\nclass ModelMetaclass(type):\n\tdef __new__(cls, name, bases, attrs):\n\t\tif name==\"Model\":\n\t\t\treturn type.__new__(cls, name, bases, attrs)\n\t\tprint('Found model: %s' % name)\n\t\tmappings = dict()\n\t\tfor k, v in attrs.items():\n\t\t\tif isinstance(v, Field):\n\t\t\t\tprint('Found mapping %s ==> %s' % (k, v))\n\t\t\t\tmappings[k] = v\n\t\tfor k in mappings.keys():\n\t\t\tattrs.pop(k)\n\t\tattrs['__mappings__'] = mappings\n\t\tattrs['__table__'] = name\n\t\treturn type.__new__(cls, name, bases, attrs)\n","sub_path":"learnpy/simpleORM/ModelMetaclass.py","file_name":"ModelMetaclass.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"87458014","text":"import numpy as np\nimport matplotlib.pyplot as plt\nerr1=np.load('10errorvec.npy')\nblkerr1=np.load('10blkerrorvec.npy')\nSNR1=np.load('10SNR.npy')\nerr2=np.load('10-128-20gaussianSNRtest/10errorvec.npy')/50000*100\nblkerr2=np.load('10-128-20gaussianSNRtest/10blkerrorvec.npy')/5000*100\nSNR2=np.load('10-128-20gaussianSNRtest/10SNR.npy')\n\ntrainSNR2=np.zeros([SNR2.shape[0],])\nleng=SNR2.shape[0]\nfor i in range(0,leng):\n trainSNR2[i]=SNR2[i,i]\n\n\n\n\n#(trainSNr, testSNR)\n\n\nprint ('dummy')\n#(trainsize,TestSNR)\nfor i in range(0,20):\n plt.plot(trainSNR2[0:i+2],err2[0:i+2,i])\n plt.show()\n print(np.mean(SNR2[:,i]))\n print('dummy')\n #code for certain training SNr, draw bit rate vs SNR\n\n\n\n\nfor i in range(0,20):\n plt.plot(SNR2[i,:],blkerr2[i,:])\n print(trainSNR2[i])\n print('dummy')\n #code for certain training SNr, draw block rate vs SNR\n#plt.figlegend((line1, line2, line3),('label1', 'label2', 'label3'),'upper right')\nplt.show()\nprint ('dummy')\n\nfor i in range(0,20):\n plt.plot(SNR2[i,:],err2[i,:])\n print(trainSNR2[i])\n print('dummy')\n #code for certain training SNr, draw bit rate vs SNR\nplt.show()\nprint ('dummy')\n","sub_path":"Obsolete/drawpic.py","file_name":"drawpic.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"595125393","text":"from django.contrib import admin\nfrom app_registry.models import *\nfrom django.http import HttpResponse\n\nimport csv\nfrom django.utils.encoding import smart_str\n\nimport xlsxwriter\nimport io\n\nadmin.site.register(Areas)\n\nclass PersonaAdmin(admin.ModelAdmin):\n def export_csv(modeladmin, request, queryset):\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=DatosEstudiantes.csv'\n writer = csv.writer(response, csv.excel)\n response.write(u'\\ufeff'.encode('utf8'))\n writer.writerow([\n smart_str(u\"Tipo\"),\n smart_str(u\"Area\"),\n smart_str(u\"Apellidos\"),\n smart_str(u\"Nombres\"),\n smart_str(u\"Documento Identificacion\"),\n smart_str(u\"Nacionalidad\"),\n smart_str(u\"Sexo\"),\n smart_str(u\"Fecha Inicio\"),\n smart_str(u\"Fecha Fin\"),\n smart_str(u\"Fecha Nacimiento\"),\n smart_str(u\"Estado Civil\"),\n smart_str(u\"Estado Nacimiento\"),\n smart_str(u\"Pais Nacimiento\"),\n\n ])\n for obj in queryset:\n if obj.sexo == 0:\n sexo = 'Femenino'\n else:\n sexo ='Masculino'\n\n if obj.tipo == 0:\n tipo ='Pasantia'\n elif obj.tipo == 1:\n tipo = 'Post-Grado'\n elif obj.tipo == 2:\n tipo = 'Fellow'\n elif obj.tipo == 3:\n tipo = 'Visitor'\n\n if obj.fecha_nacimiento == None:\n fecha_nac = \"\"\n else:\n fecha_nac = obj.fecha_nacimiento\n\n if obj.estado_civil == 0:\n estado_civil ='Soltero'\n elif obj.estado_civil == 1:\n estado_civil = 'Casado'\n elif obj.estado_civil == 2:\n estado_civil= 'Divorciado'\n elif obj.estado_civil == 3:\n estado_civil= 'Viudo'\n else:\n estado_civil = \"\"\n\n writer.writerow([\n smart_str(tipo),\n smart_str(obj.area.nombre),\n smart_str(obj.apellidos),\n smart_str(obj.nombres),\n smart_str(obj.didentificacion),\n smart_str(obj.nacionalidad),\n smart_str(sexo),\n smart_str(obj.fecha_inicio),\n smart_str(obj.fecha_fin),\n smart_str(fecha_nac),\n smart_str(estado_civil),\n smart_str(obj.estado_nacimiento),\n smart_str(obj.pais_nacimiento),\n ])\n return response\n export_csv.short_description = u\"Descargar informacion formato CSV\"\n\n\n def export_xls(modeladmin, request, queryset): \n output = io.BytesIO()\n\n workbook = xlsxwriter.Workbook(output, {'in_memory': True})\n worksheet = workbook.add_worksheet(\"Profesionales\")\n\n row_num = 0\n columns = [\n (u\"Tipo\", 10),\n (u\"Área\", 20),\n (u\"Apellidos\", 20),\n (u\"Nombres\", 20),\n (u\"Documento Identificación\", 15),\n (u\"Nacionalidad\", 15),\n (u\"Sexo\", 10),\n (u\"Fecha Inicio\", 15),\n (u\"Fecha Fin\", 15),\n (u\"Fecha Nacimiento\", 15),\n (u\"Estado Civil\", 10),\n (u\"Estado Nacimiento\", 15),\n (u\"Pais Nacimiento\", 15),\n ]\n bold = workbook.add_format({'bold': 1})\n for col_num in range(len(columns)):\n worksheet.set_column(1, col_num, columns[col_num][1]) # Col width\n worksheet.write(row_num, col_num, columns[col_num][0], bold) # Col content\n\n for obj in queryset:\n if obj.sexo == 0:\n sexo = 'Femenino'\n else:\n sexo ='Masculino'\n\n if obj.tipo == 0:\n tipo ='Pasantia'\n elif obj.tipo == 1:\n tipo = 'Post-Grado'\n elif obj.tipo == 2:\n tipo = 'Fellow'\n elif obj.tipo == 3:\n tipo = 'Visitor'\n\n if obj.fecha_nacimiento == None:\n fecha_nac = \"\"\n else:\n fecha_nac = obj.fecha_nacimiento\n\n if obj.estado_civil == 0:\n estado_civil ='Soltero'\n elif obj.estado_civil == 1:\n estado_civil = 'Casado'\n elif obj.estado_civil == 2:\n estado_civil= 'Divorciado'\n elif obj.estado_civil == 3:\n estado_civil= 'Viudo'\n else:\n estado_civil = \"\"\n\n row_num += 1\n row = [\n tipo,\n obj.area.nombre,\n obj.apellidos,\n obj.nombres,\n obj.didentificacion,\n obj.nacionalidad,\n sexo,\n obj.fecha_inicio,\n obj.fecha_fin,\n fecha_nac,\n estado_civil,\n obj.estado_nacimiento,\n obj.pais_nacimiento\n ]\n for col_num in range(len(row)):\n if (col_num == 7) or (col_num == 8) or (col_num == 9): \n worksheet.write(row_num, col_num, str(row[col_num]))\n else:\n worksheet.write(row_num, col_num, row[col_num])\n\n workbook.close()\n \n output.seek(0)\n\n response = HttpResponse(output.read(), content_type='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=DatosProfesionales.xlsx'\n return response\n\n export_xls.short_description = u\"Descargar informacion formato XLS\"\n\n\n search_fields = ['nombres', 'apellidos', 'didentificacion', 'hospital_procedencia']\n\n actions = [export_csv, export_xls]\n\nadmin.site.register(Persona, PersonaAdmin)","sub_path":"hoimigrate/app_registry/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"27839453","text":"\"\"\"Supporting variables and functions used in stewi.\"\"\"\nimport pandas as pd\nimport requests\nimport json\nimport urllib\nfrom pathlib import Path\n\nfrom stewi.globals import config, log\n\nMODULEPATH = Path(__file__).resolve().parent\nDATA_PATH = MODULEPATH / 'data'\nOUTPUT_PATH = MODULEPATH / 'output'\n\nSRSconfig = config(config_path=MODULEPATH)['databases']['SRS']\nbase = SRSconfig['url']\n\n# Certain characters return errors or missing results but if replaces\n# with '_' this work per advice from Tim Bazel (CGI Federal) on 6/27/2018\nsrs_replace_group = ['%2B', '/', '.']\n\ninventory_to_SRSlist_acronymns = SRSconfig['inventory_lists']\n\n\n# Return json object with SRS result\ndef get_SRSInfo_for_substance_name(name):\n name_for_query = urllib.parse.quote(name)\n nameprefix = 'substance/name/'\n nameprefixexcludeSynonyms = '?excludeSynonyms=True'\n for i in srs_replace_group:\n name_for_query = name_for_query.replace(i, '_')\n url = base + nameprefix + name_for_query + nameprefixexcludeSynonyms\n flow_info = query_SRS_for_flow(url)\n return flow_info\n\n\ndef get_SRSInfo_for_program_list(inventory):\n # See all lists\n # https://cdxnodengn.epa.gov/cdx-srs-rest/reference/substance_lists\n # Base URL for queries\n srs_flow_df = pd.DataFrame()\n for listname in inventory_to_SRSlist_acronymns[inventory]:\n log.debug('Getting %s', listname)\n url = f'{base}substances/list_acronym/{urllib.parse.quote(listname)}'\n flow_info = query_SRS_for_program_list(url, inventory)\n if len(flow_info) == 0:\n log.info(f'No flows found for {listname}')\n srs_flow_df = pd.concat([srs_flow_df, flow_info])\n srs_flow_df = srs_flow_df.drop_duplicates()\n if(inventory == 'TRI'):\n srs_flow_df['PGM_ID'] = srs_flow_df['PGM_ID'].apply(\n lambda x: str(x).lstrip('0'))\n srs_flow_df = srs_flow_df.sort_values(by='PGM_ID')\n return srs_flow_df\n\n\ndef query_SRS_for_program_list(url, inventory):\n field_dict = {\n 'currentCasNumber': 'SRS_CAS',\n 'subsKey': 'SRS_ID',\n 'synonyms': 'synonyms'\n }\n try:\n df = (pd.read_json(requests.get(url).text)\n .filter(field_dict.keys())\n .rename(columns=field_dict)\n )\n except:\n return \"Error:404\"\n\n df['PGM_ID'] = df['synonyms'].apply(lambda x:\n list(pd.DataFrame(x).synonymName.unique())\n )\n\n df = (df\n .drop(columns='synonyms')\n .explode('PGM_ID'))\n return df\n\n\ndef query_SRS_for_flow(url, for_single_flow=False):\n try:\n chemicallistresponse = requests.get(url)\n chemicallistjson = json.loads(chemicallistresponse.text)\n except:\n return \"Error:404\"\n if len(chemicallistjson) == 0:\n return \"Error: No SRS info found\"\n else:\n flow_info = process_single_SRS_json_response(chemicallistjson)\n return flow_info\n\n\n# Processes json response, returns a dataframe with key and CAS\ndef process_single_SRS_json_response(srs_json_response):\n chemical_srs_info = pd.DataFrame(columns=[\"SRS_ID\", \"SRS_CAS\"])\n chemical_srs_info.loc[0, \"SRS_ID\"] = srs_json_response[0]['subsKey']\n chemical_srs_info.loc[0, \"SRS_CAS\"] = srs_json_response[0]['currentCasNumber']\n return chemical_srs_info\n\n\ndef add_manual_matches(df_matches, include_proxies=True):\n manual_matches = pd.read_csv(DATA_PATH.joinpath('chemicalmatches_manual.csv'),\n header=0,\n dtype={'FlowID': 'str', 'SRS_ID': 'str'})\n if not include_proxies:\n manual_matches = manual_matches[manual_matches['Proxy_Used'] == 0]\n manual_matches = manual_matches.drop(columns=['Proxy_Used', 'Proxy_Name',\n 'FlowName'])\n manual_matches = manual_matches.rename(columns={'SRS_ID': 'SRS_ID_Manual'})\n df_matches = pd.merge(df_matches, manual_matches,\n on=['FlowID', 'Source'], how='left')\n # Set null SRS_IDs to those manually found. Replaces null with null if not\n df_matches.loc[df_matches['SRS_ID'].isnull(), 'SRS_ID'] = df_matches['SRS_ID_Manual']\n df_matches = df_matches.drop(columns=['SRS_ID_Manual'])\n return df_matches\n\n\ndef read_cm_file(file='match'):\n if file == 'match':\n name = 'ChemicalsByInventorywithSRS_IDS_forStEWI.csv'\n elif file == 'missing':\n name = 'flows_missing_SRS_ID.csv'\n df = pd.read_csv(OUTPUT_PATH.joinpath(name),\n dtype={\"SRS_ID\": \"str\"})\n return df\n","sub_path":"chemicalmatcher/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"134227243","text":"\"\"\"Tests related to extracting footprints\"\"\"\n\nimport json\nimport os\nimport unittest\n\nimport numpy as np\nfrom pyproj import Proj\nimport rasterio\n\nfrom rf.uploads.landsat8.io import get_tempdir\nfrom rf.uploads.landsat8.footprint import (\n create_tif_mask,\n transform_polygon_coordinates,\n extract_polygon\n)\n\n\nclass Landsat8FootprintTestCase(unittest.TestCase):\n \"\"\"Test footprint extraction\"\"\"\n\n def setUp(self):\n cwd = os.path.abspath(os.path.dirname(__file__))\n self.landsat8_tif = os.path.join(cwd, 'data', 'landsat8-clipped.tif')\n self.mask_tif = os.path.join(cwd, 'data', 'test_mask.TIF')\n self.good_json = os.path.join(cwd, 'data', 'mask.json')\n\n def test_create_tif_mask(self):\n \"\"\"Test that creating a tif mask works properly\"\"\"\n with get_tempdir() as temp_dir:\n new_mask_tif = create_tif_mask(temp_dir, self.landsat8_tif)\n files = os.listdir(temp_dir)\n self.assertEqual(len(files), 1, 'Should have created a mask tif')\n \n with rasterio.open(new_mask_tif) as src:\n band = src.read(1)\n self.assertEqual(band.size, 260832,\n 'Size of band is {} instead of {}'.format(band.size, 260832))\n non_zero_pixels = np.sum(band)\n self.assertEqual(\n non_zero_pixels, 117687,\n 'Number of pixels is {} should be {}'.format(non_zero_pixels, 117687)\n )\n\n def test_polygon_transform(self):\n \"\"\"Test that reprojecting a polygon works properly\"\"\"\n test_feature = {\"type\": \"Polygon\", \"coordinates\": [\n [[45, 47.754097979680026],\n [45, 52.908902047770276],\n [55.54687499999999, 52.908902047770276],\n [55.54687499999999, 47.754097979680026],\n [45, 47.754097979680026]]\n ]}\n src_crs = Proj(init='epsg:4326')\n target_crs = Proj(init='epsg:3857')\n transformed_feature = transform_polygon_coordinates(test_feature, src_crs, target_crs)\n transformed_coordinates = [[(5009377.085697311, 6066042.564711587),\n (5009377.085697311, 6966165.0097978255),\n (6183449.840157617, 6966165.0097978255),\n (6183449.840157617, 6066042.564711587),\n (5009377.085697311, 6066042.564711587)]]\n self.assertEqual(transformed_feature['coordinates'], transformed_coordinates,\n 'Coordinates did not match after transformation')\n\n def test_extract_polygon(self):\n \"\"\"Test that extracting a polygon works correctly\"\"\"\n feature = extract_polygon(self.mask_tif)\n num_features = len(feature['features'])\n\n coords = feature['features'][0]['geometry']['coordinates'][0]\n num_coords = len(coords)\n \n with open(self.good_json, 'rb') as fh:\n good_json = json.loads(fh.read())\n self.assertEqual(num_features, 1,\n 'Should have only extracted one feature, got {}'.format(num_features))\n \n good_json_coords = good_json['features'][0]['geometry']['coordinates'][0]\n self.assertEqual(\n good_json_coords[0], list(coords[0]), 'Coordinates did not match (produced {}, should be {}'.format(\n coords[0], good_json_coords[0]\n )\n )\n\n num_good_coords = len(good_json_coords) \n self.assertEqual(num_good_coords, num_coords, 'Number of coordinates did not match')","sub_path":"app-tasks/rf/tests/uploads/landsat8/test_footprint.py","file_name":"test_footprint.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"579154546","text":"#!/usr/bin/python\n\nimport matplotlib.pyplot as plt\nfrom prep_terrain_data import makeTerrainData\nfrom class_vis import prettyPicture\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.metrics import accuracy_score\n\nfeatures_train, labels_train, features_test, labels_test = makeTerrainData()\n\n\n### the training data (features_train, labels_train) have both \"fast\" and \"slow\"\n### points mixed together--separate them so we can give them different colors\n### in the scatterplot and identify them visually\ngrade_fast = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==0]\nbumpy_fast = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==0]\ngrade_slow = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==1]\nbumpy_slow = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==1]\n\n\n#### initial visualization\nplt.xlim(0.0, 1.0)\nplt.ylim(0.0, 1.0)\nplt.scatter(bumpy_fast, grade_fast, color = \"b\", label=\"fast\")\nplt.scatter(grade_slow, bumpy_slow, color = \"r\", label=\"slow\")\nplt.legend()\nplt.xlabel(\"bumpiness\")\nplt.ylabel(\"grade\")\nplt.show()\n################################################################################\n# We try adaboost with a simple manual implementation of 'grid search' (we haven't\n# seen this technique in the course yet, so that's why we make it this way)\nnum_estimators = [20, 25, 30, 35, 40]\nlearning_rates = [0.3, 0.4, 0.5, 0.6, 0.7]\n\nbest_accuracy = 0\nbest_num_estimators = None\nbest_learning_rate = None\n\nfor n_estimator in num_estimators:\n for learning_rate in learning_rates:\n print(f'Training using {n_estimator} estimators and learning rate of {learning_rate:.2f}')\n clf = AdaBoostClassifier(n_estimators=n_estimator, learning_rate=learning_rate)\n clf.fit(features_train, labels_train)\n preds = clf.predict(features_test)\n accuracy = accuracy_score(labels_test, preds)\n print(f\"Accuracy: {accuracy:.3f}\\n\")\n\n if accuracy > best_accuracy:\n best_accuracy = accuracy\n best_num_estimators = n_estimator\n best_learning_rate = learning_rate\n\nprint(f'Best model accuracy: {best_accuracy}')\nprint(f'Best parameters: n_estimators={best_num_estimators}, learning_rate={best_learning_rate}.')\n\n\n\n\n\n\n\n\ntry:\n prettyPicture(clf, features_test, labels_test)\nexcept NameError:\n pass\n","sub_path":"choose_your_own/your_algorithm.py","file_name":"your_algorithm.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"213457337","text":"from tkinter import *\nimport sqlite3\n\n\nclass Registro: \n\n db_name = 'BaseDatos.db' \n\n def Inicio(self):\n\n ventanaRegistro = Tk()\n # Tamaño de la ventana\n ox, oy = ventanaRegistro.winfo_screenwidth()/5, ventanaRegistro.winfo_screenheight()/5\n ventanaRegistro.geometry(\"=700x400+%d+%d\" % (ox--90, oy--50))\n ventanaRegistro.title(\"Nuevo empleado\")\n ventanaRegistro.resizable(False, False)\n ventanaRegistro.configure(background = \"#83D6A8\" )\n\n #Encabezado\n encabezado = Label(ventanaRegistro, text = \"Registro de nuevo empleado\" ) \n encabezado.config(\n fg = \"black\",\n bg = \"#83D6A8\",\n font = (\"Arial\", 18),\n padx = 10,\n pady = 10\n )\n encabezado.place(x=175, y=0)\n\n #Nombre \n self.texto1= Label(ventanaRegistro, text = \"Nombre:\")\n self.texto1.config(\n bg = \"#83D6A8\",\n font = \"Arial 10 bold\"\n )\n self.texto1.place(x=50, y=75)\n self.nombreIn = Entry(ventanaRegistro)\n self.nombreIn.place(x=200, y=75)\n\n\n #Apellido\n self.texto2= Label(ventanaRegistro, text = \"Apellido:\")\n self.texto2.config(\n bg = \"#83D6A8\",\n font = \"Arial 10 bold\"\n )\n self.texto2.place(x=50, y=125)\n\n self.apellidoIn = Entry(ventanaRegistro)\n self.apellidoIn.place(x=200, y=125)\n\n #Documento\n self.texto3 = Label(ventanaRegistro, text = \"Documento:\")\n self.texto3.config(\n bg = \"#83D6A8\",\n font = \"Arial 10 bold\"\n )\n self.texto3.place(x=50, y=175)\n self.documentoIn = Entry(ventanaRegistro)\n self.documentoIn.place(x=200,y=175)\n\n #Teléfono\n self.texto4 = Label(ventanaRegistro, text= \"Telefono\")\n self.texto4.config(\n bg = \"#83D6A8\",\n font = \"Arial 10 bold\"\n )\n self.texto4.place(x= 375, y=75)\n self.telefonoIn = Entry(ventanaRegistro)\n self.telefonoIn.place(x=500, y= 75)\n\n #Dirección\n self.texto5 = Label(ventanaRegistro, text = \"Dirección:\")\n self.texto5.config(\n bg = \"#83D6A8\",\n font = \"Arial 10 bold\"\n )\n self.texto5.place(x=375, y=125)\n self.direccionIn = Entry(ventanaRegistro)\n self.direccionIn.place(x=500, y=125)\n\n #E-mail\n self.texto6 = Label(ventanaRegistro, text = \"E-mail:\")\n self.texto6.config(\n bg = \"#83D6A8\",\n font = \"Arial 10 bold\"\n )\n self.texto6.place(x=375, y=175)\n self.correoIn = Entry(ventanaRegistro)\n self.correoIn.place(x=500, y=175)\n\n\n\n #Boton ingresar\n\n botonRegistrar = Button(ventanaRegistro, text = \"Registrar empleado\")\n botonRegistrar.config(\n font = \"Arial 10 bold\",\n bg= \"darkgray\",\n relief = \"solid\",\n padx = 70,\n pady= 3,\n command = self.llenar_tabla\n )\n botonRegistrar.place(x=225, y=300)\n\n #Boton regresar\n botonVolver = Button(ventanaRegistro, text = \"Volver\")\n botonVolver.config(\n font = \"Arial 10 bold\",\n bg= \"darkgray\",\n relief = \"solid\",\n padx = 112,\n pady= 3,\n command = ventanaRegistro.destroy \n )\n botonVolver.place(x=225, y=350)\n ventanaRegistro.mainloop()\n \n def validarCampos(self):\n if (len(self.nombreIn.get()) != 0 and len(self.apellidoIn.get()) != 0 and len(self.documentoIn.get()) != 0 and len(self.telefonoIn.get()) != 0 and len(self.direccionIn.get()) != 0):\n return TRUE\n else:\n return FALSE\n \n def ejecutar(self, consulta, parametros = ()):\n with sqlite3.connect(self.db_name) as conn:\n cursor = conn.cursor() \n resultado = cursor.execute(consulta, parametros)\n conn.commit()\n return resultado\n raise Exception('Error')\n \n def llenar_tabla(self):\n if self.validarCampos() == TRUE:\n consulta = 'INSERT INTO Personal VALUES(NULL, ?, ?, ?, ?, ?, ?)'\n parametros = (self.nombreIn.get(), self.apellidoIn.get(), self.documentoIn.get(), self.telefonoIn.get(), self.correoIn.get(), self.direccionIn.get())\n self.nombreIn.delete(0,END)\n self.apellidoIn.delete(0,END)\n self.documentoIn.delete(0,END)\n self.telefonoIn.delete(0,END)\n self.direccionIn.delete(0,END)\n self.correoIn.delete(0,END)\n\n self.ejecutar(consulta, parametros)\n ","sub_path":"Registro_empleados.py","file_name":"Registro_empleados.py","file_ext":"py","file_size_in_byte":4681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"284440398","text":"import sys\nimport json\nimport re\n\n\ndef main():\n afinnfile = open(sys.argv[1])\n\n scores = {} # initialize an empty dictionary\n for line in afinnfile:\n term, score = line.split(\"\\t\") # The file is tab-delimited. \"\\t\" means \"tab character\"\n scores[term] = int(score) # Convert the score to an integer.\n\n tweet_file = open(sys.argv[2])\n for line in tweet_file:\n tweet = json.loads(line)\n if \"text\" in tweet:\n formatted_text = re.split(r\"[\\s\\.,\\?\\:]+\", tweet[\"text\"])\n sentiment = 0\n\n for word in formatted_text:\n if word in scores:\n sentiment = sentiment + scores[word]\n\n for word in formatted_text:\n if word not in scores:\n print(word + \" \" + str(sentiment))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"week1/term_sentiment.py","file_name":"term_sentiment.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"621761508","text":"\nimport os\nfrom setuptools import setup, find_packages\nimport sys\n\nfile_setup = os.path.abspath(os.path.dirname(__file__))\nimport codecs\n\nrequires = ['Django>=2.0,<2.1', 'djangorestframework>=3.7,<3.8', 'python-magic>=0.4,<0.5']\n\nsetup(\n name='django-rest-datastore',\n version='0.1',\n author='Makina Corpus',\n author_email='terralego-pypi@makina-corpus.com',\n url='https://github.com/makinacorpus/django-rest-datastore',\n download_url=\"http://pypi.python.org/pypi/django-datastore/\",\n description=\"\",\n long_description=codecs.open(\n os.path.join(\n file_setup, 'README.rst'), 'r', 'utf-8').read() + '\\n\\n' +\n codecs.open(\n os.path.join(file_setup, 'CHANGES'),\n 'r', 'utf-8').read(),\n license='LPGL, see LICENSE file.',\n install_requires=requires,\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n classifiers=['Topic :: Utilities',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Intended Audience :: Developers',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7'],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"117509402","text":"from bbb.models.genus import Genus\nfrom bbb.models.species import Species\nfrom bbb.models.flora import Flora\nfrom .test_db_fixtures import one_plant\n\ndef test_empty_record():\n f = Flora()\n assert \"Plant:\" in f.__repr__()\n\ndef test_add_plant():\n g1 = Genus(name='Greenus')\n s1 = Species(name='plantus')\n p1 = Flora(genus=g1,species=s1)\n g1.plants.append(p1)\n assert p1.genus.name == 'Greenus'\n assert p1.species.name == 'plantus'\n assert len(g1.plants) == 1\n\ndef test_description():\n p1 = Flora(desc='SCF')\n assert p1.desc == 'SCF'\n\ndef test_germination_code():\n p1 = Flora(germination_code='wet')\n assert p1.germination_code == 'wet'\n\ndef test_plant_fixture(one_plant):\n assert 'Greenus' in one_plant.genus.name\n assert 'plantus' in one_plant.species.name\n assert 'Greenus plantus' in one_plant.name","sub_path":"tests/models/test_flora.py","file_name":"test_flora.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"176251291","text":"'''\nFoldering support using :mod:`memex_dossier.store` and :mod:`dossier.label`\n=====================================================================\n\n.. This software is released under an MIT/X11 open source license.\n Copyright 2012-2015 Diffeo, Inc.\n\n.. autoclass:: Folders\n\nN.B. This is deprecated and should not be used.\n'''\nfrom __future__ import absolute_import, division, print_function\n\nfrom collections import defaultdict\nfrom itertools import groupby, imap\nimport logging\nimport urllib\n\nfrom memex_dossier.fc import FeatureCollection\nfrom dossier.label import CorefValue, Label\n\nlogger = logging.getLogger(__name__)\n\n\nclass Folders(object):\n '''Provides basic foldering support by using labels.\n\n :class:`Folders` implements a simple abstraction for\n storing folders in a :class:`memex_dossier.fc.Store` and a\n :class:`dossier.label.LabelStore`. A fixed hierarchy of three\n levels is supported: folders contain subfolders and subfolders\n contain items.\n\n Folders and subfolders each have an identifier and its name is\n derived from that identifier. The identifier scheme is similar to\n what MediaWiki uses. If `The_Id` is the identifier, then `The Id`\n is the name (and vice versa). Note that the ASCII space character\n (``0x20``) and the ASCII slash character (``0x2F``) are not allowed\n in folder identifiers.\n\n Folders may be empty. Subfolders *cannot* be empty.\n\n Items in a subfolder are pairs of `(content_id, subtopic_id)`.\n The precise form of `content_id` and `subtopic_id` is not\n specified (it is application specific).\n\n Folders cannot be deleted or modified.\n\n .. automethod:: id_to_name\n .. automethod:: name_to_id\n .. automethod:: __init__\n .. automethod:: add_folder\n .. automethod:: add_item\n .. automethod:: folders\n .. automethod:: subfolders\n .. automethod:: items\n .. automethod:: parent_subfolders\n '''\n DEFAULT_ANNOTATOR_ID = 'unknown'\n\n @staticmethod\n def id_to_name(ident):\n 'Converts a folder id to a folder name.'\n if ident is None:\n return ident\n else:\n return ident.replace('_', ' ')\n\n @staticmethod\n def name_to_id(name):\n 'Converts a folder name to a folder id.'\n if name is None:\n return name\n else:\n return name.replace(' ', '_')\n\n def __init__(self, store, label_store, prefix=''):\n '''Create a new :class:`Folders` instance.\n\n :param store: An FC store\n :type store: :class:`memex_dossier.store.Store`\n :param label_store: A label store\n :type label_store: :class:`dossier.label.LabelStore`\n :param prefix: A folder id prefix\n :type prefix: unicode\n :rtype: :class:`Folders`\n '''\n self.store = store\n self.label_store = label_store\n self.prefix = prefix.encode('utf-8')\n\n def folders(self, ann_id=None):\n '''Yields an unordered generator for all available folders.\n\n By default (with ``ann_id=None``), folders are shown for all\n anonymous users. Optionally, ``ann_id`` can be set to a username,\n which restricts the list to only folders owned by that user.\n\n :param str ann_id: Username\n :rtype: generator of folder_id\n '''\n ann_id = self._annotator(ann_id)\n if len(self.prefix) > 0:\n prefix = '|'.join([urllib.quote(self.prefix, safe='~'),\n 'topic', ann_id, ''])\n else:\n prefix = '|'.join(['topic', ann_id, ''])\n logger.info('Scanning for folders with prefix %r', prefix)\n return imap(lambda id: self.unwrap_folder_content_id(id)['folder_id'],\n self.store.scan_prefix_ids(prefix))\n\n def subfolders(self, folder_id, ann_id=None):\n '''Yields an unodered generator of subfolders in a folder.\n\n By default (with ``ann_id=None``), subfolders are shown for all\n anonymous users. Optionally, ``ann_id`` can be set to a username,\n which restricts the list to only subfolders owned by that user.\n\n :param str folder_id: Folder id\n :param str ann_id: Username\n :rtype: generator of subfolder_id\n '''\n self.assert_valid_folder_id(folder_id)\n ann_id = self._annotator(ann_id)\n folder_cid = self.wrap_folder_content_id(ann_id, folder_id)\n if self.store.get(folder_cid) is None:\n raise KeyError(folder_id)\n all_labels = self.label_store.directly_connected(folder_cid)\n return nub(la.subtopic_for(folder_cid) for la in all_labels)\n\n def parent_subfolders(self, ident, ann_id=None):\n '''An unordered generator of parent subfolders for ``ident``.\n\n ``ident`` can either be a ``content_id`` or a tuple of\n ``(content_id, subtopic_id)``.\n\n Parent subfolders are limited to the annotator id given.\n\n :param ident: identifier\n :type ident: ``str`` or ``(str, str)``\n :param str ann_id: Username\n :rtype: generator of ``(folder_id, subfolder_id)``\n '''\n ann_id = self._annotator(ann_id)\n cid, _ = normalize_ident(ident)\n for lab in self.label_store.directly_connected(ident):\n folder_cid = lab.other(cid)\n subfolder_sid = lab.subtopic_for(folder_cid)\n if not folder_cid.startswith('topic|'):\n continue\n folder = self.unwrap_folder_content_id(folder_cid)\n subfolder = self.unwrap_subfolder_subtopic_id(subfolder_sid)\n if folder['annotator_id'] != ann_id:\n continue\n yield (folder['folder_id'], subfolder)\n\n def items(self, folder_id, subfolder_id, ann_id=None):\n '''Yields an unodered generator of items in a subfolder.\n\n The generator yields items, which are represented by a tuple\n of ``content_id`` and ``subtopic_id``. The format of these\n identifiers is unspecified.\n\n By default (with ``ann_id=None``), subfolders are shown for all\n anonymous users. Optionally, ``ann_id`` can be set to a username,\n which restricts the list to only subfolders owned by that user.\n\n :param str folder_id: Folder id\n :param str subfolder_id: Subfolder id\n :param str ann_id: Username\n :rtype: generator of ``(content_id, subtopic_id)``\n '''\n self.assert_valid_folder_id(folder_id)\n self.assert_valid_folder_id(subfolder_id)\n ann_id = self._annotator(ann_id)\n folder_cid = self.wrap_folder_content_id(ann_id, folder_id)\n subfolder_sid = self.wrap_subfolder_subtopic_id(subfolder_id)\n ident = (folder_cid, subfolder_sid)\n\n if self.store.get(folder_cid) is None:\n raise KeyError(folder_id)\n for lab in self.label_store.directly_connected(ident):\n cid = lab.other(folder_cid)\n subid = lab.subtopic_for(cid)\n yield (cid, subid)\n\n def grouped_items(self, folder_id, subfolder_id, ann_id=None):\n '''Returns a dictionary from content ids to subtopic ids.\n\n Namely, the mapping is ``content_id |--> list of subtopic id``.\n\n By default (with ``ann_id=None``), subfolders are shown for all\n anonymous users. Optionally, ``ann_id`` can be set to a username,\n which restricts the list to only subfolders owned by that user.\n\n :param str folder_id: Folder id\n :param str subfolder_id: Subfolder id\n :param str ann_id: Username\n :rtype: ``dict`` of ``content_id |--> [subtopic_id]``\n '''\n d = defaultdict(list)\n for cid, subid in self.items(folder_id, subfolder_id, ann_id=ann_id):\n d[cid].append(subid)\n return d\n\n def add_folder(self, folder_id, ann_id=None):\n '''Add a folder.\n\n If ``ann_id`` is set, then the folder is owned by the given user.\n Otherwise, the folder is owned and viewable by all anonymous\n users.\n\n :param str folder_id: Folder id\n :param str ann_id: Username\n '''\n self.assert_valid_folder_id(folder_id)\n ann_id = self._annotator(ann_id)\n cid = self.wrap_folder_content_id(ann_id, folder_id)\n self.store.put([(cid, FeatureCollection())])\n logger.info('Added folder %r with content id %r', folder_id, cid)\n\n def add_item(self, folder_id, subfolder_id, content_id, subtopic_id=None,\n ann_id=None):\n '''Add an item to a subfolder.\n\n The format of ``content_id`` and ``subtopic_id`` is\n unspecified. It is application specific.\n\n If ``ann_id`` is set, then the item is owned by the given user.\n Otherwise, the item is owned and viewable by all anonymous\n users.\n\n :param str folder_id: Folder id\n :param str subfolder_id: Folder id\n :param str content_id: content identifier\n :param str subtopic_id: subtopic identifier\n :param str ann_id: Username\n '''\n self.assert_valid_folder_id(folder_id)\n self.assert_valid_folder_id(subfolder_id)\n ann_id = self._annotator(ann_id)\n folder_cid = self.wrap_folder_content_id(ann_id, folder_id)\n subfolder_sid = self.wrap_subfolder_subtopic_id(subfolder_id)\n\n if self.store.get(folder_cid) is None:\n raise KeyError(folder_id)\n\n lab = Label(folder_cid, content_id,\n ann_id, CorefValue.Positive,\n subtopic_id1=subfolder_sid,\n subtopic_id2=subtopic_id)\n self.label_store.put(lab)\n logger.info('Added subfolder item: %r', lab)\n\n def _annotator(self, ann_id):\n '''Returns the default annotator iff ``ann_id is None``.'''\n return self.DEFAULT_ANNOTATOR_ID if ann_id is None else ann_id\n\n def assert_valid_folder_id(self, ident):\n if ' ' in ident or '/' in ident:\n raise ValueError(\"Folder ids cannot contain spaces \"\n \"or '/' characters.\")\n\n def wrap_folder_content_id(self, annotator_id, fid):\n prefix = urllib.quote(self.prefix, safe='~')\n parts = [prefix] if len(prefix) > 0 else []\n parts.extend([\n 'topic',\n urllib.quote(annotator_id, safe='~'),\n urllib.quote(fid, safe='~'),\n ])\n return '|'.join(parts)\n\n def unwrap_folder_content_id(self, cid):\n parts = cid.split('|')\n if len(parts) == 3:\n _, annotator_id, fid = parts\n else:\n _, _, annotator_id, fid = parts\n return {\n 'annotator_id': urllib.unquote(annotator_id),\n 'folder_id': urllib.unquote(fid),\n }\n\n def wrap_subfolder_subtopic_id(self, sfid):\n return sfid\n\n def unwrap_subfolder_subtopic_id(self, subtopic_id):\n return subtopic_id\n\n\ndef nub(it):\n '''Dedups an iterable in arbitrary order.\n\n Uses memory proportional to the number of unique items in ``it``.\n '''\n seen = set()\n for v in it:\n h = hash(v)\n if h in seen:\n continue\n seen.add(h)\n yield v\n\n\ndef dedup(it):\n '''Dedups a sorted iterable in constant memory.'''\n for _, group in groupby(it):\n for lab in group:\n yield lab\n break\n\n\ndef normalize_ident(ident):\n '''Splits a generic identifier.\n\n If ``ident`` is a tuple, then ``(ident[0], ident[1])`` is returned.\n Otherwise, ``(ident[0], None)`` is returned.\n '''\n if isinstance(ident, tuple) and len(ident) == 2:\n return ident[0], ident[1] # content_id, subtopic_id\n else:\n return ident, None\n","sub_path":"memex_dossier/web/label_folders.py","file_name":"label_folders.py","file_ext":"py","file_size_in_byte":11619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"97119958","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nfrom nornir.core import Nornir\nfrom functions.discovery_protocols.cdp.get_cdp import get_cdp\nfrom functions.discovery_protocols.cdp.cdp_compare import compare_cdp\nfrom functions.global_tools import open_file\nfrom const.constants import (\n NOT_SET,\n LEVEL1,\n TEST_TO_EXECUTE_FILENAME,\n PATH_TO_VERITY_FILES,\n CDP_SRC_FILENAME,\n TEST_TO_EXC_CDP_KEY,\n)\nfrom functions.verbose_mode import verbose_mode\n\n\nERROR_HEADER = \"Error import [cdp_run.py]\"\nHEADER = \"[cdp_run.py]\"\n\n\ndef run_cdp(nr: Nornir, test_to_execute: dict) -> bool:\n exit_value = True\n if TEST_TO_EXC_CDP_KEY in test_to_execute.keys():\n if test_to_execute[TEST_TO_EXC_CDP_KEY] is True:\n get_cdp(nr)\n cdp_data = open_file(\n f\"{PATH_TO_VERITY_FILES}{CDP_SRC_FILENAME}\"\n )\n same = compare_cdp(nr, cdp_data)\n if (\n test_to_execute[TEST_TO_EXC_CDP_KEY] and\n same is False\n ):\n exit_value = False\n print(\n f\"{HEADER} CDP sessions are the same that defined in\"\n f\"{PATH_TO_VERITY_FILES}{CDP_SRC_FILENAME} = {same} !!\"\n )\n else:\n print(f\"{HEADER} CDP sessions tests are not executed !!\")\n else:\n if verbose_mode(\n user_value=os.environ.get(\"NETESTS_VERBOSE\", NOT_SET),\n needed_value=LEVEL1\n ):\n print(\n f\"{HEADER} CDP sessions key is not defined in\"\n f\"{PATH_TO_VERITY_FILES}{TEST_TO_EXECUTE_FILENAME} !!\"\n )\n return exit_value\n","sub_path":"functions/discovery_protocols/cdp/cdp_run.py","file_name":"cdp_run.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"228072340","text":"\nimport os\nimport uuid\nimport io\n\nimport config\nimport pandas as pd\nfrom flask import request\nfrom pathlib import Path\n# from docx2pdf import convert\n\n# from libreoffice import LibreOffice\n\nfrom datetime import datetime\nimport PyPDF2\nimport subprocess\nfrom models.user_files import UserFiles\nfrom PyPDF2 import PdfReader, PdfWriter\n\nfrom anuvaad_auditor.loghandler import log_error\nfrom anuvaad_auditor.loghandler import log_info\nfrom anuvaad_auditor.loghandler import log_exception\nfrom models.response import CustomResponse\nfrom models.status import Status\n\nALLOWED_FILE_TYPES = config.ALLOWED_FILE_TYPES\nALLOWED_FILE_EXTENSIONS = config.ALLOWED_FILE_EXTENSIONS\n\nfrom utilities.s3_utils import S3BucketUtils\nfrom utilities.fetch_content import FetchContent\n# from resources.file_handler import FileUploader\n# from resources.file_handler import FileUploader\n\ndef is_file_empty(file_bfr, file_path):\n file = file_bfr\n file_name = file.filename\n mime_type = file.mimetype\n if mime_type in ['text/csv']:\n csv_file = pd.read_csv(file_path)\n return csv_file.empty\n elif mime_type in ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']:\n xls_file = pd.read_excel(file, engine='openpyxl')\n return xls_file.empty\n else:\n return False\n\n\n\ndef page_restrictions_pdf(filename):\n # file = open(config.download_folder + filename) \n filepath = config.download_folder\n with open(filepath+'/'+filename, 'rb') as pdf_file:\n # Create a PDF reader object\n pdf_reader = PyPDF2.PdfReader(io.BytesIO(pdf_file.read()))\n page_number = len(pdf_reader.pages)\n print(page_number)\n return page_number\n\n# def upload_doc(filename): #, timeout=None\n# filepath = config.download_folder\n# file_Ext = filename.split('.')[1]\n# print(filepath+'/'+filename)\n# # args = ['unoconv','-f', 'pdf', filepath+'/'+filename]\n# # print('args',args)\n# args = [\"libreoffice\", '--headless', '--convert-to', 'pdf', '--outdir', filepath,\n# filepath+'/'+filename]\n# s = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #, timeout=timeout\n# print(\"test5:\",s)\n# print(filename)\n# filename = filename.split('.')[0]\n# filename = filename+'.pdf'\n# print('test7:',filepath+'/'+filename)\n# # if filename in filepath:\n# print('fi-------:', filename)\n# file = open(filepath + '/' + filename, \"rb\")\n# print(file)\n# pdfReader = PyPDF2.PdfFileReader(file)\n# page_number = pdfReader.numPages #len(pdfReader.pages)\n# print(page_number)\n# return page_number\n\n## this function is to reduce the number of pages. currently not in use\ndef reduce_page(filenames,filepath,file_extension):\n # filepath = filepath\n print(f\"check file ={filenames,filepath}\")\n # filename = file_name\n input_pdf = PdfFileReader(filepath)\n i = 1\n page_limit = 20\n j = 0\n\n while (i+20 eval(str(config.MAX_UPLOAD_SIZE)):\n os.remove(filepath)\n res = CustomResponse(Status.ERROR_FILE_SIZE.value, None)\n return res.getresjson(), 400\n # if is_file_empty(f, filepath) or file_size <= 0:\n if file_size <= 0:\n os.remove(filepath)\n res = CustomResponse(Status.FILE_BLANK_ERROR.value, None)\n return res.getresjson(), 400\n\n # userfile = UserFiles(created_by=request.headers.get('x-user-id'),\n # filename=filename, file_real_name=file_real_name + file_extension,\n # created_on=datetime.now())\n # userfile.save()\n\n zip_name =str(job_id)+\".zip\"\n file_names= [src_filename, filename]\n s3_bucket = S3BucketUtils()\n s3_bucket.compress(file_names,zip_name)\n zip_path = os.path.join(config.download_folder, zip_name)\n upload_to_s3 = s3_bucket.upload_file(zip_path,None)\n fc_obj = FetchContent()\n fc_obj.store_reference_link(job_id=job_id, location=upload_to_s3)\n log_info(\"SUCCESS: File Uploaded -- \" + str(f.filename),None)\n os.remove(zip_path)\n res = CustomResponse(Status.SUCCESS.value, str(upload_to_s3))\n return res.getres()\n else:\n log_info(\"ERROR: Unsupported File -- \" + str(f.filename),None)\n res = CustomResponse(Status.ERROR_UNSUPPORTED_FILE.value, None)\n return res.getresjson(), 400\n except Exception as e:\n log_exception(\"Exception while uploading the file: \" ,None, str(e))\n res = CustomResponse(Status.FAILURE.value, None)\n return res.getresjson(), 500\n","sub_path":"anuvaad-etl/anuvaad-extractor/file-uploader/src/services/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":7070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"230975816","text":"# Copyright (C) 2020 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phono3py.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\nimport numpy as np\nfrom phonopy.units import Hbar, EV, THz\nfrom phonopy.phonon.degeneracy import degenerate_sets\nfrom phono3py.phonon3.triplets import get_triplets_integration_weights\nfrom phono3py.phonon.func import bose_einstein\nfrom phono3py.file_IO import (write_gamma_detail_to_hdf5,\n write_imag_self_energy_at_grid_point)\n\n\ndef get_imag_self_energy(interaction,\n grid_points,\n temperatures,\n sigmas=None,\n frequency_points=None,\n frequency_step=None,\n num_frequency_points=None,\n num_points_in_batch=None,\n scattering_event_class=None, # class 1 or 2\n write_gamma_detail=False,\n return_gamma_detail=False,\n output_filename=None,\n log_level=0):\n \"\"\"Imaginary part of self energy at frequency points\n\n Band indices to be calculated at are kept in Interaction instance.\n\n Parameters\n ----------\n interaction : Interaction\n Ph-ph interaction.\n grid_points : array_like\n Grid-point indices where imag-self-energeis are caclculated.\n dtype=int, shape=(grid_points,)\n temperatures : array_like\n Temperatures where imag-self-energies are calculated.\n dtype=float, shape=(temperatures,)\n sigmas : array_like, optional\n A set of sigmas. simgas=[None, ] means to use tetrahedron method,\n otherwise smearing method with real positive value of sigma.\n For example, sigmas=[None, 0.01, 0.03] is possible. Default is None,\n which results in [None, ].\n dtype=float, shape=(sigmas,)\n frequency_points : array_like, optional\n Frequency sampling points. Default is None. In this case,\n num_frequency_points or frequency_step is used to generate uniform\n frequency sampling points.\n dtype=float, shape=(frequency_points,)\n frequency_step : float, optional\n Uniform pitch of frequency sampling points. Default is None. This\n results in using num_frequency_points.\n num_frequency_points: int, optional\n Number of sampling sampling points to be used instead of\n frequency_step. This number includes end points. Default is None,\n which gives 201.\n num_points_in_batch: int, optional\n Number of sampling points in one batch. This is for the frequency\n sampling mode and the sampling points are divided into batches.\n Lager number provides efficient use of multi-cores but more\n memory demanding. Default is None, which give the number of 10.\n scattering_event_class : int, optional\n Specific choice of scattering event class, 1 or 2 that is specified\n 1 or 2, respectively. The result is stored in gammas. Therefore\n usual gammas are not stored in the variable. Default is None, which\n doesn't specify scattering_event_class.\n write_gamma_detail : bool, optional\n Detailed gammas are written into a file in hdf5. Default is False.\n return_gamma_detail : bool, optional\n With True, detailed gammas are returned. Default is False.\n log_level: int\n Log level. Default is 0.\n\n Returns\n -------\n tuple :\n (frequency_points, gammas) are returned. With return_gamma_detail=True,\n (frequency_points, gammas, detailed_gammas) are returned.\n\n \"\"\"\n\n if sigmas is None:\n _sigmas = [None, ]\n else:\n _sigmas = sigmas\n\n if (interaction.get_phonons()[2] == 0).any():\n if log_level:\n print(\"Running harmonic phonon calculations...\")\n interaction.run_phonon_solver()\n\n mesh = interaction.mesh_numbers\n frequencies = interaction.get_phonons()[0]\n max_phonon_freq = np.amax(frequencies)\n\n _frequency_points = get_frequency_points(\n max_phonon_freq=max_phonon_freq,\n sigmas=_sigmas,\n frequency_points=frequency_points,\n frequency_step=frequency_step,\n num_frequency_points=num_frequency_points)\n\n ise = ImagSelfEnergy(\n interaction, with_detail=(write_gamma_detail or return_gamma_detail))\n gamma = np.zeros(\n (len(grid_points), len(_sigmas), len(temperatures),\n len(interaction.band_indices), len(_frequency_points)),\n dtype='double', order='C')\n detailed_gamma = []\n\n for i, gp in enumerate(grid_points):\n ise.set_grid_point(gp)\n if log_level:\n weights = interaction.get_triplets_at_q()[1]\n print(\"------------------- Imaginary part of self energy (%d/%d) \"\n \"-------------------\" % (i + 1, len(grid_points)))\n print(\"Grid point: %d\" % gp)\n print(\"Number of ir-triplets: \"\n \"%d / %d\" % (len(weights), weights.sum()))\n\n ise.run_interaction()\n\n if log_level:\n adrs = interaction.grid_address[gp]\n q = adrs.astype('double') / mesh\n print(\"q-point: %s\" % q)\n print(\"Phonon frequency:\")\n text = \"[ \"\n for bi, freq in enumerate(frequencies[gp]):\n if bi % 6 == 0 and bi != 0:\n text += \"\\n\"\n text += \"%8.4f \" % freq\n text += \"]\"\n print(text)\n sys.stdout.flush()\n\n if write_gamma_detail or return_gamma_detail:\n (triplets, weights,\n map_triplets, _) = interaction.get_triplets_at_q()\n num_band0 = len(interaction.band_indices)\n num_band = frequencies.shape[1]\n detailed_gamma_at_gp = np.zeros(\n (len(_sigmas), len(temperatures), len(_frequency_points),\n len(weights), num_band0, num_band, num_band),\n dtype='double')\n else:\n detailed_gamma_at_gp = None\n\n for j, sigma in enumerate(_sigmas):\n if log_level:\n if sigma:\n print(\"Sigma: %s\" % sigma)\n else:\n print(\"Tetrahedron method is used for BZ integration.\")\n\n ise.set_sigma(sigma)\n\n # Run one by one at frequency points\n if detailed_gamma_at_gp is None:\n detailed_gamma_at_gp_at_j = None\n else:\n detailed_gamma_at_gp_at_j = detailed_gamma_at_gp[j]\n run_ise_at_frequency_points_batch(\n _frequency_points,\n ise,\n temperatures,\n gamma[i, j],\n write_gamma_detail=write_gamma_detail,\n return_gamma_detail=return_gamma_detail,\n detailed_gamma_at_gp=detailed_gamma_at_gp_at_j,\n scattering_event_class=scattering_event_class,\n nelems_in_batch=num_points_in_batch,\n log_level=log_level)\n\n if write_gamma_detail:\n full_filename = write_gamma_detail_to_hdf5(\n temperatures,\n mesh,\n gamma_detail=detailed_gamma_at_gp[j],\n grid_point=gp,\n triplet=triplets,\n weight=weights,\n triplet_map=map_triplets,\n sigma=sigma,\n frequency_points=_frequency_points,\n filename=output_filename)\n\n if log_level:\n print(\"Contribution of each triplet to imaginary part of \"\n \"self energy is written in\\n\\\"%s\\\".\" % full_filename)\n\n if return_gamma_detail:\n detailed_gamma.append(detailed_gamma_at_gp)\n\n if return_gamma_detail:\n return _frequency_points, gamma, detailed_gamma\n else:\n return _frequency_points, gamma\n\n\ndef get_frequency_points(max_phonon_freq=None,\n sigmas=None,\n frequency_points=None,\n frequency_step=None,\n num_frequency_points=None):\n if frequency_points is None:\n if sigmas is not None:\n sigma_vals = [sigma for sigma in sigmas if sigma is not None]\n else:\n sigma_vals = []\n if sigma_vals:\n fmax = max_phonon_freq * 2 + np.max(sigma_vals) * 4\n else:\n fmax = max_phonon_freq * 2\n fmax *= 1.005\n fmin = 0\n _frequency_points = _sample_frequency_points(\n fmin,\n fmax,\n frequency_step=frequency_step,\n num_frequency_points=num_frequency_points)\n else:\n _frequency_points = np.array(frequency_points, dtype='double')\n\n return _frequency_points\n\n\ndef _sample_frequency_points(f_min,\n f_max,\n frequency_step=None,\n num_frequency_points=None):\n if num_frequency_points is None:\n if frequency_step is not None:\n frequency_points = np.arange(\n f_min, f_max, frequency_step, dtype='double')\n else:\n frequency_points = np.array(np.linspace(\n f_min, f_max, 201), dtype='double')\n else:\n frequency_points = np.array(np.linspace(\n f_min, f_max, num_frequency_points), dtype='double')\n\n return frequency_points\n\n\ndef write_imag_self_energy(imag_self_energy,\n mesh,\n grid_points,\n band_indices,\n frequency_points,\n temperatures,\n sigmas,\n scattering_event_class=None,\n output_filename=None,\n is_mesh_symmetry=True,\n log_level=0):\n for gp, ise_sigmas in zip(grid_points, imag_self_energy):\n for sigma, ise_temps in zip(sigmas, ise_sigmas):\n for t, ise in zip(temperatures, ise_temps):\n for i, bi in enumerate(band_indices):\n pos = 0\n for j in range(i):\n pos += len(band_indices[j])\n filename = write_imag_self_energy_at_grid_point(\n gp,\n bi,\n mesh,\n frequency_points,\n ise[pos:(pos + len(bi))].sum(axis=0) / len(bi),\n sigma=sigma,\n temperature=t,\n scattering_event_class=scattering_event_class,\n filename=output_filename,\n is_mesh_symmetry=is_mesh_symmetry)\n if log_level:\n print(\"Imaginary parts of self-energies were \"\n \"written to \\\"%s\\\".\" % filename)\n\n\ndef average_by_degeneracy(imag_self_energy, band_indices, freqs_at_gp):\n deg_sets = degenerate_sets(freqs_at_gp)\n imag_se = np.zeros_like(imag_self_energy)\n for dset in deg_sets:\n bi_set = []\n for i, bi in enumerate(band_indices):\n if bi in dset:\n bi_set.append(i)\n for i in bi_set:\n if imag_self_energy.ndim == 1:\n imag_se[i] = (imag_self_energy[bi_set].sum() /\n len(bi_set))\n else:\n imag_se[:, i] = (\n imag_self_energy[:, bi_set].sum(axis=1) /\n len(bi_set))\n return imag_se\n\n\nclass ImagSelfEnergy(object):\n def __init__(self,\n interaction,\n frequency_points=None,\n temperature=None,\n sigma=None,\n sigma_cutoff=None,\n with_detail=False,\n unit_conversion=None,\n lang='C'):\n self._pp = interaction\n self._sigma = None\n self.set_sigma(sigma, sigma_cutoff=sigma_cutoff)\n self._temperature = None\n self.set_temperature(temperature)\n self._frequency_points = None\n self.set_frequency_points(frequency_points)\n self._grid_point = None\n\n self._lang = lang\n self._imag_self_energy = None\n self._detailed_imag_self_energy = None\n self._pp_strength = None\n self._frequencies = None\n self._triplets_at_q = None\n self._weights_at_q = None\n self._with_detail = with_detail\n self._unit_conversion = None\n self._cutoff_frequency = interaction.cutoff_frequency\n\n self._g = None # integration weights\n self._g_zero = None # Necessary elements of interaction strength\n self._g_zero_frequency_points = None\n self._g_zero_zeros = None # always zeros for frequency sampling mode\n self._mesh = self._pp.mesh_numbers\n self._is_collision_matrix = False\n\n # Unit to THz of Gamma\n if unit_conversion is None:\n self._unit_conversion = (18 * np.pi / (Hbar * EV) ** 2\n / (2 * np.pi * THz) ** 2\n * EV ** 2)\n else:\n self._unit_conversion = unit_conversion\n\n def run(self):\n if self._pp_strength is None:\n self.run_interaction()\n\n num_band0 = self._pp_strength.shape[1]\n if self._frequency_points is None:\n self._imag_self_energy = np.zeros(num_band0, dtype='double')\n if self._with_detail:\n self._detailed_imag_self_energy = np.empty_like(\n self._pp_strength)\n self._detailed_imag_self_energy[:] = 0\n self._ise_N = np.zeros_like(self._imag_self_energy)\n self._ise_U = np.zeros_like(self._imag_self_energy)\n self._run_with_band_indices()\n else:\n self._imag_self_energy = np.zeros(\n (len(self._frequency_points), num_band0),\n order='C', dtype='double')\n if self._with_detail:\n self._detailed_imag_self_energy = np.zeros(\n (len(self._frequency_points),) + self._pp_strength.shape,\n order='C', dtype='double')\n self._ise_N = np.zeros_like(self._imag_self_energy)\n self._ise_U = np.zeros_like(self._imag_self_energy)\n self._run_with_frequency_points()\n\n def run_interaction(self, is_full_pp=True):\n if is_full_pp or self._frequency_points is not None:\n self._pp.run(lang=self._lang)\n else:\n self._pp.run(lang=self._lang, g_zero=self._g_zero)\n self._pp_strength = self._pp.interaction_strength\n\n def set_integration_weights(self, scattering_event_class=None):\n if self._frequency_points is None:\n bi = self._pp.band_indices\n f_points = self._frequencies[self._grid_point][bi]\n else:\n f_points = self._frequency_points\n\n self._g, _g_zero = get_triplets_integration_weights(\n self._pp,\n np.array(f_points, dtype='double'),\n self._sigma,\n self._sigma_cutoff,\n is_collision_matrix=self._is_collision_matrix)\n if self._frequency_points is None:\n self._g_zero = _g_zero\n else:\n # g_zero feature can not be used in frequency sampling mode.\n # zero values of the following array shape is used in C-routine.\n # shape = [num_triplets, num_band0, num_band, num_band]\n shape = list(self._g.shape[1:])\n shape[1] = len(self._pp.band_indices)\n self._g_zero_zeros = np.zeros(shape=shape, dtype='byte', order='C')\n self._g_zero_frequency_points = _g_zero\n\n if scattering_event_class == 1 or scattering_event_class == 2:\n self._g[scattering_event_class - 1] = 0\n\n def get_imag_self_energy(self):\n if self._cutoff_frequency is None:\n return self._imag_self_energy\n else:\n return self._average_by_degeneracy(self._imag_self_energy)\n\n def get_imag_self_energy_N_and_U(self):\n if self._cutoff_frequency is None:\n return self._ise_N, self._ise_U\n else:\n return (self._average_by_degeneracy(self._ise_N),\n self._average_by_degeneracy(self._ise_U))\n\n def get_detailed_imag_self_energy(self):\n return self._detailed_imag_self_energy\n\n def get_integration_weights(self):\n return self._g, self._g_zero\n\n def get_unit_conversion_factor(self):\n return self._unit_conversion\n\n def set_grid_point(self, grid_point=None, stores_triplets_map=False):\n if grid_point is None:\n self._grid_point = None\n else:\n self._pp.set_grid_point(grid_point,\n stores_triplets_map=stores_triplets_map)\n self._pp_strength = None\n (self._triplets_at_q,\n self._weights_at_q) = self._pp.get_triplets_at_q()[:2]\n self._grid_point = grid_point\n self._frequencies, self._eigenvectors, _ = self._pp.get_phonons()\n\n def set_sigma(self, sigma, sigma_cutoff=None):\n if sigma is None:\n self._sigma = None\n else:\n self._sigma = float(sigma)\n\n if sigma_cutoff is None:\n self._sigma_cutoff = None\n else:\n self._sigma_cutoff = float(sigma_cutoff)\n\n self.delete_integration_weights()\n\n def set_frequency_points(self, frequency_points):\n if frequency_points is None:\n self._frequency_points = None\n else:\n self._frequency_points = np.array(frequency_points, dtype='double')\n\n def set_temperature(self, temperature):\n if temperature is None:\n self._temperature = None\n else:\n self._temperature = float(temperature)\n\n def set_averaged_pp_interaction(self, ave_pp):\n num_triplets = len(self._triplets_at_q)\n num_band = self._pp.get_primitive().get_number_of_atoms() * 3\n num_grid = np.prod(self._mesh)\n bi = self._pp.get_band_indices()\n self._pp_strength = np.zeros(\n (num_triplets, len(bi), num_band, num_band), dtype='double')\n\n for i, v_ave in enumerate(ave_pp):\n self._pp_strength[:, i, :, :] = v_ave / num_grid\n\n def set_interaction_strength(self, pp_strength):\n self._pp_strength = pp_strength\n self._pp.set_interaction_strength(pp_strength, g_zero=self._g_zero)\n\n def delete_integration_weights(self):\n self._g = None\n self._g_zero = None\n self._pp_strength = None\n\n def _run_with_band_indices(self):\n if self._g is not None:\n if self._lang == 'C':\n if self._with_detail:\n # self._detailed_imag_self_energy.shape =\n # (num_triplets, num_band0, num_band, num_band)\n # self._imag_self_energy is also set.\n self._run_c_detailed_with_band_indices_with_g()\n else:\n # self._imag_self_energy.shape = (num_band0,)\n self._run_c_with_band_indices_with_g()\n else:\n print(\"Running into _run_py_with_band_indices_with_g()\")\n print(\"This routine is super slow and only for the test.\")\n self._run_py_with_band_indices_with_g()\n else:\n print(\"get_triplets_integration_weights must be executed \"\n \"before calling this method.\")\n import sys\n sys.exit(1)\n\n def _run_with_frequency_points(self):\n if self._g is not None:\n if self._lang == 'C':\n if self._with_detail:\n self._run_c_detailed_with_frequency_points_with_g()\n else:\n self._run_c_with_frequency_points_with_g()\n else:\n print(\"Running into _run_py_with_frequency_points_with_g()\")\n print(\"This routine is super slow and only for the test.\")\n self._run_py_with_frequency_points_with_g()\n else:\n print(\"get_triplets_integration_weights must be executed \"\n \"before calling this method.\")\n import sys\n sys.exit(1)\n\n def _run_c_with_band_indices_with_g(self):\n import phono3py._phono3py as phono3c\n\n if self._g_zero is None:\n _g_zero = np.zeros(self._pp_strength.shape,\n dtype='byte', order='C')\n else:\n _g_zero = self._g_zero\n\n phono3c.imag_self_energy_with_g(self._imag_self_energy,\n self._pp_strength,\n self._triplets_at_q,\n self._weights_at_q,\n self._frequencies,\n self._temperature,\n self._g,\n _g_zero,\n self._cutoff_frequency,\n -1)\n self._imag_self_energy *= self._unit_conversion\n\n def _run_c_detailed_with_band_indices_with_g(self):\n import phono3py._phono3py as phono3c\n\n if self._g_zero is None:\n _g_zero = np.zeros(self._pp_strength.shape,\n dtype='byte', order='C')\n else:\n _g_zero = self._g_zero\n\n phono3c.detailed_imag_self_energy_with_g(\n self._detailed_imag_self_energy,\n self._ise_N, # Normal\n self._ise_U, # Umklapp\n self._pp_strength,\n self._triplets_at_q,\n self._weights_at_q,\n self._pp.get_grid_address(),\n self._frequencies,\n self._temperature,\n self._g,\n _g_zero,\n self._cutoff_frequency)\n\n self._detailed_imag_self_energy *= self._unit_conversion\n self._ise_N *= self._unit_conversion\n self._ise_U *= self._unit_conversion\n self._imag_self_energy = self._ise_N + self._ise_U\n\n def _run_c_with_frequency_points_with_g(self):\n import phono3py._phono3py as phono3c\n num_band0 = self._pp_strength.shape[1]\n ise_at_f = np.zeros(num_band0, dtype='double')\n\n for i in range(len(self._frequency_points)):\n phono3c.imag_self_energy_with_g(ise_at_f,\n self._pp_strength,\n self._triplets_at_q,\n self._weights_at_q,\n self._frequencies,\n self._temperature,\n self._g,\n self._g_zero_frequency_points,\n self._cutoff_frequency,\n i)\n self._imag_self_energy[i] = ise_at_f\n self._imag_self_energy *= self._unit_conversion\n\n def _run_c_detailed_with_frequency_points_with_g(self):\n import phono3py._phono3py as phono3c\n num_band0 = self._pp_strength.shape[1]\n g_shape = list(self._g.shape)\n g_shape[2] = num_band0\n g = np.zeros((2,) + self._pp_strength.shape, order='C', dtype='double')\n detailed_ise_at_f = np.zeros(\n self._detailed_imag_self_energy.shape[1:5],\n order='C', dtype='double')\n ise_at_f_N = np.zeros(num_band0, dtype='double')\n ise_at_f_U = np.zeros(num_band0, dtype='double')\n _g_zero = np.zeros(g_shape, dtype='byte', order='C')\n\n for i in range(len(self._frequency_points)):\n for j in range(g.shape[2]):\n g[:, :, j, :, :] = self._g[:, :, i, :, :]\n phono3c.detailed_imag_self_energy_with_g(\n detailed_ise_at_f,\n ise_at_f_N,\n ise_at_f_U,\n self._pp_strength,\n self._triplets_at_q,\n self._weights_at_q,\n self._pp.grid_address,\n self._frequencies,\n self._temperature,\n g,\n _g_zero,\n self._cutoff_frequency)\n self._detailed_imag_self_energy[i] = (detailed_ise_at_f *\n self._unit_conversion)\n self._ise_N[i] = ise_at_f_N * self._unit_conversion\n self._ise_U[i] = ise_at_f_U * self._unit_conversion\n self._imag_self_energy[i] = self._ise_N[i] + self._ise_U[i]\n\n def _run_py_with_band_indices_with_g(self):\n if self._temperature > 0:\n self._ise_thm_with_band_indices()\n else:\n self._ise_thm_with_band_indices_0K()\n\n def _ise_thm_with_band_indices(self):\n freqs = self._frequencies[self._triplets_at_q[:, [1, 2]]]\n freqs = np.where(freqs > self._cutoff_frequency, freqs, 1)\n n = bose_einstein(freqs, self._temperature)\n for i, (tp, w, interaction) in enumerate(zip(self._triplets_at_q,\n self._weights_at_q,\n self._pp_strength)):\n for j, k in list(np.ndindex(interaction.shape[1:])):\n f1 = self._frequencies[tp[1]][j]\n f2 = self._frequencies[tp[2]][k]\n if (f1 > self._cutoff_frequency and\n f2 > self._cutoff_frequency):\n n2 = n[i, 0, j]\n n3 = n[i, 1, k]\n g1 = self._g[0, i, :, j, k]\n g2_g3 = self._g[1, i, :, j, k] # g2 - g3\n self._imag_self_energy[:] += (\n (n2 + n3 + 1) * g1 +\n (n2 - n3) * (g2_g3)) * interaction[:, j, k] * w\n\n self._imag_self_energy *= self._unit_conversion\n\n def _ise_thm_with_band_indices_0K(self):\n for i, (w, interaction) in enumerate(zip(self._weights_at_q,\n self._pp_strength)):\n for j, k in list(np.ndindex(interaction.shape[1:])):\n g1 = self._g[0, i, :, j, k]\n self._imag_self_energy[:] += g1 * interaction[:, j, k] * w\n\n self._imag_self_energy *= self._unit_conversion\n\n def _run_py_with_frequency_points_with_g(self):\n if self._temperature > 0:\n self._ise_thm_with_frequency_points()\n else:\n self._ise_thm_with_frequency_points_0K()\n\n def _ise_thm_with_frequency_points(self):\n for i, (tp, w, interaction) in enumerate(zip(self._triplets_at_q,\n self._weights_at_q,\n self._pp_strength)):\n for j, k in list(np.ndindex(interaction.shape[1:])):\n f1 = self._frequencies[tp[1]][j]\n f2 = self._frequencies[tp[2]][k]\n if (f1 > self._cutoff_frequency and\n f2 > self._cutoff_frequency):\n n2 = bose_einstein(f1, self._temperature)\n n3 = bose_einstein(f2, self._temperature)\n g1 = self._g[0, i, :, j, k]\n g2_g3 = self._g[1, i, :, j, k] # g2 - g3\n for l in range(len(interaction)):\n self._imag_self_energy[:, l] += (\n (n2 + n3 + 1) * g1 +\n (n2 - n3) * (g2_g3)) * interaction[l, j, k] * w\n\n self._imag_self_energy *= self._unit_conversion\n\n def _ise_thm_with_frequency_points_0K(self):\n for i, (w, interaction) in enumerate(zip(self._weights_at_q,\n self._pp_strength)):\n for j, k in list(np.ndindex(interaction.shape[1:])):\n g1 = self._g[0, i, :, j, k]\n for l in range(len(interaction)):\n self._imag_self_energy[:, l] += g1 * interaction[l, j, k] * w\n\n self._imag_self_energy *= self._unit_conversion\n\n def _average_by_degeneracy(self, imag_self_energy):\n return average_by_degeneracy(imag_self_energy,\n self._pp.band_indices,\n self._frequencies[self._grid_point])\n\n\ndef run_ise_at_frequency_points_batch(\n _frequency_points,\n ise,\n temperatures,\n gamma,\n write_gamma_detail=False,\n return_gamma_detail=False,\n detailed_gamma_at_gp=None,\n scattering_event_class=None,\n nelems_in_batch=50,\n log_level=0):\n if nelems_in_batch is None:\n _nelems_in_batch = 10\n else:\n _nelems_in_batch = nelems_in_batch\n\n batches = _get_batches(len(_frequency_points), _nelems_in_batch)\n\n if log_level:\n print(\"Calculations at %d frequency points are devided into \"\n \"%d batches.\" % (len(_frequency_points), len(batches)))\n\n for bi, fpts_batch in enumerate(batches):\n if log_level:\n print(\"%d/%d: %s\" % (bi + 1, len(batches), fpts_batch + 1))\n sys.stdout.flush()\n\n ise.set_frequency_points(_frequency_points[fpts_batch])\n ise.set_integration_weights(\n scattering_event_class=scattering_event_class)\n for l, t in enumerate(temperatures):\n ise.set_temperature(t)\n ise.run()\n gamma[l, :, fpts_batch] = ise.get_imag_self_energy()\n if write_gamma_detail or return_gamma_detail:\n detailed_gamma_at_gp[l, fpts_batch] = (\n ise.get_detailed_imag_self_energy())\n\n\ndef _get_batches(tot_nelems, nelems=10):\n nbatch = tot_nelems // nelems\n batches = [np.arange(i * nelems, (i + 1) * nelems)\n for i in range(nbatch)]\n if tot_nelems % nelems > 0:\n batches.append(np.arange(nelems * nbatch, tot_nelems))\n return batches\n","sub_path":"phono3py/phonon3/imag_self_energy.py","file_name":"imag_self_energy.py","file_ext":"py","file_size_in_byte":31708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"465156153","text":"import time\nimport datetime\nimport requests\nimport json\n\nfrom collections import OrderedDict\n\nfrom requests.exceptions import ConnectionError\n\nfrom provisioning_config_parser import hosts_for_tag\n\n\ndef dump_results(test_folder, gateload_results, sync_gateway_results):\n with open(\"testsuites/syncgateway/performance/results/{}/gateload_expvars.json\".format(test_folder), \"w\") as f:\n f.write(json.dumps(gateload_results))\n\n with open(\"testsuites/syncgateway/performance/results/{}/sync_gateway_expvars.json\".format(test_folder), \"w\") as f:\n f.write(json.dumps(sync_gateway_results))\n\n\ndef write_expvars(results_obj, endpoint):\n\n resp = requests.get(\"http://{}\".format(endpoint))\n resp.raise_for_status()\n expvars = resp.json()\n\n now = \"{}\".format(datetime.datetime.utcnow())\n results_obj[now] = {\n \"endpoint\": endpoint,\n \"expvars\": expvars\n }\n\n\ndef log_expvars(folder_name):\n usage = \"\"\"\n usage: log_expvars.py\"\n \"\"\"\n\n # Get gateload ips from ansible inventory\n lgs_host_vars = hosts_for_tag(\"load_generators\")\n lgs = [lg[\"ansible_host\"] for lg in lgs_host_vars]\n\n print(\"Monitoring gateloads: {}\".format(lgs))\n lgs_expvar_endpoints = [lg + \":9876/debug/vars\" for lg in lgs]\n\n # Get sync_gateway ips from ansible inventory\n sgs_host_vars = hosts_for_tag(\"sync_gateways\")\n sgs = [sgv[\"ansible_host\"] for sgv in sgs_host_vars]\n\n print(\"Monitoring sync_gateways: {}\".format(sgs))\n sgs_expvar_endpoints = [sg + \":4985/_expvar\" for sg in sgs]\n\n start_time = time.time()\n\n gateload_results = OrderedDict()\n sync_gateway_results = OrderedDict()\n\n gateload_is_running = True\n while gateload_is_running:\n\n # Caputure expvars for gateloads\n for endpoint in lgs_expvar_endpoints:\n try:\n write_expvars(gateload_results, endpoint)\n except ConnectionError as he:\n # connection to gateload expvars has been closed\n print(he)\n print(\"Gateload no longer reachable. Writing expvars ...\")\n dump_results(folder_name, gateload_results, sync_gateway_results)\n gateload_is_running = False\n\n # Capture expvars for sync_gateways\n for endpoint in sgs_expvar_endpoints:\n try:\n write_expvars(sync_gateway_results, endpoint)\n except ConnectionError as he:\n # Should not happen unless sg crashes\n print(he)\n print(\"ERROR: sync_gateway not reachable. Dumping results\")\n dump_results(folder_name, gateload_results, sync_gateway_results)\n\n print(\"Elapsed: {} minutes\".format((time.time() - start_time) / 60.0))\n time.sleep(30)\n","sub_path":"libraries/utilities/log_expvars.py","file_name":"log_expvars.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"362173238","text":"import luigi\nimport os\nimport git\nimport time\n\n\nclass PrintDateTask(luigi.Task):\n path = luigi.Parameter()\n current_date = time.strftime(\"%A, %B %d %Y\")\n\n def run(self):\n with open(self.path, 'w') as out_file:\n out_file.write(self.current_date)\n out_file.close()\n\n def output(self):\n return luigi.LocalTarget(self.path)\n\n def requires(self):\n\n return [\n MakeDirectory(path=os.path.dirname(self.path)),\n ]\n\n\nclass PrintTimeTask(luigi.Task):\n path = luigi.Parameter()\n current_time = time.strftime(\"%I:%M:%S%p %Z\")\n\n def run(self):\n with open(self.path, 'w') as out_file:\n out_file.write(self.current_time)\n out_file.close()\n\n def output(self):\n return luigi.LocalTarget(self.path)\n\n def requires(self):\n\n return [\n MakeDirectory(path=os.path.dirname(self.path)),\n ]\n\n\nclass CreateDateTimeFilesTask(luigi.Task):\n id = luigi.Parameter(default=0)\n\n def run(self):\n with open(self.input()[0].path, 'r') as date_file:\n current_date = date_file.read()\n with open(self.input()[1].path, 'r') as time_file:\n current_time = time_file.read()\n with open(self.output().path, 'w') as output_file:\n content = 'It is now: {} {}'.format(current_date, current_time)\n output_file.write(content)\n output_file.close()\n\n def requires(self):\n return [\n PrintDateTask(\n path='results/{}/date.txt'.format(self.id)\n ),\n PrintTimeTask(\n path='results/{}/time.txt'.format(self.id)\n ),\n ]\n\n def output(self):\n path = 'results/{}/datetime.txt'.format(self.id)\n return luigi.LocalTarget(path)\n\n\nclass DateTimeTask(luigi.Task):\n id = luigi.Parameter(default=0)\n\n def run(self):\n\n # push new date file to git\n self.push_to_git()\n\n date_path = 'results/{}/date.txt'.format(self.id)\n time_path = 'results/{}/time.txt'.format(self.id)\n datetime_path = 'results/{}/datetime.txt'.format(self.id)\n\n # cleanup\n os.remove(date_path)\n os.remove(time_path)\n os.remove(datetime_path)\n\n def requires(self):\n return [\n CreateDateTimeFilesTask(\n id=self.id\n )\n ]\n\n def push_to_git(self):\n\n current_datetime = time.strftime(\"%c\")\n\n repo = git.Repo('.')\n repo.git.add('.')\n repo.git.commit(m='Auto create and commit files {}'.format(current_datetime))\n repo.git.push()\n repo.git.status()\n\n\nclass MakeDirectory(luigi.Task):\n path = luigi.Parameter()\n\n def output(self):\n return luigi.LocalTarget(self.path)\n\n def run(self):\n os.makedirs(self.path)\n\n\nif __name__ == '__main__':\n luigi.run()\n","sub_path":"luigi_git.py","file_name":"luigi_git.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"448440389","text":"from flask import Flask, jsonify, request \r\n\r\napp = Flask(__name__)\r\n\r\ncontacts = [\r\n {\r\n \"ID\" : 1 ,\r\n \"Name\" : \"Steve\" ,\r\n \"Contact\" : \"1259874569\" ,\r\n \"Done\" : False\r\n },\r\n\r\n {\r\n \"ID\" : 2 ,\r\n \"Name\" : \"Alex\" ,\r\n \"Contact\" : \"1259878569\" ,\r\n \"Done\" : False\r\n },\r\n\r\n {\r\n \"ID\" : 3 ,\r\n \"Name\" : \"Herobrine\" ,\r\n \"Contact\" : \"1259074569\" ,\r\n \"Done\" : False\r\n }\r\n\r\n]\r\n\r\n@app.route(\"/\") \r\n\r\ndef hello_world(): \r\n return \"Hello World!\"\r\n\r\n@app.route(\"/add-data\", methods=[\"POST\"]) \r\n\r\ndef add_contact(): \r\n if not request.json: \r\n return jsonify({ \"status\":\"error\", \"message\": \"Please provide the data!\" },400) \r\n\r\n else:\r\n contact = { \r\n 'ID': contacts[-1]['ID'] + 1 , \r\n 'Name': request.json['Name'] , \r\n 'Contact': request.json.get('Contact', \"\") , \r\n 'Done': False \r\n } \r\n\r\n contacts.append(contact) \r\n\r\n return jsonify({ \"status\":\"success\", \"message\": \"Contact registered succesfully!\" })\r\n\r\n@app.route(\"/get-data\") \r\n\r\ndef get_contact(): \r\n return jsonify({ \"data\" : contacts }) \r\n \r\nif (__name__ == \"__main__\"): \r\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"331365120","text":"from flask import Flask, jsonify, request, g\nfrom remoteFoil.airfoil_finder import AirfoilFinder\nimport sys\nfinder = None\napp = Flask(__name__)\nTRUTHIES = ['true', 'yes', 'y', 't', '1', 'on', 'enabled']\n\n\ndef _error(name, caller, reason):\n url = request.url.replace(request.url_root[:-1], '')\n return {'status': 'fail', 'action': caller, 'url': url, 'name': name, 'reason': reason}\n\ndef _success(name, caller):\n url = request.url.replace(request.url_root[:-1], '')\n return {'status': 'success', 'action': caller, 'url': url, 'name': name}\n\n\n@app.route('/')\ndef get_airfoils():\n airfoils = []\n for af in finder.airfoils.values():\n airfoils.append({'name': af.name, 'ip': af.ip})\n return jsonify({'airfoils': airfoils})\n\n@app.before_request\ndef _get_args():\n g.disconnected = False\n g.names = []\n g.ids = []\n g.volume = None\n g.seconds = 3\n g.ticks = 10\n g.action = None\n for k, v in request.args.items():\n newk = k.lower()\n newv = v.lower()\n if newk == 'ids':\n g.ids = [i for i in newv.split(',') if i]\n if newk == 'names':\n g.names = [n for n in newv.split(',') if n]\n if newk in ['disconnected', 'all']:\n g.disconnected = newv in TRUTHIES\n if newk in ['end_volume', 'level', 'volume']:\n g.volume = newv\n if newk == 'seconds':\n g.seconds = newv\n if newk == 'ticks':\n g.ticks = newv\n if newk == 'action':\n g.action = newv\n\n\ndef _parse_speaker_cmd(name, speaker, functions):\n if speaker == 'speakers':\n speakers = [c._asdict() for c in _airfoil_cmd(name, functions['multi'])]\n else:\n speakers = [c._asdict() for c in _airfoil_cmd(name, functions['specific'], speaker=speaker)]\n caller = sys._getframe(1).f_code.co_name\n result = _success(name, caller)\n result['speakers'] = speakers\n return jsonify(result)\n\n\ndef _airfoil_cmd(name, cmd, speaker=None):\n caller = sys._getframe(1).f_code.co_name\n name = name.lower()\n airfoil = finder.airfoils.get(name, None)\n if airfoil:\n if not speaker:\n return cmd(airfoil)\n else:\n match = airfoil.find_speaker(unknown=speaker)\n if match:\n return cmd(airfoil, match)\n else:\n return _error(name, caller, f'No speaker found with name, id, or keywords: \\'{speaker}\\'')\n else:\n return _error(name, caller, f'No remoteFoil instance found with name \\'{name}\\'')\n\n\ndef _media_button(name, cmd):\n caller = sys._getframe(1).f_code.co_name\n cmds = {\n 'play': lambda airfoil: airfoil.play_pause(),\n 'next': lambda airfoil: airfoil.next_track(),\n 'back': lambda airfoil: airfoil.last_track()\n }\n source = _airfoil_cmd(name, lambda airfoil: airfoil.get_current_source())\n if not source.source_controllable:\n response = _error(name, caller, 'current source does not support remote control by Airfoil')\n else:\n result = _airfoil_cmd(name, cmds[cmd])\n if result:\n response = _success(name, caller)\n source = _airfoil_cmd(name, lambda airfoil: airfoil.get_current_source())\n else:\n response = _error(name, caller, 'unknown')\n response['current_source'] = source._asdict()\n return jsonify(response)\n\n\n@app.route('//')\n@app.route('/')\ndef get_airfoil(name):\n return jsonify(_airfoil_cmd(name, lambda airfoil: {'remoteFoil': {'name': airfoil.name, 'ip': airfoil.ip}}))\n\n\n@app.route('//pause/')\n@app.route('//pause')\n@app.route('//play/')\n@app.route('//play')\n@app.route('//play_pause/')\n@app.route('//play_pause')\ndef play_pause(name):\n return _media_button(name, 'play')\n\n\n@app.route('//skip/')\n@app.route('//skip')\n@app.route('//next/')\n@app.route('//next')\n@app.route('//next_track/')\n@app.route('//next_track')\ndef next_track(name):\n return _media_button(name, 'next')\n\n\n@app.route('//prev/')\n@app.route('//prev')\n@app.route('//last/')\n@app.route('//last')\n@app.route('//back/')\n@app.route('//back')\n@app.route('//prev_track/')\n@app.route('//prev_track')\n@app.route('//last_track/')\n@app.route('//last_track')\ndef last_track(name):\n return _media_button(name, 'back')\n\n\n@app.route('//sources/')\n@app.route('//sources')\ndef get_sources(name):\n source_icon = request.args.get('source_icon', '').lower() in TRUTHIES\n sources = _airfoil_cmd(name, lambda airfoil: airfoil.get_sources(source_icon))\n return jsonify([s._asdict() for s in sources])\n\n\n@app.route('//current_source/')\n@app.route('//current_source')\n@app.route('//source/')\n@app.route('//source')\ndef get_current_source(name):\n source_name = request.args.get('name', '')\n source_id = request.args.get('id', '')\n keywords = [kw for kw in request.args.get('keywords', '').split(',') if kw]\n if source_name or source_id or keywords:\n return set_source(source_name=source_name, source_id=source_id, keywords=keywords)\n\n machine_icon = request.args.get('machine_icon', '').lower() == 'true'\n album_art = request.args.get('album_art', '').lower() == 'true'\n source_icon = request.args.get('source_icon', '').lower() == 'true'\n track_meta = request.args.get('track_meta', '').lower() == 'true'\n\n source = _airfoil_cmd(name, lambda airfoil: airfoil.get_current_source(\n machine_icon=machine_icon, album_art=album_art, source_icon=source_icon, track_meta=track_meta))\n return jsonify(source._asdict())\n\n\n@app.route('//source//')\n@app.route('//source/')\ndef set_source(name, source='', source_name='', source_id='', keywords=[]):\n if [bool(source), bool(source_name), bool(source_id), bool(keywords)].count(True) > 1:\n return jsonify(_error(name, 'More than one parameter was specified for set_source'))\n\n airfoil = finder.airfoils.get(name, None)\n match = None\n if airfoil:\n try:\n if source_name or source_id or keywords:\n match = airfoil.find_source(name=source_name, id=source_id, keywords=keywords)\n except ValueError:\n return jsonify(_error(name, 'no source was found with the specified url keyword parameter'))\n if source:\n try:\n match = airfoil.find_source(name=source)\n except ValueError:\n try:\n match = airfoil.find_source(id=source)\n except ValueError:\n keywords = airfoil.get_keywords(source)\n try:\n match = airfoil.find_source(keywords=keywords)\n except ValueError:\n pass\n response = {'action': 'set_source', 'status': 'success', 'current_source': None}\n if match:\n source = airfoil.set_source(id=match.id)._asdict()\n if source['source_name'] != match.name:\n response['status'] = 'fail'\n response['reason'] = 'source was not successfully changed. check Airfoil.'\n else:\n source = airfoil.get_current_source()._asdict()\n response['status'] = 'fail'\n response['reason'] = 'no source was found with the given name.'\n response['current_source'] = source\n return jsonify(response)\n\n\n\n else:\n return _error(name, f'No remoteFoil instance found with name \\'{name}\\'')\n\n\n@app.route('///')\n@app.route('//')\n@app.route('////')\n@app.route('///')\n@app.route('/////')\n@app.route('////')\n@app.route('//////')\n@app.route('/////')\n@app.route('///////')\n@app.route('//////')\ndef speaker_uri(name, speaker, action=None, arg1=None, arg2=None, arg3=None):\n g.action = action = action.lower() if action else g.action\n g.volume = arg1 if arg1 else g.volume\n level_error = f'{g.action} requires an end volume in the following formats: A number between 0 and 1 inclusive ' \\\n f'with up to 8 digits after the decimal point, or a percentage. values greater than 1 or less than ' \\\n f'0 will be constrained to valid values. valid values for volume include 0, 1, 0.75432111, 35%, 100%'\n try: # make sure given volume is a valid value\n if g.volume is not None:\n g.volume = _airfoil_cmd(name, lambda airfoil: airfoil._parse_volume(g.volume))\n except ValueError:\n return jsonify(_error(name, action, level_error))\n\n if not any([action, arg1, arg2, arg3]):\n if speaker == 'speakers': # get list of all speakers /remoteFoil/speakers\n return get_speakers(name)\n else:\n return get_speaker(name, speaker) # get specific speaker info /remoteFoil/my_speaker\n\n if action in ['on', 'yes', 'true', 'connect', 'enable', 'enabled']:\n return connect(name, speaker)\n if action in ['off', 'no', 'false', 'disconnect', 'disable', 'disabled']:\n return disconnect(name, speaker)\n if action in ['toggle', 'reset', 'cycle']:\n return toggle(name, speaker)\n if action in ['mute', 'silence', 'silent', 'quiet']:\n return mute(name, speaker)\n if action == 'unmute':\n return unmute(name, speaker)\n if action in ['volume', 'level']:\n return volume(name, speaker)\n if action in ['source', 'current_source']:\n return get_current_source(name)\n if action in ['play', 'pause', 'play_pause']:\n return play_pause(name)\n if action in ['skip', 'next', 'next_track']:\n return next_track(name)\n if action in ['prev', 'last', 'back', 'prev_track', 'last_track']:\n return last_track(name)\n\n if action in ['fade', 'ramp', 'transition']:\n g.seconds = arg2 if arg2 else g.seconds\n try:\n g.seconds = abs(float(g.seconds))\n except ValueError:\n return jsonify(_error(name, g.action, f'seconds must be a positive numeric value like 5, 3.25, 15.021, not '\n f'\\'{g.seconds}\\''))\n g.ticks = arg3 if arg3 else g.ticks\n try:\n g.ticks = int(g.ticks)\n except ValueError:\n return jsonify(_error(name, g.action, f'ticks must be a positive numeric value like 4 or 20, not '\n f'\\'{g.ticks}\\''))\n return fade(name, speaker)\n\n try:\n g.volume = _airfoil_cmd(name, lambda airfoil: airfoil._parse_volume(action))\n return volume(name, speaker)\n except ValueError:\n pass\n return jsonify(_error(name, action, f'action for speaker is not recognized: \\'{action}\\''))\n\n\ndef get_speakers(name):\n speakers = _airfoil_cmd(name, lambda airfoil: airfoil.get_speakers())\n return jsonify([s._asdict() for s in speakers])\n\n\ndef get_speaker(name, speaker):\n return jsonify(_airfoil_cmd(name, lambda _, match: match._asdict(), speaker=speaker))\n\n\ndef connect(name, speaker):\n functions = {'multi':\n lambda airfoil: airfoil.connect_some(names=g.names, ids=g.ids),\n 'specific':\n lambda airfoil, match: airfoil.disconnect_speaker(id=match.id)\n }\n return _parse_speaker_cmd(name, speaker, functions)\n\n\ndef disconnect(name, speaker):\n functions = {'multi':\n lambda airfoil: airfoil.disconnect_some(names=g.names, ids=g.ids),\n 'specific':\n lambda airfoil, match: airfoil.disconnect_speaker(id=match.id)\n }\n return _parse_speaker_cmd(name, speaker, functions)\n\n\ndef toggle(name, speaker):\n functions = {'multi':\n lambda airfoil: airfoil.toggle_some(names=g.names, ids=g.ids, include_disconnected=g.disconnected),\n 'specific':\n lambda airfoil, match: airfoil.toggle_speaker(id=match.id)\n }\n return _parse_speaker_cmd(name, speaker, functions)\n\n\ndef mute(name, speaker):\n functions = {'multi':\n lambda airfoil: airfoil.mute_some(names=g.names, ids=g.ids, include_disconnected=g.disconnected),\n 'specific':\n lambda airfoil, match: airfoil.mute(id=match.id)\n }\n return _parse_speaker_cmd(name, speaker, functions)\n\n\ndef unmute(name, speaker):\n functions = {'multi':\n lambda airfoil: airfoil.unmute_some(names=g.names, ids=g.ids, default_volume=g.volume,\n include_disconnected=g.disconnected),\n 'specific':\n lambda airfoil, match: airfoil.unmute(id=match.id, default_volume=g.volume)\n }\n return _parse_speaker_cmd(name, speaker, functions)\n\n\ndef fade(name, speaker):\n functions = {'multi':\n lambda airfoil: airfoil.fade_some(names=g.names, ids=g.ids, end_volume=g.volume, seconds=g.seconds,\n ticks=g.ticks, include_disconnected=g.disconnected),\n 'specific':\n lambda airfoil, match: airfoil.fade_volume(id=match.id, end_volume=g.volume, seconds=g.seconds, ticks=g.ticks)}\n return _parse_speaker_cmd(name, speaker, functions)\n\n\ndef volume(name, speaker):\n functions = {'multi':\n lambda airfoil: airfoil.set_volumes(g.volume, names=g.names, ids=g.ids, include_disconnected=g.disconnected),\n 'specific':\n lambda airfoil, match: airfoil.set_volume(g.volume, id=match.id)\n }\n return _parse_speaker_cmd(name, speaker, functions)\n\ndef start():\n cli = sys.modules['flask.cli']\n cli.show_server_banner = lambda *x: None\n finder = AirfoilFinder()\n app.run(host='0.0.0.0', port='80', threaded=True)\n\nif __name__=='__main__':\n start()\n\n\n","sub_path":"airfoil_http.py","file_name":"airfoil_http.py","file_ext":"py","file_size_in_byte":13995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"342833081","text":"import rospy\nfrom sensor_msgs.msg import Image\nfrom std_msgs.msg import String\nfrom cv_bridge import CvBridge,CvBridgeError\n\nclass AvtCamera():\n\n def __init__(self):\n self.trigger = rospy.Publisher('/trigger', String, queue_size=1)\n self.img_sub = rospy.Subscriber('avt_camera_img', Image, self.image_callback)\n self.lastest_img = None\n self.img_received = False \n self.bridge = CvBridge()\n\n def image_callback(self, msg):\n try:\n img = self.bridge.imgmsg_to_cv2(msg, \"bgr8\")\n except CvBridgeError as e:\n print(e)\n self.lastest_img = img.copy()\n self.img_received = True \n\n def trigger_image(self):\n self.img_received = False\n self.trigger.publish(String('Hi!'))\n while(not self.img_received):\n continue\n self.img_received = False","sub_path":"src/include/avt_camera.py","file_name":"avt_camera.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"115375944","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 6 13:31:31 2017\n\n@author: adurand\n\"\"\"\n\n# Distance en voiture Ville à ville des 100 plus grandes villes de france\n# en utilsant API Google\n\n\nimport pandas as pd\nimport googlemaps as gm\n\n# /!\\ INSERT YOUR OWN KEY /!\\\n# =========================== \nmy_key =''\n\n# On utilise comme base un fichier listant les 100 plus grandes villes\nfilename = './ville.csv'\ndf_ville = pd.read_csv(filename, sep=',', index_col=0)\n\n\norigins = [df_ville.iloc[i,0] for i in range(0, 10)]\ndestinations = origins\nprint(origins)\n\n\nclient = gm.Client(key=my_key)\ndistance_matrix = gm.client.distance_matrix(client, origins, destinations,\n mode='driving')\n\ndf = pd.DataFrame(index=origins, columns=origins)\n\n# Here, we print it as a Cartesian product.\nfor isrc, src in enumerate(distance_matrix['origin_addresses']):\n for idst, dst in enumerate(distance_matrix['destination_addresses']):\n if isrc <= idst:\n row = distance_matrix['rows'][isrc]\n cell = row['elements'][idst]\n if cell['status'] == 'OK':\n df.at[origins[isrc], origins[idst]] = int(cell['distance']['value']/1000)\n #print('{} to {}: {}, {}.'.format(src, dst, cell['distance']['text'], cell['duration']['text']))\n else:\n print('{} to {}: status = {}'.format(src, dst, cell['status']))\n\n\ndf.fillna(value='-', inplace=True)\ndf.to_csv('./distance_km_matrix.csv', index=True)\nprint(df)\n\n\n# distance_matrix['rows'][i] ==> information pour la ie origine vers toutes les destinations\n # distance_matrix['rows'][i]['elements'][j] ==> ie origine vers la je destination\n\n#def distance_matrix(client, origins, destinations,\n# mode=None, language=None, avoid=None, units=None,\n# departure_time=None, arrival_time=None, transit_mode=None,\n# transit_routing_preference=None, traffic_model=None)\n","sub_path":"Lesson3/exo_cc_lesson_03.py","file_name":"exo_cc_lesson_03.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"264343232","text":"import numpy as np\nimport cudarray as ca\nfrom ..feedforward.layers import Activation, FullyConnected\nfrom ..feedforward.loss import Loss\nfrom ..base import Model, PickleMixin\nfrom ..input import Input\nfrom ..parameter import Parameter\n\n\nclass Autoencoder(Model, PickleMixin):\n def __init__(self, n_out, weights, bias=0.0, activation='sigmoid',\n loss='bce'):\n self.name = 'autoenc'\n self.n_out = n_out\n self.activation = Activation(activation)\n self.activation_decode = Activation(activation)\n self.loss = Loss.from_any(loss)\n self.W = Parameter.from_any(weights)\n self.b = Parameter.from_any(bias)\n self.b_prime = Parameter.from_any(bias)\n self._initialized = False\n\n def _setup(self, input):\n if self._initialized:\n return\n next_shape = input.x_shape\n n_input = next_shape[1]\n W_shape = (n_input, self.n_out)\n b_shape = self.n_out\n b_prime_shape = n_input\n self.W._setup(W_shape)\n if not self.W.name:\n self.W.name = self.name + '_W'\n self.b._setup(b_shape)\n if not self.b.name:\n self.b.name = self.name + '_b'\n self.b_prime._setup(b_prime_shape)\n if not self.b_prime.name:\n self.b_prime.name = self.name + '_b_prime'\n self.loss._setup((next_shape[0], self.n_out))\n self._initialized = True\n\n @property\n def _params(self):\n return self.W, self.b, self.b_prime\n\n @_params.setter\n def _params(self, params):\n self.W, self.b, self.b_prime = params\n\n def output_shape(self, input_shape):\n return (input_shape[0], self.n_out)\n\n def encode(self, x):\n self._tmp_last_x = x\n y = ca.dot(x, self.W.array) + self.b.array\n return self.activation.fprop(y, '')\n\n def decode(self, y):\n self._tmp_last_y = y\n x = ca.dot(y, self.W.array.T) + self.b_prime.array\n return self.activation_decode.fprop(x, '')\n\n def decode_bprop(self, x_grad):\n x_grad = self.activation_decode.bprop(x_grad)\n ca.dot(x_grad.T, self._tmp_last_y, out=self.W.grad_array)\n ca.sum(x_grad, axis=0, out=self.b_prime.grad_array)\n return ca.dot(x_grad, self.W.array)\n\n def encode_bprop(self, y_grad):\n y_grad = self.activation.bprop(y_grad)\n # Because W's gradient has already been updated by decode_bprop() at\n # this point, we should add its contribution from the encode step.\n W_grad = self.W.grad_array\n W_grad += ca.dot(self._tmp_last_x.T, y_grad)\n ca.sum(y_grad, axis=0, out=self.b.grad_array)\n return ca.dot(y_grad, self.W.array.T)\n\n def _update(self, x):\n y_prime = self.encode(x)\n x_prime = self.decode(y_prime)\n x_prime_grad = self.loss.grad(x, x_prime)\n y_grad = self.decode_bprop(x_prime_grad)\n self.encode_bprop(y_grad)\n return self.loss.loss(x, x_prime)\n\n def _reconstruct_batch(self, x):\n y = self.encode(x)\n return self.decode(y)\n\n def reconstruct(self, input):\n \"\"\" Returns the reconstructed input. \"\"\"\n input = Input.from_any(input)\n x_prime = np.empty(input.x.shape)\n offset = 0\n for x_batch in input.batches('test'):\n x_prime_batch = np.array(self._reconstruct_batch(x_batch))\n batch_size = x_prime_batch.shape[0]\n x_prime[offset:offset+batch_size, ...] = x_prime_batch\n offset += batch_size\n return x_prime\n\n def _embed_batch(self, x):\n return self.encode(x)\n\n def embed(self, input):\n \"\"\" Returns the embedding of the input. \"\"\"\n input = Input.from_any(input)\n y = np.empty(self.output_shape(input.x.shape))\n offset = 0\n for x_batch in input.batches('test'):\n y_batch = np.array(self._embed_batch(x_batch))\n batch_size = y_batch.shape[0]\n y[offset:offset+batch_size, ...] = y_batch\n offset += batch_size\n return y\n\n def feedforward_layers(self):\n return [FullyConnected(self.n_out, self.W.array, self.b.array),\n self.activation]\n\n\nclass DenoisingAutoencoder(Autoencoder):\n def __init__(self, n_out, weights, bias=0.0, activation='sigmoid',\n loss='bce', corruption=0.25):\n super(DenoisingAutoencoder, self).__init__(\n n_out=n_out, weights=weights, bias=bias, activation=activation,\n loss=loss\n )\n self.corruption = corruption\n\n def corrupt(self, x):\n mask = ca.random.uniform(size=x.shape) < (1-self.corruption)\n return x * mask\n\n def _update(self, x):\n x_tilde = self.corrupt(x)\n y_prime = self.encode(x_tilde)\n x_prime = self.decode(y_prime)\n x_prime_grad = self.loss.grad(x, x_prime)\n y_grad = self.decode_bprop(x_prime_grad)\n self.encode_bprop(y_grad)\n return self.loss.loss(x, x_prime)\n","sub_path":"deeppy/autoencoder/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"387183479","text":"# [95] 不同的二叉搜索树 II\n#\n\n'''\n 分治法,递归实现\n'''\n# @lc code=start\n# Definition for a binary tree node.\n\nfrom typing import List\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n List_node = [i for i in range(1,n+1)]\n def Build_BTrees(l_node: List) ->List[TreeNode]:\n res = []\n if len(l_node) == 1:\n return [TreeNode(val=l_node[0])]\n elif len(l_node) == 0:\n return [None]\n for k in range(len(l_node)):\n for left in (Build_BTrees(l_node[:k])):\n for right in (Build_BTrees(l_node[k+1:])):\n node = TreeNode(val = l_node[k], left=left, right= right)\n res.append(node)\n return res\n if n == 0:\n return []\n return Build_BTrees(List_node)\n\n# @lc code=end\n\n'''\nAccepted\n9/9 cases passed (76 ms)\nYour runtime beats 30.01 % of python3 submissions\nYour memory usage beats 12.5 % of python3 submissions (15.7 MB)\n'''","sub_path":"DHY_LeetCode/Tree/0095.py","file_name":"0095.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"131262566","text":"from collections import Iterable\nimport urllib.parse\nimport json\n\nimport requests\nimport redis\n\ntemplate = 'http://{server}/{service}/v1/{profile}/{coords}'\n\nconfig = json.load(open('config.json'))['redis']\nr = redis.Redis(**config)\n\ndef redis_cache(func):\n def inner(*args, **kwargs):\n key = func.__name__ + str(args) + str(kwargs)\n data = r.get(key)\n if data:\n return json.loads(data.decode())\n else:\n result = func(*args, **kwargs)\n data = json.dumps(result)\n r.set(key, data)\n return result\n return inner\n\n\ndef coords_to_string(coords):\n if any(isinstance(el, Iterable) and not isinstance(el, (str, int, float)) for el in coords):\n return ';'.join('{},{}'.format(*coord) for coord in coords)\n else:\n return '{},{}'.format(*coords)\n\n@redis_cache\ndef request(server, profile, service, coords, **kwargs):\n coords = coords_to_string(coords)\n url = template.format(server=server, service=service, profile=profile, coords=coords)\n result = requests.get(url, params=kwargs).json()\n return result","sub_path":"osrm.py","file_name":"osrm.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"33617991","text":"import random\nimport numpy as np\nimport networkx as nx\nimport scipy as sp\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn import metrics\n#import ExpressionData \t\t#ATM this will run the script as is, before doing this one\n\n# http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html # to read matlab file\n# https://networkx.github.io/documentation/latest/reference/classes.graph.html\n# https://networkx.github.io/documentation/latest/reference/generated/networkx.linalg.graphmatrix.adjacency_matrix.html\n# http://pythoncentral.io/how-to-sort-a-list-tuple-or-object-with-sorted-in-python/\n# http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html\n\n# Have code started for parsing and using data from new files\n# need to sort out the reading of the file, and change some\n# parts depending on whether multiple items can be returned or not\n# if it does work then add some comments\n\n#Parsing data from the gene annotation file to extract a list of\n#genes with their GO \ndef readFile():\n\t#Reading and parsing the file\n\tfullGeneDataList = []\n\tgoList = []\n\ttempList = []\n\n\twith open('C:\\ThirdYear\\Dissertation\\Python_Code\\GR_V1.6+\\GSE5496.txt') as infile:\n\t\tnext(infile)\n\t\tfor line in infile:\n\t\t\ttempList = line.split(\"\t\")\t\t\n\t\t\tif ((tempList[6] == \"\") or (tempList[4] == \"\")):\n\t\t\t\tnext(infile)\n\t\t\telse:\n\t\t\t\tfullGeneDataList.append(tempList[0])\n\t\t\t\ttempGoList1 = (tempList[13].split(\"///\"))\n\t\t\t\ttempGoList2 = (tempList[14].split(\"///\"))\n\t\t\t\ttempGoList3 = (tempList[15].split(\"///\"))\n\t\t\t\tgoList = tempGoList1 + tempGoList2 + tempGoList3\n\t\t\t\tfullGeneDataList.append(goList)\n\t\t\t\tfullGeneDataList.append(abs(float(tempList[5])))\n\t\t\t\tfullGeneDataList.append(tempList[6])\n\t\t\t\tgoList = []\n\t\n\t#print (fullGeneDataList)\n\treturn fullGeneDataList\n\ndef makeGraph(fullGeneDataList):\n\tG = nx.Graph()\n\ti = 0\n\twhile (i < len(fullGeneDataList)):\n\t\tG.add_node(fullGeneDataList[i])\t\t# add a node for each gene\n\t\ti = i + 4\n\treturn G\n\t\ndef connectGraph(G, fullGeneDataList):\n\ti = 1\n\tj = 1\n\tk = 1\n\twhile (i < len(fullGeneDataList)):\t\n\t\twhile (j < len(fullGeneDataList)):\n\t\t\tif (i != j):\n\t\t\t\tif(bool(set(fullGeneDataList[i]) & set(fullGeneDataList[j]))):\t\t\t\n\t\t\t\t\tG.add_edge(fullGeneDataList[i-1],fullGeneDataList[j-1])\n\t\t\t\tj = j + 4\n\t\t\tj = j + 4\n\t\ti = i + 4 \t# THE FINAL GENE HAS NO CONNECTIONS, FIX IT\n\t\tk = k + 4 # file dropped size a fair bit.\n\t\tj = k\n\n\tnx.write_graphml(G, \"testGraph.xml\")\n\tA = nx.adjacency_matrix(G) \t# Creates an adjacency matrix of the graph above.\n\t\n\treturn G\n\n# assuming incoming list is in the form of [geneID, go_values, ex_data, geneName].\ndef getMultipleLists(fullGeneDataList):\n\tgeneIDList = []\n\texprDataList = []\n\tnormExprDataList = []\n\tgeneNameList = []\n\tsumOfEx = 0\n\ti = 0\n\tj = 0\n\t\n\twhile (i