\n \"\"\"\n\n def __init__(self):\n pass\n\n def get_news_html_contents(self, news_data, descrip=\"\"):\n \"\"\"\n news_data (dict):\n {\n \"timestamp\": 1553613896.8034308,\n \"news_page_title\": \"iThome\"\n \"news_contents\": {\n \"2a1bf0cedf6d8d855b432d1af5034f17\": {\n \"link\": \"https://www.ithome.com.tw/news/129580\",\n \"image\": \"https://s4.itho.me/sites/default/files/styles/picture...\",\n \"title\": \"MIT用胺基酸序列搭配機器學習預測複雜蛋白質結構\"\n },\n \"deca65bdc81d9292541a47eaa435e9ce\": {\n \"link\": \"https://www.ithome.com.tw/news/129594\",\n \"image\": \"https://s4.itho.me/sites/default/files/styles/p...\",\n \"title\": \"Google加碼投資臺灣,明年啟用臺灣新辦公室,可容納超過4千人\"\n },\n },\n ...\n ...\n ...\n }\n \"\"\"\n news_html = \"\"\n news_html += self._get_news_provider_frame(news_data[\"news_page_title\"])\n\n news_data_cp = copy.deepcopy(news_data)\n all_news = news_data_cp[\"news_contents\"]\n while all_news:\n if (len(all_news) % 2) == 0:\n news1_key = random.choice(list(all_news.keys()))\n news1 = all_news[news1_key]\n news1_tag = self._get_news_tag(news1[\"title\"], descrip, news1[\"link\"])\n news1_img_tag = self._get_image_tag(news1[\"link\"], news1[\"image\"])\n all_news.pop(news1_key)\n\n news2_key = random.choice(list(all_news.keys()))\n news2 = all_news[news2_key]\n news2_tag = self._get_news_tag(news2[\"title\"], descrip, news2[\"link\"])\n news2_img_tag = self._get_image_tag(news2[\"link\"], news2[\"image\"])\n news_frame = self._get_news_row_pair_frame(news1_tag, news1_img_tag, news2_tag, news2_img_tag)\n all_news.pop(news2_key)\n else:\n news1_key = random.choice(list(all_news.keys()))\n news1 = all_news[news1_key]\n news1_tag = self._get_news_tag(news1[\"title\"], \"\", news1[\"link\"])\n news1_img_tag = self._get_image_tag(news1[\"link\"], news1[\"image\"])\n news_frame = self._get_news_row_frame(news1_tag, news1_img_tag)\n all_news.pop(news1_key)\n\n news_html += news_frame\n return news_html\n\n def get_email_html(self, title: str, news_rows: str):\n return self.NEWS_OUTLINE.format(email_title=title, news_rows=news_rows)\n\n def _get_news_provider_frame(self, news_provider: str):\n return self.NEWS_PROVIDER_FRAME.format(provider=news_provider)\n\n def _get_news_tag(self, descrip: str, title: str, link: str):\n return self.NEWS_TAG.format(news_title=title, news_descrip=descrip, news_link=link)\n\n def _get_image_tag(self, news: str, img: str):\n return self.IMG_TAG.format(news_link=news, img_link=img)\n\n def _get_news_row_pair_frame(self, link1: str, img1: str, link2: str, img2: str):\n return self.NEWS_ROW_DATA_PAIR.format(\n left_img_tag=img1, right_img_tag=img2, left_news_data=link1, right_news_data=link2)\n\n def _get_news_row_frame(self, link1: str, img1: str):\n return self.NEWS_ROW_DATA_ODD.format(left_img_tag=img1, left_news_data=link1)\n","sub_path":"technews/mail_helper.py","file_name":"mail_helper.py","file_ext":"py","file_size_in_byte":7167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"145680373","text":"from flask import current_app, request\nfrom ujson import dumps\n\n\ndef ultrajsonify(*args, **kwargs):\n \"\"\"This function reimplements ``flask.json.jsonify``\n using ``ujson.dumps`` instead of ``json.dumps``.\n \"\"\"\n indent = 0\n ensure_ascii = current_app.config.get('JSON_AS_ASCII', True)\n mimetype = current_app.config.get('JSONIFY_MIMETYPE', 'application/json')\n\n if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and \\\n not request.is_xhr:\n indent = 2\n\n if args and kwargs:\n raise ValueError(\n 'ultrajsonify behavior undefined when passed both args and kwargs'\n )\n elif len(args) == 1:\n data = args[0]\n else:\n data = args or kwargs\n\n return current_app.response_class(\n dumps(\n data,\n indent=indent,\n ensure_ascii=ensure_ascii\n ),\n mimetype=mimetype\n )\n","sub_path":"flask_ultrajson.py","file_name":"flask_ultrajson.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"411083641","text":"from flask import Flask, render_template, flash, redirect, url_for, request\nfrom flask import abort, jsonify\nfrom flask_bootstrap import Bootstrap\nfrom category_items.forms import RegistrationForm, LoginForm, CategoryForm\nfrom category_items.forms import ItemForm\nfrom category_items.models import User, Category, Item\nfrom category_items import app, db, bcrypt\nfrom flask_login import login_user, current_user, logout_user, login_required\nfrom sqlalchemy import desc\nfrom flask import session, json, make_response\nfrom flask_oauth import OAuth\n\nBootstrap(app)\n\n#these 3 values must configured from Google APIs console\n#https://code.google.com/apis/console\nID = '378967825839-dto87c0v0r6q9t5ukakgh760ecujuq6m.apps.googleusercontent.com'\nSECRET = 'j6ASZB4fdgio5S0AbZmdJAP8'\n\n#one of the Redirect URIs from Google APIs console\n\nREDIRECT_URI = '/authorized'\nAUTH_URL = 'https://accounts.google.com/o/oauth2/auth'\nREQ_TOKEN = 'https://www.googleapis.com/auth/userinfo.email'\nACCESS_TOKEN = 'https://accounts.google.com/o/oauth2/token'\noauth = OAuth()\n\ngoogle = oauth.remote_app('google',\n base_url='https://www.google.com/accounts/',\n authorize_url=AUTH_URL,\n request_token_url=None,\n request_token_params={'scope': REQ_TOKEN,\n 'response_type': 'code'},\n access_token_url=ACCESS_TOKEN,\n access_token_method='POST',\n access_token_params={\n 'grant_type': 'authorization_code'},\n consumer_key=ID,\n consumer_secret=SECRET)\n\n\n@app.route('/google_login')\ndef google_login():\n callback = url_for('authorized', _external=True)\n return google.authorize(callback=callback)\n\n\n@app.route(REDIRECT_URI)\n@google.authorized_handler\ndef authorized(resp):\n access_token = resp['access_token']\n session['access_token'] = access_token, ''\n access_token = session.get('access_token')\n if access_token is None:\n return redirect(url_for('google_login'))\n\n access_token = access_token[0]\n from urllib2 import Request, urlopen, URLError\n\n headers = {'Authorization': 'OAuth '+access_token}\n req = Request('https://www.googleapis.com/oauth2/v1/userinfo',\n None, headers)\n try:\n res = urlopen(req)\n\n encoding = res.read().decode(\"utf-8\")\n dic = json.loads(encoding)\n '''{ \"id\": \"1234567\",\n \"email\": \"email@gmail.com\",\n \"verified_email\": true,\n \"picture\":\n \"https://lh5.googleusercontent.com/-cQgy-dvOEJQ/AAAAAAAAAAI/AAAAAAAAAAA/sxuKCxAiBr0/photo.jpg\"\n }'''\n user = User.query.filter_by(email=dic[\"email\"]).first()\n if user is None:\n hashed_password = bcrypt.generate_password_hash(\n '123456').decode('utf-8')\n new_user = User(\n email=str(dic[\"email\"]),\n username=str(dic[\"email\"].split(\"@\")[0]),\n password=hashed_password\n )\n db.session.add(new_user)\n db.session.commit()\n login_user(new_user)\n else:\n login_user(user)\n categories = Category.query.filter_by(\n user_id=user.id).order_by(\n desc(Category.date_category)).all()\n items = Item.query.filter_by(\n user_id=user.id).order_by(\n desc(Item.date_item)).all()\n return render_template(\n 'home.html', title='Home', category_exists='True',\n categories=categories, items=items)\n except URLError:\n if URLError.code == 401:\n\n#Unauthorized \"bad token\"\n\n session.pop('access_token', None)\n return redirect(url_for('google_login'))\n return res.read()\n return redirect(url_for('home'))\n\n\n@google.tokengetter\ndef get_access_token():\n return session.get('access_token')\n\n\n#list of all categories for JSON Endpoint\n\n@app.route('/categories/JSON')\ndef categories_json():\n categories = Category.query.order_by(desc(Category.date_category)).all()\n return jsonify(categories=[i.serialize for i in categories])\n\n\n#list of all items for JSON Endpoint\n\n@app.route('/items/JSON')\ndef items_json():\n items = Item.query.order_by(desc(Item.date_item)).all()\n return jsonify(items=[i.serialize for i in items])\n\n\n#list of all users for JSON Endpoint\n\n@app.route('/users/JSON')\ndef users_json():\n users = User.query.all()\n return jsonify(users=[i.serialize for i in users])\n\n\n#list of all items within certain category for JSON Endpoint\n\n@app.route(\n '/categories//item//JSON')\ndef categories_item_json(category_id, item_id):\n items = Item.query.filter_by(id=item_id, cat_id=category_id).all()\n return jsonify(items=[i.serialize for i in items])\n\n\n#web page containing all categories and items\n\n@app.route('/')\n@app.route(\"/home\")\ndef home():\n categories = Category.query.order_by(\n desc(Category.date_category)).all()\n items = Item.query.order_by(desc(Item.date_item)).all()\n return render_template(\n 'home.html', title='Home', category_exists='True',\n categories=categories, items=items)\n\n\n#web page used for displaying registeration form and creating user\n\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = RegistrationForm()\n if form.validate_on_submit():\n hashed_password = bcrypt.generate_password_hash(\n form.password.data).decode('utf-8')\n user = User(\n username=form.username.data,\n email=form.email.data, password=hashed_password)\n db.session.add(user)\n db.session.commit()\n msg = 'Account created for ' + form.username.data + '!'\n flash(msg, 'success')\n return redirect(url_for('home'))\n return render_template('register.html', title='Register', form=form)\n\n\n''' web page used for displaying login form\nand the process of authenticating the user'''\n\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user and bcrypt.check_password_hash(\n user.password, form.password.data):\n login_user(user, remember=form.remember.data)\n next_page = request.args.get('next')\n home = redirect(url_for('home'))\n return redirect(next_page) if next_page else home\n else:\n flash(\n 'Login Unsuccessful. Please check email and password',\n 'danger')\n return render_template('login.html', title='Login', form=form)\n\n\n#logging out from the project\n\n@app.route(\"/logout\")\ndef logout():\n logout_user()\n return redirect(url_for('home'))\n\n\n#creating and storing new categories\n\n@app.route(\"/category/new\", methods=['GET', 'POST'])\n@login_required\ndef new_category():\n form = CategoryForm()\n if form.validate_on_submit():\n category = Category(name=form.name.data, user_id=current_user.id)\n db.session.add(category)\n db.session.commit()\n flash('Your category has been created!', 'success')\n return redirect(url_for('home'))\n return render_template(\n 'create_category.html', title='New Category',\n form=form, legend='New Category')\n\n\n#creating and storing new items\n\n@app.route(\"/item/new\", methods=['GET', 'POST'])\n@login_required\ndef new_item():\n form = ItemForm()\n categories = Category.query.all()\n cat_dict = dict()\n cat_array = []\n for category in categories:\n cat_dict = {'id': str(category.id), 'name': category.name}\n cat_array.append(cat_dict)\n\n if form.validate_on_submit():\n item = Item(\n title=form.title.data, description=form.description.data,\n cat_id=form.category.data, user_id=current_user.id)\n db.session.add(item)\n db.session.commit()\n flash('Your item has been created!', 'success')\n return redirect(url_for('home'))\n return render_template(\n 'create_item.html', title='New Item',\n form=form, legend='New Item', categories=cat_array)\n\n\n#going to certain category and its details for each category\n\n@app.route(\"/category/\")\ndef category(category_id):\n category = Category.query.get_or_404(category_id)\n categories = Category.query.order_by(desc(Category.date_category)).all()\n items = Item.query.order_by(\n desc(Item.date_item)).filter_by(\n cat_id=category_id).all()\n number_items = Item.query.order_by(\n desc(Item.date_item)).filter_by(\n cat_id=category_id).count()\n return render_template(\n 'home.html', title=category.name,\n number_items=number_items,\n categories=categories, items=items)\n\n\n#going to certain item and its details\n\n@app.route(\"/item/\")\ndef item(item_id):\n item = Item.query.get_or_404(item_id)\n return render_template('item.html', title=item.title, item=item)\n\n\n#displaying edit page and edit certain item\n\n@app.route(\"/item//update\", methods=['GET', 'POST'])\n@login_required\ndef update_item(item_id):\n categories = Category.query.all()\n item = Item.query.get_or_404(item_id)\n if item.user_id != current_user.id:\n abort(403)\n form = ItemForm()\n if form.validate_on_submit():\n item.title = form.title.data\n item.description = form.description.data\n item.cat_id = form.category.data\n db.session.commit()\n flash('Your item has been updated!', 'success')\n return redirect(url_for('item', item_id=item.id))\n elif request.method == 'GET':\n form.title.data = item.title\n form.category.data = item.cat_id\n form.description.data = item.description\n return render_template(\n 'create_item.html', title='Update Item',\n form=form, legend='Update Item',\n item_id=item_id, categories=categories)\n\n\n#deleting an item\n\n@app.route(\"/item//delete\", methods=['POST'])\n@login_required\ndef delete_item(item_id):\n item = Item.query.get_or_404(item_id)\n if item.user_id != current_user.id:\n abort(403)\n db.session.delete(item)\n db.session.commit()\n flash('Your item has been deleted!', 'success')\n return redirect(url_for('home'))\n","sub_path":"category_items/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":11108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"570727093","text":"# talos\n# Hyperparameter Optimization for Keras Models\n#website: https://towardsdatascience.com/hyperparameter-optimization-with-keras-b82e6364ca53\n#also gpyopt can be used in keras\n\nimport talos as ta\nimport os\nimport itertools\nimport codecs\nimport re\nimport datetime\nimport cairocffi as cairo\nimport editdistance\nimport numpy as np\nfrom scipy import ndimage\nimport pylab\nfrom keras import backend as K\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.layers import Input, Dense, Activation\nfrom keras.layers import Reshape, Lambda\nfrom keras.layers.merge import add, concatenate\nfrom keras.models import Model\nfrom keras.layers.recurrent import GRU\nfrom keras.optimizers import SGD\nfrom keras.utils.data_utils import get_file\nfrom keras.preprocessing import image\nimport keras.callbacks\n\n# first we have to make sure to input data and params into the function\ndef breast_cancer_model(x_train, y_train, x_val, y_val, params):\n\n # next we can build the model exactly like we would normally do it\n model = Sequential()\n model.add(Dense(10, input_dim=x_train.shape[1],\n activation=params['activation'],\n kernel_initializer='normal'))\n \n model.add(Dropout(params['dropout']))\n \n # if we want to also test for number of layers and shapes, that's possible\n hidden_layers(model, params, 1)\n \n # then we finish again with completely standard Keras way\n model.add(Dense(1, activation=params['last_activation'],\n kernel_initializer='normal'))\n \n model.compile(loss=params['losses'],\n # here we add a regulizer normalization function from Talos\n optimizer=params['optimizer'](lr=lr_normalizer(params['lr'],params['optimizer'])),\n metrics=['acc', fmeasure])\n \n history = model.fit(x_train, y_train, \n validation_data=[x_val, y_val],\n batch_size=params['batch_size'],\n epochs=params['epochs'],\n verbose=0)\n \n # finally we have to make sure that history object and model are returned\n return history, model\n \np = {'lr': (0.5, 5, 10),\n 'first_neuron':[4, 8, 16, 32, 64],\n 'hidden_layers':[0, 1, 2],\n 'batch_size': (2, 30, 10),\n 'epochs': [150],\n 'dropout': (0, 0.5, 5),\n 'weight_regulizer':[None],\n 'emb_output_dims': [None],\n 'shape':['brick','long_funnel'],\n 'optimizer': [Adam, Nadam, RMSprop],\n 'losses': [logcosh, binary_crossentropy],\n 'activation':[relu, elu],\n 'last_activation': [sigmoid]}\n\np = {'lr': (0.8, 1.2, 3),\n 'first_neuron':[4, 8, 16, 32, 64],\n 'hidden_layers':[0, 1, 2],\n 'batch_size': (1, 5, 5),\n 'epochs': [50, 100, 150],\n 'dropout': (0, 0.2, 3),\n 'weight_regulizer':[None],\n 'emb_output_dims': [None],\n 'shape':['brick','long_funnel'],\n 'kernel_initializer': ['uniform','normal'],\n 'optimizer': [Adam, Nadam, RMSprop],\n 'losses': [binary_crossentropy],\n 'activation':[relu, elu],\n 'last_activation': [sigmoid]}\n\n\n# and run the experiment\nt = ta.Scan(x=x,\n y=y,\n model=breast_cancer_model,\n grid_downsample=0.01, \n params=p,\n dataset_name='breast_cancer',\n experiment_no='1')\n","sub_path":"tools/trade_algotithms/talos_opt_for_keras.py","file_name":"talos_opt_for_keras.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"566112703","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ptick\nimport matplotlib.dates as mdates\nimport japanize_matplotlib\nimport seaborn as sns\nimport glob\nimport os\n\nfrom datetime import datetime as dt\nfrom WaterClass import Water\nfrom MoistAirClass import MoistAir\nfrom InstanceAirClass import InstanceAir\n\n#将来暗黙的に登録された日時コンバータをmatplotlibプロット方法に使用する。\n#コンバータはインポート時にPandasによって登録されました。\n#将来のバージョンのPandasでは明示的にmatplotlibコンバータを登録する必要があります。\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n\n#dateディレクトリ内のCSVファイルを表示\nFileList = [os.path.basename(r) for r in glob.glob('./data/*.csv')]\nfor fl in FileList:\n print(fl)\n\n#読み込むCSVファイルの選択と入力\nprint(\"上記リストより読み込むcsvファイルをコピペしてください。\")\nCsvFile = str(input())\n\n#風量AirVolume[m3/hr]の値入力\nprint(\"風量[m3/hr]を入力してください。\")\nAirVolume = int(input())\n\n#補足情報の入力\nprint(\"補足情報を入力してください。!!英語入力のみ有効!! 例:Cooling Mode When StartUp EA FAN 20Hz\")\nComplementaryInfo = str(input())\n\n#data instance\nos.chdir(\"./data\")\ndf = pd.read_csv(CsvFile)\n\n#NaNの除外 = NaNが含まれると値Float型となってしまうため予め除外しておく\ndf = df.dropna(how='all')\n\n#df[\"Date/Time\"]を日付型に変換\ndf[\"Date/Time\"] = pd.to_datetime(df[\"Date/Time\"])\n\n#int型変換\n\"\"\"\ndf['year'] = df['year'] .astype(int)\ndf['month'] = df['month'] .astype(int)\ndf['day'] = df['day'] .astype(int)\n\n#int型 ⇒ string型変換\ndf['year'] = df['year'] .astype(str)\ndf['month'] = df['month'] .astype(str)\ndf['day'] = df['day'] .astype(str)\n\n#Date/Time列に年月日時間を結合して日付・時間を代入 & Datetime型に変換\ndf[\"Date/Time\"] = pd.to_datetime(df['year'] + '-' + df['month'] + '-' + df['day'] + ' ' + df['time'])\n\n#df[\"Date/Time\"] = pd.to_datetime(df[\"Date/Time\"])\n\"\"\"\n\n#Date/Time列をインデックスに設定\ndf = df.set_index(\"Date/Time\")\n\n#year month day time を消去\n#df = df.drop(['year','month','day','time'],axis=1)\n\n#最新Pandasデータを確認(頭5行のみ)\n#print(df.head())\n\n#PandasデータをNumpyデータに変換\ndataframe = df.values\ndataframe = dataframe * 0.1\n\ncount = dataframe.shape[0] #データ行数のカウント:境界条件設定\n\n#状態量保存用Arrayの定義 (1次元目)\nstate_array = np.zeros(8)\n\n#初期値=0\n#temporary_array [0]:絶対湿度Array\n#temporary_array [1]:エンタルピーArray\n#temporary_array [2]:露点温度Array\n#temporary_array [3]:比容積Array\n#temporary_array [4]:全熱量Array\n#temporary_array [5]:顕熱量Array\n#temporary_array [6]:潜熱量Array\n#temporary_array [7]:水分量Array\n\n#print(state_array)\n\n#dataframeの行数のカウント:時間ごと状態量の数量\ny_count = dataframe.shape[0]\n#print(y_count)\n#dataframeの列数のカウント\nx_count = dataframe.shape[1]\n#print(x_count)\n\n#state_arrayの要素数カウント\nstate_array_count = state_array.size\n#print(state_array_count)\n\n#時間ごと状態量Arrayの定義 (2次元目) #初期値=0\nt_state_array = np.zeros((y_count,state_array_count))\n\n#print(t_state_array)\n\ni = 0 #カウンタi 初期化 (計算回数)\nn = 0 #カウンタt 初期化 (時間ごと状態量Array2次元目配列への連続代入用)\nv = 0 #カウンタv 初期化 (_tempデータのカウンタ)\nw = 24 #カウンタw 初期化 (_rhumデータのカウンタ)\nz = 0 #カウンタz 初期化 (温度、湿度インスタンスごとのカウンタ)\n\n#温度・湿度インスタンスごとの時間毎状態量 Arrayの定義 (3次元目) #初期値=0\ninst_t_state_array = np.zeros((7,y_count,state_array_count))\n\n#各行の温度と相対湿度データを引数として、temporary_array各項目の計算と代入\nwhile z < 7:\n\n #カウンタの初期化\n i = 0\n n = 0\n\n while i < y_count:\n _temp = dataframe[i,v]\n _rhum = dataframe[i,w]\n\n #MoistAir Classのインスタンス化\n moistair = MoistAir(_temp , _rhum)\n\n #各状態量の計算\n ah = moistair.GetHumidityRatioFromDryBulbTemperatureAndRelativeHumidity()\n e = moistair.GetEnthalpyFromHumidityRatioAndRelativeHumidity()\n dp = moistair.GetSaturationDryBulbTemperatureFromHumidityRatio()\n sv = moistair.GetSpecificVolumeFromDryBulbTemperatureAndHumidityRatio()\n\n #InstantceAir Classのインスタンス化\n instanceair = InstanceAir(_temp , _rhum , AirVolume)\n\n #各状態量の計算\n TH = instanceair.GetTotalHeatCapacity()\n SH = instanceair.GetSensitiveHeatCapacity()\n LH = instanceair.GetLatentHeatCapacity()\n W = instanceair.GetWaterMass()\n\n #state_array(1次元)への代入\n state_array[0] = ah\n state_array[1] = e\n state_array[2] = dp\n state_array[3] = sv\n state_array[4] = TH\n state_array[5] = SH\n state_array[6] = LH\n state_array[7] = W\n\n #inst_t_state_arrayの各要素へ状態量代入\n for n in range(0,int(state_array_count)):\n\n inst_t_state_array[z,i,n] = state_array[n]\n\n n += 1\n\n i += 1\n\n #条件変更\n v += 1\n w += 1\n z += 1\n\n#表示桁数および指数表示の設定\nnp.set_printoptions(precision=3, suppress=True)\n#inst_t_state_arrayの内容確認\n#print(inst_t_state_array)\n\n#データ列数のDataFrameカウント初期化\nx_count = dataframe.shape[1]\n\n#カウンタの初期化\ni = 0\nz = 0\ns = 0 #各状態量数\n\n#NumpyデータをPandasデータに変換して、Pandas DataFrameへ挿入\nwhile z < 7:\n\n #カウンタの初期化\n i = 0\n\n while i < int(y_count):\n\n #3次元データフレームから必要要素の列を抽出し、変数へ代入(各状態量を抽出、格納)\n a0 = inst_t_state_array[z:(z+1),:,0:(0+1)]\n a1 = inst_t_state_array[z:(z+1),:,1:(1+1)]\n a2 = inst_t_state_array[z:(z+1),:,2:(2+1)]\n a3 = inst_t_state_array[z:(z+1),:,3:(3+1)]\n a4 = inst_t_state_array[z:(z+1),:,4:(4+1)]\n a5 = inst_t_state_array[z:(z+1),:,5:(5+1)]\n a6 = inst_t_state_array[z:(z+1),:,6:(6+1)]\n a7 = inst_t_state_array[z:(z+1),:,7:(7+1)]\n\n #列データを行データに変換\n a0 = a0.transpose((0,2,1))\n a1 = a1.transpose((0,2,1))\n a2 = a2.transpose((0,2,1))\n a3 = a3.transpose((0,2,1))\n a4 = a4.transpose((0,2,1))\n a5 = a5.transpose((0,2,1))\n a6 = a6.transpose((0,2,1))\n a7 = a7.transpose((0,2,1))\n\n #3次元データフレームを1次元データフレームへ変換\n a0 = a0.flatten()\n a1 = a1.flatten()\n a2 = a2.flatten()\n a3 = a3.flatten()\n a4 = a4.flatten()\n a5 = a5.flatten()\n a6 = a6.flatten()\n a7 = a7.flatten()\n\n #pandas DataFlame df にNumpyData inst_t_state_arrayデータ抽出し代入\n df[\"Ahum\"+str(z)] = np.array(a0)\n df[\"Enthalpy\"+str(z)] = np.array(a1)\n df[\"DewPoint\"+str(z)] = np.array(a2)\n df[\"SpecificVolume\"+str(z)] = np.array(a3)\n df[\"THCapa\"+str(z)] = np.array(a4)\n df[\"SHCapa\"+str(z)] = np.array(a5)\n df[\"LHCapa\"+str(z)] = np.array(a6)\n df[\"WaterMass\"+str(z)] = np.array(a7)\n\n i += 1\n\n z += 1\n\n\n#データ列数の上書き\nx_count = df.shape[1]\n\n#交換熱量列の追加\ndf[\"PreCoil_TH(kW)\"] = abs(df.THCapa1-df.THCapa2)\ndf[\"PreCoil_SH(kW)\"] = abs(df.SHCapa1-df.SHCapa2)\ndf[\"PreCoil_LH(kW)\"] = abs(df.LHCapa1-df.LHCapa2)\ndf[\"PreCoil_W(L/hr)\"] = abs(df.WaterMass1-df.WaterMass2)\ndf[\"Coil_TH(kW)\"] = abs(df.THCapa2-df.THCapa3)\ndf[\"Coil_SH(kW)\"] = abs(df.SHCapa2-df.SHCapa3)\ndf[\"Coil_LH(kW)\"] = abs(df.LHCapa2-df.LHCapa3)\ndf[\"Coil_W(kg/h)\"] = abs(df.WaterMass2-df.WaterMass3)\ndf[\"TCoil_TH(kW)\"] = abs(df.THCapa1-df.THCapa3)\ndf[\"TCoil_SH(kW)\"] = abs(df.SHCapa1-df.SHCapa3)\ndf[\"TCoil_LH(kW)\"] = abs(df.LHCapa1-df.LHCapa3)\ndf[\"TCoil_W(kg/h)\"] = abs(df.WaterMass1-df.WaterMass3)\n\n#再熱量列の追加\ndf[\"ReHeat_TH(kW)\"] = (df.THCapa4-df.THCapa3)\ndf[\"ReHeat_SH(kW)\"] = (df.SHCapa4-df.SHCapa3)\ndf[\"ReHeat_LH(kW)\"] = (df.LHCapa4-df.LHCapa3)\n\n#全熱交換器効率\ndf[\"SHE(%)\"] = (abs(df.SHCapa0-df.SHCapa1) / abs(df.SHCapa0-df.SHCapa5))*100\ndf[\"THE(%)\"] = (abs(df.THCapa0-df.THCapa1) / abs(df.THCapa0-df.THCapa5))*100\n\n#温度変化\ndf[\"OATemp\"] = (df.iloc[:, [0]]) / 10\ndf[\"hxTemp\"] = (df.iloc[:, [1]]) / 10\ndf[\"preTemp\"] = (df.iloc[:, [2]]) / 10\ndf[\"evaTemp\"] = (df.iloc[:, [3]]) / 10\ndf[\"condTemp\"] = (df.iloc[:, [4]]) / 10\ndf[\"diffTemp\"] = df.condTemp - df.evaTemp\n\n#最新Pandasデータを確認(頭5行のみ)\n#print(df.head())\n\n#最新PndasデータをCSV形式で出力\nos.chdir('../result')\ndf.to_csv('result_' + str(AirVolume) +'m3__' + ComplementaryInfo + '__' + CsvFile)\n\n#グラフ fig インスタンス生成(交換熱量グラフ)\nfig_heat = plt.figure(figsize=(14,8))\n#グラフ表示数 縦\nv_heat = 4\n#グラフ表示数 横\nh_heat = 1\n# グラフ番号(プロット番号)カウント\nplotnumber_heat = v_heat * h_heat\n#ax_heatオブジェクト保持用list\nax_heat = []\n\n#グラフ fig インスタンス生成(再熱量グラフ)\nfig_reheat = plt.figure(figsize=(14,8))\n#グラフ表示数 縦\nv_reheat = 3\n#グラフ表示数 横\nh_reheat = 1\n# グラフ番号(プロット番号)カウント\nplotnumber_reheat = v_reheat * h_reheat\n#ax_heatオブジェクト保持用list\nax_reheat = []\n\n#グラフ fig インスタンス生成(全熱交換器効率グラフ)\nfig_hxe = plt.figure(figsize=(14,8))\n#グラフ表示数 縦\nv_hxe = 2\n#グラフ表示数 横\nh_hxe = 1\n# グラフ番号(プロット番号)カウント\nplotnumber_hxe = v_hxe * h_hxe\n#ax_heatオブジェクト保持用list\nax_hxe = []\n\n#グラフ fig インスタンス生成(温度変化グラフ)\nfig_temp = plt.figure(figsize=(14,8))\n#グラフ表示数 縦\nv_temp = 1\n#グラフ表示数 横\nh_temp = 1\n# グラフ番号(プロット番号)カウント\nplotnumber_temp = v_temp * h_temp\n#ax_temp AXESインスタンス生成\nax_temp = fig_temp.add_subplot(1,1,1)\nax_diff = ax_temp.twinx()\n\n#seabornデフォルトスタイルを適用\nsns.set()\n\n#使用できる色の設定\ncolor = ['tomato', 'royalblue', 'forestgreen', 'darkorange', 'darkviolet','midnightblue']\ncolor10 = 'lightgrey'\n\n#カウンタ初期化\ni_h = 1\ni_rh = 1\ni_hxe = 1\ni_temp = 1\n\n#グラフタイトル名の設定\nGraghTitle = CsvFile.replace(\".csv\", \"_\")\nGraghTitle = GraghTitle.replace(\"input\", \"_\")\nGraghTitle = 'result' + GraghTitle + '_' + str(AirVolume) +'m3/h' + '__' + ComplementaryInfo\n\n#交換熱量グラフの描画と書式設定\nfor i_h in range(1, plotnumber_heat+1): # 1から始まり、plotnunber_heat+1まで処理する\n ax_heat = np.append(ax_heat,fig_heat.add_subplot(v_heat,h_heat,i_h)) # AXESをfig_heatへ追加(v,h)&順序i ⇒ この配列情報ax_heat list型に追加\n\n ax_heat[i_h-1].plot(df.iloc[:, [i_h+103]], color = color[0], label=df.columns.values[i_h+103])\n ax_heat[i_h-1].set_ylabel(df.columns.values[i_h+103])\n #ax_heat[i_h-1].grid() #seabornデフォルトスタイルを適用時はOFF\n ax_heat[i_h-1].xaxis.set_major_locator(mdates.HourLocator()) #時系列のX軸の(主)間隔設定\n ax_heat[i_h-1].xaxis.set_minor_locator(mdates.MinuteLocator(30)) #時系列のX軸の(副)間隔設定\n ax_heat[i_h-1].yaxis.set_minor_locator(ptick.MultipleLocator(1)) #Y軸の(主)間隔設定\n ax_heat[i_h-1].tick_params(axis='x', which='major')\n ax_heat[i_h-1].grid(which='minor') #小目盛に対してグリッド表示\n ax_heat[i_h-1].set_ylim(0,4)\n ax_heat[i_h-1].set_facecolor(color10)\n\n #最後のグラフ以外はX軸表記しない\n if i_h < (plotnumber_heat):\n ax_heat[i_h-1].set_xticklabels([])\n #最初のグラフの上左にタイトル表示\n if i_h == 1:\n #グラフタイトルの表示\n ax_heat[i_h-1].set_title(GraghTitle + '_HeatExchange', loc=\"left\", fontsize=15, fontweight='bold')\n\n#再熱量グラフの描画と書式設定\nfor i_rh in range(1, plotnumber_reheat+1): # 1から始まり、plotnunber_reheat+1まで処理する\n ax_reheat = np.append(ax_reheat,fig_reheat.add_subplot(v_reheat,h_reheat,i_rh)) # AXESをfig_reheatへ追加(v,h)&順序i ⇒ この配列情報ax_reheat list型に追加\n\n ax_reheat[i_rh-1].plot(df.iloc[:, [i_rh+107]], color = color[0], label=df.columns.values[i_rh+107])\n ax_reheat[i_rh-1].set_ylabel(df.columns.values[i_rh+107])\n #ax_reheat[i_rh-1].grid() #seabornデフォルトスタイルを適用時はOFF\n ax_reheat[i_rh-1].xaxis.set_major_locator(mdates.HourLocator()) #時系列のX軸の(主)間隔設定\n ax_reheat[i_rh-1].xaxis.set_minor_locator(mdates.MinuteLocator(30)) #時系列のX軸の(副)間隔設定\n ax_reheat[i_rh-1].yaxis.set_minor_locator(ptick.MultipleLocator(1)) #Y軸の(主)間隔設定\n ax_reheat[i_rh-1].tick_params(axis='x', which='major')\n ax_reheat[i_rh-1].grid(which='minor') #小目盛に対してグリッド表示\n ax_reheat[i_rh-1].set_ylim(-2,2)\n ax_reheat[i_rh-1].set_facecolor(color10)\n\n #最後のグラフ以外はX軸表記しない\n if i_rh < (plotnumber_reheat):\n ax_reheat[i_rh-1].set_xticklabels([])\n #最初のグラフの上左にタイトル表示\n if i_rh == 1:\n #グラフタイトルの表示\n ax_reheat[i_rh-1].set_title(GraghTitle + '_ReHeat', loc=\"left\", fontsize=15, fontweight='bold')\n\n#全熱交換器効率グラフの描画と書式設定\nfor i_hxe in range(1, plotnumber_hxe+1): # 1から始まり、plotnunber_hxeまで処理する\n ax_hxe = np.append(ax_hxe,fig_hxe.add_subplot(v_hxe,h_hxe,i_hxe)) # AXESをfig_hxeへ追加(v,h)&順序i ⇒ この配列情報ax_hxe list型に追加\n\n ax_hxe[i_hxe-1].plot(df.iloc[:, [i_hxe+110]], color = color[0], label=df.columns.values[i_hxe+110])\n ax_hxe[i_hxe-1].set_ylabel(df.columns.values[i_hxe+110])\n #ax_hxe[i_hxe-1].grid() #seabornデフォルトスタイルを適用時はOFF\n ax_hxe[i_hxe-1].xaxis.set_major_locator(mdates.HourLocator()) #時系列のX軸の(主)間隔設定\n ax_hxe[i_hxe-1].xaxis.set_minor_locator(mdates.MinuteLocator(30)) #時系列のX軸の(副)間隔設定\n ax_hxe[i_hxe-1].yaxis.set_minor_locator(ptick.MultipleLocator(10)) #Y軸の(主)間隔設定\n ax_hxe[i_hxe-1].tick_params(axis='x', which='major')\n ax_hxe[i_hxe-1].grid(which='minor') #小目盛に対してグリッド表示\n ax_hxe[i_hxe-1].set_ylim(0,100)\n ax_hxe[i_hxe-1].set_facecolor(color10)\n\n #最後のグラフ以外はX軸表記しない\n if i_hxe < (plotnumber_hxe):\n ax_hxe[i_hxe-1].set_xticklabels([])\n #最初のグラフの上左にタイトル表示\n if i_hxe == 1:\n #グラフタイトルの表示\n ax_hxe[i_hxe-1].set_title(GraghTitle + '_HeatExchangeEfficent', loc=\"left\", fontsize=15, fontweight='bold')\n\n#温度変化グラフの描画と書式設定\n\n#第1軸設定\nfor i_temp in range (1, 6):\n ax_temp.plot(df.iloc[:, [i_temp+112]], color = color[i_temp-1], label=df.columns.values[i_temp+112])\n\n#第2軸設定\nax_diff.plot(df.iloc[:, [118]], color = color[5], label=df.columns.values[118], ls=\"--\")\n\n#第1軸の書式設定\nax_temp.grid(which='major')\nax_temp.xaxis.set_major_locator(mdates.HourLocator()) #時系列のX軸の(主)間隔設定\nax_temp.xaxis.set_minor_locator(mdates.MinuteLocator(30)) #時系列のX軸の(副)間隔設定\nax_temp.yaxis.set_minor_locator(ptick.MultipleLocator(5)) #Y軸の(主)間隔設定\nax_temp.tick_params(axis='x', which='major')\nax_temp.grid(which='minor', ls=\":\") #小目盛に対してグリッド表示\nax_temp.set_ylim(0,50)\nax_temp.set_ylabel('Temp(C)')\nax_temp.set_facecolor(color10)\nax_temp.set_title(GraghTitle + '_Temprature', loc=\"left\", fontsize=15, fontweight='bold')\n\n#第2軸の書式設定\nax_diff.yaxis.set_minor_locator(ptick.MultipleLocator(5)) #Y軸の(主)間隔設定\nax_diff.set_ylim(0,50)\nax_diff.set_ylabel('DiffTemp Cond & Eva (C)')\n\n#重ね順の設定。\nax_temp.set_zorder(2)\nax_diff.set_zorder(1)\n\n#折れ線グラフの背景を透明に。\nax_temp.patch.set_alpha(0)\n\n#凡例を表示(グラフ左上、ax2をax1のやや下に持っていく)\nax_temp.legend(bbox_to_anchor=(0, 1), loc='upper left', borderaxespad=0.5, fontsize=10)\nax_diff.legend(bbox_to_anchor=(0.1, 1), loc='upper left', borderaxespad=0.5, fontsize=10)\n\n#グラフ下段のみX軸書式設定\nax_heat[i_h-1].set_xlabel('Date/Time')\nax_heat[i_h-1].xaxis.set_major_formatter(mdates.DateFormatter('%m/%d\\n%H:%M'))\n\nax_reheat[i_rh-1].set_xlabel('Date/Time')\nax_reheat[i_rh-1].xaxis.set_major_formatter(mdates.DateFormatter('%m/%d\\n%H:%M'))\n\nax_hxe[i_hxe-1].set_xlabel('Date/Time')\nax_hxe[i_hxe-1].xaxis.set_major_formatter(mdates.DateFormatter('%m/%d\\n%H:%M'))\n\nax_temp.set_xlabel('Date/Time')\nax_temp.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d\\n%H:%M'))\n\n\n#グラフ位置など自動調整\nplt.tight_layout()\n\n#グラフ上の値(x,y)を表示\nplt.style.use('ggplot')\n\n#グラフをpng形式で保存 保存先resultディレクトリ\nos.chdir('../result')\nPngFile = CsvFile.replace(\".csv\", \".png\")\nfig_heat.savefig('result_' + str(AirVolume) +'m3__' + ComplementaryInfo + '__heat_' + PngFile, transparent=False, bbox_inches='tight', dpi=400)\nfig_reheat.savefig('result_' + str(AirVolume) +'m3__' + ComplementaryInfo + '__reheat_' + PngFile, transparent=False, bbox_inches='tight', dpi=400)\nfig_hxe.savefig('result_' + str(AirVolume) +'m3__' + ComplementaryInfo + '__hxe_' + PngFile, transparent=False, bbox_inches='tight', dpi=400)\nfig_temp.savefig('result_' + str(AirVolume) +'m3__' + ComplementaryInfo + '__temp_' + PngFile, transparent=False, bbox_inches='tight', dpi=400)\n\n#グラフ表示\n#plt.show()\n","sub_path":"main_input.py","file_name":"main_input.py","file_ext":"py","file_size_in_byte":18139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"144916952","text":"# TUPLES:\n\n#Task\n#Given an integer, n, and n space-separated integers as input, create a tuple, t, of those n integers.\n#Then compute and print the result of hash(t).\n#Link = https://www.hackerrank.com/challenges/python-tuples/problem\n\n\nif __name__ == '__main__':\n n = int(input())\n integer_list = map(int, input().split())\n my_tuple = tuple(integer_list)\n\n print(hash(my_tuple))\n","sub_path":"tuples.py","file_name":"tuples.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"522832290","text":"# SPDX-FileCopyrightText: AISEC Pentesting Team\n#\n# SPDX-License-Identifier: Apache-2.0\n\nimport asyncio\nfrom argparse import Namespace\n\nfrom gallia.command import UDSScanner\nfrom gallia.services.uds import NegativeResponse\nfrom gallia.services.uds.core.utils import g_repr\nfrom gallia.utils import auto_int\n\n\nclass ReadErrorLogPrimitive(UDSScanner):\n \"\"\"Read the error log via the DTC service\"\"\"\n\n COMMAND = \"error-log\"\n GROUP = \"primitive\"\n SHORT_HELP = \"read the error log via DTC\"\n\n def configure_parser(self) -> None:\n self.parser.set_defaults(properties=False)\n\n self.parser.add_argument(\n \"--sessions\",\n type=auto_int,\n nargs=\"*\",\n help=\"set list of sessions to perform test in, or all\",\n )\n self.parser.add_argument(\n \"--clear-dtc\",\n action=\"store_true\",\n help=\"Clear DTC log\",\n )\n\n async def main(self, args: Namespace) -> None:\n sessions = args.sessions\n if sessions is None or len(sessions) == 0:\n sessions = list(range(1, 0x80))\n sessions = await self.ecu.find_sessions(sessions)\n msg = f\"Found {len(sessions)} sessions: {g_repr(sessions)}\"\n self.logger.result(msg)\n\n for sess in sessions:\n await self.ecu.set_session(sess)\n resp = await self.ecu.read_dtc()\n if isinstance(resp, NegativeResponse):\n self.logger.warning(resp)\n else:\n self.logger.result(resp.dtc_and_status_record)\n await self.ecu.leave_session(sess)\n\n if args.clear_dtc:\n await self.ecu.clear_dtc()\n await self.ecu.read_dtc()\n self.logger.info(\"Rebooting ECU...\")\n await self.ecu.ecu_reset(1)\n await asyncio.sleep(2)\n await self.ecu.read_dtc()\n","sub_path":"src/gallia/commands/primitive/uds/read_error_log.py","file_name":"read_error_log.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"493358672","text":"import RPi.GPIO as GPIO\nimport time\nimport threading\n\nclass Motion:\n\tdef __init__(self, light, database):\n\t\tself.active = True\n\t\tself.updateTime = 1\n\t\tself.timer = None\n\t\tself.running = True\n\t\tself.INPUT_WIRE = 17\n\t\tGPIO.setmode(GPIO.BCM)\n\t\tGPIO.setup(self.INPUT_WIRE, GPIO.IN)\n\t\tself.light = light\n\t\tself.db = database\n\t\tself.lock = threading.Lock()\n\t\t\n\tdef __del__(self):\n\t\tself.stop_Timer()\n\t\n\tdef loop(self):\n\t\tprint(\"start loop motion\")\n\t\twhile self.running:\n\t\t\tvalue = GPIO.input(self.INPUT_WIRE)\n\t\t\tif value and self.isActive():\n\t\t\t\tself.light.update(\"Lumos\")\n\t\t\ttime.sleep(self.updateTime)\n\t\t\t\n\tdef start_Timer(self):\n\t\tself.stop_Timer()\n\t\tself.lock.acquire()\n\t\tself.timer = threading.Timer(600.0, self.no_Activity)\n\t\tself.timer.start()\n\t\tself.lock.release()\n\t\t\n\tdef stop_Timer(self):\n\t\tself.lock.acquire()\n\t\tif self.timer:\n\t\t\tself.timer.cancel()\n\t\tself.lock.release()\n\t\t\t\n\tdef isActive(self):\n\t\tstart_time, end_time = self.get_Motion_Times()\n\t\tlocal_time = time.localtime()\n\t\t\n\t\tstart_time = start_time.tm_hour * 60 + start_time.tm_min\n\t\tend_time = end_time.tm_hour * 60 + end_time.tm_min\n\t\tlocal_time = local_time.tm_hour * 60 + local_time.tm_min\n\t\t\n\t\tif start_time > end_time:\n\t\t\tif local_time > start_time:\n\t\t\t\tend_time = 1440\n\t\t\telse:\n\t\t\t\tstart_time = -1\n\t\tif start_time < local_time < end_time:\n\t\t\tself.start_Timer()\n\t\t\treturn True\n\t\treturn False\n\t\t\t\n\tdef set_Running(self, running):\n\t\tself.running = running\n\t\n\tdef set_Motion_Times(self, times):\n\t\tstart_Time = times[10:12] + times[13:15] + '00'\n\t\tend_Time = times[16:18] + times[19:21] + '00'\n\t\tresult = self.db.execute_Query(\"UPDATE motion SET start_time = \" + start_Time + \n\t\t\t\t\t\t\t\t\t\t\t\t\t \", end_time = \" + end_Time + \" WHERE motion_id = 0\")\n\t\t\n\tdef get_Motion_Times(self):\n\t\tresult = self.db.execute_Query(\"SELECT * FROM motion WHERE motion_id = 0\")\n\t\tfor reading in result:\n\t\t\tstart_time, end_time = time.gmtime(reading[0].seconds), time.gmtime(reading[1].seconds)\n\t\t\treturn (start_time, end_time)\n\t\treturn (time.gmtime(0), time.gmtime(0))\n\t\t\t\n\tdef no_Activity(self):\n\t\tif self.isActive():\n\t\t\tself.light.update(\"Nox\")\n","sub_path":"pyweb/hardware/Motion.py","file_name":"Motion.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"328317826","text":"import requests\nimport random\n\nurl=\"http://www.weather.com.cn/weather/101301103.shtml\"\nheader={\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n 'Connection': 'keep-alive',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'\n }\ntimeout=random.choice(range(80,180))\nr=requests.get(url,headers=header,timeout=timeout)\nr.encoding=\"utf-8\"\nprint(r.text)","sub_path":"爬虫/requests_1028/requests01.py","file_name":"requests01.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"271815112","text":"from newMCTS import MCTSnet\nfrom Connect4 import Connect4\nimport config\nimport numpy as np\nimport pickle\nfrom IPython.core.debugger import set_trace\n\nconnect4 = Connect4()\nactions = connect4.actions\ncalculate_reward = connect4.calculate_reward\nget_legal_actions = connect4.get_legal_actions\ntransition = connect4.transition\ntest_valid = connect4.test_valid\n\nroot_state = np.zeros(shape=(3, 6, 7), dtype=\"float32\")\niteration = 0\n\n# mcts_net = MCTSnet(actions=actions, calculate_reward=calculate_reward,\n# get_legal_actions=get_legal_actions, transition=transition)\n\n#I suspect that the memories are not correctly propagating the gradient to \n#the networks. Need to inspect that and see if they are working correctly\n\ntry:\n memories = pickle.load(\n open(\"checkpoints/memories.p\", \"rb\"))\nexcept FileNotFoundError:\n print(\"Memories not found, making new memories.\")\n memories = []\n\nprint(\"Number of memories: \"+str(len(memories)))\nmcts_net = MCTSnet(actions=actions, calculate_reward=calculate_reward,\n get_legal_actions=get_legal_actions, transition=transition, test_valid=test_valid)\n# mcts_net.save_training_model()\n\nwhile True:\n if len(memories) > config.MIN_MEMORIES:\n mcts_net.train_memories(memories)\n else:\n print(\"Not enough memories ({}), need {}\".format(len(memories), config.MIN_MEMORIES))\n\n memories = mcts_net.self_play(root_state, memories)\n # mcts_net.save_memories()\n # print(\"Number of memories: \"+str(len(memories)))\n # mcts_net.load_training_model()\n # mcts_net = MCTSnet(actions=actions, calculate_reward=calculate_reward,\n # get_legal_actions=get_legal_actions, transition=transition, trainer=True, \n # memories=memories)\n\n print(\"Saving memories\")\n pickle.dump(memories,\n open(\"checkpoints/memories.p\", \"wb\"))\n\n iteration += 1\n print(\"Iteration Number \"+str(iteration))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"244967593","text":"__author__ = 'drzzh'\n'''\n一个比较愚蠢的递归解法:\n 先求左子树的镜像,然后判断镜像树是否和右子树相等\n如何求树的镜像:\n 递归啊,先交换当前节点的左右子树,然后递归解左右子树的镜像树\n\n'''\n\n\n\n\nclass Solution:\n # @param root, a tree node\n # @return a boolean\n def isSymmetric(self, root):\n if not root:\n return True\n if not root.left and not root.right:\n return True\n left = self.minor(root.left)\n return self.isSameTree(left, root.right)\n\n\n def minor(self, root):\n if not root:\n return\n temp = root.left\n root.left = root.right\n root.right = temp\n self.minor(root.left)\n self.minor(root.right)\n return root\n\n\n def isSameTree(self, p, q):\n if not q and not p:\n return True\n if not q or not p:\n return False\n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n","sub_path":"Tree/Symmetric Tree.py","file_name":"Symmetric Tree.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"1837726","text":"#調整資料夾內所有圖片檔影像寬度, 加logo\n \nimport sys, os, glob\nfrom PIL import Image, ImageDraw\nimport shutil\n\nsource_dir = 'C:/_git/vcs/_1.data/______test_files1/source_pic'\ntarget_dir = 'C:/_git/vcs/_1.data/______test_files2/resized_pic'\n#logo_filename = 'C:/_git/vcs/_1.data/______test_files1/burn.bmp' #fail\nlogo_filename = 'C:/_git/vcs/_1.data/______test_files1/logo.png'\n\n#準備輸出資料夾 若已存在, 則先刪除再建立 若不存在, 則建立\nif os.path.exists(target_dir):\n #os.remove(target_dir) #存取被拒 不可用\n shutil.rmtree(target_dir)\nif not os.path.exists(target_dir):\n os.mkdir(target_dir)\n\nimage_width = 800\n\nprint(\"將資料夾 \" + source_dir + \" 內所有圖片檔調整寬度成 \" + str(image_width) + \" 像素\")\n\nprint('Processing: {}'.format(source_dir))\n\n#單層\nallfiles = glob.glob(source_dir + '/*.jpg') + glob.glob(source_dir + '/*.png')\n\nlogo = Image.open(logo_filename) #PIL讀取本機圖片\nlogo = logo.resize((150, 150)) #調整圖像大小\n\nfor target_image in allfiles:\n\tpathname, filename = os.path.split(target_image)\n\tprint(filename)\n\timage = Image.open(target_image) #PIL讀取本機圖片\n\tw, h = image.size\n\timage = image.resize((800, int(800 / float(w) * h)))\n\timage.paste(logo, (0, 0), logo)\n\timage.save(target_dir + '/' + filename)\n\timage.close()\n\nprint(\"完成\")\nprint('輸出圖片資料夾 : ', target_dir)\n\n\t\n","sub_path":"_4.python/PIL/PIL02.py","file_name":"PIL02.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"333490975","text":"# -*- encoding: utf-8 -*-\n\nimport sys\nimport os.path\nimport argparse\nimport logging\nimport regex # supports POSIX classes\n\nre_tag = regex.compile('^<.+>$')\n\n\ndef subst_char_class(rule):\n rule = rule.replace(r'\\p{IsPi}', r'\\p{Initial_Punctuation}\\p{Dash_Punctuation}')\n rule = rule.replace(r'\\p{IsPf}', r'\\p{Final_Punctuation}')\n rule = rule.replace(r'\\p{IsAlnum}', r'\\w')\n rule = rule.replace(r'\\p{IsUpper}', r'\\p{Uppercase_Letter}\\p{Other_Letter}')\n return rule\n\n# Prefix file utilities\n\n\ndef get_prefix_filename(language):\n prefixfile = getprefixfile(language)\n # default back to English if we don't have a language-specific prefix file\n if not os.path.isfile(prefixfile):\n prefixfile = getprefixfile(\"en\")\n logging.info(\"WARNING: No known abbreviations for language '%s', attempting fall-back to English version...\\n\", language)\n if not os.path.isfile(prefixfile):\n raise RuntimeError(\"ERROR: No abbreviations files found in \" + prefixfile)\n return prefixfile\n\n\ndef load_prefix_file(prefixfile):\n NONBREAKING_PREFIX = {}\n with open(prefixfile, encoding='utf8') as file:\n for line in file.readlines():\n line = line.strip()\n if len(line) and line[0] != \"#\":\n m = regex.match('(.*)[\\s]+(\\#NUMERIC_ONLY\\#)', line)\n if m:\n NONBREAKING_PREFIX[m.group(1)] = 2\n else:\n NONBREAKING_PREFIX[line] = 1\n return NONBREAKING_PREFIX\n\n\ndef getprefixfile(language):\n mydir = \"nonbreaking_prefixes\"\n prefixfile = os.path.join(os.path.dirname(__file__), mydir, \"nonbreaking_prefix.\" + language)\n return prefixfile\n\n################################################################################\n\n\nclass SentenceSplitter:\n def __init__(self, language):\n name = get_prefix_filename(language)\n self.NONBREAKING_PREFIX = load_prefix_file(name)\n\n def process_string(self, text):\n lines = text.split('\\n')\n return process_lines(lines, self.NONBREAKING_PREFIX)\n\n def process_file(self, file_name):\n with open(file_name, mode='r', encoding='utf8') as file:\n lines = file.readlines()\n return process_lines(lines, self.NONBREAKING_PREFIX)\n\n#paragraph_end = '
'\nparagraph_end = '\\n'\n\ndef process_lines(lines, NONBREAKING_PREFIX):\n # loop text, add lines together until we get a blank line or a
\n out_text = ''\n\n text = \"\"\n for line in lines:\n line = line.strip()\n m = re_tag.match(line)\n if m is None:\n m = regex.match('^\\s*$', line)\n\n if m is not None:\n # time to process this block, we've hit a blank or
\n out_text += do_it_for(text, line, NONBREAKING_PREFIX)\n if regex.match('^\\s*$', line) and len(text): ##if we have text followed by
\n out_text += paragraph_end + \"\\n\"\n text = \"\"\n else:\n # append the text, with a space\n text += line + \" \"\n\n # do the leftover text\n if len(text):\n out_text += do_it_for(text, \"\", NONBREAKING_PREFIX)\n return out_text\n\n\ndef do_it_for(text, markup, NONBREAKING_PREFIX):\n result = preprocess(text, NONBREAKING_PREFIX)\n if len(text):\n return result\n if re_tag.match(markup):\n return markup + \"\\n\"\n return ''\n\n\ndef preprocess(text, NONBREAKING_PREFIX):\n # clean up spaces at head and tail of each line as well as any double-spacing\n text = regex.sub('\\s+', ' ', text)\n text = regex.sub('\\n ', '\\n', text)\n text = regex.sub(' \\n', '\\n', text)\n text = regex.sub('^\\s', '', text)\n text = regex.sub('\\s$', '', text)\n\n # this is one paragraph\n # add sentence breaks as needed#####\n # non-period end of sentence markers (?!) followed by sentence starters.\n text = regex.sub (subst_char_class(r'([?!])\\s+([\\'\\\"\\(\\[\\¿\\¡\\p{IsPi}]*[\\p{IsUpper}])'), r'\\1\\n\\2', text)\n\n # multi-dots followed by sentence starters\n text = regex.sub (subst_char_class(r'(\\.[\\.]+)\\s+([\\'\\\"\\(\\[\\¿\\¡\\p{IsPi}]*[\\p{IsUpper}])'), r'\\1\\n\\2', text)\n\n # add breaks for sentences that end with some sort of punctuation inside a quote or parenthetical and\n # are followed by a possible sentence starter punctuation and upper case\n text = regex.sub (subst_char_class(r'([?!\\.][\\s]*[\\'\\\"\\)\\]\\p{IsPf}]+)\\s+([\\'\\\"\\(\\[\\¿\\¡\\p{IsPi}]*[\\s]*[\\p{IsUpper}])'), r'\\1\\n\\2', text)\n\n # add breaks for sentences that end with some sort of punctuation are followed by a sentence starter punctuation and\n # upper case\n text = regex.sub(subst_char_class(r'([?!\\.])\\s+([\\'\\\"\\(\\[\\¿\\¡\\p{IsPi}]+\\s*[\\p{IsUpper}])'), r'\\1\\n\\2', text) #, flags=regex.MULTILINE)\n\n text = regex.sub(subst_char_class(r'。'), r'。\\n', text)\n\n # special punctuation cases are covered. Check all remaining periods.\n words = text.split(' ')\n text = \"\"\n for i in range(len(words)-1):\n m = regex.match(subst_char_class(r'([\\p{IsAlnum}\\.\\-]*)([\\'\\\"\\)\\]\\%\\p{IsPf}]*)(\\.+)$'), words[i], flags=regex.S)\n if m:\n # check if $1 is a known honorific and $2 is empty, never break\n prefix = m.group(1)\n starting_punct = m.group(2)\n if prefix and NONBREAKING_PREFIX.get(prefix) == 1 and not starting_punct:\n # not breaking;\n pass\n elif regex.match(subst_char_class(r'[\\.][\\p{IsUpper}\\-]+(\\.+)$'), words[i]):\n pass\n # not breaking - upper case acronym\n elif regex.match(subst_char_class(r'^([\\s]*[\\'\\\"\\(\\[\\¿\\¡\\p{IsPi}]*[\\s]*[\\p{IsUpper}0-9])'), words[i+1]):\n # the next word has a bunch of initial quotes, maybe a space, then either upper case or a number\n if prefix and NONBREAKING_PREFIX.get(prefix, 0) == 2 and not starting_punct and (regex.match(r'^[0-9]+', words[i+1])):\n pass\n else:\n words[i] += \"\\n\"\n # we always add a return for these unless we have a numeric non-breaker and a number start\n\n text += words[i] + \" \"\n\n # we stopped one token from the end to allow for easy look-ahead. Append it now.\n text += words[-1]\n\n # clean up spaces at head and tail of each line as well as any double-spacing\n text = regex.sub(r' +', ' ', text)\n text = regex.sub(r'\\n ', '\\n', text)\n text = regex.sub(r' \\n', '\\n', text)\n text = regex.sub(r'^ ', '', text)\n text = regex.sub(r' $', '', text)\n\n # add trailing break\n if len(text) != 0 and text[-1] != '\\n':\n text += \"\\n\"\n\n return text\n\n\ndef get_command_args(args):\n parser = argparse.ArgumentParser(description='Split a text into sentences.')\n parser.add_argument('--quiet', '-q', help='Be quiet', action='store_true')\n parser.add_argument('--language', '-l', default='en', metavar='en|fr|ru|ja|...',\n type=str, help='Sets the language of the input text. English is default.')\n parser.add_argument('infile', help='Input file name')\n parser.add_argument('outfile', help='Output file name', nargs='?')\n\n res = parser.parse_args(args=args)\n return res.language, res.quiet, res.infile, res.outfile\n\ndef main():\n language, quiet, infile, outfile = get_command_args(sys.argv[1:])\n splitter = SentenceSplitter(language)\n text = splitter.process_file(infile)\n if outfile is None or len(outfile) == 0:\n print(text)\n else:\n with open(outfile, mode='w', encoding='utf8') as file:\n file.write(text)\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"splitter/splitter.py","file_name":"splitter.py","file_ext":"py","file_size_in_byte":7553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"81132119","text":"#\r\n# Copyright 2018 rn9dfj3\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\nimport bpy\r\nimport numpy as np\r\n\r\nbl_info = {\r\n \"name\": \"Love2D3D\",\r\n \"author\": \"rn9dfj3\",\r\n \"version\": (0, 1),\r\n \"blender\": (2, 79, 0),\r\n \"location\": \"3D View > Object Mode > Tool Shelf > Create > Love2D3D\",\r\n \"description\": \"Create 3D object from 2D image\",\r\n \"warning\": \"\",\r\n \"support\": \"COMMUNITY\",\r\n \"wiki_url\": \"https://github.com/rn9dfj3/love2d3d/wiki\",\r\n \"tracker_url\": \"https://github.com/rn9dfj3/love2d3d/issues\",\r\n \"category\": \"Add Mesh\"\r\n}\r\n\r\nRGBA = 4 # Color size per pixels\r\nRGB = 3 # Color size per pixels\r\nR = 0 # Index of color\r\nG = 1 # Index of color\r\nB = 2 # Index of color\r\nA = 3 # Index of color\r\nX = 0 # Index\r\nY = 1 # Index\r\nLEFT = 2 # Index\r\nRIGHT = 3 # Index\r\nBOTTOM = 4 # Index\r\nTOP = 5 # Index\r\nQUAD = 4 # Vertex Numer of Quad\r\nFRONT = 0\r\nBACK = 1\r\nNAME = \"Love2D3D\" # Name of 3D object\r\n\r\n\r\nclass CreateObject(bpy.types.Operator):\r\n\r\n bl_idname = \"object.create_love2d3d\"\r\n bl_label = \"Create love2D3D\"\r\n bl_description = \"Create 3D object from 2D image.\"\r\n bl_options = {'REGISTER', 'UNDO'}\r\n\r\n def execute(self, context):\r\n image = context.window_manager.love2d3d.image_front # Image ID\r\n if image == \"\":\r\n return {\"CANCELLED\"}\r\n image = context.blend_data.images[image] # Get image\r\n resolution = context.window_manager.love2d3d.rough # Get resolution\r\n w, h = image.size # Image width and height\r\n all = w * h\r\n pixels = image.pixels[:] # Get slice of color infomation\r\n fronts = []\r\n backs = [[True for i in range(w)] for j in range(h)]\r\n e1 = h-resolution\r\n e2 = w-resolution\r\n opacity = context.window_manager.love2d3d.opacity\r\n threshold = context.window_manager.love2d3d.threshold\r\n for y in range(resolution, e1)[::resolution]:\r\n left = 0 + y * w\r\n b2 = RGBA * left # Get Left color of image\r\n for x in range(resolution, e2)[::resolution]:\r\n back = False\r\n for v in range(resolution):\r\n for u in range(resolution):\r\n p = (x+u) + (y+v) * w\r\n b1 = RGBA * p # Get each color of image\r\n if opacity: # Whether opaque or not\r\n c1 = pixels[b1+A]\r\n c2 = pixels[b2+A]\r\n back = back or c1 <= threshold\r\n else: # Whether same color or not\r\n c1 = pixels[b1:b1+RGB]\r\n c2 = pixels[b2:b2+RGB]\r\n back = back or abs(c1[R] - c2[R]) + \\\r\n abs(c1[G] - c2[G]) \\\r\n + abs(c1[B] - c2[B]) <= threshold * 3.0\r\n if back:\r\n break\r\n if back:\r\n break\r\n backs[y][x] = back\r\n if not back:\r\n fronts.append((x//resolution, y//resolution))\r\n del e1, e2, b1, b2, c1, c2, back, pixels, p, left\r\n terms = []\r\n for k, f in enumerate(fronts):\r\n fx = f[X]\r\n fy = f[Y]\r\n x = fx * resolution\r\n y = fy * resolution\r\n left = backs[y][x-resolution]\r\n right = backs[y][x+resolution]\r\n back = backs[y-resolution][x]\r\n top = backs[y+resolution][x]\r\n if not backs[y][x] and (left or right or back or top):\r\n terms.append((fx, fy)) # Get edge\r\n fronts[k] = (fx, fy, left, right, back, top) # Insert edge info\r\n lens = [[0.0 for i in range(w)[::resolution]]\r\n for j in range(h)[::resolution]]\r\n if len(fronts) == 0:\r\n return {\"CANCELLED\"}\r\n sqAll = all ** 2\r\n xs = np.array([f[X] for f in fronts]) # X coordinate of each point\r\n ys = np.array([f[Y] for f in fronts]) # Y coordinate of each point\r\n ls = np.full(len(fronts), sqAll)\r\n for t in terms:\r\n ms = np.minimum(ls, np.power(t[X]-xs, 2) + np.power(t[Y] - ys, 2))\r\n ls = ms # Watershed algorithm\r\n ms = np.sqrt(ls) + 1\r\n m = np.max(ms)\r\n ls = np.divide(ms, m) # Nomalize\r\n ms = (np.sin(ls * np.pi * 0.5)+0)\r\n for k, f in enumerate(fronts):\r\n fx = f[X]\r\n fy = f[Y]\r\n ls = ms[k]/4.0 # Blur of height for edge\r\n lens[fy][fx] += ls\r\n fxi = fx+1\r\n fyi = fy+1\r\n lens[fy][fxi] += ls\r\n lens[fyi][fx] += ls\r\n lens[fyi][fxi] += ls\r\n del fx, fy, fxi, fyi, left, right, back, top, k, f, ms, ls, m\r\n verts = []\r\n nei = 1 # Neighbor\r\n uvs = []\r\n uvx = 0 / w\r\n uvy = 0 / h\r\n backs = []\r\n depth_front = context.window_manager.love2d3d.depth_front\r\n depth_back = context.window_manager.love2d3d.depth_back\r\n for f in fronts:\r\n x = f[X]\r\n y = f[Y]\r\n xi = x+nei\r\n yi = y+nei\r\n x1 = x * resolution\r\n x2 = xi * resolution\r\n y1 = y * resolution\r\n y2 = yi * resolution\r\n lu = x1/w\r\n ru = x2/w\r\n bu = y1/h\r\n tu = y2/h\r\n # Front face\r\n p1 = (x1, -lens[yi][x] * depth_front, y2)\r\n p2 = (x1, -lens[y][x] * depth_front, y1)\r\n p3 = (x2, -lens[y][xi] * depth_front, y1)\r\n p4 = (x2, -lens[yi][xi] * depth_front, y2)\r\n verts.extend([p1, p2, p3, p4])\r\n u1 = (lu + uvx, tu + uvy)\r\n u2 = (lu + uvx, bu + uvy)\r\n u3 = (ru + uvx, bu + uvy)\r\n u4 = (ru + uvx, tu + uvy)\r\n uvs.extend([u1, u2, u3, u4])\r\n backs.append(FRONT)\r\n # Back face\r\n p5 = (x2, lens[yi][xi] * depth_back, y2)\r\n p6 = (x2, lens[y][xi] * depth_back, y1)\r\n p7 = (x1, lens[y][x] * depth_back, y1)\r\n p8 = (x1, lens[yi][x] * depth_back, y2)\r\n verts.extend([p5, p6, p7, p8])\r\n uvs.extend([u4, u3, u2, u1])\r\n backs.append(BACK)\r\n if f[LEFT]: # Left face\r\n verts.extend([p8, p7, p2, p1])\r\n uvs.extend([u1,u2,u2,u1])\r\n backs.append(FRONT)\r\n if f[RIGHT]: # Right face\r\n verts.extend([p4,p3,p6,p5])\r\n uvs.extend([u4,u3,u3,u4])\r\n backs.append(FRONT)\r\n if f[TOP]: # Top face\r\n verts.extend([p8,p1,p4,p5])\r\n uvs.extend([u1,u1,u4,u4])\r\n backs.append(FRONT)\r\n if f[BOTTOM]: # Bottom face\r\n verts.extend([p2,p7,p6,p3])\r\n uvs.extend([u2,u2,u3,u3])\r\n backs.append(FRONT)\r\n del p1, p2, p3, p4, p5, p6, p7, p8, lens, nei, x, y\r\n del xi, yi, lu, ru, bu, tu, x1, x2, y1, y2\r\n del u1, u2, u3, u4\r\n faces = [(0, 0, 0, 0)] * (len(verts)//QUAD)\r\n for n, f in enumerate(faces):\r\n faces[n] = (QUAD * n, QUAD * n + 1, QUAD * n + 2, QUAD * n + 3)\r\n msh = bpy.data.meshes.new(NAME)\r\n msh.from_pydata(verts, [], faces) # Coordinate is Blender Coordinate\r\n msh.update()\r\n del verts, faces\r\n obj = bpy.data.objects.new(NAME, msh) # Create 3D object\r\n scene = bpy.context.scene\r\n scene.objects.link(obj)\r\n bpy.ops.object.select_all(action='DESELECT')\r\n if bpy.ops.object.mode_set.poll():\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n obj.select = True\r\n bpy.context.scene.objects.active = obj\r\n obj.location = (-w/2, 0, -h/2) # Translate to origin\r\n bpy.ops.object.transform_apply(location=True)\r\n scale = context.window_manager.love2d3d.scale\r\n obj.scale = (scale, scale, scale)\r\n bpy.ops.object.transform_apply(scale=True)\r\n channel_name = \"uv\"\r\n msh.uv_textures.new(channel_name) # Create UV coordinate\r\n for idx, dat in enumerate(msh.uv_layers[channel_name].data):\r\n dat.uv = uvs[idx]\r\n del uvs, scale\r\n # Crate fornt material\r\n matf = bpy.data.materials.new('Front')\r\n tex = bpy.data.textures.new('Front', type='IMAGE')\r\n tex.image = image\r\n matf.texture_slots.add()\r\n matf.texture_slots[0].texture = tex\r\n obj.data.materials.append(matf)\r\n # Crate back material\r\n matb = bpy.data.materials.new('Back')\r\n tex = bpy.data.textures.new('Back', type='IMAGE')\r\n image_back = context.window_manager.love2d3d.image_back\r\n if image_back == \"\":\r\n tex.image = image\r\n else:\r\n image_back = context.blend_data.images[image_back]\r\n tex.image = image_back\r\n matb.texture_slots.add()\r\n matb.texture_slots[0].texture = tex\r\n obj.data.materials.append(matb)\r\n for k, f in enumerate(obj.data.polygons):\r\n f.material_index = backs[k] # Set back material\r\n bpy.context.scene.objects.active = obj\r\n bpy.ops.object.mode_set(mode='EDIT') # Remove doubled point\r\n bpy.ops.mesh.remove_doubles()\r\n bpy.ops.object.mode_set(mode='OBJECT')\r\n bpy.context.scene.objects.active = obj # Apply modifiers\r\n bpy.ops.object.modifier_add(type='SMOOTH')\r\n smo = obj.modifiers[\"Smooth\"]\r\n smo.iterations = context.window_manager.love2d3d.smooth\r\n bpy.ops.object.modifier_add(type='DISPLACE')\r\n dis = obj.modifiers[\"Displace\"]\r\n dis.strength = context.window_manager.love2d3d.fat\r\n if context.window_manager.love2d3d.modifier:\r\n bpy.ops.object.modifier_apply(apply_as='DATA', modifier=\"Smooth\")\r\n bpy.ops.object.modifier_apply(apply_as='DATA', modifier=\"Displace\")\r\n obj.select = True\r\n bpy.ops.object.shade_smooth()\r\n return {'FINISHED'}\r\n\r\n\r\nclass VIEW3D_PT_love2d3d(bpy.types.Panel):\r\n\r\n bl_label = \"Love2D3D\"\r\n bl_space_type = 'VIEW_3D'\r\n bl_region_type = 'TOOLS'\r\n bl_category = \"Create\"\r\n bl_context = \"objectmode\"\r\n\r\n def draw(self, context):\r\n layout = self.layout\r\n col = layout.column(align=True)\r\n col.label(text=\"Object\", icon=\"OBJECT_DATA\")\r\n col.operator(CreateObject.bl_idname, text=\"Create\")\r\n col = layout.column(align=True)\r\n col.label(text=\"Image\", icon=\"IMAGE_DATA\")\r\n col.operator(\"image.open\", icon=\"FILESEL\")\r\n col.prop_search(context.window_manager.love2d3d,\r\n \"image_front\", context.blend_data, \"images\")\r\n col.prop_search(context.window_manager.love2d3d,\r\n \"image_back\", context.blend_data, \"images\")\r\n layout.separator()\r\n col = layout.column(align=True)\r\n col.label(text=\"Separation\", icon=\"IMAGE_RGB_ALPHA\")\r\n col.prop(context.window_manager.love2d3d, \"threshold\")\r\n col.prop(context.window_manager.love2d3d, \"opacity\")\r\n layout.separator()\r\n col = layout.column(align=True)\r\n col.label(text=\"Geometry\", icon=\"EDITMODE_HLT\")\r\n col.prop(context.window_manager.love2d3d, \"depth_front\")\r\n col.prop(context.window_manager.love2d3d, \"depth_back\")\r\n col.prop(context.window_manager.love2d3d, \"scale\")\r\n layout.separator()\r\n col = layout.column(align=True)\r\n col.label(text=\"Quality\", icon=\"MOD_SMOOTH\")\r\n col.prop(context.window_manager.love2d3d, \"rough\")\r\n col.prop(context.window_manager.love2d3d, \"smooth\")\r\n col.prop(context.window_manager.love2d3d, \"fat\")\r\n layout.separator()\r\n col = layout.column(align=True)\r\n col.label(text=\"Option\", icon=\"SCRIPTWIN\")\r\n col.prop(context.window_manager.love2d3d, \"modifier\")\r\n\r\n\r\nclass Love2D3DProps(bpy.types.PropertyGroup):\r\n image_front = bpy.props.StringProperty(name=\"Front Image\",\r\n description=\"Front image of mesh\")\r\n image_back = bpy.props.StringProperty(name=\"Back Image\",\r\n description=\"Back image of mesh\")\r\n rough = bpy.props.IntProperty(name=\"Rough\",\r\n description=\"Roughness of image\", min=1,\r\n default=8, subtype=\"PIXEL\")\r\n smooth = bpy.props.IntProperty(name=\"Smooth\",\r\n description=\"Smoothness of mesh\",\r\n min=1, default=30)\r\n scale = bpy.props.FloatProperty(name=\"Scale\",\r\n description=\"Length per pixel\",\r\n unit=\"LENGTH\", min=0.01, default=0.01)\r\n depth_front = bpy.props.FloatProperty(name=\"Front Depth\",\r\n description=\"Depth of front face\",\r\n unit=\"LENGTH\", min=0, default=40)\r\n depth_back = bpy.props.FloatProperty(name=\"Back Depth\",\r\n description=\"Depth of back face\",\r\n unit=\"LENGTH\", min=0, default=40)\r\n fat = bpy.props.FloatProperty(name=\"Fat\",\r\n description=\"Fat of mesh\",\r\n default=0.2, min=0.0)\r\n modifier = bpy.props.BoolProperty(name=\"Modifier\",\r\n description=\"Apply modifiers to object\",\r\n default=True)\r\n threshold = bpy.props.FloatProperty(name=\"Threshold\",\r\n description=\"Threshold of image\",\r\n min=0.0, max=1.0,\r\n default=0.0, subtype=\"FACTOR\")\r\n opacity = bpy.props.BoolProperty(name=\"Opacity\",\r\n description=\"Use Opacity for threshold\")\r\n\r\n\r\ndef register():\r\n bpy.utils.register_module(__name__)\r\n bpy.types.WindowManager.love2d3d \\\r\n = bpy.props.PointerProperty(type=Love2D3DProps)\r\n\r\n\r\ndef unregister():\r\n del bpy.types.WindowManager.love2d3d\r\n bpy.utils.unregister_module(__name__)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n register()\r\n","sub_path":"love2d3d.py","file_name":"love2d3d.py","file_ext":"py","file_size_in_byte":14847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"178385532","text":"# (0, 0), 90, 40\n# (60, -), (-, 60)\nfrom icecream import ic\n\n\ndef successors(x, y, X, Y):\n return {\n (0, y): \"倒空x\",\n (x, 0): \"倒空y\",\n (x+y-Y, Y) if x+y>=Y else (0, x+y): \"x倒入y中\",\n (X, x+y-X) if x+y>=X else (x+y, 0): \"y倒入x中\",\n (X, y): \"��满x\",\n (x, Y): \"装满y\",\n }\n\ndef search_solution(capacity1, capacity2, goal, start=(0, 0)):\n paths = [[('init', start)]]\n\n explored = set() # 防止重复\n\n while paths:\n path = paths.pop(0)\n frontier = path[-1]\n (x, y) = frontier[-1]\n\n for state, action in successors(x, y, capacity1, capacity2).items():\n # ic(frontier, state, action)\n if state in explored: continue\n\n new_path = path + [(action, state)]\n # ic(new_path)\n\n if goal in state:\n return new_path\n else:\n paths.append(new_path)\n\n explored.add(state)\n return None\n\n\n\nif __name__ == '__main__':\n path = search_solution(90, 40, 60, (0, 0))\n\n for p in path:\n print(\"=>\")\n print(p)\n\n","sub_path":"Machine_Learning_and_ai/1/water_pouring.py","file_name":"water_pouring.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"591333738","text":"# ____ ___ _ ___ ____ __\n# / ___/ _ \\| \\ | \\ \\ / /\\ \\/ /\n# | | | | | | \\| |\\ V / \\ /\n# | |__| |_| | |\\ | | | / \\\n# \\____\\___/|_| \\_| |_| /_/\\_\\\n#\n# Console Nyx Client\n#\n# Conyx Text User Interface Main Menu Library\n#\n# version 0.1.6\n#\n# You can do whatever You want with Conyx.\n# But I don't take reponsbility nor even\n# implied responsibility for the harm,\n# damage, loss or anything negative\n# You cause using Conyx.\n#\n# There is no service provided. The program\n# is AS-IS and there is ABSOLUTELY no warranty\n# provided.\n#\n# encoding=utf-8\n\nimport sys, os, traceback\nreload(sys)\nsys.setdefaultencoding('utf8')\nsys.path.insert(0, (os.environ['CONYX']+'/lib'))\nfrom math import *\nimport curses\nfrom conyxDBQuery import conyxDBQuery\nimport locale\nimport sys\nimport re\nfrom conyxOps import *\nfrom tuiBuffer import * \n\nactual_char='>'\nheight=0\nwidth=0\n\n# BUGS\n# ukazuje i mimo posledni prvek\ndef tuiMainMenu(typ_klubu=0):\n strings=[]\n screen = curses.initscr()\n curses.noecho()\n curses.cbreak()\n curses.start_color()\n screen.keypad(1)\n curses.init_pair(1,curses.COLOR_BLACK,curses.COLOR_CYAN)\n global width\n global height\n height,width=screen.getmaxyx()\n #nr,buf=nyx_list_disc(\"\",0)\n #screen.addstr(1,1,\"Stazeno \" + str(nr) + \" zahlavi klubu.\")\n #screen.getch()\n last_pos=1\n last_page=1\n encoding = locale.getpreferredencoding()\n locale.setlocale(locale.LC_ALL, '')\n #screen.getch()\n x=\"\"\n try:\n if typ_klubu==1:\n cols,rows=conyxDBQuery(\"select id_klub, jmeno||'|'||unread||'|'||replies txt from klub_cache where unread != '0' order by jmeno asc\")\n elif typ_klubu==2:\n cols,rows=conyxDBQuery(\"select id_klub, jmeno||'|'||unread||'|'||replies txt from klub_cache where unread != '0' and replies != '0' order by jmeno asc\")\n else:\n cols,rows=conyxDBQuery(\"select id_klub, jmeno||'|'||unread||'|'||replies txt from klub_cache order by jmeno asc\")\n strings=[]\n refs=[]\n ret=0\n for i in rows:\n strings.append(cleanHtml(i[1].replace('\\n','')))\n refs.append(i[0])\n row_num=len(strings)\n if last_pos!=0 and row_num>0:\n tmp=[] \n for i in strings:\n tmp.append(i[:width-10])\n strings=tmp\n highlightText=curses.color_pair(1)\n normalText=curses.A_NORMAL\n max_row=height-2\n box=curses.newwin(height+1,width+1,0,0)\n pages=int(ceil(row_num/max_row))\n position=last_pos \n page=last_page\n for i in range(1+(max_row*(page-1)),max_row+1+(max_row*(page-1))):\n if (i+(max_row*(page-1))==position+(max_row*(page-1))):\n box.addstr(i-(max_row*(page-1)),2,actual_char+\" \"+cleanHtml(strings[i-1]), highlightText)\n else:\n box.addstr(i-(max_row*(page-1)),2,\" \"+cleanHtml(strings[i-1]),normalText)\n if i==row_num:\n break;\n\n screen.refresh()\n box.refresh()\n \n while x != ord('q'): # dokud neni stisknuta klavesa 'q'\n ret=0\n if x==curses.KEY_DOWN and position < row_num: \n if position 1:\n if position>1+(max_row*(page-1)):\n position=position-1\n else:\n page=page-1\n position=max_row+(max_row*(page-1))\n if x == curses.KEY_LEFT:\n if page > 1:\n page=page-1\n position=1+(max_row*(page-1))\n if x == curses.KEY_RIGHT:\n if page<=pages: \n page=page+1\n position=1+(max_row*(page-1))\n if x == ord( \"\\n\" ) and row_num != 0:\n screen.erase()\n ret=refs[position-1] \n \n box.erase()\n \n for i in range(1+(max_row*(page-1)),max_row+1+(max_row*(page-1))):\n if row_num == 0:\n box.addstr(1,1,\"Zadna data.\",highlightText)\n else:\n if (i+(max_row*(page-1))==position+(max_row*(page-1))):\n box.addstr(i-(max_row*(page-1)),2,actual_char+\" \"+cleanHtml(strings[i-1]), highlightText)\n else:\n box.addstr(i-(max_row*(page-1)),2,\" \"+cleanHtml(strings[i-1]),normalText)\n if i==row_num:\n break;\n\n box.addstr(height-1,0,\"pos \" + str(position) + \" page \" + str(page) + \" mr \" + str(max_row) + \" row_num \" + str(row_num))\n\n if ret!=0:\n #screen.getch()\n buf=nyx_show_disc_msgs(str(ret))\n cols, rows = conyxDBQuery('select prisp_from || \"|\" || prisp_text || \"|\" || prisp_hodnoceni wu_rating from prispevek_cache')\n buffer=[]\n for i in rows:\n buffer.append(i[0])\n if len(rows)>0:\n klub_name=getKlubNameFromID(ret)[:width-10]\n tuiBuffer(klub_name,buffer)\n screen.refresh()\n box.refresh()\n x = screen.getch()\n else:\n screen.addstr(0,0,\"Nemas zadne neprectene kluby.\")\n screen.getch()\n curses.endwin()\n except Exception:\n curses.endwin()\n traceback.print_exc(file=sys.stdout)\n print(\"Problem s textovym uzivatelskym rozhranim\")\n #exit()\n#\n#tuiMainMenu()\n","sub_path":"lib/tuiMainMenu.py","file_name":"tuiMainMenu.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"559340817","text":"__package_name__ = 'tfhelpers'\n__version__ = '0.0.1'\n__description__ = 'Tensorflow Helpers'\n__url__ = 'https://github.com/kingspp/tfhelpers'\n__author__ = 'Prathyush SP'\n__author_email__ = 'kingspprathyush gmail(dot) com'\n__licence__ = 'MIT'\n__keywords__ = 'tensorflow deeplearning dl tf'\n__required_packages__ = ['tensorflow','pandas', 'numpy', 'jsonpickle', 'sphinx']\n\n","sub_path":"tfhelpers/__metadata__.py","file_name":"__metadata__.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"32210338","text":"\"\"\"Functions for converting between color spaces.\n\nThe \"central\" color space in this module is RGB, more specifically the linear\nsRGB color space using D65 as a white-point [1]_. This represents a\nstandard monitor (w/o gamma correction). For a good FAQ on color spaces see\n[2]_.\n\nThe API consists of functions to convert to and from RGB as defined above, as\nwell as a generic function to convert to and from any supported color space\n(which is done through RGB in most cases).\n\n\nSupported color spaces\n----------------------\n* RGB : Red Green Blue.\n Here the sRGB standard [1]_.\n* HSV : Hue, Saturation, Value.\n Uniquely defined when related to sRGB [3]_.\n* RGB CIE : Red Green Blue.\n The original RGB CIE standard from 1931 [4]_. Primary colors are 700 nm\n (red), 546.1 nm (blue) and 435.8 nm (green).\n* XYZ CIE : XYZ\n Derived from the RGB CIE color space. Chosen such that\n ``x == y == z == 1/3`` at the whitepoint, and all color matching\n functions are greater than zero everywhere.\n* LAB CIE : Lightness, a, b\n Colorspace derived from XYZ CIE that is intended to be more\n perceptually uniform\n* LUV CIE : Lightness, u, v\n Colorspace derived from XYZ CIE that is intended to be more\n perceptually uniform\n* LCH CIE : Lightness, Chroma, Hue\n Defined in terms of LAB CIE. C and H are the polar representation of\n a and b. The polar angle C is defined to be on ``(0, 2*pi)``\n\n:author: Nicolas Pinto (rgb2hsv)\n:author: Ralf Gommers (hsv2rgb)\n:author: Travis Oliphant (XYZ and RGB CIE functions)\n:author: Matt Terry (lab2lch)\n:author: Alex Izvorski (yuv2rgb, rgb2yuv and related)\n\n:license: modified BSD\n\nReferences\n----------\n.. [1] Official specification of sRGB, IEC 61966-2-1:1999.\n.. [2] http://www.poynton.com/ColorFAQ.html\n.. [3] https://en.wikipedia.org/wiki/HSL_and_HSV\n.. [4] https://en.wikipedia.org/wiki/CIE_1931_color_space\n\"\"\"\n\n\nimport numpy as np\nfrom scipy import linalg\n\n\ndef guess_spatial_dimensions(image):\n \"\"\"Make an educated guess about whether an image has a channels dimension.\n\n Parameters\n ----------\n image : ndarray\n The input image.\n\n Returns\n -------\n spatial_dims : int or None\n The number of spatial dimensions of `image`. If ambiguous, the value\n is ``None``.\n\n Raises\n ------\n ValueError\n If the image array has less than two or more than four dimensions.\n \"\"\"\n if image.ndim == 2:\n return 2\n if image.ndim == 3 and image.shape[-1] != 3:\n return 3\n if image.ndim == 3 and image.shape[-1] == 3:\n return None\n if image.ndim == 4 and image.shape[-1] == 3:\n return 3\n else:\n raise ValueError(\"Expected 2D, 3D, or 4D array, got %iD.\" % image.ndim)\n\n\ndef _prepare_colorarray(arr):\n \"\"\"Check the shape of the array and convert it to\n floating point representation.\n \"\"\"\n arr = np.asanyarray(arr)\n\n if arr.shape[-1] != 3:\n msg = (\"the input array must be have a shape == ([ ..,] 3)), \" +\n \"got (\" + (\", \".join(map(str, arr.shape))) + \")\")\n raise ValueError(msg)\n\n return arr.astype(float)\n\n\ndef _prepare_rgba_array(arr):\n \"\"\"Check the shape of the array to be RGBA and convert it to\n floating point representation.\n \"\"\"\n arr = np.asanyarray(arr)\n\n if arr.shape[-1] != 4:\n msg = (\"the input array must have a shape == ([ ..,] 4)), \"\n \"got {0}\".format(arr.shape))\n raise ValueError(msg)\n\n return arr.astype(float)\n\n\ndef rgba2rgb(rgba, background=(1, 1, 1)):\n \"\"\"RGBA to RGB conversion.\n\n Parameters\n ----------\n rgba : array_like\n The image in RGBA format, in a 3-D array of shape ``(.., .., 4)``.\n background : array_like\n The color of the background to blend the image with. A tuple\n containing 3 floats between 0 to 1 - the RGB value of the background.\n\n Returns\n -------\n out : ndarray\n The image in RGB format, in a 3-D array of shape ``(.., .., 3)``.\n\n Raises\n ------\n ValueError\n If `rgba` is not a 3-D array of shape ``(.., .., 4)``.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending\n\n Examples\n --------\n >>> from skimage import color\n >>> from skimage import data\n >>> img_rgba = data.logo()\n >>> img_rgb = color.rgba2rgb(img_rgba)\n \"\"\"\n arr = _prepare_rgba_array(rgba)\n if isinstance(background, tuple) and len(background) != 3:\n raise ValueError('the background must be a tuple with 3 items - the '\n 'RGB color of the background. Got {0} items.'\n .format(len(background)))\n\n alpha = arr[..., -1]\n channels = arr[..., :-1]\n out = np.empty_like(channels)\n\n for ichan in range(channels.shape[-1]):\n out[..., ichan] = np.clip(\n (1 - alpha) * background[ichan] + alpha * channels[..., ichan],\n a_min=0, a_max=1)\n return out\n\n\ndef rgb2hsv(rgb):\n \"\"\"RGB to HSV color space conversion.\n\n Parameters\n ----------\n rgb : array_like\n The image in RGB format, in a 3-D array of shape ``(.., .., 3)``.\n\n Returns\n -------\n out : ndarray\n The image in HSV format, in a 3-D array of shape ``(.., .., 3)``.\n\n Raises\n ------\n ValueError\n If `rgb` is not a 3-D array of shape ``(.., .., 3)``.\n\n Notes\n -----\n Conversion between RGB and HSV color spaces results in some loss of\n precision, due to integer arithmetic and rounding [1]_.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/HSL_and_HSV\n\n Examples\n --------\n >>> from skimage import color\n >>> from skimage import data\n >>> img = data.astronaut()\n >>> img_hsv = color.rgb2hsv(img)\n \"\"\"\n arr = _prepare_colorarray(rgb)\n out = np.empty_like(arr)\n\n # -- V channel\n out_v = arr.max(-1)\n\n # -- S channel\n delta = arr.ptp(-1)\n # Ignore warning for zero divided by zero\n old_settings = np.seterr(invalid='ignore')\n out_s = delta / out_v\n out_s[delta == 0.] = 0.\n\n # -- H channel\n # red is max\n idx = (arr[:, :, 0] == out_v)\n out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]\n\n # green is max\n idx = (arr[:, :, 1] == out_v)\n out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]\n\n # blue is max\n idx = (arr[:, :, 2] == out_v)\n out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]\n out_h = (out[:, :, 0] / 6.) % 1.\n out_h[delta == 0.] = 0.\n\n np.seterr(**old_settings)\n\n # -- output\n out[:, :, 0] = out_h\n out[:, :, 1] = out_s\n out[:, :, 2] = out_v\n\n # remove NaN\n out[np.isnan(out)] = 0\n\n return out\n\n\ndef hsv2rgb(hsv):\n \"\"\"HSV to RGB color space conversion.\n\n Parameters\n ----------\n hsv : array_like\n The image in HSV format, in a 3-D array of shape ``(.., .., 3)``.\n\n Returns\n -------\n out : ndarray\n The image in RGB format, in a 3-D array of shape ``(.., .., 3)``.\n\n Raises\n ------\n ValueError\n If `hsv` is not a 3-D array of shape ``(.., .., 3)``.\n\n Notes\n -----\n Conversion between RGB and HSV color spaces results in some loss of\n precision, due to integer arithmetic and rounding [1]_.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/HSL_and_HSV\n\n Examples\n --------\n >>> from skimage import data\n >>> img = data.astronaut()\n >>> img_hsv = rgb2hsv(img)\n >>> img_rgb = hsv2rgb(img_hsv)\n \"\"\"\n arr = _prepare_colorarray(hsv)\n\n hi = np.floor(arr[:, :, 0] * 6)\n f = arr[:, :, 0] * 6 - hi\n p = arr[:, :, 2] * (1 - arr[:, :, 1])\n q = arr[:, :, 2] * (1 - f * arr[:, :, 1])\n t = arr[:, :, 2] * (1 - (1 - f) * arr[:, :, 1])\n v = arr[:, :, 2]\n\n hi = np.dstack([hi, hi, hi]).astype(np.uint8) % 6\n out = np.choose(hi, [np.dstack((v, t, p)),\n np.dstack((q, v, p)),\n np.dstack((p, v, t)),\n np.dstack((p, q, v)),\n np.dstack((t, p, v)),\n np.dstack((v, p, q))])\n\n return out\n\n\n# ---------------------------------------------------------------\n# Primaries for the coordinate systems\n# ---------------------------------------------------------------\ncie_primaries = np.array([700, 546.1, 435.8])\nsb_primaries = np.array([1. / 155, 1. / 190, 1. / 225]) * 1e5\n\n# ---------------------------------------------------------------\n# Matrices that define conversion between different color spaces\n# ---------------------------------------------------------------\n\n# From sRGB specification\nxyz_from_rgb = np.array([[0.412453, 0.357580, 0.180423],\n [0.212671, 0.715160, 0.072169],\n [0.019334, 0.119193, 0.950227]])\n\nrgb_from_xyz = linalg.inv(xyz_from_rgb)\n\n# From https://en.wikipedia.org/wiki/CIE_1931_color_space\n# Note: Travis's code did not have the divide by 0.17697\nxyz_from_rgbcie = np.array([[0.49, 0.31, 0.20],\n [0.17697, 0.81240, 0.01063],\n [0.00, 0.01, 0.99]]) / 0.17697\n\nrgbcie_from_xyz = linalg.inv(xyz_from_rgbcie)\n\n# construct matrices to and from rgb:\nrgbcie_from_rgb = rgbcie_from_xyz @ xyz_from_rgb\nrgb_from_rgbcie = rgb_from_xyz @ xyz_from_rgbcie\n\n\ngray_from_rgb = np.array([[0.2125, 0.7154, 0.0721],\n [0, 0, 0],\n [0, 0, 0]])\n\nyuv_from_rgb = np.array([[ 0.299 , 0.587 , 0.114 ],\n [-0.14714119, -0.28886916, 0.43601035 ],\n [ 0.61497538, -0.51496512, -0.10001026 ]])\n\nrgb_from_yuv = linalg.inv(yuv_from_rgb)\n\n\n# CIE LAB constants for Observer=2A, Illuminant=D65\n# NOTE: this is actually the XYZ values for the illuminant above.\nlab_ref_white = np.array([0.95047, 1., 1.08883])\n\n# XYZ coordinates of the illuminants, scaled to [0, 1]. For each illuminant I\n# we have:\n#\n# illuminant[I][0] corresponds to the XYZ coordinates for the 2 degree\n# field of view.\n#\n# illuminant[I][1] corresponds to the XYZ coordinates for the 10 degree\n# field of view.\n#\n# The XYZ coordinates are calculated from [1], using the formula:\n#\n# X = x * ( Y / y )\n# Y = Y\n# Z = ( 1 - x - y ) * ( Y / y )\n#\n# where Y = 1. The only exception is the illuminant \"D65\" with aperture angle\n# 2, whose coordinates are copied from 'lab_ref_white' for\n# backward-compatibility reasons.\n#\n# References\n# ----------\n# .. [1] https://en.wikipedia.org/wiki/Standard_illuminant\n\nilluminants = \\\n {\"A\": {'2': (1.098466069456375, 1, 0.3558228003436005),\n '10': (1.111420406956693, 1, 0.3519978321919493)},\n \"D50\": {'2': (0.9642119944211994, 1, 0.8251882845188288),\n '10': (0.9672062750333777, 1, 0.8142801513128616)},\n \"D55\": {'2': (0.956797052643698, 1, 0.9214805860173273),\n '10': (0.9579665682254781, 1, 0.9092525159847462)},\n \"D65\": {'2': (0.95047, 1., 1.08883), # This was: `lab_ref_white`\n '10': (0.94809667673716, 1, 1.0730513595166162)},\n \"D75\": {'2': (0.9497220898840717, 1, 1.226393520724154),\n '10': (0.9441713925645873, 1, 1.2064272211720228)},\n \"E\": {'2': (1.0, 1.0, 1.0),\n '10': (1.0, 1.0, 1.0)}}\n\n\ndef get_xyz_coords(illuminant, observer):\n \"\"\"Get the XYZ coordinates of the given illuminant and observer [1]_.\n\n Parameters\n ----------\n illuminant : {\"A\", \"D50\", \"D55\", \"D65\", \"D75\", \"E\"}, optional\n The name of the illuminant (the function is NOT case sensitive).\n observer : {\"2\", \"10\"}, optional\n The aperture angle of the observer.\n\n Returns\n -------\n (x, y, z) : tuple\n A tuple with 3 elements containing the XYZ coordinates of the given\n illuminant.\n\n Raises\n ------\n ValueError\n If either the illuminant or the observer angle are not supported or\n unknown.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/Standard_illuminant\n\n \"\"\"\n illuminant = illuminant.upper()\n try:\n return illuminants[illuminant][observer]\n except KeyError:\n raise ValueError(\"Unknown illuminant/observer combination\\\n (\\'{0}\\', \\'{1}\\')\".format(illuminant, observer))\n\n# -------------------------------------------------------------\n# The conversion functions that make use of the matrices above\n# -------------------------------------------------------------\n\n\ndef _convert(matrix, arr):\n \"\"\"Do the color space conversion.\n\n Parameters\n ----------\n matrix : array_like\n The 3x3 matrix to use.\n arr : array_like\n The input array.\n\n Returns\n -------\n out : ndarray, dtype=float\n The converted array.\n \"\"\"\n arr = _prepare_colorarray(arr)\n\n return arr @ matrix.T.copy()\n\n\ndef xyz2rgb(xyz):\n \"\"\"XYZ to RGB color space conversion.\n\n Parameters\n ----------\n xyz : array_like\n The image in XYZ format, in a 3-D array of shape ``(.., .., 3)``.\n\n Returns\n -------\n out : ndarray\n The image in RGB format, in a 3-D array of shape ``(.., .., 3)``.\n\n Raises\n ------\n ValueError\n If `xyz` is not a 3-D array of shape ``(.., .., 3)``.\n\n Notes\n -----\n The CIE XYZ color space is derived from the CIE RGB color space. Note\n however that this function converts to sRGB.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space\n\n Examples\n --------\n >>> from skimage import data\n >>> from skimage.color import rgb2xyz, xyz2rgb\n >>> img = data.astronaut()\n >>> img_xyz = rgb2xyz(img)\n >>> img_rgb = xyz2rgb(img_xyz)\n \"\"\"\n # Follow the algorithm from http://www.easyrgb.com/index.php\n # except we don't multiply/divide by 100 in the conversion\n arr = _convert(rgb_from_xyz, xyz)\n mask = arr > 0.0031308\n arr[mask] = 1.055 * np.power(arr[mask], 1 / 2.4) - 0.055\n arr[~mask] *= 12.92\n return arr\n\n\ndef rgb2xyz(rgb):\n \"\"\"RGB to XYZ color space conversion.\n\n Parameters\n ----------\n rgb : array_like\n The image in RGB format, in a 3- or 4-D array of shape\n ``(.., ..,[ ..,] 3)``.\n\n Returns\n -------\n out : ndarray\n The image in XYZ format, in a 3- or 4-D array of shape\n ``(.., ..,[ ..,] 3)``.\n\n Raises\n ------\n ValueError\n If `rgb` is not a 3- or 4-D array of shape ``(.., ..,[ ..,] 3)``.\n\n Notes\n -----\n The CIE XYZ color space is derived from the CIE RGB color space. Note\n however that this function converts from sRGB.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space\n\n Examples\n --------\n >>> from skimage import data\n >>> img = data.astronaut()\n >>> img_xyz = rgb2xyz(img)\n \"\"\"\n # Follow the algorithm from http://www.easyrgb.com/index.php\n # except we don't multiply/divide by 100 in the conversion\n arr = _prepare_colorarray(rgb).copy()\n mask = arr > 0.04045\n arr[mask] = np.power((arr[mask] + 0.055) / 1.055, 2.4)\n arr[~mask] /= 12.92\n return _convert(xyz_from_rgb, arr)\n\n\ndef rgb2rgbcie(rgb):\n \"\"\"RGB to RGB CIE color space conversion.\n\n Parameters\n ----------\n rgb : array_like\n The image in RGB format, in a 3-D array of shape ``(.., .., 3)``.\n\n Returns\n -------\n out : ndarray\n The image in RGB CIE format, in a 3-D array of shape ``(.., .., 3)``.\n\n Raises\n ------\n ValueError\n If `rgb` is not a 3-D array of shape ``(.., .., 3)``.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space\n\n Examples\n --------\n >>> from skimage import data\n >>> from skimage.color import rgb2rgbcie\n >>> img = data.astronaut()\n >>> img_rgbcie = rgb2rgbcie(img)\n \"\"\"\n return _convert(rgbcie_from_rgb, rgb)\n\n\ndef rgbcie2rgb(rgbcie):\n \"\"\"RGB CIE to RGB color space conversion.\n\n Parameters\n ----------\n rgbcie : array_like\n The image in RGB CIE format, in a 3-D array of shape ``(.., .., 3)``.\n\n Returns\n -------\n out : ndarray\n The image in RGB format, in a 3-D array of shape ``(.., .., 3)``.\n\n Raises\n ------\n ValueError\n If `rgbcie` is not a 3-D array of shape ``(.., .., 3)``.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space\n\n Examples\n --------\n >>> from skimage import data\n >>> from skimage.color import rgb2rgbcie, rgbcie2rgb\n >>> img = data.astronaut()\n >>> img_rgbcie = rgb2rgbcie(img)\n >>> img_rgb = rgbcie2rgb(img_rgbcie)\n \"\"\"\n return _convert(rgb_from_rgbcie, rgbcie)\n\n\ndef rgb2gray(rgb):\n \"\"\"Compute luminance of an RGB image.\n\n Parameters\n ----------\n rgb : array_like\n The image in RGB format, in a 3-D or 4-D array of shape\n ``(.., ..,[ ..,] 3)``, or in RGBA format with shape\n ``(.., ..,[ ..,] 4)``.\n\n Returns\n -------\n out : ndarray\n The luminance image - an array which is the same size as the input\n array, but with the channel dimension removed.\n\n Raises\n ------\n ValueError\n If `rgb2gray` is not a 3-D or 4-D arrays of shape\n ``(.., ..,[ ..,] 3)`` or ``(.., ..,[ ..,] 4)``.\n\n Notes\n -----\n The weights used in this conversion are calibrated for contemporary\n CRT phosphors::\n\n Y = 0.2125 R + 0.7154 G + 0.0721 B\n\n If there is an alpha channel present, it is ignored.\n\n References\n ----------\n .. [1] http://www.poynton.com/PDFs/ColorFAQ.pdf\n\n Examples\n --------\n >>> from skimage.color import rgb2gray\n >>> from skimage import data\n >>> img = data.astronaut()\n >>> img_gray = rgb2gray(img)\n \"\"\"\n\n if rgb.ndim == 2:\n return np.ascontiguousarray(rgb)\n\n rgb = _prepare_colorarray(rgb[..., :3])\n coeffs = np.array([0.2125, 0.7154, 0.0721], dtype=rgb.dtype)\n return rgb @ coeffs\n\n\nrgb2grey = rgb2gray\n\n\ndef xyz2lab(xyz, illuminant=\"D65\", observer=\"2\"):\n \"\"\"XYZ to CIE-LAB color space conversion.\n\n Parameters\n ----------\n xyz : array_like\n The image in XYZ format, in a 3- or 4-D array of shape\n ``(.., ..,[ ..,] 3)``.\n illuminant : {\"A\", \"D50\", \"D55\", \"D65\", \"D75\", \"E\"}, optional\n The name of the illuminant (the function is NOT case sensitive).\n observer : {\"2\", \"10\"}, optional\n The aperture angle of the observer.\n\n Returns\n -------\n out : ndarray\n The image in CIE-LAB format, in a 3- or 4-D array of shape\n ``(.., ..,[ ..,] 3)``.\n\n Raises\n ------\n ValueError\n If `xyz` is not a 3-D array of shape ``(.., ..,[ ..,] 3)``.\n ValueError\n If either the illuminant or the observer angle is unsupported or\n unknown.\n\n Notes\n -----\n By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values\n x_ref=95.047, y_ref=100., z_ref=108.883. See function `get_xyz_coords` for\n a list of supported illuminants.\n\n References\n ----------\n .. [1] http://www.easyrgb.com/index.php?X=MATH&H=07#text7\n .. [2] https://en.wikipedia.org/wiki/Lab_color_space\n\n Examples\n --------\n >>> from skimage import data\n >>> from skimage.color import rgb2xyz, xyz2lab\n >>> img = data.astronaut()\n >>> img_xyz = rgb2xyz(img)\n >>> img_lab = xyz2lab(img_xyz)\n \"\"\"\n arr = _prepare_colorarray(xyz)\n\n xyz_ref_white = get_xyz_coords(illuminant, observer)\n\n # scale by CIE XYZ tristimulus values of the reference white point\n arr = arr / xyz_ref_white\n\n # Nonlinear distortion and linear transformation\n mask = arr > 0.008856\n arr[mask] = np.cbrt(arr[mask])\n arr[~mask] = 7.787 * arr[~mask] + 16. / 116.\n\n x, y, z = arr[..., 0], arr[..., 1], arr[..., 2]\n\n # Vector scaling\n L = (116. * y) - 16.\n a = 500.0 * (x - y)\n b = 200.0 * (y - z)\n\n return np.concatenate([x[..., np.newaxis] for x in [L, a, b]], axis=-1)\n\n\ndef lab2xyz(lab, illuminant=\"D65\", observer=\"2\"):\n \"\"\"CIE-LAB to XYZcolor space conversion.\n\n Parameters\n ----------\n lab : array_like\n The image in lab format, in a 3-D array of shape ``(.., .., 3)``.\n illuminant : {\"A\", \"D50\", \"D55\", \"D65\", \"D75\", \"E\"}, optional\n The name of the illuminant (the function is NOT case sensitive).\n observer : {\"2\", \"10\"}, optional\n The aperture angle of the observer.\n\n Returns\n -------\n out : ndarray\n The image in XYZ format, in a 3-D array of shape ``(.., .., 3)``.\n\n Raises\n ------\n ValueError\n If `lab` is not a 3-D array of shape ``(.., .., 3)``.\n ValueError\n If either the illuminant or the observer angle are not supported or\n unknown.\n UserWarning\n If any of the pixels are invalid (Z < 0).\n\n Notes\n -----\n By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x_ref\n = 95.047, y_ref = 100., z_ref = 108.883. See function 'get_xyz_coords' for\n a list of supported illuminants.\n\n References\n ----------\n .. [1] http://www.easyrgb.com/index.php?X=MATH&H=07#text7\n .. [2] https://en.wikipedia.org/wiki/Lab_color_space\n\n \"\"\"\n\n arr = _prepare_colorarray(lab).copy()\n\n L, a, b = arr[..., 0], arr[..., 1], arr[..., 2]\n y = (L + 16.) / 116.\n x = (a / 500.) + y\n z = y - (b / 200.)\n\n out = np.stack([x, y, z], axis=-1)\n\n mask = out > 0.2068966\n out[mask] = np.power(out[mask], 3.)\n out[~mask] = (out[~mask] - 16.0 / 116.) / 7.787\n\n # rescale to the reference white (illuminant)\n xyz_ref_white = get_xyz_coords(illuminant, observer)\n out *= xyz_ref_white\n return out\n\n\ndef rgb2lab(rgb, illuminant=\"D65\", observer=\"2\"):\n \"\"\"RGB to lab color space conversion.\n\n Parameters\n ----------\n rgb : array_like\n The image in RGB format, in a 3- or 4-D array of shape\n ``(.., ..,[ ..,] 3)``.\n illuminant : {\"A\", \"D50\", \"D55\", \"D65\", \"D75\", \"E\"}, optional\n The name of the illuminant (the function is NOT case sensitive).\n observer : {\"2\", \"10\"}, optional\n The aperture angle of the observer.\n\n Returns\n -------\n out : ndarray\n The image in Lab format, in a 3- or 4-D array of shape\n ``(.., ..,[ ..,] 3)``.\n\n Raises\n ------\n ValueError\n If `rgb` is not a 3- or 4-D array of shape ``(.., ..,[ ..,] 3)``.\n\n Notes\n -----\n This function uses rgb2xyz and xyz2lab.\n By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values\n x_ref=95.047, y_ref=100., z_ref=108.883. See function `get_xyz_coords` for\n a list of supported illuminants.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/Standard_illuminant\n \"\"\"\n return xyz2lab(rgb2xyz(rgb), illuminant, observer)\n\n\ndef lab2rgb(lab, illuminant=\"D65\", observer=\"2\"):\n \"\"\"Lab to RGB color space conversion.\n\n Parameters\n ----------\n lab : array_like\n The image in Lab format, in a 3-D array of shape ``(.., .., 3)``.\n illuminant : {\"A\", \"D50\", \"D55\", \"D65\", \"D75\", \"E\"}, optional\n The name of the illuminant (the function is NOT case sensitive).\n observer : {\"2\", \"10\"}, optional\n The aperture angle of the observer.\n\n Returns\n -------\n out : ndarray\n The image in RGB format, in a 3-D array of shape ``(.., .., 3)``.\n\n Raises\n ------\n ValueError\n If `lab` is not a 3-D array of shape ``(.., .., 3)``.\n\n Notes\n -----\n This function uses lab2xyz and xyz2rgb.\n By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values\n x_ref=95.047, y_ref=100., z_ref=108.883. See function `get_xyz_coords` for\n a list of supported illuminants.\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/Standard_illuminant\n \"\"\"\n return xyz2rgb(lab2xyz(lab, illuminant, observer))\n\n\ndef xyz2luv(xyz, illuminant=\"D65\", observer=\"2\"):\n \"\"\"XYZ to CIE-Luv color space conversion.\n\n Parameters\n ----------\n xyz : (M, N, [P,] 3) array_like\n The 3 or 4 dimensional image in XYZ format. Final dimension denotes\n channels.\n illuminant : {\"A\", \"D50\", \"D55\", \"D65\", \"D75\", \"E\"}, optional\n The name of the illuminant (the function is NOT case sensitive).\n observer : {\"2\", \"10\"}, optional\n The aperture angle of the observer.\n\n Returns\n -------\n out : (M, N, [P,] 3) ndarray\n The image in CIE-Luv format. Same dimensions as input.\n\n Raises\n ------\n ValueError\n If `xyz` is not a 3-D or 4-D array of shape ``(M, N, [P,] 3)``.\n ValueError\n If either the illuminant or the observer angle are not supported or\n unknown.\n\n Notes\n -----\n By default XYZ conversion weights use observer=2A. Reference whitepoint\n for D65 Illuminant, with XYZ tristimulus values of ``(95.047, 100.,\n 108.883)``. See function 'get_xyz_coords' for a list of supported\n illuminants.\n\n References\n ----------\n .. [1] http://www.easyrgb.com/index.php?X=MATH&H=16#text16\n .. [2] https://en.wikipedia.org/wiki/CIELUV\n\n Examples\n --------\n >>> from skimage import data\n >>> from skimage.color import rgb2xyz, xyz2luv\n >>> img = data.astronaut()\n >>> img_xyz = rgb2xyz(img)\n >>> img_luv = xyz2luv(img_xyz)\n \"\"\"\n arr = _prepare_colorarray(xyz)\n\n # extract channels\n x, y, z = arr[..., 0], arr[..., 1], arr[..., 2]\n\n eps = np.finfo(np.float).eps\n\n # compute y_r and L\n xyz_ref_white = np.array(get_xyz_coords(illuminant, observer))\n L = y / xyz_ref_white[1]\n mask = L > 0.008856\n L[mask] = 116. * np.cbrt(L[mask]) - 16.\n L[~mask] = 903.3 * L[~mask]\n\n u0 = 4 * xyz_ref_white[0] / ([1, 15, 3] @ xyz_ref_white)\n v0 = 9 * xyz_ref_white[1] / ([1, 15, 3] @ xyz_ref_white)\n\n # u' and v' helper functions\n def fu(X, Y, Z):\n return (4. * X) / (X + 15. * Y + 3. * Z + eps)\n\n def fv(X, Y, Z):\n return (9. * Y) / (X + 15. * Y + 3. * Z + eps)\n\n # compute u and v using helper functions\n u = 13. * L * (fu(x, y, z) - u0)\n v = 13. * L * (fv(x, y, z) - v0)\n\n return np.concatenate([q[..., np.newaxis] for q in [L, u, v]], axis=-1)\n\n\ndef luv2xyz(luv, illuminant=\"D65\", observer=\"2\"):\n \"\"\"CIE-Luv to XYZ color space conversion.\n\n Parameters\n ----------\n luv : (M, N, [P,] 3) array_like\n The 3 or 4 dimensional image in CIE-Luv format. Final dimension denotes\n channels.\n illuminant : {\"A\", \"D50\", \"D55\", \"D65\", \"D75\", \"E\"}, optional\n The name of the illuminant (the function is NOT case sensitive).\n observer : {\"2\", \"10\"}, optional\n The aperture angle of the observer.\n\n Returns\n -------\n out : (M, N, [P,] 3) ndarray\n The image in XYZ format. Same dimensions as input.\n\n Raises\n ------\n ValueError\n If `luv` is not a 3-D or 4-D array of shape ``(M, N, [P,] 3)``.\n ValueError\n If either the illuminant or the observer angle are not supported or\n unknown.\n\n Notes\n -----\n XYZ conversion weights use observer=2A. Reference whitepoint for D65\n Illuminant, with XYZ tristimulus values of ``(95.047, 100., 108.883)``. See\n function 'get_xyz_coords' for a list of supported illuminants.\n\n References\n ----------\n .. [1] http://www.easyrgb.com/index.php?X=MATH&H=16#text16\n .. [2] https://en.wikipedia.org/wiki/CIELUV\n\n \"\"\"\n\n arr = _prepare_colorarray(luv).copy()\n\n L, u, v = arr[..., 0], arr[..., 1], arr[..., 2]\n\n eps = np.finfo(np.float).eps\n\n # compute y\n y = L.copy()\n mask = y > 7.999625\n y[mask] = np.power((y[mask] + 16.) / 116., 3.)\n y[~mask] = y[~mask] / 903.3\n xyz_ref_white = get_xyz_coords(illuminant, observer)\n y *= xyz_ref_white[1]\n\n # reference white x,z\n uv_weights = np.array([1, 15, 3])\n u0 = 4 * xyz_ref_white[0] / (uv_weights @ xyz_ref_white)\n v0 = 9 * xyz_ref_white[1] / (uv_weights @ xyz_ref_white)\n\n # compute intermediate values\n a = u0 + u / (13. * L + eps)\n b = v0 + v / (13. * L + eps)\n c = 3 * y * (5 * b - 3)\n\n # compute x and z\n z = ((a - 4) * c - 15 * a * b * y) / (12 * b)\n x = -(c / b + 3. * z)\n\n return np.stack([x, y, z], axis=-1)\n\n\ndef rgb2luv(rgb):\n \"\"\"RGB to CIE-Luv color space conversion.\n\n Parameters\n ----------\n rgb : (M, N, [P,] 3) array_like\n The 3 or 4 dimensional image in RGB format. Final dimension denotes\n channels.\n\n Returns\n -------\n out : (M, N, [P,] 3) ndarray\n The image in CIE Luv format. Same dimensions as input.\n\n Raises\n ------\n ValueError\n If `rgb` is not a 3-D or 4-D array of shape ``(M, N, [P,] 3)``.\n\n Notes\n -----\n This function uses rgb2xyz and xyz2luv.\n\n References\n ----------\n .. [1] http://www.easyrgb.com/index.php?X=MATH&H=16#text16\n .. [2] http://www.easyrgb.com/index.php?X=MATH&H=02#text2\n .. [3] https://en.wikipedia.org/wiki/CIELUV\n\n \"\"\"\n return xyz2luv(rgb2xyz(rgb))\n\n\ndef luv2rgb(luv):\n \"\"\"Luv to RGB color space conversion.\n\n Parameters\n ----------\n luv : (M, N, [P,] 3) array_like\n The 3 or 4 dimensional image in CIE Luv format. Final dimension denotes\n channels.\n\n Returns\n -------\n out : (M, N, [P,] 3) ndarray\n The image in RGB format. Same dimensions as input.\n\n Raises\n ------\n ValueError\n If `luv` is not a 3-D or 4-D array of shape ``(M, N, [P,] 3)``.\n\n Notes\n -----\n This function uses luv2xyz and xyz2rgb.\n \"\"\"\n return xyz2rgb(luv2xyz(luv))\n","sub_path":"napari/utils/colormaps/vendored/colorconv.py","file_name":"colorconv.py","file_ext":"py","file_size_in_byte":29428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"539785531","text":"# coding=utf8\n\"\"\"WenBlog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom WenBlog import settings\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n\n url(r'^$', 'blog.views.index'),\n\n # name 是url的一个别称\n url(r'^page/(?P\\d+)/$', 'blog.views.index', name='view_blog_page'),\n\n url(r'^view/(?P.+)/$', 'blog.views.view_post', name='view_blog_post'),\n\n url(r'^category/(?P.+)/page/(?P\\d+)/$',\n 'blog.views.view_category',\n name='view_blog_category_page'\n ),\n\n\n url(r'^category/(?P.+)/$',\n 'blog.views.view_category',\n name='view_blog_category'\n ),\n\n url(r'^about_me/$', 'blog.views.about_me'),\n\n url(r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),\n]\n","sub_path":"WenBlog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"20650876","text":"import os\nfrom flask import Flask, redirect, url_for, request, render_template\nfrom pymongo import MongoClient\n\napp = Flask(__name__)\n\nclient = MongoClient('mongodb://' + os.environ['MONGODB_HOSTNAME'], 27017)\ndb = client.tododb\n\n@app.route('/')\ndef index():\n return render_template('index.html',\n\t\t\t items=list(db.tododb.find()))\n\n@app.route('/insert/', methods=['POST'])\ndef insert():\n item_doc = {\n 'title': request.form['title'],\n 'body': request.form['body']\n }\n db.tododb.insert_one(item_doc)\n\n return redirect(url_for('index'))\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', debug=True)\n","sub_path":"DockerMongo/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"179405946","text":"#-*- coding: UTF-8 -*-\nfrom collections import Counter\nimport xlrd\nimport json\nimport csv\n\ndata_path = \"/Users/maciel/Documents/Model/Modeling-Problems/Terrorists/Script/data.xlsx\"\n# dataframe = pd.read_excel(data_path, sheet_name=None, header=0)\n# print(dataframe)\n# print(type(dataframe))\n\ndata = xlrd.open_workbook(data_path)\ntable = data.sheets()[0]\n# print(table)\nprint(table.cell(0, 0).value)\nprint(table.cell(1, 0).value)\nnum = table.nrows\nprint(num)\n\nterrorists = {}\nlocation = []\ndates = []\nfor i in range(1, num):\n dict = {}\n eventid = str(table.cell(i, 0).value)[:5].replace(\".\", \"\")\n dates.append(eventid)\n dict['eventid'] = eventid\n dict['latitude'] = table.cell(i, 13).value\n dict['longitude'] = table.cell(i, 14).value\n location.append(dict)\n# print(location)\n\n# 转换生成时间跨度文件(time.csv)\ntime_dict = Counter(dates)\nprint(time_dict)\nwith open('time.csv', 'wb') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(['time', 'nums'])\n for key, value in time_dict.items():\n writer.writerow([key, value])\n\n# 转换生成json文件\n# terrorists[\"Name\"] = \"distribution\"\n# terrorists[\"Location\"] = location\n# jsonObj = json.dumps(terrorists)\n#\n# fileObject = open('distribution.json', 'w')\n# fileObject.write(jsonObj)\n# fileObject.close()","sub_path":"Terrorists/Script/terrorist.py","file_name":"terrorist.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"416550803","text":"# import libraries\nimport numpy as np\nimport pandas as pd\n# Load dataset\ndata = np.genfromtxt('401K.csv',delimiter=',', dtype=float, skip_header = 1)\n# Separate independent and dependant variables in different dataframes\nY = data[:,0:1]\nTempX = data[:,1:2]\nTempX.size\n# Add 1's in the column\nK = np.ones((1534,1))\n# Stack by column, 1s and two columns above\nX = np.column_stack ((K,TempX))\n# Dot product of dot products to compute coefficient\nB = np.dot (np.linalg.inv (np.dot(X.T,X)), np.dot(X.T,Y))\n# Calculate error term\nE = Y - np.dot(X,B)\n# Calculate Sum of squared Errors\nSSE = np.dot(E.T, E)\n# Read aaple stock data\nimport pandas_datareader.data as web\ndf = pd.read_csv('aapl.csv')\n# Create Value, product of Volume and Strike\nValue = df.Strike * df.Vol\n# Store it as Size in the dataframe\ndf['size'] = Value\n# See the sum of Size\ndf['size'].sum()\n# Calculate Sum/Volume\ndf['size'].sum()/df['Vol'].sum()\n# Similarly calculate for Opening price\n# Calculate the weighted strike price using ‘Vol’ as weights for put\n(df['Open_Int']*df['Strike']).sum()/df['Open_Int'].sum()\ndf[df['Type'] == 'call']['size'].sum()/df[df['Type'] == 'call']['Vol'].sum()\n# # Calculate the weighted strike price using ‘Vol’ as weights for put\ndf[df['Type'] == 'put']['size'].sum()/df[df['Type'] == 'put']['Vol'].sum()\n# # Calculate the weighted strike price using ‘Vol’ as weights for call\n# weighted strike price using ‘Open_Int’ as weights\n(df[df['Type'] == 'call']['Strike'] * df[df['Type'] == 'call']['Open_Int'] ).sum()/df[df['Type'] == 'call']['Open_Int'].sum()\n(df[df['Type'] == 'put']['Strike'] * df[df['Type'] == 'put']['Open_Int'] ).sum()/df[df['Type'] == 'put']['Open_Int'].sum()\n# Only ones Expiry is on 3/4/2016\ndf1 = df[df['Expiry'] == '3/4/2016' ]\n# Find the weighted strike price using ‘Vol’ as weights for call and put\n(df1[df1['Type'] == 'call']['Strike'] * df1[df1['Type'] == 'call']['Vol'] ).sum()/df1[df1['Type'] == 'call']['Vol'].sum()\n(df1[df1['Type'] == 'put']['Strike'] * df1[df1['Type'] == 'put']['Vol'] ).sum()/df1[df1['Type'] == 'put']['Vol'].sum()\n# Find the weighted strike price using ‘Open_Int’ as weights for put and call\n(df1[df1['Type'] == 'call']['Strike'] * df1[df1['Type'] == 'call']['Open_Int'] ).sum()/df1[df1['Type'] == 'call']['Open_Int'].sum()\n(df1[df1['Type'] == 'put']['Strike'] * df1[df1['Type'] == 'put']['Open_Int'] ).sum()/df1[df1['Type'] == 'put']['Open_Int'].sum()\n","sub_path":"numpyPandas.py","file_name":"numpyPandas.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"77490313","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport numpy as np\nPATH = 'abbildungen/'\nname = 'sim_duration'\n\ndef plot(data, info, figsize):\n import matplotlib.pyplot as plt\n from plottools import label_line, MARKER_DICT, L_WIDTH\n \n data = data[0]\n marker_dict = MARKER_DICT\n l_width = L_WIDTH\n \n fig, ax = plt.subplots(1, 1, figsize=figsize)#, sharex=True, sharey=True)\n\n ax.errorbar(info, data[:, 0, 0], yerr=data[:, 0, 1], xerr=None,\n color='black', label='$MMS_{n=2}$', linewidth=L_WIDTH)\n ax.errorbar(info, data[:, 1, 0], yerr=data[:, 1, 1], xerr=None,\n linestyle='--', color='black', label='$MMS_{n=4}$', linewidth=L_WIDTH)\n ax.errorbar(info, data[:, 2, 0], yerr=data[:, 2, 1], xerr=None,\n color='C7', label='$PWS$', linewidth=L_WIDTH)\n \n ax.scatter(info, data[:, 0, 0], marker='o', s=5, c='black')\n ax.scatter(info, data[:, 1, 0], marker='o', s=5, c='black')\n ax.scatter(info, data[:, 2, 0], marker='o', s=5, c='C7')\n\n ax.set_xlabel(\"Simulationszeit $T_{sim}$ in s\")\n ax.set_ylabel(\"mittlere Rechenzeit $T$ in s\")\n ax.legend()\n \n ax.set_xticks(info)\n ax.grid(axis='y', linewidth=L_WIDTH/4)\n #ax.set_xlim([1, 10])\n #ax.set_ylim([0, 0.1])\n #ax.xaxis.set_major_locator(plt.MaxNLocator(5))\n #ax.yaxis.set_major_locator(plt.MaxNLocator(7))\n \n plt.tight_layout()\n \nif __name__ == \"__main__\":\n import matplotlib as mpl\n mpl.use('pgf')\n import matplotlib.pyplot as plt\n from plottools import figsize, get_colors, MPL_OPTIONS\n \n plt.style.use('default')\n mpl.rcParams.update(MPL_OPTIONS)\n \n plot(*np.load(PATH + name + '_2.npy'), figsize=figsize(0.5, ratio=1))\n plt.savefig(PATH + name + '.pgf')","sub_path":"abbildungen/sim_duration.py","file_name":"sim_duration.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"68428582","text":"# -*- coding: utf-8 -*-\r\n\r\nimport astropy.units as u\r\nimport lightkurve as lk\r\nimport numpy as np\r\nimport pytest\r\n\r\nfrom astropy.units import cds\r\nfrom sloscillations import oscillations\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\ncds.enable()\r\n\r\ndef test_oscillations():\r\n # Cadence in seconds\r\n dt = 29.4*60\r\n # Time array - 1000 days\r\n t = np.arange(0, 1000*86400, dt)\r\n # Compute Nyquist frequency\r\n nyq = 1.0 / (2*dt)\r\n # Compute bin width\r\n bw = 1.0 / t[-1]\r\n # Convert time array into days from seconds\r\n t = (t/86400.0) * u.day\r\n \r\n # Set up oscillation test parameters\r\n params = np.array([10.0, 100.0, 0.2]).reshape(1,-1)\r\n # White noise level (in ppm)\r\n white = 1.0\r\n # Compute the kernel of the oscillation mode\r\n osc = oscillations.Oscillations(t)\r\n kernel, gp = osc.compute_gp(params, white=white)\r\n # Compute\r\n gp.compute(t.value)\r\n # model from Kallinger (2014)\r\n # Sample from gp \r\n y = gp.sample()\r\n\r\n # Give units of ppm for lightkurve\r\n y = y*cds.ppm\r\n\r\n #\r\n lc = lk.LightCurve(time=t, flux=y)\r\n\r\n # Approximate Nyquist Frequency and frequency bin width in terms of days\r\n nyquist = 0.5 * (1./(np.median(np.diff(lc.time))))\r\n\r\n # Compute periodogram\r\n ps = lc.to_periodogram(normalization='psd',\r\n freq_unit=u.microhertz)\r\n\r\n # Compute frequency array for analytical mode profile computation\r\n # and for evaluating gp psd\r\n f = np.arange(bw, nyq, bw) * 1e6\r\n # Standard lorentzian profile\r\n lor = osc.compute_lor_model(f, params, dt, white=white)\r\n # Analytical psd for chosen gp kernel\r\n full = osc.compute_full_model(f, params, dt, white=white)\r\n\r\n # Convert frequency to 1/day for computation of psd\r\n psd = kernel.get_psd(2*np.pi*f*(86400.0/1e6))\r\n\r\n # Get back into correct units i.e. normalisation\r\n psd *= (2 / (t.max().value))\r\n psd *= (2 / (f[1]-f[0]))\r\n psd += (2e-6*white**2*dt)\r\n\r\n #plt.plot(f, psd)\r\n #plt.plot(f, lor)\r\n #plt.show()\r\n\r\n #plt.plot(f, psd/lor)\r\n #plt.show()\r\n\r\n assert np.allclose(psd, full)\r\n\r\nif __name__==\"__main__\":\r\n\r\n test_oscillations()","sub_path":"sloscillations/tests/test_datageneration.py","file_name":"test_datageneration.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"578158593","text":"import sqlalchemy, random\n\nclass breed:\n def __init__(self, name):\n self.name = name\n\nbreed = [\"husky\",\"chocolate lab\",\"greyhound\",\"golden retriever\",\"poodle\",\"corgi\",\"pitbull\",\n\"boxer\",\"German shepard\",\"beagle\",\"great dane\",\"pug\",\"bulldog\",\"dacshund\",\n\"chihuahua\",\"yellow lab\"]\n\ndef getNewBreed():\n breedA = random.choice(breed)\n breedB = random.choice(breed)\n return breedA[0:random.randint(4,5)] + breedB[random.randint(3,4):]\n\n\nfor i in range(100):\n howIsDog = getNewBreed()\n breed.append(howIsDog)\n print (howIsDog)\n\nwith open(\"breed.txt\",\"w\") as f: #in write mode\n f.write(\"{}\".format(breed))\n\nbreed = input('enter new breed if want')\n","sub_path":"Dogbreedgen.py","file_name":"Dogbreedgen.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"609594865","text":"import os\nimport unittest\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import MetaData\nfrom sqlalchemy import Integer\nfrom sqlalchemy import Unicode\nimport yaml\n\nfrom cumulusci.utils import temporary_dir\n\nfrom cumulusci.tasks.bulkdata.utils import create_table, generate_batches\n\n\ndef create_db_file(filename):\n \"\"\"Create a SQLite file from a filename\"\"\"\n db_url = \"sqlite:///%s\" % filename\n engine = create_engine(db_url)\n metadata = MetaData()\n metadata.bind = engine\n return engine, metadata\n\n\nclass TestCreateTable(unittest.TestCase):\n def test_create_table_legacy_oid_mapping(self):\n mapping_file = os.path.join(os.path.dirname(__file__), \"mapping_v1.yml\")\n with open(mapping_file, \"r\") as fh:\n content = yaml.safe_load(fh)\n account_mapping = content[\"Insert Contacts\"]\n\n with temporary_dir() as d:\n tmp_db_path = os.path.join(d, \"temp.db\")\n\n engine, metadata = create_db_file(tmp_db_path)\n t = create_table(account_mapping, metadata)\n assert t.name == \"contacts\"\n assert isinstance(t.columns[\"sf_id\"].type, Unicode)\n assert isinstance(t.columns[\"first_name\"].type, Unicode)\n assert isinstance(t.columns[\"last_name\"].type, Unicode)\n assert isinstance(t.columns[\"email\"].type, Unicode)\n\n def test_create_table_modern_id_mapping(self):\n mapping_file = os.path.join(os.path.dirname(__file__), \"mapping_v2.yml\")\n with open(mapping_file, \"r\") as fh:\n content = yaml.safe_load(fh)\n account_mapping = content[\"Insert Contacts\"]\n\n with temporary_dir() as d:\n tmp_db_path = os.path.join(d, \"temp.db\")\n\n engine, metadata = create_db_file(tmp_db_path)\n t = create_table(account_mapping, metadata)\n assert t.name == \"contacts\"\n assert isinstance(t.columns[\"id\"].type, Integer)\n assert isinstance(t.columns[\"first_name\"].type, Unicode)\n assert isinstance(t.columns[\"last_name\"].type, Unicode)\n assert isinstance(t.columns[\"email\"].type, Unicode)\n\n\nclass TestBatching(unittest.TestCase):\n def test_batching_no_remainder(self):\n batches = list(generate_batches(num_records=20, batch_size=10))\n assert batches == [(10, 0), (10, 1)]\n\n batches = list(generate_batches(num_records=20, batch_size=5))\n assert batches == [(5, 0), (5, 1), (5, 2), (5, 3)]\n\n batches = list(generate_batches(num_records=3, batch_size=1))\n assert batches == [(1, 0), (1, 1), (1, 2)]\n\n batches = list(generate_batches(num_records=3, batch_size=3))\n assert batches == [(3, 0)]\n\n def test_batching_with_remainder(self):\n batches = list(generate_batches(num_records=20, batch_size=7))\n assert batches == [(7, 0), (7, 1), (6, 2)]\n","sub_path":"cumulusci/tasks/bulkdata/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"374138022","text":"# http 服务器,加入多线程方式\nimport socket\nimport threading \n\ndef handle_client(client_socket):\n recv_data = client_socket.recv(1024).decode('utf-8')\n print(recv_data)\n recv_data_list = recv_data.split()\n print(recv_data_list[1])\n response_header = 'HTTP/1.1 200 OK\\r\\n'\n response_header += '\\r\\n'\n # file_name\n response_body = recv_data_list[1]\n response = response_header + response_body\n response = response_header\n client_socket.send(response.encode('utf-8'))\n print(response)\n\n file_data = read_file(recv_data_list[1])\n client_socket.send(file_data)\n client_socket.close()\n\ndef read_file(file_name):\n try:\n with open (file_name[1:],'rb') as f:\n file_content = f.read()\n except Exception:\n file_content = b'
404 error
'\n return file_content\n\ndef main():\n server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n server_socket.bind(('',7890))\n server_socket.listen(128)\n while True:\n client_socket,client_addr = server_socket.accept()\n p = threading.Thread(target = handle_client, args=(client_socket,))\n p.start()\n #client_socket.close() 子线程不复制主线程的资源,所以不用关闭两次\n\n server_socket.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"http_server_03_threading.py","file_name":"http_server_03_threading.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"365139181","text":"# Importing requests to get information from websites\r\n# Importing random to randomly pick dad joke\r\n# Importing pyfiglet & colorama to create colorized ASCII art for the header\r\nimport requests\r\nimport random\r\nimport pyfiglet\r\nfrom colorama import Fore, Back, init\r\n\r\n# Resets colorama settings after each time it is ran\r\ninit(autoreset=True)\r\n\r\n# Creating the ASCII art and saving it to a variable\r\nheader = pyfiglet.figlet_format(\"DAD JOKES 3000\", font=\"standard\")\r\n\r\n# Colorizing and printing the ASCII art\r\nprint(Fore.RED + header)\r\n\r\n# Asking the user for a joke topic, & saving it to a variable\r\nuser_choice = input(\"What do you want to hear a joke about?: \")\r\n\r\n# Requesting dad jokes from website\r\nurl = \"https://icanhazdadjoke.com/search\"\r\nresponse = requests.get(\r\n url,\r\n headers={\"Accept\": \"application/json\"},\r\n params={\"term\": user_choice})\r\n\r\n# Turning response into dict via .json, stripping away other uneeded\r\n# information and compiling jokes into one full list\r\ndata = response.json()\r\njoke_dict = data[\"results\"]\r\njokes = [li['joke'] for li in joke_dict]\r\n\r\n# This will count the amount of jokes on the subject the user entered\r\njoke_count = 0\r\nfor x in jokes:\r\n joke_count += 1\r\n\r\n# If any jokes are returned, one is picked at random and printed, else print that none are found\r\nif joke_count > 0:\r\n print(f\"Okay! I have {joke_count} jokes about {user_choice}s, here's one!\")\r\n dad_joke = random.choice(jokes)\r\n print(dad_joke)\r\nelse:\r\n print(\"Sorry, I don't have any jokes about that...\")\r\n","sub_path":"DadJokeGenerator.py","file_name":"DadJokeGenerator.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"268714222","text":"import rospy\nimport tensorflow as tf\nimport numpy as np\nfrom styx_msgs.msg import TrafficLight\n\nMIN_CLASSIFICATION_CONFIDENCE = 0.85\nINFERENCE_MODEL_PATH = 'models/tl_site_mobilenet_1_224_graph.pb'\n\n\nclass TLClassifierSite(object):\n def __init__(self):\n # Load classifier\n\n self.graph = tf.Graph()\n graph_def = tf.GraphDef()\n\n with open(INFERENCE_MODEL_PATH, \"rb\") as f:\n graph_def.ParseFromString(f.read())\n with self.graph.as_default():\n tf.import_graph_def(graph_def)\n\n input_name = \"import/input\"\n output_name = \"import/final_result\"\n\n # Get input tensor from the graph\n self.image_tensor = self.graph.get_operation_by_name(\n input_name).outputs[0]\n # Get classification tensor from the graph\n self.classification_tensor = self.graph.get_operation_by_name(\n output_name).outputs[0]\n\n with self.graph.as_default():\n self.input_tensor = tf.placeholder(tf.float32, [None, None, 3])\n float_caster = tf.cast(self.input_tensor, tf.float32)\n dims_expander = tf.expand_dims(float_caster, 0)\n resized = tf.image.resize_bilinear(dims_expander, [224, 224])\n self.image_normalized = tf.divide(tf.subtract(\n resized, [128]), [128])\n\n self.sess = tf.Session(graph=self.graph)\n\n def get_classification(self, image):\n \"\"\"Determines the color of the traffic light in the image\n\n Args:\n image (cv::Mat): image containing the traffic light\n\n Returns:\n int: ID of traffic light color\n (specified in styx_msgs/TrafficLight)\n\n \"\"\"\n\n with self.graph.as_default():\n # normalize image\n feed_dict = {self.input_tensor: image}\n image_np_expanded = self.sess.run(self.image_normalized,\n feed_dict=feed_dict)\n\n # Run inference\n feed_dict = {self.image_tensor: image_np_expanded}\n classes = self.sess.run(self.classification_tensor,\n feed_dict=feed_dict)\n\n results = np.squeeze(classes)\n\n output = self.graph_class_to_traffic_light(results)\n\n rospy.loginfo('Traffic Light: {}'\n .format(self.traffic_light_to_str(output)))\n return output\n\n @staticmethod\n def graph_class_to_traffic_light(results):\n \"\"\" Converts from a class number as defined in the TensorFlow\n model, to a class number as defined in styx_msgs/TrafficLight\n \"\"\"\n top_k = results.argsort()[:][::-1]\n\n rospy.loginfo(\"Traffic lights classes scores: {}\".format(results))\n best_class = top_k[0]\n if results[best_class] < MIN_CLASSIFICATION_CONFIDENCE:\n rospy.loginfo(\"best class score {}\".format(results[best_class]))\n return TrafficLight.UNKNOWN\n\n if best_class == 0:\n return TrafficLight.GREEN\n elif best_class == 1:\n return TrafficLight.UNKNOWN\n elif best_class == 2:\n return TrafficLight.RED\n elif best_class == 3:\n return TrafficLight.YELLOW\n\n return TrafficLight.UNKNOWN\n\n @staticmethod\n def traffic_light_to_str(traffic_light):\n if traffic_light == TrafficLight.GREEN:\n return 'GREEN'\n elif traffic_light == TrafficLight.YELLOW:\n return 'YELLOW'\n elif traffic_light == TrafficLight.RED:\n return 'RED'\n return 'UNKNOWN'\n","sub_path":"ros/src/tl_detector/light_classification/tl_classifier_site.py","file_name":"tl_classifier_site.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"3435206","text":"\"\"\"\n题目描述\n 给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。\n 如果小数部分为循环小数,则将循环的部分括在括号内。\n\"\"\"\n\n\ndef fractionToDecimal(numerator, denominator):\n \"\"\"\n :type numerator: int\n :type denominator: int\n :rtype: str\n \"\"\"\n if numerator == 0:\n return '0'\n elif denominator == 0:\n return ''\n else:\n isNegative = (numerator < 0) ^ (denominator < 0)\n numerator = abs(numerator)\n denominator = abs(denominator)\n res = ''\n res += '-' if isNegative else ''\n res += str(numerator // denominator)\n numerator %= denominator\n if numerator == 0:\n return res\n else:\n res += '.'\n dic = {}\n while numerator:\n if numerator in dic:\n start = dic[numerator]\n end = len(res)\n res = res[:start] + '(' + res[start:end] + ')'\n return res\n dic[numerator] = len(res)\n res += str(numerator * 10 // denominator)\n numerator = numerator * 10 % denominator\n return res\n\n\nprint(fractionToDecimal(int(input()), int(input())))\n","sub_path":"Code/CodeRecords/2097/60782/290585.py","file_name":"290585.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"458352798","text":"from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom .serializers import FoodSerializer, DailyDiarySerializer, DailyDiarySaveSerializer\nfrom django.http import Http404\nfrom datetime import date\nfrom django.utils.dateparse import parse_date\n\nfrom .models import Food, DailyDiary, User\nfrom rest_framework.parsers import JSONParser\n\n\n# Create your views here.\n@api_view(['GET', 'POST'])\ndef foods(request):\n if request.method == 'GET':\n foods = Food.objects.all()\n serializer = FoodSerializer(foods, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = FoodSerializer(data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET', 'DELETE'])\ndef food(request, pk):\n try:\n food = Food.objects.get(id=pk)\n except Food.DoesNotExist:\n return Response({'message': 'Posilek nie istnieje'}, status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = FoodSerializer(food, many=False)\n return Response(serializer.data)\n\n elif request.method == 'DELETE':\n food.delete()\n return Response({'message': 'Posilek zostal pomyslnie usuniety'}, status=status.HTTP_204_NO_CONTENT)\n\n\n@api_view(['GET'])\ndef foods_for_diary(request, pk):\n if request.method == 'GET':\n daily_diary = DailyDiary.objects.get(id=pk)\n if daily_diary is None:\n return Response({'message': 'Dziennik nie istnieje'}, status=status.HTTP_404_NOT_FOUND)\n foods = daily_diary.foods\n serializer = FoodSerializer(foods, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET', 'POST'])\ndef diaries(request):\n if request.method == 'GET':\n daily_diaries = DailyDiary.objects.all()\n serializer = DailyDiarySerializer(daily_diaries, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = DailyDiarySaveSerializer(data=request.data)\n\n if serializer.is_valid():\n\n user_id = request.data['user']\n date_str = request.data['date']\n date_parsed = parse_date(date_str)\n daily_diary = DailyDiary.objects.filter(user=user_id).filter(date=date_parsed).first()\n\n if daily_diary is not None:\n return Response({'message': 'Istnieje juz dziennik dla tego uzytkownika w tym dniu'},\n status=status.HTTP_400_BAD_REQUEST)\n\n serializer.save()\n return Response(serializer.data)\n\n return Response(serializer.errors)\n\n\n@api_view(['GET'])\ndef diaries_by_user(request, pk):\n if request.method == 'GET':\n daily_diaries = DailyDiary.objects.filter(user=pk)\n if daily_diaries is None:\n return Response({'message': 'Brak dziennikow dla tego uzytkownika'}, status=status.HTTP_404_NOT_FOUND)\n serializer = DailyDiarySerializer(daily_diaries, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef diaries_by_user_today(request, pk):\n if request.method == 'GET':\n today = date.today()\n daily_diary = DailyDiary.objects.filter(user=pk).filter(date=today).first()\n if daily_diary is None:\n try:\n user_from_db = User.objects.get(id=pk)\n except User.DoesNotExist:\n return Response({'message': 'Uzytkownik o podanym id nie zostal odnaleziony'},\n status=status.HTTP_404_NOT_FOUND)\n\n serializer = DailyDiarySaveSerializer(data={'user': user_from_db.id})\n\n if serializer.is_valid():\n serializer.save()\n id = serializer.data['id']\n try:\n daily_diary = DailyDiary.objects.get(id=id)\n except DailyDiary.DoesNotExist:\n return Response({'message': 'Nieokreslony blad podczas tworzenia dziennika'},\n status=status.HTTP_400_BAD_REQUEST)\n\n serializer_response = DailyDiarySerializer(daily_diary, many=False)\n return Response(serializer_response.data)\n\n serializer = DailyDiarySerializer(daily_diary)\n return Response(serializer.data)\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef diary(request, pk):\n try:\n daily_diary = DailyDiary.objects.get(id=pk)\n except DailyDiary.DoesNotExist:\n return Response({'message': 'Dziennik nie istnieje'}, status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n serializer = DailyDiarySerializer(daily_diary, many=False)\n return Response(serializer.data)\n\n elif request.method == 'PUT':\n serializer = DailyDiarySaveSerializer(instance=daily_diary, data=request.data)\n\n if serializer.is_valid():\n user_id = request.data['user']\n if user_id is None:\n return Response({'message': 'Podaj obecnego uzytkownika'}, status=status.HTTP_400_BAD_REQUEST)\n if user_id != daily_diary.user.id:\n return Response({'message': 'Id usera sie nie zgadza'}, status=status.HTTP_400_BAD_REQUEST)\n date_str = request.data['date']\n if date_str is None:\n return Response({'message': 'Podaj obecna date'}, status=status.HTTP_400_BAD_REQUEST)\n date_parsed = parse_date(date_str)\n if date_parsed == daily_diary.date:\n serializer.save()\n return Response(serializer.data)\n\n return Response({'message': 'Data musi pozostac niezmieniona'}, status=status.HTTP_400_BAD_REQUEST)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n daily_diary.delete()\n return Response({'message': 'Dziennik zostal pomyslnie usuniety'}, status=status.HTTP_204_NO_CONTENT)\n","sub_path":"foods/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"334934917","text":"import logging\nimport os\n\nLOGNAME = \"my_log\"\nINFO = logging.INFO\nERROR = logging.ERROR\nDEBUG = logging.DEBUG\n\n\n# 配置日志输出,方便debug\ndef initial_logger(log_name=LOGNAME):\n if not os.path.exists(\"./log/\"):\n os.mkdir(\"./log/\")\n log_file = \"./log/{}.log\".format(log_name)\n log_level = logging.DEBUG\n # 创建日志\n logger = logging.getLogger(log_name)\n logger.setLevel(log_level)\n # 日志格式的设置\n formatter = logging.Formatter(\"[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s\")\n # 输出到文件的日志\n file_handler = logging.FileHandler(log_file)\n file_handler.setFormatter(formatter)\n # 输出到控制台的日志\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(formatter)\n # 添加输出到文件和控制台的日志处理器\n logger.addHandler(file_handler)\n logger.addHandler(stream_handler)\n return logger\n\n\ndef get_logger(log_name=LOGNAME):\n return logging.getLogger(log_name)\n","sub_path":"clipDict/utils_log.py","file_name":"utils_log.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"537489168","text":"# Provided for Question 5, Assignment 1, Data Mining Course, York University\n\n###########################################################################################################\n# This file will read input data ( walmart_trans.csv ), generate frequent itemsets and association rules using\n# the efficient_apriori library. The association rules will be stored in 'walmart_rules.csv'\n###########################################################################################################\n\n\nfrom efficient_apriori import apriori\nimport pandas as pd\n\n\nfile =open('walmart_trans.csv', 'r')\n\n# Read the input file into a list of lists\ndata_tr = []\nfor line in file:\n line = line[:-1] # Remove the \\n character at the end of the line\n data_tr.append(line.split(','))\n\n# Prompt the user to input support and confidence thresholds\nsupport_threshold = float(input('Input support threshold: '))\nconfidence_threshold = float(input('Input confidence threshold: '))\n\nprint(\"Generating frequent itemsets and association rules ...\")\n\n# Call the apriori function to generate frequent itemsets and strong association rules\nfreq_itemsets, rules = apriori(data_tr, min_support=support_threshold, min_confidence=confidence_threshold)\n\n# Output the generated frequent itemsets to the standard output\nfor itemsetlen, itemsets in freq_itemsets.items():\n print('Length-', itemsetlen, 'frequent itemsets:')\n for itemset, support_count in itemsets.items():\n print(itemset, ':', support_count)\n\n# Output the generated association rules to the standard output\nprint('\\nStrong Association Rules:')\nresults = []\nfor rule in rules:\n print(rule)\n results.append([rule.lhs, rule.rhs, rule.confidence, rule.lift, rule.support])\n\n# Output the generated association rules to a csv file \nresultsdf = pd.DataFrame(results, columns=['Antecedent', 'Consequent', 'confidence','lift','support'])\nresultsdf.to_csv('walmart_rules.csv', index=False)","sub_path":"A1/association.py","file_name":"association.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"432419572","text":"import os, sys\nimport pygame\n\nSHOT_BG_POSITION = 60, 440\nSHOT_POSITION = 60, 440\nSHOT_RECT = 0, 43, 70, 43\nBULLET_RECT = 200, 59, 13, 17\n\nclass Gun(object):\n def __init__(self, surface):\n self.surface = surface\n self.mousePos = (0,0)\n self.mouseImg = pygame.image.load(os.path.join('media', 'crosshairs.png'))\n self.shotImgs = pygame.image.load(os.path.join('media', 'screenobjects.png'))\n self.blastSound = os.path.join('media', 'blast.mp3')\n self.rounds = 3\n\n def render(self):\n self.surface.blit(self.mouseImg, self.mousePos)\n self.surface.blit(self.shotImgs, SHOT_POSITION, SHOT_RECT)\n\n # Show the rounds left\n startingX, startingY = SHOT_POSITION\n for i in range(self.rounds):\n x = startingX + 10 + (i * 20)\n y = startingY + 5\n self.surface.blit(self.shotImgs, (x, y), BULLET_RECT)\n\n def reloadIt(self):\n self.rounds = 3\n\n def moveCrossHairs(self, pos):\n xOffset = self.mouseImg.get_width() / 2\n yOffset = self.mouseImg.get_height() / 2\n x, y = pos\n self.mousePos = (x - xOffset), (y - yOffset)\n\n def shoot(self):\n if self.rounds <= 0:\n return False\n\n pygame.mixer.music.load(self.blastSound)\n pygame.mixer.music.play()\n self.rounds = self.rounds - 1\n return True\n","sub_path":"gun.py","file_name":"gun.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"139976844","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import scale, normalize\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.semi_supervised import LabelPropagation\n# from sklearn.semi_supervised import label_propagation\nfrom imblearn.over_sampling import SMOTE\n\n\n\ndef load_all_data():\n # Read am partition the matrix\n data = pd.read_feather('./feature_stage_data_all.ftr')\n x = data[data.columns[3:]]\n y = data['stage']\n o = data.observation\n x = x.values\n x = normalize(x)\n y = y.values\n x_va = x[[i in [8, 9] for i in o.values]]\n y_va = y[[i in [8, 9] for i in o.values]]\n x = x[[i not in [8, 9] for i in o.values]]\n y = y[[i not in [8, 9] for i in o.values]]\n o.unique()\n \n \n nnl = lambda a: np.invert(np.isnan(a))\n nul = lambda a: np.isnan(a)\n x_obs = x[nnl(y)]\n y_obs = y[nnl(y)]\n \n # apply Label Spreading\n x_nuls = x[nul(y)]\n label_spread = LabelPropagation(kernel='knn')\n label_spread.fit(x_obs, y_obs)\n x_all = np.concatenate([x_obs, x_nuls], axis=0)\n y_all = np.concatenate([y_obs, label_spread.predict(x_nuls)], axis=0)\n \n # Over sample the stages\n zen = SMOTE(random_state=8675309)\n x, y = zen.fit_resample(x_all, y_all)\n x, y = shuffle(x, y, random_state=42)\n x_tr, x_te, y_tr, y_te = train_test_split(x, y, test_size = 0.20)\n return x_tr, y_tr, x_te, y_te, x_va, y_va\n\n\n","sub_path":"oversample.py","file_name":"oversample.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"643201707","text":"from pippi import dsp\n\na0 = 27.5 \n\njust = [\n (1.0, 1.0), # P1\n (16.0, 15.0), # m2\n (9.0, 8.0), # M2\n (6.0, 5.0), # m3\n (5.0, 4.0), # M3\n (4.0, 3.0), # P4\n (45.0, 32.0), # TT\n (3.0, 2.0), # P5\n (8.0, 5.0), # m6\n (5.0, 3.0), # M6\n (9.0, 5.0), # m7\n (15.0, 8.0), # M7\n]\n\nvary = [ (dsp.rand(-0.05, 0.05) + i[0], dsp.rand(-0.05, 0.05) + i[1]) for i in just ]\n\nterry = [\n (1.0, 1.0), # P1\n (16.0, 15.0), # m2\n (10.0, 9.0), # M2\n (6.0, 5.0), # m3\n (5.0, 4.0), # M3\n (4.0, 3.0), # P4\n (64.0, 45.0), # TT\n (3.0, 2.0), # P5\n (8.0, 5.0), # m6\n (27.0, 16.0), # M6\n (16.0, 9.0), # m7\n (15.0, 8.0), # M7\n]\n\nyoung = [\n (1.0, 1.0), # P1 0\n (567.0, 512.0), # m2 1\n (9.0, 8.0), # M2 2\n (147.0, 128.0), # m3 3\n (21.0, 16.0), # M3 4\n (1323.0, 1024.0), # P4 5\n (189.0, 128.0), # TT 6\n (3.0, 2.0), # P5 7\n (49.0, 32.0), # m6 8\n (7.0, 4.0), # M6 9\n (441.0, 256.0), # m7 10\n (63.0, 32.0), # M7 11\n]\n\nlouis = [\n (1.0, 1.0), # P1 1.0\n (1.0, 1.0), # m2 1.0\n (9.0, 8.0), # M2 1.125\n (9.0, 8.0), # m3 1.125\n (5.0, 4.0), # M3 1.25\n (5.0, 4.0), # P4 1.25\n (3.0, 2.0), # TT 1.5\n (3.0, 2.0), # P5 1.5\n (8.0, 5.0), # m6 1.6\n (7.0, 4.0), # M6 1.75\n (9.0, 5.0), # m7 1.8\n (9.0, 5.0), # M7 1.8\n]\n\n\n# Handy subsets of the chromatic scale\nmajor = [0, 2, 4, 5, 7, 9, 11]\nminor = [0, 2, 3, 5, 7, 8, 10]\n\n# Maps to chromatic ratio lists above\nnotes = { \n 'a': 0,\n 'a#': 1,\n 'bb': 1, \n 'b': 2,\n 'c': 3, \n 'c#': 4, \n 'db': 4, \n 'd': 5, \n 'd#': 6, \n 'eb': 6, \n 'e': 7, \n 'f': 8, \n 'f#': 9, \n 'gb': 9, \n 'g': 10, \n 'g#': 11, \n 'ab': 11, \n }\n\n\ndef nti(note):\n \"\"\" Note to index\n returns the index of enharmonic note names\n or False if not found\n \"\"\"\n return notes.get(note, False)\n\ndef ntf(note, octave=4, ratios=None):\n \"\"\" Note to freq \n \"\"\"\n if ratios is None:\n ratios = terry\n\n return ratios[nti(note)][0] / ratios[nti(note)][1] * (a0 * (2.0**octave))\n\ndef stf(index):\n degree = index % 24\n octave = index / 24\n\n return (2 ** (degree / 24.0)) * (a0 / 4.0) * (2.0 ** octave)\n\ndef fts(freq):\n # Try to find closest eq temp freq to input\n # Generate entire range of possible eq temp freqs\n all_freq = [ stf(index) for index in range(2**8) ]\n\n count = 0\n cfreq = 0\n while freq > cfreq and count < 2**8:\n cfreq = all_freq[count]\n count = count + 1\n\n count = count - 1\n\n return count % 55\n\ndef nts(note, octave):\n octave = octave if octave >= -2 else -2\n octave = octave if octave <= 8 else 8 \n\n degree = notes[note] * 2\n\n degree = degree + ((octave + 2) * 24) \n\n return degree\n\ndef fromdegrees(scale_degrees=None, octave=2, root='c', scale=None, ratios=None):\n if scale_degrees is None:\n scale_degrees = [1,3,5]\n\n if ratios is None:\n ratios = terry\n\n if scale is None:\n scale = major\n\n freqs = []\n root = ntf(root, octave, ratios)\n\n for index, degree in enumerate(scale_degrees):\n degree = int(degree)\n register = degree / len(scale)\n chromatic_degree = scale[degree % len(scale) - 1]\n ratio = ratios[chromatic_degree]\n freqs += [ root * (ratio[0] / ratio[1]) * 2**register ]\n\n return freqs\n\ndef step(degree=0, root='c', octave=4, scale=None, quality=None, ratios=None):\n # TODO. Many qualities of jank. Fix.\n\n if scale is None:\n scale = [1,3,5,8]\n\n if quality is None:\n quality = major\n\n if ratios is None:\n ratios = terry\n\n diatonic = scale[degree % len(scale) - 1]\n chromatic = quality[diatonic % len(quality) - 1]\n\n pitch = ratios[chromatic][0] / ratios[chromatic][1]\n pitch *= octave + int(diatonic / len(quality))\n pitch *= ntf(root, octave, ratios)\n\n return pitch\n\ndef scale(pitches=None, quality=None):\n if pitches is None:\n pitches = [1,3,5]\n\n if quality is None:\n quality = major\n\n return [quality[p - 1] for p in pitches]\n","sub_path":"pippi/tune.py","file_name":"tune.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"117329015","text":"def eh_primo (numero):\n if numero<=1:\n return False\n if numero%2==0 and numero!=2:\n return False\n eh_primo = True\n i=2\n while i= 1) or p_all_files:\n os.remove(v_file)\n except Exception as exc:\n pass\n\ndef startup_procedure():\n user_database.work()\n clean_temp_folder(True)\n\n #removing existing sessions\n database_sessions = OmniDatabase.Generic.InstantiateDatabase(\n 'sqlite','','',settings.SESSION_DATABASE,'','','0',''\n )\n try:\n database_sessions.v_connection.Execute('''\n delete\n from django_session\n ''')\n except Exception as exc:\n print('Error:')\n print(exc)\n","sub_path":"OmniDB/OmniDB/startup.py","file_name":"startup.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"67069945","text":"from matplotlib.image import imread\nfrom matplotlib import pyplot as PLT\nimport numpy as np\n\nclass ImageProcessor:\n def load(self, path):\n img = imread(path)\n x = np.shape(img)[0]\n y = np.shape(img)[1]\n print(\"Loading image of dimensions \" + str(x) + \" x \"+str(y))\n return img\n\n def display(self, arr):\n PLT.imshow(arr)\n PLT.show()\n\n","sub_path":"D03/ex01/ImageProcesor.py","file_name":"ImageProcesor.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"402802853","text":"import pickle\nCURRENT_TERM =\"SPRING2015\"\n\nclass Student:\n def __init__(self, student_id, student_lastname, student_firstname, courses_taken=set()):\n self.student_id = student_id\n self.student_lastname = student_lastname\n self.student_firstname = student_firstname\n self.courses_taken=courses_taken\n\n def get_courses_taken(self):\n return self.courses_taken\n\n def add_course(self, course):\n self.courses_taken.add(course)\n\n def get_info(self):\n return self.student_id, self.student_lastname, self.student_firstname\n\nclass Course:\n\n def __init__(self, course_id,course_units, preresquisites=set()):\n self.course_id = course_id\n self.course_units=int(course_units)\n self.preresquisites=preresquisites\n\n def get_course_info(self):\n '''returns ID[0] units[1]'''\n return self.course_id, self.course_units\n\n def get_prerequisites(self):\n return self.preresquisites\n\n def set_prerequisites(self, new_prerequisite, action='add'):\n if action =='del':\n self.preresquisites.remove(new_prerequisite)\n else:\n self.preresquisites.add(new_prerequisite)\n\n\nclass Major_Diagram:\n\n def __init__(self, name, courses=set()):\n self.name=name\n self.corses_required=courses\n def get_courses_required(self):\n return self.corses_required\n def get_name(self):\n return self.name\n\n\n\nclass Schedule:\n\n def __init__(self, student_id, term, list_of_sections_in_the_schedule=set()):\n self.student_id=student_id\n self.term=term\n self.list_of_sections_in_the_schedule=list_of_sections_in_the_schedule\n\n def set_schedule(self, section, action='add'):\n if action == 'del':\n self.schedule.remove(section)\n else:\n self.schedule.add(section)\n\n def get_schedule(self):\n return self.list_of_sections_in_the_schedule\n\n\nclass Section:\n def __init__(self, section_id, course_id, meeting_days,meeting_times):\n self.section_id=section_id\n self.course_id=course_id\n self.meeting_times=meeting_times\n self.meeting_days=meeting_days\n\n def get_section_id(self):\n return self.section_id\n def get_course_id(self):\n return self.course_id\n def get_meeting_times(self):\n return self.meeting_times\n def get_meeting_days(self):\n return self.meeting_days\n\n\n\n#class Catalog:\n def __init__(self,list_of_courses, term):\n self.list_of_courses=list_of_courses\n self.term=term\n def in_catalog(self, check_course):\n if check_course in self.list_of_courses:\n return True\n else:\n return False\n def modify_catalog(self, new_course, action='add'):\n if action =='del':\n self.list_of_courses.remove(new_course)\n else:\n self.list_of_courses.add(new_course)\n\n def get_courses(self):\n return self.list_of_courses\n\n def get_term(self):\n return self.term\n\n\ndef add_student():\n list_of_courses=set()\n print('\\nAdding new student\\nPlease enter new student\\'s ID')\n new_student_ID=input()\n print('\\nEnter the lastname: ')\n new_student_lastname=input()\n print('\\nEnter the firstname: ')\n new_student_firstname=input()\n print('\\nEnter the courses taken by this student separated by comma.'\n '\\nThis list can be edited at any time\\nPress ENTER to finish: ')\n string_of_courses=input().upper()\n for course in string_of_courses.split(','):\n list_of_courses.add(course)\n return Student(new_student_ID,new_student_lastname,new_student_firstname,list_of_courses)\n\ndef add_course():\n list_of_prerequisites=set()\n print('\\nAdding new course\\nPlease enter new course\\'s ID')\n new_course_id=input()\n print('\\nHow many units?')\n new_course_units=input()\n\n print('\\nEnter the prerequisites for the course separated by comma.'\n '\\nThis list can be edited at any time\\nPress ENTER to finish: ')\n string_of_courses=input().upper()\n for course in string_of_courses.split(','):\n list_of_prerequisites.add(course)\n return Course(new_course_id, new_course_units, list_of_prerequisites)\n\ndef modify_catalog(list_of_catalogs):\n print('\\n1.Modify existing Catalog\\n2.Add new Catalog\\n3.Remove existing Catalog.\\n4.Cancel and return\\n')\n menu_choice=int(input())\n if menu_choice == 1:\n term = input(\"What term\").upper()\n for catalog in list_of_catalogs:\n if catalog.get_term().upper() == term:\n sub_menu_choice=int(input(\"\\n1.Add course\\n2.Remove Course.\\n3.Cancel and return\\n\"))\n while sub_menu_choice != 3:\n if sub_menu_choice ==1:\n new_course=input('Enter a new course to add: ')\n catalog.modify_catalog(new_course, 'add')\n if sub_menu_choice ==2:\n new_course=input('Enter a new course to remove: ')\n catalog.modify_catalog(new_course, 'del')\n sub_menu_choice=int(input(\"\\n1.Add course\\n2.Remove Course.\\n3.Cancel and return\\n\"))\n list_of_catalogs.add(catalog)\n return list_of_catalogs\n\n print('\\nThere is no a Catalog for %s' %term)\n\n if menu_choice ==2:\n term = input(\"What term\").upper()\n new_catalog_string=''\n print('\\nEnter couses you want to add separated by comma, ENTER to finish')\n new_catalog_string=input().upper().split(',')\n C=Catalog(set(new_catalog_string), term)\n list_of_catalogs.add(C)\n return list_of_catalogs\n if menu_choice ==4 : return\n\n\ndef modify_major_diargam(list_of_MD):\n print('\\n1.Show existind Diagrams\\n2.Add new Diagram\\n3.Modify Existing Diagram\\n4.Exit\\n')\n menu_choice=int(input())\n if menu_choice ==1:\n for diagram in list_of_MD:\n print(diagram.get_name())\n for course in diagram.get_courses_required():\n print(course)\n\n if menu_choice ==2:\n name = input('\\nEnter the nme of the Diagram: ').upper()\n list_of_courses=input('\\nEnter the courses required separated by comma').upper().split(',')\n M=Major_Diagram(name, set(list_of_courses))\n list_of_MD.add(M)\n return list_of_MD\n\ndef main_menu():\n print('\\n1.Add course\\n2.Add course to the Catalog\\n3.Add a student\\n'\n '4.Login as a student\\n5.Modify Catalog\\n6.Modify Major Diagram\\n7.Show ALL courses\\n'\n '8.Show ALL Students\\n11.Show ALL Diagrams\\n'\n '9.Exit\\n\\nEnter your selection:')\n menu_choice=int(input())\n return menu_choice\n\ndef show_students(list_of_students):\n for student in list_of_students:\n studentId, studentLN, studentFN=student.get_info()\n print(studentId, studentLN, studentFN)\n\n\ndef show_courses(list_of_courses):\n for course in list_of_courses:\n courseID, courseUnits = course.get_course_info()\n prereqs=course.get_prerequisites()\n print('Course %s, %d units\\n----------\\nPrerequisites for this course:\\n' %(courseID, courseUnits))\n for p in prereqs:\n print(p)\n\ndef show_diagrams(list_of_diagrams):\n for diagram in list_of_diagrams:\n print(diagram.get_name())\n\n\ndef restore_data():\n f = open('GoF_pickle', 'rb')\n list_of_students,list_of_courses,list_of_schedules,list_of_catalogs,list_of_major_diagrams = pickle.load(f)\n return list_of_students,list_of_courses,list_of_schedules,list_of_catalogs,list_of_major_diagrams\n f.close()\n\ndef save_data(list_of_students,list_of_courses,list_of_schedules,list_of_catalogs,list_of_major_diagrams):\n f = open('GoF_pickle', 'wb')\n pickle.dump([list_of_students,list_of_courses,list_of_schedules,list_of_catalogs,list_of_major_diagrams],f)\n f.close()\n\n\ndef authenticate_student(list_of_students):\n print(\"\\nEnter Student ID: \")\n student_id=input()\n for student in list_of_students:\n if student_id == student.get_info()[0]:\n return student\n print(\"\\nThere is no student with this ID\")\n return False\n\ndef get_remaining_courses(list_of_diagrams, student):\n major=input('\\nEnter the Diagram\\'s name')\n for diagram in list_of_diagrams:\n if major == diagram.get_name():\n difference= diagram.get_courses_required() - student.classes_taken()\n return difference\n print('\\nTher is no such Diagram')\n\n\ndef show_needed_courses_which_available(list_of_MD, list_of_catalogs, student, term):\n remaining=get_remaining_courses(list_of_MD, student)\n for catalog in list_of_catalogs:\n if catalog.get_term() == term:\n available = catalog.get_courses()\n return available.intersection(remaining)\n print('There is no such Catalog')\n\n\ndef student_menu():\n return int(input('\\n1.Show ALL remaining courses\\n2.Show ALL remaining Courses available in this Term'))\n\n\ndef GoF_main_logic():\n student_logged = False\n\n\n\ndef main_old():\n\n list_of_students,list_of_courses,list_of_schedules,list_of_catalogs,list_of_major_diagrams=restore_data()\n\n menu_choice=0\n while menu_choice !=9 and not student_logged:\n menu_choice=main_menu()\n\n if menu_choice ==1:\n list_of_courses.add(add_course())\n\n\n\n if menu_choice==3:\n list_of_students.add(add_student())\n\n\n if menu_choice ==4:\n logged_student = authenticate_student(list_of_students)\n if logged_student != False:\n student_logged = True\n\n if menu_choice ==5:\n modify_catalog(list_of_catalogs)\n if menu_choice ==6:\n modify_major_diargam(list_of_major_diagrams)\n if menu_choice ==7:\n show_courses(list_of_courses)\n if menu_choice == 8:\n show_students(list_of_students)\n if menu_choice == 11:\n show_diagrams(list_of_major_diagrams)\n\n if (student_logged ==True and logged_student !=False):\n menu_choice = student_menu()\n if menu_choice == 1:\n remaining= get_remaining_courses(list_of_major_diagrams, logged_student)\n if menu_choice == 2:\n remaining = show_needed_courses_which_available(list_of_major_diagrams, list_of_catalogs, logged_student, CURRENT_TERM)\n if remaining:\n for element in remaining:\n print(element)\n\n save_data(list_of_students,list_of_courses,list_of_schedules,list_of_catalogs,list_of_major_diagrams)\n\n\n\n\n","sub_path":"work/GoF_backend.py","file_name":"GoF_backend.py","file_ext":"py","file_size_in_byte":10517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"204971667","text":"import torch\nfrom torch.autograd import Variable\nfrom triforce_helper_functions import eval\nimport numpy as np\n\nclass Analyzer():\n\n # main analysis function\n def analyze(self, tools, testLoader, out_file):\n\n [classifier, regressor, GAN] = tools\n classifier_test_loss = 0\n regressor_test_loss = 0\n GAN_test_loss = 0\n classifier_test_accuracy = 0\n GAN_test_accuracy = 0\n regressor_test_mean = 0\n regressor_test_sigma = 0\n regressor_pred = []\n regressor_true = []\n classifier_outputs = []\n regressor_outputs = []\n GAN_outputs = []\n\n n_test_batches = 0\n for data in testLoader:\n ECALs, HCALs, ys, energies = data\n ECALs, HCALs, ys, energies = Variable(ECALs.cuda()), Variable(HCALs.cuda()), Variable(ys.cuda()), Variable(energies.cuda())\n if (classifier != None): classifier_outputs.append(eval(classifier, ECALs, HCALs, ys))\n else: classifier_outputs.append((0,0,0,0,0,0))\n if (regressor != None): regressor_outputs.append(eval(regressor, ECALs, HCALs, energies))\n else: regressor_outputs.append((0,0,0,0,0,0))\n if (GAN != None): GAN_outputs.append(eval(GAN, ECALs, HCALs, ys))\n else: GAN_outputs.append((0,0,0,0,0,0))\n classifier_test_loss += classifier_outputs[-1][0]\n regressor_test_loss += regressor_outputs[-1][0]\n GAN_test_loss += GAN_outputs[-1][0]\n classifier_test_accuracy += classifier_outputs[-1][1]\n GAN_test_accuracy += GAN_outputs[-1][1]\n regressor_test_mean += regressor_outputs[-1][-2]\n regressor_test_sigma += regressor_outputs[-1][-1]\n regressor_pred.append(regressor_outputs[-1][2])\n regressor_true.append(regressor_outputs[-1][3])\n n_test_batches += 1\n\n classifier_test_loss /= n_test_batches\n GAN_test_loss /= n_test_batches\n classifier_test_accuracy /= n_test_batches\n GAN_test_accuracy /= n_test_batches\n regressor_test_mean /= n_test_batches\n regressor_test_sigma /= n_test_batches\n pred = np.concatenate(regressor_pred).ravel()\n true = np.concatenate(regressor_true).ravel()\n print('test accuracy: (C) %.4f, (G) %.4f' % (classifier_test_accuracy, GAN_test_accuracy))\n if (classifier != None): out_file.create_dataset(\"classifier_test_accuracy\", data=classifier_test_accuracy)\n if (regressor != None): out_file.create_dataset(\"regressor_pred\", data=pred)\n if (regressor != None): out_file.create_dataset(\"regressor_true\", data=true)\n if (GAN != None): out_file.create_dataset(\"GAN_test_accuracy\", data=GAN_test_accuracy)\n\n # outputs in form [loss, accuracy, outputs, truth, mean_rel_diff, sigma_rel_diff]\n return [classifier_outputs,regressor_outputs,GAN_outputs]\n","sub_path":"Analysis/Default_Analyzer.py","file_name":"Default_Analyzer.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"172045022","text":"# coding:utf-8\nfrom flask import jsonify, json, request\nfrom flask_jwt_extended import jwt_required, get_jwt_identity, current_user\n\nfrom common.DatatimeNow import getTimeToStrfdate, getTimeStrfTimeStampNow\nfrom common.FormatStr import dictRemoveNone\nfrom common.OperationOfDB import conditionDataListFind, findById, deleteById, insertToSQL, updataById, deleteByIdBoss\nfrom common.OperationOfDBClass import OperationOfDB\nfrom common.ReturnMessage import returnMsg, returnErrorMsg, returnErrorMsg, errorCode\nfrom version.v3.bossConfig import app\nfrom models.Boss.EditSettlement import EditSettlement, EditSettlementChangeDic as tableChangeDic, intList\nfrom common.Log import queryLog, addLog, deleteLog, updateLog\nimport Res\nfrom models.Data.SubFlow import SubFlow\nfrom common.FlowCommon import sendUp, returnUp\nfrom models.Data.Aidance import Aidance\nfrom models.Data.AidanceCheck import AidanceCheck, AidanceCheckChangeDic, intList as aidanceCheckIntList\nfrom common.FlowCommon import getFlowSort\n\n\n# 添加\n@app.route(\"/addEditSettlement\", methods=[\"POST\"])\n@jwt_required\ndef addEditSettlement():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n taskId = dataDict.get(\"taskId\", None)\n counselorId = dataDict.get(\"counselorId\", None)\n customerName = dataDict.get(\"customerName\", None)\n projectName = dataDict.get(\"projectName\", None)\n declarationLimit = dataDict.get(\"declarationLimit\", None)\n declarationPlan = dataDict.get(\"declarationPlan\", None)\n editFee = dataDict.get(\"editFee\", None)\n acceptFee = dataDict.get(\"acceptFee\", None)\n royaltyBase = dataDict.get(\"royaltyBase\", None)\n royaltyRatio = dataDict.get(\"royaltyRatio\", None)\n projectRoyalty = dataDict.get(\"projectRoyalty\", None)\n actualPayment = dataDict.get(\"actualPayment\", None)\n projectStatus = dataDict.get(\"projectStatus\", None)\n remark = dataDict.get(\"remark\", None)\n createPerson = dataDict.get(\"createPerson\", None)\n createTime = dataDict.get(\"createTime\", None)\n executePerson = dataDict.get(\"executePerson\", None)\n executeTime = dataDict.get(\"executeTime\", None)\n isDone = dataDict.get(\"isDone\", None)\n executeDone = dataDict.get(\"executeDone\", None)\n columsStr = (taskId, counselorId, customerName, projectName, declarationLimit, declarationPlan, editFee, acceptFee,\n royaltyBase, royaltyRatio, projectRoyalty, actualPayment, projectStatus, remark, createPerson,\n createTime,\n executePerson, executeTime, isDone, executeDone)\n table = insertToSQL(EditSettlement, *columsStr)\n if not table:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n resultDict = returnMsg({})\n return jsonify(resultDict)\n\n\n# 获取详情\n@app.route(\"/getEditSettlementDetail\", methods=[\"POST\"])\n@jwt_required\ndef getEditSettlementDetail():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n id = dataDict.get(\"id\", [])\n if not id:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n\n table = findById(EditSettlement, \"id\", id)\n if not table:\n resultDict = returnErrorMsg(errorCode[\"query_fail\"])\n return jsonify(resultDict)\n infoDict = tableSort(table)\n resultDict = returnMsg(infoDict)\n return jsonify(resultDict)\n\n\n# 商务经理 渠道商列表 待上报 已上报 已成功\n@app.route(\"/findEditSettlementByCondition\", methods=[\"POST\"])\n@jwt_required\ndef findEditSettlementByCondition():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n if dataDict.get('condition', None) == None:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n condition = dataDict.get(\"condition\")\n newList = [{\n \"field\": \"createPerson\",\n \"op\": \"equal\",\n \"value\": current_user.admin_name\n }]\n for newDict in newList:\n condition.append(newDict)\n tablename = EditSettlement.__tablename__\n intColumnClinetNameList = intList\n orderByStr = \" order by create_time desc \"\n tableList, count = conditionDataListFind(dataDict, tableChangeDic, intColumnClinetNameList, tablename,\n orderByStr=orderByStr)\n if tableList:\n InfoList = []\n for tableData in tableList:\n infoDict = tableSortDict(tableData)\n InfoList.append(infoDict)\n resultDict = returnMsg(InfoList)\n resultDict[\"total\"] = count\n else:\n resultDict = returnErrorMsg()\n return jsonify(resultDict)\n\n\n# 商务经理 被退回 列表\n@app.route(\"/findViewInnerEditSettlementByCondition\", methods=[\"POST\"])\n@jwt_required\ndef findViewInnerEditSettlementByCondition():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n if dataDict.get('condition', None) == None:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n condition = dataDict.get(\"condition\")\n newList = [{\n \"field\": \"createPerson\",\n \"op\": \"equal\",\n \"value\": current_user.admin_name\n }]\n for newDict in newList:\n condition.append(newDict)\n tablename = \"view_aidance_check_edit_settlement\" # view_aidance_check_channel_user\n intColumnClinetNameList = intList\n orderByStr = \" order by create_time desc \"\n tableList, count = conditionDataListFind(dataDict, view_aidance_check_flow_boss_edit_settlement_change,\n intColumnClinetNameList,\n tablename,\n orderByStr=orderByStr)\n if tableList:\n InfoList = []\n for tableData in tableList:\n infoDict = view_aidance_check_flow_boss_edit_settlement_fun(tableData)\n InfoList.append(infoDict)\n resultDict = returnMsg(InfoList)\n resultDict[\"total\"] = count\n else:\n resultDict = returnErrorMsg()\n return jsonify(resultDict)\n\n\n# 合同中间人 列表\n@app.route(\"/findViewEditSettlementByCondition\", methods=[\"POST\"])\n@jwt_required\ndef findViewEditSettlementByCondition():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n roleId = dataDict.get(\"roleId\", None)\n if not ((dataDict.has_key(\"condition\")) and roleId):\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n condition = dataDict.get(\"condition\")\n flowId = Res.workFlow[\"xmjssh\"]\n sort = getFlowSort(flowId, roleId)\n if not sort:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n # 传入 flowId and checkStatus\n newDictList = [{\n \"field\": \"checkPerson\",\n \"op\": \"equal\",\n \"value\": current_user.admin_name\n }, {\n \"field\": \"sort\",\n \"op\": \"equal\",\n \"value\": sort\n }]\n for newDict in newDictList:\n condition.append(newDict)\n tableName = \"view_aidance_check_edit_settlement\"\n intColumnClinetNameList = [\"sort\", u'id', u'flowId', u'checkId', u'fromId', u'serviceId', u'flowStep',\n u'acceptStatus',\n u'isDone', u'aidanceCheckId', u'aidanceId', u'checkType', u'checkStatus', u'isCheck',\n \"taskType\"]\n\n orderByStr = \" order by create_time desc\"\n resultList, count = conditionDataListFind(dataDict, view_aidance_check_flow_boss_edit_settlement_change,\n intColumnClinetNameList=intColumnClinetNameList,\n tableName=tableName, orderByStr=orderByStr)\n if resultList:\n infoList = []\n for tableData in resultList:\n _infoDict = view_aidance_check_flow_boss_edit_settlement_fun(tableData)\n infoList.append(_infoDict)\n resultDict = returnMsg(infoList)\n resultDict[\"total\"] = count\n else:\n resultDict = returnErrorMsg()\n return jsonify(resultDict)\n\n\n# 商务经理送审 # 上报\n@app.route(\"/updataUpEditSettlementCheckStatus\", methods=[\"POST\"])\n@jwt_required\ndef updataUpEditSettlementCheckStatus():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n idList = dataDict.get(\"ids\", \"\") # 单项服务id\n roleId = dataDict.get(\"roleId\", \"\")\n choicePerson = dataDict.get(\"choicePerson\", \"\")\n if not (idList and roleId):\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n dbOperation = OperationOfDB()\n for id in idList:\n table = findById(EditSettlement, \"id\", id)\n if not table:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n reslut = sendUp(table, choicePerson, dbOperation, flowId=Res.workFlow[\"xmjssh\"], taskType=None)\n if not reslut:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n if dbOperation.commitToSQL():\n resultDict = returnMsg({})\n else:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"commit_fail\"])\n return jsonify(resultDict)\n\n\n# 更新 完善 并上报\n@app.route(\"/updataEditSettlement\", methods=[\"POST\"])\n@jwt_required\ndef updataEditSettlement():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n id = dataDict.get(\"id\", \"\")\n checkStatus = dataDict.get('checkStatus', \"\")\n if not id:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n popList = [\"choicePerson\", \"checkStatus\"]\n for popStr in popList:\n if dataDict.has_key(popStr):\n dataDict.pop(popStr)\n dbOperation = OperationOfDB()\n table = dbOperation.updateThis(EditSettlement, EditSettlement.id, id, dataDict, tableChangeDic)\n if not table:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n if checkStatus == 2:\n reslut = sendUp(table, None, dbOperation, flowId=Res.workFlow[\"xmjssh\"], taskType=None)\n if not reslut:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n if dbOperation.commitToSQL():\n resultDict = returnMsg({})\n else:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"commit_fail\"])\n return jsonify(resultDict)\n\n\n# 退回 重新上报\n@app.route(\"/updataUpReturnEditSettlement\", methods=[\"POST\"])\n@jwt_required\ndef updataUpReturnEditSettlement():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n id = dataDict.get(\"id\", \"\")\n checkStatus = dataDict.get(\"checkStatus\")\n choicePerson = dataDict.get(\"choicePerson\", \"\")\n if not id:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n popList = [\"choicePerson\", \"checkStatus\"]\n for popStr in popList:\n if dataDict.has_key(popStr):\n dataDict.pop(popStr)\n dbOperation = OperationOfDB()\n aidanceTable = findById(Aidance, \"id\", id)\n if not aidanceTable:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n serviceId = aidanceTable.service_id\n table = dbOperation.updateThis(EditSettlement, EditSettlement.id, serviceId, dataDict, tableChangeDic)\n if not table:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n if checkStatus == 2:\n result = returnUp(aidanceTable, table, dbOperation, choicePerson)\n if not result:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n if dbOperation.commitToSQL():\n resultDict = returnMsg({})\n else:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"commit_fail\"])\n return jsonify(resultDict)\n\n\n# 退回 上报\n@app.route(\"/sendUpReturnEditSettlement\", methods=[\"POST\"])\n@jwt_required\ndef sendUpReturnEditSettlement():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n idList = dataDict.get(\"ids\", \"\")\n choicePerson = dataDict.get(\"choicePerson\", \"\")\n if not idList:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n popList = [\"choicePerson\", \"checkStatus\"]\n for popStr in popList:\n if dataDict.has_key(popStr):\n dataDict.pop(popStr)\n dbOperation = OperationOfDB()\n for id in idList:\n aidanceTable = findById(Aidance, \"id\", id)\n if not aidanceTable:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"query_fail\"])\n return jsonify(resultDict)\n serviceId = aidanceTable.service_id\n table = findById(EditSettlement, \"id\", serviceId)\n if not table:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n result = returnUp(aidanceTable, table, dbOperation, choicePerson)\n if not result:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n if dbOperation.commitToSQL():\n resultDict = returnMsg({})\n else:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"commit_fail\"])\n return jsonify(resultDict)\n\n\n# 商务合同 转移给其他商务经理\n@app.route(\"/EditSettlementTransferOtherPerson\", methods=[\"POST\"])\n@jwt_required\ndef EditSettlementTransferOtherPerson():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n idList = dataDict.get(\"ids\", \"\")\n createPerson = dataDict.get(\"createPerson\", \"\")\n if not (idList and createPerson):\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n dbOperation = OperationOfDB()\n for id in idList:\n table = dbOperation.updateThis(EditSettlement, EditSettlement.id, id, dataDict,\n tableChangeDic)\n if not table:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n if dbOperation.commitToSQL():\n resultDict = returnMsg({})\n else:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"commit_fail\"])\n return jsonify(resultDict)\n\n\n# 删除 \n@app.route(\"/deleteEditSettlement\", methods=[\"POST\"])\n@jwt_required\ndef deleteEditSettlement():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n idList = dataDict.get(\"ids\", [])\n if not idList:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n count = deleteByIdBoss(EditSettlement, idList, \"id\")\n if count == len(idList):\n resultDict = returnMsg({})\n else:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n\n\n# 总经理同意\n@app.route(\"/finallyCheckEditSettlement\", methods=[\"POST\"])\n@jwt_required\ndef finallyCheckEditSettlement():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n id = dataDict.get(\"id\", \"\")\n checkStatus = dataDict.get(\"checkStatus\", \"\")\n if not (id and checkStatus):\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n if dataDict.has_key(\"roleId\"):\n dataDict.pop(\"roleId\")\n aidanceTable = findById(Aidance, \"id\", id)\n if not aidanceTable:\n resultDict = returnErrorMsg(errorCode[\"query_fail\"])\n return jsonify(resultDict)\n dbOperation = OperationOfDB()\n now = getTimeStrfTimeStampNow()\n if checkStatus == Res.AuditCode[\"pass\"]:\n # 更新 aidance\n aidanceTable.accept_status = 1\n aidanceTable.execute_person = current_user.admin_name\n aidanceTable.is_done = 2\n aidanceTable.complete_time = now\n aidanceTable.flow_step += 1\n aidanceTable = dbOperation.addTokenToSql(aidanceTable)\n if not aidanceTable:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n serviceId = aidanceTable.service_id\n # 更新 明细\n serviceTable = dbOperation.findById(EditSettlement, \"id\", serviceId)\n if not serviceTable:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"query_fail\"])\n return jsonify(resultDict)\n serviceTable.is_done = 2\n if not serviceTable:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n\n # communicateInfo = dbOperation.insertToSQL(Communicate, *CommunicateStr)\n # if not communicateInfo:\n # dbOperation.commitRollback()\n # resultDict = returnErrorMsg(errorCode[\"param_error\"])\n # return jsonify(resultDict)\n elif checkStatus == Res.AuditCode[\"fail\"]:\n aidanceTable.flow_step = 1\n aidanceTable = dbOperation.addTokenToSql(aidanceTable)\n if not aidanceTable:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"query_fail\"])\n return jsonify(resultDict)\n else:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n checkId = aidanceTable.check_id\n intColumnClinetNameList = aidanceCheckIntList\n checkInfo = dbOperation.updateThis(AidanceCheck, AidanceCheck.id, checkId, dataDict, AidanceCheckChangeDic,\n intColumnClinetNameList=intColumnClinetNameList)\n if not checkInfo:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"update_fail\"])\n return jsonify(resultDict)\n if dbOperation.commitToSQL():\n resultDict = returnMsg({})\n else:\n dbOperation.commitRollback()\n resultDict = returnErrorMsg(errorCode[\"commit_fail\"])\n return jsonify(resultDict)\n\n\n# NewAidanceApi.py checkAidanceCheck\n\ndef tableSort(table):\n _infoDict = {\"id\": table.id,\n \"taskId\": table.task_id,\n \"counselorId\": table.counselor_id,\n \"customerName\": table.customer_name,\n \"projectName\": table.project_name,\n \"declarationLimit\": table.declaration_limit,\n \"declarationPlan\": table.declaration_plan,\n \"editFee\": table.edit_fee,\n \"acceptFee\": table.accept_fee,\n \"royaltyBase\": table.royalty_base,\n \"royaltyRatio\": table.royalty_ratio,\n \"projectRoyalty\": table.project_royalty,\n \"actualPayment\": table.actual_payment,\n \"projectStatus\": table.project_status,\n \"remark\": table.remark,\n \"createPerson\": table.create_person,\n \"createTime\": table.create_time,\n \"executePerson\": table.execute_person,\n \"executeTime\": table.execute_time,\n \"isDone\": table.is_done,\n \"executeDone\": table.execute_done, }\n _infoDict = dictRemoveNone(_infoDict)\n return _infoDict\n\n\ndef tableSortDict(tableData):\n _infoDict = {\"id\": tableData[0],\n \"taskId\": tableData[1],\n \"counselorId\": tableData[2],\n \"customerName\": tableData[3],\n \"projectName\": tableData[4],\n \"declarationLimit\": tableData[5],\n \"declarationPlan\": tableData[6],\n \"editFee\": tableData[7],\n \"acceptFee\": tableData[8],\n \"royaltyBase\": tableData[9],\n \"royaltyRatio\": tableData[10],\n \"projectRoyalty\": tableData[11],\n \"actualPayment\": tableData[12],\n \"projectStatus\": tableData[13],\n \"remark\": tableData[14],\n \"createPerson\": tableData[15],\n \"createTime\": tableData[16],\n \"executePerson\": tableData[17],\n \"executeTime\": tableData[18],\n \"isDone\": tableData[19],\n \"executeDone\": tableData[20], }\n _infoDict = dictRemoveNone(_infoDict)\n return _infoDict\n\n\ndef view_aidance_check_flow_boss_edit_settlement_fun(tableData):\n _infoDict = {\n \"id\": tableData[0],\n \"customerName\": tableData[1],\n \"createReason\": tableData[2],\n \"createRealName\": tableData[3],\n \"createTime\": tableData[4],\n \"flowId\": tableData[5],\n \"remark\": tableData[6],\n \"executePerson\": tableData[7],\n \"createPerson\": tableData[8],\n \"completeTime\": tableData[9],\n \"checkId\": tableData[10],\n \"fromId\": tableData[11],\n \"serviceId\": tableData[12],\n \"flowStep\": tableData[13],\n \"acceptStatus\": tableData[14],\n \"isDone\": tableData[15],\n \"taskType\": tableData[16],\n \"submitTime\": tableData[17],\n \"submitPerson\": tableData[18],\n \"checkStatus\": tableData[19],\n \"checkTime\": tableData[20],\n \"checkPerson\": tableData[21],\n \"checkRemark\": tableData[22],\n \"sort\": tableData[23],\n \"name\": tableData[24],\n \"desc\": tableData[25],\n \"num\": tableData[26],\n \"counselorId\": tableData[27],\n \"editCustomerName\": tableData[28],\n \"projectName\": tableData[29],\n \"declarationLimit\": tableData[30],\n \"declarationPlan\": tableData[31],\n \"editFee\": tableData[32],\n \"acceptFee\": tableData[33],\n \"royaltyBase\": tableData[34],\n \"royaltyRatio\": tableData[35],\n \"projectRoyalty\": tableData[36],\n \"actualPayment\": tableData[37],\n \"projectStatus\": tableData[38],\n \"editRemark\": tableData[39], }\n _infoDict = dictRemoveNone(_infoDict)\n return _infoDict\n\n\nview_aidance_check_flow_boss_edit_settlement_change = {\n \"id\": \"id\",\n \"customerName\": \"customer_name\",\n \"createReason\": \"create_reason\",\n \"createRealName\": \"create_real_name\",\n \"createTime\": \"create_time\",\n \"flowId\": \"flow_id\",\n \"remark\": \"remark\",\n \"executePerson\": \"execute_person\",\n \"createPerson\": \"create_person\",\n \"completeTime\": \"complete_time\",\n \"checkId\": \"check_id\",\n \"fromId\": \"from_id\",\n \"serviceId\": \"service_id\",\n \"flowStep\": \"flow_step\",\n \"acceptStatus\": \"accept_status\",\n \"isDone\": \"is_done\",\n \"taskType\": \"task_type\",\n \"submitTime\": \"submit_time\",\n \"submitPerson\": \"submit_person\",\n \"checkStatus\": \"check_status\",\n \"checkTime\": \"check_time\",\n \"checkPerson\": \"check_person\",\n \"checkRemark\": \"check_remark\",\n \"sort\": \"sort\",\n \"name\": \"name\",\n \"desc\": \"desc\",\n \"num\": \"num\",\n \"counselorId\": \"counselor_id\",\n \"editCustomerName\": \"edit_customer_name\",\n \"projectName\": \"project_name\",\n \"declarationLimit\": \"declaration_limit\",\n \"declarationPlan\": \"declaration_plan\",\n \"editFee\": \"edit_fee\",\n \"acceptFee\": \"accept_fee\",\n \"royaltyBase\": \"royalty_base\",\n \"royaltyRatio\": \"royalty_ratio\",\n \"projectRoyalty\": \"project_royalty\",\n \"actualPayment\": \"actual_payment\",\n \"projectStatus\": \"project_status\",\n \"editRemark\": \"edit_remark\", }\n","sub_path":"boss_service/controllers/EditSettlementApi.py","file_name":"EditSettlementApi.py","file_ext":"py","file_size_in_byte":23746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"312470045","text":"from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem\n\n\ndef createTableFromPYMYSQL(table_data=None, parent=None):\n table = QTableWidget(parent)\n table.setEditTriggers(QTableWidget.NoEditTriggers)\n try:\n table.setColumnCount(len(table_data.keys()))\n table.setRowCount(len(table_data[list(table_data.keys())[0]]))\n table.setHorizontalHeaderLabels(table_data.keys())\n for col, key in enumerate(table_data.keys()):\n for row, value in enumerate(table_data[key]):\n table.setItem(row, col, QTableWidgetItem(str(value)))\n table.resizeColumnsToContents()\n except:\n table.setColumnCount(1)\n table.setRowCount(1)\n table.setItem(0, 0, QTableWidgetItem(\"None\"))\n table.resizeColumnsToContents()\n finally:\n return table\n\n\ndef createTableFromMYSQLDB(table_data=None, headers=None, parent=None):\n table = QTableWidget(parent)\n table.setEditTriggers(QTableWidget.NoEditTriggers)\n try:\n table.setColumnCount(len(headers))\n table.setRowCount(len(table_data))\n table.setHorizontalHeaderLabels(headers)\n for row, record in enumerate(table_data):\n for col, value in enumerate(record):\n table.setItem(row, col, QTableWidgetItem(str(value)))\n table.resizeColumnsToContents()\n except:\n table.setColumnCount(1)\n table.setRowCount(1)\n table.setItem(0, 0, QTableWidgetItem(\"None\"))\n table.resizeColumnsToContents()\n finally:\n return table\n\n\ndef getRow(items):\n row = None\n for item in items:\n if row == None:\n row = item.row()\n elif row != item.row():\n return (row, False)\n return (row, True)\n\n\nclass NoneConnectionError(AttributeError):\n ''''''\n","sub_path":"additional_modules.py","file_name":"additional_modules.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"575441276","text":"def line(txt:str = '', totalcaracters:int = 0, upper:bool = False):\n\n \"\"\"\n Makes a line before and after the text you write\n :param txt: The text that you will be passing through\n :param totalcaracters: The number of caracters that it will be ocuping (Default = 0)\n :param upper: If the caracters will be on upper case\n \"\"\"\n if(txt == ''):\n text = '-' * totalcaracters\n elif(totalcaracters < (len(txt) + 2)):\n if(upper == True):\n text = ('{} \\n{} \\n{}'.format('-' * (len(txt) + 2), txt.upper().center(len(txt) + 2), '-' * (len(txt) + 2)))\n else: \n text = ('{} \\n{} \\n{}'.format('-' * (len(txt) + 2), txt.center(len(txt) + 2), '-' * (len(txt) + 2)))\n else:\n if(upper == True):\n text = ('{} \\n{} \\n{}'.format('-' * totalcaracters, txt.upper().center(totalcaracters), '-' * (totalcaracters)))\n else: \n text = ('{} \\n{} \\n{}'.format('-' * totalcaracters, txt.center(totalcaracters), '-' * (totalcaracters)))\n \n print(text)","sub_path":"utils/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"501941234","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 ('ProjectManager', '0002_auto_20150814_0248'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Task',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('Task', models.CharField(max_length=200)),\n ('objective', models.CharField(max_length=200)),\n ('Due_Date', models.DateTimeField()),\n ('Finish_Date', models.DateTimeField()),\n ],\n ),\n migrations.RenameModel(\n old_name='Contacts',\n new_name='Contact',\n ),\n migrations.DeleteModel(\n name='Tasks',\n ),\n ]\n","sub_path":"ProjectManager/migrations/0003_auto_20150907_1913.py","file_name":"0003_auto_20150907_1913.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"560930410","text":"import pandas as pd\nimport numpy as np\nfrom mlxtend.preprocessing import TransactionEncoder\nfrom mlxtend.frequent_patterns import apriori\nimport matplotlib.pyplot as plt\n\n\nsaveFigure = False\nplot_base_path = 'plots/lab3/'\n\n\nall_data = pd.read_csv('datasets/dataset_group.csv',header=None)\n# all_data['date'] = pd.to_datetime(all_data[0])\n\n\nall_data.dtypes\n\n\nunique_id = all_data[1].unique()\nprint(unique_id.size)\n\n\nitems = all_data[2].unique()\nprint(items.size)\n\n\ndataset = [[elem for elem in all_data[all_data[1] == id][2] if elem in items] for id in unique_id]\n\n\nte = TransactionEncoder()\nte_ary = te.fit_transform(dataset)\ndf = pd.DataFrame(te_ary, columns=te.columns_)\n\n\n# 1\nresults = apriori(df, min_support=0.3, use_colnames=True)\nresults['length'] = results['itemsets'].apply(lambda x: len(x))\nprint(results)\n\n\nresults_orig = apriori(df, min_support=0.3, use_colnames=True, max_len=1)\nresults_orig['length'] = results_orig['itemsets'].apply(lambda x: len(x))\nprint(results_orig)\n\n\nresults = apriori(df, min_support=0.3, use_colnames=True)\nresults['length'] = results['itemsets'].apply(lambda x: len(x))\nresults_2 = results[results['length'] == 2]\nprint(results_2)\n\n\nprint('\\nCount of result itemstes = ',len(results_2))\n\n\nmin_sups = np.arange(0.05, 0.74, 0.01)\ncounts_of_itemesets = []\napriori_results = []\n\n\nfor min_sup in min_sups:\n apriori_results.append(apriori(df, min_support=min_sup, use_colnames=True))\n counts_of_itemesets.append(apriori_results[-1].shape[0])\ncounts_of_itemesets = np.array(counts_of_itemesets)\n\n\nmax_len_of_itemsets = np.fromiter(map(lambda x: x.itemsets.map(len).max(), apriori_results), dtype=int)\n\n\ndf_ = pd.DataFrame({'min_sup': min_sups, 'count_of_itemeset': counts_of_itemesets})\n\n\nminimal_min_sup_for_itemsets_count = []\nunique_max_len_of_items = np.unique(max_len_of_itemsets)\nfor count in unique_max_len_of_items:\n minimal_min_sup_for_itemsets_count.append(\n np.where(max_len_of_itemsets == count)[0][0]\n )\n\n\n# unique_max_len_of_items\nminimal_min_sup_for_itemsets_count\n\n\nend_of_generating_n_length_itemsets = list(reversed(minimal_min_sup_for_itemsets_count))[1:]\n\n\n# 4+5\nfig, ax = plt.subplots(figsize=(8,6))\nfig.suptitle('Зависимость количества наборов от уровня поддержки', fontsize=16)\nax.plot(df_.min_sup, df_.count_of_itemeset, linewidth=2)\nfor i in end_of_generating_n_length_itemsets:\n plt.axvline(df_.min_sup[i] - 0.005, color='red')\nax.set_yscale('log')\nax.set_xlabel('Уровень поддержки')\nax.set_ylabel('Количество наборов')\nif saveFigure:\n plt.savefig(plot_base_path+'count_of_sets_supp.png')\nplt.show()\n\n\n# 6\nresults = apriori(df, min_support=0.38, use_colnames=True, max_len=1)\nnew_items = [ list(elem)[0] for elem in results['itemsets']]\nnew_dataset = [[elem for elem in all_data[all_data[1] == id][2] if elem in new_items] for id in unique_id]\n\n\n# 7\nte = TransactionEncoder()\nte_ary = te.fit_transform(new_dataset)\ndf_new = pd.DataFrame(te_ary, columns=te.columns_)\n\n\n# 8\nresults_new = apriori(df_new, min_support=0.3, use_colnames=True)\nresults_new['length'] = results_new['itemsets'].apply(lambda x: len(x))\nprint(results_new)\n\n\n# 9\nresults = apriori(df_new, min_support=0.15, use_colnames=True)\nresults['length'] = results['itemsets'].apply(lambda x: len(x))\nprint(results)\n\n\n# 10\ndiff = set(list(df)) - set(list(df_new))\ndiff_items = [ list(elem)[0] for elem in results['itemsets']]\ndiff_dataset = [[elem for elem in all_data[all_data[1] == id][2] if elem not in diff_items] for id in unique_id]\nte = TransactionEncoder()\nte_ary = te.fit_transform(diff_dataset)\ndf_new = pd.DataFrame(te_ary, columns=te.columns_)\n\n\n# 11\nprint(apriori(df, min_support=0.3, use_colnames=True))\n\n\n# 12\ndef two_elems_starts_with_s(df, threshold=2):\n return df[\n df['itemsets'].apply(\n lambda x: np.fromiter(\n map(lambda y: y[0]=='s', x), dtype=bool\n ).sum()>=threshold\n )\n ]\n\n\nprint(two_elems_starts_with_s(apriori_results[0]))\n\n\n# 13\ndef subset_10_25(df):\n return df[np.logical_and(df.support>=0.1, df.support <= 0.25)]\n\n\nprint(subset_10_25(apriori_results[0]))\n\n\n","sub_path":"6304_Dobrokhvalov/labs/lab3/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"121348399","text":"import scrublet as scr\nimport scipy.io\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd \n\n#def scr_pipe(file_name,gene_name,exp_rate=0.1):\ndef scr_pipe(file_name,exp_rate=0.1):\n counts_matrix = scipy.io.mmread(file_name).T.tocsc()\n if \"/\" in file_name:\n home_dir=\"/\".join(file_name.split(\"/\")[0:len(file_name.split(\"/\"))-5])\n pr_name=file_name.split(\"/\")[-2]\n file_name=file_name.split(\"/\")[-1]\n else :\n home_dir=\"/\".join(os.getcwd().split(\"/\")[0:len(os.getcwd().split(\"/\"))-3])\n pr_name=os.getcwd().split(\"/\")[-1]\n \n name=file_name.split(\".raw\")[0]\n out_dir=home_dir+\"/Scrublet/output/\"+pr_name+\"/\"\n #genes = np.array(scr.load_genes(home_dir+data_dir+pr_name + 'genes.tsv', delimiter='\\t', column=1))\n print('Counts matrix shape: {} rows, {} columns'.format(counts_matrix.shape[0], counts_matrix.shape[1]))\n scrub = scr.Scrublet(counts_matrix, expected_doublet_rate=exp_rate)\n doublet_scores, predicted_doublets = scrub.scrub_doublets(min_counts=2, \n min_cells=3, \n min_gene_variability_pctl=85, \n n_prin_comps=30)\n print(out_dir+name+\".Scr.doublet.scores.\"+str(exp_rate)+\"exp_rate.csv\")\n pd.DataFrame(doublet_scores).to_csv(out_dir+name+\".Scr.doublet.scores.\"+str(exp_rate)+\"exp_rate.csv\")","sub_path":"Python/scr_pipe.py","file_name":"scr_pipe.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"274690206","text":"nol, st = [x for x in input().split()]\nnol = int(nol)\nFortune = True\nLucky = False\nfor x in st:\n if x not in [\"4\", \"7\", \"0\"]:\n Fortune = False\n break\nif Fortune:\n left = sum([int(x) for x in st[:nol//2]])\n rite = sum([int(x) for x in st[nol//2:]])\n if left == rite : Lucky = True\nprint(\"YES\" if Lucky else \"NO\")\n","sub_path":"codechef/COX031.py","file_name":"COX031.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"391566958","text":"# noinspection DuplicatedCode,SpellCheckingInspection\nclass Actor:\n __actor_full_name: str\n __actor_id: int\n\n def __init__(self, actor_full_name: str):\n if actor_full_name == \"\" or type(actor_full_name) is not str or actor_full_name == \"\\n\":\n self.__actor_full_name = None\n else:\n self.__actor_full_name = actor_full_name.strip()\n self.colleague_dict = {f\"{self.__repr__()}\": []}\n # check for multiple names\n self.names_count = self.__actor_full_name.count(\" \") + 1\n # assign first and last names\n if self.names_count < 3:\n if \" \" in self.__actor_full_name:\n self.firstname = self.actor_full_name[:self.__actor_full_name.find(\" \")]\n self.lastname = self.actor_full_name[self.__actor_full_name.find(\" \") + 1:]\n else:\n self.firstname = self.__actor_full_name\n self.lastname = self.actor_full_name # In case actor goes by single name, first and last name\n # will be assigned the same name for indexing purposes.\n # Assign first, middle and last names\n else:\n self.firstname = self.actor_full_name[:self.__actor_full_name.find(\" \")]\n self.middlenames = self.__actor_full_name[\n actor_full_name.find(\" \") + 1: self.__actor_full_name.rfind(\"\")]\n self.lastname = self.__actor_full_name[self.__actor_full_name.rfind(\" \") + 1:]\n self.__firstname = self.firstname\n self.__lastname = self.lastname\n self.__actor_id = self.__hash__()\n\n\n def check_if_this_actor_worked_with(self, colleague):\n if colleague.actor_full_name in self.colleague_dict[self.__repr__()]:\n return True\n elif self.actor_full_name in colleague.colleague_dict[colleague.__repr__()]:\n return True\n else:\n return False\n\n def add_actor_colleague(self, colleague):\n if colleague.actor_full_name not in self.colleague_dict.values():\n self.colleague_dict[self.__repr__()].append(colleague.actor_full_name)\n\n if self.actor_full_name not in colleague.colleague_dict.values():\n colleague.colleague_dict[colleague.__repr__()].append(self.actor_full_name)\n\n @property\n def actor_full_name(self) -> str:\n return self.__actor_full_name\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n return self.__actor_full_name == other.__actor_full_name\n\n def __lt__(self, other):\n # The following code is duplicated in the Actor class\n # Consider moving the following into a separate function or method accessible to both classes\n # Duplicate code start:\n name_list = [self, other]\n if hasattr(self, \"firstname\") and hasattr(other, \"firstname\"):\n if self.firstname != other.firstname:\n name_list.sort(key=lambda x: x.firstname)\n elif self.lastname != other.lastname:\n name_list.sort(key=lambda x: x.lastname)\n else:\n if self.middlenames.lower() == other.middlenames.lower():\n name_list.sort(key=lambda x: x.middlenames)\n if self == name_list[0]:\n return True\n else:\n return False\n # Duplicate code end\n\n def __hash__(self):\n if hasattr(self, \"firstname\"):\n hash_string = f\"{self.firstname[0]}{self.lastname}-{self.firstname}{self.lastname}-{self.__actor_full_name}\"\n return hash(hash_string)\n else:\n return None\n @property\n def firstname(self):\n return self.__firstname\n\n @property\n def lastname(self):\n return self.__lastname\n\n @lastname.setter\n def lastname(self, value):\n self.__lastname = value\n\n @firstname.setter\n def firstname(self, value):\n self.__firstname = value\n\n\n# noinspection DuplicatedCode\nclass TestActorMethods:\n\n def test_init(self):\n actor1 = Actor(\"Taika Waititi\")\n actor2 = Actor(\"\")\n actor3 = Actor(42)\n actor4 = Actor(\"\\n\")\n actor5 = Actor(\"Quo Quo\")\n actor6 = Actor(\"Taika Woititi\")\n actor7 = Actor(\"Edgar Allan Poe\")\n actor8 = Actor(\"Edgar Allan Poe Poe\")\n actor9 = Actor(\"James Earl Joyce\")\n actor10 = Actor(\"James earl Joyce\")\n actor11 = Actor(\"James Earl Jimmy Joyce\")\n actor12 = Actor(\"James Earl jimmy Jones\")\n actor13 = Actor(\"Tarantino\")\n actor14 = Actor(\"James earl Jimmy Jones\")\n actor15 = Actor(\".\")\n assert repr(actor1) == \"\"\n assert actor1.lastname == \"Waititi\"\n assert actor2.actor_full_name is None\n assert actor3.actor_full_name is None\n assert actor4.actor_full_name is None\n assert actor1.firstname == \"Taika\"\n assert actor13.lastname == \"Tarantino\"\n assert actor14.__lt__(actor12) == \"Possible duplicate\"\n assert actor2.__lt__(actor4) is None\n assert actor7.actor_full_name == \"Edgar Allan Poe\"\n assert actor7.firstname == \"Edgar\"\n assert actor7.names_count == 3\n assert actor8.names_count == 4\n assert actor7.middlenames == \"Allan Poe\"\n assert actor4.__eq__(actor4) is True\n assert actor4.__eq__(actor1) is False\n assert actor1.__lt__(actor6) is True # [actor1.actor_full_name, actor6.actor_full_name]\n assert actor9.__lt__(actor10) == \"Possible duplicate\"\n assert actor10.__lt__(actor11) is True # == [actor10.actor_full_name, actor11.actor_full_name]\n assert actor11.__lt__(actor12) is False # == [actor12.actor_full_name, actor11.actor_full_name]\n assert actor5.__lt__(actor1) is True # == [actor5.actor_full_name, actor1.actor_full_name]\n assert actor1.__lt__(actor5) is False # == [actor5.actor_full_name, actor1.actor_full_name]\n assert actor1.__lt__(actor6) is True # == [actor1.actor_full_name, actor6.actor_full_name]\n assert actor15.firstname == \".\"\n\n# actor1 = Actor(\"Taika Waititi\")\n# actor2 = Actor(\"\")\n# actor3 = Actor(42)\n# actor4 = Actor(\"\\n\")\n# actor5 = Actor(\"Quo Quo\")\n# actor6 = Actor(\"Taika Woititi\")\n# actor7 = Actor(\"Edgar Allan Poe\")\n# actor8 = Actor(\"Edgar Allan Poe Poe\")\n# actor9 = Actor(\"James Earl Joyce\")\n# actor10 = Actor(\"James earl Joyce\")\n# actor11 = Actor(\"James Earl Jimmy Joyce\")\n# actor12 = Actor(\"James Earl jimmy Jones\")\n# actor13 = Actor(\"Tarantino\")\n# actor14 = Actor(\"James earl Jimmy Jones\")\n# actor15 = Actor(\".\")\n#\n# print(actor1.__hash__())\n# print(actor2.__hash__())\n\n\n# actor1 = Actor(\"Cameron Diaz\")\n# actor2 = Actor(\"Angelina Jolie\")\n# actor3 = Actor(\"Brad Pitt\")\n# print(actor1 < actor2)\n# print(actor1 > actor3)\n# print(actor2 < actor3)\n\n# actor1 = Actor(\"Angelina Jolie\")\n# print(actor1)\n# actor2 = Actor(\"\")\n# print(actor2)\n# actor3 = Actor(42)\n# print(actor3)\n# actor4 = Actor(\"Brad Pitt\")\n# actor5 = Actor(\"Seth Rogan\")\n# print(actor1.check_if_this_actor_worked_with(actor4))\n# print(actor1.add_actor_colleague(actor4))\n# print(actor1.add_actor_colleague(actor5))\n# print(actor1.check_if_this_actor_worked_with(actor4))\n# print(actor4.check_if_this_actor_worked_with(actor1))\n# print(actor1.check_if_this_actor_worked_with(actor5))\n#\n","sub_path":"appl/domainmodel/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":7397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"422214849","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/8/20 10:13\n# @Author : Wang fang chen\n# @Email : itjavawfc@163.com\n# @WeiXin :w335441537\n# @File : 简单算法.py\n# @Software: PyCharm\narray = [[col for col in range(5)] for row in range(5)] # 初始化一个4*4数组\n# array=[[col for col in 'abcde'] for row in range(5)]\n\nfor row in array: # 旋转前先看看数组长啥样\n print(row)\n\nprint('-------------')\nfor i, row in enumerate(array):\n\n for index in range(i, len(row)):\n tmp = array[index][i] # get each rows' data by column's index\n array[index][i] = array[i][index] #\n print(tmp, array[i][index]) # = tmp\n array[i][index] = tmp\n for r in array: print(r)\n\n print('--one big loop --')\n\nprint('*'*60)\n#冒泡排序 将一个不规则的数组按从小到大的顺序进行排序\ndata = [10, 4, 33, 21, 54, 3, 8, 11, 5, 22, 2, 1, 17, 13, 6]\nprint(\"before sort:\", data)\nprevious = data[0]\nfor j in range(len(data)):\n print(j)\n tmp = 0\n for i in range(len(data) - 1):\n if data[i] > data[i + 1]:\n tmp = data[i]\n data[i] = data[i + 1]\n data[i + 1] = tmp\n print(data)\nprint(\"after sort:\", data)\n\n\n","sub_path":"com/wfc/python/day2/简单算法.py","file_name":"简单算法.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"316864953","text":"def main():\n letters = [letter for letter in input() if letter.isalpha()]\n def distinct_letters(letters):\n dletters = {}\n for letter in letters: \n if letter not in dletters:\n dletters[letter] = None\n return len(dletters)\n\n print(distinct_letters(letters))\nif __name__ == '__main__':\n main()","sub_path":"Code Forecs Problems/anton_and_letters.py","file_name":"anton_and_letters.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"506245402","text":"# Socurce of project :\r\n# Build Simple \r\n# Restful Api With Python and Flask Part 2\r\n# by Mukhammad Ginanjar Azie\r\n\r\n\r\n\r\nfrom flask import Flask , request , jsonify \r\nfrom flask_sqlalchemy import SQLAlchemy \r\nfrom flask_marshmallow import Marshmallow\r\nimport os\r\n\r\napp = Flask(__name__)\r\n#basedir = os.path.abspath(os.path.dirname(__file__))\r\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///crud.db'\r\n# + os.path.join(basedir, 'crud.sqlite')\r\n\r\n\r\ndb = SQLAlchemy(app)\r\nma = Marshmallow(app)\r\n\r\n\r\n\r\nclass User(db.Model):\r\n\tid = db.Column(db.Integer,primary_key='True')\r\n\tusername = db.Column(db.String(80) , unique = True )\r\n\temail = db.Column(db.String(120),unique = True)\r\n\r\n\tdef __init__(self,username,email):\r\n\t\tself.username = username\r\n\t\tself.email = email\r\n\r\n\r\nclass UserSchema(ma.Schema):\r\n\tclass Meta:\r\n\t\tfields = ('username','email')\r\n\r\nuser_schema = UserSchema()\r\nusers_schema = UserSchema(many=True)\r\n\r\n\r\n@app.route(\"/user\", methods=[\"POST\"])\r\ndef add_user():\r\n username = request.json['username']\r\n email = request.json['email']\r\n \r\n new_user = User(username, email)\r\n\r\n db.session.add(new_user)\r\n db.session.commit()\r\n\r\n return user_schema.jsonify(new_user)\r\n\r\n\r\n@app.route('/user',methods=['GET'])\r\ndef get_user():\r\n\tall_users = User.query.all()\r\n\tresult = users_schema.dumps(all_users)\r\n\treturn jsonify(result.data)\r\n\r\n\r\n@app.route('/user/',methods=['GET'])\r\ndef user_details(id):\r\n\tuser = User.query.get(id)\r\n\treturn user_schema.jsonify(user)\r\n\r\n\r\n\r\n@app.route('/user/',methods=['PUT'])\r\ndef user_update(id):\r\n\tuser = User.query.get(id)\r\n\t\r\n\tusername = request.json['username']\r\n\temail = request.json['email']\r\n\r\n\tuser.username = username\r\n\tuser.email= email\r\n\r\n\tdb.session.commit()\r\n\r\n\treturn user_schema.jsonify(user)\r\n\r\n\r\n@app.route('/user/',methods=[\"DELETE\"])\r\ndef user_delete(id):\r\n\tuser = User.query.get(id)\r\n\tdb.session.delete(user)\r\n\tdb.session.commit()\r\n\treturn user_schema.jsonify(user)\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tapp.run(debug=True)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"myenv/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"171223828","text":"import string\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nfrom nltk import download\nfrom nltk.tokenize import TweetTokenizer, word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk import FreqDist\n\npunctuation = []\npunctuation += string.punctuation\npunctuation.append('``')\npunctuation.append(\"''\")\npunctuation.append('--')\npunctuation.append('...')\n\n# tokenizer = TweetTokenizer()\ndef remove_stopwords_and_punct(words):\n no_stop = [x.lower() for x in tqdm(words) if x.lower() not in set(stopwords.words('english'))]\n no_stop_no_punct = [x for x in tqdm(no_stop) if x not in punctuation]\n return no_stop_no_punct\ndef get_tokenized(words):\n words = words.lower()\n tokens = word_tokenize(words)\n contractions = {\n \"'s\": \"is\",\n \"'re\": \"are\",\n \"n't\": \"not\",\n \"'m\": \"am\",\n \"'ll\": \"will\",\n \"ca\": \"can\",\n \"'ve\": \"have\",\n \"u\": \"\"\n }\n long_forms = []\n for token in tokens:\n if token in contractions:\n long_forms.append(contractions[token])\n else:\n long_forms.append(token)\n \n return remove_stopwords_and_punct(long_forms)\n\ndef get_distribution(tokens):\n dist = FreqDist(tokens)\n return dist\n\nfrom nltk.stem.wordnet import WordNetLemmatizer\nlem = WordNetLemmatizer()\n\ndef get_lemmatized(words, pos=\"n\"):\n lemmas = []\n for word in words:\n lemma = lem.lemmatize(word, pos)\n lemmas.append(lemma)\n return lemmas\n\n# with open(\"./corpus_clean_no_tokens.txt\") as fp:\n# songs = fp.read()\n# tokenized_songs = get_tokenized(songs)\n\n# lemmas = get_lemmatized(tokenized_songs)\n# lemma_dist = get_distribution(lemmas)\n# lemma_dist.plot(30, cumulative=False)\n\n\nfrom nltk.corpus import brown\nbrown = brown.words()\nbrown_clean = remove_stopwords_and_punct(brown)\nbrown_lemma = get_lemmatized(brown_clean)\nbrown_dist = get_distribution(brown_lemma)\nbrown_dist.plot(30, cumulative=False)\n\nplt.show()\n# songs_dist = get_distribution(tokenized_songs)\n# songs_dist.plot(30, cumulative=False)\n\n\n\n# plt.show()\n\n\n\n\"\"\"\ndef apply_softmax_to_tuples(tuples):\n words = np.array(tuples)[:, 0]\n dim = np.array(np.array(tuples)[:, 1], dtype=np.int)\n\n softmaxed_values = np.array([x / np.sum(dim) for x in dim])\n\n softmaxed_tuples = [(words[x], y) for x, y in enumerate(softmaxed_values)]\n\n return softmaxed_tuples\n\nsongs_most_common_words = np.array(songs_dist.most_common(100))[:, 0]\n\nsongs_softmaxed = apply_softmax_to_tuples(songs_dist.most_common(100))\n\nsongs_sum = np.sum(np.array(songs_dist.most_common(brown_dist.N()))[:, 1].astype(int))\nbrown_sum = np.sum(np.array(brown_dist.most_common(brown_dist.N()))[:, 1].astype(int))\n\nx = np.array(songs_softmaxed)[:, 1]\ny = np.array([brown_dist[word]/brown_sum for word in songs_most_common_words])\n\nnorm = plt.Normalize(1, 4)\n\nfig, ax = plt.subplots()\nsc = plt.scatter(np.flip(x), np.flip(y))\n\n# annot = ax.annotate(\"\", xy=(0,0), xytext=(20, 20), textcoords=\"offset points\", bbox=dict(boxstyle=\"round\", fc=\"w\"), arrowprops=dict(arrowstyle=\"->\"))\n# annot.set_visible(False)\n\n# def update_annot(ind):\n# pos = sc.get_offsets()[ind[\"ind\"][0]]\n# annot.xy = pos\n# text = \"{}, {}\".format(\" \".join(list(map(str,ind[\"ind\"]))), \n# \" \".join([songs_most_common_words[n] for n in ind[\"ind\"]]))\n# annot.set_text(text)\n# annot.get_bbox_patch().set_alpha(0.4)\n\n# def hover(event):\n# vis = annot.get_visible()\n# if event.inaxes == ax:\n# cont, ind = sc.contains(event)\n# if cont:\n# update_annot(ind)\n# annot.set_visible(True)\n# fig.canvas.draw_idle()\n# else:\n# if vis:\n# annot.set_visible(False)\n# fig.canvas.draw_idle()\n\n# fig.canvas.mpl_connect(\"motion_notify_event\", hover)\n\nplt.show()\n\nprint(songs_dist.most_common(100))\n\"\"\"","sub_path":"analysis/dataset_comparison.py","file_name":"dataset_comparison.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"42701446","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/advancedcaching/qt/searchgeocachesdialog.py\n# Compiled at: 2011-04-23 08:43:29\nimport logging\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nimport geocaching\nfrom searchresultsdialog import QtSearchResultsDialog\nfrom ui_searchgeocachesdialog import Ui_SearchGeocachesDialog\nd = lambda x: x.decode('utf-8')\nlogger = logging.getLogger('qtsearchgeocachesdialog')\n\nclass QtSearchGeocachesDialog(Ui_SearchGeocachesDialog, QDialog):\n RADI = [\n 1, 2, 3, 5, 10, 15, 20, 50, 100]\n TYPELIST = [\n (\n 'traditional', geocaching.GeocacheCoordinate.TYPE_REGULAR),\n (\n 'multi stage', geocaching.GeocacheCoordinate.TYPE_MULTI),\n (\n 'virtual', geocaching.GeocacheCoordinate.TYPE_VIRTUAL),\n (\n 'earth', geocaching.GeocacheCoordinate.TYPE_EARTH),\n (\n 'event', geocaching.GeocacheCoordinate.TYPE_EVENT),\n (\n 'mystery', geocaching.GeocacheCoordinate.TYPE_MYSTERY),\n (\n 'webcam', geocaching.GeocacheCoordinate.TYPE_WEBCAM),\n (\n 'all/other', geocaching.GeocacheCoordinate.TYPE_UNKNOWN)]\n\n def __init__(self, core, map_position, user_position, parent=None):\n QDialog.__init__(self, parent)\n self.core = core\n self.setupUi(self)\n self.populateUi()\n self.setModal(True)\n self.dialogButtonBox.clicked.connect(self.__button_clicked)\n self.map_position = map_position\n self.user_position = user_position\n\n def populateUi(self):\n for (name, type) in self.TYPELIST:\n m = QListWidgetItem(name, self.listWidgetType)\n m.setCheckState(Qt.Unchecked if type == geocaching.GeocacheCoordinate.TYPE_UNKNOWN else Qt.Checked)\n\n self.comboBoxLocation.currentIndexChanged.connect(self.__combo_box_changed)\n\n def __combo_box_changed(self, index):\n self.spinBoxRadius.setEnabled(index != 0)\n if index == 1:\n text = self.map_position.get_latlon() if self.map_position != None else 'not available'\n elif index == 2:\n text = self.user_position.get_latlon() if self.user_position != None else 'not available'\n else:\n text = ''\n self.labelLocation.setText(d(text))\n return\n\n def show(self):\n QDialog.show(self)\n\n def __button_clicked(self, button):\n id = self.dialogButtonBox.standardButton(button)\n if id == QDialogButtonBox.Ok:\n self.__start_search()\n\n def __start_search(self):\n name = str(self.lineEditName.text()).strip().lower()\n if name == '':\n name = None\n logger.debug('Name: %s' % name)\n i = self.comboBoxLocation.currentIndex()\n if i == 1 and self.map_position != None:\n center = self.map_position\n elif i == 2 and self.user_position != None:\n center = self.user_position\n else:\n center = None\n if center != None:\n radius = self.spinBoxRadius.value()\n sqrt_2 = 1.41421356\n c1 = center.transform(-45, radius * 1000 * sqrt_2)\n c2 = center.transform(135, radius * 1000 * sqrt_2)\n location = (c2, c1)\n logger.debug('Location: %s %s' % location)\n else:\n location = None\n logger.debug('Location: None')\n types = [ self.TYPELIST[x][1] for x in range(self.listWidgetType.count()) if self.listWidgetType.item(x).checkState() == Qt.Checked ]\n if geocaching.GeocacheCoordinate.TYPE_UNKNOWN in types:\n types = None\n logger.debug('Types: %s' % types)\n if self.checkBoxHideFound.checkState() == Qt.Checked:\n found = False\n else:\n found = None\n logger.debug('Found: %s' % found)\n if self.checkBoxShowOnlyMarked.checkState() == Qt.Checked:\n marked = True\n else:\n marked = False\n logger.debug('Marked: %s' % marked)\n sizes = [ x + 1 for x in range(self.listWidgetSize.count()) if self.listWidgetSize.item(x).checkState() == Qt.Checked ]\n if sizes == [1, 2, 3, 4, 5]:\n sizes = None\n logger.debug('Sizes: %s' % sizes)\n r = lambda x: int(x / 0.5) * 0.5\n diff_min = r(self.doubleSpinBoxDifficultyMin.value())\n diff_max = r(self.doubleSpinBoxDifficultyMax.value() + 0.5)\n if diff_min == 1 and diff_max == 5.5:\n difficulties = None\n else:\n difficulties = [ x / 10.0 for x in range(int(diff_min * 10), int(diff_max * 10), 5) ]\n logger.debug('Difficulties: %s' % difficulties)\n terr_min = r(self.doubleSpinBoxTerrainMin.value())\n terr_max = r(self.doubleSpinBoxTerrainMax.value() + 0.5)\n if terr_min == 1 and terr_max == 5.5:\n terrains = None\n else:\n terrains = [ x / 10.0 for x in range(int(terr_min * 10), int(terr_max * 10), 5) ]\n logger.debug('Terrains: %s' % terrains)\n results = self.core.get_points_filter(found=found, name_search=name, size=sizes, terrain=terrains, diff=difficulties, ctype=types, marked=marked, location=location)\n logger.debug('Found %d results' % len(results[0]))\n self.__show_results(results)\n return\n\n def __show_results(self, results):\n d = QtSearchResultsDialog(self.core)\n d.show(results[0])","sub_path":"pycfiles/agua-0.1.1.tar/searchgeocachesdialog.py","file_name":"searchgeocachesdialog.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"195301810","text":"# coding: utf-8\n\"\"\"Script that takes a previously created Knowledge Base and trains an entity linking\npipeline. The provided KB directory should hold the kb, the original nlp object and\nits vocab used to create the KB, and a few auxiliary files such as the entity definitions,\nas created by the script `wikidata_create_kb`.\n\nFor the Wikipedia dump: get enwiki-latest-pages-articles-multistream.xml.bz2\nfrom https://dumps.wikimedia.org/enwiki/latest/\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport random\nimport logging\nimport spacy\nfrom pathlib import Path\nimport plac\nfrom tqdm import tqdm\n\nfrom bin.wiki_entity_linking import wikipedia_processor\nfrom bin.wiki_entity_linking import TRAINING_DATA_FILE, KB_MODEL_DIR, KB_FILE, LOG_FORMAT, OUTPUT_MODEL_DIR\nfrom bin.wiki_entity_linking.entity_linker_evaluation import measure_performance\nfrom bin.wiki_entity_linking.kb_creator import read_kb\n\nfrom spacy.util import minibatch, compounding\n\nlogger = logging.getLogger(__name__)\n\n\n@plac.annotations(\n dir_kb=(\"Directory with KB, NLP and related files\", \"positional\", None, Path),\n output_dir=(\"Output directory\", \"option\", \"o\", Path),\n loc_training=(\"Location to training data\", \"option\", \"k\", Path),\n epochs=(\"Number of training iterations (default 10)\", \"option\", \"e\", int),\n dropout=(\"Dropout to prevent overfitting (default 0.5)\", \"option\", \"p\", float),\n lr=(\"Learning rate (default 0.005)\", \"option\", \"n\", float),\n l2=(\"L2 regularization\", \"option\", \"r\", float),\n train_articles=(\"# training articles (default 90% of all)\", \"option\", \"t\", int),\n dev_articles=(\"# dev test articles (default 10% of all)\", \"option\", \"d\", int),\n labels_discard=(\"NER labels to discard (default None)\", \"option\", \"l\", str),\n)\ndef main(\n dir_kb,\n output_dir=None,\n loc_training=None,\n epochs=10,\n dropout=0.5,\n lr=0.005,\n l2=1e-6,\n train_articles=None,\n dev_articles=None,\n labels_discard=None\n):\n if not output_dir:\n logger.warning(\"No output dir specified so no results will be written, are you sure about this ?\")\n\n logger.info(\"Creating Entity Linker with Wikipedia and WikiData\")\n\n output_dir = Path(output_dir) if output_dir else dir_kb\n training_path = loc_training if loc_training else dir_kb / TRAINING_DATA_FILE\n nlp_dir = dir_kb / KB_MODEL_DIR\n kb_path = dir_kb / KB_FILE\n nlp_output_dir = output_dir / OUTPUT_MODEL_DIR\n\n # STEP 0: set up IO\n if not output_dir.exists():\n output_dir.mkdir()\n\n # STEP 1 : load the NLP object\n logger.info(\"STEP 1a: Loading model from {}\".format(nlp_dir))\n nlp = spacy.load(nlp_dir)\n logger.info(\"Original NLP pipeline has following pipeline components: {}\".format(nlp.pipe_names))\n\n # check that there is a NER component in the pipeline\n if \"ner\" not in nlp.pipe_names:\n raise ValueError(\"The `nlp` object should have a pretrained `ner` component.\")\n\n logger.info(\"STEP 1b: Loading KB from {}\".format(kb_path))\n kb = read_kb(nlp, kb_path)\n\n # STEP 2: read the training dataset previously created from WP\n logger.info(\"STEP 2: Reading training & dev dataset from {}\".format(training_path))\n train_indices, dev_indices = wikipedia_processor.read_training_indices(training_path)\n logger.info(\"Training set has {} articles, limit set to roughly {} articles per epoch\"\n .format(len(train_indices), train_articles if train_articles else \"all\"))\n logger.info(\"Dev set has {} articles, limit set to rougly {} articles for evaluation\"\n .format(len(dev_indices), dev_articles if dev_articles else \"all\"))\n if dev_articles:\n dev_indices = dev_indices[0:dev_articles]\n\n # STEP 3: create and train an entity linking pipe\n logger.info(\"STEP 3: Creating and training an Entity Linking pipe for {} epochs\".format(epochs))\n if labels_discard:\n labels_discard = [x.strip() for x in labels_discard.split(\",\")]\n logger.info(\"Discarding {} NER types: {}\".format(len(labels_discard), labels_discard))\n else:\n labels_discard = []\n\n el_pipe = nlp.create_pipe(\n name=\"entity_linker\", config={\"pretrained_vectors\": nlp.vocab.vectors.name,\n \"labels_discard\": labels_discard}\n )\n el_pipe.set_kb(kb)\n nlp.add_pipe(el_pipe, last=True)\n\n other_pipes = [pipe for pipe in nlp.pipe_names if pipe != \"entity_linker\"]\n with nlp.disable_pipes(*other_pipes): # only train Entity Linking\n optimizer = nlp.begin_training()\n optimizer.learn_rate = lr\n optimizer.L2 = l2\n\n logger.info(\"Dev Baseline Accuracies:\")\n dev_data = wikipedia_processor.read_el_docs_golds(nlp=nlp, entity_file_path=training_path,\n dev=True, line_ids=dev_indices,\n kb=kb, labels_discard=labels_discard)\n\n measure_performance(dev_data, kb, el_pipe, baseline=True, context=False, dev_limit=len(dev_indices))\n\n for itn in range(epochs):\n random.shuffle(train_indices)\n losses = {}\n batches = minibatch(train_indices, size=compounding(8.0, 128.0, 1.001))\n batchnr = 0\n articles_processed = 0\n\n # we either process the whole training file, or just a part each epoch\n bar_total = len(train_indices)\n if train_articles:\n bar_total = train_articles\n\n with tqdm(total=bar_total, leave=False, desc='Epoch ' + str(itn)) as pbar:\n for batch in batches:\n if not train_articles or articles_processed < train_articles:\n with nlp.disable_pipes(\"entity_linker\"):\n train_batch = wikipedia_processor.read_el_docs_golds(nlp=nlp, entity_file_path=training_path,\n dev=False, line_ids=batch,\n kb=kb, labels_discard=labels_discard)\n docs, golds = zip(*train_batch)\n try:\n with nlp.disable_pipes(*other_pipes):\n nlp.update(\n docs=docs,\n golds=golds,\n sgd=optimizer,\n drop=dropout,\n losses=losses,\n )\n batchnr += 1\n articles_processed += len(docs)\n pbar.update(len(docs))\n except Exception as e:\n logger.error(\"Error updating batch:\" + str(e))\n if batchnr > 0:\n logging.info(\"Epoch {} trained on {} articles, train loss {}\"\n .format(itn, articles_processed, round(losses[\"entity_linker\"] / batchnr, 2)))\n # re-read the dev_data (data is returned as a generator)\n dev_data = wikipedia_processor.read_el_docs_golds(nlp=nlp, entity_file_path=training_path,\n dev=True, line_ids=dev_indices,\n kb=kb, labels_discard=labels_discard)\n measure_performance(dev_data, kb, el_pipe, baseline=False, context=True, dev_limit=len(dev_indices))\n\n if output_dir:\n # STEP 4: write the NLP pipeline (now including an EL model) to file\n logger.info(\"Final NLP pipeline has following pipeline components: {}\".format(nlp.pipe_names))\n logger.info(\"STEP 4: Writing trained NLP to {}\".format(nlp_output_dir))\n nlp.to_disk(nlp_output_dir)\n\n logger.info(\"Done!\")\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)\n plac.call(main)\n","sub_path":"bin/wiki_entity_linking/wikidata_train_entity_linker.py","file_name":"wikidata_train_entity_linker.py","file_ext":"py","file_size_in_byte":7831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"554744651","text":"# Arik Rakibullah\n# Lab 5\n\nimport tkinter as tk\nimport tkinter.filedialog\nimport tkinter.messagebox as tkmb\nimport os\nimport re\nimport threading\nimport os.path\nimport cis41b.filesearch\n\nclass FindWin(tk.Tk):\n \n def __init__(self):\n ''' Sets up a GUI for file searching'''\n super().__init__()\n \n # set the start directory to be the user's home directory\n self._directoryVar = tk.StringVar()\n self._directoryVar.set(os.path.expanduser('~'))\n \n # expand the entry and listbox widgets as the window resizes\n self.grid_columnconfigure(2,weight = 1)\n self.grid_rowconfigure(4,weight = 1)\n \n # title the window\n self.title(\"File Search\")\n \n # create labels to display the current directory\n tk.Label(self,text = \"Current Folder:\").grid()\n tk.Label(self,textvariable = self._directoryVar).grid(row = 0, column = 1)\n \n # create a button to allow the user to change directory\n tk.Button(self, text = \"Change Folder\", command = self._selectDir).grid(row = 1, column = 0)\n \n # create a label/entry widget for the regex filter\n tk.Label(self, text = \"Regex filter:\").grid(row = 2, column = 0, sticky = 'e')\n self._regexVar = tk.StringVar()\n regexEntry = tk.Entry(self, textvariable = self._regexVar)\n \n # put the focus on the regex entry widget\n regexEntry.focus_set()\n regexEntry.grid(row = 2, column = 1, columnspan = 2, sticky = 'we')\n \n # bind the regex search entry widget to the return key\n regexEntry.bind(\"\", self._search)\n \n # create a label/entry widget for the string search\n tk.Label(self, text = \"Search String:\").grid(row = 3, column = 0, sticky = 'e')\n self._stringVar = tk.StringVar()\n searchEntry = tk.Entry(self, textvariable = self._stringVar)\n searchEntry.grid(row = 3, column = 1, columnspan = 2, sticky = 'we')\n \n # bind the string search entry widget to the return key\n searchEntry.bind(\"\", self._search)\n \n # create a scrollbar/listbox to display matching files\n s = tk.Scrollbar(self)\n self._LB = tk.Listbox(self, height = 10, yscrollcommand = s.set)\n self._LB.grid(row = 4, column = 0, columnspan = 3, sticky = 'wesn')\n s.config(command = self._LB.yview)\n s.grid(row = 4, column = 3, sticky = 'wns')\n \n # create a label to display the number of found files\n self._filesFoundVar = tk.StringVar()\n self._filesFoundVar.set(\"Found 0 files\")\n tk.Label(self, textvariable = self._filesFoundVar).grid(sticky = 'w')\n \n # create an empty results list\n self._resultsList = []\n \n # create an event to signal to the search method when to stop searching\n self._keepSearching = threading.Event()\n \n # initialize the event flag to be clear\n self._keepSearching.clear()\n \n self.protocol(\"WM_DELETE_WINDOW\", self._exit)\n \n # show the window on screen\n self.update()\n \n # initialize the fileSearch object\n self._fileSearch = cis41b.filesearch.FileSearch(self._directoryVar.get())\n \n def _exit(self):\n ''' Method to exit after making sure all threads are ended. '''\n \n # if the search thread is still searching, end it and wait for it to finish before exiting\n if self._keepSearching.isSet(): self._cancelSearch()\n self.destroy()\n \n def _selectDir(self):\n ''' Method to allow the user to change the current directory\n Searches through the updated directory using the current regex entry and search string\n \n '''\n # prompt the user for a new directory\n newDir = tk.filedialog.askdirectory(initialdir = self._directoryVar.get())\n \n # if the user doesn't click cancel, update the directory and file search object and\n # then redo the search using what ever regex and search string has been entered\n if newDir != '':\n self._directoryVar.set(newDir)\n self._filesFoundVar.set('Loading directory...')\n self.update()\n self._fileSearch = cis41b.filesearch.FileSearch(newDir)\n self._search()\n \n \n def _search(self, *args):\n ''' Callback method to perform a regular expression search on all files in the current directory\n Updates the file count label and listbox accordingly. \n \n '''\n # make sure that the regex is valid\n try :\n regex = re.compile(self._regexVar.get(),re.I)\n except Exception as e :\n print(\"Invalid regex: \" + str(e))\n return\n \n # if the search thread is currently searching, cancel the search\n if self._keepSearching.isSet(): self._cancelSearch()\n \n # clear the listbox\n self._LB.delete(0,tk.END)\n \n # search through the files using the regex and search string\n self._resultsList.clear()\n self._keepSearching.set()\n self._filesFoundVar.set(\"Searching...\")\n \n # create and start a thread to do the searching\n self._searchThread = threading.Thread(target = self._fileSearch.searchName, args = (self._regexVar.get(), self._stringVar.get(), self._resultsList, self._keepSearching))\n self._searchThread.start()\n \n # update the listbox 100ms later\n self._updateListBoxThread = self.after(100,self._updateListBox)\n \n def _cancelSearch(self):\n ''' Method to cancel the current search thread. \n Clears the listbox update from the queue, clears the keepSearching flag, and then waits for the search to end.\n \n '''\n self.after_cancel(self._updateListBoxThread)\n self._keepSearching.clear()\n self._searchThread.join()\n \n def _updateListBox(self):\n ''' Updates the list box with current search results. '''\n \n # if the search is still going on, update the list box again in 100ms\n if self._searchThread.isAlive():\n self._updateListBoxThread = self.after(100,self._updateListBox)\n \n # if the search is over, update the filesFoundVar and pop up a message box if necessary\n else:\n # clear the event flag\n self._keepSearching.clear()\n # if there were more than 1000 files found, notify the user and update the file count\n if len(self._resultsList) > 1000:\n tkmb.showerror(\"Too many files\", \"There were more than 1000 files found with the given regex and search string. Ending the search now.\", parent = self)\n self._filesFoundVar.set(\"Found >1000 files\")\n # if there were fewer than 1000 files found, update the listbox and file count\n else:\n self._filesFoundVar.set(\"Found \" + str(len(self._resultsList)) + \" files\")\n # if no files were found, notify the user\n if len(self._resultsList) == 0: tkmb.showerror(\"No Files Found\", \"There were no files found with the given regex and search string.\", parent = self) \n \n # update the listbox with any new resultList entries\n self._LB.insert(tk.END,*self._resultsList[self._LB.size():]) \n \ndef __main__():\n f = FindWin()\n f.mainloop()\n\n__main__()","sub_path":"Module 5/lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":7505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"256600705","text":"# time:\n\n\ndef qsort(array):\n\n if len(array) < 2:\n return array\n else:\n pivot = array[0]\n lower = [ i for i in array[1:] if i <= pivot ]\n upper = [ i for i in array[1:] if i > pivot ]\n\n print('current result: ',lower + [pivot] + upper)\n return qsort(lower) + [pivot] + qsort(upper)\n\n\nprint(qsort([5, 4, 9, 3, 14, 12]))\n","sub_path":"algorithms/quicksort_trial1.py","file_name":"quicksort_trial1.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"348427081","text":"'''\nAuthor: Puffrora\nDate: 2022-04-28 14:35:07\nLastModifiedBy: Puffrora\nLastEditTime: 2022-04-28 14:57:31\n'''\n\n\n# Trie\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n\n total_nodes = 3 * 2**(n-1)\n if k > total_nodes:\n return \"\"\n \n node = {\n \"a\": [\"b\", \"c\"],\n \"b\": [\"a\", \"c\"],\n \"c\": [\"a\", \"b\"],\n }\n\n q, r = divmod(k-1, 2**(n-1))\n mapping = {\n 0: \"a\",\n 1: \"b\",\n 2: \"c\",\n }\n root_char = mapping[q]\n res = [root_char]\n\n # it means target is in the q-th trie, r-th leaf node\n r_bin = []\n while r:\n if r & 1:\n r_bin.append(1)\n else:\n r_bin.append(0)\n r >>= 1\n r_bin = r_bin[::-1]\n r_bin = [0]*(n-1-len(r_bin))+r_bin\n\n cur_node = node[root_char]\n for c in r_bin:\n res.append(cur_node[c])\n cur_node = node[cur_node[c]]\n \n return \"\".join(res)\n","sub_path":"Leetcode/leetcode1415 长度为 n 的开心字符串中字典序第 k 小的字符串.py","file_name":"leetcode1415 长度为 n 的开心字符串中字典序第 k 小的字符串.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"534257756","text":"import pandas as pd\nimport numpy as np\nimport random\nfrom analysis import TextAnalysis\n\ndata = {\n 'title' : '다행이다.',\n 'content' : '''약도 아침/자기전으로 잘 챙겨먹고\n\n 옛날보다 더 몸이 건강해진것같다\n\n 지금 이 몸무게에 들어갈수 없었던 바지도 잘들어가고\n\n 너무 좋다 그리고 과하게 살이 쪘을땐 뭐든지 짜증이 났는데\n\n 별다른 이벤트가 없다면 그냥 그러려니 잘 넘긴다\n\n 나 정말 다행이야\n\n 어제는 사고싶은 옷들이 있어서 인터넷으로 옷을 주문했다\n\n 그리고 돈을 아끼려고 많이 노력중이다\n\n 나 잘할수 있다고 믿을래!''',\n 'stickers' : [{'emotion': {'name': 'happy'}}, {'emotion': {'name':'delight'}}]\n }\na = TextAnalysis(data)\nout = a.text_analysis()\nemotion = out['feel'][0][0]\n\ndata = pd.read_csv('C:/Users/multicampus/Desktop/response.csv', encoding='CP949')\n\nchoice = random.choice(data[emotion])\nprint(choice)","sub_path":"NLP/recommand.py","file_name":"recommand.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"584525866","text":"# This file is part of the mt5b3 package\r\n# mt5b3 home: https://github.com/paulo-al-castro/mt5b3\r\n# Author: Paulo Al Castro\r\n# Date: 2020-11-17\r\n\r\nimport numpy.random as rand\r\nimport mt5b3 as b3\r\nimport time\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nclass DummyTrader(b3.Trader):\r\n def __init__(self):\r\n pass\r\n\r\n def setup(self,dbars):\r\n print('just getting started!')\r\n\r\n def trade(self,ops,dbars):\r\n orders=[] \r\n assets=ops['assets']\r\n for asset in assets:\r\n if rand.randint(2)==1: \r\n order=b3.buyOrder(asset,100)\r\n else:\r\n \torder=b3.sellOrder(asset,100)\r\n orders.append(order)\r\n return orders\r\n \r\n def ending(self,dbars):\r\n print('Ending stuff')\r\n\r\n \r\n\r\nclass MonoAssetTrader(b3.Trader):\r\n def trade(self,bts,dbars):\r\n assets=dbars.keys()\r\n asset=list(assets)[0]\r\n orders=[]\r\n bars=dbars[asset]\r\n curr_shares=b3.backtest.getShares(bts,asset)\r\n # number of shares that you can buy\r\n free_shares=b3.backtest.getAfforShares(bts,dbars,asset)\r\n rsi=b3.tech.rsi(bars)\r\n if rsi>=70: \r\n order=b3.buyOrder(asset,free_shares)\r\n else:\r\n order=b3.sellOrder(asset,curr_shares)\r\n if rsi>=70 and free_shares>0: \r\n order=b3.buyOrder(asset,free_shares)\r\n elif rsi<70 and curr_shares>0:\r\n order=b3.sellOrder(asset,curr_shares)\r\n if order!=None:\r\n orders.append(order)\r\n return orders \r\n\r\n\r\n\r\nclass MultiAssetTrader(b3.Trader):\r\n def trade(self,bts,dbars):\r\n assets=dbars.keys()\r\n orders=[]\r\n for asset in assets:\r\n bars=dbars[asset]\r\n curr_shares=b3.backtest.getShares(bts,asset)\r\n money=b3.backtest.getBalance(bts)/len(assets) # divide o saldo em dinheiro igualmente entre os ativos\r\n # number of shares that you can buy of asset \r\n free_shares=b3.backtest.getAfforShares(bts,dbars,asset,money)\r\n rsi=b3.tech.rsi(bars)\r\n if rsi>=70 and free_shares>0: \r\n order=b3.buyOrder(asset,free_shares)\r\n elif rsi<70 and curr_shares>0:\r\n order=b3.sellOrder(asset,curr_shares)\r\n else:\r\n order=None\r\n if order!=None:\r\n orders.append(order)\r\n return orders \r\n\r\n\r\nfrom sklearn import tree\r\nfrom sklearn.preprocessing import KBinsDiscretizer\r\n \r\nclass SimpleAITrader(b3.Trader):\r\n\r\n def setup(self,dbars):\r\n assets=list(dbars.keys())\r\n if len(assets)!=1:\r\n print('Error, this trader is supposed to deal with just one asset')\r\n return None\r\n bars=dbars[assets[0]]\r\n timeFrame=10 # it takes into account the last 10 bars\r\n horizon=1 # it project the closing price for next bar\r\n target='close' # name of the target column\r\n ds=b3.ai_utils.bars2Dataset(bars,target,timeFrame,horizon)\r\n\r\n X=b3.ai_utils.fromDs2NpArrayAllBut(ds,['target'])\r\n discretizer = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform') \r\n\r\n ds['target']=b3.ai_utils.discTarget(discretizer,ds['target'])\r\n Y=b3.ai_utils.fromDs2NpArray(ds,['target'])\r\n\r\n clf = tree.DecisionTreeClassifier()\r\n\r\n clf = clf.fit(X, Y)\r\n self.clf=clf\r\n\r\n def trade(self,bts,dbars):\r\n assets=dbars.keys()\r\n orders=[]\r\n timeFrame=10 # it takes into account the last 10 bars\r\n horizon=1 # it project the closing price for next bar\r\n target='close' # name of the target column\r\n for asset in assets:\r\n curr_shares=b3.backtest.getShares(asset)\r\n money=b3.backtest.getBalance()/len(assets) # divide o saldo em dinheiro igualmente entre os ativos\r\n free_shares=b3.backtest.getAfforShares(asset,money,dbars)\r\n # get new information (bars), transform it in X\r\n bars=dbars[asset]\r\n #remove irrelevant info\r\n del bars['time']\r\n # convert from bars to dataset\r\n ds=b3.ai_utils.bars2Dataset(bars,target,timeFrame,horizon)\r\n # Get X fields\r\n X=b3.ai_utils.fromDs2NpArrayAllBut(ds,['target'])\r\n\r\n # predict the result, using the latest info\r\n p=self.clf.predict([X[-1]])\r\n if p==2:\r\n #buy it\r\n order=b3.buyOrder(asset,free_shares)\r\n elif p==0:\r\n #sell it\r\n order=b3.sellOrder(asset,curr_shares)\r\n else:\r\n order=None\r\n if order!=None:\r\n orders.append(order)\r\n return orders \r\n","sub_path":"mt5b3/mt5b3/sampleTraders.py","file_name":"sampleTraders.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"460287855","text":"import random\nfrom copy import deepcopy\n\nimport numpy as np\nfrom PPA import config\nfrom operator import attrgetter\n\n\n# the survivor selection class, selection survivors to participate in the next generation\nclass SurvivorSelection:\n\n def __init__(self, method_name: str, pop_size: int):\n self.method = self.set_method(method_name)\n self.pop_size = pop_size\n\n # we dynamically assign a selection method to the class object \"method\" this way every run can call the same\n # fucntion, but containing different selection methods\n def set_method(self, method_name):\n if method_name == 'mulambda':\n return self.mulambda\n elif method_name == 'mupluslambda':\n return self.mupluslambda\n elif method_name == 'tournament':\n self.tournament_size = config.tournament_size\n return self.tournament\n elif method_name == 'single_elitist_tournament':\n self.tournament_size = config.tournament_size\n return self.single_elitist_tournament\n elif method_name == 'no_replacement_tournament':\n self.tournament_size = config.tournament_size\n return self.no_replacement_tournament\n elif method_name == 'roulette_wheel':\n return self.rws\n elif method_name == 'linear_ranking':\n return self.linear_ranking\n elif method_name == 'single_elitist_rws':\n return self.single_elitist_rws\n else:\n raise Exception('the specified survivor selection method does not exist')\n\n # we call the dynamically assigned selection method\n def select_survivors(self, parents: [], offspring: []):\n return self.method(parents, offspring)\n\n # =============\n # Below are the selection methods as specified in the research\n # =============\n\n # add best individuals from offspring\n def mulambda(self, parents: [], offspring: []):\n new_population = offspring[:]\n new_population.sort(key=lambda i: i.objective_value)\n\n return new_population[:self.pop_size]\n\n # add popsize best individuals from parents + offspring\n def mupluslambda(self, parents: [], offspring: []):\n new_population = parents + offspring\n new_population.sort(key=lambda i: i.objective_value)\n\n return new_population[:self.pop_size]\n\n # tournament selection selecting one less individual, but add the best individual of parents + offspring\n def single_elitist_tournament(self, parents: [], offspring: []):\n new_population = self.tournament(parents, offspring, self.pop_size - 1)\n combined_population = parents[:] + offspring[:]\n new_population.append(min(combined_population, key=attrgetter('objective_value')))\n\n return new_population\n\n # this function performs exactly the same as tournament selection, except the individuals are selected without\n # replacement, made possible by using random.sample, instead of random.choices\n def no_replacement_tournament(self, parents: [], offspring: []):\n new_population = self.tournament(parents, offspring, self.pop_size, False)\n return new_population\n\n # the tournament selection method used by both with and without replacement tournament selection methods\n def tournament(self, parents: [], offspring: [], custom_pop_size=-1, replacement=True):\n combined_population = parents + offspring\n new_population = []\n new_pop_size = custom_pop_size if custom_pop_size > 0 else self.pop_size\n for i in range(new_pop_size):\n # the random.choices samples with replacement, the random.sample without replacement\n if replacement:\n tournament = random.choices(combined_population, k=self.tournament_size)\n else:\n tournament = random.sample(combined_population, k=self.tournament_size)\n winner = min(tournament, key=attrgetter('objective_value'))\n\n new_population.append(winner)\n return new_population\n\n # roulette wheel selection, except there is one less indivual selected, instead the best individual is\n # automatically transferred\n def single_elitist_rws(self, parents: [], offspring: []):\n new_population = self.rws(parents, offspring, self.pop_size - 1)\n combined_population = parents[:] + offspring[:]\n new_population.append(min(combined_population, key=attrgetter('objective_value')))\n return new_population\n\n # selection method where the relative objective value size is proportional to the selection probability\n def rws(self, parents: [], offspring: [], custom_pop_size=-1):\n combined_population = parents[:] + offspring[\n :]\n # (re-)normalize objective values because otherwise the the higher the objective value, the higher the\n # selection probability, which we do not want, we want the reverse to be true\n min_objective_val = min(individual.objective_value for individual in combined_population)\n max_objective_val = max(individual.objective_value for individual in combined_population)\n epsilon = 1e-100\n summed_renorm_objective_value = 0\n\n for i in combined_population:\n i.renorm_objective_value = (max_objective_val - i.objective_value) / (\n (max_objective_val - min_objective_val) + epsilon)\n summed_renorm_objective_value += i.renorm_objective_value\n\n new_population = []\n\n population_size = custom_pop_size if custom_pop_size > 0 else self.pop_size\n\n # select popsize or custom popsize individuals form the parents+offspring\n for t in range(population_size):\n roulette_wheel = 0\n r = random.uniform(0, summed_renorm_objective_value)\n for i in combined_population:\n\n roulette_wheel += i.renorm_objective_value\n if roulette_wheel >= r:\n new_population.append(i)\n break\n\n return new_population\n # Select individuals based on rank, summing all ranks available and drawing a random number; next we add rank by\n # rank until the random number is met or passed\n def linear_ranking(self, parents: [], offspring: []):\n new_population = []\n combined_population = parents[:] + offspring[:]\n combined_population.sort(key=lambda i: i.objective_value)\n sum_of_ranks = sum(np.arange(1, len(combined_population) + 1,\n 1)) # added 1 because the minimal position is 0, but should be rank 1\n\n for t in range(self.pop_size):\n y = 0\n r = random.uniform(0, sum_of_ranks)\n rank = len(combined_population) + 1\n for i in combined_population:\n rank -= 1\n y += rank\n if y >= r:\n new_population.append(i)\n break\n\n return new_population\n","sub_path":"classes/SurvivorSelection.py","file_name":"SurvivorSelection.py","file_ext":"py","file_size_in_byte":6989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"587621803","text":"import sublime\n\nfrom .log import GsLogCommand\nfrom ...common import util\n\nPADDING = \" \"\nGIT_RESET_MODES = [\n # See analysis at http://stackoverflow.com/questions/34149356/what-exactly-is-the-difference-between-all-the-git-reset-modes/34155307#34155307\n [\"--mixed\" + PADDING, \"unstage staged, keep unstaged, don't touch working (safe)\"],\n [\"--soft\", \"just move HEAD, stage differences (safe)\"],\n [\"--hard\", \"discard staged, discard unstaged, update working (unsafe)\"],\n [\"--merge\", \"discard staged, keep unstaged, update working (abort if unsafe)\"],\n [\"--keep\", \"unstage staged, keep unstaged, update working (abort if unsafe)\"]\n # For reference, in case we ever include the (very similar) checkout command\n # [\"--checkout\", \"keep staged, keep unstaged, update working, move branches (abort if unsafe)\"]\n]\n\n\nclass GsResetCommand(GsLogCommand):\n\n def on_hash_selection(self, index):\n if index == -1:\n return\n\n if index == self._limit:\n self._pagination += self._limit\n sublime.set_timeout_async(lambda: self.run_async(), 1)\n return\n\n self._selected_hash = self._hashes[index]\n\n use_reset_mode = sublime.load_settings(\"GitSavvy.sublime-settings\").get(\"use_reset_mode\")\n\n if use_reset_mode:\n self.on_reset(use_reset_mode)\n else:\n self.window.show_quick_panel(\n GIT_RESET_MODES, self.on_reset_mode_selection, flags=sublime.MONOSPACE_FONT\n )\n\n def on_reset_mode_selection(self, index):\n if 0 <= index < len(GIT_RESET_MODES):\n self.on_reset(GIT_RESET_MODES[index][0].strip())\n\n def on_reset(self, reset_mode):\n # Split the reset mode to support multiple args, e.g. \"--mixed -N\"\n args = reset_mode.split() + [self._selected_hash]\n do_reset = lambda: self.git(\"reset\", *args)\n\n if reset_mode == \"--hard\":\n util.actions.destructive(\"perform a hard reset\")(do_reset)()\n else:\n do_reset()\n\n\nclass GsResetReflogCommand(GsResetCommand):\n\n def run_async(self):\n log_output = self.git(\n \"reflog\",\n \"-{}\".format(self._limit) if self._limit else None,\n \"--skip={}\".format(self._pagination) if self._pagination else None,\n '--format=%h%n%H%n%s%n%gs%n%gd%n%an%n%at%x00'\n ).strip(\"\\x00\")\n\n self._entries = []\n self._hashes = []\n for entry in log_output.split(\"\\x00\"):\n try:\n short_hash, long_hash, summary, reflog_name, reflog_selector, author, datetime = (\n entry.strip(\"\\n\").split(\"\\n\"))\n\n self._entries.append([\n reflog_selector + \" \" + reflog_name,\n short_hash + \" \" + summary,\n author + \", \" + util.dates.fuzzy(datetime)\n ])\n self._hashes.append(long_hash)\n\n except ValueError:\n # Empty line - less expensive to catch the exception once than\n # to check truthiness of entry.strip() each time.\n pass\n\n if not len(self._entries) < self._limit:\n self._entries.append([\n \">>> NEXT {} COMMITS >>>\".format(self._limit),\n \"Skip this set of reflog entries and choose from the next-oldest batch.\"\n ])\n\n self.window.show_quick_panel(\n self._entries,\n self.on_hash_selection,\n flags=sublime.MONOSPACE_FONT\n )\n","sub_path":"core/commands/reset.py","file_name":"reset.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"162163600","text":"import torch\nimport inspect\n\n\nclass Scheduler(torch.optim.lr_scheduler._LRScheduler):\n def __new__(cls, *args, **kwargs):\n\n if \"scheduler\" not in kwargs.keys():\n return None\n\n # List schedulers available in pytorch\n torch_schedulers = dict()\n for m in inspect.getmembers(torch.optim.lr_scheduler):\n if inspect.isclass(m[1]):\n torch_schedulers[m[0]] = m[1]\n # Here we list schedulers that are available from our own packages\n custom_schedulers = dict()\n if kwargs[\"scheduler\"] in torch_schedulers:\n cls = torch_schedulers[kwargs[\"scheduler\"]]\n elif kwargs[\"scheduler\"] in custom_schedulers:\n cls = custom_schedulers[kwargs[\"scheduler\"]]\n else:\n raise Exception(f\"Scheduler {kwargs['scheduler']} is not supported\")\n # Filter only arguments expected by the selected class\n expected_args = inspect.getfullargspec(cls)[0][1:]\n expected_args.remove('optimizer')\n expected_kwargs = dict()\n for k,v in kwargs.items():\n if k in expected_args:\n expected_kwargs[k] = v\n return cls(*args, **expected_kwargs)\n\n\nclass Optimizer(torch.optim.Optimizer):\n def __new__(cls, *args, **kwargs):\n\n if \"optimizer\" not in kwargs.keys():\n return None\n\n # List optimizers available in pytorch\n torch_optimizers = dict()\n for m in inspect.getmembers(torch.optim):\n if inspect.isclass(m[1]):\n torch_optimizers[m[0]] = m[1]\n # Here we list optimizers that are available from our own packages\n custom_optimizers = dict()\n if kwargs[\"optimizer\"] in torch_optimizers:\n cls = torch_optimizers[kwargs[\"optimizer\"]]\n elif kwargs[\"optimizer\"] in custom_optimizers:\n cls = custom_optimizers[kwargs[\"optimizer\"]]\n else:\n raise Exception(f\"Optimizer {kwargs['optimizer']} is not supported\")\n # Filter only arguments expected by the selected class\n expected_args = inspect.getfullargspec(cls)[0][1:]\n expected_kwargs = dict()\n for k,v in kwargs.items():\n if k in expected_args:\n expected_kwargs[k] = v\n return cls(*args, **expected_kwargs)","sub_path":"common/optim/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"83440123","text":"# -*- coding: utf-8 -*-\n\nimport tst\nimport json\n\n\nclass WordFreq(object):\n\n def __init__(self):\n self.tagger = tst.TernarySearchTrie()\n\n\n def calc(self, comments):\n sum_com = len(comments)\n negative = {}\n negative['count_com'] = sum_com\n negative['word_all'] = {}\n negative['ccount_all'] = {}\n\n word_list = []\n hit = {}\n\n l1_freq_dic = {}\n l2_freq_dic = {}\n\n for c in comments:\n sentence = c.get('ccnt', '')\n if sentence:\n words = self.tagger.tag(sentence)\n dd = {}\n hit_c = {}\n for t, word in words:\n\n if t == 'level1':\n if word not in l1_freq_dic:\n l1_freq_dic[word] = 1\n else:\n l1_freq_dic[word] += 1\n\n if t == 'level2':\n if word not in l2_freq_dic:\n l2_freq_dic[word] = 1\n else:\n l2_freq_dic[word] += 1\n \n if t in ['level1', 'level2']:\n if t not in hit_c:\n hit_c[t] = 1\n \n #print t, word\n # 统计总词频数\n if word not in dd:\n dd[word] = 1\n else:\n dd[word] += 1\n word_list.append(dd)\n \n for l, _ in hit_c.items():\n if l not in hit:\n hit[l] = 1\n else:\n hit[l] += 1\n\n word_all_dic = {}\n ccount_all_dic = {}\n for dc in word_list:\n for word, count in dc.items():\n if word not in word_all_dic:\n word_all_dic[word] = count\n else:\n word_all_dic[word] += count\n\n if word not in ccount_all_dic:\n ccount_all_dic[word] = 1\n else:\n ccount_all_dic[word] += 1\n pcount_all_dic = {}\n for word, count in ccount_all_dic.items():\n pcount_all_dic[word] = float(count) / sum_com\n\n d_hit = {}\n for k, c in hit.items():\n d_d = {'count_hit': c}\n d_d['count_com'] = sum_com\n p_d = float(c) / sum_com\n d_d['rate'] = p_d\n d_hit[k] = d_d\n \n\n negative['word_all'] = word_all_dic\n negative['ccount_all'] = ccount_all_dic\n negative['pcount_all'] = pcount_all_dic\n negative['rate_all'] = d_hit\n \n #line = json.dumps(negative)\n #return line\n\n #d_hit['count_com'] = sum_com\n return d_hit, l1_freq_dic, l2_freq_dic\n \n\nif __name__ == '__main__':\n sen = u\"\"\"其难吃他欠房租不好吃都不没人记搬得态度不好了,暂停收录只暂停收录记得再也不来冰要的不会来小拖欠份,上工资来转租后出租大的出兑吓我转让了停业。我爱难吃北京\"\"\"\n wf = WordFreq()\n coms = [{'ccnt': sen}, {'ccnt': sen}]\n wf.calc(coms)\n","sub_path":"dzdp/comments/wordfreq.py","file_name":"wordfreq.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"467451965","text":"from django.conf.urls.defaults import *\nfrom django.conf import settings\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\t# Uncomment the admin/doc line below and add 'django.contrib.admindocs'\n\t# to INSTALLED_APPS to enable admin documentation:\n\t# (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n\t(r'^', include('ultimate.index.urls')),\n\t(r'^admin/', include(admin.site.urls)),\n\t(r'^captain/', include('ultimate.captain.urls')),\n\t(r'^forum/', include('pybb.urls', namespace='pybb')),\n\t(r'^junta/', include('ultimate.junta.urls')),\n\t(r'^leagues/', include('ultimate.leagues.urls')),\n\t(r'^user/', include('ultimate.user.urls')),\n)\n","sub_path":"ultimate/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"284823741","text":"import numpy as np\n\nfrom pathlib import Path\nfrom napari.utils.io import magic_imread\nfrom vispy.color import Colormap\n\nfrom brainio import brainio\nfrom imlib.general.system import get_sorted_file_paths\n\nfrom neuro.visualise.vis_tools import (\n get_image_scales,\n get_most_recent_log,\n read_log_file,\n)\nfrom neuro.visualise.napari_tools.utils import (\n convert_vtk_spline_to_napari_path,\n)\n\n\nlabel_red = Colormap([[0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0]])\n\n\ndef add_raw_image(viewer, image_path, name):\n \"\"\"\n Add a raw image (as a virtual stack) to the napari viewer\n :param viewer: Napari viewer object\n :param image_path: Path to the raw data\n :param str name: Name to give the data\n \"\"\"\n paths = get_sorted_file_paths(image_path, file_extension=\".tif\")\n images = magic_imread(paths, use_dask=True, stack=True)\n viewer.add_image(images, name=name, opacity=0.6, blending=\"additive\")\n\n\ndef display_raw(viewer, args):\n \"\"\"\n Display raw data\n :param viewer:\n :param args:\n :return:\n \"\"\"\n print(\n \"Starting raw image viewer. Streaming full-resolution data.\"\n \" This may be slow.\"\n )\n log_entries = read_log_file(get_most_recent_log(args.amap_directory))\n config_file = Path(args.amap_directory, \"config.conf\")\n image_scales = get_image_scales(log_entries, config_file)\n add_raw_image(viewer, log_entries[\"image_paths\"], name=\"Raw data\")\n\n if args.raw_channels:\n for raw_image in args.raw_channels:\n name = Path(raw_image).name\n print(f\"Found additional raw image to add to viewer: \" f\"{name}\")\n add_raw_image(viewer, raw_image, name=name)\n\n return image_scales\n\n\ndef display_downsampled(viewer, args, paths):\n \"\"\"\n Display downsampled data\n :param viewer:\n :param args:\n :param paths:\n :return:\n \"\"\"\n image_scales = (1, 1, 1)\n load_additional_downsampled_images(\n viewer, args.amap_directory, paths, memory=args.memory\n )\n\n viewer.add_image(\n prepare_load_nii(paths.downsampled_brain_path, memory=args.memory),\n name=\"Downsampled raw data\",\n )\n\n return image_scales\n\n\ndef display_registration(\n viewer, atlas, boundaries, image_scales, memory=False\n):\n \"\"\"\n Display results of the registration\n :param viewer: napari viewer object\n :param atlas: Annotations in sample space\n :param boundaries: Annotation boundaries in sample space\n :param tuple image_scales: Scaling of images from annotations -> data\n :param memory: Load data into memory\n \"\"\"\n viewer.add_image(\n prepare_load_nii(boundaries, memory=memory),\n name=\"Outlines\",\n contrast_limits=[0, 1],\n colormap=(\"label_red\", label_red),\n scale=image_scales,\n )\n\n # labels added last so on top\n labels = viewer.add_labels(\n prepare_load_nii(atlas, memory=memory),\n name=\"Annotations\",\n opacity=0.2,\n scale=image_scales,\n )\n labels.editable = False\n return labels\n\n\ndef load_additional_downsampled_images(\n viewer,\n amap_directory,\n paths,\n search_string=\"downsampled_\",\n extension=\".nii\",\n memory=False,\n):\n \"\"\"\n Loads additional downsampled (i.e. from nii) images into napari viewer\n :param viewer: Napari viewer object\n :param amap_directory: Directory containing images\n :param paths: amap paths object\n :param search_string: String that defines the images.\n Default: \"downampled_\"\n :param extension: File extension of the downsampled images. Default: \".nii\"\n :param memory: Load data into memory\n \"\"\"\n\n amap_directory = Path(amap_directory)\n\n for file in amap_directory.iterdir():\n if (\n (file.suffix == \".nii\")\n and file.name.startswith(search_string)\n and file != Path(paths.downsampled_brain_path)\n and file != Path(paths.tmp__downsampled_filtered)\n ):\n print(\n f\"Found additional downsampled image: {file.name}, \"\n f\"adding to viewer\"\n )\n name = file.name.strip(search_string).strip(extension)\n viewer.add_image(\n prepare_load_nii(file, memory=memory), name=name,\n )\n\n\ndef prepare_load_nii(nii_path, memory=False):\n \"\"\"\n Transforms a nii file into the same coordinate space as the raw data\n :param nii_path: Path to the nii file\n :param memory: Load data into memory\n :return: Numpy array in the correct coordinate space\n \"\"\"\n nii_path = str(nii_path)\n image = brainio.load_any(nii_path, as_numpy=memory)\n image = np.swapaxes(image, 2, 0)\n return image\n\n\ndef display_channel(viewer, reg_dir, channel_fname, memory=False, name=None):\n reg_dir = Path(reg_dir)\n\n layer = viewer.add_image(\n prepare_load_nii(reg_dir / channel_fname, memory=memory), name=name,\n )\n return layer\n\n\ndef add_new_label_layer(\n viewer,\n base_image,\n name=\"region\",\n selected_label=1,\n num_colors=10,\n brush_size=30,\n):\n \"\"\"\n Takes an existing napari viewer, and adds a blank label layer\n (same shape as base_image)\n :param viewer: Napari viewer instance\n :param np.array base_image: Underlying image (for the labels to be\n referencing)\n :param str name: Name of the new labels layer\n :param int selected_label: Label ID to be preselected\n :param int num_colors: How many colors (labels)\n :param int brush_size: Default size of the label brush\n :return label_layer: napari labels layer\n \"\"\"\n labels = np.empty_like(base_image)\n label_layer = viewer.add_labels(labels, num_colors=num_colors, name=name)\n label_layer.selected_label = selected_label\n label_layer.brush_size = brush_size\n return label_layer\n\n\ndef view_spline(\n viewer,\n image_layer,\n spline,\n x_scaling,\n y_scaling,\n z_scaling,\n spline_size,\n name=\"Spline fit\",\n):\n max_z = len(image_layer.data)\n napari_spline = convert_vtk_spline_to_napari_path(\n spline, x_scaling, y_scaling, z_scaling, max_z\n )\n\n viewer.add_points(\n napari_spline,\n size=spline_size,\n edge_color=\"cyan\",\n face_color=\"cyan\",\n blending=\"additive\",\n opacity=0.7,\n name=name,\n )\n","sub_path":"neuro/visualise/napari_tools/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":6272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"456284788","text":"# Copyright 2023, Kay Hayen, mailto:kay.hayen@gmail.com\n#\n# Part of \"Nuitka\", an optimizing Python compiler that is compatible and\n# integrates with CPython, but also works on its own.\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#\n\"\"\" Release related common functionality.\n\n\"\"\"\n\nimport os\n\nfrom nuitka.utils.Execution import NuitkaCalledProcessError, check_output\nfrom nuitka.utils.FileOperations import (\n getFileContents,\n getFileFirstLine,\n openTextFile,\n)\nfrom nuitka.Version import getNuitkaVersion\n\n\ndef checkAtHome(expected=\"Nuitka Staging\"):\n assert os.path.isfile(\"setup.py\")\n\n if os.path.isdir(\".git\"):\n git_dir = \".git\"\n else:\n line = getFileFirstLine(\".git\", \"r\").strip()\n git_dir = line[8:]\n\n git_description_filename = os.path.join(git_dir, \"description\")\n description = getFileContents(git_description_filename).strip()\n\n assert description == expected, (expected, description)\n\n\ndef getBranchName():\n # Using a fallback for old git, hopefully not necessary as much anymore.\n try:\n branch_name = check_output(\"git branch --show-current\".split()).strip()\n except NuitkaCalledProcessError:\n branch_name = check_output(\"git symbolic-ref --short HEAD\".split()).strip()\n\n if str is not bytes:\n branch_name = branch_name.decode()\n\n return branch_name\n\n\ndef checkBranchName():\n branch_name = getBranchName()\n\n nuitka_version = getNuitkaVersion()\n\n assert branch_name in (\n \"main\",\n \"develop\",\n \"factory\",\n \"release/\" + nuitka_version,\n \"hotfix/\" + nuitka_version,\n ), branch_name\n\n return branch_name\n\n\ndef getBranchCategory(branch_name):\n \"\"\"There are 3 categories of releases. Map branch name on them.\"\"\"\n\n if (\n branch_name.startswith(\"release\")\n or branch_name == \"main\"\n or branch_name.startswith(\"hotfix/\")\n ):\n category = \"stable\"\n elif branch_name == \"factory\":\n category = \"factory\"\n elif branch_name == \"develop\":\n category = \"develop\"\n else:\n assert False\n\n return category\n\n\ndef checkNuitkaChangelog():\n with openTextFile(\"Changelog.rst\", \"r\") as f:\n # First paragraph doesn't count\n while True:\n line = f.readline().strip()\n if line.startswith(\"***\") and line.endswith(\"***\"):\n break\n\n # Second line is the actual title.\n line = f.readline()\n\n if \"(Draft)\" in line:\n return \"draft\"\n else:\n return \"final\"\n","sub_path":"nuitka/tools/release/Release.py","file_name":"Release.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"373799275","text":"import pygame as pyg\nimport math\nimport sys\nfrom utilities import constants as c\nfrom entities import Memory, Game, agent\nfrom recordtype import recordtype\nfrom itertools import count\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass PlayerSprite(pyg.sprite.Sprite):\n def __init__(self, row, col, turn):\n pyg.sprite.Sprite.__init__(self)\n self.image = pyg.transform.scale(images[turn - 1], (round(c.WIDTH / 6), round(c.HEIGHT / 6)))\n self.image.set_colorkey(c.BLACK)\n self.rect = self.image.get_rect()\n self.rect.center = (c.WIDTH / 10 * (col * 2 + 3), c.HEIGHT / 10 * (row * 2 + 3))\n\n\ndef draw_text(surf, text, size, x, y, color=(255, 255, 255)):\n font = pyg.font.Font(font_name, size)\n text_surface = font.render(text, True, color)\n text_rect = text_surface.get_rect()\n text_rect.center = (x, y)\n surf.blit(text_surface, text_rect)\n\n\ndef draw_background():\n for i in range(2, 4, 1):\n pyg.draw.line(screen, c.GREY,\n (c.WIDTH / 5 * i, c.HEIGHT / 5),\n (c.WIDTH / 5 * i, c.HEIGHT / 5 * 4), 11)\n pyg.draw.line(screen, c.GREY,\n (c.WIDTH / 5, c.HEIGHT / 5 * i),\n (c.WIDTH / 5 * 4, c.HEIGHT / 5 * i), 11)\n\n\ndef pygame_loop():\n # Game loop\n running = True\n while running:\n clock.tick(c.FPS)\n for event in pyg.event.get():\n if event.type == pyg.QUIT:\n running = False\n elif event.type == pyg.MOUSEBUTTONDOWN:\n x, y = pyg.mouse.get_pos()\n if (c.WIDTH / 5) < x < (c.WIDTH / 5 * 4) and (c.HEIGHT / 5) < y < (c.HEIGHT / 5 * 4):\n col = math.floor(x / (c.WIDTH / 5) - 1)\n row = math.floor(y / (c.HEIGHT / 5) - 1)\n termination_state, sprite_params = game.new_play(row, col)\n game.PLAY_SPRITES.append(\n PlayerSprite(sprite_params[0], sprite_params[1], sprite_params[2]))\n all_sprites.add(game.PLAY_SPRITES[-1])\n all_sprites.draw(screen)\n pyg.display.flip()\n if termination_state == -1:\n game_over_screen(game.winner)\n elif event.type == pyg.KEYDOWN:\n key_state = pyg.key.get_pressed()\n if key_state[pyg.K_ESCAPE]:\n running = False\n # Update\n all_sprites.update()\n\n # Draw / render\n screen.fill(c.BLACK)\n draw_background()\n previous_turn = game.turn\n\n if game.turn == agent.adversary:\n pyg.draw.rect(screen, c.RED,\n (round(c.WIDTH / 20),\n round(c.HEIGHT / 20),\n round(c.WIDTH / 20 * 3),\n round(c.HEIGHT / 20 * 3)),\n 5,\n 8)\n else:\n pyg.draw.rect(screen, c.CYAN,\n (round(c.WIDTH / 20 * 16),\n round(c.HEIGHT / 20),\n round(c.WIDTH / 20 * 3),\n round(c.HEIGHT / 20 * 3)), 5, 8)\n if c.HUMAN_VS_AI:\n termination_state, sprite_params = game.AI_play()\n else:\n termination_state, sprite_params = agent.play_visual(previous_turn, game)\n game.PLAY_SPRITES.append(PlayerSprite(sprite_params[0], sprite_params[1], sprite_params[2]))\n all_sprites.add(game.PLAY_SPRITES[-1])\n all_sprites.draw(screen)\n pyg.display.flip()\n if termination_state == -1:\n game_over_screen(game.winner)\n\n draw_text(screen, str(game.score[0]), 64, c.WIDTH / 20 * 2.5, c.HEIGHT / 20 * 2.5, c.RED)\n draw_text(screen, str(game.score[1]), 64, c.WIDTH / 20 * 17.5, c.HEIGHT / 20 * 2.5, c.CYAN)\n all_sprites.draw(screen)\n pyg.display.flip()\n\n\ndef game_over_screen(winner):\n s = pyg.Surface((c.WIDTH, c.HEIGHT), pyg.SRCALPHA)\n s.fill((64, 64, 64, 164))\n screen.blit(s, (0, 0))\n draw_text(screen, \"Game Over!\", 64, c.WIDTH / 2, c.HEIGHT / 4, c.YELLOW)\n if winner == 3:\n draw_text(screen, \"It was a tie! \", 32,\n c.WIDTH / 2, c.HEIGHT / 2, c.YELLOW)\n else:\n draw_text(screen, \"Player \" + str(winner) + ' won', 32,\n c.WIDTH / 2, c.HEIGHT / 2, c.RED if winner == 1 else c.CYAN)\n game.score[winner - 1] += 1\n draw_text(screen, \"\", 24, c.WIDTH / 2, c.HEIGHT * 3 / 4, c.YELLOW)\n pyg.display.flip()\n waiting = True\n while waiting:\n clock.tick(c.FPS)\n for event in pyg.event.get():\n if event.type == pyg.QUIT:\n pyg.quit()\n sys.exit()\n if event.type == pyg.KEYDOWN or event.type == pyg.MOUSEBUTTONDOWN:\n key_state = pyg.key.get_pressed()\n if key_state[pyg.K_ESCAPE]:\n pyg.quit()\n sys.exit()\n waiting = False\n game.new_game()\n\n\ndef play_wo_training(game, agent):\n wins = 0\n looses = 0\n ties = 0\n i_episode = 0\n game.new_game()\n for i_episode in range(c.NUM_GAMES):\n for _ in count():\n previous_turn = game.turn\n if game.turn == agent.adversary:\n termination_state, _ = game.AI_play()\n else:\n termination_state, _ = agent.play_visual(previous_turn, game)\n\n if termination_state == -1:\n # print(game.state, game.winner)\n wins += 1 if game.winner == agent.NNet_player else 0\n looses += 1 if game.winner == agent.adversary else 0\n ties += 1 if game.winner == 3 else 0\n game.new_game()\n break\n print('After ', i_episode, ' games')\n print('w: ', wins, ' l:', looses, ' t:', ties)\n\n\ndef silent_training(game, agent, replay_memory):\n total_losses = []\n iteration = 0\n loss = [0]\n total_illegal_moves = []\n wins = 0\n total_wins = []\n looses = 0\n ties = 0\n game.new_game()\n for i_episode in range(c.NUM_GAMES):\n illegal_moves = 0\n for _ in count():\n iteration += 1\n previous_turn = game.turn\n if game.turn == agent.adversary:\n termination_state, _ = game.AI_play()\n if game.winner > 0:\n replay_memory.memory[-1].reward =\\\n agent.calculate_reward(previous_turn, game.turn, game.winner)\n if len(replay_memory.memory) > 0:\n replay_memory.memory[-1].next_state = game.state.copy()\n else:\n termination_state, _, illegal_moves =\\\n agent.play(previous_turn, game, replay_memory, experience, illegal_moves)\n\n # if Game over, update counters and start a new game\n if termination_state == -1:\n if game.winner == agent.NNet_player:\n wins += 1\n total_wins.append(1)\n else:\n looses += 1 if game.winner == agent.adversary else 0\n ties += 1 if game.winner == 3 else 0\n total_wins.append(0)\n game.new_game()\n break\n\n # If we have enough experiences, start optimizing\n if replay_memory.can_sample_memory(c.BATCH_SIZE * c.EPOCHS):\n experiences = replay_memory.sample(c.BATCH_SIZE * c.EPOCHS)\n loss = agent.PolicyNetwork.RL_train(experiences, agent.TargetNetwork, experience, iteration)\n total_losses.append(loss[0])\n\n if i_episode % c.TARGET_UPDATE == 0:\n agent.TargetNetwork.copy_from(agent.PolicyNetwork)\n\n if i_episode % 27 == 0:\n if len(total_wins) > 25:\n win_pctg = np.sum(np.array(total_wins[-25:])) / len(total_wins[-25:])*100\n else:\n win_pctg = np.sum(np.array(total_wins)) / len(total_wins) * 100\n\n print('\\nGame: ', i_episode,\n '| Illegal moves: ', illegal_moves,\n '| Loss: ', loss[0],\n '| Win %:', str(win_pctg), '\\n')\n\n total_illegal_moves.append(illegal_moves)\n\n if i_episode % 1000 == 0 and i_episode > 900:\n agent.PolicyNetwork.save_to_file()\n\n print('w: ', wins, ' l:', looses, ' t:', ties)\n agent.PolicyNetwork.save_to_file()\n\n fig = plt.figure()\n fig.canvas.set_window_title('Loss function across all episodes')\n fig.set_size_inches(11, 6)\n axs1 = fig.add_subplot(2, 2, 1)\n x = np.linspace(0, len(total_losses), len(total_losses))\n axs1.plot(x, total_losses, c='grey')\n moving_average_period = 64\n ma = np.convolve(total_losses, np.ones(moving_average_period), 'valid') / moving_average_period\n ma = np.concatenate((total_losses[:moving_average_period-1], ma))\n axs1.plot(x, ma, c='r')\n axs1.set_ylabel('Loss (squared error)', fontsize=10, color='.25')\n axs1.set_xlabel('Training Round', fontsize=10, color='.25')\n\n axs2 = fig.add_subplot(2, 2, 2)\n x2 = np.linspace(0, len(total_illegal_moves), len(total_illegal_moves))\n axs2.plot(x2, total_illegal_moves, c='grey')\n axs2.set_ylabel('Illegal Moves', fontsize=10, color='.25')\n axs2.set_xlabel('Episode', fontsize=10, color='.25')\n ma2 = np.convolve(total_illegal_moves, np.ones(moving_average_period), 'valid') / moving_average_period\n ma2 = np.concatenate((total_illegal_moves[:moving_average_period-1], ma2))\n axs2.plot(x2, ma2, c='r')\n\n axs3 = fig.add_subplot(2, 2, 3)\n x3 = np.linspace(0, len(total_wins), len(total_wins))\n ma3 = np.convolve(total_wins, np.ones(moving_average_period), 'valid') / moving_average_period * 100\n ma3 = np.concatenate((total_illegal_moves[:moving_average_period-1], ma3))\n axs3.set_ylabel('Win %', fontsize=10, color='.25')\n axs3.set_xlabel('Episode', fontsize=10, color='.25')\n axs3.plot(x3, ma3, c='r')\n plt.show()\n\n\nif c.VISUAL:\n # initialize pygame and create window\n pyg.init()\n pyg.mixer.init()\n screen = pyg.display.set_mode((c.WIDTH, c.HEIGHT))\n pyg.display.set_caption(\"Tic Tac Toe\")\n clock = pyg.time.Clock()\n all_sprites = pyg.sprite.Group()\n\n # load images and font\n images = [pyg.image.load('media/cross.png').convert(),\n pyg.image.load('media/circle.png').convert()]\n font_name = pyg.font.match_font('Calibri')\n\n# initialize game\ngame = Game.Game()\n\n# create neural network\nexperience = recordtype('experience', 'state action reward next_state')\nagent = agent.Agent(c.INPUTS, c.HIDDEN_LAYERS, c.OUTPUTS, c.LEARNING_RATE)\nreplay_memory = Memory.ReplayMemory(c.MEMORY_CAPACITY)\nagent.PolicyNetwork.load_from_file()\nagent.TargetNetwork.copy_from(agent.PolicyNetwork)\n\nif c.VISUAL:\n pygame_loop()\n\nif not c.VISUAL and c.TRAIN:\n silent_training(game, agent, replay_memory)\nelif not c.VISUAL and not c.TRAIN:\n play_wo_training(game, agent)\n\npyg.quit()\n","sub_path":"OwnNNet_TicTacToe.py","file_name":"OwnNNet_TicTacToe.py","file_ext":"py","file_size_in_byte":11081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"11495562","text":"import numpy as np\r\nfrom Pole import Pole as Pole\r\nfrom Rotate import Rotate as Rotate\r\nfrom StCoordLine import StCoordLine as StCoordLine\r\n\r\ndef GreatCircle(strike,dip,sttype):\r\n\t'''\r\n\tGreatCircle computes the great circle path of a plane\r\n\tin an equal angle or equal area stereonet of unit radius\r\n\t\r\n\tstrike = strike of plane\r\n\tdip = dip of plane\r\n\tsttype = type of stereonet: 0 = equal angle, 1 = equal area\r\n\tpath = x and y coordinates of points in great circle path\r\n\t\r\n\tNOTE: strike and dip should be entered in radians.\r\n\t\r\n\tGreatCircle uses functions StCoordLine, Pole and Rotate\r\n\t\r\n\tPython function translated from the Matlab function\r\n\tGreatCircle in Allmendinger et al. (2012)\r\n\t'''\r\n\tpi = np.pi\r\n\t# Compute the pole to the plane. This will be the axis of\r\n\t# rotation to make the great circle\r\n\ttrda, plga = Pole(strike,dip,1)\r\n\t\r\n\t# Now pick the strike line at the intersection of the\r\n\t# great circle with the primitive of the stereonet\r\n\ttrd = strike\r\n\tplg = 0.0\r\n\t\r\n\t# To make the great circle, rotate the line 180 degrees\r\n\t# in increments of 1 degree\r\n\trot = np.arange(0,181,1)*pi/180\r\n\tpath = np.zeros((rot.shape[0],2))\r\n\t\r\n\tfor i in range(rot.shape[0]):\r\n\t# Avoid joining ends of path\r\n\t\tif rot[i] == pi:\r\n\t\t\trot[i] = rot[i]*0.9999\r\n\t\t# Rotate line\r\n\t\trtrd, rplg = Rotate(trda,plga,rot[i],trd,plg,'a')\r\n\t\t# Calculate stereonet coordinates of rotated line\r\n\t\t# and add to great circle path\r\n\t\tpath[i,0], path[i,1] = StCoordLine(rtrd,rplg,sttype)\r\n\t\r\n\treturn path\r\n\t","sub_path":"source/functions/GreatCircle.py","file_name":"GreatCircle.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"132112815","text":"\"\"\"Common information so that all traceback generating scripts\n create files in the same format.\n\n\"\"\"\nimport os\nimport sys\nfrom contextlib import redirect_stderr\n\nimport friendly_traceback\n\n\ndef write(text):\n sys.stderr.write(text + \"\\n\")\n\n\ndef make_title(text):\n write(\"\\n\" + text)\n write(\"-\" * len(text) + \"\\n\")\n write(\".. code-block:: none\\n\")\n\n\n# The format of each item of the dict below is:\n# ExceptionClass - optional heading: (file, test_function)\n#\n# When a given exception class has more than one cases,\n# the optional heading part hast to be added since each dict item must have\n# a unique key. It can also be helpful to quickly identify if a particular\n# case is included.\n\n\nall_imports = {\n \"ArithmeticError\": (\"test_arithmetic_error\", \"test_arithmetic_error\"),\n \"FileNotFoundError\": (\n \"test_file_not_found_error\",\n \"test_file_not_found_error\",\n ),\n \"ImportError\": (\"test_import_error\", \"test_import_error\"),\n\n \"KeyError\": (\"test_key_error\", \"test_key_error\"),\n \"LookupError\": (\"test_lookup_error\", \"test_lookup_error\"),\n \"IndexError - short tuple\": (\"test_index_error\", \"test_index_error1\"),\n \"IndexError - long list\": (\"test_index_error\", \"test_index_error2\"),\n \"ModuleNotFoundError\": (\n \"test_module_not_found_error\",\n \"test_module_not_found_error\",\n ),\n \"NameError\": (\"test_name_error\", \"test_name_error\"),\n \"OverflowError\": (\"test_overflow_error\", \"test_overflow_error\"),\n \"TypeError - 1: concatenate two different types\": (\n \"test_type_error\",\n \"test_type_error1\",\n ),\n \"TypeError - 1a: concatenate two different types\": (\n \"test_type_error\",\n \"test_type_error1a\",\n ),\n \"TypeError - 1b: concatenate two different types\": (\n \"test_type_error\",\n \"test_type_error1b\",\n ),\n \"TypeError - 2: unsupported operand type(s) for +\": (\n \"test_type_error\",\n \"test_type_error2\",\n ),\n \"TypeError - 2a: unsupported operand type(s) for +=\": (\n \"test_type_error\",\n \"test_type_error2a\",\n ),\n \"TypeError - 3: unsupported operand type(s) for -\": (\n \"test_type_error\",\n \"test_type_error3\",\n ),\n \"TypeError - 3a: unsupported operand type(s) for -=\": (\n \"test_type_error\",\n \"test_type_error3a\",\n ),\n \"TypeError - 4: unsupported operand type(s) for *\": (\n \"test_type_error\",\n \"test_type_error4\",\n ),\n \"TypeError - 4a: unsupported operand type(s) for ``*=``\": (\n \"test_type_error\",\n \"test_type_error4a\",\n ),\n \"TypeError - 5: unsupported operand type(s) for /\": (\n \"test_type_error\",\n \"test_type_error5\",\n ),\n \"TypeError - 5a: unsupported operand type(s) for /=\": (\n \"test_type_error\",\n \"test_type_error5a\",\n ),\n \"TypeError - 5b: unsupported operand type(s) for //\": (\n \"test_type_error\",\n \"test_type_error5b\",\n ),\n \"TypeError - 5c: unsupported operand type(s) for //=\": (\n \"test_type_error\",\n \"test_type_error5c\",\n ),\n \"TypeError - 6: unsupported operand type(s) for &\": (\n \"test_type_error\",\n \"test_type_error6\",\n ),\n \"TypeError - 6a: unsupported operand type(s) for &=\": (\n \"test_type_error\",\n \"test_type_error6a\",\n ),\n \"TypeError - 7: unsupported operand type(s) for **\": (\n \"test_type_error\",\n \"test_type_error7\",\n ),\n \"TypeError - 7a: unsupported operand type(s) for ``**=``\": (\n \"test_type_error\",\n \"test_type_error7a\",\n ),\n \"TypeError - 8: unsupported operand type(s) for >>\": (\n \"test_type_error\",\n \"test_type_error8\",\n ),\n \"TypeError - 8a: unsupported operand type(s) for >>=\": (\n \"test_type_error\",\n \"test_type_error8a\",\n ),\n \"TypeError - 9: unsupported operand type(s) for @\": (\n \"test_type_error\",\n \"test_type_error9\",\n ),\n \"TypeError - 9a: unsupported operand type(s) for @=\": (\n \"test_type_error\",\n \"test_type_error9a\",\n ),\n \"TypeError - 10: comparison between incompatible types\": (\n \"test_type_error\",\n \"test_type_error10\",\n ),\n \"TypeError - 11: bad operand type for unary +\": (\n \"test_type_error\",\n \"test_type_error11\",\n ),\n \"TypeError - 11a: bad operand type for unary -\": (\n \"test_type_error\",\n \"test_type_error11a\",\n ),\n \"TypeError - 11b: bad operand type for unary ~\": (\n \"test_type_error\",\n \"test_type_error11b\",\n ),\n \"TypeError - 12: object does not support item assignment\": (\n \"test_type_error\",\n \"test_type_error12\",\n ),\n \"TypeError - 13: wrong number of positional arguments\": (\n \"test_type_error\",\n \"test_type_error13\",\n ),\n \"TypeError - 14: missing positional arguments\": (\n \"test_type_error\",\n \"test_type_error14\",\n ),\n \"TypeError - 15: tuple object is not callable\": (\n \"test_type_error\",\n \"test_type_error15\",\n ),\n \"TypeError - 15a: list object is not callable\": (\n \"test_type_error\",\n \"test_type_error15a\",\n ),\n \"UnboundLocalError\": (\"test_unbound_local_error\", \"test_unbound_local_error\"),\n \"Unknown exception\": (\"test_unknown_error\", \"test_unknown_error\"),\n \"ZeroDivisionError - 1\": (\"test_zero_division_error\", \"test_zero_division_error\"),\n \"ZeroDivisionError - 2\": (\"test_zero_division_error\", \"test_zero_division_error2\"),\n}\n\ncur_dir = os.getcwd()\nsys.path.append(os.path.join(cur_dir, \"except\"))\n\n\ndef create_tracebacks(target, intro_text):\n with open(target, \"w\", encoding=\"utf8\") as out:\n with redirect_stderr(out):\n write(intro_text)\n\n for title in all_imports:\n function = None\n name, function = all_imports[title]\n make_title(title)\n try:\n mod = __import__(name)\n if function is not None:\n result = getattr(mod, function)()\n write(result)\n except Exception:\n friendly_traceback.explain()\n\n\nprint(\"Number of cases in trb_common.py: \", len(all_imports))\n","sub_path":"tests/trb_common.py","file_name":"trb_common.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"258966938","text":"import numpy as np \nimport tensorflow\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Convolution2D\nfrom keras.layers import Flatten\nfrom keras.layers import MaxPooling2D\n\n\nclassifier=Sequential()\n\nclassifier.add(Convolution2D(32,3,3,activation='relu',input_shape=(64,64,3)))\nclassifier.add(MaxPooling2D(pool_size=(2,2)))\nclassifier.add(Convolution2D(64,3,3,activation='relu'))\nclassifier.add(MaxPooling2D(pool_size=(2,2)))\nclassifier.add(Flatten())\nclassifier.add(Dense(units=128,activation='relu'))\nclassifier.add(Dense(units=1,activation='sigmoid'))\nclassifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])\n\n#image augmentation\nfrom keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntraining_set = train_datagen.flow_from_directory(\n 'dataset/training_set',\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\ntest_set = test_datagen.flow_from_directory(\n 'dataset/test_set',\n target_size=(64,64),\n batch_size=32,\n class_mode='binary')\n\nclassifier.fit_generator(\n training_set,\n steps_per_epoch=8000,\n epochs=10,\n validation_data=test_set,\n validation_steps=2000)\n\nfrom keras.preprocessing import image\ntest_image=image.load_img('dataset/cat_or_dog1.png',target_size=(64,64))\ntest_image=image.img_to_array(test_image)\ntest_image=np.expand_dims(test_image,axis=0)\n\ntraining_set.class_indices\nresult=classifier.predict(test_image)\nif(result[0][0]==1):\n\tprint(\"Dog\")\nelse:\n\tprint(\"Cat\")\n#predicting the result\n","sub_path":"My_code.py","file_name":"My_code.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"510613768","text":"# -*- coding:utf-8 -*-\n_author_ = \"PayneLi\"\n_Time_ = \"18-5-10 下午10:56\"\n_File_ = \"5.天的电影票房对比条形图-1.py\"\nSoftWare = \"PyCharm\"\n\n\"\"\"create your coding\"\"\"\nfrom matplotlib import pyplot as plt\nfrom matplotlib import font_manager\n\na = [\"猩球崛起3:终极之战\", \"敦刻尔克\", \"蜘蛛侠:英雄归来\", \"战狼2\"]\nb_16 = [15746, 312, 4497, 319]\nb_15 = [12357, 156, 2045, 168]\nb_14 = [2358, 399, 2358, 362]\n\nbar_width = 0.2\n\n\nx_1 = range(3)\nx_2 = [i + bar_width for i in x_1]\nx_3 = [i + bar_width*2 for i in x_1]\nx_4 = [i + bar_width*3 for i in x_1]\n\n\ny_1 = [b_14[0], b_15[0], b_16[0]]\ny_2 = [b_14[1], b_15[1], b_16[1]]\ny_3 = [b_14[2], b_15[2], b_16[2]]\ny_4 = [b_14[3], b_15[3], b_16[3]]\n\nmy_font = font_manager.FontProperties(fname=\"/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc\")\n\nplt.figure(figsize=(20, 8), dpi=80)\n\nplt.bar(x_1, y_1, width=0.2, label=\"猩球崛起3:终极之战\")\nplt.bar(x_2, y_2, width=0.2, label=\"敦刻尔克\")\nplt.bar(x_3, y_3, width=0.2, label=\"蜘蛛侠:英雄归来\")\nplt.bar(x_4, y_4, width=0.2, label=\"战狼2\")\n\n_xticks = [\"2014-4-14\", \"2014-4-15\", \"2014-4-16\"]\n\nplt.xticks(list(range(3)), _xticks)\nplt.legend(prop=my_font, loc=\"upper_left\")\n\nplt.show()\n","sub_path":"DataAnalysis/matplotlib-demo/5.天的电影票房对比条形图-1.py","file_name":"5.天的电影票房对比条形图-1.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"505849387","text":"from django.contrib import messages\nfrom django.shortcuts import render,redirect\n# Create your views here.\nfrom badmin.sms import sendSMS\nfrom user.models import ResiterModel\n\ndef saveDetails(request):\n uname=request.POST.get(\"t1\")\n passwd=request.POST.get(\"t2\")\n if uname==\"thrilok\" and passwd==\"THRILOK\":\n return redirect('admin_home')\n else:\n messages.error(request,\"invalid login details\")\n return redirect('admin_login')\ndef pending_reg(request):\n reg=ResiterModel.objects.filter(status=\"pending\")\n return render(request,\"badmin_templates/pending_reg.html\",{\"msg\":reg})\n\ndef approved_reg(request):\n result=ResiterModel.objects.filter(status=\"approved\")\n return render(request,\"badmin_templates/approved_reg.html\",{\"msg\":result})\ndef declined_reg(request):\n result=ResiterModel.objects.filter(status=\"declined\")\n return render(request,\"badmin_templates/declined_reg.html\",{\"msg\":result})\ndef approved(request):\n x=request.POST[\"t1\"]\n result=ResiterModel.objects.filter(name=x)\n name=\"\"\n contact=\"\"\n for x in result:\n name=x.name\n contact=x.contact\n result.update(status=\"approved\")\n mess='Hello Mr/Miss :'+ name +'your registration was approved '\n x=sendSMS(str(contact),mess)\n print(x)\n return redirect('approved_reg')\n\ndef declined(request):\n x=request.POST.get(\"t2\")\n result = ResiterModel.objects.filter(name=x)\n name = \"\"\n contact = \"\"\n for x in result:\n name = x.name\n contact = x.contact\n result.update(status=\"approved\")\n mess = 'Hello Mr/Miss :' + name + 'your registration was declined '\n x = sendSMS(str(contact), mess)\n print(x)\n return redirect('declined_reg')\n\ndef logout(request):\n return redirect('home')","sub_path":"badmin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"67866240","text":"# Copyright 2021 Huawei Technologies Co., Ltd\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# =========================================================================\n\nimport os\nimport glob\nimport numpy as np\nfrom src.config import config as cfg\nfrom src.transform import ExpandChannel, LoadData, Orientation, ScaleIntensityRange, RandomCropSamples, OneHot\n\nimport torchvision\nimport torch\n\nclass TorchDataset(torch.utils.data.Dataset):\n \"\"\"\n A generic dataset with a length property and an optional callable data transform\n when fetching a data sample.\n\n Args:\n data: input data to load and transform to generate dataset for model.\n seg: segment data to load and transform to generate dataset for model\n \"\"\"\n def __init__(self, data, seg, transform=None):\n self.data = data\n self.seg = seg\n self.transform = transform\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index):\n data = self.data[index]\n seg = self.seg[index]\n for trans in self.transform:\n data, seg = trans(data, seg)\n return data, seg\n\nclass ConvertLabel:\n \"\"\"\n Crop at the center of image with specified ROI size.\n\n Args:\n roi_size: the spatial size of the crop region e.g. [224,224,128]\n If its components have non-positive values, the corresponding size of input image will be used.\n \"\"\"\n def operation(self, data):\n \"\"\"\n Apply the transform to `img`, assuming `img` is channel-first and\n slicing doesn't apply to the channel dim.\n \"\"\"\n data[data > cfg['upper_limit']] = 0\n data = data - (cfg['lower_limit'] - 1)\n data = np.clip(data, 0, cfg['lower_limit'])\n return data\n\n def __call__(self, image, label):\n label = self.operation(label)\n return image, label\n\n\n\n\ndef create_dataset(data_path, seg_path, config, is_training=True):\n seg_files = sorted(glob.glob(os.path.join(seg_path, \"*.nii.gz\")))\n train_files = [os.path.join(data_path, os.path.basename(seg)) for seg in seg_files]\n\n if is_training:\n transform_image = [LoadData(),\n ExpandChannel(),\n Orientation(),\n ScaleIntensityRange(src_min=config.min_val, src_max=config.max_val, tgt_min=0.0, \\\n tgt_max=1.0, is_clip=True),\n RandomCropSamples(roi_size=config.roi_size, num_samples=2),\n ConvertLabel(),\n OneHot(num_classes=config.num_classes)]\n else:\n transform_image = [LoadData(),\n ExpandChannel(),\n Orientation(),\n ScaleIntensityRange(src_min=config.min_val, src_max=config.max_val, tgt_min=0.0, \\\n tgt_max=1.0, is_clip=True),\n ConvertLabel()]\n\n dataset = TorchDataset(data=train_files, seg=seg_files, transform=transform_image)\n data_loader = torch.utils.data.DataLoader(dataset=dataset, \n batch_size=cfg.batch_size, shuffle=True, drop_last=True, num_workers=8)\n\n return data_loader\n","sub_path":"unet3d-pytorch-half/src/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"160593818","text":"from __future__ import absolute_import\nimport config\nfrom dns.resolver import Resolver\n\n# DEFAULTS\ndns_config = {\n\t'timeout': 15,\n\t'lifetime': 15,\n}\n# /DEFAULTS\n\n# CONFIG\nif \"dns\" in config.CHECKS:\n\tdns_config.update(config.CHECKS[\"dns\"])\n# /CONFIG\n\ndef check_dns(check, data):\n\tcheck.addOutput(\"ScoreEngine: {} Check\\n\".format(check.getServiceName()))\n\tcheck.addOutput(\"EXPECTED: Sucessful and correct query against the DNS server\")\n\tcheck.addOutput(\"OUTPUT:\\n\")\n\n\t# Setup the resolver\n\tresolv = Resolver()\n\tresolv.nameservers = [data[\"HOST\"]]\n\tresolv.timeout = dns_config[\"timeout\"]\n\tresolv.lifetime = dns_config[\"lifetime\"]\n\n\tcheck.addOutput(\"Starting check...\")\n\n\ttry:\n\t\t# Query resolver\n\t\tcheck.addOutput(\"Querying {HOST} for '{LOOKUP}'...\".format(**data))\n\t\tlookup = resolv.query(data[\"LOOKUP\"], data[\"TYPE\"])\n\n\t\tfound = False\n\t\tfor ans in lookup:\n\t\t\tif str(ans) == data[\"EXPECTED\"]:\n\t\t\t\tfound = True\n\t\t\telse:\n\t\t\t\tcheck.addOutput(\"NOTICE: DNS Server returned {}\".format(ans))\n\n\t\tif not found:\n\t\t\tcheck.addOutput(\"ERROR: DNS Server did not respond with the correct IP\")\n\t\t\treturn\n\n\t\t# We're good!\n\t\tcheck.setPassed()\n\t\tcheck.addOutput(\"Check successful!\")\n\texcept Exception as e:\n\t\tcheck.addOutput(\"ERROR: {}: {}\".format(type(e).__name__, e))\n\n\t\treturn\n","sub_path":"scoring/checks/dns.py","file_name":"dns.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"364940658","text":"\r\nimport uvicorn\r\nfrom fastapi import FastAPI\r\nfrom Readings import Reading\r\nimport numpy as np\r\nimport pickle\r\nimport pandas as pd\r\n\r\napp = FastAPI()\r\npickle_in = open(\"classifier.pkl\",\"rb\")\r\nclassifier =pickle.load(pickle_in)\r\n\r\n@app.get('/')\r\ndef index():\r\n return {'message' : 'Hello, Stranger'}\r\n\r\n@app.get('/{name}')\r\ndef get_name(name:str):\r\n return {'welcome' : f'{name}'}\r\n\r\n@app.post('/predict')\r\ndef predict_risk(data:Reading):\r\n data = data.dict()\r\n age = data['age']\r\n sex = data['sex']\r\n cp = data['cp'] \r\n trestbps = data['trestbps']\r\n chol = data['chol'] \r\n fbs = data['fbs']\r\n restecg = data['restecg']\r\n thalach = data['thalach']\r\n exang = data['exang']\r\n oldpeak = data['oldpeak']\r\n slope = data['slope']\r\n ca = data['ca'] \r\n thal = data['thal']\r\n print(classifier.predict([[age,sex,cp,trestbps,chol,fbs,restecg,thalach,exang,oldpeak,slope,ca,thal]]))\r\n prediction = classifier.predict([[age,sex,cp,trestbps,chol,fbs,restecg,thalach,exang,oldpeak,slope,ca,thal]])\r\n if(prediction[0]>0.5):\r\n prediction = \"The person has a risk of heart disease\"\r\n else:\r\n prediction = \"The person does not have any risk of heart disease\"\r\n return{\r\n 'prediction': prediction}\r\n\r\nif __name__ == '__main__':\r\n uvicorn.run(app,host='127.0.0.1',port=8000)\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"206036842","text":"#!/usr/bin/env python\n\nfrom wishbone import Actor\n\n\nclass BiggerAndSmaller(Actor):\n\n '''**Checks whether an integer is between min and max.**\n\n Checks whether an integer is between the defined minimum and maximum\n values. When the value is inside the scope it is submitted to the\n *inside* queue otherwise it is submitted to the *outside* queue.\n\n\n Parameters:\n\n - selection(str)('@data')\n | The value\n\n - min(int)(1)\n | The minimum integer value.\n\n - max(int)(100)\n | The maximum integer value.\n\n Queues:\n\n - inbox\n | Incoming messages\n\n - inside\n | Values are inside the and values.\n\n - outside\n | Values are outside the and values.\n '''\n\n def __init__(self, actor_config, selection='@data', min=1, max=100):\n Actor.__init__(self, actor_config)\n\n self.pool.createQueue(\"inbox\")\n self.pool.createQueue(\"inside\")\n self.pool.createQueue(\"outside\")\n self.registerConsumer(self.consume, \"inbox\")\n\n def consume(self, event):\n\n if not isinstance(event.data, int):\n raise TypeError(\"Event data is not type integer\")\n\n if event.get(self.kwargs.selection) >= self.kwargs.min and event.data <= self.kwargs.max:\n self.submit(event, self.pool.queue.inside)\n else:\n self.submit(event, self.pool.queue.outside)\n\n","sub_path":"docs/static/examples/biggerandsmaller.py","file_name":"biggerandsmaller.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"239702840","text":"\"\"\"Flask API for geospatial utils.\"\"\"\nimport logging\nfrom distutils.util import strtobool\nfrom os import getenv\n\nfrom caching import cache_file\n\nfrom flask import Flask, Response, jsonify, request\n\nfrom flask_caching import Cache\n\nfrom flask_cors import CORS\n\nfrom timer import timed\n\nfrom zonal_stats import calculate_stats\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\napp = Flask(__name__)\napp.config['JSON_AS_ASCII'] = False\nCORS(app)\n\n# For more configuration options, check out the documentation\n# Caching durations are in seconds.\ncache = Cache(app, config={'CACHE_TYPE': 'simple'})\n\n\n@timed\n@cache.memoize(3600)\ndef _calculate_stats(zones, geotiff, stats, prefix, group_by, geojson_out):\n \"\"\"Calculate stats.\"\"\"\n return calculate_stats(\n zones,\n geotiff,\n stats=stats,\n prefix=prefix,\n group_by=group_by,\n geojson_out=geojson_out\n )\n\n\n@app.route('/stats', methods=['POST'])\n@timed\ndef stats():\n \"\"\"Return zonal statistics.\"\"\"\n # Accept data as json or form.\n data = request.get_json() or request.form\n geotiff_url = data.get('geotiff_url')\n zones_url = data.get('zones_url')\n if geotiff_url is None or zones_url is None:\n logger.error('Received {}'.format(data))\n return Response(\n response='400: geotiff_url and zones_url are both required.',\n status=400\n )\n\n geojson_out = strtobool(data.get('geojson_out', 'False'))\n group_by = data.get('group_by')\n\n geotiff = cache_file(\n prefix='raster',\n url=geotiff_url\n )\n\n zones = cache_file(\n prefix='zones',\n url=zones_url\n )\n\n features = _calculate_stats(\n zones,\n geotiff,\n stats=['min', 'max', 'mean', 'median', 'sum', 'std'],\n prefix='stats_',\n group_by=group_by,\n geojson_out=geojson_out\n )\n return jsonify(features)\n\n\n@app.route('/demo', methods=['GET'])\n@timed\ndef stats_demo():\n \"\"\"Return examples of zonal statistics.\"\"\"\n # The GET endpoint is used for demo purposes only\n geotiff_url = 'https://mongolia.sibelius-datacube.org:5000/?service=WCS&'\\\n 'request=GetCoverage&version=1.0.0&coverage=ModisAnomaly&'\\\n 'crs=EPSG%3A4326&bbox=86.5%2C36.7%2C119.7%2C55.3&width=1196&'\\\n 'height=672&format=GeoTIFF&time=2020-03-01'\n\n zones_url = 'https://prism-admin-boundaries.s3.us-east-2.amazonaws.com/'\\\n 'mng_admin_boundaries.json'\n\n geotiff = cache_file(\n prefix='raster_test',\n url=geotiff_url\n )\n\n zones = cache_file(\n prefix='zones_test',\n url=zones_url\n )\n\n geojson_out = request.args.get('geojson_out', 'False')\n group_by = request.args.get('group_by', None)\n\n geojson_out = strtobool(geojson_out)\n\n features = _calculate_stats(\n zones,\n geotiff,\n stats=['min', 'max', 'mean', 'median', 'sum', 'std'],\n prefix='stats_',\n group_by=group_by,\n geojson_out=geojson_out\n )\n\n # TODO - Properly encode before returning. Mongolian characters are returned as hex.\n return jsonify(features)\n\n\nif __name__ == '__main__' and getenv('FLASK_ENV') == 'development':\n # Only for debugging while developing\n app.run(host='0.0.0.0', debug=True, port=80)\n","sub_path":"api-flask/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"581609002","text":"##############################################################################\n#\n# Copyright (c) 2004 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Test tree item filters.\n\"\"\"\nimport unittest\n\nfrom zope.interface import directlyProvides\nfrom zope.interface.interface import InterfaceClass\n\nfrom zope.app.tree.filters import AllButInterfacesFilter\nfrom zope.app.tree.filters import OnlyInterfacesFilter\n\nfrom .test_adapters import SampleContent\n\n\nIRobot = InterfaceClass('IRobot', (), {})\nIHuman = InterfaceClass('IHuman', (), {})\nIAlien = InterfaceClass('IAlien', (), {})\nISpaceShipCaptain = InterfaceClass('ISpaceShipCaptain', (), {})\nIDeliveryBoy = InterfaceClass('IDeliveryBoy', (IHuman,), {})\nIProfessor = InterfaceClass('IProfessor', (IHuman,), {})\n\n\nclass FilterTestCase(unittest.TestCase):\n\n def setUp(self):\n self.makeObjects()\n\n def makeObjects(self):\n to_be_made = {\n 'bender': IRobot,\n 'fry': IDeliveryBoy,\n 'farnesworth': IProfessor,\n 'zapp': (IHuman, ISpaceShipCaptain),\n 'lur': (IAlien, ISpaceShipCaptain),\n 'kif': IAlien,\n }\n self.items = items = {}\n for name, iface in to_be_made.items():\n items[name] = obj = SampleContent()\n directlyProvides(obj, iface)\n\n def filterAndCompare(self, filter, expected):\n items = self.items\n result = [name for name, obj in items.items()\n if filter.matches(obj)]\n for name in expected:\n self.assertIn(name, result)\n result.remove(name)\n self.assertEqual(len(result), 0)\n\n def test_only_interfaces_filter(self):\n filter = OnlyInterfacesFilter(IHuman)\n self.filterAndCompare(filter,\n ('fry', 'farnesworth', 'zapp'))\n\n # even if we add delivery boy to it, the list shouldn't change\n filter = OnlyInterfacesFilter(IHuman, IDeliveryBoy)\n self.filterAndCompare(filter,\n ('fry', 'farnesworth', 'zapp'))\n\n # Lur from Omicron Persei 8 is a starship captain too\n # (he also likes to eating hippies and destroying earth)\n filter = OnlyInterfacesFilter(IHuman, ISpaceShipCaptain)\n self.filterAndCompare(filter,\n ('fry', 'farnesworth', 'zapp', 'lur'))\n\n def test_all_but_interfaces_filter(self):\n # \"death to all humans!\"\n filter = AllButInterfacesFilter(IHuman)\n self.filterAndCompare(filter, ('lur', 'kif', 'bender'))\n\n # and to all spaceship captains...\n filter = AllButInterfacesFilter(IHuman, ISpaceShipCaptain)\n self.filterAndCompare(filter, ('kif', 'bender'))\n\n\ndef test_suite():\n return unittest.defaultTestLoader.loadTestsFromName(__name__)\n","sub_path":"src/zope/app/tree/tests/test_filters.py","file_name":"test_filters.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"288219788","text":"# Enable admin\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nfrom django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = patterns('',\n # Admin & documentation\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n\n # Pages\n url(r'^$', 'chartsapp.views.home', name='home'),\n url(r'^login/$', 'chartsapp.views.login', name='login'),\n url(r'^signup/$', 'chartsapp.views.signup', name='signup'),\n url(r'^logout/$', 'chartsapp.views.logout', name='logout'),\n url(r'^tw/dashboard/$', 'chartsapp.views.dashboard_tw', name='dashboard_tw'),\n url(r'^tw/view_watches/(?P
[-\\w]+)/$', 'chartsapp.views.view_watches_tw',\n name='view_watches_tw'),\n url(r'^tw/view_watches/$', 'chartsapp.views.view_watches_tw', name='view_watches_tw'),\n url(r'^tw/manage_watches/$', 'chartsapp.views.manage_watches_tw', name='manage_watches_tw'),\n\n)\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL,\n document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n","sub_path":"charts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"45577754","text":"S = list(input())\nN = len(S)\nstart = 0\nend = 0\nans = [0]*N\n\nfor i in range(1,N):\n if S[i-1] == S[i]:\n continue\n elif S[i-1] == 'R' and S[i] == 'L':\n r = i-1\n l = i\n\n elif S[i-1] == 'L' and S[i] == 'R':\n end = i-1\n\n ans[r] = int((r-start+2)/2) + int((end-l+1)/2)\n ans[l] = int((end-l+2)/2) + int((r-start+1)/2)\n start = i\n\nend = N-1\nans[r] = int((r-start+2)/2) + int((end-l+1)/2)\nans[l] = int((end-l+2)/2) + int((r-start+1)/2)\n\nfor a in ans:\n print(a, end=' ')\nprint(\"\")","sub_path":"ABC136/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"280331419","text":"# -*- coding: utf-8 -*-\n# Copyright Duncan Macleod 2018\n#\n# This file is part of GWOSC.\n#\n# GWOSC is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# GWOSC is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with GWOSC. If not, see .\n\n\"\"\"Tests for :mod:`gwosc.locate`\n\"\"\"\n\nimport os.path\nimport re\n\nimport pytest\n\nfrom .. import (\n locate,\n urls as gwosc_urls,\n utils,\n)\n\n__author__ = 'Duncan Macleod '\n\n\n@pytest.mark.remote\ndef test_get_urls():\n # test simple fetch for S6 data returns only files within segment\n detector = 'L1'\n start = 934000000\n end = 934100000\n span = (start, end)\n urls = locate.get_urls(detector, start, end)\n for url in urls:\n assert os.path.basename(url).startswith(\n '{}-{}'.format(detector[0], detector))\n assert utils.segments_overlap(\n utils.url_segment(url), span)\n\n # test fetch for GW170817 data\n assert len(locate.get_urls(\n 'L1', 1187007040, 1187009088,\n dataset=\"GW170817\",\n )) == 2\n\n # test for O1 data\n assert len(locate.get_urls(\"L1\", 1135136228, 1135140324)) == 2\n\n # assert no hits raises exception\n with pytest.raises(ValueError): # no data in 1980\n locate.get_urls(detector, 0, 1)\n with pytest.raises(ValueError): # no Virgo data for S6\n locate.get_urls('V1', start, end)\n\n\n@pytest.mark.remote\ndef test_get_urls_deprecated_tag():\n # test `tag` prints a warning\n pytest.deprecated_call(\n locate.get_urls,\n \"L1\",\n 1187007040,\n 1187009088,\n tag=\"TEST\",\n )\n\n\n@pytest.mark.remote\ndef test_get_event_urls(gw150914_urls):\n # find latest version by brute force\n latestv = sorted(\n gwosc_urls.URL_REGEX.match(\n os.path.basename(u['url'])).groupdict()['version'] for\n u in gw150914_urls)[-1]\n\n event = 'GW150914'\n urls = locate.get_event_urls(event)\n v_regex = re.compile(\"_[RV]{}-\".format(latestv))\n for url in urls:\n assert url.endswith('.hdf5') # default format\n assert '_4KHZ_' in url # default sample rate\n assert v_regex.search(url) # highest matched version\n\n urls = locate.get_event_urls(event, version=1)\n v1_regex = re.compile(\"_[RV]1-\")\n for url in urls:\n assert v1_regex.search(url)\n\n\n@pytest.mark.remote\ndef test_get_urls_gw170104():\n # check that we can find the right URL from an event dataset for\n # a GPS time that doesn't overlap with the event, and starts after\n # the end of the 32-second files (this used to not work)\n urls = locate.get_urls('L1', 1167558912.6, 1167559012.6, version=1)\n assert list(map(os.path.basename, urls)) == [\n \"L-L1_GWOSC_4KHZ_R1-1167557889-4096.hdf5\",\n ]\n","sub_path":"gwosc/tests/test_locate.py","file_name":"test_locate.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"300795582","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Dimitrios Paraschas\n# 1562\n# Dimitrios Greasidis\n# 1624\n# Stefanos Papanastasiou\n# 1608\n\n\nfrom __future__ import print_function\nimport sys\nimport logging\nimport json\nimport socket\n\n\ndef send_message(connection, message):\n try:\n connection.sendall(message)\n except socket.error:\n logging.error(\"error, send_message\")\n sys.exit(-1)\n\n logging.info(\"message sent: \" + message)\n\n\ndef json_load(json_file):\n with open(json_file, \"rb\") as file_:\n json_ = json.load(file_)\n\n return json_\n\n\ndef json_save(json_file, json_):\n with open(json_file, \"wb+\") as file_:\n json.dump(json_, file_, sort_keys=True, indent=4, separators=(\",\", \": \"))\n\n\nif __name__ == \"__main__\":\n print(\"This file is meant to be imported, not run.\")\n","sub_path":"client/library/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"33274410","text":"import numpy as np\nimport tensorflow as tf\nimport functools\nfrom model import *\n\n\ndef lazy_property(function):\n attribute = '_cache_' + function.__name__\n\n @property\n @functools.wraps(function)\n def decorator(self):\n if not hasattr(self, attribute):\n setattr(self, attribute, function(self))\n return getattr(self, attribute)\n\n return decorator\n\n\nclass RNNModel(Model):\n\n def __init__(self, cell, data, target):\n self.cell = cell\n self.data = data\n self.target = target\n self.prediction\n self.optimize\n self.error\n self.weight = tf.Variable(-1.0, validate_shape=False, name=\"weight\", dtype=tf.float64)\n self.bias = tf.Variable(-1.0, validate_shape=False, name=\"bias\", dtype=tf.float64)\n\n @lazy_property\n def prediction(self):\n val, _ = tf.nn.dynamic_rnn(self.cell, self.data, dtype=tf.float64)\n val = tf.transpose(val, [1, 0, 2])\n last = tf.gather(val, int(val.get_shape()[0]) - 1)\n\n data_size = int(self.data.get_shape()[1])\n target_size = int(self.target.get_shape()[1])\n\n self.weight = tf.Variable(tf.cast(tf.truncated_normal([self.cell.state_size, int(target_size)]), dtype=tf.float64), name=\"weight\")\n self.bias = tf.Variable(tf.cast(tf.constant(0.1, shape=[target_size]), dtype=tf.float64), name=\"bias\")\n return tf.nn.softmax(tf.matmul(last, self.weight) + self.bias)\n\n @lazy_property\n def optimize(self):\n cross_entropy = -tf.reduce_sum(self.target * tf.log(self.prediction))\n # I should try different optimizing functions\n optimizer = tf.train.AdamOptimizer()\n return optimizer.minimize(cross_entropy)\n\n @lazy_property\n def error(self):\n mistakes = tf.not_equal(tf.argmax(self.target, 1), tf.argmax(self.prediction, 1))\n return tf.reduce_mean(tf.cast(mistakes, tf.float64))\n\n def start_session(self):\n init_op = tf.initialize_all_variables()\n self.sess = tf.Session()\n self.sess.run(init_op)\n\n def end_session(self):\n self.sess.close()\n\n def train(self, batch_size, epoch, train_input, train_output):\n self.saver = tf.train.Saver()\n no_of_batches = int(len(train_input)) / batch_size\n for i in range(epoch):\n ptr = 0\n for j in range(no_of_batches):\n inp, out = train_input[ptr:ptr + batch_size], train_output[ptr:ptr + batch_size]\n ptr += batch_size\n incorrect = self.sess.run(self.optimize, {self.data: inp, self.target: out})\n if incorrect is None:\n incorrect = 1\n path = self.saver.save(self.sess, 'models/model_%d' % i)\n print(\"Session saved at: %s\" % path)\n\n def test(self, test_input, test_output):\n predictions = self.get_predictions(test_input)[:, 1]\n real_output = np.array(test_output)[:, 1]\n return self.test_and_set_stats(predictions, real_output)\n\n def get_predictions(self, test_input):\n return self.sess.run(self.prediction, {self.data: test_input})\n\n def predict(self, input_vector):\n return self.sess.run(self.prediction, {self.data: [input_vector]})[0]\n\n def save(self):\n # Add ops to save and restore all the variables.\n tf.add_to_collection('vars', self.weight)\n tf.add_to_collection('vars', self.bias)\n self.saver = tf.train.Saver({\"weight\": self.weight, \"bias\": self.bias})\n # Save the variables to disk.\n save_path = self.saver.save(self.sess, \"models/model.ckpt\")\n print(\"Model saved in file: %s\" % save_path)\n print(self.sess.run(self.weight))\n\n def restore(self):\n # Add ops to save and restore all the variables.\n self.saver = tf.train.Saver({\"weight\": self.weight, \"bias\": self.bias})\n # Restore variables from disk.\n with tf.Session() as sess:\n save_path = \"models/model.ckpt\"\n self.saver.restore(self.sess, save_path)\n print(\"Model restored from file: %s\" % save_path)\n #self.weight = sess.run(self.weight)\n #print(self.weight)\n\n def save_meta(self):\n print(self.sess.run(self.weight), self.sess.run(self.bias))\n tf.add_to_collection('vars', self.weight)\n tf.add_to_collection('vars', self.bias)\n sess = tf.Session()\n sess.run(tf.initialize_all_variables())\n self.saver.save(sess, 'models/model.ckpt')\n # `save` method will call `export_meta_graph` implicitly.\n # you will get saved graph files: models/model.ckpt.meta\n\n def restore_meta(self):\n with tf.Session() as sess:\n new_saver = tf.train.import_meta_graph('models/model.ckpt.meta')\n new_saver.restore(sess, tf.train.latest_checkpoint('models/'))\n all_vars = tf.get_collection('vars')\n for v in all_vars:\n v_ = sess.run(v)\n print(v_)\n\n def reset(self):\n tf.reset_default_graph()\n\n\nclass BasicRNNModel(RNNModel):\n\n def __init__(self, data, target):\n self.name = \"Basic RNN\"\n cell = tf.nn.rnn_cell.BasicRNNCell\n super().__init__(cell, data, target)\n\n\nclass LSTMModel(RNNModel):\n\n def __init__(self, data, target):\n self.name = \"LSTM\"\n cell = tf.nn.rnn_cell.LSTMCell\n super().__init__(cell, data, target)\n\n\nclass GRUModel(RNNModel):\n\n def __init__(self, data, target):\n self.name = \"GRU\"\n cell = tf.nn.rnn_cell.GRUCell\n super().__init__(cell, data, target)\n","sub_path":"ML/rnn_model2.py","file_name":"rnn_model2.py","file_ext":"py","file_size_in_byte":5557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"198347851","text":"def calculateLec(ttl,atl):\n temp = atl\n tempttl = ttl\n \n ans = 0\n\n #ans = int((100*atl)/ttl)\n\n while(ans <= 75):\n ans = int((100*atl)/ttl)\n\n if ans > 75:\n #print(ans,ttl,atl)\n break\n else:\n ttl = tempttl + ttl\n atl = atl+tempttl\n\n while(ans != 75):\n\n ttl = ttl-1\n atl = atl-1\n\n ans = int((100*atl)/ttl)\n #print(ans,ttl,atl)\n\n minlec = atl-temp\n\n if minlec < 0:\n return 0\n return minlec\n\n \n\n\n \n \n\nif __name__ == \"__main__\":\n ttl = 7\n atl = 6\n\n print(calculateLec(ttl,atl))\n","sub_path":"calculateLecture.py","file_name":"calculateLecture.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"589506008","text":"from gevent import monkey\nmonkey.patch_all()\n\nfrom flask import Flask, jsonify\nfrom flask import render_template, jsonify\nfrom flask_socketio import SocketIO\nfrom flask_socketio import send, emit\nimport random, time\nimport serial.tools.list_ports as porty\nimport serial\n\nfrom stoppable_thread import StoppableThread\n\napp = Flask(__name__)\napp.debug = True\nsocketio = SocketIO(app)\n\n'''\ndef background_thread():\n print(\"Starting thread\")\n while True:\n time.sleep(5)\n print(\"SERIAL FOUND\")\n socketio.emit('jack', {'data': 'hi'}, namespace='/test')\n\n ser.close()\n'''\nprint(\"Running app\")\n\nclass SerialProcess(StoppableThread):\n def __init__(self):\n print(\"Starting serial worker\")\n time.sleep(1)\n self.ser = serial.Serial(\"COM3\", 9600)\n\n super().__init__()\n\n def run(self):\n while not self.stopped():\n time.sleep(0.5)\n line = self.ser.readline()\n print(\"Line is {}\")\n socketio.emit('jack', {'data': line}, namespace='/test')\n\n self._stop()\n print(\"Ive been stopped\")\n\nthread = SerialProcess()\nthread.setDaemon(True)\nthread.start()\n\n#port = '/dev/ttyS0'\n#ser = serial.Serial(port, 115200, timeout=0)\n\n\n\n@app.route('/', methods=['GET'])\ndef index():\n '''\n Home view\n '''\n\n user = {'username':'Tom'}\n return render_template('index.html', title='Home', user=user)\n\n@app.route('/ports', methods=['GET', 'POST'])\ndef get_ports():\n \"\"\"\n Retrieve the ports or select which port the daemon uses\n \"\"\"\n port_list = [comport for comport in porty.comports()]\n print(porty.comports())\n print('Ports are {}'.format(port_list))\n return jsonify({'ports': port_list})\n\n@app.route('/die', methods=['GET'])\ndef kill_serial():\n \"\"\"\n Kill the daemon\n \"\"\"\n print(\"Killing the thread\")\n global thread\n thread.stop()\n thread.join()\n return jsonify({'data':'OK'})\n\n\n@socketio.on('connected_message', namespace='/test')\ndef connect_handler(message):\n print(\"Connected\")\n\n@socketio.on('test', namespace='/test')\ndef test_handler(json):\n print(\"In test handler\")\n print(json)\n #input_queue.put(json)\n emit('jack', {'data':json}, broadcast=True)\n\n@socketio.on('serial_thread', namespace='/test')\ndef test_handler(json):\n print(\"In serial thread handler\")\n print(json)\n #input_queue.put(json)\n emit('jack', {'data':json}, broadcast=True)\n\n\n\n","sub_path":"app/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"145378074","text":"#(5) 네트워크\n\ndef dfs(computers, visited, start):\n record = [start]\n while record:\n j = record.pop()\n if visited[j] == 0:\n visited[j] = 1\n for i in range(0, len(computers)):\n if computers[j][i] ==1 and visited[i] == 0:\n record.append(i)\n \ndef solution(n, computers):\n answer = 0\n visited = [0]*n\n start = 0\n while 0 in visited:\n if visited[start] ==0:\n dfs(computers, visited, start)\n answer +=1\n start+=1\n return answer\n\n\t\n#다른 코드\n'''\ndef solution(n, computers):\n networks = [{i} for i in range(n)]\n for computer1 in range(n):\n for computer2 in range(computer1+1,n):\n if computers[computer1][computer2] == 1:\n for pos,network in enumerate(networks):\n if computer1 in network:position1 = pos\n if computer2 in network:position2 = pos\n if position1 != position2:\n new_network = networks[position1]|networks[position2]\n networks.pop(max(position1,position2))\n networks.pop(min(position1,position2))\n networks.append(new_network)\n return len(networks)\n'''","sub_path":"level3/level3_ex05.py","file_name":"level3_ex05.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"8398574","text":"\"\"\"704. Binary Search\nGiven an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.\n\nYou must write an algorithm with O(log n) runtime complexity.\n\nExample 1:\nInput: nums = [-1,0,3,5,9,12], target = 9\nOutput: 4\nExplanation: 9 exists in nums and its index is 4\n\nExample 2:\nInput: nums = [-1,0,3,5,9,12], target = 2\nOutput: -1\nExplanation: 2 does not exist in nums so return -1\n\nConstraints:\n1 <= nums.length <= 104\n-104 < nums[i], target < 104\nAll the integers in nums are unique.\nnums is sorted in ascending order.\"\"\"\n\n\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n left, right = 0, len(nums) - 1\n\n while left <= right:\n mid = (right + left) // 2\n if target < nums[mid]: # look to the left\n right = mid - 1\n elif target > nums[mid]: # look in the right\n left = mid + 1\n else:\n return mid\n return -1\n\n\n\"\"\"Submission\nRuntime: 414 ms, faster than 26.14% of Python3 online submissions for Binary Search.\nMemory Usage: 15.4 MB, less than 71.43% of Python3 online submissions for Binary Search.\"\"\"\n","sub_path":"leetcode/704_binary_search.py","file_name":"704_binary_search.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"265905495","text":"import numpy as np\nfrom prml.random.random import RandomVariable\nfrom prml.random.beta import Beta\n\n\nclass Bernoulli(RandomVariable):\n \"\"\"\n Bernoulli distribution\n p(x|mu(prob)) = mu^x (1 - mu)^(1 - x)\n \"\"\"\n\n def __init__(self, prob=None):\n \"\"\"\n construct Bernoulli distribution\n\n Parameters\n ----------\n prob : (ndim,) np.ndarray or Beta\n probability of value 1\n \"\"\"\n assert prob is None or isinstance(prob, (np.ndarray, Beta))\n self.prob = prob\n\n def __setattr__(self, name, value):\n if name is \"prob\":\n if isinstance(value, np.ndarray):\n assert value.ndim == 1\n assert (value >= 0).all() and (value <= 1.).all()\n self.ndim = value.size\n object.__setattr__(self, name, value)\n elif isinstance(value, Beta):\n self.ndim = value.ndim\n self.prob_prior = value\n object.__setattr__(self, name, value)\n else:\n object.__setattr__(self, name, None)\n else:\n object.__setattr__(self, name, value)\n\n def __repr__(self):\n return \"Bernoulli(prob={})\".format(self.prob)\n\n @property\n def mean(self):\n return self.prob\n\n @property\n def var(self):\n return np.diag(self.prob * (1 - self.prob))\n\n def _ml(self, X):\n n_zeros = np.count_nonzero((X == 0).astype(np.int))\n n_ones = np.count_nonzero((X == 1).astype(np.int))\n assert X.size == n_zeros + n_ones, (\n \"{X.size} is not equal to {n_zeros} plus {n_ones}\"\n )\n self.prob = np.mean(X, axis=0)\n\n def _map(self, X):\n assert isinstance(self.prob, Beta)\n n_zeros = np.count_nonzero((X == 0).astype(np.int))\n n_ones = np.count_nonzero((X == 1).astype(np.int))\n assert X.size == n_zeros + n_ones\n n_ones += self.prob.n_ones\n n_zeros += self.prob.n_zeros\n self.prob = (n_ones - 1) / (n_ones + n_zeros - 2)\n\n def _bayes(self, X):\n assert isinstance(self.prob, Beta)\n n_zeros = np.count_nonzero((X == 0).astype(np.int))\n n_ones = np.count_nonzero((X == 1).astype(np.int))\n assert X.size == n_zeros + n_ones\n self.prob = Beta(\n n_ones=self.prob.n_ones + n_ones,\n n_zeros=self.prob.n_zeros + n_zeros\n )\n\n def _pdf(self, X):\n return np.prod(self.prob ** X * (1 - self.prob) ** (1 - X), axis=-1)\n\n def _draw(self, sample_size=1):\n if isinstance(self.prob, np.ndarray):\n return (\n self.prob > np.random.uniform(size=(sample_size, self.ndim))\n ).astype(np.int)\n elif isinstance(self.prob, Beta):\n return (\n self.prob.n_ones / (self.prob.n_ones + self.prob.n_zeros)\n > np.random.uniform(size=(sample_size, self.ndim))\n ).astype(np.int)\n elif isinstance(self.prob, RandomVariable):\n return (\n self.prob.draw(sample_size)\n > np.random.uniform(size=(sample_size, self.ndim))\n ).astype(np.int)\n else:\n raise AttributeError\n","sub_path":"prml/random/bernoulli.py","file_name":"bernoulli.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"523561560","text":"import twitter\nimport file_system_status as status\nfrom markovate import Markovator\n\nimport settings\nimport random\nfrom HTMLParser import HTMLParser\n\n\ndef create_markovated_tweet(tweets, max_length, unwanted_markovations=[]):\n tweets_texts = map(lambda t: t['text'].strip(), tweets)\n markovator = Markovator()\n markovator.parse_sentences(tweets_texts)\n markovation = markovator.markovate()\n\n unwanted_markovations.extend(tweets_texts)\n\n count = 0\n while len(markovation) > max_length or markovation in unwanted_markovations:\n markovation = markovator.markovate()\n count += 1\n if count > 20:\n return None\n\n return markovation\n\n\ndef filter_tweets(tweets):\n return filter_out_mentions(filter_out_links(tweets))\n\n\ndef filter_out_mentions(tweets):\n # TODO This is to be polite, we could keep tweets that mention people that follow us\n return filter(lambda t: not '@' in t['text'], tweets)\n\n\ndef filter_out_links(tweets):\n # Links are almost guaranteed to ruin the context of the markovation\n return filter(lambda t: not ('http://' in t['text'].lower() or\n 'https://' in t['text'].lower()), tweets)\n\n\ndef filter_out_bad_words(tweets):\n # Might be offensive/inappropriate for humour\n return filter(lambda t: not ('cancer' in t['text'].lower() or\n 'r.i.p' in t['text'].lower() or\n 'RIP' in t['text']), tweets)\n\n\ndef reply_to_user(client, user, tweet_id, app_status):\n if user['protected']:\n print(\"@\" + user['screen_name'] + \" if your tweets weren't protected I'd be able to say something constructive\")\n return\n\n screen_name = user['screen_name']\n\n print(screen_name)\n\n tweets = filter_tweets(twitter.get_tweets(client, screen_name))\n\n if len(tweets) <= 1:\n print(\"Not enough tweets\")\n fail_reply = \"@\" + screen_name + \" you don't say much, do you?\"\n if settings.post_replies:\n twitter.post_tweet(client, fail_reply)\n app_status['latest_reply'] = fail_reply\n return\n\n tweet_prefix = '@' + screen_name + ' '\n ideal_tweet_length = 140 - len(tweet_prefix)\n\n best_tweet = create_markovated_tweet(tweets, ideal_tweet_length)\n\n if best_tweet is not None:\n tweet = tweet_prefix + best_tweet\n if settings.post_replies:\n twitter.post_tweet(client, tweet, reply_to_id=tweet_id)\n encoded = unicode(tweet).encode('utf-8')\n print(encoded + '(' + str(len(encoded)) + ')')\n app_status['latest_reply'] = encoded\n else:\n print('
Could not generate reply
')\n app_status['latest_reply'] = 'Could not generate'\n\n\ndef process_replies(client):\n app_status = status.load()\n since_id = app_status.get('reply_since_id', -1)\n\n if since_id:\n mentions = twitter.get_mentions(client, since_id)\n else:\n mentions = twitter.get_mentions(client)\n\n print(str(len(mentions)) + \" mentions since \" + str(since_id))\n\n mentions.reverse()\n for mention in mentions:\n twitter.follow_user(client, mentions[-1]['user']['screen_name'])\n reply_to_user(client, mention['user'], mention['id'], app_status)\n\n app_status['reply_since_id'] = mention['id']\n app_status['latest_user_replied_to'] = mention['user']['screen_name']\n\n # Save after each one so if we crash we don't resend replies\n status.save(app_status)\n\n\ndef produce_next_tweet(client, app_status, query=''):\n app_status = status.load()\n tweet_length = 140\n word_count = 0\n query_is_hashtag = False\n\n if query == '':\n tweets = twitter.get_timeline_tweets(client, 800)\n else:\n tweets = twitter.get_search_tweets(client, 800, query)['statuses']\n\n tweets = filter_tweets(tweets)\n\n if len(tweets) <= 1:\n print('Could not generate tweet (not enough eligible tweets)')\n app_status['latest_tweet'] = 'Could not generate tweet (not enough eligible tweets)'\n return\n\n if query.startswith('#'):\n tweet_length -= len(query)\n query_is_hashtag = True\n\n recent_tweets = twitter.get_tweets(client, settings.screen_name)\n best_tweet = HTMLParser().unescape(create_markovated_tweet(tweets, tweet_length, map(lambda t: t['text'].strip(), recent_tweets)))\n\n # Try to avoid tweets that are just hashtags\n for word in best_tweet.split():\n if not word.startswith('#'):\n word_count += 1\n\n if best_tweet is not None and word_count > 0:\n if query_is_hashtag and query.lower() not in best_tweet.lower():\n best_tweet += ' ' + query # only add hashtag if not present\n if settings.post_tweets:\n twitter.post_tweet(client, best_tweet)\n encoded = unicode(best_tweet).encode('utf-8')\n print(encoded + '(' + str(len(encoded)) + ')')\n app_status['latest_tweet'] = encoded\n else:\n print('Could not generate tweet')\n app_status['latest_tweet'] = 'Could not generate tweet'\n\n status.save(app_status)\n\nif __name__ == \"__main__\":\n print(\"Started\")\n # First, try to authenticate\n client = twitter.auth_client(settings.consumer_key,\n settings.consumer_secret,\n settings.token_key,\n settings.token_secret)\n\n if client:\n #TODO move reply processing loop here\n process_replies(client)\n if random.randrange(100) < settings.tweet_chance:\n produce_next_tweet(client, status, settings.search_key)\n\n print(\"Finished\")\n","sub_path":"twitomatic.py","file_name":"twitomatic.py","file_ext":"py","file_size_in_byte":5608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"583221576","text":"import matplotlib.image as mpimg\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport cv2\r\nimport glob\r\nimport time\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn.preprocessing import StandardScaler\r\n# NOTE: the next import is only valid\r\n# for scikit-learn version <= 0.17\r\n# if you are using scikit-learn >= 0.18 then use this:\r\n# from sklearn.model_selection import train_test_split\r\nfrom sklearn.cross_validation import train_test_split\r\n\r\nimport sys\r\n\r\nfrom color_feature import extract_color_features\r\nfrom color_feature import scale_norm\r\nfrom load_data import load_training_images\r\n\r\n\r\ndef color_svc(X, y):\r\n print('Feature vector length:', len(X[0]))\r\n # Use a linear SVC\r\n svc = LinearSVC()\r\n # Check the training time for the SVC\r\n t = time.time()\r\n svc.fit(X, y)\r\n t2 = time.time()\r\n print(round(t2 - t, 2), 'Seconds to train SVC...')\r\n return svc\r\n\r\n\r\ndef try_color_parameters(path):\r\n cars, noncars = load_training_images(path)\r\n\r\n sample_size = 2000\r\n cars = cars[0:sample_size]\r\n notcars = noncars[0:sample_size]\r\n print('select', sample_size, 'images from', len(cars),\r\n 'car images and', len(noncars), 'non car images each')\r\n\r\n for spatial_color in 'RGB', 'YUV', 'LUV', 'YCrCb', 'GRAY', 'HLS', 'HSV':\r\n for hist_color in 'RGB', 'YUV', 'LUV', 'YCrCb', 'GRAY', 'HLS', 'HSV':\r\n for spatial_size in (16, 32):\r\n for histbin in (16, 32, 64):\r\n car_features = extract_color_features(cars, spatial_color=spatial_color, spatial_size=(\r\n spatial_size, spatial_size), hist_color=hist_color, hist_bins=histbin, hist_range=(0, 256))\r\n notcar_features = extract_color_features(noncars, spatial_color=spatial_color, spatial_size=(\r\n spatial_size, spatial_size), hist_color=hist_color, hist_bins=histbin, hist_range=(0, 256))\r\n\r\n # Create an array stack of feature vectors\r\n X = np.vstack((car_features, notcar_features)).astype(np.float64)\r\n scaled_X, scaler = scale_norm(X)\r\n\r\n # Define the labels vector\r\n y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\r\n\r\n # Split up data into randomized training and test sets\r\n rand_state = np.random.randint(0, 100)\r\n X_train, X_test, y_train, y_test = train_test_split(\r\n scaled_X, y, test_size=0.2, random_state=rand_state)\r\n\r\n print('Using spatial color space of:', spatial_color, 'spatial binning of:', spatial_size,\r\n '\\nhistogram in color space of:', hist_color, 'and', histbin, 'histogram bins')\r\n\r\n svc = color_svc(X_train, y_train)\r\n\r\n # Check the score of the SVC\r\n print('Test Accuracy of SVC = ', round(\r\n svc.score(X_test, y_test), 4))\r\n # Check the prediction time for a single sample\r\n t = time.time()\r\n n_predict = 10\r\n print('My SVC predicts: ',\r\n svc.predict(X_test[0:n_predict]))\r\n print('For these', n_predict,\r\n 'labels: ', y_test[0:n_predict])\r\n t2 = time.time()\r\n print(round(t2 - t, 5), 'Seconds to predict',\r\n n_predict, 'labels with SVC')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n test_dir = \"train_images\"\r\n if len(sys.argv) == 1:\r\n print(\"use default dir:\", test_dir)\r\n else:\r\n test_dir = sys.argv.pop()\r\n\r\n try_color_parameters(test_dir)\r\n","sub_path":"color_classify.py","file_name":"color_classify.py","file_ext":"py","file_size_in_byte":3747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"344033629","text":"#!/usr/bin/python3\n\nimport subprocess, datetime, time\nfrom datetime import timedelta\nfrom decimal import *\nfrom influxdb import InfluxDBClient\nfrom flask import Flask, request, render_template, url_for, flash, redirect\n\nhost = ''\nport = '8086'\nuser = 'admin'\npassword = ''\ndbname = 'utilities_new'\n\napp = Flask(__name__)\n\ndef subtract_one_month(dt0):\n dt1 = dt0.replace(day=1)\n dt2 = dt1 - timedelta(days=1)\n dt3 = dt2.replace(day=1)\n return dt3\n\ndef get_enmax_floats(f1,f2,f3,f4,f5):\n try:\n getcontext().prec = 2\n n1 = float(f1)\n n2 = float(f2)\n n3 = float(f3)\n n4 = float(f4)\n n5 = float(f5)\n except ValueError:\n print(\"Input should be numbers. Try again.\")\n return 500\n else:\n return n1, n2, n3, n4, n5\n\ndef get_cui_floats(f1,f2,f3,f4,f5,f6,f7,f8,f9):\n try:\n n1 = float(f1)\n n2 = float(f2)\n n3 = float(f3)\n n4 = float(f4)\n n5 = float(f5)\n n6 = float(f6)\n n7 = float(f7)\n n8 = float(f8)\n n9 = float(f9)\n except ValueError:\n print(\"Input should be numbers. Try again.\")\n return 500\n else:\n return n1, n2, n3, n4, n5, n6, n7, n8, n9\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route(\"/\", methods=['POST'])\ndef index_post():\n provider = str(request.form['target'])\n\n if provider == 'Enmax':\n EnmaxEusage = request.form['Enmax.eusage']\n EnmaxNGusage = request.form['Enmax.ngusage']\n EnmaxEcost= request.form['Enmax.ecost']\n EnmaxNGcost = request.form['Enmax.ngcost']\n EnmaxTcost = request.form['Enmax.tcost']\n EnmaxYear = str(subtract_one_month(datetime.datetime.now()))\n EnmaxYear = int(EnmaxYear[0:4])\n\n try:\n EnmaxMonth = int(request.form['emonth'])\n except ValueError:\n print(\"Please select a month\")\n return 'Please select a month'\n\n dt = datetime.datetime(year=EnmaxYear, month=EnmaxMonth, day=15)\n EnmaxEpoch = int(time.mktime(dt.timetuple())) * int(1000000000)\n utilities_tuple = get_enmax_floats(EnmaxEusage, EnmaxNGusage, EnmaxEcost, EnmaxNGcost, EnmaxTcost)\n if utilities_tuple == 500:\n return 'Input should be numbers. Try again.'\n else:\n dbclient = InfluxDBClient(host, port, user, password, dbname)\n \n json_body = [\n {\n \"measurement\": \"utilities\",\n \"tags\": {\n \"vendor\": \"enmax\"\n },\n \"time\": EnmaxEpoch,\n \"fields\": {\n \"electricity_usage\": (utilities_tuple[0]),\n \"natural_gas_usage\": (utilities_tuple[1]),\n \"electrical_cost\": (utilities_tuple[2]),\n \"natural_gas_cost\": (utilities_tuple[3]),\n \"carbon_levy\": 0.0,\n \"total_cost\": (utilities_tuple[4]),\n }\n }\n ]\n \n dbclient.write_points(json_body)\n\n return 'OK'\n\n elif provider == 'CUI':\n CUIgarbage = request.form['CUI.garbage']\n CUIrecycle = request.form['CUI.recycle']\n CUIrstorm = request.form['CUI.rstorm']\n CUIrsewer = request.form['CUI.rsewer']\n CUIrwater = request.form['CUI.rwater']\n CUIwusage = request.form['CUI.wusage']\n CUIwcost = request.form['CUI.wcost']\n CUIscost = request.form['CUI.scost']\n CUItcost = request.form['CUI.tcost']\n CUIYear = str(subtract_one_month(datetime.datetime.now()))\n CUIYear = int(CUIYear[0:4])\n\n try:\n CUIMonth = int(request.form['cuimonth'])\n except ValueError:\n print(\"Please select a month\")\n return 'Please select a month'\n\n dt = datetime.datetime(year=CUIYear, month=CUIMonth, day=15)\n CUIEpoch = int(time.mktime(dt.timetuple())) * int(1000000000)\n utilities_tuple = get_cui_floats(CUIgarbage, CUIrecycle, CUIrstorm, CUIrsewer, CUIrwater, CUIwusage, CUIwcost, CUIscost, CUItcost)\n if utilities_tuple == 500:\n return 'Input should be numbers. Try again.'\n else:\n dbclient = InfluxDBClient(host, port, user, password, dbname)\n \n json_body = [\n {\n \"measurement\": \"utilities\",\n \"tags\": {\n \"vendor\": \"cui\"\n },\n \"time\": CUIEpoch,\n \"fields\": {\n \"garbage\": (utilities_tuple[0]),\n \"lifecycle\": 0.0,\n \"recycle_centre\": (utilities_tuple[1]),\n \"res_storm\": (utilities_tuple[2]),\n \"res_sewer\": (utilities_tuple[3]),\n \"res_water\": (utilities_tuple[4]),\n \"water_usage\": (utilities_tuple[5]),\n \"water_consume_charge\": (utilities_tuple[6]),\n \"sewer_consume_charge\": (utilities_tuple[7]),\n \"total_cost\": (utilities_tuple[8]),\n }\n }\n ]\n \n dbclient.write_points(json_body)\n\n return 'OK'\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=True, port=80)\n","sub_path":"utilities_app/docker/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"153237904","text":"from BinaryTree import *\n\nprint(\"\\n\\nBinaryTree:\\n\")\nr = BinaryTree()\nr1 = BinaryTree()\nr1.makeTree(1,None,None)\nr2 = BinaryTree()\nr2.makeTree(2,r1,None)\nr3 = BinaryTree()\nr3.makeTree(3,None,None)\nr4 = BinaryTree()\nr4.makeTree(4,r2,r3)\nr5 = BinaryTree()\nr5.makeTree(5,None,None)\nr6 = BinaryTree()\nr6.makeTree(6,None,None)\nr7 = BinaryTree()\nr7.makeTree(7,r5,r6)\nr.makeTree(8,r4,r7)\nprint('PreOrder')\nr.preOrder(r)\nprint('InOrder')\nr.inOrder(r)\nprint('PostOrder')\nr.postOrder(r)\nprint('levelOrder')\nr.levelOrder(r)\nprint('invertOrder')\nr.invertOrder(r)\n","sub_path":"test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"87957093","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n'''Risk2S'''\n# 纯文本文件 city.txt为城市信息, 里面的内容 内容写到 city.xls\nimport json,xlwt\nfile = \"city.txt\"\nwith open(file, \"r\") as f:\n data = f.read()\ndata_n = json.loads(data)\nprint(data_n)\nworkbook = xlwt.Workbook(encoding = 'ascii')\nworksheet = workbook.add_sheet('city')\nfor i in data_n:\n worksheet.write(int(i)-1, 0, label=i)\n worksheet.write(int(i) - 1, 1, label=data_n[i])\nworkbook.save(\"city.xls\")","sub_path":"15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"224681631","text":"# coding=utf-8\nfrom config import Config\nfrom qsonac.application import Application\nfrom qsonac.asynchttpserver import serve\n\napp = Application()\n\n\n@app.route(\"/\")\ndef hello(*args, **kwargs):\n request = kwargs.pop(\"request\")\n return str(request.headers)\n\n\n@app.route(\"/static/file\")\ndef file_provide_test(*args, **kwargs):\n return app.send_static_file(\"./static/testFile.htm\")\n\n\nserve(app, host=Config.host, port=Config.port)\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"633420648","text":"#!/usr/bin/env python\nfrom __future__ import unicode_literals\n\nimport logging\n\nfrom prompt_toolkit.application import AbortAction\nfrom prompt_toolkit.contrib.completers import WordCompleter\nfrom prompt_toolkit.contrib.telnet.application import TelnetApplication\nfrom prompt_toolkit.contrib.telnet.server import TelnetServer\nfrom prompt_toolkit.shortcuts import create_prompt_application\nfrom pygments.lexers import HtmlLexer\n\n# Set up logging\nlogging.basicConfig()\nlogging.getLogger().setLevel(logging.INFO)\n\n\nclass ExampleApplication(TelnetApplication):\n def client_connected(self, telnet_connection):\n # When a client is connected, erase the screen from the client and say\n # Hello.\n telnet_connection.erase_screen()\n telnet_connection.send('Welcome!\\n')\n\n # Set CommandLineInterface.\n animal_completer = WordCompleter(['alligator', 'ant'])\n telnet_connection.set_application(\n create_prompt_application(message='Say something: ',\n lexer=HtmlLexer,\n completer=animal_completer,\n on_abort=AbortAction.RETRY),\n self.handle_command)\n\n def handle_command(self, telnet_connection, document):\n # When the client enters a command, just reply.\n if document.text == 'exit':\n telnet_connection.close()\n else:\n telnet_connection.send('You said: %s\\n\\n' % document.text)\n\n def client_leaving(self, telnet_connection):\n # Say 'bye' when the client quits.\n telnet_connection.send('Bye.\\n')\n\n\nif __name__ == '__main__':\n TelnetServer(application=ExampleApplication(), port=2323).run()\n","sub_path":"ctf/atualizar/files/python-prompt-toolkit/examples/telnet.py","file_name":"telnet.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"259525431","text":"# -*- coding: utf-8 -*- {{{\n# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:\n\n# Copyright (c) 2015, Battelle Memorial Institute\n# 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\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. 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# 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 FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# The views and conclusions contained in the software and documentation\n# are those of the authors and should not be interpreted as representing\n# official policies, either expressed or implied, of the FreeBSD\n# Project.\n#\n# This material was prepared as an account of work sponsored by an\n# agency of the United States Government. Neither the United States\n# Government nor the United States Department of Energy, nor Battelle,\n# nor any of their employees, nor any jurisdiction or organization that\n# has cooperated in the development of these materials, makes any\n# warranty, express or implied, or assumes any legal liability or\n# responsibility for the accuracy, completeness, or usefulness or any\n# information, apparatus, product, software, or process disclosed, or\n# represents that its use would not infringe privately owned rights.\n#\n# Reference herein to any specific commercial product, process, or\n# service by trade name, trademark, manufacturer, or otherwise does not\n# necessarily constitute or imply its endorsement, recommendation, or\n# favoring by the United States Government or any agency thereof, or\n# Battelle Memorial Institute. The views and opinions of authors\n# expressed herein do not necessarily state or reflect those of the\n# United States Government or any agency thereof.\n#\n# PACIFIC NORTHWEST NATIONAL LABORATORY\n# operated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY\n# under Contract DE-AC05-76RL01830\n#}}}\n\n'''VOLTTRON platform™ agent event scheduling classes.'''\n\n\nimport heapq\nimport time as time_mod\n\n\nclass Event(object):\n '''Base class for schedulable objects.'''\n\n __slots__ = ['function', 'args', 'kwargs', 'canceled', 'finished']\n\n def __init__(self, function, args=None, kwargs=None):\n self.function = function\n self.args = args or []\n self.kwargs = kwargs or {}\n self.canceled = False\n self.finished = False\n\n def cancel(self):\n '''Mark the timer as canceled to avoid a callback.'''\n self.canceled = True\n\n def __call__(self, deadline):\n if not self.canceled:\n self.function(*self.args, **self.kwargs)\n self.finished = True\n \nclass EventWithTime(Event): \n '''Event that passes deadline to event handler.'''\n def __call__(self, deadline):\n if not self.canceled:\n self.function(deadline, *self.args, **self.kwargs)\n self.finished = True\n\n\nclass RecurringEvent(Event):\n __slots__ = ['period']\n\n def __init__(self, period, function, args=None, kwargs=None):\n super(RecurringEvent, self).__init__(function, args, kwargs)\n self.period = period\n\n def __call__(self, deadline):\n if not self.canceled:\n self.function(*self.args, **self.kwargs)\n if not self.canceled:\n return deadline + self.period\n self.finished = True\n\n\nclass Queue(object):\n def __init__(self):\n self._queue = []\n\n def schedule(self, time, event):\n heapq.heappush(self._queue, (time, event))\n\n def execute(self, time):\n if not self._queue:\n return\n deadline, callback = event = self._queue[0]\n if deadline > time:\n return\n assert heapq.heappop(self._queue) == event\n time = callback(deadline)\n if time is not None:\n if hasattr(time, 'timetuple'):\n time = time_mod.mktime(time.timetuple())\n heapq.heappush(self._queue, (time, callback))\n return True\n\n def delay(self, time):\n if not self._queue:\n return\n deadline, _ = self._queue[0]\n return deadline - time if deadline > time else 0\n\n def __nonzero__(self):\n return bool(self._queue)\n\n","sub_path":"volttron/platform/agent/sched.py","file_name":"sched.py","file_ext":"py","file_size_in_byte":5178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"481943215","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/customization/customization_properties_sheet.py\nfrom collections import namedtuple\nfrom itertools import islice\nfrom CurrentVehicle import g_currentVehicle\nfrom gui import DialogsInterface\nfrom gui.Scaleform.daapi.settings.views import VIEW_ALIAS\nfrom gui.Scaleform.daapi.view.dialogs import DIALOG_BUTTON_ID, PMConfirmationDialogMeta\nfrom gui.Scaleform.daapi.view.lobby.customization.shared import SCALE_SIZE\nfrom gui.Scaleform.daapi.view.meta.CustomizationPropertiesSheetMeta import CustomizationPropertiesSheetMeta\nfrom gui.Scaleform.daapi.view.lobby.customization.customization_inscription_controller import PersonalNumEditStatuses\nfrom gui.Scaleform.daapi.view.lobby.customization.shared import C11nTabs\nfrom gui.Scaleform.genConsts.CUSTOMIZATION_ALIASES import CUSTOMIZATION_ALIASES\nfrom gui.Scaleform.locale.RES_ICONS import RES_ICONS\nfrom gui.Scaleform.locale.VEHICLE_CUSTOMIZATION import VEHICLE_CUSTOMIZATION\nfrom gui.hangar_cameras.hangar_camera_common import CameraRelatedEvents\nfrom gui.shared import EVENT_BUS_SCOPE\nfrom gui.shared.formatters import text_styles\nfrom gui.shared.gui_items import GUI_ITEM_TYPE\nfrom helpers import dependency\nfrom skeletons.gui.customization import ICustomizationService\nfrom gui.shared.gui_items.customization.c11n_items import camoIconTemplate\nfrom skeletons.gui.shared import IItemsCache\nfrom gui import makeHtmlString\nfrom helpers.i18n import makeString as _ms\nfrom items.components.c11n_constants import SeasonType\nfrom gui.customization.shared import getAppliedRegionsForCurrentHangarVehicle, getCustomizationTankPartName, C11nId\nfrom gui.shared.gui_items.customization.outfit import Area\nfrom skeletons.gui.shared.utils import IHangarSpace\nfrom constants import CLIENT_COMMAND_SOURCES\nCustomizationCamoSwatchVO = namedtuple('CustomizationCamoSwatchVO', 'paletteIcon selected')\n_MAX_PALETTES = 3\n_PALETTE_TEXTURE = 'gui/maps/vehicles/camouflages/camo_palette_{colornum}.dds'\n_DEFAULT_COLORNUM = 1\n_PALETTE_BACKGROUND = 'gui/maps/vehicles/camouflages/camo_palettes_back.dds'\n_PALETTE_WIDTH = 42\n_PALETTE_HEIGHT = 42\n_C11nEditModes = {CUSTOMIZATION_ALIASES.CUSTOMIZATION_POJECTION_INTERACTION_DEFAULT: 0,\n CUSTOMIZATION_ALIASES.CUSTOMIZATION_POJECTION_INTERACTION_MOVE: 1,\n CUSTOMIZATION_ALIASES.CUSTOMIZATION_POJECTION_INTERACTION_SCALE: 2,\n CUSTOMIZATION_ALIASES.CUSTOMIZATION_POJECTION_INTERACTION_ROTATION: 3}\n_SEASONS_REMOVE_TEXT = {SeasonType.SUMMER: VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_SEASONS_SUMMER,\n SeasonType.WINTER: VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_SEASONS_WINTER,\n SeasonType.DESERT: VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_SEASONS_DESERT,\n SeasonType.SUMMER | SeasonType.WINTER: VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_SEASONS_SUMMER_WINTER,\n SeasonType.SUMMER | SeasonType.DESERT: VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_SEASONS_SUMMER_DESERT,\n SeasonType.WINTER | SeasonType.DESERT: VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_SEASONS_WINTER_DESERT}\n_APPLY_TO_OTHER_SEASONS_DIALOG = 'customization/applyProjectionDecalToOtherSeasons'\n\nclass CustomizationPropertiesSheet(CustomizationPropertiesSheetMeta):\n itemsCache = dependency.instance(IItemsCache)\n service = dependency.descriptor(ICustomizationService)\n _hangarSpace = dependency.descriptor(IHangarSpace)\n\n def __init__(self):\n super(CustomizationPropertiesSheet, self).__init__()\n self.__ctx = None\n self._slotID = -1\n self._regionID = -1\n self._areaID = -1\n self._isVisible = False\n self._editMode = False\n self._extraMoney = None\n self._isItemAppliedToAll = False\n self._showSwitchers = False\n self._isNarrowSlot = False\n self.__inscriptionController = None\n self.__interactionType = CUSTOMIZATION_ALIASES.CUSTOMIZATION_POJECTION_INTERACTION_DEFAULT\n self.__changes = [False] * 3\n return\n\n def _onRegisterFlashComponent(self, viewPy, alias):\n if alias == VIEW_ALIAS.CUSTOMIZATION_INSCRIPTION_CONTROLLER:\n self.__inscriptionController = viewPy\n\n @property\n def isVisible(self):\n return self._isVisible\n\n @property\n def attachedSlot(self):\n return C11nId(areaId=self._areaID, slotType=self._slotID, regionIdx=self._regionID)\n\n def editMode(self, value, interactionType):\n self._editMode = value\n if self._editMode:\n self.__interactionType = interactionType\n else:\n self.interactionStatusUpdate(False)\n self.__interactionType = -1\n\n def interactionStatusUpdate(self, value):\n self.fireEvent(CameraRelatedEvents(CameraRelatedEvents.FORCE_DISABLE_CAMERA_MOVEMENT, ctx={'disable': value}), EVENT_BUS_SCOPE.DEFAULT)\n\n def setScale(self, value):\n pass\n\n def setRotation(self, value):\n pass\n\n def registerInscriptionController(self, inscriptionController, inputLines):\n self.__ctx.vehicleAnchorsUpdater.registerInscriptionController(inscriptionController, inputLines)\n\n def _populate(self):\n super(CustomizationPropertiesSheet, self)._populate()\n self.__ctx = self.service.getCtx()\n self._extraMoney = None\n self._isItemAppliedToAll = False\n self.__ctx.onCacheResync += self.__onCacheResync\n self.__ctx.onCustomizationSeasonChanged += self.__onSeasonChanged\n self.__ctx.onCustomizationItemInstalled += self.__onItemsInstalled\n self.__ctx.onCustomizationItemsRemoved += self.__onItemsRemoved\n self.__ctx.onCamouflageColorChanged += self.__onCamouflageColorChanged\n self.__ctx.onCamouflageScaleChanged += self.__onCamouflageScaleChanged\n self.__ctx.onProjectionDecalScaleChanged += self.__onProjectionDecalScaleChanged\n self.__ctx.onProjectionDecalMirrored += self.__onProjectionDecalMirrored\n self.__ctx.onCustomizationItemsBought += self.__onItemsBought\n self.__ctx.onCustomizationItemSold += self.__onItemSold\n self.__ctx.onChangeAutoRent += self.onChangeAutoRent\n return\n\n def _dispose(self):\n self.__ctx.onCustomizationItemSold -= self.__onItemSold\n self.__ctx.onCustomizationItemsBought -= self.__onItemsBought\n self.__ctx.onCamouflageScaleChanged -= self.__onCamouflageScaleChanged\n self.__ctx.onCamouflageColorChanged -= self.__onCamouflageColorChanged\n self.__ctx.onProjectionDecalScaleChanged -= self.__onProjectionDecalScaleChanged\n self.__ctx.onProjectionDecalMirrored -= self.__onProjectionDecalMirrored\n self.__ctx.onCustomizationItemsRemoved -= self.__onItemsRemoved\n self.__ctx.onCustomizationItemInstalled -= self.__onItemsInstalled\n self.__ctx.onCustomizationSeasonChanged -= self.__onSeasonChanged\n self.__ctx.onCacheResync -= self.__onCacheResync\n self.__ctx.onChangeAutoRent -= self.onChangeAutoRent\n self._extraMoney = None\n self._isItemAppliedToAll = False\n self._slotID = -1\n self._regionID = -1\n self._areaID = -1\n self.__ctx = None\n self.__inscriptionController = None\n super(CustomizationPropertiesSheet, self)._dispose()\n return\n\n def show(self, areaID, slotID, regionID, showSwitchers, isNarrowSlot, forceUpdate=False):\n prevAnchor = C11nId(self._areaID, self._slotID, self._regionID)\n newAnchor = C11nId(areaID, slotID, regionID)\n self.__ctx.vehicleAnchorsUpdater.changeAnchorParams(prevAnchor, isDisplayed=True, isAutoScalable=True)\n self.__ctx.vehicleAnchorsUpdater.changeAnchorParams(newAnchor, isDisplayed=not showSwitchers, isAutoScalable=False)\n if self._slotID == slotID and self._regionID == regionID and self._areaID == areaID and self.isVisible and not forceUpdate:\n return\n self._slotID = slotID\n self._regionID = regionID\n self._areaID = areaID\n self._isVisible = True\n self._showSwitchers = showSwitchers\n self._isNarrowSlot = isNarrowSlot\n if self.__update():\n if self._currentItem and self._currentItem.itemTypeID == GUI_ITEM_TYPE.PERSONAL_NUMBER and self.__inscriptionController and (self._currentComponent.number == '' or self.__ctx.numberEditModeActive):\n self.__inscriptionController.show()\n elif self.__inscriptionController:\n self.__inscriptionController.hide()\n self.__ctx.onPropertySheetShown()\n self.__ctx.vehicleAnchorsUpdater.displayMenu(True)\n\n def hide(self, storePeronalNumber=False):\n anchor = C11nId(self._areaID, self._slotID, self._regionID)\n if not self.isVisible:\n return\n self._isVisible = False\n self.as_hideS()\n if self.__inscriptionController:\n self.__inscriptionController.hide()\n self.__ctx.onPropertySheetHidden()\n self.__ctx.vehicleAnchorsUpdater.changeAnchorParams(anchor, True, True)\n if not storePeronalNumber:\n self.__ctx.clearStoredPersonalNumber()\n\n def elementControlsHide(self):\n self.__ctx.vehicleAnchorsUpdater.displayMenu(False)\n\n def onActionBtnClick(self, actionType, actionData):\n if actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_APPLY_TO_ALL_PARTS:\n self._isItemAppliedToAll = not self._isItemAppliedToAll\n self.__applyToOtherAreas(self._isItemAppliedToAll)\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_APPLY_TO_ALL_SEASONS:\n self.__applyToOtherSeasons()\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_REMOVE_ONE:\n self.__removeElement()\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_RENT_CHECKBOX_CHANGE:\n self.__ctx.changeAutoRent(CLIENT_COMMAND_SOURCES.RENTED_STYLE_RADIAL_MENU)\n self.__update()\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_REMOVE_FROM_ALL_PARTS:\n self.__removeFromAllAreas()\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_SCALE_CHANGE:\n if self._slotID == GUI_ITEM_TYPE.CAMOUFLAGE:\n if self._currentComponent.patternSize != actionData:\n self.__ctx.changeCamouflageScale(self._areaID, self._regionID, actionData)\n elif self._slotID == GUI_ITEM_TYPE.PROJECTION_DECAL:\n actionData += 1\n if self._currentComponent.scaleFactorId != actionData:\n self.__ctx.changeProjectionDecalScale(self._areaID, self._regionID, actionData)\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_COLOR_CHANGE:\n if self._currentComponent.palette != actionData:\n self.__ctx.changeCamouflageColor(self._areaID, self._regionID, actionData)\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_CLOSE:\n self.hide()\n self.__ctx.onClearItem()\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_MIRROR:\n self.__ctx.mirrorProjectionDecal(self._areaID, self._regionID)\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_MOVE:\n self.__ctx.moveProjectionDecal(self._areaID, self._regionID, actionData)\n self.__update()\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_EDIT:\n self.hide(storePeronalNumber=True)\n self.__ctx.onPersonalNumberEditModeChanged(PersonalNumEditStatuses.EDIT_MODE_STARTED)\n elif actionType == CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_INFO:\n self.__ctx.onShowStyleInfo()\n\n def onClose(self):\n self.hide()\n\n @property\n def _currentSlotData(self):\n if self._slotID == -1 or self._areaID == -1 or self._slotID == GUI_ITEM_TYPE.STYLE:\n return\n else:\n slot = self.__ctx.currentOutfit.getContainer(self._areaID).slotFor(self._slotID)\n if slot is None or self._regionID == -1:\n return\n slotId = self.__ctx.getSlotIdByAnchorId(C11nId(self._areaID, self._slotID, self._regionID))\n return slot.getSlotData(slotId.regionIdx)\n\n @property\n def _currentItem(self):\n slotData = self._currentSlotData\n return None if slotData is None else slotData.item\n\n @property\n def _currentComponent(self):\n slotData = self._currentSlotData\n return None if slotData is None else slotData.component\n\n @property\n def _currentStyle(self):\n return self.__ctx.modifiedStyle if self._slotID == GUI_ITEM_TYPE.STYLE else None\n\n def __update(self):\n if self._isVisible and self._slotID != -1 and self._regionID != -1 and self._areaID != -1:\n self.__updateItemAppliedToAllFlag()\n self.__updateExtraPrice()\n if self._currentStyle or self._currentItem:\n self.as_setDataAndShowS(self.__makeVO())\n self.__ctx.caruselItemUnselected()\n self.__ctx.onPropertySheetShown()\n return True\n return False\n\n def __applyToOtherAreas(self, installItem):\n if self.__ctx.currentTab not in (C11nTabs.PAINT, C11nTabs.CAMOUFLAGE):\n return\n currentSeason = self.__ctx.currentSeason\n if installItem:\n self.__ctx.installItemToAllTankAreas(currentSeason, self._slotID, self._currentSlotData)\n else:\n self.__ctx.removeItemFromAllTankAreas(currentSeason, self._slotID)\n self.__update()\n\n def __removeFromAllAreas(self):\n currentSeason = self.__ctx.currentSeason\n self.__ctx.removeItemFromAllTankAreas(currentSeason, self._slotID)\n self.__update()\n\n def __applyToOtherSeasons(self):\n if self.__ctx.currentTab not in (C11nTabs.EFFECT,\n C11nTabs.EMBLEM,\n C11nTabs.INSCRIPTION,\n C11nTabs.PROJECTION_DECAL):\n return\n if not self._isItemAppliedToAll:\n if self.__ctx.currentTab == C11nTabs.PROJECTION_DECAL:\n lockedSeasons = self.__ctx.getLockedProjectionDecalSeasons(self._regionID)\n if lockedSeasons:\n self.__showApplyToOtherSeasonsDialog(lockedSeasons)\n return\n self.__ctx.installItemForAllSeasons(self._areaID, self._slotID, self._regionID, self._currentSlotData)\n self._isItemAppliedToAll = True\n else:\n self.__ctx.removeItemForAllSeasons(self._areaID, self._slotID, self._regionID)\n self._isItemAppliedToAll = False\n self.__update()\n\n def __showApplyToOtherSeasonsDialog(self, lockedSeasons):\n removedText = text_styles.alert(VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_SEASONS_REMOVED)\n seasonsString = self.__getLockedSeasonsString(lockedSeasons)\n if len(lockedSeasons) == 1:\n dialogMessage = _ms(VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_DIALOG_SEASON)\n else:\n dialogMessage = _ms(VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_DIALOG_SEASONS)\n message = makeHtmlString('html_templates:lobby/customization/dialog', 'decal', {'value': _ms(dialogMessage, season=seasonsString.decode('utf-8').upper(), removed=removedText.decode('utf-8').upper())})\n DialogsInterface.showDialog(PMConfirmationDialogMeta(_APPLY_TO_OTHER_SEASONS_DIALOG, messageCtx={'message': message,\n 'icon': RES_ICONS.MAPS_ICONS_LIBRARY_ICON_ALERT_90X84}, focusedID=DIALOG_BUTTON_ID.CLOSE), self.__installProjectionDecalToAllSeasonsDialogCallback)\n\n def __installProjectionDecalToAllSeasonsDialogCallback(self, confirmed):\n if not confirmed:\n return\n lockedSeasons = self.__ctx.getLockedProjectionDecalSeasons(self._regionID)\n projectionDecalsFilter = lambda item: item.itemTypeID == GUI_ITEM_TYPE.PROJECTION_DECAL\n for season in lockedSeasons:\n outfit = self.__ctx.getModifiedOutfit(season)\n self.__ctx.removeItemsFromOutfit(outfit, projectionDecalsFilter, refresh=False)\n\n self.__ctx.installItemForAllSeasons(self._areaID, self._slotID, self._regionID, self._currentSlotData)\n self._isItemAppliedToAll = True\n\n def __removeElement(self):\n if self._slotID == GUI_ITEM_TYPE.STYLE:\n self.__ctx.removeStyle(self._currentStyle.intCD)\n else:\n slotId = self.__ctx.getSlotIdByAnchorId(C11nId(areaId=self._areaID, slotType=self._slotID, regionIdx=self._regionID))\n if slotId is not None:\n self.__ctx.removeItemFromSlot(self.__ctx.currentSeason, slotId)\n return\n\n def __updateItemAppliedToAllFlag(self):\n self._isItemAppliedToAll = False\n if self.__ctx.currentTab in (C11nTabs.PAINT, C11nTabs.CAMOUFLAGE):\n self._isItemAppliedToAll = True\n for areaId in Area.TANK_PARTS:\n regionsIndexes = getAppliedRegionsForCurrentHangarVehicle(areaId, self._slotID)\n multiSlot = self.__ctx.currentOutfit.getContainer(areaId).slotFor(self._slotID)\n for regionIdx in regionsIndexes:\n slotData = multiSlot.getSlotData(regionIdx)\n df = self._currentSlotData.weakDiff(slotData)\n if slotData.item is None or df.item is not None:\n break\n else:\n continue\n\n self._isItemAppliedToAll = False\n break\n\n elif self.__ctx.currentTab in (C11nTabs.EFFECT,\n C11nTabs.EMBLEM,\n C11nTabs.INSCRIPTION,\n C11nTabs.PROJECTION_DECAL):\n self._isItemAppliedToAll = True\n firstSeason = SeasonType.COMMON_SEASONS[0]\n firstSlotId = self.__ctx.getSlotIdByAnchorId(self.attachedSlot, firstSeason)\n if firstSlotId is None:\n self._isItemAppliedToAll = False\n return\n fistSlotData = self.__ctx.getModifiedOutfit(firstSeason).getContainer(firstSlotId.areaId).slotFor(firstSlotId.slotType).getSlotData(firstSlotId.regionIdx)\n if fistSlotData.item is not None:\n for season in SeasonType.COMMON_SEASONS[1:]:\n slotId = self.__ctx.getSlotIdByAnchorId(self.attachedSlot, season)\n if slotId is None:\n self._isItemAppliedToAll = False\n break\n slotData = self.__ctx.getModifiedOutfit(season).getContainer(slotId.areaId).slotFor(slotId.slotType).getSlotData(slotId.regionIdx)\n df = fistSlotData.weakDiff(slotData)\n if slotData.item is None or df.item is not None:\n self._isItemAppliedToAll = False\n break\n\n else:\n self._isItemAppliedToAll = False\n return\n\n def __makeVO(self):\n currentElement = self._currentStyle if self._slotID == GUI_ITEM_TYPE.STYLE else self._currentItem\n isPersonalNumberEdit = self.__ctx.numberEditModeActive\n vo = {'renderersData': self.__makeRenderersVOs() if currentElement and not isPersonalNumberEdit else [],\n 'isProjectionEnable': self._slotID == GUI_ITEM_TYPE.PROJECTION_DECAL,\n 'isBigRadius': self._slotID in (GUI_ITEM_TYPE.INSCRIPTION, GUI_ITEM_TYPE.PROJECTION_DECAL, GUI_ITEM_TYPE.EMBLEM),\n 'showSwitchers': self._showSwitchers and not isPersonalNumberEdit,\n 'isNarrowSlot': self._isNarrowSlot}\n return vo\n\n def __makeSlotVO(self):\n vo = None\n if not self._currentItem:\n vo = {'imgIconSrc': RES_ICONS.MAPS_ICONS_LIBRARY_TANKITEM_BUY_TANK_POPOVER_SMALL}\n return vo\n\n def __makeRenderersVOs(self):\n renderers = []\n if self._slotID == GUI_ITEM_TYPE.PAINT:\n renderers.append(self.__makeSetOnOtherTankPartsRendererVO())\n elif self._slotID == GUI_ITEM_TYPE.CAMOUFLAGE:\n renderers.append(self.__makeCamoColorRendererVO())\n renderers.append(self.__makeScaleRendererVO())\n renderers.append(self.__makeSetOnOtherTankPartsRendererVO())\n elif self._slotID in (GUI_ITEM_TYPE.EMBLEM, GUI_ITEM_TYPE.INSCRIPTION, GUI_ITEM_TYPE.MODIFICATION):\n if self._currentItem.itemTypeID == GUI_ITEM_TYPE.PERSONAL_NUMBER:\n renderers.append(self.__makeEditInscriptionRendererVO())\n renderers.append(self.__makeSetOnOtherSeasonsRendererVO())\n elif self._slotID == GUI_ITEM_TYPE.STYLE:\n isExtentionEnabled = self._currentStyle and self._currentStyle.isRentable\n if isExtentionEnabled:\n renderers.append(self.__makeExtensionRendererVO())\n elif self._slotID == GUI_ITEM_TYPE.PROJECTION_DECAL:\n renderers.append(self.__makeMirorRendererVO())\n renderers.append(self.__makeScaleRendererVO())\n renderers.append(self.__makeMoveRendererVO())\n renderers.append(self.__makeSetOnOtherSeasonsRendererVO())\n renderers.append(self.__makeRemoveRendererVO())\n renderers.append(self.__makeCloseeRendererVO())\n return renderers\n\n def __updateExtraPrice(self):\n if self._isItemAppliedToAll and self._currentItem:\n appliedIems = tuple((it for it in self.__ctx.getPurchaseItems() if not it.isDismantling and it.item.intCD == self._currentItem.intCD))\n if self.__ctx.currentTab in (C11nTabs.PAINT, C11nTabs.CAMOUFLAGE):\n appliedIems = tuple((it for it in appliedIems if it.group == self.__ctx.currentSeason))\n outfit = self.__ctx.originalOutfit\n slotData = outfit.getContainer(self._areaID).slotFor(self._slotID).getSlotData(self._regionID)\n isCurrentlyApplied = slotData.item == self._currentItem\n itemCache = self.itemsCache.items.getItemByCD(self._currentItem.intCD)\n inventoryCount = itemCache.inventoryCount\n appliedItemPrice = itemCache.getBuyPrice()\n extraInventoryCount = max(0, len(appliedIems) - max(inventoryCount, int(not isCurrentlyApplied)))\n self._extraMoney = appliedItemPrice.price * extraInventoryCount\n else:\n self._extraMoney = None\n return\n\n def __makeSetOnOtherTankPartsRendererVO(self):\n icon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_FULL_TANK\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_FULL_TANK_HOVER\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_APPLYTOWHOLETANK\n disableTooltip = _ms(VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_APPLYTOWHOLETANKDISABLED, itemType=_ms('#vehicle_customization:propertySheet/actionBtn/forCurrentItem/' + self._currentItem.itemTypeName))\n enabled = True\n if self._isItemAppliedToAll:\n icon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_DEL_TANK\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_DEL_TANK_HOVER\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_CANCEL\n else:\n enabled = self.__ctx.isPossibleToInstallToAllTankAreas(self.__ctx.currentSeason, self._slotID, self._currentSlotData)\n return {'iconSrc': icon,\n 'iconHoverSrc': hoverIcon,\n 'iconDisableSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_DISABLE_ICON_FULL_TANK_DISABLE,\n 'actionBtnLabel': actionBtnLabel,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_APPLY_TO_ALL_PARTS,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_BTN_RENDERER_UI,\n 'animatedTransition': True,\n 'disableTooltip': disableTooltip,\n 'enabled': enabled}\n\n def __makeMirorRendererVO(self):\n if self._slotID not in (GUI_ITEM_TYPE.PROJECTION_DECAL,):\n return {'iconSrc': '',\n 'iconHoverSrc': '',\n 'iconDisableSrc': '',\n 'actionBtnLabel': '',\n 'actionType': '',\n 'rendererLnk': '',\n 'enabled': False}\n isMirrorOn = self._currentItem.canBeMirrored\n alreadyMirrored = self._currentComponent.isMirrored()\n icon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_MIRROR_01_NORMAL\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_MIRROR_01_HOVER\n if alreadyMirrored:\n icon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_MIRROR_02_NORMAL\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_MIRROR_02_HOVER\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_MIRROR\n return {'iconSrc': icon,\n 'iconHoverSrc': hoverIcon,\n 'iconDisableSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_DISABLE_ICON_MIRROR_01_DISABLED,\n 'actionBtnLabel': actionBtnLabel,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_MIRROR,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_BTN_RENDERER_UI,\n 'disableTooltip': VEHICLE_CUSTOMIZATION.CUSTOMIZATION_PROPERTYSHEET_DISABLED_MIRROR,\n 'enabled': isMirrorOn}\n\n def __makeMoveRendererVO(self):\n anchor = g_currentVehicle.item.getAnchorById(self._currentComponent.slotId)\n parent = anchor if anchor.isParent else g_currentVehicle.item.getAnchorById(anchor.parentSlotId)\n availableAnchors = parent.getChilds(self._currentItem.formfactor)\n currentIdx = availableAnchors.index(anchor.slotId)\n actionBtnLabel = _ms(VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_MOVE, current=str(currentIdx + 1), total=str(len(availableAnchors)))\n return {'actionBtnLabel': actionBtnLabel,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_MOVE,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_SWITCH_RENDERER_UI,\n 'disableTooltip': VEHICLE_CUSTOMIZATION.CUSTOMIZATION_PROPERTYSHEET_DISABLED_MOVE,\n 'buttonMode': True,\n 'enabled': len(availableAnchors) > 1}\n\n def __makeRemoveRendererVO(self):\n iconSrc = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_STYLE_X\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_STYLE_X_HOVER\n if self._slotID == GUI_ITEM_TYPE.MODIFICATION:\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_REMOVE_TANK\n iconSrc = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_DEL_TANK\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_DEL_TANK_HOVER\n elif self._slotID == GUI_ITEM_TYPE.EMBLEM:\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_REMOVE_EMBLEM\n iconSrc = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_EMBLEM_X\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_EMBLEM_X_HOVER\n elif self._slotID == GUI_ITEM_TYPE.INSCRIPTION:\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_REMOVE_INSCRIPTION\n iconSrc = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_TYPE_X\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_TYPE_X_HOVER\n elif self._slotID == GUI_ITEM_TYPE.PROJECTION_DECAL:\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_REMOVE_PROJECTIONDECAL\n iconSrc = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_DECAL_X_HOVER\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_DECAL_X_NORMAL\n elif self._slotID == GUI_ITEM_TYPE.STYLE:\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_REMOVESTYLE\n else:\n actionBtnLabel = VEHICLE_CUSTOMIZATION.getSheetBtnRemoveText(getCustomizationTankPartName(self._areaID, self._regionID))\n if self._slotID == GUI_ITEM_TYPE.CAMOUFLAGE:\n iconSrc = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_CAMO_X\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_CAMO_X_HOVER\n elif self._slotID == GUI_ITEM_TYPE.PAINT:\n iconSrc = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_COLORS_X\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_COLORS_X_HOVER\n return {'iconSrc': iconSrc,\n 'iconHoverSrc': hoverIcon,\n 'actionBtnLabel': actionBtnLabel,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_BTN_RENDERER_UI,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_REMOVE_ONE,\n 'animatedTransition': True,\n 'enabled': True}\n\n def __makeCloseeRendererVO(self):\n iconSrc = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_CLOSE\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_CLOSE_HOVER\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_CLOSE\n return {'iconSrc': iconSrc,\n 'iconHoverSrc': hoverIcon,\n 'actionBtnLabel': actionBtnLabel,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_BTN_RENDERER_UI,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_CLOSE,\n 'enabled': True}\n\n def __makeStyleInfoRendererVO(self):\n enabled = True\n return {'iconSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_INFO,\n 'iconHoverSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_INFO_HOVER,\n 'iconDisableSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_DISABLE_ICON_INFO_DISABLE,\n 'actionBtnLabel': VEHICLE_CUSTOMIZATION.CUSTOMIZATION_POPOVER_STYLE_INFO,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_BTN_RENDERER_UI,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_INFO,\n 'enabled': enabled}\n\n def __makeExtensionRendererVO(self):\n if self.__ctx.autoRentEnabled():\n icon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_DEL_RENT\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_DEL_RENT_HOVER\n label = VEHICLE_CUSTOMIZATION.CUSTOMIZATION_POPOVER_STYLE_NOTAUTOPROLONGATIONLABEL\n else:\n icon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_RENTAL\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_RENTAL_HOVER\n label = VEHICLE_CUSTOMIZATION.CUSTOMIZATION_POPOVER_STYLE_AUTOPROLONGATIONLABEL\n return {'iconSrc': icon,\n 'iconHoverSrc': hoverIcon,\n 'iconDisableSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_DISABLE_ICON_RENTAL_DISABLE,\n 'actionBtnLabel': label,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_RENT_CHECKBOX_CHANGE,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_BTN_RENDERER_UI,\n 'animatedTransition': True,\n 'enabled': True}\n\n def __makeCamoColorRendererVO(self):\n btnsBlockVO = []\n colornum = _DEFAULT_COLORNUM\n for palette in self._currentItem.palettes:\n colornum = max(colornum, sum(((color >> 24) / 255.0 > 0 for color in palette)))\n\n for idx, palette in enumerate(islice(self._currentItem.palettes, _MAX_PALETTES)):\n texture = _PALETTE_TEXTURE.format(colornum=colornum)\n icon = camoIconTemplate(texture, _PALETTE_WIDTH, _PALETTE_HEIGHT, palette, background=_PALETTE_BACKGROUND)\n btnsBlockVO.append(CustomizationCamoSwatchVO(icon, idx == self._currentComponent.palette)._asdict())\n\n return {'iconSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_PALETTE,\n 'iconHoverSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_PALETTE_HOVER,\n 'iconDisableSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_DISABLE_ICON_PALETTE_DISABLE,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_COLOR_CHANGE,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_SCALE_COLOR_RENDERER_UI,\n 'btnsBlockVO': btnsBlockVO,\n 'disableTooltip': VEHICLE_CUSTOMIZATION.CUSTOMIZATION_PROPERTYSHEET_DISABLED_COLOR,\n 'enabled': len(btnsBlockVO) == _MAX_PALETTES}\n\n def __makeScaleRendererVO(self):\n btnsBlockVO = []\n if self._slotID == GUI_ITEM_TYPE.CAMOUFLAGE:\n selected = self._currentComponent.patternSize\n elif self._slotID == GUI_ITEM_TYPE.PROJECTION_DECAL:\n selected = self._currentComponent.scaleFactorId - 1\n else:\n return {'iconSrc': '',\n 'iconHoverSrc': '',\n 'iconDisableSrc': '',\n 'actionType': '',\n 'rendererLnk': '',\n 'btnsBlockVO': '',\n 'enabled': False}\n for idx, scaleSizeLabel in enumerate(SCALE_SIZE):\n btnsBlockVO.append({'paletteIcon': '',\n 'label': scaleSizeLabel,\n 'selected': selected == idx,\n 'value': idx})\n\n return {'iconSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_SCALE,\n 'iconHoverSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_SCALE_HOVER,\n 'iconDisableSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_DISABLE_ICON_SCALE_DISABLE,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_SCALE_CHANGE,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_SCALE_COLOR_RENDERER_UI,\n 'btnsBlockVO': btnsBlockVO,\n 'enabled': True}\n\n def __makeSetOnOtherSeasonsRendererVO(self):\n icon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_SEASON\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_SEASON_HOVER\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_APPLYTOALLMAPS\n notifyString = ''\n enabled = True\n needNotify = False\n disableTooltip = _ms(VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_APPLYTOALLMAPSDISABLED, itemType=_ms('#vehicle_customization:propertySheet/actionBtn/forCurrentItem/' + self._currentItem.itemTypeName))\n if self._isItemAppliedToAll:\n actionBtnLabel = VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_REMOVE_SEASONS\n icon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_DEL_ALL_SEASON\n hoverIcon = RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_REMOVE_ICON_SEASON_X_HOVER\n else:\n enabled = self.__ctx.isPossibleToInstallItemForAllSeasons(self._areaID, self._slotID, self._regionID, self._currentSlotData)\n if self._slotID == GUI_ITEM_TYPE.MODIFICATION:\n disableTooltip = VEHICLE_CUSTOMIZATION.CUSTOMIZATION_PROPERTYSHEET_DISABLED_SEASONEFFECT\n elif self._slotID == GUI_ITEM_TYPE.EMBLEM:\n disableTooltip = VEHICLE_CUSTOMIZATION.CUSTOMIZATION_PROPERTYSHEET_DISABLED_SEASONEMBLEM\n elif self._slotID == GUI_ITEM_TYPE.INSCRIPTION:\n disableTooltip = VEHICLE_CUSTOMIZATION.CUSTOMIZATION_PROPERTYSHEET_DISABLED_SEASONINSCRIPTION\n elif self._slotID == GUI_ITEM_TYPE.PROJECTION_DECAL:\n disableTooltip = VEHICLE_CUSTOMIZATION.CUSTOMIZATION_PROPERTYSHEET_DISABLED_SEASONDECAL\n lockedSeasons = self.__ctx.getLockedProjectionDecalSeasons(self._regionID)\n if lockedSeasons:\n needNotify = True\n notifyString = self.__makeProjectionDecalInstallToOtherSeasonsNotifyString(lockedSeasons)\n return {'iconSrc': icon,\n 'iconHoverSrc': hoverIcon,\n 'iconDisableSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_DISABLE_ICON_SEASON_DISABLE,\n 'actionBtnLabel': actionBtnLabel,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_APPLY_TO_ALL_SEASONS,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_BTN_RENDERER_UI,\n 'animatedTransition': True,\n 'disableTooltip': disableTooltip,\n 'notifyText': notifyString,\n 'needNotify': needNotify,\n 'enabled': enabled}\n\n def __makeProjectionDecalInstallToOtherSeasonsNotifyString(self, lockedSeasons):\n removedText = text_styles.alert(VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_SEASONS_REMOVED)\n seasonsText = self.__getLockedSeasonsString(lockedSeasons)\n if len(lockedSeasons) == 1:\n tooltipText = _ms(VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_TOOLTIP_SEASON)\n else:\n tooltipText = _ms(VEHICLE_CUSTOMIZATION.PROPERTYSHEET_NOTIFY_DECAL_TOOLTIP_SEASONS)\n notifyString = makeHtmlString('html_templates:lobby/customization/notify', 'decal', {'value': _ms(tooltipText, season=seasonsText, removed=removedText)})\n return notifyString\n\n def __getLockedSeasonsString(self, lockedSeasons):\n seasonsMask = SeasonType.UNDEFINED\n for season in lockedSeasons:\n seasonsMask |= season\n\n seasonsString = text_styles.alert(_SEASONS_REMOVE_TEXT.get(seasonsMask, ''))\n return seasonsString\n\n def __makeEditInscriptionRendererVO(self):\n return {'iconSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_EDIT,\n 'iconHoverSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_IDLE_ICON_EDIT_HOVER,\n 'iconDisableSrc': RES_ICONS.MAPS_ICONS_CUSTOMIZATION_PROPERTY_SHEET_DISABLE_ICON_EDIT_DISABLE,\n 'actionBtnLabel': VEHICLE_CUSTOMIZATION.PROPERTYSHEET_ACTIONBTN_EDIT_INSCRIPTION,\n 'actionType': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_ACTION_EDIT,\n 'rendererLnk': CUSTOMIZATION_ALIASES.CUSTOMIZATION_SHEET_BTN_RENDERER_UI,\n 'animatedTransition': True,\n 'enabled': True}\n\n def __onCacheResync(self, *_):\n if not g_currentVehicle.isPresent():\n self.hide()\n return\n self.__update()\n\n def __onSeasonChanged(self, seasonType):\n self.hide()\n\n def __onCamouflageColorChanged(self, areaId, regionIdx, paletteIdx):\n self.__update()\n\n def __onCamouflageScaleChanged(self, areaId, regionIdx, scale):\n self.__update()\n\n def __onProjectionDecalScaleChanged(self, areaId, regionIdx, scale):\n self.__update()\n\n def __onProjectionDecalMirrored(self, areaId, regionIdx):\n self.__update()\n\n def __onItemsInstalled(self, *args):\n self.__update()\n\n def __onItemsRemoved(self):\n self.hide()\n\n def __onItemsBought(self, purchaseItems, results):\n self.__update()\n\n def __onItemSold(self, item, count):\n self.__update()\n\n def onChangeAutoRent(self):\n self.__update()\n","sub_path":"source/res/scripts/client/gui/Scaleform/daapi/view/lobby/customization/customization_properties_sheet.py","file_name":"customization_properties_sheet.py","file_ext":"py","file_size_in_byte":38823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"408886098","text":"from sys import stdin\n\ndef puntos(n):\n if n>1:\n x = puntos(n-1)+(3*n)-2\n print(x)\n return x\n else:\n print(1)\n return 1\ndef main():\n a = int(stdin.readline())\n puntos(a)\nmain()\n","sub_path":"ejercicios/Math/puntos.py","file_name":"puntos.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"360618178","text":"from datetime import datetime, timedelta\n\nimport pytest\nfrom django.utils import timezone\n\nfrom vehicles.factories import LocationFactory, VehicleFactory\nfrom vehicles.models import EventType, Location\nfrom vehicles.tests.utils import get_detail, get_list, get_location_data_from_obj, TWO_YEARS_IN_SECONDS\n\n\n@pytest.fixture(autouse=True)\ndef default_settings(settings):\n settings.STREET_MAINTENANCE_DELAY = None\n\n\n@pytest.fixture\ndef vehicle():\n return VehicleFactory.create()\n\n\n@pytest.fixture\ndef locations_for_vehicle(vehicle):\n locations = LocationFactory.create_batch(10, vehicle=vehicle)\n\n for location in locations:\n location.events.add(EventType.objects.get(identifier='au'))\n location.events.add(EventType.objects.get(identifier='hi'))\n\n\ndef test_list_and_detail_endpoint(vehicle, locations_for_vehicle):\n last_location = Location.objects.last()\n last_location.events.add(EventType.objects.get(identifier='au'))\n last_location.events.add(EventType.objects.get(identifier='hi'))\n\n expected_data = {\n 'location_history': [],\n 'id': vehicle.id,\n 'last_location': get_location_data_from_obj(last_location)\n }\n\n list_data = get_list()\n assert list_data == [expected_data]\n\n detail_data = get_detail(vehicle)\n assert detail_data == expected_data\n\n\ndef test_location_history(vehicle, locations_for_vehicle):\n data = get_detail(vehicle, {'history': 3})\n assert len(data['location_history']) == 3\n\n locations = vehicle.locations.order_by('-timestamp')\n history = data['location_history']\n\n last_obj = locations[0]\n assert history[2] == get_location_data_from_obj(last_obj)\n\n second_last_obj = locations[1]\n assert history[1] == get_location_data_from_obj(second_last_obj)\n\n\ndef test_cannot_get_location_history_in_list(locations_for_vehicle):\n data = get_list({'history': 3})\n assert data[0]['location_history'] == []\n\n\ndef test_limit():\n vehicles = VehicleFactory.create_batch(3)\n ids = [vehicle.id for vehicle in vehicles]\n\n # create location timestamps sequentially for the vehicles\n base_datetime = timezone.make_aware(datetime(2000, 2, 18, 10, 00))\n for i, vehicle in enumerate(vehicles):\n LocationFactory.create(vehicle=vehicle, timestamp=base_datetime + timedelta(seconds=10 * i))\n\n data = get_list({'limit': 2})\n assert {location['id'] for location in data} == {ids[2], ids[1]} # second last and last\n\n data = get_list({'limit': 1})\n assert {location['id'] for location in data} == {ids[2]} # only last\n\n\ndef test_default_limit():\n LocationFactory.create_batch(15)\n data = get_list()\n assert len(data) == 10\n\n\ndef test_since_in_list():\n old_vehicles = VehicleFactory.create_batch(3)\n\n for vehicle in old_vehicles:\n LocationFactory.create(vehicle=vehicle, year=2000)\n\n new_vehicles = VehicleFactory.create_batch(3)\n new_ids = [vehicle.id for vehicle in new_vehicles]\n\n for vehicle in new_vehicles:\n LocationFactory.create(vehicle=vehicle, year=timezone.now().year - 1)\n\n data = get_list({'since': '2years ago'})\n assert {location['id'] for location in data} == set(new_ids)\n\n\ndef test_since_in_detail(vehicle):\n LocationFactory.create_batch(4, vehicle=vehicle, year=2000)\n LocationFactory.create_batch(7, vehicle=vehicle, year=timezone.now().year - 1)\n\n data = get_detail(vehicle, {'since': '2years ago'})\n assert len(data['location_history']) == 7\n\n\ndef test_temporal_resolution(vehicle):\n for i in range(10):\n base_datetime = timezone.make_aware(datetime(2000, 2, 18, 10, 00))\n LocationFactory.create(vehicle=vehicle, timestamp=base_datetime + timedelta(seconds=i))\n\n data = get_detail(vehicle, {'history': 10, 'temporal_resolution': 2})\n assert len(data['location_history']) == 5\n\n\ndef test_delay_in_list(settings):\n settings.STREET_MAINTENANCE_DELAY = TWO_YEARS_IN_SECONDS\n\n vehicle_from_2000 = VehicleFactory.create()\n LocationFactory.create_batch(4, vehicle=vehicle_from_2000, year=2000)\n vehicle_from_2000.update_last_location()\n\n vehicle_from_last_year = VehicleFactory.create()\n LocationFactory.create_batch(7, vehicle=vehicle_from_last_year, year=timezone.now().year - 1)\n vehicle_from_last_year.update_last_location()\n\n data = get_list()\n assert {vehicle['id'] for vehicle in data} == {vehicle_from_2000.id}\n\n\ndef test_delay_in_detail(vehicle, settings):\n settings.STREET_MAINTENANCE_DELAY = TWO_YEARS_IN_SECONDS\n\n LocationFactory.create_batch(4, vehicle=vehicle, year=2000)\n LocationFactory.create_batch(7, vehicle=vehicle, year=timezone.now().year - 1)\n vehicle.update_last_location()\n\n data = get_detail(vehicle, {'history': 100})\n assert len(data['location_history']) == 4\n","sub_path":"vehicles/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":4759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"136486442","text":"from __future__ import division\n\n'''\nAuthor : Lyubimov, A.Y.\nCreated : 05/01/2016\nLast Changed: 10/21/2018\nDescription : PRIME GUI Initialization module\n'''\n\nimport os\nimport wx\n\nfrom libtbx import easy_run\nimport iotbx.phil as ip\n\nfrom iota import prime_description, prime_license\nfrom iota.components.iota_utils import Capturing\nfrom iota.components.iota_ui_base import IOTABaseFrame\nimport iota.components.iota_ui_controls as ct\nfrom prime.postrefine import mod_gui_frames as frm\nfrom prime.postrefine import mod_gui_dialogs as dlg\nfrom prime.postrefine.mod_input import master_phil\n\n# Platform-specific stuff\n# TODO: Will need to test this on Windows at some point\nif wx.Platform == '__WXGTK__':\n norm_font_size = 10\n button_font_size = 12\n LABEL_SIZE = 14\n CAPTION_SIZE = 12\n python = 'python'\nelif wx.Platform == '__WXMAC__':\n norm_font_size = 12\n button_font_size = 14\n LABEL_SIZE = 14\n CAPTION_SIZE = 12\n python = \"Python\"\nelif (wx.Platform == '__WXMSW__'):\n norm_font_size = 9\n button_font_size = 11\n LABEL_SIZE = 11\n CAPTION_SIZE = 9\n\nuser = os.getlogin()\nicons = os.path.join(os.path.dirname(os.path.abspath(ct.__file__)), 'icons/')\n\ndef str_split(string, delimiters=(' ', ','), maxsplit=0):\n import re\n rexp = '|'.join(map(re.escape, delimiters))\n return re.split(rexp, string, maxsplit)\n\n# ------------------------------ PRIME Windows ------------------------------- #\n\nclass PRIMEWindow(IOTABaseFrame):\n\n def __init__(self, parent, id, title, prefix='prime'):\n IOTABaseFrame.__init__(self, parent, id, title, size=(800, 500))\n\n self.prime_filename = '{}.phil'.format(prefix)\n self.prime_phil = master_phil\n\n # Toolbar\n self.initialize_toolbar()\n self.tb_btn_quit = self.add_tool(label='Quit',\n bitmap=('actions', 'exit'),\n shortHelp='Exit PRIME')\n\n self.tb_btn_prefs = self.add_tool(label='Preferences',\n bitmap=('apps', 'advancedsettings'),\n shortHelp='PRIME GUI Settings')\n self.add_toolbar_separator()\n self.tb_btn_load = self.add_tool(label='Load Script',\n bitmap=('actions', 'open'),\n shortHelp='Load PRIME Script')\n self.tb_btn_save = self.add_tool(label='Save Script',\n bitmap=('actions', 'save'),\n shortHelp='Save PRIME Script')\n self.tb_btn_reset = self.add_tool(label='Reset',\n bitmap=('actions', 'reload'),\n shortHelp='Reset Settings')\n self.toolbar.AddSeparator()\n self.tb_btn_analysis = self.add_tool(label='Recover',\n bitmap=(\n 'mimetypes', 'text-x-generic-2'),\n shortHelp='Recover PRIME run')\n self.tb_btn_run = self.add_tool(label='Run',\n bitmap=('actions', 'run'),\n shortHelp='Run PRIME')\n # These buttons will be disabled until input path is provided\n self.set_tool_state(self.tb_btn_run, enable=False)\n self.realize_toolbar()\n\n # Status bar\n self.sb = self.CreateStatusBar()\n self.sb.SetFieldsCount(3)\n self.sb.SetStatusWidths([320, 200, -2])\n\n # Menu bar\n menubar = wx.MenuBar()\n m_help = wx.Menu()\n m_file = wx.Menu()\n self.mb_load_script = m_file.Append(wx.ID_OPEN, '&Load Script...')\n self.mb_save_script = m_file.Append(wx.ID_SAVE, '&Save Script...')\n self.mb_about = m_help.Append(wx.ID_ANY, '&About')\n menubar.Append(m_file, '&File')\n menubar.Append(m_help, '&Help')\n self.SetMenuBar(menubar)\n\n # Place elements in main PRIME window\n main_box = wx.BoxSizer(wx.VERTICAL)\n\n # Instantiate windows\n self.input_window = frm.PRIMEInputWindow(self, phil=self.prime_phil)\n\n # Single input window\n main_box.Add(self.input_window, 1, flag=wx.ALL | wx.EXPAND, border=10)\n main_box.Add((-1, 20))\n\n # Menubar button bindings\n self.Bind(wx.EVT_MENU, self.OnAboutBox, self.mb_about)\n self.Bind(wx.EVT_MENU, self.onSaveScript, self.mb_save_script)\n self.Bind(wx.EVT_MENU, self.onLoadScript, self.mb_load_script)\n\n # Toolbar button bindings\n self.Bind(wx.EVT_TOOL, self.onQuit, self.tb_btn_quit)\n self.Bind(wx.EVT_TOOL, self.onPreferences, self.tb_btn_prefs)\n self.Bind(wx.EVT_TOOL, self.onRecovery, self.tb_btn_analysis)\n self.Bind(wx.EVT_TOOL, self.onRun, self.tb_btn_run)\n self.Bind(wx.EVT_TOOL, self.onLoadScript, self.tb_btn_load)\n self.Bind(wx.EVT_TOOL, self.onSaveScript, self.tb_btn_save)\n self.Bind(wx.EVT_TOOL, self.onReset, self.tb_btn_reset)\n\n # Input window bindings\n self.Bind(wx.EVT_BUTTON, self.onAdvancedOptions, self.input_window.opt_btn)\n\n\n # Draw the main window sizer\n self.SetSizer(main_box)\n\n def OnAboutBox(self, e):\n ''' About dialog '''\n info = wx.AboutDialogInfo()\n info.SetName('PRIME')\n info.SetWebSite('http://cci.lbl.gov/xfel')\n info.SetLicense(prime_license)\n info.SetDescription(prime_description)\n info.AddDeveloper('Monarin Uervirojnangkoorn')\n info.AddDeveloper('Axel Brunger')\n wx.AboutBox(info)\n\n def onPreferences(self, e):\n prefs = dlg.PRIMEPreferences(self,\n phil=self.prime_phil,\n title='Advanced PRIME Options',\n style=wx.DEFAULT_DIALOG_STYLE |\n wx.STAY_ON_TOP |\n wx.RESIZE_BORDER)\n prefs.SetMinSize((600, -1))\n prefs.Fit()\n\n if prefs.ShowModal() == wx.ID_OK:\n self.prime_phil = self.prime_phil.fetch(prefs.pref_phil)\n self.input_window.regenerate_params(self.prime_phil)\n\n def onAdvancedOptions(self, e):\n self.input_window.update_settings()\n self.prime_phil = self.prime_phil.fetch(self.input_window.prime_phil)\n advanced = dlg.PRIMEAdvancedOptions(self,\n phil=self.prime_phil,\n title='Advanced PRIME Options',\n style=wx.DEFAULT_DIALOG_STYLE |\n wx.STAY_ON_TOP |\n wx.RESIZE_BORDER)\n advanced.SetMinSize((600, -1))\n advanced.Fit()\n\n if advanced.ShowModal() == wx.ID_OK:\n self.prime_phil = self.prime_phil.fetch(advanced.phil_script)\n self.prime_phil = self.prime_phil.fetch(advanced.new_prime_phil)\n self.input_window.regenerate_params(self.prime_phil)\n\n advanced.Destroy()\n\n\n def onInput(self, e):\n if self.input_window.inp_box.ctr.GetValue() != '':\n self.set_tool_state(self.tb_btn_run, enable=True)\n else:\n self.set_tool_state(self.tb_btn_run, enable=False)\n\n def init_settings(self):\n self.input_window.update_settings()\n self.pparams = self.input_window.pparams\n self.out_dir = self.input_window.out_dir\n\n def sanity_check(self):\n '''\n Goes through and checks that the key parameters are populated; pops\n up an error message if they are not\n :return: True if satisfied, False if not\n '''\n\n # Check to see that pixel size is specified (PRIME won't run without it)\n if self.pparams.pixel_size_mm is None:\n warning = wx.MessageDialog(None,\n caption='Warning!',\n message='Pixel size not specified!',\n style=wx.OK)\n warning.ShowModal()\n warning.Destroy()\n return False\n\n return True\n\n def onRecovery(self, e):\n # Find finished runs and display results\n p_folder = os.path.abspath('{}/prime'.format(os.curdir))\n\n if not os.path.isdir(p_folder):\n open_dlg = wx.DirDialog(self, \"Choose the integration run:\",\n style=wx.DD_DEFAULT_STYLE)\n if open_dlg.ShowModal() == wx.ID_OK:\n p_folder = open_dlg.GetPath()\n open_dlg.Destroy()\n else:\n open_dlg.Destroy()\n return\n\n paths = [os.path.join(p_folder, p) for p in os.listdir(p_folder)]\n paths = [p for p in paths if (os.path.isdir(p) and\n os.path.basename(p).isdigit())]\n\n path_dlg = dlg.RecoveryDialog(self)\n path_dlg.insert_paths(paths)\n\n if path_dlg.ShowModal() == wx.ID_OK:\n selected = path_dlg.selected\n recovery = path_dlg.recovery_mode\n prime_path = selected[1]\n prime_status = selected[0]\n settings_file = os.path.join(prime_path, 'settings.phil')\n\n # If neither log-file nor stat file are found, terminate; otherwise\n # import settings\n if not os.path.isfile(settings_file):\n wx.MessageBox('Cannot Import This Run \\n(No Files Found!)',\n 'Info', wx.OK | wx.ICON_ERROR)\n return\n else:\n self.reset_settings()\n with open(settings_file, 'r') as sf:\n phil_string = sf.read()\n read_phil = ip.parse(phil_string)\n self.prime_phil = master_phil.fetch(source=read_phil)\n self.pparams = self.prime_phil.extract()\n self.input_window.regenerate_params(self.prime_phil)\n self.update_input_window()\n\n # If any cycles (or full run) were completed, show results\n if prime_status == 'Unknown':\n return\n\n if recovery == 0:\n self.prime_run_window = frm.PRIMERunWindow(self, -1,\n title='PRIME Output',\n params=self.pparams,\n prime_file=settings_file,\n recover=True)\n self.prime_run_window.Show(True)\n self.prime_run_window.recover()\n\n def onRun(self, e):\n # Run full processing\n\n self.init_settings()\n if self.sanity_check():\n prime_phil = master_phil.format(python_object=self.pparams)\n\n with Capturing() as output:\n prime_phil.show()\n\n txt_out = ''\n for one_output in output:\n txt_out += one_output + '\\n'\n\n source_dir = os.path.dirname(self.out_dir)\n prime_file = os.path.join(source_dir, self.prime_filename)\n out_file = os.path.join(self.out_dir, 'stdout.log')\n with open(prime_file, 'w') as pf:\n pf.write(txt_out)\n\n self.prime_run_window = frm.PRIMERunWindow(self, -1,\n title='PRIME Output',\n params=self.pparams,\n prime_file=prime_file)\n self.prime_run_window.prev_pids = easy_run.fully_buffered('pgrep -u {} {}'\n ''.format(user, python)).stdout_lines\n self.prime_run_window.place_and_size(set_by='parent')\n self.prime_run_window.Show(True)\n\n def onSequence(self, e):\n pass\n\n def onSaveScript(self, e):\n self.init_settings()\n\n # Generate text of params\n final_phil = master_phil.format(python_object=self.pparams)\n with Capturing() as txt_output:\n final_phil.show()\n txt_out = ''\n for one_output in txt_output:\n txt_out += one_output + '\\n'\n\n # Save param file\n save_dlg = wx.FileDialog(self,\n message=\"Save PRIME Script\",\n defaultDir=os.curdir,\n defaultFile=\"*.phil\",\n wildcard=\"*.phil\",\n style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT\n )\n if save_dlg.ShowModal() == wx.ID_OK:\n with open(save_dlg.GetPath(), 'w') as savefile:\n savefile.write(txt_out)\n\n save_dlg.Destroy()\n\n def onLoadScript(self, e):\n # Extract params from file\n load_dlg = wx.FileDialog(self,\n message=\"Load script file\",\n defaultDir=os.curdir,\n defaultFile=\"*.phil\",\n wildcard=\"*.phil\",\n style=wx.OPEN | wx.FD_FILE_MUST_EXIST,\n )\n if load_dlg.ShowModal() == wx.ID_OK:\n script = load_dlg.GetPaths()[0]\n out_dir = os.path.dirname(script)\n self.prime_filename=os.path.basename(script)\n self.load_script(out_dir=out_dir)\n load_dlg.Destroy()\n\n def onReset(self, e):\n self.reset_settings()\n\n def load_script(self, out_dir):\n ''' Loads PRIME script '''\n script = os.path.join(out_dir, self.prime_filename)\n with open(script, 'r') as sf:\n phil_string = sf.read()\n\n self.reset_settings()\n\n user_phil = ip.parse(phil_string)\n self.prime_phil = master_phil.fetch(source=user_phil)\n self.pparams = self.prime_phil.extract()\n self.input_window.pparams = self.pparams\n self.input_window.phil_string = phil_string\n self.update_input_window()\n\n\n def update_input_window(self):\n ''' Update input window with current (or default) params'''\n for input_item in self.pparams.data:\n if input_item is not None:\n self.input_window.inp_box.add_item(input_item)\n\n if self.pparams.run_no is not None:\n current_dir = os.path.dirname(self.pparams.run_no)\n else:\n current_dir = os.path.abspath(os.curdir)\n self.input_window.out_box.ctr.SetValue(str(current_dir))\n if str(self.input_window.out_box.ctr.GetValue).lower() == '':\n self.input_window.out_box.ctr.SetValue(self.out_dir)\n if str(self.pparams.title).lower() != 'none':\n self.input_window.project_title.ctr.SetValue(str(self.pparams.title))\n if str(self.pparams.hklisoin).lower() != 'none':\n self.input_window.inp_box.add_item(self.pparams.hklisoin)\n elif str(self.pparams.hklrefin).lower() != 'none':\n self.input_window.inp_box.add_item(self.pparams.hklrefin)\n self.input_window.opt_chk_useref.Enable()\n self.input_window.opt_chk_useref.SetValue(True)\n if str(self.pparams.n_residues).lower() == 'none':\n self.input_window.opt_spc_nres.ctr.SetValue(500)\n else:\n self.input_window.opt_spc_nres.ctr.SetValue(int(self.pparams.n_residues))\n self.input_window.opt_spc_nproc.ctr.SetValue(int(self.pparams.n_processors))\n\n def reset_settings(self):\n self.prime_phil = master_phil\n self.pparams = self.prime_phil.extract()\n self.input_window.inp_box.delete_all()\n self.input_window.out_box.reset_default()\n self.input_window.project_title.reset_default()\n self.input_window.opt_chk_useref.SetValue(False)\n self.input_window.opt_spc_nproc.reset_default()\n self.input_window.opt_spc_nres.reset_default()\n\n # Generate Python object and text of parameters\n with Capturing() as txt_output:\n master_phil.show()\n self.phil_string = ''\n for one_output in txt_output:\n self.phil_string += one_output + '\\n'\n\n def onQuit(self, e):\n self.Destroy()\n","sub_path":"prime/postrefine/mod_gui_init.py","file_name":"mod_gui_init.py","file_ext":"py","file_size_in_byte":15025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"37555242","text":"\"\"\"\nCollection of notebook utilities\n\"\"\"\nfrom .catalog import get_tap_service, get_catalog, retrieve_query\nfrom .forwarder import Forwarder\nfrom .utils import format_bytes, get_hostname, show_with_bokeh_server\n\n__all__ = [\n Forwarder,\n format_bytes,\n get_catalog,\n get_tap_service,\n retrieve_query,\n get_hostname,\n show_with_bokeh_server,\n]\n","sub_path":"rubin_jupyter_utils/lab/notebook/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"537619934","text":"'''\nGiven an array of integers, return indices of the two numbers such that they add up to a specific target.\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n'''\n\narray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n\nhashMap = {}\n\ntarget = 9\n\ndef AddToHashMap(array, target):\n global hashMap\n for i in range(len(array)):\n hashMap[(target - array[i])] = array[i]\n\ndef SearchMap(array, target):\n global hashMap\n for i in range(len(array)):\n if array[i] in hashMap:\n print(array[i], end=' ')\n print(hashMap[array[i]])\n\n\nAddToHashMap(array, target)\nSearchMap(array, target)","sub_path":"TwoSum.py","file_name":"TwoSum.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"386536914","text":"import requests\nfrom imutils import paths\nimport numpy as np\nimport cv2\nimport math\nimport time\nfrom array import *\nfrom numpy.linalg import inv\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter\nimport matplotlib.pyplot as plt\nimport matplotlib, time\n\n#initialize variables for plotting\ncx1 = 0\ncx2 = 0\ncy1 = 0\ncy2 = 0\ncz1 = 0\ncz2 = 0\n\n\n# initialize the known distance from the camera to the object, which\n# in this case is 15 inches\nKNOWN_DISTANCE = 15.0\nKNOWN_HEIGHT = 11.0\n\nfocalLength = (720 * KNOWN_DISTANCE) / KNOWN_HEIGHT\n\nMIN_MATCH_COUNT = 30\ndetector = cv2.xfeatures2d.SIFT_create()\nFLANN_INDEX_KDTREE = 0\nflannParam = dict(algorithm = FLANN_INDEX_KDTREE, tree = 5)\nflann = cv2.FlannBasedMatcher(flannParam,())\n\ntrainImage = cv2.imread('1.jpg', 0)\ntrainKP, trainDescriptors = detector.detectAndCompute(trainImage, None)\ntrainImage2 = cv2.imread('2.jpg',0)\ntKP2, tDesc2 = detector.detectAndCompute(trainImage2, None)\n\nfig = plt.figure()\nax = plt.axes(projection='3d')\n\n#while True:\nfor imagePath in sorted(paths.list_images(\"final\")):\n\t#scanning for the first training image\n #queryImageBGR = cv2.imread(\"final2.jpg\")\n queryImageBGR = cv2.imread(imagePath)\n print(imagePath)\n queryImage = cv2.cvtColor(queryImageBGR, cv2.COLOR_BGR2GRAY)\n queryKP, queryDescriptors = detector.detectAndCompute(queryImage, None)\n matches = flann.knnMatch(queryDescriptors, trainDescriptors, 2)\n goodMatch1 = []\n goodMatch2 = []\n\n for m, n in matches:\n if(m.distance < 0.75*n.distance):\n goodMatch1.append(m)\n\n if(len(goodMatch1)>MIN_MATCH_COUNT):\n tp = []\n qp = []\n for m in goodMatch1:\n tp.append(trainKP[m.trainIdx].pt)\n qp.append(queryKP[m.queryIdx].pt)\n tp,qp = np.float32((tp,qp))\n H, status = cv2.findHomography(tp, qp, cv2.RANSAC, 3.0)\n h, w = trainImage.shape\n trainBorder = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n queryBorder = cv2.perspectiveTransform(trainBorder, H)\n marker = (queryBorder[3][0][0] - queryBorder[0][0][0])\n\n\t\t#Finding the coordinates of the object in inches\n x0 = (queryBorder[1][0][0] - 640)/128\n y0 = (360 - queryBorder[1][0][1])/128\n x1 = (queryBorder[2][0][0] - 640)/128\n y1 = (360 - queryBorder[2][0][1])/128\n x2 = (queryBorder[0][0][0] - 640)/128\n y2 = (360 - queryBorder[0][0][1])/128\n x3 = (queryBorder[3][0][0] - 640)/128\n y3 = (360 - queryBorder[3][0][1])/128\n\n a = ((x1 - x0)*(y3 - y1) - (x3 - x1)*(y1 - y0))/((x3 - x1)*(y2 - y1) - (x2 - x1)*(y3 - y1))\n b = ((x1 - x0)*(y2 - y1) - (x2 - x1)*(y1 - y0))/((x3 - x1)*(y2 - y1) - (x2 - x1)*(y3 - y1))\n\n t0 = KNOWN_HEIGHT/math.sqrt((a*x2 - x0)*(a*x2 - x0) + (a*y2 - y0)*(a*y2 - y0) + focalLength*focalLength*(a - 1)*(a - 1)/(128*128))\n t2 = a*t0\n t3 = b*t0\n t1 = t0 + t3 - t2\n\n x0 = t0*x0\n x1 = t1*x1\n x2 = t2*x2\n x3 = t3*x3\n y0 = t0*y0\n y1 = t1*y1\n y2 = t2*y2\n y3 = t3*y3\n z0 = t0*focalLength/128\n z1 = t1*focalLength/128\n z2 = t2*focalLength/128\n z3 = t3*focalLength/128\n\n #coordinates of the center point of the image\n cx1 = (x1 + x2 + x3 + x0)/4\n cy1 = (y1 + y2 + y3 + y0)/4\n cz1 = (z0 + z1 + z2 + z3)/4\n \n dist = math.sqrt(cx1*cx1 + cy1*cy1 + cz1*cz1)\n\n cv2.putText(queryImageBGR, \"(%.2f, %.2f, %.2f)\" % (cx1, cy1, cz1), (queryImageBGR.shape[1] - 400, queryImageBGR.shape[0] - 150), cv2.FONT_HERSHEY_SIMPLEX,1.0, (0, 255, 0), 3)\n cv2.putText(queryImageBGR, \"%.1fft\" % (dist/12),(queryImageBGR.shape[1] - 400, queryImageBGR.shape[0] - 50), cv2.FONT_HERSHEY_SIMPLEX,2.0, (0, 255, 0), 3)\n cv2.polylines(queryImageBGR, [np.int32(queryBorder)],True,(0,255,0),5, cv2.LINE_AA)\n\n else:\n print('Not enough matches')\n\n\n # scanning for the second training image\n matches2 = flann.knnMatch(queryDescriptors, tDesc2, 2)\n for m,n in matches2:\n if(m.distance < 0.75*n.distance):\n goodMatch2.append(m)\n if(len(goodMatch2)>MIN_MATCH_COUNT):\n tp2 = []\n qp2 = []\n for m in goodMatch2:\n tp2.append(tKP2[m.trainIdx].pt)\n qp2.append(queryKP[m.queryIdx].pt)\n tp2,qp2 = np.float32((tp2,qp2))\n H, status = cv2.findHomography(tp2, qp2, cv2.RANSAC, 3.0)\n h, w = trainImage2.shape\n trainBorder = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n queryBorder = cv2.perspectiveTransform(trainBorder, H)\n marker = (queryBorder[3][0][0] - queryBorder[0][0][0])\n\n\t\t#Finding the coordinates of the object in inches\n x0 = (queryBorder[1][0][0] - 640)/128\n y0 = (360 - queryBorder[1][0][1])/128\n x1 = (queryBorder[2][0][0] - 640)/128\n y1 = (360 - queryBorder[2][0][1])/128\n x2 = (queryBorder[0][0][0] - 640)/128\n y2 = (360 - queryBorder[0][0][1])/128\n x3 = (queryBorder[3][0][0] - 640)/128\n y3 = (360 - queryBorder[3][0][1])/128\n\n a = ((x1 - x0)*(y3 - y1) - (x3 - x1)*(y1 - y0))/((x3 - x1)*(y2 - y1) - (x2 - x1)*(y3 - y1))\n b = ((x1 - x0)*(y2 - y1) - (x2 - x1)*(y1 - y0))/((x3 - x1)*(y2 - y1) - (x2 - x1)*(y3 - y1))\n\n t0 = KNOWN_HEIGHT/math.sqrt((a*x2 - x0)*(a*x2 - x0) + (a*y2 - y0)*(a*y2 - y0) + focalLength*focalLength*(a - 1)*(a - 1)/(128*128))\n t2 = a*t0\n t3 = b*t0\n t1 = t0 + t3 - t2\n\n x0 = t0*x0\n x1 = t1*x1\n x2 = t2*x2\n x3 = t3*x3\n y0 = t0*y0\n y1 = t1*y1\n y2 = t2*y2\n y3 = t3*y3\n z0 = t0*focalLength/128\n z1 = t1*focalLength/128\n z2 = t2*focalLength/128\n z3 = t3*focalLength/128\n\n\t\t#coordinates of the center point of the image\n cx2 = (x1 + x2 + x3 + x0)/4\n cy2 = (y1 + y2 + y3 + y0)/4\n cz2 = (z0 + z1 + z2 + z3)/4\n \n dist = math.sqrt(cx2*cx2 + cy2*cy2 + cz2*cz2)\n\n cv2.putText(queryImageBGR, \"(%.2f, %.2f, %.2f)\" % (cx2, cy2, cz2), (queryImageBGR.shape[1] - 1000, queryImageBGR.shape[0] - 150), cv2.FONT_HERSHEY_SIMPLEX,1, (255, 0, 0), 3)\n cv2.putText(queryImageBGR, \"%.1fft\" % (dist/12),(queryImageBGR.shape[1] - 1000, queryImageBGR.shape[0] - 50), cv2.FONT_HERSHEY_SIMPLEX,2.0, (255, 0, 0), 3)\n cv2.polylines(queryImageBGR, [np.int32(queryBorder)],True,(255,0,0),5, cv2.LINE_AA)\n else:\n print('Not enough matches - 2')\n\n\t#plotting the points\n # px1 = [0, cx1]\n# py1 = [0, cy1]\n# pz1 = [0, cz1]\n# \n# px2 = [0, cy1]\n# py2 = [0, cy2]\n# pz2 = [0, cz2]\n# \n# cx = [0]\n# cy = [0]\n# cz = [0]\n# \n# ax.set_xlim([-50,50])\n# ax.set_ylim([-50,50])\n# ax.set_zlim([0,300])\n# \n# ax.plot(px1, py1, pz1, color='g', marker='o')\n# ax.plot(px2, py2, pz2, color='b', marker='o')\n# ax.plot(cx, cy, cz, color = 'black', marker = 'o')\n# plt.draw()\n# plt.pause(0.001)\n# ax.cla()\n queryImageBGR = cv2.resize(queryImageBGR, (1280, 720))\n cv2.imshow('result', queryImageBGR)\n if cv2.waitKey(1) == ord('q'):\n break\n time.sleep(2)","sub_path":"Image/object-detection.py","file_name":"object-detection.py","file_ext":"py","file_size_in_byte":7229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"286440021","text":"# -*- coding: utf-8 -*-\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport plotly.express as px\nimport plotly.graph_objs as go\nfrom plotly.subplots import make_subplots\nimport pandas as pd\nimport datetime\n\nimport sys \nsys.path.append(\"..\") \n\nfrom plotCoronavirous import pathsFiles\n\nclass layperOutClass:\n def __init__(self,app):\n print(\"-------------------init-----------------\")\n self.app = app\n #self.color_lock = [ \"#cce6ff\", \"#857aad\", \"#690a3d\"]\n self.wroldData = self.getWorldData()\n self.AllCountries = self.getCountries()\n self.layerOut()\n \n def getWorldData(self):\n df = pd.read_csv(r'..\\dataCountry\\Worldwide.csv')\n #print(df.head(5))\n for col in df.columns: \n df[col] = df[col].astype(str)\n return df\n\n def getCountryData(self,country):\n df = pd.read_csv(r'..\\dataCountry\\\\' + country + '.csv')\n #print(df.head(5))\n for col in df.columns: \n df[col] = df[col].astype(str)\n return df\n \n def getCountries(self):\n countries = []\n for i in pathsFiles(r'..\\dataCountry\\\\','csv'):\n #print(i)\n country = i[i.rfind('\\\\')+1:i.rfind('.')]\n #print('country=',country)\n countries.append(country)\n return countries\n \n def layerOut(self):\n fig_lw = make_subplots(rows=2, cols=2, subplot_titles='COVID-19 statistics')\n \n dataWorld = self.wroldData.copy()\n #dataWorld = dataWorld.loc[:,['Date','Confirmed']]\n #dataWorld.set_index([\"Date\"], inplace=True)\n \n elment = go.Bar(x=dataWorld['Date'],y=dataWorld['Confirmed'], marker=dict(color=\"blue\"), showlegend=False,text='World Confirmed cases')\n fig_lw.add_trace(elment, row=1, col=1)\n elment = go.Bar(x=dataWorld['Date'],y=dataWorld['Deaths'], marker=dict(color=\"red\"), showlegend=False,text='World Deaths')\n fig_lw.add_trace(elment,row=1, col=2)\n elment = go.Bar(x=dataWorld['Date'],y=dataWorld['NewConfirmed'], marker=dict(color=\"yellow\"), showlegend=False,text='World NewConfirmed')\n fig_lw.add_trace(elment,row=2, col=1)\n elment = go.Bar(x=dataWorld['Date'],y=dataWorld['NewDeaths'], marker=dict(color=\"black\"), showlegend=False,text='World NewDeaths')\n fig_lw.add_trace(elment,row=2, col=2)\n fig_lw.update_layout(title_text=\"Wrold COVID-19 statistics\") #height=400, width=600,\n fig_lw.update_layout(margin={'l': 20, 'b': 10, 't': 50, 'r': 0}, hovermode='closest')\n #fg = px.bar(dataWorld, x='Date', y='Confirmed', hover_data=['Deaths', 'Mortality'], #color='Deaths')\n \n dicts = []\n for i in self.AllCountries:\n dicts.append({'label':i,'value':i})\n \n #print(dicts)\n dropdownCountry = dcc.Dropdown(id=\"country_dropDown\",options=dicts, value=dicts[0]['value']) \n \n self.app.layout = html.Div([\n # adding a header and a paragraph\n html.Div([html.H2(\"COVID-19 statistics dashboard @StevenHuang2020\"),\n html.P(\"Source reference:https://google.com/covid19-map/\")], style = {'padding' : '50px' , 'backgroundColor' : '#3aaab2'}),\n html.Div(id=\"slideshow-container\", children=[dcc.Graph(figure = fig_lw)], style = {'display': 'inline-block'}),\n #html.Div(id=\"country-dropDown\", children=[dropdownCountry], style = {'display': 'inline-block'}),\n \n html.Div( id=\"country\",\n children=[html.Br(),html.Br(),\n html.Label(\"Country COVID-19 statistics\"),\n dropdownCountry,\n dcc.Graph(id='Country_NewCases')], style = {\n 'width' : '50%',\n 'fontSize' : '20px',\n 'padding-left' : '60px',\n 'padding-right' : '100px',\n 'display': 'inline-block'\n })\n ])\n\ndef setupApp(layer, app):\n @app.callback(Output('Country_NewCases', 'figure'),\n [Input('country_dropDown', 'value')])\n\n def update_figure(country):\n print('country=',country)\n df = layer.getCountryData(country)\n #print(df.head(5))\n \n #dataWorld = layer.wroldData.copy()\n #fig = px.bar(dataWorld, x=\"Date\", y=\"Confirmed\", color=\"Confirmed\", custom_data=[\"NewConfirmed\"])\n if 0:\n fig = px.bar(df, x=\"Date\", y=\"Confirmed\")\n else:\n fig = make_subplots(rows=2, cols=2)\n fig.add_trace(go.Bar(x=df['Date'],y=df['NewConfirmed'],showlegend=False,text='NewConfirmed cases'),row=1, col=1)\n fig.add_trace(go.Bar(x=df['Date'],y=df['NewDeaths'],showlegend=False,text='NewDeaths'),row=1, col=2)\n fig.add_trace(go.Bar(x=df['Date'],y=df['Confirmed'],showlegend=False,text='Confirmed cases'),row=2, col=1)\n fig.add_trace(go.Bar(x=df['Date'],y=df['Deaths'],showlegend=False,text='Deaths'),row=2, col=2) \n \n #fig.update_layout(height=500, width=800) # ,title_text=\"COVID-19 country statistic\"\n fig.update_layout(margin={'l': 20, 'b': 10, 't': 50, 'r': 0}, hovermode='closest')\n return fig\n \n \nif __name__ == '__main__': \n app = dash.Dash(__name__)\n layer = layperOutClass(app)\n setupApp(layer,app)\n app.run_server(debug=True)\n","sub_path":"coronavirus/dash/dash_covid19.py","file_name":"dash_covid19.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"500912375","text":"import discord\nimport os\nimport modules.ExtFuncs as util\nimport modules.checks as customChecks\nimport json\nimport threading\nimport multiprocessing\nimport modules.twitchBot as twitchBot\nfrom discord.ext import commands\nfrom twitchio.ext import commands as twitchComs\nimport twitchio\n\ntwitchProcessName = 'twitchBot'\n\nclass botClass:\n def __init__(self, gid):\n self.guildId = gid\n self.twitchChannel = self.getChannel()\n\n def getChannel(self):\n getGlob = util.globalVars()\n return getGlob.streamers.get(str(self.guildId))\n\nclass twitchBotCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.processes = []\n self.shareData = multiprocessing.Queue()\n\n\n @commands.command(name='runTwitch')\n @customChecks.checkRole('Admins')\n async def runTwitch(self, ctx):\n gid = ctx.guild.id\n globVars = util.globalVars()\n streamers = globVars.streamers\n botData = botClass(gid)\n\n if streamers.get(str(gid)) != None:\n processName = f'{twitchProcessName}-{gid}'\n twitchProcess = multiprocessing.Process(target=twitchBot.run, kwargs={'botClass': botData.twitchChannel, 'guildId': botData.guildId, 'dataQueue': self.shareData}, name=processName)\n twitchProcess.start()\n self.processes.append(processName)\n await ctx.send(f'Twitch Bot has been started on the channel \"{streamers.get(str(gid))}\"')\n else:\n await ctx.send(f'The guild {ctx.guild.name} does not have an associated twitch channel...')\n \n def cog_unload(self):\n for process in self.processes:\n print(f'Terminating process: {process.name}')\n process.join()\n print('unloaded cog')\n\ndef setup(bot):\n bot.add_cog(twitchBotCog(bot))","sub_path":"modules/discordCogs/twitch.py","file_name":"twitch.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"114229971","text":"'''\r\nCreated on Aug 16, 2018\r\n\r\n@author: QDoan\r\n'''\r\nimport logging, os\r\n\r\nfrom myutils import utils_xmlfile, utils_files_io\r\n\r\n\r\ndef extract_assignments_list_from_availableAssignments_json(filename):\r\n ''' This function extracts a list of assignments from the availableAssignment JSON.\r\n Hidden/suppressed assignments do not appear in this JSON '''\r\n jo = utils_files_io.read_json_from_file(filename)\r\n assignments = []\r\n for i, item in enumerate(jo):\r\n logging.info(' Processign item {}...'.format(i + 1))\r\n assignment_number = item['ordinal']\r\n assignment_type_number = item['typeOrdinal']\r\n assignment_name = item['name']\r\n category_name = item['category']\r\n# if 'assignment' in category_name or 'prereq' in category_name: continue\r\n# msg = '{} - {}: {} [{}]'.format(assignment_number, assignment_type_number, assignment_name, category_name)\r\n msg = '{}. {} [{}]'.format(assignment_number, assignment_name, category_name)\r\n assignments.append(msg)\r\n# print(msg)\r\n logging.info(' ' + msg)\r\n return assignments\r\n\r\ndef extract_assignments_list_from_ndf_file(xmlfile):\r\n from lcs.utils import utils_ndf_files\r\n \r\n assignments = utils_ndf_files.extract_assignments_info_from_ndf_xml(xmlfile)\r\n \r\n ''' 1. Extract the first assignment (where previous node is NA) '''\r\n first_assignment_id = [key for key in assignments.keys() if assignments[key]['previous'] == 'NA'][0]\r\n\r\n ''' 2. Build assignments list starting with first_assignment_id '''\r\n assignments_list = []\r\n first_assignment_title = assignments[first_assignment_id]['title']\r\n assignments_list.append(first_assignment_title)\r\n next_node_id = assignments[first_assignment_id]['next']\r\n logging.info(' First assignment title: {}'.format(first_assignment_title))\r\n logging.info(' Next ID: {}'.format(next_node_id))\r\n while next_node_id != 'NA':\r\n logging.info('Looking up node {}...'.format(next_node_id))\r\n next_node_title = assignments[next_node_id]['title']\r\n next_node_id = assignments[next_node_id]['next']\r\n assignments_list.append(next_node_title)\r\n logging.info(' Title: {}'.format(next_node_title))\r\n logging.info(' Next ID: {}'.format(next_node_id))\r\n \r\n return assignments_list\r\n \r\nif __name__ == '__main__':\r\n log_file = 'C:/Workspace/Sandbox/log.txt';\r\n if os.path.isfile(log_file): os.remove(log_file)\r\n logging.basicConfig(filename = log_file, level=logging.INFO)\r\n \r\n# assignments = extract_assignments_list_from_availableAssignments_json('available_assignments/MAT081_Section3_Aug16.json')\r\n# [print(item) for item in assignments]\r\n# filename1 = 'available_assignments/MAT081_Fall_2018_assignments.txt'\r\n# filename2 = 'available_assignments/MAT081_Master_Course_assignments.txt'\r\n# utils_xmlfile.diff_two_files(filename1, filename2)\r\n \r\n ''' Extract assignments list for MAT081 Master Course from NDF file '''\r\n assignments = extract_assignments_list_from_ndf_file('data/MAT081_Master_Course_NDF_sarita.xml')\r\n for i, item in enumerate(assignments):\r\n print('{}. {}'.format(int(i)+1, item))\r\n# filename1 = 'data/MAT081_Fall_2018_NDF_tag1_assignments.txt'\r\n# filename2 = 'data/MAT081_Master_Course_NDF_sarita_assignments.txt'\r\n# utils_xmlfile.diff_two_files(filename1, filename2)\r\n\r\n ''' Diff'ing two NDF files '''\r\n# filename1 = 'prof_kurtz/MAT081_Master_Course_NDF.xml'\r\n# filename2 = 'prof_kurtz/MAT081_Master_Course_NDF_sarita.xml'\r\n# utils_xmlfile.diff_two_files(filename1, filename2)","sub_path":"DevMathPython/cdr/prof_kurtz/prof_kurtz.py","file_name":"prof_kurtz.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"108583008","text":"def main():\n n = int(input())\n C, S, F = [], [], []\n for _ in range(n - 1):\n c, s, f = list(map(int, input().split()))\n C.append(c)\n S.append(s)\n F.append(f)\n for i in range(n):\n t = 0\n for j in range(i, n - 1):\n if t <= S[j]:\n t = S[j]\n elif t % F[j] != 0:\n t += F[j] - t % F[j]\n t += C[j]\n print(t)\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python_codes/p03475/s053536164.py","file_name":"s053536164.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"464759769","text":"'''\r\nIterators:\r\n0. List, string, dict, tuple, sets and range objects are iterables and int, float, bool and None object are not iterables.\r\n1. Iterators are the objects which are created on calling the iter method on iterables.\r\n Ex\r\n y = [1,2,3]- This is iterable object\r\n x = iter(y) - This is an iterator\r\n\r\n2. The trademark or most important property of iterator object is that they can call __next__ method.\r\n3. list, string, dict, tuple, sets and range objects are not iterators, they all are iterables objects because they cannot\r\n call the __next__method.\r\n\r\n4. The use of iterators are used to fetch one value at a time, or to fetch values one at a time.\r\n5. One more important property of iterator is that, it starts the execution after that value where the execution\r\n was previously left off.\r\n\r\n6. To create iter class, you need two method __iter__ method and __next__method, it can be induced in the class by use of\r\n operator overloading.\r\n __iter__ method is used to iterate through the loop, means to fetch values one at a time means if there is not an\r\n __iter__ method, then you cannot apply for loop to iterate through it.\r\n __next__ method is trademark of the iterator, without it, no functions of iterator will work means you neither can fetch\r\n values one by one nor you can fetch values one at a time.\r\n'''\r\n\r\n# Examples-1\r\n\r\nl = [1,2,3,4]\r\n\r\n#Two ways to create iterators\r\n\r\nit = iter(l)\r\nit = l.__iter__()\r\n\r\n# Two ways to call the next method.\r\n\r\nprint(it.__next__())\r\nprint(next(it))\r\n\r\n# Looping through an iterator,\r\n\r\n'''One more important property of iterator is that, it starts the execution after that value where the execution was \r\n previously left off.'''\r\n'''As here you have already called the value 1 and 2 from the iterator, now this loop will call only 3 and 4 value.'''\r\n\r\nfor i in it:\r\n print(i)\r\n\r\n\r\n\r\n\r\n\r\nprint(\"\")\r\n\r\n# Example-2\r\n'''When you are creating your own iterator class, you need to two methods, first is iterator method and next method'''\r\n\r\nclass topten:\r\n def __init__(self):\r\n self.num = 1\r\n\r\n def __iter__(self):# If you dont use this, you cannot loop through this class or simply you cannot use for loops, Without it you can use the next method\r\n return self # here we can only write return self which means make the object an iterator.\r\n def __next__(self):# If you dont use this, you cannot use for loops and next method.\r\n\r\n\r\n if self.num <= 10:\r\n value = self.num\r\n self.num+=1\r\n return value\r\n else:\r\n raise StopIteration # this is same as break, but break applies in for loops case but there is no for loop, so\r\n # here we are using stop Iteration.\r\n\r\nt1 = topten()\r\nprint(iter(t1))# This will print the location.\r\nprint(t1.__next__())\r\nprint(next(t1))\r\nfor i in t1:\r\n print(i)\r\n\r\nprint(\"\")\r\n#Example-3\r\n'''If you call the next method in an iterator, but there is no next value in the iterator, then it would show an error\r\n of stop iteration'''\r\n\r\ny = iter([1])\r\nprint(next(y))# this will return 1\r\n#print(next(y))# This will show an error, as there is no further value.\r\n\r\n\r\n\r\n\r\n","sub_path":"64.0_Iterators.py","file_name":"64.0_Iterators.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"190448612","text":"# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory\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\nfrom rest_framework.parsers import BaseParser\nfrom django.conf import settings\n\nimport blosc\nimport numpy as np\n\nfrom bosscore.request import BossRequest\nfrom bosscore.error import BossParserError, BossError, ErrorCodes\n\nimport spdb\n\n\nclass BloscParser(BaseParser):\n \"\"\"\n Parser that handles blosc compressed binary data\n \"\"\"\n media_type = 'application/blosc'\n\n def parse(self, stream, media_type=None, parser_context=None):\n \"\"\"Method to decompress bytes from a POST that contains blosc compressed matrix data\n\n **Bytes object decompressed should be C-ordered**\n\n :param stream: Request stream\n stream type: django.core.handlers.wsgi.WSGIRequest\n :param media_type:\n :param parser_context:\n :return:\n \"\"\"\n # Process request and validate\n try:\n req = BossRequest(parser_context['request'])\n except BossError as err:\n return BossParserError(err.args[0], err.args[1], err.args[2])\n\n # Convert to Resource\n resource = spdb.project.BossResourceDjango(req)\n\n # Get bit depth\n try:\n bit_depth = resource.get_bit_depth()\n except ValueError:\n return BossParserError(\"Unsupported data type provided to parser: {}\".format(resource.get_data_type()),\n ErrorCodes.TYPE_ERROR)\n\n # Make sure cutout request is under 1GB UNCOMPRESSED\n total_bytes = req.get_x_span() * req.get_y_span() * req.get_z_span() * len(req.get_time()) * bit_depth / 8\n if total_bytes > settings.CUTOUT_MAX_SIZE:\n return BossParserError(\"Cutout request is over 1GB when uncompressed. Reduce cutout dimensions.\",\n ErrorCodes.REQUEST_TOO_LARGE)\n\n try:\n # Decompress\n raw_data = blosc.decompress(stream.read())\n data_mat = np.fromstring(raw_data, dtype=resource.get_numpy_data_type())\n except:\n return BossParserError(\"Failed to decompress data. Verify the datatype/bitdepth of your data \"\n \"matches the channel/layer.\", ErrorCodes.DATATYPE_DOES_NOT_MATCH)\n\n # Reshape and return\n try:\n if len(req.get_time()) > 1:\n # Time series data\n return np.reshape(data_mat, (len(req.get_time()), req.get_z_span(), req.get_y_span(), req.get_x_span()),\n order='C')\n else:\n return np.reshape(data_mat, (req.get_z_span(), req.get_y_span(), req.get_x_span()), order='C')\n except ValueError:\n return BossParserError(\"Failed to unpack data. Verify the datatype of your POSTed data and \"\n \"xyz dimensions used in the POST URL.\", ErrorCodes.DATA_DIMENSION_MISMATCH)\n\n\nclass BloscPythonParser(BaseParser):\n \"\"\"\n Parser that handles blosc compressed binary data in python numpy format\n \"\"\"\n media_type = 'application/blosc-python'\n\n def parse(self, stream, media_type=None, parser_context=None):\n \"\"\"Method to decompress bytes from a POST that contains blosc compressed numpy ndarray\n\n Only should be used if data sent was compressed using blosc.pack_array()\n\n :param stream: Request stream\n stream type: django.core.handlers.wsgi.WSGIRequest\n :param media_type:\n :param parser_context:\n :return:\n \"\"\"\n try:\n req = BossRequest(parser_context['request'])\n except BossError as err:\n return BossParserError(err.args[0], err.args[1], err.args[2])\n\n # Convert to Resource\n resource = spdb.project.BossResourceDjango(req)\n\n # Get bit depth\n try:\n bit_depth = resource.get_bit_depth()\n except ValueError:\n return BossParserError(\"Unsupported data type provided to parser: {}\".format(resource.get_data_type()),\n ErrorCodes.TYPE_ERROR)\n\n # Make sure cutout request is under 1GB UNCOMPRESSED\n total_bytes = req.get_x_span() * req.get_y_span() * req.get_z_span() * len(req.get_time()) * bit_depth / 8\n if total_bytes > settings.CUTOUT_MAX_SIZE:\n return BossParserError(\"Cutout request is over 1GB when uncompressed. Reduce cutout dimensions.\",\n ErrorCodes.REQUEST_TOO_LARGE)\n\n # Decompress and return\n try:\n return blosc.unpack_array(stream.read())\n except EOFError:\n return BossParserError(\"Failed to unpack data. Verify the datatype of your POSTed data and \"\n \"xyz dimensions used in the POST URL.\", ErrorCodes.DATA_DIMENSION_MISMATCH)\n\n","sub_path":"django/bossspatialdb/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":5358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"646656871","text":"import timeit\nfrom PIL import Image\nimport numpy as np\nimport vektor # fungsi/prosedur menghitung nilai dan vektor eigen (vektor.py)\nimport svd # fungsi/prosedur menghitung svd (svd.py)\n\ndef main(file_name, c_rate):\n # Timer Start\n start = timeit.default_timer()\n\n # Open image\n img = Image.open(r\"static\\uploads\\\\\"+file_name)\n M = np.asarray(img).astype(float) # convert image to matrix\n\n # jenis gambar : color/grayscale/png\n if (M.ndim == 2):\n new_M, size0, new_size = svd.svdGrayscale(M, c_rate)\n c_img = Image.fromarray(new_M.astype(np.uint8), 'L')\n elif (M.ndim == 3 and M.shape[2] == 3):\n new_M, size0, new_size = svd.svdColor(M, c_rate)\n c_img = Image.fromarray(new_M.astype(np.uint8), 'RGB')\n elif (M.ndim == 3 and M.shape[2] == 4):\n new_M, size0, new_size = svd.svdColorPNG(M, c_rate)\n c_img = Image.fromarray(new_M.astype(np.uint8), 'RGBA')\n\n # Timer Stop\n stop = timeit.default_timer()\n Time = round(stop - start, 3)\n\n # Ouput\n init_size = 'Initial Size : ' + str(size0) + ' bytes'\n comp_size = 'Compressed Size : ' + str(new_size) + ' bytes' \n percentage = 'Image Pixel Difference Percentage : ' + str(round(float(new_size/size0*100), 2)) + '%' \n time = 'Image Compression Time : ' + str(Time) + ' seconds' \n return init_size, comp_size, percentage, time, c_img","sub_path":"src/img_compress.py","file_name":"img_compress.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"340355261","text":"'''\r\n@author: Quyen Doan, https://github.com/qdoan1651/DevMathPython\r\n@file: lcs/retrieve_wsid_with_course_key/retrieve_wsid_with_course_key.py\r\n@desc: Retrieve course workspace ID with course key\r\n'''\r\nimport logging, os, re, requests\r\nfrom lcs.get_base_url import get_base_url\r\n\r\ndef retrieve_wsid_with_course_key_v1(course_key):\r\n ''' Returns course workspace ID with provided course key, or None if course key not found.\r\n This version uses Selenium to extract the wsid from the web page '''\r\n from selenium import webdriver\r\n from selenium.common.exceptions import NoSuchElementException\r\n from selenium.webdriver.common.by import By\r\n from selenium.webdriver.support.wait import WebDriverWait\r\n from selenium.webdriver.support import expected_conditions as EC\r\n \r\n driver = webdriver.Chrome('C:/Workspace/Tools/drivers/chromedriver.exe')\r\n driver.set_window_size(1600, 1050)\r\n\r\n print('Processing course key {}...'.format(course_key))\r\n base_url = 'https://lcs-v2-int.cengage.info'\r\n driver.get('{}/lcs-explorer/index.html#/lcs/prod/workspaces/byLabels/courseKey:{}?_k=j2iqt4'.format(base_url, course_key))\r\n try:\r\n locator = (By.XPATH, \"//table[@id='workspaceListTables']/tbody/tr/td[1]\")\r\n wsid = WebDriverWait(driver, 30).until(EC.visibility_of_element_located(locator)).text\r\n return wsid\r\n except NoSuchElementException:\r\n print('*** Info: Course workspace ID is not found for course {}'.format(course_key))\r\n return None\r\n\r\ndef retrieve_wsid_with_course_key(course_key, env):\r\n ''' Extract WSID for a course using REST endpoint '''\r\n logging.info(' Retrieving workspace ID with course key {}...'.format(course_key))\r\n \r\n # Modify course key when needed\r\n if '-' in course_key and len(course_key) == 14: \r\n # Remove dashes from course key for non-LMS course\r\n course_key = re.sub('-', '', course_key)\r\n elif '-' not in course_key and len(course_key) == 16:\r\n # Add dashes to LMS course\r\n course_key = '-'.join([course_key[0:4], course_key[4:8], course_key[8:12], course_key[12:16]]) \r\n \r\n body_data = {\"labels\":[{\"type\":\"courseKey\",\"value\":\"{}\".format(course_key)}]}\r\n \r\n base_url = get_base_url.get_base_url(env)\r\n url = base_url + \"/ws/workspaces/byLabels\"\r\n try:\r\n logging.info(' Sending POST request {}...'.format(url))\r\n r = requests.post(url, json=body_data)\r\n if r.status_code == 200:\r\n wsid = r.json()['workspaces'][0]['id']\r\n logging.info(' Successfully retrieved workspace ID: {}'.format(wsid))\r\n return wsid\r\n else:\r\n msg = 'Failed to retrieve workspace ID. Status code: {}'.format(r.status_code)\r\n print('*** Error: ' + msg)\r\n logging.error(' ' + msg)\r\n return None\r\n except:\r\n msg = 'Failed to retrieve workspace ID. Exception occurs.'\r\n print('*** Error: ' + msg)\r\n logging.error(' ' + msg)\r\n return None\r\n \r\nif __name__ == '__main__':\r\n logfile = 'C:/Workspace/Sandbox/log.txt'\r\n if os.path.isfile(logfile): os.remove(logfile)\r\n logging.basicConfig(filename=logfile, level=logging.INFO)\r\n \r\n ''' Test retrieve_wsid_with_course_key() function '''\r\n course_list = ['DEPP-M2SP-DTXD', 'DEPPM2SPDTXD', 'GWDM-S4AT-2MMM-MG4U', 'GWDMS4AT2MMMMG4U']\r\n for course_key in course_list:\r\n print('Retrieving workspace ID with course key {}...'.format(course_key))\r\n wsid = retrieve_wsid_with_course_key(course_key, 'prod')\r\n print(wsid)\r\n ","sub_path":"DevMathPython/lcs/retrieve_course_wsid_with_course_key/retrieve_wsid_with_course_key.py","file_name":"retrieve_wsid_with_course_key.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"66273687","text":"import scrapy\n\n\nclass QuotesSpider(scrapy.Spider):\n name = \"quotes\"\n\n def start_requests(self):\n urls = [\n 'http://quotes.toscrape.com/page/1/',\n 'http://quotes.toscrape.com/page/2/',\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n page = response.url.split(\"/\")[-2]\n filename = f'quotes-{page}.html'\n with open(filename, 'wb') as f:\n f.write(response.body)\n self.log(f'Saved file {filename}')\n\n\nclass QuotesSpider2(scrapy.Spider):\n name = \"quotes2\"\n\n start_urls = [\n 'http://quotes.toscrape.com/page/1/',\n 'http://quotes.toscrape.com/page/2/',\n ]\n\n def parse(self, response):\n for quote in response.css('.quote'):\n yield {\n 'text' : quote.css('span.text::text').get(),\n 'author' : quote.css('.author::text').get(),\n 'tags' : quote.css('.tags .tag::text').getall(),\n }\n\n\nclass QuotesSpider3(scrapy.Spider):\n name = \"quotes3\"\n\n start_urls = [\n 'http://quotes.toscrape.com/page/1/',\n ]\n\n def parse(self, response):\n for quote in response.css('.quote'):\n yield {\n 'text' : quote.css('.text::text').get(),\n 'author' : quote.css('.author::text').get(),\n 'tags' : quote.css('.tags .tag::text').getall(),\n }\n\n next_page = response.css('.next a::attr(href)').get()\n if next_page is not None:\n next_page = response.urljoin(next_page)\n yield scrapy.Request(next_page, callback=self.parse)\n\n\nclass QuotesSpider4(scrapy.Spider):\n name = \"quotes4\"\n\n start_urls = [\n 'http://quotes.toscrape.com/page/1/',\n ]\n\n def parse(self, response):\n for quote in response.css('.quote'):\n yield {\n 'text' : quote.css('.text::text').get(),\n 'author' : quote.css('.author::text').get(),\n 'tags' : quote.css('.tags .tag::text').getall(),\n }\n\n for a in response.css('.next a'):\n yield response.follow(a, callback=self.parse)\n\n\nclass QuotesSpider5(scrapy.Spider):\n name = \"quotes5\"\n\n def start_requests(self):\n url = 'http://quotes.toscrape.com/'\n tag = getattr(self, 'tag', None)\n if tag is not None:\n url = url + 'tag/' + tag\n yield scrapy.Request(url, self.parse)\n\n def parse(self, response):\n for quote in response.css('div.quote'):\n yield {\n 'text': quote.css('span.text::text').get(),\n 'author': quote.css('small.author::text').get(),\n }\n\n next_page = response.css('li.next a::attr(href)').get()\n if next_page is not None:\n yield response.follow(next_page, self.parse)","sub_path":"tutorial/tutorial/spiders/quotes_spiders.py","file_name":"quotes_spiders.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"562040443","text":"# -*- coding: utf-8 -*-\nimport unittest\nimport uuid\n\nfrom mongoengine import Document, connect\nfrom mongoengine.connection import get_db\nfrom mongoengine.fields import StringField, UUIDField, ListField\n\n__all__ = ('ConvertToBinaryUUID', )\n\n\nclass ConvertToBinaryUUID(unittest.TestCase):\n\n def setUp(self):\n connect(db='mongoenginetest')\n self.db = get_db()\n\n def test_how_to_convert_to_binary_uuid_fields(self):\n \"\"\"Demonstrates migrating from 0.7 to 0.8\n \"\"\"\n\n # 1. Old definition - using dbrefs\n class Person(Document):\n name = StringField()\n uuid = UUIDField(binary=False)\n uuids = ListField(UUIDField(binary=False))\n\n Person.drop_collection()\n Person(name=\"Wilson Jr\", uuid=uuid.uuid4(),\n uuids=[uuid.uuid4(), uuid.uuid4()]).save()\n\n # 2. Start the migration by changing the schema\n # Change UUIDFIeld as now binary defaults to True\n class Person(Document):\n name = StringField()\n uuid = UUIDField()\n uuids = ListField(UUIDField())\n\n # 3. Loop all the objects and mark parent as changed\n for p in Person.objects:\n p._mark_as_changed('uuid')\n p._mark_as_changed('uuids')\n p.save()\n\n # 4. Confirmation of the fix!\n wilson = Person.objects(name=\"Wilson Jr\").as_pymongo()[0]\n self.assertTrue(isinstance(wilson['uuid'], uuid.UUID))\n self.assertTrue(all([isinstance(u, uuid.UUID) for u in wilson['uuids']]))\n","sub_path":"tests/migration/uuidfield_to_binary.py","file_name":"uuidfield_to_binary.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"130624923","text":"#from numpy import frombuffer\nimport numpy as np\nimport requests, gzip\nfrom pathlib import Path\n\n#----------------------------------------------------------------------------------------------\n# taken from https://ludius0.github.io/my-blog/ai/deep%20learning%20(dl)/2020/12/14/Neural-network-from-scratch.html\n\ndef fetch(url): \n name = url.split(\"/\")[-1]\n dirs = Path(\"dataset/mnist\")\n path = (dirs / name)\n if path.exists():\n with path.open(\"rb\") as f:\n dat = f.read()\n else:\n if not dirs.is_dir(): dirs.mkdir(parents=True, exist_ok=True)\n with path.open(\"wb\") as f:\n dat = requests.get(url).content\n f.write(dat)\n return np.frombuffer(gzip.decompress(dat), dtype=np.uint8).copy()\n\ndef one_hot_encoding(y):\n N = y.shape[0]\n Z = np.zeros((N, 10))\n Z[np.arange(N), y] = 1\n return Z\n\ndef normalize(X): \n return (X - np.mean(X)) / np.std(X)\n\ndef mnist_dataset():\n print(\" collecting data\")\n X_train = fetch(\"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\")[0x10:].reshape((-1, 28, 28))\n Y_train = fetch(\"http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\")[8:]\n X_test = fetch(\"http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\")[0x10:].reshape((-1, 28, 28))\n Y_test = fetch(\"http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\")[8:]\n\n\n #converting 2D images to 3D\n X_train = np.array([ img[np.newaxis, :, :] for img in X_train ]) \n X_test = np.array([ img[np.newaxis, :, :] for img in X_test ]) \n\n # pre processing data\n X_train = normalize(X_train) \n Y_train = one_hot_encoding(Y_train)\n\n X_test = normalize(X_test)\n Y_test = one_hot_encoding(Y_test)\n\n return (X_train, Y_train, X_test, Y_test)\n \n#X_train, Y_train, X_test, Y_test = mnist_dataset()\n\n","sub_path":"src/MNISTLoader.py","file_name":"MNISTLoader.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"263507613","text":"from Embedded_CSS_Optimizer.Optimizer.Optimize import *\nfrom Embedded_CSS_Optimizer.Read.ReadCss import *\nfrom Embedded_CSS_Optimizer.Read.ReadHtml import *\nfrom Embedded_CSS_Optimizer.Step1.RefreshStep1 import *\nfrom Embedded_CSS_Optimizer.Step2.RefreshStep2 import *\nfrom Embedded_CSS_Optimizer.Step3.RefreshStep3 import *\nfrom Embedded_CSS_Optimizer.StepWarning.RefreshWarning import *\nimport os\n\ndef ReadFile( lfStep1, lfStep2, lfWarning, lfStep3, CssPath, HtmlPath, CssTable, HtmlTable, ModifierDict, WarningList, CBStep2State, ButtonList, ChoiceList, ChoiceList2, WindowSetting):\n\n #Unexpected action handler\n\n if(len(CssPath) == 0):\n try:\n tkinter.messagebox.showerror (\"Error: No CSS\", \"Please add a CSS file\")\n except:\n tkMessageBox.showerror (\"Error: No CSS\", \"Please add a CSS file\")\n return\n elif(len(HtmlPath) == 0):\n try:\n tkinter.messagebox.showerror (\"Error: No HTML\", \"Please add an HTML file\")\n except:\n tkMessageBox.showerror (\"Error: No HTML\", \"Please add an HTML file\")\n return\n else:\n\n Error = \"The following files are unvalid:\"\n DefaultErrorLenght = len(Error)\n RemoveCss = []\n RemoveHtml = []\n for i in range(0, len(CssPath)):\n if(os.path.isfile(str(CssPath[i])) == False):\n Error += \"\\n...\" + CssPath[i][-40:] + \": Not Found\" + \"\\n\"\n RemoveCss.append(i)\n for i in RemoveCss[::-1]:\n CssPath.remove(CssPath[i])\n RemoveCss = []\n\n for i in range(0, len(HtmlPath)):\n if(os.path.isfile(str(HtmlPath[i])) == False):\n Error += \"\\n...\" + HtmlPath[i][-40:] + \": Not Found\" + \"\\n\"\n RemoveHtml.append(i)\n for i in RemoveHtml[::-1]:\n HtmlPath.remove(HtmlPath[i])\n RemoveHtml = []\n\n for i in range(0, len(CssPath)):\n if(CssPath[i][-4] != \".\" or CssPath[i][-3] != \"c\" or CssPath[i][-2] != \"s\" or CssPath[i][-1] != \"s\"):\n Error += \"\\n...\" + CssPath[i][-40:] + \": Not CSS\" + \"\\n\"\n RemoveCss.append(i)\n for i in RemoveCss[::-1]:\n CssPath.remove(CssPath[i])\n RemoveCss = []\n\n for i in range(0, len(HtmlPath)):\n if((HtmlPath[i][-5] != \".\" or HtmlPath[i][-4] != \"h\" or HtmlPath[i][-3] != \"t\" or HtmlPath[i][-2] != \"m\" or HtmlPath[i][-1] != \"l\")\n and(HtmlPath[i][-4] != \".\" or HtmlPath[i][-3] != \"h\" or HtmlPath[i][-2] != \"t\" or HtmlPath[i][-1] != \"m\")\n and(HtmlPath[i][-4] != \".\" or HtmlPath[i][-3] != \"i\" or HtmlPath[i][-2] != \"n\" or HtmlPath[i][-1] != \"c\")):\n Error += \"\\n...\" + HtmlPath[i][-40:] + \": Not HTML\" + \"\\n\"\n RemoveHtml.append(i)\n for i in RemoveHtml[::-1]:\n HtmlPath.remove(HtmlPath[i])\n RemoveHtml = []\n\n for i in range(0, len(CssPath)):\n if(CssPath.count(CssPath[i]) > 1):\n Error += \"\\n...\" + CssPath[i][-40:] + \": Found Multiple times\" + \"\\n\"\n RemoveCss.append(i)\n\n for i in RemoveCss[::-1]:\n del CssPath[i]\n RemoveCss = []\n\n for i in range(0, len(HtmlPath)):\n if(HtmlPath.count(HtmlPath[i]) > 1):\n Error += \"\\n...\" + HtmlPath[i][-40:] + \": Found Multiple times\" + \"\\n\"\n RemoveHtml.append(i)\n\n for i in RemoveHtml[::-1]:\n del HtmlPath[i]\n RemoveHtml = []\n\n if(len(Error) > DefaultErrorLenght):\n try:\n tkinter.messagebox.showerror (\"Error: Incorrect File(s)\", Error)\n except:\n tkMessageBox.showerror (\"Error: Incorrect File(s)\", Error)\n RefreshStep1(lfStep1, WindowSetting, HtmlPath, CssPath)\n lfStep1.children[\"read\"].grid(row=len(CssPath) + len(HtmlPath) + 9, column=0, pady=\"5\")\n return\n\n\n # Disable path modifications\n\n lfStep1.children[\"browsecss\"].configure(state=\"disabled\")\n lfStep1.children[\"browsehtml\"].configure(state=\"disabled\")\n lfStep1.children[\"read\"].configure(state=\"disabled\")\n lfStep1.children[\"entryhtml\"].configure(state=\"disabled\")\n lfStep1.children[\"entrycss\"].configure(state=\"disabled\")\n\n #Read the files\n\n ReadCSS(CssPath, CssTable, ModifierDict)\n ReadHTML(HtmlPath, HtmlTable)\n Optimize(WarningList, HtmlTable, CssTable, HtmlPath)\n\n #Display Step 2\n\n RefreshStep2(\"\", lfStep2, CBStep2State, ModifierDict, CssTable, ButtonList, ChoiceList, ChoiceList2, WindowSetting)\n\n #Display warning\n\n RefreshWarning(lfWarning, WarningList, WindowSetting)\n\n #Display Step 3\n\n RefreshStep3(lfStep3)\n\n # Move the window to the center of the screen\n \"\"\"\n Window.update_idletasks()\n Window.state('zoomed')\n X= Window.winfo_width()\n Y= Window.winfo_height()\n Window.state('normal')\n w,h,x,y=GetWindowData(Window.geometry())\n Window.geometry(\"%dx%d%+d%+d\" % (w,h,((X-w)//2)-50,10))\n \"\"\"\n\npass\n","sub_path":"build/lib/Embedded_CSS_Optimizer/Read/ReadFile.py","file_name":"ReadFile.py","file_ext":"py","file_size_in_byte":4977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"480317902","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport multiprocessing as mp\r\nimport os\r\n\r\nfrom scipy.integrate import odeint\r\nfrom scipy.interpolate import interp2d, griddata\r\n\r\nGRAV = 6.672e-11\r\nSOL_M = 1.9891e30\r\nAU = 149597870700\r\n\r\nmeas_dtype = np.dtype(([('t', np.float64), ('r', np.float64), ('dv', np.float64), ('phi0', np.float64)]))\r\n\r\nclass Planet(object):\r\n def __init__(self, m, r, rr, phi0):\r\n self.m = m\r\n self.r = r\r\n self.rr = rr\r\n self.phi0 = phi0\r\n if rr > 0:\r\n self.v = np.sqrt(GRAV * SOL_M / rr)\r\n self.T = 2 * np.pi * rr / self.v\r\n else:\r\n self.T = 1\r\n self.v = 1\r\n\r\n def pos(self, t):\r\n return np.asarray([\r\n self.rr * np.cos(2 * np.pi * t / self.T + self.phi0),\r\n self.rr * np.sin(2 * np.pi * t / self.T + self.phi0)\r\n ])\r\n\r\n def vel(self, t):\r\n return np.asarray([\r\n -self.v * np.sin(2 * np.pi * t / self.T + self.phi0),\r\n self.v * np.cos(2 * np.pi * t / self.T + self.phi0)\r\n ])\r\n\r\n def f(self, x, t):\r\n return -GRAV * self.m * (x - self.pos(t)) / np.linalg.norm(x - self.pos(t))**3\r\n\r\n def well(self, x, t):\r\n return -GRAV * self.m / np.linalg.norm(x - self.pos(t))\r\n\r\n\r\nsun = Planet(m=SOL_M, r=6.957e8, rr=0, phi0=0)\r\nearth = Planet(m=5.97219e24, r=6371e3, rr=AU, phi0=0)\r\n\r\nplanets = [sun]\r\n\r\n\r\ndef model(y, t):\r\n # X, Y, VX, VY\r\n dydt = np.asarray([y[2], y[3], 0, 0])\r\n for p in planets:\r\n dydt[2:] = dydt[2:] + p.f(y[:2], t)\r\n\r\n return dydt\r\n\r\n\r\ndef get_calendar(meas, dv, rmin=1.45*AU, rmax=1.55*AU):\r\n xx = [meas[(meas['dv'] < dv) & (meas['r'] > rmin) & (meas['r'] < rmax) &\r\n (meas['phi0'] > 2*np.pi/12 * month) & (meas['phi0'] < 2*np.pi/12 * (month + 1))]['t']\r\n for month in range(12)]\r\n\r\n return [np.min(x)/24/60/60 if len(x) > 0 else 1e99 for x in xx]\r\n\r\n\r\ndef calc(NN):\r\n meas = np.zeros(0, dtype=meas_dtype)\r\n for run in range(NN):\r\n # initial condition\r\n burn_phi = np.random.uniform(0, np.pi)\r\n burn_vel = np.random.uniform(0, 100000)\r\n dv = burn_vel # escape velocity from Earth to Planet not counted\r\n y0 = np.asarray([earth.pos(0)[0], earth.pos(0)[1],\r\n earth.vel(0)[0] + np.cos(burn_phi)*burn_vel, earth.vel(0)[1]] + np.sin(burn_phi)*burn_vel,\r\n dtype=np.float64)\r\n\r\n # vis viva - exclusion of trajectories too close to Sun\r\n r = np.linalg.norm(y0[:2])\r\n v = np.linalg.norm(y0[2:])\r\n E = v*v/2 - GRAV*SOL_M / r\r\n L = abs(np.cross(y0[:2], y0[2:]))\r\n vmax = GRAV*SOL_M / L + np.sqrt(GRAV*SOL_M / L * GRAV*SOL_M / L + 2*E)\r\n rmin = L / vmax\r\n\r\n if rmin < AU/20:\r\n print('abort at', rmin / AU)\r\n continue\r\n\r\n a = 1/(2/r - v**2/(SOL_M*GRAV))\r\n T = 20 * 365 * 24 * 60 * 60.0\r\n if a > 0:\r\n T = min(T, 2*np.pi*np.sqrt(a**3/(SOL_M*GRAV)))\r\n\r\n print('{} {:.2f} {:.0f} {:.1f}'.format(run, a / AU, v, T/365/24/60/60))\r\n\r\n t = np.linspace(0, T, num=int(T/(24*60*60)))\r\n y = odeint(model, y0, t, mxstep=50000, h0=1e6)\r\n\r\n result = np.zeros(len(y), dtype=meas_dtype)\r\n for yy, tt, res in zip(y, t, result):\r\n r = np.linalg.norm(yy[:2])\r\n\r\n res['t'] = tt\r\n res['r'] = r\r\n res['dv'] = dv + np.abs(np.linalg.norm(yy[2:]) - np.sqrt(GRAV*SOL_M/r))\r\n\r\n # synodic period\r\n T = 2 * np.pi * r / np.sqrt(GRAV * SOL_M / r)\r\n res['phi0'] = np.mod(np.arctan2(yy[1], yy[0]) - np.mod(tt / T * 2 * np.pi, 2 * np.pi)\r\n - np.arctan2(earth.pos(0)[1], earth.pos(0)[0]) + 4*np.pi, 2 * np.pi)\r\n\r\n meas = np.concatenate([meas, result])\r\n\r\n return to_gridmap(meas)\r\n\r\n\r\ndef coords(meas):\r\n rc, vc, pc = int(meas['r'] / AU * 10 + 0.5), int(meas['dv'] / 1000 + 0.5), int(meas['phi0'] / 2 / np.pi * 100 + 0.5)\r\n return (rc, vc, pc) if max(rc, vc) < 1000 and pc < 100 else (0, 0, 0)\r\n\r\n\r\ndef coords_inv(coords):\r\n meas = np.zeros(1, dtype=meas_dtype)\r\n meas['r'] = coords[0] * AU / 10\r\n meas['dv'] = coords[1] * 1000\r\n meas['phi0'] = coords[2] * 2 * np.pi / 100\r\n return meas\r\n\r\n\r\ndef to_gridmap(meas):\r\n gridmap = np.zeros((1000, 1000, 100), dtype=np.float32) + 1e99\r\n\r\n for m in meas:\r\n gridmap[coords(m)] = np.min((gridmap[coords(m)], m['t']))\r\n\r\n return gridmap\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n if os.path.isfile('out.npz'):\r\n with np.load('out.npz') as dat:\r\n glob_grid = dat['grid']\r\n else:\r\n glob_grid = None\r\n\r\n cpus = mp.cpu_count()\r\n with mp.Pool(cpus) as p:\r\n glob_grid_vec = p.map(calc, [25 for i in range(cpus)])\r\n\r\n if glob_grid is None:\r\n glob_grid = glob_grid_vec[0]\r\n\r\n for g in glob_grid_vec:\r\n glob_grid = np.minimum(glob_grid, g)\r\n\r\n np.savez_compressed('out.npz', grid=glob_grid)\r\n\r\n fixed_ind = 20\r\n glob_2d_grid = glob_grid[fixed_ind, :, :]\r\n r, phi, t = [], [], []\r\n for i in range(glob_2d_grid.shape[0]):\r\n for j in range(glob_2d_grid.shape[1]):\r\n if glob_2d_grid[i, j] < 1e60:\r\n values = coords_inv((fixed_ind, i, j))\r\n r.append(values['dv'][0])\r\n phi.append(values['phi0'][0])\r\n t.append(glob_2d_grid[i, j])\r\n\r\n grid_r, grid_phi = np.mgrid[0:100:1000j, 0:2*np.pi:100j]\r\n grid_z0 = griddata(np.asarray([[rr/1000, pp] for rr, pp in zip(r, phi)]), np.asarray(t), (grid_r, grid_phi), method='nearest')\r\n\r\n plt.imshow(grid_z0.T, extent=(0, 2*np.pi, 0, 100), origin='lower')\r\n plt.title('Nearest')\r\n plt.show()\r\n\r\n glob_grid[glob_grid > 1e60] = 0\r\n\r\n print(glob_grid[150, :, :])\r\n\r\n glob_2d_grid = glob_grid[:, 200, :]\r\n glob_2d_grid[glob_2d_grid > 0] = 1\r\n plt.imshow(glob_2d_grid)\r\n plt.show()\r\n\r\n\r\n assert(coords(coords_inv((10, 10, 10))) == (10, 10, 10))\r\n\r\n ## plot results\r\n #plt.plot([yy[0] / AU for yy in y], [yy[1] / AU for yy in y])\r\n #plt.plot([earth.pos(tt)[0] / AU for tt in t], [earth.pos(tt)[1] / AU for tt in t])\r\n #plt.xlabel('x(t)')\r\n #plt.ylabel('y(t)')\r\n #plt.show()","sub_path":"Python/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":6298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"415907428","text":"from modules.Observer import Subject\nimport sqlite3, os, subprocess\nimport numpy as np\nfrom scipy.io.wavfile import write, read\n\n\nclass Model(Subject):\n\n def __init__(self):\n Subject.__init__(self)\n\n def create_note(self, octa, note, is_pure_note, is_harmonic, is_chord, duration=1):\n connect = sqlite3.connect(\"frequencies.db\")\n cursor = connect.cursor()\n freqs = cursor.execute(\"SELECT * FROM frequencies\")\n notes = [\"oct\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"]\n index = notes.index(note)\n\n file_path = 'Sounds/{}{}.wav'.format(note, int(octa))\n\n for f in freqs:\n freq = f[index]*(2**(int(octa)-3))\n\n print(freq)\n\n fs = 44100 # sampling rate, Hz, must be integer\n\n left_audio = (np.sin(2*np.pi*np.arange(fs*duration)*freq/fs)).astype(np.float32)\n righ_audio = (np.sin(2*np.pi*np.arange(fs*duration)*freq/fs)).astype(np.float32)\n audio = np.stack((left_audio, righ_audio), axis=1)\n\n if is_pure_note:\n write(file_path, fs, audio)\n\n if is_harmonic:\n for i in range(1, 9, 2):\n freq += 2*freq\n left_audio = (1/i)*(np.sin(2*np.pi*np.arange(fs*duration)*freq/fs)).astype(np.float32)\n righ_audio = (1/i)*(np.sin(2*np.pi*np.arange(fs*duration)*freq/fs)).astype(np.float32)\n audio += np.stack((left_audio, righ_audio), axis=1)\n \n file_path = 'Sounds/{}{}_H.wav'.format(note, int(octa))\n write(file_path, fs, audio)\n\n if is_chord:\n for i in range(4, 8, 3):\n freq *= 2**(i/12)\n\n left_audio = (1/i)*(np.sin(2*np.pi*np.arange(fs*duration)*freq/fs)).astype(np.float32)\n righ_audio = (1/i)*(np.sin(2*np.pi*np.arange(fs*duration)*freq/fs)).astype(np.float32)\n audio += np.stack((left_audio, righ_audio), axis=1)\n\n print(max(audio[:, 1]))\n file_path = 'Sounds/{}{}Major.wav'.format(note, int(octa))\n write(file_path, fs, audio)\n\n self.notify()\n\n def play_note(self, note):\n file_path = 'Sounds/{}'.format(note)\n log = os.system('aplay {}'.format(file_path))\n \n if log != 0:\n print('Note not found. You must first create the note.')\n\n def del_note(self, note):\n file_path = 'Sounds/{}'.format(note)\n os.remove(file_path)\n self.notify()\n\n def get_audio(self, note):\n file_path = 'Sounds/{}'.format(note)\n _ , audio = read(file_path)\n\n return audio[:378, 1]","sub_path":"modules/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"299109476","text":"import unittest\nfrom CsvReader import CsvReader, ClassFactory\n\n\nclass MyTestCase(unittest.TestCase):\n\n def setUp(self) -> None:\n self.csv_reader = CsvReader('Source/Addition.csv')\n\n def test_return_data(self):\n values = self.csv_reader.return_data('Value')\n self.assertIsInstance(values, list)\n test_class = ClassFactory('Value', self.csv_reader.data[0])\n for value in values:\n self.assertEqual(value.__name__, test_class.__name__)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"Tests/CSVTest.py","file_name":"CSVTest.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"9725440","text":"import cv2\nimport numpy as np\n\nimage = cv2.imread(\"face.jpg\") # busca a img pelo diretorio\nimggray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # transforma as cores da img em cinza\n\ndef detect_eye():\n eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')\n eyes = eye_cascade.detectMultiScale(imggray) #detecta objetos de diferentes tamanhos\n for (ex, ey, ew, eh) in eyes:\n roi_gray = imggray[ey:ey + eh, ex:ex + ew]\n cv2.rectangle(imggray, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)\n\n square_eye = cv2.rectangle(roi_gray, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2).copy()\n cv2.imshow(\"Only Eyes\", square_eye)\n cv2.imshow(\"Eyes\", imggray) # mostra a img em janela\n cv2.waitKey(0) # não espera nenhuma tecla para fechar a janela\n\n\ndetect_eye()","sub_path":"detect-eye.py","file_name":"detect-eye.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"171408653","text":"sent = \"Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.\"\r\n\r\nwords = sent.replace(\".\",\"\").split(\" \")\r\n\r\nsingle = [0, 4, 5, 6, 7, 8, 14, 15, 18]\r\n\r\nword_dict = {}\r\nfor i in range(len(words)):\r\n if i in single:\r\n word_dict[words[i][:2]] = words[i]\r\n else:\r\n word_dict[words[i][:1]] = words[i]\r\n\r\nprint(word_dict)","sub_path":"coffeemountain/chapter1/nlp_04.py","file_name":"nlp_04.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"606151770","text":"import det\r\nimport ctrl_panel\r\nimport key_ops\r\nimport random\r\nimport integrals\r\nimport math\r\nimport test\r\n\r\n# Provides all operations on a dictionary whose values are Det objects.\r\n# The keys are tuples whose bit representations correspond to orbital occupations.\r\n\r\ndef merge(dets_p, dets_c):\r\n\t\"\"\"Merges dets_c into dets_p.\"\"\"\r\n\t\r\n\tfor key in dets_c:\r\n\t\tif key in dets_p:\r\n\t\t\t# Parent list includes this determinant.\r\n\t\t\tdets_p[key].value += dets_c[key].value\r\n\t\t\tif dets_p[key].value == 0:\r\n\t\t\t\tdel dets_p[key]\r\n\t\t\telse:\r\n\t\t\t\tdets_p[key].flag = (abs(dets_p[key].value) >= ctrl_panel.init_crit_w_num)\r\n\t\telse:\r\n\t\t\t# Parent list does not include this determinant.\r\n\t\t\tif dets_c[key].if_survive_as_child():\r\n\t\t\t\t# The merged walker survives if the child meets survival criterions.\r\n\t\t\t\tdets_p[key] = dets_c[key]\r\n\t\t\t\tdets_p[key].set_diag_entry(key)\r\n\t\t\t\tdets_p[key].flag = (abs(dets_p[key].value) >= ctrl_panel.init_crit_w_num)\r\n\r\ndef spawn(dets_p, dets_c, key_p, spawn_map, tau, update_spawn_map_flag):\r\n\t\"\"\"Spawning of all parents on the determinant indexed by key_p.\"\"\"\r\n\t\r\n\t# Spawning.\r\n\tp_sign = (dets_p[key_p].value > 0)\r\n\tp_u_num = abs(dets_p[key_p].value)\r\n\tcount = 0\r\n\t\r\n\tfor count in range(p_u_num):\r\n\t\t# Single or double excitation.\r\n\t\trand_val = random.random()\r\n\t\tif rand_val < ctrl_panel.single_prob:\r\n\t\t\t# Single excitation.\r\n\t\t\torbs_p, key_c, sign, p_gen, orbs_diff = key_ops.single_excite(key_p)\r\n\t\t\tp_sing_or_doub = ctrl_panel.single_prob\r\n\t\telse:\r\n\t\t\t# Double excitation.\r\n\t\t\torbs_p, key_c, sign, p_gen, orbs_diff = key_ops.double_excite(key_p)\r\n\t\t\tp_sing_or_doub = 1 - ctrl_panel.single_prob\r\n\t\tmat_element = integrals.sandwich(orbs_p, orbs_diff)\r\n\t\tif not sign:\r\n\t\t\t# Accounts for a possible negative sign from permuting the spawned determinant.\r\n\t\t\tmat_element = -mat_element\r\n\t\tprob = tau * mat_element / p_gen / p_sing_or_doub\r\n\t\t\r\n\t\t# Gets the sign of children.\r\n\t\tif prob < 0:\r\n\t\t\tc_sign = p_sign\r\n\t\t\tprob = -prob\r\n\t\telse:\r\n\t\t\tc_sign = not p_sign\r\n\t\t\r\n\t\tc_num = int(prob)\r\n\t\t# At least we have c_num children.\r\n\t\t\r\n\t\tprob_frac = prob - c_num\r\n\t\trand_val = random.random()\r\n\t\tif rand_val < prob_frac:\r\n\t\t\t# One more child.\r\n\t\t\tc_num += 1\r\n\t\t\r\n\t\tif c_num != 0:\r\n\t\t\t# Add c_num children to the list.\r\n\t\t\tif not c_sign:\r\n\t\t\t\tc_num = -c_num\r\n\t\t\tif key_c in dets_c:\r\n\t\t\t\tdets_c[key_c].value += c_num\r\n\t\t\t\tif dets_c[key_c].value == 0:\r\n\t\t\t\t\tdel dets_c[key_c]\r\n\t\t\t\telse:\r\n\t\t\t\t\tdets_c[key_c].flag = dets_p[key_p].flag\r\n\t\t\telse:\r\n\t\t\t\tdets_c[key_c] = det.Det(c_num, dets_p[key_p].flag)\r\n\t\t\tif update_spawn_map_flag:\r\n\t\t\t\tkey_index_p = ctrl_panel.key_list.index(key_p)\r\n\t\t\t\tspawn_map[key_index_p][ctrl_panel.key_list.index(key_c)] += abs(c_num)\r\n\t\r\ndef die(dets_p, key_p, tau, shift):\r\n\t\"\"\"Dying/cloning of all parents on the determinant indexed by key.\"\"\"\r\n\t\r\n\tprob = tau * (dets_p[key_p].diag_entry - shift)\r\n\tp_sign = (dets_p[key_p].value > 0)\r\n\tp_u_num = abs(dets_p[key_p].value)\r\n\tcount = 0\r\n\t\r\n\tif prob < 0:\r\n\t\t# Cloning.\r\n\t\tprob = -prob\r\n\t\tprob_frac = prob - int(prob)\r\n\t\tclone_num = int(prob) * p_u_num\r\n\t\t# At least we have clone_num clones.\r\n\t\t\r\n\t\tfor count in range(p_u_num):\r\n\t\t\trand_val = random.random()\r\n\t\t\tif rand_val < prob_frac:\r\n\t\t\t\t# One more cloning event.\r\n\t\t\t\tclone_num += 1\r\n\t\tif clone_num != 0:\r\n\t\t\tif not p_sign:\r\n\t\t\t\tclone_num = -clone_num\r\n\t\t\tdets_p[key_p].value += clone_num\r\n\telse:\r\n\t\t# Dying.\r\n\t\tfor count in range(p_u_num):\r\n\t\t\trand_val = random.random()\r\n\t\t\tif rand_val < prob:\r\n\t\t\t\t# Dead.\r\n\t\t\t\tif p_sign:\r\n\t\t\t\t\tdets_p[key_p].value -= 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tdets_p[key_p].value += 1\r\n\tif dets_p[key_p].value == 0:\r\n\t\tdel dets_p[key_p]\r\n\r\ndef annih(dets_p, dets_c):\r\n\t\"\"\"Overall annihilation step.\"\"\"\r\n\t\r\n\tmerge(dets_p, dets_c)\r\n\r\ndef single_step(dets_p, spawn_map, tau, shift, update_spawn_map_flag = False):\r\n\t\"\"\"The whole process of spawning, dying and annihilation.\"\"\"\r\n\t\r\n\tdets_c = {}\r\n\t\r\n\t# Spawning and dying/cloning.\r\n\tp_keys = dets_p.keys()\r\n\tfor key_p in p_keys:\r\n\t\tspawn(dets_p, dets_c, key_p, spawn_map, tau, update_spawn_map_flag)\r\n\t\tdie(dets_p, key_p, tau, shift)\r\n\t\r\n\t# Annihilation.\r\n\tannih(dets_p, dets_c)\r\n\r\ndef count_u_num(dets):\r\n\t\"\"\"Count the unsigned number of walkers.\"\"\"\r\n\t\r\n\ttotal_u_num = 0\r\n\tfor key in dets:\r\n\t\ttotal_u_num += int(abs(dets[key].value))\r\n\treturn total_u_num\r\n\r\ndef dets_2_vec(dets):\r\n\t\"\"\"From a determinant list to a normalized eigenvector.\"\"\"\r\n\t\r\n\tvec = [0] * len(ctrl_panel.key_list)\r\n\tnorm_sq = 0\r\n\tfor i in range(len(ctrl_panel.key_list)):\r\n\t\tkey = ctrl_panel.key_list[i]\r\n\t\tif key in dets:\r\n\t\t\tnorm_sq += dets[key].value ** 2\r\n\tfor i in range(len(ctrl_panel.key_list)):\r\n\t\tkey = ctrl_panel.key_list[i]\r\n\t\tif key in dets:\r\n\t\t\tvec[i] = dets[key].value / math.sqrt(norm_sq)\r\n\treturn vec\r\n\r\ndef dot_prod(dets_1, dets_2, norm_flag):\r\n\t\"\"\"Calculate the dot product between two determinant lists.\"\"\"\r\n\t\r\n\tprod = 0\r\n\tfor key in dets_1:\r\n\t\tif key in dets_2:\r\n\t\t\tprod += dets_1[key].value * dets_2[key].value\r\n\tif norm_flag:\r\n\t\tnorm_sq_1 = dot_prod(dets_1, dets_1, False)\r\n\t\tnorm_sq_2 = dot_prod(dets_2, dets_2, False)\r\n\t\tprod = prod / math.sqrt(norm_sq_1) / math.sqrt(norm_sq_2)\r\n\treturn prod\r\n\r\ndef corr_by_proj(dets_p, ref_key):\r\n\t\"\"\"Calculates correlation energy by projection.\"\"\"\r\n\t\r\n\t# E_corr = sum_j!=o(*(/))\r\n\t# Returns numerator and denominator separately, such that they can both be averaged over iterations.\r\n\tref_orbs = key_ops.key_2_orbs(ref_key)\r\n\tnumer = 0 # Initializes numerator.\r\n\t\r\n\tfor key in dets_p:\r\n\t\tif key != ref_key:\r\n\t\t\torbs_gnd, sign_exc, orbs_diff, count = key_ops.difference(ref_key, key)\r\n\t\t\tif orbs_gnd != None:\r\n\t\t\t\tterm = integrals.sandwich(orbs_gnd, orbs_diff) * dets_p[key].value\r\n\t\t\t\tif not sign_exc:\r\n\t\t\t\t\tterm = -term\r\n\t\t\t\tnumer += term\r\n\tdenom = float(dets_p[ref_key].value) # Denominator.\r\n\treturn numer, denom\r\n\r\ndef find_ref(dets_p):\r\n\t\"\"\"Finds the determinant that has the most population.\"\"\"\r\n\t\r\n\t# This is used when a true D0 is not applicable, such that an arbitrary determinant is used as reference.\r\n\t# By running this method after sufficient iterations, the true D0 can be obtained.\r\n\tmax_num = 0\r\n\tfor key in dets_p:\r\n\t\tif max_num < abs(dets_p[key].value):\r\n\t\t\tmax_num = abs(dets_p[key].value)\r\n\t\t\tref_key = key\r\n\treturn ref_key","sub_path":"FCIQMC_v3.0/det_ops.py","file_name":"det_ops.py","file_ext":"py","file_size_in_byte":6181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"112366864","text":"from pymongo import MongoClient\nimport os\nimport time\n\n\n# MONGO_HOST = '95.85.7.219'\n# MONGO_DBNAME = 'happyhour'\n\n# MONGO_HOST = '95.85.7.219'\n# MONGO_HOST = \"db\"\n# MONGO_HOST = os.environ['DB_PORT_27017_TCP_ADDR']\n# MONGO_PORT = int(os.environ['DB_PORT_27017_TCP_PORT'])\n\n# MONGO_HOST = \"dockerhost\"\nMONGO_HOST = \"mongo\"\nMONGO_PORT = 27017\n\n# MONGO_PORT = 49155\n\nprint(MONGO_HOST + \" \" + str(MONGO_PORT))\n\n# MONGO_USERNAME = 'omegagotcha.nl'\n# MONGO_PASSWORD = 'omeganen'\nMONGO_DBNAME = 'gotcha'\n\n# db = MongoClient(MONGO_HOST, 27017)\n# con = MongoClient(\"mongodb://omegagotcha.nl:omeganen@95.85.7.219:49155/gotcha\")\n# con = MongoClient(\"db\")\n\ntime.sleep(2)\n# con = MongoClient(\n# \"db\")\ncon = MongoClient(\n MONGO_HOST, MONGO_PORT)\ndb = con[MONGO_DBNAME]\n\n# client = MongoClient(\n# os.environ['DB_PORT_27017_TCP_ADDR'],\n# 27017)\n#\n# client = MongoClient(\n# MONGO_HOST)\n# db = client.gotcha\nprint(db)","sub_path":"backend/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"324865049","text":"from django.conf.urls import url\nfrom .views import (BugWorkTimeListDaily, display_stats, BugWorkTimeListWeekly, \\\nBugWorkTimeListMonthly, CurrentBugUpvotes, OpenBugUpvotes, OpenFeaturesContributions, \\\ndisplay_feature_stats, display_upvotes)\n\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nurlpatterns = [\n url(r'^api/chart/data/daily', BugWorkTimeListDaily.as_view(), name=\"workflow_daily\"),\n url(r'^api/chart/data/weekly', BugWorkTimeListWeekly.as_view(), name=\"workflow_weekly\"),\n url(r'^api/chart/data/monthly', BugWorkTimeListMonthly.as_view(), name=\"workflow_monthly\"),\n url(r'^api/chart/data/bug/working/upvotes', CurrentBugUpvotes.as_view(), name=\"current_bugs_upvotes\"),\n url(r'^api/chart/data/bug/open/upvotes', OpenBugUpvotes.as_view(), name=\"open_bugs_upvotes\"),\n url(r'^api/chart/data/feature/open/contributions', OpenFeaturesContributions.as_view(), name=\"open_feature_contributions\"),\n \n url(r'^bugs/workflow$', display_stats, name=\"workflow\"),\n url(r'^bugs/upvotes$', display_upvotes, name=\"bug_upvotes\"),\n url(r'^features$', display_feature_stats, name=\"feature_contributions\")\n ]\n \nurlpatterns = format_suffix_patterns(urlpatterns)","sub_path":"stats/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":"12"}
+{"seq_id":"398870107","text":"\n\n#calss header\nclass _CLAMP():\n\tdef __init__(self,): \n\t\tself.name = \"CLAMP\"\n\t\tself.definitions = [u'to fasten two things together, using a clamp: ', u'If the police or another person in authority clamps a vehicle, they fix a metal device to one of its wheels, usually because it is parked illegally. The device is usually only removed when the owner pays an amount of money: ', u'If you clamp something in a particular place, you hold it there tightly: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_clamp.py","file_name":"_clamp.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"531988801","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Copyright (c) 2017 - Limber Cheng \n# @Author : Limber Cheng\n# @File : toposort.py\n# @Software: PyCharm\n\nimport sys\npostorder=[]\nvisited = []\ndef explore(v):\n visited.append(v)\n for w in adj[v]:\n if not w in visited:\n explore(w)\n postorder.append(v)\ndef dfs(adj,n):\n for v in range(n):\n if not v in visited:\n explore(v)\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n data = list(map(int, input.split()))\n n, m = data[0:2]\n data = data[2:]\n edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))\n adj = [[] for _ in range(n)]\n for (a, b) in edges:\n adj[a - 1].append(b - 1)\n dfs(adj,n)\n for i in range(len(postorder)):\n print(postorder[len(postorder)-i-1]+1,end=' ')\n print()\n","sub_path":"week2/toposort/toposort.py","file_name":"toposort.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"322074517","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Secant Method\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as pt\n\n\n# Here's a function: (Look here! No derivative.)\n\n# In[3]:\n\n\ndef f(x):\n return x**3 - x +1\n\nxmesh = np.linspace(-2, 2, 100)\npt.ylim([-3, 10])\npt.grid()\npt.plot(xmesh, f(xmesh))\n\n\n# In[7]:\n\n\nguesses = [2, 1.5]\n\n\n# Evaluate this cell many times in-place (using Ctrl-Enter)\n\n# In[30]:\n\n\n\n# grab last two guesses\nx = guesses[-1]\nxbefore = guesses[-2]\n\nslope = (f(x)-f(xbefore))/(x-xbefore)\n\n# plot approximate function\npt.plot(xmesh, f(xmesh))\npt.plot(xmesh, f(x) + slope*(xmesh-x))\npt.plot(x, f(x), \"o\")\npt.plot(xbefore, f(xbefore), \"o\")\npt.ylim([-3, 10])\npt.axhline(0, color=\"black\")\n\n# Compute approximate root\nxnew = x - f(x) / slope\nguesses.append(xnew)\nprint(xnew)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"demos/upload/nonlinear/Secant Method.py","file_name":"Secant Method.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"55714766","text":"from django.conf.urls import url\nfrom wrapper import views\n\nurlpatterns = [\n url(r'^favorites/$', views.favorite_list),\n url(r'^favorite/$', views.favorite),\n url(r'^reddit/$', views.reddit_hot_list),\n url(r'^tag/$', views.tag),\n url(r'^register/$', views.register),\n url(r'^login/$', views.login),\n]","sub_path":"reddit/wrapper/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"24494388","text":"import sklearn\nfrom sklearn.model_selection import train_test_split\nfrom keras import Sequential, optimizers\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.optimizers import Adam\nfrom keras.layers import Flatten, Dense, Conv2D, Lambda, Cropping2D, Dropout, LeakyReLU\nfrom random import shuffle, randint\nimport numpy as np\nimport cv2\nimport csv\nimport os\n\n# Load data\n# '../DrivingData02/\n\n\ndef loadData(path, changePathinCSV=False):\n samples = []\n if changePathinCSV:\n with open(path + 'driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n path = line[0]\n path_l = line[1]\n path_r = line[2]\n filename = path.split('/')[-1]\n filename_l = path_l.split('/')[-1]\n filename_r = path_r.split('/')[-1]\n line[0] = path + 'IMG/' + filename\n line[1] = path + 'IMG/' + filename_l\n line[2] = path + 'IMG/' + filename_r\n samples.append(line)\n else:\n with open(path + 'driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n samples.append(line)\n\n samples = sklearn.utils.shuffle(samples)\n return samples\n\n\ndef randomDarkener(image):\n alpha = 1\n beta = randint(-30, 0)\n res = cv2.addWeighted(image, alpha, np.zeros(\n image.shape, image.dtype), 0, beta)\n return res\n\n\ndef generator(samples, batch_size=32):\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n for i in range(3):\n name = batch_sample[i].strip()\n if os.path.isfile(name):\n image = cv2.cvtColor(\n cv2.imread(name), cv2.COLOR_BGR2RGB)\n else:\n image = cv2.imread(name)\n exit(1)\n angle = float(batch_sample[3])\n if i == 1:\n angle += 0.20\n if i == 2:\n angle -= 0.20\n images.append(image)\n angles.append(angle)\n if i == 0:\n image_flipped = np.fliplr(image)\n images.append(image_flipped)\n measurement_flipped = -angle\n angles.append(measurement_flipped)\n if randint(0, 1000) % 30 == 0:\n image = randomDarkener(image)\n images.append(image)\n angles.append(angle)\n\n # trim image to only see section with road\n X_train = np.array(images)\n y_train = np.array(angles)\n yield sklearn.utils.shuffle(X_train, y_train)\n\n\ndef CNN(train_samples, validation_samples, batch_size):\n\n model = Sequential()\n model.add(Lambda(lambda x: x / 255.0 - 0.5, input_shape=(160, 320, 3)))\n model.add(Cropping2D(cropping=((60, 25), (0, 0))))\n model.add(Conv2D(24, (5, 5), strides=(2, 2)))\n model.add(LeakyReLU(alpha=.01))\n model.add(Conv2D(36, (5, 5), strides=(2, 2)))\n model.add(LeakyReLU(alpha=.01))\n model.add(Conv2D(48, (5, 5), strides=(2, 2)))\n model.add(LeakyReLU(alpha=.01))\n model.add(Dropout(0.5))\n model.add(Conv2D(64, (3, 3)))\n model.add(LeakyReLU(alpha=.01))\n model.add(Conv2D(64, (3, 3)))\n model.add(LeakyReLU(alpha=.01))\n model.add(Dropout(0.5))\n model.add(Flatten())\n model.add(Dropout(0.5))\n model.add(Dense(100))\n model.add(Dense(50))\n model.add(Dense(10))\n model.add(Dense(1))\n model.summary()\n\n return model\n\n\ndef main():\n samples = []\n # Loading Data from 3 different folders\n # Each folder has different runs on simulator\n samples += loadData('../DrivingData/')\n samples += loadData('../DrivingData02/')\n samples += loadData('data/')\n print(len(samples))\n # Spliting the data between trainnig (80%) and validation (20%)\n train_samples, validation_samples = train_test_split(\n samples, test_size=0.2)\n\n # Setting the batch size\n batch_size = 32\n # Getting the model\n model = CNN(train_samples, validation_samples, batch_size)\n\n # Running the model, saving only the best models based on validation loss\n checkpoint = ModelCheckpoint('model-{epoch:03d}.h5',\n monitor='val_loss',\n verbose=0,\n save_best_only=True,\n mode='auto')\n\n model.compile(loss='mse', optimizer=Adam(lr=1.0e-4))\n\n train_generator = generator(train_samples, batch_size=batch_size)\n validation_generator = generator(validation_samples, batch_size=batch_size)\n\n model.fit_generator(train_generator, steps_per_epoch=len(train_samples)/batch_size, validation_data=validation_generator,\n validation_steps=len(validation_samples)/batch_size, epochs=30, callbacks=[checkpoint])\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"120749329","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 7 14:39:05 2017\n\n@author: svd\n\"\"\"\n\nimport logging\nlog = logging.getLogger(__name__)\n\nimport scipy\nimport numpy as np\nimport pickle\nimport os\nimport copy\nimport io\nimport json\nimport h5py\n\nimport urllib\n\nimport nems.utilities as ut\nfrom nems_config.defaults import DEMO_MODE\n\ntry:\n import boto3\n import nems_config.Storage_Config as sc\n AWS = sc.USE_AWS\nexcept Exception as e:\n log.info(e)\n from nems_config.defaults import STORAGE_DEFAULTS\n sc = STORAGE_DEFAULTS\n AWS = False\n\n\n\"\"\"\nload_single_model - load and evaluate a model, specified by cellid, batch and modelname\n\nexample:\n import lib.nems_main as nems\n cellid='bbl061h-a1'\n batch=291\n modelname='fb18ch100_ev_fir10_dexp_fit00'\n stack=nems.load_single_model(cellid,batch,modelname)\n stack.quick_plot()\n\n\"\"\"\n\n\ndef load_single_model(cellid, batch, modelname, evaluate=True):\n\n filename = get_file_name(cellid, batch, modelname)\n stack = load_model(filename)\n\n if evaluate:\n stack.valmode = True\n stack.evaluate()\n try:\n pass\n\n except Exception as e:\n log.info(\"Error evaluating stack\")\n log.info(e)\n\n # TODO: What to do here? Is there a special case to handle, or\n # did something just go wrong?\n\n return stack\n\n\ndef load_from_dict(batch, cellid, modelname):\n filepath = get_file_name(cellid, batch, modelname)\n sdict = load_model_dict(filepath)\n\n # Maybe move some of this to the load_model_dict function?\n stack = ns.nems_stack()\n\n stack.meta = sdict['meta']\n stack.nests = sdict['nests']\n parm_list = []\n for i in sdict['parm_fits']:\n parm_list.append(np.array(i))\n stack.parm_fits = parm_list\n # stack.cv_counter=sdict['cv_counter']\n stack.fitted_modules = sdict['fitted_modules']\n\n for i in range(0, len(sdict['modlist'])):\n stack.append(op.attrgetter(sdict['modlist'][i])(\n nm), **sdict['mod_dicts'][i])\n # stack.evaluate()\n\n stack.valmode = True\n stack.evaluate()\n # stack.quick_plot()\n return stack\n\n\ndef save_model(stack, file_path):\n\n # truncate data to save disk space\n stack2 = copy.deepcopy(stack)\n for i in range(1, len(stack2.data)):\n del stack2.data[i][:]\n\n if AWS:\n # TODO: Need to set up AWS credentials in order to test this\n # TODO: Can file key contain a directory structure, or do we need to\n # set up nested 'buckets' on s3 itself?\n s3 = boto3.resource('s3')\n # this leaves 'nems_saved_models/' as a prefix, so that s3 will\n # mimick a saved models folder\n key = file_path[len(sc.DIRECTORY_ROOT):]\n fileobj = pickle.dumps(stack2, protocol=pickle.HIGHEST_PROTOCOL)\n s3.Object(sc.PRIMARY_BUCKET, key).put(Body=fileobj)\n else:\n directory = os.path.dirname(file_path)\n\n try:\n os.stat(directory)\n except BaseException:\n os.mkdir(directory)\n\n if os.path.isfile(file_path):\n log.info(\"Removing existing model at: {0}\".format(file_path))\n os.remove(file_path)\n\n try:\n # Store data (serialize)\n with open(file_path, 'wb') as handle:\n pickle.dump(stack2, handle, protocol=pickle.HIGHEST_PROTOCOL)\n except FileExistsError:\n # delete pkl file first and try again\n log.info(\"Removing existing model at: {0}\".format(file_path))\n os.remove(file_path)\n with open(file_path, 'wb') as handle:\n pickle.dump(stack2, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n os.chmod(file_path, 0o666)\n log.info(\"Saved model to {0}\".format(file_path))\n\n\ndef save_model_dict(stack, filepath=None):\n sdict = dict.fromkeys(\n ['modlist', 'mod_dicts', 'parm_fits', 'meta', 'nests', 'fitted_modules'])\n sdict['modlist'] = []\n sdict['mod_dicts'] = []\n parm_list = []\n for i in stack.parm_fits:\n parm_list.append(i.tolist())\n sdict['parm_fits'] = parm_list\n sdict['nests'] = stack.nests\n sdict['fitted_modules'] = stack.fitted_modules\n\n # svd 2017-08-10 -- pull out all of meta\n sdict['meta'] = stack.meta\n sdict['meta']['mse_est'] = []\n\n for m in stack.modules:\n sdict['modlist'].append(m.name)\n sdict['mod_dicts'].append(m.get_user_fields())\n\n # TODO: normalization parms have to be saved as part of the normalization\n # module(s)\n try:\n d = stack.d\n g = stack.g\n sdict['d'] = d\n sdict['g'] = g\n except BaseException:\n pass\n\n # to do: this info should go to a table in celldb if compact enough\n if filepath:\n if AWS:\n s3 = boto3.resource('s3')\n key = filepath[len(sc.DIRECTORY_ROOT):]\n fileobj = json.dumps(sdict)\n s3.Object(sc.PRIMARY_BUCKET, key).put(Body=fileobj)\n else:\n with open(filepath, 'w') as fp:\n json.dump(sdict, fp)\n\n return sdict\n\n\ndef load_model_dict(filepath):\n # TODO: need to add AWS stuff\n if AWS:\n s3_client = boto3.client('s3')\n key = filepath[len(sc.DIRECTORY_ROOT):]\n fileobj = s3_client.get_object(Bucket=sc.PRIMARY_BUCKET, Key=key)\n sdict = json.loads(fileobj['Body'].read())\n else:\n with open(filepath, 'r') as fp:\n sdict = json.load(fp)\n\n return sdict\n\n\ndef load_model(file_path):\n if AWS:\n # TODO: need to set up AWS credentials to test this\n s3_client = boto3.client('s3')\n key = file_path[len(sc.DIRECTORY_ROOT):]\n fileobj = s3_client.get_object(Bucket=sc.PRIMARY_BUCKET, Key=key)\n stack = pickle.loads(fileobj['Body'].read())\n\n return stack\n else:\n try:\n # Load data (deserialize)\n with open(file_path, 'rb') as handle:\n stack = pickle.load(handle)\n log.info('stack successfully loaded')\n\n if not stack.data:\n raise Exception(\"Loaded stack from pickle, but data is empty\")\n\n return stack\n except Exception as e:\n # TODO: need to do something else here maybe? removed return stack\n # at the end b/c it was being returned w/o assignment when\n # open file failed.\n log.info(\"error loading {0}\".format(file_path))\n raise e\n\n\ndef get_file_name(cellid, batch, modelname):\n\n filename = (\n sc.DIRECTORY_ROOT + \"nems_saved_models/batch{0}/{1}/{2}.pkl\"\n .format(batch, cellid, modelname)\n )\n\n return filename\n\n\ndef get_mat_file(filename, chars_as_strings=True):\n \"\"\"\n get_mat_file : load matfile using scipy loadmat, but redirect to s3 if toggled on.\n TODO: generic support of s3 URI, not NEMS-specific\n check for local version (where, cached? before loading from s3)\n \"\"\"\n # If the file exists on the standard filesystem, just load from that.\n if os.path.exists(filename):\n log.info(\"Local file existed, loading... \\n{0}\".format(filename))\n return scipy.io.loadmat(filename, chars_as_strings=chars_as_strings)\n\n # Else, retrieve it from the default\n s3_client = boto3.client('s3')\n key = filename[len(sc.DIRECTORY_ROOT):]\n try:\n log.info(\"File not found locally, checking s3...\".format(filename))\n fileobj = s3_client.get_object(Bucket=sc.PRIMARY_BUCKET, Key=key)\n data = scipy.io.loadmat(\n io.BytesIO(fileobj['Body'].read()),\n chars_as_strings=chars_as_strings\n )\n return data\n except Exception as e:\n log.error(\"File not found on S3 or local storage: {0}\".format(key))\n raise e\n\n\ndef load_matlab_file(filename=None, chars_as_strings=True):\n \"\"\"\n load matlab file via scipy.io library\n parse the filename to determine if it's a web url or s3 address and deal \n with loading from the relevant source\n \"\"\"\n \n o=urllib.parse.urlparse(filename)\n \n if o.scheme=='https' or o.scheme=='http':\n \n response=urllib.request.urlopen(filename)\n data = scipy.io.loadmat(\n io.BytesIO(response.read()),\n chars_as_strings=chars_as_strings)\n \n elif o.scheme=='s3':\n # todo: s3 support \n pass\n #s3-us-west-2.amazonaws.com/nemspublic/sample_data/gus021d-a2_NAT_resp_fs100.mat\n s3_client = boto3.client('s3', region_name='us-west-2')\n bucket='nemspublic'\n file='sample_data/gus021d-a2_NAT_resp_fs100.mat'\n fileobj = s3_client.get_object(Bucket=bucket, Key=file)\n data = scipy.io.loadmat(\n io.BytesIO(fileobj['Body'].read()),\n chars_as_strings=chars_as_strings)\n \n else:\n data = scipy.io.loadmat(filename,\n chars_as_strings=chars_as_strings)\n \n return data\n\ndef load_matlab_matrix(filename=None, key='resp', label=None, channelaxis=None,\n eventaxis=None,timeaxis=None, repaxis=None, fs=100,\n chars_as_strings=True):\n \"\"\"\n load a single matrix out of a matlab file (loaded via load_matlab_file)\n\n \"\"\" \n if label is None:\n label=key\n \n data=load_matlab_file(filename)\n \n d=data[key]\n if d.ndim==1:\n # assume time X 1\n if timeaxis is None:\n timeaxis=0\n elif d.ndim==2:\n # assume event X time\n if eventaxis is None:\n eventaxis=0\n if timeaxis is None:\n timeaxis=1\n elif d.ndim==3 and repaxis is None:\n # assume channel X event X time\n if channelaxis is None:\n channelaxis=0\n if eventaxis is None:\n eventaxis=1\n if timeaxis is None:\n timeaxis=2\n\n elif d.ndim==3:\n # assume event X time X rep\n if eventaxis is None:\n eventaxis=0\n if timeaxis is None:\n timeaxis=1\n if repaxis is None:\n repaxis=2\n \n # create dummy dimensions if not specified\n if channelaxis is None:\n channelaxis=d.ndim\n d=np.expand_dims(d,axis=channelaxis)\n if eventaxis is None:\n eventaxis=d.ndim\n d=np.expand_dims(d,axis=eventaxis)\n \n if repaxis is None:\n d=np.transpose(d,axes=[channelaxis,eventaxis,timeaxis])\n else:\n d=np.transpose(d,axes=[channelaxis,eventaxis,timeaxis,repaxis])\n \n return d\n\n\ndef load_baphy_data(est_files=[], fs=100, parent_stack=None, avg_resp=True):\n \"\"\" load data from baphy export file. current \"standard\" data format\n for LBHB\n \n TODO: support for multiple data[] entries?? right now just \n returns a single data dictionary\n \"\"\"\n\n # load contents of Matlab data file and save in data list\n for f in est_files:\n matdata = get_mat_file(f)\n\n # go through each entry in structure array 'data'\n for s in matdata['data'][0]:\n\n data = {}\n if 'stimids' in s.dtype.names:\n # new format: stimulus events logged in stimids and\n # pulled from stim matrix or from a separate file\n tstim = s['stim']\n stimids = s['stimids']\n stimtrials = s['stimtrials']\n stimtimes = np.double(s['stimtimes'])\n stimshape = tstim.shape\n respshape = s['resp_raster'].shape\n chancount = stimshape[0]\n stimbins = np.round(stimtimes * np.double(s['stimfs']))\n stim = np.zeros([chancount, respshape[0], respshape[2]])\n eventcount = len(stimtimes)\n for ii in range(0, eventcount):\n startbin = np.int(stimbins[ii])\n stopbin = startbin + stimshape[1]\n if stimids[ii] < stimshape[2] and stopbin <= respshape[0]:\n stim[:, startbin:stopbin, stimtrials[ii] -\n 1] = tstim[:, :, stimids[ii] - 1]\n data['stim'] = stim\n\n else:\n # old format, stimulus saved as raster aligned with spikes\n data['stim'] = s['stim']\n\n try:\n data['resp'] = s['resp_raster']\n data['respFs'] = s['respfs'][0][0]\n data['stimFs'] = s['stimfs'][0][0]\n data['stimparam'] = [str(''.join(letter))\n for letter in s['fn_param']]\n data['isolation'] = s['isolation']\n data['prestim'] = s['tags'][0]['PreStimSilence'][0][0][0]\n data['poststim'] = s['tags'][0]['PostStimSilence'][0][0][0]\n data['duration'] = s['tags'][0]['Duration'][0][0][0]\n except BaseException:\n log.info(\"load_mat: alternative load. does this ever execute?\")\n data = scipy.io.loadmat(f, chars_as_strings=True)\n data['raw_stim'] = data['stim'].copy()\n data['raw_resp'] = data['resp'].copy()\n try:\n data['pupil'] = s['pupil'] / 100\n except BaseException:\n data['pupil'] = None\n try:\n data['state'] = s['state']\n except BaseException:\n data['state'] = None\n # data['tags']=s.get('tags',None)\n\n try:\n if s['estfile']:\n data['est'] = True\n else:\n data['est'] = False\n except ValueError:\n pass\n #print(\"Est/val conditions not flagged in datafile\")\n try:\n data['filestate'] = s['filestate'][0][0]\n except BaseException:\n data['filestate'] = 0\n\n # deal with extra dimensions in RDT data\n if data['stim'].ndim > 3:\n data['stim1'] = data['stim'][:, :, :, 1]\n data['stim2'] = data['stim'][:, :, :, 2]\n data['stim'] = data['stim'][:, :, :, 0]\n stimvars = ['stim', 'stim1', 'stim2']\n else:\n stimvars = ['stim']\n\n # resample if necessary\n data['fs'] = fs\n noise_thresh = 0.05\n stim_resamp_factor = int(data['stimFs'] / data['fs'])\n resp_resamp_factor = int(data['respFs'] / data['fs'])\n\n if parent_stack:\n parent_stack.unresampled = {'resp': data['resp'], 'respFs': data['respFs'], 'duration': data['duration'],\n 'poststim': data['poststim'], 'prestim': data['prestim'], 'pupil': data['pupil']}\n\n for sname in stimvars:\n # reshape stimulus to be channel X time\n data[sname] = np.transpose(data[sname], (0, 2, 1))\n\n if stim_resamp_factor in np.arange(0, 10):\n data[sname] = ut.utils.bin_resamp(\n data[sname], stim_resamp_factor, ax=2)\n\n elif stim_resamp_factor != 1:\n data[sname] = ut.utils.thresh_resamp(\n data[sname], stim_resamp_factor, thresh=noise_thresh, ax=2)\n\n # resp time (axis 0) should be resampled to match stim time\n # (axis 1)\n\n # Changed resample to decimate w/ 'fir' and threshold, as it produces less ringing when downsampling\n #-njs June 16, 2017\n if resp_resamp_factor in np.arange(0, 10):\n data['resp'] = ut.utils.bin_resamp(\n data['resp'], resp_resamp_factor, ax=0)\n if data['pupil'] is not None:\n data['pupil'] = ut.utils.bin_resamp(\n data['pupil'], resp_resamp_factor, ax=0)\n # save raw pupil-- may be somehow transposed\n # differently than resp_raw\n data['pupil_raw'] = data['pupil'].copy()\n\n elif resp_resamp_factor != 1:\n data['resp'] = ut.utils.thresh_resamp(\n data['resp'], resp_resamp_factor, thresh=noise_thresh)\n if data['pupil'] is not None:\n data['pupil'] = ut.utils.thresh_resamp(\n data['pupil'], resp_resamp_factor, thresh=noise_thresh)\n # save raw pupil-- may be somehow transposed\n # differently than resp_raw\n data['pupil_raw'] = data['pupil'].copy()\n\n # fund number of reps of each stimulus\n data['repcount'] = np.sum(\n np.isfinite(data['resp'][0, :, :]), axis=0)\n\n if parent_stack:\n parent_stack.unresampled['repcount'] = data['repcount']\n\n # average across trials\n # TODO - why does this execute(and produce a warning?)\n if data['resp'].shape[1] > 1:\n data['avgresp'] = np.nanmean(data['resp'], axis=1)\n else:\n data['avgresp'] = np.squeeze(data['resp'], axis=1)\n\n data['avgresp'] = np.transpose(data['avgresp'], (1, 0))\n\n if avg_resp is True:\n data['resp_raw'] = data['resp'].copy()\n data['resp'] = data['avgresp']\n else:\n data['stim'], data['resp'], data['pupil'], data['replist'] = ut.utils.stretch_trials(\n data)\n data['resp_raw'] = data['resp']\n\n # new: add extra first dimension to resp/pupil (and eventually pred)\n # resp,pupil,state,pred now channel X stim/trial X time\n data['resp'] = data['resp'][np.newaxis, :, :]\n\n data['behavior_condition'] = np.ones(\n data['resp'].shape) * (data['filestate'] > 0)\n data['behavior_condition'][np.isnan(data['resp'])] = np.nan\n\n if data['pupil'] is not None:\n if data['pupil'].ndim == 3:\n data['pupil'] = np.transpose(data['pupil'], (1, 2, 0))\n if avg_resp is True:\n data['state'] = np.concatenate((np.mean(data['pupil'], 0)[np.newaxis, :, :],\n data['behavior_condition']), 0)\n else:\n data['state'] = data['behavior_condition']\n\n elif data['pupil'].ndim == 2:\n data['pupil'] = data['pupil'][np.newaxis, :, :]\n # add file state as second dimension to pupil\n data['state'] = np.concatenate((data['pupil'],\n data['behavior_condition']), axis=0)\n\n else:\n data['state'] = data['behavior_condition']\n\n return data\n\n\ndef load_ecog(stack, fs=25, avg_resp=True, stimfile=None, respfile=None, resp_channels=None):\n \"\"\"\n special hard-coded loader from ECOG data from Sam\n \"\"\"\n\n cellinfo = stack.meta[\"cellid\"].split(\"-\")\n channel = int(cellinfo[1])\n\n stimfile = '/auto/data/daq/ecog/coch.mat'\n respfile = '/auto/data/daq/ecog/reliability0.1.mat'\n\n stimdata = h5py.File(stimfile, 'r')\n respdata = h5py.File(respfile, 'r')\n\n data = {}\n for name, d in respdata.items():\n #print (name)\n data[name] = d.value\n for name, d in stimdata.items():\n #print (name)\n data[name] = d.value\n data['resp'] = data['D'][channel, :, :] # shape to stim X time (25Hz)\n\n # reshape stimulus to be channel X stim X time and downsample from 400 to\n # 25 Hz\n stim_resamp_factor = int(400 / 25)\n noise_thresh = 0\n # reduce spectral sampling to speed things up\n data['stim'] = ut.utils.thresh_resamp(\n data['coch_all'], 6, thresh=noise_thresh, ax=1)\n\n # match temporal sampling to response\n data['stim'] = ut.utils.thresh_resamp(\n data['stim'], stim_resamp_factor, thresh=noise_thresh, ax=2)\n data['stim'] = np.transpose(data['stim'], [1, 0, 2])\n\n data['repcount'] = np.ones([data['resp'].shape[0], 1])\n data['pred'] = data['stim']\n data['respFs'] = 25\n data['stimFs'] = 400 # original\n data['fs'] = 25 # final, matched for both\n del data['D']\n del data['coch_all']\n\n return data\n\ndef load_factor(stack=None, fs=100, avg_resp=True, stimfile=None, respfile=None, resp_channels=None):\n\n log.info(\"Loading stim data from file {0}\".format(stimfile))\n data=load_baphy_data(est_files=[stimfile], fs=fs, avg_resp=avg_resp)\n\n # response data to paste into a \"standard\" data object\n log.info(\"Loading resp data from file {0}\".format(respfile))\n matdata = ut.io.get_mat_file(respfile)\n\n resp=matdata['lat_vars'][:,:,resp_channels]\n resp=np.transpose(resp,[2,1,0])\n data['resp']=resp\n\n return data\n\n\ndef load_site_data(stack=None, fs=100, avg_resp=True, stimfile=None, respfile=None, resp_channels=None):\n \n d=stack.meta['d']\n batch=stack.meta['batch']\n cellcount=len(d)\n \n \"\"\" load all the data for this site \"\"\"\n cellid=d['cellid'][0]\n file=ut.baphy.get_celldb_file(batch,cellid,fs=fs,stimfmt='ozgf',chancount=18)\n log.info(\"Initializing site data with file {0}\".format(file))\n \n data=load_baphy_data(est_files=[file], fs=fs, parent_stack=stack, avg_resp=avg_resp)\n \n for ii in range(1,cellcount):\n cellid=d['cellid'][ii]\n file=ut.baphy.get_celldb_file(batch,cellid,fs=fs,stimfmt='ozgf',chancount=18)\n log.info(\"Loading response: {0}\".format(file))\n data2=load_baphy_data(est_files=[file], fs=fs, parent_stack=stack, avg_resp=avg_resp)\n data['resp']=np.concatenate((data['resp'],data2['resp']),axis=0)\n \n return data\n\n\ndef load_nat_cort(fs=100, prestimsilence=0.5, duration=3, poststimsilence=0.5):\n \"\"\"\n special hard-coded loader for cortical filtered version of NAT\n\n file saved with 200 Hz fs and 3-sec duration + 1-sec poststim silence to tail off filters\n use pre/dur/post parameters to adjust size appropriately\n \"\"\"\n\n stimfile = '/auto/data/tmp/filtcoch_PCs_100.mat'\n stimfile = '/auto/users/nems/data/filtcoch_PCs_100.mat'\n stimdata = h5py.File(stimfile, 'r')\n\n data = {}\n for name, d in stimdata.items():\n #print (name)\n # if name=='S_mod':\n # S_mod=d.value\n if name == 'U_mod':\n U_mod = d.value\n # if name=='V_mod':\n # V_mod=d.value\n fs_in = 200\n noise_thresh = 0.0\n stim_resamp_factor = int(fs_in / fs)\n\n # reshape and normalize to max of approx 1\n\n data['stim'] = np.reshape(U_mod, [100, 93, 800]) / 0.05\n if stim_resamp_factor != 1:\n data['stim'] = ut.utils.thresh_resamp(\n data['stim'], stim_resamp_factor, thresh=noise_thresh, ax=2)\n s = data['stim'].shape\n prepad = np.zeros([s[0], s[1], int(prestimsilence * fs)])\n offbin = int((duration + poststimsilence) * fs)\n data['stim'] = np.concatenate(\n (prepad, data['stim'][:, :, 0:offbin]), axis=2)\n data['stimFs'] = fs_in\n data['fs'] = fs\n\n return data\n\n\ndef load_nat_coch(fs=100, prestimsilence=0.5, duration=3, poststimsilence=0.5):\n \"\"\"\n special hard-coded loader for cortical filtered version of NAT\n\n file saved with 200 Hz fs and 3-sec duration + 1-sec poststim silence to tail off filters\n use pre/dur/post parameters to adjust size appropriately\n \"\"\"\n\n stimfile = '/auto/data/tmp/coch.mat'\n stimdata = h5py.File(stimfile, 'r')\n\n data = {}\n for name, d in stimdata.items():\n if name == 'coch_all':\n coch_all = d.value\n\n fs_in = 200\n noise_thresh = 0.0\n stim_resamp_factor = int(fs_in / fs)\n\n # reduce spectral sampling to speed things up\n # data['stim']=ut.utils.thresh_resamp(coch_all,2,thresh=noise_thresh,ax=1)\n\n data['stim'] = coch_all\n data['stim'] = np.transpose(data['stim'], [1, 0, 2])\n\n if stim_resamp_factor != 1:\n data['stim'] = ut.utils.thresh_resamp(\n data['stim'], stim_resamp_factor, thresh=noise_thresh, ax=2)\n s = data['stim'].shape\n prepad = np.zeros([s[0], s[1], int(prestimsilence * fs)])\n offbin = int((duration + poststimsilence) * fs)\n data['stim'] = np.concatenate(\n (prepad, data['stim'][:, :, 0:offbin]), axis=2)\n data['stimFs'] = fs_in\n data['fs'] = fs\n\n return data\n","sub_path":"nems/utilities/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":24306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"471305334","text":"import curses\nimport time\nfrom ascii_draw import AsciiDraw\nfrom menu import Menu\nfrom inputs import Inputs\nfrom screen import Screen\n\ninputs = Inputs.getInstance()\nscreen = Screen.getInstance()\n\nclass WelcomeScreen():\n def __init__(self):\n self.welcome_msg = \"Welcome to Brown-Arch Installer 1.0\"\n \n # Create ascii-dog\n self.dog = AsciiDraw(screen.screen, \"ascii_logo\")\n\n self.init_curses_attributes()\n\n # Define menu items\n self.menu = [\"Install Arch\", \"Install Brown-Arch\"]\n\n # Create first screen menu\n self.welcome_menu = Menu(screen.screen, self.menu)\n\n # Get terminal height, width and center x,y\n self.h, self.w, self.cy, self.cx = screen.get_scr_attribs()\n\n def init_curses_attributes(self):\n # Init default text color\n curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n screen.screen.attron(curses.color_pair(1))\n\n # Init default menu choice color\n curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_GREEN)\n\n # Hide cursor\n curses.curs_set(0)\n\n def print_welcome(self, y, x, msg):\n screen.screen.addstr(int(y), int(x), msg)\n\n def print_frame(self, h, w):\n h = h - 2\n w = w - 2\n for i in range(h):\n screen.screen.addstr(i + 1, 0, \"#\")\n screen.screen.addstr(i + 1, w + 1, \"#\")\n\n for i in range(w):\n screen.screen.addstr(0, i + 1, \"#\")\n screen.screen.addstr(h + 1, i + 1, \"#\")\n\n def run(self):\n \n w = self.w\n h = self.h\n cy = self.cy\n cx = self.cx\n welcome = self.welcome_msg\n welcome_menu = self.welcome_menu\n\n while True:\n \n screen.screen.clear()\n \n self.print_welcome(\n cy / 4, cx - int(len(welcome)//2), welcome)\n self.dog.draw(welcome_menu.menu_len)\n self.print_frame(h, w)\n choice = welcome_menu.update()\n \n welcome_menu.print_centered_menu()\n \n screen.screen.refresh()\n\n key = screen.screen.getch()\n\n if key in [27, 113]:\n break\n \n inputs.update(key)\n \n if choice != None:\n return choice\n","sub_path":"welcome_screen.py","file_name":"welcome_screen.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"58356893","text":"import datetime\nimport logging\nimport sys\nimport traceback\n\nfrom django.conf import settings\nfrom django.core.mail import mail_admins\nfrom django.db.models.signals import post_save, pre_delete\n\nfrom multidb.pinning import pin_this_thread, unpin_this_thread\n\nfrom fjord.celery import app\nfrom fjord.search.index import index_chunk\nfrom fjord.search.models import Record\nfrom fjord.search.utils import from_class_path, to_class_path\n\n\nlog = logging.getLogger('i.task')\n\n\n@app.task()\ndef index_chunk_task(index, batch_id, rec_id, chunk):\n \"\"\"Index a chunk of things.\n\n :arg index: the name of the index to index to\n :arg batch_id: the name for the batch this chunk belongs to\n :arg rec_id: the id for the record for this task\n :arg chunk: a (cls_path, id_list) of things to index\n \"\"\"\n cls_path, id_list = chunk\n cls = from_class_path(cls_path)\n rec = None\n\n try:\n # Pin to master db to avoid replication lag issues and stale\n # data.\n pin_this_thread()\n\n # Update record data.\n rec = Record.objects.get(pk=rec_id)\n rec.start_time = datetime.datetime.now()\n rec.message = u'Reindexing into %s' % index\n rec.status = Record.STATUS_IN_PROGRESS\n rec.save()\n\n index_chunk(cls, id_list)\n\n rec.mark_success()\n\n except Exception:\n if rec is not None:\n rec.mark_fail(u'Errored out %s %s' % (\n sys.exc_type, sys.exc_value))\n raise\n\n finally:\n unpin_this_thread()\n\n\n# Note: If you reduce the length of RETRY_TIMES, it affects all tasks\n# currently in the celery queue---they'll throw an IndexError.\nRETRY_TIMES = (\n 60, # 1 minute\n 5 * 60, # 5 minutes\n 10 * 60, # 10 minutes\n 30 * 60, # 30 minutes\n 60 * 60, # 60 minutes\n )\nMAX_RETRIES = len(RETRY_TIMES)\n\n\n@app.task()\ndef index_item_task(cls_path, item_id, **kwargs):\n \"\"\"Index an item given it's DocType cls_path and id\"\"\"\n doctype = from_class_path(cls_path)\n retries = kwargs.get('task_retries', 0)\n log.debug('Index attempt #%s', retries)\n try:\n resp = doctype.get_model().objects.get(id=item_id)\n doc = doctype.extract_doc(resp)\n doctype.docs.bulk_index(docs=[doc])\n\n except Exception as exc:\n log.exception('Error while live indexing %s %d: %s',\n doctype, item_id, exc)\n if retries >= MAX_RETRIES:\n raise\n retry_time = RETRY_TIMES[retries]\n\n args = (cls_path, item_id)\n if not kwargs:\n # Celery requires that kwargs be non empty, but when EAGER\n # is true, it provides empty kwargs. Yay.\n kwargs['_dummy'] = True\n index_item_task.retry(args, kwargs, exc, countdown=retry_time)\n\n\n@app.task()\ndef unindex_item_task(cls_path, item_id, **kwargs):\n \"\"\"Remove item from index, given it's DocType class_path and id\"\"\"\n doctype = from_class_path(cls_path)\n try:\n doctype.docs.delete(item_id)\n\n except Exception as exc:\n retries = kwargs.get('task_retries', 0)\n log.exception('Error while live unindexing %s %d: %s',\n doctype, item_id, exc)\n if retries >= MAX_RETRIES:\n raise\n retry_time = RETRY_TIMES[retries]\n\n args = (doctype, item_id)\n if not kwargs:\n # Celery is lame. It requires that kwargs be non empty, but when\n # EAGER is true, it provides empty kwargs.\n kwargs['_dummy'] = True\n unindex_item_task.retry(args, kwargs, exc, countdown=retry_time)\n\n\ndef _live_index_handler(sender, **kwargs):\n if (not settings.ES_LIVE_INDEX\n or 'signal' not in kwargs\n or 'instance' not in kwargs):\n return\n\n instance = kwargs['instance']\n\n try:\n if kwargs['signal'] == post_save:\n cls_path = to_class_path(instance.get_doctype())\n index_item_task.delay(cls_path, instance.id)\n\n elif kwargs['signal'] == pre_delete:\n cls_path = to_class_path(instance.get_doctype())\n unindex_item_task.delay(cls_path, instance.id)\n\n except Exception:\n # At this point, we're trying to create an indexing task for\n # some response that's changed. When an indexing task is\n # created, it uses amqp to connect to rabbitmq to put the\n # new task in the queue. If a user is leaving feadback and\n # this fails (which it does with some regularity), the user\n # gets an HTTP 500 which stinks.\n #\n # The problem is exacerbated by the fact I don't know the full\n # list of exceptions that can get kicked up here. So what\n # we're going to do is catch them all, look for \"amqp\" in the\n # frames and if it's there, we'll ignore the exception and\n # send an email. We can collect reasons and narrow this down\n # at some point if that makes sense to do. If \"amqp\" is not in\n # the frames, then it's some other kind of error that we want\n # to show up, so we'll re-raise it. Sorry, user!\n #\n # In this way, users will stop seeing HTTP 500 errors during\n # rabbitmq outages.\n exc_type, exc_value, exc_tb = sys.exc_info()\n frames = traceback.extract_tb(exc_tb)\n for fn, ln, fun, text in frames:\n if 'amqp' in fn:\n # This is an amqp frame which indicates that we\n # should ignore this and send an email.\n mail_admins(\n subject='amqp error',\n message=(\n 'amqp error:\\n\\n' +\n traceback.format_exc()\n )\n )\n return\n\n # No amqp frames, so re-raise it.\n raise\n\n\ndef register_live_index(model_cls):\n \"\"\"Register a model and index for auto indexing.\"\"\"\n uid = str(model_cls) + 'live_indexing'\n post_save.connect(_live_index_handler, model_cls, dispatch_uid=uid)\n pre_delete.connect(_live_index_handler, model_cls, dispatch_uid=uid)\n # Enable this to be used as decorator.\n return model_cls\n","sub_path":"fjord/search/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":6103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"592641168","text":"\"\"\"\nDo the recalibration of the given intervals\n\"\"\"\nimport sys\nimport argparse\nimport logging\nimport tensorflow as tf\nimport numpy as np\n\nfrom decision_interval_recalibrator import DecisionIntervalRecalibrator\nfrom common import pickle_to_file, pickle_from_file, process_params, get_normal_ci, load_model\n\n\ndef parse_args(args):\n ''' parse command line arguments '''\n\n parser = argparse.ArgumentParser(description=__doc__)\n\n parser.add_argument('--data-file',\n type=str,\n default=\"_output/data.pkl\")\n parser.add_argument('--data-split-file',\n type=str,\n default=\"_output/data_split.pkl\")\n parser.add_argument('--fitted-file',\n type=str,\n default=\"_output/fitted.pkl\")\n parser.add_argument('--out-file',\n type=str,\n default=\"_output/recalibrated_coverages.pkl\")\n parser.add_argument('--log-file',\n type=str,\n default=\"_output/recalibrated_log.txt\")\n parser.add_argument('--alphas',\n type=str,\n help=\"\"\"\n Specifies which alpha values to calibrate for\n comma separated list\n \"\"\",\n default=\"0.05,0.1,0.2\")\n parser.set_defaults()\n args = parser.parse_args()\n args.alphas = process_params(args.alphas, float)\n return args\n\ndef main(args=sys.argv[1:]):\n args = parse_args(args)\n logging.basicConfig(format=\"%(message)s\", filename=args.log_file, level=logging.DEBUG)\n print(args)\n logging.info(args)\n\n # Read all data\n data_dict = pickle_from_file(args.data_file)\n # Get the appropriate datasplit\n split_dict = pickle_from_file(args.data_split_file)\n recalib_data = data_dict[\"train\"].subset(split_dict[\"recalibrate_idxs\"])\n\n # Load model\n fitted_model = load_model(args.fitted_file)\n\n coverage_dict = {}\n for alpha in args.alphas:\n recalibrator = DecisionIntervalRecalibrator(fitted_model, alpha)\n inference_dict = recalibrator.recalibrate(recalib_data)\n print(\"RECALIB INF DICT\", inference_dict[\"cov_given_accept\"])\n est_cov_given_accept = inference_dict[\"cov_given_accept\"][\"mean\"]\n logging.info(\"Alpha %f, ideal cov %f, est cov|accept %f\", alpha, 1 - alpha, est_cov_given_accept)\n logging.info(get_normal_ci(inference_dict[\"cov_given_accept\"]))\n coverage_dict[alpha] = inference_dict\n pickle_to_file(coverage_dict, args.out_file)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"do_recalibration.py","file_name":"do_recalibration.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"37228704","text":"#Não precisa pegar dados do usuario\n\n\ndef miracle(intT: tuple):\n impList = [x for x in intT if(x % 2 != 0)]\n posParT = tuple(x for x in intT if intT.index(x) % 2 == 0) # pos: 0, 2, 4, ...\n return impList, posParT\n\n\nnumbsT = tuple(range(100)) # tuple(str.split(input('Digite numeros: ')))\n # numbsT = tuple(int(x) for x in numbsT)\nimplist, posParT = miracle(numbsT)\nprint('lista com impares: ', implist)\nprint('tupla de index par: ', posParT)\n","sub_path":"Samples/Exercice/AT-DR2/dr2-at-6.py","file_name":"dr2-at-6.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"497881389","text":"\"\"\"Handles uploads of .RAW files.\"\"\"\nfrom werkzeug import secure_filename\nfrom cravattdb import app\nimport pathlib\n\n\ndef upload(files, username, name):\n name = secure_filename(name)\n username = secure_filename(username)\n\n path = pathlib.Path(\n app.instance_path,\n 'processing',\n username,\n name\n )\n\n path.mkdir(parents=True)\n\n for i, f in enumerate(sorted(files, key=lambda f: f.filename)):\n # only allow .raw extension\n filename = secure_filename(f.filename)\n filepath = pathlib.PurePath(filename)\n\n if filepath.suffix.lower() == '.raw':\n # rename raw files to reflect dataset name\n # adding _INDEX to please cimage\n filename = name + '_{}.raw'.format(i + 1)\n f.save(str(path.joinpath(filename)))\n\n return name, path\n","sub_path":"cravattdb/auto/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"357629170","text":"import os\nfrom pathlib import Path\nimport re\nimport shutil\n\nfrom invoke import task, Exit\ntry:\n from pabot import pabot\n import pytest\n from robot.libdoc import libdoc\nexcept ModuleNotFoundError:\n print('Assuming that this is for \"inv deps\" command and ignoring error.')\n\nroot_dir = Path(os.path.dirname(__file__))\natest_output = root_dir / \"atest\" / \"output\"\ndist_dir = root_dir / \"dist\"\nbuild_dir = root_dir / \"build\"\nproto_sources = (root_dir / \"protobuf\").glob(\"*.proto\")\npython_src_dir = root_dir / \"Browser\"\npython_protobuf_dir = python_src_dir / \"generated\"\nnode_protobuf_dir = root_dir / \"node\" / \"playwright-wrapper\" / \"generated\"\nnode_dir = root_dir / \"node\"\nnode_timestamp_file = node_dir / \".built\"\nnode_lint_timestamp_file = node_dir / \".linted\"\npython_lint_timestamp_file = python_src_dir / \".linted\"\n\n\n@task\ndef deps(c):\n c.run(\"pip install -U pip\")\n c.run(\"pip install -r Browser/dev-requirements.txt\")\n c.run(\"pip install -r Browser/requirements.txt\")\n c.run(\"yarn\")\n\n\n@task\ndef clean(c):\n for target in [dist_dir, build_dir, python_protobuf_dir, node_protobuf_dir]:\n if target.exists():\n shutil.rmtree(target)\n for timestamp_file in [\n node_timestamp_file,\n node_lint_timestamp_file,\n python_lint_timestamp_file,\n ]:\n timestamp_file.unlink(missing_ok=True)\n\n\n@task\ndef protobuf(c):\n if not python_protobuf_dir.exists():\n python_protobuf_dir.mkdir()\n c.run(f\"touch {python_protobuf_dir / '__init__.py'}\")\n if not node_protobuf_dir.exists():\n node_protobuf_dir.mkdir()\n gen_timestamp_file = python_protobuf_dir / \".generated\"\n if _sources_changed(proto_sources, gen_timestamp_file):\n _python_protobuf_gen(c)\n _node_protobuf_gen(c)\n gen_timestamp_file.touch()\n else:\n print(\"no changes in .proto files, skipping protobuf build\")\n\n\ndef _python_protobuf_gen(c):\n c.run(\n f\"python -m grpc_tools.protoc -I protobuf --python_out=Browser/generated --grpc_python_out={python_protobuf_dir} --mypy_out={python_protobuf_dir} protobuf/*.proto\"\n )\n genfile = python_protobuf_dir / \"playwright_pb2_grpc.py\"\n content = (\n open(genfile)\n .read()\n .replace(\n \"import playwright_pb2 as playwright__pb2\",\n \"from Browser.generated import playwright_pb2 as playwright__pb2\",\n )\n )\n with open(genfile, \"w\") as outfile:\n outfile.write(content)\n\n\ndef _node_protobuf_gen(c):\n protoc_plugin = root_dir / \"node_modules\" / \".bin\" / \"grpc_tools_node_protoc_plugin\"\n protoc_ts_plugin = root_dir / \"node_modules\" / \".bin\" / \"protoc-gen-ts\"\n c.run(\n f\"yarn run grpc_tools_node_protoc \\\n\t\t--js_out=import_style=commonjs,binary:{node_protobuf_dir} \\\n\t\t--grpc_out={node_protobuf_dir} \\\n\t\t--plugin=protoc-gen-grpc={protoc_plugin} \\\n\t\t-I ./protobuf \\\n\t\tprotobuf/*.proto\"\n )\n c.run(\n f\"yarn run grpc_tools_node_protoc \\\n\t\t--plugin=protoc-gen-ts={protoc_ts_plugin} \\\n\t\t--ts_out={node_protobuf_dir} \\\n\t\t-I ./protobuf \\\n\t\tprotobuf/*.proto\"\n )\n\n\n@task(protobuf)\ndef node_build(c):\n if _sources_changed(node_dir.glob(\"**/*.ts\"), node_timestamp_file):\n c.run(\"yarn build\")\n node_timestamp_file.touch()\n else:\n print(\"no changes in .ts files, skipping node build\")\n\n\n@task(protobuf, node_build)\ndef build(c):\n c.run(\"python -m Browser.gen_stub\")\n\n\ndef _sources_changed(source_files, timestamp_file):\n if timestamp_file.exists():\n last_built = timestamp_file.lstat().st_mtime\n src_last_modified = [f.lstat().st_mtime for f in source_files]\n return not all([last_built >= modified for modified in src_last_modified])\n return True\n\n\n@task(build)\ndef watch(c):\n c.run(\"yarn watch\")\n\n\n@task\ndef utest(c):\n status = pytest.main()\n raise Exit()\n\n\n@task\ndef utest_watch(c):\n c.run(\"ptw --ignore ./node_modules --ignore ./.venv\")\n\n\n@task\ndef clean_atest(c):\n if atest_output.exists():\n shutil.rmtree(atest_output)\n\n\n@task(clean_atest)\ndef atest(c):\n _run_robot(\n [\"--pythonpath\", \".\",]\n )\n\n\n@task(clean_atest)\ndef atest_global_pythonpath(c):\n _run_robot()\n\n\n# Running failed tests can't clean be cause the old output.xml is required for parsing which tests failed\n@task()\ndef atest_failed(c):\n _run_robot([\"--rerunfailed\", \"atest/output/output.xml\"])\n\n\ndef _run_robot(extra_args=None):\n os.environ[\"ROBOT_SYSLOG_FILE\"] = str(atest_output / \"syslog.txt\")\n pabot_args = [\"--pabotlib\", \"--verbose\"]\n default_args = [\n \"--exclude\",\n \"Not-Implemented\",\n \"--loglevel\",\n \"DEBUG\",\n \"--outputdir\",\n str(atest_output),\n \"atest/test\",\n ]\n pabot.main(pabot_args + (extra_args or []) + default_args)\n\n\n@task\ndef lint_python(c):\n all_py_sources = list(python_src_dir.glob(\"**/*.py\")) + list(\n (root_dir / \"utest\").glob(\"**/*.py\")\n )\n if _sources_changed(all_py_sources, python_lint_timestamp_file):\n c.run(\"mypy --config-file Browser/mypy.ini Browser/ utest/\")\n c.run(\"black --config Browser/pyproject.toml Browser/\")\n c.run(\"flake8 --config Browser/.flake8 Browser/ utest/\")\n c.run(\"isort Browser/\")\n python_lint_timestamp_file.touch()\n else:\n print(\"no changes in .py files, skipping python lint\")\n\n\n@task\ndef lint_node(c):\n if _sources_changed(node_dir.glob(\"**/*.ts\"), node_lint_timestamp_file):\n c.run(\"yarn run lint\")\n node_lint_timestamp_file.touch()\n else:\n print(\"no changes in .ts files, skipping node lint\")\n\n\n@task\ndef lint_robot(c):\n c.run(\"python -m robot.tidy --recursive atest/test\")\n\n\n@task(lint_python, lint_node, lint_robot)\ndef lint(c):\n pass\n\n\n@task\ndef docker(c):\n c.run(\"docker build --tag rfbrowser --file atest/docker/Dockerfile .\")\n\n\n@task(clean_atest, build)\ndef docker_test(c):\n c.run(\n \"docker run -it --rm --ipc=host --security-opt seccomp=atest/docker/chrome.json -v $(shell pwd)/atest/:/atest rfbrowser robot --loglevel debug --exclude Not-Implemented -d /atest/output /atest/test\"\n )\n\n\n@task(build)\ndef run_test_app(c):\n c.run(\"node node/dynamic-test-app/dist/server.js\")\n\n\n@task\ndef docs(c):\n libdoc(\"Browser\", str(root_dir / \"docs\" / \"Browser.html\"))\n\n\n@task(clean, build, docs)\ndef package(c):\n shutil.copy(root_dir / \"package.json\", root_dir / \"Browser\" / \"wrapper\")\n c.run(\"python setup.py sdist bdist_wheel\")\n\n\n@task(package)\ndef release(c):\n c.run(\"python -m twine upload --repository pypi dist/*\")\n\n\n@task\ndef version(c, version):\n if not version:\n print(\"Give version with inv version \")\n py_version_file = root_dir / \"Browser\" / \"version.py\"\n py_version_matcher = re.compile(\"VERSION = .*\")\n _replace_version(py_version_file, py_version_matcher, f'VERSION = \"{version}\"')\n node_version_file = root_dir / \"package.json\"\n node_version_matcher = re.compile('\"version\": \".*\"')\n _replace_version(node_version_file, node_version_matcher, f'\"version\": \"{version}\"')\n workflow_file = root_dir / \".github\" / \"workflows\" / \"python-package.yml\"\n workflow_version_matcher = re.compile(\"VERSION: .*\")\n _replace_version(workflow_file, workflow_version_matcher, f\"VERSION: {version}\")\n\n\ndef _replace_version(filepath, matcher, version):\n content = filepath.open().read()\n with open(filepath, \"w\") as out:\n out.write(matcher.sub(version, content))\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":7426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"229115635","text":"import tensorflow as tf\nimport numpy as np\n\nfrom opennmt.utils import transformer\n\n\nclass TransformerTest(tf.test.TestCase):\n\n def testScaledDotAttention(self):\n batch_size = 3\n values_length = [5, 3, 7]\n queries_length = [8, 6, 10]\n depth = 20\n\n queries = tf.placeholder_with_default(\n np.random.randn(batch_size, max(queries_length), depth).astype(np.float32),\n shape=(None, None, depth))\n values = tf.placeholder_with_default(\n np.random.randn(batch_size, max(values_length), depth).astype(np.float32),\n shape=(None, None, depth))\n keys = values\n\n context, attn = transformer.scaled_dot_attention(\n queries,\n keys,\n values,\n tf.estimator.ModeKeys.PREDICT,\n values_length=tf.constant(values_length))\n\n with self.test_session() as sess:\n context, attn = sess.run([context, attn])\n self.assertTupleEqual((batch_size, max(queries_length), depth), context.shape)\n self.assertTupleEqual((batch_size, max(queries_length), max(values_length)), attn.shape)\n\n for i in range(batch_size):\n length = values_length[i]\n padding_length = max(values_length) - length\n if padding_length > 0:\n self.assertEqual(0.0, np.sum(attn[i, :, length:max(values_length)]))\n\n def testMaskedScaledDotAttention(self):\n batch_size = 3\n queries_length = [8, 6, 10]\n depth = 20\n\n queries = tf.placeholder_with_default(\n np.random.randn(batch_size, max(queries_length), depth).astype(np.float32),\n shape=(None, None, depth))\n\n context, attn = transformer.scaled_dot_attention(\n queries,\n queries,\n queries,\n tf.estimator.ModeKeys.PREDICT,\n values_length=tf.constant(queries_length),\n mask_future=True)\n\n with self.test_session() as sess:\n context, attn = sess.run([context, attn])\n illegal_connections = np.triu_indices(max(queries_length), 1)\n for i in range(batch_size):\n self.assertEqual(0.0, np.sum(attn[i][illegal_connections]))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n","sub_path":"opennmt/tests/transformer_test.py","file_name":"transformer_test.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"323589312","text":"#The number of rounds the user has won\n#Number of user's selected weapon (Rock,Paper,Scissors)\n#Number of rounds computer has won\n#Number of rounds that are tied ties\nr = 0\np = 0\ns = 0\nuserScore = {\n \"Wins\": 0,\n \"Tie\": 0,\n \"Loss\": 0\n}\nuserChoice = {\n \"Rock\": 0,\n \"Paper\": 0,\n \"Scissor\": 0\n}\ncomputerScore = {\n \"Wins\": 0,\n \"Tie\": 0,\n \"Loss\": 0\n}\n#print(userScore, computerScore)","sub_path":"score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"287296168","text":"import numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\nsns.set(style=\"whitegrid\", color_codes=True)\n\n# np.random.seed(sum(map(ord, \"categorical\")))\n# titanic = sns.load_dataset(\"titanic\")\n\n# d = {'number of observations': [26, 18, 15, 11, 10, 9, 5, 4, 4, 3],\n# 'categories_db': [\"building\",\n# \"floor device\",\n# \"facility/site/\\nplant\",\n# \"trade\",\n# \"room number \\ndevice\",\n# \"building section\",\n# \"zone\",\n# \"production line\",\n# \"information focus\",\n# \"business entity/\\ntype of cost\"]}\n\nd = {'Anzahl der Beobachtungen': [26, 18, 15, 11, 10, 9, 5, 4, 4, 3],\n 'Kategorien': [\"Gebäude\",\n \"Geschoss Gerät\",\n \"Liegenschaft/Standort/\\nWerk\",\n \"Gewerk\",\n \"Raumnummer \\nGerät\",\n \"Gebäudeteil \\nGerät\",\n \"Zone\",\n \"Fertigungslinie\",\n \"Informationsschwerpunkt\",\n \"Wirtschaftseinheit/\\nKostengruppe\"]}\n\n\n\n\n\ndf = pd.DataFrame(data=d)\nsns.set_context(\"talk\", font_scale=2.3)\n#clrs = ['grey' if (x == 3) else \"OrRd_r\" for x in df.values ]\nfig, ax = plt.subplots()\n# fig.set_size_inches(16, 9)\nfig.set_size_inches(32, 9)\npal = sns.color_palette('PuBu_r', 10)\nabc=pal.as_hex()\nabc[3]=\"#CD2626\"\n\n# plot=sns.barplot(x='categories_db',\n# y='number of observations',\n# # palette=\"OrRd_r\",\n# palette=abc,\n# data=df)\n\nplot=sns.barplot(x='Kategorien',\n y='Anzahl der Beobachtungen',\n palette=abc,\n data=df)\n\n\n# plt.xlabel('categories_db', fontweight='bold')\n# plt.ylabel('number of observations', fontweight='bold')\n\nplt.xlabel('Kategorien', fontweight='bold')\nplt.ylabel('Anzahl der Beobachtungen', fontweight='bold')\n\n\nax.set_ylim([0, 30])\nplot.set_xticklabels(plot.get_xticklabels(), \n rotation=60,\n ha=\"right\",\n rotation_mode='anchor')\n\n\n\n#plot.set_size_inches(11.7, 8.27)\nfig.savefig('plot_categories_standards.png', bbox_inches='tight')\n","sub_path":"Examples/BPACS/Plots_BUDO/bar_chart_budo.py","file_name":"bar_chart_budo.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"632488090","text":"from flask import Flask, request, jsonify\napp = Flask(__name__)\n\n@app.route('/login', methods=['POST'])\ndef handleLogin():\n login_request = request.json\n print(login_request)\n output = {\n token: 'fake-token-i-made'\n }\n return jsonify(output)\n\n\n@app.route('/add', methods=['POST'])\ndef handleAdd():\n i = request.json\n print(i)\n numbers = i['numbers']\n answer = sum(numbers)\n output = {\n 'output': answer\n }\n return jsonify(output)\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"486654595","text":"import argparse, os, time, pickle\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nimport utils \nfrom DIWAE import DIWAE\n\ndef train(model, args, data_loader_tr, data_loader_vl):\n\n if args.gpu_mode:\n model.cuda()\n\n print('---------- Networks architecture -------------')\n utils.print_network(model)\n print('-----------------------------------------------')\n\n optimizer = optim.Adam(model.parameters(), lr=args.lr, betas=(args.beta1, args.beta2))\n\n\n\n train_hist = {}\n train_hist['tr_loss'] = []\n train_hist['vl_loss'] = []\n train_hist['per_epoch_time'] = []\n train_hist['total_time'] = []\n\n model.train()\n print('training start!!')\n start_time = time.time()\n for epoch in range(args.epoch):\n\n model.train()\n epoch_start_time = time.time()\n for iter, (x_, y_) in enumerate(data_loader_tr):\n if iter * args.batch_size < 50000:\n if iter == data_loader_tr.dataset.__len__() // args.batch_size:\n break\n\n if args.gpu_mode:\n x_ = Variable(x_.cuda())\n else:\n x_ = Variable(x_)\n\n # update G network\n optimizer.zero_grad()\n\n recon_batch, mu, logvar, Z = model(x_)\n lle, loss = model.loss_function(recon_batch, x_, Z, mu, logvar)\n train_hist['tr_loss'].append(lle.data[0])\n lle.backward()\n \n # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.\n torch.nn.utils.clip_grad_norm(model.parameters(), args.clip)\n optimizer.step()\n\n train_hist['per_epoch_time'].append(time.time() - epoch_start_time)\n visualize_results(model, epoch+1, args)\n\n model.eval()\n for iter, (x_, y_) in enumerate(data_loader_vl):\n if iter * args.batch_size <= 10000:\n if iter == data_loader_vl.dataset.__len__() // args.batch_size:\n break\n\n if args.gpu_mode:\n x_ = Variable(x_.cuda())\n else:\n x_ = Variable(x_)\n \n recon_batch, mu, logvar, z = model(x_, testF=True)\n lle, _ = model.loss_function(recon_batch, x_, z, mu, logvar)\n elbo = model.elbo(recon_batch[:,0], x_, mu, logvar)\n train_hist['vl_loss'].append(lle.data[0])\n\n\n if ((iter + 1) % 100) == 0:\n print(\"Epoch: [%2d] [%4d/%4d] Train loss: %.8f Valid lle (loss) %.8f Elbo %.8f\" %\n ((epoch + 1), \\\n (iter + 1), \\\n len(data_loader_vl.dataset) // args.batch_size, \\\n train_hist['tr_loss'][-1],\\\n train_hist['vl_loss'][-1],\\\n elbo.data[0]))\n\n if epoch % 25 :\n save(model, epoch, args.save_dir, args.dataset, \\\n args.model_type, args.batch_size, train_hist)\n\n train_hist['total_time'].append(time.time() - start_time)\n print(\"Avg one epoch time: %.2f, total %d epochs time: %.2f\" % \\\n (np.mean(train_hist['per_epoch_time']),\n epoch, train_hist['total_time'][0]))\n print(\"Training finish!... save training results\")\n\n save(model, epoch, args.save_dir, args.dataset, args.model_type, \\\n args.batch_size, train_hist)\n utils.generate_animation(args.result_dir + '/' + args.dataset + '/' \\\n + args.model_type + '/' + args.model_type, epoch)\n utils.loss_plot(train_hist, os.path.join(args.save_dir, args.dataset, \\\n args.model_type), args.model_type)\n\n\ndef visualize_results(model, epoch, args, sample_num=100, fix=True):\n model.eval()\n\n if not os.path.exists(args.result_dir + '/' + args.dataset + '/' + args.model_type):\n os.makedirs(args.result_dir + '/' + args.dataset + '/' + args.model_type)\n\n tot_num_samples = min(sample_num, args.batch_size)\n image_frame_dim = int(np.floor(np.sqrt(tot_num_samples)))\n\n if fix:\n \"\"\" fixed noise \"\"\"\n samples = model.decode(model.sample_z_)\n else:\n \"\"\" random noise \"\"\"\n if args.gpu_mode:\n sample_z_ = Variable(torch.rand((args.batch_size, 1, args.z_dim)).cuda(), volatile=True)\n else:\n sample_z_ = Variable(torch.rand((args.batch_size, 1, args.z_dim)), volatile=True)\n\n samples = model.sample(sample_z_)\n\n N,T,C,IW,IH = samples.size()\n samples = samples.view([N,C,IW,IH])\n if args.gpu_mode:\n samples = samples.cpu().data.numpy().transpose(0, 2, 3, 1)\n else:\n samples = samples.data.numpy().transpose(0, 2, 3, 1)\n\n utils.save_images(samples[:image_frame_dim * image_frame_dim, :, :, :], [image_frame_dim, image_frame_dim],\n args.result_dir + '/' + args.dataset + '/' + args.model_type + '/' + args.model_type + '_epoch%03d' % epoch + '.png')\n\n\ndef save(model, epoch, save_dir, dataset, model_type, batch_size, train_hist):\n save_dir = os.path.join(save_dir, dataset, model_type)\n\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n torch.save(model.state_dict(), os.path.join(save_dir, model_type + '_encoder_epoch' + str(epoch)+'_batch_sz' + str(batch_size)+'.pkl'))\n\n with open(os.path.join(save_dir, model_type + '_history.pkl'), 'wb') as f:\n pickle.dump(train_hist, f)\n\n\ndef load(model, save_dir, dataset='MNIST', model_type='IWAE'):\n save_dir = os.path.join(save_dir, dataset, model_type)\n model.load_state_dict(torch.load(os.path.join(save_dir, model_type + '.pkl')))\n\n\n\n\n\n\"\"\"parsing and configuration\"\"\"\ndef parse_args():\n desc = \"Pytorch implementation of DIWAE collections\"\n parser = argparse.ArgumentParser(description=desc)\n\n parser.add_argument('--model_type', type=str, default='IWAE',\n choices=['IWAE', 'DIWAE'],\n help='The type of IWAE')#, required=True)\n parser.add_argument('--dataset', type=str, default='mnist', choices=['mnist', 'fmnist'],\n help='The name of dataset')\n parser.add_argument('--epoch', type=int, default=1000, help='The number of epochs to run')\n parser.add_argument('--batch_size', type=int, default=100, help='The size of batch')\n parser.add_argument('--save_dir', type=str, default='models',\n help='Directory name to save the model')\n parser.add_argument('--result_dir', type=str, default='results',\n help='Directory name to save the generated images')\n parser.add_argument('--log_dir', type=str, default='logs',\n help='Directory name to save training logs')\n parser.add_argument('--arch_type', type=str, default='fc',\\\n help=\"'conv' | 'fc'\")\n parser.add_argument('--num_sam', type=float, default=5)\n parser.add_argument('--z_dim', type=float, default=128)\n parser.add_argument('--lr', type=float, default=3e-4)\n parser.add_argument('--beta1', type=float, default=0.9)\n parser.add_argument('--beta2', type=float, default=0.999)\n parser.add_argument('--clip', type=float, default=5.0)\n parser.add_argument('--gpu_mode', type=bool, default=True)\n\n return check_args(parser.parse_args())\n\n\n\"\"\"checking arguments\"\"\"\ndef check_args(args):\n # --save_dir\n if not os.path.exists(args.save_dir):\n os.makedirs(args.save_dir)\n\n # --result_dir\n if not os.path.exists(args.result_dir):\n os.makedirs(args.result_dir)\n\n # --result_dir\n if not os.path.exists(args.log_dir):\n os.makedirs(args.log_dir)\n\n # --epoch\n try:\n assert args.epoch >= 1\n except:\n print('number of epochs must be larger than or equal to one')\n\n # --batch_size\n try:\n assert args.batch_size >= 1\n except:\n print('batch size must be larger than or equal to one')\n\n return args\n\n\n\"\"\"main\"\"\"\ndef main():\n # parse arguments\n args = parse_args()\n if args is None:\n exit()\n\n\n # declare instance for IWAE\n if args.model_type == 'IWAE' or args.model_type == 'DIWAE':\n model = DIWAE(args)\n else:\n raise Exception(\"[!] There is no option for \" + args.model_type)\n\n # load dataset\n if args.dataset == 'mnist':\n data_loader_tr = DataLoader(datasets.MNIST('data/mnist', train=True, download=True,\n transform=transforms.Compose(\n [transforms.ToTensor()])),\n batch_size=args.batch_size, shuffle=False)\n\n data_loader_vl = DataLoader(datasets.MNIST('data/mnist', train=False, download=True,\n transform=transforms.Compose(\n [transforms.ToTensor()])),\n batch_size=args.batch_size, shuffle=False)\n elif args.dataset == 'fmnist':\n data_loader_tr = DataLoader(datasets.FashionMNIST('data/fashion-mnist', train=True, download=True,\n transform=transforms.Compose(\n [transforms.ToTensor()])),\n batch_size=args.batch_size, shuffle=False)\n\n data_loader_vl = DataLoader(datasets.FashionMNIST('data/fashion-mnist', train=False, download=True,\n transform=transforms.Compose(\n [transforms.ToTensor()])),\n batch_size=args.batch_size, shuffle=False)\n\n\n # launch the graph in a session\n train(model, args, data_loader_tr, data_loader_vl)\n print(\" [*] Training finished!\")\n\n # visualize learned generator\n #model.visualize_results(args.epoch)\n print(\" [*] Testing finished!\")\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"main_iwae.py","file_name":"main_iwae.py","file_ext":"py","file_size_in_byte":10390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"632840685","text":"#python\n\nimport openpyxl\n\n#load the workbook\nwb = openpyxl.load_workbook('file.xlsx')\n\n# save the workbook as \"new_file.xlxs\"\n#wb.save('new_file.xlsx')\n\n# get the sheets in the workbook\n#print wb.get_sheet_names()\n\nws = wb.active\n\n# print the title of the active worksheet\n#print ws.titlep\n\n#print the content of cell A1\nws['A2'].value = \"test\"\n\nwb.save('newfile.xlsx')\n","sub_path":"file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"61037966","text":"\r\n# Testing for python database server\r\n#\r\n# submits post request to pythonanywhere\r\n#\r\n\r\n# importing the requests library\r\nimport requests\r\n\r\n# api-endpoint\r\nURL = \"http://Npgreader2.pythonanywhere.com\"\r\n\r\n# set up params\r\nqueryType = \"Exact\"\r\nfoodName = \"bagelswheat\"\r\n\r\n# defining a params dict for the parameters to be sent to the API\r\nPARAMS = {'queryType':queryType,'parameters':foodName}\r\nheader = {'Content-Type':'application/json'};\r\n\r\n\r\n# sending post request and saving the response as response object\r\nr = requests.post(url = URL, json = PARAMS, headers = header)\r\n\r\n# extracting data in json format\r\nprint(r);\r\nprint(r.text);\r\ndata = r.json()\r\nprint(data);\r\nprint(data['sanity']);\r\n","sub_path":"html/PYTHON_SQL/pythontest3.py","file_name":"pythontest3.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"427426827","text":"import pygame\n\npygame.init()\n\nwindow = pygame.display.set_mode([1280, 720])\npygame.display.set_caption(\"Football Pong\")\n\nwin = pygame.image.load(\"assets/win.png\")\n\nscore1 = 0\nscore1_image = pygame.image.load(\"assets/score/0.png\")\nscore2 = 0\nscore2_image = pygame.image.load(\"assets/score/0.png\")\n\nfield = pygame.image.load(\"assets/field.png\")\n\nplayer1 = pygame.image.load(\"assets/player1.png\")\nplayer1_y = 290\nplayer1_moveup = False\nplayer1_movedown = False\n\nplayer2 = pygame.image.load(\"assets/player2.png\")\nplayer2_y = 290\n\nball = pygame.image.load(\"assets/ball.png\")\nball_x = 617\nball_y = 337\nball_dir = -6\nball_dir_y = 1\n\n\ndef player_move():\n global player1_y\n\n if player1_moveup and player1_y > 0:\n player1_y -= 10\n\n if player1_movedown and player1_y < 575:\n player1_y += 10\n\n\ndef player2_move():\n global player2_y\n player2_y = ball_y\n\n\ndef move_ball():\n global ball_x\n global ball_y\n global ball_dir\n global ball_dir_y\n global score1\n global score1_image\n global score2\n global score2_image\n\n ball_x += ball_dir\n ball_y += ball_dir_y\n\n if ball_x < 120:\n if player1_y < ball_y + 23 and player1_y + 146 > ball_y:\n ball_dir *= -1\n ball_dir += 2\n\n if ball_x > 1100:\n if player2_y < ball_y + 23 and player2_y + 146 > ball_y:\n ball_dir *= -1\n ball_dir -= 2\n\n if ball_y > 670:\n ball_dir_y *= -1\n elif ball_y < 0:\n ball_dir_y *= -1\n\n if ball_x < -50:\n ball_x = 617\n ball_y = 337\n ball_dir *= -1\n ball_dir_y *= -1\n score2 += 1\n score2_image = pygame.image.load(f\"assets/score/{score2}.png\")\n ball_dir = -6\n\n elif ball_x > 1320:\n ball_x = 617\n ball_y = 337\n ball_dir *= -1\n ball_dir_y *= -1\n score1 += 1\n score1_image = pygame.image.load(f\"assets/score/{score1}.png\")\n ball_dir = -6\n\n\ndef draw():\n if score1 or score2 < 9:\n window.blit(field, (0, 0))\n window.blit(player1, (50, player1_y))\n window.blit(player2, (1150, player2_y))\n window.blit(ball, (ball_x, ball_y))\n window.blit(score1_image, (500, 50))\n window.blit(score2_image, (710, 50))\n move_ball()\n player_move()\n player2_move()\n else:\n window.blit(win, (300, 330))\n\n\nloop = True\nwhile loop:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n loop = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP or event.key == pygame.K_w:\n player1_moveup = True\n if event.key == pygame.K_DOWN or event.key == pygame.K_s:\n player1_movedown = True\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_UP or event.key == pygame.K_w:\n player1_moveup = False\n if event.key == pygame.K_DOWN or event.key == pygame.K_s:\n player1_movedown = False\n\n draw()\n pygame.display.update()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"207053771","text":"import numpy as np\nimport os\nfrom ctypes import *\nfrom scipy import integrate, LowLevelCallable\n\ndef slf_sample_init(lib_path):\n lib = CDLL(os.path.abspath(lib_path))\n lib.integrand_pos.restype = c_double\n lib.integrand_pos.argtypes = (c_int, POINTER(c_double), c_void_p)\n\n lib.integrand_dir.restype = c_double\n lib.integrand_dir.argtypes = (c_int, POINTER(c_double), c_void_p)\n\n return lib\n\ndef slf_sample(lib, a_pos, a_dir, N, max_radius_pos=200, max_radius_dir=20):\n '''\n Return random frequencies as in Random Fourier Features.\n\n The kernel is defined as:\n K = exp(-||x_a-x_a'||^2*a_pos) * max(0, )^a_dir\n\n We first take the Fourier transform of K and regard it as a (unnormalized)\n probability distribution. We then sample from it.\n '''\n # Take the fourier transform of positional kernel. Store the transform as a\n # function of the norm of frequency.\n R_p = np.linspace(0, max_radius_pos, 150)\n F_p = np.zeros_like(R_p)\n for i, r in enumerate(R_p):\n c = np.array([r, a_pos])\n user_data = cast(c.ctypes.data_as(POINTER(c_double)), c_void_p)\n func = LowLevelCallable(lib.integrand_pos, user_data)\n F_p[i] = integrate.nquad(func, [[-2, 2], [-2, 2], [-2, 2]])[0]\n\n # Take the fourier transform of directional kernel. Store the transform as a\n # function of the norm of frequency.\n R_d = np.linspace(0, max_radius_dir, 100)\n F_d = np.zeros_like(R_d)\n for i, r in enumerate(R_d):\n c = np.array([r, a_dir])\n user_data = cast(c.ctypes.data_as(POINTER(c_double)), c_void_p)\n func = LowLevelCallable(lib.integrand_dir, user_data)\n F_d[i] = integrate.nquad(func, [[-2, 2], [-2, 2], [-2, 2]])[0]\n\n # perform rejection sampling\n samples = np.zeros((N*2, 6))\n i = 0\n\n while i < N:\n x,y,z = np.random.uniform(-R_p[-1], R_p[-1], (3, N))\n dx,dy,dz = np.random.uniform(-R_d[-1], R_d[-1], (3, N))\n p = np.random.uniform(0, F_p[0]*F_d[0], N)\n u = np.interp((x*x+y*y+z*z)**0.5, R_p, F_p, right=0) * np.interp((dx*dx+dy*dy+dz*dz)**0.5, R_d, F_d, right=0)\n\n mask = p < u\n if mask.sum() > 0:\n samples[i:i+mask.sum()] = np.hstack([\n x[mask].reshape((-1,1)), \n y[mask].reshape((-1,1)), \n z[mask].reshape((-1,1)), \n dx[mask].reshape((-1,1)), \n dy[mask].reshape((-1,1)), \n dz[mask].reshape((-1,1))])\n i += mask.sum()\n return samples[:N]","sub_path":"sample/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"326466280","text":"from logging import getLogger\nfrom cryptoexchange.exchanges.exchange import Exchange\nfrom cryptoexchange.exceptions.exceptions import RestMessengerError\nfrom cryptoexchange.es.es_doc import EsDoc\n\nlogger = getLogger()\n\n\nclass Binance(Exchange):\n exchange_uri = \"https://api.binance.com\"\n name = \"binance\"\n\n def __init__(self):\n super(self.__class__, self).__init__()\n\n async def get_symbols_info_from_exchange(self):\n \"\"\"\n Queries binance for symbol info\n :return: A list of dictionaries with the following keys: \"symbol, price\"\n \"\"\"\n logger.debug(\"Get all symbols info from {}\".format(self.name))\n try:\n return await self.get_json(self.exchange_uri + \"/api/v3/ticker/price\")\n except RestMessengerError as e:\n logger.error(\"Unable to get all symbols info from {} due to .. {}\".format(self.name, e.message))\n return []\n\n def to_es_doc_list(self, exchange_result):\n \"\"\"\n Convert a Binance result containing symbols information into EsDocs\n :param exchange_result: a list of dictionaries with the following keys: \"symbol, price\"\n :return: a list of esDoc objects\n \"\"\"\n es_docs = []\n timestamp = self.get_current_time()\n for item in exchange_result:\n es_docs.append(EsDoc(symbol=item[\"symbol\"], price=item[\"price\"], timestamp=timestamp,\n exchange_name=self.name))\n return es_docs\n","sub_path":"cryptoexchange/exchanges/binance.py","file_name":"binance.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"133461812","text":"from django.conf import settings\nfrom django.core.paginator import InvalidPage, Paginator\nfrom django.http import Http404\nfrom django.shortcuts import render\nfrom operator import itemgetter\nimport psutil\nfrom django.http import HttpResponse\n\nfrom ..product.utils import products_with_details\nfrom ..product.models import Product, ProductRating\nfrom ..product.utils.availability import products_with_availability,get_availability\nfrom ..dictionary.utils.helper import FeatureHelper\nfrom ..feature.models import (CleanProductDetails,Feature,ProductFeature)\nfrom .forms import SearchForm\nfrom math import log10\nfrom joblib import (Parallel, delayed)\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.contrib.sessions.backends.db import SessionStore\nfrom django.db.models import Avg\n\ntotal = 0\nquery_appendix = {}\nproduct_appendix = []\ndef paginate_results(results, get_data, paginate_by=settings.PAGINATE_BY):\n print('now paginate result')\n paginator = Paginator(results, paginate_by)\n page_number = get_data.get('page', 1)\n try:\n page = paginator.page(page_number)\n except InvalidPage:\n raise Http404('No such page!')\n return page\n\n\ndef evaluate_search_query(form, request):\n results = products_with_details(request.user) & form.search()\n return products_with_availability(results, discounts=request.discounts,\n local_currency=request.currency)\n\ndef check_similarity(item):\n global total\n global query_appendix\n\n element = {}\n detail = item.details.split(' ')\n c = len(detail)\n similarity = 0\n for q in query_appendix:\n if query_appendix[q] > 0:\n f = detail.count(q)/c\n similarity += (f*(log10(1+total/query_appendix[q])))\n element['id'] = item.product_id\n element['similarity'] = similarity\n if similarity > 0:\n global product_appendix\n product_appendix.append(element)\n\ndef render_item(item,discounts,currency):\n availability = get_availability(item,discounts=discounts,\n local_currency=currency)\n rating = ProductRating.objects.filter(product_id=item).aggregate(Avg('value'))\n rating['value__avg'] = 0.0 if rating['value__avg'] is None else rating['value__avg']\n return item, rating, availability\n\ndef custom_query_validation(query,request,request_page):\n global query_appendix\n global total\n global product_appendix\n\n if product_appendix:\n product_appendix = []\n\n available = products_with_details(request.user)\n query = list(set(query.split(' ')))\n queryset = Q()\n for q in query:\n query_appendix[q] = 0\n queryset = queryset | Q(details__icontains=q)\n product_details = CleanProductDetails.objects.filter(product_id__in=available).filter(queryset)\n\n if product_details:\n for q in query_appendix:\n for item in product_details:\n if q in item.details:\n query_appendix[q] += 1\n\n total = len(product_details)\n Parallel(n_jobs=psutil.cpu_count()*2,\n verbose=50,\n require='sharedmem')(map(delayed(check_similarity),product_details))\n print('Job Done')\n product_appendix = sorted(product_appendix, key=itemgetter('similarity'), reverse=True)\n product_appendix = [item['id'].pk for item in product_appendix]\n print('Sorted')\n start = (settings.PAGINATE_BY*(request_page-1))\n end = start+(settings.PAGINATE_BY)\n products = product_appendix[start:end]\n\n results = []\n results = Parallel(n_jobs=psutil.cpu_count()*2,\n verbose=50,\n require='sharedmem',\n backend=\"threading\")(delayed(render_item)(Product.objects.get(id=item),request.discounts,request.currency) for item in products)\n front = [i for i in range((start))]\n\n results = front+results\n\n for item in product_appendix[end:]:\n results.append(item)\n return results\n else:\n return []\n\ndef search_view(request):\n\n clean_query = ''\n if not settings.ENABLE_SEARCH:\n raise Http404('No such page!')\n form = SearchForm(data=request.GET or None)\n\n if form.is_valid():\n miner = FeatureHelper()\n query = form.cleaned_data.get('q', '')\n request_page = int(request.GET.get('page','')) if request.GET.get('page','') else 1\n clean_query = miner.stem_query(query)\n if not clean_query:\n query, results = '', []\n else:\n if 'query' in request.session and 'query_results' in request.session and request.session['query'] and request.session['query_results']:\n prev_query = request.session['query']\n compare = [p==c for p in prev_query.split(' ') for c in clean_query.split(' ')].count(True)\n if compare == len(prev_query.split(' ')) and len(prev_query.split(' ')) == len(clean_query.split(' ')):\n results = []\n start = (settings.PAGINATE_BY*(request_page-1))\n end = start+(settings.PAGINATE_BY)\n products = request.session['query_results'][start:end]\n \n if not products:\n raise Http404('No such page!')\n results = Parallel(n_jobs=psutil.cpu_count()*2,\n verbose=50,\n require='sharedmem',\n backend=\"threading\")(delayed(render_item)(Product.objects.get(id=item),request.discounts,request.currency) for item in products)\n front = [i for i in range((start))]\n results = front+results\n for item in request.session['query_results'][end:]:\n results.append(item)\n else:\n results = custom_query_validation(clean_query, request, request_page)\n if not results:\n query, results = '', []\n else:\n results = custom_query_validation(clean_query, request, request_page)\n if not results:\n query, results = '', []\n else:\n query, results = '', []\n page = paginate_results(list(results), request.GET)\n\n ctx = {\n 'query': query,\n 'results': page,\n 'query_string': '?q=%s' % query}\n response = render(request, 'search/results.html', ctx)\n request.session['query'] = clean_query\n request.session['query_results'] = [item for item in product_appendix]\n return response\n\ndef search_ajax(request):\n return HttpResponse('bla')\n","sub_path":"saleor/search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"157900456","text":"# Electrum - Lightweight Bitcoin Client\n# Copyright (c) 2011-2016 Thomas Voegtlin\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation files\n# (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge,\n# publish, distribute, sublicense, and/or sell copies of the Software,\n# and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom collections import defaultdict\nimport errno\nimport json\nimport os\nimport queue\nimport random\nimport re\nimport select\nimport socket\nimport stat\nimport threading\nimport time\n\nimport socks\nfrom bitcoinx import MissingHeader, IncorrectBits, InsufficientPoW\n\nfrom . import bitcoin\nfrom . import blockchain\nfrom . import util\nfrom .app_state import app_state\nfrom .bitcoin import COIN, bfh\nfrom .blockchain import Blockchain\nfrom .crypto import sha256d\nfrom .i18n import _\nfrom .interface import Connection, Interface\nfrom .logs import logs\nfrom .networks import Net\nfrom .version import PACKAGE_VERSION, PROTOCOL_VERSION\nfrom .simple_config import SimpleConfig\n\n\nlogger = logs.get_logger(\"network\")\n\n\nclass RPCError(Exception):\n pass\n\n\nNODES_RETRY_INTERVAL = 60\nSERVER_RETRY_INTERVAL = 10\n\n# Called by util.py:get_peers()\ndef parse_servers(result):\n \"\"\" parse servers list into dict format\"\"\"\n servers = {}\n for item in result:\n host = item[1]\n out = {}\n version = None\n pruning_level = '-'\n if len(item) > 2:\n for v in item[2]:\n if re.match(r\"[st]\\d*\", v):\n protocol, port = v[0], v[1:]\n if port == '': port = Net.DEFAULT_PORTS[protocol]\n out[protocol] = port\n elif re.match(r\"v(.?)+\", v):\n version = v[1:]\n elif re.match(r\"p\\d*\", v):\n pruning_level = v[1:]\n if pruning_level == '': pruning_level = '0'\n if out:\n out['pruning'] = pruning_level\n out['version'] = version\n servers[host] = out\n return servers\n\n# Imported by scripts/servers.py\ndef filter_version(servers):\n def is_recent(version):\n try:\n return util.normalize_version(version) >= util.normalize_version(PROTOCOL_VERSION)\n except Exception as e:\n return False\n return {k: v for k, v in servers.items() if is_recent(v.get('version'))}\n\n\n# Imported by scripts/peers.py\ndef filter_protocol(hostmap, protocol = 's'):\n '''Filters the hostmap for those implementing protocol.\n The result is a list in serialized form.'''\n eligible = []\n for host, portmap in hostmap.items():\n port = portmap.get(protocol)\n if port:\n eligible.append(serialize_server(host, port, protocol))\n return eligible\n\ndef _get_eligible_servers(hostmap=None, protocol=\"s\", exclude_set=None):\n if exclude_set is None:\n exclude_set = set()\n if hostmap is None:\n hostmap = Net.DEFAULT_SERVERS\n return list(set(filter_protocol(hostmap, protocol)) - exclude_set)\n\ndef _pick_random_server(hostmap=None, protocol='s', exclude_set=None):\n if exclude_set is None:\n exclude_set = set()\n eligible = _get_eligible_servers(hostmap, protocol, exclude_set)\n return random.choice(eligible) if eligible else None\n\nproxy_modes = ['socks4', 'socks5', 'http']\n\n\ndef _serialize_proxy(p):\n if not isinstance(p, dict):\n return None\n return ':'.join([p.get('mode'), p.get('host'), p.get('port'),\n p.get('user', ''), p.get('password', '')])\n\n\ndef _deserialize_proxy(s):\n if not isinstance(s, str):\n return None\n if s.lower() == 'none':\n return None\n proxy = { \"mode\":\"socks5\", \"host\":\"localhost\" }\n args = s.split(':')\n n = 0\n if proxy_modes.count(args[n]) == 1:\n proxy[\"mode\"] = args[n]\n n += 1\n if len(args) > n:\n proxy[\"host\"] = args[n]\n n += 1\n if len(args) > n:\n proxy[\"port\"] = args[n]\n n += 1\n else:\n proxy[\"port\"] = \"8080\" if proxy[\"mode\"] == \"http\" else \"1080\"\n if len(args) > n:\n proxy[\"user\"] = args[n]\n n += 1\n if len(args) > n:\n proxy[\"password\"] = args[n]\n return proxy\n\n\n# Imported by gui.qt.network_dialog.py\ndef deserialize_server(server_str):\n host, port, protocol = str(server_str).rsplit(':', 2)\n assert protocol in 'st'\n int(port) # Throw if cannot be converted to int\n return host, port, protocol\n\n# Imported by gui.qt.network_dialog.py\ndef serialize_server(host, port, protocol):\n return str(':'.join([host, port, protocol]))\n\n\nclass Network(util.DaemonThread):\n \"\"\"\n The Network class manages a set of connections to remote electrum\n servers, each connected socket is handled by an Interface() object.\n Connections are initiated by a Connection() thread which stops once\n the connection succeeds or fails.\n \"\"\"\n\n def __init__(self, config=None):\n super().__init__('network')\n if config is None:\n config = {} # Do not use mutables as default values!\n self.config = SimpleConfig(config) if isinstance(config, dict) else config\n self.num_server = 10 if not self.config.get('oneserver') else 0\n # FIXME - this doesn't belong here; it's not a property of the Network\n # Leaving it here until startup is rationalized\n Blockchain.read_blockchains()\n # Server for addresses and transactions\n self.default_server = self.config.get('server', None)\n self.blacklisted_servers = set(self.config.get('server_blacklist', []))\n logger.debug(\"server blacklist: %s\", self.blacklisted_servers)\n # Sanitize default server\n if self.default_server:\n try:\n deserialize_server(self.default_server)\n except:\n logger.error('failed to parse server-string; falling back to random.')\n self.default_server = None\n if not self.default_server or self.default_server in self.blacklisted_servers:\n self.default_server = _pick_random_server()\n\n self.lock = threading.Lock()\n # locks: if you need to take several acquire them in the order they are defined here!\n self.interface_lock = threading.RLock() # <- re-entrant\n self.pending_sends_lock = threading.Lock()\n\n self.pending_sends = []\n self.message_id = 0\n self.verifications_required = 1\n # If the height is cleared from the network constants, we're\n # taking looking to get 3 confirmations of the first verification.\n if Net.VERIFICATION_BLOCK_HEIGHT is None:\n self.verifications_required = 3\n self.checkpoint_height = Net.VERIFICATION_BLOCK_HEIGHT\n self.debug = False\n self.irc_servers = {} # returned by interface (list from irc)\n self.recent_servers = self._read_recent_servers()\n\n self.banner = ''\n self.donation_address = ''\n self.relay_fee = None\n # callbacks passed with subscriptions\n self.subscriptions = defaultdict(list)\n self.sub_cache = {} # note: needs self.interface_lock\n # callbacks set by the GUI\n self.callbacks = defaultdict(list)\n\n dir_path = os.path.join( self.config.path, 'certs')\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n os.chmod(dir_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)\n\n # subscriptions and requests\n self.subscribed_addresses = set()\n # Requests from client we've not seen a response to\n self.unanswered_requests = {}\n # retry times\n self.server_retry_time = time.time()\n self.nodes_retry_time = time.time()\n # kick off the network. interface is the main server we are currently\n # communicating with. interfaces is the set of servers we are connecting\n # to or have an ongoing connection with\n self.interface = None # note: needs self.interface_lock\n self.interfaces = {} # note: needs self.interface_lock\n self.auto_connect = self.config.get('auto_connect', True)\n self.connecting = set()\n self.socket_queue = queue.Queue()\n self._start_network(deserialize_server(self.default_server)[2],\n _deserialize_proxy(self.config.get('proxy')))\n\n # Called by gui.qt.main_window.py:__init__()\n # Called by gui.qt.coinsplitting_tab.py:_on_split_button_clicked()\n # Called by gui.qt.network_dialog.py:__init__()\n # Called by scripts/stdio.py\n # Called by scripts/text.py\n def register_callback(self, callback, events):\n with self.lock:\n for event in events:\n self.callbacks[event].append(callback)\n\n # Called by gui.qt.main_window.py:clean_up()\n # Called by gui.qt.coinsplitting_tab.py:_split_cleanup()\n def unregister_callback(self, callback):\n with self.lock:\n for callbacks in self.callbacks.values():\n if callback in callbacks:\n callbacks.remove(callback)\n\n # Called by exchange_rate.py:on_quotes()\n # Called by exchange_rate.py:on_history()\n # Called by synchronizer.py:tx_response()\n # Called by synchronizer.py:run()\n def trigger_callback(self, event, *args):\n with self.lock:\n callbacks = self.callbacks[event][:]\n [callback(event, *args) for callback in callbacks]\n\n def _recent_servers_file(self):\n return os.path.join(self.config.path, \"recent-servers\")\n\n def _read_recent_servers(self):\n if not self.config.path:\n return []\n try:\n with open(self._recent_servers_file(), \"r\", encoding='utf-8') as f:\n data = f.read()\n return json.loads(data)\n except:\n return []\n\n def _save_recent_servers(self):\n if not self.config.path:\n return\n s = json.dumps(self.recent_servers, indent=4, sort_keys=True)\n try:\n with open(self._recent_servers_file(), \"w\", encoding='utf-8') as f:\n f.write(s)\n except:\n pass\n\n # Called by daemon.py:run_daemon()\n # Called by gui.qt.main_window.py:update_status()\n def get_server_height(self):\n return self.interface.tip if self.interface else 0\n\n def _server_is_lagging(self):\n sh = self.get_server_height()\n if not sh:\n logger.debug('no height for main interface')\n return True\n lh = self.get_local_height()\n result = (lh - sh) > 1\n if result:\n logger.debug('%s is lagging (%d vs %d)', self.default_server, sh, lh)\n return result\n\n def _set_status(self, status):\n self.connection_status = status\n self._notify('status')\n\n # Called by daemon.py:run_daemon()\n # Called by gui.qt.main_window.py:notify_tx_cb()\n # Called by gui.qt.main_window.py:update_status()\n # Called by gui.qt.main_window.py:update_wallet()\n # Called by gui.qt.network_dialog.py:__init__()\n # Called by gui.stdio.py:get_balance()\n # Called by gui.text.py:print_balance()\n # Called by wallet.py:wait_until_synchronized()\n # Called by scripts/block_headers.py\n # Called by scripts/watch_address.py\n def is_connected(self):\n return self.interface is not None\n\n # Called by scripts/block_headers.py\n # Called by scripts/watch_address.py\n def is_connecting(self):\n return self.connection_status == 'connecting'\n\n def _queue_request(self, method, params, interface=None):\n # If you want to queue a request on any interface it must go\n # through this function so message ids are properly tracked\n if interface is None:\n interface = self.interface\n message_id = self.message_id\n self.message_id += 1\n if self.debug:\n logger.debug(\"%s --> %s %s %s\", interface.host, method, params, message_id)\n interface.queue_request(method, params, message_id)\n return message_id\n\n def _send_subscriptions(self):\n logger.debug('sending subscriptions to %s %d %d', self.interface.server,\n len(self.unanswered_requests), len(self.subscribed_addresses))\n self.sub_cache.clear()\n # Resend unanswered requests\n requests = self.unanswered_requests.values()\n self.unanswered_requests = {}\n for request in requests:\n message_id = self._queue_request(request[0], request[1])\n self.unanswered_requests[message_id] = request\n self._queue_request('server.banner', [])\n self._queue_request('server.donation_address', [])\n self._queue_request('server.peers.subscribe', [])\n self._queue_request('blockchain.relayfee', [])\n for h in self.subscribed_addresses:\n self._queue_request('blockchain.scripthash.subscribe', [h])\n\n def _get_status_value(self, key):\n if key == 'status':\n value = self.connection_status\n elif key == 'banner':\n value = self.banner\n elif key == 'updated':\n value = (self.get_local_height(), self.get_server_height())\n elif key == 'servers':\n value = self.get_servers()\n elif key == 'interfaces':\n value = self.get_interfaces()\n return value\n\n def _notify(self, key):\n if key in ['status', 'updated']:\n self.trigger_callback(key)\n else:\n self.trigger_callback(key, self._get_status_value(key))\n\n # Called by daemon.py:run_daemon()\n # Called by gui.qt.main_window.py:donate_to_server()\n # Called by gui.qt.network_dialog.py:update()\n # Called by gui.qt.network_dialog.py:fill_in_proxy_settings()\n # Called by gui.qt.network_dialog.py:follow_server()\n # Called by gui.qt.network_dialog.py:set_server()\n # Called by gui.qt.network_dialog.py:set_proxy()\n def get_parameters(self):\n host, port, protocol = deserialize_server(self.default_server)\n return host, port, protocol, self.proxy, self.auto_connect\n\n # Called by gui.qt.main_window.py:donate_to_server()\n def get_donation_address(self):\n if self.is_connected():\n return self.donation_address\n\n # Called by daemon.py:run_daemon()\n # Called by gui.qt.network_dialog.py:update()\n # Called by scripts/util.py\n def get_interfaces(self):\n '''The interfaces that are in connected state'''\n return list(self.interfaces.keys())\n\n # Called by commands.py:getservers()\n # Called by gui.qt.network_dialog.py:update()\n def get_servers(self):\n out = Net.DEFAULT_SERVERS\n if self.irc_servers:\n out.update(filter_version(self.irc_servers.copy()))\n else:\n for s in self.recent_servers:\n try:\n host, port, protocol = deserialize_server(s)\n except:\n continue\n if host not in out:\n out[host] = { protocol:port }\n return out\n\n def _start_interface(self, server_key):\n \"\"\"Start the given server if it is not already active or being connected to.\n\n Arguments:\n server_key --- server specifier in the form of '::'\n \"\"\"\n if (not server_key in self.interfaces and not server_key in self.connecting):\n if server_key == self.default_server:\n logger.debug(\"connecting to %s as new interface\", server_key)\n self._set_status('connecting')\n self.connecting.add(server_key)\n c = Connection(server_key, self.socket_queue, self.config.path)\n\n def _get_unavailable_servers(self):\n exclude_set = set(self.interfaces)\n exclude_set = exclude_set.union(self.connecting)\n exclude_set = exclude_set.union(self.disconnected_servers)\n exclude_set = exclude_set.union(self.blacklisted_servers)\n return exclude_set\n\n def _start_random_interface(self):\n exclude_set = self._get_unavailable_servers()\n server_key = _pick_random_server(self.get_servers(), self.protocol, exclude_set)\n if server_key:\n self._start_interface(server_key)\n\n def _start_interfaces(self):\n self._start_interface(self.default_server)\n for i in range(self.num_server - 1):\n self._start_random_interface()\n\n def _set_proxy(self, proxy):\n self.proxy = proxy\n # Store these somewhere so we can un-monkey-patch\n if not hasattr(socket, \"_socketobject\"):\n socket._socketobject = socket.socket\n socket._getaddrinfo = socket.getaddrinfo\n if proxy:\n logger.debug(\"setting proxy '%s'\", proxy)\n proxy_mode = proxy_modes.index(proxy[\"mode\"]) + 1\n socks.setdefaultproxy(proxy_mode,\n proxy[\"host\"],\n int(proxy[\"port\"]),\n # socks.py seems to want either None or a non-empty string\n username=(proxy.get(\"user\", \"\") or None),\n password=(proxy.get(\"password\", \"\") or None))\n socket.socket = socks.socksocket\n # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy\n socket.getaddrinfo = lambda *args: [(socket.AF_INET, socket.SOCK_STREAM,\n 6, '', (args[0], args[1]))]\n else:\n socket.socket = socket._socketobject\n socket.getaddrinfo = socket._getaddrinfo\n\n def _start_network(self, protocol, proxy):\n assert not self.interface and not self.interfaces\n assert not self.connecting and self.socket_queue.empty()\n logger.debug('starting network')\n self.disconnected_servers = set([])\n self.protocol = protocol\n self._set_proxy(proxy)\n self._start_interfaces()\n\n def _stop_network(self):\n logger.debug(\"stopping network\")\n for interface in list(self.interfaces.values()):\n self._close_interface(interface)\n if self.interface:\n self._close_interface(self.interface)\n assert self.interface is None\n assert not self.interfaces\n self.connecting = set()\n # Get a new queue - no old pending connections thanks!\n self.socket_queue = queue.Queue()\n\n # Called by network_dialog.py:follow_server()\n # Called by network_dialog.py:set_server()\n # Called by network_dialog.py:set_proxy()\n def set_parameters(self, host, port, protocol, proxy, auto_connect):\n proxy_str = _serialize_proxy(proxy)\n server = serialize_server(host, port, protocol)\n # sanitize parameters\n try:\n deserialize_server(serialize_server(host, port, protocol))\n if proxy:\n proxy_modes.index(proxy[\"mode\"]) + 1\n int(proxy['port'])\n except:\n return\n self.config.set_key('auto_connect', auto_connect, False)\n self.config.set_key(\"proxy\", proxy_str, False)\n self.config.set_key(\"server\", server, True)\n # abort if changes were not allowed by config\n if self.config.get('server') != server or self.config.get('proxy') != proxy_str:\n return\n self.auto_connect = auto_connect\n if self.proxy != proxy or self.protocol != protocol:\n # Restart the network defaulting to the given server\n self._stop_network()\n self.default_server = server\n self._start_network(protocol, proxy)\n elif self.default_server != server:\n self.switch_to_interface(server, self.SWITCH_SET_PARAMETERS)\n else:\n self._switch_lagging_interface()\n self._notify('updated')\n\n def _switch_to_random_interface(self):\n '''Switch to a random connected server other than the current one'''\n servers = self.get_interfaces() # Those in connected state\n if self.default_server in servers:\n servers.remove(self.default_server)\n if servers:\n self.switch_to_interface(random.choice(servers))\n\n def _switch_lagging_interface(self):\n '''If auto_connect and lagging, switch interface'''\n if self._server_is_lagging() and self.auto_connect:\n # switch to one that has the longest chain\n interfaces = self.interfaces_by_blockchain().get(Blockchain.longest())\n if interfaces:\n choice = random.choice(interfaces)\n self.switch_to_interface(choice.server, self.SWITCH_LAGGING)\n\n SWITCH_DEFAULT = 'SWITCH_DEFAULT'\n SWITCH_RANDOM = 'SWITCH_RANDOM'\n SWITCH_LAGGING = 'SWITCH_LAGGING'\n SWITCH_SOCKET_LOOP = 'SWITCH_SOCKET_LOOP'\n SWITCH_FOLLOW_CHAIN = 'SWITCH_FOLLOW_CHAIN'\n SWITCH_SET_PARAMETERS = 'SWITCH_SET_PARAMETERS'\n\n # Called by network_dialog.py:follow_server()\n def switch_to_interface(self, server, switch_reason=None):\n '''Switch to server as our interface. If no connection exists nor\n being opened, start a thread to connect. The actual switch will\n happen on receipt of the connection notification. Do nothing\n if server already is our interface.'''\n self.default_server = server\n if server not in self.interfaces:\n self.interface = None\n self._start_interface(server)\n return\n i = self.interfaces[server]\n if self.interface != i:\n logger.debug(\"switching to '%s' reason '%s'\", server, switch_reason)\n # stop any current interface in order to terminate subscriptions\n # fixme: we don't want to close headers sub\n #self._close_interface(self.interface)\n self.interface = i\n self._send_subscriptions()\n self._set_status('connected')\n self._notify('updated')\n\n def _close_interface(self, interface):\n if interface:\n if interface.server in self.interfaces:\n self.interfaces.pop(interface.server)\n if interface.server == self.default_server:\n self.interface = None\n interface.close()\n\n def _add_recent_server(self, server):\n # list is ordered\n if server in self.recent_servers:\n self.recent_servers.remove(server)\n self.recent_servers.insert(0, server)\n self.recent_servers = self.recent_servers[0:20]\n self._save_recent_servers()\n\n def _process_response(self, interface, request, response, callbacks):\n if self.debug:\n logger.debug(\"<-- %s\", response)\n error = response.get('error')\n result = response.get('result')\n method = response.get('method')\n params = response.get('params')\n\n # We handle some responses; return the rest to the client.\n if method == 'server.version':\n self._on_server_version(interface, result)\n elif method == 'blockchain.headers.subscribe':\n if error is None:\n self._on_notify_header(interface, result)\n elif method == 'server.peers.subscribe':\n if error is None:\n self.irc_servers = parse_servers(result)\n self._notify('servers')\n elif method == 'server.banner':\n if error is None:\n self.banner = result\n self._notify('banner')\n elif method == 'server.donation_address':\n if error is None:\n self.donation_address = result\n elif method == 'blockchain.relayfee':\n if error is None:\n self.relay_fee = int(result * COIN)\n logger.debug(\"relayfee %s\", self.relay_fee)\n elif method == 'blockchain.block.headers':\n self._on_block_headers(interface, request, response)\n elif method == 'blockchain.block.header':\n self._on_header(interface, request, response)\n\n for callback in callbacks:\n callback(response)\n\n def _get_index(self, method, params):\n \"\"\" hashable index for subscriptions and cache\"\"\"\n return str(method) + (':' + str(params[0]) if params else '')\n\n def _process_responses(self, interface):\n responses = interface.get_responses()\n for request, response in responses:\n if request:\n method, params, message_id = request\n k = self._get_index(method, params)\n # client requests go through self.send() with a\n # callback, are only sent to the current interface,\n # and are placed in the unanswered_requests dictionary\n client_req = self.unanswered_requests.pop(message_id, None)\n if client_req:\n assert interface == self.interface\n callbacks = [client_req[2]]\n else:\n # fixme: will only work for subscriptions\n k = self._get_index(method, params)\n callbacks = self.subscriptions.get(k, [])\n\n # Copy the request method and params to the response\n response['method'] = method\n response['params'] = params\n # Only once we've received a response to an addr subscription\n # add it to the list; avoids double-sends on reconnection\n if method == 'blockchain.scripthash.subscribe':\n self.subscribed_addresses.add(params[0])\n else:\n if not response: # Closed remotely / misbehaving\n self._connection_down(interface.server)\n break\n # Rewrite response shape to match subscription request response\n method = response.get('method')\n params = response.get('params')\n k = self._get_index(method, params)\n if method == 'blockchain.headers.subscribe':\n response['result'] = params[0]\n response['params'] = []\n elif method == 'blockchain.scripthash.subscribe':\n response['params'] = [params[0]] # addr\n response['result'] = params[1]\n callbacks = self.subscriptions.get(k, [])\n\n # update cache if it's a subscription\n if method.endswith('.subscribe'):\n with self.interface_lock:\n self.sub_cache[k] = response\n # Response is now in canonical form\n self._process_response(interface, request, response, callbacks)\n\n # Called by synchronizer.py:subscribe_to_addresses()\n def subscribe_to_scripthashes(self, scripthashes, callback):\n msgs = [('blockchain.scripthash.subscribe', [sh])\n for sh in scripthashes]\n self.send(msgs, callback)\n\n # Called by synchronizer.py:on_address_status()\n def request_scripthash_history(self, sh, callback):\n self.send([('blockchain.scripthash.get_history', [sh])], callback)\n\n # Called by commands.py:notify()\n # Called by websockets.py:reading_thread()\n # Called by websockets.py:run()\n # Called locally.\n def send(self, messages, callback):\n '''Messages is a list of (method, params) tuples'''\n if messages:\n with self.pending_sends_lock:\n self.pending_sends.append((messages, callback))\n\n def _process_pending_sends(self):\n # Requests needs connectivity. If we don't have an interface,\n # we cannot process them.\n if not self.interface:\n return\n\n with self.pending_sends_lock:\n sends = self.pending_sends\n self.pending_sends = []\n\n for messages, callback in sends:\n for method, params in messages:\n r = None\n if method.endswith('.subscribe'):\n k = self._get_index(method, params)\n # add callback to list\n l = self.subscriptions.get(k, [])\n if callback not in l:\n l.append(callback)\n self.subscriptions[k] = l\n # check cached response for subscriptions\n r = self.sub_cache.get(k)\n if r is not None:\n logger.debug(\"cache hit '%s'\", k)\n callback(r)\n else:\n message_id = self._queue_request(method, params)\n self.unanswered_requests[message_id] = method, params, callback\n\n # Called by synchronizer.py:release()\n def unsubscribe(self, callback):\n '''Unsubscribe a callback to free object references to enable GC.'''\n # Note: we can't unsubscribe from the server, so if we receive\n # subsequent notifications _process_response() will emit a harmless\n # \"received unexpected notification\" warning\n with self.lock:\n for v in self.subscriptions.values():\n if callback in v:\n v.remove(callback)\n\n def _connection_down(self, server, blacklist=False):\n '''A connection to server either went down, or was never made.\n We distinguish by whether it is in self.interfaces.'''\n if blacklist:\n self.blacklisted_servers.add(server)\n # rt12 --- there might be a better place for this.\n self.config.set_key(\"server_blacklist\", list(self.blacklisted_servers), True)\n else:\n self.disconnected_servers.add(server)\n if server == self.default_server:\n self._set_status('disconnected')\n if server in self.interfaces:\n self._close_interface(self.interfaces[server])\n self._notify('interfaces')\n for b in Blockchain.blockchains:\n if b.catch_up == server:\n b.catch_up = None\n\n def _new_interface(self, server_key, socket):\n self._add_recent_server(server_key)\n\n interface = Interface(server_key, socket)\n interface.requested_chunks = set()\n interface.blockchain = None\n interface.tip_raw = None\n interface.tip = 0\n interface.set_mode(Interface.MODE_VERIFICATION)\n\n with self.interface_lock:\n self.interfaces[server_key] = interface\n\n # server.version should be the first message\n params = [PACKAGE_VERSION, PROTOCOL_VERSION]\n self._queue_request('server.version', params, interface)\n if not self._request_checkpoint_headers(interface):\n self._subscribe_headers([interface])\n if server_key == self.default_server:\n self.switch_to_interface(server_key, self.SWITCH_DEFAULT)\n\n def _subscribe_headers(self, interfaces):\n # The interface will immediately respond with it's last known header.\n for interface in interfaces:\n interface.logger.debug('subscribing to headers')\n self._queue_request('blockchain.headers.subscribe', [], interface)\n\n def _maintain_sockets(self):\n '''Socket maintenance.'''\n # Responses to connection attempts?\n while not self.socket_queue.empty():\n server, socket = self.socket_queue.get()\n if server in self.connecting:\n self.connecting.remove(server)\n if socket:\n self._new_interface(server, socket)\n else:\n self._connection_down(server)\n\n # Send pings and shut down stale interfaces\n # must use copy of values\n with self.interface_lock:\n interfaces = list(self.interfaces.values())\n for interface in interfaces:\n if interface.has_timed_out():\n self._connection_down(interface.server)\n elif interface.ping_required():\n self._queue_request('server.ping', [], interface)\n\n now = time.time()\n # nodes\n with self.interface_lock:\n server_count = len(self.interfaces) + len(self.connecting)\n if server_count < self.num_server:\n self._start_random_interface()\n if now - self.nodes_retry_time > NODES_RETRY_INTERVAL:\n logger.debug('retrying connections')\n self.disconnected_servers = set([])\n self.nodes_retry_time = now\n\n # main interface\n with self.interface_lock:\n if not self.is_connected():\n if self.auto_connect:\n if not self.is_connecting():\n self._switch_to_random_interface()\n else:\n if self.default_server in self.disconnected_servers:\n if now - self.server_retry_time > SERVER_RETRY_INTERVAL:\n self.disconnected_servers.remove(self.default_server)\n self.server_retry_time = now\n else:\n self.switch_to_interface(self.default_server, self.SWITCH_SOCKET_LOOP)\n\n def _request_headers(self, interface, base_height, count):\n assert count <=2016\n cp_height = app_state.headers.checkpoint.height\n params = (base_height, count, cp_height if base_height + count < cp_height else 0)\n # The verifier spams us...\n if params not in interface.requested_chunks:\n interface.requested_chunks.add(params)\n interface.logger.info(f'requesting {count:,d} headers from height {base_height:,d}')\n self._queue_request('blockchain.block.headers', params, interface)\n\n def _on_block_headers(self, interface, request, response):\n '''Handle receiving a chunk of block headers'''\n error = response.get('error')\n result = response.get('result')\n params = response.get('params')\n\n if not request or result is None or params is None or error is not None:\n interface.logger.error(error or 'bad response')\n return\n\n request_params = request[1]\n request_base_height, expected_header_count, cp_height = request_params\n\n # Ignore unsolicited chunks (how can this even happen with request provided?)\n try:\n interface.requested_chunks.remove(request_params)\n except KeyError:\n interface.logger.error(\"unsolicited chunk base_height=%s count=%s\",\n request_base_height, expected_header_count)\n return\n\n hexdata = result['hex']\n header_hexsize = 80 * 2\n raw_chunk = bfh(hexdata)\n actual_header_count = len(raw_chunk) // 80\n # We accept fewer headers than we asked for, to cover the case where the distance\n # to the tip was unknown.\n if actual_header_count > expected_header_count:\n interface.logger.error(\"chunk data size incorrect expected_size=%s actual_size=%s\",\n expected_header_count * 80, len(raw_chunk))\n return\n\n proof_was_provided = False\n if 'root' in result and 'branch' in result:\n header_height = request_base_height + actual_header_count - 1\n header_offset = (actual_header_count - 1) * header_hexsize\n header = hexdata[header_offset : header_offset + header_hexsize]\n if not self._validate_checkpoint_result(interface, result[\"root\"],\n result[\"branch\"], header, header_height):\n # Got checkpoint validation data, server failed to provide proof.\n interface.logger.error(\"blacklisting server for incorrect checkpoint proof\")\n self._connection_down(interface.server, blacklist=True)\n return\n proof_was_provided = True\n elif len(request_params) == 3 and request_params[2] != 0:\n # Expected checkpoint validation data, did not receive it.\n self._connection_down(interface.server)\n return\n\n were_needed = Blockchain.needs_checkpoint_headers\n try:\n interface.blockchain = Blockchain.connect_chunk(request_base_height, raw_chunk,\n proof_was_provided)\n except (IncorrectBits, InsufficientPoW, MissingHeader) as e:\n interface.logger.error(f'blacklisting server for failed connect_chunk: {e}')\n self._connection_down(interface.server, blacklist=True)\n return\n\n interface.logger.debug(\"connected chunk, height=%s count=%s\",\n request_base_height, actual_header_count)\n\n # If we connected the checkpoint headers all interfaces can subscribe to headers\n if were_needed and not self._request_checkpoint_headers(interface):\n with self.interface_lock:\n self._subscribe_headers(self.interfaces.values())\n\n if not interface.requested_chunks:\n if interface.blockchain.height() < interface.tip:\n self._request_headers(interface, interface.blockchain.height(), 1000)\n else:\n interface.set_mode(Interface.MODE_DEFAULT)\n interface.logger.debug('catch up done %s', interface.blockchain.height())\n interface.blockchain.catch_up = None\n self._notify('updated')\n\n def _request_header(self, interface, height):\n '''\n This works for all modes except for 'default'.\n\n If it is to be used for piecemeal filling of the sparse blockchain\n headers file before the checkpoint height, it needs extra\n handling for the 'default' mode.\n\n A server interface does not get associated with a blockchain\n until it gets handled in the response to it's first header\n request.\n '''\n interface.logger.debug(\"requesting header %d\", height)\n if height > Net.VERIFICATION_BLOCK_HEIGHT:\n params = [height]\n else:\n params = [height, Net.VERIFICATION_BLOCK_HEIGHT]\n self._queue_request('blockchain.block.header', params, interface)\n return True\n\n def _on_header(self, interface, request, response):\n '''Handle receiving a single block header'''\n result = response.get('result')\n if not result:\n interface.logger.error(response)\n self._connection_down(interface.server)\n return\n\n if not request:\n interface.logger.error(\"blacklisting server for sending unsolicited header, \"\n \"no request, params=%s\", response['params'])\n self._connection_down(interface.server, blacklist=True)\n return\n request_params = request[1]\n height = request_params[0]\n\n response_height = response['params'][0]\n # This check can be removed if request/response params are reconciled in some sort\n # of rewrite.\n if height != response_height:\n interface.logger.error(\"unsolicited header request=%s request_height=%s \"\n \"response_height=%s\", request_params, height, response_height)\n self._connection_down(interface.server)\n return\n\n # FIXME: we need to assert we get a proof if we need / requested one\n proof_was_provided = False\n hexheader = None\n if 'root' in result and 'branch' in result and 'header' in result:\n hexheader = result[\"header\"]\n if not self._validate_checkpoint_result(interface, result[\"root\"],\n result[\"branch\"], hexheader, height):\n # Got checkpoint validation data, failed to provide proof.\n interface.logger.error(\"unprovable header request=%s height=%s\",\n request_params, height)\n self._connection_down(interface.server)\n return\n proof_was_provided = True\n else:\n hexheader = result\n\n # Simple header request.\n raw_header = bfh(hexheader)\n try:\n _header, interface.blockchain = Blockchain.connect(height, raw_header,\n proof_was_provided)\n interface.logger.debug(f'Connected header at height {height:,d}')\n except MissingHeader as e:\n interface.logger.info(f'failed to connect header at height {height:,d}: {e}')\n interface.blockchain = None\n except (IncorrectBits, InsufficientPoW) as e:\n interface.logger.error(f'blacklisting server for failed _on_header connect: {e}')\n self._connection_down(interface.server, blacklist=True)\n return\n\n if interface.mode == Interface.MODE_BACKWARD:\n if interface.blockchain:\n interface.set_mode(Interface.MODE_BINARY)\n interface.good = height\n next_height = (interface.bad + interface.good) // 2\n else:\n # A backwards header request should not happen before the checkpoint\n # height. It isn't requested in this context, and it isn't requested\n # anywhere else. If this happens it is an error. Additionally, if the\n # checkpoint height header was requested and it does not connect, then\n # there's not much ElectrumSV can do about it (that we're going to\n # bother). We depend on the checkpoint being relevant for the blockchain\n # the user is running against.\n assert height > Net.VERIFICATION_BLOCK_HEIGHT\n interface.bad = height\n delta = interface.tip - height\n # If the longest chain does not connect at any point we check to the\n # chain this interface is serving, then we fall back on the checkpoint\n # height which is expected to work.\n next_height = max(Net.VERIFICATION_BLOCK_HEIGHT + 1,\n interface.tip - 2 * delta)\n elif interface.mode == Interface.MODE_BINARY:\n if interface.blockchain:\n interface.good = height\n else:\n interface.bad = height\n next_height = (interface.bad + interface.good) // 2\n if next_height == interface.good:\n interface.set_mode(Interface.MODE_CATCH_UP)\n elif interface.mode == Interface.MODE_CATCH_UP:\n if interface.blockchain is None:\n # go back\n interface.logger.info(\"cannot connect %d\", height)\n interface.set_mode(Interface.MODE_BACKWARD)\n interface.bad = height\n next_height = height - 1\n else:\n next_height = height + 1 if height < interface.tip else None\n\n if next_height is None:\n # exit catch_up state\n interface.logger.debug('catch up done %d', interface.blockchain.height())\n interface.blockchain.catch_up = None\n self._switch_lagging_interface()\n self._notify('updated')\n elif interface.mode == Interface.MODE_DEFAULT:\n interface.logger.error(f'ignored header {_header} received in default mode')\n return\n\n # If not finished, get the next header\n if next_height:\n if interface.mode == Interface.MODE_CATCH_UP and interface.tip > next_height:\n self._request_headers(interface, next_height, 1000)\n else:\n self._request_header(interface, next_height)\n else:\n interface.set_mode(Interface.MODE_DEFAULT)\n self._notify('updated')\n # refresh network dialog\n self._notify('interfaces')\n\n def maintain_requests(self):\n with self.interface_lock:\n interfaces = list(self.interfaces.values())\n for interface in interfaces:\n if interface.unanswered_requests and time.time() - interface.request_time > 20:\n # The last request made is still outstanding, and was over 20 seconds ago.\n interface.logger.error(\"blockchain request timed out\")\n self._connection_down(interface.server)\n continue\n\n def wait_on_sockets(self):\n # Python docs say Windows doesn't like empty selects.\n # Sleep to prevent busy looping\n if not self.interfaces:\n time.sleep(0.1)\n return\n with self.interface_lock:\n interfaces = list(self.interfaces.values())\n rin = [i for i in interfaces]\n win = [i for i in interfaces if i.num_requests()]\n try:\n rout, wout, xout = select.select(rin, win, [], 0.1)\n except socket.error as e:\n # TODO: py3, get code from e\n code = None\n if code == errno.EINTR:\n return\n raise\n assert not xout\n for interface in wout:\n interface.send_requests()\n for interface in rout:\n self._process_responses(interface)\n\n def run(self):\n while self.is_running():\n self._maintain_sockets()\n self.wait_on_sockets()\n self.maintain_requests()\n if not Blockchain.needs_checkpoint_headers:\n self.run_jobs() # Synchronizer and Verifier and Fx\n self._process_pending_sends()\n self._stop_network()\n self.on_stop()\n\n def _on_server_version(self, interface, version_data):\n interface.server_version = version_data\n\n def _request_checkpoint_headers(self, interface):\n start_height, count = Blockchain.required_checkpoint_headers()\n if count:\n interface.logger.info('requesting checkpoint headers')\n self._request_headers(interface, start_height, count)\n return count != 0\n\n def _on_notify_header(self, interface, header_dict):\n '''\n When we subscribe for 'blockchain.headers.subscribe', a server will send\n us it's topmost header. After that, it will forward on any additional\n headers as it receives them.\n '''\n if 'hex' not in header_dict or 'height' not in header_dict:\n self._connection_down(interface.server)\n return\n\n header_hex = header_dict['hex']\n raw_header = bfh(header_hex)\n height = header_dict['height']\n\n # If the server is behind the verification height, then something is wrong with\n # it. Drop it.\n if height <= Net.VERIFICATION_BLOCK_HEIGHT:\n self._connection_down(interface.server)\n return\n\n # We will always update the tip for the server.\n interface.tip_raw = raw_header\n interface.tip = height\n interface.set_mode(Interface.MODE_DEFAULT)\n self._process_latest_tip(interface)\n\n def _process_latest_tip(self, interface):\n if interface.mode != Interface.MODE_DEFAULT:\n return\n\n try:\n header, blockchain = Blockchain.connect(interface.tip, interface.tip_raw, False)\n except MissingHeader as e:\n interface.logger.info(str(e))\n except (IncorrectBits, InsufficientPoW) as e:\n interface.logger.error(f'blacklisting server for failed connect: {e}')\n self._connection_down(interface.server, blacklist=True)\n return\n else:\n interface.logger.info(f'Connected {header}')\n interface.blockchain = blockchain\n self._switch_lagging_interface()\n self._notify('updated')\n self._notify('interfaces')\n return\n\n height = interface.tip\n heights = [x.height() for x in Blockchain.blockchains]\n tip = max(heights)\n if tip > Net.VERIFICATION_BLOCK_HEIGHT:\n interface.logger.debug('attempt to connect: our tip={tip:,d} their tip={height:,d}')\n interface.set_mode(Interface.MODE_BACKWARD)\n interface.bad = height\n self._request_header(interface, min(tip, height - 1))\n else:\n interface.logger.debug('attempt to catch up: our tip={tip:,d} their tip={height:,d}')\n chain = Blockchain.longest()\n if chain.catch_up is None:\n chain.catch_up = interface\n interface.set_mode(Interface.MODE_CATCH_UP)\n interface.blockchain = chain\n interface.logger.debug(\"switching to catchup mode %s\", tip)\n self._request_header(interface,\n Net.VERIFICATION_BLOCK_HEIGHT + 1)\n else:\n interface.logger.debug(\"chain already catching up with %s\", chain.catch_up.server)\n\n def _validate_checkpoint_result(self, interface, merkle_root, merkle_branch,\n header, header_height):\n '''\n header: hex representation of the block header.\n merkle_root: hex representation of the server's calculated merkle root.\n branch: list of hex representations of the server's calculated merkle root branches.\n\n Returns a boolean to represent whether the server's proof is correct.\n '''\n received_merkle_root = bytes(reversed(bfh(merkle_root)))\n if Net.VERIFICATION_BLOCK_MERKLE_ROOT:\n expected_merkle_root = bytes(reversed(bfh(\n Net.VERIFICATION_BLOCK_MERKLE_ROOT)))\n else:\n expected_merkle_root = received_merkle_root\n\n if received_merkle_root != expected_merkle_root:\n interface.logger.error(\"Sent unexpected merkle root, expected: '%s', got: '%s'\",\n Net.VERIFICATION_BLOCK_MERKLE_ROOT,\n merkle_root)\n return False\n\n header_hash = sha256d(bfh(header))\n byte_branches = [ bytes(reversed(bfh(v))) for v in merkle_branch ]\n proven_merkle_root = blockchain.root_from_proof(header_hash, byte_branches, header_height)\n if proven_merkle_root != expected_merkle_root:\n interface.logger.error(\"Sent incorrect merkle branch, expected: '%s', proved: '%s'\",\n Net.VERIFICATION_BLOCK_MERKLE_ROOT,\n util.hfu(reversed(proven_merkle_root)))\n return False\n\n return True\n\n def blockchain(self):\n if self.interface and self.interface.blockchain:\n return self.interface.blockchain # Can be None\n return Blockchain.longest()\n\n def interfaces_by_blockchain(self):\n '''Returns a map {blockchain: list of interfaces} for each blockchain being\n followed by any interface.'''\n result = defaultdict(list)\n for interface in self.interfaces.values():\n if interface.blockchain:\n result[interface.blockchain].append(interface)\n return result\n\n def blockchain_count(self):\n return len(self.interfaces_by_blockchain())\n\n # Called by daemon.py:run_daemon()\n # Called by verifier.py:run()\n # Called by gui.qt.main_window.py:update_status()\n # Called by gui.qt.network_dialog.py:update()\n # Called by wallet.py:sweep()\n def get_local_height(self):\n return self.blockchain().height()\n\n # Called by gui.qt.main_window.py:do_process_from_txid()\n # Called by wallet.py:append_utxos_to_inputs()\n # Called by scripts/get_history.py\n def synchronous_get(self, request, timeout=30):\n q = queue.Queue()\n self.send([request], q.put)\n try:\n r = q.get(True, timeout)\n except queue.Empty:\n raise Exception('Server did not answer')\n if r.get('error'):\n raise Exception(r.get('error'))\n return r.get('result')\n\n @staticmethod\n def __wait_for(it):\n \"\"\"Wait for the result of calling lambda `it`.\"\"\"\n q = queue.Queue()\n it(q.put)\n try:\n result = q.get(block=True, timeout=30)\n except queue.Empty:\n raise util.TimeoutException(_('Server did not answer'))\n\n if result.get('error'):\n # Text should not be sanitized before user display\n raise RPCError(result['error'])\n\n return result.get('result')\n\n @staticmethod\n def __with_default_synchronous_callback(invocation, callback):\n \"\"\" Use this method if you want to make the network request\n synchronous. \"\"\"\n if not callback:\n return Network.__wait_for(invocation)\n\n invocation(callback)\n\n # Called by commands.py:broadcast()\n # Called by main_window.py:broadcast_transaction()\n def broadcast_transaction(self, transaction):\n command = 'blockchain.transaction.broadcast'\n invocation = lambda c: self.send([(command, [str(transaction)])], c)\n our_txid = transaction.txid()\n\n try:\n their_txid = Network.__wait_for(invocation)\n except RPCError as e:\n msg = sanitized_broadcast_message(e.args[0])\n return False, _('transaction broadcast failed: ') + msg\n except util.TimeoutException:\n return False, e.args[0]\n\n if their_txid != our_txid:\n try:\n their_txid = int(their_txid, 16)\n except ValueError:\n return False, _('bad server response; it is unknown whether '\n 'the transaction broadcast succeeded')\n logger.warning(f'server TxID {their_txid} differs from ours {our_txid}')\n\n return True, our_txid\n\n # Called by verifier.py:run()\n def get_merkle_for_transaction(self, tx_hash, tx_height, callback=None):\n command = 'blockchain.transaction.get_merkle'\n invocation = lambda c: self.send([(command, [tx_hash, tx_height])], c)\n\n return Network.__with_default_synchronous_callback(invocation, callback)\n\n\ndef sanitized_broadcast_message(error):\n unknown_reason = _('reason unknown')\n try:\n msg = str(error['message'])\n except:\n msg = '' # fall-through\n\n if 'dust' in msg:\n return _('very small \"dust\" payments')\n if ('Missing inputs' in msg or 'Inputs unavailable' in msg or\n 'bad-txns-inputs-spent' in msg):\n return _('missing, already-spent, or otherwise invalid coins')\n if 'insufficient priority' in msg:\n return _('insufficient fees or priority')\n if 'bad-txns-premature-spend-of-coinbase' in msg:\n return _('attempt to spend an unmatured coinbase')\n if 'txn-already-in-mempool' in msg or 'txn-already-known' in msg:\n return _(\"it already exists in the server's mempool\")\n if 'txn-mempool-conflict' in msg:\n return _(\"it conflicts with one already in the server's mempool\")\n if 'bad-txns-nonstandard-inputs' in msg:\n return _('use of non-standard input scripts')\n if 'absurdly-high-fee' in msg:\n return _('fee is absurdly high')\n if 'non-mandatory-script-verify-flag' in msg:\n return _('the script fails verification')\n if 'tx-size' in msg:\n return _('transaction is too large')\n if 'scriptsig-size' in msg:\n return _('it contains an oversized script')\n if 'scriptpubkey' in msg:\n return _('it contains a non-standard signature')\n if 'bare-multisig' in msg:\n return _('it contains a bare multisig input')\n if 'multi-op-return' in msg:\n return _('it contains more than 1 OP_RETURN input')\n if 'scriptsig-not-pushonly' in msg:\n return _('a scriptsig is not simply data')\n if 'bad-txns-nonfinal' in msg:\n return _(\"transaction is not final\")\n logger.info(f'server error (untrusted): {error}')\n return unknown_reason\n","sub_path":"electrumsv/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":56598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"304824994","text":"import FWCore.ParameterSet.Config as cms\nprocess = cms.Process(\"RECO2\")\n\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load('Configuration.EventContent.EventContent_cff')\nprocess.load('Configuration.StandardSequences.GeometryRecoDB_cff')\nprocess.load('Configuration.Geometry.GeometrySimDB_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_38T_PostLS1_cff')\nprocess.load('Configuration.StandardSequences.EndOfProcess_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nprocess.load('Configuration.StandardSequences.RawToDigi_cff')\nprocess.load('Configuration.StandardSequences.Reconstruction_cff')\n\nprocess.XMLFromDBSource.label = cms.string(\"Extended2015ZeroMaterial\")\nprocess.GlobalTag.globaltag = 'POSTLS172_V7::All'\n\n#### CONFIGURE IT HERE\nisMC = True\ndoTimeProfiling = False\n#####################\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1\n\n# start from RAW format for more flexibility\nprocess.raw2digi_step = cms.Sequence(process.RawToDigi)\n\n# get uncalibrechits with global method / time from ratio\nimport RecoLocalCalo.EcalRecProducers.ecalGlobalUncalibRecHit_cfi\nprocess.ecalGlobalUncalibRecHit = RecoLocalCalo.EcalRecProducers.ecalGlobalUncalibRecHit_cfi.ecalGlobalUncalibRecHit.clone()\n# get uncalib rechits from multifit method / time from ratio\nimport RecoLocalCalo.EcalRecProducers.ecalMultiFitUncalibRecHit_cfi\nprocess.ecalMultiFitUncalibRecHit = RecoLocalCalo.EcalRecProducers.ecalMultiFitUncalibRecHit_cfi.ecalMultiFitUncalibRecHit.clone()\nprocess.ecalMultiFitUncalibRecHit.timealgo = cms.string(\"None\")\nprocess.ecalMultiFitUncalibRecHit.ampErrorCalculation = cms.bool(False)\n# get uncalib rechits from multifit method / time from weights\nprocess.ecalMultiFit2UncalibRecHit = RecoLocalCalo.EcalRecProducers.ecalMultiFitUncalibRecHit_cfi.ecalMultiFitUncalibRecHit.clone()\nprocess.ecalMultiFit2UncalibRecHit.timealgo = cms.string(\"None\")\nprocess.ecalMultiFit2UncalibRecHit.ampErrorCalculation = cms.bool(False)\nprocess.ecalMultiFit2UncalibRecHit.ITSignificanceThr = cms.double(3.0)\nprocess.ecalMultiFit2UncalibRecHit.OOTSignificanceThr = cms.double(3.0)\n\n# get the recovered digis\nif isMC:\n process.ecalDetIdToBeRecovered.ebSrFlagCollection = 'simEcalDigis:ebSrFlags'\n process.ecalDetIdToBeRecovered.eeSrFlagCollection = 'simEcalDigis:eeSrFlags'\n process.ecalRecHit.recoverEBFE = False\n process.ecalRecHit.recoverEEFE = False\n process.ecalRecHit.killDeadChannels = False\n process.ecalRecHit.ebDetIdToBeRecovered = ''\n process.ecalRecHit.eeDetIdToBeRecovered = ''\n process.ecalRecHit.ebFEToBeRecovered = ''\n process.ecalRecHit.eeFEToBeRecovered = ''\n\n\nprocess.ecalRecHitGlobal = process.ecalRecHit.clone()\nprocess.ecalRecHitGlobal.EBuncalibRecHitCollection = 'ecalGlobalUncalibRecHit:EcalUncalibRecHitsEB'\nprocess.ecalRecHitGlobal.EEuncalibRecHitCollection = 'ecalGlobalUncalibRecHit:EcalUncalibRecHitsEE'\nprocess.ecalRecHitGlobal.EBrechitCollection = 'EcalRecHitsGlobalEB'\nprocess.ecalRecHitGlobal.EErechitCollection = 'EcalRecHitsGlobalEE'\n\nprocess.ecalRecHitMultiFit = process.ecalRecHit.clone()\nprocess.ecalRecHitMultiFit.EBuncalibRecHitCollection = 'ecalMultiFitUncalibRecHit:EcalUncalibRecHitsEB'\nprocess.ecalRecHitMultiFit.EEuncalibRecHitCollection = 'ecalMultiFitUncalibRecHit:EcalUncalibRecHitsEE'\nprocess.ecalRecHitMultiFit.EBrechitCollection = 'EcalRecHitsMultiFitEB'\nprocess.ecalRecHitMultiFit.EErechitCollection = 'EcalRecHitsMultiFitEE'\n\nprocess.ecalRecHitMultiFit2 = process.ecalRecHit.clone()\nprocess.ecalRecHitMultiFit2.EBuncalibRecHitCollection = 'ecalMultiFit2UncalibRecHit:EcalUncalibRecHitsEB'\nprocess.ecalRecHitMultiFit2.EEuncalibRecHitCollection = 'ecalMultiFit2UncalibRecHit:EcalUncalibRecHitsEE'\nprocess.ecalRecHitMultiFit2.EBrechitCollection = 'EcalRecHitsMultiFit2EB'\nprocess.ecalRecHitMultiFit2.EErechitCollection = 'EcalRecHitsMultiFit2EE'\n\n\n####### clustering\n# do just the 5x5 clusters\n# with the RECO rechits\nprocess.load(\"RecoEcal.EgammaClusterProducers.multi5x5BasicClusters_cfi\")\nprocess.fixed5x5ClustersReco = process.multi5x5BasicClustersCleaned.clone()\nprocess.fixed5x5ClustersReco.doBarrel = True\nprocess.fixed5x5ClustersReco.barrelHitTag = cms.InputTag('ecalRecHitGlobal','EcalRecHitsGlobalEB')\nprocess.fixed5x5ClustersReco.endcapHitTag = cms.InputTag('ecalRecHitGlobal','EcalRecHitsGlobalEE')\nprocess.fixed5x5ClustersReco.barrelClusterCollection = 'Barrel5x5Clusters'\nprocess.fixed5x5ClustersReco.endcapClusterCollection = 'Endcap5x5Clusters'\n\n# with the new rechits \nprocess.fixed5x5ClustersMultiFit = process.multi5x5BasicClustersCleaned.clone()\nprocess.fixed5x5ClustersMultiFit.doBarrel = True\nprocess.fixed5x5ClustersMultiFit.barrelHitTag = cms.InputTag('ecalRecHitMultiFit','EcalRecHitsMultiFitEB')\nprocess.fixed5x5ClustersMultiFit.endcapHitTag = cms.InputTag('ecalRecHitMultiFit','EcalRecHitsMultiFitEE')\nprocess.fixed5x5ClustersMultiFit.barrelClusterCollection = 'Barrel5x5Clusters'\nprocess.fixed5x5ClustersMultiFit.endcapClusterCollection = 'Endcap5x5Clusters'\n\n# with the new rechits \nprocess.fixed5x5ClustersMultiFit2 = process.multi5x5BasicClustersCleaned.clone()\nprocess.fixed5x5ClustersMultiFit2.doBarrel = True\nprocess.fixed5x5ClustersMultiFit2.barrelHitTag = cms.InputTag('ecalRecHitMultiFit2','EcalRecHitsMultiFit2EB')\nprocess.fixed5x5ClustersMultiFit2.endcapHitTag = cms.InputTag('ecalRecHitMultiFit2','EcalRecHitsMultiFit2EE')\nprocess.fixed5x5ClustersMultiFit2.barrelClusterCollection = 'Barrel5x5Clusters'\nprocess.fixed5x5ClustersMultiFit2.endcapClusterCollection = 'Endcap5x5Clusters'\n\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )\npath = '/store/group/comm_ecal/localreco/cmssw_720p4_zeromaterial/photongun_pu25_ave40/'\nprocess.source = cms.Source(\"PoolSource\",\n duplicateCheckMode = cms.untracked.string(\"noDuplicateCheck\"),\n fileNames = cms.untracked.vstring(path+'photongun_pu25_ave40_0.root',\n path+'photongun_pu25_ave40_1.root',\n path+'photongun_pu25_ave40_10.root',\n path+'photongun_pu25_ave40_100.root',\n path+'photongun_pu25_ave40_1000.root',\n path+'photongun_pu25_ave40_1001.root',\n path+'photongun_pu25_ave40_1002.root',\n path+'photongun_pu25_ave40_1003.root',\n path+'photongun_pu25_ave40_1004.root',\n path+'photongun_pu25_ave40_1005.root'\n ))\n\n\nprocess.ecalAmplitudeReco = cms.Sequence( process.ecalGlobalUncalibRecHit *\n process.ecalMultiFitUncalibRecHit *\n process.ecalMultiFit2UncalibRecHit\n )\n\nprocess.ecalRecHitsReco = cms.Sequence( process.ecalRecHitGlobal *\n process.ecalRecHitMultiFit *\n process.ecalRecHitMultiFit2 )\n\nprocess.ecalClustersReco = cms.Sequence(process.fixed5x5ClustersReco\n * process.fixed5x5ClustersMultiFit\n * process.fixed5x5ClustersMultiFit2 )\n\n\nprocess.ecalTestRecoLocal = cms.Sequence( process.raw2digi_step * process.ecalAmplitudeReco * process.ecalRecHitsReco * process.ecalClustersReco )\n\nprocess.load(\"EcalReconstruction.EcalTools.calocluster_dumper_cfi\")\nprocess.caloclusterDumper.fileName = cms.untracked.string('tree_ecalclusters.root')\n\nfrom PhysicsTools.PatAlgos.tools.helpers import *\n\nprocess.p = cms.Path(process.ecalTestRecoLocal)\nprocess.outpath = cms.EndPath(process.caloclusterDumper)\n\n\n#########################\n# Time Profiling #\n#########################\n\n#https://twiki.cern.ch/twiki/bin/viewauth/CMS/FastTimerService\nif(doTimeProfiling):\n process.MessageLogger.categories.append('FastReport')\n process.MessageLogger.cerr.FastReport = cms.untracked.PSet( limit = cms.untracked.int32( 10000000 ) )\n \n # remove any instance of the FastTimerService\n if 'FastTimerService' in process.__dict__:\n del process.FastTimerService\n \n # instrument the menu with the FastTimerService\n process.load( \"HLTrigger.Timer.FastTimerService_cfi\" )\n \n # this is currently ignored in 7.x, and alway uses the real tim clock\n process.FastTimerService.useRealTimeClock = True\n \n # enable specific features\n process.FastTimerService.enableTimingPaths = True\n process.FastTimerService.enableTimingModules = True\n process.FastTimerService.enableTimingExclusive = True\n \n # print a text summary at the end of the job\n process.FastTimerService.enableTimingSummary = True\n \n # skip the first path (useful for HLT timing studies to disregard the time spent loading event and conditions data)\n process.FastTimerService.skipFirstPath = False\n \n # enable per-event DQM plots\n process.FastTimerService.enableDQM = True\n \n # enable per-path DQM plots\n process.FastTimerService.enableDQMbyPathActive = True\n process.FastTimerService.enableDQMbyPathTotal = True\n process.FastTimerService.enableDQMbyPathOverhead = True\n process.FastTimerService.enableDQMbyPathDetails = True\n process.FastTimerService.enableDQMbyPathCounters = True\n process.FastTimerService.enableDQMbyPathExclusive = True\n \n # enable per-module DQM plots\n process.FastTimerService.enableDQMbyModule = True\n process.FastTimerService.enableDQMbyModuleType = True\n \n # enable per-event DQM sumary plots\n process.FastTimerService.enableDQMSummary = True\n \n # enable per-event DQM plots by lumisection\n process.FastTimerService.enableDQMbyLumiSection = True\n process.FastTimerService.dqmLumiSectionsRange = 2500 # lumisections (23.31 s)\n\n # set the time resolution of the DQM plots\n process.FastTimerService.dqmTimeRange = 1000. # ms\n process.FastTimerService.dqmTimeResolution = 5. # ms\n process.FastTimerService.dqmPathTimeRange = 100. # ms\n process.FastTimerService.dqmPathTimeResolution = 0.5 # ms\n process.FastTimerService.dqmModuleTimeRange = 1000. # ms\n process.FastTimerService.dqmModuleTimeResolution = 0.5 # ms\n \n # set the base DQM folder for the plots\n process.FastTimerService.dqmPath = \"HLT/TimerService\"\n process.FastTimerService.enableDQMbyProcesses = True\n \n # save the DQM plots in the DQMIO format\n process.dqmOutput = cms.OutputModule(\"DQMRootOutputModule\",\n fileName = cms.untracked.string(\"DQM_pu40.root\")\n )\n process.FastTimerOutput = cms.EndPath( process.dqmOutput )\n\n","sub_path":"EcalTools/test/fromRawToClustersAndNtupleDump_cfg.py","file_name":"fromRawToClustersAndNtupleDump_cfg.py","file_ext":"py","file_size_in_byte":11339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"95418245","text":"import PyPDF2\r\n\r\n# from PyPDF2 import PdfFileReader ,PdfFileWriter\r\npdfR = PyPDF2.PdfFileReader(\"001.pdf\")\r\npdfN = pdfR.numPages\r\nIi = 1\r\nOo = pdfN // Ii + 1 if pdfN % Ii else 0\r\nfor num in range(1, pdfN+1):\r\n pdfW = PyPDF2.PdfFileWriter()\r\n for pageNum in range(Ii * (num - 1), Ii * num if num != Oo else pdfN):\r\n pageObj = pdfR.getPage(pageNum)\r\n pdfW.addPage(pageObj)\r\n with open(\"PDFread %s\" % num + \".pdf\", \"wb\")as pdfOutputFile:\r\n pdfW.write(pdfOutputFile)\r\n","sub_path":"PDF拆分.py","file_name":"PDF拆分.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"553458148","text":"#!/usr/bin/env python\n\nimport argparse\nimport re\n\n#function to take in user input\ndef get_args():\n \"\"\"\n take user input, no examples necessary\n \"\"\"\n parser = argparse.ArgumentParser(description=\"remove PCR duplicates from fastq files\")\n parser.add_argument(\"-f\", \"--file\", help=\"Input sam file to be analyzed for PCR duplicates\", type=str, required=False)\n parser.add_argument(\"-u\", \"--umi\", help=\"File containing UMI sequences used in experiment\", type=str, required=False)\n parser.add_argument(\"-p\", \"--paired\", help=\"Input sam file is from a paired-end experiment\", type=str, required=False)\n #parser.add_argument(\"-h\", \"--help\", help=\"Flag to give help message\", type=str, required = False)\n return parser.parse_args()\n\nargs = get_args()\n\nif args.paired:\n print(\"Paired not configured. Please contact @spencerseale and complain.\")\n exit()\n\ndef write_read(line, pointer):\n \"\"\"\n write current read out to specified file using file pointer and current line\n example input: K00337:113:HN7KGBBXX:4:1116:22983:39629:AACGCCAT\t99\t10\t33369999\t255\t90M\t=\t33370333\t530\tGCCAGCAATGACACAAGTCCTTTTTTGTCAAGTTCAATGAGCTTAAGGTGCTGTAACGTTTTCAGTGCAGAATCGTTGACTTTCATGTTT\tJJJJJJJJJJJJJJJFJJFFJJJJJJJJFJFFJJJFJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJFA< th] = 1\n pred[pred <= th] = 0\n\n img_name = image_name.split(\"/\")[-1]\n image = io.imread(image_name)\n\n mask = transform.resize(pred, (image.shape[0],image.shape[1]), anti_aliasing=False, mode = 'constant', order=0)\n mask = np.tile(np.expand_dims(mask, axis=-1), (1, 1, 3))\n # kernel = np.ones((3, 3), np.uint8)\n # mask = cv2.erode(mask, kernel, iterations=1)\n olay = image * mask\n\n aaa = img_name.split(\".\")\n bbb = aaa[0:-1]\n imidx = bbb[0]\n for i in range(1, len(bbb)):\n imidx = imidx + \".\" + bbb[i]\n\n olay = olay.astype('uint8')\n #mask[mask<0.2] = 0\n mask = (mask*255).astype('uint8')\n io.imsave(o_dir + imidx + '.jpg', olay)\n io.imsave(d_dir + imidx + '.jpg', mask)\n\n\ndef train(train_loader, model, optimizer, epoch):\n model.train()\n for i, pack in enumerate(train_loader, start=1):\n optimizer.zero_grad()\n images, gts = pack\n images = Variable(images)\n gts = Variable(gts)\n images = images.cuda()\n gts = gts.cuda()\n\n atts, dets = model(images) #\n loss1 = CE(atts, gts)\n loss2 = CE(dets, gts)\n loss = loss1 + loss2\n loss.backward()\n\n clip_gradient(optimizer, opt.clip)\n optimizer.step()\n\n # print(str(i) + '/' + str(total_step))\n # sys.stdout.write(\"\\033[F\")\n\n # if i == total_step:\n # print('{} Epoch [{:03d}/{:03d}], Step [{:04d}/{:04d}], Loss1: {:.4f} Dice1: {:0.4f}'.\n # format(datetime.now(), epoch, opt.epoch, i, total_step, loss1.data, loss.data, ))\n\n if epoch == opt.epoch:\n model.eval()\n torch.save(model.state_dict(), 'calib_weights.pth')\n\n\ndef test(test_model, test_loader, save_path, tr=0.3, after=False):\n inf_times = []\n for i in range(test_loader.size):\n image_orig, image, gt, name = test_loader.load_data()\n image = image.cuda()\n start_time = time.time()\n if after:\n res = test_model(image)\n else:\n _, res = test_model(image)\n torch.cuda.synchronize()\n inf_times.append(time.time() - start_time)\n res = F.upsample(res, size=(image_orig.shape[0], image_orig.shape[1]), mode='bilinear', align_corners=False)\n res = res.sigmoid().data.cpu().numpy().squeeze()\n res = (res - res.min()) / (res.max() - res.min() + 1e-8)\n #print(res)\n #input('wait')\n res[res < tr] = 0\n olay_mask = np.tile(np.expand_dims(res, axis=-1), (1, 1, 3))\n olay = image_orig * olay_mask\n #imageio.imwrite(save_path+name, res)\n olay = olay.astype('uint8')\n imageio.imwrite(save_path + name, olay)\n if after:\n print('average inference time: ' + str(sum(inf_times[3:])/(len(inf_times)-2)))\n\n\nfor i_test, data_test in enumerate(test_salobj_dataloader):\n inputs_test = data_test['image']\n inputs_test = inputs_test.type(torch.FloatTensor)\n image_resized = inputs_test.numpy()[0, :, :, :].transpose((1, 2, 0))\n # io.imsave('after_resize.png', inputs_test.numpy()[0, :, :, :].transpose((1, 2, 0)))\n if torch.cuda.is_available():\n inputs_test = Variable(inputs_test.cuda())\n else:\n inputs_test = Variable(inputs_test)\n\n start = time.time()\n d1, d2, d3, d4, d5, d6, d7, d8 = teach_model(inputs_test) # ,d2,d3,d4,d5,d6,d7,d8\n # print(d1)\n torch.cuda.synchronize()\n # d1 = d1.cpu()\n\n print('generating masks: ' + str(i_test) + '/' + str(num_calib_images))\n sys.stdout.write(\"\\033[F\")\n\n pred = normPRED(d1)\n # pred = overlay(image_resized, pred.squeeze().cpu().data.numpy())\n # save results to test_results folder\n save_output(img_name_list[i_test], pred, mask_path, olay_path)\n\nprint('mask generation finished!')\n\n#model_dir = 'CPD.pth'\nif opt.is_ResNet == 'resnet':\n model = CPD_ResNet()\n model.load_state_dict(torch.load(model_dir))\nelif opt.is_ResNet == 'vgg':\n model = CPD_VGG()\n model.load_state_dict(torch.load(model_dir))\n #model.load_state_dict(torch.load('CPD.pth'))\nelif opt.is_ResNet == 'mobile':\n model = CPD_MobileNet()\n model.load_state_dict(torch.load(model_dir))\n\n\n# model = torch.load(model_dir)\nmodel.cuda().eval()\n\ntest_img_dir = '/home/hypevr/Desktop/demo/test_fold/test_images/'\ntest_mask_dir = '/home/hypevr/Desktop/demo/test_fold/test_images/'\n\ntest_loader = test_dataset(test_img_dir, test_mask_dir, opt.testsize, True)\nprint('pre-testing with '+ str(test_loader.size) + ' images')\ntest(model, test_loader, '/home/hypevr/Desktop/demo/test_fold/before_calib/')\n\nmodel.train()\ntrain_loader = get_loader(image_path, mask_path, batchsize=opt.batchsize, trainsize=opt.trainsize, fake_back_rate=opt.fake_rate, back_dir=back_path)\n\nparams = model.parameters()\noptimizer = torch.optim.Adam(params, opt.lr)\nfor epoch in range(1, opt.epoch+1):\n print('calibrating epoch: '+ str(epoch) + '/' + str(opt.epoch))\n sys.stdout.write(\"\\033[F\")\n adjust_lr(optimizer, opt.lr, epoch, opt.decay_rate, opt.decay_epoch)\n train(train_loader, model, optimizer, epoch)\n\nprint('calibration finished!')\nmodel = CPD_MobileNet_Single()\nmodel.load_state_dict(torch.load('calib_weights.pth'))\nmodel.eval().cuda()\nscriptedmodel = torch.jit.script(model)\ntorch.jit.save(scriptedmodel, dataset_path + 'calib_model.pt')\n\nmodel = torch.load(dataset_path + 'calib_model.pt')\nmodel.cuda().eval()\nprint('after testing with '+ str(test_loader.size) + ' images')\ntest_loader = test_dataset(test_img_dir, test_mask_dir, opt.testsize, True)\ntest(model, test_loader, '/home/hypevr/Desktop/demo/test_fold/after_calib/', after=True)\nprint('all done')\n\n\n\n\n","sub_path":"test_CPD_calib.py","file_name":"test_CPD_calib.py","file_ext":"py","file_size_in_byte":8826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"426922938","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 ('courses', '0004_auto_20150710_1617'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Batch',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('modified', models.DateTimeField(auto_now=True)),\n ('number', models.PositiveSmallIntegerField()),\n ('start_date', models.DateField()),\n ('comments', models.TextField(blank=True)),\n ('accepting_applications', models.BooleanField(default=False)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.AddField(\n model_name='courseinstance',\n name='batch',\n field=models.ForeignKey(to='courses.Batch', null=True, blank=True),\n ),\n ]\n","sub_path":"rmotr_sis/courses/migrations/0005_auto_20150904_2309.py","file_name":"0005_auto_20150904_2309.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"226217892","text":"import journal\r\n\r\nfile_name = \"default.txt\"\r\nentries = list()\r\n\r\n\r\ndef user_input():\r\n cmd = None\r\n\r\n while cmd != 'x':\r\n cmd = input(\"enter [l] for listing [a] for adding [e] to exit \")\r\n cmd = cmd.lower().strip()\r\n\r\n if cmd == 'l':\r\n list_entries()\r\n\r\n elif cmd == 'a':\r\n add_entries()\r\n\r\n elif cmd == 'x':\r\n print(\"good bye...!!!\")\r\n journal.save(file_name,entries)\r\n\r\n else:\r\n print(\"wrong choice..please input again...\")\r\n\r\n\r\ndef list_entries():\r\n #journal.load(file_name)\r\n entries = journal.load(file_name)\r\n for idx, entry in enumerate(entries):\r\n print(\"{}) {}\".format(idx + 1, entry))\r\n\r\n\r\n\r\ndef add_entries():\r\n data = input(\"please enter the record : \")\r\n journal.add_entry(data,entries)\r\n # entries.append(data)\r\n\r\n\r\nuser_input()\r\n","sub_path":"PycharmProjects/pyStart/journalApp.py","file_name":"journalApp.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"520478523","text":"'''\nCreated on 9 Apr 2019\n\n@author: jamie\n\n Take in an input of column differences\n Find 0s\n Check right column or left difference is 0\n Check opposite column to the one checked above.\n Choose column with the large column difference opposite value.\n'''\n\nimport random\nfrom random import randint\nimport copy\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport numpy as np\nimport pickle\nimport time\n\nrandom.seed(0)\ndef gen_batch(samples):\n \"\"\"\n Generates a batch of samples for column differences\n \"\"\"\n column_differences = []\n column_differences.append([0,0,0,0,0,0,0,0,0,0])\n column_differences.append([0,0,2,0,0,0,0,0,0,0])\n column_differences.append([0,0,0,0,2,0,0,0,0,0])\n column_differences.append([0,0,0,0,0,0,2,0,0,0])\n column_differences.append([0,0,0,0,0,0,0,0,2,0])\n for x in range(0, samples):\n column_difference = [0]\n for y in range(0,9):\n column_difference.append(randint(-2,2) * 2)\n \n zero_locations = []\n for z in range(0, len(column_difference)):\n if column_difference[z] == 0:\n zero_locations.append(z)\n if len(zero_locations) > 1:\n zero_location = randint(0, len(zero_locations))\n \n if zero_location == 0:\n #make column to the right also 0\n column_difference[zero_location+1] = 0\n break\n elif zero_location == len(column_difference) - 1:\n #make column to the left also 0\n column_difference[zero_location-1] = 0\n break\n else:\n left = randint(0,1)\n if left == 0:\n #make column to the right 0\n column_difference[zero_location+1] = 0\n break\n else:\n #make column to the left 0\n column_difference[zero_location-1] = 0\n break\n print(column_difference)\n column_differences.append(column_difference)\n return column_differences\n\ndef create_appended_batches(batches):\n \"\"\"\n for each batch:\n Take in an input of column differences\n Find 0s\n Check right column or left difference is 0\n Check opposite column to the one checked above.\n Choose column with the largest column difference opposite value.\n \"\"\"\n appended_batches=[]\n for batch in batches: \n zero_locations=[]\n for column_number in range(0, len(batch)):\n if batch[column_number] == 0:\n zero_locations.append([column_number])\n for column in range(0, len(zero_locations)):\n if zero_locations[column][0] < len(batch) - 1: #For all columns that are not the last\n #if batch[column[0]+1] == 0: #Means value next to this cell is also 0\n if zero_locations[column][0] == 0:\n zero_locations[column].append(0)\n else:\n placement_column = zero_locations[column][0] - 1\n zero_locations[column].append(batch[placement_column])\n cleaning = True\n while cleaning == True:\n #Clears zero locations that do not have a 0 next to it\n cleaning = False\n for location in range(0, len(zero_locations)):\n if len(zero_locations) > 0:\n #print(batch)\n #print(zero_locations)\n if len(zero_locations[location]) <= 1:\n zero_locations.pop(location)\n location = -1\n cleaning = True\n break\n if len(zero_locations) == 0:\n #Ensures there is at least one value \n zero_locations.append([0,0])\n sorted = sort_two_dimensions(zero_locations)\n target_list = create_target(sorted[0][0])\n appended_batch = [batch,target_list]\n appended_batches.append(appended_batch)\n return appended_batches\n \ndef sort_two_dimensions(array):\n \"\"\"\n Sorts a 2D array by its values in the second index in descending order\n \"\"\"\n sorted_array = copy.deepcopy(array)\n sorting=True\n while sorting == True:\n sorting=False\n for row in range(0, len(sorted_array)):\n if row != 0:\n if sorted_array[row][1] > sorted_array[row-1][1]:\n sorting=True\n temp=sorted_array[row-1]\n sorted_array[row-1] = sorted_array[row]\n sorted_array[row] = temp\n return sorted_array\n\ndef create_target(column_number):\n \"\"\"\n Creates a 40 item array based off of the column the tetromino should be placed \n \"\"\"\n target = []\n for x in range(0, 10):\n \"\"\"\n if x == column_number or x == (10 + column_number) or x == (20 + column_number) or x == (30 + column_number):\n target.append(2)\n \"\"\"\n if x == column_number - 1:\n target.append(2)\n else:\n target.append(0)\n return target\n\ndef convert_array_to_numpy(array):\n \"\"\"\n Converts a standard python array to a numpy array\n \"\"\"\n x = np.array([array])\n return np.array([array])\n\ndef save_neural_network(neural_net):\n \"\"\"\n Serializes the neural network.\n \"\"\"\n file_path = \"trim-\" + str(time.strftime(\"%d-%m-%y_%H:%M:%S\"))\n agent_information = [0.1, False, False, neural_net]\n handler = open(file_path + \".obj\", 'wb')\n pickle.dump(agent_information, handler)\n handler.close()\n\nbatch_number = 1000 #Number of batches to train on\nepisodes = 30000 #Decides number of episodes of training\nappended_batches = create_appended_batches(gen_batch(batch_number - 5)) #-5 due to hard-coded non-random batches to train ANN to clear line.\n#Create ANN\nneural_net = Sequential()\nneural_net.add(Dense(10, input_dim=10, activation='tanh'))\nneural_net.add(Dense(10, activation='linear'))\nneural_net.add(Dense(10, activation='linear'))\nneural_net.compile(loss='mean_squared_error',\n optimizer='sgd',\n metrics=['accuracy'])\n\n#Append targets to generated batches\ntraining = []\ntarget = []\nfor x in range(0, batch_number):\n training.append(appended_batches[x][0])\n target.append(appended_batches[x][1])\n \nfor x in range(0, episodes): \n for training_round in range(0, batch_number):\n print(\"Round: \" + str(x) + \" / \" + str(episodes))\n print(\"Batch: \" + str(training_round))\n training_data = convert_array_to_numpy(training[training_round])\n target_data = convert_array_to_numpy(target[training_round])\n neural_net.fit(training_data, target_data, epochs=1)\n\n#Prints the outputs of predictions\nprint(\"***********************\\n\"+str([0,0,4,4,-4,4,2,2,-2,-4]))\nprint(neural_net.predict(convert_array_to_numpy([0,0,4,4,-4,4,2,2,-2,-4])))\nprint(\"***********************\\n\"+str([0,8,0,0,-4,4,2,2,-2,-4]))\nprint(neural_net.predict(convert_array_to_numpy([0,8,0,0,-4,4,2,2,-2,-4])))\nprint(\"***********************\\n\"+str([0,8,0,0,-4,4,0,0,-2,-4]))\nprint(neural_net.predict(convert_array_to_numpy([0,8,0,0,-4,4,0,0,-2,-4])))\nprint(\"***********************\\n\"+str([0,0,0,0,0,0,0,0,0,0]))\nprint(neural_net.predict(convert_array_to_numpy([0,0,0,0,0,0,0,0,0,0])))\nprint(\"***********************\\n\"+str([0,0,2,0,0,0,0,0,0,0]))\nprint(neural_net.predict(convert_array_to_numpy([0,0,2,0,0,0,0,0,0,0])))\nprint(\"***********************\\n\"+str([0,0,2,0,0,0,0,0,0,0]))\nprint(neural_net.predict(convert_array_to_numpy([0,0,2,0,0,0,0,0,0,0])))\nprint(\"***********************\\n\"+str([0,0,0,0,2,0,0,0,0,0]))\nprint(neural_net.predict(convert_array_to_numpy([0,0,0,0,2,0,0,0,0,0])))\nprint(\"***********************\\n\"+str([0,0,0,0,0,0,2,0,0,0]))\nprint(neural_net.predict(convert_array_to_numpy([0,0,0,0,0,0,2,0,0,0])))\nprint(\"***********************\\n\"+str([0,0,0,0,0,0,0,0,2,0]))\nprint(neural_net.predict(convert_array_to_numpy([0,0,0,0,0,0,0,0,2,0])))\nprint(\"***********************\\nTraining complete. Saving neural network to .obj file.\")\nsave_neural_network(neural_net)\nprint(\"done\")\n\n\n \n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":8371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"276209047","text":"from chap4.mapping import DataProcessor\nimport matplotlib.pyplot as plt\n\ndp = DataProcessor()\nmorph_list = dp.return_shaped_list()\n\n# 高速化できるのでは\nword_freq = {}\nfor morph in morph_list:\n if morph['surface'] not in word_freq:\n word_freq.update({morph['surface']:0})\n else:\n word_freq[morph['surface']] += 1\n\nword_freq = sorted(word_freq.items(), key=lambda x:x[1])\nfreq_dict = {}\nfor freq in word_freq:\n if freq[1] not in freq_dict:\n freq_dict.update({freq[1]:1})\n else:\n freq_dict[freq[1]] +=1\n\n# left = [i for i in range(50)]\nheight = []\nleft = []\nfor key, value in freq_dict.items():\n if key > 50:\n break\n else:\n height.append(value)\n left.append(key)\nprint(height)\nprint(left)\n# labels = [key for key in word_freq]\n# height = [value['value'] for value in freq_dict[-50:]]\n\nplt.rcParams['font.family'] = 'AppleGothic'\nplt.bar(left, height)\nplt.show()\n","sub_path":"chap4/38.py","file_name":"38.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"379708840","text":"#!/usr/bin/env python\nfrom wsgiref.handlers import CGIHandler\nfrom wsgiref.util import shift_path_info\nfrom philologic.PhiloDB import PhiloDB\nfrom philologic.DirtyFormatter import Formatter\nfrom philologic import shlaxtree \nfrom sqlite3 import OperationalError\nimport urlparse\nimport re\nimport sys\nimport urllib\n\nfrom object_service import object_service\nfrom conc_service import conc_service\nfrom form_service import form_service\nfrom cite_list_service import cite_list_service\nfrom object_children_service import object_children_service\nfrom freq_service import freq_service\nfrom freq_json_service import freq_json_service\nfrom colloc_service import colloc_service\nfrom colloc_filter_service import colloc_filter_service\n\ndef philo_dispatcher(environ,start_response):\n environ[\"parsed_params\"] = urlparse.parse_qs(environ[\"QUERY_STRING\"],keep_blank_values=True)\n cgi = environ[\"parsed_params\"]\n\n dbname = shift_path_info(environ)\n environ[\"philologic_dbname\"] = dbname\n myname = environ[\"SCRIPT_NAME\"]\n print >> sys.stderr, myname\n dbfile = \"/var/lib/philologic/databases/\" + dbname\n print >> sys.stderr, dbfile\n try:\n db = PhiloDB(dbfile,7)\n except OperationalError:\n return\n\n environ[\"philologic_dbname\"] = dbname\n\n if environ[\"PATH_INFO\"]:\n print >> sys.stderr, \"scanning path info\"\n scanned = environ[\"PATH_INFO\"].split(\"/\")\n scanned = [i for i in scanned if i is not \"\"]\n print >> sys.stderr, \"%s scanned.\" % repr(scanned)\n if \"children\" in scanned:\n environ[\"philologic_id\"] = environ[\"PATH_INFO\"]\n return object_children_service(environ,start_response)\n elif \"form\" in scanned:\n return form_service(environ,start_response)\n elif scanned:\n environ[\"philologic_id\"] = environ[\"PATH_INFO\"]\n print >> sys.stderr, \"passing to object formatter\"\n return object_service(environ,start_response)\n \n \n if \"query\" in cgi and cgi[\"query\"][0]:\n if \"report\" in cgi:\n if cgi[\"report\"][0] == \"frequency\":\n if \"json\" in cgi:\n if \"field\" in cgi and cgi[\"field\"][0] == \"collocates\":\n from colloc_json_service import colloc_json_service\n return colloc_json_service(environ,start_response)\n return freq_json_service(environ,start_response)\n return freq_service(environ,start_response)\n elif cgi[\"report\"][0] == \"collocation\":\n if \"json\" in cgi:\n from colloc_json_service import colloc_json_service\n return colloc_json_service(environ,start_response)\n return colloc_service(environ,start_response)\n return conc_service(environ,start_response)\n elif \"colloc_filter\" in cgi:\n return colloc_filter_service(environ,start_response)\n else:\n return conc_service(environ,start_response)\n\n else:\n return cite_list_service(environ,start_response)\n\nif __name__ == \"__main__\":\n CGIHandler().run(philo_dispatcher)\n","sub_path":"python/examples/services/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"171194491","text":"import os\nfrom eduticket.admin import AuthView, ImageView, ContentView\nfrom eduticket.model import db, User, Role, Content, Image, Tag\nfrom flask import Flask\nfrom flask.ext.security import SQLAlchemyUserDatastore, Security\nfrom flask_admin import Admin\nfrom flask_admin import helpers as admin_helpers\nfrom flask_bootstrap import Bootstrap\n\n\ndef create_app(object_name):\n app = Flask(__name__)\n if not object_name:\n raise Exception('No Configuration selected!')\n app.config.from_object(object_name)\n\n # SQLAlchemy\n db.init_app(app)\n\n # Bootstrap\n Bootstrap(app)\n\n # Flask-Admin\n admin = Admin(app, name='eduticket', template_mode='bootstrap3')\n\n admin.add_view(AuthView(User, db.session))\n admin.add_view(AuthView(Role, db.session))\n admin.add_view(ContentView(Content, db.session))\n admin.add_view(ImageView(Image, db.session))\n admin.add_view(AuthView(Tag, db.session))\n\n # Flask-Security\n user_datastore = SQLAlchemyUserDatastore(db, User, Role)\n security = Security(app, user_datastore)\n\n @security.context_processor\n def security_context_processor():\n return dict(\n admin_base_template=admin.base_template,\n admin_view=admin.index_view,\n h=admin_helpers,\n )\n\n return app\n\n\n# Config 오브젝트를 지정하지 않을 시 Development Config로 자동으로 설정된다\napp = create_app(os.environ.get('CONFIG', 'eduticket.settings.DevelopmentConfig'))\n\nimport eduticket.views\n","sub_path":"eduticket/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"66051928","text":"import cv2\nimport requests\nfrom threading import Thread\n\ndef playing(url, path):\n\n car_file = \"study4/03/cars.xml\"\n cascade1 = cv2.CascadeClassifier(car_file)\n color1 = (0, 0, 255)\n body_file = \"study4/03/haarcascade_fullbody.xml\"\n cascade2 = cv2.CascadeClassifier(body_file)\n color2 = (255, 0, 0)\n\n while(True):\n cap = cv2.VideoCapture(path)\n try:\n while(cap.isOpened()):\n ret, frame = cap.read()\n car_list = cascade1.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=1,minSize = (50,50))\n body_list = cascade2.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=1,minSize = (50,50))\n if len(body_list) > 0: \n for body in body_list:\n x, y, w, h = body\n cv2.rectangle(frame, (x,y), (x+w, y+h), color2, thickness=8)\n if len(car_list) > 0: \n for car in car_list:\n x, y, w, h = car\n cv2.rectangle(frame, (x,y), (x+w, y+h), color1, thickness=8)\n\n ret, jpgImage = cv2.imencode('.jpg', frame)\n file = {'image' : jpgImage}\n res = requests.post(url, files=file)\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\n except :\n cap.release()\n\nt1 = Thread(target=playing, args=('http://localhost:8090/monitor/camera/1', 'study4/03/video1.avi')) \nt2 = Thread(target=playing, args=('http://localhost:8090/monitor/camera/2', 'study4/03/vtest.avi')) \n\nt1.start()\nt2.start()","sub_path":"study4/03/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"450459848","text":"from unittest import TestCase\nfrom unittest.mock import patch\nimport character\n\n# May Chau\n# A01080616\n# 2019-03-11\n\n\n@patch('character.kween', {\n 'Name': 'May',\n 'Fierceness': 10,\n 'Position': [5, 5],\n})\nclass TestGetName(TestCase):\n def test_get_name(self):\n self.assertEqual(character.get_name(), 'May')\n","sub_path":"SUD - RuPaul Drag Race/test_get_name.py","file_name":"test_get_name.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"565531802","text":"\"\"\" goTenna radio objects - part of pyGT https://github.com/sybip/pyGT \"\"\"\n\"\"\" WARNING: not to be confused with gtapiobj.py (API objects) \"\"\"\n\nfrom struct import pack, unpack\nfrom binascii import hexlify, unhexlify\nfrom datetime import datetime\nimport time\n\nfrom pyTLV import tlvPack\nfrom pygth16 import gtAlgoH16\nfrom gtdefs import * # noqa: F403\n\n\ndef gtMakeAirMsg(msgBlob, msgClass, msgAppID, fromGID, destGID=0, destTag=0,\n meshTTL=3, seqNo0=0, seqNo1=0, crypt=0):\n \"\"\"\n Assemble a GTM radio compatible message PDU (NO top-level TLVs)\n (for gtm-lab command !tx)\n \"\"\"\n\n # 1) Message destination element\n msgDest = pack('!BH', msgClass, msgAppID)\n if msgClass in (MSG_CLASS_P2P, MSG_CLASS_GROUP):\n # Destination address only in addressed messages\n msgDest += unhexlify('%012x%02x' % (destGID, destTag))\n\n # 2) Message header element (sender GID, timestamp and seq numbers)\n msgHead = pack('!BQLHB', crypt, fromGID, int(time.time()), seqNo0, seqNo1)\n msgHeadTLV = tlvPack(MESG_TLV_HEAD, msgHead)\n\n # 3) Assemble the PDU: Dest, 0x04, Data (Head + Blob), Mesh TTL\n msgFullPDU = msgDest\n if msgClass == MSG_CLASS_P2P:\n # Element 0x04 only in P2P messages\n msgFullPDU += b'\\xff\\x00\\x00'\n msgFullPDU += msgHeadTLV + msgBlob\n\n return msgFullPDU\n\n\ndef gtReadAirMsg(msgPDU, verbose=1):\n \"\"\"\n Parse a GTM radio message PDU (NO top-level TLVs)\n (via gtm-lab RX_MSG)\n \"\"\"\n msg = {}\n headPos = 3 # if DEST element is short\n\n (msg['classID'], msg['appID']) = unpack(\"!BH\", msgPDU[:3])\n\n if msg['classID'] in (MSG_CLASS_P2P, MSG_CLASS_GROUP):\n # Non-broadcast messages have a destination address:\n # extract 6-byte destGID and 1-byte dest tag\n # (there's no unpack template for 48-bit numbers, so we\n # unpack AppID+GID as a 64-bit number and mask out AppID)\n msg['destGID'] = unpack('!Q', msgPDU[1:9])[0] & 0xffffffffffff\n msg['destTag'] = bytearray(msgPDU)[9]\n if msg['classID'] == MSG_CLASS_P2P:\n # Element 04 only in P2P class messages\n msg['tlv_04'] = msgPDU[10:13]\n headPos = 13 # long DEST element and element 04\n else:\n headPos = 10 # long DEST element, no element 04\n\n (tFB, t10) = unpack('BB', msgPDU[headPos:headPos+2])\n if (tFB != MESG_TLV_HEAD) or (t10 != 0x10):\n print(\"HEAD element not in expected position\")\n return False\n\n (msg['cryptFlag'], msg['fromGID'], msg['tstamp'], msg['seqNo0'],\n msg['seqNo1']) = unpack('!BQLHB', msgPDU[headPos+2:headPos+18])\n\n msg['hashID'] = gtAlgoH16(msgPDU[headPos+2:headPos+18])\n\n msg['msgBlob'] = msgPDU[headPos+18:]\n\n if verbose:\n print(\"[MSGD] CLASSID: %02x (%s)\" %\n (msg['classID'], MSG_CLASS_NAME[msg['classID']]))\n print(\"[MSGD] APPID : %04x\" % msg['appID'])\n\n if 'destGID' in msg:\n print(\"[MSGD] DESTGID: %012x\" % msg['destGID'])\n print(\"[MSGD] DESTTAG: %02x\" % msg['destTag'])\n\n print(\"[MSGH] ENCRYPT: %01x\" % msg['cryptFlag'])\n print(\"[MSGH] FROMGID: %012x\" % msg['fromGID'])\n print(\"[MSGH] DTSTAMP: \" + \"%08x (%s)\" % (msg['tstamp'],\n datetime.fromtimestamp(msg['tstamp']).\n strftime(\"%Y-%m-%d %H:%M:%S\")))\n print(\"[MSGH] SEQNO_0: %04x\" % msg['seqNo0'])\n print(\"[MSGH] SEQNO_1: %02x\" % msg['seqNo1'])\n\n return msg\n","sub_path":"gtairobj.py","file_name":"gtairobj.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"318204179","text":"import gym\nimport gym_hybrid\n\n\nif __name__ == '__main__':\n env = gym.make('Moving-v0')\n env.reset()\n\n ACTION_SPACE = env.action_space[0].n\n PARAMETERS_SPACE = env.action_space[1].shape[0]\n OBSERVATION_SPACE = env.observation_space.shape[0]\n\n done = False\n while not done:\n state, reward, done, info = env.step(env.action_space.sample())\n print(f'State: {state} Reward: {reward} Done: {done}')\n time.sleep(0.1)\n","sub_path":"tests/moving.py","file_name":"moving.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"61261071","text":"#!coding=utf-8\nimport datetime\nimport sys\nimport os\n\n'''\n:param 0~4\nfirst param plus 1 day 1~4 for airflow.sql to execute\n'''\ndef backfill_continuously(latest_day, days):\n exec_days = list(xrange(latest_day, days))\n exec_days.reverse()\n for i in exec_days:\n today = datetime.datetime.now()\n exec_day = (today + datetime.timedelta(days=-i)).strftime('%Y%m%d')\n last_day = (today + datetime.timedelta(days=-i - 1)).strftime('%Y%m%d')\n last_2_days = (today + datetime.timedelta(days=-i - 2)).strftime('%Y%m%d')\n # print exec_day, last_day, last_2_days\n command = \"bash /home/wrt/sparkdata/airflow.sql/wrt/ec/shopitem_c/backfill/shopitem_c_backfill.sh {last_day} {last_2_days}\".format(\n last_day=last_day, last_2_days=last_2_days)\n os.system(command)\n\ndef backfill_individually(last_day, last_update_day):\n command = \"bash /home/wrt/sparkdata/airflow.sql/wrt/ec/shopitem_c/backfill/shopitem_c_backfill.sh {last_day} {last_update_day}\".format(\n last_day=last_day, last_update_day=last_update_day)\n os.system(command)\n\n\n'''\n:param 0~4\nfirst param plus 1 day like 1~4 for airflow.sql to execute\nsecond param subtract 1 day like 1~3 for tolerancing\n'''\ndef backfill_allkindsof(last_day, last_update_day, latest_day, days):\n backfill_individually(last_day, last_update_day)\n backfill_continuously(latest_day, days-1)\nbackfill_continuously(0,2)\n\n\n\n","sub_path":"airflow/wrt/ec/shopitem_c/backfill/shopitem_c_backfill.py","file_name":"shopitem_c_backfill.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"281345758","text":"from typing import Callable, Dict, Optional, Tuple, Type\n\nfrom django.forms import BaseForm\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.shortcuts import redirect\nfrom django.views.generic import ListView\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\nfrom django.views.generic.edit import FormMixin\n\n\nclass FormListView(ListView, FormMixin):\n\n def get_context_data(self, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n context = super().get_context_data()\n context['form'] = form\n return context\n\n def post(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n if form.is_valid():\n self.form_valid(form)\n else:\n return self.get(request, *args, **kwargs)\n\n\nclass MultipleFormMixin(ContextMixin):\n \"\"\"\n Based on https://www.codementor.io/lakshminp/handling-multiple-forms-on-the-same-page-in-django-fv89t2s3j\n \"\"\"\n initial = {}\n form_classes = {}\n success_urls = {}\n stored = {}\n prefixes = {}\n forms_valid_func = {}\n forms_kwargs_func = {}\n\n def add_form(self,\n form_name: str,\n form_class: Type[BaseForm],\n valid_func: Optional[Callable[[BaseForm], HttpResponse]] = None,\n success_url: Optional[str] = None,\n initial: Optional[dict] = None,\n prefix: Optional[str] = None,\n get_kwargs_func: Optional[Callable[[], Tuple[list, dict]]] = None):\n assert valid_func or success_url\n self.form_classes[form_name] = form_class\n if valid_func:\n self.forms_valid_func[form_name] = valid_func\n if success_url:\n self.success_urls[form_name] = success_url\n if initial:\n self.initial[form_name] = initial\n if prefix:\n self.prefixes[form_name] = prefix\n if get_kwargs_func:\n self.forms_kwargs_func[form_name] = get_kwargs_func\n\n def get_initial(self, form: str) -> dict:\n initial = self.initial.get(form)\n initial = initial if initial else {}\n return {**initial, 'action': form}\n\n def get_success_url(self, form: str) -> Optional[str]:\n return self.success_urls.get(form)\n\n def get_prefix(self, form: str) -> Optional[str]:\n return self.prefixes.get(form)\n\n def get_form_kwargs(self, form: str) -> Tuple[list, dict]:\n kwargs = {\n 'initial': self.get_initial(form),\n 'prefix': self.get_prefix(form)\n }\n if self.request.method in ('POST', 'PUT'):\n kwargs.update(self.stored.get(form, {}))\n if self.request.POST['action'] == form:\n post_data = {'data': self.request.POST,\n 'files': self.request.FILES}\n self.stored.update({form: post_data})\n kwargs.update(post_data)\n else:\n self.stored = {}\n return [], kwargs\n\n def get_forms(self) -> Dict[str, BaseForm]:\n forms = {}\n for key, form_class in self.form_classes.items():\n args, kwargs = self.forms_kwargs_func.get(key, self.get_form_kwargs)(key)\n forms[key] = form_class(*args, **kwargs)\n return forms\n\n def form_valid(self, form: BaseForm, form_name: str) -> HttpResponse:\n valid_method = self.forms_valid_func.get(form_name)\n if valid_method:\n return valid_method(form)\n else:\n return redirect(self.get_success_url(form_name))\n\n def form_invalid(self, forms: Dict[str, BaseForm]) -> HttpResponse:\n return self.render_to_response(self.get_context_data(forms=forms))\n\n def get_context_data(self, **kwargs) -> dict:\n if 'forms' not in kwargs:\n kwargs['forms'] = self.get_forms()\n return super().get_context_data(**kwargs)\n\n\nclass ProcessMultipleFormView(View):\n\n def get(self, request, *args, **kwargs) -> HttpResponse:\n return self.render_to_response(self.get_context_data())\n\n def post(self, request, *args, **kwargs) -> HttpResponse:\n form_name = request.POST.get('action')\n forms = self.get_forms()\n form = forms.get(form_name)\n if not form:\n return HttpResponseBadRequest()\n elif form.is_valid():\n return self.form_valid(form, form_name)\n else:\n return self.form_invalid(forms)\n\n def put(self, *args, **kwargs):\n return self.post(*args, **kwargs)\n\n\nclass BaseMultipleFormView(MultipleFormMixin, ProcessMultipleFormView):\n \"\"\"A base view for displaying multiple forms\"\"\"\n\n\nclass MultipleFormView(TemplateResponseMixin, BaseMultipleFormView):\n \"\"\"A view for displaying multiple forms\"\"\"\n","sub_path":"training_calendar/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"218264709","text":"from tqdm import tqdm\nfrom elasticsearch import Elasticsearch\nimport xml.dom.minidom as xmldom\nimport os\nimport json\nimport pandas as pd\n\ndef fusion_model():\n\n querys, questions, narratives = generate_query_sets()\n\n weight1 = 70\n weight2 = 100\n weight3 = 3\n\n for i in range(len(querys)):\n\n total_doc = {}\n\n cur_query = querys[i]\n\n search_query2 = {\"query\": {\"multi_match\" : {\"query\" : extract_stemming_porter(cur_query), \"fields\" : [\"title\", \"abstract\"]}}, \"size\" : 5000}\n search_query3 = {\"query\": {\"multi_match\" : {\"query\" : extract_stemming_snowball(cur_query), \"fields\" : [\"title\", \"abstract\"]}}, \"size\" : 5000}\n\n query_res_1 = es.search(index=\"id_meta_gs_stem2_dfr\", doc_type=\"meta_id_stem3\", body=search_query2)\n for candidate_doc in query_res_1[\"hits\"][\"hits\"]:\n total_doc[candidate_doc[\"_source\"][\"id\"]] = [candidate_doc[\"_score\"]]\n #print(i + 1, \"Q0\", candidate_doc[\"_source\"][\"id\"], 0 ,candidate_doc[\"_score\"], \"STANDARD\")\n\n query_res_2 = es.search(index=\"id_meta_gs_stem3_dfr1\", doc_type=\"meta_id_stem3\", body=search_query3)\n for candidate_doc in query_res_2[\"hits\"][\"hits\"]:\n if candidate_doc[\"_source\"][\"id\"] in total_doc.keys():\n total_doc[candidate_doc[\"_source\"][\"id\"]].append(candidate_doc[\"_score\"])\n else:\n total_doc[candidate_doc[\"_source\"][\"id\"]] = [0, candidate_doc[\"_score\"]]\n \n for doc in total_doc:\n if(len(total_doc[doc]) == 1):\n total_doc[doc].append(0)\n\n\n query_res_3 = es.search(index=\"id_meta_gs_stem3_dfr2\", doc_type=\"meta_id_stem3\", body=search_query3)\n for candidate_doc in query_res_3[\"hits\"][\"hits\"]:\n if candidate_doc[\"_source\"][\"id\"] in total_doc.keys():\n total_doc[candidate_doc[\"_source\"][\"id\"]].append(candidate_doc[\"_score\"])\n else:\n total_doc[candidate_doc[\"_source\"][\"id\"]] = [0, 0, candidate_doc[\"_score\"]]\n\n for doc in total_doc:\n if(len(total_doc[doc]) == 2):\n total_doc[doc].append(0)\n\n for doc in total_doc:\n weight_sum = 0\n final_score = 0\n if total_doc[doc][0] != 0:\n weight_sum += weight1\n final_score += weight1 * total_doc[doc][0]\n if total_doc[doc][1] != 0:\n weight_sum += weight2\n final_score += weight2 * total_doc[doc][1]\n if total_doc[doc][2] != 0:\n weight_sum += weight3\n final_score += weight3 * total_doc[doc][2]\n\n final_score /= weight_sum\n\n print(i + 1, \"Q0\", doc, 0 ,final_score, \"STANDARD\")\n \n return\n\ndef run_search(cur_query, cur_index, cur_doctype):\n\n es = Elasticsearch()\n es.indices.create(index='pdf_doc', ignore=400)\n\n querys, questions, narratives = generate_query_sets()\n\n for i in range(len(querys)):\n cur_query = querys[i]\n\n query = {\"query\": {\"multi_match\" : {\"query\" : cur_query, \"fields\" : [\"title\", \"abstract\"]}}}\n\n cur_query = query\n \n query_res = es.search(index=cur_index, doc_type=cur_doctype, body=cur_query)\n \n for candidate_doc in query_res[\"hits\"][\"hits\"]:\n print(i + 1, \"Q0\", candidate_doc[\"_source\"][\"id\"], 0 ,candidate_doc[\"_score\"], \"STANDARD\")\n \n\n","sub_path":"Search.py","file_name":"Search.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"637869397","text":"# collect ALL STATS \n\n# Written in Python 2.7\n# RCK\n# 8-5-11\n\nimport sys\nsys.path.append('../common modules and helper scripts')\n\nfrom optparse import OptionParser\nimport read_intermediate_files as rif\n\n# Set up options\nusage = \"\"\"usage: %prog [options] output_filename task_name_translation_file.txt data_file1 [ data_file2 ... ] \n\"\"\"\nparser = OptionParser(usage)\n## fetch the args\n(options, args) = parser.parse_args()\n\n## parameter error\nif len(args) < 3:\n parser.error(\"incorrect number of arguments\")\n\noutput_filename = args[0]\n\ntask_name_translation_file = args[1]\n\ndata_files = args[2:]\n\ndata_structure = {} ## keyed by backbone task\n\ntranslation = {}\ntranslation_file = open( task_name_translation_file )\nfor line in translation_file:\n line = line.strip()\n if (len(line) == 0):\n continue\n\n line = line.split()\n translation[line[0]] = line[1]\n\ntranslation_file.close()\n\nfor file in data_files:\n file = file.strip()\n\n if len(file) == 0:\n continue\n\n filenamebits = file.split('_')\n ## interpret the filename, which should be in the following format: 33_Andn_Backbone__mann_whitney_u_stats__control_vs_punish_xor\n ## 1 11 12\n backbone_task = translation[ filenamebits[1] ]\n fluctuating_task = translation[ filenamebits[12] ] # should be the same as [-1]\n punish_or_nopunish = filenamebits[11] \n\n if not backbone_task in data_structure.keys():\n data_structure[backbone_task] = {} ## keyed by the fluctuating task\n\n if not fluctuating_task in data_structure[backbone_task].keys():\n data_structure[backbone_task][fluctuating_task] = {} ## keyed by the punish/nopunish\n\n data = rif.read_intermediate_datafile(file)\n\n data_structure[backbone_task][fluctuating_task][ punish_or_nopunish ] = data\n\n \nmeans = {}\npvalues = {}\n\nfor backbone_task in data_structure.keys(): ## loop through the backbone tasks\n means[ backbone_task ] = {}\n pvalues[ backbone_task ] = {}\n for fluctuating_task in data_structure[ backbone_task ].keys():\n\n for punish_or_nopunish in data_structure[ backbone_task ][ fluctuating_task ].keys():\n if len(data_structure[ backbone_task ][ fluctuating_task ][ punish_or_nopunish ].keys()) > 0:\n\n control_mean_of_backbone_task = float( data_structure[ backbone_task ][ fluctuating_task ][ punish_or_nopunish ][ 'Mean_Median_Task_Oscillation_Amplitude_By_Task__Control'][ backbone_task ][0] )\n treatment_mean_of_backbone_task = float( data_structure[ backbone_task ][ fluctuating_task ][ punish_or_nopunish ][ 'Mean_Median_Task_Oscillation_Amplitude_By_Task__Treatment'][ backbone_task ][0] )\n difference_in_backbone_mean_fluctuaction = abs( treatment_mean_of_backbone_task - control_mean_of_backbone_task )\n\n control_std = float( data_structure[ backbone_task ][ fluctuating_task ][ punish_or_nopunish ][ 'Mean_Median_Task_Oscillation_Amplitude_By_Task__Control'][ backbone_task ][2] )\n treatment_std = float( data_structure[ backbone_task ][ fluctuating_task ][ punish_or_nopunish ][ 'Mean_Median_Task_Oscillation_Amplitude_By_Task__Treatment'][ backbone_task ][2] )\n\n ## assign the outgoing mean difference\n means[ backbone_task ][ fluctuating_task ] = difference_in_backbone_mean_fluctuaction\n\n if 'Mann_Whitney_U_Statistics_By_Task' in data_structure[ backbone_task ][ fluctuating_task ][ punish_or_nopunish ].keys() and difference_in_backbone_mean_fluctuaction > control_std and difference_in_backbone_mean_fluctuaction > treatment_std:\n pvalues[ backbone_task ][ fluctuating_task ] = float( data_structure[ backbone_task ][ fluctuating_task ][ punish_or_nopunish ][ 'Mann_Whitney_U_Statistics_By_Task' ][ backbone_task ][1] )\n else:\n pvalues[ backbone_task ][ fluctuating_task ] = 1\n else:\n means[ backbone_task ][ fluctuating_task ] = 0\n pvalues[ backbone_task ][ fluctuating_task ] = 1\n\n## plot the thing\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.ticker as ticker\n##### extra imports for dates example. remove after conversion\nimport matplotlib.dates as dates\nimport datetime, random\nimport matplotlib.colors as mplc\nimport matplotlib.cm as cm\n\ntask_order = [ 'Echo', 'Not', 'Nand', 'And', 'OrNot', 'Or', 'AndNot', 'Nor', 'Xor', 'Equals' ]\ntask_order_reverse = ['Equals', 'Xor', 'Nor', 'AndNot', 'Or', 'OrNot', 'And', 'Nand', 'Not', 'Echo' ]\n\n\n######## THINGY!\ndef format_value(x, array=None):\n return task_order[x] #use FuncFormatter to dump out the strings\n\ndef format_value_rev(x, array=None):\n return task_order_reverse[x] #use FuncFormatter to dump out the strings\n\n\n#r_d = random_date()\n#some_dates = [dates.date2num(r_d.next()) for i in range(0,20)]\n########## END THINGY\n\nxplacements = np.arange( 10 ) ## 10 bars\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d', xticklabels=task_order )\n\n#x_values = range(10) * 10 ## x\n#y_values = range(10) * 10 ## y \nx_values = []\ny_values = []\nbar_heights = [] ## dz\ncolors = []\nnormalized_pvalues = []\nhatching = []\nfor y_index in range(10): ## from front to back\n for x_index in range(10): ## from left to right\n\n if (x_index == y_index):\n continue\n\n backbone = task_order[ y_index ]\n fluct = task_order[ x_index ]\n\n if pvalues[ backbone ][ fluct ] == 1:\n continue\n\n\n# if pvalues[ backbone ][ fluct ] <= 0.05:\n# hatching.append('/')\n# else:\n# hatching.append('')\n\n \n \n #means[ backbone ][ fluct ]\n #print str(x_index) + \",\" + str(y_index) + backbone + fluct + str(means[ backbone ][ fluct ])\n\n x_values.append( x_index - .25 )\n y_values.append( y_index - .25 )\n bar_heights.append( means[ backbone ][ fluct ] )\n\n #if pvalues[ backbone ][ fluct ] <= 0.01:\n # colors.append('red')\n #elif pvalues[ backbone ][ fluct ] <= 0.05:\n # colors.append('lightpink')\n #else:\n # colors.append('white')\n\n #print pvalues[ backbone ][ fluct ]\n\n if pvalues[ backbone ][ fluct ] <= 0.05:\n #print \"OK : \" + str( pvalues[ backbone ][ fluct ] )\n normalized_pvalues.append( pvalues[ backbone ][ fluct ] )\n else:\n #print \"BAD: \" + str( pvalues[ backbone ][ fluct ] )\n normalized_pvalues.append( pvalues[ backbone ][ fluct ] + .3)\n\n\nz_values = [0] * len(bar_heights) ## z\nwidths = [.5] * len(bar_heights) ## dx\ndepths = [.5] * len(bar_heights) ## dy\n\n\ncolors = [ cm.RdYlBu( pval ) for pval in normalized_pvalues ]\n\nax.bar3d(x_values, y_values, z_values, widths, depths, bar_heights, color=colors )\n\nm = cm.ScalarMappable(cmap=cm.RdYlBu)\nm.set_array(normalized_pvalues)\ncb = plt.colorbar(m, ticks=[0.4, 0.05, 0.01])\ncb.ax.set_ylabel('P-Value')\ncb.set_ticklabels(ticklabels=['0.1', '0.05', '0.01'])\n\n##### SET THE TICKS\nax.w_xaxis.set_major_locator(ticker.FixedLocator(range(10))) # I want all the dates on my xaxis\nax.w_xaxis.set_major_formatter(ticker.FuncFormatter(format_value))\n#for tl in ax.w_xaxis.get_ticklabels(): # re-create what autofmt_xdate but with w_xaxis\n# tl.set_ha('left')\n #tl.set_rotation(40) \n\nax.w_yaxis.set_major_locator(ticker.FixedLocator(range(10))) # I want all the dates on my xaxis\nax.w_yaxis.set_major_formatter(ticker.FuncFormatter(format_value))\n#for tl in ax.w_yaxis.get_ticklabels(): # re-create what autofmt_xdate but with w_xaxis\n# tl.set_ha('right')\n #tl.set_rotation(340)\n#### done setting the ticks\n\n#ax.view_init(70,135)\n#ax.dist = 15\n#ax.elev = 90\nax.azim = 210\n#print ax.azim\n\n\nax.set_xlabel('Fluctuating Tasks')\nax.set_ylabel('Backbone Tasks')\nax.set_zlabel('Mean Amplitude Difference between Treatment and Control')\nplt.hot()\n\nplt.savefig(output_filename)\n\n","sub_path":"research_scripts/__deprecated/analyze task oscillations pipeline/task_oscillation__collect_all_data_and_plot_3d_chart__bar3d.py","file_name":"task_oscillation__collect_all_data_and_plot_3d_chart__bar3d.py","file_ext":"py","file_size_in_byte":8060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"274345631","text":"#!/usr/bin/env python\n#\n# Copyright 2011 David Wyde and Chris Hart.\n#\n\n\"\"\"Use CouchDB as a storage backend for notebooks.\n\"\"\"\n\nimport couchdb\nfrom uuid import uuid4\n\ndef new_id():\n \"\"\"Get a new UUID.\n \n Call this when a notebook cell is created.\n \"\"\"\n \n return uuid4().hex\n\nclass Methods:\n \"\"\"Update CouchDB with changes from a frontend notebook.\"\"\"\n \n def __init__(self, couch_port, database):\n couch = couchdb.Server('http://localhost:%d' % (couch_port,))\n self.database = couch[database]\n\n def save_cell(self, cell_id, fields):\n \"\"\"Store notebook cell documents in CouchDB.\n \n .. warning:: There are **NO** security measures at the moment. \n \n If a non-empty :class:`string` or :class:`unicode` is submitted \n as the `cell_id`, it will be accepted as the cell's ID. \n \n This will be fixed, but it's a problem right now.\n \n :param cell_id: A cell's UUID, for both notebook frontends and CouchDB.\n :param fields: A :class:`dict` of key-value pairs to add to this \\\n CouchDB document.\n \n If an empty string is provided as the `cell_id`, a new UUID is generated\n and a new cell created in the database.\n \n Other \"incorrect\" inputs will cause an immeidate return.\n \"\"\"\n \n if not isinstance(cell_id, basestring):\n return\n elif cell_id == '':\n cell_id = new_id()\n try:\n doc = self.database[cell_id]\n for field, data in fields.iteritems():\n doc[field] = data\n if hasattr(doc, '_rev'):\n doc.update({'_rev': doc.rev, '_id': doc.id})\n except couchdb.client.ResourceNotFound:\n doc = {'input': fields.get('input', ''), 'output': '',\n 'type': 'cell'}\n \n self.database[cell_id] = doc\n\n def save_worksheet(self, worksheet_id, cell_list):\n \"\"\"Save a worksheet into CouchDB.\n \n .. warning:: Two open instances of the same worksheet can overwrite \\\n each other.\n \n The parameter `cell_list` is generated on the client side,\n and there are currently no locks on the CouchDB documents.\n \n :param worksheet_id: A worksheet document's UUID.\n :param cell_list: A list of cell UUIDs contained by this worksheet.\n \"\"\"\n \n doc = {'cells': cell_list, 'type': 'worksheet'}\n try:\n existing = self.database[worksheet_id]\n doc['_rev'] = existing.rev\n except (couchdb.client.PreconditionFailed,\n couchdb.client.ResourceNotFound):\n pass\n\n self.database[worksheet_id] = doc\n \n def delete_cell(self, cell_id):\n \"\"\"Delete a cell from CouchDB.\n \n .. warning:: Users can delete any cell, whether or not they own it.\n \"\"\"\n cell = self.database[cell_id]\n if cell.get('type') == 'cell':\n self.database.delete(cell)\n","sub_path":"service/db_layer.py","file_name":"db_layer.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"340417364","text":"def set_level(level_num):\n def set_func(func):\n def call_func(*args, **kwargs):\n if level_num == 1:\n print(\"---权限级别1,验证---\")\n elif level_num == 2:\n print(\"---权限级别2,验证---\")\n else:\n print(\"---其他权限级别,验证---\")\n ret = func(*args, **kwargs)\n print(\"函数执行完后的装饰功能\")\n return ret\n\n return call_func\n return set_func\n\n@set_level(1) # 用set_level(1)的返回函数对test1进行装饰\ndef test1(*args, **kwargs):\n print(args, kwargs)\n return \"test1 finished\"\n\n@set_level(2)\ndef test2(*args, **kwargs):\n print(args, kwargs)\n return \"test2 finished\"\n\n\nif __name__ == '__main__':\n t1 = test1(1, 2, a=1, b=2)\n print(t1)\n \"\"\"\n ---权限级别1,验证---\n (1, 2) {'a': 1, 'b': 2}\n 函数执行完后的装饰功能\n test1 finished\n \"\"\"\n\n t2 = test2(3, 4, a=3, b=4)\n print(t2)\n \"\"\"\n ---权限级别2,验证---\n (3, 4) {'a': 3, 'b': 4}\n 函数执行完后的装饰功能\n test2 finished\n \"\"\"","sub_path":"Closures_and_decorators/9_带有参数的装饰器.py","file_name":"9_带有参数的装饰器.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"119107567","text":"from keras.layers import *\nfrom lipoClass import lipoClass\nfrom SmilesEnumerator import SmilesEnumerator\nfrom keras.preprocessing import image\nfrom scipy import io\nimport itertools as iter\nfrom testCaseGeneration import *\nfrom testObjective import *\nfrom oracle import *\nfrom record import writeInfo\nimport random\n\ndef lipo_lstm_train():\n lipo = lipoClass()\n lipo.train_model()\n\ndef lipo_lstm_test(r,threshold_SC,threshold_BC,symbols_TC,seq,TestCaseNum,Mutation,CoverageStop):\n r.resetTime()\n seeds = 3\n random.seed(seeds)\n # set oracle radius\n oracleRadius = 0.2\n # load model\n lipo = lipoClass()\n lipo.load_data()\n lipo.load_model()\n sme = SmilesEnumerator()\n\n # test layer\n layer = 1\n\n # choose time steps to cover\n t1 = int(seq[0])\n t2 = int(seq[1])\n indices = slice(t1, t2 + 1)\n\n # calculate mean and std for z-norm\n h_train = lipo.cal_hidden_keras(lipo.X_train, layer)\n mean_TC, std_TC, max_SC, min_SC, max_BC, min_BC = aggregate_inf(h_train, indices)\n\n n_seeds = 200\n # get the seeds pool\n smiles_seeds = []\n for item in lipo.X_orig_train:\n if sme.randomize_smiles(item,0) != None:\n smiles_seeds.append(item)\n if len(smiles_seeds) == n_seeds:\n break\n smiles_seeds = np.array(smiles_seeds)\n X_seeds = lipo.smile_vect(smiles_seeds)\n\n # predict logD value from smiles representation\n smiles = np.array(['SCC(=O)O[C@@]1(SC[NH+](C[C@H]1SC=C)C)c2SCSCc2'])\n test = np.squeeze(lipo.smile_vect(smiles))\n [h_t, c_t, f_t] = lipo.cal_hidden_state(test,layer)\n\n # test objective NC\n nctoe = NCTestObjectiveEvaluation(r)\n threshold_nc = 0\n nctoe.testObjective.setParamters(lipo.model, layer, threshold_nc, test)\n\n # test objective KMNC\n kmnctoe = KMNCTestObjectiveEvaluation(r)\n k_sec = 10\n kmnctoe.testObjective.setParamters(lipo.model, layer, k_sec, test)\n\n # test objective NBC\n nbctoe = NBCTestObjectiveEvaluation(r)\n ub = 0.7\n lb = -0.7\n nbctoe.testObjective.setParamters(lipo.model, layer, ub, lb, test)\n\n # test objective SNAC\n snactoe = NCTestObjectiveEvaluation(r)\n threshold_snac = 0.7\n snactoe.testObjective.setParamters(lipo.model, layer, threshold_snac, test)\n\n # test objective SC\n SCtoe = SCTestObjectiveEvaluation(r)\n SC_test_obj = 'h'\n act_SC = SCtoe.get_activations(np.array([h_t]))\n SCtoe.testObjective.setParamters(lipo.model, SC_test_obj, layer, float(threshold_SC), indices, max_SC, min_SC, np.squeeze(act_SC))\n\n # test objective BC\n BCtoe = BCTestObjectiveEvaluation(r)\n BC_test_obj = 'h'\n act_BC = BCtoe.get_activations(np.array([h_t]))\n BCtoe.testObjective.setParamters(lipo.model, BC_test_obj, layer, float(threshold_BC), indices, max_BC, min_BC, np.squeeze(act_BC))\n\n # test objective TC\n TCtoe = TCTestObjectiveEvaluation(r)\n seq_len = 5\n TC_test_obj = 'h'\n TCtoe.testObjective.setParamters(lipo.model, TC_test_obj, layer, int(symbols_TC), seq_len, indices, mean_TC, std_TC)\n\n y_seeds = np.squeeze(lipo.model.predict(X_seeds))\n X_test = []\n r_t = 400 // len(X_seeds)\n while lipo.numSamples < int(TestCaseNum):\n\n # generate test cases\n unique_test = np.repeat(np.arange(len(X_seeds)), r_t, axis=0)\n smiles_test1 = np.repeat(smiles_seeds, r_t, axis=0)\n y_test1 = np.repeat(y_seeds, r_t, axis=0)\n new_smiles = np.array([sme.randomize_smiles(smiles_test1[i], i+lipo.numSamples) for i in range(len(smiles_test1))])\n test2 = lipo.smile_vect(new_smiles)\n\n if lipo.numSamples > 0 and Mutation == 'genetic':\n y_test1 = np.concatenate((y_test1, np.array([sc_test_1]), np.array([bc_test_1]), np.array([tc_test_1])))\n test2 = np.concatenate((test2, np.array([sc_test_2]), np.array([bc_test_2]), np.array([tc_test_2])))\n unique_test = np.concatenate((unique_test, np.array([seed_id_sc]), np.array([seed_id_bc]), np.array([seed_id_tc])))\n\n y_test2 = np.squeeze(lipo.model.predict(test2))\n # # display statistics of adv.\n lipo.displayInfo(y_test1, y_test2, unique_test)\n\n # calculate the hidden state\n h_test = lipo.cal_hidden_keras(test2, layer)\n\n # update the coverage\n # update NC coverage\n nctoe.update_features(test2)\n # update KMNC coverage\n kmnctoe.update_features(test2)\n # update NBC coverage\n nbctoe.update_features(test2)\n # update SNAC coverage\n snactoe.update_features(test2)\n # update SC coverage\n SCtoe.update_features(h_test, len(X_test))\n # update BC coverage\n BCtoe.update_features(h_test, len(X_test))\n # update TC coverage\n TCtoe.update_features(h_test, len(X_test))\n\n X_test = X_test + test2.tolist()\n\n if Mutation == 'genetic':\n num_generation = 10\n sc_test_record = SCtoe.testObjective.test_record\n bc_test_record = BCtoe.testObjective.test_record\n tc_test_record = TCtoe.testObjective.test_record\n\n if len(sc_test_record) != 0:\n print('boost coverage for SC')\n sc_feature, sc_cov_fit = random.choice(list(sc_test_record.items()))\n seed_id_sc = sc_cov_fit[0] % len(X_seeds)\n sc_test_1 = y_seeds[seed_id_sc]\n # boost coverage with GA\n sc_test_2 = getNextInputByGA(lipo, SCtoe, sc_feature, np.array(X_test[sc_cov_fit[0]]), num_generation,\n lipo.numSamples)\n print('\\n')\n else:\n sc_test_1 = y_seeds[0]\n sc_test_2 = X_seeds[0]\n seed_id_sc = 0\n\n if len(bc_test_record) != 0:\n print('boost coverage for BC')\n bc_feature, bc_cov_fit = random.choice(list(bc_test_record.items()))\n seed_id_bc = bc_cov_fit[0] % len(X_seeds)\n bc_test_1 = y_seeds[seed_id_bc]\n # boost coverage with GA\n bc_test_2 = getNextInputByGA(lipo, BCtoe, bc_feature, np.array(X_test[bc_cov_fit[0]]), num_generation,\n lipo.numSamples)\n print('\\n')\n else:\n bc_test_1 = y_seeds[0]\n bc_test_2 = X_seeds[0]\n seed_id_bc = 0\n\n\n if len(tc_test_record) != 0:\n print('boost coverage for TC')\n tc_feature, tc_cov_fit = random.choice(list(tc_test_record.items()))\n seed_id_tc = tc_cov_fit[1] % len(X_seeds)\n tc_test_1 = y_seeds[seed_id_tc]\n # boost coverage with GA\n tc_test_2 = getNextInputByGA(lipo, TCtoe, tc_feature, np.array(X_test[tc_cov_fit[1]]), num_generation,\n lipo.numSamples)\n else:\n tc_test_1 = y_seeds[0]\n tc_test_2 = X_seeds[0]\n seed_id_tc = 0\n\n # write information to file\n writeInfo(r, lipo.numSamples, lipo.numAdv, lipo.perturbations, nctoe.coverage, kmnctoe.coverage, nbctoe.coverage,\n snactoe.coverage, SCtoe.coverage, BCtoe.coverage, TCtoe.coverage, len(lipo.unique_adv))\n\n print(\"statistics: \\n\")\n nctoe.displayCoverage()\n kmnctoe.displayCoverage()\n nbctoe.displayCoverage()\n snactoe.displayCoverage()\n SCtoe.displayCoverage()\n BCtoe.displayCoverage()\n TCtoe.displayCoverage()\n print('unique adv.', len(lipo.unique_adv))\n lipo.displaySuccessRate()\n","sub_path":"src/lipoTestSuite.py","file_name":"lipoTestSuite.py","file_ext":"py","file_size_in_byte":7568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"379036593","text":"import torch\nfrom fairseq.models.bart import BARTModel\nimport time, os, sys\nfrom sms import mes\nfrom oneToMany import o2m\nfrom pyrouge_test import pyrouge_go\nfrom datetime import datetime\nfrom glob import glob\nimport sys\n\nf_name = os.path.basename(__file__)\n\n\ndef hypogen(ckpt, iter=0, is_test=False, num_to_write=-1, cal_rouge=True, summa_gen=True):\n dir_name_base = ckpt.split('/')[-3]\n bsz = 24 # for 12GB GPU memory\n print('hypogen start..')\n cal_rouge, summa_gen = cal_rouge, summa_gen\n dataset = 'cnndm'\n src_file = './{}/test.source'.format(dataset)\n tgt_dir = './cnndm_hypos/{}'.format(dir_name_base)\n print('src file :', src_file)\n if not os.path.exists(tgt_dir):\n os.makedirs(tgt_dir)\n if num_to_write < 0:\n with open(src_file) as f:\n n_to_write = len(f.readlines())\n else:\n n_to_write = num_to_write\n if dataset == 'cnndm':\n beam, lenpen, max_len_b, min_len, data = 4, 2.0, 140, 30, 'cnndm'\n else:\n beam, lenpen, max_len_b, min_len, data = 6, 1.0, 60, 0, 'xsum'\n # try:\n start_time = time.time()\n filename = os.path.join(tgt_dir,\n 'cnndm_test_%d.hypo' % (num_to_write))\n print('ckpt : {}\\nwrite file : {}\\n'.format(ckpt, filename))\n print(datetime.now())\n print('\\nmode : {}, beam : {}, lenpen : {}, max_len : {}, min_len : {}'.format(data, beam, lenpen, max_len_b,\n min_len))\n # model gen summary write\n if summa_gen:\n bart = BARTModel.from_pretrained(\n './', checkpoint_file=ckpt, data_name_or_path='cnndm-bin_orig'\n )\n bart.cuda()\n bart.eval()\n bart.half()\n count = 1\n print('cnndm summa gen start ..')\n with open(src_file, 'r', encoding='utf8') as source, open(filename, 'w',\n encoding='utf8') as fout:\n sline = source.readline().strip()\n slines = [sline]\n for sline in source:\n if count % bsz == 0:\n with torch.no_grad():\n hypotheses_batch = bart.sample(slines, beam=beam, lenpen=lenpen, max_len_b=max_len_b,\n min_len=min_len, no_repeat_ngram_size=3)\n\n for hypothesis in hypotheses_batch:\n fout.write(hypothesis + '\\n')\n fout.flush()\n slines = []\n\n slines.append(sline.strip())\n count += 1\n if count >= n_to_write:\n break\n if slines != []:\n hypotheses_batch = bart.sample(slines, beam=beam, lenpen=lenpen, max_len_b=max_len_b,\n min_len=min_len, no_repeat_ngram_size=3)\n for hypothesis in hypotheses_batch:\n fout.write(hypothesis + '\\n')\n fout.flush()\n\n del bart, hypotheses_batch, slines\n torch.cuda.empty_cache()\n\n # rouge score calcul\n if cal_rouge:\n try:\n gold_label = './{}/{}.target'.format(dataset, os.path.basename(src_file).split('.')[0])\n if num_to_write > 0:\n true_gold_file = './cnndm/{}_{}.target'.format(os.path.basename(src_file).split('.')[0],\n num_to_write)\n if not os.path.exists(true_gold_file):\n with open(true_gold_file, 'w') as fout, open(gold_label) as fin:\n gold_lines = fin.readlines()\n for line in gold_lines[:n_to_write]:\n fout.write(line)\n \"\"\"\n true_gold_file = './xsum_ST/{}_{}.target'.format(os.path.basename(src_file).split('.')[0],\n num_to_write)\n if not os.path.exists(true_gold_file):\n with open(true_gold_file, 'w') as fout, open(gold_label) as fin:\n gold_lines = fin.readlines()\n for line in gold_lines[:n_to_write]:\n fout.write(line)\n \"\"\"\n else:\n true_gold_file = gold_label\n hypo_file = filename\n print('start o2m. filename : ', hypo_file)\n if is_test:\n sys_dir = './cnndm_rouge_results_test/{}'.format(dir_name_base)\n else:\n sys_dir = './cnndm_rouge_results_test/{}'.format(dir_name_base)\n if not os.path.exists(sys_dir):\n os.makedirs(sys_dir)\n rouge_results, wk_time, res_file = pyrouge_go(\n o2m(hypo_file, true_gold_file, onefile_dir='./cnndm',\n sys_dir=sys_dir))\n except Exception as e:\n mes('error during rouge result: ' + str(e))\n print('error during rouge result: ', e)\n end_time = time.time()\n fintime = (end_time - start_time) / 60.0\n print('finished %s in ' % filename.split('/')[-1], fintime, 'min')\n mes('{:0.2f}min. | hypogen done. | {}'.format(fintime, f_name))\n return filename\n\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n ckpts = glob(os.path.join(os.path.dirname(sys.argv[1]), 'checkpoint' + '*'))\n if len(ckpts) > 1:\n ckpts2 = [j for j in ckpts if j != sys.argv[1]]\n if len(ckpts) > len(ckpts2):\n left = 0\n else:\n ckpts2 = sorted(ckpts2)\n left = 1\n best_loss, stop_epoch = None, None\n for k in ckpts2[left:]:\n os.remove(k)\n print('Removed ckpts | {} ..'.format(k))\n\n # for generation\n if len(sys.argv) > 4: # unsup hypo\n hypofile = hypogen(sys.argv[1], int(sys.argv[2]), bool(sys.argv[3]), int(sys.argv[4]))\n print('hypo written at {}'.format(hypofile))\n elif len(sys.argv) >= 3: # test\n hypofile = hypogen(sys.argv[1], int(sys.argv[2]), bool(sys.argv[3]))\n","sub_path":"xsum_ST/hypogen_fortest_cnndm.py","file_name":"hypogen_fortest_cnndm.py","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"295314279","text":"import sys\n#determine if the player wants to fight \ndef determine_yes_or_no(decision):\n first_letter = decision[0]\n upper_letter = first_letter.upper()\n return upper_letter == 'Y'\n \n#make an announcement about the players decision\ndef make_announcement(announcement):\n equal_header = '============'\n for letter in announcement:\n equal_header = equal_header + '='\n print(' ')\n print(equal_header)\n print('!!!!! ' + announcement + ' !!!!!')\n print(equal_header) \n print(' ') \n\n#print a \"dragon\"\ndef print_dragon():\n print(' o<')\n print('^^(0)^^')\n print(' ^ ^')\n\n# Define a main() function that prints a little greeting.\ndef main():\n print('\\nWelcome!')\n print('This is a text adventure about dragons\\n')\n \n #get player name\n player_name = raw_input('To get started please enter your name: ')\n \n #ask if they want to play\n fight_decision = raw_input('\\nHello ' + player_name + '. Would you like to fight a dragon? ')\n \n if determine_yes_or_no(fight_decision):\n #fight the dragon\n make_announcement(player_name + ' has decided to fight')\n #pick weapon\n player_weapon = raw_input('What weapon will you use? (come up with whatever you want): ')\n make_announcement(player_name + ' will fight the dragon with a ' + player_weapon)\n #dragon arrives\n make_announcement('The dragon is here')\n print_dragon()\n make_announcement(\"That's a baby bird. NOT a dragon\")\n #new choice\n continue_fight = raw_input('Still want to fight? ')\n if (determine_yes_or_no(continue_fight)):\n #fight the bird\n make_announcement('The fight will go on')\n make_announcement(player_name + \"'s \" + player_weapon + \" broke and the bird killed them\")\n else:\n #spare the bird\n make_announcement(player_name + ' has decided to spare the bird because it is so cute')\n make_announcement(player_name + ' will donate their ' + player_weapon + ' to the townspeople') \n else:\n #don't fight\n make_announcement(player_name + ' has declined the fight')\n make_announcement('We are sad to see ' + player_name + ' go :(')\n \n #finish the game\n make_announcement('THE END') \n \n\n# This is the standard boilerplate that calls the main() function.\nif __name__ == '__main__':\n main()","sub_path":"adventure.py","file_name":"adventure.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"324138722","text":"# Nima Vahdat 610397163\r\nfrom suffixTree import SuffixTree\r\nimport PySimpleGUI as sg\r\nimport os.path\r\n\r\nsg.theme('DarkBlue10')\r\n\r\ndef string_maker(string):\r\n flag = False\r\n final_string = \"\"\r\n for s in string:\r\n if s == \">\":\r\n final_string += \">\"\r\n flag = True\r\n if s == \"\\n\":\r\n flag = False\r\n \r\n if not flag and s != \"\\n\":\r\n final_string += s\r\n \r\n final_string = final_string[1:] + \"$\"\r\n return final_string\r\n\r\nstring_sec = [\r\n [sg.Text(\"Brows a file or inter string\")],\r\n [sg.Text('File path\\nfor main Strings:'), sg.InputText(enable_events=True, key=\"-FOLDER-\"), sg.FileBrowse()],\r\n [sg.Text('\\nOR')],\r\n [sg.Text(' Strings:'), sg.Multiline(enable_events=True, key=\"-FOLDER1-\")],\r\n [sg.Button(\"Creat Tree\", key = \"Creat-Tree\"), sg.Text(\" \"*30, key = \"-create-\")]\r\n ]\r\nfind_sec = [[sg.Text('File path\\nfor results:\\n'), sg.InputText(enable_events=True, key=\"-FOLDER2-\"), sg.FolderBrowse()],\r\n [sg.Text(' K:'), sg.InputText(key=\"-PATTERN-\")],\r\n [sg.Button(\"Find\"), sg.Text(\" \"*30, key = \"-FIND-\")]\r\n ]\r\n\r\nlayout = [\r\n [\r\n sg.Column(string_sec),\r\n sg.VSeparator(),\r\n sg.Column(find_sec)\r\n ]\r\n]\r\n\r\n# Create the window\r\nwindow = sg.Window(\"Longest Substring (PART 2)\", layout)\r\n# Create an event loop\r\nwhile True:\r\n event, values = window.read()\r\n\r\n if event == sg.WIN_CLOSED:\r\n break\r\n\r\n elif event == \"Creat-Tree\":\r\n x = values[\"-FOLDER-\"]\r\n if x == '':\r\n tree = SuffixTree(string_maker(values[\"-FOLDER1-\"]))\r\n else:\r\n f = open(x, \"r\")\r\n string = f.read()\r\n tree = SuffixTree(string_maker(string))\r\n window['-create-'].Update('Created!')\r\n\r\n elif event == \"Find\":\r\n a = tree.find_k_sub(int(values[\"-PATTERN-\"]))\r\n if values[\"-FOLDER2-\"]:\r\n path_ = values[\"-FOLDER2-\"] + \"/result.txt\"\r\n else:\r\n path_ = \"result.txt\"\r\n f2 = open(path_, 'w')\r\n final = \"RESULT:\\n\" + str(a)\r\n f2.write(final)\r\n f2.close()\r\n window['-FIND-'].Update('Check the result.txt!')\r\nwindow.close()","sub_path":"part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"514582195","text":"import os\nfrom keywordgroup import KeywordGroup\n\n\nclass _JavaScriptKeywords(KeywordGroup):\n\n # Public\n\n def execute_javascript(self, *code):\n \"\"\"Executes the given JavaScript code.\n\n `code` may contain multiple lines of code and may be divided into\n multiple cells in the test data. In that case, the parts are\n catenated together without adding spaces.\n\n If `code` is an absolute path to an existing file, the JavaScript\n to execute will be read from that file. Forward slashes work as\n a path separator on all operating systems.\n\n The JavaScript executes in the context of the currently selected\n frame or window as the body of an anonymous function. Use _window_ to\n refer to the window of your application and _document_ to refer to the\n document object of the current frame or window, e.g.\n _document.getElementById('foo')_.\n\n This keyword returns None unless there is a return statement in the\n JavaScript. Return values are converted to the appropriate type in\n Python, including WebElements.\n\n Examples:\n | Execute JavaScript | window.my_js_function('arg1', 'arg2') | |\n | Execute JavaScript | ${CURDIR}/js_to_execute.js | |\n | ${sum}= | Execute JavaScript | return 1 + 1; |\n | Should Be Equal | ${sum} | ${2} |\n \"\"\"\n js = self._get_javascript_to_execute(''.join(code))\n self._info(\"Executing JavaScript:\\n%s\" % js)\n return self._current_browser().execute_script(js)\n\n def execute_async_javascript(self, *code):\n \"\"\"Executes asynchronous JavaScript code.\n\n Similar to `Execute Javascript` except that scripts executed with\n this keyword must explicitly signal they are finished by invoking the\n provided callback. This callback is always injected into the executed\n function as the last argument.\n\n Scripts must complete within the script timeout or this keyword will\n fail. See the `Timeouts` section for more information.\n\n Examples:\n | Execute Async JavaScript | var callback = arguments[arguments.length - 1]; | window.setTimeout(callback, 2000); |\n | Execute Async JavaScript | ${CURDIR}/async_js_to_execute.js | |\n | ${retval}= | Execute Async JavaScript | |\n | ... | var callback = arguments[arguments.length - 1]; | |\n | ... | function answer(){callback(\"text\");}; | |\n | ... | window.setTimeout(answer, 2000); | |\n | Should Be Equal | ${retval} | text |\n \"\"\"\n js = self._get_javascript_to_execute(''.join(code))\n self._info(\"Executing Asynchronous JavaScript:\\n%s\" % js)\n return self._current_browser().execute_async_script(js)\n\n # Private\n\n def _get_javascript_to_execute(self, code):\n codepath = code.replace('/', os.sep)\n if not (os.path.isabs(codepath) and os.path.isfile(codepath)):\n return code\n self._html('Reading JavaScript from file %s.'\n % (codepath.replace(os.sep, '/'), codepath))\n codefile = open(codepath)\n try:\n return codefile.read().strip()\n finally:\n codefile.close()\n","sub_path":"Selenium2Library/src/Selenium2Library/keywords/_javascript.py","file_name":"_javascript.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"596963163","text":"import re, urllib.request, io\nfrom esports_site import EsportsSite\nfrom PIL import Image, ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\ndef login(user, wiki, timeout = 30):\n\t\treturn EsportsSite(user, wiki)\n\ndef log_into_fandom(user, wiki):\n\tif user == 'me':\n\t\tpassword = open('password_fandom.txt').read().strip()\n\t\tsite = extended_site.ExtendedSite('%s.fandom.com' % wiki, path='/')\n\t\tsite.login('RheingoldRiver', password)\n\t\treturn site\n\ndef report_errors(report_page, page, errors):\n\ttext = report_page.text()\n\terror_text = '\\n* '.join([e.args[0] for e in errors])\n\tnewtext = text + '\\n==Python Error Report==\\nPage: [[{}]] Messages:\\n* {}'.format(page, error_text)\n\treport_page.save(newtext)\n\ndef api_parse_query(site, datatype, values):\n\tquery_text = '{{#invoke:PrintParsedText|unordered|type=' + datatype + '|' + '|'.join(values) + '}}'\n\tquery_result = site.api(\n\t\t'parse',\n\t\tformat='json',\n\t\ttext=query_text,\n\t\tprop='text',\n\t\tdisablelimitreport=1,\n\t\twrapoutputclass=''\n\t)\n\tresult = query_result['parse']['text']['*']\n\tresult = result.replace('
', '').replace('\\n
', '')\n\tresult_tbl = result.split(',')\n\treturn result_tbl\n\ndef parse_ordered_field(val, sep):\n\tif not sep:\n\t\tsep = ','\n\ttbl = re.split('\\s*' + sep + '\\s*' + '\\s*', val)\n\treturn tbl\n\ndef check_links(template, key1, key2, sep, name, link):\n\tif not sep:\n\t\tsep = ','\n\tif template.has(key1):\n\t\tval1 = template.get(key1).value.strip()\n\t\ttbl1 = parse_ordered_field(val1, sep)\n\t\ttbl2 = ['' for _ in range(len(tbl1))] # list(range(len(tbl1)))\n\t\tif template.has(key2):\n\t\t\tval2 = template.get(key2).value.strip()\n\t\t\ttbl2 = parse_ordered_field(val2, sep)\n\t\tif name in tbl1:\n\t\t\ti = tbl1.index(name)\n\t\t\ttbl2[i] = link\n\t\t\ttemplate.add(key2,sep.join(tbl2), before=key1)\n\t\t\ttemplate.add(key1, val1, before=key2)\n\ndef get_filename_url_to_open(site, filename, size=None):\n\tpattern = r'.*src\\=\\\"(.+?)\\\".*'\n\tsize = '|' + str(size) + 'px' if size else ''\n\tto_parse_text = '[[File:{}|link=%s]]'.format(filename, size)\n\tresult = site.api('parse', title='Main Page', text=to_parse_text, disablelimitreport=1)\n\tparse_result_text = result['parse']['text']['*']\n\tprint(parse_result_text)\n\turl = re.match(pattern, parse_result_text)[1]\n\treturn url\n\ndef open_file_url(url):\n\treturn Image.open(io.BytesIO(urllib.request.urlopen(url).read()))\n\ndef open_image_from_filename(site, filename, size=None):\n\turl = get_filename_url_to_open(site, filename, size=size)\n\treturn open_file_url(url)\n\ndef tl_matches(tl, arr):\n\treturn [_ for _ in arr if tl.name.matches(_)]\n","sub_path":"log_into_wiki.py","file_name":"log_into_wiki.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"643061463","text":"# Day 2 - Challenge 1\n# 🚨 Don't change the code below 👇\ntwo_digit_number = int(input(\"Type a two digit number: \"))\n# 🚨 Don't change the code above 👆\n\n####################################\n#Write your code below this line 👇\nfrom math import log10\n\ndef digitize(x):\n n = int(log10(x))\n for i in range(n, -1, -1):\n factor = 10**i\n k = x // factor\n yield k\n x -= k * factor\n\nres = list(digitize(two_digit_number))\n\nfor i in res:\n i = i + i\n\nprint(i - 1)\n","sub_path":"Day2/ch1.py","file_name":"ch1.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"595523310","text":"import unittest\nimport random\nfrom skiplist import SkipList, LayerList\n\nMAX = 5000\n\nclass TestLayerList(unittest.TestCase):\n def test_layerlist(self):\n xs = LayerList(None)\n sample = range(MAX)\n random.shuffle(sample)\n for i in sample:\n xs.insert(i)\n self.assertTrue(i in xs)\n\n for i in sample:\n self.assertTrue(i in xs)\n\n self.assertFalse(-1 in xs)\n self.assertFalse(MAX in xs)\n \n xs.remove(-1)\n self.assertFalse(-1 in xs)\n\n random.shuffle(sample)\n for i in sample:\n self.assertTrue(i in xs)\n xs.remove(i)\n self.assertFalse(i in xs)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_layerlist.py","file_name":"test_layerlist.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"129517590","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport serial\nimport time\n\nt = np.arange(0, 10, 0.1)\nx = np.arange(0, 1, 0.01)\ny = np.arange(0, 1, 0.01)\nz = np.arange(0, 1, 0.01)\ndisplace = np.arange(100)\n\nserdev = '/dev/ttyACM0'\ns = serial.Serial(serdev)\n\nfor i in range(100):\n line = s.readline()\n x[i] = float(line)\n line = s.readline()\n y[i] = float(line)\n line = s.readline()\n z[i] = float(line)\n line = s.readline()\n displace[i] = int(line)\n \nfig, ax = plt.subplots(2, 1)\nax[0].plot(t, x, color='blue', linewidth=1, linestyle='-', label='x')\nax[0].plot(t, y, color='red', linewidth=1, linestyle='-', label='y')\nax[0].plot(t, z, color='green', linewidth=1, linestyle='-', label='z')\nax[0].legend(loc='lower left')\nax[0].set_xlabel('Time')\nax[0].set_ylabel('Acc Vector')\nax[1].stem(t, displace)\nax[1].set_xlabel('Time')\nax[1].set_ylabel('displace')\nplt.show()\ns.close()\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"69136880","text":"from sklearn.datasets import load_digits\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import confusion_matrix,classification_report,accuracy_score\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata=load_digits()\n\nX=data.images\ny=data.target\n\nlabe=list(zip(X,y))\n\nfor index,(image,label) in enumerate (labe[:6]):\n plt.subplot(3,6,index+1)\n plt.axis('off')\n plt.imshow(image,cmap=plt.cm.gray_r,interpolation='nearest')\n plt.title(label)\n \n\n#print(image)\nplt.show()\n#print(y)\n\nq=len(X)\n\nX1=X.reshape(q,-1) \n\nX_train=X1[:q//2]\ny_train=y[:q//2]\nX_test=X1[q//2:]\ny_test=y[q//2:]\n\nmodel=SVC(gamma=0.001)\nmodel.fit(X_train,y_train)\n\ny_pred=model.predict(X_test)\nprint(y_pred)\n\nprint(classification_report(y_test,y_pred))\nprint(accuracy_score(y_test,y_pred))\nprint(confusion_matrix(y_test,y_pred))\n\nlabe=list(zip(X//2,y_pred))\n\nfor index,(image,label) in enumerate (labe[:8]):\n plt.subplot(3,6,index+1)\n plt.axis('off')\n plt.imshow(image,cmap=plt.cm.gray_r,interpolation='nearest')\n plt.title(label)\n\nplt.show()\n\n\nq=len(X)\n \n \n\nX_train=X[:q//2]\ny_train=y[:q//2]\nX_test=X[q//2:]\ny_test=y[q//2:]\n\nmodel=SVC(gamma=0.001)\nmodel.fit(X_train,y_train)\n\ny_pred1=model.predict(X_test)\nprint(y_pred1)\n\n\n","sub_path":"DAY6/DAY6.py","file_name":"DAY6.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"202407270","text":"# Copyright (c) Amber Brown, 2015\n# See LICENSE for details.\n\nimport os\n\nimport configparser\n\n\ndef load_config(from_dir):\n\n config = configparser.ConfigParser()\n config.read(os.path.join(from_dir, \"towncrier.ini\"))\n\n if 'towncrier' not in config.sections():\n raise ValueError(\"No [towncrier] section.\")\n\n if 'package' not in config['towncrier']:\n raise ValueError(\n \"The [towncrier] section has no required 'package' key.\")\n\n return {\n 'package': config['towncrier']['package'],\n 'package_dir': config['towncrier'].get('package_dir', '.'),\n 'filename': config['towncrier'].get('filename', 'NEWS.rst'),\n 'sections': {'': ''},\n }\n","sub_path":"src/towncrier/_settings.py","file_name":"_settings.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"452623239","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n\n\"\"\"\n\nimport numpy as np\nimport os\nimport unittest\nfrom scipy import linalg\n\nfrom .. import auxfn_vers2 as auxfn\nfrom ..model.io_triangle import IOTriangle as green\nfrom . import test_tools\n\ncurrentdir = os.path.join(os.getcwd(), \"mea/tests\")\n\n@unittest.skip(\"This class is equivalent to GFAux.\")\nclass TestGFAuxC(unittest.TestCase):\n \"\"\" A class that implements tests for the Auxiliary green function class. If input is given \n as a sE file of a cluster, then it builds an auxiliary GF (it can do so\n for real or complex frequencies. However, imaginary frequencies is implicit).\n However, if an auxiliary green function file is given, \n it can extract the self energy (it is implicit then that the frequencies\n are on the real axis\"\"\"\n \n @classmethod\n def setUpClass(TestGFAux):\n print(\"\\nIn testauxfn_vers2.\\n\")\n\n def test_init(self):\n \"\"\" \"\"\"\n fin_sE_to = os.path.join(currentdir, \"files/self_moy.dat\")\n gf_aux = auxfn.GFAuxC(fin_sE_to=fin_sE_to)\n \n self.assertEqual(gf_aux.zn_col, 0)\n self.assertEqual(gf_aux.fin_sE_to, fin_sE_to)\n self.assertEqual(gf_aux.fout_sE_ctow, \"self_ctow.dat\")\n self.assertEqual(gf_aux.fout_gf_aux_to, \"gf_aux_to.dat\")\n \n \n def test_build_gfvec_aux(self):\n \"\"\" \"\"\"\n mu = 2.1\n fin_sE_to = os.path.join(currentdir, \"files/self_short_moy.dat\") \n gf_aux = auxfn.GFAuxC(fin_sE_to=fin_sE_to, mu=mu)\n gf_aux2 = auxfn.GFAuxC(fin_sE_to=fin_sE_to, rm_sE_ifty=True, mu=mu)\n gf_aux.build_gfvec_aux()\n gf_aux2.build_gfvec_aux()\n \n\n zn_vec = np.array([5.235989e-002, 1.570800e-001, 2.6179900e-001, 1.5027299e+001])\n \n \n sE_t = np.array([\n [ 7.29148945e+00 -1.25688297e+00j, 4.31791692e+00 -7.37366863e-01j,\n -4.37618486e+00 +7.44382438e-01j, 6.02348575e+00 -9.90968651e-01j,\n 4.05606418e+00 -4.07146712e-01j, 2.59560959e-01 -3.97514439e-03j],\n [ 6.37534240e+00 -3.08656815e+00j , 3.92112500e+00 -1.86394356e+00j,\n -3.80134014e+00 +1.78496589e+00j , 5.15813767e+00 -2.33078630e+00j,\n 3.66679027e+00 -9.42835945e-01j ,2.35758219e-01 -9.62837241e-03j],\n [ 5.42233260e+00 -4.06248226e+00j , 3.52542822e+00 -2.58309048e+00j,\n -3.22922418e+00 +2.29211959e+00j , 4.28316747e+00 -2.88633370e+00j,\n 3.28618116e+00 -1.15036779e+00j , 2.02677966e-01 -1.32361189e-02j],\n [ 5.55747767e+00 -2.25696764e+00j , 5.68107370e+00 -2.11065758e+00j,\n -2.65143495e-01 +3.18872569e-02j , 6.68961495e-02 +1.31238862e-02j,\n 7.97463733e-02 +5.27132295e-02j , 3.05312358e-03 -2.81419793e-02j]\n ]\n )\n\n sEvec_c = np.zeros((zn_vec.shape[0], 4, 4), dtype=complex)\n sEvec_c[:, 0, 0] = sE_t[:, 0] ; sEvec_c[:, 0, 1] = sE_t[:, 2] ; sEvec_c[:, 0, 2] = sE_t[:, 3] ; sEvec_c[:, 0, 3] = sE_t[:, 2]\n sEvec_c[:, 1, 0] = sEvec_c[:, 0, 1]; sEvec_c[:, 1, 1] = sE_t[:, 1] ; sEvec_c[:, 1, 2] = sEvec_c[:, 0, 1] ; sEvec_c[:, 1, 3] = sE_t[:, 4]\n sEvec_c[:, 2, 0] = sEvec_c[:, 0, 2] ; sEvec_c[:, 2, 1] = sEvec_c[:, 1, 2] ; sEvec_c[:, 2, 2] = sEvec_c[:, 0, 0] ; sEvec_c[:, 2, 3] = sEvec_c[:, 0, 1]\n sEvec_c[:, 3, 0] = sEvec_c[:, 0, 3] ; sEvec_c[:, 3, 1] = sEvec_c[:, 1, 3] ; sEvec_c[:, 3, 2] = sEvec_c[:, 2, 3] ; sEvec_c[:, 3, 3] = sEvec_c[:, 1, 1]\n\n sEvec_ir = green().c_to_ir(sEvec_c)\n\n sE_ifty = green().read_green_infty(sEvec_ir)\n\n \n \n # now let us form the gf_aux\n gfvec_test_c = np.zeros((zn_vec.shape[0], 4, 4), dtype=complex)\n gfvec_test_ir = gfvec_test_c.copy()\n \n for (i, sE) in enumerate(sEvec_c.copy()):\n zz = 1.0j*zn_vec[i] + mu\n gfvec_test_c[i] = linalg.inv(np.eye(4)*zz - sE)\n\n gfvec_test_ir = green().c_to_ir(gfvec_test_c)\n\n\n try:\n np.testing.assert_allclose(gf_aux.zn_vec, zn_vec, rtol=1e-7, atol=1e-7)\n np.testing.assert_allclose(gf_aux.sEvec_c, sEvec_c, rtol=1e-7, atol=1e-7)\n np.testing.assert_allclose(gf_aux.sE_infty, sE_ifty, rtol=1e-7, atol=1e-7)\n np.testing.assert_allclose(gf_aux.sEvec_c[:, 3, 3], sE_t[:, 1], rtol=1e-7, atol=1e-7)\n np.testing.assert_allclose(gf_aux.gfvec_aux_c.shape, gfvec_test_c.shape, rtol=1e-7, atol=1e-7)\n # np.testing.assert_allclose(gf_aux.gfvec_aux_c, gfvec_test_c, rtol=1e-7, atol=1e-7)\n # np.testing.assert_allclose(gf_aux2.gfvec_aux_ir, gfvec_test_ir, rtol=1e-7, atol=1e-7)\n # np.testing.assert_allclose(gf_aux.gfvec_aux_ir, gfvec_test_ir2, rtol=1e-7, atol=1e-7)\n except AssertionError:\n self.fail(\"ayaya np.allclose failed at test_build_gf_aux\")\n\n\n\n # def test_ac(self):\n # \"\"\" \"\"\"\n \n # fin_sE_to = os.path.join(currentdir, \"files/self_moyb60U3n05.dat\")\n # gf_aux = auxfn.GFAux(fin_sE_to=fin_sE_to, rm_sE_ifty=False)\n # gf_aux.build_gfvec_aux()\n \n # gf_aux.ac(fin_OME_default=os.path.join(currentdir, \"files/OME_default.dat\"), \\\n # fin_OME_other=os.path.join(currentdir, \"files/OME_other.dat\"), \\\n # fin_OME_input=os.path.join(currentdir, \"files/OME_input_test.dat\")\n # )\n\n # # gf_aux.get_sE_w_list() put this line in the next test\n # Aw_manual_small_truncation = np.loadtxt(os.path.join(currentdir,\"files/Aw_manual_small_truncation.dat\"))\n # w_n_manual = Aw_manual_small_truncation[:, 0]\n # Aw_manual = np.delete(Aw_manual_small_truncation,0, axis=1)\n\n # w_n =gf_aux.w_vec_list[0]\n # Aw = gf_aux.Aw_t_list[0][:, 0][:, np.newaxis]\n # # print(\"Aw.shape = \", Aw.shape)\n # # print(Aw_manual.shape)\n\n\n # try:\n # np.testing.assert_allclose(w_n.shape, w_n_manual.shape)\n # np.testing.assert_allclose(Aw.shape, Aw_manual.shape)\n # test_tools.compare_arrays(w_n, w_n_manual, rprecision=10**-2, n_diff_max=5, zero_equivalent=10**-5)\n # test_tools.compare_arrays(Aw, Aw_manual, rprecision=10**-2, n_diff_max=5, zero_equivalent=10**-5)\n # except AssertionError:\n # self.fail(\"ayaya np.allclose failed at test_build_gf_aux\") \n\n\n \n \n # def test_get_sEvec_w(self):\n # \"\"\" \"\"\"\n # #print(\"\\n\\n IN test_get_sE_w \\n\\n\")\n # fin_sE_to = os.path.join(currentdir, \"files/self_moy.dat\")\n # gf_aux = auxfn.GFAux(fin_sE_to=fin_sE_to, rm_sE_ifty=False)\n # gf_aux.build_gfvec_aux()\n \n # gf_aux.ac(fin_OME_default=os.path.join(currentdir, \"files/OME_default.dat\"), \\\n # fin_OME_other=os.path.join(currentdir, \"files/OME_other.dat\"), \\\n # fin_OME_input=os.path.join(currentdir, \"files/OME_input_get_sE.dat\")\n # )\n \n # gf_aux.get_sEvec_w_list()\n\n # sE_w_to_test = np.loadtxt(\"self_ctow0.dat\")\n # sE_w_to_test_good = np.loadtxt(os.path.join(currentdir, \"files/self_ctow_test_good.dat\"))\n\n # try:\n # # print(\"SHAPEs in test_auxiliary = \", sE_w_to_test.shape, \" \", sE_w_to_test_good.shape)\n # arr1 = sE_w_to_test.flatten()\n # arr2 = sE_w_to_test_good.flatten()\n # for i in range(arr1.shape[0]):\n # if abs(arr1[i]) > 10**-2.0:\n # tmp = abs(arr1[i] - arr2[i])/abs(arr1[i])\n # if tmp > 10**-2.0:\n # print(tmp)\n # test_tools.compare_arrays(sE_w_to_test, sE_w_to_test_good, rprecision=10**-2, n_diff_max=10, zero_equivalent=10**-2)\n # #np.testing.assert_allclose(sE_w_to_test, sE_w_to_test_good, rtol=1e-3)\n # except AssertionError:\n # self.fail(\"Ayaya, np.allclose failed at test_get_sE_w\")\n\n\n\n\nif __name__ == '__main__':\n unittest.main() ","sub_path":"mea/tests/test_auxfn_vers2.py","file_name":"test_auxfn_vers2.py","file_ext":"py","file_size_in_byte":8105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"76184704","text":"\"\"\"\nCopyright 2012 Basho Technologies, Inc.\n\nThis file is provided to you under the Apache License,\nVersion 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain\na copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied. See the License for the\nspecific language governing permissions and limitations\nunder the License.\n\"\"\"\nimport riak_pb\nfrom riak.riak_object import RiakObject\n\nRIAKC_RW_ONE = 4294967294\nRIAKC_RW_QUORUM = 4294967293\nRIAKC_RW_ALL = 4294967292\nRIAKC_RW_DEFAULT = 4294967291\n\n\nclass RiakPbcCodec(object):\n \"\"\"\n Protobuffs Encoding and decoding methods for RiakPbcTransport.\n \"\"\"\n\n rw_names = {\n 'default': RIAKC_RW_DEFAULT,\n 'all': RIAKC_RW_ALL,\n 'quorum': RIAKC_RW_QUORUM,\n 'one': RIAKC_RW_ONE\n }\n\n def __init__(self, **unused_args):\n if riak_pb is None:\n raise NotImplementedError(\"this transport is not available\")\n super(RiakPbcCodec, self).__init__(**unused_args)\n\n def translate_rw_val(self, rw):\n \"\"\"\n Converts a symbolic quorum value into its on-the-wire\n equivalent.\n\n :param rw: the quorum\n :type rw: string, integer\n :rtype: integer\n \"\"\"\n val = self.rw_names.get(rw)\n if val is None:\n return rw\n elif type(rw) is int and rw >= 0:\n return val\n else:\n return None\n\n def decode_content(self, rpb_content, robj):\n \"\"\"\n Decodes a single sibling from the protobuf representation into\n a RiakObject.\n\n :rtype: (RiakObject)\n \"\"\"\n\n if rpb_content.HasField(\"deleted\"):\n robj.deleted = True\n if rpb_content.HasField(\"content_type\"):\n robj.content_type = rpb_content.content_type\n if rpb_content.HasField(\"charset\"):\n robj.charset = rpb_content.charset\n if rpb_content.HasField(\"content_encoding\"):\n robj.content_encoding = rpb_content.content_encoding\n if rpb_content.HasField(\"vtag\"):\n robj.vtag = rpb_content.vtag\n links = []\n for link in rpb_content.links:\n if link.HasField(\"bucket\"):\n bucket = link.bucket\n else:\n bucket = None\n if link.HasField(\"key\"):\n key = link.key\n else:\n key = None\n if link.HasField(\"tag\"):\n tag = link.tag\n else:\n tag = None\n links.append((bucket, key, tag))\n if links:\n robj.links = links\n if rpb_content.HasField(\"last_mod\"):\n robj.last_mod = rpb_content.last_mod\n if rpb_content.HasField(\"last_mod_usecs\"):\n robj.last_mod_usecs = rpb_content.last_mod_usecs\n usermeta = {}\n for usermd in rpb_content.usermeta:\n usermeta[usermd.key] = usermd.value\n if len(usermeta) > 0:\n robj.usermeta = usermeta\n indexes = set()\n for index in rpb_content.indexes:\n if index.key.endswith(\"_int\"):\n indexes.add((index.key, int(index.value)))\n else:\n indexes.add((index.key, index.value))\n\n if len(indexes) > 0:\n robj.indexes = indexes\n\n robj.encoded_data = rpb_content.value\n robj.exists = True\n\n return robj\n\n def encode_content(self, robj, rpb_content):\n \"\"\"\n Fills an RpbContent message with the appropriate data and\n metadata from a RiakObject.\n \"\"\"\n if robj.content_type:\n rpb_content.content_type = robj.content_type\n if robj.charset:\n rpb_content.charset = robj.charset\n if robj.content_encoding:\n rpb_content.content_encoding = robj.content_encoding\n for uk in robj.usermeta:\n pair = rpb_content.usermeta.add()\n pair.key = uk\n pair.value = robj.usermeta[uk]\n for link in robj.links:\n pb_link = rpb_content.links.add()\n try:\n bucket, key, tag = link\n except ValueError:\n raise RiakError(\"Invalid link tuple %s\" % link)\n\n pb_link.bucket = bucket\n pb_link.key = key\n if tag:\n pb_link.tag = tag\n else:\n pb_link.tag = ''\n\n for field, value in robj.indexes:\n pair = rpb_content.indexes.add()\n pair.key = field\n pair.value = str(value)\n\n rpb_content.value = str(robj.encoded_data)\n","sub_path":"riak/transports/pbc/codec.py","file_name":"codec.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"648894426","text":"import cv2\r\nimport numpy as np\r\n\r\nface_classifier=cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\r\n#face_eye=cv2.CascadeClassifier(\"haarcascade_eye.xml\")\r\ncap=cv2.VideoCapture(0)\r\n\r\nwhile cap.isOpened():\r\n _,img=cap.read()\r\n\r\n gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n faces=face_classifier.detectMultiScale(img,1.1,5) # x,y,w,h values\r\n \r\n\r\n for (x,y,w,h) in faces:\r\n cv2.rectangle(img,(x,y),(x+w,y+h) ,(125,0,255),4)\r\n roi_gray=gray[y:y+h,x:x+w]\r\n roi_color=img[y:y+h,x:x+w]\r\n #cv2.putText(roi_color,'harsh',(30,35),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)\r\n '''\r\n eye=face_eye.detectMultiScale(roi_gray,1.1,5)\r\n for (ex,ey,ew,eh) in eye:\r\n a=cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh) ,(125,142,0),4)\r\n #if bool(a) == False:\r\n # print('blink')q\r\n '''\r\n\r\n c=len(faces)\r\n \r\n cv2.putText(img,str(c)+' faces',(400,450),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)\r\n cv2.imshow(\"image\",img)\r\n if cv2.waitKey(1)==27:\r\n break\r\nprint(c)\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\n\r\n\r\n","sub_path":"COUNTING FACES.py","file_name":"COUNTING FACES.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"153780693","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\niris = pd.read_csv('../Dataset/Pandas Foundations/iris.csv')\n\nprint(iris.head())\n\nprint(iris['species'].describe())\n# count 150\n# unique 3\n# top versicolor\n# freq 50\n# Name: species, dtype: object\n# count: # non-null entries\n# unique: # distinct values\n# top: most frequent category\n# Freq: # No Occurences of Top\n\n# To Get the Unique Values\nprint(iris['species'].unique())\n\n# Filtering by Species\nindices = iris['species'] == 'setosa'\nsetosa = iris.loc[indices,:] # Extract New DataFrame\nindices = iris['species'] == 'versicolor'\nversicolor = iris.loc[indices,:] # Extract New DataFrame\nindices = iris['species'] == 'virginica'\nvirginica = iris.loc[indices,:] # Extract New DataFrame\n# Print\nprint(setosa.head(2))\nprint(versicolor.head(2))\nprint(virginica.head(2))\n\niris.plot(kind = 'hist', bins = 50, range=(0,8), alpha=0.3)\nplt.title('Entire iris data set')\nplt.xlabel('[cm]')\n\nsetosa.plot(kind = 'hist', bins = 50, range=(0,8), alpha=0.3)\nplt.title('Entire setosa data set')\nplt.xlabel('[cm]')\n\nversicolor.plot(kind = 'hist', bins = 50, range=(0,8), alpha=0.3)\nplt.title('Entire versicolor data set')\nplt.xlabel('[cm]')\n\nvirginica.plot(kind = 'hist', bins = 50, range=(0,8), alpha=0.3)\nplt.title('Entire virginica data set')\nplt.xlabel('[cm]')\n\nplt.show()\n\n# Statistical EDA: describe()\n\ndescribe_all = iris.describe()\ndescribe_setosa = setosa.describe()\ndescribe_versicolor = versicolor.describe()\ndescribe_virginica = virginica.describe()\n\n# Computing Errors\nerror_setosa = 100 * np.abs(describe_setosa - describe_all)\nerror_setosa = error_setosa / describe_setosa\n\nerror_versicolor = 100 * np.abs(describe_versicolor - describe_all)\nerror_versicolor = error_versicolor / describe_versicolor\n\nerror_virginica = 100 * np.abs(describe_virginica - describe_all)\nerror_virginica = error_virginica / describe_virginica\n\nprint(error_setosa)\nprint(error_virginica)\nprint(error_versicolor)","sub_path":"03_Pandas Foundations/07_EDA_Separating_Populations.py","file_name":"07_EDA_Separating_Populations.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"40733005","text":"\"\"\"Tests for ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.ops import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import googletest\n\nfrom ops import *\n\nclass SmoothCosineSimilarityTest(test_util.TensorFlowTestCase):\n def testSmoothCosineSimilarity(self):\n m = constant_op.constant(\n [[1,2,3],\n [2,2,2],\n [3,2,1],\n [0,2,4]], dtype=np.float32)\n v = constant_op.constant([2,2,2], dtype=np.float32)\n for use_gpu in [True, False]:\n with self.test_session(use_gpu=use_gpu):\n sim = smooth_cosine_similarity(m, v).eval()\n self.assertAllClose(sim, [0.92574867671153,\n 0.99991667361053,\n 0.92574867671153,\n 0.77454667246876])\n\nclass CircularConvolutionTest(test_util.TensorFlowTestCase):\n def testCircularConvolution(self):\n v = constant_op.constant([1,2,3,4,5,6,7], dtype=tf.float32)\n k = constant_op.constant([0,0,1], dtype=tf.float32)\n for use_gpu in [True, False]:\n with self.test_session(use_gpu=use_gpu):\n cir_conv = circular_convolution(v, k).eval()\n self.assertAllEqual(cir_conv, [7,1,2,3,4,5,6])\n\nclass BinaryCrossEntropyTest(test_util.TensorFlowTestCase):\n def testBinaryCrossEntropy(self):\n logits = np.array([0,1,0,1,0], dtype=np.float32)\n targets = np.array([0,1,1,1,1], dtype=np.float32)\n for use_gpu in [True, False]:\n with self.test_session(use_gpu=use_gpu):\n loss = binary_cross_entropy_with_logits(logits, targets).eval()\n self.assertAllClose(loss, 11.052408446371)\n\nif __name__ == \"__main__\":\n googletest.main()\n\n\n\n\n\n\n","sub_path":"tensorflow/model1/ops_test.py","file_name":"ops_test.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"167906537","text":"#coding:utf-8\n\nimport tkinter\nimport random\nimport time\nimport joueur\n\n\ndef melanger_str(motMystere):\n\tmotMystere.strip()\n\ti = 0\n\tmelange = ''\n\twhile i < len(motMystere):\n\t\tnbre_alea = random.randint(0,len(motMystere) - 1)\n\t\tmelange += motMystere[nbre_alea]\n\t\tmotMystere = motMystere[:nbre_alea] + motMystere[nbre_alea+1:]\n\treturn melange\n\ndef get_motInDico():\n\twith open(\"dico.txt\",\"r\") as dico: #autre façon d'ouvrir des fichier\n\t\tlisteDico = dico.readlines() # C'EST MIEUX :)\n\t\tnbre_ligne = len(listeDico)\n\t\treturn listeDico[random.randint(0,nbre_ligne)].strip()\n\ndef frame_quit(): \n\tapp.quit()\n\ndef button_new_game():\n\tvarTk_verif.set(f\"Le mot mystere était : {var_motMystere.get()}\")\n\tnew_game()\n\ndef new_game():\n\tvar_motMystere.set(get_motInDico())\n\tmotMystereMelange = melanger_str(var_motMystere.get())\n\tvarTk_indice.set(\"indice : {}\".format(motMystereMelange))\n\tvar_tk_text.set(\"\")\n\n\n\ndef testValid():\n\tmotMystere = var_motMystere.get()\n\tsaisie = var_tk_text.get()\n\tif saisie == motMystere:\n\t\tvarTk_verif.set(\"c'est cela ! le mot mystere était donc : {}\".format(motMystere))\n\t\tprint(\"vrai\")\n\t\tjoueur1.setScore(joueur1.getScore() + 1)\n\t\tvarTk_label_Score.set(f\"score : {joueur1.getScore()}\")\n\t\ttime.sleep(1.5)\n\t\tnew_game()\n\telse:\n\t\tvarTk_verif.set(\"faux !\")\n\t\tprint(\"faux\")\n\njoueur1 = joueur.Joueur() #creation joueur pour enregistré le score \n# creation fenetre -----------------------------------------------\napp = tkinter.Tk()\napp.resizable(width=False,height=False)\nscreen_x = app.winfo_screenwidth()\nscreen_y = app.winfo_screenheight()\nwindow_x = 450\nwindow_y = 250\n\npos_X = (screen_x // 2) - (window_x // 2)\npos_Y = (screen_y // 2) - (window_y // 2)\n\ngeo = \"{}x{}+{}+{}\".format(window_x,window_y,pos_X,pos_Y)\napp.geometry(geo)\n\nmainFrame = tkinter.Frame(app,width=450,height=250)\nmainFrame.pack()\n\ngameFrame = tkinter.LabelFrame(mainFrame,borderwidth=2,width=100,height=150)\ngameFrame.place(x=10,y=10)\nvar_motMystere = tkinter.StringVar()\nvar_motMystere.set(get_motInDico())\nmotMystereMelange = melanger_str(var_motMystere.get())\n\nvarTk_indice = tkinter.StringVar()\nvarTk_indice.set(\"indice : {}\".format(motMystereMelange))\ntk_label_indice = tkinter.Label(gameFrame, textvariable=varTk_indice)\ntk_label_indice.pack()\n\n\nvar_tk_text = tkinter.StringVar()\ntk_text = tkinter.Entry(gameFrame,textvariable=var_tk_text)\ntk_text.bind(\"\",lambda event : testValid())\ntk_text.pack()\n\n\n\nvarTk_verif = tkinter.StringVar()\ntk_label_verif = tkinter.Label(gameFrame, textvariable=varTk_verif)\ntk_label_verif.pack()\n\n\ntk_btn_valid = tkinter.Button(gameFrame,width=4,height=1,text=\"check\",command=testValid)\ntk_btn_valid.pack()\nbuttonControl = tkinter.LabelFrame(mainFrame,borderwidth=2)\nbuttonControl.place(x=320,y=5)\nbtn_newGame = tkinter.Button(buttonControl,text=\"changer de mot\",bg='red',width=16,height=2,command=button_new_game)\nbtn_newGame.pack()\n\nbtn_quit = tkinter.Button(buttonControl,text=\"quitter le programme\", bg='red',width=16,height=2,command=frame_quit)\nbtn_quit.pack()\n\nFrameScore = tkinter.LabelFrame(mainFrame,borderwidth=2)\nFrameScore.place(x=10,y=150)\n\nvarTk_label_Score = tkinter.StringVar()\nvarTk_label_Score.set(f\"score : {joueur1.getScore()}\")\ntk_label_Score = tkinter.Label(FrameScore,textvariable=varTk_label_Score)\ntk_label_Score.pack()\n\n\napp.mainloop()","sub_path":"projet/projet 2 - devine mot/v2.2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"381505721","text":"#LLAMA PARTY\n#This is a party for all of the llamas to play in.\ndef llamaParty():\n pic = makePicture('/Users/vanessalandayan/Downloads/CPS109/mediasources-4ed/llama.jpg')\n gift(pic)\n ribbon(pic)\n streamers(pic, 0, 20, 359, 20, 10, pink)\n streamers(pic, 0, 30, 359, 30, 10, cyan)\n streamers(pic, 0, 40, 359, 40, 10, pink)\n circle(pic, 190, 200, 30, green)\n redLights(pic)\n show(pic)\n\n#Function 1\n#This function puts a blue gift box beside the llama. \ndef gift(picture):\n pixels = getPixels(picture)\n for pixel in pixels:\n x = getX(pixel)\n y = getY(pixel)\n if 245 < x < 345 and 350 < y < 410:\n setColor(pixel, blue)\n\n#Function 2\n#This function puts green lines for ribbon on top of the gift. \ndef ribbon(picture):\n pixels = getPixels(picture)\n for pixel in pixels:\n x = getX(pixel)\n y = getY(pixel)\n if 295 < x < 305 and 350 < y < 410:\n setColor(pixel, green)\n if 245 < x < 345 and 380 < y < 390:\n setColor(pixel, green)\n\n#Function 3\n#This function puts creates a thick lines for streamers on the ceiling. \ndef streamers(picture, x1, y1, x2, y2, thickness, color) : \n pixels = getPixels(picture)\n m = 1.0 * (y2 - y1) / (x2 - x1)\n b = y1 - m * x1\n for pixel in pixels : \n x = getX(pixel)\n y = getY(pixel)\n y_line = m * x + b\n distance = int(abs(y_line - y) + 0.5) \n if distance < thickness / 2 :\n setColor(pixel, color)\n\n#Function 4\n#This function makes the color of the picture more red, so it looks like\n#there are red lights for the party. \ndef redLights(picture):\n for p in getPixels(picture):\n Blue = getBlue(p)\n Red = getRed(p)\n Green = getGreen(p)\n setBlue(p, Blue/2)\n setRed(p, Red*1.25)\n setGreen(p, Green/2) \n\n#Function 5\n#This function makes a circle to resemble a ball on the llama's back for him\n#to play with at the party.\ndef circle(picture, xc, yc, radius, color) :\n pixels = getPixels(picture) \n for pixel in pixels :\n x = getX(pixel)\n y = getY(pixel)\n distance = math.sqrt((x - xc)**2 + (y - yc)**2) \n if distance < radius :\n setColor(pixel, color)\n","sub_path":"rose1.py","file_name":"rose1.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"412020695","text":"from graphics import *\r\n\r\n\r\ndef drawPatchNine(win, colour, startX, startY):\r\n \r\n endX=startX+100\r\n endY=startY+100\r\n \r\n colour1 = colour\r\n colour2 = \"white\"\r\n \r\n for i in range (10):\r\n rectangle = Rectangle(Point(startX,startY),Point(endX, endY))\r\n rectangle.setFill(colour2)\r\n rectangle.setOutline(colour2)\r\n rectangle.draw(win)\r\n endX = endX - 10\r\n endY = endY - 10\r\n \r\n colour1,colour2 = colour2,colour1\r\n \r\n \r\n\r\ndef drawPatchOne(win, colour, startX, startY):\r\n\r\n colour1 = colour\r\n colour2 = \"white\"\r\n \r\n for i in range (4): \r\n for x in range (2):\r\n \r\n rectangle = Rectangle(Point(startX,startY),Point(startX+50,startY+25))\r\n rectangle.setFill(colour2)\r\n rectangle.setOutline(\"black\")\r\n rectangle.draw(win)\r\n \r\n divider = Line(Point(startX+25,startY),Point(startX+25,startY+25))\r\n divider.draw(win)\r\n \r\n rect1 = Rectangle(Point(startX+5,startY+0),Point(startX+20,startY+10.5))\r\n rect1.setFill(colour1)\r\n rect1.draw(win)\r\n \r\n rect2 = Rectangle(Point(startX+5,startY+14.5),Point(startX+20,startY+25))\r\n rect2.setFill(colour1)\r\n rect2.draw(win)\r\n \r\n rect3 = Rectangle(Point(startX+25,startY+5),Point(startX+35,startY+20))\r\n rect3.setFill(colour1)\r\n rect3.draw(win)\r\n \r\n rect4 = Rectangle(Point(startX+40,startY+5),Point(startX+50,startY+20))\r\n rect4.setFill(colour1)\r\n rect4.draw(win)\r\n \r\n startX = startX + 50\r\n colour1,colour2 = colour2,colour1\r\n \r\n startY = startY + 25\r\n startX = startX - 100\r\n \r\n colour1,colour2 = colour2,colour1\r\n \r\n \r\n\r\n\r\ndef mainFull():\r\n \r\n gridSize, colours = getInputs() \r\n \r\n patchworkSize = gridSize * 100\r\n patchNineBorder = patchworkSize - 200\r\n \r\n win = GraphWin(\"draw Patch\", patchworkSize, patchworkSize)\r\n win.setCoords(0,0,patchworkSize,patchworkSize)\r\n \r\n startX = 0\r\n startY = 0\r\n \r\n \r\n for i in range (gridSize):\r\n for q in range (gridSize):\r\n \r\n if startX < patchNineBorder and startY < patchNineBorder:\r\n if startX == startY:\r\n drawPatchNine(win, colours[1], startX, startY)\r\n \r\n elif startX > startY:\r\n drawPatchNine(win, colours[2], startX, startY)\r\n \r\n else:\r\n drawPatchNine(win, colours[0], startX, startY)\r\n\r\n else:\r\n if startX == startY:\r\n drawPatchOne(win, colours[1], startX, startY)\r\n \r\n elif startX > startY:\r\n drawPatchOne(win, colours[2], startX, startY)\r\n \r\n else:\r\n drawPatchOne(win, colours[0], startX, startY)\r\n\r\n startX = startX + 100\r\n \r\n \r\n startX = startX - patchworkSize\r\n startY = startY + 100\r\n \r\n \r\n while True:\r\n click = win.getMouse()\r\n clickedX = click.getX()\r\n clickedY = click.getY()\r\n bottomLeft = Point(clickedX-(clickedX%100),clickedY-(clickedY%100)) \r\n topRight = Point(clickedX+(100-clickedX%100),clickedY+(100-clickedY%100)) \r\n box = Rectangle(bottomLeft,topRight)\r\n box.setWidth(5) \r\n box.draw(win)\r\n editingGrid(win, bottomLeft,topRight, box)\r\n \r\n \r\ndef getInputs():\r\n \r\n validGridSizes = [5,7,9]\r\n sizeSet = False\r\n while not sizeSet:\r\n gridSize = int(input(\"enter the grid size\\t\"))\r\n if gridSize not in validGridSizes:\r\n print(\"the only valid sizes are 5, 7, and 9\")\r\n else:\r\n sizeSet = True \r\n \r\n \r\n colours = [\"first\",\"second\",\"third\"]\r\n replaced = 0\r\n while replaced < 3:\r\n colour = input(\"Enter the {} colour,\\t\".format(colours[replaced]))\r\n if colour == \"red\" or colour == \"green\" or colour == \"blue\" or colour == \"magenta\" or colour == \"orange\" or colour == \"pink\":\r\n colours[replaced] = colour\r\n replaced = replaced + 1 \r\n else:\r\n print(\"this is not a valid colour.\\n\")\r\n return(gridSize, colours)\r\n\r\n\r\n\r\ndef editingGrid(win, bottomLeft,topRight, box):\r\n enterPressed = False\r\n dPressed = False\r\n \r\n while not enterPressed:\r\n \r\n keyPress = win.getKey()\r\n \r\n if keyPress == \"d\":\r\n erase = Rectangle(bottomLeft,topRight)\r\n erase.setFill(\"white\")\r\n erase.setWidth(0)\r\n erase.draw(win)\r\n \r\n dPressed = True\r\n\r\n if keyPress == \"m\":\r\n if dPressed == True:\r\n drawPatchNine(win,\"magenta\",bottomLeft.getX(),bottomLeft.getY())\r\n dPressed = False\r\n\r\n\r\n\r\n if keyPress == \"g\":\r\n if dPressed == True:\r\n drawPatchNine(win,\"green\",bottomLeft.getX(),bottomLeft.getY())\r\n dPressed = False\r\n\r\n if keyPress == \"b\":\r\n if dPressed == True:\r\n drawPatchNine(win,\"blue\",bottomLeft.getX(),bottomLeft.getY())\r\n dPressed = False\r\n\r\n if keyPress == \"r\":\r\n if dPressed ==True:\r\n drawPatchNine(win,\"red\",bottomLeft.getX(),bottomLeft.getY())\r\n dPressed = False\r\n\r\n\r\n if keyPress == \"o\":\r\n if dPressed == True:\r\n drawPatchNine(win,\"orange\",bottomLeft.getX(),bottomLeft.getY())\r\n dPressed = False\r\n\r\n\r\n if keyPress == \"p\":\r\n if dPressed == True:\r\n drawPatchNine(win,\"pink\",bottomLeft.getX(),bottomLeft.getY())\r\n dPressed = False\r\n\r\n\r\n box.undraw()\r\n box.draw(win)\r\n \r\n if keyPress == \"Return\":\r\n enterPressed = True\r\n box.undraw()\r\n \r\n \r\n if keyPress == \"Escape\":\r\n enterPressed = True\r\n win.close()\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"Python/graphical code/889519.py","file_name":"889519.py","file_ext":"py","file_size_in_byte":6367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"561590663","text":"from pathlib import Path\nimport abc\nimport typing\n\nfrom hat.util import json\nimport hat.monitor.common\n\n\njson_schema_repo = json.SchemaRepository(\n json.json_schema_repo,\n hat.monitor.common.json_schema_repo,\n json.SchemaRepository.from_json(Path(__file__).parent /\n 'json_schema_repo.json'))\n\n\nAdapterConf = json.Data\n\nCreateAdapter = typing.Callable[[AdapterConf, 'AdapterEventClient'],\n typing.Awaitable['Adapter']]\n\n\nclass Adapter(abc.ABC):\n \"\"\"Adapter interface\n\n Adapters are implemented as python modules which are dynamically imported.\n Each adapter instance has configuration which must include `module` -\n python module identifier. It is expected that this module implements:\n\n * json_schema_id (Optional[str]): JSON schema id\n * event_type_prefix (Optional[hat.event.common.EventType]):\n event type prefix\n * create (Callable[[json.Data,AdapterEventClient],Adapter]):\n coroutine responsible for creating adapter\n\n If module defines JSON schema id, it will be used for aditional\n validation of module's configuration.\n\n Event type prefix is used for filtering events that can be obtained\n by calling :meth:`AdapterEventClient.receive`. It can not contain\n subscription wildchars. If it is None, adapter will not receive any\n event notifications.\n\n `create` coroutine is called with adapter instance configuration and\n adapter event client.\n\n \"\"\"\n\n @property\n @abc.abstractmethod\n def closed(self):\n \"\"\"asyncio.Future: closed future\"\"\"\n\n @abc.abstractmethod\n async def async_close(self):\n \"\"\"Async close\"\"\"\n\n @abc.abstractmethod\n async def create_session(self, client):\n \"\"\"Create new adapter session\n\n Args:\n client (AdapterSessionClient): adapter session client\n\n Returns:\n AdapterSession\n\n \"\"\"\n\n\nclass AdapterSession(abc.ABC):\n \"\"\"Adapter's single client session\"\"\"\n\n @property\n @abc.abstractmethod\n def closed(self):\n \"\"\"asyncio.Future: closed future\"\"\"\n\n @abc.abstractmethod\n async def async_close(self):\n \"\"\"Async close\"\"\"\n\n\nclass AdapterSessionClient(abc.ABC):\n \"\"\"Adapter's session client represents single juggler connection\"\"\"\n\n @property\n def user(self):\n \"\"\"str: user identifier\"\"\"\n\n @property\n def roles(self):\n \"\"\"List[str]: user roles\"\"\"\n\n @property\n def local_data(self):\n \"\"\"json.Data: json serializable local data\"\"\"\n\n @property\n def remote_data(self):\n \"\"\"json.Data: json serializable remote data\"\"\"\n\n def register_change_cb(self, cb):\n \"\"\"Register remote data change callback\n\n Args:\n cb (Callable[[],None]): change callback\n\n Returns:\n util.RegisterCallbackHandle\n\n \"\"\"\n\n def set_local_data(self, data):\n \"\"\"Set local data\n\n Args:\n data (json.Data): json serializable local data\n\n \"\"\"\n\n async def send(self, msg):\n \"\"\"Send message\n\n Args:\n msg (json.Data): json serializable message\n\n \"\"\"\n\n async def receive(self):\n \"\"\"Receive message\n\n Returns:\n json.Data: json serializable message\n\n \"\"\"\n\n\nclass AdapterEventClient(abc.ABC):\n \"\"\"Adapters interface to event client\n\n Received event notifications include only those that start with\n `event_type_prefix` as defined by adapter implementation.\n\n \"\"\"\n\n async def receive(self):\n \"\"\"See :meth:`hat.event.client.Client.receive`\"\"\"\n\n def register(self, events):\n \"\"\"See :meth:`hat.event.client.Client.register`\"\"\"\n\n async def register_with_response(self, events):\n \"\"\"See :meth:`hat.event.client.Client.register_with_response`\"\"\"\n\n async def query(self, data):\n \"\"\"See :meth:`hat.event.client.Client.query`\"\"\"\n","sub_path":"src_py/hat/gui/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"407409361","text":"\nfrom django.conf.urls import url\n\nfrom projects import views\n\nurlpatterns = [\n url(r'^$', views.ProjectListView.as_view(), name='ProjectsListView'),\n url(r'^(?P\\S+)/$', views.ProjectDetailView.as_view(), name=\"ProjectDetailView\"),\n url(r'^tag/(?P\\S+)$', views.TagDetailView.as_view(), name=\"TagDetailView\"),\n]","sub_path":"projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"181437322","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nPost Process\nUsage:\n post_process.py \n post_process.py (-h | --help)\nOptions:\n -h --help Show this help\n\"\"\"\n\nimport os\nimport sys\nimport glob\nimport shutil\n\nsys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))\n\nfrom docopt import docopt\n\nfrom scihub_eva.utils.sys_utils import *\n\n\nUSELESS_QT_LIBS = [\n 'Qt3D',\n 'Qt3DAnimation',\n 'Qt3DCore',\n 'Qt3DExtras',\n 'Qt3DInput',\n 'Qt3DLogic',\n 'Qt3DQuick',\n 'Qt3DQuickAnimation',\n 'Qt3DQuickExtras',\n 'Qt3DQuickInput',\n 'Qt3DQuickRender',\n 'Qt3DQuickScene2D',\n 'Qt3DRender',\n 'Qt5Compat',\n 'QtBluetooth',\n 'QtBodymovin',\n 'QtCharts',\n 'QtChartsQml',\n 'QtDataVisualization',\n 'QtDataVisualizationQml',\n 'QtDesigner',\n 'QtDesignerComponents',\n 'QtLabsAnimation',\n 'QtLanguageServer',\n 'QtLabsWavefrontMesh',\n 'QtLocation',\n 'QtMultimedia',\n 'QtMultimediaQuick',\n 'QtMultimediaWidgets',\n 'QtNetworkAuth',\n 'QtNfc',\n 'QtPositioning',\n 'QtPositioningQuick',\n 'QtQuick3D',\n 'QtQuick3DAssetImport',\n 'QtQuick3DAssetUtils',\n 'QtQuick3DEffects',\n 'QtQuick3DHelpers',\n 'QtQuick3DParticleEffects',\n 'QtQuick3DParticles',\n 'QtQuick3DRuntimeRender',\n 'QtQuick3DUtils',\n 'QtQuickTest',\n 'QtQuickTimeline',\n 'QtRemoteObjects',\n 'QtRemoteObjectsQml',\n 'QtScxml',\n 'QtScxmlQml',\n 'QtSensors',\n 'QtSensorsQuick',\n 'QtSerialBus',\n 'QtSerialPort',\n 'QtShaderTools',\n 'QtSpatialAudio',\n 'QtSql',\n 'QtStateMachine',\n 'QtStateMachineQml',\n 'QtTest',\n 'QtTextToSpeech',\n 'QtUiTools',\n 'QtVirtualKeyboard',\n 'QtWebChannel',\n 'QtWebEngine',\n 'QtWebEngineCore',\n 'QtWebEngineQuick',\n 'QtWebEngineQuickDelegatesQml',\n 'QtWebSockets',\n 'QtWebView',\n 'QtWebViewQuick',\n 'QtXmlPatterns',\n]\n\nUSELESS_QT_DIRS_PREFIX = [\n 'examples',\n 'glue',\n 'include',\n 'scripts',\n 'support',\n 'translations',\n 'typesystems',\n 'Qt/lib/cmake',\n 'Qt/lib/metatypes',\n 'Qt/lib/objects-RelWithDebInfo',\n 'Qt/libexec',\n 'Qt/metatypes',\n 'Qt/plugins/assetimporters',\n 'Qt/plugins/canbus',\n 'Qt/plugins/designer',\n 'Qt/plugins/generic',\n 'Qt/plugins/geometryloaders',\n 'Qt/plugins/multimedia',\n 'Qt/plugins/networkinformation',\n 'Qt/plugins/platforminputcontexts',\n 'Qt/plugins/position',\n 'Qt/plugins/qmltooling',\n 'Qt/plugins/renderers',\n 'Qt/plugins/renderplugins',\n 'Qt/plugins/sceneparsers',\n 'Qt/plugins/scxmldatamodel',\n 'Qt/plugins/sensors',\n 'Qt/plugins/sqldrivers',\n 'Qt/plugins/texttospeech',\n 'Qt/plugins/tls',\n 'Qt/plugins/virtualkeyboard',\n 'Qt/qml/QtLocation',\n 'Qt/qml/QtPositioning',\n 'Qt/qml/QtTextToSpeech',\n 'Qt/translations',\n]\n\nUSELESS_PACKAGES = [\n 'PyInstaller',\n 'tcl',\n 'tcl8',\n 'tk',\n]\n\nUSELESS_LIBRARIES = [\n 'tcl',\n 'tk',\n]\n\n\ndef change_cwd():\n cwd = os.getcwd()\n\n if os.path.split(cwd)[1] == 'building':\n os.chdir(os.path.join(cwd, os.pardir))\n\n\ndef post_process_win(dist_folder):\n windows_app_path = os.path.join(dist_folder, 'SciHubEVA')\n\n # remove useless Qt modules\n for qt_lib in USELESS_QT_LIBS:\n qt_lib_win = qt_lib.replace('Qt', 'Qt6')\n qt_lib_win += '.dll'\n qt_lib_path = os.path.join(windows_app_path, 'PySide6', qt_lib_win)\n if os.path.exists(qt_lib_path):\n os.remove(qt_lib_path)\n\n qt_qml_dir = os.path.join(windows_app_path, 'PySide6', 'qml', qt_lib)\n if os.path.isdir(qt_qml_dir):\n shutil.rmtree(qt_qml_dir, ignore_errors=True)\n\n # remove useless Qt directories\n for qt_file_prefix in USELESS_QT_DIRS_PREFIX:\n qt_file_win_prefix = qt_file_prefix.replace('Qt/', '')\n qt_dir = os.path.join(windows_app_path, 'PySide6', qt_file_win_prefix)\n shutil.rmtree(qt_dir, ignore_errors=True)\n\n # remove useless packages\n for package in USELESS_PACKAGES:\n package_dir = os.path.join(windows_app_path, package)\n\n if os.path.isdir(package_dir):\n shutil.rmtree(package_dir, ignore_errors=True)\n\n # remove useless libraries\n for library in USELESS_LIBRARIES:\n for lib in glob.glob(\n os.path.join(\n windows_app_path, 'lib{}*.dll'.format(\n library)), recursive=False):\n os.remove(lib)\n\n # remove useless directory\n for postfix in ['.egg-info', '.dist-info']:\n for directory in glob.glob(\n os.path.join(windows_app_path, '*{}'.format(\n postfix)), recursive=False):\n if os.path.isdir(directory):\n shutil.rmtree(directory, ignore_errors=True)\n\n\ndef post_process_macos(dist_folder):\n macos_app_path = os.path.join(dist_folder, 'SciHubEVA.app')\n\n # remove useless Qt modules\n for qt_lib in USELESS_QT_LIBS:\n qt_lib_path = os.path.join(macos_app_path, 'Contents', 'MacOS', qt_lib)\n if os.path.exists(qt_lib_path):\n os.remove(qt_lib_path)\n\n qt_qml_dir = os.path.join(\n macos_app_path, 'Contents', 'MacOS', 'PySide6', 'Qt', 'qml', qt_lib)\n if os.path.isdir(qt_qml_dir):\n shutil.rmtree(qt_qml_dir, ignore_errors=True)\n\n # remove useless Qt directories\n for qt_file_prefix in USELESS_QT_DIRS_PREFIX:\n qt_dir = os.path.join(\n macos_app_path, 'Contents', 'MacOS', 'PySide6', qt_file_prefix)\n shutil.rmtree(qt_dir, ignore_errors=True)\n\n # remove useless packages\n for package in USELESS_PACKAGES:\n package_dir = os.path.join(\n macos_app_path, 'Contents', 'Resources', package)\n package_link = os.path.join(\n macos_app_path, 'Contents', 'MacOS', package)\n\n if os.path.isdir(package_dir):\n shutil.rmtree(package_dir, ignore_errors=True)\n\n if os.path.islink(package_link):\n os.remove(package_link)\n\n # remove useless libraries\n for library in USELESS_LIBRARIES:\n for lib in glob.glob(\n os.path.join(\n macos_app_path, 'Contents', 'MacOS', 'lib{}*.dylib'.format(\n library)), recursive=False):\n os.remove(lib)\n\n # remove useless directory\n for postfix in ['.egg-info', '.dist-info']:\n for directory in glob.glob(\n os.path.join(\n macos_app_path, 'Contents', 'Resources', '*{}'.format(\n postfix)), recursive=False):\n if os.path.isdir(directory):\n shutil.rmtree(directory, ignore_errors=True)\n\n for directory in glob.glob(\n os.path.join(\n macos_app_path, 'Contents', 'MacOS', '*{}'.format(\n postfix)), recursive=False):\n if os.path.islink(directory):\n os.remove(directory)\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n change_cwd()\n\n if is_windows():\n post_process_win(args[''])\n elif is_macos():\n post_process_macos(args[''])\n","sub_path":"building/post_process.py","file_name":"post_process.py","file_ext":"py","file_size_in_byte":7143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"438792284","text":"# from statistics import mode\n\n\n# import cv2\n# from keras.models import load_model\n# import numpy as np\n# import landmark\n\n\n# def preprocess_input(x, v2=True):\n# x = x.astype('float32')\n# x = x / 255.0\n# if v2:\n# x = x - 0.5\n# x = x * 2.0\n# return x\n\n# # parameters for loading data and images\n# emotion_model_path = 'fer2013_mini_XCEPTION.102-0.66.hdf5'\n# emotion_classifier = load_model(emotion_model_path, compile=False)\n# emotion_labels = {0: 'angry', 1: 'disgust', 2: 'fear', 3: 'happy', 4: 'sad', 5: 'surprise', 6: 'neutral'}\n\n\n\n# img = cv2.imread('test.jpg')\n# results = landmark.detect('test.jpg')\n# result = results[0]\n# x1, y1, x2, y2 = result['bbox']\n# face = img[y1:y2, x1:x2, :]\n# img = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)\n# img = cv2.resize(img, (64, 64))\n# img = preprocess_input(img)\n# img = img[None, :, :, None]\n# res = emotion_classifier.predict(img)\n\nimport cv2\nimport emotion\n\nimg = cv2.imread('test.jpg')\nresults = emotion.detect(img)\n\nfor result in results:\n x1, y1, x2, y2 = result['bbox']\n emotion = result['emotion']\n cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n cv2.putText(img, emotion, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, fontScale=1, color=(0, 255, 0), thickness=2)\n\ncv2.imshow(\"Emotion\", img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"projects/emotion/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"446093769","text":"import csv\nfrom datetime import datetime\n\nfrom chut import console_script\nfrom jinja2 import Template\n\n\nTEMPLATE = '''\n{{ r.date }} {{ r.amount }}€ {{r.kind}} {{ r.type }}{{ r.status }}\n {{ r.description }}\n {{ r.comment or '' }}\n\n'''\n\ntypes = {\n 'Teeshirt': 'Goodies',\n 'FraisPubli': 'Goodies',\n 'Alimentation': 'Alimentation',\n 'Transport': 'Transport',\n 'Partenaire:PyConFR08': 'Pycon08',\n 'Partenaire:PyConFR07': 'PyCon07',\n 'SCBC': 'VariousEvents',\n 'Fraisbanca': 'FraisBanque',\n 'Hébergement': 'Hosting',\n 'Fraish': 'Hebergement',\n 'Fraisdeser': 'FraisDivers',\n 'VariousEvents': 'SponsoringEvents',\n 'SponsoringEvenements': 'SponsoringEvents',\n}\n\n\ndef transform_item(record):\n record = {key.lower(): value for key, value in record.items()}\n record['date'] = datetime.strptime(record['date'],\n '%d/%m/%y').strftime('%Y/%m/%d')\n record['amount'] = float(record['amount'].replace(',', '.'))\n record['comment'] = record['comment'].decode('utf8') or None\n record['description'] = record['description'].decode('utf8') or None\n record['type'] = record['type'].decode('utf8').replace(' ', '')\n record['info'] = record['info'].decode('utf8') or None\n\n if record['info'] is not None:\n if record['comment'] is None:\n record['comment'] = record['info']\n else:\n record['comment'] += ' ; ' + record['info']\n\n if record['amount'] == 0:\n record['type'] = 'Cotisation'\n record['amount'] = 20.\n\n st = record['status']\n if st.startswith('Pending'):\n record['status'] = ' P'\n else:\n record['status'] = ' X'\n\n t = record['type']\n for k, v in types.items():\n if t.startswith(k):\n t = v\n record['type'] = t\n if not t:\n if record['description'] == 'Sac Ecobags':\n t = 'Goodies'\n elif record['amount'] == 20:\n t = 'Cotisation'\n else:\n raise LookupError(t)\n record['type'] = t\n\n k = record['kind']\n if k.startswith('TransferTransaction'):\n k = 'Transfer'\n elif k.startswith('ServiceCharge'):\n k = 'ServiceCharge'\n elif k.startswith('StandingOrder'):\n k = 'Order'\n elif k.startswith('Check'):\n k = 'Check'\n elif k.startswith('CreditCard'):\n k = 'CreditCard'\n elif k.startswith('Cash'):\n k = 'Cash'\n elif k.startswith('Other'):\n if t == 'Don':\n k = 'Transfer'\n elif record['description'] == 'Sac Ecobags':\n record['type'] = 'Goodies'\n k = 'Check'\n elif 'shirt' in record['description']:\n t = 'Goodies'\n k = 'Check'\n else:\n k = 'Other'\n if record['amount'] != 20:\n if 'pycon' in record['description'].lower():\n k = 'Check'\n elif record['amount'] in (100, 200, 400):\n k = 'Check'\n else:\n raise LookupError(k)\n record['kind'] = k\n\n for key in ['conciled date', 'ending date', 'frequency', 'taxes']:\n record[key] = record[key].decode('utf8')\n return record\n\n\ndef print_record(record):\n template = Template(TEMPLATE)\n move = template.render(\n r=record,\n ).encode('utf8')\n print(move.strip() + '\\n')\n\n\ndef parse_csv(filename):\n with open(filename) as csvfile:\n reader = csv.DictReader(csvfile, delimiter=';')\n for record in reader:\n yield transform_item(record)\n\n\n@console_script\ndef csv2pyash(args):\n \"\"\"Usage: %prog \"\"\"\n records = parse_csv(args[''])\n for record in records:\n print_record(record)\n\n\nif __name__ == '__main__':\n csv2pyash()\n","sub_path":"pyash/csv2pyash.py","file_name":"csv2pyash.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"599899047","text":"import abc\nimport time\n\nimport gtimer as gt\nimport numpy as np\nimport torch\n\nfrom rlkit.core import logger\nfrom rlkit.data_management.env_replay_buffer import MultiTaskReplayBuffer\n\nfrom rlkit.data_management.path_builder import PathBuilder\nfrom rlkit.policies.base import ExplorationPolicy\nfrom rlkit.samplers.in_place import InPlacePathSampler\n\nimport memory_profiler\nfrom memory_profiler import profile\n\nimport visdom\nvis = visdom.Visdom(port=8095, env='sac')\nvis.close()\n\nclass MetaRLAlgorithm(metaclass=abc.ABCMeta):\n def __init__(\n self,\n env,\n policy,\n train_tasks,\n eval_tasks,\n meta_batch=64,\n num_iterations=100,\n num_train_steps_per_itr=1000,\n num_tasks_sample=100,\n num_steps_per_task=100,\n num_evals=10,\n num_steps_per_eval=1000,\n batch_size=1024,\n embedding_batch_size=1024,\n embedding_mini_batch_size=1024,\n max_path_length=1000,\n discount=0.99,\n replay_buffer_size=1000000, #1000000,\n reward_scale=1,\n train_embedding_source='posterior_only',\n eval_embedding_source='initial_pool',\n eval_deterministic=True,\n render=False,\n save_replay_buffer=False,\n save_algorithm=False,\n save_environment=False,\n obs_emb_dim=0\n ):\n \"\"\"\n Base class for Meta RL Algorithms\n :param env: training env\n :param policy: policy that is conditioned on a latent variable z that rl_algorithm is responsible for feeding in\n :param train_tasks: list of tasks used for training\n :param eval_tasks: list of tasks used for eval\n :param meta_batch: number of tasks used for meta-update\n :param num_iterations: number of meta-updates taken\n :param num_train_steps_per_itr: number of meta-updates performed per iteration\n :param num_tasks_sample: number of train tasks to sample to collect data for\n :param num_steps_per_task: number of transitions to collect per task\n :param num_evals: number of independent evaluation runs, with separate task encodings\n :param num_steps_per_eval: number of transitions to sample for evaluation\n :param batch_size: size of batches used to compute RL update\n :param embedding_batch_size: size of batches used to compute embedding\n :param embedding_mini_batch_size: size of batch used for encoder update\n :param max_path_length: max episode length\n :param discount:\n :param replay_buffer_size: max replay buffer size\n :param reward_scale:\n :param render:\n :param save_replay_buffer:\n :param save_algorithm:\n :param save_environment:\n \"\"\"\n self.env = env\n self.policy = policy\n self.exploration_policy = policy # Can potentially use a different policy purely for exploration rather than also solving tasks, currently not being used\n self.train_tasks = train_tasks\n self.eval_tasks = eval_tasks\n self.meta_batch = meta_batch\n self.num_iterations = num_iterations\n self.num_train_steps_per_itr = num_train_steps_per_itr\n self.num_tasks_sample = num_tasks_sample\n self.num_steps_per_task = num_steps_per_task\n self.num_evals = num_evals\n self.num_steps_per_eval = num_steps_per_eval\n self.batch_size = batch_size\n self.embedding_batch_size = embedding_batch_size\n self.embedding_mini_batch_size = embedding_mini_batch_size\n self.max_path_length = max_path_length\n self.discount = discount\n self.replay_buffer_size = min(int(replay_buffer_size/(len(train_tasks))), 1000)\n self.reward_scale = reward_scale\n self.train_embedding_source = train_embedding_source\n self.eval_embedding_source = eval_embedding_source # TODO: add options for computing embeddings on train tasks too\n self.eval_deterministic = eval_deterministic\n self.render = render\n self.save_replay_buffer = save_replay_buffer\n self.save_algorithm = save_algorithm\n self.save_environment = save_environment\n\n self.eval_sampler = InPlacePathSampler(\n env=env,\n policy=policy,\n max_samples=self.num_steps_per_eval,\n max_path_length=self.max_path_length,\n )\n\n # separate replay buffers for\n # - training RL update\n # - training encoder update\n # - testing encoder\n self.replay_buffer = MultiTaskReplayBuffer(\n self.replay_buffer_size,\n env,\n self.train_tasks,\n state_dim=obs_emb_dim\n )\n\n self.enc_replay_buffer = MultiTaskReplayBuffer(\n self.replay_buffer_size,\n env,\n self.train_tasks,\n state_dim=obs_emb_dim\n )\n self.eval_enc_replay_buffer = MultiTaskReplayBuffer(\n self.replay_buffer_size,\n env,\n self.eval_tasks,\n state_dim=obs_emb_dim\n\n )\n\n self._n_env_steps_total = 0\n self._n_train_steps_total = 0\n self._n_rollouts_total = 0\n self._do_train_time = 0\n self._epoch_start_time = None\n self._algo_start_time = None\n self._old_table_keys = None\n self._current_path_builder = PathBuilder()\n self._exploration_paths = []\n\n def make_exploration_policy(self, policy):\n return policy\n\n def make_eval_policy(self, policy):\n return policy\n\n def sample_task(self, is_eval=False):\n '''\n sample task randomly\n '''\n if is_eval:\n idx = np.random.randint(len(self.eval_tasks))\n else:\n idx = np.random.randint(len(self.train_tasks))\n return idx\n\n def train(self):\n '''\n meta-training loop\n '''\n self.pretrain()\n params = self.get_epoch_snapshot(-1)\n logger.save_itr_params(-1, params)\n gt.reset()\n gt.set_def_unique(False)\n self._current_path_builder = PathBuilder()\n self.train_obs = self._start_new_rollout()\n\n # at each iteration, we first collect data from tasks, perform meta-updates, then try to evaluate\n for it_ in gt.timed_for(\n range(self.num_iterations),\n save_itrs=True,\n ):\n self._start_epoch(it_)\n self.training_mode(True)\n if it_ == 0:\n print('collecting initial pool of data for train and eval')\n # temp for evaluating\n for idx in self.train_tasks:\n print('train task', idx)\n self.task_idx = idx\n self.env.reset_task(idx)\n self.collect_data_sampling_from_prior(num_samples=self.max_path_length * 10,\n resample_z_every_n=self.max_path_length,\n eval_task=False)\n \"\"\"\n for idx in self.eval_tasks:\n self.task_idx = idx\n self.env.reset_task(idx)\n # TODO: make number of initial trajectories a parameter\n self.collect_data_sampling_from_prior(num_samples=self.max_path_length * 20,\n resample_z_every_n=self.max_path_length,\n eval_task=True)\n \"\"\"\n\n # Sample data from train tasks.\n for i in range(self.num_tasks_sample):\n idx = np.random.randint(len(self.train_tasks))\n self.task_idx = idx\n self.env.reset_task(idx)\n\n # TODO: there may be more permutations of sampling/adding to encoding buffer we may wish to try\n if self.train_embedding_source == 'initial_pool':\n # embeddings are computed using only the initial pool of data\n # sample data from posterior to train RL algorithm\n self.collect_data_from_task_posterior(idx=idx,\n num_samples=self.num_steps_per_task,\n add_to_enc_buffer=False)\n elif self.train_embedding_source == 'posterior_only':\n self.collect_data_from_task_posterior(idx=idx, num_samples=self.num_steps_per_task, eval_task=False,\n add_to_enc_buffer=True)\n elif self.train_embedding_source == 'online_exploration_trajectories':\n # embeddings are computed using only data collected using the prior\n # sample data from posterior to train RL algorithm\n self.enc_replay_buffer.task_buffers[idx].clear()\n # resamples using current policy, conditioned on prior\n\n self.collect_data_sampling_from_prior(num_samples=self.num_steps_per_task,\n resample_z_every_n=self.max_path_length,\n add_to_enc_buffer=True)\n\n self.env.reset_task(idx)\n\n self.collect_data_from_task_posterior(idx=idx,\n num_samples=self.num_steps_per_task,\n add_to_enc_buffer=False,\n viz=True)\n\n elif self.train_embedding_source == 'online_on_policy_trajectories':\n # sample from prior, then sample more from the posterior\n # embeddings computed from both prior and posterior data\n self.enc_replay_buffer.task_buffers[idx].clear()\n self.collect_data_online(idx=idx,\n num_samples=self.num_steps_per_task,\n add_to_enc_buffer=True)\n else:\n raise Exception(\"Invalid option for computing train embedding {}\".format(self.train_embedding_source))\n\n # Sample train tasks and compute gradient updates on parameters.\n for train_step in range(self.num_train_steps_per_itr):\n indices = np.random.choice(self.train_tasks, self.meta_batch)\n self._do_training(indices, train_step)\n self._n_train_steps_total += 1\n gt.stamp('train')\n\n #self.training_mode(False)\n\n # eval\n self._try_to_eval(it_)\n gt.stamp('eval')\n\n self._end_epoch()\n\n def pretrain(self):\n \"\"\"\n Do anything before the main training phase.\n \"\"\"\n pass\n\n def sample_z_from_prior(self):\n \"\"\"\n Samples z from the prior distribution, which can be either a delta function at 0 or a standard Gaussian\n depending on whether we use the information bottleneck.\n :return: latent z as a Numpy array\n \"\"\"\n pass\n\n def sample_z_from_posterior(self, idx, eval_task):\n \"\"\"\n Samples z from the posterior distribution given data from task idx, where data comes from the encoding buffer\n :param idx: task idx from which to compute the posterior from\n :param eval_task: whether or not the task is an eval task\n :return: latent z as a Numpy array\n \"\"\"\n pass\n\n # TODO: maybe find a better name for resample_z_every_n?\n def collect_data_sampling_from_prior(self, num_samples=1, resample_z_every_n=None, eval_task=False,\n add_to_enc_buffer=True):\n # do not resample z if resample_z_every_n is None\n if resample_z_every_n is None:\n self.policy.clear_z()\n self.collect_data(self.policy, num_samples=num_samples, eval_task=eval_task,\n add_to_enc_buffer=add_to_enc_buffer)\n else:\n # collects more data in batches of resample_z_every_n until done\n while num_samples > 0:\n self.collect_data_sampling_from_prior(num_samples=min(resample_z_every_n, num_samples),\n resample_z_every_n=None,\n eval_task=eval_task,\n add_to_enc_buffer=add_to_enc_buffer)\n num_samples -= resample_z_every_n\n\n def collect_data_from_task_posterior(self, idx, num_samples=1, resample_z_every_n=None, eval_task=False,\n add_to_enc_buffer=True, viz=False):\n # do not resample z if resample_z_every_n is None\n if resample_z_every_n is None:\n self.sample_z_from_posterior(idx, eval_task=eval_task)\n self.collect_data(self.policy, num_samples=num_samples, eval_task=eval_task,\n add_to_enc_buffer=add_to_enc_buffer, viz=viz)\n else:\n # collects more data in batches of resample_z_every_n until done\n while num_samples > 0:\n self.collect_data_from_task_posterior(idx=idx,\n num_samples=min(resample_z_every_n, num_samples),\n resample_z_every_n=None,\n eval_task=eval_task,\n add_to_enc_buffer=add_to_enc_buffer,\n viz=viz)\n num_samples -= resample_z_every_n\n\n # split number of prior and posterior samples\n def collect_data_online(self, idx, num_samples, eval_task=False, add_to_enc_buffer=True):\n self.collect_data_sampling_from_prior(num_samples=num_samples,\n resample_z_every_n=self.max_path_length,\n eval_task=eval_task,\n add_to_enc_buffer=True)\n self.env.reset_task(idx)\n self.collect_data_from_task_posterior(idx=idx,\n num_samples=num_samples,\n resample_z_every_n=self.max_path_length,\n eval_task=eval_task,\n add_to_enc_buffer=add_to_enc_buffer,\n viz=True)\n\n\n # TODO: since switching tasks now resets the environment, we are not correctly handling episodes terminating\n # correctly. We also aren't using the episodes anywhere, but we should probably change this to make it gather paths\n # until we have more samples than num_samples, to make sure every episode cleanly terminates when intended.\n\n # @profile\n def collect_data(self, agent, num_samples=1, max_resets=None, eval_task=False, add_to_enc_buffer=True, viz=False):\n '''\n collect data from current env in batch mode\n with given policy\n '''\n\n images = []\n # if num_samples == 50:\n # import pdb; pdb.set_trace()\n\n env_time = self.env.time\n rews = []\n terms = []\n n_resets = 0\n\n for _ in range(num_samples):\n action, agent_info = self._get_action_and_info(agent, self.train_obs)\n if self.render:\n self.env.render()\n \n next_ob, raw_reward, terminal, env_info = (\n self.env.step(action)\n )\n if viz:\n images.append(next_ob)\n # vis.image(next_ob[-1])\n \n reward = raw_reward\n rews += [reward]\n terms += [terminal]\n\n terminal = np.array([terminal])\n reward = np.array([reward])\n self._handle_step(\n self.task_idx,\n np.concatenate(\n [self.train_obs.flatten()[None], agent_info['obs_emb']], axis=-1\n ),\n action,\n reward,\n np.concatenate(\n [next_ob.flatten()[None], torch.zeros(agent_info['obs_emb'].shape)], axis=-1\n ),\n terminal,\n eval_task=eval_task,\n add_to_enc_buffer=add_to_enc_buffer,\n agent_info=agent_info,\n env_info=env_info,\n )\n\n # TODO USE masking here to handle the terminal episodes\n # print(len(self._current_path_builder))\n if terminal or len(self._current_path_builder) >= self.max_path_length:\n self._handle_rollout_ending(eval_task=eval_task)\n self.train_obs = self._start_new_rollout()\n n_resets += 1\n\n if _ + self.max_path_length > num_samples - 1:\n break\n if max_resets is not None and n_resets > max_resets:\n break\n\n else:\n # print((next_ob - self.train_obs).sum())\n # self.train_obs = None\n self.train_obs = next_ob\n \n\n if viz and np.random.random() < 0.3:\n # import pdb; pdb.set_trace()\n vis.images(np.stack(images)[:, -1:])\n vis.line(np.array([rews, terms]).T, opts=dict(width=400, height=320))\n vis.text('', opts=dict(width=10000, height=5))\n # vis.video(np.stack(images))\n \n if not eval_task:\n self._n_env_steps_total += num_samples\n gt.stamp('sample')\n\n def _try_to_eval(self, epoch):\n logger.save_extra_data(self.get_extra_data_to_save(epoch))\n if self._can_evaluate():\n self.evaluate(epoch)\n\n params = self.get_epoch_snapshot(epoch)\n logger.save_itr_params(epoch, params)\n table_keys = logger.get_table_key_set()\n if self._old_table_keys is not None:\n assert table_keys == self._old_table_keys, (\n \"Table keys cannot change from iteration to iteration.\"\n )\n self._old_table_keys = table_keys\n\n logger.record_tabular(\n \"Number of train steps total\",\n self._n_train_steps_total,\n )\n logger.record_tabular(\n \"Number of env steps total\",\n self._n_env_steps_total,\n )\n logger.record_tabular(\n \"Number of rollouts total\",\n self._n_rollouts_total,\n )\n\n times_itrs = gt.get_times().stamps.itrs\n train_time = times_itrs['train'][-1]\n sample_time = times_itrs['sample'][-1]\n eval_time = times_itrs['eval'][-1] if epoch > 0 else 0\n epoch_time = train_time + sample_time + eval_time\n total_time = gt.get_times().total\n\n logger.record_tabular('Train Time (s)', train_time)\n logger.record_tabular('(Previous) Eval Time (s)', eval_time)\n logger.record_tabular('Sample Time (s)', sample_time)\n logger.record_tabular('Epoch Time (s)', epoch_time)\n logger.record_tabular('Total Train Time (s)', total_time)\n\n logger.record_tabular(\"Epoch\", epoch)\n logger.dump_tabular(with_prefix=False, with_timestamp=False)\n else:\n logger.log(\"Skipping eval for now.\")\n\n def _can_evaluate(self):\n \"\"\"\n One annoying thing about the logger table is that the keys at each\n iteration need to be the exact same. So unless you can compute\n everything, skip evaluation.\n\n A common example for why you might want to skip evaluation is that at\n the beginning of training, you may not have enough data for a\n validation and training set.\n\n :return:\n \"\"\"\n # import pdb; pdb.set_trace()\n return (\n # len(self._exploration_paths) > 0\n # and \n self.replay_buffer.num_steps_can_sample(self.task_idx) >= self.batch_size\n )\n\n def _can_train(self):\n return all([self.replay_buffer.num_steps_can_sample(idx) >= self.batch_size for idx in self.train_tasks])\n\n def _get_action_and_info(self, agent, observation):\n \"\"\"\n Get an action to take in the environment.\n :param observation:\n :return:\n \"\"\"\n agent.set_num_steps_total(self._n_env_steps_total)\n return agent.get_action(observation,)\n\n def _start_epoch(self, epoch):\n self._epoch_start_time = time.time()\n self._exploration_paths = []\n self._do_train_time = 0\n logger.push_prefix('Iteration #%d | ' % epoch)\n\n def _end_epoch(self):\n logger.log(\"Epoch Duration: {0}\".format(\n time.time() - self._epoch_start_time\n ))\n logger.log(\"Started Training: {0}\".format(self._can_train()))\n logger.pop_prefix()\n\n def _start_new_rollout(self):\n ret = self.env.reset()\n if isinstance(ret, tuple):\n ret = ret[0]\n return ret\n\n # not used\n def _handle_path(self, path):\n \"\"\"\n Naive implementation: just loop through each transition.\n :param path:\n :return:\n \"\"\"\n for (\n ob,\n action,\n reward,\n next_ob,\n terminal,\n agent_info,\n env_info\n ) in zip(\n path[\"observations\"],\n path[\"actions\"],\n path[\"rewards\"],\n path[\"next_observations\"],\n path[\"terminals\"],\n path[\"agent_infos\"],\n path[\"env_infos\"],\n ):\n self._handle_step(\n ob.reshape(-1),\n action,\n reward,\n next_ob.reshape(-1),\n terminal,\n agent_info=agent_info,\n env_info=env_info,\n )\n self._handle_rollout_ending()\n\n def _handle_step(\n self,\n task_idx,\n observation,\n action,\n reward,\n next_observation,\n terminal,\n agent_info,\n env_info,\n eval_task=False,\n add_to_enc_buffer=True,\n ):\n \"\"\"\n Implement anything that needs to happen after every step\n :return:\n \"\"\"\n self._current_path_builder.add_all(\n task=task_idx,\n observations=observation,\n actions=action,\n rewards=reward,\n next_observations=next_observation,\n terminals=terminal,\n agent_infos=agent_info,\n env_infos=env_info,\n )\n if eval_task:\n self.eval_enc_replay_buffer.add_sample(\n task=task_idx,\n observation=observation,\n action=action,\n reward=reward,\n terminal=terminal,\n next_observation=next_observation,\n agent_info=agent_info,\n env_info=env_info,\n )\n else:\n self.replay_buffer.add_sample(\n task=task_idx,\n observation=observation,\n action=action,\n reward=reward,\n terminal=terminal,\n next_observation=next_observation,\n agent_info=agent_info,\n env_info=env_info,\n )\n if add_to_enc_buffer:\n self.enc_replay_buffer.add_sample(\n task=task_idx,\n observation=observation,\n action=action,\n reward=reward,\n terminal=terminal,\n next_observation=next_observation,\n agent_info=agent_info,\n env_info=env_info,\n )\n\n def _handle_rollout_ending(self, eval_task=False):\n \"\"\"\n Implement anything that needs to happen after every rollout.\n \"\"\"\n if eval_task:\n self.eval_enc_replay_buffer.terminate_episode(self.task_idx)\n else:\n self.replay_buffer.terminate_episode(self.task_idx)\n self.enc_replay_buffer.terminate_episode(self.task_idx)\n\n self._n_rollouts_total += 1\n if len(self._current_path_builder) > 0:# and False:\n # self._exploration_paths.append(\n # self._current_path_builder.get_all_stacked()\n # )\n self._current_path_builder = PathBuilder()\n\n def get_epoch_snapshot(self, epoch):\n data_to_save = dict(\n epoch=epoch,\n exploration_policy=self.exploration_policy,\n )\n if self.save_environment:\n data_to_save['env'] = self.training_env\n return data_to_save\n\n def get_extra_data_to_save(self, epoch):\n \"\"\"\n Save things that shouldn't be saved every snapshot but rather\n overwritten every time.\n :param epoch:\n :return:\n \"\"\"\n if self.render:\n self.training_env.render(close=True)\n data_to_save = dict(\n epoch=epoch,\n )\n if self.save_environment:\n data_to_save['env'] = self.training_env\n if self.save_replay_buffer:\n data_to_save['replay_buffer'] = self.replay_buffer\n if self.save_algorithm:\n data_to_save['algorithm'] = self\n return data_to_save\n\n @abc.abstractmethod\n def training_mode(self, mode):\n \"\"\"\n Set training mode to `mode`.\n :param mode: If True, training will happen (e.g. set the dropout\n probabilities to not all ones).\n \"\"\"\n pass\n\n @abc.abstractmethod\n def evaluate(self, epoch):\n \"\"\"\n Evaluate the policy, e.g. save/print progress.\n :param epoch:\n :return:\n \"\"\"\n pass\n\n @abc.abstractmethod\n def _do_training(self):\n \"\"\"\n Perform some update, e.g. perform one gradient step.\n :return:\n \"\"\"\n pass\n","sub_path":"rlkit/core/rl_algorithm.py","file_name":"rl_algorithm.py","file_ext":"py","file_size_in_byte":26422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"297691363","text":"from bs4 import BeautifulSoup as bs\r\nimport requests\r\nimport re\r\nfrom datetime import date\r\nimport string\r\nfrom random import randint\r\n#fetch the group stage from bbc url\r\nurl='https://www.bbc.com/sport/football/world-cup/schedule/group-stage'\r\n#get current date and append to the fixtures url to iterate on each match\r\ntoday = str(date.today())\r\nfixture_url = 'http://www.newsnow.co.uk/h/Sport/Football/2018+FIFA+World+Cup'\r\n\r\ndef soup_maker(fixture_url):\r\n r = requests.get(fixture_url)\r\n markup = r.content\r\n soup = bs(markup, 'lxml')\r\n return soup\r\n\r\ndef group_stage(soup):\r\n final_details = {}\r\n table = soup.find('div', {'class': 'newsbox_inner'})\r\n with open('w_news.txt', 'a',encoding='utf-8') as file:\r\n file.write(table.text)\r\n\r\ndef viewItem():\r\n remove_empty_lines('w_news.txt')\r\n f = open('w_news.txt', 'r')\r\n data = f.readlines()\r\n return (data)\r\n\r\ndef remove_empty_lines(filename):\r\n \"\"\"Overwrite the file, removing empty lines and lines that contain only whitespace.\"\"\"\r\n with open(filename, 'r+') as f:\r\n lines = f.readlines()\r\n f.seek(0)\r\n f.writelines(line for line in lines if line.strip())\r\n f.truncate()\r\n\r\nsoup = soup_maker(fixture_url)\r\n#print (group_stage(soup))\r\ngroup_stage(soup)\r\na = viewItem()\r\nb=len(a)\r\nrandom_number = (randint(2, 10))\r\nprint (a[-random_number])\r\n\r\n\r\n","sub_path":"worldcup_news1.py","file_name":"worldcup_news1.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"196356744","text":"#### K-means ####\n# 1. set K(initial center)\n# 2. allocate every data to K\n# 3. update : calculate new K\n# ==============================\n\nimport matplotlib.pyplot as plt\n#%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\n#graph package\nimport seaborn as sns\n\n\nnum_vectors = 1000\nnum_clusters = 10\nnum_steps = 100\nvector_values = []\n\n#### data generate ####\n# xrange(written in book) don't work\n# np.random.random() : return random float in the half-open interval [0.0, 1.0)\n'''for i in range(num_vectors):\n if np.random.random() > 0.5:\n vector_values.append([np.random.normal(0.6, 0.1),\n np.floor(np.random.normal(0.5, 0.3))])\n else:\n vector_values.append([np.random.normal(2.5, 0.4),\n np.floor(np.random.normal(1.3, 0.5))])\n\ndf = pd.DataFrame({\"x\": [v[0] for v in vector_values], \"y\": [v[1] for v in vector_values]})\nsns.lmplot(\"x\", \"y\", data=df, fit_reg=False, size=7)\nplt.show()\n'''\nraw_data = pd.read_csv('~/ST4000DM000/W300BH8D.csv', parse_dates=['date'], index_col='date')\ndata = pd.DataFrame()\n#data['serial_number'] = raw_data['serial_number']\ndata['5'] = raw_data['smart_5_normalized']\ndata['187'] = raw_data['smart_187_normalized']\ndata['188'] = raw_data['smart_188_normalized']\ndata['197'] = raw_data['smart_197_normalized']\ndata['198'] = raw_data['smart_198_normalized']\n\nsmart_values = data.values.tolist()\n\n\n\n#moving every data to tensor\n#vectors = tf.constant(vector_values)\nvectors = tf.constant(smart_values)\n\n##### 1. set K #####\n# tf.Variable : create variable\n# tf.random_shuffle : shuffle element based on the first dimension\n# select random center as many as \"num_clusters\"\n#'input' is [ [[1, 1, 1], [2, 2, 2]], \n#\t\t[[3, 3, 3], [4, 4, 4]], \n#\t\t[[5, 5, 5], [6, 6, 6]] ]\n#tf.slice(input, [1, 0, 0], [1, 1, 3]) ==> [[[3, 3, 3]]]\n#tf.slice(input, [1, 0, 0], [1, 2, 3]) ==> [[[3, 3, 3],\n# [4, 4, 4]]]\n#tf.slice(input, [1, 0, 0], [2, 1, 3]) ==> [[[3, 3, 3]],\n# [[5, 5, 5]]]\ncentroids = tf.Variable(tf.slice(tf.random_shuffle(vectors), [0,0], [num_clusters,-1]))\n##### 1. set K #####\n\n\n##### 2. allocate K #####\n# add dimension\nexpanded_vectors = tf.expand_dims(vectors, 0)\nexpanded_centroids = tf.expand_dims(centroids, 1)\n#print(expanded_vectors.get_shape()) (1000, 2) -> (1, 1000, 2)\n#print(expanded_centroids.get_shape()) (3, 2) -> (3, 1, 2)\n\n#tf.sub : [ [center1-data1], [center1-data2], [C1-D3], .... [C1-D1000],\n#\t [C2-D1], [C2-D2], ... [C2-D1000],\n#\t [C3-D1], [C3-D2], ... [C3-D1000] ]\n# Dimension= (3,1000,2)\n#tf.square : ^2\n#tf.reduce_sum (ex) (200,300) => (500), (100,200,300) => (600)\n#tf.reduce_sum : distance [ C1~D1, C1~D2, ....\n# C2~D1, C2~D2, ....\n# C3~D1, C3~D2, .... ] Dimenstion = (3, 1000)\n#tf.argmin : return index which have minimum value\n# Dimension= (1000), [0, 1, 2, 2, 0, 1, 2 .....] \ndistances = tf.reduce_sum(tf.square(tf.sub(expanded_vectors, expanded_centroids)), 2)\nassignments = tf.argmin(distances, 0)\n##### 2. allocate K #####\n\n\n##### 3. new K #####\n#tf.equal : return true where equal\n#tf.where : return index where the element is true\n#tf.reshape : center1 [3, 55, 100, ....], center2 [1, 20, ...]\n#tf.gather(index -> real) : gather data from index(tf.reshape)\n# [3, 55, 100, ....] -> [ [200,100], [100, 200], ....]\n#tf.reduce_mean : calculate means in serveral center\n#tf.concat : concat new center [[100,100] , [200,200], [300,300]]\nmeans = tf.concat(0, [\n tf.reduce_mean(\n tf.gather(vectors, tf.reshape(tf.where(tf.equal(assignments, c)),[1,-1])),\n\t\treduction_indices=[1])\n for c in range(num_clusters)])\n\nupdate_centroids = tf.assign(centroids, means)\n##### 3. new K #####\n\ninit_op = tf.initialize_all_variables()\n\nsess = tf.Session()\nsess.run(init_op)\n\nfor step in range(num_steps):\n _, centroid_values, assignment_values = sess.run([update_centroids, centroids, assignments])\n\nprint(\"centroids\")\nprint(centroid_values)\n\ndata = {\"x\": [], \"y\": [], \"cluster\": []}\nfor i in range(len(assignment_values)):\n data[\"x\"].append(vector_values[i][0])\n data[\"y\"].append(vector_values[i][1])\n data[\"cluster\"].append(assignment_values[i])\n\nfor i in range(0, 3) :\n\tdata[\"x\"].append(centroid_values[i][0])\n\tdata[\"y\"].append(centroid_values[i][1])\n\tdata[\"cluster\"].append(3)\n\ndf = pd.DataFrame(data)\nsns.lmplot(\"x\", \"y\", data=df,fit_reg=False, size=7, hue=\"cluster\", legend=False)\nplt.show()\n","sub_path":"clustering/smartd_kmeans.py","file_name":"smartd_kmeans.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"556042552","text":"from bs4 import BeautifulSoup\nimport urllib.request\nimport ssl\nimport xlwt\n\nssl._create_default_https_context = ssl._create_unverified_context\n\nheaders = {\n # 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0 ',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-HK,zh-TW;q=0.9,zh;q=0.8,ar;q=0.7,zh-CN;q=0.6',\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n}\n\nworkbook = xlwt.Workbook(encoding='ascii')\n\nimg_sheet = workbook.add_sheet('my_sheet')\n\ndef get_html(url):\n req = urllib.request.Request(url)\n req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36')\n res = urllib.request.urlopen(url)\n return res.read().decode('utf-8', 'ignore')\n\n\ndef insert_sheet(alt, src,index):\n style = xlwt.XFStyle()\n font = xlwt.Font()\n font.name = 'Time New Roman'\n font.bold = True\n font.underline = True\n font.italic = True\n style.font = font\n\n img_sheet.write(index, 0, alt)\n img_sheet.write(index, 1, src)\n tall_style = xlwt.easyxf('font:height 200')\n row = img_sheet.row(index)\n row.set_style(tall_style)\n img_sheet.col(0).width = 3333\n\n\ndef get_images():\n html = get_html('https://www.meitulu.com/t/meizi/')\n soup = BeautifulSoup(html, 'lxml')\n images = soup.find_all('img')\n\n for index in range(len(images)):\n insert_sheet(images[index].get('alt'), images[index].get('src'), index)\n\n workbook.save('formatting.xls')\n\n\nget_images()\n","sub_path":"python/beautifluSoup/firstTry.py","file_name":"firstTry.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"51006547","text":"import os\r\nimport urllib.request\r\nimport io\r\n\r\n# note - you would need to pip install this (or add it with GUI in pycharm\r\n# (file->settings->project->project interperter->install (a green \"+\" sign)\r\nfrom tld import get_tld\r\n\r\n\r\ndef create_dir(directory):\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n\r\ndef write_file(path, data):\r\n f = open(path, 'w')\r\n f.write(data)\r\n f.close()\r\n\r\ndef get_domain_name(url):\r\n domain_name = get_tld(url)\r\n return domain_name\r\n\r\n# this is the linux version\r\n# def get_ip_address(url):\r\n# command = \"host\" + url\r\n# process = os.popen(command)\r\n# results = str(process.read())\r\n# marker = results.find('has address') + 12\r\n# return results[marker].splitlines()[0]\r\n\r\n# this is the windows version\r\ndef get_ip_address(url):\r\n command = \"nslookup \" + url\r\n process = os.popen(command)\r\n results = str(process.read())\r\n # there's a problem - on some websites the ip will be on the 5th line (index 4) and some it will be on different\r\n # so I just take everything\r\n # marker = results.splitlines()[4]\r\n return results\r\n\r\n# this will work for linux automatically.\r\n# Windows users need to download it from here: https://nmap.org/download.html\r\ndef get_nmap(domain):\r\n command = \"nmap \" + domain\r\n process = os.popen(command)\r\n results = str(process.read())\r\n return results\r\n\r\ndef get_robots_txt(url):\r\n if url.endswith('/'):\r\n path = url\r\n else:\r\n path = url + '/'\r\n req = urllib.request.urlopen(path + 'robots.txt', data=None)\r\n data = io.TextIOWrapper(req, encoding='utf-8')\r\n return data.read()\r\n\r\n\r\n# notice that the command in this function will only work on linux, while in windows you have to download whois\r\n# https://technet.microsoft.com/en-us/sysinternals/whois.aspx\r\n# You might have to add the directory path of where you unpack whois to the system variables\r\n# if so, check:\r\n# http://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them\r\ndef get_whois(url):\r\n command = \"whois \" + url\r\n process = os.popen(command)\r\n results = str(process.read())\r\n return results\r\n\r\n\r\ndef gather_info(name, url):\r\n domain_name = get_domain_name(url)\r\n ip_address = get_ip_address(domain_name)\r\n nmap = get_nmap(domain_name) # ('-F', ip_address) - this is the linux version\r\n robots_txt = get_robots_txt(url)\r\n whois = get_whois(domain_name)\r\n create_report(name, url, domain_name, ip_address, nmap, robots_txt, whois)\r\n\r\ndef create_report(name, full_url, domain_name, ip_address, nmap, robots_txt, whois):\r\n project_dir = ROOT_DIR + '/' + name\r\n create_dir(project_dir)\r\n write_file(project_dir + '/full_url.txt', full_url)\r\n write_file(project_dir + '/domain_name.txt', domain_name)\r\n write_file(project_dir + '/ipaddress.txt', ip_address)\r\n write_file(project_dir + '/nmap.txt', nmap)\r\n write_file(project_dir + '/robots.txt', robots_txt)\r\n write_file(project_dir + '/whois.txt', whois)\r\n\r\nROOT_DIR = 'companies'\r\ncreate_dir(ROOT_DIR)\r\ngather_info('thenewboston', 'https://www.thenewboston.com/')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"73189007","text":"#!user/bin/python\n# -*- coding: utf-8 -*\n\nimport sys\nimport json\nclass Solution:\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n maps = {'I': 1, 'V' : 5, 'X' : 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} # ' ' is a must to add, be careful\n results = 0\n for i in range(len(s)-1):\n if maps[s[i+1]] > maps[s[i]]:\n results = results - maps[s[i]]\n else:\n results = results + maps[s[i]]\n return results + maps[s[-1]]\n\nif __name__ == '__main__':\n s = json.loads(sys.argv[1])\n print (Solution().romanToInt(s))","sub_path":"13.Roman_to_Integer.py","file_name":"13.Roman_to_Integer.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"433211115","text":"import os\nimport shutil\nfrom ..common.NrckiLogger import NrckiLogger\n\n_logger = NrckiLogger().getLogger(\"DDM\")\n\nclass LocalSEPlugin():\n def __init__(self, params={}):\n pass\n\n def get(self, src, dest):\n _logger.debug('LOCAL: Try to get file from %s to %s' % (src, dest))\n try:\n if not os.path.isfile(src):\n _logger.error(\"%s: File not found\" % src)\n\n shutil.copy2(src, dest)\n except:\n _logger.error('Unable to move:%s %s' % (src, dest))\n\n\n def put(self, src, dest):\n _logger.debug('LOCAL: Try to put file from %s to %s' % (src, dest))\n if not os.path.isfile(src):\n _logger.error(\"%s: File not found\" % src)\n\n self.get(src, dest)\n shutil.rmtree(os.path.join(src.split('/')[:-1]))","sub_path":"nrckiclient/ddm/LocalSEPlugin.py","file_name":"LocalSEPlugin.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"561127649","text":"#A script that compares two atomic geometries with each other to evaluate how \n#big the overall changes are\nimport math\nimport numpy as np\n\n#Parse a POSCAR file\ndef parsePoscar(data_file):\n\n f = open(str(data_file),'r')\n poscar_data = f.read().split('\\n')\n f.close()\n\n #Contains the scaling factor\n scale=float(poscar_data[1])\n\n #Contains the lattice\n lattice=[]\n temp=poscar_data[2].split()\n lattice.append([float(temp[0]),float(temp[1]),float(temp[2])])\n temp=poscar_data[3].split()\n lattice.append([float(temp[0]),float(temp[1]),float(temp[2])])\n temp=poscar_data[4].split()\n lattice.append([float(temp[0]),float(temp[1]),float(temp[2])])\n\n #Contains composition\n comp={}\n atoms=poscar_data[5].split()\n nat=poscar_data[6].split()\n ntotal=0\n for itype in range(0,len(temp)):\n comp[atoms[itype]]=int(nat[itype])\n ntotal=ntotal+int(nat[itype])\n\n #Contains coordinate type\n coordtype=poscar_data[7].split()\n if (coordtype[0] != \"Direct\" and coordtype[0] != \"direct\"):\n print(\"Warning: Coordinate type not recognized, but should not cause an error\")\n\n #Contains the atomic coordinates\n coord=[]\n for iline in range(8,8+ntotal):\n temp=poscar_data[iline].split()\n coord.append([float(temp[0]),float(temp[1]),float(temp[2])]) \n\n structure = {}\n structure[\"natoms\"]=ntotal\n structure[\"comp\"]=comp\n structure[\"scale\"]=scale\n structure[\"lattice\"]=lattice\n structure[\"coord\"]=coord\n return structure\n\ndef compareStruct(structure1,structure2):\n \n #Compare the compositions\n if (structure1[\"comp\"] != structure2[\"comp\"]):\n print(\"The compositions are not the same: NOT IMPLEMENTED YET\")\n sys.exit()\n\n #Compare the lattices\n for ilat in range(0,2):\n for jlat in range(0,2):\n a1=structure1[\"scale\"]*structure1[\"lattice\"][ilat][jlat]\n a2=structure2[\"scale\"]*structure2[\"lattice\"][ilat][jlat]\n if (a1 != a2):\n print(\"Warning: The lattices of the two structures are not the same?\")\n print(\"Are you sure you know what you are using this code for?\")\n sys.exit()\n\n lat=np.array(structure1[\"lattice\"])\n lat=lat*structure1[\"scale\"]\n\n #Finally, compare the geometries\n ntotal = structure1[\"natoms\"]\n minmoved = lat.max()\n maxmoved = 0.0\n\n for iat in range(0,ntotal):\n\n vec1=np.array(structure1[\"coord\"][iat])\n vec2=np.array(structure2[\"coord\"][iat])\n\n #This is a kind of shitty way to compare over the periodic boundary\n for ix in range(0,2):\n if abs(vec1[ix]-vec2[ix]) > 0.5:\n if vec1[ix] > 0.5:\n vec1[ix] = vec1[ix] - 1\n else:\n vec2[ix] = vec2[ix] - 1\n\n vec1=np.dot(lat,vec1)\n vec2=np.dot(lat,vec2)\n\n dist=0.0\n for ix in range(0,2):\n dist=dist+(vec1[ix]-vec2[ix])**2\n dist=math.sqrt(dist)\n\n #Keep track of the furthest moved and the least moved distances\n if (dist < minmoved):\n minmoved = dist\n if (dist > maxmoved):\n maxmoved = dist\n\n #Not really interested in things that didnt move\n if ( dist > 0.05):\n print(\"%3i %5.3f\"% (iat+1, dist))\n\n print(\"The min amount of movement: %6.4f; max amount: %6.4f in AA\"% (minmoved,maxmoved))\n\nfile1=\"CONTCAR-q0\"\nfile2=\"CONTCAR-q1\"\nfile3=\"POSCAR_init-q1\"\nfile4=\"POSCAR_init-q0\"\n\nstructure1 = parsePoscar(file1)\nstructure2 = parsePoscar(file4)\n\ncompareStruct(structure1,structure2)\n\nstructure1 = parsePoscar(file3)\nstructure2 = parsePoscar(file4)\n\ncompareStruct(structure1,structure2)\n","sub_path":"scripts/evaluate_relaxation.py","file_name":"evaluate_relaxation.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"522306143","text":"import sys\r\n\r\ndef setFileName(args):\r\n \"\"\"récupération des emplacements des fichiers si spécifiés \r\n sinon le nom est demandé à l'utilisateur\"\"\"\r\n inputFileName = \"\"\r\n outputFileName = \"resultat.py\" #valeur par défaut du fichier de sortie\r\n\r\n while len(args) > 1: #tant qu'il y a des arguments à lire, on traite les areguments (ils viennent par paire: le comutateur et la valeur)\r\n if args[0] == '-i': #si c'est le comutateur du fichier d'entrée, on atribue la valeur à la variable\r\n inputFileName = args[1]\r\n elif args[0] == '-o': #si le nom du fichier de sortie est spécifié, la variable est modifiée\r\n outputFileName = args[1]\r\n else:\r\n print(f\"Argument {args[0]} non reconnus\") #si l'argument n'est pas reconnus, un message est envoyé à l'utilisateur\r\n args = args[2:]\r\n\r\n return inputFileName, outputFileName\r\n\r\ndef fileIsValid(data):\r\n \"\"\"Fonction qui prend les données d'un fichier d'entrée en paremètre\r\n et qui renvois True si le fichier est valide\"\"\"\r\n fileValid = \"\"\r\n if data.count(\"axiome\") > 1: #vérification de l'existance d'un unique axiome\r\n fileValid = \"Il y a plus d'un axiome dans le fichier en entrée.\"\r\n if \"angle\" not in data: #vérification de l'existence de l'angle et de la taille\r\n fileValid = \"L'angle n'as pas été spécifié dans le fichier en entrée.\"\r\n if \"taille\" not in data:\r\n fileValid = \"La taille n'as pas été spécifié dans le fichier en entrée.\"\r\n if \"\\n \" not in data: #vérification de la présence d'au moins une regle\r\n fileValid = \"Aucune règle n'as été spécifiée dans le fichier en entrée.\"\r\n\r\n if fileValid != \"\":\r\n print(fileValid) #Si la variable fileVazlid a été changée, c'est qu'il y a une erreur et elle est affichée\r\n return False\r\n return True\r\n\r\ndef readRule(i, data):\r\n value = {} #dictionnaire contenant les regles sous la forme : {[lettre, avant, apres]: regle}\r\n d = 1 #d correspond à l'offset, il est définis à 1 car l'index transmis est celui de la ligne précédente\r\n while data[i+d][0] == \" \": #tant qu'on se trouve sur une ligne contenant des règles\r\n symbole, regle = (data[i+d].split('\"')[1]).split(\"=\") #extraction de la chaine de caractère et séparation du symbole et de la valeur\r\n if len(symbole) == 1: #si le symbole a un longeur de 1, c'est qu'il n'y a pas de contexte, et la regle est faite\r\n value[(symbole, \"\", \"\")] = regle\r\n elif len(symbole) == 3: #si il y a UNE indication de position\r\n if symbole[1] == '>': #et que c'est une indication à droite, on attribue la règle en conséquence, même chose à gauche\r\n value[(symbole[0], \"\", symbole[2])] = regle\r\n else:\r\n value[(symbole[2], symbole[0], \"\")] = regle\r\n else:\r\n value[(symbole[2], symbole[0], symbole[4])] = regle #Sinon c'est que c'est une règle multidirectionnelle\r\n d += 1\r\n return value\r\n\r\ndef readData(inputFileName):\r\n \"\"\"Fonction pour lire les données du fichier en entrée \r\n et renvois une liste avec touts les paramètres\"\"\"\r\n config = [\"\", {}, 0, 0, 0, []] #variable contenant la configuration (axiome, regles, angle, taille, niveau, constantes)\r\n with open(inputFileName, 'r') as file: #lecture du fichier en entrée\r\n data = file.read()\r\n if fileIsValid(data): #vérification de la validité du fichier en entrée\r\n data = data.split(\"\\n\") #séparation de chaques lignes\r\n for i in range(len(data)):\r\n row = data[i]\r\n if len(row) > 0 and row[0] != \" \": #pour chaque ligne, on regarde si elle n'est pas vide et si elle ne contient pas d'espace (sinon c'est une règle)\r\n parameter, value = row.replace(\" \", \"\").split(\"=\") #séparation de la ligne entre le paramètre et la valeur avec le symbole =\r\n\r\n if parameter.replace(\"è\", \"e\") == \"regles\": #si c'est une règle, execution de la fonction de récupération des règles\r\n config[1] = readRule(i, data)\r\n elif parameter == \"axiome\":\r\n config[0] = value.split('\"')[1] #extraction de l'axiome des guillemets\r\n elif parameter == \"angle\":\r\n config[2] = float(value) #le reste est juste une conversion vers int ou float\r\n elif parameter == \"taille\":\r\n config[3] = float(value)\r\n elif parameter == \"niveau\":\r\n config[4] = int(value)\r\n elif parameter == \"constantes\": #récupération des constantes\r\n config[5] = value\r\n return config\r\n\r\ndef checkContext(path, rule, constant):\r\n \"\"\"Fonction qui prend en entrée la chaine à vérifier\r\n et la regle à tester et renvois les emplacements où la regle est vérifiée\"\"\"\r\n pos = []\r\n if not (rule[1] != \"\" and rule[2] != \"\"): #cas ou il y a un contexte à droite ou à gauche (porte nand)\r\n match = rule[1] #match correspond à la chaine à retrouver avant le symbole en question\r\n reverse = False #booléen qui mémorise si on va vers la droite (True) ou vers la gauche (False)\r\n if rule[2] !=\"\": #si on regarde à droite, on inverse la liste, c'est le même algorithme\r\n path = \"\".join(path[::-1]).replace(\"[\", \"¤\").replace(\"]\", \"[\").replace(\"¤\", \"]\") #inversion de l'axiome et inversion des crochets (on a utilisé ¤ car il a très peu de chances d'être utilisé comme symbole)\r\n match = rule[2][::-1] #[::-1] permet d'inverser une chaîne de caractère\r\n reverse = True\r\n index = 0 #index permet de parcourir path\r\n mem = [] #mem permet de garder tmp en mémoire quand le programme explore une branche sous forme de pile\r\n tmp = [\"\"] *len(match) #correspond aux len(match) derniers caractères parcourus\r\n while index < len(path):\r\n if \"\".join(tmp) == match and path[index] == rule[0]: #pour les autres lettres, si on obtient la séquence de match, et que le symbole est le bon, c'est qu'on a trouvé un emplacement\r\n toappend = len(path) - index - 1 if reverse else index #inversion de l'index si on travaille à l'envers (à droite)\r\n pos.append(toappend) #ajout de la position dans la liste des positions\r\n if path[index] not in constant: #si la lettre parcourue n'est pas dans les constantes (voir ligne 3)\r\n if path[index] == \"[\": #si on rencontre une branche, on sauvegarde le tmp (l'historique) dans la pile\r\n mem.append(tmp.copy())\r\n elif path[index] == \"]\": #récupération de l'élément en haut de la pile\r\n tmp = mem.pop()\r\n elif tmp != []: #si tmp n'est pas nul, on retire le dernier élément et on ajoute celui actuel (tmp est une file)\r\n tmp.pop(0)\r\n tmp.append(path[index])\r\n index += 1\r\n else: #cas ou il y a un contexte à droite et à gauche, on fait l'union du contexte seulement à droite et le contexte seulement à gauche\r\n pos = list(set(checkContext(path, [rule[0], \"\", rule[2]], constant)) & set(checkContext(path, [rule[0], rule[1], \"\"], constant)))\r\n return pos\r\n\r\ndef generate(config):\r\n \"\"\"Fonction qui permet d'établir \r\n l'était du système au niveau demandé\"\"\"\r\n path = config[0] #path correspond à l'axiome\r\n for _ in range(config[4]): #pour chaque niveau\r\n newPath = [\"\"]*len(path) #création d'une nouvelle variable qui contiendra le résultat\r\n for rule in config[1].keys(): #boucle pour chaque règle\r\n for place in checkContext(path, rule, config[5]): #récupération des positions qui correspondent à la règle\r\n newPath[place] = config[1][rule] #à chaque position, la valeur est attribuée\r\n for i in range(len(newPath)): #pour chaque emplacement où newPath est vide, c'est qu'il n'y a pas de règle valide, le symbole est recopié\r\n if newPath[i] == \"\":\r\n newPath[i] = path[i]\r\n path = \"\".join(newPath) #modification de la variable path\r\n return path\r\n\r\ndef translate(processed, config):\r\n \"\"\"Fonction permettant de traduire\r\n l'était du système en instruction turtle\"\"\"\r\n size = config[3] #attribution des valeurs suivant la configuration\r\n angle = config[2]\r\n equivalent = {'a': f\"pd();fd({size});\", #equivalent est un dictionnaire servant à traduire les caractères en code python pour turtle\r\n 'b': f\"pu();fd({size});\", \r\n '+': f\"right({angle});\", \r\n '-': f\"left({angle});\", \r\n '*': \"right(180);\", \r\n '[': \"mem.append((pos(), heading()));\", \r\n ']': \"pu();tmp=mem.pop();goto(tmp[0]);seth(tmp[1]);\",\r\n 'l': \"pensize(6);\",\r\n 'm': \"pensize(3);\",\r\n 's': \"pensize(1);\",\r\n 'r': \"pencolor('#FF0000');\",\r\n 'g': \"pencolor('#00FF00');\",\r\n 'b': \"pencolor('#0000FF');\"}\r\n\r\n result = \"from turtle import *\\ncolor('black')\\nspeed(0)\\nmem=[]\\n\" #code par défaut dans tous les fichiers résultat\r\n\r\n for letter in processed: #pour chaque lettre, on regarde son équivalent, si il n'en a pas, rien ne se passera. Un retour à la ligne est ajouté pour plus de lisibilité\r\n if letter in equivalent.keys():\r\n result += equivalent[letter] + \"\\n\"\r\n\r\n result += \"exitonclick();\" #ajout de la dernière ligne permettant de quitter le programme une fois le tracé finis\r\n return result\r\n\r\ndef main():\r\n \"\"\"Fonction principale qui execute toutes les autres fonctions\"\"\"\r\n args = sys.argv[1:] #récupération des arguments passés lors de l'execution du programme, on n'as pas besoins du premier (nom du fichier executé)\r\n inputFileName, outputFileName = setFileName(args) #récupération du fichier d'entrée et de sortie\r\n if inputFileName == \"\": #arrêt du programme aucun fichier n'as été spécifié en entrée\r\n print(\"Aucun fichier n'as été spécifié avec le commutateur -i\")\r\n return False\r\n config = readData(inputFileName) #création de la variable des paramètres\r\n if config[0] == \"\": #si le ficher est invalide ou qu'il y a des règles incopmpatibles, le programme est quitté\r\n return False\r\n processed = generate(config) #génération de la chaine de caractère au niveau demandé\r\n result = translate(processed, config) #conversion de la chaine en code turtle\r\n print(result)\r\n\r\n with open(outputFileName, \"w\") as file: #sauvegarde du résultat\r\n file.write(result)\r\n\r\n exec(result) #execution du résultat\r\n \r\nif __name__=='__main__' : \r\n main()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"25871336","text":"from vardb.datamodel import allele, assessment\nfrom api.v1.resources.workflow.similaralleles import get_nearby_allele_ids\nfrom conftest import mock_allele\nfrom api.config import config\nfrom typing import List\n\n\ndef test_nearbyalleles(session, test_database, client):\n genepanel_name = \"HBOC\"\n genepanel_version = \"v01\"\n\n def _create_allele(start: int, end: int, classification: str = None) -> allele.Allele:\n a: allele.Allele = mock_allele(\n session, {\"chromosome\": \"TEST\", \"start_position\": start, \"open_end_position\": end + 1}\n )\n if classification is not None:\n aa = assessment.AlleleAssessment(\n user_id=1,\n allele_id=a.id,\n classification=classification,\n evaluation={},\n genepanel_name=genepanel_name,\n genepanel_version=genepanel_version,\n )\n session.add(aa)\n return a\n\n def _test_nearby(input: allele.Allele, expected_output: List[allele.Allele]):\n res = get_nearby_allele_ids(session, [input.id])\n assert set(res[input.id]) == set(map(lambda x: x.id, expected_output))\n\n # 0 1 2 3 4 5 6 7\n # 012345678901234567890123456789012345678901234567890123456789012345678901234567\n # aa 1111 2222 3333\n # aa 44\n # aq 11 3 5 6 8\n # aq 222 444 7 9 a\n #\n # aa: alleles assessments\n # aq: query alleles\n\n aa_1 = _create_allele(0, 3, \"4\")\n aa_2 = _create_allele(8, 11, \"3\")\n aa_3 = _create_allele(14, 17, \"2\")\n aa_4 = _create_allele(14, 15, \"1\")\n aq_1 = _create_allele(1, 2)\n aq_2 = _create_allele(2, 4)\n aq_3 = _create_allele(5, 5)\n aq_4 = _create_allele(7, 9)\n aq_5 = _create_allele(7, 7)\n aq_6 = _create_allele(11, 11)\n aq_7 = _create_allele(12, 12)\n aq_8 = _create_allele(13, 13)\n aq_9 = _create_allele(14, 14)\n aq_a = _create_allele(17, 17)\n session.flush()\n\n config[\"similar_alleles\"][\"max_genomic_distance\"] = 0\n _test_nearby(aq_1, [aa_1])\n _test_nearby(aq_2, [aa_1])\n _test_nearby(aq_3, [])\n _test_nearby(aq_4, [aa_2])\n _test_nearby(aq_5, [])\n _test_nearby(aq_6, [aa_2])\n _test_nearby(aq_7, [])\n _test_nearby(aq_8, [])\n _test_nearby(aq_9, [aa_3, aa_4])\n _test_nearby(aq_a, [aa_3])\n\n config[\"similar_alleles\"][\"max_genomic_distance\"] = 5\n _test_nearby(aq_1, [aa_1])\n _test_nearby(aq_2, [aa_1, aa_2])\n _test_nearby(aq_3, [aa_1, aa_2])\n _test_nearby(aq_4, [aa_1, aa_2, aa_3, aa_4])\n _test_nearby(aq_5, [aa_1, aa_2])\n _test_nearby(aq_6, [aa_2, aa_3, aa_4])\n _test_nearby(aq_7, [aa_2, aa_3, aa_4])\n _test_nearby(aq_8, [aa_2, aa_3, aa_4])\n _test_nearby(aq_9, [aa_2, aa_3, aa_4])\n _test_nearby(aq_a, [aa_3, aa_4])\n\n\ndef test_similaralleles(session, test_database, client):\n test_database.refresh()\n\n genepanel_name = \"HBOC\"\n genepanel_version = \"v01\"\n\n for aid in [1, 2]:\n aa = assessment.AlleleAssessment(\n user_id=1,\n allele_id=aid,\n classification=\"1\",\n evaluation={},\n genepanel_name=genepanel_name,\n genepanel_version=genepanel_version,\n )\n session.add(aa)\n session.commit()\n config[\"similar_alleles\"][\"max_genomic_distance\"] = 100\n query_ids = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]\n response = client.get(\n \"/api/v1/workflows/similar_alleles/{}/{}/?allele_ids={}\".format(\n genepanel_name, genepanel_version, \",\".join(query_ids)\n )\n )\n assert response.status_code == 200\n similar_alleles = response.get_json()\n # we want an entry for each query id\n assert set(similar_alleles.keys()) == set(query_ids)\n # we want both in the same order\n assert list(similar_alleles.keys()) == query_ids\n # no identical alleles\n for qid in query_ids:\n sim_ids = list(map(lambda x: x[\"id\"], similar_alleles[qid]))\n assert qid not in sim_ids\n # specific checks\n assert list(map(lambda x: x[\"id\"], similar_alleles[\"1\"])) == [2]\n assert list(map(lambda x: x[\"id\"], similar_alleles[\"2\"])) == [1]\n assert list(map(lambda x: x[\"id\"], similar_alleles[\"3\"])) == [1, 2]\n assert list(map(lambda x: x[\"id\"], similar_alleles[\"4\"])) == [1, 2]\n assert list(map(lambda x: x[\"id\"], similar_alleles[\"5\"])) == [1, 2]\n assert list(map(lambda x: x[\"id\"], similar_alleles[\"6\"])) == []\n","sub_path":"src/api/tests/test_similaralleles.py","file_name":"test_similaralleles.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"279689500","text":"import info\nfrom CraftOS.osutils import OsUtils\n\n\nclass subinfo(info.infoclass):\n def setTargets(self):\n self.svnTargets['master'] = 'git://anongit.kde.org/rkward'\n self.defaultTarget = 'master'\n self.displayName = \"RKWard\"\n\n def setDependencies(self):\n self.buildDependencies[\"extragear/rkward/rkward-translations\"] = None\n self.runtimeDependencies[\"binary/r-base\"] = \"default\"\n self.runtimeDependencies[\"kde/frameworks/tier1/ki18n\"] = \"default\"\n self.runtimeDependencies[\"kde/frameworks/tier3/ktexteditor\"] = \"default\"\n self.runtimeDependencies[\"kde/frameworks/tier1/kwindowsystem\"] = \"default\"\n self.runtimeDependencies[\"kde/frameworks/tier3/kdewebkit\"] = \"default\"\n # not strictly runtimeDependencies, but should be included in the package\n self.runtimeDependencies[\"kde/applications/kate\"] = \"default\"\n self.runtimeDependencies[\"kde/frameworks/tier1/breeze-icons\"] = \"default\"\n\nfrom Package.CMakePackageBase import *\n\n\nclass Package(CMakePackageBase):\n def __init__(self):\n CMakePackageBase.__init__(self)\n self.translations = CraftPackageObject.get(\"extragear/rkward/rkward-translations\").instance\n\n if OsUtils.isWin():\n if CraftCore.compiler.isX64():\n self.r_dir = os.path.join(CraftCore.standardDirs.craftRoot(), \"lib\", \"R\", \"bin\", \"x64\")\n else:\n self.r_dir = os.path.join(CraftCore.standardDirs.craftRoot(), \"lib\", \"R\", \"bin\", \"i386\")\n self.subinfo.options.configure.args = \" -DR_EXECUTABLE=\" + OsUtils.toUnixPath(os.path.join(self.r_dir, \"R.exe\"))\n elif OsUtils.isMac():\n self.subinfo.options.configure.args = \" -DR_EXECUTABLE=\" + os.path.join(CraftCore.standardDirs.craftRoot(), \"lib\", \"R\", \"R.framework\", \"Resources\", \"R\")\n\n if self.subinfo.hasSvnTarget:\n self.subinfo.options.configure.args += f\" -DTRANSLATION_SRC_DIR={OsUtils.toUnixPath(self.translations.sourceDir())}\"\n\n def fetch(self):\n # Temporary workaround for failure to pull due to local modification of ver.R. Remove the line below around June, 2018.\n utils.deleteFile(os.path.join(self.checkoutDir(), \"rkward\", \"rbackend\", \"rpackages\", \"rkward\", \"R\", \"ver.R\"))\n\n if not CMakePackageBase.fetch(self):\n return False\n if self.subinfo.hasSvnTarget:\n return self.translations.fetch(noop=False)\n return True\n\n def install(self):\n ret = CMakePackageBase.install(self)\n if OsUtils.isWin():\n # Make installation movable, by providing rkward.ini with relative path to R\n rkward_ini = open(os.path.join(self.imageDir(), \"bin\", \"rkward.ini\"), \"w\")\n if CraftCore.compiler.isX64():\n rkward_ini.write(\"R executable=../lib/R/bin/x64/R.exe\\n\")\n else:\n rkward_ini.write(\"R executable=../lib/R/bin/i386/R.exe\\n\")\n rkward_ini.close()\n return ret\n\n def configure(self):\n if CraftCore.compiler.isMSVC():\n # Need to create a .lib-file for R.dll, first\n dump = subprocess.check_output([\"dumpbin\", \"/exports\", os.path.join(self.r_dir, \"R.dll\")]).decode(\n \"latin1\").splitlines()\n exports = []\n for line in dump:\n fields = line.split()\n if len(fields) != 4:\n continue\n exports.append(fields[3])\n self.enterBuildDir()\n with open(os.path.join(self.buildDir(), \"R.def\"), \"wt+\") as deffile:\n deffile.write(\"EXPORTS\\n\")\n deffile.write(\"\\n\".join(exports))\n subprocess.call([\"lib\", \"/def:R.def\", \"/out:R.lib\", f\"/machine:{CraftCore.compiler.architecture}\"])\n return super().configure()\n\n def createPackage(self):\n self.defines[\"executable\"] = \"bin\\\\rkward.exe\"\n self.defines[\"icon\"] = os.path.join(self.sourceDir(), \"rkward\", \"icons\", \"app-icon\", \"rkward.ico\")\n\n self.ignoredPackages.append(\"binary/mysql\")\n self.ignoredPackages.append(\"data/hunspell-dictionaries\")\n self.whitelist_file.append(os.path.join(self.packageDir(), 'whitelist.txt'))\n\n if OsUtils.isMac():\n return self.debugCreatePackageMac()\n else:\n return TypePackager.createPackage(self)\n\n def preArchive(self):\n if OsUtils.isMac():\n # during packaging, the relative path between rkward and R gets changed, so we need to create an rkward.ini to help rkward find R\n rkward_dir = os.path.join(self.archiveDir(), \"Applications\", \"KDE\", \"rkward.app\", \"Contents\", \"MacOS\")\n utils.createDir(rkward_dir)\n rkward_ini = open(os.path.join(rkward_dir, \"rkward.ini\"), \"w\")\n rkward_ini.write(\"R executable=../Frameworks/R/R.framework/Resources/R\\n\")\n rkward_ini.close()\n return super().preArchive()\n\n # HACK: Remove me. This is a copy of MacDMGPackager, for the purpose of pinning down just what exactly causes\n # the .dmg detach to hang on the binary factory.\n def debugCreatePackageMac(self):\n \"\"\" create a package \"\"\"\n CraftCore.log.debug(\"packaging using the MacDMGPackager\")\n\n self.internalCreatePackage()\n self.preArchive()\n\n self._setDefaults()\n\n\n archive = os.path.normpath(self.archiveDir())\n appPath = self.defines['apppath']\n if not appPath:\n apps = glob.glob(os.path.join(archive, f\"**/{self.defines['appname']}.app\"), recursive=True)\n if len(apps) != 1:\n CraftCore.log.error(f\"Failed to detect *.app for {self}, please provide self.defines['apppath']\")\n return False\n appPath = apps[0]\n appPath = os.path.join(archive, appPath)\n appPath = os.path.normpath(appPath)\n CraftCore.log.info(f\"Packaging {appPath}\")\n\n targetLibdir = os.path.join(appPath, \"Contents\", \"Frameworks\")\n utils.createDir(targetLibdir)\n\n moveTargets = [\n (os.path.join(archive, \"lib\", \"plugins\"), os.path.join(appPath, \"Contents\", \"PlugIns\")),\n (os.path.join(archive, \"plugins\"), os.path.join(appPath, \"Contents\", \"PlugIns\")),\n (os.path.join(archive, \"lib\"), targetLibdir),\n (os.path.join(archive, \"share\"), os.path.join(appPath, \"Contents\", \"Resources\"))]\n\n if not appPath.startswith(archive):\n moveTargets += [(os.path.join(archive, \"bin\"), os.path.join(appPath, \"Contents\", \"MacOS\"))]\n\n for src, dest in moveTargets:\n if os.path.exists(src):\n if not utils.mergeTree(src, dest):\n return False\n\n with utils.ScopedEnv({'DYLD_FALLBACK_LIBRARY_PATH' : os.path.join(CraftStandardDirs.craftRoot(), \"lib\")}):\n if not utils.system([\"dylibbundler\",\n \"--overwrite-files\",\n \"--bundle-deps\",\n \"--install-path\", \"@executable_path/../Frameworks\",\n \"--dest-dir\", targetLibdir,\n \"--fix-file\", os.path.join(appPath, \"Contents\", \"MacOS\", self.defines['appname'])]):\n return False\n\n utils.system([\"ls\", \"-Rl\", appPath], True);\n utils.system([\"du\", \"-s\", appPath], True);\n\n if not utils.system([\"macdeployqt\", appPath, \"-always-overwrite\", \"-verbose=1\"]):\n return False\n\n name = self.binaryArchiveName(fileType=\"\", includeRevision=True)\n dmgDest = os.path.join(self.packageDestinationDir(), f\"{name}.dmg\")\n if os.path.exists(dmgDest):\n utils.deleteFile(dmgDest)\n if not utils.system([\"create-dmg\", \"--volname\", name, dmgDest, appPath]):\n return False\n\n CraftHash.createDigestFiles(dmgDest)\n\n return True\n","sub_path":"extragear/rkward/rkward/rkward.py","file_name":"rkward.py","file_ext":"py","file_size_in_byte":7984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"164353170","text":"# Copyright The PyTorch Lightning team.\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.\nimport pickle\nfrom copy import deepcopy\n\nimport pytest\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torchmetrics import Metric\n\nimport tests.helpers.utils as tutils\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning.trainer.connectors.logger_connector.result import _Sync, MetricSource, ResultCollection\nfrom tests.helpers import BoringModel\nfrom tests.helpers.runif import RunIf\n\n\nclass DummyMetric(Metric):\n\n def __init__(self):\n super().__init__()\n self.add_state(\"x\", torch.tensor(0), dist_reduce_fx=\"sum\")\n\n def update(self, x):\n self.x += x\n\n def compute(self):\n return self.x\n\n\ndef _setup_ddp(rank, worldsize):\n import os\n\n os.environ[\"MASTER_ADDR\"] = \"localhost\"\n\n # initialize the process group\n dist.init_process_group(\"gloo\", rank=rank, world_size=worldsize)\n\n\ndef _ddp_test_fn(rank, worldsize):\n _setup_ddp(rank, worldsize)\n torch.tensor([1.0])\n\n metric_a = DummyMetric()\n metric_b = DummyMetric()\n metric_c = DummyMetric()\n\n metric_a = metric_a.to(f\"cuda:{rank}\")\n metric_b = metric_b.to(f\"cuda:{rank}\")\n metric_c = metric_c.to(f\"cuda:{rank}\")\n\n result = ResultCollection(True, torch.device(f\"cuda:{rank}\"))\n\n for _ in range(3):\n cumulative_sum = 0\n for i in range(5):\n metric_a(i)\n metric_b(i)\n metric_c(i)\n\n cumulative_sum += i\n\n result.log('h', 'a', metric_a, on_step=True, on_epoch=True)\n result.log('h', 'b', metric_b, on_step=False, on_epoch=True)\n result.log('h', 'c', metric_c, on_step=True, on_epoch=False)\n\n batch_log = result.metrics(True)[MetricSource.LOG]\n assert batch_log == {\"a_step\": i, \"c\": i}\n\n epoch_log = result.metrics(False)[MetricSource.LOG]\n result.reset()\n\n # assert metric state reset to default values\n assert metric_a.x == metric_a._defaults['x'], (metric_a.x, metric_a._defaults['x'])\n assert metric_b.x == metric_b._defaults['x']\n assert metric_c.x == metric_c._defaults['x']\n\n assert epoch_log == {\"b\": cumulative_sum * worldsize, \"a_epoch\": cumulative_sum * worldsize}\n\n\n@RunIf(skip_windows=True, min_gpus=2)\ndef test_result_reduce_ddp():\n \"\"\"Make sure result logging works with DDP\"\"\"\n tutils.set_random_master_port()\n\n worldsize = 2\n mp.spawn(_ddp_test_fn, args=(worldsize, ), nprocs=worldsize)\n\n\ndef test_result_metric_integration():\n metric_a = DummyMetric()\n metric_b = DummyMetric()\n metric_c = DummyMetric()\n\n result = ResultCollection(True, torch.device(\"cpu\"))\n\n for _ in range(3):\n cumulative_sum = 0\n for i in range(5):\n metric_a(i)\n metric_b(i)\n metric_c(i)\n\n cumulative_sum += i\n\n result.log('h', 'a', metric_a, on_step=True, on_epoch=True)\n result.log('h', 'b', metric_b, on_step=False, on_epoch=True)\n result.log('h', 'c', metric_c, on_step=True, on_epoch=False)\n\n batch_log = result.metrics(True)[MetricSource.LOG]\n assert batch_log == {\"a_step\": i, \"c\": i}\n\n epoch_log = result.metrics(False)[MetricSource.LOG]\n result.reset()\n\n # assert metric state reset to default values\n assert metric_a.x == metric_a._defaults['x']\n assert metric_b.x == metric_b._defaults['x']\n assert metric_c.x == metric_c._defaults['x']\n\n assert epoch_log == {\"b\": cumulative_sum, \"a_epoch\": cumulative_sum}\n\n assert str(result) == (\n \"ResultCollection(True, cpu, {\"\n \"'h.a': ResultMetric(value=DummyMetric()), \"\n \"'h.b': ResultMetric(value=DummyMetric()), \"\n \"'h.c': ResultMetric(value=DummyMetric())\"\n \"})\"\n )\n\n\ndef test_result_collection_simple_loop():\n result = ResultCollection(True, torch.device(\"cpu\"))\n current_fx_name = None\n batch_idx = None\n\n def lightning_log(fx, *args, **kwargs):\n nonlocal current_fx_name\n if current_fx_name != fx and batch_idx in (None, 0):\n result.reset(metrics=False, fx=fx)\n result.log(fx, *args, **kwargs)\n current_fx_name = fx\n\n lightning_log('a0', 'a', torch.tensor(0.), on_step=True, on_epoch=True)\n lightning_log('a1', 'a', torch.tensor(0.), on_step=True, on_epoch=True)\n for epoch in range(2):\n lightning_log('b0', 'a', torch.tensor(1.) + epoch, on_step=True, on_epoch=True)\n lightning_log('b1', 'a', torch.tensor(1.) + epoch, on_step=True, on_epoch=True)\n for batch_idx in range(2):\n lightning_log('c0', 'a', torch.tensor(2.) + epoch, on_step=True, on_epoch=True)\n lightning_log('c1', 'a', torch.tensor(2.) + epoch, on_step=True, on_epoch=True)\n lightning_log('c2', 'a', torch.tensor(2.) + epoch, on_step=True, on_epoch=True)\n batch_idx = None\n lightning_log('d0', 'a', torch.tensor(3.) + epoch, on_step=False, on_epoch=True)\n lightning_log('d1', 'a', torch.tensor(3.) + epoch, on_step=False, on_epoch=True)\n\n for k in ('a0.a', 'a1.a'):\n assert result[k].value == torch.tensor(0.), k\n assert result[k].cumulated_batch_size == torch.tensor(1.), k\n\n for k in ('b0.a', 'b1.a'):\n assert result[k].value == torch.tensor(1.) + epoch, k\n assert result[k].cumulated_batch_size == torch.tensor(1.), k\n\n for k in ('c0.a', 'c1.a', 'c2.a'):\n assert result[k].value == torch.tensor(4.) + epoch * 2, k\n assert result[k].cumulated_batch_size == torch.tensor(2.), k\n\n for k in ('d0.a', 'd1.a'):\n assert result[k].value == torch.tensor(3.) + epoch, k\n assert result[k].cumulated_batch_size == torch.tensor(1.), k\n\n\ndef my_sync_dist(x):\n return x\n\n\ndef test_result_collection_restoration(tmpdir):\n \"\"\"\"\n This test make sure metrics are properly reloaded on failure.\n \"\"\"\n\n result = ResultCollection(True, torch.device(\"cpu\"))\n metric_a = DummyMetric()\n metric_b = DummyMetric()\n metric_c = DummyMetric()\n metric_d = DummyMetric()\n current_fx_name = None\n batch_idx = None\n\n def lightning_log(fx, *args, **kwargs):\n nonlocal current_fx_name\n if current_fx_name != fx and batch_idx in (None, 0):\n result.reset(metrics=False, fx=fx)\n result.log(fx, *args, **kwargs, sync_dist_fn=my_sync_dist)\n current_fx_name = fx\n\n for _ in range(2):\n\n cumulative_sum = 0\n\n for i in range(3):\n\n a = metric_a(i)\n b = metric_b(i)\n c = metric_c(i)\n metric_d(i)\n\n cumulative_sum += i\n\n metric = metric_a if i < 1 else metric_d\n lightning_log('training_step', 'a', metric, on_step=True, on_epoch=True)\n lightning_log('training_step', 'b', metric_b, on_step=False, on_epoch=True)\n lightning_log('training_step', 'c', metric_c, on_step=True, on_epoch=False)\n lightning_log('training_step', 'a_1', a, on_step=True, on_epoch=True)\n lightning_log('training_step', 'b_1', b, on_step=False, on_epoch=True)\n lightning_log('training_step', 'c_1', {'1': c, '2': c}, on_step=True, on_epoch=False)\n\n batch_log = result.metrics(on_step=True)[MetricSource.LOG]\n assert set(batch_log) == {\"a_step\", \"c\", \"a_1_step\", \"c_1\"}\n assert set(batch_log['c_1']) == {'1', '2'}\n\n result_copy = deepcopy(result)\n new_result = ResultCollection(True, torch.device(\"cpu\"))\n state_dict = result.state_dict()\n # check the sync fn was dropped\n assert 'fn' not in state_dict['items']['training_step.a']['meta']['_sync']\n new_result.load_state_dict(state_dict)\n # should match\n assert result_copy == new_result\n # the sync fn has been kept\n assert result_copy['training_step.a'].meta.sync.fn == new_result['training_step.a'].meta.sync.fn\n\n epoch_log = result.metrics(on_step=False)[MetricSource.LOG]\n epoch_log_copy = result_copy.metrics(on_step=False)[MetricSource.LOG]\n assert epoch_log == epoch_log_copy\n\n lightning_log('train_epoch_end', 'a', metric_a, on_step=False, on_epoch=True)\n epoch_log = result.metrics(on_step=False)[MetricSource.LOG]\n assert epoch_log == {\n 'a_1_epoch': 1,\n 'a_epoch': cumulative_sum,\n 'a': cumulative_sum,\n 'b': cumulative_sum,\n 'b_1': 1\n }\n\n # make sure can be pickled\n pickle.loads(pickle.dumps(result))\n # make sure can be torch.loaded\n filepath = str(tmpdir / 'result')\n torch.save(result, filepath)\n torch.load(filepath)\n\n # assert metric state reset to default values\n result.reset()\n assert metric_a.x == metric_a._defaults['x']\n assert metric_b.x == metric_b._defaults['x']\n assert metric_c.x == metric_c._defaults['x']\n\n batch_idx = None\n\n\n@pytest.mark.parametrize('device', ('cpu', pytest.param('cuda', marks=RunIf(min_gpus=1))))\ndef test_lightning_module_logging_result_collection(tmpdir, device):\n\n class LoggingModel(BoringModel):\n\n def __init__(self):\n super().__init__()\n self.metric = DummyMetric()\n\n def validation_step(self, batch, batch_idx):\n v = self.metric(batch_idx)\n self.log_dict({\"v\": v, \"m\": self.metric})\n return super().validation_step(batch, batch_idx)\n\n def on_save_checkpoint(self, checkpoint) -> None:\n results = self.trainer._results\n state_dict = results.state_dict()\n\n # check device\n assert results['validation_step.v'].value.device.type == device\n assert state_dict['items']['validation_step.v']['value'].device.type == device\n\n # sync fn should be kept\n assert results['validation_step.v'].meta.sync.fn == self.trainer.training_type_plugin.reduce\n\n # sync fn dropped from the state dict\n assert 'fn' not in state_dict['items']['validation_step.v']['meta']['_sync']\n results.load_state_dict(state_dict)\n\n # check device after loading\n assert results['validation_step.v'].value.device.type == device\n\n # sync fn was preserved in the original result\n assert results['validation_step.v'].meta.sync.fn == self.trainer.training_type_plugin.reduce\n\n # default sync fn\n new_results = ResultCollection(False, device)\n new_results.load_state_dict(state_dict, map_location='cpu')\n assert new_results['validation_step.v'].meta.sync.fn == _Sync.no_op\n\n # check map location\n assert new_results['validation_step.v'].value.device.type == 'cpu'\n\n model = LoggingModel()\n ckpt = ModelCheckpoint(dirpath=tmpdir, save_last=True)\n trainer = Trainer(\n default_root_dir=tmpdir,\n max_epochs=2,\n limit_train_batches=2,\n limit_val_batches=2,\n callbacks=[ckpt],\n gpus=1 if device == 'cuda' else 0,\n )\n trainer.fit(model)\n","sub_path":"tests/core/test_metric_result_integration.py","file_name":"test_metric_result_integration.py","file_ext":"py","file_size_in_byte":11798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"145275990","text":"\"\"\"\"A sphinx extension to add a ``panels`` directive.\"\"\"\nimport os\n\nfrom docutils import nodes\nfrom docutils.parsers.rst import directives, Directive\n\nfrom .button import setup_link_button\nfrom .dropdown import setup_dropdown\nfrom .panels import setup_panels\nfrom .icons import setup_icons\n\n__version__ = \"0.4.1\"\n\n\nLOCAL_FOLDER = os.path.dirname(os.path.abspath(__file__))\n\n\ndef add_static_paths(app):\n app.config.html_static_path.append(os.path.join(LOCAL_FOLDER, \"css\"))\n app.add_css_file(\"sphinx-dropdown.css\")\n if app.config.panels_add_boostrap_css:\n app.add_css_file(\"panels-bootstrap.min.css\")\n\n\nclass Div(Directive):\n \"\"\"Same as the ``container`` directive,\n but does not add the ``container`` class in HTML outputs,\n which can interfere with Bootstrap CSS.\n \"\"\"\n\n optional_arguments = 1\n final_argument_whitespace = True\n option_spec = {\"name\": directives.unchanged}\n has_content = True\n\n def run(self):\n self.assert_has_content()\n text = \"\\n\".join(self.content)\n try:\n if self.arguments:\n classes = directives.class_option(self.arguments[0])\n else:\n classes = []\n except ValueError:\n raise self.error(\n 'Invalid class attribute value for \"%s\" directive: \"%s\".'\n % (self.name, self.arguments[0])\n )\n node = nodes.container(text, is_div=True)\n node[\"classes\"].extend(classes)\n self.add_name(node)\n self.state.nested_parse(self.content, self.content_offset, node)\n return [node]\n\n\ndef visit_container(self, node):\n classes = \"docutils container\"\n if node.get(\"is_div\", False):\n # we don't want the CSS for container for these nodes\n classes = \"docutils\"\n self.body.append(self.starttag(node, \"div\", CLASS=classes))\n\n\ndef depart_container(self, node):\n self.body.append(\"\\n\")\n\n\ndef setup(app):\n app.add_directive(\"div\", Div)\n app.add_config_value(\"panels_add_boostrap_css\", True, \"env\")\n app.connect(\"builder-inited\", add_static_paths)\n # we override container html visitors, to stop the default behaviour\n # of adding the `container` class to all nodes.container\n app.add_node(\n nodes.container, override=True, html=(visit_container, depart_container)\n )\n\n setup_panels(app)\n setup_link_button(app)\n setup_dropdown(app)\n setup_icons(app)\n\n return {\n \"version\": __version__,\n \"parallel_read_safe\": True,\n \"parallel_write_safe\": True,\n }\n","sub_path":"sphinx_panels/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"478349102","text":"import pandas as pd\nimport warnings\nimport logging\nfrom sklearn.preprocessing import MinMaxScaler \nwarnings.filterwarnings(\"ignore\")\n\ndef preprocessor(df):\n df.drop('customerID',axis='columns',inplace=True)\n\n # Where ever there is ' ' in TotalCharges it is ignored and rest is stored in df1\n df = df[df.TotalCharges!=' ']\n df.TotalCharges = pd.to_numeric(df.TotalCharges)\n df.replace('No internet service','No',inplace=True)\n df.replace('No phone service','No',inplace=True)\n\n ## These are all the columns with yes and no\n yes_no_columns = ['Partner','Dependents','PhoneService','MultipleLines','OnlineSecurity','OnlineBackup',\n 'DeviceProtection','TechSupport','StreamingTV','StreamingMovies','PaperlessBilling','Churn']\n \n ## Applying the for loop for 1's and 0's in place of yes and no\n for col in yes_no_columns:\n df[col].replace({'Yes': 1,'No': 0},inplace=True)\n\n ## Similarly for male and female\n df['gender'].replace({'Female':1,'Male': 0},inplace=True)\n\n ## For all the columns which has more than 2 classes we apply get_dummies\n data1 = pd.get_dummies(data=df , columns=['InternetService','Contract','PaymentMethod'])\n\n ## Normalizing data using MinMax scaler\n columns_to_be_scaled = ['tenure', 'MonthlyCharges', 'TotalCharges']\n scaler = MinMaxScaler()\n data1[columns_to_be_scaled] = scaler.fit_transform(data1[columns_to_be_scaled])\n\n\n pd.set_option('display.max_columns', None)\n print(data1.head(2))\n return data1\n","sub_path":"src/utils/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"533990379","text":"from bs4 import BeautifulSoup\nfrom html2text import html2text\n\nimport sys\nimport datetime\nimport os\nimport json\n\nfrom simple import db, Post\n\ndef read_to_post(src_path):\n\twith open(src_path, 'r') as f:\n\t\tsoup = BeautifulSoup(f)\n\t\theader = soup.find_all('div', class_='post_header')[0]\n\t\tbody = soup.find_all('div', class_='post_body')[0]\n\t\tpost_time_str = ' '.join(header.find('span', class_=\"post_time\").string.split())\n\t\tpost_time = datetime.datetime.strptime(post_time_str, '%B %d %Y, %I:%M %p')\n\t\ttitle = header.find('h3').string.strip()\n\n\t\tpost = Post(title = title, created_at = post_time)\n\n\t\tembed = body.find('div', class_='p_audio_embed')\n\t\tif embed:\n\t\t\thref = embed.a.get('href')\n\t\t\thref = '/uploads/posterous' + href[href.find('/audio/'):]\n\t\t\tmp3 = soup.new_tag('a', href=href)\n\t\t\tmp3.attrs['class'] = 'sm2_button'\n\t\t\tmp3.string = 'Listen'\n\t\t\tembed.a.replace_with(mp3)\n\n\t\tsrc_name,_ = os.path.splitext(os.path.basename(src_path))\n\t\tpost.readable_id = post.readable_id + src_name\n\n\t\t#must set this so that set_content() can detect links (for has_audio)\n\t\t#if not set, it doesn't convert to html first... so links is []\n\t\tpost.text_type = 'markdown' \n\t\n\t\tpost.set_content(html2text(unicode(body)))\n\t\tpost.draft = False\n\t\treturn post\n\n\n\nsrc_dir = sys.argv[1]\n\nfor dir_path, dirs, files in os.walk(src_dir):\n\tfor file_name in files:\n\t\tif file_name.endswith('.html'):\n\t\t\tfile_path = os.path.join(dir_path, file_name)\n\t\t\tpost = read_to_post(file_path)\n\t\t\tprint(post.readable_id)\n\t\t\tdb.session.add(post)\ndb.session.commit()\n","sub_path":"import_from_posterous.py","file_name":"import_from_posterous.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"418094857","text":"import os, sys, shutil\nFHMCLIB = \"/home/nam4/\"\nsys.path.append(FHMCLIB)\nimport FHMCAnalysis\nimport FHMCAnalysis.moments.win_patch.windows as win\nimport FHMCSimulation.helper.window_helper as hP\n\n# Overwrite existing inputs\noverwrite = True\n\n# Establish bounds for windows\nntot_max = 600\nfinal_window_width = 20\nnum_windows = 24\nnum_overlap = 6\n\n# Need installation information\ninstall_dir = \"/home/nam4/FHMCSimulation/\"\nbinary = install_dir+\"/bin/fhmc_tmmc\"\ngit_head = install_dir+\"/.git/logs/HEAD\"\njobs_per = 12\nscratch_dir = \"/scratch/nam4/\"\nq = \"mml\"\ntag = \"lam1.5-1.1(2)\"\nhours = 72\n\t\n# Window settings\ninput_name = \"input.json\"\nprefix = \"./\"\nbeta = 1.0/1.10\nbounds = win.ntot_window_scaling (ntot_max, final_window_width, num_windows, num_overlap)\n\nsett = {}\nsett[\"beta\"] = beta\nfor w in range(num_windows):\n\tdname = prefix+\"/\"+str(w+1)\n\tif ((str(w+1) in os.listdir(prefix)) and overwrite):\n\t\tshutil.rmtree(dname, pure_settings)\n\tos.makedirs(dname)\n\n\tsett[\"bounds\"] = bounds[w]\n\thP.make_input (dname+\"/\"+input_name, sett, hP.pure_settings)\n\thP.make_sleeper (dname+\"/sleeper.sh\")\n\nhP.raritan_sbatch (num_windows, binary, git_head, tag, prefix, input_name, jobs_per, q, hours, scratch_dir)\n","sub_path":"example/ntot/square_well/T_1.10/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"59105590","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport torch\nimport numpy as np\nprint(torch.__version__)\n\n\n# 返回的数组大小5x4的矩阵\nprint(torch.Tensor(5, 4))\n#使用torch.tensor创建Tensor\nprint(torch.tensor([5,4]))\n# 得到矩阵大小\na = torch.rand(5, 4)\nprint(a.size())\n# numpy 类似的返回5x4大小的矩阵\nprint(np.ones((5, 4)))\n# numpy 和 torch.Tensor 之间的转换\na = torch.rand(5, 4)\nb = a.numpy()\nprint(b)\na = np.array([[3, 4], [3, 6]])\nb = torch.from_numpy(a)\nprint(b)\n\n\n# 运算和numpy类似\nx = torch.rand(5, 4)\ny = torch.rand(5, 4)\nc = 3\nprint(c * x)\nprint(x + y)\nprint(x.add(y))\n# 可以直接进行操作改变原对象,x+y或者x.add()并不会改变x,但是x.add_()则会对x进行改变\nx.add_(y)\nprint(x)\n\n\n# 将 torch.Tensor 放到 GPU 上\n# 判断一下电脑是否支持GPU\ntorch.cuda.is_available()\na = torch.rand(5, 4)\n# a = a.cuda()\nprint(a)\n\n\n# ### torch 的自动求导功能\n# torch 和大部分框架一样有着自动求导功能,对象不再是 torch.Tensor,而是torch.autograd.Variable\n# 本质上Variable和Tensor没有什么区别,不过Variable会放在一个计算图里面,可以进行前向传播和反向传播以及求导 \n# 里面的creator表示通过什么操作得到的这个Variable,grad表示反向传播的梯度\n\nfrom torch.autograd import Variable\n# requires_grad 表示是否对其求梯度,默认是False\nx = Variable(torch.Tensor([3]), requires_grad=True)\ny = Variable(torch.Tensor([5]), requires_grad=True)\nz = 2 * x + y + 4\n# 对 x 和 y 分别求导,默认只求一次导,如果要多次求导需要设置 retain_graph=True\nz.backward()\n# x 的导数和 y 的导数\nprint('dz/dx: {}'.format(x.grad.data))\nprint('dz/dy: {}'.format(y.grad.data))\n\n\n# ### 神经网络部分\n# 所依赖的主要是 torch.nn 和 torch.nn.functional\n# torch.nn 里面有着所有的神经网络的层的操作,其用来构建网络,只有执行一次网络的运算才执行一次 \n# torch.nn.functional 表示的是直接对其做一次向前运算操作\n\n# 基本的网络构建类模板\nclass net_name(torch.nn.Module):\n def __init__(self):\n super(net_name, self).__init__()\n # 可以添加各种网络层\n self.conv1 = torch.nn.Conv2d(3, 10, 3)\n # 具体每种层的参数可以去查看文档\n \n def forward(self, x):\n # 定义向前传播\n out = self.conv1(x)\n return out\n","sub_path":"00-Pytorch Basics/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"587599245","text":"# 체육복\n#문제를 꼼꼼하게 읽자 \n# n번 학생은 n-1 or n+1 학생에게만 체육복을 빌려줄 수 있다.\ndef solution(n, lost, reserve):\n answer = 0\n for i in range(1, n+1):\n if i not in lost:\n answer += 1\n elif i in reserve:\n lost.remove(i)\n reserve.remove(i)\n answer+=1\n # 반복문을 돌릴때 remove하면 누락되는 요소가 생김. \n\n # n-1, n+1 비교하기\n for i in lost:\n if i -1 in reserve:\n reserve.remove(i-1)\n answer+=1\n elif i+1 in reserve:\n reserve.remove(i+1)\n answer+=1\n return answer\n \nprint(solution(5, [4, 5], [1, 2, 3]))","sub_path":"programmers/42862.py","file_name":"42862.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"467856750","text":"\"\"\"Energy distance functions\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\nfrom __future__ import unicode_literals\n\nimport warnings\n\nimport numpy as np\n\nfrom . import distances\nfrom ._utils import _transform_to_2d\n\n\ndef _check_valid_energy_exponent(exponent):\n if not 0 < exponent < 2:\n warning_msg = ('The energy distance is not guaranteed to be '\n 'a valid metric if the exponent value is '\n 'not in the range (0, 2). The exponent passed '\n 'is {exponent}.'.format(exponent=exponent))\n\n warnings.warn(warning_msg)\n\n\ndef _energy_distance_from_distance_matrices(\n distance_xx, distance_yy, distance_xy):\n \"\"\"Compute energy distance with precalculated distance matrices.\"\"\"\n return (2 * np.mean(distance_xy) - np.mean(distance_xx) -\n np.mean(distance_yy))\n\n\ndef _energy_distance_imp(x, y, exponent=1):\n \"\"\"\n Real implementation of :func:`energy_distance`.\n\n This function is used to make parameter ``exponent`` keyword-only in\n Python 2.\n\n \"\"\"\n x = _transform_to_2d(x)\n y = _transform_to_2d(y)\n\n _check_valid_energy_exponent(exponent)\n\n distance_xx = distances.pairwise_distances(x, exponent=exponent)\n distance_yy = distances.pairwise_distances(y, exponent=exponent)\n distance_xy = distances.pairwise_distances(x, y, exponent=exponent)\n\n return _energy_distance_from_distance_matrices(distance_xx=distance_xx,\n distance_yy=distance_yy,\n distance_xy=distance_xy)\n\n\ndef energy_distance(x, y, **kwargs):\n \"\"\"\n energy_distance(x, y, *, exponent=1)\n\n Computes the estimator for the energy distance of the\n random vectors corresponding to :math:`x` and :math:`y`.\n Both random vectors must have the same number of components.\n\n Parameters\n ----------\n x: array_like\n First random vector. The columns correspond with the individual random\n variables while the rows are individual instances of the random vector.\n y: array_like\n Second random vector. The columns correspond with the individual random\n variables while the rows are individual instances of the random vector.\n exponent: float\n Exponent of the Euclidean distance, in the range :math:`(0, 2)`.\n\n Returns\n -------\n numpy scalar\n Value of the estimator of the energy distance.\n\n Examples\n --------\n >>> import numpy as np\n >>> import dcor\n >>> a = np.array([[1, 2, 3, 4],\n ... [5, 6, 7, 8],\n ... [9, 10, 11, 12],\n ... [13, 14, 15, 16]])\n >>> b = np.array([[1, 0, 0, 1],\n ... [0, 1, 1, 1],\n ... [1, 1, 1, 1]])\n >>> dcor.energy_distance(a, a)\n 0.0\n >>> dcor.energy_distance(a, b) # doctest: +ELLIPSIS\n 20.5780594...\n >>> dcor.energy_distance(b, b)\n 0.0\n\n A different exponent for the Euclidean distance in the range\n :math:`(0, 2)` can be used:\n\n >>> dcor.energy_distance(a, a, exponent=1.5)\n 0.0\n >>> dcor.energy_distance(a, b, exponent=1.5)\n ... # doctest: +ELLIPSIS\n 99.7863955...\n >>> dcor.energy_distance(b, b, exponent=1.5)\n 0.0\n\n \"\"\"\n return _energy_distance_imp(x, y, **kwargs)\n","sub_path":"dcor/_energy.py","file_name":"_energy.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"61554139","text":"from typing import Tuple, List\nfrom disjoint_set import DisjointSet\nfrom collections import deque\nimport random\n\nclass Maze:\n # Avaliable directions\n LEFT = 1 << 0\n RIGHT = 1 << 1\n UP = 1 << 2\n DOWN = 1 << 3\n\n # Offsets\n OFF_LEFT = (0, -1)\n OFF_RIGHT = (0, 1)\n OFF_UP = (-1, 0)\n OFF_DOWN = (1, 0)\n # Special markers\n EMPTY = 0\n VISITED = 1\n SOLUTION = 2\n\n # Algorithms\n DFS = 'dfs'\n KRUSKAL = 'kruskal'\n DIVISION = 'division'\n\n @staticmethod\n def get_dir(i_offset: int, j_offset: int) -> int:\n pass\n\n @staticmethod\n def neg_mask(d: int) -> int:\n return (Maze.LEFT | Maze.RIGHT | Maze.UP | Maze.DOWN) - d\n\n @staticmethod\n def can_go(cell: int, d: int) -> bool:\n return True if cell == Maze.EMPTY else cell & d > 0\n\n def __init__(self, w: int=10, h: int=10\n ,start: Tuple[int ,int]=(0, 0), end: Tuple[int, int] = None, algorithm='kruskal'):\n # Inits\n self.w = w\n self.h = h\n self.start = start\n self.maze = None\n self.solution = None\n self.algorithm = algorithm\n if end is None:\n end = (h-1, w-1)\n self.end = end\n self.compute_aux_maps()\n \n def get_avail_neighbour_offset(self, y: int, x: int) -> List[Tuple[int, int]]:\n nbs = []\n for (i, j) in self.OFF_DIR.keys():\n if y + i < 0 or y + i >= self.h or x + j < 0 or x + j >= self.w:\n continue\n if self.maze[y + i][x + j] == self.EMPTY:\n nbs.append((i, j))\n return nbs\n\n def set_dir(self, y: int, x: int, d: int):\n self.maze[y][x] = max(self.maze[y][x], 0) | d\n \n def populate_dfs(self):\n stack = []\n # Run DFS, create a stack of nodes\n stack.append((self.start))\n while stack:\n i, j = stack.pop()\n # Select a new neighbor\n nbs = self.get_avail_neighbour_offset(i, j)\n if not nbs:\n continue\n random.shuffle(nbs)\n # pair the cells\n for nb in nbs:\n nd = self.OFF_DIR[nb]\n self.set_dir(i, j, nd)\n self.set_dir(i+nb[0], j+nb[1], self.OPOSITE[nd])\n stack.append((i+nb[0], j+nb[1]))\n\n def populate_kruskal(self):\n cells = []\n edges = []\n for i in range(self.h):\n for j in range(self.w):\n cells.append((i, j))\n if i + 1 < self.h:\n edges.append(((i, j), (i + 1, j)))\n if j + 1 < self.w:\n edges.append(((i, j), (i, j + 1)))\n ds = DisjointSet(cells)\n random.shuffle(edges)\n for edge in edges:\n (a, b), (c, d) = edge\n if ds.union((a, b), (c, d)):\n nb = (c-a, d-b)\n nd = self.OFF_DIR[nb]\n self.set_dir(a, b, nd)\n self.set_dir(c, d, self.OPOSITE[nd])\n \n def populate_recursive(self, start: Tuple[int, int], end: Tuple[int, int]):\n i1, j1 = start\n i2, j2 = end\n # if grid is less than 2x2 return\n if i2 - i1 < 2 or j2 - j1 < 2:\n return\n # choose x, y in the middle\n y = (i1 + i2) // 2\n x = (j1 + j2) // 2\n # set walls\n for j in range(j1, j2):\n self.maze[y-1][j] &= self.neg_mask(self.DOWN)\n self.maze[y][j] &= self.neg_mask(self.UP)\n for i in range(i1, i2):\n self.maze[i][x-1] &= self.neg_mask(self.RIGHT)\n self.maze[i][x] &= self.neg_mask(self.LEFT)\n # select a random index from each one of the 4 smaller walls formed by the intersection \n walls = [\n (y, random.randint(j1, x-1), -1, 0, self.UP, self.DOWN),\n (y, random.randint(x, j2-1), -1, 0, self.UP, self.DOWN),\n (random.randint(i1, y-1), x, 0, -1, self.LEFT, self.RIGHT),\n (random.randint(y, i2-1), x, 0, -1, self.LEFT, self.RIGHT),\n ]\n # keep only 3 of them\n toremove = random.choice(walls)\n walls.remove(toremove)\n # remove selected walls\n for wall in walls:\n i, j, o1, o2, d1, d2 = wall\n self.maze[i][j] |= d1\n self.maze[i+o1][j+o2] |= d2\n # populate the maze in all 4 sub mazes generated\n self.populate_recursive((i1, j1), (y, x))\n self.populate_recursive((i1, x), (y, j2))\n self.populate_recursive((y, j1), (i2, x))\n self.populate_recursive((y, x), (i2, j2))\n\n def populate(self):\n self.erase()\n if self.algorithm == self.DFS:\n self.populate_dfs()\n elif self.algorithm == self.KRUSKAL:\n self.populate_kruskal()\n elif self.algorithm == self.DIVISION:\n self.populate_recursive((0, 0), (self.h, self.w))\n \n def solve(self):\n self.solution = [[self.EMPTY for _ in range(self.w)] for _ in range(self.h)]\n prevs = {self.start: None}\n queue = deque()\n queue.append(self.start)\n while queue:\n x = queue.popleft()\n if x == self.end:\n break\n i, j = x\n self.solution[i][j] = self.VISITED\n # get available neighbors\n nbs = []\n for k in self.OFF_DIR:\n (oi, oj), d = k, self.OFF_DIR[k]\n # if valid neighbor (in offsets, dir not blocked and not visited)\n if ((0 <= i + oi < self.h and 0 <= j + oj < self.w )\n and self.maze[i+oi][j+oj] & self.OPOSITE[d] > 0 and self.solution[i+oi][j+oj] == self.EMPTY and (i+oi, j+oj) not in prevs):\n nbs.append((i+oi, j+oj))\n prevs[(i+oi, j+oj)] = x\n # add neighbors in queue\n queue.extend(nbs)\n # calculate paths\n p = self.end\n while p is not None:\n i, j = p\n self.solution[i][j] = self.SOLUTION\n p = prevs[p]\n \n def erase(self):\n if self.algorithm == self.DIVISION:\n self.maze = [[self.LEFT | self.RIGHT | self.UP | self.DOWN for _ in range(self.w)] for _ in range(self.h)]\n self.maze[0] = [x & self.neg_mask(self.UP) for x in self.maze[0]]\n self.maze[-1] = [x & self.neg_mask(self.DOWN) for x in self.maze[-1]]\n for i in range(self.h):\n self.maze[i][0] &= self.neg_mask(self.LEFT)\n self.maze[i][-1] &= self.neg_mask(self.RIGHT)\n else:\n self.maze = [[self.EMPTY for _ in range(self.w)] for _ in range(self.h)]\n \n def print(self):\n if self.maze is None:\n return\n for i, line in enumerate(self.maze):\n char_func = lambda j_v: self.CHARS_EMPTY[j_v[1]] if (self.solution is not None \n and self.solution[i][j_v[0]] == self.SOLUTION) else self.CHARS[j_v[1]]\n line = list(map(char_func, enumerate(line)))\n print(\"\".join(line))\n\n def compute_aux_maps(self):\n self.OFF_DIR = {\n self.OFF_LEFT: self.LEFT,\n self.OFF_RIGHT: self.RIGHT,\n self.OFF_UP: self.UP,\n self.OFF_DOWN: self.DOWN\n }\n # opposite\n self.OPOSITE = {\n self.LEFT: self.RIGHT,\n self.RIGHT: self.LEFT,\n self.UP: self.DOWN,\n self.DOWN: self.UP\n }\n # drawing chars\n self.CHARS = {\n self.EMPTY: \" \",\n self.LEFT: \"\\u2578\",\n self.RIGHT: \"\\u257a\",\n self.UP: \"\\u2579\",\n self.DOWN: \"\\u257b\",\n self.LEFT | self.RIGHT: \"\\u2501\",\n self.LEFT | self.UP: \"\\u251b\",\n self.LEFT | self.DOWN: \"\\u2513\",\n self.RIGHT | self.UP: \"\\u2517\",\n self.RIGHT | self.DOWN: \"\\u250f\",\n self.UP | self.DOWN: \"\\u2503\",\n self.LEFT | self.RIGHT | self.UP: \"\\u253b\",\n self.LEFT | self.RIGHT | self.DOWN: \"\\u2533\",\n self.LEFT | self.UP | self.DOWN: \"\\u252b\",\n self.RIGHT | self.UP | self.DOWN: \"\\u2523\",\n self.LEFT | self.RIGHT | self.UP | self.DOWN: \"\\u254b\"\n }\n self.CHARS_EMPTY = {\n self.EMPTY: \" \",\n self.LEFT: \"\\u2555\",\n self.RIGHT: \"\\u2558\",\n self.UP: \"\\u2559\",\n self.DOWN: \"\\u2556\",\n self.LEFT | self.RIGHT: \"\\u2550\",\n self.LEFT | self.UP: \"\\u255d\",\n self.LEFT | self.DOWN: \"\\u2557\",\n self.RIGHT | self.UP: \"\\u255a\",\n self.RIGHT | self.DOWN: \"\\u2554\",\n self.UP | self.DOWN: \"\\u2551\",\n self.LEFT | self.RIGHT | self.UP: \"\\u2569\",\n self.LEFT | self.RIGHT | self.DOWN: \"\\u2566\",\n self.LEFT | self.UP | self.DOWN: \"\\u2563\",\n self.RIGHT | self.UP | self.DOWN: \"\\u2560\",\n self.LEFT | self.RIGHT | self.UP | self.DOWN: \"\\u256c\"\n }\n\n\nif __name__ == \"__main__\":\n maze = Maze(20, 20, algorithm=Maze.DIVISION)\n maze.populate()\n maze.solve()\n maze.print()\n\n\n\n","sub_path":"mazegen.py","file_name":"mazegen.py","file_ext":"py","file_size_in_byte":9243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"53079490","text":"from collections import deque\nimport sys\ninput = sys.stdin.readline\n\n\ndef topologicalSort():\n for _ in range(N):\n if not dq:\n return\n\n target = dq.popleft()\n\n for x in adjList[target]:\n sequence[x] = max(sequence[x], sequence[target] + D[x])\n indegree[x] -= 1\n \n if not indegree[x]:\n dq.append(x)\n\n\nT = int(input())\n\nfor _ in range(T):\n N, K = map(int, input().split())\n D = [0] + list(map(int, input().split()))\n\n sequence = [0] * (N + 1)\n indegree = [0] * (N + 1)\n adjList = [[] for _ in range(N + 1)]\n\n for _ in range(K):\n X, Y = map(int, input().split())\n\n indegree[Y] += 1\n adjList[X].append(Y)\n \n W = int(input())\n\n dq = deque()\n for i in range(1, N + 1):\n if not indegree[i]:\n sequence[i] = D[i]\n dq.append(i)\n\n topologicalSort()\n\n print(sequence[W])\n","sub_path":"BaekjoonOnlineJudge/1005/1005.py","file_name":"1005.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"272748831","text":"from graphics import *\nfrom time import sleep\n\ndef plotPoint(x,y,wi):\n\tpt = Point(round(x),round(y))\n\tpt.setFill(\"blue\")\n\tpt.draw(wi)\n\ndef Bresenham(x1,y1,x2,y2):\n\twin = GraphWin(\"DDA\",600,600)\n\twin.setBackground(color_rgb(0,0,0))\n\twin.setCoords(-300,-300,300,300)\n\tx = x1\n\ty = y1\n\n\tdx = x2-x1\n\tdy = y2-y1\n\tp = 2*dx-dy\n\twhile(x <= x2):\n\t\tplotPoint(x,y,win)\n\t\tx+=1\n\t\tif(p<0):\n\t\t\tp = p+2*dy\n\t\telse:\n\t\t\tp = p+2*dy-2*dx\n\t\t\ty+=1\n\t\tsleep(0.02)\n\n\twin.getMouse()\n\twin.close()\n\nif __name__ == '__main__':\n\tx1 = int(input( \"Enter x1: \" ))\n\ty1 = int(input( \"Enter y1: \" ))\n\tx2 = int(input( \"Enter x2: \" ))\n\ty2 = int(input( \"Enter y2: \" ))\n\tBresenham(x1,y1,x2,y2)","sub_path":"Bresenham.py","file_name":"Bresenham.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"288183129","text":"import requests,json\ndef test():\n furl = \"http://127.0.0.1:8000/fposition\"\n surl = \"http://127.0.0.1:8000/sposition\"\n for i in range(1000):\n dummy_fdata = {\"angle\": \"90.0\", \"distance\":\"125.0\"}\n dummy_sdata = {\"angle\": \"80.0\", \"distance\":\"124.0\"}\n fpost = requests.post(url=furl,data=dummy_fdata)\n spost = requests.post(url=surl,data=dummy_sdata)\n fget = requests.get(url=furl)\n sget = requests.get(url=surl)\n\ndef test_ben(benchmark):\n benchmark(test)\n","sub_path":"webview/monitor/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"53443076","text":"#cd Desktop/Python/workspace/school_manager\n#git add .\n#git commit -m \"\"\n#git push origin master\n\nimport tkinter as tk\nfrom tkinter import ttk\n\nOFF_WHITE = '#bdc3c7'\nFONT = ('Segoe UI', 10)\nFONT_BIG = ('Segoe UI', 14, 'bold')\n\nSTART_MENU = None\nSCHEDULE_MENU = None\n\ndef set_menu(root, menu):\n root.config(menu = menu)\n\ndef create_label(frame, text, row = 0, column = 0, colspan = 1, padx = 5, pady = 5, sticky = tk.NSEW, relief = tk.FLAT):\n lab = tk.Label(frame, text = text, relief = relief, font = FONT)\n lab.grid(row = row, column = column, columnspan = colspan, padx = padx, pady = pady, sticky = sticky)\n return lab\n\ndef create_button(frame, text, command, row = 0, column = 0, sticky = tk.NSEW, padx = 5, pady = 5, colspan = 1) -> ttk.Button:\n s = ttk.Style()\n s.configure('TButton', font = FONT)\n button = ttk.Button(frame, text = text, command = command, style = 'TButton')\n button.grid(row = row, column = column, padx = padx, pady = pady, sticky = sticky, columnspan = colspan)\n return button\n \ndef create_labeled_entry(frame, label_text, row, column = 0, padx = 5, pady = 5, insert = '') -> tk.Entry:\n tk.Label(frame, text = label_text, font = FONT).grid(row = row , column = column, padx = padx, pady = pady)\n entry = tk.Entry(frame)\n entry.insert(0, insert)\n entry.grid(row = row, column = column + 1, padx = padx, pady = pady)\n return entry\n\ndef create_option_menu(frame, str_var, options: [str], row, column, padx = 5, pady = 5) -> ttk.OptionMenu:\n menu = ttk.OptionMenu(frame, str_var, options[0], *options)\n menu.grid(row = row, column = column, padx = padx, pady = pady)\n return menu\n\ndef create_title(frame, text, colspan = 0, padx = 5, pady = 5, pack = False) -> None:\n lab = tk.Label(frame, text = text, font = FONT_BIG, bg = 'light grey')\n sep = ttk.Separator(frame, orient = tk.HORIZONTAL)\n if pack:\n lab.pack(fill = tk.X, padx = padx, pady = pady)\n sep.pack(fill = tk.X, pady = pady)\n else:\n lab.grid(row = 0, column = 0, columnspan = colspan, sticky = tk.NSEW, padx = padx, pady = pady)\n sep.grid(row = 1, column = 0, columnspan = colspan, sticky = tk.NSEW, pady = pady)\n \ndef create_separator(frame, row, col, colspan, padx = 5, pady = 5) -> ttk.Separator:\n sep = ttk.Separator(frame, orient = tk.HORIZONTAL)\n sep.grid(row = row, column = col, columnspan = colspan, sticky = tk.NSEW, padx = padx, pady = pady)\n return sep\n\ndef raise_frame(frame) -> None:\n frame.tkraise()\n \ndef clear_frame(frame) -> None:\n for widget in frame.winfo_children():\n widget.destroy()\n \ndef set_widget_image(widget: 'TkWidget', image: str, x = 1, y = 1) -> None:\n img = tk.PhotoImage(file = image)\n img = img.subsample(x, y)\n widget['image'] = img\n widget.img = img\n \ndef configure_frame(frame, rowspan = 0, rowoffset = 0, colspan = 0, coloffset = 0) -> None:\n for i in range(rowspan - rowoffset):\n frame.rowconfigure(i + rowspan, weight = 1)\n for i in range(colspan - coloffset):\n frame.columnconfigure(i + coloffset, weight = 1)\n \ndef init_theme() -> None:\n try:\n ttk.Style().theme_use('vista')\n except:\n print('Failed to change theme to vista, attempting aqua.')\n try:\n ttk.Style().theme_use('aqua')\n except:\n print('Failed to change theme to aqua, using default.')\n \ndef create_labelframe(frame, text, row, column, padx = 30, pady = 10, colspan = 1) -> ttk.LabelFrame:\n labelframe = ttk.Labelframe(frame, labelwidget = tk.Label(frame, text = text, fg = '#365ddc'), borderwidth = 15, labelanchor = tk.N, style = 'TLabelframe')\n labelframe.grid(row = row, column = column, columnspan = colspan, sticky = tk.NSEW, padx = padx, pady = pady)\n return labelframe\n \ndef init_root_options(root) -> None:\n root.option_add('*Font', FONT)\n root.option_add('*Background', 'white')\n root['bg'] = 'white'\n s = ttk.Style(root)\n s.configure('TLabelframe', background = 'white')\n \n \n ","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"563207147","text":"from ndscheduler import job\nimport RPi.GPIO as GPIO\n\n\nclass RPIOJob(job.JobBase):\n\n @classmethod\n def meta_info(cls):\n return {\n 'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),\n 'notes': 'This will toggle an RPIO input/ouput!',\n 'arguments': [{\n 'type': 'string',\n 'description': 'New state (on / off)'\n }],\n 'example_arguments': '[\"off\"]'\n }\n\n def run(self, action, * args, ** kwargs):\n GPIO.setmode(GPIO.BCM)\n switchPin = 23\n GPIO.setwarnings(False)\n GPIO.setup(switchPin, GPIO.OUT)\n print('--RPIOJob argument: %s' % (action))\n if action == \"on\":\n GPIO.output(switchPin, GPIO.HIGH)\n if action == \"off\":\n GPIO.output(switchPin, GPIO.LOW)\n return action\n\n\nif __name__ == \"__main__\":\n # You can easily test this job here\n job = RPIOJob.create_test_instance()\n job.run(\"on\")\n","sub_path":"thePlug/jobs/rpio_job.py","file_name":"rpio_job.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"98674970","text":"class Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n #O(n^2) DP\n res = 0\n memo = [1 for i in range(len(nums))] #memo[i] indicates the length longest increasing subsequence from begining to nums[i]\n for i in range(len(nums)):\n for j in range(i):\n if nums[j] < nums[i]:\n memo[i] = max(memo[i], memo[j] + 1)\n \n res = max(res, memo[i])\n \n return res","sub_path":"codes/Nancy/LC300.py","file_name":"LC300.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"275553077","text":"# -*- coding: utf-8 -*-\nimport socket\nimport struct\nimport sys\nimport pickle\nimport json\nimport ast\nimport time\nimport os\n\nfrom pip._vendor.distlib.compat import raw_input\n\nlat_to = -7.265441\nlong_to = 112.797661\n\n\nport = 10003\ntime_limit = 10\nhop_limit = 1\npesanDikirim = []\n\ndef sendPosition():\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.settimeout(20)\n client.connect(('192.168.100.37', 35))\n data = {\n 'port' : port,\n 'lat' : lat_to,\n 'long' : long_to\n }\n client.send(pickle.dumps(data))\n print('sukses mengirim lokasi !')\n return client.close()\n\ndef multicast():\n multicast_group = '224.3.29.71'\n server_address = ('', port)\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.bind(server_address)\n group = socket.inet_aton(multicast_group)\n mreq = struct.pack('4sL', group, socket.INADDR_ANY)\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n while True:\n print('\\nwaiting to receive message')\n data, address = sock.recvfrom(1024)\n data = json.loads(data.decode('utf-8'))\n print('received %s bytes from %s' % (len(data), address))\n pesan = data[0]\n print('message : ' + pesan)\n rute = data[1]\n hop = data[2] + 1\n getSecond = time.time() - data[3]\n timestamp = time.time()\n duration = data[4] + getSecond\n sock.sendto(b'ack', address)\n if(data[2] > hop_limit):\n print('jumlah hop : ' + str(hop))\n print('hop telah melebihi limit')\n exit()\n if not data[1]:\n sock.sendto(b'ack', address)\n print ('ini adalah rute DTN terakhir')\n print ('durasi pengiriman pesan : ' + str(data[4]))\n print ('jumlah hop : ' + str(data[2]))\n exit()\n sendMsg(pesan,rute,hop,timestamp,duration)\n\ndef sendMsg(pesan,rute,hop,timestamp,duration):\n p = rute[0][0]\n del rute[0]\n pesanDikirim.insert(0,pesan)\n pesanDikirim.insert(1,rute)\n pesanDikirim.insert(2,hop)\n pesanDikirim.insert(3,timestamp)\n pesanDikirim.insert(4,duration)\n settime = time.time()\n timecek = 0\n print('mengirimkan pesan ke port ' + str(p))\n hasil = send(pesanDikirim, p)\n while (timecek < time_limit):\n if hasil == 0:\n hasil = send(pesanDikirim, p)\n else:\n break\n timecek = time.time() - settime\n if hasil == 0:\n print('Umur pesan melebihi batas waktu, pesan akan dihapus\\n')\n else:\n exit()\n\ndef send(message,port):\n multicast_group = ('224.3.29.71', port)\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.settimeout(0.2)\n ttl = struct.pack('b', 1)\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)\n sock.sendto(json.dumps(message).encode('utf8'), multicast_group)\n while True:\n try:\n sock.recvfrom(16)\n except:\n sock.close()\n return 0\n else:\n print ('pesan berhasil dikirim')\n sock.close()\n return 1\n\nif __name__ == '__main__':\n print(\"receiver port \" + str(port) + \": \")\n print(\"==============\")\n while 1:\n print(\"1. send lokasi\")\n print(\"2. menerima pesan dan mengirimkan ke node selanjutnya\")\n print(\"3. keluar\")\n inputan = raw_input('Pilihan > ')\n if (inputan == '1'):\n sendPosition()\n elif (inputan == '2'):\n multicast()\n elif (inputan == '3'):\n exit()\n else:\n print('inputan salah')","sub_path":"receiver3/receive.py","file_name":"receive.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"138151434","text":"\"\"\"\n**Challenge 48**\n\n*Bleichenbacher's PKCS 1.5 Padding Oracle (Complete Case)*\n\nThis is a continuation of challenge #47; it implements the complete BB'98 attack.\n\nSet yourself up the way you did in #47, but this time generate a 768 bit modulus.\n\nTo make the attack work with a realistic RSA keypair, you need to reproduce step\n2b from the paper, and your implementation of Step 3 needs to handle multiple\nranges.\n\nThe full Bleichenbacher attack works basically like this:\n * Starting from the smallest 's' that could possibly produce a plaintext\n bigger than 2B, iteratively search for an 's' that produces a conformant\n plaintext.\n * For our known 's1' and 'n', solve m1=m0s1-rn (again: just a definition of\n modular multiplication) for 'r', the number of times we've wrapped the\n modulus.\n * 'm0' and 'm1' are unknowns, but we know both are conformant PKCS#1v1.5\n plaintexts, and so are between [2B,3B].\n * We substitute the known bounds for both, leaving only 'r' free, and solve\n for a range of possible 'r' values. This range should be small!\n * Solve m1=m0s1-rn again but this time for 'm0', plugging in each value of\n 'r' we generated in the last step. This gives us new intervals to work\n with. Rule out any interval that is outside 2B,3B.\n * Repeat the process for successively higher values of 's'. Eventually, this\n process will get us down to just one interval, whereupon we're back to\n exercise #47.\n\nWhat happens when we get down to one interval is, we stop blindly incrementing\n's'; instead, we start rapidly growing 'r' and backing it out to 's' values by\nsolving m1=m0s1-rn for 's' instead of 'r' or 'm0'. So much algebra! Make your\nteenage son do it for you! *Note: does not work well in practice*\n\"\"\"\nimport os, sys, unittest\nsys.path.insert(0, '../set5')\nsys.path.insert(0, '../set6')\nimport c39, c47\nfrom Crypto.Util import number\n\n# So I did this for c47 already. Let's just run it. It takes longer.\n\nclass TestChallenge48(unittest.TestCase):\n def setUp(self):\n pub, priv = c39.rsa_keygen(bit_len=768)\n self.pub = pub\n self.priv = priv\n c47.G_PRIV = priv\n #c47.DEBUG = true\n self.msg = b'kick it, CC'\n\n def test_rsa(self):\n ctxt = c39.rsa_encrypt(self.msg, self.pub)\n ptxt = c39.rsa_decrypt(ctxt, self.priv)\n self.assertEqual(self.msg, ptxt)\n\n def test_pad(self):\n e, n = self.pub\n padd = c47.pkcs15_pad(self.msg, n)\n ctxt = c39.rsa_encrypt(padd, self.pub)\n self.assertTrue(c47.padding_oracle(number.bytes_to_long(ctxt)))\n\n def test_attack(self):\n e, n = self.pub\n padd = c47.pkcs15_pad(self.msg, n)\n ctxt = c39.rsa_encrypt(padd, self.pub)\n decoded = c47.attack_rsa(number.bytes_to_long(ctxt), self.pub)\n self.assertEqual(decoded, padd)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"cryptopals-py/set6/c48.py","file_name":"c48.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"565479240","text":"from Tkinter import Tk\nfrom tkFileDialog import askopenfilename\nimport tkMessageBox\nfrom Crypto.Cipher import AES\n\n\ndef pop_window(title, message):\n tkMessageBox.showinfo(title, message)\n\n\ndef select_file():\n Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing\n filename = askopenfilename() # show an \"Open\" dialog box and return the path to the selected file\n return filename\n\n\ndef decrypt(ciphertext, key):\n iv = ciphertext[:AES.block_size]\n cipher = AES.new(key, AES.MODE_CBC, iv)\n plaintext = cipher.decrypt(ciphertext[AES.block_size:])\n return plaintext.rstrip(b\"\\0\")\n\n\ndef decrypt_file(file_name, key):\n with open(file_name, 'rb') as fo:\n cipher_text = fo.read()\n dec = decrypt(cipher_text, key)\n with open(file_name, 'wb') as fo:\n fo.write(dec)\n\n\n\n# SELECT ANY FILE\npop_window(\"SELECT key\", \"Select a KEY.PEM from your computer to encrypt\")\nselected_key = select_file()\n\n# ASK THE USER TO INPUT THE FILE TO ENCRYPT\nkey = open(selected_key, 'rb').readline()\n\n\n# OPEN FILE TO DECRYPT\npop_window(\"SELECT FILE\", \"Select a Message.txt from your computer to decrypt\")\ncmsg = select_file()\n\n# DECRYPT THE FILE\ndecrypt_file(cmsg, key)\n\n# RETURN TO MAIN MENU\nexecfile(\"AESencr.py\")\n\n\n\n","sub_path":"Cryptology/Vault/AESdecr.py","file_name":"AESdecr.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"607479479","text":"from kafka import KafkaConsumer,KafkaProducer\nfrom json import loads,dumps\nfrom elasticsearch import Elasticsearch\n\nelasticSearch= Elasticsearch([{'host':'localhost','port':9200}])\n\nproducer = KafkaProducer(bootstrap_servers=['localhost:9092'],\n value_serializer=lambda x: \n dumps(x).encode('utf-8'),\n\t\t\t\t\t\t api_version=(0, 10, 1))\n\nconsumer = KafkaConsumer(\n 'persistence', # NAME OF CHANAL WHICH WE GET DATA FROM.\n bootstrap_servers=['localhost:9092'],\n auto_offset_reset='earliest',\n enable_auto_commit=True,\n group_id='my-group',\n value_deserializer=lambda x: loads(x.decode('utf-8')),\n auto_commit_interval_ms=100,\n\t api_version=(0, 10, 1))\n\n\nfor message in consumer: \n tweet = message.value\n \n # send data to elasticSearch:\n elasticSearch.index(index=\"tweeter\",doc_type=\"tweeter\",body=tweet)\n \n # Send data to next topic if its nessecary:\n # roducer.send('persistence', value=tweet)\n \n","sub_path":"Part2_ZahraEbrahimian/Insert_to_Kafka.py","file_name":"Insert_to_Kafka.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"163737777","text":"#import statements\n\n#function definitions\ndef get_initials(fullname):\n count = 0\n initials = []\n name = fullname.upper()\n initials.append(fullname[0])\n for char in name:\n count += 1\n if char == \" \":\n initials.append(fullname[count])\n return \"\".join(initials).upper()\n\n#main function definition\ndef main():\n name = input(str(\"Please enter your full name.\"))\n #name = raw_input(str(\"Please enter your full name.\"))\n get_initials(name)\n\n#run main if file is being executed\nif __name__ == \"__main__\":\n main()\n\n ","sub_path":"codecamp/initials/initials.py","file_name":"initials.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"68234550","text":"from sys import stdin\ndef main():\n n=[int(i) for i in stdin.readline().strip().split(\"→\")]\n for elm in n:\n if n.count(elm)>1:\n n.remove(elm)\n n= \"→\".join([str(j) for j in n])\n print(n)\n print(True)\n break\nmain()\n","sub_path":"laboratorios/Lab-7/E/EE.py","file_name":"EE.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"602406650","text":"#!/usr/bin/env python\n\"\"\"\nConstruct the new inventory file to add new workers.\n\nSee main() for the main routine.\n\nwrites to a file called \"openshift-ansible-hosts-upscale\"\n\nThere are also some unit tests towards the end of the file\n\"\"\"\n\nimport argparse\nimport re\nimport os\nimport yaml\n\n# Py2/Py3 compatibility is provided by 'six'\nfrom six.moves.configparser import ConfigParser\n\n\n# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n\nclass UpscalingMasterNodeException(Exception):\n \"\"\" An exception raised if we find we're trying to add\n a Master (because this isn't supported at present)\"\"\"\n pass\n\n\nclass AnsibleInventory(ConfigParser):\n \"\"\"\n A representation of an Ansible INI file. This is based on the ConfigParser,\n which can read normal windows INI files, but Ansible INI files are slightly\n different. This class handles these differences.\n\n http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html\n https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory\n \"\"\"\n def __init__(self, filename=None):\n \"\"\" Constructor for a new Inventory object. \"\"\"\n # ConfigParser is an old-style class; can't use Super()\n ConfigParser.__init__(self, allow_no_value=True)\n if filename:\n self.read(filename)\n\n def get_groups_dict(self):\n \"\"\" Retrieve a dict of the groups from the inventory.\n The keys are the section names. the values are the node names,\n without any further parameters, or keys without values in the case of\n [OSE3:vars]\n\n Ansible INI files separate node from parameters with a space,\n which is not a standard INI file thing. Here, we identify a space\n in a \"node name\" and remove the right-hand part.\n \"\"\"\n out = {}\n for section in self.sections():\n out[section] = []\n for pair in self.items(section):\n node = pair[0] # items() returns a list of 2-tuples\n if ' ' in node:\n node = node.split(' ')[0]\n if node is not None:\n out[section].append(node)\n return out\n\n def create_ini(self):\n \"\"\" construct the contents of the INI file (as a string)\n Does part of what ConfigParser.write() does\n \"\"\"\n out = []\n for s in self.sections():\n out.append(\"[{}]\".format(s))\n for (n, v) in self.items(s):\n # This if/else is different from ConfigParser.write()\n if v:\n out.append(\"{}={}\".format(n, v))\n else:\n out.append(n)\n return '\\n'.join(out)\n\n def set_host_in_section(self, section, hostname, params):\n \"\"\" set a node in a specified section.\n Because ansible variables are space-separated name=value pairs,\n which differs from the ConfigParser, this method provides a\n convenience function that better suits Ansible inventories.\n\n Args:\n section: the name of the [section] to hold the value\n hostname: the hostname to go in this section\n params: a set of space-separated name=value pairs (a list of\n tuples)\n Returns: nothing\n \"\"\"\n if not params:\n host_and_first_key = hostname\n remaining_kvps = None\n else:\n # ConfigParser splits on '='. Fake up a left-hand-side\n # with the hostname and the first bit of the Ansible params.\n host_and_first_key = '{} {}'.format(hostname, params[0][0])\n\n # Fake up the right-hand-side with he remaining params\n remaining_kvps = params[0][1]\n for kvp in params[1:]:\n remaining_kvps = remaining_kvps + ' ' + kvp[0] + '=' + kvp[1]\n\n self.set(section, host_and_first_key, remaining_kvps)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='Test if we need to upscale')\n parser.add_argument(\n '--debug', help='show debug', action='store_true')\n args = parser.parse_args()\n return args\n\n\ndef read_hosts_from_inventory(inventory_file):\n \"\"\"\n Args:\n inventory_file: the filename containing the inventory.\n\n Returns:\n a dict representing the hosts from the inventory file.\n The following keys should be present:\n ['OSEv3:children', 'OSEv3:vars', 'dns',\n 'etcd', 'loadbalancers', 'masters', 'nodes']\n \"\"\"\n ivm = AnsibleInventory(filename=inventory_file)\n return ivm.get_groups_dict()\n\n\ndef read_hosts_from_config_yaml(vars_config_file):\n \"\"\"\n Read from the ansible vars file group_vars/all.yml\n\n Return a list of 2-tuples, each item being (hostname, ip_address)\n\n \"\"\"\n with open(vars_config_file, 'r') as vars_fh:\n vars_config = yaml.load(vars_fh)\n\n output = []\n for k, v in vars_config.items():\n if k in ['haproxy_details', 'master_details', 'worker_details']:\n for ip, host in v.items():\n output.append((host, ip))\n return output\n\n\ndef find_missing_hosts(all_inventory_hosts, new_hosts_list):\n \"\"\"\n Look for any hostnames that are only in one of the two\n config files\n\n Args:\n all_inventory_hosts: a list of hostnames, originating\n from the inventory file.\n new_hosts_list: a list of tuples of all the hosts that should be\n in the enlarged cluster. Each is (hostname, ip_address)\n \"\"\"\n\n discovered_hosts = []\n added = []\n\n for hostname, ip_addr in new_hosts_list:\n discovered_hosts.append(hostname)\n if hostname not in all_inventory_hosts:\n added.append((hostname, ip_addr))\n\n return added\n\n\ndef write_scale_up_inventory(old_inventory_file, upscaled_inventory_file,\n new_hosts, debug=False):\n \"\"\"\n Scripted implementation of the instructions at\n https://docs.openshift.com/container-platform/3.5/install_config/\n adding_hosts_to_existing_cluster.html#adding-nodes-advanced\n\n Adds a worker node as follows:\n\n - Add a new value called \"new_nodes\" to the section [OSEv3:children]\n - Add a new section [new_nodes]\n - Add the new workers to the [new_nodes] section, and append the\n Ansible parameters \"openshift_ip\" and \"openshift_node_labels\".\n - The value attached to \"openshift_node_labels\" differs, depending on the\n worker ID.\n\n Attempting to add a master node results in an Exception being thrown,\n as this is not currently supported.\n\n \"\"\"\n inventory = AnsibleInventory(filename=old_inventory_file)\n\n for host, ip_arg in new_hosts:\n # the new host is either \"master-*.\" or\n # worker-*.\" We don't have to match on the suffix\n\n host_type = ''\n host_num = -1\n if debug:\n print(\"DEBG: {}\".format(host))\n mtch = re.match('(worker|master)-(\\d+)\\.', host)\n if mtch:\n host_type = mtch.group(1)\n host_num = int(mtch.group(2))\n assert mtch, \"Hostname '{}' did not match pattern\".format(host)\n if host_type == 'master':\n raise UpscalingMasterNodeException\n # if is_master:\n # add_\"new_masters\" to [OSEv3:children]\n # add new group [new_masters]\n # add new group [new_nodes]\n # add the hostnames to both groups\n elif host_type == 'worker':\n inventory.set('OSEv3:children', 'new_nodes', None)\n if 'new_nodes' not in inventory.sections():\n inventory.add_section('new_nodes')\n\n # Only the first 3 workers (0, 1, 2) have \"router: true\"\n # N.B. The equivalent compare in the Jinja code is 1-based.\n if host_num < 3:\n node_labels = \"\\\"{'router':'true','purpose':'tenant','failure-domain.beta.kubernetes.io/zone':'nova'}\\\"\"\n else:\n node_labels = \"\\\"{'purpose':'tenant','failure-domain.beta.kubernetes.io/zone':'nova'}\\\"\"\n\n inventory.set_host_in_section(\n 'new_nodes', host,\n [('openshift_ip', ip_arg),\n ('openshift_node_labels', node_labels)])\n\n with open(upscaled_inventory_file, 'w') as out_fh:\n out_fh.write(inventory.create_ini())\n if debug:\n print(inventory.create_ini())\n\n\ndef main():\n \"\"\" - \"\"\"\n args = parse_args()\n\n vars_config_file = 'group_vars/all.yml'\n inventory_file = 'openshift-ansible-hosts'\n\n upscale_inventory_file = 'openshift-ansible-hosts-upscale'\n\n assert os.path.exists(inventory_file)\n assert os.path.exists(vars_config_file)\n\n # Read all the hosts from the config file; includes new ones.\n new_hosts_list = read_hosts_from_config_yaml(vars_config_file)\n if args.debug:\n print('DBUG: 1 %r' % new_hosts_list)\n\n # Read the list of all existing hosts\n inventory = read_hosts_from_inventory(inventory_file)\n all_inventory_hosts = inventory['nodes'] + inventory['loadbalancers']\n if args.debug:\n print('DBUG: %r' % all_inventory_hosts)\n\n # Work out which hosts need to be added\n added_hosts = find_missing_hosts(all_inventory_hosts, new_hosts_list)\n\n for host, ipaddr in added_hosts:\n print(\"Adding: %s %s\" % (host, ipaddr))\n\n # Generate the new inventory for upscaling\n if len(added_hosts) > 0:\n write_scale_up_inventory(inventory_file, upscale_inventory_file,\n added_hosts, args.debug)\n\n\n#\n#\n# Unit tests follow\n#\n#\n# To run these tests, ensure the files \"group_vars/all.yml and\n# \"openshift-ansible-hosts\" are available locally (taken from the test\n# deployment, then run ``pytest create-upscale-inventory.py``\n\n\ndef test_read_hosts_from_config_yaml():\n \"\"\" - \"\"\"\n expected = [\n ('haproxy-0.openstacklocal', '10.2.1.8'),\n ('haproxy-1.openstacklocal', '10.2.1.6'),\n ('worker-0.openstacklocal', '10.2.1.11'),\n ('worker-1.openstacklocal', '10.2.1.9'),\n ('worker-2.openstacklocal', '10.2.1.13'),\n ('master-0.openstacklocal', '10.2.1.10'),\n ('master-2.openstacklocal', '10.2.1.12'),\n ('master-1.openstacklocal', '10.2.1.7'),\n ]\n actual = read_hosts_from_config_yaml('group_vars/all.yml')\n assert expected == actual\n\n\ndef test_read_hosts_from_inventory():\n \"\"\" read_hosts_from_inventory returns everything in the inventory\n file, each section being a dict key..\"\"\"\n should_contain = {\n 'masters': [\n 'master-0.openstacklocal',\n 'master-2.openstacklocal',\n 'master-1.openstacklocal',\n ],\n 'etcd': [\n 'master-0.openstacklocal',\n 'master-2.openstacklocal',\n 'master-1.openstacklocal',\n ],\n 'loadbalancers': [\n 'haproxy-0.openstacklocal',\n 'haproxy-1.openstacklocal',\n ],\n 'dns': [\n 'haproxy-0.openstacklocal',\n 'haproxy-1.openstacklocal',\n ],\n 'nodes': [\n 'master-0.openstacklocal',\n 'master-2.openstacklocal',\n 'master-1.openstacklocal',\n 'worker-0.openstacklocal',\n 'worker-1.openstacklocal',\n ]\n }\n\n actual = read_hosts_from_inventory('openshift-ansible-hosts')\n\n for k, v in should_contain.items():\n assert actual[k] == v\n assert sorted(actual.keys()) == ['OSEv3:children', 'OSEv3:vars', 'dns',\n 'etcd', 'loadbalancers', 'masters',\n 'nodes']\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/create-upscale-inventory.py","file_name":"create-upscale-inventory.py","file_ext":"py","file_size_in_byte":11659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"420717840","text":"def Hopfield_energy(a, b, c, d, e):\n \"\"\"Calculates the global energy for the Hopfield network\n given in Question 5.\"\"\"\n\n W_ac = 1\n W_bc = 1\n W_ce = 2\n W_cd = 2\n W_be = -3\n W_ad = -2\n W_de = 3\n\n E = -(W_ac * a * c\n + W_bc * b * c\n + W_ce * c * e\n + W_cd * c * d\n + W_be * b * e\n + W_ad * a * d\n + W_de * d * e)\n\n return E\n\n\nif __name__ == '__main__':\n pos_E_states = {}\n for a in range(2):\n for b in range(2):\n for c in range(2):\n for d in range(2):\n for e in range(2):\n pos_E_states[str(a) + str(b) + str(c) + str(d) +\n str(e)] = Hopfield_energy(a, b, c, d, e)\n\n sort_low_E_states = sorted(pos_E_states, key=pos_E_states.get)\n print(\"The lowest and second lowest energy configurations for the \"\n \"Hopfield network given in Question 5 are: {0} and {1} with \"\n \"energies {2} and {3}, respectively.\".format(\n sort_low_E_states[0], sort_low_E_states[1],\n pos_E_states[sort_low_E_states[0]],\n pos_E_states[sort_low_E_states[1]]))\n","sub_path":"Quiz/Lecture11_Q5.py","file_name":"Lecture11_Q5.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"221197471","text":"import ua_mapper\nfrom ua_mapper.mapper import UAMapper\n\nfrom django.http import Http404, HttpResponse\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.template import loader, RequestContext\n\n\n\n\nfrom templateswitcher.views import flatpageview\n\n#from mobile.sniffer.chain import ChainedSniffer\n\n#==============================================================================\nclass TemplateDirSwitcher(object):\n \"\"\"\n Template Switching Middleware. Switches template dirs by using preset conditions\n and device families according to the devices capabilities. Returns the device\n object in the request object and resets the TEMPLATE_DIRS attr in the project \n settings.\n \"\"\"\n \n #--------------------------------------------------------------------------\n def process_request(self, request):\n if request.path.startswith(\"/admin\"):\n return None\n # Use hash as the key since UA's can be quite llong, dont want to hit memcache 250 byte limit\n device_cache_key = hash(request.META['HTTP_USER_AGENT'])\n template_set = cache.get(device_cache_key)\n if template_set == \"unsupported\":\n return HttpResponse(loader.get_template('pages/418_service_error.html').render(RequestContext(request)))\n \n full_path = request.get_full_path()\n media_request = (full_path.startswith(settings.MEDIA_URL) or\n full_path.startswith(settings.ADMIN_MEDIA_PREFIX) or full_path.startswith('/favicon'))\n \n if not template_set:\n \n template_set = ua_mapper.get_template_set(request.META['HTTP_USER_AGENT'])\n \n if not template_set:\n \n mapper = UAMapper()\n user_agent, device, template_set = mapper.map_by_request(request) \n \n device_cache_timeout = getattr(settings, 'DEVICE_CACHE_TIMEOUT', 72000)\n cache.set(device_cache_key, template_set, device_cache_timeout) \n \n if not media_request and template_set:\n # switch the template dir for the given device\n settings.TEMPLATE_DIRS = settings.DEVICE_TEMPLATE_DIRS[template_set]\n \n request.template_set = template_set\n\n return None\n\n#==============================================================================\nclass FlatpageFallbackMiddleware(object):\n \"\"\"\n Template Switching Flatpages. Works exactly the same as regular flatpages,\n just template-set aware.\n \"\"\"\n \n #--------------------------------------------------------------------------\n def process_response(self, request, response):\n if response.status_code != 404:\n return response # No need to check for a flatpage for non-404 responses.\n try:\n return flatpageview(request)\n # Return the original response if any errors happened. Because this\n # is a middleware, we can't assume the errors will be caught elsewhere.\n except Http404:\n return response\n except:\n if settings.DEBUG:\n raise\n return response","sub_path":"templateswitcher/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"75687702","text":"import numpy as np\n\n# N4SID algorithm implementation for identification of the space following page 52 of the overscheer book.\n\ndef blockHankel(x, nrows, ncols):\n\t\"\"\"\n\tx contains one input in each column\n\t\"\"\"\n\n\tassert(x.shape[1] >= nrows)\n\n\tm = x.shape[0]\n\tresult = np.zeros((m * nrows, ncols))\n\tfor col in range(ncols):\n\t\tfor row in range(nrows):\n\t\t\tresult[m * row : m * (row + 1), col] = x[:, col + row]\n\n\treturn result\n\ndef n4sid(x, y, order, k):\n\t\"\"\"\n\tx contains one input in each column\n\ty contains one output in each column\n\t\"\"\"\n\n\tm = x.shape[0]\n\tnx = x.shape[1]\n\tl = y.shape[0]\n\tny = y.shape[1]\n\n\t# Determinar o numero de columns para as matrizes de Hankel\n\tN = ny - 2 * order + 1\n\n\t#Create block hankel matrices from in and output\n\tX = blockHankel(x, 2*order, N)\n\tY = blockHankel(y, 2*order, N)\n\t\n\tXp = X[:, 0 : k*m]#X[:, 1 : k*m]\n\tXf = X[:, k*m : 2*k*m]#X[:, k*m+1 : 2*k*m]\n\tYp = Y[:, 0:k*l]#Y[:, 1:k*l]\n\tYf = Y[:, k*l:2*k*l]#Y[:, k*l+1:2*k*l]\n\tkm = Xp.shape[0]#size(Xp,1);\n\tkl = Yp.shape[0]#size(Yp,1);\n\tWp = np.concatenate((Xp, Xp), axis = 1)#[Xp;Xp];\n\t# *********** ALGORITMO ***********\n\t#Passo 1\n\t#decomposicao LQ\n\tQ, L = np.linalg.qr(np.concatenate((Xf, Xp, Yp, Yf), axis = 1).T)#np.linalg.qr([Xf;Xp;Yp;Yf].T);\n\tQ = Q.T\n\tL = L.T\n\n\tL11 = L[0:km, 0:km]#L[1:km,1:km]\n\tL21 = L[km:2*km, 0:km]#L[km+1:2*km,1:km]\n\tL22 = L[km:2*km, km+1:2*km]#L[km+1:2*km,km+1:2*km]\n\tL31 = L[2*km:2*km+kl, 0:km]#L[2*km+1:2*km+kl,1:km]\n\tL32 = L[2*km:2*km+kl, km:2*km]#L[2*km+1:2*km+kl,km+1:2*km]\n\tL33 = L[2*km:2*km+kl, 2*km:2*km+kl]#L[2*km+1:2*km+kl,2*km+1:2*km+kl]\n\tL41 = L[2*km+kl:2*km+2*kl, 0:km]#L[2*km+kl+1:2*km+2*kl,1:km]\n\tL42 = L[2*km+kl:2*km+2*kl, km:2*km]#L[2*km+kl+1:2*km+2*kl,km+1:2*km]\n\tL43 = L[2*km+kl:2*km+2*kl, 2*km:2*km+kl]#L[2*km+kl+1:2*km+2*kl,2*km+1:2*km+kl]\n\tL44 = L[2*km+kl:2*km+2*kl, 2*km+kl:2*km+2*kl]#L[2*km+kl+1:2*km+2*kl,2*km+kl+1:2*km+2*kl]\n\tR11 = L11\n\n\tprint(L32)\n\tprint(L33)\n\tR21 = np.concatenate((L21, L32), axis = 1)#[L21;L31];\n\tR22 = np.concatenate((np.concatenate((L22, np.zeros(km,kl)), axis = 0), np.concatenate((L32, L33), axis = 0)), axis = 1)#[L22 zeros(km,kl); L32 L33];\n\tR31 = L41\n\tR32 = np.concatenate((L42, L43), axis = 0)#[L42 L43]\n\n\txi = R32.dot(np.linalg.pinv(R22).dot(Wp))\n\t#Passo 2\n\tXX, SS, VV = np.linalg.svd(xi)\n\tss = np.diag(SS)\n\tn = np.argwhere(np.cumsum(ss) > 0.85 * np.sum(ss))[0]\n\t# n=4;\n\t# hold off\n\t# figure(1)\n\t# title('Valores singulares');\n\t# xlabel('Ordem');\n\t# plot(ss)\n\t# pause;\n\t# figure(2)\n\t# title('Valores singulares');\n\t# xlabel('Ordem');\n\t# bar(ss)\n\t# n = input(' Ordem do sistema ? ');\n\t# while isempty(n)\n\t# n = input(' Ordem do sistema ? ');\n\t# \n\tX1 = XX[:, 1:order]\n\tS1 = SS[1:order, 1:order]\n\tV1 = VV[1:order, :]\n\t#Matrizes A e C\n\tOk = X1.dot(np.linalg.sqrtm(S1))\n\tC = Ok[1:l, 1:order]\n\tA = np.linalg.pinv(Ok[1:l*(k-1), 1:n]).dot(Ok[l+1:l*k, 1:order])\n\n\t#Passo 3\n\t#Matrizes B e D\n\tTOEP = R31 - R32.dot(np.linalg.pinv(R22)).dot(R21).dot(np.linalg.pinv(R11))\n\tG = TOEP[:,1:m]\n\tG0 = G[1:l,:]\n\tG1 = G[l+1:2*l,:]\n\tG2 = G[2*l+1:3*l,:]\n\tG3 = G[3*l+1:4*l,:]\n\tG4 = G[4*l+1:5*l,:]\n\tD = G0\n\tHk = np.concatenate((np.concatenate((G1, G2), axis = 0), np.concatenate((G2, G3), axis = 0), np.concatenate((G3, G4), axis = 0)), axis = 1)#[G1 G2;G2 G3;G3 G4];\n\tOk1 = Ok[1:3*l,:]\n\tCk = np.linalg.pinv(Ok1).dot(Hk)\n\tB = Ck[:,1:m]\n\n\treturn A, B, C, D\n","sub_path":"utils/n4sid.py","file_name":"n4sid.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"390506010","text":"###############################################################################\n# Module: mssql_sql_builder\n# Purpose: Builds generic sql statements for mssql db\n#\n# Notes: This module focuses on logic for applying CDCs, often involving\n# execution of individual SQL statements\n#\n###############################################################################\n\nimport logging\nimport data_pipeline.constants.const as const\n\nfrom abc import ABCMeta, abstractmethod\nfrom .sql_builder import SqlBuilder\n\n\nclass MssqlSqlBuilder(SqlBuilder):\n def __init__(self, argv):\n super(MssqlSqlBuilder, self).__init__(argv)\n self._logger = logging.getLogger(__name__)\n\n def build_keycolumnlist_sql(self, schemas, tables):\n schemas_sql = const.COMMASPACE.join([\"'{}'\".format(s) for s in schemas])\n tables_sql = const.COMMASPACE.join([\"'{}'\".format(s) for s in tables])\n sql = \"\"\"\n SELECT t.table_name, c.column_name\n FROM information_schema.key_column_usage AS c\n LEFT JOIN information_schema.table_constraints AS t\n ON t.constraint_name = c.constraint_name\n WHERE t.constraint_type = 'PRIMARY KEY'\n AND t.table_schema in ({schemas})\n AND t.table_name in ({tables})\"\"\".format(\n schemas=schemas_sql,\n tables=tables_sql,\n )\n return sql\n","sub_path":"data_pipeline/sql/builder/mssql_sql_builder.py","file_name":"mssql_sql_builder.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"187776132","text":"\"\"\"\n Tutorial arcade\n\n - Class(arcade.window)\n - on_draw\n\n rect is a square\n self.step = rect_width (and rect_height)\n\"\"\"\n\nimport arcade\nimport enum\nimport random\n\nTITLE = \"Snake AI Game\"\nSCREEN_WIDTH = 640\nSCREEN_HEIGHT = 480\nRECT_SIDE = 80\n\n\nclass Snake():\n\n # start_x, start_y: initial starting positions\n def __init__(self, start_x, start_y):\n # Rectangle variables\n self.rect_x = start_x\n self.rect_y = start_y\n self.rect_width = RECT_SIDE\n self.rect_height = RECT_SIDE\n\n # Moving\n self.LEFT = 0\n self.RIGHT = 1\n self.DOWN = 2\n self.UP = 3\n self.direction = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n\n # Step\n self.step = RECT_SIDE\n\n def move_left(self):\n self.rect_x -= self.step\n\n def move_right(self):\n self.rect_x += self.step\n\n def move_up(self):\n self.rect_y += self.step\n\n def move_down(self):\n self.rect_y -= self.step\n\n def draw(self):\n arcade.draw_rectangle_filled(self.rect_x, self.rect_y, \n self.rect_width, self.rect_height, arcade.color.BLACK)\n\n\nclass MyGame(arcade.Window):\n def __init__(self, width, height, title):\n super().__init__(width, height, title)\n arcade.set_background_color(arcade.color.WHEAT)\n \n # Window variables\n self.title = title\n self.width = width\n self.height = height\n self.step = RECT_SIDE\n self.xvalues = [x for x in range(RECT_SIDE // 2, SCREEN_WIDTH, self.step)]\n self.yvalues = [y for y in range(RECT_SIDE // 2, SCREEN_HEIGHT, self.step)]\n\n # Snake\n self.snake = Snake(self.xvalues[len(self.xvalues) // 2 - 1], \n self.yvalues[len(self.yvalues) // 2 - 1])\n\n # Circle variables\n self.circle_x, self.circle_y = self.get_random_position()\n self.radius = 20\n\n # Score\n self.score = 0\n self.text_x = 480\n self.text_y = 360\n\n # Generate random position\n def get_random_position(self):\n randx = self.xvalues[random.randint(0, len(self.xvalues) - 1)]\n randy = self.yvalues[random.randint(0, len(self.yvalues) - 1)]\n return randx, randy\n\n # Arcade draw function\n def on_draw(self):\n arcade.start_render()\n arcade.draw_text(\"Score:\" + str(self.score), self.text_x, self.text_y, arcade.color.BLACK, 20)\n arcade.draw_circle_filled(self.circle_x, self.circle_y, self.radius, arcade.color.RED)\n self.snake.draw()\n\n # Check if snake has eaten a circle\n def has_eaten_circle(self):\n return self.snake.rect_x == self.circle_x and self.snake.rect_y == self.circle_y\n\n # Arcade function update\n def update(self, delta_time):\n if self.has_eaten_circle():\n self.score += 1\n self.circle_x, self.circle_y = self.get_random_position()\n\n # Arcade key event handler\n def on_key_press(self, key, modifiers):\n if key == arcade.key.UP and self.snake.rect_y < self.height - RECT_SIDE:\n self.snake.move_up()\n\n elif key == arcade.key.DOWN and self.snake.rect_y > RECT_SIDE:\n self.snake.move_down()\n\n elif key == arcade.key.LEFT and self.snake.rect_x > RECT_SIDE:\n self.snake.move_left()\n\n elif key == arcade.key.RIGHT and self.snake.rect_x < self.width - RECT_SIDE // 2:\n self.snake.move_right()\n\n\ndef main():\n game = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, \"Snake AI Game\")\n arcade.run()\n print(\"Release:\", arcade.RELEASE)\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"square-circle.py","file_name":"square-circle.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"445409005","text":"from bottle import get, post, request, response, abort, view\nimport MySQLdb\nimport json\n\n\n# obtain db cursors for each dataset\nDATASETS = ('www2013','www2013_2_trending_24h_20_21_nov','www2013_3_stream_9h_23_nov','primarie2012')\ndef get_cursor(dataset):\n if dataset not in DATASETS:\n abort(404, 'No such dataset: '+dataset)\n return MySQLdb.connect(host='opendata', user='www2013', passwd='www2013', db=dataset).cursor()\n\n@get('//network.json')\ndef get_network_json(dataset):\n c = get_cursor(dataset)\n \n network = {'nodes': [], 'links': []}\n id_map = {}\n \n # nodes\n c.execute('''SELECT id, keyword, `group`, tweets FROM tweetset ORDER BY `group` ASC''')\n for i, tweetset in enumerate(c.fetchall()):\n id, keyword, group, tweets = tweetset\n \n # translation map to sequential IDs\n id_map[id] = i\n \n network['nodes'].append({\n 'keyword': keyword,\n 'group': group,\n 'tweets': tweets\n })\n \n # links\n c.execute('''SELECT tweetset_a, tweetset_b, content, community, trend FROM similarity''')\n for similarity in c.fetchall():\n tweetset_a, tweetset_b, content, community, trend = similarity\n \n network['links'].append({\n 'source': id_map[tweetset_a],\n 'target': id_map[tweetset_b],\n 'content': content,\n 'community': community,\n 'trend': trend\n })\n \n return json.dumps(network)\n\n@get('//links.csv')\ndef get_links_csv(dataset):\n c = get_cursor(dataset)\n \n links = ''\n id_map = {}\n \n # nodes\n c.execute('''SELECT id, keyword FROM tweetset''')\n for i, tweetset in enumerate(c.fetchall()):\n id, keyword = tweetset\n \n # translation map to term strings\n id_map[id] = keyword\n \n c.execute('''SELECT tweetset_a, tweetset_b, content, community, trend FROM similarity ORDER BY tweetset_a ASC, tweetset_b ASC''')\n for similarity in c.fetchall():\n tweetset_a, tweetset_b, content, community, trend = similarity\n \n links += id_map[tweetset_a] + ';' + id_map[tweetset_b] + ';' + json.dumps(content) + ';' + json.dumps(community) + ';' + json.dumps(trend) + '\\n' # json.dumps is used to treat Nones as JSON nulls\n \n response.content_type = 'text/csv'\n \n return links\n ","sub_path":"server/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"152035692","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 21 15:14:18 2021\r\n\r\n@author: Priyank Rao\r\n\"\"\"\r\nimport os\r\n\r\n# My two categories\r\nX = \"CAT\"\r\nY = \"DOG\"\r\n\r\n# sampleX = 'static\\example4.jpg'\r\n# sampleY = 'static\\example1.jpg'\r\n\r\n# Two example images for the website, they are in the static directory next \r\n# where this file is and must match the filenames here\r\nsampleX = 'static\\example4.jpg'\r\nsampleY = 'static\\example1.jpg'\r\n\r\n# Where I will keep user uploads\r\nUPLOAD_FOLDER = 'static/uploads'\r\n# Allowed files\r\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}\r\n# Machine Learning Model Filename\r\nML_MODEL_FILENAME = 'saved_model.h5'\r\n\r\n#Load operation system library\r\nimport os\r\n\r\n#website libraries\r\nfrom flask import render_template\r\nfrom flask import Flask, flash, request, redirect, url_for\r\nfrom werkzeug.utils import secure_filename\r\n\r\n#Load math library\r\nimport numpy as np\r\n\r\n#Load machine learning libraries\r\nfrom tensorflow.keras.preprocessing import image\r\nfrom keras.models import load_model\r\nfrom tensorflow.python.keras.backend import set_session\r\nimport tensorflow as tf\r\n\r\n# Create the website object\r\napp = Flask(__name__)\r\n\r\ndef load_model_from_file():\r\n #Set up the machine learning session\r\n mySession = tf.compat.v1.Session()\r\n set_session(mySession)\r\n myModel = load_model(ML_MODEL_FILENAME)\r\n myGraph = tf.compat.v1.get_default_graph()\r\n return (mySession,myModel,myGraph)\r\n\r\n#Try to allow only images\r\ndef allowed_file(filename):\r\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\r\n\r\n#Define the view for the top level page\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef upload_file():\r\n #Initial webpage load\r\n if request.method == 'GET' :\r\n return render_template('index.html',myX=X,myY=Y,mySampleX=sampleX,mySampleY=sampleY)\r\n else: # if request.method == 'POST':\r\n # check if the post request has the file part\r\n if 'file' not in request.files:\r\n flash('No file part')\r\n return redirect(request.url)\r\n file = request.files['file']\r\n # if user does not select file, browser may also\r\n # submit an empty part without filename\r\n if file.filename == '':\r\n flash('No selected file')\r\n return redirect(request.url)\r\n # If it doesn't look like an image file\r\n if not allowed_file(file.filename):\r\n flash('I only accept files of type'+str(ALLOWED_EXTENSIONS))\r\n return redirect(request.url)\r\n #When the user uploads a file with good parameters\r\n if file and allowed_file(file.filename):\r\n filename = secure_filename(file.filename)\r\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\r\n return redirect(url_for('uploaded_file', filename=filename))\r\n\r\nfilename = 'Cat_2.jpg' \r\n@app.route('/uploads/')\r\ndef uploaded_file(filename):\r\n test_image = image.load_img(UPLOAD_FOLDER+\"/\"+filename,target_size=(150,150))\r\n test_image = image.img_to_array(test_image)\r\n test_image = np.expand_dims(test_image, axis=0)\r\n\r\n mySession = app.config['SESSION']\r\n myModel = app.config['MODEL']\r\n myGraph = app.config['GRAPH']\r\n result = myModel.predict(test_image)\r\n image_src = \"/\"+UPLOAD_FOLDER +\"/\"+filename\r\n if result[0] < 0.5 :\r\n answer = \"
guess:\"+X+\" \"+str(result[0])+\"
\" \r\n else:\r\n answer = \"
guess:\"+Y+\" \"+str(result[0])+\"
\" \r\n results.append(answer)\r\n return render_template('index.html',myX=X,myY=Y,mySampleX=sampleX,mySampleY=sampleY,len=len(results),results=results)\r\n\r\n\r\n\r\ndef main():\r\n (mySession,myModel,myGraph) = load_model_from_file()\r\n \r\n app.config['SECRET_KEY'] = 'super secret key'\r\n \r\n app.config['SESSION'] = mySession\r\n app.config['MODEL'] = myModel\r\n app.config['GRAPH'] = myGraph\r\n\r\n app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\r\n app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 #16MB upload limit\r\n app.run()\r\n\r\n# Create a running list of results\r\nresults = []\r\n\r\n#Launch everything\r\nmain()\r\n\r\n","sub_path":"website.py","file_name":"website.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"557031955","text":"# NetPredict is now FutureGenie!\n# yay!\n# Made by Neal C (nealpointerexception)\n# I do not claim rights to any of the used libraries\nimport wx\n\n\n\n # create main class for frame/ window\nclass MainClass(wx.Frame):\n\n def __init__(self, parent, id):\n # define frame -- self, parent, id, name, frame size\n wx.Frame.__init__(self, parent, id, 'Future Genie 2.0', size=(400, 650))\n mainPanel = wx.Panel(self)\n # parent , label, position, size\n randomButton = wx.Button(mainPanel, label='exit', pos= (130, 200), size = (100, 60) )\n self.indexBox = wx.TextCtrl(mainPanel)\n # you must bind an event to the button bind clicks to actions\n # # event function name, button\n self.Bind(wx.EVT_BUTTON, self.CloseProgram, randomButton)\n self.Bind(wx.EVT_TEXT_ENTER, self.printOut, indexBox)\n\n\n def CloseProgram(self, event):\n print(self.indexBox.GetValue())\n def printOut(self, event):\n print(event.Getvalue())\n\nif __name__ == '__main__':\n #application object that runs the program\n app = wx.App(False)\n # displays the object\n frame = MainClass(parent=None, id=-1)\n frame.Show()\n #run app\n app.MainLoop()\n","sub_path":"FutureGenie(2_0)(DEPRECATED).py","file_name":"FutureGenie(2_0)(DEPRECATED).py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"177130580","text":"import math\n\n\ndef calc_circle(r):\n area = pow(r, 2) * math.pi\n circumference = 2 * r * math.pi\n print(\"{} {}\".format(area, circumference))\n\n\nif __name__ == \"__main__\":\n r = float(input().rstrip())\n calc_circle(r)\n","sub_path":"AOJ/Lesson-ITP1/itp1_4_b.py","file_name":"itp1_4_b.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"448871912","text":"\"\"\"You're given an array of non-negative integers. Your task is to rearrange its elements in such a way that any 2 adjacent elements sum up to a perfect square. If there are several answers, output the lexicographically smallest one. If there are no possible answers, return an empty array.\n\nExample\n\nFor a = [12, 5, 4, 13], the output should be [5, 4, 12, 13].\n\nAll adjacent elements sum to perfect squares:\n\n5 + 4 = 9 = 3^2\n4 + 12 = 16 = 4^2\n12 + 13 = 25 = 5^2\nNote: [13, 12, 4, 5] is another possible arrangement, but [5, 4, 12, 13] is smaller lexicographically.\n\nInput / Output\n\n[execution time limit] 4 seconds (py)\n\n[input] array.integer a\n\nAn array of integers that we'd like to arrange in such a way that every pair of adjacent elements add up to a square number.\n\nGuaranteed constraints:\n2 ≤ a.length ≤ 500\n0 ≤ a[i] ≤ 10^9\n\n[output] array.integer\n\nAn array of integers containing the elements of a arranged such that each adjacent pair adds to a perfect square, in the lexicographically smallest way (or [] if it's not possible).\"\"\"\n\n\n### DFS Search\n\ndef adjacentSquare(a):\n ## Keep a list of numbers without duplicates\n # Also keep the list sorted to quickly get lexicographically smallest one\n cand = sorted(set(a))\n \n ## Using a dictionary to keep track of duplicates\n count = {i: 0 for i in cand}\n for i in a:\n count[i] += 1\n \n ## Preprocessing\n friend = {i: [j for j in cand if pow(i + j, 0.5) % 1 == 0] for i in cand}\n \n ## DFS Search\n def rec(cur, con):\n if len(cur) == len(a):\n return cur\n else:\n for i in (friend[cur[-1]] if cur else cand):\n if con[i] > 0:\n con[i] -= 1\n output = rec(cur + [i],con)\n if output:\n return output\n con[i] += 1\n return []\n \n return rec([],count)\n","sub_path":"Challenges/Graphs-Trees/adjacentSquare.py","file_name":"adjacentSquare.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"51048967","text":"\"\"\"\nmake and save histograms showing SS_QSS distribution from HALO CAS measurements\n\"\"\"\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.colors import LinearSegmentedColormap, LogNorm\nfrom netCDF4 import Dataset\nimport numpy as np\nimport os\nimport sys\n\nfrom revmywrf import DATA_DIR, FIG_DIR\nfrom revmywrf.ss_qss_calculations import get_lwc, get_ss, linregress\n\n#for plotting\nversionstr = 'v2_'\nmatplotlib.rcParams.update({'font.size': 23})\nmatplotlib.rcParams.update({'font.family': 'serif'})\ncolors = [(1, 1, 1), (0.3, 0.3, 0.3)]\ncmap = LinearSegmentedColormap.from_list('grey', colors, N=250)\ncolors_arr = cm.get_cmap('magma', 10).colors\nmagma_pink = colors_arr[4]\n\nlwc_filter_val = 1.e-4\nw_cutoff = 2\n\ncase_label_dict = {'Polluted':'C_BG/', 'Unpolluted':'C_PI/'}\n\nss_min = -5\nss_max = 20\nz_min = -100\nz_max = 6500\n\ncutoff_bins = True\nincl_rain = True\nincl_vent = True\nfull_ss = True\n\ndef main():\n \n for case_label in case_label_dict.keys():\n make_and_save_ss_qss_vs_z(case_label, case_label_dict[case_label], \\\n cutoff_bins, full_ss, incl_rain, \\\n incl_vent, versionstr)\n\ndef make_and_save_ss_qss_vs_z(case_label, case_dir_name, \\\n cutoff_bins, full_ss, \\\n incl_rain, incl_vent, versionstr):\n\n #get met file variables \n met_file = Dataset(DATA_DIR + case_dir_name + \\\n 'wrfout_d01_met_vars', 'r')\n met_vars = met_file.variables\n\n #get dsd sum file variables\n dsdsum_file = Dataset(DATA_DIR + case_dir_name + \\\n 'wrfout_d01_all_dsdsum_vars_v2', 'r')\n dsdsum_vars = dsdsum_file.variables\n\n #get relevant physical qtys\n lwc = get_lwc(met_vars, dsdsum_vars, cutoff_bins, incl_rain, incl_vent)\n temp = met_vars['temp'][...]\n w = met_vars['w'][...]\n z = met_vars['z'][...]\n ss_qss = get_ss(met_vars, dsdsum_vars, cutoff_bins, \\\n full_ss, incl_rain, incl_vent)\n\n #close files for memory\n met_file.close()\n dsdsum_file.close()\n\n #before filtering, get z bins\n z_bins = get_z_bins(z)\n print(z_bins)\n\n #apply filtering criteria\n filter_inds = np.logical_and.reduce((\n (lwc > lwc_filter_val), \\\n (w > w_cutoff), \\\n (temp > 273)))\n\n del lwc, temp #for memory\n\n w_filt = w[filter_inds]\n up10perc_cutoff = np.percentile(w_filt, 90)\n up10perc_inds = np.logical_and.reduce((\n (filter_inds), \\\n (w > up10perc_cutoff)))\n\n up10perc_ss_qss = ss_qss[up10perc_inds]\n ss_qss = ss_qss[filter_inds]\n\n up10perc_z = z[up10perc_inds]\n z = z[filter_inds]\n\n #plot the supersaturations against each other with regression line\n fig, [ax1, ax2] = plt.subplots(1, 2, sharey=True)\n fig.set_size_inches(32, 12)\n\n #all points passing filtering criteria\n hist, bins = np.histogram(z, bins=z_bins, density=True)\n z_color_scalars = get_z_color_scalars(hist, z_bins)\n im1 = ax1.imshow(z_color_scalars, cmap=cmap, origin='lower', \\\n norm=LogNorm(), aspect='auto', \\\n #vmin=np.min(hist), vmax=np.max(hist), \\\n extent=[ss_min, ss_max, z_bins[0], z_bins[-1]])\n avg_ss_qss, avg_z = get_avg_ss_qss_and_z(ss_qss, z, z_bins)\n ax1.plot(avg_ss_qss, avg_z, 'o-', color=magma_pink, \\\n markeredgecolor=magma_pink, markerfacecolor=magma_pink, \\\n linewidth=4)\n #cbar1 = fig.colorbar(im1, ax=ax1)\n #cbar1.set_label(r'$\\frac{dn_{points}}{dz}$ (m$^{-1}$)')\n\n #top 10th percentile (wrt w) of points passing filtering criteria\n up10perc_hist, bins = np.histogram(up10perc_z, bins=z_bins, density=True)\n up10perc_z_color_scalars = get_z_color_scalars(up10perc_hist, z_bins)\n im2 = ax2.imshow(up10perc_z_color_scalars, cmap=cmap, origin='lower', \\\n norm=LogNorm(), aspect='auto', \\\n #vmin=np.min(hist), vmax=np.max(hist), \\\n extent=[ss_min, ss_max, z_bins[0], z_bins[-1]])\n up10perc_avg_ss_qss, up10perc_avg_z = get_avg_ss_qss_and_z(up10perc_ss_qss, \\\n up10perc_z, z_bins)\n ax2.plot(up10perc_avg_ss_qss, up10perc_avg_z, 'o-', color=magma_pink, \\\n markeredgecolor=magma_pink, markerfacecolor=magma_pink, \\\n linewidth=4)\n\n cbar = fig.colorbar(im2, ax=[ax1, ax2], orientation='vertical')\n cbar.set_label(r'$\\frac{dn_{points}}{dz}$ (m$^{-1}$)')\n\n ax1.set_xlabel(r'$SS_{QSS}$ (%)')\n ax2.set_xlabel(r'$SS_{QSS}$ (%)')\n ax1.set_ylabel(r'z (m)')\n outfile = FIG_DIR + versionstr + 'FINAL_heatmap_ss_qss_vs_z_' \\\n + case_label + '_figure.png'\n plt.savefig(outfile)\n plt.close(fig=fig) \n\ndef get_z_bins(z):\n\n n_bins = np.shape(z)[1]\n n_edges = n_bins + 1\n avg_z = np.array([np.mean(z[:, i, :, :]) for i in range(n_bins)])\n z_bins = [] \n\n for i in range(1, n_bins):\n layer_geom_mean = np.sqrt(avg_z[i-1]*avg_z[i])\n if layer_geom_mean < z_max:\n z_bins.append(layer_geom_mean)\n else:\n break\n\n z_bins.insert(0, avg_z[0]*np.sqrt(avg_z[0]/avg_z[1]))\n\n return np.array(z_bins[:-1])\n\ndef get_avg_ss_qss_and_z(ss_qss, z, z_bins):\n\n avg_ss_qss = np.zeros(np.shape(z_bins)[0] - 1)\n avg_z = np.zeros(np.shape(z_bins)[0] - 1)\n\n for i, val in enumerate(z_bins[:-1]):\n lower_bin_edge = val\n upper_bin_edge = z_bins[i+1]\n\n bin_filter = np.logical_and.reduce((\n (z > lower_bin_edge), \\\n (z < upper_bin_edge)))\n\n n_in_bin = np.sum(bin_filter)\n if n_in_bin == 0:\n avg_ss_qss[i] = np.nan\n avg_z[i] = np.nan\n else:\n ss_qss_slice = ss_qss[bin_filter]\n z_slice = z[bin_filter]\n avg_ss_qss[i] = np.nanmean(ss_qss_slice)\n avg_z[i] = np.nanmean(z_slice)\n\n return avg_ss_qss, avg_z\n\ndef get_z_color_scalars(hist, z_bins):\n \n d_z = (z_bins[1] - z_bins[0])/100.\n upper_bin_edge_ind = 1\n n_bins = np.shape(z_bins)[0]\n z = z_bins[0]\n z_color_scalars = np.zeros(np.shape(np.arange(z_bins[0], z_bins[-1], d_z)))\n\n for i, val in enumerate(z_color_scalars):\n if z >= z_bins[upper_bin_edge_ind] and upper_bin_edge_ind < n_bins:\n upper_bin_edge_ind += 1\n z_color_scalars[i] = hist[upper_bin_edge_ind-1]\n z += d_z\n\n return np.reshape(z_color_scalars, (-1, 1))\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"src/revmywrf/FINAL_heatmap_ss_qss_vs_z_figsrc.py","file_name":"FINAL_heatmap_ss_qss_vs_z_figsrc.py","file_ext":"py","file_size_in_byte":6632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"268567759","text":"#\n# For licensing see accompanying LICENSE file.\n# Copyright (C) 2020 Apple Inc. All Rights Reserved.\n#\n\nimport torch\nimport torch.nn as nn\n\neps = 1e-20\n\nclass ProbabilisticAttention(nn.Module):\n def __init__(self, uniform_query_precision=False, uniform_value_precision=False, magnitude_priors=False,\n key_adaptation=False, key_adaptation_iters=0, value_belief_propagation_iters=0):\n super(ProbabilisticAttention, self).__init__()\n self.uniform_query_precision = uniform_query_precision\n self.uniform_value_precision = uniform_value_precision\n self.magnitude_priors = magnitude_priors\n self.key_adaptation = key_adaptation\n self.key_adaptation_iters = key_adaptation_iters\n self.value_belief_propagation_iters = value_belief_propagation_iters\n\n def forward(self, q, zeta, alpha, mu, beta, pi=None, v_init=None, v_fixed=None,\n zeta_prior_precision=None, mu_prior_precision=None,\n q_pos_emb=None, zeta_pos_emb=None, v_pos_emb=None, nonzero_wts_mask=None):\n \"\"\"\n Runs an update of the probabilistic version of attention based on a Mixture of Gaussians model.\n This layer is equivalent to a standard dot product attention when:\n self.uniform_query_precision = True\n self.uniform_value_precision = True\n sef.magnitude_priors = True\n alpha = 1/sqrt(C) (Could be a scalar to save some memory)\n beta = 0 (Could be a scalar to save some memory)\n v_init = None\n v_fixed = None\n :param q: A tensor of queries with dims N, G, C, H\n :param zeta: A tensor of keys (query/key Gaussian means) with dims N, G, C, H\n :param alpha: A scalar (see special case above) or tensor of query/key Gaussian precisions with dims N, G, C, H\n :param mu: A tensor of value Gaussian means with dims N, G, Cv, H\n :param beta: A scalar (see special case above) or tensor of value Gaussian precisions with dims N, G, C, H\n :param pi: A tensor of mixture component priors with dims N, G, H, H\n :param v_init: A tensor of initial vals for the values with dims N, G, Cv, H (optional)\n :param v_fixed: A tensor of fixed vals for the values with dims N, G, (Cv+1), H (optional). The extra (last) channel is an indicator for the fixed val locations\n :param zeta_prior_precision: A tensor of precisions for the Gaussian prior over zeta with dims N, G, C, H (optional)\n :param mu_prior_precision: A tensor of precisions for the Gaussian prior over mu with dims N, G, Cv, H (optional)\n :param q_pos_emb: A tensor of query positional embeddings with dims C, H, H\n :param zeta_pos_emb: A tensor of key positional embeddings with dims C, H, H\n :param v_pos_emb: A tensor of value positional embeddings with dims Cv, H, H\n :param nonzero_wts_mask: A boolean indexing tensor for setting weight matrix values to zero (where mask value is false) with dims H, H\n :return: Updated values with dims N, G, Cv, H if no position embedding (v_pos_emb=None) else N, G, 2*Cv, H\n \"\"\"\n\n N, G, C_qk, H = q.shape\n C_v = mu.shape[-2]\n\n def update_weights():\n q_2 = torch.sum(q**2, dim=-2) #torch.sum(torch.square(q), dim=-2)\n zeta_2 = torch.sum(zeta**2, dim=-2) #torch.sum(torch.square(zeta), dim=-2)\n q_zeta = torch.einsum('bgci, bgcj->bgij', q, zeta)\n #q_m_zeta = q_2.unsqueeze(-1) + zeta_2.unsqueeze(-2) - 2 * q_zeta\n log_p_q_v = q_2.unsqueeze(-1) + zeta_2.unsqueeze(-2) - 2 * q_zeta\n if q_pos_emb is not None:\n q_pos_emb_2 = torch.sum(q_pos_emb**2, dim=0)\n q_q_pos_emb = torch.einsum('bgci, cij->bgij', q, q_pos_emb)\n #q_m_q_pos_emb = q_2.unsqueeze(-1) + q_pos_emb_2.unsqueeze(0).unsqueeze(0) - 2 * q_q_pos_emb\n #q_m_zeta += q_m_q_pos_emb\n log_p_q_v += q_2.unsqueeze(-1) + q_pos_emb_2.unsqueeze(0).unsqueeze(0) - 2 * q_q_pos_emb\n if zeta_pos_emb is not None:\n zeta_pos_emb_2 = torch.sum(zeta_pos_emb ** 2, dim=0).transpose(0, 1)\n zeta_zeta_pos_emb = torch.einsum('bgci, cij->bgij', zeta, zeta_pos_emb).transpose(2, 3)\n #zeta_m_zeta_pos_emb = zeta_2.unsqueeze(-2) + zeta_pos_emb_2.unsqueeze(0).unsqueeze(0) - 2 * zeta_zeta_pos_emb\n #q_m_zeta += zeta_m_zeta_pos_emb\n log_p_q_v += zeta_2.unsqueeze(-2) + zeta_pos_emb_2.unsqueeze(0).unsqueeze(0) - 2 * zeta_zeta_pos_emb\n if self.uniform_query_precision:\n #log_p_q = -0.5 * alpha * q_m_zeta\n log_p_q_v = -0.5 * alpha * log_p_q_v\n else:\n #log_p_q = -0.5 * alpha.unsqueeze(-2) * q_m_zeta\n log_p_q_v = -0.5 * alpha.unsqueeze(-2) * log_p_q_v\n\n #log_p_v = 0\n mu_2 = torch.sum(mu**2, dim=-2) #torch.sum(torch.square(mu), dim=-2)\n if v_init is not None:\n v_init_2 = torch.sum(v_init**2, dim=-2) #torch.sum(torch.square(v_init), dim=-2)\n v_init_mu = torch.einsum('bgci, bgcj->bgij', v_init, mu)\n #v_init_m_mu = v_init_2.unsqueeze(-1) + mu_2.unsqueeze(-2) - 2 * v_init_mu\n if self.uniform_value_precision:\n #log_p_v = -0.5 * beta * v_init_m_mu\n log_p_q_v += -0.5 * beta * (v_init_2.unsqueeze(-1) + mu_2.unsqueeze(-2) - 2 * v_init_mu)\n else:\n #log_p_v = -0.5 * beta.unsqueeze(-2) * v_init_m_mu\n log_p_q_v += -0.5 * beta.unsqueeze(-2) * (v_init_2.unsqueeze(-1) + mu_2.unsqueeze(-2) - 2 * v_init_mu)\n\n #log_pi = 0\n if pi is not None:\n #log_pi = torch.log(pi)\n log_p_q_v += torch.log(pi)\n elif self.magnitude_priors:\n if self.uniform_query_precision:\n alpha_tensor = alpha\n else:\n alpha_tensor = alpha.unsqueeze(-2)\n #log_pi += 0.5 * alpha_tensor * zeta_2.unsqueeze(-2)\n log_p_q_v += 0.5 * alpha_tensor * zeta_2.unsqueeze(-2)\n if q_pos_emb is not None:\n #log_pi = log_pi.expand(-1, -1, H, -1).clone()\n #log_pi += 0.5 * alpha_tensor * q_pos_emb_2.unsqueeze(0).unsqueeze(0)\n log_p_q_v += 0.5 * alpha_tensor * q_pos_emb_2.unsqueeze(0).unsqueeze(0)\n if zeta_pos_emb is not None:\n #log_pi += 0.5 * alpha_tensor * zeta_2.unsqueeze(-2)\n #log_pi += 0.5 * alpha_tensor * zeta_pos_emb_2.unsqueeze(0).unsqueeze(0)\n log_p_q_v += 0.5 * alpha_tensor * zeta_2.unsqueeze(-2)\n log_p_q_v += 0.5 * alpha_tensor * zeta_pos_emb_2.unsqueeze(0).unsqueeze(0)\n if self.uniform_value_precision:\n beta_tensor = beta\n else:\n beta_tensor = beta.unsqueeze(-2)\n if v_pos_emb is not None:\n mu_p_v_pos_emb = mu.unsqueeze(-2) + v_pos_emb.unsqueeze(0).unsqueeze(0)\n mu_p_v_pos_emb_2 = torch.sum(mu_p_v_pos_emb**2, dim=-3)\n #log_pi += 0.5 * beta_tensor * mu_p_v_pos_emb_2\n log_p_q_v += 0.5 * beta_tensor * mu_p_v_pos_emb_2\n else:\n #log_pi += 0.5 * beta_tensor * mu_2.unsqueeze(-2)\n log_p_q_v += 0.5 * beta_tensor * mu_2.unsqueeze(-2)\n\n #log_p_q_v = log_pi + log_p_q + log_p_v\n # log_sum_exp trick to avoid numerical underflow\n m, idx = torch.max(log_p_q_v, dim=-1, keepdim=True)\n # Debugging\n \"\"\"\n zeta_2_max, zeta_2_max_idx = torch.max(zeta_2, dim=-1, keepdim=True)\n log_pi_max, log_pi_max_idx = torch.max(log_pi, dim=-1, keepdim=True)\n \"\"\"\n\n weights = torch.exp(log_p_q_v - m)\n if nonzero_wts_mask is not None:\n weights = weights * nonzero_wts_mask.unsqueeze(0).unsqueeze(0).float()\n sum_weights = torch.sum(weights, dim=-1, keepdim=True) + eps\n weights = weights.div(sum_weights)\n return weights\n\n weights = update_weights()\n\n if self.key_adaptation:\n # Online key adaptation\n for ka_iter in range(self.key_adaptation_iters):\n zeta_update = torch.einsum('bgij,bgci->bgcj', weights, q)\n sum_weights = torch.sum(weights, dim=-2, keepdim=True)\n if zeta_prior_precision is not None:\n zeta = zeta_prior_precision * zeta + alpha * zeta_update\n zeta = zeta.div(zeta_prior_precision + alpha * sum_weights)\n else:\n zeta = zeta_update\n zeta = zeta.div(sum_weights)\n weights = update_weights()\n\n wve = torch.zeros_like(mu).cuda() if torch.cuda.is_available() else torch.zeros_like(mu)\n if v_fixed is not None:\n # Online value belief propagation\n for vbp_iter in range(self.value_belief_propagation_iters):\n if torch.sum(v_fixed[:, :, -1, :]) > 0:\n mu_update = torch.einsum('bgij,bgci->bgcj', weights, v_fixed[:, :, :C_v, :])\n sum_weights = torch.einsum('bgij,bgi->bgj', weights, v_fixed[:, :, -1, :]).unsqueeze(-2) + eps\n if mu_prior_precision is not None:\n mu = mu_prior_precision * mu + beta * mu_update\n mu = mu.div(mu_prior_precision + beta * sum_weights)\n else:\n mu = mu_update\n mu = mu.div(sum_weights)\n # Offset contributions from v_pos_emb with learnt parameters\n if v_pos_emb is not None:\n wve += torch.einsum('bgij,bgcj->bgci', weights, v_fixed[:, :, C_v:-1, :])\n # Update weights\n weights = update_weights()\n\n v_updated = torch.einsum('bgij,bgcj->bgci', weights, mu) # Should we force v_updated = v_fixed at specified locs?\n if v_pos_emb is not None:\n wve += torch.einsum('bgij,cij->bgci', weights, v_pos_emb)\n v_updated = torch.cat([v_updated, wve], dim=-1).view(N, G, C_v * 2, H)\n return v_updated\n","sub_path":"probabilisticattention.py","file_name":"probabilisticattention.py","file_ext":"py","file_size_in_byte":10376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"89245705","text":"from django.db import models\nfrom mptt.models import MPTTModel, TreeForeignKey\nfrom mptt.managers import TreeManager\nfrom djchoices import DjangoChoices, ChoiceItem\nfrom django.core.validators import RegexValidator\nfrom django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned\nfrom django.db.models import Q\nfrom .utils_data import KLADR_TYPE_SOCR_CHOICE\n\nREGION_ADJUST = {\n '77000000000': '50000000000', # Москва -> Московская область\n '78000000000': '47000000000', # С-Петербург -> Ленинградская область\n '92000000000': '91000000000', # Севастополь -> Крым\n}\n\n# Кастомные менеджеры для модели кладера\n# -----------------------------------------------------------------------------\n\n\nclass KladrActualManager(TreeManager):\n\n \"\"\"\n Выдаёт только актуальные объекты\n \"\"\"\n\n def get_queryset(self):\n return super(KladrActualManager, self).\\\n get_queryset().\\\n filter(code_relevance=0)\n\n def find_object_with_region(self, city, region=None):\n \"\"\"\n Более устойчивый поиск\n \"\"\"\n if region:\n # Нормализация региона\n region = region.replace('.', '')\n region = ' '.join((\n r for r in region.split(' ')\n if all(\n (r not in socr for socr in KLADR_TYPE_SOCR_CHOICE.keys())\n )\n ))\n\n try:\n # попробовать вернуть объект в лоб\n return Kladr.actual.get(name=city)\n except ObjectDoesNotExist:\n # если его нет, то вернуть регион если он есть,\n # если нет то ничего\n if region:\n return Kladr.actual.get(name=region)\n else:\n return None\n except MultipleObjectsReturned:\n # если объектов много, то попытаться вернуть с совпадением региона\n # если нет или их тоже много то вернуть тот где больше домов\n if region:\n try:\n return self.actual.\\\n filter(name=city, full_name__icontains=region).\\\n order_by('-houses_num')[0]\n except IndexError:\n # хз\n return self.actual.\\\n filter(name=city).\\\n order_by('-houses_num')[0]\n else:\n return self.actual.\\\n filter(name=city).\\\n order_by('-houses_num')[0]\n\n\nclass KladrSubjectManager(KladrActualManager):\n\n \"\"\"\n Актуальные субьекты\n \"\"\"\n\n def get_queryset(self):\n return super(KladrSubjectManager, self).\\\n get_queryset().\\\n filter(code_region=0,\n code_city=0,\n code_locality=0,\n code_street=0)\n\n\nclass KladrRegionManager(KladrActualManager):\n\n \"\"\"\n Актуальные региона\n \"\"\"\n\n def get_queryset(self):\n return super(KladrRegionManager, self).\\\n get_queryset().\\\n filter(~Q(code_region=0),\n code_city=0,\n code_locality=0,\n code_street=0)\n\n\nclass KladrCityManager(KladrActualManager):\n\n \"\"\"\n Актуальные города\n \"\"\"\n\n def get_queryset(self):\n return super(KladrCityManager, self).\\\n get_queryset().\\\n filter(~Q(code_city=0),\n code_locality=0,\n code_street=0)\n\n\nclass KladrLocalityManager(KladrActualManager):\n\n \"\"\"\n Актуальные населённые пункты/районы\n \"\"\"\n\n def get_queryset(self):\n return super(KladrLocalityManager, self).\\\n get_queryset().\\\n filter(~Q(code_locality=0),\n code_street=0)\n\n\nclass KladrStreetManager(KladrActualManager):\n\n \"\"\"\n Актуальные улицы\n \"\"\"\n\n def get_queryset(self):\n return super(KladrStreetManager, self).\\\n get_queryset().\\\n filter(~Q(code_street=0))\n\n\n# Модель кладера\n# -----------------------------------------------------------------------------\n\nclass Kladr(MPTTModel, models.Model):\n\n \"\"\"\n Модель КЛАДРа.\n https://www.nalog.ru/rn77/program//5961265/\n Дата обращения (Чт мар 16 12:36:52 MSK 2017)\n\n Соответствует официальной таблице КЛАДРа.\n Также, добавлен MPTT индекс, для работы с моделью,\n как с иерархической структурой.\n \"\"\"\n\n # Кастомные менеджеры\n objects = TreeManager()\n actual = KladrActualManager()\n subjects = KladrSubjectManager()\n regions = KladrRegionManager()\n citys = KladrCityManager()\n localitys = KladrLocalityManager()\n streets = KladrStreetManager()\n\n # Булевые Свойства\n @property\n def is_subject(self):\n if self.code_subject and not any((self.code_region,\n self.code_city,\n self.code_locality,\n self.code_street)):\n return True\n else:\n return False\n\n @property\n def is_region(self):\n if self.code_region and not any((self.code_city,\n self.code_locality,\n self.code_street)):\n return True\n else:\n return False\n\n @property\n def is_city(self):\n if self.code_city and not any((self.code_locality,\n self.code_street)):\n return True\n else:\n return False\n\n @property\n def is_locality(self):\n if self.code_locality and not self.code_street:\n return True\n else:\n return False\n\n @property\n def is_street(self):\n if self.code_street:\n return True\n else:\n return False\n\n # Код Кладера как строка\n code = models.CharField(\n verbose_name='Код КЛАДРа',\n unique=True,\n blank=False,\n db_index=True,\n max_length=17,\n validators=[RegexValidator(\n regex='^(\\d{13})|(\\d{17})|(\\d{19})$',\n message='Kladr Core Error',\n code='nomatch')\n ]\n )\n # Код Субьекта\n code_subject = models.PositiveSmallIntegerField(\n verbose_name=\"Код Субьекта\",\n default=0,\n # editable=False,\n )\n # Код Региона\n code_region = models.PositiveSmallIntegerField(\n verbose_name=\"Код Региона\",\n default=0,\n # editable=False,\n )\n # Код Города\n code_city = models.PositiveSmallIntegerField(\n verbose_name=\"Код Города\",\n default=0,\n # editable=False,\n )\n # Код Района\n code_locality = models.PositiveSmallIntegerField(\n verbose_name=\"Код Района\",\n default=0,\n # editable=False,\n )\n # Код улицы\n code_street = models.PositiveSmallIntegerField(\n verbose_name=\"Код улицы\",\n default=0,\n # editable=False,\n )\n # Код Актуальности\n code_relevance = models.PositiveSmallIntegerField(\n verbose_name=\"Код Актуальности\",\n default=0,\n # editable=False,\n )\n\n # Коды в виде словаря\n def get_codes(self):\n return {\n 'code_subject': self.code_subject,\n 'code_region': self.code_region,\n 'code_city': self.code_city,\n 'code_locality': self.code_locality,\n 'code_street': self.code_street,\n 'code_relevance': self.code_relevance\n }\n\n # Родительский Кладр, присваивается методом _find_parent\n parent = TreeForeignKey(\n 'self',\n null=True,\n blank=True,\n related_name='Предок',\n db_index=True\n )\n\n # Имя кладра\n name = models.CharField(\n verbose_name='Название',\n max_length=1024,\n blank=False,\n db_index=True\n )\n # Полное имя, включая имя предка\n full_name = models.CharField(\n verbose_name='Полное Название',\n max_length=1024 * 6,\n default=\"\",\n db_index=True\n )\n\n def get_full_name(self):\n return ' » '.join(\n [\"{0}, {1}\".format(x.name, x.kladr_type)\n for x in reversed(self.get_ancestors(include_self=True))]\n )\n\n # Сокращение кладра (тип объекта)\n kladr_type_socr = models.CharField(\n verbose_name='Тип объекта(сокращение)',\n max_length=256,\n blank=False,\n )\n # Десериализованное значение kladr_type_socr\n kladr_type = models.CharField(\n verbose_name='Тип объекта(полное имя)',\n max_length=256,\n blank=False,\n )\n # Почтовый индекс\n index = models.PositiveIntegerField(\n verbose_name='Почтовый индекс',\n unique=False,\n default=0,\n blank=True,\n )\n\n # Количество домов\n houses_num = models.PositiveIntegerField(\n verbose_name='Почтовый индекс',\n default=0,\n )\n\n # Статус Объекта\n class StatusType(DjangoChoices):\n _0 = ChoiceItem(0, '0 Не центр')\n _1 = ChoiceItem(1, '1 Центр района')\n _2 = ChoiceItem(2, '2 Центр (столица) региона')\n _3 = ChoiceItem(3, '3 Центр района и региона (1+2)')\n _4 = ChoiceItem(4, '4 Центральный район центра региона')\n\n status = models.PositiveSmallIntegerField(\n verbose_name='Статус объекта',\n default=0,\n blank=True,\n choices=StatusType.choices,\n validators=[StatusType.validator]\n )\n\n @classmethod\n def _find_parent(cls, codes):\n \"\"\"\n Метод класса ищет по коду предка, если не находит,\n идё по рекурсии. Принимает �� качестве параметра результат\n метода get_codes с обнулённым code_relevance.\n\n В конечном итоге если не будет субъекта предка,\n будет вызвано исключение\n \"\"\"\n if codes['code_street']:\n codes['code_street'] = 0\n elif codes['code_locality']:\n codes['code_locality'] = 0\n elif codes['code_city']:\n codes['code_city'] = 0\n elif codes['code_region']:\n codes['code_region'] = 0\n else:\n raise ValueError('Bad Klard Code')\n\n from django.core.exceptions import ObjectDoesNotExist\n try:\n return Kladr.actual.get(**codes)\n except ObjectDoesNotExist:\n return cls._find_parent(codes)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Метод перезаписывает некоторые поля\n\n ССРРРГГГПППАА - для кладера регион\n ССРРРГГГПППУУУУАА - для кладера улицы\n ССРРРГГГПППУУУУДДДД - для кладера дома\n \"\"\"\n # self.kladr_type = KLADR_TYPE_SOCR_CHOICE.get(\n # self.kladr_type_socr,\n # self.kladr_type_socr\n # )\n # self.full_name = self.get_full_name()\n\n # if len(self.code) == len(\"ССРРРГГГПППАА\"):\n # self.code_subject = int(self.code[:2])\n # self.code_region = int(self.code[2:5])\n # self.code_city = int(self.code[5:8])\n # self.code_locality = int(self.code[8:11])\n # self.code_relevance = int(self.code[11:13])\n # elif len(self.code) == len(\"ССРРРГГГПППУУУУАА\"):\n # pass\n # elif len(self.code) == len(\"ССРРРГГГПППУУУУДДДД\"):\n # pass\n # else:\n # raise ValueError(\"Kladr code langth must be 13, 17 or 19\")\n\n # if not self.is_subject:\n # codes = self.get_codes()\n # codes['code_relevance'] = 0\n # self.parent = self._find_parent(codes)\n super(Kladr, self).save(*args, **kwargs)\n\n def __str__(self):\n return(self.code)\n","sub_path":"geo/backend/kladr/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"503006086","text":"\n# dp[i][j] means the counts when the last dice is dice i with consecutive frequency j\n\nclass Solution(object):\n def dieSimulator(self, n, rollMax):\n \"\"\"\n :type n: int\n :type rollMax: List[int]\n :rtype: int\n \"\"\"\n LIMIT = 10**9 + 7\n N = max(rollMax)+1 # max allowed frequence\n dp1 = [[0 for j in range(16)] for i in range(7)]\n for i in range(1, 7):\n if rollMax[i-1] >= 1:\n dp1[i][1] = 1\n \n for time in range(2, n+1):\n dp2 = [[0 for j in range(N)] for i in range(7)]\n for i in range(1, 7):\n total = sum(dp1[i]) # next time different dice\n for temp in range(1, 7):\n if temp != i and rollMax[temp-1] >= 1:\n dp2[temp][1] += total\n dp2[temp][1] %= 10**9 + 7\n for j in range(1, N):\n if dp1[i][j] == 0:\n continue\n if j + 1 <= rollMax[i-1]: # next time is still self \n dp2[i][j+1] += dp1[i][j]\n dp2[i][j+1] %= LIMIT\n dp1 = dp2\n \n return sum([sum(row)%LIMIT for row in dp1])%LIMIT\n\n\n#n = 2\n#rollMax = [1,1,2,2,2,3]\nn = 2000\nrollMax = [12,6,5,12,10,9]\nprint(Solution().dieSimulator(n, rollMax))\n\n","sub_path":"5224. Dice Roll Simulation.py","file_name":"5224. Dice Roll Simulation.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"243165000","text":"# Напишите программу, которая считывает из файла строку, соответствующую тексту,\n# сжатому с помощью кодирования повторов, и производит обратную операцию, получая исходный текст.\n# Запишите полученный текст в файл и прикрепите его, как ответ на это задание.\nwith open('in.txt', encoding='utf-8') as inf:\n text = inf.read()\n\ntext_out = ''\nch = ''\nnum = ''\nfor j in range(len(text) - 2):\n if not text[j].isdigit():\n ch = text[j]\n if text[j + 1].isdigit():\n num += text[j + 1]\n else:\n text_out += ch * (int(num) if num else 1)\n ch = ''\n num = ''\n\nwith open('out.txt', 'w', encoding='utf-8') as inf:\n inf.write(text_out)","sub_path":"Stepic/Программирование на Python/задача со stepic 3.4 на Файловый ввод вывод.py","file_name":"задача со stepic 3.4 на Файловый ввод вывод.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"77591182","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template\nfrom flask.ext.script import Manager\nfrom flask.ext.migrate import Migrate, MigrateCommand\nfrom flask_mail import Message\n\nfrom ca import app, db, mail\nfrom ca.models import Request\n\nimport datetime\nfrom subprocess import call\n\n\nmigrate = Migrate(app, db)\n\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\nrequests_subcommands = Manager(usage=\"Handle certificate requests\")\nmanager.add_command('requests', requests_subcommands)\n\ncertificates_subcommands = Manager(usage=\"Handle existing certificates\")\nmanager.add_command('certificates', certificates_subcommands)\n\n\ndef mail_certificate(id, email):\n msg = Message(\n app.config['MAIL_SUBJECT'],\n sender=app.config['MAIL_FROM'],\n recipients=[email]\n )\n msg.body = render_template('mail.txt')\n certificate_path = \"{}/freifunk_{}.tgz\".format(\n app.config['DIRECTORY_CLIENTS'],\n id\n )\n with app.open_resource(certificate_path) as fp:\n msg.attach(\n \"freifunk_{}.tgz\".format(id),\n \"application/gzip\",\n fp.read()\n )\n mail.send(msg)\n\n\ndef mail_request_rejected(id, email):\n msg = Message(\n app.config['MAIL_SUBJECT'],\n sender=app.config['MAIL_FROM'],\n recipients=[email]\n )\n msg.body = render_template('mail_request_rejected.txt')\n mail.send(msg)\n\n\n@requests_subcommands.command\ndef process():\n \"Process new certificate requests\"\n for request in Request.query.filter(Request.generation_date == None).all(): # noqa\n if app.config['SHOW_SIGNED_REQUESTS']:\n numsigned = Request.query.filter(Request.email == request.email, Request.generation_date != None).count()\n prompt = \"Do you want to generate a certificate for {}, {}?\\n\\talready signed to this address: {}\"\n print(prompt.format(request.id, request.email, numsigned))\n else:\n prompt = \"Do you want to generate a certificate for {}, {} ?\"\n print(prompt.format(request.id, request.email))\n print(\"Type 'y' to approve, 'n' to reject or 'any key' to skip\")\n confirm = input('>')\n if confirm in ['Y', 'y']:\n print('generating certificate')\n# call([app.config['COMMAND_BUILD'], request.id, request.email])\n request.generation_date = datetime.date.today()\n db.session.commit()\n# mail_certificate(request.id, request.email)\n print()\n elif confirm in ['N', 'n']:\n print('rejecting request')\n db.session.delete(request)\n db.session.commit()\n mail_request_rejected(request.id, request.email)\n else:\n print('skipping generation \\n')\n\n\n@requests_subcommands.command\ndef show():\n \"Show new certificate requests\"\n for request in Request.query.filter(Request.generation_date == None).all(): # noqa\n prompt = \"ID: {} - Email: {}\"\n print(prompt.format(request.id, request.email))\n\n\n@certificates_subcommands.command\ndef send():\n \"Send existing certificate again\"\n print(\"Which existing certificate do you want to send again? Type the ID\")\n send_again_id = input('>')\n print(\"Where should it be sent? Please type the Email\")\n send_again_mail = input('>')\n try:\n mail_certificate(send_again_id, send_again_mail)\n print(\"OK\")\n except:\n print(\"That didn't work.\")\n\n\n@certificates_subcommands.command\ndef show():\n \"Show already existing certificates\"\n for request in Request.query.filter(Request.generation_date != None).all(): # noqa\n prompt = \"ID: {} - Email: {}\"\n print(prompt.format(request.id, request.email))\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"320085439","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom multimedia_test_case import TestMultimedia\n\n\nclass TestLocalVideoResumeToStartPlay(TestMultimedia):\n def __init__(self, doc, level, owner):\n super(TestLocalVideoResumeToStartPlay, self).__init__(doc, level, owner)\n self.package_name = \"cn.whaley.cases.Helios.media.video.local.LocalTestSets\"\n self.test_content = \"testResumeBackToStart\"\n\n def execute(self):\n super(TestLocalVideoResumeToStartPlay, self).execute()\n\n\nif __name__ == \"__main__\":\n TestLocalVideoResumeToStartPlay(\n \"Play shark tale and seek to played 5min loc then quit and resume play to the start play point\", 'p1',\n \"wangdd\").run()\n","sub_path":"Python_Java_UIautomator/case/platform/multiMedia/test_local_sharkTale_resumeToStartPlay.py","file_name":"test_local_sharkTale_resumeToStartPlay.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"239192091","text":"import tensorflow as tf\n\nfrom nalp.corpus import TextCorpus\nfrom nalp.datasets import LanguageModelingDataset\nfrom nalp.encoders import IntegerEncoder\nfrom nalp.models.generators import LSTMGenerator\n\n# Creating a character TextCorpus from file\ncorpus = TextCorpus(from_file=\"data/text/chapter1_harry.txt\", corpus_type=\"char\")\n\n# Creating an IntegerEncoder, learning encoding and encoding tokens\nencoder = IntegerEncoder()\nencoder.learn(corpus.vocab_index, corpus.index_vocab)\nencoded_tokens = encoder.encode(corpus.tokens)\n\n# Creating Language Modeling Dataset\ndataset = LanguageModelingDataset(\n encoded_tokens, max_contiguous_pad_length=10, batch_size=64\n)\n\n# Creating the LSTM\nlstm = LSTMGenerator(\n encoder=encoder, vocab_size=corpus.vocab_size, embedding_size=256, hidden_size=512\n)\n\n# As NALP's LSTMs are stateful, we need to build it with a fixed batch size\nlstm.build((64, None))\n\n# Compiling the LSTM\nlstm.compile(\n optimizer=tf.optimizers.Adam(learning_rate=0.001),\n loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=[tf.metrics.SparseCategoricalAccuracy(name=\"accuracy\")],\n)\n\n# Fitting the LSTM\nlstm.fit(dataset.batches, epochs=100)\n\n# Evaluating the LSTM\n# lstm.evaluate(dataset.batches)\n\n# Saving LSTM weights\nlstm.save_weights(\"trained/lstm\", save_format=\"tf\")\n","sub_path":"examples/models/generators/train_lstm.py","file_name":"train_lstm.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"271050922","text":"\"\"\"\nSimulator for GTR models\nStuart Bradley - 5931269\n30/7/2015\n\nThis script tests whether the two versions of the GTR model produce\nthe same result. \n\"\"\"\nfrom CognateSet import CognateSet\nfrom RateMatrix import RateMatrix\nfrom Language import Language\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport numpy\n\nLan = Language(seq=[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0])\nset_l = CognateSet(langs=[Lan])\nrm = RateMatrix([0,1], [[-0.5,0.5],[0.5,-0.5]])\n\n# Simulates 1000 instances of the first method to determine the probabilities are\n# equal for both methods.\nd_1_1 = []\nd_2_1 = []\nfor i in range(100000):\n\tLan = Language(seq=[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0])\n\tset_l = CognateSet(langs=[Lan])\n\td_1_1.append(set_l.mutate_language_GTR_timed(set_l.language_list[0], rm, 100).sequence.count(1))\n\tLan = Language(seq=[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0])\n\tset_l = CognateSet(langs=[Lan])\n\td_2_1.append(set_l.mutate_language_GTR_timed_2(set_l.language_list[0], rm, 100).sequence.count(1))\n\ndensity_1 = stats.kde.gaussian_kde(d_1_1)\ndensity_2 = stats.kde.gaussian_kde(d_2_1)\nx = numpy.arange(0, 20, 1)\nplt.plot(x, density_1(x),color='b', label='Algorithm 1')\nplt.plot(x, density_2(x),color='r', label='Algorithm 2')\nplt.title(\"Simulation of 100000 Language Evolutions\")\nplt.xlabel(\"Number of cognates\")\nplt.ylabel(\"Proportion\")\nplt.legend()\nplt.show()","sub_path":"Utility Classes/simulator_gtr.py","file_name":"simulator_gtr.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"280266749","text":"# Program: Algoritmo350_OrdenaNomeVetor.py \n# Author: Ramon R. Valeriano\n# Description:\n# Developed: 25/04/2020 - 12:48\n# Updated:\n\nlista = list()\nquantity = 5\nfor e in range(quantity):\n name = str(input(\"Enter with %d name: \" %(e+1)))\n lista.append(name)\n\nfor n in range(quantity):\n for y in range((n+1), quantity):\n if lista[n]>lista[y]:\n aux = lista[n]\n lista[n] = lista[y]\n lista[y] = aux\nprint(lista)\n","sub_path":"Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 5/Exemplos 5a/Algoritmo350_OrdenaNomeVetor.py","file_name":"Algoritmo350_OrdenaNomeVetor.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"319339903","text":"from django.urls import path\nfrom . import views\n\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\napp_name = 'tot'\nurlpatterns = [\n # path('', views.index, name='index'),\n path('', views.IndexView.as_view(), name='index'),\n\n path('/', views.DetailView.as_view(), name='detail'),\n\n path('drinkresults/', views.drinkresults, name='drinkresults'),\n\n path('ingredientresults/', views.ingredientresults, name='ingredientresults'),\n\n path('add/', views.addForm, name='add'),\n\n path('/drink', views.drink, name='drink'),\n\n path('/delete', views.DrinkDelete.as_view(), name='deletedrink'),\n\n path('upload/', views.upload, name='upload'),\n\n path('contact/', views.contact, name='contact'),\n\n url(r'^admin/', admin.site.urls),\n]","sub_path":"tot/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"93734321","text":"import spotipy\nimport numpy as np\nimport json\nimport os\n\ndef crawl():\n\n \"\"\"Crawls Spotify API for MPD track audio features and writes to no-ext TSV file.\n\n One minute pauses after 10 queries/1k tracks, and after API error responses.\n \"\"\"\n\n token = spotipy.util.prompt_for_user_token(\n username = 'reenee29',\n client_id = '1a204c422a7c48828ccc3baa467a46ae', \n client_secret = '4706b8a8097740fd8585f122a28520b6', \n redirect_uri = 'http://localhost/callback')\n crawler = spotipy.Spotify(auth = token)\n print('spotify connected')\n\n root = '../../../../'\n\n # load data saved before last crash, or start fresh if no data found\n savepath = root + 'data/processed/mpd/aux/tracks/mpd.t_audio_features'\n if os.path.exists(savepath):\n t_audio_features = np.loadtxt(savepath, delimiter = '\\t', dtype = str)\n t_audio_features = {row[0] : list(row[1:]) for row in t_audio_features} # convert np.array to dict with values on same line\n else:\n t_audio_features = {} # dict instead of list to remove track duplicates\n\n # loop through MPD for tracks without saved audio features\n tracks_to_query = set()\n\n folder = root + 'data/raw/mpd/data/'\n for file in os.listdir(folder):\n filepath = os.path.join(folder, file) # join folder path with filename in folder\n\n with open(filepath) as f:\n data = json.load(f)['playlists']\n\n for playlist in data:\n\n for track in playlist['data']: \n t_uri = playlist['tracks'][i]['track_uri'][14:]\n\n if t_uri not in t_audio_features:\n tracks_to_query.add(t_uri)\n\n # query 100 tracks at a time for audio features\n tracks_to_query = list(tracks_to_query)\n split_into_100 = [tracks_to_query[x:x + 100] for x in range(0, len(tracks_to_query), 100)]\n\n for query, chunk in enumerate(split_into_100): # keep track of num queries so far for saving/pausing\n results = crawler.audio_features(chunk)\n\n for i, af in enumerate(results):\n if af: # some tracks return no audio features\n t_audio_features[chunk[i]] = list(af.values())[:11] # chunk[i] is t_uri\n\n # save data and pause for 1 min every 10 queries/1k tracks\n if query % 10 == 0: \n t_audio_features = [[k]+vs for k, vs in t_audio_features.items()] # values on same line\n np.savetxt(savepath, t_audio_features, delimiter = '\\t', fmt = '%s')\n\n print('pausing for 1 min after saving data')\n time.sleep(60)\n\n # if program reaches this point, tracks that didn't return audio features\n # are ignored, and rest are all saved\n\nwhile True:\n try:\n crawl()\n except:\n print(traceback.format_exc())\n print('pausing for 1 min after crash')\n time.sleep(60)\n else:\n break # breaks out of while loop if crawl() is successful","sub_path":"scripts/data/processed/mpd/mpd.aux_crawl.py","file_name":"mpd.aux_crawl.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"619890853","text":"import numpy as np\nimport astropy.units as u\nfrom astropy.modeling.models import Gaussian2D\n\n\ndef uncorrelated_gaussian_noise_background(shape, mean=0, sigma=1.0):\n normal_noise = np.random.randn(*shape)\n return (sigma * normal_noise) + mean\n\n\ndef gaussian_point_source(x_centre,\n y_centre,\n amplitude=1.0,\n semimajor_gaussian_sigma=1.5,\n semiminor_gaussian_sigma=1.2,\n position_angle=1. * u.rad,\n ):\n return Gaussian2D(amplitude=amplitude,\n x_mean=x_centre,\n y_mean=y_centre,\n x_stddev=semimajor_gaussian_sigma,\n y_stddev=semiminor_gaussian_sigma,\n theta=position_angle.to(u.rad)\n )\n\n\ndef evaluate_model_on_pixel_grid(image_shape, model):\n ydim, xdim = image_shape\n ygrid, xgrid = np.mgrid[:ydim, :xdim]\n return model(xgrid, ygrid)\n","sub_path":"tests/fixtures/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"518467839","text":"import models\nfrom flask import Blueprint, jsonify, request\nfrom playhouse.shortcuts import model_to_dict\nfrom flask_login import current_user\n\nplace = Blueprint('places', 'place')\n\n@place.route('/', methods=['GET'])\ndef get_all_places():\n try:\n all_places = models.Place.select()\n all_places = [model_to_dict(place) for place in all_places]\n return jsonify(data=all_places, status={'code': 200, 'message': 'Success'})\n except models.DoesNotExist:\n return jsonify(data={}, status={'code': 401, 'message': 'Error getting the resources'})\n\n@place.route('/user/', methods=['GET'])\ndef get_user_places():\n print('place index route')\n try:\n this_users_places = models.Place.select().where(models.Place.user == current_user.id)\n\n this_users_places = [model_to_dict(place) for place in this_users_places]\n\n print(this_users_places)\n return jsonify(data=this_users_places, status={'code': 200, 'message': 'Success'})\n except models.DoesNotExist:\n return jsonify(data={}, status={'code': 401, 'message': 'Error getting the resources'})\n\n@place.route('//',methods=['GET'])\ndef show_place(placeId):\n # if not current_user.is_authenticated: # Checks if user is logged in\n # return jsonify(data={}, status={'code': 401, 'message': 'You must be logged in to view this place'})\n try:\n found_place = models.Place.get(id=placeId)\n place_dict = model_to_dict(found_place)\n \n return jsonify(data=place_dict,status={\"code\":\"201\",\"message\":\"place found\"})\n except models.DoesNotExist:\n return jsonify(data={}, status={'code': 401, 'message': 'Place to show does not exist'})\n\n@place.route('/', methods=['POST'])\ndef create_place():\n print('place create route')\n print('CURRENT USER', current_user)\n if not current_user.is_authenticated:\n print(current_user, 'NOT ALLOWED')\n return jsonify(data={}, status={'code': 401, 'message': 'You must be logged in to create a place'})\n # user = models.User.get_by_id(current_user.id)\n # user_dict = model_to_dict(user)\n # print(user_dict, 'User DICT')\n\n payload = request.get_json()\n # payload['user'] = current_user.id\n created_place = models.Place.create(**payload)\n create_place_dict = model_to_dict(created_place)\n return jsonify(status={'code': 201, 'msg': 'success'}, data=create_place_dict)\n\n@place.route('//', methods=['PUT'])\ndef update_place(placeId):\n print('place edit route')\n payload = request.get_json()\n if not current_user.is_authenticated:\n return jsonify(data={}, status={'code': 401, 'message':'You must be logged in to update place'})\n try:\n place = models.Place.get_by_id(placeId)\n place_dict = model_to_dict(place)\n print(place_dict, 'PLACE DICT')\n # if place_dict.user.id is not current_user.id: \n # return jsonify(data={}, status={'code': 401, 'message': 'You can only update your own places'})\n updated_place = models.Place.update(\n main_entrance=payload['main_entrance'],\n bathroom=payload['bathroom'],\n overall=payload['overall'],\n ).where(models.Place.id==placeId).execute()\n updated_place_dict = model_to_dict(models.Place.get(id=placeId))\n return jsonify(data=updated_place_dict, status={\"code\": 201, \"message\": \"Place updated\"})\n except models.DoesNotExist:\n return jsonify(data={}, status={'code': 401, 'message': 'Place to update does not exist'})\n\n@place.route('//', methods=['DELETE'])\n# @login_required\ndef delete_place(placeId):\n \n place_to_delete = models.Place.get_by_id(placeId)\n\n if place_to_delete.user.id != current_user.id:\n return jsonify(data=\"Forbidden\", status={'code': 403, 'message': \"User can only delete their own places.\"})\n else:\n place_name = place_to_delete.name\n # articles_to_delete = models.Article.select().where(models.Article.topic.user.id == current_user.id)\n \n # articles_to_delete.delete()\n place_to_delete.delete_instance(recursive=True)\n return jsonify(data='Place successfully deleted', status={\"code\": 200, \"message\": \"{} deleted successfully\".format(place_name)})","sub_path":"resources/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":4241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"86758635","text":"from itertools import chain\nimport operator\nfrom collections import defaultdict\nfrom nineml.exceptions import (\n NineMLRuntimeError, NineMLInvalidElementTypeException)\nfrom nineml.xmlns import NINEML\n\n\nclass BaseNineMLObject(object):\n\n \"\"\"\n Base class for user layer classes\n \"\"\"\n children = []\n\n def __init__(self, annotations=None):\n if annotations is None:\n annotations = nineml.annotations.Annotations()\n else:\n assert isinstance(annotations, nineml.annotations.Annotations)\n self._annotations = annotations\n\n @property\n def annotations(self):\n return self._annotations\n\n def __eq__(self, other):\n try:\n if self.element_name != other.element_name:\n return False\n except AttributeError:\n return False\n if self.defining_attributes != other.defining_attributes:\n return False\n for name in self.defining_attributes:\n self_elem = getattr(self, name)\n other_elem = getattr(other, name)\n if not isinstance(self_elem, dict):\n # Try to sort the elements (so they are order non-specific) if\n # they are an iterable list, ask forgiveness and fall back to\n # standard equality if they aren't\n try:\n if len(self_elem) > 1 and len(other_elem) > 1:\n self_elem = sorted(self_elem, key=lambda x: x._name)\n other_elem = sorted(other_elem, key=lambda x: x._name)\n except (TypeError, AttributeError):\n pass\n if self_elem != other_elem:\n return False\n return True\n\n def __ne__(self, other):\n return not self == other\n\n def get_children(self):\n return chain(getattr(self, attr) for attr in self.children)\n\n def accept_visitor(self, visitor):\n raise NotImplementedError(\n \"Derived class '{}' has not overriden accept_visitor method.\"\n .format(self.__class__.__name__))\n\n def find_mismatch(self, other, indent=' '):\n \"\"\"\n A function used for debugging where two NineML objects differ\n \"\"\"\n if not indent:\n result = (\"Mismatch between '{}' types:\"\n .format(self.__class__.__name__))\n else:\n result = ''\n if type(self) != type(other):\n result += \"mismatch in type ({} and {})\".format(type(self),\n type(other))\n else:\n for attr_name in self.__class__.defining_attributes:\n self_attr = getattr(self, attr_name)\n other_attr = getattr(other, attr_name)\n if self_attr != other_attr:\n result += \"\\n{}Attribute '{}': \".format(indent, attr_name)\n result += self._unwrap_mismatch(self_attr, other_attr,\n indent + ' ')\n return result\n\n @classmethod\n def _unwrap_mismatch(cls, s, o, indent):\n result = ''\n if isinstance(s, BaseNineMLObject):\n result += s.find_mismatch(o, indent=indent + ' ')\n elif isinstance(s, dict):\n if set(s.keys()) != set(o.keys()):\n result += ('keys do not match ({} and {})'\n .format(set(s.keys()), set(o.keys())))\n else:\n for k in s:\n if s[k] != o[k]:\n result += \"\\n{}Key '{}':\".format(indent + ' ', k)\n result += cls._unwrap_mismatch(s[k], o[k],\n indent + ' ')\n elif isinstance(s, list):\n if len(s) != len(o):\n result += 'differ in length ({} to {})'.format(len(s), len(o))\n else:\n for i, (s_elem, o_elem) in enumerate(zip(s, o)):\n if s_elem != o_elem:\n result += \"\\n{}Index {}:\".format(indent + ' ', i)\n result += cls._unwrap_mismatch(s_elem, o_elem,\n indent + ' ')\n else:\n result += \"{} != {}\".format(s, o)\n return result\n\n @classmethod\n def check_tag(cls, element):\n assert element.tag in (cls.element_name, NINEML + cls.element_name), (\n \"Found '{}' element, expected '{}'\".format(element.tag,\n cls.element_name))\n\n\nclass DocumentLevelObject(object):\n\n def __init__(self, url):\n self._url = url\n\n @property\n def url(self):\n return self._url\n\n @property\n def attributes_with_dimension(self):\n return [] # To be overridden in derived classes\n\n @property\n def attributes_with_units(self):\n return [] # To be overridden in derived classes\n\n @property\n def all_units(self):\n return [a.units for a in self.attributes_with_units]\n\n @property\n def all_dimensions(self):\n return [a.dimension for a in self.attributes_with_dimension]\n\n def write(self, fname):\n \"\"\"\n Writes the top-level NineML object to file in XML.\n \"\"\"\n nineml.write(self, fname) # Calls nineml.document.Document.write\n\n\nclass ContainerObject(object):\n \"\"\"\n An abstract base class for handling the manipulation of member objects\n (which are stored in dictionaries that can be detected by member type).\n\n Deriving classes are expected to have the 'class_to_member' class\n attribute\n \"\"\"\n\n def __init__(self):\n self._indices = defaultdict(dict)\n\n def add(self, element):\n dct = self._member_dict(element)\n if element._name in dct:\n raise NineMLRuntimeError(\n \"Could not add '{}' {} to component class as it clashes with \"\n \"an existing element of the same name\"\n .format(element.name, type(element).__name__))\n dct[element._name] = element\n\n def remove(self, element):\n dct = self._member_dict(element)\n try:\n del dct[element._name]\n except KeyError:\n raise NineMLRuntimeError(\n \"Could not remove '{}' from component class as it was not \"\n \"found in member dictionary (use 'ignore_missing' option \"\n \"to ignore)\".format(element._name))\n\n def _update_member_key(self, old_key, new_key):\n \"\"\"\n Updates the member key for a given element_type\n \"\"\"\n for element_type in self.class_to_member:\n member_dict = self._member_dict(element_type)\n try:\n member_dict[new_key] = member_dict.pop(old_key)\n except KeyError:\n pass\n\n def elements(self, as_class=None):\n \"\"\"\n Iterates through all the core member elements of the container. For\n core 9ML objects this will be the same as those iterated by the\n __iter__ magic method, where as for 9ML extensions.\n \"\"\"\n if as_class is None:\n as_class = type(self)\n return chain(*(self._members_iter(et, as_class=as_class)\n for et in as_class.class_to_member))\n\n def element(self, name, as_class=None):\n \"\"\"\n Looks a member item by \"name\" (identifying characteristic)\n \"\"\"\n if as_class is None:\n as_class = type(self)\n for element_type in as_class.class_to_member:\n try:\n elem = self._member_accessor(\n element_type, as_class=as_class)(name)\n # Ignore send ports as they otherwise mask\n # aliases/state variables\n if not isinstance(elem, SendPortBase):\n return elem\n except KeyError:\n pass\n raise KeyError(\"'{}' was not found in '{}' {} object\"\n .format(name, self._name, as_class.__name__))\n\n def num_elements(self, as_class=None):\n if as_class is None:\n as_class = type(self)\n return reduce(operator.add,\n *(self._num_members(et, as_class=as_class)\n for et in as_class.class_to_member))\n\n def element_names(self, as_class=None):\n if as_class is None:\n as_class = type(self)\n for element_type in as_class.class_to_member:\n # Some of these do not meet the stereotypical *_names format, e.g.\n # time_derivative_variables, could change these to *_keys instead\n try:\n for name in self._member_names_iter(element_type,\n as_class=as_class):\n yield name\n except AttributeError:\n pass\n\n def __getitem__(self, name):\n \"\"\"\n Looks a member item by \"name\" (identifying characteristic) in any of\n of the base classes in the same order as the MRO.\n \"\"\"\n # Loop through all base classes to see if the name fits any member\n # of any base class\n for cls in type(self).__mro__:\n if hasattr(cls, 'class_to_member'):\n try:\n return self.element(name, as_class=cls)\n except KeyError:\n pass\n raise KeyError(\"'{}' was not found in '{}' {} object\"\n .format(name, self._name, type(self).__name__))\n\n def __contains__(self, element):\n \"\"\"\n Checks whether the element belongs to the container object or any sub-\n containers. The element can either be a string representing a named\n object or an element that is meant to equal an element within the\n container.\n \"\"\"\n if isinstance(element, basestring):\n for cls in type(self).__mro__:\n try:\n for type_name in cls.class_to_member:\n if element in self._member_dict(type_name):\n return True\n for member in self._members_iter(type_name):\n if (isinstance(member, ContainerObject) and\n element in member):\n return True\n except AttributeError:\n pass\n return False\n else:\n return self._find_element(element) # Lookup via full-search\n\n def __iter__(self):\n raise ValueError(\"'{}' {} container is not iterable\"\n .format(self.name, type(self).__name__))\n\n def index_of(self, element, key=None):\n \"\"\"\n Returns the index of an element amongst others of its type. The indices\n are generated on demand but then remembered to allow them to be\n referred to again. The `key` argument can be provided to manually\n override the types with which the element is grouped, which allows the\n indexing of elements within supersets of various types.\n\n This function can be useful during code-generation from 9ML, where the\n name of an element can be replaced with a unique integer value (and\n referenced elsewhere in the code).\n \"\"\"\n if key is None:\n for cls in type(self).__mro__:\n if hasattr(cls, 'class_to_member'):\n try:\n key = accessor_name_from_type(cls, element)\n except NineMLInvalidElementTypeException:\n pass\n if key is None:\n raise NineMLInvalidElementTypeException(\n \"Could not find member of type {} in {} or its base \"\n \"classes\".format(type(element), type(self)))\n dct = self._indices[key]\n try:\n index = dct[element]\n except KeyError:\n # Get the first index ascending from 0 not in the set\n try:\n index = next(iter(sorted(\n set(xrange(len(dct))).difference(dct.itervalues()))))\n except StopIteration:\n index = len(dct)\n dct[element] = index\n return index\n\n # =========================================================================\n # Each member element_name is associated with a member accessor by the\n # class attribute 'class_to_member' dictionary. From this name accessors\n # for the set of members of this type, and their names and length, can be\n # derrived from the stereotypical naming structure used\n # =========================================================================\n\n def _member_accessor(self, element_type, as_class=None):\n if as_class is None:\n as_class = type(self)\n return getattr(self, accessor_name_from_type(as_class,\n element_type))\n\n def _members_iter(self, element_type, as_class=None):\n \"\"\"\n Looks up the name of values iterator from the element_name of the\n element argument.\n \"\"\"\n if as_class is None:\n as_class = type(self)\n return getattr(\n self, pluralise(accessor_name_from_type(as_class,\n element_type)))\n\n def _member_names_iter(self, element_type, as_class=None):\n if as_class is None:\n as_class = type(self)\n try:\n return getattr(\n self, (accessor_name_from_type(as_class, element_type)\n + '_names'))\n except AttributeError:\n raise AttributeError(\n \"Elements of type {} aren't named\".format(element_type))\n\n def _num_members(self, element_type, as_class=None):\n if as_class is None:\n as_class = type(self)\n return getattr(\n self, ('num_' +\n pluralise(accessor_name_from_type(as_class,\n element_type))))\n\n def _member_dict(self, element_type):\n return getattr(\n self, '_' + pluralise(accessor_name_from_type(\n self, element_type)))\n\n\ndef accessor_name_from_type(class_type, element_type):\n \"\"\"\n Looks up the name of the accessor method from the element_name of the\n element argument for a given container type\n \"\"\"\n if not isinstance(element_type, basestring):\n element_type = element_type.element_name\n try:\n return class_type.class_to_member[element_type]\n except KeyError:\n raise NineMLInvalidElementTypeException(\n \"Could not get member attr for element of type '{}' for object \"\n \"'{}' container\".format(element_type, class_type))\n\n\ndef pluralise(word):\n if word.endswith('s'):\n word = word + 'es'\n else:\n word = word + 's'\n return word\n\n\nclass SendPortBase(object):\n \"\"\"\n Dummy class to allow look up via inheritence of SendPort in this module\n without causing circular import problems\n \"\"\"\n\n\nimport nineml\n","sub_path":"nineml/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":15140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"11892762","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n sum = 0\n def sumRootToLeaf(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n self.sumRootLeaft(root, '')\n return self.sum\n \n def sumRootLeaft(self, root, num):\n if root.left is None and root.right is None:\n self.sum += int(num + str(root.val), 2)\n if root.left:\n self.sumRootLeaft(root.left, num + str(root.val))\n if root.right:\n self.sumRootLeaft(root.right, num + str(root.val))\n \n","sub_path":"LeetCode/Sum of Root To Leaf Binary Numbers.py","file_name":"Sum of Root To Leaf Binary Numbers.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"119281501","text":"import os\nimport time\nfrom itertools import combinations\n\nimport numpy as np\n\nimport pandas as pd\n\nimport cv2\nimport torch\nfrom torch.nn import Softmax\n\nfrom .model_definition import TransferModel\n\nimport requests\n\nITEM_NAMES_FILE = os.getcwd() + '/models/food-items.txt'\nMODEL_FILE = os.getcwd() + '/models/model.pt'\nIMAGE_SIZE = 224\nSTRIDE = 112\n\nAPP_ID = '569fabe5'\nAPP_KEY = 'ce79f2d3e113d81b70c13dbfc2f4bb35'\n\nN_RECIPES = 10\n\nwith open(ITEM_NAMES_FILE) as f:\n item_names = f.read().splitlines()\n\n# Count the number of items\nn_classes = len(item_names)\n\n# Make dictionaries to turn labels into indicies\nlabel_dict_itos = dict(zip(range(0, n_classes), item_names))\n\nVEGETARIAN = {\n'bacon',\n'beef',\n'chicken_breast',\n'chicken_leg',\n'chicken_wing',\n'pork',\n'pork_ribs',\n'salmon',\n'tuna',\n'tilapia'\n}\n\nVEGAN = {\n'eggs',\n'cheddar_cheese',\n'mozzarella_cheese',\n'parmesan_cheese'\n}\n\nmodel = torch.load(MODEL_FILE)\nsoftmax = Softmax()\n\ndef find_recipes(file_path, options):\n \"\"\"\n \"\"\"\n # get_items - runs the nn on the image, returning a set of items\n\n print(\"Making predictions...\")\n orig_predictions = get_items(file_path)\n print(orig_predictions)\n predictions = orig_predictions\n if options[1][1]: # If option for vegetarian\n predictions = orig_predictions - VEGETARIAN\n\n if options[0][1]: # If option for vegan\n predictions = predictions - VEGAN - VEGETARIAN\n\n print(\"Finding recipes...\")\n recipes = get_matching_recipes(predictions, options)\n\n return orig_predictions, recipes \n\ndef get_matching_recipes(ingredients, options):\n # Keep finding recipes until there are at least N_RECIPES\n recipes = []\n\n # API call with subset of ingredients \n for i in range(len(ingredients), 0, min(-1, -(len(ingredients) // 2))):\n if i < 1:\n i = 1\n\n for ingredient_set in combinations(ingredients, i):\n print(ingredient_set)\n # Call API and get json data \n json_data = call_api(ingredient_set, options)\n \n # What to do if we get an error?\n if json_data is None:\n return recipes\n\n # Look through each hit\n for hit in json_data['hits']:\n recipe_url = hit['recipe']['url']\n recipe_title = hit['recipe']['label']\n recipe_image = hit['recipe']['image']\n\n recipe = {'title': recipe_title, \n 'url': recipe_url, \n 'imgsrc': recipe_image,\n 'uses': ', '.join(ingredient_set).replace('_', ' ') }\n recipes.append(recipe)\n\n if len(recipes) >= N_RECIPES:\n return recipes\n \n\ndef call_api(ingredients, options):\n base_url = \"https://api.edamam.com/search?app_id={}&app_key={}\".format(APP_ID, APP_KEY)\n\n query = 'q=' + (','.join(ingredients)).replace('_', '%20')\n \n options = map(lambda x: x[0].replace('_', '-'), (filter(lambda x: x[1] == 1, options)))\n health = '&'.join(['health=' + option for option in options])\n\n request_url = '&'.join([base_url, query, health])\n\n r = requests.get(request_url)\n\n if r.status_code == 403:\n return None\n\n # We get 401 when we made too many requests. What to do?\n while r.status_code == 401:\n return None\n\n json_data = r.json()\n\n return json_data\n\ndef get_items_mock(file_path):\n return {'potato', 'chicken', 'apples'}\n\ndef get_items(file_path):\n \"\"\"Return a list of items detected in image.\n file_path (str): Image in the form of 3d array to apply transformation to.\n \"\"\"\n image = cv2.cvtColor(cv2.imread(file_path), cv2.COLOR_BGR2RGB)\n\n preds_on_orig = sample_and_predict(image)\n preds_on_scaled = sample_and_predict(cv2.resize(image, (0,0), fx=1.2, fy=1.2))\n\n return set(preds_on_orig + preds_on_scaled)\n\ndef sample_and_predict(image):\n \"\"\"Make predictions on windows taken from image.\n image (np.ndarray): Image to sample and make predictions on.\n\n \"\"\"\n height = image.shape[0]\n width = image.shape[1]\n\n rows = 1 + (height - IMAGE_SIZE) // STRIDE\n cols = 1 + (width - IMAGE_SIZE) // STRIDE\n\n predictions = []\n i = 1 \n y_pos = 0\n while y_pos + IMAGE_SIZE < height:\n x_pos = 0\n while x_pos + IMAGE_SIZE < width:\n # Get a crop from the original image\n crop = image[y_pos:y_pos+IMAGE_SIZE, x_pos:x_pos+IMAGE_SIZE]\n\n # Turn it into a tensor for the model\n crop_tensor = torch.tensor([[crop[:,:,0], crop[:,:,1], crop[:,:,2]]])\\\n .type_as(torch.FloatTensor())\n # Make predictions and ave them\n probs = softmax(model(crop_tensor).data).numpy()\n\n if probs.max() > 0.6:\n pred = label_dict_itos[np.argmax(probs, axis=1)[0]]\n predictions.append(pred)\n \n # Move the window to the right\n x_pos += STRIDE\n i += 1 # next subplot\n # Move the window down\n y_pos += STRIDE\n\n return predictions","sub_path":"app/backend/src/quickrecipe.py","file_name":"quickrecipe.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"531268762","text":"\n\n#calss header\nclass _GLOBETROTTER():\n\tdef __init__(self,): \n\t\tself.name = \"GLOBETROTTER\"\n\t\tself.definitions = [u'someone who often travels to a lot of different countries: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_globetrotter.py","file_name":"_globetrotter.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"354500023","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 28 12:15:42 2016\r\n\r\n@author: matthew.smith\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport sklearn\r\nimport seaborn as sns\r\nimport bokeh\r\n\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.preprocessing import Imputer\r\nfrom sklearn import metrics\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.cross_validation import train_test_split\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom imblearn.under_sampling import RandomUnderSampler\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn import svm\r\nfrom sklearn import tree\r\nfrom sklearn.grid_search import GridSearchCV\r\nfrom IPython.display import Image\r\nfrom sklearn.grid_search import GridSearchCV\r\nimport datetime as dt\r\n\r\n\r\ndf=pd.read_csv('S:\\CG ANALYTICS\\Learning\\Sustainers\\FIFCampaignResponses.csv', encoding='latin-1', parse_dates=True)\r\n\r\n#df=pd.read_csv('C:\\\\Users\\\\matthew.smith\\\\Desktop\\\\Learning\\\\Sustainers\\\\FIFCampaignResponses.csv', encoding='latin-1', parse_dates=True)\r\n\r\n# Reorder columns so it is easier to exclude dates\r\n\r\ndf = df[['#ID', 'Lastgift', 'Maxgift', 'Totalgifts', 'Totalpayamount', 'Firstgift','Maxgiftdate', 'Firstgiftdate', 'Lastgiftdate', 'Mail?']]\r\n\r\n# Find out if data has any NULL values\r\n\r\nprint(df.isnull().any(), '\\n')\r\n\r\n# Change First Gift Date and Last Gift Date to Ordinal \r\ndf['Firstgiftdate']= (pd.to_datetime(df['Firstgiftdate'])).map(dt.datetime.toordinal)\r\ndf['Lastgiftdate'] = (pd.to_datetime(df['Lastgiftdate'])).map(dt.datetime.toordinal)\r\ndf['Maxgiftdate'] = (pd.to_datetime(df['Maxgiftdate'])).map(dt.datetime.toordinal)\r\n\r\n# Split between X and y\r\n\r\ndf_X = df[['Lastgift','Maxgift','Totalgifts','Totalpayamount','Firstgift','Firstgiftdate','Lastgiftdate','Maxgiftdate']]\r\n\r\ndf_y = df[['Mail?']]\r\n\r\nprint(df_X.describe(), '\\n')\r\nprint(df_y.describe(), '\\n')\r\n\r\n# Remove headers from dataset\r\n\r\noriginal_headers_X = list(df_X.columns.values)\r\n\r\noriginal_headers_y = list(df_y.columns.values)\r\n\r\nprint('Feature Headers: ', original_headers_X)\r\nprint('Target Header: ', original_headers_y, '\\n')\r\n\r\n# Convert data into NumPy Array\r\n\r\nX_matrix = df_X.values\r\n\r\ny_matrix = df_y.values\r\n\r\ny = y_matrix.flatten()\r\n\r\nprint('Shape of original dataset:', df.shape, '\\n')\r\nprint('Shape of features:', X_matrix.shape)\r\nprint('Shape of targets:', y.shape, '\\n')\r\nprint('Total Number of Samples (rows): ', X_matrix.shape[0])\r\nprint('Total Number of Features (columns): ', X_matrix.shape[1], '\\n')\r\n\r\n#Run Imputer to fill in NULL values\r\n\r\nimp = Imputer(missing_values='NaN', strategy='mean', axis=0)\r\nimp.fit(X_matrix)\r\nX_imp = imp.fit_transform(X_matrix)\r\n\r\n# Use Scaler\r\n\r\nscaler = StandardScaler()\r\nX = scaler.fit_transform(X_imp)\r\n\r\nprint('Shape of Imputed Features: ', X.shape)\r\nprint('Shape of Target: ', y.shape, '\\n')\r\n\r\n#Fixing imbalance of negative class with undersampling of positive class\r\n\r\n# Instanciate a PCA object for the sake of easy visualisation\r\npca = PCA(n_components=2)\r\n\r\n# Fit and transform x to visualise inside a 2D feature space\r\nX_vis = pca.fit_transform(X)\r\n\r\n# Apply the random over-sampling\r\nUS = RandomUnderSampler()\r\nusx,usy = US.fit_sample(X,y)\r\nX_res_vis = pca.transform(usx)\r\n\r\n# Two subplots, unpack the axes array immediately\r\n\r\nX_vis_2 = pd.DataFrame(X_vis)\r\nX_vis_2.columns= [\"x\",\"y\"]\r\n\r\nfrom bokeh.charts import Scatter, show\r\nscatter = Scatter(X_vis_2, x = \"x\", y = \"y\")\r\n\r\nshow(scatter)\r\n\r\nusX_vis_2 = pd.DataFrame(X_res_vis)\r\nusX_vis_2.columns=[\"x\",\"y\"]\r\n\r\nfrom bokeh.charts import Scatter, show\r\nscatter = Scatter(usX_vis_2, x = \"x\", y = \"y\")\r\n\r\nshow(scatter)\r\n\r\n# Set Estimator for KNN\r\n\r\nknn = KNeighborsClassifier(n_neighbors=30)\r\n\r\n# Fit Estimator to the dataset\r\n\r\nknn.fit(usx,usy)\r\n\r\n# Predict using X_imp\r\n\r\ny_pred_knn = knn.predict(usx)\r\n\r\n# Cross-validation for KNN\r\n\r\nknn_scores = cross_val_score(knn, usx, usy, cv=10, scoring='accuracy')\r\n\r\n# Grid Search for KNN\r\n\r\nk_range = list(range(1,31))\r\nparam_grid = dict(n_neighbors=k_range)\r\ngrid = GridSearchCV(knn, param_grid, cv=10, scoring='accuracy')\r\ngrid.fit(usx,usy)\r\n\r\ngrid_mean_scores = [result.mean_validation_score for result in grid.grid_scores_]\r\n\r\nplt.plot(k_range, grid_mean_scores)\r\nplt.xlabel('Value of K for KNN')\r\nplt.ylabel('Cross-Validated Accuracy')\r\nplt.show()\r\n\r\nprint('Grid Best Score: ', grid.best_score_)\r\nprint('Grid Best Parameter: ', grid.best_params_)\r\nprint('Grid Best Estimator: ', grid.best_estimator_)\r\n\r\n# Cross-validation for Logistic Regression\r\n\r\nlogreg = LogisticRegression()\r\nlog_scores = cross_val_score(logreg, usx, usy, cv=10, scoring='accuracy')\r\n\r\n# Cross-validation for SVM\r\n\r\nsvc = svm.SVC()\r\nsvc_scores = cross_val_score(svc, usx, usy, cv=10, scoring='accuracy')\r\n\r\nk_range = list(range(1,100))\r\nk_scores = []\r\nfor k in k_range:\r\n knn = KNeighborsClassifier(n_neighbors=k)\r\n scores = cross_val_score(knn, usx, usy, cv=10, scoring='accuracy')\r\n k_scores.append(scores.mean())\r\n\r\n# Decision Tree\r\n\r\ntree = tree.DecisionTreeClassifier()\r\n\r\ntree_k_range = list(range(1,31))\r\ntree_param_grid = dict(max_depth=tree_k_range)\r\ntree_grid = GridSearchCV(tree, tree_param_grid, cv=10, scoring='accuracy')\r\ntree_grid.fit(usx,usy)\r\n\r\ntree_grid_mean_scores = [result.mean_validation_score for result in tree_grid.grid_scores_]\r\n\r\nplt.plot(tree_k_range, tree_grid_mean_scores)\r\nplt.xlabel('Value of Max Depth for Tree')\r\nplt.ylabel('Cross-Validated Accuracy')\r\nplt.show()\r\n\r\nprint('Grid Max Depth Best Score: ', tree_grid.best_score_)\r\nprint('Grid Max Depth Best Parameter: ', tree_grid.best_params_)\r\nprint('Grid Max Depth Best Estimator: ', tree_grid.best_estimator_)\r\n\r\n# Plot of the value of K versus the Accuracy\r\n\r\nplt.plot(k_range, k_scores)\r\nplt.xlabel('Value of K for KNN')\r\nplt.ylabel('Cross-Validated Accuracy')\r\nplt.show()\r\n\r\nprint('Average accuracy score for KNN Cross-Validation: ', knn_scores.mean(), '\\n')\r\nprint('Average accuracy score for Logistic Regression Cross-Validation: ', log_scores.mean(), '\\n')\r\nprint('Average accuracy score for Support Vector Machine: ', svc_scores.mean())\r\n\r\n#Predict Values for Logistic Regression - Call prediction first and then pass through probability\r\n\r\nlogreg.fit(usx,usy)\r\n\r\nprediction=logreg.predict_proba(X)\r\n\r\nprint(prediction)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"FIFLearning_v10_GridSearch.py","file_name":"FIFLearning_v10_GridSearch.py","file_ext":"py","file_size_in_byte":6348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"654433249","text":"class Movie():\n \"\"\"Movie is the class that stores information about a motion picture\"\"\"\n\n def __init__(self, movie_title, movie_storyline, poster_image,\n trailer_youtube):\n \"\"\"Initializes and instance of the Movie class\"\"\"\n self.title = movie_title\n self.storyline = movie_storyline\n self.poster_image_url = poster_image\n self.trailer_youtube_url = trailer_youtube\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"56946664","text":"import asyncio\nfrom typing import Any, Awaitable, Dict, List, Optional\n\nimport aiopg\nimport psycopg2.sql\nfrom psycopg2.extras import Json, RealDictCursor\n\nfrom procrastinate import store\n\n\ndef wrap_json(arguments: Dict[str, Any]):\n return {\n key: Json(value) if isinstance(value, dict) else value\n for key, value in arguments.items()\n }\n\n\ndef get_connection(dsn=\"\", **kwargs) -> Awaitable[aiopg.Connection]:\n # tell aiopg not to register adapters for hstore & json by default, as\n # those are registered at the module level and could overwrite previously\n # defined adapters\n kwargs.setdefault(\"enable_json\", False)\n kwargs.setdefault(\"enable_hstore\", False)\n return aiopg.connect(dsn=dsn, **kwargs)\n\n\nasync def execute_query(\n connection: aiopg.Connection, query: str, **arguments: Any\n) -> None:\n # aiopg can work with psycopg2's cursor class\n async with connection.cursor(cursor_factory=RealDictCursor) as cursor:\n await cursor.execute(query, wrap_json(arguments))\n\n\nasync def execute_query_one(\n connection: aiopg.Connection, query: str, **arguments: Any\n) -> Dict[str, Any]:\n # aiopg can work with psycopg2's cursor class\n async with connection.cursor(cursor_factory=RealDictCursor) as cursor:\n await cursor.execute(query, wrap_json(arguments))\n\n return await cursor.fetchone()\n\n\nasync def execute_query_all(\n connection: aiopg.Connection, query: str, **arguments: Any\n) -> List[Dict[str, Any]]:\n # aiopg can work with psycopg2's cursor class\n async with connection.cursor(cursor_factory=RealDictCursor) as cursor:\n await cursor.execute(query, wrap_json(arguments))\n\n return await cursor.fetchall()\n\n\ndef make_dynamic_query(query: str, **identifiers: str) -> str:\n return psycopg2.sql.SQL(query).format(\n **{key: psycopg2.sql.Identifier(value) for key, value in identifiers.items()}\n )\n\n\nasync def wait_for_jobs(connection: aiopg.Connection, socket_timeout: float):\n try:\n await asyncio.wait_for(connection.notifies.get(), timeout=socket_timeout)\n except asyncio.futures.TimeoutError:\n pass\n\n\ndef interrupt_wait(connection: aiopg.Connection):\n asyncio.get_event_loop().call_soon_threadsafe(connection.notifies.put_nowait, \"s\")\n\n\nclass PostgresJobStore(store.BaseJobStore):\n \"\"\"\n Uses ``aiopg`` to establish an asynchronous\n connection to a PostgreSQL database.\n \"\"\"\n\n def __init__(self, *, socket_timeout: float = store.SOCKET_TIMEOUT, **kwargs: Any):\n \"\"\"\n All parameters except ``socket_timeout`` are passed to\n :py:func:`aiopg.connect` (see the documentation__)\n\n .. __: https://aiopg.readthedocs.io/en/stable/core.html#connection\n\n Parameters\n ----------\n socket_timeout:\n This parameter should generally not be changed.\n It indicates the maximum duration (in seconds) procrastinate workers wait\n between each database job pull. Job activity will be pushed from the db to\n the worker, but in case the push mechanism fails somehow, workers will not\n stay idle longer than the number of seconds indicated by this parameters.\n \"\"\"\n\n self._connection_parameters = kwargs\n self._connection: Optional[aiopg.Connection] = None\n self.socket_timeout = socket_timeout\n\n async def get_connection(self):\n if not self._connection:\n self._connection = await get_connection(**self._connection_parameters)\n return self._connection\n\n async def close_connection(self) -> None:\n if not self._connection:\n return\n\n await self._connection.close()\n\n async def execute_query(self, query: str, **arguments: Any) -> None:\n await execute_query(await self.get_connection(), query=query, **arguments)\n\n async def execute_query_one(self, query: str, **arguments: Any) -> Dict[str, Any]:\n return await execute_query_one(\n await self.get_connection(), query=query, **arguments\n )\n\n async def execute_query_all(\n self, query: str, **arguments: Any\n ) -> List[Dict[str, Any]]:\n return await execute_query_all(\n await self.get_connection(), query=query, **arguments\n )\n\n def make_dynamic_query(self, query: str, **identifiers: str) -> str:\n return make_dynamic_query(query=query, **identifiers)\n\n async def wait_for_jobs(self):\n return await wait_for_jobs(\n connection=await self.get_connection(), socket_timeout=self.socket_timeout\n )\n\n def stop(self):\n if self._connection:\n interrupt_wait(connection=self._connection)\n","sub_path":"procrastinate/aiopg_connector.py","file_name":"aiopg_connector.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"66249698","text":"from datetime import date\n\nfrom fastapi_users.db import TortoiseBaseUserModel\nfrom tortoise.models import Model\nfrom tortoise import fields\n\n\nclass User(TortoiseBaseUserModel):\n balance = fields.FloatField(default=0.0)\n\n\nclass Movie(Model):\n title = fields.CharField(max_length=100)\n year = fields.IntField()\n genre = fields.CharField(max_length=10)\n\n\nclass Rent(Model):\n user = fields.ForeignKeyField(\"models.User\")\n movie = fields.ForeignKeyField(\"models.Movie\")\n date = fields.DateField(default=date.today)\n\n class Meta:\n unique_together = ((\"user\", \"movie\"),)\n","sub_path":"src/rentamovie/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"34780135","text":"l = [int(input()) for x in range(int(input()))]\nnumber = max(l)\nprimes = [2, 3]\n\ndef is_prime(n):\n if n%2 == 0:\n return False\n if n%3 == 0:\n return False\n for x in range(2, int(n**0.5)+1):\n if n%x == 0:\n return False\n return True\n\nwhile len(primes) < number+1:\n check = primes[-1] + 1\n while not is_prime(check):\n check += 1\n primes.append(check)\n\nfor n in l:\n print(primes[n-1])\n","sub_path":"Timus Online Judge/Correct/1086.py","file_name":"1086.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"284024406","text":"# -*- coding: utf-8 -*-\n\"\"\"\nrefrigeration loads\n\"\"\"\nfrom __future__ import division\nimport numpy as np\nimport pandas as pd\nfrom cea.technologies import heatpumps\nfrom cea.constants import HOURS_IN_YEAR\n\n__author__ = \"Jimeno A. Fonseca\"\n__copyright__ = \"Copyright 2016, Architecture and Building Systems - ETH Zurich\"\n__credits__ = [\"Jimeno A. Fonseca\"]\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Daren Thomas\"\n__email__ = \"cea@arch.ethz.ch\"\n__status__ = \"Production\"\n\n\ndef has_refrigeration_load(bpr):\n \"\"\"\n Checks if building has a hot water system\n\n :param bpr: BuildingPropertiesRow\n :type bpr: cea.demand.building_properties.BuildingPropertiesRow\n :return: True or False\n :rtype: bool\n \"\"\"\n\n if bpr.internal_loads['Qcre_Wm2'] > 0:\n return True\n else:\n return False\n\ndef calc_Qcre_sys(bpr, tsd, schedules):\n\n tsd['Qcre_sys'] = schedules['Qcre'] * bpr.internal_loads['Qcre_Wm2']\n\n def function(Qcre_sys):\n if Qcre_sys > 0:\n Tcref_re_0 = 5\n Tcref_sup_0 = 1\n mcpref = Qcre_sys/(Tcref_re_0-Tcref_sup_0)\n else:\n mcpref = 0.0\n Tcref_re_0 = 0.0\n Tcref_sup_0 = 0.0\n return mcpref, Tcref_re_0, Tcref_sup_0\n\n tsd['mcpcre_sys'], tsd['Tcre_sys_re'], tsd['Tcre_sys_sup'] = np.vectorize(function)(tsd['Qcre_sys'])\n\n return tsd\n\ndef calc_Qref(locator, bpr, tsd):\n \"\"\"\n it calculates final loads\n \"\"\"\n # GET SYSTEMS EFFICIENCIES\n data_systems = pd.read_excel(locator.get_life_cycle_inventory_supply_systems(), \"COOLING\").set_index('code')\n type_system = bpr.supply['type_cs']\n energy_source = data_systems.loc[type_system, 'source_cs']\n\n if energy_source == \"GRID\":\n if bpr.supply['type_cs'] in {'T2', 'T3'}:\n if bpr.supply['type_cs'] == 'T2':\n t_source = (tsd['T_ext'] + 273)\n if bpr.supply['type_cs'] == 'T3':\n t_source = (tsd['T_ext_wetbulb'] + 273)\n\n # heat pump energy\n tsd['E_cre'] = np.vectorize(heatpumps.HP_air_air)(tsd['mcpcre_sys'], (tsd['Tcre_sys_sup'] + 273),\n (tsd['Tcre_sys_re'] + 273), t_source)\n # final to district is zero\n tsd['DC_cre'] = np.zeros(HOURS_IN_YEAR)\n elif energy_source == \"DC\":\n tsd['DC_cre'] = tsd['Qcre_sys']\n tsd['E_cre'] = np.zeros(HOURS_IN_YEAR)\n else:\n tsd['E_cre'] = np.zeros(HOURS_IN_YEAR)\n\n return tsd\n\n","sub_path":"cea/demand/refrigeration_loads.py","file_name":"refrigeration_loads.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"210063973","text":"from smtplib import SMTPException\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.validators import MinLengthValidator\nfrom django.core.mail.message import EmailMultiAlternatives\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\n\nfrom cms.models.pluginmodel import CMSPlugin\n\nfrom common.models import ActivableModel, TimestampedModel\n\n\nclass ContactFormPluginModel(CMSPlugin):\n name_fname = models.CharField(\n _('name of the name field'), max_length=100,\n default=_('Your name')\n )\n name_placeholder = models.CharField(\n _('placeholder of the name field'), max_length=100,\n default=_('Type your name')\n )\n email_fname = models.CharField(\n _('name of the e-mail field'), max_length=100,\n default=_('Your e-mail')\n )\n email_placeholder = models.CharField(\n _('placeholder of the e-mail field'), max_length=100,\n default=_('Type your e-mail')\n )\n message_fname = models.CharField(\n _('name of the message field'), max_length=100,\n default=_('Your message')\n )\n message_placeholder = models.CharField(\n _('placeholder of the message field'), max_length=100,\n default=_('Type your message here')\n )\n button_text = models.CharField(\n _('submit button text'), max_length=100,\n default=_('SEND MESSAGE')\n )\n\n def __str__(self):\n return '(Contact Form)'\n\n\nclass Recipient(ActivableModel, TimestampedModel):\n TO, CC, BCC = ('TO', 'CC', 'BCC')\n R_TYPE_CHOICES = (\n (TO, TO),\n (CC, CC),\n (BCC, BCC)\n )\n plugin = models.ForeignKey(\n verbose_name=_('Contact Form Plugin'),\n to=ContactFormPluginModel, null=True, on_delete=models.SET_NULL,\n related_name='recipients'\n )\n name = models.CharField(_('name'), max_length=100)\n email = models.EmailField(_('e-mail'))\n recipient_type = models.CharField(\n _('recipient type'), max_length=3, choices=R_TYPE_CHOICES, default=TO,\n help_text=_(\n 'Type of the recipient: TO - normal, CC - copy, BCC - hidden copy.'\n )\n )\n\n def __str__(self):\n return (\n f'{self.get_recipient_type_display()}: '\n f'{self.name} <{self.email}>'\n )\n\n\nclass ContactMessage(TimestampedModel):\n STATUS_PENDING, STATUS_SUCCESS, STATUS_ERROR = range(1, 4)\n STATUS_CHOICES = (\n (STATUS_PENDING, _('pending')),\n (STATUS_SUCCESS, _('sent')),\n (STATUS_ERROR, _('error'))\n )\n\n sender_name = models.CharField(\n _('sender name'), max_length=100,\n null=False, blank=False\n )\n sender_email = models.EmailField(\n _('sender e-mail'),\n null=False, blank=False\n )\n message = models.TextField(\n _('message'), null=False, blank=False,\n validators=[MinLengthValidator(20)],\n )\n status = models.SmallIntegerField(\n _('status'), choices=STATUS_CHOICES, default=STATUS_PENDING\n )\n status_msg = models.TextField(\n _('Status message')\n )\n recipients = models.ManyToManyField(\n to=Recipient, verbose_name=_('recipients'),\n blank=False\n )\n\n class Meta:\n verbose_name = _('Contact Message')\n verbose_name_plural = _('Contact Messages')\n\n def __str__(self):\n return _('{status} message from {email}').format(\n status=self.get_status_display(),\n email=self.sender_email\n )\n\n def send(self, do_save=True):\n recipients = self.recipients.all()\n to = [r.email for r in recipients if r.recipient_type == Recipient.TO]\n bcc = [r.email for r in recipients if r.recipient_type == Recipient.BCC]\n cc = [r.email for r in recipients if r.recipient_type == Recipient.CC]\n \n msg_body = render_to_string(\n 'contact/email/contact_message.txt',\n {\n 'project_title': settings.PROJECT_TITLE,\n 'instance': self\n }\n )\n mail = EmailMultiAlternatives(\n subject=settings.CONTACT_MSG_SUBJECT.format(\n PROJECT_TITLE=settings.PROJECT_TITLE\n ),\n body=msg_body,\n to=to, bcc=bcc, cc=cc,\n reply_to=[self.sender_email]\n )\n try:\n mail.send()\n except SMTPException as e:\n self.status = self.STATUS_ERROR\n self.status_msg = _('Sending failed:\\n{}').format(e)\n if do_save:\n self.save()\n return False\n else:\n self.status = self.STATUS_SUCCESS\n self.status_msg = _('Successfully sent.')\n if do_save:\n self.save()\n return True\n","sub_path":"contact/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"510250990","text":"from .views import AboutPage, BasePage, HomePage, ProfilePage, BlogDetailView, BlogListView, BlogCreateView, BlogUpdateView, BlogDeleteView\nfrom django.urls import path, include\nfrom .models import Postblog\nfrom . import views\n\nurlpatterns = [ \n path('blog', BlogListView.as_view(), name='blog'), \n path('blog/new/', BlogCreateView.as_view(model=Postblog, success_url=\"/blog\"), name='blog_add'),\n path('blog//delete/', BlogDeleteView.as_view(model=Postblog, success_url=\"/blog\"), name='blog_delete'),\n path('blog//edit/',BlogUpdateView.as_view(model=Postblog, success_url=\"/blog\"), name='blog_edit'),\n path('blog//', BlogDetailView.as_view(model=Postblog), name='blog_detail'),\n \n path('about', AboutPage.as_view()),\n path('home', HomePage.as_view()),\n path('profile', ProfilePage.as_view()),\n path('', HomePage.as_view()),\n] \n","sub_path":"Superheros/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"165794298","text":"import os, sys, csv\n\n# prevent the creation of \"__pycache__\"\nsys.dont_write_bytecode = True\n\nimport pickle\nimport itertools\nimport numpy as np\nfrom shutil import rmtree\nfrom operator import itemgetter\nfrom PIL import Image, ImageOps\nfrom random import sample, choice\nfrom skimage.metrics import structural_similarity as ssim\n\n####################################################################################\n# CONTROL VARIABLES\n####################################################################################\nMODE = sys.argv[1] if(len(sys.argv) == 3) else \"gan\"\nGENUINE_OR_IMPOSTOR = sys.argv[2] if(len(sys.argv) == 3) else \"G\"\nTRAIN_PERCENTAGE = 0.9 if(MODE != \"gan\") else 1.0\nVALIDATION_PERCENTAGE = 0.1 if(MODE != \"gan\") else 0.0\nTEST_PERCENTAGE = 0.0 if(MODE != \"gan\") else 0.0\nGAN_IMAGE_SIZE = 256\nCNN_LIME_SHAP_IMAGE_SIZE = 256 # 224\nNUM_GOOD_PAIRS = 4 # any value between [12, 432] that is divisible by both 2 and 3\n\ndef get_attributes(image_name): # auxiliary function, retrieves the attributes of a given image\n\n atts = []\n\n with open(\"../../dataset/annotations.csv\", \"r\") as file:\n content = list(csv.reader(file, delimiter = ','))\n header = content[0][1:]\n \n for i in content[1:]:\n if(i[0] == image_name): \n for jdx, j in enumerate(i[1:]):\n if(j == \"1\"): atts.append(header[jdx])\n \n return(atts)\n\ndef initialize_master_ids_dict(subset): # auxiliary function, initializes the dictionary with every image per id (with additional information about the annotations)\n\n master_ids_dict = {}\n\n for i in ids[subset]:\n master_ids_dict.update({i[0]: {}}) # example: master_ids_dict = {C1: {\"atts_1\": [images], \"atts_1_og_size\": 30, \"atts_1_round\": 1, ...}}\n\n for j in i[1]:\n atts = get_attributes(j)\n if(not ((\", \".join(atts)) in master_ids_dict[i[0]])): master_ids_dict[i[0]].update({\", \".join(atts): [j], (\", \".join(atts) + \"_og_size\"): 1, (\", \".join(atts) + \"_round\"): 1})\n else: master_ids_dict[i[0]].update({\", \".join(atts): master_ids_dict[i[0]][\", \".join(atts)] + [j], (\", \".join(atts) + \"_og_size\"): master_ids_dict[i[0]][\", \".join(atts) + \"_og_size\"] + 1})\n\n return(master_ids_dict)\n\ndef get_score(base_id_atts, other_id_atts): # auxiliary function, computes the difference between both sets of attributes\n\n score = 0.0\n\n for idx, att in enumerate(other_id_atts):\n if(base_id_atts[idx] != att):\n\n try: score += ranking_dict[(base_id_atts[idx], att)]\n except: score += ranking_dict[(att, base_id_atts[idx])]\n\n return(score)\n\ndef get_eligible_ids(base_id, base_id_atts): # auxiliary function, retrieves the IDs that can be used to make impostor pairs with \"base_id\"\n\n eligible_ids = []\n \n for k, v in master_ids_dict.items():\n\n if(k == base_id): continue\n\n possible = []\n atts_aux = [i for i in v.keys() if((not (\"_og_size\" in i)) and (not (\"_round\" in i)))]\n \n for i in atts_aux:\n score = get_score(base_id_atts, i.split(\", \"))\n possible.append([k, i])\n\n if(possible == []): continue\n\n if(len(possible) != 1): # this ID has more than one type of attribute configuration\n chosen = [\"\", \"\", 0.0]\n for i in possible:\n if((len(v[i[1]]) / v[i[1] + \"_og_size\"]) > chosen[2]): chosen = [i[0], i[1], (len(v[i[1]]) / v[i[1] + \"_og_size\"])]\n\n else: chosen = [possible[0][0], possible[0][1], (len(v[possible[0][1]]) / v[possible[0][1] + \"_og_size\"])]\n\n eligible_ids.append(chosen)\n\n return(eligible_ids)\n\nif(__name__ == \"__main__\"): \n\n #############################################################################################################\n # GATHER THE IDS AND SOME IMAGES FOR EACH ONE\n #############################################################################################################\n ids_aux = {}\n\n # get every ID\n for i in list(filter(lambda x : x[0] != \".\", os.listdir(\"../../dataset/dataset_one_folder\"))):\n if(not (i.split(\"_\")[0] in ids_aux)): ids_aux.update({i.split(\"_\")[0]: [i]})\n else: ids_aux.update({i.split(\"_\")[0]: ids_aux[i.split(\"_\")[0]] + [i]})\n\n IDS_BASE = []\n for k, v in ids_aux.items(): IDS_BASE.append([k, v])\n\n # separate the IDs into 3 subsets: train, validation and test\n train = sample(IDS_BASE, int(TRAIN_PERCENTAGE * len(IDS_BASE)))\n validation = sample([i for i in IDS_BASE if(not (i in train))], int(VALIDATION_PERCENTAGE * len(IDS_BASE)))\n test = [i for i in IDS_BASE if(not (i in train) and not (i in validation))]\n \n if(MODE == \"gan\"): ids = {\"train_pairs\": train + validation + test, \"validation_pairs\": [], \"test_pairs\": []}\n else: ids = {\"train_pairs\": train, \"validation_pairs\": validation, \"test_pairs\": test}\n \n # load the annotations ranking\n with open(\"attribute_similarity_ranking.csv\", \"r\") as file:\n ranking = list(csv.reader(file, delimiter = ','))[1:]\n\n ranking_dict = {}\n for i in ranking: ranking_dict.update({(i[0], i[1]): float(i[2])})\n\n ##############################################################################################\n # CREATE SOME DIRECTORIES\n ##############################################################################################\n if(os.path.exists(\"../../dataset/data\")): rmtree(\"../../dataset/data\")\n os.makedirs(\"../../dataset/data\")\n\n if((GENUINE_OR_IMPOSTOR != \"G\") or (MODE != \"gan\")): os.makedirs(\"../../dataset/data/train/0\")\n if((GENUINE_OR_IMPOSTOR != \"I\") or (MODE != \"gan\")): os.makedirs(\"../../dataset/data/train/1\")\n\n if(MODE != \"gan\"):\n os.makedirs(\"../../dataset/data/validation/0\")\n os.makedirs(\"../../dataset/data/validation/1\")\n os.makedirs(\"../../dataset/data/test/0\")\n os.makedirs(\"../../dataset/data/test/1\")\n \n #####################################################################################################################################################################################################################################################\n # MAKE THE IMAGE PAIRS\n #####################################################################################################################################################################################################################################################\n for subset in [\"train_pairs\", \"validation_pairs\"]: # for each of the 3 subsets (training, validation and test)\n \n print(\"Preparing the IDs...\")\n\n if(GENUINE_OR_IMPOSTOR != \"G\"):\n\n master_ids_dict = initialize_master_ids_dict(subset)\n\n with open(\"dict.pickle\", \"wb\") as file:\n pickle.dump(master_ids_dict, file, protocol = pickle.HIGHEST_PROTOCOL)\n\n print(\"Done preparing the IDs!\")\n\n for idx, i in enumerate(ids[subset]): # for every ID in that subset\n id_pairs = []\n\n if(len(i[1]) < 4): continue\n NUM_GOOD_PAIRS = 4 if(len(i[1]) == 4) else 204\n \n # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n # if required, create genuine pairs (same ID)\n # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n if(GENUINE_OR_IMPOSTOR != \"I\"):\n\n possible_good_pairs = list(itertools.permutations(i[1], 2))\n ssim_scores = {\"left_left\": [], \"right_right\": []}\n side_that_flips = \"L\"\n\n # for every possible good pair, store it according to the side configuration (L + L, R + R or otherwise) and the corresponding SSIM score\n for j in possible_good_pairs:\n img_a = Image.open(\"../../dataset/dataset_one_folder/\" + j[0]).convert(\"L\")\n img_b = Image.open(\"../../dataset/dataset_one_folder/\" + j[1]).convert(\"L\")\n\n if(((\"L\" in j[0]) and (\"R\" in j[1])) or ((\"R\" in j[0]) and (\"L\" in j[1]))): # this pair has images from different sides\n\n index_image_keep_side = 0 if((side_that_flips == \"L\" and (\"R\" in j[0])) or (side_that_flips == \"R\" and (\"L\" in j[0]))) else 1\n index_image_change_side = 0 if(index_image_keep_side == 1) else 1\n \n img_a = np.asarray(ImageOps.mirror(img_a)) if(index_image_change_side == 0) else np.asarray(img_a)\n img_b = np.asarray(ImageOps.mirror(img_b)) if(index_image_change_side == 1) else np.asarray(img_b)\n\n score = ssim(img_a, img_b, data_range = (img_b.max() - img_b.min()))\n\n if(side_that_flips == \"R\"): ssim_scores.update({\"left_left\": ssim_scores[\"left_left\"] + [(j[0], j[1], score, index_image_change_side)]})\n else: ssim_scores.update({\"right_right\": ssim_scores[\"right_right\"] + [(j[0], j[1], score, index_image_change_side)]})\n\n current_flip = \"R\" if(side_that_flips == \"L\") else \"L\"\n \n else: # this pair has images from the same side\n\n img_a = np.asarray(img_a)\n img_b = np.asarray(img_b)\n\n score = ssim(img_a, img_b, data_range = (img_b.max() - img_b.min()))\n\n # store this pair and its SSIM score\n if((\"L\" in j[0]) and (\"L\" in j[1])): ssim_scores.update({\"left_left\": ssim_scores[\"left_left\"] + [(j[0], j[1], score)]})\n elif((\"R\" in j[0]) and (\"R\" in j[1])): ssim_scores.update({\"right_right\": ssim_scores[\"right_right\"] + [(j[0], j[1], score)]})\n \n # sort the pairs by their SSIM scores (ascending order)\n ssim_scores[\"left_left\"] = sorted(ssim_scores[\"left_left\"], key = lambda x : x[2])\n ssim_scores[\"right_right\"] = sorted(ssim_scores[\"right_right\"], key = lambda x : x[2])\n\n # choose equidistant pairs (to ensure an even distribution of side configurations and scores)\n l_l_chosen = list(itemgetter(*(np.linspace(0, len(ssim_scores[\"left_left\"]) - 1, num = (NUM_GOOD_PAIRS // 2)).astype(int).tolist()))(ssim_scores[\"left_left\"]))\n r_r_chosen = list(itemgetter(*(np.linspace(0, len(ssim_scores[\"right_right\"]) - 1, num = (NUM_GOOD_PAIRS // 2)).astype(int).tolist()))(ssim_scores[\"right_right\"]))\n \n # bring it all together\n good_pairs = l_l_chosen + r_r_chosen\n\n id_pairs = good_pairs\n\n # ----------------------------------------------------------------------------------------------------------------------------------------------\n # if required, create impostor pairs (different IDs)\n # ----------------------------------------------------------------------------------------------------------------------------------------------\n if(GENUINE_OR_IMPOSTOR != \"G\"):\n\n bad_pairs = []\n current_image_index = 0\n \n count = 0\n while(count < NUM_GOOD_PAIRS):\n \n # -------------------------------------------------------\n # choose an image from the base ID and get its attributes\n # -------------------------------------------------------\n chosen_base_id_image = i[1][current_image_index]\n\n # get the attributes of the base ID's image\n atts = get_attributes(chosen_base_id_image)\n\n # --------------------------------------------------------------------------------------------------------------------------------------\n # get every ID that can be matched with this ID to create an impostor pair with image at index \"current_image_index\"\n # --------------------------------------------------------------------------------------------------------------------------------------\n eligible_ids = get_eligible_ids(i[0], atts)\n chosen_id = choice(sorted(eligible_ids, key = lambda x : x[2], reverse = True))\n \n try:\n base_id_image_side = \"L\" if(\"L\" in chosen_base_id_image) else \"R\"\n other_id_image = list(filter(lambda x : (\"_\" + base_id_image_side + \"_\") in x, (master_ids_dict[chosen_id[0]][chosen_id[1]]))).pop()\n \n # there are no images left to create bad pairs with\n except Exception as e:\n with open(\"dict.pickle\", \"rb\") as file:\n master_ids_dict = pickle.load(file)\n continue\n\n # update the image counter\n current_image_index = 0 if(current_image_index == (len(i[1]) - 1)) else (current_image_index + 1)\n\n # ----------------------------------------------------------------------------------------\n # save the generated pair\n # ----------------------------------------------------------------------------------------\n pair = (chosen_base_id_image, other_id_image, get_score(atts, (chosen_id[1].split(\", \"))))\n\n bad_pairs.append(pair)\n count += 1\n\n # save all the pairs we've created\n for j in bad_pairs: id_pairs.append(j)\n \n print(\"ID \" + str(idx + 1) + \"/\" + str(len(ids[subset])))\n \n # -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n # actually make the image pairs\n # -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n for j in id_pairs:\n \n # wrong image pairs\n if(((j[0].split(\"_\")[0]) != (j[1].split(\"_\")[0]))): dir_name = \"0\"\n\n # right image pairs\n else: dir_name = \"1\"\n\n # concatenate the images depthwise\n img1 = Image.open(\"../../dataset/dataset_one_folder/\" + j[0])\n img2 = Image.open(\"../../dataset/dataset_one_folder/\" + j[1])\n \n flipped = \"\"\n if(len(j) == 4): # one of the images needs to be flipped\n if(j[3] == 0): \n img1 = ImageOps.mirror(img1)\n flipped = \"+flipped0\"\n else: \n img2 = ImageOps.mirror(img2)\n flipped = \"+flipped1\"\n\n # build the final filename\n if(dir_name == \"0\"): final_name = \"../../dataset/data/\" + subset.split(\"_\")[0] + \"/\" + dir_name + \"/\" + j[0].replace(\".jpg\", \"\") + \"_+_\" + j[1].replace(\".jpg\", \"+score\" + str(j[2]) + flipped)\n else: final_name = \"../../dataset/data/\" + subset.split(\"_\")[0] + \"/\" + dir_name + \"/\" + j[0].replace(\".jpg\", \"\") + \"_+_\" + j[1].replace(\".jpg\", \"+ssim-score\" + str(round(j[2], 2)) + flipped)\n \n if(MODE != \"cnn_lime_shap\"): \n # build the pair\n pair = np.dstack((np.asarray(img1), np.asarray(img2)))\n \n # save the pair\n np.save(final_name + \".npy\", pair)\n\n else: \n # build the pair\n pair = np.zeros((CNN_LIME_SHAP_IMAGE_SIZE, CNN_LIME_SHAP_IMAGE_SIZE, 3))\n pair[\n (CNN_LIME_SHAP_IMAGE_SIZE // 4):((CNN_LIME_SHAP_IMAGE_SIZE // 4) + (CNN_LIME_SHAP_IMAGE_SIZE // 2)), \n :, \n :\n ] = np.column_stack((np.asarray(img1.resize((CNN_LIME_SHAP_IMAGE_SIZE // 2, CNN_LIME_SHAP_IMAGE_SIZE // 2), Image.LANCZOS)), np.asarray(img2.resize((CNN_LIME_SHAP_IMAGE_SIZE // 2, CNN_LIME_SHAP_IMAGE_SIZE // 2), Image.LANCZOS))))\n \n # save the pair\n Image.fromarray(pair.astype(np.uint8)).save(final_name + \".jpg\")\n \n # the GAN only needs training data\n if(MODE == \"gan\"): break\n \n if(os.path.exists(\"dict.pickle\")): os.remove(\"dict.pickle\")","sub_path":"learning/prepare_dataset/dataset_make_pairs_and_move_to_folders.py","file_name":"dataset_make_pairs_and_move_to_folders.py","file_ext":"py","file_size_in_byte":16905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"283398287","text":"#!/opt/dionaea/bin/python3\nimport sqlite3\nimport sys\nfrom datetime import datetime\n\n#\n# Statistics script for Dionaea\n# Mimics output of InfoSanity's submissions2stats.py script written for Nepenthes\n#\n# Author: Andrew Waite\n# Date: 2009-11-10\n#\n# Patch to mitigate errors with both 0 submissions and/or statistics for < 1 day.\n# Provided by Miguel Jacq (www.mig5.net)\n# Date: 2010-06-05\n#\n\n#\n#Print header\nsys.stdout.write( '\\nStatistics engine written by Andrew Waite - www.infosanity.co.uk\\n\\n')\n\n#\n#Create SQLite connection\nconn = sqlite3.connect('/opt/dionaea/var/dionaea/dionaea.sqlite')\nc = conn.cursor()\n\n#\n#Calculate number of binary submissions\nc.execute('SELECT count() FROM downloads')\nfor row in c:\n\tnumSubmissions = row[0]\nsys.stdout.write( \"Number of submissions: %i \\n\" %(numSubmissions))\n\n#\n#Calculate number of unique submissions\nc.execute('SELECT download_md5_hash FROM downloads GROUP BY download_md5_hash')\nnumSamples = 0\nfor row in c:\n\tnumSamples += 1\nsys.stdout.write( \"Number of unique samples: %i\\n\" %(numSamples)) \n\n#\n#Calculate unique soure IP addresses\nc.execute('SELECT connections.remote_host FROM connections, downloads WHERE downloads.connection = connections.connection GROUP BY connections.remote_host')\nnumSourceIPs = 0\nfor row in c:\n\tnumSourceIPs += 1\nsys.stdout.write( \"Number of unique source IPs: %i\\n\" %(numSourceIPs))\n\n#\n#Find first sample date\nif numSubmissions > 0:\n\tc.execute('SELECT connections.connection_timestamp FROM connections, downloads WHERE downloads.connection = connections.connection ORDER BY connections.connection_timestamp LIMIT 1')\n\tfor row in c:\n\t\tfirstSampleTimestamp = row[0]\n\tsys.stdout.write(\"\\nFirst sample seen: %s\\n\" %(datetime.fromtimestamp(firstSampleTimestamp)))\n\n\t#\n\t#Find last sample date\n\tc.execute('SELECT connections.connection_timestamp FROM connections, downloads WHERE downloads.connection = connections.connection ORDER BY connections.connection_timestamp DESC LIMIT 1')\n\tfor row in c:\n\t\tlastSampleTimestamp = row[0]\n\tsys.stdout.write(\"Last sample seen: %s\\n\" %(datetime.fromtimestamp(lastSampleTimestamp)))\n\n\t#\n\t#Determine duration of uptime\n\tuptime = datetime.fromtimestamp(lastSampleTimestamp) - datetime.fromtimestamp(firstSampleTimestamp)\n\tsys.stdout.write(\"System Uptime: %s\\n\" %(uptime))\n\n\t#\n\t#Avg downloads per day\n\tif uptime.days >= 1:\n\t\taverageDownloads = numSubmissions / uptime.days\n\t\tsys.stdout.write(\"Average daily submissions: %s\\n\" %(averageDownloads))\n\n\t#\n\t#List most recent downloads\n\tsys.stdout.write(\"\\nMost recent submissions:\\n\")\n\tc.execute('SELECT connections.connection_timestamp, connections.remote_host, downloads.download_url, downloads.download_md5_hash FROM downloads, connections WHERE connections.connection = downloads.connection ORDER BY connections.connection_timestamp desc limit 5')\n\tfor row in c:\n\t\tsys.stdout.write(\"\\t%s, %s, %s, %s\\n\" %(datetime.fromtimestamp(row[0]), row[1], row[2], row[3]))\n\n\n# Original Nepenthes script output\n#\n#Statistics engine written by Andrew Waite - www.InfoSanity.co.uk\n#\n#Number of submissions: 4189\n#Number of unique samples: 1189\n#Number of unique source IPs: 2024\n#\n#First sample seen on 2008-05-09\n#Last sample seen on 2009-10-31\n#Days running: 540\n#Average daily submissions: 7\n#\n#Most recent submissions:\n#\t\n","sub_path":"Dionaea/0.6/dionaea-scripts/mimic-nepstats.py","file_name":"mimic-nepstats.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"78009006","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nimport sys\n\nclass MyWindow(QMainWindow):\n def __init__(self):\n super(MyWindow,self).__init__()\n self.initUI()\n\n def initUI(self):\n self.label = QtWidgets.QLabel(self)\n self.label.setText(\"test\")\n self.b1 = QtWidgets.QPushButton(self)\n self.b1.move(50,50)\n self.b1.setText('Click Me')\n self.b1.clicked.connect(self.clicked)\n\n def clicked(self):\n self.label.setText('')\n self.update()\n\n def update(self):\n self.label.adjustSize()\n\ndef window():\n app = QApplication(sys.argv)\n win = MyWindow()\n win.setGeometry(200,200,300,200)\n\n \n\n win.show()\n sys.exit(app.exec_())\nwindow()\n","sub_path":"gui/OLD/giu2.py","file_name":"giu2.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"584487658","text":"#https://www.youtube.com/watch?v=bP6OyB-tC_c&t=9s로부터 게임 진행 아이디어 착안\r\n\r\nimport pygame, random, time\r\n\r\ndef initgame() : #게임기본설정\r\n global f, list, listlen, background, white, green, point, starttime, paper, font, wallpaper\r\n\r\n pygame.init()\r\n\r\n f = open('text.txt', 'r')\r\n list = f.readlines()\r\n listlen = len(list)\r\n\r\n background = (200, 200, 255)\r\n white = (255, 255, 255)\r\n green = (30, 150, 30)\r\n point = 0\r\n\r\n paper = pygame.display.set_mode((1000, 700))\r\n pygame.display.set_caption(\"리듬을 타자\")\r\n font = pygame.font.SysFont(\"Agency FB\", 50)\r\n wallpaper = pygame.image.load('background.png')\r\n\r\n\r\ndef gamestart(): #게임 시작화면\r\n global mainpaper, startpaper\r\n mainpaper = pygame.image.load('main.png')\r\n startpaper = pygame.image.load('start.png')\r\n\r\n check = True\r\n\r\n paper.fill(background)\r\n paper.blit(mainpaper, (0, 0))\r\n pygame.display.update()\r\n\r\n while check:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: # 종료 버튼 누르면 게임 종료\r\n pygame.quit()\r\n quit()\r\n\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == 13: # 엔터키 누르면 화면 넘어가기\r\n check = False\r\n\r\n paper.fill(background)\r\n paper.blit(startpaper, (0, 0))\r\n pygame.display.update()\r\n\r\n while not check:\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: # 종료 버튼 누르면 게임 종료\r\n pygame.quit()\r\n quit()\r\n\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == 13: # 엔터키 누르면 화면 넘어가기\r\n check = True\r\n\r\n return check\r\n\r\ndef maingame(): #메인게임 진행\r\n global inputline, point, starttime\r\n\r\n initgame()\r\n\r\n if gamestart():\r\n\r\n pygame.mixer.music.load('music.mp3') #노래 재생\r\n pygame.mixer.music.play()\r\n starttime = time.time() + 0.5 #노래 재생 지연 보정\r\n\r\n\r\n fileopen()\r\n changeline(True)\r\n\r\n while True:\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: # 종료 버튼 누르면 게임 종료\r\n pygame.quit()\r\n quit()\r\n\r\n elif event.type == pygame.KEYDOWN:\r\n\r\n if event.key == 32: # 스페이스바 예외 처리\r\n inputline += ' '\r\n else:\r\n inputline += pygame.key.name(event.key) # 누른 키에 해당하는 알파펫 입력문장에 추가\r\n\r\n if chosenline.startswith(inputline): # 입력문장과 선택문장 일치시 점수 올리고 문장 교체\r\n if chosenline == inputline:\r\n point += len(inputline)\r\n changeline(True)\r\n else:\r\n inputline = '' # 입력 문장과 선택문장 일치하지 않으면 초기화\r\n changeline(False)\r\n\r\n #점수와 입력 문장 띄우기\r\n pointCaption = font.render(str(point), True, green)\r\n paper.blit(pointCaption, (860, 135))\r\n\r\n input = font.render(str(inputline), True, green)\r\n paper.blit(input, (190, 570))\r\n\r\n pygame.display.update()\r\n\r\ndef fileopen(): # txt파일 열고 문장단위로 끊어 읽기\r\n for i in range(listlen):\r\n list[i] = list[i].split('=')\r\n list[i][1] = list[i][1].lower()\r\n for i in range(listlen - 1):\r\n list[i][1] = list[i][1][:-1]\r\n\r\n list.insert(0,[-9999999,'test'])\r\n list.append([999999999999,'last'])\r\n\r\ndef changeline(change): #문장 교체\r\n\r\n global chosenline, pressedWord, text, pointCaption, timesec, inputline, chosenwords,starttime\r\n\r\n # 화면 초기화\r\n paper.fill(background)\r\n paper.blit(wallpaper, (0, 0))\r\n\r\n inputline = '' #입력 글자 초기화\r\n\r\n timesec = time.time() - starttime\r\n chosenline = list[0][1]\r\n\r\n if(change) : # 문장 맞췄을 때 만 문장 교체 및 삭제\r\n\r\n print(timesec)\r\n\r\n if int(list[0][0]) <= timesec:\r\n if int(list[1][0]) <= timesec: # 시간초과시 게임종료\r\n gameend()\r\n else:\r\n del list[0] # 제 시간 안에 입력시 삭제\r\n\r\n if list[0][1] == 'last': # 모두 입력하여 리스트가 비었으면 성공\r\n gamesuccess()\r\n return True\r\n chosenline = list[0][1]\r\n\r\n chosenwords = chosenline.split(' ') #해당가사 띄어쓰기 단위로 잘라서 랜덤으로 띄우기\r\n for i in range(len(chosenwords)):\r\n text = font.render(chosenwords[i], True, white)\r\n paper.blit(text, (random.randint(100, 600), random.randint(100, 400)))\r\n\r\n\r\ndef gameend(): #시간 초과시 게임 종료\r\n endpaper = pygame.image.load('end.png')\r\n\r\n paper.fill(background)\r\n paper.blit(endpaper, (0, 0))\r\n pygame.mixer.music.stop()\r\n\r\n pygame.display.update()\r\n\r\n while(True):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: # 종료 버튼 누르면 게임 종료\r\n pygame.quit()\r\n quit()\r\n\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == 13: # 엔터누르면 다시시작\r\n maingame()\r\n return True\r\n\r\ndef gamesuccess(): #게임 성공시 점수 띄우고 게임종료\r\n\r\n successpaper = pygame.image.load('success.png')\r\n\r\n paper.fill(background)\r\n paper.blit(successpaper, (0, 0))\r\n pygame.mixer.music.stop()\r\n\r\n point_result = font.render(str(point), True, white)\r\n paper.blit(point_result, (490, 300))\r\n pygame.display.update()\r\n\r\n\r\n while(True):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: # 종료 버튼 누르면 게임 종료\r\n pygame.quit()\r\n quit()\r\n\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == 13: #enter 누르면 다시 시작\r\n maingame()\r\n return True\r\n\r\n# 게임 시작\r\nmaingame()\r\n","sub_path":"rythm taja.py","file_name":"rythm taja.py","file_ext":"py","file_size_in_byte":6362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"514444529","text":"# -*- coding:utf-8 -*-\n\"\"\"\nIndex view\nauthor: xindervella\n\"\"\"\n\nimport random\nfrom django.contrib.auth.models import User\nfrom django.core.context_processors import csrf\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom book.models import UserDetail, Room, Hotel\n\n\ndef index(request):\n if request.method == 'GET':\n if request.user.is_authenticated():\n user = User.objects.get(username=request.user)\n try:\n user_detail = UserDetail.objects.get(user=user)\n except ObjectDoesNotExist:\n user_detail = None\n else:\n user = None\n user_detail = None\n\n index_dict = {}\n hotel_set = Hotel.objects.all()\n hotel_number = {}\n cities = list(set([hotel.city for hotel in hotel_set]))\n cities = [cities[i] for i in random.sample(xrange(len(cities)), 2)]\n\n for city in cities:\n hotels = {}\n for hotel in Hotel.objects.filter(city=city).order_by('up')[:6]:\n try:\n room_1 = [Room.objects.filter(hotel=hotel).order_by('price')[0]]\n except IndexError:\n room_1 = []\n try:\n room_2 = [Room.objects.filter(hotel=hotel, people_limit=1)[0]]\n except IndexError:\n room_2 = []\n try:\n room_3 = [Room.objects.filter(hotel=hotel, people_limit=2)[0]]\n except IndexError:\n room_3 = []\n hotels[hotel] = room_1 + room_2 + room_3\n # print city\n index_dict[city] = hotels\n # print index_dict\n hotel_number[city] = len(Hotel.objects.filter(city=city))\n\n data = {\n 'url': 'index',\n 'user': user,\n 'user_detail': user_detail,\n 'index_dict': index_dict,\n 'hotel_number': hotel_number,\n }\n data.update(csrf(request))\n return render_to_response('index.html', data)\n else:\n return HttpResponse(status=404)","sub_path":"book/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"36277264","text":"#!/usr/bin/python\n\nimport os, sys\nfrom time import strftime\nfrom datetime import datetime\nfrom cassandra.cluster import Cluster\n\n# connect to database\ndb_configs = os.getenv('DATABASE_PORT_9042_TCP').replace('tcp://', '')\nHOST, PORT = db_configs.split(':')\ncluster = Cluster([HOST], port=PORT)\nsession = cluster.connect('wolf')\n\nfor t in sys.stdin:\n f = t.split('\\t')\n pair = f[0].strip()\n issued_at = f[1].strip()\n bid = f[2].strip()\n ask = f[3].strip()\n\n utc_day = datetime.fromtimestamp(float(issued_at)).strftime('%Y-%m-%d')\n utc_hour = datetime.fromtimestamp(float(issued_at)).strftime('%Y-%m-%d %H:%M:%S+0000')\n\n q = \"INSERT INTO ticks_avg_s (pair_day,issued_at,bid,ask) VALUES (\"\n q = q + \"'\" + pair + \":\" + utc_day + \"',\"\n q = q + \"'\" + utc_hour + \"',\"\n q = q + \"\" + bid + \",\"\n q = q + \"\" + ask + \") USING TTL 10800\"\n\n m = \"pushing \" + pair + \" \"\n m = m + utc_hour + \" \"\n m = m + \"to key \" + pair + \":\" + utc_day\n\n print(m)\n session.execute(q)\n\n\ncluster.shutdown()\n","sub_path":"data.aggregator.batch/src/2.aggregate.py","file_name":"2.aggregate.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"401864797","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# @Filename: step15_multiprocessing_county_level_event_list\n# @Date: 2018-12-02\n# @Author: Mark Wang\n# @Email: wangyouan@gamil.com\n\n\n\"\"\"\npython3 -m generate_vars_20181120.step15_multiprocessing_county_level_event_list\n\"\"\"\n\nimport os\nimport multiprocessing\n\nimport pandas as pd\nfrom pandas import DataFrame\n\nfrom constants import Constants as const\n\nif __name__ == '__main__':\n data_df: DataFrame = pd.read_pickle(\n os.path.join(const.TEMP_PATH, '20181005_third_part_concise_3018_append_fips.pkl'))\n branch_bank_df: DataFrame = pd.read_pickle(\n os.path.join(const.TEMP_PATH, '20181202_bhc_commercial_branch_link_76_16.pkl'))\n branch_bank_df.loc[:, const.FIPS] = branch_bank_df[const.FIPS].apply(int)\n\n\n def acquire_row_info_list(row):\n acq_9001: str = row[const.ACQ_9001]\n tar_9001: str = row[const.TAR_9001]\n common_county_event = pd.DataFrame(columns=[const.FIPS, const.YEAR, const.COMMERCIAL_RSSD9364])\n\n if acq_9001.isdigit():\n acq_9001 = int(acq_9001)\n else:\n return common_county_event\n\n if tar_9001.isdigit():\n tar_9001 = int(tar_9001)\n else:\n return common_county_event\n\n year = int(row[const.YEAR_MERGE])\n\n current_branch_df = branch_bank_df[branch_bank_df[const.YEAR] == year]\n\n acq_branch = current_branch_df[current_branch_df[const.RSSD9001] == acq_9001]\n tar_branch = current_branch_df[current_branch_df[const.RSSD9001] == tar_9001]\n\n if tar_branch.empty or acq_branch.empty:\n return common_county_event\n\n co_exist_county = acq_branch[acq_branch[const.FIPS].isin(set(tar_branch[const.FIPS]))]\n if co_exist_county.empty:\n return common_county_event\n\n fips_list = list(set(co_exist_county[const.FIPS]))\n for fips in fips_list:\n common_county_event = common_county_event.append({const.FIPS: fips, const.YEAR: year,\n const.COMMERCIAL_RSSD9364: acq_9001}, ignore_index=True)\n common_county_event = common_county_event.append({const.FIPS: fips, const.YEAR: year,\n const.COMMERCIAL_RSSD9364: tar_9001}, ignore_index=True)\n\n return common_county_event\n\n\n row_list = [i for _, i in data_df.iterrows()]\n\n pool = multiprocessing.Pool(38)\n result_dfs = pool.map(acquire_row_info_list, row_list)\n event_df: DataFrame = pd.concat(result_dfs, ignore_index=True, sort=False)\n # event_df.to_pickle(os.path.join(const.TEMP_PATH, '20181202_common_county_event_rssd9001.pkl')) matched with 9001\n # event_df.to_pickle(os.path.join(const.TEMP_PATH, '20181202_common_county_event_rssd.pkl')) matched with 9364\n\n # merged version\n event_df.to_pickle(os.path.join(const.TEMP_PATH, '20181202_common_county_event.pkl'))\n","sub_path":"generate_vars_20181120/step15_multiprocessing_county_level_event_list.py","file_name":"step15_multiprocessing_county_level_event_list.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"18852307","text":"from faker import Factory\r\nfrom faker import Faker\r\nimport sys\r\nimport os\r\nimport random\r\nimport time\r\n\r\nfake = Faker()\r\nfake = Factory.create('pt_BR')\r\n\r\ndef main():\r\n\r\n print(\"Programa Iniciado\")\r\n time.sleep(2)\r\n gerarArquivo()\r\n\r\ndef gerarArquivo():\r\n\r\n arquivoSql = open(\"geradorproduto.sql\", 'wt')\r\n arquivoSql.write(getScriptProduto())\r\n\r\n arquivoSql.close()\r\n\r\n print(\"Arquivo gerado com sucesso!\")\r\n input()\r\n\r\n return;\r\n \r\ndef getScriptProduto():\r\n\r\n\tsql='INSERT INTO produto (idproduto, nome, idmedida, idmarca, unidade, valido) VALUES\\n'\r\n\tidproduto=1;\r\n\tcont=1\r\n\tfor i in range(1,100001):\r\n\t\tnome= ['Banana', 'Maçã', 'Pera','Arroz', 'Feijão','Suco de Caju','Milho', 'Miojo', 'Queijo',\r\n 'Requijão', 'Vinagre', 'Sal Grosso', 'Pão Fracês', 'Suco de Macarujá','Jiló', 'Refrigerante']\r\n\t\tindexNomeLista = random.randint(0, len(nome)-1) \t\t\r\n\t\tidcompra=random.randint(1, 10)\r\n\t\tpreco=round(random.uniform(5, 100),2)\r\n\t\tidmedida=random.randint(1, 10)\r\n\t\tidmarca=random.randint(1, 10)\r\n\t\tif cont!=100000:\r\n\t\t\tsql += \"(\"+str(idproduto)+\",'\"+nome[indexNomeLista]+\"',\"+str(idmedida)+\",\"+str(idmarca)+\",1,1),\\n\"\r\n\t\telse:\r\n\t\t\tsql += \"(\"+str(idproduto)+\",'\"+nome[indexNomeLista]+\"',\"+str(idmedida)+\",\"+str(idmarca)+\",1,1);\"\t\t\t\t\r\n\t\tidproduto+=1\r\n\t\tcont+=1\r\n\t\r\n\treturn sql \r\n\r\n\r\nif (__name__ == '__main__'):\r\n main()\r\n","sub_path":"Scripts_geracao_de_dados/geradorproduto.py","file_name":"geradorproduto.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"400631002","text":"\r\nimport cupy as cp\r\n#the network is composed of node and edge,node denotes the operation between variables,such as dot,add,minus...,and edge represents the connection between nodes.for example,given node1(+),below graph decribes: var1+var2\r\n# output\r\n# \\\r\n# \\ (edge)\r\n# \\\r\n# \\\r\n# ( + ) ->node1\r\n# | \\\r\n# | \\\r\n#(variable1) (variable2)\r\n\r\n\r\n\r\n\r\nclass Node(object):\r\n '''\r\n basic class for layers in network\r\n '''\r\n def __init__(self,outbound_layers=None,shape=None,output_tensor=None,name=None):\r\n '''\r\n :param inbound_edges:list,collections of all input edges\r\n '''\r\n\r\n self.inbound_layers=[]\r\n\r\n self.outbound_layers=[] if outbound_layers is None else list(outbound_layers)\r\n\r\n self.output_tensor=output_tensor\r\n #current node's name\r\n self.shape=shape\r\n\r\n self.require_grads=True\r\n #store the grads from next layer\r\n\r\n self.grads=None\r\n\r\n self.name=name\r\n\r\n\r\n\r\n def forward(self):\r\n pass\r\n\r\n\r\n def backward(self):\r\n pass\r\n\r\n\r\n def __add__(self, other):\r\n return add(self, other)\r\n\r\n\r\n def __sub__(self, other):\r\n return subtract(self,other)\r\n\r\n\r\n def __matmul__(self, other):\r\n return matmul(self, other)\r\n\r\n\r\n def __mul__(self, other):\r\n return multiply(self, other)\r\n\r\n\r\n def __neg__(self):\r\n return negative(self)\r\n\r\n\r\n # @property\r\n # def value(self):\r\n # return self.output_tensor\r\n\r\n\r\n\r\nclass Constant(Node):\r\n def __init__(self,output_tensor,name='constant'):\r\n Node.__init__(self)\r\n self.output_tensor=cp.array(output_tensor)\r\n self.name=name\r\n\r\n\r\n\r\n\r\n\r\nclass Variable(Node):\r\n def __init__(self,initial_output_tensor=None,shape=None,name='variable'):\r\n Node.__init__(self,shape=shape)\r\n if initial_output_tensor is None:\r\n self.output_tensor=initial_output_tensor\r\n else:\r\n self.output_tensor=cp.array(initial_output_tensor)\r\n self.shape=self.output_tensor.shape\r\n self.name=name\r\n\r\n\r\n @property\r\n def get_value(self):\r\n return self.output_tensor\r\n\r\n#for nodes\r\ndef add(a,b,outputs=None):\r\n if outputs is None:\r\n return Variable(initial_output_tensor=a.output_tensor+b.output_tensor)\r\n else:\r\n outputs.output_tensor=a.output_tensor+b.output_tensor\r\n return outputs\r\n\r\n\r\ndef negative(a,outputs=None):\r\n if outputs is None:\r\n return Variable(initial_output_tensor=-a.output_tensor)\r\n else:\r\n outputs.output_tensor=-a.output_tensor\r\n return outputs\r\n\r\n\r\ndef subtract(a,b,outputs=None):\r\n if outputs is None:\r\n return Variable(initial_output_tensor=a.output_tensor - b.output_tensor)\r\n else:\r\n outputs.output_tensor = a.output_tensor - b.output_tensor\r\n return outputs\r\n\r\n\r\n\r\ndef multiply(a,b,outputs=None):\r\n if outputs is None:\r\n return Variable(initial_output_tensor=a.output_tensor * b.output_tensor)\r\n else:\r\n outputs.output_tensor = a.output_tensor * b.output_tensor\r\n return outputs\r\n\r\n\r\n\r\n\r\ndef matmul(a, b, outputs=None):\r\n if outputs is None:\r\n return Variable(initial_output_tensor=cp.dot(a.output_tensor,b.output_tensor))\r\n else:\r\n outputs.output_tensor = cp.dot(a.output_tensor, b.output_tensor)\r\n return outputs\r\n\r\n\r\n\r\n\r\nclass Layer(object):\r\n def __init__(self,inbound_layers=None, outbound_layers=None,input_shape=None,output_shape=None,input_tensor=None,output_tensor=None,variables=None):\r\n\r\n self.inbound_layers = [] if inbound_layers is None else list(inbound_layers)\r\n\r\n self.outbound_layers = [] if outbound_layers is None else list(outbound_layers)\r\n\r\n self.input_shape=input_shape\r\n\r\n self.output_shape=output_shape\r\n\r\n self.input_tensor=input_tensor\r\n\r\n self.output_tensor=output_tensor\r\n\r\n self.variables=[] if variables is None else list(variables)\r\n #record how many other layers require this layer\r\n self.counts=0\r\n self.require_grads=True\r\n self.grads=None\r\n\r\n\r\n def __call__(self, inbound_layer):\r\n # inbound_node.counts+=1\r\n if not isinstance(inbound_layer,(list,tuple)):\r\n inbound_layer=[inbound_layer]\r\n for layer in inbound_layer:\r\n self.inbound_layers.append(layer)\r\n self.input_shape=layer.output_shape\r\n layer.outbound_layers.append(self)\r\n # for var in self.variables:\r\n # if var.require_grads:\r\n # var.grads=cp.zeros_like(var.output_tensor)\r\n\r\n\r\n\r\n def connect(self,inbound_layer):\r\n if inbound_layer is None:\r\n pass\r\n else:\r\n self.inbound_layers.append(inbound_layer)\r\n self.input_shape = inbound_layer.output_shape\r\n inbound_layer.outbound_layers.append(self)\r\n # for var in self.variables:\r\n # if var.require_grads:\r\n # var.grads=cp.zeros_like(var.output_tensor)\r\n\r\n\r\n def _initial_params(self,*args):\r\n pass\r\n\r\n\r\n def compute_output_shape(self,*args):\r\n pass\r\n\r\n\r\n def forward(self,is_training):\r\n for layer in self.outbound_layers:\r\n layer.input_tensor = self.output_tensor\r\n if is_training:\r\n if self.require_grads:\r\n self.grads=cp.zeros_like(self.output_tensor)\r\n\r\n\r\n\r\n def backward(self):\r\n raise NotImplementedError\r\n\r\n\r\n def __add__(self, other):\r\n return Add()([self, other])\r\n\r\n\r\n def __sub__(self, other):\r\n return Add()([self, Negative(other)])\r\n\r\n\r\n\r\n def __matmul__(self, other):\r\n return Matmul()([self, other])\r\n\r\n\r\n def __mul__(self, other):\r\n return Multiply()([self, other])\r\n\r\n\r\n def __neg__(self):\r\n return Negative()(self)\r\n\r\n\r\n\r\n\r\nclass Input(Layer):\r\n def __init__(self,shape,value=None):\r\n super(Input,self).__init__()\r\n self.input_shape=shape\r\n self.output_shape=self.input_shape\r\n self.output_tensor=value\r\n self.require_grads=False\r\n\r\n\r\n\r\n def connect(self,prev_layer):\r\n if prev_layer is not None:\r\n self.input_shape=prev_layer.output_shape\r\n self.output_shape=self.input_shape\r\n\r\n\r\n\r\n\r\n def forward(self,is_training):\r\n self.output_tensor=self.input_tensor\r\n super(Input,self).forward(is_training)\r\n\r\n\r\n\r\n def backward(self):\r\n pass\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass Operation(Layer):\r\n\r\n def __call__(self,inbounds):\r\n Layer.__init__(self)\r\n for inbound in inbounds:\r\n # inbound.counts+=1\r\n inbound.outbound_layers.append(self)\r\n self.inbound_layers.append(inbound)\r\n self.variables=self.inbound_layers\r\n return self\r\n\r\n\r\n\r\n\r\n#for layer\r\nclass Add(Operation):\r\n\r\n\r\n\r\n def __call__(self, inbounds):\r\n super(Add,self).__call__(inbounds)\r\n x,y=inbounds\r\n shape_a=x.output_shape\r\n shape_b=y.output_shape\r\n assert len(shape_a)==len(shape_b)\r\n output_shape=tuple()\r\n for a,b in zip(shape_a[1:],shape_b[1:]):\r\n output_shape+=(max(a,b),)\r\n output_shape=(None,)+output_shape\r\n self.output_shape=output_shape\r\n return self\r\n\r\n\r\n\r\n\r\n\r\n def forward(self,is_training=True):\r\n x,y=self.variables\r\n self.output_tensor=cp.add(x.output_tensor,y.output_tensor)\r\n if is_training:\r\n if x.require_grads:\r\n x.grads=cp.zeros_like(x.output_tensor)\r\n if y.require_grads:\r\n y.grads=cp.zeros_like(x.output_tensor)\r\n super().forward(is_training)\r\n\r\n\r\n\r\n\r\n def backward(self):\r\n x,y=[node for node in self.variables]\r\n grad_x,grad_y=self.grads,self.grads\r\n while grad_x.ndim >x.output_tensor.ndim:\r\n grad_x=cp.sum(grad_x,axis=0)\r\n for axis,size in enumerate(x.output_tensor.shape):\r\n #in case of broadcast,for example, when forward propagation,x shape:(1,3,3,3),y shape:(3,3,3,3),x+y shape:(3,3,3,3),so grad shape does,and grad_x shape should be (1,3,3,3),thus needs to sum axis.\r\n if size==1:\r\n grad_x=cp.sum(grad_x,axis=axis,keepdims=True)\r\n\r\n while grad_y.ndim >y.output_tensor.ndim:\r\n grad_y=cp.sum(grad_y,axis=0)\r\n for axis,size in enumerate(y.output_tensor.shape):\r\n #in case of broadcast,for example, when forward propagation,x shape:(1,3,3,3),y shape:(3,3,3,3),x+y shape:(3,3,3,3),so grad shape does,and grad_x shape should be (1,3,3,3),thus needs to sum axis.\r\n if size==1:\r\n grad_y=cp.sum(grad_y,axis=axis,keepdims=True)\r\n\r\n x.grads+=grad_x\r\n y.grads+=grad_y\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass Negative(Operation):\r\n\r\n\r\n def forward(self,is_training=True):\r\n x,=self.variables\r\n self.output_tensor=-x.output_tensor\r\n if is_training:\r\n if x.require_grads:\r\n x.grads=cp.zeros_like(x.output_tensor)\r\n super().forward(is_training)\r\n\r\n\r\n\r\n\r\n def backward(self):\r\n x, = self.variables\r\n x.grads+=-self.grads\r\n\r\n\r\n\r\nclass Multiply(Operation):\r\n\r\n\r\n def forward(self,is_training=True):\r\n x, y = self.variables\r\n self.output_tensor=cp.multiply(x.output_tensor,y.output_tensor)\r\n if is_training:\r\n if x.require_grads:\r\n x.grads=cp.zeros_like(x.output_tensor)\r\n if y.require_grads:\r\n y.grads=cp.zeros_like(x.output_tensor)\r\n\r\n super().forward(is_training)\r\n\r\n\r\n def backward(self):\r\n x, y = [node for node in self.variables]\r\n grad_x,grad_y = self.grads,self.grads\r\n while grad_x.ndim > x.output_tensor.ndim:\r\n grad_x = cp.sum(grad_x, axis=0)\r\n for axis, size in enumerate(x.output_tensor.shape):\r\n # in case of broadcast,for example, when forward propagation,x shape:(1,3,3,3),y shape:(3,3,3,3),x+y shape:(3,3,3,3),so grad shape does,and grad_x shape should be (1,3,3,3),thus needs to sum axis.\r\n if size == 1:\r\n grad_x = cp.sum(grad_x, axis=axis, keepdims=True)\r\n grad_x=grad_x*y.output_tensor\r\n\r\n\r\n while grad_y.ndim > y.output_tensor.ndim:\r\n grad_y = cp.sum(grad_y, axis=0)\r\n for axis, size in enumerate(y.output_tensor.shape):\r\n # in case of broadcast,for example, when forward propagation,x shape:(1,3,3,3),y shape:(3,3,3,3),x+y shape:(3,3,3,3),so grad shape does,and grad_x shape should be (1,3,3,3),thus needs to sum axis.\r\n if size == 1:\r\n grad_y = cp.sum(grad_y, axis=axis, keepdims=True)\r\n grad_y=grad_y*x.output_tensor\r\n\r\n x.grads += grad_x\r\n y.grads += grad_y\r\n\r\n\r\n\r\nclass Matmul(Operation):\r\n\r\n\r\n\r\n\r\n def forward(self,is_training=True):\r\n x, y = self.variables\r\n self.output_tensor=cp.dot(x.output_tensor,y.output_tensor)\r\n if is_training:\r\n if x.require_grads:\r\n x.grads=cp.zeros_like(x.output_tensor)\r\n if y.require_grads:\r\n y.grads=cp.zeros_like(x.output_tensor)\r\n\r\n super().forward(is_training)\r\n\r\n\r\n\r\n def backward(self):\r\n x, y = [node for node in self.variables]\r\n #for example ,x shape:(4,3),y shape:(3,2),x dot y shape:(4,2),so does grad shape.\r\n grad_x=cp.dot(self.grads,y.output_tensor.T)\r\n grad_y=cp.dot(x.output_tensor.T,self.grads)\r\n x.grads += grad_x\r\n y.grads += grad_y\r\n\r\n\r\n\r\nclass Log(Operation):\r\n\r\n\r\n\r\n def forward(self,is_training=True):\r\n x,=self.variables\r\n self.output_tensor=cp.log(x.output_tensor)\r\n if is_training:\r\n if x.require_grads:\r\n x.grads=cp.zeros_like(x.output_tensor)\r\n\r\n super().forward(is_training)\r\n\r\n\r\n def backward(self):\r\n x,=self.variables\r\n x.grads+=self.grads*1/x.output_tensor\r\n\r\n\r\n\r\n\r\nclass Exp(Operation):\r\n\r\n\r\n\r\n def forward(self,is_training=True):\r\n x, = self.variables\r\n self.output_tensor=cp.exp(x.output_tensor)\r\n if is_training:\r\n if x.require_grads:\r\n x.grads=cp.zeros_like(x.output_tensor)\r\n\r\n super().forward(is_training)\r\n\r\n\r\n def backward(self):\r\n x,=self.variables\r\n x.grads+=self.grads*self.output_tensor\r\n\r\n\r\n\r\nclass Reciprocal(Operation):\r\n\r\n\r\n\r\n\r\n def forward(self,is_training=True):\r\n x,=self.variables\r\n self.output_tensor= 1./x.output_tensor\r\n if is_training:\r\n if x.require_grads:\r\n x.grads=cp.zeros_like(x.output_tensor)\r\n\r\n super().forward(is_training)\r\n\r\n\r\n def backward(self):\r\n x,=self.variables\r\n x.grads += -self.grads*1/cp.square(x.output_tensor)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"layers/Base.py","file_name":"Base.py","file_ext":"py","file_size_in_byte":12834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"41231079","text":"# -*- coding: utf-8 -*-\n__version__ = \"0.5.6\"\nfrom .notebooks import (\n ampl_notebook,\n)\n\nfrom .modules import (\n activate as activate_license,\n)\n\nfrom .utils import (\n cloud_platform_name,\n register_magics,\n add_to_path,\n)\n\n_SUPPORT_MESSAGE = \"\"\"\n\nPlease report any bugs at: https://github.com/ampl/amplpy\n\nFor support/feedback go to https://discuss.ampl.com or e-mail \n\"\"\"","sub_path":"amplpy/vendor/ampltools/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"610365939","text":"from django.urls import path\nfrom . import views\n\napp_name = 'contacts'\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('add_contact/', views.add_contact, name='add-contact'),\n path('show_contacts/', views.show_all, name='show-contacts'),\n path('show_contacts//',\n views.ContactDetailView.as_view(), name='contact-detail'),\n path('show_contacts//update',\n views.ContactUpdateView.as_view(), name='contact-update'),\n path('show_contacts//delete',\n views.ContactDeleteView.as_view(), name='contact-delete'),\n path('show_contacts//add_phone',\n views.AddPhone.as_view(), name='add-phone'),\n path('show_contacts/add_phone/',\n views.add_phone, name='add_phone'),\n path('search_contact/', views.search),\n path('search_contact/', views.search),\n path('/', views.download_file),\n]\n","sub_path":"personalhelper/personalhelper/contacts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"597542922","text":"import json\nfrom copy import deepcopy \nfrom time import sleep\nfrom datetime import datetime\n\nfrom django.utils.timezone import utc\nfrom ws4redis.publisher import RedisPublisher\nfrom quotes.base import RedisStockFight\n \n\nsf_redis = RedisStockFight()\n\n\ndef send_quotes(prices):\n redis_publisher = RedisPublisher(facility=\"quotes\", broadcast=True)\n redis_publisher.publish_message(json.dumps(prices))\n\n\ndef equals(symbols, quotes, old_quotes):\n for symbol in symbols:\n if not symbol in old_quotes:\n return False\n if quotes[symbol] != old_quotes[symbol]:\n return False\n return True\n\n\ndef publish_quotes(): \n symbols = sf_redis.get_symbols()\n quotes = {}\n while True:\n sleep(0.2)\n old_quotes = deepcopy(quotes)\n \n now = datetime.now().replace(tzinfo=utc)\n quotes = sf_redis.get_prices(symbols, now)\n if equals(symbols, quotes, old_quotes):\n continue\n\n prices = {'type': 'quotes', 'quotes': quotes}\n send_quotes(prices)\n\n\ndef init_quotes(pk):\n now = datetime.utcnow()\n symbols = sf_redis.get_symbols()\n quotes = sf_redis.get_prices(symbols, now)\n prices = {'type': 'quotes', 'quotes': quotes}\n send_quotes(pk, prices)\n\n\nif __name__ == \"__main__\":\n publish_quotes() \n","sub_path":"stockfight/quotes/publish_quotes_pipline.py","file_name":"publish_quotes_pipline.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"446628982","text":"from .base_agent import MyBaseAgent\nfrom pommerman import constants\nfrom pommerman import characters\nfrom pommerman import utility\nimport numpy as np\nimport random\nfrom copy import deepcopy\n\n\nverbose = False\n\n\nclass BattleAgent(MyBaseAgent):\n\n \"\"\"\n This agent should be used when there are no more Woods and Powerups even in the flames.\n Just focus on killin enemies, while surviving.\n \"\"\"\n \n def act(self, obs, action_space, info):\n\n #\n # Definitions\n #\n\n self._search_range = 10\n\n board = obs['board']\n my_position = obs[\"position\"] # tuple([x,y]): my position\n my_ammo = obs['ammo'] # int: the number of bombs I have\n my_blast_strength = obs['blast_strength']\n my_enemies = [constants.Item(e) for e in obs['enemies']]\n my_teammate = obs[\"teammate\"]\n my_kick = obs[\"can_kick\"] # whether I can kick\n\n print(\"my position\", my_position, end=\"\\t\")\n \n #\n # Understand current situation\n #\n\n # List of the set of survivable time-positions at each time\n # and preceding positions\n survivable_no_move, prev_no_move \\\n = self._search_time_expanded_network(info[\"list_boards_no_move\"],\n my_position)\n\n # Items that can be reached in a survivable manner\n reachable_items_no_move, reached_no_move, next_to_items_no_move \\\n = self._find_reachable_items(info[\"list_boards_no_move\"],\n my_position,\n survivable_no_move)\n\n # Simulation assuming enemies move\n\n for enemy_mobility in range(3, -1, -1):\n # List of boards simulated\n list_boards, _ = self._board_sequence(board,\n info[\"curr_bombs\"],\n info[\"curr_flames\"],\n self._search_range,\n my_position,\n enemy_mobility=enemy_mobility)\n\n # List of the set of survivable time-positions at each time\n # and preceding positions\n survivable, prev = self._search_time_expanded_network(list_boards,\n my_position)\n\n if len(survivable[1]) > 0:\n # Gradually reduce the mobility of enemy, so we have at least one survivable action\n break\n\n # Items that can be reached in a survivable manner\n reachable_items, reached, next_to_items \\\n = self._find_reachable_items(list_boards,\n my_position,\n survivable)\n\n # Survivable actions\n is_survivable, survivable_with_bomb \\\n = self._get_survivable_actions(survivable,\n obs,\n info[\"curr_bombs\"],\n info[\"curr_flames\"])\n\n survivable_actions = [a for a in is_survivable if is_survivable[a]]\n \n # if verbose:\n if True:\n print(\"survivable actions are\", survivable_actions)\n\n # Positions where we kick a bomb if we move to\n if my_kick:\n kickable = self._kickable_positions(obs, info[\"moving_direction\"])\n else:\n kickable = set()\n\n print()\n for t in range(0):\n print(list_boards[t])\n print(survivable[t])\n for key in prev[t]:\n print(key, prev[t][key])\n\n #\n # Choose an action\n #\n\n \"\"\"\n # This is not effective in the current form\n if len(survivable_actions) > 1:\n # avoid the position if only one position at the following step\n # the number of positions that can be reached from the next position\n next = defaultdict(set)\n next_count = defaultdict(int)\n for position in survivable[1]:\n next[position] = set([p for p in prev[2] if position in prev[2][p]])\n next_count[position] = len(next[position])\n print(\"next count\", next_count)\n if max(next_count.values()) > 1:\n for position in survivable[1]:\n if next_count[position] == 1:\n risky_action = self._get_direction(my_position, position)\n is_survivable[risky_action] = False\n survivable_actions = [a for a in is_survivable if is_survivable[a]] \n \"\"\"\n\n # Do not stay on a bomb if I can\n if all([obs[\"bomb_life\"][my_position] > 0,\n len(survivable_actions) > 1,\n is_survivable[constants.Action.Stop]]):\n is_survivable[constants.Action.Stop] = False\n survivable_actions = [a for a in is_survivable if is_survivable[a]]\n\n if len(survivable_actions) == 0:\n\n print(\"Must die\")\n return None\n\n elif len(survivable_actions) == 1:\n\n # move to the position if it is the only survivable position\n action = survivable_actions[0]\n print(\"The only survivable action\", action)\n return action.value\n\n # TODO : shoud check the survivability of all agents in one method\n\n # Place a bomb if\n # - it does not significantly reduce my survivability\n # - it can reduce the survivability of enemies\n\n consider_bomb = True\n if survivable_with_bomb is None:\n consider_bomb = False\n elif any([len(s) <= 2 for s in survivable_with_bomb[1:]]):\n # if not sufficiently survivable all the time after bomb, do not bomb\n consider_bomb = False\n\n if consider_bomb:\n # place bomb if can reach fog/enemy\n if self._can_break(info[\"list_boards_no_move\"][-1],\n my_position,\n my_blast_strength,\n [constants.Item.Fog] + my_enemies):\n print(\"Bomb to break fog/enemy\", constants.Action.Bomb)\n print(info[\"list_boards_no_move\"][-1])\n return constants.Action.Bomb.value\n\n for enemy in my_enemies:\n # check if the enemy is reachable\n if len(reachable_items_no_move[enemy]) == 0:\n continue\n\n # can reach the enemy at enemy_position in enemy_time step\n enemy_time = reachable_items_no_move[enemy][0][0]\n enemy_position = reachable_items_no_move[enemy][0][1:3]\n\n # check if placing a bomb can reduce the survivability\n # of the enemy\n survivable_before, _ = self._search_time_expanded_network(info[\"list_boards_no_move\"],\n enemy_position)\n\n board_with_bomb = deepcopy(obs[\"board\"])\n curr_bombs_with_bomb = deepcopy(info[\"curr_bombs\"])\n # lay a bomb\n board_with_bomb[my_position] = constants.Item.Bomb.value\n bomb = characters.Bomb(characters.Bomber(), # dummy owner of the bomb\n my_position,\n constants.DEFAULT_BOMB_LIFE,\n my_blast_strength,\n None)\n curr_bombs_with_bomb.append(bomb)\n list_boards_with_bomb, _ \\\n = self._board_sequence(board_with_bomb,\n curr_bombs_with_bomb,\n info[\"curr_flames\"],\n self._search_range,\n my_position,\n enemy_mobility=0)\n survivable_after, _ \\\n = self._search_time_expanded_network(list_boards_with_bomb,\n enemy_position)\n\n good_before = np.array([len(s) for s in survivable_before])\n good_after = np.array([len(s) for s in survivable_after])\n\n # TODO : what are good criteria?\n if any(good_after < good_before):\n # place a bomb if it makes sense\n print(\"Bomb to kill an enemy\", constants.Action.Bomb)\n print(\"before\", good_before)\n print(\"after \", good_after)\n print([len(s) for s in survivable])\n print([len(s) for s in survivable_with_bomb])\n return constants.Action.Bomb.value\n \n \"\"\"\n # find direction towards enemy\n positions = set([x[1:3] for x in next_to_items_no_move[enemy]])\n for t in range(enemy_time, 1, -1):\n _positions = set()\n for position in positions:\n _positions = _positions.union(prev_no_move[t][position])\n positions = _positions.copy()\n\n if enemy_time <= my_blast_strength:\n #if True:\n positions.add(my_position)\n positions_after_bomb = set(survivable[1]).difference(positions)\n if positions_after_bomb:\n print(\"Bomb to kill an enemy\", enemy, constants.Action.Bomb)\n return constants.Action.Bomb.value\n \"\"\"\n\n # if I can kick, consider placing a bomb to kick\n if my_kick and my_position in survivable_with_bomb[3]:\n # consdier a sequence of actions: place bomb -> move (action) -> move back (kick)\n for action in [constants.Action.Up,\n constants.Action.Down,\n constants.Action.Left,\n constants.Action.Right]:\n if not is_survivable[action]:\n continue\n\n if action == constants.Action.Up:\n # kick direction is down\n dx = 1\n dy = 0\n elif action == constants.Action.Down:\n # kick direction is up\n dx = -1\n dy = 0 \n elif action == constants.Action.Left:\n # kick direction is right\n dx = 0\n dy = 1\n elif action == constants.Action.Right:\n # kick direction is left\n dx = 0\n dy = -1\n else:\n raise ValueError()\n\n _next_position = (my_position[0] + dx, my_position[1] + dy)\n if not self._on_board(_next_position):\n continue\n else:\n next_position = _next_position\n\n # Find where the bomb stops if kicked\n for t in range(int(obs[\"bomb_life\"][my_position]) - 2):\n if not utility.position_is_passage(board, next_position):\n break\n _next_position = (next_position[0] + dx, next_position[1] + dy)\n if not self._on_board(_next_position):\n break\n else:\n next_position = _next_position\n if utility.position_is_fog(board, next_position):\n print(\"Bomb to kick into fog\", action)\n return constants.Action.Bomb.value\n elif utility.position_is_enemy(list_boards[t+2], next_position, my_enemies):\n print(\"Bomb to kick towards enemy\", action)\n return constants.Action.Bomb.value\n\n \"\"\"\n x0, y0 = my_position\n positions_against = [(2*x0-x, 2*y0-y) for (x, y) in positions]\n positions_after_bomb = set(survivable[1]).intersection(positions_against)\n\n if positions_after_bomb:\n print(\"Bomb to kick\", enemy, constants.Action.Bomb)\n return constants.Action.Bomb.value\n \"\"\"\n\n # kick \n if len(kickable) > 0:\n\n while kickable:\n # then consider what happens if I kick a bomb\n next_position = kickable.pop()\n\n # do not kick a bomb if it will break enemies\n if info[\"moving_direction\"][next_position] is None:\n # if it is a static bomb\n if self._can_break(info[\"list_boards_no_move\"][0],\n next_position,\n my_blast_strength,\n my_enemies):\n continue\n \n my_action = self._get_direction(my_position, next_position)\n list_boards_with_kick, next_position \\\n = self._board_sequence(obs[\"board\"],\n info[\"curr_bombs\"],\n info[\"curr_flames\"],\n self._search_range,\n my_position,\n my_action=my_action,\n can_kick=True,\n enemy_mobility=3)\n survivable_with_kick, prev_kick \\\n = self._search_time_expanded_network(list_boards_with_kick[1:],\n next_position)\n if next_position in survivable_with_kick[0]:\n print(\"Kicking\", my_action)\n return my_action.value\n\n # if on a bomb, consider where to kick in the following step \n if obs[\"bomb_life\"][my_position] > 0:\n # For each survivable move in the next step,\n # check what happens if we kick in the following step.\n # If the bomb is kicked into a fog, plan to kick.\n # If the bomb is kicked toward an enemy, plan to kick.\n # Otherwise, do not plan to kick.\n for action in [constants.Action.Up,\n constants.Action.Down,\n constants.Action.Left,\n constants.Action.Right]:\n if not is_survivable[action]:\n continue\n\n if action == constants.Action.Up:\n # kick direction is down\n dx = 1\n dy = 0\n elif action == constants.Action.Down:\n # kick direction is up\n dx = -1\n dy = 0 \n elif action == constants.Action.Left:\n # kick direction is right\n dx = 0\n dy = 1\n elif action == constants.Action.Right:\n # kick direction is left\n dx = 0\n dy = -1\n else:\n raise ValueError()\n\n _next_position = (my_position[0] + dx, my_position[1] + dy)\n if not self._on_board(_next_position):\n continue\n else:\n next_position = _next_position\n\n # Find where the bomb stops if kicked\n for t in range(int(obs[\"bomb_life\"][my_position]) - 1):\n if not utility.position_is_passage(board, next_position):\n break\n _next_position = (next_position[0] + dx, next_position[1] + dy)\n if not self._on_board(_next_position):\n break\n else:\n next_position = _next_position\n if utility.position_is_fog(board, next_position):\n print(\"Moving to kick into fog\", action)\n return action.value\n elif utility.position_is_enemy(list_boards[t+2], next_position, my_enemies):\n print(\"Moving to kick towards enemy\", action)\n\n # Move towards an enemy\n good_time_positions = set()\n for enemy in my_enemies:\n good_time_positions = good_time_positions.union(next_to_items[enemy])\n\n if len(good_time_positions) > 0:\n action = self._find_distance_minimizer(my_position,\n good_time_positions,\n prev,\n is_survivable)\n\n if action is not None:\n print(\"Moving toward enemy\", action)\n return action.value\n\n #\n # Random action\n #\n action = random.choice(survivable_actions)\n print(\"Random action\", action)\n return action.value\n \n","sub_path":"build/BBM/pommerman_v1.5/src/agents/battle_agent_org.py","file_name":"battle_agent_org.py","file_ext":"py","file_size_in_byte":17536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"356697986","text":"import torch\nimport torch.nn as nn\nfrom torchsummary import summary\nfrom models.BasicModule import BasicModule\nfrom IPython import embed\n\n\ndef activation(act_type='prelu'):\n if act_type == 'prelu':\n act = nn.PReLU()\n elif act_type == 'relu':\n act = nn.ReLU(inplace=True)\n else:\n raise NotImplementedError\n return act\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv1d(in_planes, out_planes, kernel_size=7, stride=stride,\n padding=3, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm1d(planes)\n self.relu = activation('relu')\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm1d(planes)\n self.downsample = downsample\n self.stride = stride\n self.dropout = nn.Dropout(.2)\n #self.dropout = nn.Dropout(.5)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.dropout(out)\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv1d(inplanes, planes, kernel_size=7, bias=False, padding=3)\n self.bn1 = nn.BatchNorm1d(planes)\n self.conv2 = nn.Conv1d(planes, planes, kernel_size=11, stride=stride,\n padding=5, bias=False)\n self.bn2 = nn.BatchNorm1d(planes)\n self.conv3 = nn.Conv1d(planes, planes * 4, kernel_size=7, bias=False, padding=3)\n self.bn3 = nn.BatchNorm1d(planes * 4)\n self.relu = activation('relu')\n self.downsample = downsample\n self.stride = stride\n self.dropout = nn.Dropout(.2)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n out = self.dropout(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(BasicModule):\n\n def __init__(self, block, layers, num_classes=55):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv1d(8, 64, kernel_size=15, stride=2, padding=7,\n bias=False)\n self.bn1 = nn.BatchNorm1d(64)\n self.relu = activation('relu')\n self.maxpool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n # Baseline\n self.avgpool = nn.AdaptiveAvgPool1d(1)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n # V1\n #self.avgpool = nn.AdaptiveAvgPool1d(2)\n #self.fc = nn.Linear(2 * 512 * block.expansion, num_classes)\n # v2\n #self.conv2 = nn.Conv1d(2048, 64, kernel_size=1, stride=1, padding=0,\n # bias=False)\n #self.bn2 = nn.BatchNorm1d(64)\n #self.avgpool = nn.AdaptiveAvgPool1d(8)\n #self.fc = nn.Linear(64 * 8, num_classes)\n\n self.sigmoid = nn.Sigmoid()\n self.init()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv1d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm1d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, data):\n x = self.conv1(data)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n\n x = self.fc(x)\n x = self.sigmoid(x)\n\n return x\n\n\ndef ResNet34(num_classes=55):\n return ResNet(BasicBlock, [3, 4, 6, 3], num_classes)\n\n\ndef ResNet50_Basic(num_classes=55):\n return ResNet(Bottleneck, [3, 4, 6, 3], num_classes)\n\n\ndef ResNet101_Basic(num_classes=55):\n return ResNet(Bottleneck, [3, 4, 23, 3], num_classes)\n\n\ndef ResNet152(num_classes=55):\n return ResNet(Bottleneck, [3, 8, 36, 3], num_classes)\n\n\ndef test_ResNet():\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n net = ResNet50_Basic()\n model = net.to(device)\n print( summary(net, input_size=(8, 5000)) )\n\n\nif __name__ == '__main__':\n test_ResNet()\n","sub_path":"models/ResNet_Basic.py","file_name":"ResNet_Basic.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"285072644","text":"# -*-coding:utf-8 -*-\n# fit 健身头条\n\nimport requests\nimport time\nimport json\nimport webbrowser\n\n# 请求的时间戳\nfrom requests import HTTPError\n\ncurrentTime = int(time.time())\n\n# 请求头\nrequestHeaders = {\n 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0.1; vivo Y66 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/51.0.2704.81 Mobile Safari/537.36',\n 'content-type': 'application/json',\n 'Host': 's.lmstyle.cn',\n 'Connection': 'Keep-Alive',\n 'Accept-Encoding': 'gzip',\n 'Content-Length': '555'\n}\n# 请求body体\nrequestBody = {\"appkey\": \"7f4756ead2bb3e88\", \"pid\": \"1737502\", \"v\": \"2.1a\", \"s\": 1, \"timestamp\": currentTime,\n \"device\": {\"adid\": \"\", \"anid\": \"d70ac4e6752e71f9\", \"brand\": \"vivo\",\n \"ua\": \"Mozilla\\/5.0 (Linux; Android 6.0.1; vivo Y66 Build\\/MMB29M; wv) AppleWebKit\\/537.36 (KHTML, like Gecko) Version\\/4.0 Chrome\\/51.0.2704.81 Mobile Safari\\/537.36\",\n \"density\": \"2.0\", \"imei\": \"866117035052641\", \"imsi\": \"null\", \"lang\": \"zh\", \"lat\": \"-1.0\",\n \"lon\": \"-1.0\", \"mac\": \"1C:DA:27:D3:40:67\", \"mcc\": \"\", \"mnc\": \"\", \"model\": \"vivo Y66\",\n \"orientation\": \"0\", \"osv\": \"6.0.1\", \"os\": 1, \"sh\": 1280, \"sw\": 720, \"type\": 0,\n \"connection\": 1}}\n\n# 请求的url\nurl = 'http://s.lmstyle.cn/ad/get'\n\nhtml = ''\n\nfor x in range(100):\n try:\n res = requests.post(url, json.dumps(requestBody), requestHeaders)\n print('第' + str(x) + '次获取广告数据 ===========>')\n print('状态码==>', res.status_code)\n print('body ==>', res.text)\n resp = json.loads(res.text)\n\n # showreport\n print(len(resp['ads'][0]['show_report']))\n for x in range(len(resp['ads'][0]['show_report'])):\n if resp['ads'][0]['show_report'][x] != '':\n print(resp['ads'][0]['show_report'][x])\n requests.get(resp['ads'][0]['show_report'][x])\n\n # 命名生成的html\n GEN_HTML = \"hangjiashuo.html\"\n f = open(GEN_HTML, 'w')\n if resp.get('ads') and resp.get('ads')[0].get('html'):\n print('广告类型为 html========>')\n html = resp.get('ads')[0].get('html')\n elif resp.get('ads') and resp.get('ads')[0].get('image_url'):\n print('广告类型为图片=====>')\n html = \"\"\"\n \n \n \n \n \n \"\"\" % (resp['ads'][0]['image_url'][0])\n f.write(html)\n f.close()\n # 运行完自动在网页中显示\n webbrowser.open(GEN_HTML, new=0, autoraise=True)\n\n # 重新赋值\n time.sleep(10)\n currentTime = int(time.time())\n requestBody['timestamp'] = currentTime\n except HTTPError as e:\n print('出现异常==>', e)\n except AttributeError as e:\n print(\"Tag was not found\")","sub_path":"AdverBrush/src/ad/hangjiashuo.py","file_name":"hangjiashuo.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"197560471","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template, jsonify\nfrom random import randint\n\nimport serial\nimport thread\n\nserial_port = \"/dev/tty.HC-05-DevB\"\n\n\nclass InjuryType:\n ALL_OK = 0\n BLEEDING = 1\n LIMB_MISSING = 2\n ALL_OK_TEXT = ''\n BLEEDING_TEXT = 'Verejooks'\n LIMB_MISSING_TEXT = 'Eemaldunud jäse'\n\n\nclass BodyPart:\n id = None\n instructions = {\n InjuryType.ALL_OK: [],\n InjuryType.BLEEDING: ['Aseta haava peale side!'],\n InjuryType.LIMB_MISSING: ['Aseta peale žgutt.']\n }\n\n @classmethod\n def get_instruction(cls, injury_type):\n return cls.instructions.get(injury_type, [])\n\n\nclass LeftArm(BodyPart):\n id = 'leftArm'\n\n\nclass RightArm(BodyPart):\n id = 'rightArm'\n\n\nclass BodyPartInjuryDetector:\n def __init__(self, body_part):\n self.is_bleeding = False\n self.is_removed = False\n self.body_part = body_part\n\n def update_values(self, is_bleeding, is_removed):\n self.is_bleeding = is_bleeding\n self.is_removed = is_removed\n\n def get_json_values(self):\n injury_type, injury_text = self.get_injury()\n return {\n 'bodyPart': self.body_part.id,\n 'injury': injury_text,\n 'injuryType': injury_type,\n 'instructions': self.body_part.get_instruction(injury_type)\n }\n\n def get_injury(self):\n if self.is_removed:\n return InjuryType.LIMB_MISSING, InjuryType.LIMB_MISSING_TEXT\n elif self.is_bleeding:\n return InjuryType.BLEEDING, InjuryType.BLEEDING_TEXT\n else:\n return InjuryType.ALL_OK, InjuryType.ALL_OK_TEXT\n\n\nright_arm = BodyPartInjuryDetector(RightArm)\nleft_arm = BodyPartInjuryDetector(LeftArm)\n\n\n# reading bluetooth data\ndef read_sensor_data():\n try:\n serial_connection = serial.Serial(port=serial_port)\n serial_connection.flush()\n while True:\n line = serial_connection.readline()\n if line:\n try:\n data = line.replace('\\n', '').replace('\\r', '').split(\",\")\n bleeding = data[0] == \"1\"\n left_missing = data[1] == \"1\"\n right_missing = data[2] == \"1\"\n left_arm.update_values(bleeding, left_missing)\n right_arm.update_values(False, right_missing)\n except Exception as e:\n print('Parsing bluetooth data failed', e)\n except Exception as e:\n print(\"Bluetooth error\", e)\n\n\ntry:\n thread.start_new_thread(read_sensor_data, ())\nexcept Exception:\n print(\"Error: unable to start thread\")\n\napp = Flask(__name__, static_url_path='/static')\n\n\n@app.route(\"/\")\ndef index():\n page_name = \"index\"\n version = randint(0, 999999)\n return render_template('%s.html' % page_name, version=version)\n\n\n@app.route(\"/injuries\", methods=['GET', 'POST'])\ndef get_injuries():\n # return jsonify(left_arm.get_json_values())\n return jsonify([left_arm.get_json_values(), right_arm.get_json_values()])\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"487594843","text":"# -*- coding: utf-8 -*-\n\"\"\"\nJinja2 templates for deform.\n\nTo use in Pyramid:\n\nIn your settings.ini::\n\n # default:\n # deform_jinja2.i18n.domain=deform\n\n # One of:\n deform_jinja2.template_search_path=deform_jinja2:templates\n deform_jinja2.template_search_path=deform_jinja2:uni_templates\n deform_jinja2.template_search_path=deform_jinja2:bootstrap_templates\n\nIn your app initialization::\n\n config.include('deform_jinja2')\n\n\"\"\"\n\nfrom jinja2 import Environment\nfrom jinja2 import FileSystemLoader\nfrom jinja2.utils import import_string\nfrom pkg_resources import resource_filename\n\nfrom compat import string_types\n\n\ndef splitlines(s):\n return filter(None, [x.strip() for x in s.splitlines()])\n\n\ndef maybe_import_string(val):\n if isinstance(val, string_types):\n return import_string(val.strip())\n return val\n\n\ndef parse_config(config):\n \"\"\"\n Parses config values from .ini file and returns a dictionary with\n imported objects\n \"\"\"\n # input must be a string or dict\n result = {}\n if isinstance(config, string_types):\n for f in splitlines(config):\n name, impl = f.split('=', 1)\n result[name.strip()] = maybe_import_string(impl)\n else:\n for name, impl in config.items():\n result[name] = maybe_import_string(impl)\n return result\n\n\nclass DummyTranslator(object):\n @staticmethod\n def gettext(message):\n return message\n\n @staticmethod\n def ngettext(singular, plural, n):\n if n > 1:\n return plural\n\n return singular\n\n\nclass jinja2_renderer_factory(object):\n def __init__(self, search_paths=(),\n default_templates='deform_jinja2:templates',\n translator=None, extensions=[], filters=None):\n\n if 'jinja2.ext.i18n' not in extensions:\n extensions.append('jinja2.ext.i18n')\n\n self.env = Environment(extensions=extensions)\n self.env.loader = FileSystemLoader(())\n\n for path in search_paths:\n self.add_search_path(path)\n\n if translator is None:\n translator = DummyTranslator\n\n self.env.install_gettext_callables(translator.gettext,\n translator.ngettext)\n\n self.add_search_path(default_templates)\n\n filters = filters or {}\n self.env.filters.update(filters)\n\n def add_search_path(self, path):\n self.env.loader.searchpath.append(\n resource_filename(*(path.split(':'))))\n\n def __call__(self, tname, **kw):\n if not '.jinja2' in tname:\n tname += '.jinja2'\n\n template = self.env.get_template(tname)\n return template.render(**kw)\n\n\ndef includeme(config):\n from translator import PyramidTranslator\n import deform\n settings = config.registry.settings\n domain = settings.get('deform_jinja2.i18n.domain', 'deform')\n search_path = settings.get('deform_jinja2.template_search_path', '')\n filters = parse_config(settings.get('deform_jinja2.filters', ''))\n\n renderer = jinja2_renderer_factory(\n search_paths=search_path.strip().split(),\n translator=PyramidTranslator(domain=domain),\n filters=filters\n )\n deform.Form.set_default_renderer(renderer)\n","sub_path":"deform_jinja2/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"595892653","text":"# Copyright Contributors to the Amundsen project.\n# SPDX-License-Identifier: Apache-2.0\n\nimport copy\nfrom typing import Union, Dict, Any # noqa: F401\n\nfrom databuilder.models.neo4j_csv_serde import Neo4jCsvSerializable, NODE_KEY, \\\n NODE_LABEL, RELATION_START_KEY, RELATION_START_LABEL, RELATION_END_KEY, \\\n RELATION_END_LABEL, RELATION_TYPE, RELATION_REVERSE_TYPE\nfrom databuilder.publisher.neo4j_csv_publisher import UNQUOTED_SUFFIX\n\n\nclass User(Neo4jCsvSerializable):\n # type: (...) -> None\n \"\"\"\n User model. This model doesn't define any relationship.\n \"\"\"\n USER_NODE_LABEL = 'User'\n USER_NODE_KEY_FORMAT = '{email}'\n USER_NODE_EMAIL = 'email'\n USER_NODE_FIRST_NAME = 'first_name'\n USER_NODE_LAST_NAME = 'last_name'\n USER_NODE_FULL_NAME = 'full_name'\n USER_NODE_GITHUB_NAME = 'github_username'\n USER_NODE_TEAM = 'team_name'\n USER_NODE_EMPLOYEE_TYPE = 'employee_type'\n USER_NODE_MANAGER_EMAIL = 'manager_email'\n USER_NODE_SLACK_ID = 'slack_id'\n USER_NODE_IS_ACTIVE = 'is_active{}'.format(UNQUOTED_SUFFIX) # bool value needs to be unquoted when publish to neo4j\n USER_NODE_UPDATED_AT = 'updated_at'\n USER_NODE_ROLE_NAME = 'role_name'\n\n USER_MANAGER_RELATION_TYPE = 'MANAGE_BY'\n MANAGER_USER_RELATION_TYPE = 'MANAGE'\n\n def __init__(self,\n email, # type: str\n first_name='', # type: str\n last_name='', # type: str\n name='', # type: str\n github_username='', # type: str\n team_name='', # type: str\n employee_type='', # type: str\n manager_email='', # type: str\n slack_id='', # type: str\n is_active=True, # type: bool\n updated_at=0, # type: int\n role_name='', # type: str\n do_not_update_empty_attribute=False, # type: bool\n **kwargs # type: Dict\n ):\n # type: (...) -> None\n \"\"\"\n This class models user node for Amundsen people.\n\n :param first_name:\n :param last_name:\n :param name:\n :param email:\n :param github_username:\n :param team_name:\n :param employee_type:\n :param manager_email:\n :param is_active:\n :param updated_at: everytime we update the node, we will push the timestamp.\n then we will have a cron job to update the ex-employee nodes based on\n the case if this timestamp hasn't been updated for two weeks.\n :param role_name: the role_name of the user (e.g swe)\n :param do_not_update_empty_attribute: If False, all empty or not defined params will be overwritten with\n empty string.\n :param kwargs: Any K/V attributes we want to update the\n \"\"\"\n self.first_name = first_name\n self.last_name = last_name\n self.name = name\n\n self.email = email\n self.github_username = github_username\n # todo: team will be a separate node once Amundsen People supports team\n self.team_name = team_name\n self.manager_email = manager_email\n self.employee_type = employee_type\n # this attr not available in team service, either update team service, update with FE\n self.slack_id = slack_id\n self.is_active = is_active\n self.updated_at = updated_at\n self.role_name = role_name\n self.do_not_update_empty_attribute = do_not_update_empty_attribute\n self.attrs = None\n if kwargs:\n self.attrs = copy.deepcopy(kwargs)\n\n self._node_iter = iter(self.create_nodes())\n self._rel_iter = iter(self.create_relation())\n\n def create_next_node(self):\n # type: (...) -> Union[Dict[str, Any], None]\n # return the string representation of the data\n try:\n return next(self._node_iter)\n except StopIteration:\n return None\n\n def create_next_relation(self):\n # type: () -> Union[Dict[str, Any], None]\n \"\"\"\n :return:\n \"\"\"\n try:\n return next(self._rel_iter)\n except StopIteration:\n return None\n\n @classmethod\n def get_user_model_key(cls,\n email=None):\n # type: (...) -> str\n if not email:\n return ''\n return User.USER_NODE_KEY_FORMAT.format(email=email)\n\n def create_nodes(self):\n # type: () -> List[Dict[str, Any]]\n \"\"\"\n Create a list of Neo4j node records\n :return:\n \"\"\"\n result_node = {\n NODE_KEY: User.get_user_model_key(email=self.email),\n NODE_LABEL: User.USER_NODE_LABEL,\n User.USER_NODE_EMAIL: self.email,\n User.USER_NODE_IS_ACTIVE: self.is_active,\n }\n\n result_node[User.USER_NODE_FIRST_NAME] = self.first_name if self.first_name else ''\n result_node[User.USER_NODE_LAST_NAME] = self.last_name if self.last_name else ''\n result_node[User.USER_NODE_FULL_NAME] = self.name if self.name else ''\n result_node[User.USER_NODE_GITHUB_NAME] = self.github_username if self.github_username else ''\n result_node[User.USER_NODE_TEAM] = self.team_name if self.team_name else ''\n result_node[User.USER_NODE_EMPLOYEE_TYPE] = self.employee_type if self.employee_type else ''\n result_node[User.USER_NODE_SLACK_ID] = self.slack_id if self.slack_id else ''\n result_node[User.USER_NODE_ROLE_NAME] = self.role_name if self.role_name else ''\n\n if self.updated_at:\n result_node[User.USER_NODE_UPDATED_AT] = self.updated_at\n elif not self.do_not_update_empty_attribute:\n result_node[User.USER_NODE_UPDATED_AT] = 0\n\n if self.attrs:\n for k, v in self.attrs.items():\n if k not in result_node:\n result_node[k] = v\n\n if self.do_not_update_empty_attribute:\n for k, v in list(result_node.items()):\n if not v:\n del result_node[k]\n\n return [result_node]\n\n def create_relation(self):\n # type: () -> List[Dict[str, Any]]\n if self.manager_email:\n # only create the relation if the manager exists\n return [{\n RELATION_START_KEY: User.get_user_model_key(email=self.email),\n RELATION_START_LABEL: User.USER_NODE_LABEL,\n RELATION_END_KEY: self.get_user_model_key(email=self.manager_email),\n RELATION_END_LABEL: User.USER_NODE_LABEL,\n RELATION_TYPE: User.USER_MANAGER_RELATION_TYPE,\n RELATION_REVERSE_TYPE: User.MANAGER_USER_RELATION_TYPE\n }]\n return []\n\n def __repr__(self):\n # type: () -> str\n return 'User({!r}, {!r}, {!r}, {!r}, {!r}, ' \\\n '{!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r})'.format(self.first_name,\n self.last_name,\n self.name,\n self.email,\n self.github_username,\n self.team_name,\n self.slack_id,\n self.manager_email,\n self.employee_type,\n self.is_active,\n self.updated_at,\n self.role_name)\n","sub_path":"databuilder/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":7853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"579957123","text":"# Trying to put all the scraper code here, and then just call this\n\nimport requests\nfrom datetime import *\nimport timeit\n\ndef scraper(baseUrl, startDate, sourceAppend, imgLocalPath):\n BASE_URL = baseUrl\n\n # generates dates for the scraper loop to iterate over\n def dateRange(start_date, end_date):\n for n in range(int((end_date - start_date).days)):\n yield start_date + timedelta(n)\n\n start_date = startDate\n end_date = date.today()\n start_time = timeit.default_timer() # starts timer to time script\n\n for single_date in dateRange(start_date, end_date):\n DATE = single_date.strftime('%Y%m%d')\n SOURCE_APPEND = sourceAppend\n imageURL = BASE_URL + SOURCE_APPEND\n r = requests.head(imageURL)\n if r.status_code == 200:\n imageContent = requests.get(imageURL).content\n output = open('Scraped/'+imgLocalPath, 'wb')\n output.write(imageContent)\n output.close()\n print(\"Comic for \" + str(single_date) + \" written.\")\n else:\n print('No comic posted for ' + str(single_date))\n start_date = end_date - timedelta(1) # sets start date to last day included in last scrape\n\n # stops and formats timer\n stop = timeit.default_timer()\n time_elapsed = stop - start_time\n minutes, seconds = divmod(time_elapsed, 60)\n hours, minutes = divmod(minutes, 60)\n\n # prints elapsed time, as well as what the next start date is so you can run the script easily\n print(\"Scrape complete. Next start date set to \" + str(start_date))\n print(\"Scraper running time: %d:%d:%d. \\n\" % (hours, minutes, seconds))","sub_path":"Scraper/Scraper.py","file_name":"Scraper.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"273784227","text":"#create spectrograms\nimport numpy as np\nfrom numpy.lib import stride_tricks\nimport os\nfrom PIL import Image\nimport scipy.io.wavfile as wav\n\"\"\"\nThis script creates spectrogram matrices from wav files that can be passed \\\nto the CNN. This was heavily adopted from Frank Zalkow's work.\n\"\"\"\n\n\ndef stft(sig, frameSize, overlapFac=0.5, window=np.hanning):\n \"\"\"\n Short-time Fourier transform of audio signal.\n \"\"\"\n win = window(frameSize)\n hopSize = int(frameSize - np.floor(overlapFac * frameSize))\n # zeros at beginning (thus center of 1st window should be for sample nr. 0)\n samples = np.append(np.zeros(int(np.floor(frameSize/2.0))), sig)\n # cols for windowing\n cols = np.ceil((len(samples) - frameSize) / float(hopSize)) + 1\n # zeros at end (thus samples can be fully covered by frames)\n samples = np.append(samples, np.zeros(frameSize))\n frames = stride_tricks.as_strided(samples, shape=(int(cols), int(frameSize)),\n strides=(samples.strides[0]*hopSize,\n samples.strides[0])).copy()\n frames *= win\n return np.fft.rfft(frames)\n\n\ndef logscale_spec(spec, sr=44100, factor=20.):\n \"\"\"\n Scale frequency axis logarithmically.\n \"\"\"\n timebins, freqbins = np.shape(spec)\n\n scale = np.linspace(0, 1, freqbins) ** factor\n scale *= (freqbins-1)/max(scale)\n scale = np.unique(np.round(scale))\n\n # create spectrogram with new freq bins\n newspec = np.complex128(np.zeros([timebins, len(scale)]))\n for i in range(0, len(scale)):\n if i == len(scale)-1:\n newspec[:, i] = np.sum(spec[:, int(scale[i]):], axis=1)\n else:\n newspec[:, i] = np.sum(spec[:, int(scale[i]):int(scale[i+1])], axis=1)\n\n # list center freq of bins\n allfreqs = np.abs(np.fft.fftfreq(freqbins*2, 1./sr)[:freqbins+1])\n freqs = []\n for i in range(0, len(scale)):\n if i == len(scale)-1:\n freqs += [np.mean(allfreqs[int(scale[i]):])]\n else:\n freqs += [np.mean(allfreqs[int(scale[i]):int(scale[i+1])])]\n\n return newspec, freqs\n\n\ndef stft_matrix(audiopath, binsize=2**10, png_name='tmp.png',\n save_png=False, offset=0):\n \"\"\"\n A function that converts a wav file into a spectrogram represented by a \\\n matrix where rows represent frequency bins, columns represent time, and \\\n the values of the matrix represent the decibel intensity. A matrix of \\\n this form can be passed as input to the CNN after undergoing normalization.\n \"\"\"\n samplerate, samples = wav.read(audiopath)\n s = stft(samples, binsize)\n\n sshow, freq = logscale_spec(s, factor=1, sr=samplerate)\n ims = 20.*np.log10(np.abs(sshow)/10e-6) # amplitude to decibel\n timebins, freqbins = np.shape(ims)\n\n ims = np.transpose(ims)\n ims = np.flipud(ims) # weird - not sure why it needs flipping\n\n if save_png:\n create_png(ims, png_name)\n\n return ims\n\ndef get_random_samples(matrix, n_samples, crop_width):\n \"\"\"\n Get N random samples with width of crop_width from the numpy matrix\n representing the participant's audio spectrogram.\n \"\"\"\n # crop full spectrogram into segments of width = crop_width\n clipped_mat = matrix[:, (matrix.shape[1] % crop_width):]\n n_splits = clipped_mat.shape[1] / crop_width\n cropped_sample_ls = np.split(clipped_mat, n_splits, axis=1)\n # get random samples\n samples = random.sample(cropped_sample_ls, int(n_samples))\n\n return samples","sub_path":"Research Work/FeatureExtraction.py","file_name":"FeatureExtraction.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"141918631","text":"from gevent import monkey; monkey.patch_all() # 使用monkey.patch_all(),gevent才会识别其他包的IO操作\nimport time\nimport gevent\n\n\ndef eat():\n print('eat')\n time.sleep(1)\n print('eat over')\n\n\ndef drink():\n print('drink')\n time.sleep(1)\n print('drink over')\n\n\ng1 = gevent.spawn(eat)\ng2 = gevent.spawn(drink)\ng1.join()\ng2.join()\n\n","sub_path":"协程/gev.py","file_name":"gev.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"213949721","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\n ┏┛ ┻━━━━━┛ ┻┓\n ┃ ┃\n ┃ ━ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┃\n ┃ ┻ ┃\n ┃ ┃\n ┗━┓ ┏━━━┛\n ┃ ┃ 神兽保佑\n ┃ ┃ 代码无BUG!\n ┃ ┗━━━━━━━━━┓\n ┃ ┣┓\n ┃ ┏┛\n ┗━┓ ┓ ┏━━━┳ ┓ ┏━┛\n ┃ ┫ ┫ ┃ ┫ ┫\n ┗━┻━┛ ┗━┻━┛\n\"\"\"\n\nimport tensorflow as tf\n\nfrom translation.models.mutiHeadAttention import MutiHeadAttention\nfrom translation.models.model_utils import feed_forward_network\n\n\nclass EncoderLayer(tf.keras.layers.Layer):\n def __init__(self, d_model, n_heads, ddf, dropout_rate=0.1):\n \"\"\"\n\n :param d_model:\n :param n_heads:\n :param ddf: ffn的隐藏层个数\n :param dropout_rate:\n \"\"\"\n super(EncoderLayer, self).__init__()\n self.muti_head_attn = MutiHeadAttention(d_model, n_heads)\n self.ffn = feed_forward_network(d_model, ddf)\n\n self.layerNorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n self.layerNorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n\n self.dropout1 = tf.keras.layers.Dropout(dropout_rate)\n self.dropout2 = tf.keras.layers.Dropout(dropout_rate)\n\n def call(self, inputs, training, mask):\n # self attn 的 qkv都一样\n attn_output, _ = self.muti_head_attn(inputs, inputs, inputs, mask)\n attn_output = self.dropout1(attn_output, training=training)\n out1 = self.layerNorm1(inputs + attn_output)\n ffn_output = self.ffn(out1)\n ffn_output = self.dropout2(ffn_output, training=training)\n out2 = self.layerNorm2(out1 + ffn_output)\n return out2\n\n\nif __name__ == '__main__':\n sample_encoder_layer = EncoderLayer(512, 8, 2048)\n sample_encoder_layer_output = sample_encoder_layer(\n tf.random.uniform((64, 43, 512)), False, None)\n\n print(sample_encoder_layer_output.shape)\n","sub_path":"translation/models/encoderLayer.py","file_name":"encoderLayer.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"101050052","text":"\"\"\"sheetshare URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom query_mutation.views import *\nfrom django.contrib import admin\nfrom sheetsys.views import *\nfrom query_gene.views import *\nfrom staff.views import *\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nurlpatterns = [\n url(r'^admincreatetype',admin_create_type),\n url(r'^recorddetail',record_detail),\n url(r'^adminupdatetype',admin_updateType),\n url(r'^admindeltype',admin_del_type),\n url(r'^adminsearchstaff',admin_search_staff),\n url(r'^adminsearchtype',admin_search_type),\n url(r'^staffcreaterecord',staff_createrecord),\n url(r'^staffalltype', staff_all_type),\n url(r'^staffallrecord', staff_all_record),\n url(r'^staffmanageallrecord',staff_manage_all_record),\n url(r'^staffsearchrecord', staff_search_record),\n url(r'^staffsearchtype', staff_search_type),\n url(r'^$',login),\n url(r'^logout',logout),\n url(r'^adminalltype',admin_all_type),\n url(r'^adminallstaff', admin_all_staff),\n url(r'^adminallrecord', admin_all_record),\n url(r'^adminsearchrecord', admin_search_record),\n url(r'^staffupdaterecord', staff_update_record),\n url(r'^admindelstaff',admin_del_staff),\n url(r'^adminpublishtype',admin_publish_type),\n url(r'^admincreatestaff',admin_create_staff),\n url(r'^adminindex',admin_index),\n url(r'^adminstaffupdate',admin_staff_update),\n url(r'^admindelrecord',admin_del_record),\n url(r'^checkallrecord',check_all_record),\n url(r'^checkalltype',check_all_type),\n url(r'^allsearchtype',all_search_type),\n url(r'^searchallrecord',search_all_record),\n url(r'^staffdelrecord',staff_del_record),\n url(r'^updateself',updateself),\n url(r'^recordinput',staff_record_input),\n url(r'^staffshowallrecord',staff_show_all_record),\n url(r'^admin_add_position',admin_add_position),\n url(r'^manage_position',admin_manage_position),\n url(r'^get_all_position/$',get_all_position),\n url(r'^adminmanageposition/$',admin_manage_position),\n url(r'^update_position_form/$',update_position_form),\n url(r'^admin_del_position/$',admin_del_position),\n url(r'^download_record/$',download_record),\n url(r'^jishuconfirmrecord/$',jishu_confirm_record),\n url(r'^staffsearchmanagetype/$', staff_search_manage_type),\n url(r'^update_database_DP/$', update_database_DP),\n url(r'^update_database_HGMD/$', update_database_HGMD),\n url(r'^update_database_OGM/$', update_database_OGM),\n url(r'^update_database_GD/$', update_database_GD),\n url(r'^update_database_MT/$', update_database_MT),\n url(r'^search_database_gene/$', search_database_gene),\n url(r'^to_specific_gene/$', to_specific_gene),\n url(r'^search_database_phenotype/$', search_database_phenotype),\n url(r'^to_update/$', to_update),\n url(r'^to_mutation_list/$', to_mutation_list),\n url(r'^to_specific_mutation/$', to_specific_mutation),\n\n]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"sheetshare/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"442011898","text":"from django.conf.urls import url\nfrom apps.home.views import *\n\napp_name = 'home'\nurlpatterns = [\n url(r'^$', index, name='index'),\n url(r'^login/$', login, name='login'),\n url(r'^logout/$', logout, name='logout'),\n url(r'^question/$', question, name='question'),\n url(r'^question/insert/$', question_insert, name='question_insert'),\n url(r'^schedule/$', schedule, name='schedule'),\n url(r'^detail/(?P[0-9]+)/$', detail, name='detail'),\n url(r'^post/$', post, name='post'),\n url(r'^post/insert/$', post_insert, name='post_insert'),\n url(r'^ajax/feeds/$', ajax_load_more, name='load_more_feeds'),\n url(r'^ajax/delete/$', ajax_delete_post, name='ajax_delete_post'),\n url(r'^ajax/dislike/$', ajax_downvote_post, name='ajax_downvote_post'),\n url(r'^ajax/undislike/$', ajax_undo_downvote_post, name='ajax_undo_downvote_post'),\n]\n","sub_path":"apps/home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"435957828","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport efd\n\ndef boundary_from_pixelated_mask(pixelated_mask):\n rows, columns = np.where(pixelated_mask == True)\n prev_r = 0\n coordinates_l = []\n coordinates_r = []\n for i, r in enumerate(rows):\n if prev_r != r:\n coordinates_l.append([columns[i]-0.5, r-0.5])\n coordinates_l.append([columns[i]-0.5, r+0.5])\n coordinates_r.append([columns[i-1]+0.5, prev_r-0.5])\n coordinates_r.append([columns[i-1]+0.5, prev_r+0.5])\n prev_r = r\n del coordinates_r[0:2] # pop initial useless value\n coordinates_r.append([columns[-1]+0.5, rows[-1]-0.5]) # add last value missing\n coordinates_r.append([columns[-1]+0.5, rows[-1]+0.5]) # add last value missing\n last_columns = np.where(rows == rows[-1])\n for i in np.arange(0.5, columns[-1]-columns[last_columns[0][0]], 1):\n coordinates_r.append([columns[-1]-i, rows[-1]+0.5])\n coordinates_r.reverse() # revers to add to l\n first_columns = np.where(rows == rows[0])\n for i in np.arange(0.5, columns[first_columns[0][-1]] - columns[0] , 1):\n coordinates_r.append([columns[first_columns[0][-1]]-i, rows[0]-0.5])\n coordinates = coordinates_l + coordinates_r\n coordinates.append(coordinates[0]) # duplicate start point\n return np.array(coordinates)\n\ndef smooth_boundary(boundary, descriptors):\n locus = efd.calculate_dc_coefficients(boundary)\n coeffs = efd.elliptic_fourier_descriptors(boundary, order=descriptors)\n contour = efd.reconstruct_contour(coeffs, locus=locus, num_points=100)\n return contour\n\ndef smooth_fd_boundary(boundary, descriptors):\n complex_boundary = np.array([x+1j*y for x, y in boundary])\n dft = np.fft.fft(complex_boundary)\n dft[1+descriptors:-descriptors] = 0\n smoothed_boundary = np.fft.ifft(dft)\n smoothed_boundary = np.stack((smoothed_boundary.real, smoothed_boundary.imag),-1)\n return smoothed_boundary\n\ndef create_mask(pred_mask):\n pred_mask = tf.argmax(pred_mask, axis=-1)\n pred_mask = pred_mask[..., tf.newaxis]\n return pred_mask[0]\n\ndef segment_cell(cell, model, pad_flag = True, height=80):\n # Normalize\n cell = (cell-np.min(cell))/(np.max(cell)-np.min(cell))\n if pad_flag:\n # Pad cell\n pad = (height - cell.shape[0]) / 2\n if pad.is_integer():\n cell = np.pad(cell, ((int(pad), int(\n pad)), (0, 0)), mode='constant', constant_values=0)\n else:\n cell = np.pad(cell, ((\n int(pad - 0.5), int(pad + 0.5)), (0, 0)),\n mode='constant', constant_values=0)\n\n # Add extra channel\n cell = cell[...,tf.newaxis]\n\n # Predict\n prediction = model.predict(cell[tf.newaxis, ...])\n pixelated_mask = create_mask(prediction)[:,:,0].numpy()\n\n # Remove padding \n if pad_flag:\n if pad.is_integer():\n pixelated_mask = pixelated_mask[int(pad):-int(pad),:]\n else:\n pixelated_mask = pixelated_mask[int(pad-0.5):-int(pad+0.5), :]\n\n return pixelated_mask\n\ndef display(display_list):\n plt.figure(figsize=(15, 15))\n\n title = ['Input Image', 'Predicted Mask']\n\n for i in range(len(display_list)):\n plt.subplot(1, len(display_list), i+1)\n plt.title(title[i])\n plt.imshow(display_list[i])\n plt.axis('off')\n plt.show()\n\ndef display_boundary(cell, boundaries):\n plt.figure(figsize=(15, 15))\n\n title = ['Pixelated Boundary', 'Smoothed Boundary']\n colors = ['r', 'g']\n\n plt.imshow(cell)\n for i in range(len(boundaries)):\n plt.plot(boundaries[i][:,0], boundaries[i][:,1], colors[i], label=title[i])\n plt.legend()\n plt.show()\n","sub_path":"segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"353553063","text":"#!/usr/bin/env python\n\"\"\"\nLicensed to the Apache Software Foundation (ASF) under one\nor more contributor license agreements. See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership. The ASF licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAmbari Agent\n\n\"\"\"\n\nimport time\nimport re\nimport logging\n\nfrom resource_management.core.exceptions import ExecutionFailed\nfrom resource_management.core.providers import Provider\nfrom resource_management.core.logger import Logger\nfrom resource_management.core import shell\nfrom ambari_commons import shell as ac_shell\n\n\nPACKAGE_MANAGER_LOCK_ACQUIRED_MSG = \"Cannot obtain lock for Package manager. Retrying after {0} seconds. Reason: {1}\"\nPACKAGE_MANAGER_REPO_ERROR_MSG = \"Cannot download the package due to repository unavailability. Retrying after {0} seconds. Reason: {1}\"\n\n\nclass PackageProvider(Provider):\n def __init__(self, *args, **kwargs):\n super(PackageProvider, self).__init__(*args, **kwargs) \n \n def install_package(self, name, use_repos={}, skip_repos=set(), is_upgrade=False):\n raise NotImplementedError()\n\n def remove_package(self, name, ignore_dependencies=False):\n raise NotImplementedError()\n\n def upgrade_package(self, name, use_repos={}, skip_repos=set(), is_upgrade=True):\n raise NotImplementedError()\n\n def action_install(self):\n package_name = self.get_package_name_with_version()\n self.install_package(package_name, self.resource.use_repos, self.resource.skip_repos)\n\n def action_upgrade(self):\n package_name = self.get_package_name_with_version()\n self.upgrade_package(package_name, self.resource.use_repos, self.resource.skip_repos)\n\n def action_remove(self):\n package_name = self.get_package_name_with_version()\n self.remove_package(package_name, self.resource.ignore_dependencies)\n\n def get_package_name_with_version(self):\n if self.resource.version:\n return self.resource.package_name + '-' + self.resource.version\n else:\n return self.resource.package_name\n\n def check_uncompleted_transactions(self):\n \"\"\"\n Check package manager against uncompleted transactions.\n\n :rtype bool\n \"\"\"\n return False\n\n def print_uncompleted_transaction_hint(self):\n \"\"\"\n Print friendly message about they way to fix the issue\n\n \"\"\"\n pass\n\n def get_available_packages_in_repos(self, repositories):\n \"\"\"\n Gets all (both installed and available) packages that are available at given repositories.\n :type repositories resource_management.libraries.functions.repository_util.CommandRepository\n :return: installed and available packages from these repositories\n \"\"\"\n raise NotImplementedError()\n\n def normalize_select_tool_versions(self, versions):\n \"\"\"\n Function expect output from get_all_package_versions\n\n :type versions str|list|set\n :rtype list\n \"\"\"\n raise NotImplementedError()\n\n def get_repo_update_cmd(self):\n raise NotImplementedError()\n\n def get_all_package_versions(self, pkg_name):\n \"\"\"\n :rtype list[str]\n \"\"\"\n raise NotImplementedError()\n\n def installed_pkgs_by_name(self, all_installed_packages, pkg_name):\n return list([i[0] for i in all_installed_packages if i[0].startswith(pkg_name)])\n\n def all_installed_packages(self, from_unknown_repo=False):\n \"\"\"\n Return all installed packages in the system except packages in REPO_URL_EXCLUDE\n\n :arg from_unknown_repo return packages from unknown repos\n :type from_unknown_repo bool\n\n :return result_type formatted list of packages\n \"\"\"\n raise NotImplementedError()\n\n def all_available_packages(self, result_type=list, group_by_index=-1):\n \"\"\"\n Return all available packages in the system except packages in REPO_URL_EXCLUDE\n\n :arg result_type Could be list or dict, defines type of returning value\n :arg group_by_index index of element in the __packages_reader result, which would be used as key\n :return result_type formatted list of packages, including installed and available in repos\n\n :type result_type type\n :type group_by_index int\n :rtype list|dict\n \"\"\"\n raise NotImplementedError()\n\n def get_installed_repos(self, hint_packages, all_packages, ignore_repos):\n \"\"\"\n Gets all installed repos by name based on repos that provide any package\n contained in hintPackages\n Repos starting with value in ignoreRepos will not be returned\n hintPackages must be regexps.\n \"\"\"\n all_repos = []\n repo_list = []\n\n for hintPackage in hint_packages:\n for item in all_packages:\n if re.match(hintPackage, item[0]) and not item[2] in all_repos:\n all_repos.append(item[2])\n\n for repo in all_repos:\n ignore = False\n for ignoredRepo in ignore_repos:\n if self.name_match(ignoredRepo, repo):\n ignore = True\n if not ignore:\n repo_list.append(repo)\n\n return repo_list\n\n def get_installed_pkgs_by_repo(self, repos, ignore_packages, installed_packages):\n \"\"\"\n Get all the installed packages from the repos listed in repos\n \"\"\"\n packages_from_repo = []\n packages_to_remove = []\n for repo in repos:\n sub_result = []\n for item in installed_packages:\n if repo == item[2]:\n sub_result.append(item[0])\n packages_from_repo = list(set(packages_from_repo + sub_result))\n\n for package in packages_from_repo:\n keep_package = True\n for ignorePackage in ignore_packages:\n if self.name_match(ignorePackage, package):\n keep_package = False\n break\n if keep_package:\n packages_to_remove.append(package)\n return packages_to_remove\n\n def get_installed_pkgs_by_names(self, pkg_names, all_packages_list=None):\n \"\"\"\n Gets all installed packages that start with names in pkgNames\n :type pkg_names list[str]\n :type all_packages_list list[str]\n \"\"\"\n if not all_packages_list:\n all_packages_list = self.all_installed_packages()\n\n packages = []\n for pkg_name in pkg_names:\n sub_result = self.installed_pkgs_by_name(all_packages_list, pkg_name)\n packages.extend(sub_result)\n\n return list(set(packages))\n\n def get_package_details(self, installed_packages, found_packages):\n \"\"\"\n Gets the name, version, and repoName for the packages\n :type installed_packages list[tuple[str,str,str]]\n :type found_packages list[str]\n \"\"\"\n package_details = []\n\n for package in found_packages:\n pkg_detail = {}\n for installed_package in installed_packages:\n if package == installed_package[0]:\n pkg_detail['name'] = installed_package[0]\n pkg_detail['version'] = installed_package[1]\n pkg_detail['repoName'] = installed_package[2]\n\n package_details.append(pkg_detail)\n\n return package_details\n\n def get_repos_to_remove(self, repos, ignore_list):\n repos_to_remove = []\n for repo in repos:\n add_to_remove_list = True\n for ignore_repo in ignore_list:\n if self.name_match(ignore_repo, repo):\n add_to_remove_list = False\n continue\n if add_to_remove_list:\n repos_to_remove.append(repo)\n return repos_to_remove\n\n def get_installed_package_version(self, package_name):\n raise NotImplementedError()\n\n def verify_dependencies(self):\n \"\"\"\n Verify that we have no dependency issues in package manager. Dependency issues could appear because of aborted or terminated\n package installation process or invalid packages state after manual modification of packages list on the host\n\n :return True if no dependency issues found, False if dependency issue present\n :rtype bool\n \"\"\"\n raise NotImplementedError()\n\n def name_match(self, lookup_name, actual_name):\n tokens = actual_name.strip().lower()\n lookup_name = lookup_name.lower()\n\n return \" \" not in lookup_name and lookup_name in tokens\n\n def is_locked_output(self, out):\n return False\n\n def is_repo_error_output(self, out):\n return False\n\n def get_logoutput(self):\n return self.resource.logoutput is True and Logger.logger.isEnabledFor(logging.INFO) or self.resource.logoutput is None and Logger.logger.isEnabledFor(logging.DEBUG)\n\n def call_with_retries(self, cmd, **kwargs):\n return self._call_with_retries(cmd, is_checked=False, **kwargs)\n \n def checked_call_with_retries(self, cmd, **kwargs):\n return self._call_with_retries(cmd, is_checked=True, **kwargs)\n\n def checked_call(self, cmd, **kwargs):\n return shell.checked_call(cmd, **kwargs)\n\n def _call_with_retries(self, cmd, is_checked=True, **kwargs):\n func = shell.checked_call if is_checked else shell.call\n code, out = -1, None\n\n # at least do one retry, to run after repository is cleaned\n try_count = 2 if self.resource.retry_count < 2 else self.resource.retry_count\n\n for i in range(try_count):\n is_first_time = (i == 0)\n is_last_time = (i == try_count - 1)\n\n try:\n code, out = func(cmd, **kwargs)\n except ExecutionFailed as ex:\n should_stop_retries = self._handle_retries(cmd, ex.code, ex.out, is_first_time, is_last_time)\n if should_stop_retries:\n raise\n else:\n should_stop_retries = self._handle_retries(cmd, code, out, is_first_time, is_last_time)\n if should_stop_retries:\n break\n\n time.sleep(self.resource.retry_sleep)\n\n return code, out\n\n def _call_with_timeout(self, cmd):\n \"\"\"\n :type cmd list[str]|str\n :rtype dict\n \"\"\"\n try:\n return ac_shell.subprocess_with_timeout(cmd)\n except Exception as e:\n Logger.error(\"Unexpected error:\" + str(e))\n\n return None\n\n def _executor_error_handler(self, command, error_log, exit_code):\n \"\"\"\n Error handler for ac_shell.process_executor\n\n :type command list|str\n :type error_log list\n :type exit_code int\n \"\"\"\n if isinstance(command, (list, tuple)):\n command = \" \".join(command)\n\n Logger.error(\"Command execution error: command = \\\"{0}\\\", exit code = {1}, stderr = {2}\".format(\n command, exit_code, \"\\n\".join(error_log)))\n\n def _handle_retries(self, cmd, code, out, is_first_time, is_last_time):\n # handle first failure in a special way (update repo metadata after it, so next try has a better chance to succeed)\n if is_first_time and code and not self.is_locked_output(out):\n self._update_repo_metadata_after_bad_try(cmd, code, out)\n return False\n\n handled_error_log_message = None\n if self.resource.retry_on_locked and self.is_locked_output(out):\n handled_error_log_message = PACKAGE_MANAGER_LOCK_ACQUIRED_MSG.format(self.resource.retry_sleep, out)\n elif self.resource.retry_on_repo_unavailability and self.is_repo_error_output(out):\n handled_error_log_message = PACKAGE_MANAGER_REPO_ERROR_MSG.format(self.resource.retry_sleep, out)\n\n is_handled_error = (handled_error_log_message is not None)\n if is_handled_error and not is_last_time:\n Logger.info(handled_error_log_message)\n\n return (is_last_time or not code or not is_handled_error)\n\n def _update_repo_metadata_after_bad_try(self, cmd, code, out):\n name = self.get_package_name_with_version()\n repo_update_cmd = self.get_repo_update_cmd()\n\n Logger.info(\"Execution of '%s' returned %d. %s\" % (shell.string_cmd_from_args_list(cmd), code, out))\n Logger.info(\"Failed to install package %s. Executing '%s'\" % (name, shell.string_cmd_from_args_list(repo_update_cmd)))\n code, out = shell.call(repo_update_cmd, sudo=True, logoutput=self.get_logoutput())\n\n if code:\n Logger.info(\"Execution of '%s' returned %d. %s\" % (repo_update_cmd, code, out))\n\n Logger.info(\"Retrying to install package %s after %d seconds\" % (name, self.resource.retry_sleep))\n\n\nclass RPMBasedPackageProvider(PackageProvider):\n \"\"\"\n RPM Based abstract package provider\n \"\"\"\n INSTALLED_PACKAGE_VERSION_COMMAND = \"rpm -q --queryformat '%{{version}}-%{{release}}' \\\"{0}\\\"\"\n\n def rpm_check_package_available(self, name):\n import rpm # this is faster then calling 'rpm'-binary externally.\n ts = rpm.TransactionSet()\n packages = ts.dbMatch()\n\n name_regex = re.escape(name).replace(\"\\\\?\", \".\").replace(\"\\\\*\", \".*\") + '$'\n regex = re.compile(name_regex)\n\n for package in packages:\n if regex.match(package['name']):\n return True\n return False\n\n def get_installed_package_version(self, package_name):\n version = None\n\n result = self.checked_call(self.INSTALLED_PACKAGE_VERSION_COMMAND.format(package_name))\n try:\n if result[0] == 0:\n version = result[1].strip().partition(\".el\")[0]\n except IndexError:\n pass\n\n return version\n","sub_path":"ambari-common/src/main/python/resource_management/core/providers/package/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"237024538","text":"\"\"\"\nCopyright (c) 2019, Oracle and/or its affiliates. All rights reserved.\nLicensed under the Universal Permissive License v 1.0 as shown at http://oss.oracle.com/licenses/upl.\n\"\"\"\nimport unittest\n\nfrom wlsdeploy.aliases.aliases import Aliases\nfrom wlsdeploy.aliases.wlst_modes import WlstModes\nfrom wlsdeploy.aliases.location_context import LocationContext\nfrom wlsdeploy.util.model_context import ModelContext\n\n\nclass AttributesTypeTestCase(unittest.TestCase):\n \"\"\"\n 1) Unit tests must be a class that extends unittest.TestCase\n 2) Class methods with names starting with 'test' will be executed by the framework (all others skipped)\n \"\"\"\n wls_version = '12.2.1.3'\n\n def testDelimitedAttributes(self):\n # This test ensures that delimited attributes are always comma-delimited for the model.\n # Space-delimited attributes are allowed to bypass this rule.\n\n model_context = ModelContext(\"test\", {})\n aliases = Aliases(model_context=model_context, wlst_mode=WlstModes.OFFLINE, wls_version=self.wls_version)\n\n location = LocationContext()\n self._check_folder(location, aliases)\n\n for folder_name in aliases.get_model_top_level_folder_names():\n location = LocationContext()\n location.append_location(folder_name)\n self._check_folder(location, aliases)\n\n def _check_folder(self, location, aliases):\n test_value = ['one', 'two']\n expected_value = ','.join(test_value)\n\n attr_infos = aliases.get_model_attribute_names_and_types(location)\n for key in attr_infos.keys():\n model_type = attr_infos[key]\n if model_type.startswith(\"delimited_string\") and not model_type.endswith(\"[space]\"):\n\n wlst_name = aliases.get_wlst_attribute_name(location, key)\n if wlst_name is not None:\n model_name, value = aliases.get_model_attribute_name_and_value(location, wlst_name, test_value)\n message = \"Value for attribute \" + key + \" in location \" + str(location.get_folder_path()) + \\\n \" should be comma-delimited\"\n self.assertEqual(expected_value, value, message)\n\n folder_names = aliases.get_model_subfolder_names(location)\n for folder_name in folder_names:\n new_location = LocationContext(location).append_location(folder_name)\n self._check_folder(new_location, aliases)\n return\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"core/src/test/python/attributes_type_test.py","file_name":"attributes_type_test.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"530530624","text":"from queue import Queue\n\nf = open('words.txt')\nwords = f.read().split(\"\\n\")\nf.close()\n\nword_set = set()\nfor word in words:\n word_set.add(word.lower())\n\nletters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n\n# Get Neighbors\ndef get_neighbors(word):\n neighbors = []\n\n # Turn our word into a letters list\n string_word = list(word)\n\n # For each of the letters; Iterate\n for index in range(len(string_word)):\n\n # Swap this letter with each letter in alphabet\n for letter in letters:\n temp_word = list(string_word)\n temp_word[index] = letter\n w = \"\".join(temp_word)\n if w != word and w in word_set:\n neighbors.append(w)\n return neighbors\n\n# BFS with path\ndef find_ladders(begin_word, end_word):\n queue = Queue()\n visited = set()\n queue.enqueue([begin_word])\n\n while queue.size() > 0:\n path = queue.dequeue()\n vertex = path[-1]\n\n if vertex not in visited:\n visited.add(vertex)\n if vertex == end_word:\n return path\n\n for neighbor in get_neighbors(vertex):\n path_copy = list(path)\n path_copy.append(neighbor)\n queue.enqueue(path_copy)\n","sub_path":"word_ladder.py","file_name":"word_ladder.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"464840872","text":"# !/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as scipy\nimport scipy.signal\n\nimport peakutils.peak\n\nfrom Utils.fileHandler import *\nfrom Utils.findpeaks import detect_peaks as detect_peaks_1\nfrom Utils.findpeaks import findpeaks as detect_peaks_2\nfrom Utils.findpeaks import peakdetect as detect_peaks_3\nfrom Utils.findpeaks import tony_beltramelli_detect_peaks as detect_peaks_4\n\nfrom Utils.dataHelper import *\nfrom Utils.fileHandler2 import *\n\ndef easy_plot(file_name):\n data = np.loadtxt(file_name)\n\n plt.figure(1)\n plt.plot(data, 'b')\n plt.show()\n\ndef easy_dot(file_name):\n data = np.loadtxt(file_name)\n\n plt.figure(1)\n plt.plot(data, '.')\n plt.show()\n\ndef plot_with_point_max_min(file_name):\n data = np.loadtxt(file_name)\n plt.figure(1)\n ax1 = plt.subplot(221)\n ax2 = plt.subplot(222)\n ax3 = plt.subplot(223)\n ax4 = plt.subplot(224)\n\n data_changed = data ** 5\n\n data_changed_v = np.diff(data_changed)\n data_changed_v_changed_v = np.diff(data_changed_v)\n\n data_changed_v_smoothed = get_center_of_the_data(data_changed_v, turn=10, all=5)\n data_changed_v_changed_v_smoothed = get_center_of_the_data(data_changed_v_changed_v, turn=10, all=5)\n\n data_changed_v_smoothed_max_index_list = detect_peaks_2.findpeaks(np.array(data_changed_v_smoothed), spacing=10)\n # data_changed_v_smoothed_max_index_list = get_min_index_below_the_base(data_changed_v_smoothed, base=0)\n\n plt.sca(ax1)\n plt.plot(data, 'b')\n\n for i in range(len(data_changed_v_smoothed_max_index_list)-1):\n index_max_2 = findpeaks(data[data_changed_v_smoothed_max_index_list[i]: data_changed_v_smoothed_max_index_list[i+1]], spacing=3, limit=None, type=True, base=data_changed_v_smoothed_max_index_list[i])\n data_tmp = []\n for index in index_max_2:\n data_tmp.append(data[index])\n if data_tmp:\n max_data = max(data_tmp)\n for i in range(len(index_max_2)):\n if max_data == data[index_max_2[i]]:\n max_index = index_max_2[i]\n if max_index != 0 and max_data != 0:\n plt.scatter(max_index, max_data, 10, color ='red')\n\n for i in range(len(data_changed_v_smoothed_max_index_list)-1):\n index_min_2 = findpeaks(data[data_changed_v_smoothed_max_index_list[i]: data_changed_v_smoothed_max_index_list[i+1]], spacing=3, limit=None, type=False, base=data_changed_v_smoothed_max_index_list[i])\n data_tmp = []\n for index in index_min_2:\n data_tmp.append(data[index])\n if data_tmp:\n min_data = min(data_tmp)\n for i in range(len(index_min_2)):\n if min_data == data[index_min_2[i]]:\n min_index = index_min_2[i]\n if min_index != 0 and min_data != 0:\n plt.scatter(min_index, min_data, 10, color ='green')\n\n plt.sca(ax3)\n plt.plot(data_changed_v_smoothed, 'b')\n for i in range(len(data_changed_v_smoothed_max_index_list)-1):\n plt.scatter(data_changed_v_smoothed_max_index_list[i], data_changed_v_smoothed[data_changed_v_smoothed_max_index_list[i]], 10, color ='red')\n\n plt.sca(ax2)\n plt.plot(data_changed_v, 'b')\n plt.sca(ax4)\n plt.plot(data_changed_v_changed_v, 'b')\n\n plt.show()\n\n# 小波变换\ndef plot_with_test_1(file_name):\n data = np.loadtxt(file_name)\n index_list = scipy.signal.find_peaks_cwt(data, np.arange(1, 20), max_distances=np.arange(1, 20)*2)\n index_list = np.array(index_list) - 1\n plt.figure(1)\n plt.plot(data, 'b')\n for index in index_list:\n plt.scatter(index, data[index], 10, color ='red')\n plt.show()\n\n# 差分(一个数的大小比较)\ndef plot_with_test_2(file_name):\n data = np.loadtxt(file_name)\n index_list = detect_peaks_1.detect_peaks(data, mpd=60)\n plt.figure(1)\n plt.plot(data, 'b')\n for index in index_list:\n plt.scatter(index, data[index], 10, color ='red')\n plt.show()\n\n# 差分(一个数的大小比较)\ndef plot_with_test_3(file_name):\n data = np.loadtxt(file_name)\n index_list = peakutils.peak.indexes(np.array(data), thres=7.0/max(data), min_dist=16)\n plt.figure(1)\n plt.plot(data, 'b')\n for index in index_list:\n plt.scatter(index, data[index], 10, color ='red')\n plt.show()\n# 大小比较(一个数的大小比较)\ndef plot_with_test_4(file_name):\n data = np.loadtxt(file_name)\n peaks = detect_peaks_3.peakdetect(np.array(data), lookahead=2, delta=2)\n index_list = []\n for posOrNegPeaks in peaks:\n for peak in posOrNegPeaks:\n index_list.append(peak[0])\n plt.figure(1)\n plt.plot(data, 'b')\n for index in index_list:\n plt.scatter(index, data[index], 10, color ='red')\n plt.show()\n\n# def plot_with_test_5(file_name):\n# data = np.loadtxt(file_name)\n# octave.eval(\"pkg load signal\")\n# (pks, indexes) = octave.findpeaks(np.array(data), 'DoubleSided',\n# 'MinPeakHeight', 6, 'MinPeakDistance', 2, 'MinPeakWidth', 0)\n# index_list = indexes[0].astype(int) - 1\n# plt.figure(1)\n# plt.plot(data, 'b')\n# for index in index_list:\n# plt.scatter(index, data[index], 10, color ='red')\n# plt.show()\n\n# 左右spacing个数大小比较\ndef plot_with_test_6(file_name):\n data = np.loadtxt(file_name)\n index_list = detect_peaks_2.findpeaks(np.array(data), spacing=10, limit=7)\n plt.figure(1)\n plt.plot(data, 'b')\n for index in index_list:\n plt.scatter(index, data[index], 10, color ='red')\n plt.show()\n\n# 用了什么方法平滑了曲线\n# 差分(一个数的大小比较)\ndef plot_with_test_7(file_name):\n data = np.loadtxt(file_name)\n # data = [1, 4, 9, 16, 25, 9, 1, 4, 9, 16, 25, 9, 36, 25, 9, 1]\n data = [1, 2, 3, 2, 1]\n index_list = detect_peaks_4.detect_peaks(data, 1.5)\n\n plt.figure(1)\n plt.plot(data, 'b')\n for index in index_list:\n plt.scatter(index, data[index], 10, color ='red')\n plt.show()\n\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"store/Python/learn/learn_scipy/find_peaks.py","file_name":"find_peaks.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"521396468","text":"from datetime import timedelta\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.db.models import Case, When\nfrom django.db.models.functions import Cast\nfrom django.urls import reverse\nfrom django.utils import timezone\n\nfrom adminsortable.models import SortableMixin\nfrom ckeditor_uploader.fields import RichTextUploadingField\nfrom sorl.thumbnail import ImageField\n\nfrom tags.models import Tag\n\nfrom . import choices\nfrom .managers import ResourceManager\n\n\nclass Resource(models.Model):\n title = models.CharField(max_length=140, unique=True)\n slug = models.SlugField(unique=True, null=True, max_length=140)\n abstract = models.TextField(\n max_length=140,\n help_text='This text will appear in search results',\n )\n content = RichTextUploadingField()\n categories = models.ManyToManyField('resources.ResourceCategory')\n tags = models.ManyToManyField(Tag, blank=True)\n image = ImageField(\n 'Background Image',\n upload_to='uploads/resources/images/%Y/%m/%d',\n blank=True,\n )\n organisation = models.ForeignKey(\n 'directory.Organisation',\n help_text='Of the groups you belong to, which one owns this resource?',\n on_delete=models.SET_NULL,\n null=True,\n )\n privacy = models.ManyToManyField(\n 'directory.Organisation',\n help_text='Of the groups you belong to, which should this resource be visible to?',\n related_name='resources_privacy',\n blank=True,\n )\n status = models.IntegerField(\n choices=choices.RESOURCES_STATUSES, default=choices.RESOURCE_WAITING_FOR_APPROVAL\n )\n likes = models.ManyToManyField(\n settings.AUTH_USER_MODEL, blank=True, related_name='resources_likes'\n )\n tried = models.ManyToManyField(\n settings.AUTH_USER_MODEL, blank=True, related_name='resources_tried'\n )\n hits = models.PositiveIntegerField('How many times page been hit?', default=0)\n\n created_by = models.ForeignKey(\n settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='resources_created'\n )\n updated_by = models.ForeignKey(\n settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='resources_updated'\n )\n created_at = models.DateTimeField(default=timezone.now)\n updated_at = models.DateTimeField(auto_now=True)\n\n objects = ResourceManager()\n\n class Meta:\n ordering = ('-created_at',)\n\n def __str__(self):\n return self.title\n\n def get_absolute_url(self):\n url = ''\n if self.slug:\n url = reverse('resources:resource-detail', kwargs={'slug': self.slug})\n return url\n\n def private_for_organisation(self, organisation):\n return organisation in self.privacy.all()\n\n @staticmethod\n def get_carousel_resources(user=None, limit=5):\n \"\"\" Get most popular resources for the last 7 days. \"\"\"\n resources = Resource.objects.approved(user=user).filter(\n created_at__gte=timezone.now() - timedelta(days=7)\n ).annotate(\n popular_count=(\n Cast(models.Count('tried'), models.PositiveIntegerField()) +\n Cast(models.Count('likes'), models.PositiveIntegerField()) + models.F('hits')\n )\n ).order_by('-popular_count')[:limit]\n return resources\n\n @staticmethod\n def get_latest(user=None):\n try:\n resource = Resource.objects.approved(user=user).earliest('created_at')\n except Resource.DoesNotExist:\n resource = None\n return resource\n\n @staticmethod\n def get_most_liked(user=None, exclude=None, limit=1):\n resources = Resource.objects.approved(user=user).exclude(id=exclude).annotate(\n most_liked=models.Count('likes')\n ).order_by(\n '-most_liked',\n )[:limit]\n return resources\n\n @staticmethod\n def get_most_tried(user=None, exclude=None, limit=1):\n resources = Resource.objects.approved(user=user).exclude(id=exclude).annotate(\n most_tried=models.Count('tried')\n ).order_by(\n '-most_tried',\n )[:limit]\n return resources\n\n def get_related(self, user=None, limit=3):\n data = {}\n results = {}\n ids_with_tags = Resource.objects.approved(\n user=user,\n ).exclude(\n id=self.id,\n ).values_list(\n 'id',\n 'tags',\n )\n for resource_id, tag in ids_with_tags:\n if resource_id in data:\n data[resource_id].append(tag)\n else:\n data[resource_id] = [tag]\n resource_tags = set(self.tags.values_list('id', flat=True))\n\n for resource_id, tags in data.items():\n matches = set(tags) & resource_tags\n results[resource_id] = len(matches)\n\n resources_ids = sorted(results, key=results.get, reverse=True)[:limit]\n preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(resources_ids)])\n resources = Resource.objects.filter(id__in=resources_ids).order_by(preserved)\n return resources\n\n\nclass ResourceCategory(models.Model):\n title = models.CharField(max_length=64, unique=True)\n slug = models.SlugField(max_length=64, unique=True)\n description = models.TextField()\n image = ImageField(\n 'Lead category image',\n upload_to='uploads/resources/categories/images/%Y/%m/%d',\n )\n\n class Meta:\n ordering = ('title',)\n verbose_name_plural = 'Resource categories'\n\n def __str__(self):\n return self.title\n\n def get_resource_count(self, user=None):\n return self.resource_set.approved(user).count()\n\n get_resource_count.verbose_name = 'Resources'\n\n def get_absolute_url(self):\n return reverse('resources:resource-category-detail', kwargs={'slug': self.slug})\n\n def get_approved_featured_resources(self, user):\n categories_featured_resources = self.category_featured_resources.values_list('resource_id')\n\n return Resource.objects.approved(user).filter(id__in=categories_featured_resources)\n\n\nclass ResourceCategoryFeatured(SortableMixin):\n category = models.ForeignKey(\n ResourceCategory, on_delete=models.CASCADE, related_name='category_featured_resources'\n )\n resource = models.ForeignKey(Resource, on_delete=models.CASCADE)\n project_order = models.PositiveIntegerField(default=0, editable=False, db_index=True)\n\n class Meta:\n verbose_name = 'Featured Resource'\n ordering = ['project_order']\n\n def __str__(self):\n return self.resource.title\n","sub_path":"apps/resources/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"456712542","text":"# -*- coding: utf8 -*-\n\n\"\"\"\ndiscord.py-docker test script\n\nthis script is used to determine if a container has built correctly or not\n\"\"\"\n\nimport importlib\nfrom pprint import pprint\n\nimport pytest\nfrom pip._internal.operations.freeze import freeze\n\nINSTALLED_PKGS = {\n x[0].lower(): (x[1] if len(x) >= 2 else None)\n for x in (\n y.split('==') for y in freeze()\n )\n}\n\nprint('\\nInstalled packages:')\npprint(INSTALLED_PKGS)\n\n\n@pytest.mark.skipif(\n 'uvloop' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'uvloop'\"\n)\ndef test_has_uvloop():\n import asyncio\n import uvloop\n\n asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\n\ndef test_has_discord():\n import discord\n assert discord.__version__\n\n client = discord.Client(intents=discord.Intents.all())\n assert hasattr(client, 'run')\n\n from discord.ext import commands\n\n bot = commands.Bot('?', intents=discord.Intents.all())\n assert hasattr(bot, 'on_message')\n\n\ndef test_has_voice():\n from discord.voice_client import has_nacl\n from discord.opus import is_loaded, Encoder\n\n Encoder() # Ensure opus gets loaded\n\n assert has_nacl\n assert is_loaded()\n\n\n@pytest.mark.skipif(\n 'pyyaml' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'pyyaml'\"\n)\ndef test_has_pyyaml():\n from inspect import cleandoc\n from random import randint\n\n from yaml import safe_load, dump\n\n data = safe_load(cleandoc('''\n - 123\n - \"quoted text\"\n - unquoted text\n - sample: |\n some text right here\n '''))\n\n assert data[0] == 123\n assert data[1] == 'quoted text'\n assert data[2] == 'unquoted text'\n assert isinstance(data[3], dict)\n assert data[3]['sample'].strip() == 'some text right here'\n\n random_data = [randint(0, 1000) for x in range(200)]\n assert safe_load(dump(random_data)) == random_data\n\n\n@pytest.mark.skipif(\n 'ruamel.yaml' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'ruamel.yaml'\"\n)\ndef test_has_ruamel():\n from inspect import cleandoc\n from random import randint\n from io import StringIO\n\n from ruamel.yaml import YAML\n\n yaml = YAML(typ='safe')\n data = yaml.load(cleandoc('''\n - 123\n - \"quoted text\"\n - unquoted text\n - sample: |\n some text right here\n '''))\n\n assert data[0] == 123\n assert data[1] == 'quoted text'\n assert data[2] == 'unquoted text'\n assert isinstance(data[3], dict)\n assert data[3]['sample'].strip() == 'some text right here'\n\n buff = StringIO()\n\n random_data = [randint(0, 1000) for x in range(200)]\n yaml.dump(random_data, buff)\n buff.seek(0)\n assert yaml.load(buff) == random_data\n\n\n@pytest.mark.skipif(\n 'fuzzywuzzy' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'fuzzywuzzy'\"\n)\ndef test_has_fuzzywuzzy():\n from fuzzywuzzy import fuzz, process\n\n assert fuzz.ratio('this is a test', 'this is a test!') > 96\n guess, confidence = process.extractOne('apple', 'alpha beta gamma sigma'.split())\n assert guess == 'alpha'\n assert confidence < 50\n\n\n@pytest.mark.skipif(\n 'pycryptodome' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'pycryptodome'\"\n)\n@pytest.mark.parametrize(\n 'hash_type',\n ['SHA256', 'SHA384', 'SHA512']\n)\ndef test_has_pycryptodome_hash(hash_type: str):\n import hashlib\n\n from Crypto import Random\n\n hashlib_hash = getattr(hashlib, hash_type.lower())\n pycrypto_hash = importlib.import_module(f'Crypto.Hash.{hash_type}')\n\n rndfile = Random.new()\n\n test = rndfile.read(1024)\n factory = pycrypto_hash.new()\n factory.update(test)\n assert hashlib_hash(test).digest() == factory.digest()\n\n\n@pytest.mark.skipif(\n 'pycryptodome' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'pycryptodome'\"\n)\n@pytest.mark.parametrize(\n 'cipher_type',\n ['AES', 'ARC2', 'Blowfish', 'CAST', 'DES3']\n)\ndef test_has_pycryptodome_cipher(cipher_type):\n from Crypto import Random\n\n pycrypto_cipher = importlib.import_module(f'Crypto.Cipher.{cipher_type}')\n\n rndfile = Random.new()\n\n key = rndfile.read(pycrypto_cipher.key_size[-1])\n iv = rndfile.read(pycrypto_cipher.block_size)\n\n enc = pycrypto_cipher.new(key=key, mode=pycrypto_cipher.MODE_CBC, iv=iv)\n\n text = rndfile.read(1024)\n ciphertext = enc.encrypt(text)\n\n dec = pycrypto_cipher.new(key=key, mode=pycrypto_cipher.MODE_CBC, iv=iv)\n\n return_text = dec.decrypt(ciphertext)\n\n assert text != ciphertext\n assert text == return_text\n\n@pytest.mark.skipif(\n 'pillow' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'pillow'\"\n)\ndef test_has_pillow():\n import colorsys\n import itertools\n import pathlib\n from PIL import Image, ImageChops\n\n data = bytes([int(x*255) for x in itertools.chain(*[colorsys.hsv_to_rgb(x / 255, 1, 1) for x in range(256)])])\n\n with Image.frombytes('RGB', (256, 1), data).resize((256, 100), Image.ANTIALIAS) as im:\n # write standard PNG file\n im.save('_test_pillow.png', 'png')\n assert pathlib.Path('_test_pillow.png').exists()\n\n # test quantization\n quantized = im.quantize()\n\n # write paletted BMP file\n quantized.save('_test_pillow.bmp', 'bmp')\n assert pathlib.Path('_test_pillow.bmp').exists()\n\n # write paletted GIF file\n quantized.save('_test_pillow.gif', 'gif')\n assert pathlib.Path('_test_pillow.gif').exists()\n\n # double quantization\n quantized2 = im.quantize(colors=16)\n\n # write paletted BMP file\n quantized2.save('_test_pillow_2.bmp', 'bmp')\n assert pathlib.Path('_test_pillow_2.bmp').exists()\n\n # write paletted GIF file\n quantized2.save('_test_pillow_2.gif', 'gif')\n assert pathlib.Path('_test_pillow_2.gif').exists()\n\n r, g, b = im.split()\n a = ImageChops.add(r, b, scale=2)\n im2 = Image.merge('RGBA', (r, g, b, a))\n\n # write transparent PNG file\n im2.save('_test_pillow_2.png', 'png')\n assert pathlib.Path('_test_pillow_2.png').exists()\n\n\n@pytest.mark.skipif(\n 'lxml' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'lxml'\"\n)\ndef test_lxml():\n from lxml import etree\n\n root = etree.Element('root')\n etree.SubElement(root, 'a')\n etree.SubElement(root, 'b')\n c = etree.SubElement(root, 'c')\n d = etree.SubElement(c, 'd')\n e = etree.SubElement(d, 'e')\n e.text = 'test'\n tree = etree.ElementTree(root)\n\n assert etree.tostring(tree) == b'test'\n\n\n@pytest.mark.skipif(\n 'beautifulsoup4' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'beautifulsoup4'\"\n)\ndef test_bs4():\n from bs4 import BeautifulSoup\n soup = BeautifulSoup('test title\\ntest text', 'html.parser')\n assert soup.title.string == 'test title'\n assert soup.get_text() == 'test title\\ntest text'\n\n\n@pytest.mark.parametrize(\n 'db',\n ['aiomysql', 'redis', 'asyncpg']\n)\ndef test_db_shallow(db):\n db_module = pytest.importorskip(db)\n assert db_module.__version__\n assert isinstance(db_module.__version__, str)\n\n\n@pytest.mark.skipif(\n 'wand' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'wand'\"\n)\ndef test_wand():\n import pathlib\n\n from wand.color import Color\n from wand.drawing import Drawing\n from wand.image import Image\n\n with Image(width=500, height=500) as outer:\n background_color = Color('#f00')\n with Image(width=250, height=250, background=background_color) as red_inner:\n outer.composite(red_inner, left=125, top=125)\n with outer.convert('png') as converted:\n converted.save(filename='_test_wand.png')\n\n assert pathlib.Path('_test_wand.png').exists()\n\n with Drawing() as draw:\n draw.stroke_color = Color('black')\n draw.stroke_width = 2\n draw.fill_color = Color('white')\n draw.arc(\n (25, 25),\n (75, 75),\n (135, -45)\n )\n\n with Image(width=100, height=100, background=Color('lightblue')) as im:\n draw.draw(im)\n with im.convert('png') as converted:\n converted.save(filename='_test_wand_2.png')\n\n assert pathlib.Path('_test_wand_2.png').exists()\n\n\n@pytest.mark.skipif(\n 'numpy' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'numpy'\"\n)\ndef test_has_numpy():\n import numpy as np\n\n a = np.arange(15).reshape(3, 5)\n b = a.T.reshape(15)\n c = (a.T @ a).reshape(25)\n assert all(b == [0, 5, 10, 1, 6, 11, 2, 7, 12, 3, 8, 13, 4, 9, 14])\n assert all(c == [125, 140, 155, 170, 185,\n 140, 158, 176, 194, 212,\n 155, 176, 197, 218, 239,\n 170, 194, 218, 242, 266,\n 185, 212, 239, 266, 293])\n\n\n@pytest.mark.skipif(\n 'scipy' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'scipy'\"\n)\ndef test_has_scipy():\n from scipy import integrate\n\n def f(x):\n # dy/dx = 4x^3 + 6x^2\n # so\n # y = x^4 + 2x^3\n return (4 * (x ** 3)) + (6 * (x ** 2))\n\n # where x = 1, y = 1^4 + 2*(1^4) = 1 + 2 = 3\n # where x = 2, y = 2^4 + 2*(2^4) = 16 + 16 = 32\n # so integrating between 1 and 2 for dy/dx gives us 3 - 32 = 29\n answer, error = integrate.quad(f, 1, 2)\n # check within bounds\n assert answer + error >= 29\n assert answer - error <= 29\n\n\n@pytest.mark.skipif(\n 'matplotlib' not in INSTALLED_PKGS,\n reason=\"skipping test for package not installed: 'matplotlib'\"\n)\ndef test_has_matplotlib():\n import pathlib\n from io import BytesIO\n\n import matplotlib\n matplotlib.use('Agg')\n\n import numpy as np\n import matplotlib.pyplot as plt\n import matplotlib.tri as mtri\n from cycler import cycler\n from matplotlib import cm\n from mpl_toolkits.mplot3d.axes3d import get_test_data\n\n X = np.arange(-5, 5, 0.25)\n Y = np.arange(-5, 5, 0.25)\n X, Y = np.meshgrid(X, Y)\n R = np.sqrt(X**2 + Y**2)\n Z = np.sin(R)\n\n fig = plt.figure(figsize=(19.2, 14.4))\n ax = fig.add_subplot(3, 3, 1, projection='3d')\n ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis)\n\n ax.set_title('matplotlib')\n\n ax2 = fig.add_subplot(3, 3, 2, projection='3d')\n X, Y, Z = get_test_data(0.05)\n ax2.plot_wireframe(X, Y, Z, rstride=5, cstride=5, linestyles='dashdot')\n\n ax2.set_title('3d')\n\n u = np.linspace(0, 2.0 * np.pi, endpoint=True, num=50)\n v = np.linspace(-0.5, 0.5, endpoint=True, num=10)\n u, v = np.meshgrid(u, v)\n u, v = u.flatten(), v.flatten()\n\n x = (1 + 0.5 * v * np.cos(u / 2.0)) * np.cos(u)\n y = (1 + 0.5 * v * np.cos(u / 2.0)) * np.sin(u)\n z = 0.5 * v * np.sin(u / 2.0)\n\n tri = mtri.Triangulation(u, v)\n\n ax3 = fig.add_subplot(3, 3, 3, projection='3d')\n ax3.plot_trisurf(x, y, z, triangles=tri.triangles, cmap=cm.jet)\n\n ax3.set_title('plot')\n\n radii = np.linspace(0.125, 1.0, 8)\n angles = np.linspace(0, 2*np.pi, 36, endpoint=False)\n\n angles = np.repeat(angles[..., np.newaxis], 8, axis=1)\n\n x = np.append(0, (radii*np.cos(angles)).flatten())\n y = np.append(0, (radii*np.sin(angles)).flatten())\n\n z = np.sin(-x*y)\n\n ax4 = fig.add_subplot(3, 3, 4, projection='3d')\n ax4.plot_trisurf(x, y, z, linewidth=0.2, cmap=cm.Spectral)\n\n ax4.set_title('test')\n\n X, Y, Z = get_test_data(0.05)\n ax5 = fig.add_subplot(3, 3, 5, projection='3d')\n ax5.contour(X, Y, Z, extend3d=True, cmap=cm.coolwarm)\n\n ax5.set_title('for')\n\n ax6 = fig.add_subplot(3, 3, 6, projection='3d')\n\n ax6.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)\n ax6.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)\n ax6.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)\n ax6.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)\n\n ax6.set_xlim(-40, 40)\n ax6.set_ylim(-40, 40)\n ax6.set_zlim(-100, 100)\n\n ax6.set_title('docker')\n\n theta = np.linspace(0.0, 2 * np.pi, 20, endpoint=False)\n radii = 10 * np.random.rand(20)\n width = np.pi / 4 * np.random.rand(20)\n\n ax7 = fig.add_subplot(3, 3, 7, projection='polar')\n bars = ax7.bar(theta, radii, width=width, bottom=0.0)\n\n for r, bar in zip(radii, bars):\n bar.set_facecolor(cm.viridis(r / 10.))\n bar.set_alpha(0.5)\n\n ax7.set_title('also this')\n\n x = np.linspace(0, 2 * np.pi)\n offsets = np.linspace(0, 2*np.pi, 4, endpoint=False)\n\n yy = np.transpose([np.sin(x + phi) for phi in offsets])\n\n ax8 = fig.add_subplot(3, 2, 6)\n ax8.set_prop_cycle(cycler('color', ['r', 'g', 'b', 'y']) +\n cycler('linestyle', ['-', '--', ':', '-.']))\n\n ax8.plot(yy)\n\n ax8.set_title('and one of these too')\n\n # check it writes to buffer properly first\n out_buffer = BytesIO()\n plt.savefig(out_buffer, dpi=160, format='png', bbox_inches='tight')\n out_buffer.seek(0)\n\n assert out_buffer.read(4) == b'\\x89PNG'\n\n # write to file for good measure\n with open('_test_plot_image.png', 'wb') as op:\n op.write(b'\\x89PNG' + out_buffer.read())\n\n assert pathlib.Path('_test_plot_image.png').exists()\n","sub_path":"dockerfiles/discordpy/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":13328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"635328875","text":"#!/usr/bin/env python\n#coding=utf8\n\n__author__ = 'liugang'\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import sqrt, sin, cos, pi\nfrom matplotlib.colors import hsv_to_rgb\n\ndef Klein(z):\n #Klein j-函数\n return 1728*(z*(z**10+11*z**5-1))**5 / (-(z**20+1)+228*(z**15-z**5)-494*z**10)**3\n\ndef RiemannSphere(z):\n #将复平面上的点利用球极投影对应到Riemann球面上\n t = 1 + z.real**2 + z.imag**2\n return 2*z.real/t, 2*z.imag/t,2/t-1\n\ndef Mobius(z):\n #用一个mobius变换扭曲图像\n return (z-20)/(3*z+1j)\n\nx,y = np.ogrid[-5:5:800j,-5:5:800j]\nz = x + y*1j\nz = Klein(z)\nz = Mobius(z)\nz = Klein(z)\nw = RiemannSphere(z)\n\nH = sin(w[0]*pi)**2\nS = cos(w[1]*pi)**2\nV = abs(sin(w[2]*pi) * cos(w[2]*pi))**0.2\n\nHSV = np.dstack((H,S,V))\nrgb = hsv_to_rgb(HSV)\n\nfig = plt.figure(figsize=(4,4))\nax = fig.add_axes([0,0,1,1],aspect=1)\nax.axis('off')\nplt.imshow(rgb)\nplt.show()\n# plt.savefig('Icosa_Symmetry.png')","sub_path":"tool/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"146781105","text":"from enum import Enum\nimport sys\nimport re\n\nclass Tile:\n def __init__( self, wall, marks ):\n self.wall = wall # bool - is wall?\n self.marks = marks # int - number of marks - 0 for walls\n \nclass Position:\n def __init__( self, x, y, direction ):\n self.x = x\n self.y = y\n self.direction = direction\n \nclass Dimensions:\n def __init__( self, width, height ):\n self.width = width\n self.height = height\n \nclass Direction(Enum):\n North = 1\n East = 2\n South = 3\n West = 4\n \nclass World:\n def __init__( self, position, dimensions, tiles):\n self.position = position\n self.dimensions = dimensions\n self.tiles = tiles\n\ndef getDimensions(line, fileName=None):\n dimensions = line.split()\n if len(dimensions) != 2:\n if fileName:\n print(fileName + ':1: the world dimensions line is in an incorrect format', file=sys.stderr)\n return None\n if (not dimensions[0].strip().isdigit()) or (not dimensions[1].strip().isdigit()):\n if fileName:\n print(fileName + ':1: the world dimensions must be whole numbers', file=sys.stderr)\n return None\n x = int(dimensions[0])\n y = int(dimensions[1])\n if x == 0 or y == 0:\n if fileName:\n print(fileName + ':1: the world dimensions cannot be zero', file=sys.stderr)\n return None\n return Dimensions(x, y)\n \ndef getDirection(dir):\n if dir == 'n':\n return Direction.North\n elif dir == 'e':\n return Direction.East\n elif dir == 's':\n return Direction.South\n elif dir == 'w':\n return Direction.West\n else:\n print('If you see this, something went horribly wrong')\n return None\n\ndef getPosition(line, dimensions, fileName=None):\n positions = line.split()\n if len(positions) != 3:\n if fileName:\n print(fileName + ':2: the starting position line is in incorrect format', file=sys.stderr)\n return None\n if (not positions[0].strip().isdigit()) or (not positions[1].strip().isdigit()):\n if fileName:\n print(fileName + ':2: the starting postiion is in incorrect format', file=sys.stderr)\n return None\n x = int(positions[0])\n y = int(positions[1])\n if x >= dimensions.width or y >= dimensions.height:\n if fileName:\n print(fileName + ':2: the starting position cannot be outside of the world', file=sys.stderr)\n return None\n if not (len(positions[2]) == 1 and positions[2] in 'nesw'):\n if fileName:\n print(fileName + ':2: the starting direction can only be n/e/s/w', file=sys.stderr)\n return None\n return Position(int(positions[0]), int(positions[1]), getDirection(positions[2]))\n\ndef transformToTiles(line):\n tileArray = []\n for x in line:\n if x == '#':\n tileArray.append(Tile(True, 0))\n elif x == ' ':\n tileArray.append(Tile(False, 0))\n elif x.isdigit():\n tileArray.append(Tile(False, int(x)))\n else:\n print('If you see this, something went horribly wrong')\n return None\n return tileArray\n\ndef getWorld(fileName):\n lineCount = 0\n worldRegex = re.compile(r'^[# 0-9]*$')\n worldArrays = []\n with open(fileName, 'r') as world:\n for line in world:\n lineCount += 1\n if lineCount == 1:\n dimensions = getDimensions(line, fileName=fileName)\n if not dimensions:\n return None\n if lineCount == 2:\n position = getPosition(line, dimensions, fileName=fileName)\n if not position:\n return None\n if lineCount > 2:\n if line[-1] != '\\n':\n print(fileName + ':' + str(lineCount) + ': teach line in the world map must end with \\\\n', file=sys.stderr)\n return None\n line = line[:-1]\n if (lineCount - 2) > dimensions.height:\n print(fileName + ':' + str(lineCount) + ': the world map is higher than the defined height', file=sys.stderr)\n return None\n if len(line) != dimensions.width:\n print(fileName + ':' + str(lineCount) + ': the world map has incorrect dimensions (width)', file=sys.stderr)\n return None\n if not worldRegex.match(line):\n print(fileName + ':' + str(lineCount) + ': the world map contains invalid characters', file=sys.stderr)\n return None\n worldArrays.append(transformToTiles(line)) \n \n if lineCount == 0:\n print(fileName + ':1: the world file is empty', file=sys.stderr)\n return None\n if lineCount == 1:\n print(fileName + ':2: the world file has only 1 line (missing position and world map)', file=sys.stderr)\n return None\n if len(worldArrays) < dimensions.height:\n print(fileName + ':' + str(lineCount + 1) + ': file ended sooner than expected - the world map is incomplete', file=sys.stderr)\n return None\n if worldArrays[position.y][position.x].wall:\n print(fileName + ':2: karel cannot spawn inside a wall', file=sys.stderr)\n return None\n \n return World(position, dimensions, worldArrays)\n \ndef main():\n if getWorld(sys.argv[1]):\n sys.exit(0)\n else:\n sys.exit(2)\n\nif __name__ == \"__main__\":\n main()","sub_path":"karel/chk_world.py","file_name":"chk_world.py","file_ext":"py","file_size_in_byte":5509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"65121236","text":"\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport time\r\n\r\ndef fun(x):\r\n a= 1/x\r\n y= x**2+ x**3+ x**4+a\r\n\r\n return y\r\n\r\ndef fun_deriv(x):\r\n\r\n dy_dx= 2*x+ 3*x**2+ 4*x**3 - 1/x**2\r\n\r\n return dy_dx\r\n\r\nx= tf.Variable(2.0)\r\nwith tf.GradientTape(persistent= True) as g:\r\n\r\n g.watch(x)\r\n dy_dx_tens= fun_deriv(x)\r\n\r\n'''tensorflow gradient tape evaluation time'''\r\nt1_tens= time.clock()\r\ng.gradient(dy_dx_tens, x)\r\nt2_tens= time.clock()\r\nprint('time tens:{}'.format(t2_tens- t1_tens))\r\n\r\n'''gradient evaluation time using code'''\r\nt1_code= time.clock()\r\ndy_dx= fun_deriv(x)\r\nt2_code= time.clock()\r\nprint('time code:{}'.format(t2_code- t1_code))\r\n","sub_path":"tensorflow_automatic_diff_speed_test.py","file_name":"tensorflow_automatic_diff_speed_test.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"111669302","text":"#\n# @lc app=leetcode.cn id=19 lang=python3\n#\n# [19] 删除链表的倒数第 N 个结点\n#\n\n# @lc code=start\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n if head is None:\n return None\n p_fast = head\n guard_node = ListNode(0, head)\n p_pre = guard_node\n count = 1\n while p_fast.next is not None:\n if count >= n:\n p_pre = p_pre.next\n p_fast = p_fast.next\n count = count + 1\n # 进行删除\n p_pre.next = p_pre.next.next\n return guard_node.next\n# @lc code=end","sub_path":"leetcode/19.删除链表的倒数第n个结点/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"446427048","text":"\"\"\"pychatApi URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.conf.urls.static import static\nfrom api.views import start_valentine, valentine, notify, continue_new_year, birthday25, upload_file, galina_1, \\\n\tgalina_2, galina_3\nfrom pychatApi import settings\n\nurlpatterns = [\n\turl(r'^toMyDearGirlFriend', start_valentine),\n\turl(r'^ILoveYou', valentine, name='continue_valentine'),\n\turl(r'^galina_1', galina_1, name='galina_1'),\n\turl(r'^galina_2', galina_2, name='galina_2'),\n\turl(r'^galina_3', galina_3, name='galina_3'),\n\turl(r'^notify$', notify),\n\turl(r'^25', start_valentine),\n\turl(r'^HappyNewYear$', continue_new_year, name='continue_new_year'),\n\turl(r'^HappyBirthday', birthday25, name='continue_birthday'),\n\turl(r'^upload_file', upload_file),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"pychatApi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"237110522","text":"\nimport abc\nimport pystache\nimport types\n\nclass ServiceTemplate():\n __metaclass__ = abc.ABCMeta\n template = '''\n{\n \"doc_type\": \"service_description\",\n \"doc_version\": \"0.20.0\",\n \"doc_scope\": \"{{scope}}\",\n \"active\": {{active}},\n \"service_id\": \"{{service_id}}\",\n \"service_type\": \"{{service_type}}\",\n \"service_name\": \"{{service_name}}\", \n \"service_version\": \"{{service_version}}\",\n \"service_endpoint\": \"{{node_endpoint}}{{service_endpoint}}\",\n \"service_auth\": {\n \"service_authz\": [\n {{authz}}\n ],\n \"service_key\": {{service_key}},\n \"service_https\": {{service_https}}\n }{{#service_data}},\"service_data\":{{service_data}}{{/service_data}}\n}'''\n service_data_template = None\n\n def _optsoverride(self):\n return {}\n \n def _servicedata(self,**kwargs):\n if self.service_data_template != None:\n return pystache.render(self.service_data_template, self.opts)\n return None\n \n def _authz(self, **kwargs):\n return None\n\n opts = {\n \"scope\": \"node\",\n \"active\": \"false\",\n \"service_id\": None,\n \"service_type\": \"access\",\n \"service_name\": None,\n \"service_version\": None,\n \"node_endpoint\": None,\n \"service_endpoint\": None,\n \"authz\": _authz,\n \"service_key\": \"false\", \n \"service_https\": \"false\",\n \"service_data\": _servicedata\n }\n \n \n \n def render(self, **kwargs):\n self.opts.update(self._optsoverride())\n funcs = []\n for key in self.opts.keys():\n if key in kwargs:\n if isinstance(kwargs[key], types.BooleanType):\n self.opts[key] = repr(kwargs[key]).lower()\n else:\n self.opts[key] = kwargs[key]\n \n if isinstance(self.opts[key], types.FunctionType):\n funcs.append(key)\n \n for key in funcs:\n self.opts[key] = self.opts[key](self, **self.opts)\n \n return pystache.render(self.template, self.opts)\n ","sub_path":"config/services/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"652010866","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 15 16:24:53 2020\n\n@author: pedro\n\"\"\"\n\nimport pandas as pd\nimport os\nfrom subprocess import run, PIPE\nfrom Bio.Align.Applications import ClustalOmegaCommandline\nimport sys\n\n\n\n\ndef clustal(in_file = \"unaligned.fasta\", out_file = \"out_filename.fasta\"):\n # file = open(\"unaligned.fasta\", \"w\")\n # file.write(seqs)\n # file.close()\n clustalomega_cline = ClustalOmegaCommandline(infile=in_file, outfile=out_file, verbose=True, auto=False)\n os.system('cmd /c crmapp\\clustal-omega-1.2.2-win64\\\\' + \n str(clustalomega_cline) + ' --outfmt clustal --force')\n\n\ndef vfp_seqs(filename=\"Seqs_prots.csv\"):\n dataset = pd.read_csv(filename)\n \n dataset['Family'] = dataset['Family'].str.strip()\n \n dataset_3_in_family = pd.DataFrame({'Family' : [], \n 'Sequence_fusogenic': [],\n 'Sequence': []})\n \n \"\"\"\n path = \"/tmp/fastas/\"\n\n try:\n os.mkdir(path)\n except OSError:\n print (\"Creation of the directory %s failed\" % path)\n \n \"\"\"\n \n families_multiple_align = []\n \n for i in dataset.Family.unique():\n dataset_family = dataset.loc[dataset['Family'] == i]\n if dataset_family.shape[0] > 3:\n dataset_3_in_family.append(dataset_family, ignore_index=True)\n file = open(i + \".fasta\", \"w\")\n index = 1\n for j in dataset_family.values:\n file.write(\">\" + i + \" \" + str(index) + \"\\n\")\n index += 1\n file.write(j[1] + \"\\n\")\n families_multiple_align.append(i)\n \n file.close()\n \n for i in families_multiple_align:\n clustalomega_cline = ClustalOmegaCommandline(infile=i + \".fasta\", \n outfile=i + \".clustal_num\", \n verbose=True, \n auto=False) \n \n os.system('cmd /c crmapp\\clustal-omega-1.2.2-win64\\\\' \n + str(clustalomega_cline) + ' --force')\n \n \n\nvfp_seqs()\n \n \n ","sub_path":"vfp_web_server/clustal_family.py","file_name":"clustal_family.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"288847995","text":"'''code adapted from https://github.com/experiencor/keras-yolo3'''\nimport numpy as np\nimport os\nimport cv2\n\nclass BoundBox:\n def __init__(self, xmin, ymin, xmax, ymax, c = None, classes = None):\n self.xmin = xmin \n self.ymin = ymin \n self.xmax = xmax\n self.ymax = ymax\n \n self.c = c\n self.classes = classes\n\n self.label = -1\n self.score = -1\n\n def get_label(self):\n if self.label == -1:\n self.label = np.argmax(self.classes)\n \n return self.label\n \n def get_score(self):\n if self.score == -1:\n self.score = self.classes[self.get_label()]\n \n return self.score \n\ndef _interval_overlap(interval_a, interval_b):\n \n x1, x2 = interval_a\n x3, x4 = interval_b\n # overlap is lesser of x4, x2 minus the greater of x3, x1\n overlap = min(x4,x2) - max(x3,x1)\n # overlap should be >= 0 (otherwise there is no overlap)\n return max(overlap, 0) \n\ndef bbox_iou(box1, box2):\n \n intersect_w = _interval_overlap([box1.xmin, box1.xmax], [box2.xmin, box2.xmax])\n intersect_h = _interval_overlap([box1.ymin, box1.ymax], [box2.ymin, box2.ymax]) \n \n intersect = intersect_w * intersect_h\n \n w1, h1 = box1.xmax-box1.xmin, box1.ymax-box1.ymin\n w2, h2 = box2.xmax-box2.xmin, box2.ymax-box2.ymin\n \n union = w1*h1 + w2*h2 - intersect\n iou = float(intersect) / union if union > 0 else 0\n return iou\n \n\ndef draw_boxes_gt(image, boxes):\n ''' Draw ground truth boxes'''\n for box in boxes:\n xmin = box[1]\n xmax = box[3]\n ymin = box[2]\n ymax = box[4]\n\n cv2.rectangle(image, (xmin,ymin), (xmax,ymax), (0,0,255), 2)\n \n return image \ndef draw_boxes(image, boxes, labels, obj_thresh, quiet=True):\n accepted_boxes =[]\n for box in boxes:\n label_str = ''\n label = -1\n \n for i in range(len(labels)):\n if box.classes[i] > obj_thresh:\n accepted_boxes.append(box)\n if label_str != '': label_str += ', '\n label_str += (labels[i] + ' ' + str(round(box.get_score(), 2)))\n label = i\n if not quiet: print(label_str)\n \n if label >= 0:\n text_size = cv2.getTextSize(label_str, cv2.FONT_HERSHEY_SIMPLEX, 1.1e-3 * image.shape[0], 5)\n width, height = text_size[0][0], text_size[0][1]\n region = np.array([[box.xmin-3, box.ymin], \n [box.xmin-3, box.ymin-height-26], \n [box.xmin+width+13, box.ymin-height-26], \n [box.xmin+width+13, box.ymin]], dtype='int32') \n\n cv2.rectangle(img=image, pt1=(box.xmin,box.ymin), pt2=(box.xmax,box.ymax), color=(0,255,0), thickness=2)\n #cv2.fillPoly(img=image, pts=[region], color=get_color(label))\n cv2.putText(img=image, \n text=label_str, \n org=(box.xmin-3, box.ymin - 3), \n fontFace=cv2.FONT_HERSHEY_SIMPLEX, \n fontScale=7e-4 * image.shape[0], \n color=(0,255,0), \n thickness=2)\n \n return image ,accepted_boxes ","sub_path":"utils/bbox.py","file_name":"bbox.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"411299320","text":"# Patrol the village entrances.\n# If you find an enemy, attack it.\nwhile True:\n hero.moveXY(35, 34)\n leftEnemy = hero.findNearestEnemy()\n if leftEnemy:\n hero.attack(leftEnemy)\n hero.attack(leftEnemy)\n # Now move to the right entrance.\n hero.moveXY(60, 31)\n # Use findNearestEnemy again to find the right enemy.\n rightEnemy = hero.findNearestEnemy()\n # Use \"if\" to attack twice if there is a right enemy.\n if rightEnemy:\n hero.attack(rightEnemy)\n hero.attack(rightEnemy)","sub_path":"python/Backwood Forest/village guard.py","file_name":"village guard.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"328982620","text":"\"\"\"\nTwo elements of a binary search tree (BST) are swapped by mistake.\n\nRecover the tree without changing its structure.\n\nNote:\nA solution using O(n) space is pretty straight forward. Could you devise a constant space solution?\n\n\"\"\"\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\"\"\"\nA:\n 1. 题目中 二叉搜索树 中序遍历一定増序, 但是中序遍历増序不一定是 二叉搜索树.\n 2. 只交换了两个节点.\n 原来中序: 1,2,3,4,5,6,7\n swap: 1,6,3,4,5,2,7 \n 2 6交换后,导致中序遍历 不再递增,所以只要找到 这两个node 交换val即可\n\n\"\"\"\n\n\"\"\"\nS1: \n 中序递归\n 1. 记录pre\n 2. 主要是从递增的中序遍历中找到两处反常, \n first 和second 点\nR:\n 1. https://leetcode.com/discuss/13034/no-fancy-algorithm-just-simple-and-powerful-order-traversal\n\n\"\"\"\nclass Solution(object):\n def recoverTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: void Do not return anything, modify root in-place instead.\n \"\"\"\n def inOrder(p):\n global first,second,pre\n if not p :\n return \n inOrder(p.left)\n if first == None and pre.val> p.val: # 记录 first 应该是pre\n first = pre\n if first !=None and pre.val>p.val: # 记录 second 应该是当前node\n second = p\n pre = p\n inOrder(p.right)\n\n global first,second,pre\n first,second = None,None\n pre = TreeNode(-1*2**31)\n inOrder(root)\n print(first.val)\n print(second.val)\n first.val, second.val = second.val,first.val #swap\n return \n\n\n\"\"\"\nS2:\n 如果要使用o(1) 空间,可以使用 中序的Morris 遍历.\n\n\"\"\"\n\n\n\"\"\"\nS3:\n 中序迭代\n\"\"\"\nclass Solution(object):\n def recoverTree(self, root):\n\n m_stack = []\n p = root\n first,second, = None,None\n pre = TreeNode(-1*2**31)\n\n while p or m_stack:\n while p :\n m_stack.append(p)\n p = p.left\n p = m_stack.pop() #visit\n if first == None and pre.val> p.val:\n first = pre\n if first and pre.val > p.val:\n second = p\n pre = p\n p = p.right\n first.val, second.val = second.val,first.val #swap\n return \n\nif __name__ == '__main__':\n S = Solution()\n q1 = TreeNode(3)\n q2 = TreeNode(1)\n q3 = TreeNode(2)\n q1.left =q2\n q1.right = q3\n\n ss =S.recoverTree(q1)\n print(ss.left.val)\n\n\n\n\n","sub_path":"99_Recover Binary Search Tree.py","file_name":"99_Recover Binary Search Tree.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"396311029","text":"'''\nEach cell below contains comments explaing the code in it.\n1. Beginning of the file reads the compound feature matrix, kinase feature matrix and the dti matrix\n2. Builds a simple collaborative filtering model for the dti matrix - perform training and testing\n3. Builds Single task models using various ML classifiers like Logistic Regression, SVM, Neural network and KNN\n\n'''\n#%% Data Visualization\nfrom sklearn.decomposition import PCA\npca = PCA(n_components = 2)\npca.fit(compMat)\nydown = pca.transform(compMat)\nimport matplotlib.pyplot as plt\nplt.plot(ydown[:,0], ydown[:,1], '.')\nplt.xlabel(\"Principal component 1\")\nplt.ylabel(\"Principal component 2\")\nplt.title('PCA plot of drug features')\n\n\nfrom sklearn.manifold import MDS\nmds = MDS(n_components = 2, dissimilarity = 'precomputed')\nymds = mds.fit_transform(1-compSim)\nplt.plot(ymds[:,0], ymds[:,1], '.')\nplt.xlabel(\"Embedded dimension 1\")\nplt.ylabel(\"Embedded dimension 2\")\nplt.title('2-dimensional embedding of drug features with Metric MDS')\n\n\nz = ymds[:,0]\ny = ymds[:,1]\nn = np.linspace(0,len(y)-1, len(y))\nfig, ax = plt.subplots()\nax.scatter(z, y)\n\nfor i, txt in enumerate(n):\n ax.annotate(int(txt), (z[i],y[i]))\nax.xlabel('Embedded dimension 1')\nax.ylabel('Embedded dimension 2')\nax.title('2-dimensional embedding of drug features with Metric MDS')\n#%% Read matrices\nimport numpy as np\nimport pandas as pd\n#from matrix_completion import *\n# Create the 3 matrices and write cell to load them easily\n# Be in data/DrugKinet folder\ncompMat = pd.read_csv('ecfp4.csv')\ncompMat = compMat['ecfp4']\ncompMat = compMat.as_matrix()\nT = [[int(i) for i in list(x)] for x in compMat]\ncompMat = np.asarray(T)\ncompMat = 2*compMat - 1\n\nkinaseMat = pd.read_csv('../bowVecs5.csv')\nkinases = pd.read_csv('Kinases.csv')\n\n\n#Just changed\nkinaseMat2 = pd.read_csv('../readinPy.csv')\nkinaseFeat = np.zeros([246,5])\n\nfor i in range(len(kinaseMat)):\n a = kinaseMat.siRNA[i]\n ind = np.where(kinases == a)\n if(len(ind[0]) > 0):\n kinaseFeat[ind[0],:] = np.array(kinaseMat.loc[i][1:]) #Change to 2: for readinPy.csv\n #kinaseFeat[ind[0],:] = np.array(kinaseMat2.loc[i][2:]) #Change to 2: for readinPy.csv\ndti = pd.read_csv('dti.csv')\ndti = dti.as_matrix()\ndti = dti*2-1 \n\n#%% Test for compound prediction\ntemp= compMat\ncompMat = kinaseFeat\ndti = np.transpose(dti)\n\n#%% Logistic Regression, SVM, Neural network and KNN\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import metrics\nfrom sklearn.semi_supervised import LabelPropagation\nimport matplotlib.pyplot as plt\n\naucList = []; apcList = []; templist = [];\nfor trial in range(10):\n testSize = 0.3\n nRow = np.size(dti,0)\n nCol = np.size(dti,1)\n mask = np.zeros([nRow, nCol])\n temp = np.random.rand(nRow)\n mask[temp>testSize,:] = 1\n \n \n \n acc = []\n true = []; pred = []\n case = 'LR';\n for task in range(nCol):\n #print('Task:',task)\n if(case == 'LR'):\n model = LogisticRegression()\n elif(case == 'SVM'):\n model = SVC(kernel = 'linear', probability=True)\n elif(case == 'NN'):\n model = MLPClassifier(hidden_layer_sizes = (50), \\\n activation = 'logistic', verbose = False, \\\n learning_rate = 'adaptive')\n elif(case == 'KNN'):\n model = KNeighborsClassifier(n_neighbors=3, weights = 'distance')\n elif(case == 'RF'):\n model = RandomForestClassifier(n_estimators = 100, max_depth=5)\n \n testInds = (mask[:,task]==0)\n trainInds = (mask[:,task]==1) \n if(case == 'SSLP'):\n model = LabelPropagation(kernel = 'knn', n_neighbors = 5)\n X = compMat\n y = (dti[:,task]+1)/2\n y[testInds] = -1\n model.fit(X,y)\n ypred = model.predict_proba(X[testInds,:])\n ytest = dti[testInds,task]\n pred = np.append(pred,1-ypred[:,0])\n true = np.append(true,ytest)\n \n \n else:\n X = compMat[trainInds,:]\n y = dti[trainInds,task]\n try:\n model.fit(X,y)\n Xtest = compMat[testInds,:]\n ytest = dti[testInds,task]\n ypred = model.predict_proba(Xtest)\n #print(\"Accuracy =\", sum(ypred == ytest)/len(ypred))\n #acc.append(sum(ypred == ytest)/len(ypred))\n pred = np.append(pred,1-ypred[:,0])\n \n true = np.append(true,ytest)\n templist = np.append(templist, metrics.roc_auc_score(ytest, 1-ypred[:,0]))\n except:\n #print('Error')\n continue\n \n \n \n \n true = np.ndarray.flatten(np.asarray(true))\n pred = np.ndarray.flatten(np.asarray(pred))\n \n #true = true[pred=='nan']\n '''\n fpr, tpr, thresholds = metrics.roc_curve(true, pred, pos_label=1)\n plt.plot(fpr, tpr, color='darkorange',lw=2); \n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve')\n plt.show()\n '''\n auc = metrics.roc_auc_score(true, pred)\n print(\"AUC score:\",auc)\n apc = metrics.average_precision_score(true, pred) \n print(\"APC score:\",apc)\n \n aucList.append(auc);\n apcList.append(apc);\n \n \n \n '''\n from sklearn.metrics import precision_recall_curve\n from sklearn.utils.fixes import signature\n precision, recall, _ = precision_recall_curve(true, pred)\n\n # In matplotlib < 1.5, plt.fill_between does not have a 'step' argument\n step_kwargs = ({'step': 'post'}\n if 'step' in signature(plt.fill_between).parameters\n else {})\n plt.step(recall, precision, color='b', alpha=0.2,\n where='post')\n plt.fill_between(recall, precision, alpha=0.2, color='b', **step_kwargs)\n \n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.ylim([0.0, 1.05])\n plt.xlim([0.0, 1.0])\n plt.title('2-class Precision-Recall curve: AP={0:0.2f}'.format(apc))\n '''\n \n \ntemp = np.random.choice(10,100)\naucList = np.array(aucList)\naucList = aucList[temp]\nprint(\"Mean AUC score:\",np.mean(aucList))\nprint(\"CF:\",np.percentile(aucList,[2.5,97.5]))\n\napcList = np.array(apcList)\napcList = apcList[temp]\nprint(\"Mean APC score:\",np.mean(apcList))\nprint(\"CF:\",np.percentile(apcList,[2.5,97.5]))\n\n#%% MISC\ntemp= np.zeros([len(true),2]);\ntemp[:,0] = true;\ntemp[:,1] = pred;\n\n","sub_path":"DrugKinet_codes/baseAlgos.py","file_name":"baseAlgos.py","file_ext":"py","file_size_in_byte":6708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"199998278","text":"import spacy\nnlp = spacy.load('en')\n\nWORD_ORDER = [\"TIME\", \"DO\", \"SUB\", \"VERB\"]\nWORD_ORDER_IO = [\"TIME\", \"SUB\", \"IO\", \"DO\", \"VERB\"]\n# WORD_ORDER = [\"SUB\", \"VERB\", \"DO\"]\nsen_dic = {\"SUB\": [], \"IO\": [], \"DO\": [], \"VERB\": [], \"TIME\": []}\n\n\ndef findAdj(lefts, pos):\n\tfor l in lefts:\n\t\tif l.dep_ == \"amod\":\n\t\t\tsen_dic[pos].append(l)\n\ndef findSub(lefts):\n\tfor l in lefts:\n\t\tif l.dep_ == \"nsubj\":\n\t\t\tsen_dic[\"SUB\"].append(l)\n\t\t\tfindAdj(l.lefts, \"SUB\")\n\ndef findRights(rights):\n\tfor r in rights:\n\t\tif r.dep_ == \"dobj\":\n\t\t\tsen_dic[\"DO\"].append(r)\n\t\t\tfindAdj(r.lefts, \"DO\")\n\t\telif r.dep_ == \"dative\":\n\t\t\tsen_dic[\"IO\"].append(r)\n\t\t\tfindAdj(r.lefts, \"IO\")\n\ndef findVerb(sentence):\n\tfor word in sentence:\n\t\tif word.pos_ == \"VERB\":\n\t\t\tlefts = word.lefts\n\t\t\tfindSub(lefts)\n\t\t\tif word.n_rights != 0:\n\t\t\t\tsen_dic[\"VERB\"].append(word.lemma_)\n\t\t\t\trights = word.rights\n\t\t\t\tfindRights(rights)\n\n\t# # print(parsed_text)\n\n\t# output = []\n\n\t# #get token dependencies\n\t# for text in parsed_text:\n\t# \t# text = text.lemma_\n\t# \tprint(text)\n\t# \tprint(\"Tag: \" + text.tag_)\n\t# \tprint(\"Dep: \" + text.dep_)\n\t# \tif text.dep_ == 'nsubj':\n\t# \t\toutput.append(str(text).lower())\n\t# \telif text.tag_[:2] == 'VB' and text.dep_ == \"ROOT\":\n\t# \t\toutput.append(text.lemma_)\n\t# \telif text.dep_ == \"dobj\" or text.dep_ == \"oprd\":\n\t# \t\toutput.append(text.lemma_)\n\n\t# # for el in sen_dic:\n\t# # \tif \n\t# print(output)\n\t# return output\n\t# # print(subject)\n\t# # print(direct_object)\n\t# # print(indirect_object)\n\t# for token in doc:\n\t\t# print(token.text, token.dep_, token.head.text, token.head.pos_, [child for child in token.children])\n\ndef translate(sentence):\n\n\tdoc = nlp(sentence)\n\n\tif (len(sentence.split(' ')) == 1):\n\t\tprint (doc[0])\n\t\treturn doc[0]\n\tfindVerb(doc)\n\t# doc = nlp(argv[1])\n\tfor ent in doc.ents:\n\t\tif ent.label_ == \"DATE\":\n\t\t\tsen_dic[\"TIME\"] = ent\n\toutput = []\n\n\tif (len(sen_dic[\"IO\"]) == 0):\n\t\torder = WORD_ORDER\n\telse:\n\t\torder = WORD_ORDER_IO\n\n\tfor val in order:\n\t\tfor word in sen_dic[val]:\n\t\t\toutput.append(str(word).lower())\n\tprint (output)\n\treturn output\n\n\n","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"468855476","text":"#!/usr/bin/python\n\nimport subprocess\nimport sys\nimport os\n\nif len(sys.argv) < 3 or len(sys.argv) > 4:\n print (\"usage: ./match_outs.py [output_file]\")\n exit()\n\noutput = subprocess.check_output(\"cat \" + sys.argv[2] + \" | \" + sys.argv[1], shell=True).decode(\"UTF-8\").strip().split('\\n')\n\nout_filename = None\nif (len(sys.argv) == 3):\n out_filename = sys.argv[2]\n out_filename = out_filename.replace(\"input\", \"output\")\nelse:\n out_filename = sys.argv[3]\n\nwith open(out_filename) as out_file:\n match = True\n line_count = 0\n for line_memo, line_out in zip(out_file, output):\n line_memo = line_memo.strip().split(\" \")\n line_out = line_out.strip().split(\" \")\n count = 0\n for num_memo, num_out in zip(line_memo, line_out):\n if (num_memo != num_out):\n print (\"mismatch at position %i on line %i\" % (count, line_count))\n match = False\n count += 1\n line_count += 1\n\nif match:\n print (\"Answer matches that of output file \" + out_filename)\n","sub_path":"hackerrank_complete/largest_rect/match_outs.py","file_name":"match_outs.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"435281051","text":"\"\"\"Views from the 206.\"\"\"\n\n\nfrom pyramid.response import Response\nimport io\nimport os\n\n\nTHIS_DIR = os.path.dirname(__file__)\n\n\nENTRIES = [\n {\"title\": \"Entry 1\",\n \"id\": 0,\n \"creation_date\": \"Dec 20, 2016\",\n \"body\": \"Learned some stuff.\",\n },\n {\"title\": \"Entry 2\",\n \"id\": 1,\n \"creation_date\": \"Dec 20, 2016\",\n \"body\": \"Learned some stuff.\",\n },\n {\"title\": \"Entry 3\",\n \"id\": 2,\n \"creation_date\": \"Dec 20, 2016\",\n \"body\": \"Learned some stuff.\",\n },\n]\n\n\ndef list_view(request):\n \"\"\"View for index.\"\"\"\n file_path = os.path.join(THIS_DIR, \"templates\", \"index.html\")\n file_data = io.open(file_path).read()\n return Response(file_data)\n\n\ndef detail_view(request):\n \"\"\"View for individual posts.\"\"\"\n file_path = os.path.join(THIS_DIR, \"data\", \"learning-journal-day-11.html\")\n file_data = io.open(file_path).read()\n return Response(file_data)\n\n\ndef create_view(request):\n \"\"\"View for new posts.\"\"\"\n file_path = os.path.join(THIS_DIR, \"templates\", \"create.html\")\n file_data = io.open(file_path).read()\n return Response(file_data)\n\n\ndef update_view(request):\n \"\"\"View to edit posts.\"\"\"\n file_path = os.path.join(THIS_DIR, \"templates\", \"update.html\")\n file_data = io.open(file_path).read()\n return Response(file_data)\n\n\ndef includeme(config):\n \"\"\"Includeme func. The configurator will attach my views to routes.\"\"\"\n config.add_view(list_view,\n route_name=\"index\"\n )\n\n config.add_view(detail_view,\n route_name=\"detail\"\n )\n\n config.add_view(create_view,\n route_name=\"create\"\n )\n\n config.add_view(update_view,\n route_name=\"update\"\n )\n","sub_path":"learning_journal_basic/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"151043469","text":"import csv\nimport pdb\nimport picks\nimport synonyms\nfrom game import Game\nfrom round import Round\nfrom bracket import Bracket\nfrom team import Team\nimport numpy as np\nimport pickle\nimport os\n\ndef fname_from_fullpath(fullpath):\n return os.path.splitext(os.path.basename(fullpath))[0]\n\ndef load_pickle(fname):\n with open(fname, 'rb') as fp:\n data = pickle.load(fp)\n return data['ids'], data['seed_diffs']\n\ndef write_pickle(fname, ids, seed_diffs):\n with open(fname, 'wb') as fp:\n pickle.dump({'ids':ids, 'seed_diffs':seed_diffs}, fp)\n\ndef sort_region(region):\n return [region[0], region[7], region[4], region[3], \n region[5], region[2], region[6], region[1]]\n\ndef sort_first_games(first_games):\n first_games = sorted(first_games, key=lambda k:k[0].seed)\n first_games = sorted(first_games, key=lambda k:k[0].region)\n\n # Alphabetical\n East = sort_region(first_games[0:8])\n Midwest = sort_region(first_games[8:16])\n South = sort_region(first_games[16:24])\n West = sort_region(first_games[24:32])\n \n # Use order from actual bracket here\n return East + West + South + Midwest \n\ndef csv_row2dict(row, fieldnames):\n data = {}\n i = 0\n for field in row:\n field = field.strip()\n try:\n curr = float(field)\n except:\n if field == 'False':\n curr = False\n elif field == 'True':\n curr = True\n else:\n curr = field\n data[fieldnames[i]] = curr\n i = i + 1\n return data\n\nclass Forecast:\n def __init__(self, forecast_file, truth_file=''):\n self.forecast_file = forecast_file\n self.truth_file = truth_file\n self.idmap = {}\n self.teams = {} # dict id -> Team\n self.first_games = []\n\n self.read_forecast(forecast_file)\n self.make_name_to_id_lookup()\n if len(truth_file) > 0:\n self.add_truth(truth_file)\n self.hardcode_first_round() \n self.find_first_games()\n self.write_truth_file('./truth/base.truth')\n\n def get_bracket(self):\n return Bracket(self.first_games) \n\n def find_game(self, i_rnd, team_id):\n bracket = self.get_bracket()\n rnd = bracket.rounds[i_rnd-1]\n return rnd.find_game(team_id)\n\n def add_truth(self, truth_file):\n # Expects csv with a header row and then\n # two columns, Name and Final Round\n with open(truth_file, 'r') as f:\n reader = csv.reader(f, delimiter=',')\n header = reader.__next__()\n while header[0][0] == '#':\n header = reader.__next__()\n for row in reader:\n name, final_round = row[0], int(row[1])\n curr_id = self.name_to_id(name)\n self.teams[curr_id].update_final_round(final_round)\n \n def hardcode_first_round(self):\n # 11a 2057 East Belmont \n # 11b 218 East Temple \n\n # 16a 161 West Fairleigh Dickinson\n # 16b 2504 West Prairie View \n\n # 16b 2449 East North Dakota State \n # 16a 2428 East North Carolina Central \n\n # 11a 9 West Arizona State \n # 11b 2599 West St. John's (NY) \n\n playin_winners = [2057, 161, 2449, 9]\n playin_losers = [218, 2504, 2428, 2599]\n\n for t_id in playin_winners:\n self.teams[t_id].seed = float(self.teams[t_id].seed[0:2])\n self.teams[t_id].playin_flag = 0\n for t_id in playin_losers:\n self.teams.pop(t_id)\n\n for team_id, team in self.teams.items():\n if team.playin_flag > 0:\n print(team.seed, team_id, team.region, team.name)\n\n def find_first_games(self):\n games = []\n for _, team1 in self.teams.items():\n assert(not team1.playin_flag)\n if team1.seed <= 8:\n for _, team2 in self.teams.items():\n if team1.region == team2.region and team2.seed == 17 - team1.seed:\n games.append((team1, team2)) \n first_games = sort_first_games(games)\n self.first_games = Round(first_games, rnd=1)\n\n def read_forecast(self, fname):\n teams = {}\n with open(fname, 'r') as f:\n reader = csv.reader(f, delimiter=',')\n header = reader.__next__()\n id_idx = header.index('team_id')\n for row in reader:\n if row[0] == 'mens':\n curr_id = int(row[id_idx])\n team_dict = csv_row2dict(row, header)\n teams[curr_id] = Team(team_dict)\n self.teams = teams\n\n def make_name_to_id_lookup(self):\n for teamid in self.teams:\n team = self.teams[teamid]\n self.idmap[team.name.lower()] = team.id\n\n def name_to_id(self, name): \n name = name.lower().strip()\n if name in synonyms.synonyms:\n name = synonyms.synonyms[name].lower().strip()\n if name in self.idmap:\n return int(self.idmap[name])\n else:\n print('\"{}\" not found in forecast bracket'.format(name)) \n z = [x for x in self.idmap]\n z.sort()\n print(z)\n pdb.set_trace()\n # raise(\"Error\")\n\n def write_truth_file(self, outfile, title=''):\n with open(outfile, 'wt') as fo:\n fo.write('# ' + title + '\\n')\n fo.write('Name, Final Round\\n')\n for game in self.first_games.games:\n game.teams[0].write_to_truth_file(fo)\n game.teams[1].write_to_truth_file(fo)\n\n # def baseline(self):\n # return Bracket(self.first_games).convert()\n\n def get_pickle_fname(self, N):\n forecast_file = fname_from_fullpath(self.forecast_file)\n truth_file = fname_from_fullpath(self.truth_file)\n return \"./brackets/{}_{}_{}.p\".format(forecast_file, truth_file, N)\n\n def gen_brackets(self, N, use_pickle=True, verbose=False):\n fname = self.get_pickle_fname(N)\n if os.path.isfile(fname) and use_pickle:\n print('Found existing pickle')\n return load_pickle(fname)\n\n print('Generating brackets')\n ids = np.zeros((N, 63), dtype='uint16')\n seed_diffs = np.zeros((N, 63), dtype='int8')\n for i in range(N):\n if verbose and i % 1000 == 0:\n print(i)\n ids[i,:], seed_diffs[i,:] = self.get_bracket().convert()\n \n if use_pickle:\n write_pickle(fname, ids, seed_diffs)\n print('Bracket generation complete.')\n return ids, seed_diffs\n\n","sub_path":"forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":6614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"525891379","text":"import numpy as numpy\nfrom numpy import matrix\nfrom Maze import Maze\nfrom robot import Robot\n\nclass sensor_problem:\n\n def __init__(self, maze, timestep):\n\n self.maze = maze\n self.robot = Robot(self.maze, timestep)\n\n # array composed of colors SENSED by the robot (not necessarily accurate)\n # index of colors is the timestep\n self.path = self.robot.make_readings()\n self.timestep = timestep\n\n # represents what coordinates coorespond to what state\n self.index_to_color = []\n\n # maps an x-y coordinate to a state value\n # state is a single random variable X, where X_i can represent\n # the probabiliy the robot is at a given state\n self.state_map = self.make_state_map()\n\n # produce a transition matrix where T_(ij) = P(x_t = j | x_(t - 1) = i)\n self.transition_matrix = self.make_transition_matrix()\n\n # produce a dictionary of sensor matrices\n # key is a color which maps to a particular sensor matrix\n # (since colors on the map do not change)\n # sensor matrix is a diagonal matrix O_t where P(e_t | x_t = i), i = state value\n self.sensor_matrices = self.make_sensor_matrices()\n\n def solve(self):\n\n # get a starting vector\n starting = self.starting_distribution()\n\n # feed starting vector to start filtering\n solution = self.filter(starting)\n self.render_solution(solution)\n\n def render_solution(self, solution):\n\n # statistics and paths that help with debugging\n print(\"sensed path: {}\".format(str(self.path)))\n print(\"correct path: {}\".format(str(self.robot.correct_locs)))\n\n if len(self.robot.error_msgs) == 0:\n print(\"no mistakes in sensors\")\n else:\n print(\"mistakes: \")\n for msg in self.robot.error_msgs:\n print(\" {}\".format(msg))\n print(\"\")\n\n # for each iteration of the solution, display probability values\n timestep = 0\n\n # solution is a list of vectors (where vector is a distribution of probabilities)\n for vector in solution:\n\n # convert the matrix back to a list for easier processing\n l = numpy.array(vector).tolist()[0]\n display = [] # displayed solution\n row = [] # each row of a solution\n row_element = 0 # index of a particular row element\n index = 0 # index of the solution vector\n\n # build display matrix\n for item in l:\n\n color = self.index_to_color[index]\n item_string = \"|{}: \".format(color) + \"{0:.5f}\".format(item) + \"|\"\n row.append(item_string)\n\n # if reach the width, then start a new row\n row_element += 1\n if row_element > self.maze.width - 1:\n row_element = 0\n display.append(row)\n row = []\n index += 1\n\n # reorder the display vector so (0, 0) is on bottom-left\n display.reverse()\n\n # title each timestep\n if timestep == 0:\n print(\" t = 0 (starting values)\")\n elif timestep == 1:\n print(\" t = 1 (robot begins sensing)\")\n else:\n print(\" t = {}\".format(timestep))\n\n index = self.maze.height - 1\n for row in display:\n\n # build y-axis on left\n print(\"{} \".format(index), end='')\n index -= 1\n for item in row:\n print(item, end='')\n print(\"\")\n\n # build x axis on bottom\n starting = \" 0\"\n for i in range(1, self.maze.width):\n starting += \" {}\".format(i)\n print(starting)\n print(\"\")\n timestep += 1\n\n def filter(self, starting):\n\n # initliaze an array with the starting vector\n distributions = [starting]\n\n # for as long as as there is still a timestep\n for t in range(self.timestep):\n\n # get color at particular time\n color = self.path[t]\n\n # get the previous solution vector\n prev = distributions[t]\n\n # multiply that solution vector by the transposed transition matrix\n intermediate = prev * self.transition_matrix\n\n # multiply that intermediate value with the appropriate sensor matrix\n result = intermediate * self.sensor_matrices[color]\n r = normalize(result)\n distributions.append(r)\n\n # return a distribution of vectors for each timestep\n return distributions\n\n # create the starting vector (where all appropriate states have equal probability)\n def starting_distribution(self):\n start = []\n\n # starting probability is 1/(number of legal states)\n starting_probability = float(1/(len(self.state_map) - self.maze.num_walls()))\n for coord in self.state_map:\n state = self.state_map[coord]\n\n # if the state value is a wall\n if state[1]:\n start.append(0)\n\n # otherwise append the correct probability\n else:\n start.append(starting_probability)\n\n # convert to a matrix\n s = matrix(start)\n return s\n\n def make_state_map(self):\n\n state_map = {}\n state = 0\n\n # each i, j coordinate represents a state value, where robot may be\n for j in range(self.maze.height):\n for i in range(self.maze.width):\n\n # link the state value to color (with index being state value)\n self.index_to_color.append(self.maze.get_color(i, j))\n\n # state_map maps coordinate to (state value, is_wall)\n if self.maze.is_floor(i, j):\n state_map[tuple((i, j))] = (state, False)\n else:\n state_map[tuple((i, j))] = (state, True)\n state += 1\n\n return state_map\n\n def make_transition_matrix(self):\n mat = self.initialize_matrix()\n\n # fill in matrix with transition probabilities\n for j in range(self.maze.height):\n for i in range(self.maze.width):\n state, wall_at_state = self.state_map[tuple((i, j))]\n\n # if there is no wall at state, then proceed\n # otherwise, state is automatically given a value of 0\n if not wall_at_state:\n\n legal_moves = self.find_legal_moves(i, j)\n num_legal_moves = len(legal_moves)\n\n # probability of staying (explained in documentation)\n mat[state][state] = float((5 - num_legal_moves)/4)\n for move in legal_moves:\n adj_state = self.state_map[move][0]\n if adj_state != state:\n\n # there is always a .25 chance\n # of moving into a location\n mat[state][adj_state] = .25\n\n # the transpose the transition matrix\n m = matrix(mat).getT()\n return m\n\n # produces the dictionary of sensor matrices\n # only needs to be run in beginning because colors do not change\n def make_sensor_matrices(self):\n\n # dictionary that maps color to the appropriate sensor matrix\n matrices = {}\n\n for color in self.maze.colors:\n\n mat = self.initialize_matrix()\n\n for j in range(self.maze.height):\n for i in range(self.maze.width):\n\n state, wall_at_state = self.state_map[tuple((i, j))]\n\n if not wall_at_state:\n\n # the robot has an .88 chance of sensing the correct color\n if self.maze.get_color(i, j) == color:\n mat[state][state] = self.robot.error_threshold\n\n # the remaining .12 is split between the other colors\n else:\n mat[state][state] = ((1 - self.robot.error_threshold)/\n (len(self.maze.colors) - 1))\n\n m = matrix(mat)\n\n # map the color to the correct matrix\n matrices[color] = m\n\n return matrices\n\n # gets legal moves given a coordinate\n # there are up to 5 legal moves (NSEW and current location)\n # the robot can always be in the current location\n def find_legal_moves(self, x, y):\n legal_moves = []\n legal_moves.append(tuple((x, y)))\n\n # north\n if self.maze.is_floor(x, y + 1):\n legal_moves.append(tuple((x, y + 1)))\n\n # south\n if self.maze.is_floor(x, y - 1):\n legal_moves.append(tuple((x, y - 1)))\n\n # east\n if self.maze.is_floor(x + 1, y):\n legal_moves.append(tuple((x + 1, y)))\n\n # west\n if self.maze.is_floor(x - 1, y):\n legal_moves.append(tuple((x - 1, y)))\n\n return legal_moves\n\n # create an SxS 2d-list (where S is number of states)\n # fill all values with 0\n def initialize_matrix(self):\n\n mat = []\n\n # initialize maze\n for i in range(len(self.state_map)):\n row = []\n for j in range(len(self.state_map)):\n row.append(0)\n mat.append(row)\n\n return mat\n\n# from https://stackoverflow.com/questions/21030391/how-to-normalize-array-numpy\ndef normalize(v):\n norm = numpy.linalg.norm(v)\n if norm == 0:\n return v\n return v/norm\n\nif __name__ == \"__main__\":\n\n # load maze and problem\n test_maze = Maze(\"mazes/maze0.maz\")\n test_problem = sensor_problem(test_maze, 5)\n\n # display maze for debugging\n print(\"Maze (robot labeled as 1):\")\n print(test_problem.maze)\n\n test_problem.solve()\n","sub_path":"sensor_problem.py","file_name":"sensor_problem.py","file_ext":"py","file_size_in_byte":9952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"482558934","text":"#!/usr/bin/python3\n\nimport numpy as np\nimport sys\n\ncubeDirections = {\n 'se': (+1, -1, 0), 'ne': (+1, 0, -1), 'n': (0, +1, -1),\n 'nw': (-1, +1, 0), 'sw': (-1, 0, +1), 's': (0, -1, +1)\n}\n\n\ndef cubeDistance(a, b):\n return int((abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2])) / 2)\n\n\ndef main():\n for line in sys.stdin:\n position = (0, 0, 0)\n steps = [dir for dir in line.strip().split(',')]\n maximumDistance = 0\n\n for step in steps:\n position = np.add(position, cubeDirections[step])\n currentDistance = cubeDistance((0, 0, 0), position)\n\n if currentDistance > maximumDistance:\n maximumDistance = currentDistance\n\n print('Current distance:', cubeDistance((0, 0, 0), position))\n print('Maximum distance:', maximumDistance)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2017/11/puzzle1and2.py","file_name":"puzzle1and2.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"291485231","text":"from typing import Optional\n\nimport fastapi\nimport httpx\n\nfrom models.location import Location\nfrom models.umbrella_status import UmbrellaStatus\n\nrouter = fastapi.APIRouter()\n\n\n@router.get('/api/umbrella', response_model=UmbrellaStatus)\nasync def do_i_need(location: Location = fastapi.Depends()):\n url = f'https://weather.talkpython.fm/api/weather?city={location.city}&country={location.country}&units=imperial'\n if location.state:\n url += f'&state={location.state}'\n\n async with httpx.AsyncClient() as client:\n resp = await client.get(url)\n resp.raise_for_status()\n print(resp.status_code)\n print(resp.text)\n\n data = resp.json()\n\n weather = data.get('weather', {})\n category = weather.get('category', 'UNKNOWN')\n\n forecast = data.get('forecast', {})\n temp = forecast.get('temp', 0.0)\n\n bring = category.lower().strip() in {'rain', 'mist'}\n\n umbrella = UmbrellaStatus(bring_umbrella=bring, temp=temp, weather=category)\n # print(data)\n return umbrella\n","sub_path":"api/weather_api.py","file_name":"weather_api.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"340077518","text":"from flask import Blueprint, render_template\r\nfrom flask_login import current_user\r\n\r\nhome_bp = Blueprint(\r\n \"home_bp\",\r\n __name__,\r\n template_folder=\"templates\",\r\n static_folder=\"static\",\r\n static_url_path=\"assets\",\r\n)\r\n\r\n\r\n@home_bp.route(\"/\")\r\ndef index():\r\n return render_template(\"index.html\", user=current_user)\r\n","sub_path":"src/ayeauth/home/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"519535048","text":"# Copyright (c) OpenMMLab. All rights reserved.\nimport argparse\nimport logging\n\nfrom mmdeploy.apis.snpe import from_onnx\nfrom mmdeploy.utils import get_root_logger\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='Convert ONNX to snpe dlc format.')\n parser.add_argument('onnx_path', help='ONNX model path')\n parser.add_argument('output_prefix', help='output snpe dlc model path')\n parser.add_argument(\n '--log-level',\n help='set log level',\n default='INFO',\n choices=list(logging._nameToLevel.keys()))\n args = parser.parse_args()\n\n return args\n\n\ndef main():\n args = parse_args()\n logger = get_root_logger(log_level=args.log_level)\n\n onnx_path = args.onnx_path\n output_prefix = args.output_prefix\n\n logger.info(f'onnx2dlc: \\n\\tonnx_path: {onnx_path} ')\n from_onnx(onnx_path, output_prefix)\n logger.info('onnx2dlc success.')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/onnx2dlc.py","file_name":"onnx2dlc.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"101180708","text":"from unittest.mock import patch\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom evalml.exceptions import EnsembleMissingPipelinesError\nfrom evalml.model_family import ModelFamily\nfrom evalml.pipelines import BinaryClassificationPipeline, RegressionPipeline\nfrom evalml.pipelines.components import (\n BaselineRegressor,\n RandomForestClassifier,\n RandomForestRegressor,\n StackedEnsembleRegressor,\n)\nfrom evalml.problem_types import ProblemTypes\n\n\ndef test_stacked_model_family():\n assert StackedEnsembleRegressor.model_family == ModelFamily.ENSEMBLE\n\n\ndef test_stacked_default_parameters():\n assert StackedEnsembleRegressor.default_parameters == {\n \"final_estimator\": None,\n \"cv\": None,\n \"n_jobs\": -1,\n }\n\n\ndef test_stacked_ensemble_init_with_invalid_estimators_parameter():\n with pytest.raises(\n EnsembleMissingPipelinesError, match=\"must not be None or an empty list.\"\n ):\n StackedEnsembleRegressor()\n with pytest.raises(\n EnsembleMissingPipelinesError, match=\"must not be None or an empty list.\"\n ):\n StackedEnsembleRegressor(input_pipelines=[])\n\n\ndef test_stacked_ensemble_nonstackable_model_families():\n with pytest.raises(\n ValueError,\n match=\"Pipelines with any of the following model families cannot be used as base pipelines\",\n ):\n StackedEnsembleRegressor(\n input_pipelines=[RegressionPipeline([BaselineRegressor])]\n )\n\n\ndef test_stacked_different_input_pipelines_regression():\n input_pipelines = [\n RegressionPipeline([RandomForestRegressor]),\n BinaryClassificationPipeline([RandomForestClassifier]),\n ]\n with pytest.raises(\n ValueError, match=\"All pipelines must have the same problem type.\"\n ):\n StackedEnsembleRegressor(input_pipelines=input_pipelines)\n\n\ndef test_stacked_ensemble_init_with_multiple_same_estimators(\n X_y_regression, linear_regression_pipeline_class\n):\n # Checks that it is okay to pass multiple of the same type of estimator\n X, y = X_y_regression\n input_pipelines = [\n linear_regression_pipeline_class(parameters={}),\n linear_regression_pipeline_class(parameters={}),\n ]\n clf = StackedEnsembleRegressor(input_pipelines=input_pipelines, n_jobs=1)\n expected_parameters = {\n \"input_pipelines\": input_pipelines,\n \"final_estimator\": None,\n \"cv\": None,\n \"n_jobs\": 1,\n }\n assert clf.parameters == expected_parameters\n\n fitted = clf.fit(X, y)\n assert isinstance(fitted, StackedEnsembleRegressor)\n\n y_pred = clf.predict(X)\n assert len(y_pred) == len(y)\n assert not np.isnan(y_pred).all()\n\n\ndef test_stacked_ensemble_n_jobs_negative_one(\n X_y_regression, linear_regression_pipeline_class\n):\n X, y = X_y_regression\n input_pipelines = [linear_regression_pipeline_class(parameters={})]\n clf = StackedEnsembleRegressor(input_pipelines=input_pipelines)\n expected_parameters = {\n \"input_pipelines\": input_pipelines,\n \"final_estimator\": None,\n \"cv\": None,\n \"n_jobs\": -1,\n }\n assert clf.parameters == expected_parameters\n clf.fit(X, y)\n y_pred = clf.predict(X)\n assert len(y_pred) == len(y)\n assert not np.isnan(y_pred).all()\n\n\n@patch(\n \"evalml.pipelines.components.ensemble.StackedEnsembleRegressor._stacking_estimator_class\"\n)\ndef test_stacked_ensemble_does_not_overwrite_pipeline_random_seed(\n mock_stack, linear_regression_pipeline_class\n):\n input_pipelines = [\n linear_regression_pipeline_class(parameters={}, random_seed=3),\n linear_regression_pipeline_class(parameters={}, random_seed=4),\n ]\n clf = StackedEnsembleRegressor(\n input_pipelines=input_pipelines, random_seed=5, n_jobs=1\n )\n estimators_used_in_ensemble = mock_stack.call_args[1][\"estimators\"]\n assert clf.random_seed == 5\n assert estimators_used_in_ensemble[0][1].pipeline.random_seed == 3\n assert estimators_used_in_ensemble[1][1].pipeline.random_seed == 4\n\n\ndef test_stacked_ensemble_multilevel(linear_regression_pipeline_class):\n # checks passing a stacked ensemble classifier as a final estimator\n X = pd.DataFrame(np.random.rand(50, 5))\n y = pd.Series(\n np.random.rand(\n 50,\n )\n )\n base = StackedEnsembleRegressor(\n input_pipelines=[linear_regression_pipeline_class(parameters={})], n_jobs=1\n )\n clf = StackedEnsembleRegressor(\n input_pipelines=[linear_regression_pipeline_class(parameters={})],\n final_estimator=base,\n n_jobs=1,\n )\n clf.fit(X, y)\n y_pred = clf.predict(X)\n assert len(y_pred) == len(y)\n assert not np.isnan(y_pred).all()\n\n\ndef test_stacked_problem_types():\n assert ProblemTypes.REGRESSION in StackedEnsembleRegressor.supported_problem_types\n assert len(StackedEnsembleRegressor.supported_problem_types) == 2\n\n\ndef test_stacked_fit_predict_regression(X_y_regression, stackable_regressors):\n X, y = X_y_regression\n input_pipelines = [\n RegressionPipeline([regressor]) for regressor in stackable_regressors\n ]\n clf = StackedEnsembleRegressor(input_pipelines=input_pipelines, n_jobs=1)\n clf.fit(X, y)\n y_pred = clf.predict(X)\n assert len(y_pred) == len(y)\n assert isinstance(y_pred, pd.Series)\n assert not np.isnan(y_pred).all()\n\n clf = StackedEnsembleRegressor(\n input_pipelines=input_pipelines,\n final_estimator=RandomForestRegressor(),\n n_jobs=1,\n )\n clf.fit(X, y)\n y_pred = clf.predict(X)\n assert len(y_pred) == len(y)\n assert isinstance(y_pred, pd.Series)\n assert not np.isnan(y_pred).all()\n\n\n@patch(\"evalml.pipelines.components.ensemble.StackedEnsembleRegressor.fit\")\ndef test_stacked_feature_importance(mock_fit, X_y_regression, stackable_regressors):\n X, y = X_y_regression\n input_pipelines = [\n RegressionPipeline([regressor]) for regressor in stackable_regressors\n ]\n clf = StackedEnsembleRegressor(input_pipelines=input_pipelines, n_jobs=1)\n clf.fit(X, y)\n mock_fit.assert_called()\n clf._is_fitted = True\n with pytest.raises(\n NotImplementedError, match=\"feature_importance is not implemented\"\n ):\n clf.feature_importance\n","sub_path":"evalml/tests/component_tests/test_stacked_ensemble_regressor.py","file_name":"test_stacked_ensemble_regressor.py","file_ext":"py","file_size_in_byte":6227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"635214111","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSharhad Bashar\nECSE 543\nAssignment 2\nq_3Functions.py\nFunctons for generating the matrix from Assign 1\nNov 14th, 2016\n\"\"\"\n\n#using the top right quater of the cable, due to symmetry\nimport math\n#######################################################################################################\n#Generates the initial mesh, taking into considering the boundary conditions\ndef genMesh (h):\n cableHeight = 0.1\n cableWidth = 0.1\n coreHeight = 0.02\n coreWidth = 0.04\n corePot = 110.0\n nodeHeight = (int)(cableHeight/h + 1)\n nodeWidth = (int)(cableWidth/h + 1) \n #Create the mesh, with Dirchlet conditions \n mesh = [[(None,corePot) if x <= coreWidth/h and y <= coreHeight/h \\\n else ((None,0.0) if x == nodeHeight - 1 or y == nodeWidth - 1 \\\n else (0,0.0)) for x in range(nodeWidth)] for y in range(nodeHeight)] \n #update the mesh to take into account the Neuman conditions\n nodeForA = 0\n for y in range (nodeHeight):\n for x in range(nodeWidth):\n if (mesh[y][x][0] == 0):\n mesh[y][x] = (nodeForA,0.0)\n nodeForA += 1 \n return mesh \n#######################################################################################################\n#The Equation that calculates SOR \ndef SOR(mesh,h,w):\n cableHeight = 0.1\n cableWidth = 0.1\n coreHeight = 0.02\n coreWidth = 0.04\n nodeHeight = (int)(cableHeight/h + 1)\n nodeWidth = (int)(cableWidth/h + 1) \n for y in range (1,nodeHeight - 1):\n for x in range (1,nodeWidth - 1):\n if (x > (int)(coreWidth/h) or y > (int)(coreHeight/h)):\n mesh[y][x] = (1 - w) * mesh[y][x] + (w/4) * (mesh[y][x-1] + mesh[y][x+1] + mesh[y-1][x] + mesh[y+1][x]) \n return mesh \n#######################################################################################################\n#The Equation that calculates Jacobian\ndef jacobian(mesh,h):\n cableHeight = 0.1\n cableWidth = 0.1\n coreHeight = 0.02\n coreWidth = 0.04\n nodeHeight = (int)(cableHeight/h + 1)\n nodeWidth = (int)(cableWidth/h + 1) \n for y in range (1,nodeHeight - 1): \n for x in range (1,nodeWidth - 1):\n if (x > (int)(coreWidth/h) or y > (int)(coreHeight/h)):\n mesh[y][x] = (1/4) * (mesh[y][x-1] + mesh[y][x+1] + mesh[y-1][x] + mesh[y+1][x])\n return mesh\n\n####################################################################################################### \n#Equation that computes the residue \ndef computeMaxRes(mesh,h):\n cableHeight = 0.1\n cableWidth = 0.1\n coreHeight = 0.02\n coreWidth = 0.04\n nodeHeight = (int)(cableHeight/h + 1)\n nodeWidth = (int)(cableWidth/h + 1)\n maxRes = 0\n for y in range(1, nodeHeight - 1):\n for x in range(1, nodeWidth - 1):\n if (x > coreWidth/h or y > coreHeight/h):\n #calculate the residue of each free point\n res = mesh[y][x-1] + mesh[y][x+1] + mesh[y-1][x] + mesh[y+1][x] - 4 * mesh[y][x]\n res = math.fabs(res)\n if (res > maxRes):\n #Updates variable with the biggest residue amongst the free point\n maxRes = res\n return maxRes\n#######################################################################################################\n#Function that computes the number of iterations \ndef numIteration (initialMesh,h,w,method): \n minRes = 0.0001\n iteration = 1\n if (method == 's'): \n mesh = SOR(initialMesh,h,w)\n while (computeMaxRes(mesh,h) >= minRes):\n mesh = SOR(mesh,h,w)\n iteration += 1\n elif (method == 'j'):\n mesh = jacobian(initialMesh,h) \n while (computeMaxRes(mesh,h) >= minRes):\n mesh = jacobian(mesh,h)\n iteration += 1\n print ('Number of iterations: '+ str(iteration)) \n return(mesh) \n#######################################################################################################\n#Function that returns the potential at a free node \ndef getPot(mesh, x, y, h):\n cableHeight = 0.1\n cableWidth = 0.1\n nodeHeight = (int)(cableHeight/h + 1)\n nodeWidth = (int)(cableWidth/h + 1)\n xNode = int(nodeWidth - x/h - 1)\n yNode = int(nodeHeight - y/h - 1)\n return mesh[yNode][xNode] \n####################################################################################################### \n\n\n","sub_path":"Assignment 2/Question 3/q_3Functions.py","file_name":"q_3Functions.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"614166733","text":"from scapy.all import *\nimport requests, time, threading, sys, netifaces, argparse\n\n# Args parsing\nparser = argparse.ArgumentParser(prog=\"Scapy Hidden SSID reveal\",\n usage=\"%(prog)s -i mon0\",\n allow_abbrev=False)\n\nparser.add_argument(\"-i\", \"--Interface\", required=True,\n help=\"The interface that you want to send packets out of, needs to be set to monitor mode\")\n\nargs = parser.parse_args()\n\nHidden_bssids = []\n\nbssid_to_ssid = {}\n\n\n# We sniff all Dot11 probe response and beacon packets, we store for each empty beacon, the bssid associated with the AP, and for each probe response, the ssid associated with the BSSID of the AP. When we have a packet in both maps, we display the ssid of the hidden AP that we discovered.\ndef packetHandler(p):\n if p.haslayer(Dot11Beacon) and (p.info == b\"\" or p.ID != 0) and str(p.addr3) not in Hidden_bssids:\n Hidden_bssids.append(str(p.addr3))\n if str(p.addr3) in bssid_to_ssid:\n displayHiddenAP(str(p.addr3), bssid_to_ssid[str(p.addr3)])\n \n if p.haslayer(Dot11ProbeResp) and str(p.addr3) not in bssid_to_ssid:\n print(p.info)\n bssid_to_ssid[str(p.addr3)] = p.info\n if str(p.addr3) in Hidden_bssids:\n displayHiddenAP(str(p.addr3), bssid_to_ssid[str(p.addr3)])\n \n\n# Diplay function, run every time a new AP is found\ndef displayAP(bssid, ssid):\n print(\"%s %s\" % (bssid, ssid))\n print(\"Press CTRL+C to stop scanning\",end = \"\\r\")\n\nSSIDs = []\n\n\nprint(\"List of hidden SSIDs uncovered (BSSID -> SSID) : \")\n\n\n\n# Use a separate thread to sniff, so we can stop it later and can run the detection section forever\ne = threading.Event()\n\ndef _sniff(e):\n a = sniff(iface=args.Interface, prn=packetHandler, stop_filter=lambda p: e.is_set())\n\n\nt = threading.Thread(target=_sniff, args=(e,))\nt.start()\n\n# Infinite loop, until the user keyboard interrupts the script with CTRL+C\ntry:\n while True:\n time.sleep(1)\nexcept (KeyboardInterrupt, SystemExit):\n e.set()\n\n while t.is_alive():\n t.join(2)\n","sub_path":"src/ssidReveal.py","file_name":"ssidReveal.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"71196930","text":"#!/usr/bin/python3\n\nimport sys\nsys.path.append('../src/ry')\nfrom libry import *\n\nK = Configuration()\nD = K.camera()\nD.update(\"empty configuration\\n -- hit ENTER here to continue\", True)\n\nK.addFile('../rai-robotModels/pr2/pr2.g');\nK.addFile('../test/kitchen.g');\nprint(\"joint names: \", K.getJointNames())\nprint(\"frame names: \", K.getFrameNames())\nD.update(True)\n\nq = K.getJointState()\nprint('joint state: ', q)\nq[2] = q[2] + 1.\nK.setJointState(q)\nD.update(True)\n\nX = K.getFrameState()\nprint('frame state: ', X)\nX = X + .1\nK.setFrameState(X.flatten().tolist())\nD.update(True)\n\nq = K.getJointState()\nprint('joint state: ', q)\nq[2] = q[2] + 1.\nK.setJointState(q)\nD.update(True)\n\nK.addFrame(\"camera\", \"head_tilt_link\", \"Q: focalLength:.3\")\nC = K.camera(frame=\"camera\")\n\nK.addFrame(\"ball\", \"\", \"shape:sphere size:[0 0 0 .1] color:[1 1 0] X:\" );\nD.update(True)\n\nK.addFrame(\"hand\", \"pr2L\", \"shape:ssBox size:[.3 .2 .1 .01] color:[1 1 0] Q:\" );\nD.update(True);\n\ndist = K.getPairDistance(\"hand\", \"ball\");\nprint('distance: ', dist);\nD.update(True);\n\nkomo = K.komo_IK()\nkomo.addObjective(type='eq', feature='positionDiff', frames=['ball', 'hand'])\nkomo.optimize()\n\nkomo.clearObjectives()\nkomo.addObjective(type='eq', feature='positionDiff', frames=['hand', 'ball'], target=[.1, .1, .1])\nkomo.optimize()\n\n\n# komo.add_feature(time=[c1, c2], feature_type='sos', feautre_arg=['qItself', 'wrist_joint'], scale=5., target=[1,2,3])\n\n# c1 = komo.new_decision_var()\n# c2 = ...\n\n# komo.add_feature(c1 == c2)\n\n# komo.add_feature(komo.sos(10, pos_diff(c1.frame(\"right_hand\"). komo.table.frame * Frame(0.01,0,0)) ) )\n\n# komo.addFeature(DecisionVariables(c1,c2), Type().sos, Feature().posDiff('right_hand', 'table'), Scale().\n","sub_path":"examples/basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"362112996","text":"import tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport tensorflow.contrib.layers as layers\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.contrib.layers.python.layers import initializers\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.framework import ops\n\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nimport pdb, pickle\nimport numpy as np\n\n\n\n\nFLOW_SCALE = 5.0\n# Range of disparity/inverse depth values\nDISP_SCALING = 10\nMIN_DISP = 0.01\n\ndef deconv(input, lvl, name, reuse=None, is_training=True):\n with tf.variable_scope(lvl + name) as scope:\n if reuse:\n scope.reuse_variables()\n OUT = slim.conv2d_transpose(input, 2, 4, 2, 'same', scope='conv', trainable=is_training)\n # tf.layers.conv2d_transpose(inputs, filters, kernel_size, strides=(1, 1), padding='valid', ... , name)\n return OUT\n\n\ndef cost_volume(c1, warp, name, search_range=4):\n \"\"\"Build cost volume for associating a pixel from Image1 with its corresponding pixels in Image2.\n Args:\n c1: Level of the feature pyramid of Image1\n warp: Warped level of the feature pyramid of image22\n search_range: Search range (maximum displacement)\n \"\"\"\n\n padded_lvl = tf.pad(warp, [[0, 0], [search_range, search_range], [search_range, search_range], [0, 0]])\n _, h, w, _ = c1.get_shape()#tf.unstack(tf.shape(c1)\n max_offset = search_range * 2 + 1\n\n cost_vol = []\n # pdb.set_trace()\n for y in range(0, max_offset):\n for x in range(0, max_offset):\n slice = tf.slice(padded_lvl, [0, y, x, 0], [-1, int(h), int(w), -1])\n cost = tf.reduce_mean(c1 * slice, axis=3, keep_dims=True)\n cost_vol.append(cost)\n cost_vol = tf.concat(cost_vol, axis=3)\n cost_vol = tf.nn.relu(cost_vol, name=name)\n return cost_vol\n\n\ndef predict_flow(corr, pwcdata, inintial, train_BN, c1, up_flow, up_feat, lvl, use_dense_cx=True, reuse=None, is_training=True):\n \"\"\"Estimate optical flow.\n Args:\n corr: The cost volume at level lvl\n c1: The level of the feature pyramid of Image1\n up_flow: An upsampled version of the predicted flow from the previous level\n up_feat: An upsampled version of the features that were used to generate the flow prediction\n lvl: Index of the level\n name: Op scope name\n Args:\n upfeat: The features used to generate the predicted flow\n flow: The predicted flow\n Ref:\n Per page 4 of paper, section \"Optical flow estimator,\" the optical flow estimator is a multi-layer CNN. Its\n input are the cost volume, features of the first image, and upsampled optical flow and its output is the\n flow wl at the l-th level. The numbers of feature channels at each convolutional layers are\n respectively 128, 128, 96, 64, and 32, which are kept fixed at all pyramid levels. The estimators at\n different levels have their own parameters instead of sharing the same parameters. This estimation process\n is repeated until the desired level, l0.\n\n Per page 5 of paper, section \"Implementation details,\" we use a 7-level pyramid and set l0 to be 2, i.e.,\n our model outputs a quarter resolution optical flow and uses bilinear interpolation to obtain the\n full-resolution optical flow.\n\n The estimator architecture can be enhanced with DenseNet connections. The inputs to every convolutional\n layer are the output of and the input to its previous layer. DenseNet has more direct connections than\n traditional layers and leads to significant improvement in image classification.\n\n Note that we do not use DenseNet connections in this implementation because a) they increase the size of the\n model, and, b) per page 7 of paper, section \"Optical flow estimator,\" removing the DenseNet connections\n results in higher training error but lower validation errors when the model is trained on FlyingChairs\n (that being said, after the model is fine-tuned on FlyingThings3D, DenseNet leads to lower errors).\n\n Ref PyTorch code:\n def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, bias=True),\n nn.LeakyReLU(0.1))\n def predict_flow(in_planes):\n return nn.Conv2d(in_planes,2,kernel_size=3,stride=1,padding=1,bias=True)\n [...]\n nd = (2*md+1)**2\n dd = np.cumsum([128,128,96,64,32])\n od = nd\n self.conv6_0 = conv(od, 128, kernel_size=3, stride=1)\n self.conv6_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n self.conv6_2 = conv(od+dd[1],96, kernel_size=3, stride=1)\n self.conv6_3 = conv(od+dd[2],64, kernel_size=3, stride=1)\n self.conv6_4 = conv(od+dd[3],32, kernel_size=3, stride=1)\n self.predict_flow6 = predict_flow(od+dd[4])\n [...]\n od = nd+128+4\n self.conv5_0 = conv(od, 128, kernel_size=3, stride=1)\n self.conv5_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n self.conv5_2 = conv(od+dd[1],96, kernel_size=3, stride=1)\n self.conv5_3 = conv(od+dd[2],64, kernel_size=3, stride=1)\n self.conv5_4 = conv(od+dd[3],32, kernel_size=3, stride=1)\n self.predict_flow5 = predict_flow(od+dd[4])\n [...]\n od = nd+96+4\n self.conv4_0 = conv(od, 128, kernel_size=3, stride=1)\n self.conv4_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n self.conv4_2 = conv(od+dd[1],96, kernel_size=3, stride=1)\n self.conv4_3 = conv(od+dd[2],64, kernel_size=3, stride=1)\n self.conv4_4 = conv(od+dd[3],32, kernel_size=3, stride=1)\n self.predict_flow4 = predict_flow(od+dd[4])\n [...]\n od = nd+64+4\n self.conv3_0 = conv(od, 128, kernel_size=3, stride=1)\n self.conv3_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n self.conv3_2 = conv(od+dd[1],96, kernel_size=3, stride=1)\n self.conv3_3 = conv(od+dd[2],64, kernel_size=3, stride=1)\n self.conv3_4 = conv(od+dd[3],32, kernel_size=3, stride=1)\n self.predict_flow3 = predict_flow(od+dd[4])\n [...]\n od = nd+32+4\n self.conv2_0 = conv(od, 128, kernel_size=3, stride=1)\n self.conv2_1 = conv(od+dd[0],128, kernel_size=3, stride=1)\n self.conv2_2 = conv(od+dd[1],96, kernel_size=3, stride=1)\n self.conv2_3 = conv(od+dd[2],64, kernel_size=3, stride=1)\n self.conv2_4 = conv(od+dd[3],32, kernel_size=3, stride=1)\n self.predict_flow2 = predict_flow(od+dd[4])\n [...]\n self.dc_conv1 = conv(od+dd[4], 128, kernel_size=3, stride=1, padding=1, dilation=1)\n self.dc_conv2 = conv(128, 128, kernel_size=3, stride=1, padding=2, dilation=2)\n self.dc_conv3 = conv(128, 128, kernel_size=3, stride=1, padding=4, dilation=4)\n self.dc_conv4 = conv(128, 96, kernel_size=3, stride=1, padding=8, dilation=8)\n self.dc_conv5 = conv(96, 64, kernel_size=3, stride=1, padding=16, dilation=16)\n self.dc_conv6 = conv(64, 32, kernel_size=3, stride=1, padding=1, dilation=1)\n self.dc_conv7 = predict_flow(32)\n [...]\n x = torch.cat((self.conv6_0(corr6), corr6),1)\n x = torch.cat((self.conv6_1(x), x),1)\n x = torch.cat((self.conv6_2(x), x),1)\n x = torch.cat((self.conv6_3(x), x),1)\n x = torch.cat((self.conv6_4(x), x),1)\n flow6 = self.predict_flow6(x)\n ...\n x = torch.cat((corr5, c15, up_flow6, up_feat6), 1)\n x = torch.cat((self.conv5_0(x), x),1)\n x = torch.cat((self.conv5_1(x), x),1)\n x = torch.cat((self.conv5_2(x), x),1)\n x = torch.cat((self.conv5_3(x), x),1)\n x = torch.cat((self.conv5_4(x), x),1)\n flow5 = self.predict_flow5(x)\n ...\n x = torch.cat((corr4, c14, up_flow5, up_feat5), 1)\n x = torch.cat((self.conv4_0(x), x),1)\n x = torch.cat((self.conv4_1(x), x),1)\n x = torch.cat((self.conv4_2(x), x),1)\n x = torch.cat((self.conv4_3(x), x),1)\n x = torch.cat((self.conv4_4(x), x),1)\n flow4 = self.predict_flow4(x)\n ...\n x = torch.cat((corr3, c13, up_flow4, up_feat4), 1)\n x = torch.cat((self.conv3_0(x), x),1)\n x = torch.cat((self.conv3_1(x), x),1)\n x = torch.cat((self.conv3_2(x), x),1)\n x = torch.cat((self.conv3_3(x), x),1)\n x = torch.cat((self.conv3_4(x), x),1)\n flow3 = self.predict_flow3(x)\n ...\n x = torch.cat((corr2, c12, up_flow3, up_feat3), 1)\n x = torch.cat((self.conv2_0(x), x),1)\n x = torch.cat((self.conv2_1(x), x),1)\n x = torch.cat((self.conv2_2(x), x),1)\n x = torch.cat((self.conv2_3(x), x),1)\n x = torch.cat((self.conv2_4(x), x),1)\n flow2 = self.predict_flow2(x)\n \"\"\"\n # with slim.arg_scope(\n # [slim.conv2d],\n # activation_fn=tf.nn.relu,\n # normalizer_fn=slim.batch_norm,\n # normalizer_params={'training': train_BN, 'momentum': 0.95}):\n\n with tf.variable_scope(lvl, reuse=reuse, ) as scope:\n # if reuse:\n # scope.reuse_variables()\n if c1 is None and up_flow is None and up_feat is None:\n x = corr\n else:\n x = tf.concat([corr, c1, up_flow, up_feat], axis=3)\n\n # act = tf.layers.conv2d(x, filters=96, kernel_size=[3, 3], strides=1, padding='SAME', name='Pconv0', reuse=reuse)\n # x = tf.concat([act, x], axis=3) if use_dense_cx else act\n #\n # act = tf.layers.conv2d(x, 96, kernel_size=[3, 3], strides=1, padding='SAME', name='Pconv1', reuse=reuse)\n # x = tf.concat([act, x], axis=3) if use_dense_cx else act\n #\n # act = tf.layers.conv2d(x, 48, kernel_size=[3, 3], strides=1, padding='SAME', name='Pconv2', reuse=reuse)\n # x = tf.concat([act, x], axis=3) if use_dense_cx else act\n #\n # act = tf.layers.conv2d(x, 32, kernel_size=[3, 3], strides=1, padding='SAME', name='Pconv3', reuse=reuse)\n # x = tf.concat([act, x], axis=3) if use_dense_cx else act\n #\n # act = tf.layers.conv2d(x, 16, kernel_size=[3, 3], strides=1, padding='SAME', name='Pconv4', reuse=reuse)\n # x = tf.concat([act, x], axis=3) if use_dense_cx else act\n #\n # act = tf.layers.conv2d(x, 2, kernel_size=[3, 3], strides=1, padding='SAME', name='Pconv5', reuse=reuse)\n # upfeat = tf.concat([act, x], axis=3) if use_dense_cx else act\n #\n # flow = tf.layers.conv2d(x, 2, kernel_size=[3, 3], strides=1, padding='SAME', name='Pconv6', reuse=reuse)\n\n # pdb.set_trace()\n if inintial == 'default':\n act = slim.conv2d(x, 128, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv0', reuse=reuse, trainable=is_training)\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv0', reuse=reuse)\n x = tf.concat([act, x], axis=3) if use_dense_cx else act\n\n act = slim.conv2d(x, 128, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv1', reuse=reuse, trainable=is_training)\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv1', reuse=reuse)\n x = tf.concat([act, x], axis=3) if use_dense_cx else act\n\n act = slim.conv2d(x, 96, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv2', reuse=reuse, trainable=is_training)\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv2', reuse=reuse)\n x = tf.concat([act, x], axis=3) if use_dense_cx else act\n\n act = slim.conv2d(x, 64, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv3', reuse=reuse, trainable=is_training)\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv3', reuse=reuse)\n x = tf.concat([act, x], axis=3) if use_dense_cx else act\n\n act = slim.conv2d(x, 32, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv4', reuse=reuse, trainable=is_training)\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv4', reuse=reuse)\n upfeat = tf.concat([act, x], axis=3) if use_dense_cx else act\n\n\n flow = slim.conv2d(upfeat, 2, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv5', reuse=reuse, trainable=is_training)\n # flow = slim.batch_norm(flow, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv6', reuse=reuse)\n elif inintial == 'hourglass':\n act = slim.conv2d(x, 128, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv0', reuse=reuse, trainable=is_training,\n weights_initializer=tf.constant_initializer(value=pwcdata[scope.name+'/Pconv0'+'/weights']),\n biases_initializer=tf.constant_initializer(value=pwcdata[scope.name+'/Pconv0'+'/biases']))\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv0', reuse=reuse)\n x = tf.concat([act, x], axis=3) if use_dense_cx else act\n # pdb.set_trace()\n act = slim.conv2d(x, 128, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv1', reuse=reuse, trainable=is_training\n , weights_initializer=tf.constant_initializer(value=pwcdata[scope.name+'/Pconv1'+'/weights']),\n biases_initializer=tf.constant_initializer(value=pwcdata[scope.name+'/Pconv1'+'/biases']))\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv1', reuse=reuse)\n x = tf.concat([act, x], axis=3) if use_dense_cx else act\n\n act = slim.conv2d(x, 96, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv2', reuse=reuse, trainable=is_training,\n weights_initializer=tf.constant_initializer(value=pwcdata[scope.name + '/Pconv2' + '/weights']),\n biases_initializer=tf.constant_initializer(value=pwcdata[scope.name + '/Pconv2' + '/biases']))\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv2', reuse=reuse)\n x = tf.concat([act, x], axis=3) if use_dense_cx else act\n\n act = slim.conv2d(x, 64, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv3', reuse=reuse, trainable=is_training,\n weights_initializer=tf.constant_initializer( value=pwcdata[scope.name + '/Pconv3' + '/weights']),\n biases_initializer=tf.constant_initializer(value=pwcdata[scope.name + '/Pconv3' + '/biases']))\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv3', reuse=reuse)\n x = tf.concat([act, x], axis=3) if use_dense_cx else act\n\n act = slim.conv2d(x, 32, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv4', reuse=reuse, trainable=is_training,\n weights_initializer=tf.constant_initializer(value=pwcdata[scope.name + '/Pconv4' + '/weights']),\n biases_initializer=tf.constant_initializer(value=pwcdata[scope.name + '/Pconv4' + '/biases']))\n act = slim.batch_norm(act, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv4', reuse=reuse)\n upfeat = tf.concat([act, x], axis=3) if use_dense_cx else act\n\n flow = slim.conv2d(upfeat, 2, kernel_size=[3, 3], stride=1, padding='SAME', scope='Pconv5', reuse=reuse, trainable=is_training,\n weights_initializer=tf.constant_initializer( value=pwcdata[scope.name + '/Pconv5' + '/weights']),\n biases_initializer=tf.constant_initializer( value=pwcdata[scope.name + '/Pconv5' + '/biases']))\n flow = slim.batch_norm(flow, activation_fn=tf.nn.relu, is_training=is_training, scope='Pconv6', reuse=reuse)\n\n return upfeat, flow\n\n\ndef _interpolate_bilinear(grid, query_points, name='interpolate_bilinear', indexing='ij'):\n \"\"\"Similar to Matlab's interp2 function.\n\n Finds values for query points on a grid using bilinear interpolation.\n\n Args:\n grid: a 4-D float `Tensor` of shape `[batch, height, width, channels]`.\n query_points: a 3-D float `Tensor` of N points with shape `[batch, N, 2]`.\n name: a name for the operation (optional).\n indexing: whether the query points are specified as row and column (ij),\n or Cartesian coordinates (xy).\n\n Returns:\n values: a 3-D `Tensor` with shape `[batch, N, channels]`\n\n Raises:\n ValueError: if the indexing mode is invalid, or if the shape of the inputs\n invalid.\n \"\"\"\n if indexing != 'ij' and indexing != 'xy':\n raise ValueError('Indexing mode must be \\'ij\\' or \\'xy\\'')\n\n with ops.name_scope(name):\n grid = ops.convert_to_tensor(grid)\n query_points = ops.convert_to_tensor(query_points)\n shape = array_ops.unstack(array_ops.shape(grid))\n if len(shape) != 4:\n msg = 'Grid must be 4 dimensional. Received: '\n raise ValueError(msg + str(shape))\n\n batch_size, height, width, channels = shape\n query_type = query_points.dtype\n query_shape = array_ops.unstack(array_ops.shape(query_points))\n grid_type = grid.dtype\n\n if len(query_shape) != 3:\n msg = ('Query points must be 3 dimensional. Received: ')\n raise ValueError(msg + str(query_shape))\n\n _, num_queries, _ = query_shape\n\n alphas = []\n floors = []\n ceils = []\n\n index_order = [0, 1] if indexing == 'ij' else [1, 0]\n unstacked_query_points = array_ops.unstack(query_points, axis=2)\n\n for dim in index_order:\n with ops.name_scope('dim-' + str(dim)):\n queries = unstacked_query_points[dim]\n\n size_in_indexing_dimension = shape[dim + 1]\n\n # max_floor is size_in_indexing_dimension - 2 so that max_floor + 1\n # is still a valid index into the grid.\n max_floor = math_ops.cast(size_in_indexing_dimension - 2, query_type)\n min_floor = constant_op.constant(0.0, dtype=query_type)\n floor = math_ops.minimum(\n math_ops.maximum(min_floor, math_ops.floor(queries)), max_floor)\n int_floor = math_ops.cast(floor, dtypes.int32)\n floors.append(int_floor)\n ceil = int_floor + 1\n ceils.append(ceil)\n\n # alpha has the same type as the grid, as we will directly use alpha\n # when taking linear combinations of pixel values from the image.\n alpha = math_ops.cast(queries - floor, grid_type)\n min_alpha = constant_op.constant(0.0, dtype=grid_type)\n max_alpha = constant_op.constant(1.0, dtype=grid_type)\n alpha = math_ops.minimum(math_ops.maximum(min_alpha, alpha), max_alpha)\n\n # Expand alpha to [b, n, 1] so we can use broadcasting\n # (since the alpha values don't depend on the channel).\n alpha = array_ops.expand_dims(alpha, 2)\n alphas.append(alpha)\n\n flattened_grid = array_ops.reshape(grid,\n [batch_size * height * width, channels])\n batch_offsets = array_ops.reshape(\n math_ops.range(batch_size) * height * width, [batch_size, 1])\n\n # This wraps array_ops.gather. We reshape the image data such that the\n # batch, y, and x coordinates are pulled into the first dimension.\n # Then we gather. Finally, we reshape the output back. It's possible this\n # code would be made simpler by using array_ops.gather_nd.\n def gather(y_coords, x_coords, name):\n with ops.name_scope('gather-' + name):\n linear_coordinates = batch_offsets + y_coords * width + x_coords\n gathered_values = array_ops.gather(flattened_grid, linear_coordinates)\n return array_ops.reshape(gathered_values,\n [batch_size, num_queries, channels])\n\n # grab the pixel values in the 4 corners around each query point\n top_left = gather(floors[0], floors[1], 'top_left')\n top_right = gather(floors[0], ceils[1], 'top_right')\n bottom_left = gather(ceils[0], floors[1], 'bottom_left')\n bottom_right = gather(ceils[0], ceils[1], 'bottom_right')\n\n # now, do the actual interpolation\n with ops.name_scope('interpolate'):\n interp_top = alphas[1] * (top_right - top_left) + top_left\n interp_bottom = alphas[1] * (bottom_right - bottom_left) + bottom_left\n interp = alphas[0] * (interp_bottom - interp_top) + interp_top\n\n return interp\n\ndef dense_image_warp(image, flow, name='dense_image_warp'):\n \"\"\"Image warping using per-pixel flow vectors.\n\n Apply a non-linear warp to the image, where the warp is specified by a dense\n flow field of offset vectors that define the correspondences of pixel values\n in the output image back to locations in the source image. Specifically, the\n pixel value at output[b, j, i, c] is\n images[b, j - flow[b, j, i, 0], i - flow[b, j, i, 1], c].\n\n The locations specified by this formula do not necessarily map to an int\n index. Therefore, the pixel value is obtained by bilinear\n interpolation of the 4 nearest pixels around\n (b, j - flow[b, j, i, 0], i - flow[b, j, i, 1]). For locations outside\n of the image, we use the nearest pixel values at the image boundary.\n\n\n Args:\n image: 4-D float `Tensor` with shape `[batch, height, width, channels]`.\n flow: A 4-D float `Tensor` with shape `[batch, height, width, 2]`.\n name: A name for the operation (optional).\n\n Note that image and flow can be of type tf.half, tf.float32, or tf.float64,\n and do not necessarily have to be the same type.\n\n Returns:\n A 4-D float `Tensor` with shape`[batch, height, width, channels]`\n and same type as input image.\n\n Raises:\n ValueError: if height < 2 or width < 2 or the inputs have the wrong number\n of dimensions.\n \"\"\"\n with ops.name_scope(name):\n batch_size, height, width, channels = array_ops.unstack(array_ops.shape(image))\n # The flow is defined on the image grid. Turn the flow into a list of query\n # points in the grid space.\n grid_x, grid_y = array_ops.meshgrid(\n math_ops.range(width), math_ops.range(height))\n stacked_grid = math_ops.cast(\n array_ops.stack([grid_y, grid_x], axis=2), flow.dtype)\n batched_grid = array_ops.expand_dims(stacked_grid, axis=0)\n query_points_on_grid = batched_grid - flow\n query_points_flattened = array_ops.reshape(query_points_on_grid,\n [batch_size, height * width, 2])\n # Compute values at the query points, then reshape the result back to the\n # image grid.\n interpolated = _interpolate_bilinear(image, query_points_flattened)\n interpolated = array_ops.reshape(interpolated,\n [batch_size, height, width, channels])\n return interpolated\n\n\ndef refine_flow(feat, pwcdata, inintial, train_BN, flow, lvl, reuse=None, is_training=True):\n \"\"\"Post-ptrocess the estimated optical flow using a \"context\" nn.\n Args:\n feat: Features of the second-to-last layer from the optical flow estimator\n flow: Estimated flow to refine\n lvl: Index of the level\n name: Op scope name\n Ref:\n Per page 4 of paper, section \"Context network,\" traditional flow methods often use contextual information\n to post-process the flow. Thus we employ a sub-network, called the context network, to effectively enlarge\n the receptive field size of each output unit at the desired pyramid level. It takes the estimated flow and\n features of the second last layer from the optical flow estimator and outputs a refined flow.\n\n The context network is a feed-forward CNN and its design is based on dilated convolutions. It consists of\n 7 convolutional layers. The spatial kernel for each convolutional layer is 3×3. These layers have different\n dilation constants. A convolutional layer with a dilation constant k means that an input unit to a filter\n in the layer are k-unit apart from the other input units to the filter in the layer, both in vertical and\n horizontal directions. Convolutional layers with large dilation constants enlarge the receptive field of\n each output unit without incurring a large computational burden. From bottom to top, the dilation constants\n are 1, 2, 4, 8, 16, 1, and 1.\n\n Ref PyTorch code:\n def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, bias=True),\n nn.LeakyReLU(0.1))\n def predict_flow(in_planes):\n return nn.Conv2d(in_planes,2,kernel_size=3,stride=1,padding=1,bias=True)\n [...]\n self.dc_conv1 = conv(od+dd[4], 128, kernel_size=3, stride=1, padding=1, dilation=1)\n self.dc_conv2 = conv(128, 128, kernel_size=3, stride=1, padding=2, dilation=2)\n self.dc_conv3 = conv(128, 128, kernel_size=3, stride=1, padding=4, dilation=4)\n self.dc_conv4 = conv(128, 96, kernel_size=3, stride=1, padding=8, dilation=8)\n self.dc_conv5 = conv(96, 64, kernel_size=3, stride=1, padding=16, dilation=16)\n self.dc_conv6 = conv(64, 32, kernel_size=3, stride=1, padding=1, dilation=1)\n self.dc_conv7 = predict_flow(32)\n [...]\n x = torch.cat((corr2, c12, up_flow3, up_feat3), 1)\n x = torch.cat((self.conv2_0(x), x),1)\n x = torch.cat((self.conv2_1(x), x),1)\n x = torch.cat((self.conv2_2(x), x),1)\n x = torch.cat((self.conv2_3(x), x),1)\n x = torch.cat((self.conv2_4(x), x),1)\n flow2 = self.predict_flow2(x)\n x = self.dc_conv4(self.dc_conv3(self.dc_conv2(self.dc_conv1(x))))\n flow2 += self.dc_conv7(self.dc_conv6(self.dc_conv5(x)))\n \"\"\"\n # with slim.arg_scope(\n # [slim.conv2d],\n # activation_fn=tf.nn.relu,\n # normalizer_fn=slim.batch_norm,\n # normalizer_params={'training': train_BN, 'momentum': 0.95}):\n\n with tf.variable_scope(lvl, reuse=reuse):\n x = slim.conv2d(feat, 96, kernel_size=[3, 3], stride=1, padding='SAME', scope='Rconv1', reuse=reuse, trainable=is_training)\n x = slim.batch_norm(x, activation_fn=tf.nn.relu, is_training=is_training, scope='Rconv1', reuse=reuse)\n x = slim.conv2d(x, 96, kernel_size=[3, 3], stride=1, padding='SAME', scope='Rconv2', reuse=reuse, trainable=is_training)\n x = slim.batch_norm(x, activation_fn=tf.nn.relu, is_training=is_training, scope='Rconv2', reuse=reuse)\n x = slim.conv2d(x, 96, kernel_size=[3, 3], stride=1, padding='SAME', scope='Rconv3', reuse=reuse, trainable=is_training)\n x = slim.batch_norm(x, activation_fn=tf.nn.relu, is_training=is_training, scope='Rconv3', reuse=reuse)\n x = slim.conv2d(x, 64, kernel_size=[3, 3], stride=1, padding='SAME', scope='Rconv4', reuse=reuse, trainable=is_training)\n x = slim.batch_norm(x, activation_fn=tf.nn.relu, is_training=is_training, scope='Rconv4', reuse=reuse)\n x = slim.conv2d(x, 48, kernel_size=[3, 3], stride=1, padding='SAME', scope='Rconv5', reuse=reuse, trainable=is_training)\n x = slim.batch_norm(x, activation_fn=tf.nn.relu, is_training=is_training, scope='Rconv5', reuse=reuse)\n x = slim.conv2d(x, 32, kernel_size=[3, 3], stride=1, padding='SAME', scope='Rconv6', reuse=reuse, trainable=is_training)\n x = slim.batch_norm(x, activation_fn=tf.nn.relu, is_training=is_training, scope='Rconv6', reuse=reuse)\n x = slim.conv2d(x, 2, kernel_size=[3, 3], stride=1, padding='SAME', scope='Rconv7', reuse=reuse, trainable=is_training)\n x = slim.batch_norm(x, activation_fn=tf.nn.relu, is_training=is_training, scope='Rconv7', reuse=reuse)\n\n return tf.add(flow, x)\n\n\ndef predict(c1, c2, pwcdata, inintial, train_BN, flow, feat, lvl, scaler, reuse=None, is_training=True):\n # scaler values are 0.625, 1.25, 2.5, 5.0\n\n # the OPnet\n # containing the warping layer, cost value layer, optical flow estimator, context network\\\n\n if flow is None and feat is None:\n corr = cost_volume(c1, c2, name=lvl)\n upfeat, flow = predict_flow(corr, pwcdata, inintial, train_BN, None, None, None, lvl, reuse=reuse, is_training=is_training)\n else:\n # if lvl[-1] != '5':\n up_flow = deconv(flow, lvl,'/up_flow', reuse=reuse, is_training=is_training)\n up_feat = deconv(feat, lvl,'/up_feat', reuse=reuse, is_training=is_training)\n warp = dense_image_warp(c2, up_flow * scaler, lvl)\n corr = cost_volume(c1, warp, lvl)\n upfeat, flow = predict_flow(corr, pwcdata, inintial, train_BN, c1, up_flow, up_feat, lvl, reuse=reuse, is_training=is_training)\n if lvl[-1] == '4':\n flow = refine_flow(upfeat, pwcdata, inintial, train_BN, flow, lvl, reuse=reuse, is_training=is_training)\n\n return flow, upfeat\n\n\ndef inception(input, scope, pra, hourdata, inintial, train_BN, reuse =None, is_training=True):\n with tf.variable_scope(name_or_scope=scope) as scope:\n if reuse:\n scope.reuse_variables()\n if inintial == 'default':\n\n out = slim.conv2d(input, pra[0][0], kernel_size=[1, 1], stride=1, padding='SAME', scope='conv1', reuse=reuse, trainable=is_training)\n out = slim.batch_norm(out, activation_fn=tf.nn.relu, is_training=is_training, scope='conv1', reuse=reuse)\n\n for i in range(1, len(pra)):\n net = slim.conv2d(input, pra[i][1], kernel_size=[1, 1], stride=1, padding='SAME', scope='conv' + str(i) + '_1', reuse=reuse, trainable=is_training)\n net = slim.batch_norm(net, activation_fn=tf.nn.relu, is_training=is_training, scope='conv' + str(i) + '_1', reuse=reuse)\n net = slim.conv2d(net, pra[i][2], kernel_size=[pra[i][0], pra[i][0]], stride=1, padding='SAME', scope='conv' + str(i) + '_2', reuse=reuse, trainable=is_training)\n net = slim.batch_norm(net, activation_fn=tf.nn.relu, is_training=is_training, scope='conv' + str(i) + '_2', reuse=reuse)\n out = tf.concat([out, net], axis=3)\n\n elif inintial == 'hourglass':\n # pdb.set_trace()\n\n out = slim.conv2d(input, pra[0][0], kernel_size=[1, 1], stride=1, padding='SAME', scope='conv1',\n reuse=reuse, trainable=is_training,\n weights_initializer=tf.constant_initializer(value=hourdata[scope.name + '/conv1' + '/weights']),\n biases_initializer=tf.constant_initializer(value=hourdata[scope.name + '/conv1' + '/biases']))\n out = slim.batch_norm(out, activation_fn=tf.nn.relu, is_training=is_training, scope='conv1', reuse=reuse)\n\n for i in range(1, len(pra)):\n # pdb.set_trace()\n net = slim.conv2d(input, pra[i][1], kernel_size=[1, 1], stride=1, padding='SAME',\n scope='conv'+str(i)+'_1', reuse=reuse, trainable=is_training,\n weights_initializer = tf.constant_initializer(value=hourdata[scope.name + '/conv'+str(i)+'_1' + '/weights']),\n biases_initializer = tf.constant_initializer(value=hourdata[scope.name + '/conv'+str(i)+'_1' + '/biases']))\n net = slim.batch_norm(net, activation_fn=tf.nn.relu, is_training=is_training, scope='conv' + str(i) + '_1', reuse=reuse)\n\n\n net = slim.conv2d(net, pra[i][2], kernel_size=[pra[i][0], pra[i][0]], stride=1, padding='SAME',\n scope='conv'+str(i)+'_2', reuse=reuse, trainable=is_training,\n weights_initializer = tf.constant_initializer(value=hourdata[scope.name + '/conv'+str(i)+'_2' + '/weights']),\n biases_initializer = tf.constant_initializer(value=hourdata[scope.name + '/conv'+str(i)+'_2' + '/biases']))\n net = slim.batch_norm(net, activation_fn=tf.nn.relu, is_training=is_training, scope='conv' + str(i) + '_2', reuse=reuse)\n\n out = tf.concat([out, net], axis=3)\n\n return out\n\n\ndef Channels1(input, hourdata, inintial, train_BN, scope, reuse=None, is_training=True):\n with tf.variable_scope(name_or_scope=scope, reuse=reuse) as scope:\n # if reuse:\n # scope.reuse_variables()\n # EEE\n net = slim.avg_pool2d(input, kernel_size=2, stride=2, padding='VALID', scope='pool1')\n net = inception(net, 'conv1', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net = inception(net, 'conv2', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net = inception(net, 'conv3', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n _, height, width, _ = tf.unstack(tf.shape(net))\n out1 = tf.image.resize_images(net,(height*2, width*2), method=1)\n # EE\n net = inception(input, 'connect2B', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n out2 = inception(net, 'connect2B_1', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n\n out = tf.add(out1, out2)\n return out, out\n\n\ndef Channels2(input, hourdata, inintial, train_BN, scope, reuse=None, is_training=True):\n with tf.variable_scope(name_or_scope=scope, reuse=reuse) as scope:\n # if reuse:\n # scope.reuse_variables()\n # EE1EF\n net = slim.avg_pool2d(input, kernel_size=2, stride=2, padding='VALID', scope='pool1')\n net = inception(net, 'conv1', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net = inception(net, 'conv2', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net, f1_1 = Channels1(net, hourdata, inintial, train_BN, scope='Channel1', reuse=reuse, is_training=is_training)\n net = inception(net, 'conv-2', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net = inception(net, 'conv-1', [[64], [3, 64, 64], [7, 64, 64], [11, 64, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n _, height, width, _ = tf.unstack(tf.shape(net))\n out1 = tf.image.resize_images(net,(height*2, width*2), method=1)\n # EF\n net = inception(input, 'connect3E', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n out2 = inception(net, 'connect3F', [[64], [3, 64, 64], [7, 64, 64], [11, 64, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n\n out = tf.add(out1, out2)\n return out, out, f1_1\n\n\ndef Channels3(input, hourdata, inintial, train_BN, scope, reuse=None, is_training=True):\n with tf.variable_scope(name_or_scope=scope, reuse=reuse) as scope:\n # if reuse:\n # scope.reuse_variables()\n # BD2EG\n net = slim.avg_pool2d(input, kernel_size=2, stride=2, padding='VALID', scope='pool1')\n net = inception(net, 'conv1', [[32], [3, 32, 32], [5, 32, 32], [7, 32, 32]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net = inception(net, 'conv2', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net, f2_1, f1_1 = Channels2(net, hourdata, inintial, train_BN, scope='Channel2', reuse=reuse, is_training=is_training)\n net = inception(net, 'conv-2', [[64], [3, 32, 64], [5, 32, 64], [7, 32, 64]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net = inception(net, 'conv-1', [[32], [3, 32, 32], [5, 32, 32], [7, 32, 32]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n _, height, width, _ = tf.unstack(tf.shape(net))\n out1 = tf.image.resize_images(net,(height*2, width*2), method=1)\n # BC\n net = inception(input, 'connect2B', [[32], [3, 32, 32], [5, 32, 32], [7, 32, 32]], hourdata, inintial, train_BN, is_training=is_training)\n out2 = inception(net, 'connect2B_1', [[32], [3, 64, 32], [7, 64, 32], [11, 64, 32]], hourdata, inintial, train_BN, is_training=is_training)\n\n out = tf.add(out1, out2)\n return out, out, f2_1, f1_1\n\n\ndef Channels4(input, hourdata, inintial, train_BN, scope, reuse=None, is_training=True):\n with tf.variable_scope(name_or_scope=scope, reuse=reuse) as scope:\n # if reuse:\n # scope.reuse_variables()\n # BB3BA\n\n net = slim.avg_pool2d(input, kernel_size=2, stride=2, padding='VALID', scope='pool1')\n # pdb.set_trace()\n net = inception(net, 'conv1', [[32], [3, 32, 32], [5, 32, 32], [7, 32, 32]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net = inception(net, 'conv2', [[32], [3, 32, 32], [5, 32, 32], [7, 32, 32]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net, f3_1, f2_1, f1_1 = Channels3(net, hourdata, inintial, train_BN, scope='Channel3', reuse=reuse, is_training=is_training)\n net = inception(net, 'conv-2', [[32], [3, 64, 32], [5, 64, 32], [7, 64, 32]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n net = inception(net, 'conv-1', [[16], [3, 32, 16], [7, 32, 16], [11, 32, 16]], hourdata, inintial, train_BN, reuse=reuse, is_training=is_training)\n _, height, width, _ = tf.unstack(tf.shape(net))\n out1 = tf.image.resize_images(net,(height*2, width*2), method=1)\n # A\n out2 = inception(input, 'connect1', [[16], [3, 64, 16], [7, 64, 16], [11, 64, 16]], hourdata, inintial, train_BN, is_training=is_training)\n\n out = tf.add(out1, out2)\n return out, out, f3_1, f2_1, f1_1\n\n\ndef pose_net_fb(tgt_image, src_image_stack, is_training=True, reuse=False):\n inputs = tf.concat([tgt_image, src_image_stack], axis=3)\n num_source = int(src_image_stack.get_shape()[3].value//3)\n with tf.variable_scope('pose_net') as sc:\n if reuse:\n sc.reuse_variables()\n # with slim.arg_scope([slim.conv2d, slim.conv2d_transpose],\n # normalizer_fn=None,\n # weights_regularizer=slim.l2_regularizer(0.05),\n # activation_fn=tf.nn.relu):\n # cnv1 to cnv5b are shared between pose and explainability prediction\n cnv1 = slim.conv2d(inputs,16, [7, 7], stride=2, scope='cnv1', trainable=is_training)\n cnv1 = slim.batch_norm(cnv1, activation_fn=tf.nn.relu, is_training=is_training, scope='cnv1', reuse=reuse)\n cnv2 = slim.conv2d(cnv1, 32, [5, 5], stride=2, scope='cnv2', trainable=is_training)\n cnv2 = slim.batch_norm(cnv2, activation_fn=tf.nn.relu, is_training=is_training, scope='cnv2', reuse=reuse)\n cnv3 = slim.conv2d(cnv2, 64, [3, 3], stride=2, scope='cnv3', trainable=is_training)\n cnv3 = slim.batch_norm(cnv3, activation_fn=tf.nn.relu, is_training=is_training, scope='cnv3', reuse=reuse)\n cnv4 = slim.conv2d(cnv3, 128, [3, 3], stride=2, scope='cnv4', trainable=is_training)\n cnv4 = slim.batch_norm(cnv4, activation_fn=tf.nn.relu, is_training=is_training, scope='cnv4', reuse=reuse)\n cnv5 = slim.conv2d(cnv4, 256, [3, 3], stride=2, scope='cnv5', trainable=is_training)\n cnv5 = slim.batch_norm(cnv5, activation_fn=tf.nn.relu, is_training=is_training, scope='cnv5', reuse=reuse)\n cnv6 = slim.conv2d(cnv5, 256, [3, 3], stride=2, scope='cnv6', trainable=is_training)\n cnv6 = slim.batch_norm(cnv6, activation_fn=tf.nn.relu, is_training=is_training, scope='cnv6', reuse=reuse)\n cnv7 = slim.conv2d(cnv6, 256, [3, 3], stride=2, scope='cnv7', trainable=is_training)\n cnv7 = slim.batch_norm(cnv7, activation_fn=tf.nn.relu, is_training=is_training, scope='cnv7', reuse=reuse)\n # Double the number of channels\n pose_pred = slim.conv2d(cnv7, 6*num_source*2, [1, 1], scope='pred',\n stride=1, normalizer_fn=None, activation_fn=None)\n pose_avg = tf.reduce_mean(pose_pred, [1, 2])\n # Empirically we found that scaling by a small constant\n # facilitates training.\n # 1st half: target->source, 2nd half: source->target\n pose_final = 0.01 * tf.reshape(pose_avg, [-1, num_source, 6*2])\n # end_points = utils.convert_collection_to_dict(end_points_collection)\n return pose_final#, end_points\n\n\ndef hourglass(input, hourdata, inintial, train_BN, scope='HourGlass', reuse=None, is_training=True):\n\n with tf.variable_scope(name_or_scope=scope, reuse=reuse) as scope:\n\n if inintial == 'default':\n with slim.arg_scope([slim.conv2d],\n weights_initializer=initializers.xavier_initializer(),\n biases_initializer=init_ops.zeros_initializer(),\n activation_fn=tf.nn.relu,\n normalizer_fn=slim.batch_norm,\n normalizer_params={'training': train_BN, 'momentum': 0.95}):\n net = slim.conv2d(input, 128, kernel_size=[7, 7], stride=1, padding='SAME', scope='conv1', reuse=reuse, trainable=is_training)\n # middle part\n net, f4_1, f3_1, f2_1, f1_1 = Channels4(net, hourdata, inintial, train_BN, scope='Channel4', reuse=reuse, is_training=is_training)\n # last conv H\n net = slim.conv2d(net, 1, kernel_size=[3, 3], stride=1, padding='SAME', scope='conv9', reuse=reuse, trainable=is_training)\n\n elif inintial == 'hourglass':\n\n\n net = slim.conv2d(input, 128, kernel_size=[7, 7], stride=1, padding='SAME', scope='conv1', reuse=reuse, trainable=is_training,\n weights_initializer=tf.constant_initializer(value=hourdata[scope.name+'/conv1'+'/weights']),\n biases_initializer=tf.constant_initializer(value=hourdata[scope.name+'/conv1'+'/biases']))\n net = slim.batch_norm(net, activation_fn=tf.nn.relu, is_training=is_training, scope='conv1', reuse=reuse)\n # middle part\n net, f4_1, f3_1, f2_1, f1_1 = Channels4(net, hourdata, inintial, train_BN, scope='Channel4', reuse=reuse, is_training=is_training)\n # last conv H\n net = slim.conv2d(net, 1, kernel_size=[3, 3], stride=1, padding='SAME', scope='conv9', reuse=reuse,\n trainable=is_training, activation_fn=tf.sigmoid,\n weights_initializer=tf.constant_initializer(value=hourdata[scope.name + '/conv9' + '/weights']),\n biases_initializer=tf.constant_initializer(value=hourdata[scope.name + '/conv9' + '/biases']))\n net = slim.batch_norm(net, activation_fn=tf.nn.relu, is_training=is_training, scope='conv9', reuse=reuse)\n\n return net, f4_1, f3_1, f2_1, f1_1\n\n\ndef net(im1,im2, train_BN = True, inintial='hourglass', train_depth=True, train_flow=True, reuse=False, is_training=False):\n\n\n hourglassFile = '/media/disk/Backup/02congzhang/git/flow/relative-depth-using-pytorch/hourglass.pickle'\n with open(hourglassFile, 'rb') as file:\n hourdata = pickle.load(file)\n pwcFile = '/media/disk/Backup/02congzhang/git/flow/PWC-Net/PyTorch/pwc.pickle'\n with open(pwcFile, 'rb') as file:\n pwcdata = pickle.load(file)\n\n\n depth1, f4_1, f3_1, f2_1, f1_1 = hourglass(im1, hourdata, inintial, train_BN, scope='Hourglass', reuse=reuse, is_training=train_depth)\n depth2, f4_2, f3_2, f2_2, f1_2 = hourglass(im2, hourdata, inintial, train_BN, scope='Hourglass', reuse=True, is_training=train_depth)\n pose = pose_net_fb(im1, im2, is_training=train_depth)\n # pdb.set_trace()\n\n # scaler 0.625, 1.25, 2.5, 5.0\n\n # forward chuanbo\n flow1_f, fea1_f = predict(f1_1, f1_2, pwcdata, inintial, train_BN, None, None, 'flow1', 0.625, reuse=reuse, is_training=train_flow)\n flow2_f, fea2_f = predict(f2_1, f2_2, pwcdata, inintial, train_BN, flow1_f, fea1_f, 'flow2', 1.25, reuse=reuse, is_training=train_flow)\n flow3_f, fea3_f = predict(f3_1, f3_2, pwcdata, inintial, train_BN, flow2_f, fea2_f, 'flow3', 2.5, reuse=reuse, is_training=train_flow)\n flow4_f, fea4_f = predict(f4_1, f4_2, pwcdata, inintial, train_BN, flow3_f, fea3_f, 'flow4', 5.0, reuse=reuse, is_training=train_flow)\n # flow5_f, fea5_f = predict(depth1, depth2, flow4_f, fea4_f, 'flow5', 10.0, reuse=reuse)\n\n # backward chuanbo\n flow1_b, fea1_b = predict(f1_2, f1_1, pwcdata, inintial, train_BN, None, None, 'flow1', 0.625, reuse=True, is_training=train_flow)\n flow2_b, fea2_b = predict(f2_2, f2_1, pwcdata, inintial, train_BN, flow1_b, fea1_b, 'flow2', 1.25, reuse=True, is_training=train_flow)\n flow3_b, fea3_b = predict(f3_2, f3_1, pwcdata, inintial, train_BN, flow2_b, fea2_b, 'flow3', 2.5, reuse=True, is_training=train_flow)\n flow4_b, fea4_b = predict(f4_2, f4_1, pwcdata, inintial, train_BN, flow3_b, fea3_b, 'flow4', 5.0, reuse=True, is_training=train_flow)\n # flow5_b, fea5_b = predict(depth2, depth1, flow4_b, fea4_b, 'flow5', 10.0, reuse=True)\n\n flowf = []\n # flowf.append(flow5_f)\n flowf.append(flow4_f)\n flowf.append(flow3_f)\n flowf.append(flow2_f)\n flowf.append(flow1_f)\n\n flowb = []\n # flowb.append(flow5_b)\n flowb.append(flow4_b)\n flowb.append(flow3_b)\n flowb.append(flow2_b)\n flowb.append(flow1_b)\n\n\n return DISP_SCALING*depth1, DISP_SCALING*depth2, pose , flowf, flowb, im1, f4_1, f2_1, f1_1\n\n\n","sub_path":"core/hourglass.py","file_name":"hourglass.py","file_ext":"py","file_size_in_byte":47825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"48349778","text":"#Programming for the Puzzled -- Srini Devadas\n#Anagramania\n#Given a list of words, sort them such that all anagrams are grouped together\n#An elegant, efficient algorithm\n\ncorpus = ['abed', 'abet', 'abets', 'abut', 'acme', 'acre',\n 'acres', 'actors', 'actress', 'airmen', 'alert',\n 'alerted', 'ales', 'aligned', 'allergy', 'alter',\n 'altered', 'amen', 'anew', 'angel', 'angle',\n 'antler', 'apt', 'bade', 'baste', 'bead',\n 'beast', 'beat', 'beats', 'beta', 'betas',\n 'came', 'care', 'cares', 'casters', 'castor',\n 'costar', 'dealing', 'gallery', 'glean',\n 'largely', 'later', 'leading', 'learnt', 'leas',\n 'mace', 'mane', 'marine', 'mean', 'name', 'pat',\n 'race', 'races', 'recasts', 'regally', 'related',\n 'remain', 'rental', 'sale', 'scare', 'seal',\n 'tabu', 'tap', 'treadle', 'tuba', 'wane', 'wean']\n\n#Dictionary mapping letters of the alphabet to prime numbers\nchToprime = {'a': 2, 'b': 3, 'c': 5, 'd': 7, 'e': 11, 'f': 13,\n 'g': 17, 'h': 19, 'i': 23, 'j': 29, 'k': 31, 'l': 37, 'm': 41, 'n': 43, \n 'o': 47, 'p': 53, 'q': 59, 'r': 61, 's': 67, 't': 71, 'u': 73, 'v': 79, \n 'w': 83, 'x': 89, 'y': 97, 'z': 101 }\n\n#This procedure computes the hash of a string recursively\ndef primeHash(str):\n if len(str) == 0:\n return 1\n else:\n return chToprime[str[0]] * primeHash(str[1:])\n\nprint (sorted(corpus, key=primeHash))\n\nprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]\n\ndef chToprimef(ch):\n return primes[ord(ch) - 97]\n\ndef primeHashf(str):\n if len(str) == 0:\n return 1\n else:\n return chToprimef(str[0]) * primeHashf(str[1:])\n\nprint (sorted(corpus, key=primeHashf))\n\n","sub_path":"Puzzle17/anagrams.py","file_name":"anagrams.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"252584365","text":"'''\nCreated on Jul 1, 2015\n\n@author: andrei\n'''\nimport hgsTools.auxiliary as auxiliary\nimport hgsTools.messaging as messaging\nimport hgsTools.auxiliary.s3tools as s3tools\nimport os\nimport tarfile\nimport uuid\n\ndef seekArchForFiles(arch, seek_element):\n files = []\n \n with tarfile.open(arch, 'r:gz') as tar:\n content = tar.getmembers()\n for i in content:\n if seek_element in i.name:\n files.append(i.name)\n \n return files\n\ndef getArchName(arch):\n arch_split = arch.split('.', 1)\n \n return arch_split[0]\n\ndef _checkDuplicates(list_1, list_2):\n non_duplicate_index = -1\n \n for i in range(len(list_1) - 1): \n if list_1[i] != list_2[i]:\n non_duplicate_index = i\n break\n \n return non_duplicate_index\n\ndef _generateArchName():\n return str(uuid.uuid4()) + '.tgz'\n\ndef _getAppDirs(app_files, extract_dir):\n #list of paths to the application related files split up to sequence of directories\n app_files_split = []\n for app_file in app_files:\n full_path = os.path.join(extract_dir, app_file)\n app_files_split.append(auxiliary.splitPath(full_path))\n \n app_dir_tuples = list()\n if len(app_files_split) == 1:\n if len(app_files_split[0]) > 2:\n app_dir_tuples.append([app_files_split[0][1], extract_dir])\n else:\n app_dir_tuples.append([app_files_split[0][0], ''])\n else:\n for i in range(len(app_files)):\n max_non_duplicate_index = -1\n for j in range(len(app_files)):\n if i != j:\n max_non_duplicate_index = max(_checkDuplicates(app_files_split[i], app_files_split[j]), max_non_duplicate_index)\n app_dir = app_files_split[i][max_non_duplicate_index]\n app_parent_dir_path = os.path.join(*app_files_split[i][0:max_non_duplicate_index])\n \n app_dir_tuples.append([app_dir, app_parent_dir_path])\n \n return app_dir_tuples\n\ndef preprocess(return_params, kwargs):\n logger = auxiliary.getLogger()\n config = auxiliary.readConfig(os.path.join(os.environ['HOME'], '.hgsconf/hgs_new.cfg'))\n \n prefix = 's3://'\n aws_storage_bucket_name = auxiliary.read_option(config, 'aws', 'aws_storage_bucket_name')\n aws_storage_head = os.path.join(prefix, aws_storage_bucket_name)\n \n s3_app_input = auxiliary.read_option(config, 'preprocessor', 's3_app_input')\n s3_app_output = auxiliary.read_option(config, 'preprocessor', 's3_app_output')\n s3_app_scripts = auxiliary.read_option(config, 'preprocessor', 's3_app_scripts')\n \n s3cfg_path = os.path.join(os.environ['HOME'], auxiliary.read_option(config, 'preprocessor', 's3cfg'))\n \n producer = messaging.MessageProducer(\n messaging.buildRabbitMQConnectionLink(address=return_params['return_address']),\n return_params['return_queue'],\n )\n \n script_local_path = os.path.join(os.getcwd(), 'scripts/grok_hgs.py')\n script_s3_path = os.path.join(*[aws_storage_head, s3_app_scripts, os.path.basename(script_local_path)])\n s3tools.s3cmdPUT(s3cfg_path, script_local_path, script_s3_path)\n \n # TODO: handle the situation when there is no top_lvl_dir\n #create a temporary directory and process the input file in there\n with auxiliary.TemporaryDirectory() as tmp_dir:\n input_s3_path = os.path.join(aws_storage_head, kwargs['input'])\n input_local_path = os.path.join(tmp_dir, os.path.basename(input_s3_path))\n s3tools.s3cmdGET(s3cfg_path, input_s3_path, input_local_path)\n \n input_arch = os.path.basename(input_local_path)\n arch_abs_path = os.path.join(tmp_dir, input_arch)\n\n app_files = seekArchForFiles(arch_abs_path, '.grok')\n\n #list of archive names\n arch_names = []\n group_id = kwargs['group_id']\n \n #form separate archives with application input for each found application related file\n if len(app_files) > 0:\n extract_dir = 'extract'\n auxiliary.extractArch(arch_abs_path, os.path.join(tmp_dir, extract_dir))\n \n app_dir_tuples = _getAppDirs(app_files, extract_dir)\n for app_dir, app_parent_dir_path in app_dir_tuples:\n arch_name = _generateArchName()\n \n if app_parent_dir_path:\n app_parent_dir_path_full = os.path.join(tmp_dir, app_parent_dir_path)\n else:\n app_parent_dir_path_full = tmp_dir\n with auxiliary.cd_change(app_parent_dir_path_full):\n auxiliary.createArch(os.path.join(tmp_dir, arch_name), app_dir)\n \n arch_names.append(arch_name)\n #there are no application related files in the archive, maybe there are separate subarchives containing application related files\n elif len(app_files) == 0:\n #TODO\n pass\n else:\n logger.warning('Something went wrong while checking input archive!')\n \n for arch in arch_names:\n input_local_path = os.path.join(tmp_dir, arch)\n input_s3_path = os.path.join(s3_app_input, os.path.basename(input_local_path))\n input_s3_path_full = os.path.join(aws_storage_head, input_s3_path)\n output_s3_path = os.path.join(s3_app_output, 'output_' + os.path.basename(input_local_path))\n app_files = seekArchForFiles(input_local_path, '.grok')\n \n if len(app_files) == 1:\n app_file_split = auxiliary.splitPath(app_files[0])\n \n s3tools.s3cmdPUT(s3cfg_path, input_local_path, input_s3_path_full)\n message = messaging.createMessage(\n 'preprocessed', \n group_id=group_id,\n app_type='grok_hgs',\n app_input_file=input_s3_path,\n app_output_file=output_s3_path,\n app_params={\n 'app_script' : script_s3_path,\n 'app_input_file' : input_s3_path_full,\n 'app_output_file' : os.path.join(aws_storage_head, output_s3_path),\n 'licence' : '',\n 'grok' : '~/bin/grokgrok',\n 'hgs' : '~/bin/hgshgs',\n 'working_dir' : app_file_split[len(app_file_split) - 2],\n 'top_lvl_dir' : app_file_split[0],\n },\n )\n producer.publish(message)\n #print message\n else:\n # TODO: error \n pass\n message = messaging.createMessage(\n 'preprocessing_completed', \n input=kwargs['input'],\n group_id=group_id,\n )\n producer.publish(message)\n \ndef postprocess(return_params, kwargs):\n logger = auxiliary.getLogger()\n config = auxiliary.readConfig(os.path.join(os.environ['HOME'], '.hgsconf/hgs_new.cfg'))\n \n prefix = 's3://'\n aws_storage_bucket_name = auxiliary.read_option(config, 'aws', 'aws_storage_bucket_name')\n aws_storage_head = os.path.join(prefix, aws_storage_bucket_name)\n \n s3_group_output = auxiliary.read_option(config, 'postprocessor', 's3_group_output')\n \n s3cfg_path = os.path.join(os.environ['HOME'], auxiliary.read_option(config, 'postprocessor', 's3cfg'))\n \n producer = messaging.MessageProducer(\n messaging.buildRabbitMQConnectionLink(address=return_params['return_address']),\n return_params['return_queue'],\n )\n outputs_list = kwargs['outputs_list']\n group_id = kwargs['group_id']\n apps_ids_list = kwargs['apps_ids_list']\n arch_name = _generateArchName()\n \n with auxiliary.TemporaryDirectory() as tmp_dir:\n group_output_dir = os.path.join(tmp_dir, 'output')\n auxiliary.make_dirs(group_output_dir)\n \n for output in outputs_list:\n output_s3_path = os.path.join(aws_storage_head, output)\n output_local_path = os.path.join(group_output_dir, os.path.basename(output_s3_path))\n s3tools.s3cmdGET(s3cfg_path, output_s3_path, output_local_path)\n \n with auxiliary.cd_change(tmp_dir):\n auxiliary.createArch(os.path.join(tmp_dir, arch_name), 'output')\n \n group_output_local_path = os.path.join(tmp_dir, arch_name)\n group_output_s3_path = os.path.join(s3_group_output, os.path.basename(group_output_local_path))\n group_output_s3_path_full = os.path.join(aws_storage_head, group_output_s3_path)\n \n s3tools.s3cmdPUT(s3cfg_path, group_output_local_path, group_output_s3_path_full)\n \n message = messaging.createMessage(\n 'postprocessed', \n group_id=group_id,\n output=group_output_s3_path,\n apps_ids_list=apps_ids_list,\n )\n producer.publish(message)\n \n","sub_path":"hgsPreprocessing/messageHandlers.py","file_name":"messageHandlers.py","file_ext":"py","file_size_in_byte":10172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"545198975","text":"import math\nfrom datetime import datetime, timedelta\nfrom math import radians, cos, sin, asin, sqrt\n\n\n\n#http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points\ndef haversine(lat1, lat2, lon1, lon2):\n \"\"\"\n Calculate the great circle distance between two points \n on the earth (specified in decimal degrees)\n \"\"\"\n # convert decimal degrees to radians \n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n\n # haversine formula \n dlon = lon2 - lon1 \n dlat = lat2 - lat1 \n a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2\n c = 2 * asin(sqrt(a)) \n\n # 6367 km is the radius of the Earth\n km = 6367 * c\n return abs(km)\n\n\n\n\n\ndef detectTrips(dbc,imei,startDate,endDate):\n stmt = \"select * from imei{0} where stamp >= \\\"{1}\\\" and stamp <= \\\"{2}\\\" and latgps is not null and longgps is not null order by stamp\".format(imei, startDate, endDate)\n lastRow = \"\"\n lastRowTime = \"\"\n \n tripHasStarted = 0\n tripStart = 0\n tripEnd = 0\n secondsSinceLastSignifigantMovement = 0\n tripDist = 0\n \n tripStartTimes = []\n tripEndTimes = []\n tripDists = []\n \n for l in dbc.SQLSelectGenerator(stmt):\n if l is not None and abs(l[3]) > 1 and abs(l[4]) > 1:\n #print(l)\n if lastRow == \"\" :\n lastRow = l\n lastRowTime = l[0]\n \n TIMELAPSE = (l[0]-lastRowTime).total_seconds()\n d = haversine(l[3],lastRow[3], l[4], lastRow[4])*1000\n \n if TIMELAPSE >= 1200 and tripHasStarted == 1: #if we have more than a 10 minute gap in data, end prior trip if it exists \n if 500 < tripDist < 1000000: #low and high pass filter\n tripStartTimes.append(tripStart)\n tripEndTimes.append(tripEnd)\n tripDists.append(tripDist/1000)\n tripHasStarted = 0\n tripStartTime = 0\n tripEndTime = 0\n secondsSinceLastSignifigantMovement = 0\n tripDist = 0 \n lastRow = l\n lastRowTime = l[0]\n\n elif (TIMELAPSE >= 10): #only consider rows 10 seconds apart \n if d > 15 and 1000 < d/(TIMELAPSE/3600) < 80000: \n #assume that anything less than .5km/h or more than 80kmph is an error, and anything < 15 is an error\n # start trip, or add to existing trip. \n if tripHasStarted == 0:\n tripHasStarted = 1\n #print(\"STARTING TRIP\")\n tripStart = l[0]\n tripDist += d \n tripEnd = l[0] #this will get updated if its a real trip\n\n else:\n if tripHasStarted == 1: #did not move in last minute which we care about if we are on a trip\n #print(\"TRIGGERING2\")\n secondsSinceLastSignifigantMovement += TIMELAPSE\n if secondsSinceLastSignifigantMovement >= 300:\n if 1000 < tripDist < 1000000: #low and high pass filter\n tripStartTimes.append(tripStart)\n tripEndTimes.append(tripEnd)\n tripDists.append(tripDist/1000)\n tripHasStarted = 0\n tripStartTime = 0\n tripEndTime = 0\n secondsSinceLastSignifigantMovement = 0\n tripDist = 0\n lastRow = l\n lastRowTime = l[0]\n print(len(tripStartTimes))\n return tripStartTimes, tripEndTimes, tripDists\n \n\n\ndef detectChargingEvents(dbc,imei,startDate,endDate):\n \n stmt = \"select stamp, ChargingCurr, batteryvoltage from imei{0} where stamp >= \\\"{1}\\\" and stamp <= \\\"{2}\\\" and chargingCurr is not null order by stamp;\".format(imei, startDate, endDate)\n lastRow = \"\"\n lastRowTime = \"\"\n \n chargingHasStarted = 0\n chargingStart = 0\n chargingEnd = 0\n chargingStartVoltage = 0\n chargingEndVoltage = 0\n secondsSinceLastSignifigantMovement = 0\n #tripDist = 0\n \n \n chargeStartTimes = []\n chargeEndTimes = []\n chargeStartVolts = []\n chargeEndVolts= []\n \n \n for l in dbc.SQLSelectGenerator(stmt):\n if l is not None:\n #print(l)\n if lastRow == \"\" :\n lastRow = l\n lastRowTime = l[0]\n \n TIMELAPSE = (l[0]-lastRowTime).total_seconds()\n \n if TIMELAPSE >= 600 and chargingHasStarted == 1: #if we have more than a 10 minute gap in data, end prior charging event if it exists \n if 60 < (chargingEnd-chargingStart).total_seconds():\n chargeStartTimes.append(chargingStart)\n chargeEndTimes.append(chargingEnd)\n chargeStartVolts.append(chargingStartVoltage)\n chargeEndVolts.append(chargingEndVoltage)\n chargingHasStarted = 0\n chargingStart = 0\n chargingEnd = 0\n chargingStartVoltage = 0\n chargingEndVoltage = 0\n secondsSinceLastSignifigantMovement = 0\n lastRow = l\n lastRowTime = l[0]\n\n elif (TIMELAPSE >= 5): #only consider rows 10 seconds apart \n #print(l[1]) \n if l[1] > 20: \n if chargingHasStarted == 0:\n chargingHasStarted = 1\n chargingStart = l[0]\n chargingStartVoltage = l[2]\n chargingEnd = l[0] #this will get updated if its a real trip\n chargingEndVoltage = l[2]\n\n else:\n if chargingHasStarted == 1: #did not move in last minute which we care about if we are on a trip\n #print(\"TRIGGERING2\")\n secondsSinceLastSignifigantMovement += TIMELAPSE\n if chargingHasStarted >= 300:\n if 60 < (chargingEnd-chargingStart).total_seconds():\n chargeStartTimes.append(chargingStart)\n chargeEndTimes.append(chargingEnd)\n chargeStartVolts.append(chargingStartVoltage)\n chargeEndVolts.append(chargingEndVoltage)\n chargingHasStarted = 0\n chargingStart = 0\n chargingEnd = 0\n chargingStartVoltage = 0\n chargingEndVoltage = 0\n secondsSinceLastSignifigantMovement = 0\n lastRow = l\n lastRowTime = l[0]\n return chargeStartTimes, chargeEndTimes, chargeStartVolts, chargeEndVolts\n\n\n\n\n\n\n \n \n","sub_path":"compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":6990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"257976135","text":"\nimport torch\nimport torch.nn as nn\nfrom torchvision.utils import save_image\nimport numpy as np\nimport os\nimport timeit\n\nfrom utils import *\nfrom opts import parse_opts\n\n''' Settings '''\nargs = parse_opts()\nNGPU = torch.cuda.device_count()\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# some parameters in opts\nniters = args.niters_gan\nresume_niters = args.resume_niters_gan\ndim_gan = args.dim_gan\nlr_g = args.lr_g_gan\nlr_d = args.lr_d_gan\nsave_niters_freq = args.save_niters_freq\nbatch_size = min(args.batch_size_disc, args.batch_size_gene)\nnum_classes = args.cGAN_num_classes\n\nNC = args.num_channels\nIMG_SIZE = args.img_size\n\n\ndef train_CcGAN_limit(images, labels, netG, netD, save_images_folder, save_models_folder = None):\n\n netG = netG.to(device)\n netD = netD.to(device)\n\n criterion = nn.BCELoss()\n optimizerG = torch.optim.Adam(netG.parameters(), lr=lr_g, betas=(0.5, 0.999))\n optimizerD = torch.optim.Adam(netD.parameters(), lr=lr_d, betas=(0.5, 0.999))\n\n trainset = IMGs_dataset(images, labels, normalize=True)\n train_dataloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=8)\n unique_labels = np.sort(np.array(list(set(labels)))).astype(np.int)\n\n if save_models_folder is not None and resume_niters>0:\n save_file = save_models_folder + \"/CcGAN_limit_checkpoint_intrain/CcGAN_limit_checkpoint_niters_{}.pth\".format(resume_niters)\n checkpoint = torch.load(save_file)\n netG.load_state_dict(checkpoint['netG_state_dict'])\n netD.load_state_dict(checkpoint['netD_state_dict'])\n optimizerG.load_state_dict(checkpoint['optimizerG_state_dict'])\n optimizerD.load_state_dict(checkpoint['optimizerD_state_dict'])\n torch.set_rng_state(checkpoint['rng_state'])\n #end if\n\n # printed images with labels between the 5-th quantile and 95-th quantile of training labels\n n_row=10; n_col = n_row\n z_fixed = torch.randn(n_row*n_col, dim_gan, dtype=torch.float).to(device)\n start_label = np.quantile(train_labels, 0.05)\n end_label = np.quantile(train_labels, 0.95)\n selected_labels = np.linspace(start_label, end_label, num=n_row)\n y_fixed = np.zeros(n_row*n_col)\n for i in range(n_row):\n curr_label = selected_labels[i]\n for j in range(n_col):\n y_fixed[i*n_col+j] = curr_label\n print(y_fixed)\n y_fixed = torch.from_numpy(y_fixed).type(torch.float).view(-1,1).to(device)\n\n\n batch_idx = 0\n dataloader_iter = iter(train_dataloader)\n\n start_time = timeit.default_timer()\n for niter in range(resume_niters, niters):\n\n if batch_idx+1 == len(train_dataloader):\n dataloader_iter = iter(train_dataloader)\n batch_idx = 0\n\n # training images\n batch_train_images, batch_train_labels = dataloader_iter.next()\n assert batch_size == batch_train_images.shape[0]\n batch_train_images = batch_train_images.type(torch.float).to(device)\n batch_train_labels = batch_train_labels.type(torch.float).to(device)\n\n # Adversarial ground truths\n GAN_real = torch.ones(batch_size,1).to(device)\n GAN_fake = torch.zeros(batch_size,1).to(device)\n\n '''\n\n Train Generator: maximize log(D(G(z)))\n\n '''\n netG.train()\n\n # Sample noise and labels as generator input\n z = torch.randn(batch_size, dim_gan, dtype=torch.float).to(device)\n\n #generate fake images\n batch_fake_images = netG(z, batch_train_labels)\n\n # Loss measures generator's ability to fool the discriminator\n dis_out = netD(batch_fake_images, batch_train_labels)\n\n #generator try to let disc believe gen_imgs are real\n g_loss = criterion(dis_out, GAN_real)\n\n optimizerG.zero_grad()\n g_loss.backward()\n optimizerG.step()\n\n '''\n\n Train Discriminator: maximize log(D(x)) + log(1 - D(G(z)))\n\n '''\n\n # Measure discriminator's ability to classify real from generated samples\n prob_real = netD(batch_train_images, batch_train_labels)\n prob_fake = netD(batch_fake_images.detach(), batch_train_labels.detach())\n real_loss = criterion(prob_real, GAN_real)\n fake_loss = criterion(prob_fake, GAN_fake)\n d_loss = (real_loss + fake_loss) / 2\n\n optimizerD.zero_grad()\n d_loss.backward()\n optimizerD.step()\n\n batch_idx+=1\n\n if (niter+1)%20 == 0:\n print (\"CcGAN limit: [Iter %d/%d] [D loss: %.4f] [G loss: %.4f] [D prob real:%.4f] [D prob fake:%.4f] [Time: %.4f]\" % (niter+1, niters, d_loss.item(), g_loss.item(), prob_real.mean().item(),prob_fake.mean().item(), timeit.default_timer()-start_time))\n\n\n if (niter+1) % 100 == 0:\n netG.eval()\n with torch.no_grad():\n gen_imgs = netG(z_fixed, y_fixed)\n gen_imgs = gen_imgs.detach()\n save_image(gen_imgs.data, save_images_folder +'/{}.png'.format(niter+1), nrow=n_row, normalize=True)\n\n if save_models_folder is not None and ((niter+1) % save_niters_freq == 0 or (niter+1) == niters):\n save_file = save_models_folder + \"/CcGAN_limit_checkpoint_intrain/CcGAN_limit_checkpoint_niters_{}.pth\".format(niter+1)\n os.makedirs(os.path.dirname(save_file), exist_ok=True)\n torch.save({\n 'netG_state_dict': netG.state_dict(),\n 'netD_state_dict': netD.state_dict(),\n 'optimizerG_state_dict': optimizerG.state_dict(),\n 'optimizerD_state_dict': optimizerD.state_dict(),\n 'rng_state': torch.get_rng_state()\n }, save_file)\n #end for niter\n\n\n return netG, netD\n\n\n\ndef SampCcGAN_given_labels(netG, labels, path=None, NFAKE = 10000, batch_size = 500):\n '''\n labels: a numpy array; normalized label in [0,1]\n '''\n assert len(labels) == NFAKE\n if batch_size>NFAKE:\n batch_size = NFAKE\n fake_images = np.zeros((NFAKE+batch_size, NC, IMG_SIZE, IMG_SIZE), dtype=np.float)\n fake_labels = np.concatenate((labels, labels[0:batch_size]))\n netG=netG.to(device)\n netG.eval()\n\n with torch.no_grad():\n pb = SimpleProgressBar()\n tmp = 0\n while tmp < NFAKE:\n z = torch.randn(batch_size, dim_gan, dtype=torch.float).to(device)\n y = torch.from_numpy(fake_labels[tmp:(tmp+batch_size)]).type(torch.float).view(-1,1).to(device)\n batch_fake_images = netG(z, y)\n fake_images[tmp:(tmp+batch_size)] = batch_fake_images.cpu().detach().numpy()\n tmp += batch_size\n pb.update(min(float(tmp)/NFAKE, 1)*100)\n\n #remove extra entries\n fake_images = fake_images[0:NFAKE]\n fake_labels = fake_labels[0:NFAKE]\n\n if path is not None:\n raw_fake_images = (fake_images*0.5+0.5)*255.0\n raw_fake_images = raw_fake_images.astype(np.uint8)\n for i in range(NFAKE):\n filename = path + '/' + str(i) + '.jpg'\n im = Image.fromarray(raw_fake_images[i][0], mode='L')\n im = im.save(filename)\n\n return fake_images, fake_labels\n\ndef SampCcGAN_given_label(netG, label, path=None, NFAKE = 10000, batch_size = 500):\n '''\n label: a scalar; normalized label in [0,1]\n '''\n if batch_size>NFAKE:\n batch_size = NFAKE\n fake_images = np.zeros((NFAKE+batch_size, NC, IMG_SIZE, IMG_SIZE), dtype=np.float)\n netG=netG.to(device)\n netG.eval()\n\n with torch.no_grad():\n tmp = 0\n while tmp < NFAKE:\n z = torch.randn(batch_size, dim_gan, dtype=torch.float).to(device)\n y = np.ones(batch_size) * label\n y = torch.from_numpy(y).type(torch.float).view(-1,1).to(device)\n batch_fake_images = netG(z, y)\n fake_images[tmp:(tmp+batch_size)] = batch_fake_images.cpu().detach().numpy()\n tmp += batch_size\n\n #remove extra entries\n fake_images = fake_images[0:NFAKE]\n fake_labels = np.ones(NFAKE) * label #use assigned label\n\n if path is not None:\n raw_fake_images = (fake_images*0.5+0.5)*255.0\n raw_fake_images = raw_fake_images.astype(np.uint8)\n for i in range(NFAKE):\n filename = path + '/' + str(i) + '.jpg'\n im = Image.fromarray(raw_fake_images[i][0], mode='L')\n im = im.save(filename)\n\n return fake_images, fake_labels\n","sub_path":"UTKFace/UTKFace_64x64/CcGAN-improved/Train_CcGAN_limit.py","file_name":"Train_CcGAN_limit.py","file_ext":"py","file_size_in_byte":8371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"434480045","text":"from flask import Flask,jsonify,request;\nimport cx_Oracle as oracle;\nfrom flask_cors import CORS, cross_origin\nfrom flask_restful import Resource, Api\nimport json\n\nconn = oracle.connect('SYSTEM/rahul')\ncursor = conn.cursor()\n\napp=Flask(__name__)\n#from git\napi=Api(app)\nCORS(app)\n\nprint(\"RAm\")\n#functions\n@app.route(\"/users/\", methods=['GET'])\ndef getUser(id):\n query = \"select * from users where id=\"+str(id)\n cursor.execute(query)\n data = \"\"\n for name, lname, id, fname, dob, role, mobile ,email, pwd , city, state, zip in cursor:\n data='{\"user_id\":\"'+str(id)+'\",\"name\":\"'+name+'\", \"password\":\"'+pwd+'\", \"role\":\"'+role+'\"}'\n print(data)\n return json.dumps(data)\n\n@app.route(\"/users/add\",methods=['GET'])\ndef postUser():\n print(\"Hello\")\n user_data=request.args.get('user_data')\n if(user_data[-1:]!=\"}\"):\n user_data = user_data+\"}\"\n user = json.loads(user_data) \n query=\"insert into user1 values('\"+user['name']+\"','\"+user['lname']+\"',\"+str(user['id'])+\",'\"+user['fname']+\"','\"+user['dob']+\"','\"+user['role']+\"',\"+str(user['mo'])+\",'\"+user['email']+\"','\"+user['pwd']+\"','\"+user['city']+\"','\"+user['state']+\"',\"+str(user['zip'])+\")\";\n print(query)\n cursor.execute(query)\n cursor.execute(\"commit\")\n return \"\"\n\nif __name__=='__main__':\n app.run(debug=True)\n","sub_path":"oracle_db_operation.py","file_name":"oracle_db_operation.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"197448753","text":"import json\nimport os\nimport xmltodict\nimport yaml\n\n\ndef locate_ngi_config():\n config_file_path = os.environ.get(\"NGI_CONFIG\") or os.path.expandvars(\"$HOME/.ngipipeline/ngi_config.yaml\")\n if not os.path.isfile(config_file_path):\n error_msg = (\"Configuration file \\\"{}\\\" does not exist or is not a \"\n \"file. Cannot proceed.\".format(config_file_path))\n raise RuntimeError(error_msg)\n return config_file_path\n\n\ndef load_yaml_config(config_file_path):\n \"\"\"Load YAML config file, expanding environmental variables.\n\n :param str config_file_path: The path to the configuration file.\n\n :returns: A dict of the parsed config file.\n :rtype: dict\n :raises IOError: If the config file cannot be opened.\n \"\"\"\n return load_generic_config(config_file_path, config_format=\"yaml\", Loader=yaml.FullLoader)\n\n\ndef load_generic_config(config_file_path, config_format=\"yaml\", **kwargs):\n \"\"\"Parse a configuration file, returning a dict. Supports yaml, xml, and json.\n\n :param str config_file_path: The path to the configuration file.\n :param str config_format: The format of the config file; default yaml.\n\n :returns: A dict of the configuration file with environment variables expanded.\n :rtype: dict\n :raises IOError: If the config file could not be opened.\n :raises ValueError: If config file could not be parsed.\n \"\"\"\n parsers_dict = {\"json\": json.load,\n \"xml\": xmltodict.parse,\n \"yaml\": yaml.load,}\n try:\n parser_fn = parsers_dict[config_format.lower()]\n except KeyError:\n raise ValueError(\"Cannot parse config files in format specified \"\n \"(\\\"{}\\\"): format not supported.\".format(config_format))\n try:\n with open(config_file_path) as in_handle:\n config = parser_fn(in_handle, **kwargs)\n config = _expand_paths(config)\n return config\n except IOError as e:\n raise IOError(\"Could not open configuration file \\\"{}\\\".\".format(config_file_path))\n\n\ndef _expand_paths(config):\n for field, setting in config.items():\n if isinstance(config[field], dict):\n config[field] = _expand_paths(config[field])\n else:\n config[field] = expand_path(setting)\n return config\n\ndef expand_path(path):\n \"\"\"Combines os.path.expandvars with replacing ~ with $HOME.\"\"\"\n try:\n return os.path.expandvars(path.replace(\"~\", \"$HOME\"))\n except AttributeError:\n return path\n","sub_path":"ngi_pipeline/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"128338109","text":"\"\"\"\nHossein Moein\nFebruary 8, 2019\nCopyright (C) 2019-2020 Hossein Moein\nDistributed under the BSD Software License (see file LICENSE)\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Callable, List, TypeVar, Union\n\nfrom .container_item import ContainerItem\nfrom .data_item_base import AllowedBaseTypes, DataItemBase\n\n\nclass DependencyResult(Enum):\n \"\"\"Result of a dependency callback execution\"\"\"\n\n SUCCESS = 0\n FAILURE = 1\n NO_CHANGE = 2\n\n\n_SystemItemType = TypeVar('_SystemItemType', bound='SystemItem')\n_DataChangeDependencyCallback = Callable[[_SystemItemType, int, int], DependencyResult]\n_DataChangeActionCallback = Callable[[_SystemItemType, int], DependencyResult]\n\n\nclass _DependencyItem(object):\n \"\"\"An object to represent a dependency in SystemItem.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialize.\"\"\"\n super().__init__()\n # The column that needs to be changed because of independent column change.\n # We do not need to store the independent column, since it would be the index in the list\n # of dependencies.\n self.dependent_column: int = None\n # The callback for dependency or action\n self.callback: Union[_DataChangeActionCallback, _DataChangeDependencyCallback] = None\n\n\nclass SystemItem(ContainerItem):\n \"\"\"\n A system item that implements a dependency graph in a container item.\n 1. A dependency specifies a relationship between an independent column (i.e. changed) and\n a dependent column (i.e. should to change as a result).\n 2. An action specifies a reaction to a just-changed independent column.\n A system item allows many dependencies and many actions per column. Circular dependencies\n are allowed and handled properly, by going around the circle the set number of times.\n Currently, system item allows only one row in the container\n \"\"\"\n\n def __init__(self: _SystemItemType) -> None:\n \"\"\"Initialize.\"\"\"\n super().__init__()\n # The vector of dependencies/actions per column\n self._dependency_vector: List[List[_DependencyItem]] = []\n self._dependency_on: bool = True # Is dependency engine on?\n # Max number of times to go around a circular dependency before stopping\n self._dependency_circle_max: int = 1\n\n @classmethod\n def _string_format(cls, system: _SystemItemType, offset: str = '') -> str:\n \"\"\"Class method to format the system nicely.\"\"\"\n result: str = ''\n for name_and_type in system._column_names_and_types:\n result += f'{offset}{name_and_type[0]}: '\n data_idx: int = system._names_dict.get(name_and_type[0], -1)\n for data_item in system._column_data[data_idx]:\n if isinstance(data_item, ContainerItem):\n result += ' {\\n'\n result += SystemItem._string_format(data_item, offset + ' ')\n result += '}'\n else:\n result += f'{data_item.get_string()},'\n if isinstance(data_item, SystemItem):\n if (len(data_item._dependency_vector[data_idx]) > 0 and\n data_item._dependency_vector[data_idx][0].callback is not None):\n result += ' -> '\n for dep in data_item._dependency_vector[data_idx]:\n result += f'{dep.callback.__name__},'\n elif isinstance(system, SystemItem):\n if (len(system._dependency_vector[data_idx]) > 0 and\n system._dependency_vector[data_idx][0].callback is not None):\n result += ' -> '\n for dep in system._dependency_vector[data_idx]:\n result += f'{dep.callback.__name__},'\n result += '\\n'\n return result\n\n def get_value(self: _SystemItemType) -> AllowedBaseTypes:\n \"\"\"get_value() for system item.\"\"\"\n return SystemItem._string_format(self)\n\n def _dependency_engine(self: _SystemItemType, row: int, independent_column: int) -> None:\n \"\"\"The dependency loop where things happen.\"\"\"\n if self._dependency_on:\n for dep in self._dependency_vector[independent_column]:\n if dep.callback is None: # Unfortunate side-affect of how _add_column works\n break\n if dep.dependent_column is None: # This is an action\n dep.callback(independent_column)\n # This is a dependency, so we execute only if we are within the set\n # number around the circle.\n elif (self.get(column=dep.dependent_column)._dependency_circle_count <\n self._dependency_circle_max):\n # Increase the number of times we passed this item\n self.get(column=independent_column)._dependency_circle_count += 1\n dep.callback(independent_column, dep.dependent_column)\n # Decrease the number of times we passed this item\n self.get(column=independent_column)._dependency_circle_count -= 1\n else: # we did not break, so there was a dependency\n # In case this system item itself is part of another system item dependency\n self._touch()\n\n def __eq__(self: _SystemItemType, other: _SystemItemType) -> bool:\n \"\"\"Equal operator for system item.\"\"\"\n if not isinstance(other, SystemItem):\n raise TypeError(\n 'SystemItem::__eq__(): System item could only be compared '\n 'with another system container item'\n )\n\n parent_result = super().__eq__(other)\n if parent_result is False:\n return parent_result\n return self._dependency_vector == other._dependency_vector\n\n def _add_column(\n self: _SystemItemType,\n name: str,\n value: Union[AllowedBaseTypes, DataItemBase],\n column_type: type,\n ) -> DataItemBase:\n \"\"\"Private method to add a new column.\"\"\"\n new_column: DataItemBase = super()._add_column(name, value, column_type)\n\n new_column._item_change_callback = self._dependency_engine\n dep_item = _DependencyItem()\n self._dependency_vector.append([dep_item])\n return new_column\n\n def remove_column(self: _SystemItemType, column: Union[int, str]) -> None:\n raise NotImplementedError('SystemItem::remove_column(): Currently this is not implemented')\n\n def add_row(\n self: _SystemItemType,\n column: Union[str, int],\n value: Union[AllowedBaseTypes, ContainerItem],\n ) -> DataItemBase:\n \"\"\"Add a row to the given column.\"\"\"\n raise NotImplementedError('SystemItem::add_row(): You cannot add rows to a system item')\n\n def remove_row(self: _SystemItemType, column: Union[str, int], row_index: int) -> None:\n \"\"\"Remove the row for the given column.\"\"\"\n raise NotImplementedError('SystemItem::remove_row(): You cannot add rows to a system item')\n\n def add_dependency(\n self: _SystemItemType,\n independent_column: Union[int, str],\n dependent_column: Union[int, str],\n callback: _DataChangeDependencyCallback,\n ) -> None:\n \"\"\"Add a dependency callback for the given columns\"\"\"\n indep_col_idx = (\n self.column_index(independent_column)\n if type(independent_column) is str\n else independent_column\n )\n dep_col_idx = (\n self.column_index(dependent_column)\n if type(dependent_column) is str\n else dependent_column\n )\n dep_item = _DependencyItem()\n dep_item.dependent_column = dep_col_idx\n dep_item.callback = callback\n\n # Is this the first dependency being added for this column?\n if self._dependency_vector[indep_col_idx][0].callback is None:\n self._dependency_vector[indep_col_idx][0] = dep_item\n else: # append another dependency for the independent column\n self._dependency_vector[indep_col_idx].append(dep_item)\n\n def add_action(\n self: _SystemItemType,\n independent_column: Union[int, str],\n callback: _DataChangeActionCallback,\n ) -> None:\n \"\"\"Add an action callback for the given columns\"\"\"\n indep_col_idx = (\n self.column_index(independent_column)\n if type(independent_column) is str\n else independent_column\n )\n dep_item = _DependencyItem()\n dep_item.callback = callback\n\n # Is this the first action being added for this column?\n if self._dependency_vector[indep_col_idx][0].callback is None:\n self._dependency_vector[indep_col_idx][0] = dep_item\n else: # append another action for the independent column\n self._dependency_vector[indep_col_idx].append(dep_item)\n\n def is_dependency_on(self: _SystemItemType) -> bool:\n \"\"\"Is the dependency engine on?\"\"\"\n return self._dependency_on\n\n def turn_dependency_on(self: _SystemItemType) -> None:\n \"\"\"Turn on the dependency engine.\"\"\"\n self._dependency_on = True\n\n def turn_dependency_off(self: _SystemItemType) -> None:\n \"\"\"Turn off the dependency engine.\"\"\"\n self._dependency_on = False\n\n def set_dependency_circle_max(self: _SystemItemType, max_count: int) -> None:\n \"\"\"Set max number of times to go around a circular dependency before stopping.\"\"\"\n from sys import getrecursionlimit, setrecursionlimit\n\n if max_count - self._dependency_circle_max > 40:\n setrecursionlimit(getrecursionlimit() * 2)\n self._dependency_circle_max = max_count\n","sub_path":"app/system_item.py","file_name":"system_item.py","file_ext":"py","file_size_in_byte":9756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"115396493","text":"#!/usr/bin/env python\nimport ecto\nfrom ecto_opencv.highgui import imshow, NiConverter, FPSDrawer\nfrom ecto_opencv.imgproc import ConvertTo\nfrom ecto_opencv.cv_bp import CV_8UC1\nfrom ecto_openni import OpenNICapture, DEPTH_RGB, DEPTH_IR\ndevice = 0\ncapture = OpenNICapture(stream_mode=DEPTH_RGB, registration=False)\nnext_mode = DEPTH_IR\nfps = FPSDrawer('fps')\nconversion = ConvertTo(cv_type=CV_8UC1, alpha=0.5) # scale the IR so that we can visualize it.\nplasm = ecto.Plasm()\nplasm.insert(capture)\nplasm.connect(capture['image'] >> fps[:],\n fps[:] >> imshow('image display', name='image')[:],\n capture['depth'] >> imshow('depth display', name='depth')[:],\n capture['ir'] >> conversion[:],\n conversion[:] >> imshow('IR display', name='IR')[:],\n )\n\nsched = ecto.schedulers.Singlethreaded(plasm)\nwhile True:\n sched.execute(niter=100)\n #swap it modes\n next_mode, capture.params.stream_mode = capture.params.stream_mode, next_mode\n\n","sub_path":"test/openni_wrapper.py","file_name":"openni_wrapper.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"361388934","text":"# Univeral Tool Template v20.2\r\ntpl_ver = 20.20\r\ntpl_date = 220807\r\nprint(\"tpl_ver: {0}-{1}\".format(tpl_ver, tpl_date))\r\n# by ying - https://github.com/shiningdesign/universal_tool_template.py\r\n\r\nimport importlib\r\nimport sys\r\n# ---- hostMode ----\r\nhostMode = ''\r\nhostModeList = [\r\n ['maya', {'mui':'maya.OpenMayaUI', 'cmds':'maya.cmds'} ],\r\n ['nuke', {'nuke':'nuke', 'nukescripts':'nukescripts'} ],\r\n ['fusion', {'fs':'fusionscript'} ],\r\n ['houdini', {'hou':'hou'} ],\r\n ['blender', {'bpy':'bpy'} ],\r\n ['krita', {'krita':'krita'} ],\r\n ['unreal', {'unreal':'unreal'} ],\r\n ['unity', {'UnityEngine':'unity'} ],\r\n ['npp', {'Npp':'Npp'} ],\r\n]\r\nfor name, libs in hostModeList:\r\n try:\r\n for x in libs.keys():\r\n globals()[x] = importlib.import_module(libs[x])\r\n hostMode = name\r\n break\r\n except ImportError:\r\n pass\r\nif hostMode == '':\r\n hostMode = 'desktop'\r\nprint('Host: {0}'.format(hostMode))\r\n\r\n# ---- qtMode ----\r\nqtMode = 0 # 0: PySide; 1 : PyQt, 2: PySide2, 3: PyQt5\r\nqtModeList = ('PySide', 'PyQt4', 'PySide2', 'PyQt5')\r\ntry:\r\n from PySide import QtGui, QtCore\r\n import PySide.QtGui as QtWidgets\r\n qtMode = 0\r\n if hostMode == \"maya\":\r\n import shiboken\r\nexcept ImportError:\r\n try:\r\n from PySide2 import QtCore, QtGui, QtWidgets\r\n qtMode = 2\r\n if hostMode == \"maya\":\r\n import shiboken2 as shiboken\r\n except ImportError:\r\n try:\r\n from PyQt4 import QtGui,QtCore\r\n import PyQt4.QtGui as QtWidgets\r\n import sip\r\n qtMode = 1\r\n except ImportError:\r\n from PyQt5 import QtGui,QtCore,QtWidgets\r\n import sip\r\n qtMode = 3\r\nprint('Qt: {0}'.format(qtModeList[qtMode]))\r\n\r\n# ---- pyMode ----\r\n# python 2,3 support unicode function\r\ntry:\r\n UNICODE_EXISTS = bool(type(unicode))\r\nexcept NameError:\r\n # lambda s: str(s) # this works for function but not for class check\r\n unicode = str\r\nif sys.version_info[:3][0]>=3:\r\n reload = importlib.reload # add reload\r\n\r\npyMode = '.'.join([ str(n) for n in sys.version_info[:3] ])\r\nprint(\"Python: {0}\".format(pyMode))\r\n\r\n# ---- osMode ----\r\nosMode = 'other'\r\nif sys.platform in ['win32','win64']:\r\n osMode = 'win'\r\nelif sys.platform == 'darwin':\r\n osMode = 'mac'\r\nelif sys.platform == 'linux2':\r\n osMode = 'linux'\r\nprint(\"OS: {0}\".format(osMode))\r\n\r\n# ---- template module list ----\r\nimport os # for path and language code\r\nfrom functools import partial # for partial function creation\r\nimport json # for ascii data output\r\nimport re # for name pattern\r\nimport subprocess # for cmd call\r\n\r\n#=======================================\r\n# UniversalToolUI template class\r\n#=======================================\r\n\r\nclass UniversalToolUI(QtWidgets.QMainWindow): \r\n def __init__(self, parent=None):\r\n QtWidgets.QMainWindow.__init__(self, parent)\r\n\r\n # class property\r\n self.tpl_ver = tpl_ver\r\n self.tpl_date = tpl_date\r\n self.version = '0.1'\r\n self.date = '2017.01.01'\r\n self.log = 'no version log in user class'\r\n self.help = 'no help guide in user class'\r\n \r\n # class info\r\n self.name = self.__class__.__name__\r\n self.fileType='.{0}_EXT'.format(self.name)\r\n \r\n # class path and icon\r\n self.location = ''\r\n if getattr(sys, 'frozen', False):\r\n self.location = sys.executable # frozen case - cx_freeze\r\n else:\r\n self.location = os.path.realpath(sys.modules[self.__class__.__module__].__file__)\r\n self.iconPath = os.path.join(os.path.dirname(self.location),'icons',self.name+'.png')\r\n self.iconPix = QtGui.QPixmap(self.iconPath)\r\n self.icon = QtGui.QIcon(self.iconPath)\r\n \r\n # class data\r\n self.hotkey = {}\r\n self.uiList={} # for ui obj storage\r\n self.memoData = {} # key based variable data storage\r\n self.memoData['font_size_default'] = QtGui.QFont().pointSize()\r\n self.memoData['font_size'] = self.memoData['font_size_default']\r\n self.memoData['last_export'] = ''\r\n self.memoData['last_import'] = ''\r\n self.memoData['last_browse'] = ''\r\n \r\n # core function variable\r\n self.qui_core_dict = {\r\n 'vbox': 'QVBoxLayout','hbox':'QHBoxLayout','grid':'QGridLayout', 'form':'QFormLayout',\r\n 'split': 'QSplitter', 'grp':'QGroupBox', 'tab':'QTabWidget',\r\n 'btn':'QPushButton', 'btnMsg':'QPushButton', 'label':'QLabel', 'input':'QLineEdit', 'check':'QCheckBox', 'choice':'QComboBox', 'spin':'QSpinBox',\r\n 'txt': 'QTextEdit',\r\n 'list': 'QListWidget', 'tree': 'QTreeWidget', 'table': 'QTableWidget',\r\n 'space': 'QSpacerItem',\r\n 'menu' : 'QMenu', 'menubar' : 'QMenuBar',\r\n }\r\n self.qui_user_dict = {}\r\n \r\n def setupMenu(self):\r\n if 'help_menu' in self.uiList.keys():\r\n self.uiList['helpGuide_msg'] = self.help\r\n self.uiList['helpLog_msg'] = self.log\r\n item_list = [\r\n ('helpHostMode_atnNone', 'Host Mode - {}'.format(hostMode) ),\r\n ('helpPyMode_atnNone','Python Mode - {}'.format(pyMode) ),\r\n ('helpQtMode_atnNone','Qt Mode - {}'.format(qtModeList[qtMode]) ),\r\n ('helpTemplate_atnNone','Universal Tool Teamplate - {0}.{1}'.format(tpl_ver, tpl_date) ),\r\n ('_','_'),\r\n ('helpGuide_atnMsg','Usage Guide'),\r\n ('helpLog_atnMsg','About v{0} - {1}'.format(self.version, self.date) ),\r\n ]\r\n menu_str = '|'.join(['{0};{1}'.format(*x) for x in item_list])\r\n self.qui_menu(menu_str, 'help_menu')\r\n # tip info\r\n self.uiList['helpTemplate_atnNone'].setStatusTip('based on Univeral Tool Template v{0} by Shining Ying - https://github.com/shiningdesign/universal{1}tool{1}template.py'.format(tpl_ver,'_'))\r\n \r\n def setupWin(self):\r\n self.setWindowTitle(self.name + \" - v\" + self.version + \" - host: \" + hostMode)\r\n self.setWindowIcon(self.icon)\r\n \r\n def setupUI(self, layout='grid'):\r\n main_widget = QtWidgets.QWidget()\r\n self.setCentralWidget(main_widget)\r\n self.qui('main_layout;{0}'.format(layout))\r\n main_widget.setLayout(self.uiList['main_layout'])\r\n\r\n def Establish_Connections(self):\r\n for ui_name in self.uiList.keys():\r\n prefix = ui_name.rsplit('_', 1)[0]\r\n if ui_name.endswith('_btn'):\r\n self.uiList[ui_name].clicked.connect(getattr(self, prefix+\"_action\", partial(self.default_action,ui_name)))\r\n elif ui_name.endswith('_atn'):\r\n self.uiList[ui_name].triggered.connect(getattr(self, prefix+\"_action\", partial(self.default_action,ui_name)))\r\n elif ui_name.endswith('_btnMsg'):\r\n self.uiList[ui_name].clicked.connect(getattr(self, prefix+\"_message\", partial(self.default_message,ui_name)))\r\n elif ui_name.endswith('_atnMsg'):\r\n self.uiList[ui_name].triggered.connect(getattr(self, prefix+\"_message\", partial(self.default_message,ui_name)))\r\n \r\n #=======================================\r\n # ui response functions\r\n #=======================================\r\n def ____ui_response_functions____():\r\n pass\r\n def default_action(self, ui_name, *argv):\r\n print(\"No action defined for this UI element: \"+ui_name)\r\n def default_message(self, ui_name):\r\n prefix = ui_name.rsplit('_', 1)[0]\r\n msgName = prefix+\"_msg\"\r\n msg_txt = msgName + \" is not defined in uiList.\"\r\n if msgName in self.uiList:\r\n msg_txt = self.uiList[msgName]\r\n self.quickMsg(msg_txt)\r\n def default_menu_call(self, ui_name, point):\r\n if ui_name in self.uiList.keys() and ui_name+'_menu' in self.uiList.keys():\r\n self.uiList[ui_name+'_menu'].exec_(self.uiList[ui_name].mapToGlobal(point))\r\n def toggleTop_action(self):\r\n self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowStaysOnTopHint)\r\n self.show()\r\n def hotkey_action(self):\r\n txt_list = []\r\n for each_key in sorted(self.hotkey.keys()):\r\n txt_list.append(each_key+' : '+unicode(self.hotkey[each_key].key().toString()))\r\n self.quickMsg('\\n'.join(txt_list))\r\n \r\n #=======================================\r\n # ui feedback functions\r\n #=======================================\r\n def ____ui_feedback_functions____():\r\n pass\r\n def quickInfo(self, info, force=0):\r\n if hasattr( self.window(), \"quickInfo\") and force == 0:\r\n if hasattr(self.window(), 'statusBar'):\r\n self.window().statusBar().showMessage(info)\r\n else:\r\n if hasattr(self, 'statusBar'):\r\n self.statusBar().showMessage(info)\r\n def quickMsg(self, msg, block=1, ask=0):\r\n tmpMsg = QtWidgets.QMessageBox(self) # for simple msg that no need for translation\r\n tmpMsg.setWindowTitle(\"Info\")\r\n lineCnt = len(msg.split('\\n'))\r\n if lineCnt > 25:\r\n scroll = QtWidgets.QScrollArea()\r\n scroll.setWidgetResizable(1)\r\n content = QtWidgets.QWidget()\r\n scroll.setWidget(content)\r\n layout = QtWidgets.QVBoxLayout(content)\r\n tmpLabel = QtWidgets.QLabel(msg)\r\n tmpLabel.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)\r\n layout.addWidget(tmpLabel)\r\n tmpMsg.layout().addWidget(scroll, 0, 0, 1, tmpMsg.layout().columnCount())\r\n tmpMsg.setStyleSheet(\"QScrollArea{min-width:600 px; min-height: 400px}\")\r\n else:\r\n tmpMsg.setText(msg)\r\n if block == 0:\r\n tmpMsg.setWindowModality( QtCore.Qt.NonModal )\r\n if ask==0:\r\n tmpMsg.addButton(\"OK\",QtWidgets.QMessageBox.YesRole)\r\n else:\r\n tmpMsg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)\r\n if block:\r\n value = tmpMsg.exec_()\r\n if value == QtWidgets.QMessageBox.Ok:\r\n return 1\r\n else:\r\n return 0\r\n else:\r\n tmpMsg.show()\r\n return 0\r\n def quickMsgAsk(self, msg, mode=0, choice=[]):\r\n # getItem, getInteger, getDouble, getText\r\n modeOpt = (QtWidgets.QLineEdit.Normal, QtWidgets.QLineEdit.NoEcho, QtWidgets.QLineEdit.Password, QtWidgets.QLineEdit.PasswordEchoOnEdit)\r\n # option: QtWidgets.QInputDialog.UseListViewForComboBoxItems\r\n if len(choice)==0:\r\n txt, ok = QtWidgets.QInputDialog.getText(self, \"Input\", msg, modeOpt[mode])\r\n return (unicode(txt), ok)\r\n else:\r\n txt, ok = QtWidgets.QInputDialog.getItem(self, \"Input\", msg, choice, 0, 0)\r\n return (unicode(txt), ok)\r\n def quickModKeyAsk(self):\r\n modifiers = QtWidgets.QApplication.queryKeyboardModifiers()\r\n clickMode = 0 # basic mode\r\n if modifiers == QtCore.Qt.ControlModifier:\r\n clickMode = 1 # ctrl\r\n elif modifiers == QtCore.Qt.ShiftModifier:\r\n clickMode = 2 # shift\r\n elif modifiers == QtCore.Qt.AltModifier:\r\n clickMode = 3 # alt\r\n elif modifiers == QtCore.Qt.ControlModifier | QtCore.Qt.ShiftModifier | QtCore.Qt.AltModifier:\r\n clickMode = 4 # ctrl+shift+alt\r\n elif modifiers == QtCore.Qt.ControlModifier | QtCore.Qt.AltModifier:\r\n clickMode = 5 # ctrl+alt\r\n elif modifiers == QtCore.Qt.ControlModifier | QtCore.Qt.ShiftModifier:\r\n clickMode = 6 # ctrl+shift\r\n elif modifiers == QtCore.Qt.AltModifier | QtCore.Qt.ShiftModifier:\r\n clickMode = 7 # alt+shift\r\n return clickMode\r\n def quickFileAsk(self, type, ext=None, dir=None):\r\n if ext == None:\r\n ext = \"RAW data (*.json);;RAW binary data (*.dat);;Format Txt (*{0});;AllFiles (*.*)\".format(self.fileType)\r\n elif isinstance(ext, (str,unicode)):\r\n if ';;' not in ext:\r\n if ext == '':\r\n ext = 'AllFiles (*.*)'\r\n else:\r\n ext = self.extFormat(ext) + ';;AllFiles (*.*)'\r\n elif isinstance(ext, (tuple,list)):\r\n if len(ext) > 0 and isinstance(ext[0], (tuple,list)):\r\n tmp_list = [self.extFormat(x) for x in ext]\r\n tmp_list.append('AllFiles (*.*)')\r\n ext = ';;'.join(tmp_list)\r\n else:\r\n ext = ';;'.join([self.extFormat(x) for x in ext].append('AllFiles(*.*)')) \r\n elif isinstance(ext, dict):\r\n tmp_list = [self.extFormat(x) for x in ext.items()]\r\n tmp_list.append('AllFiles (*.*)')\r\n ext = ';;'.join(tmp_list)\r\n else:\r\n ext = \"AllFiles (*.*)\"\r\n file = ''\r\n if type == 'export':\r\n if dir == None:\r\n dir = self.memoData['last_export']\r\n file = QtWidgets.QFileDialog.getSaveFileName(self, \"Save File\",dir,ext)\r\n elif type == 'import':\r\n if dir == None:\r\n dir = self.memoData['last_import']\r\n file = QtWidgets.QFileDialog.getOpenFileName(self, \"Open File\",dir,ext)\r\n if isinstance(file, (list, tuple)):\r\n file = file[0] # for deal with pyside case\r\n else:\r\n file = unicode(file) # for deal with pyqt case\r\n # save last dir in memoData\r\n if file != '':\r\n if type == 'export':\r\n self.memoData['last_export'] = os.path.dirname(file) #QFileInfo().path()\r\n elif type == 'import':\r\n self.memoData['last_import'] = os.path.dirname(file)\r\n return file\r\n def extFormat(self, ext):\r\n if isinstance(ext, (tuple,list)):\r\n ext = '{0} (*.{1})'.format(ext[1],ext[0])\r\n else:\r\n if ext.startswith('.'):\r\n ext = ext[1:]\r\n ext = '{0} (*.{0})'.format(ext)\r\n return ext\r\n def quickFolderAsk(self,dir=None):\r\n if dir == None:\r\n dir = self.memoData['last_browse']\r\n if self.parent is not None and hasattr(self.parent, 'memoData'):\r\n dir = self.parent.memoData['last_browse']\r\n folder = unicode(QtWidgets.QFileDialog.getExistingDirectory(self, \"Select Directory\",dir))\r\n if folder != '':\r\n self.memoData['last_browse'] = folder\r\n return folder\r\n \r\n #=======================================\r\n # file data functions\r\n #=======================================\r\n def ____file_data_functions____():\r\n pass\r\n def readDataFile(self,file,binary=0):\r\n if binary != 0:\r\n print('Lite no longer support binary format')\r\n with open(file) as f:\r\n data = json.load(f)\r\n return data\r\n def writeDataFile(self,data,file,binary=0):\r\n if binary != 0:\r\n print('Lite no longer support binary format')\r\n with open(file, 'w') as f:\r\n json.dump(data, f)\r\n def readTextFile(self, file):\r\n with open(file) as f:\r\n txt = f.read()\r\n return txt\r\n def writeTextFile(self, txt, file, b=0):\r\n b = '' if b==0 else 'b'\r\n with open(file, 'w'+b) as f:\r\n f.write(txt)\r\n def dict_merge(self, default_dict, extra_dict, addKey=0):\r\n # dictionary merge, with optional adding extra data from extra_dict\r\n new_dict = {}\r\n for key in default_dict.keys():\r\n if not isinstance( default_dict[key], dict ):\r\n # value case\r\n if key in extra_dict.keys():\r\n is_same_text_type = isinstance(extra_dict[key], (str,unicode)) and isinstance(default_dict[key], (str,unicode))\r\n is_same_non_text_type = type(extra_dict[key]) is type(default_dict[key])\r\n if is_same_text_type or is_same_non_text_type:\r\n print('use config file value for key: '+key)\r\n new_dict[key] = extra_dict[key]\r\n else:\r\n new_dict[key] = default_dict[key]\r\n else:\r\n new_dict[key] = default_dict[key]\r\n else:\r\n # dictionary case\r\n if key in extra_dict.keys() and isinstance( extra_dict[key], dict ):\r\n new_dict[key] = self.dict_merge( default_dict[key], extra_dict[key], addKey )\r\n else:\r\n new_dict[key] = default_dict[key]\r\n # optional, add additional keys\r\n if addKey == 1:\r\n for key in [ x for x in extra_dict.keys() if x not in default_dict.keys() ]:\r\n new_dict[key] = extra_dict[key]\r\n return new_dict\r\n #=======================================\r\n # ui text functions\r\n #=======================================\r\n def ____ui_text_functions____():\r\n pass\r\n def fontNormal_action(self, uiClass_list=[]):\r\n if len(uiClass_list) == 0:\r\n uiClass_list = 'QLabel,QPushButton'.split(',')\r\n self.memoData['font_size'] = self.memoData['font_size_default']\r\n self.setStyleSheet( \"{0} { font-size: {1}pt;}\".format(','.join(uiClass_list), self.memoData['font_size']) )\r\n def fontUp_action(self, uiClass_list=[]):\r\n if len(uiClass_list) == 0:\r\n uiClass_list = 'QLabel,QPushButton'.split(',')\r\n self.memoData['font_size'] += 2\r\n self.setStyleSheet( \"{0} { font-size: {1}pt;}\".format(','.join(uiClass_list), self.memoData['font_size']) )\r\n def fontDown_action(self, uiClass_list=[]):\r\n if len(uiClass_list) == 0:\r\n uiClass_list = 'QLabel,QPushButton'.split(',')\r\n if self.memoData['font_size'] >= self.memoData['font_size_default']:\r\n self.memoData['font_size'] -= 2\r\n self.setStyleSheet( \"{0} { font-size: {1}pt;}\".format(','.join(uiClass_list), self.memoData['font_size']) )\r\n def loadLang(self, build_menu=1):\r\n # store default language\r\n self.memoData['lang']={}\r\n self.memoData['lang']['default']={}\r\n for ui_name in self.uiList.keys():\r\n ui_element = self.uiList[ui_name]\r\n if isinstance(ui_element, (QtWidgets.QLabel, QtWidgets.QPushButton, QtWidgets.QAction, QtWidgets.QCheckBox) ):\r\n # uiType: QLabel, QPushButton, QAction(menuItem), QCheckBox\r\n self.memoData['lang']['default'][ui_name] = unicode(ui_element.text())\r\n elif isinstance(ui_element, (QtWidgets.QGroupBox, QtWidgets.QMenu) ):\r\n # uiType: QMenu, QGroupBox\r\n self.memoData['lang']['default'][ui_name] = unicode(ui_element.title())\r\n elif isinstance(ui_element, QtWidgets.QTabWidget):\r\n # uiType: QTabWidget\r\n tabCnt = ui_element.count()\r\n tabNameList = []\r\n for i in range(tabCnt):\r\n tabNameList.append(unicode(ui_element.tabText(i)))\r\n self.memoData['lang']['default'][ui_name]=';'.join(tabNameList)\r\n elif isinstance(ui_element, QtWidgets.QComboBox):\r\n # uiType: QComboBox\r\n itemCnt = ui_element.count()\r\n itemNameList = []\r\n for i in range(itemCnt):\r\n itemNameList.append(unicode(ui_element.itemText(i)))\r\n self.memoData['lang']['default'][ui_name]=';'.join(itemNameList)\r\n elif isinstance(ui_element, QtWidgets.QTreeWidget):\r\n # uiType: QTreeWidget\r\n labelCnt = ui_element.headerItem().columnCount()\r\n labelList = []\r\n for i in range(labelCnt):\r\n labelList.append(unicode(ui_element.headerItem().text(i)))\r\n self.memoData['lang']['default'][ui_name]=';'.join(labelList)\r\n elif isinstance(ui_element, QtWidgets.QTableWidget):\r\n # uiType: QTableWidget\r\n colCnt = ui_element.columnCount()\r\n headerList = []\r\n for i in range(colCnt):\r\n if ui_element.horizontalHeaderItem(i):\r\n headerList.append( unicode(ui_element.horizontalHeaderItem(i).text()) )\r\n else:\r\n headerList.append('')\r\n self.memoData['lang']['default'][ui_name]=';'.join(headerList)\r\n elif isinstance(ui_element, (str, unicode) ):\r\n # uiType: string for msg\r\n self.memoData['lang']['default'][ui_name] = self.uiList[ui_name]\r\n \r\n # language menu\r\n lang_menu = 'language_menu'\r\n if build_menu == 1:\r\n self.qui_menubar('language_menu;&Language')\r\n self.qui_menu('langDefault_atnLang;Default | _', lang_menu)\r\n self.uiList['langDefault_atnLang'].triggered.connect(partial(self.setLang,'default'))\r\n \r\n # scan for language file\r\n lang_path = os.path.dirname(self.location)\r\n baseName = os.path.splitext( os.path.basename(self.location) )[0]\r\n for file in self.getPathChild(lang_path, pattern=baseName+'_lang_[a-zA-Z]+.json', isfile=1):\r\n langName = re.findall(baseName+'_lang_(.+)\\.json', file)\r\n if len(langName) == 1:\r\n langName = langName[0].upper()\r\n self.memoData['lang'][ langName ] = self.readDataFile( os.path.join(lang_path, file) )\r\n if build_menu == 1:\r\n self.qui_menu('{0}_atnLang;{0}'.format(langName), lang_menu)\r\n self.uiList[langName+'_atnLang'].triggered.connect(partial(self.setLang,langName))\r\n # if no language file detected, add export default language option\r\n if build_menu == 1:\r\n if isinstance(self, QtWidgets.QMainWindow) and len(self.memoData['lang']) == 1:\r\n self.qui_menu('langExport_atnLang;Export Default Language', lang_menu)\r\n self.uiList['langExport_atnLang'].triggered.connect(self.exportLang)\r\n \r\n def setLang(self, langName):\r\n lang_data = self.memoData['lang'][langName]\r\n for ui_name in lang_data.keys():\r\n if ui_name in self.uiList.keys() and lang_data[ui_name] != '':\r\n ui_element = self.uiList[ui_name]\r\n # '' means no translation availdanle in that data file\r\n if isinstance(ui_element, (QtWidgets.QLabel, QtWidgets.QPushButton, QtWidgets.QAction, QtWidgets.QCheckBox) ):\r\n # uiType: QLabel, QPushButton, QAction(menuItem), QCheckBox\r\n ui_element.setText(lang_data[ui_name])\r\n elif isinstance(ui_element, (QtWidgets.QGroupBox, QtWidgets.QMenu) ):\r\n # uiType: QMenu, QGroupBox\r\n ui_element.setTitle(lang_data[ui_name])\r\n elif isinstance(ui_element, QtWidgets.QTabWidget):\r\n # uiType: QTabWidget\r\n tabCnt = ui_element.count()\r\n tabNameList = lang_data[ui_name].split(';')\r\n if len(tabNameList) == tabCnt:\r\n for i in range(tabCnt):\r\n if tabNameList[i] != '':\r\n ui_element.setTabText(i,tabNameList[i])\r\n elif isinstance(ui_element, QtWidgets.QComboBox):\r\n # uiType: QComboBox\r\n itemCnt = ui_element.count()\r\n itemNameList = lang_data[ui_name].split(';')\r\n ui_element.clear()\r\n ui_element.addItems(itemNameList)\r\n elif isinstance(ui_element, QtWidgets.QTreeWidget):\r\n # uiType: QTreeWidget\r\n labelCnt = ui_element.headerItem().columnCount()\r\n labelList = lang_data[ui_name].split(';')\r\n ui_element.setHeaderLabels(labelList)\r\n elif isinstance(ui_element, QtWidgets.QTableWidget):\r\n # uiType: QTableWidget\r\n colCnt = ui_element.columnCount()\r\n headerList = lang_data[ui_name].split(';')\r\n cur_table.setHorizontalHeaderLabels( headerList )\r\n elif isinstance(ui_element, (str, unicode) ):\r\n # uiType: string for msg\r\n self.uiList[ui_name] = lang_data[ui_name]\r\n def exportLang(self):\r\n file = self.quickFileAsk('export', ext='json')\r\n if file != '':\r\n self.writeDataFile( self.memoData['lang']['default'], file )\r\n self.quickMsg(\"Languge File created: '\"+file)\r\n \r\n #=======================================\r\n # os functions\r\n #=======================================\r\n def ____os_functions____():\r\n pass\r\n def openFolder(self, folderPath):\r\n if os.path.isfile(folderPath):\r\n folderPath = os.path.dirname(folderPath)\r\n if os.path.isdir(folderPath):\r\n cmd_list = None\r\n if sys.platform == 'darwin':\r\n cmd_list = ['open', '--', folderPath]\r\n elif sys.platform == 'linux2':\r\n cmd_list = ['xdg-open', folderPath]\r\n elif sys.platform in ['win32','win64']:\r\n cmd_list = ['explorer', folderPath.replace('/','\\\\')]\r\n if cmd_list != None:\r\n try:\r\n subprocess.check_call(cmd_list)\r\n except subprocess.CalledProcessError:\r\n pass # handle errors in the called executable\r\n except OSError:\r\n pass # executable not found\r\n def openFile(self, filePath):\r\n if sys.platform in ['win32','win64']:\r\n os.startfile(filePath)\r\n elif sys.platform == 'darwin':\r\n os.open(filePath)\r\n elif sys.platform == 'linux2':\r\n os.xdg-open(filePath)\r\n def newFolder(self, parentPath, name=None):\r\n if os.path.isfile(parentPath):\r\n parentPath = os.path.dirname(parentPath)\r\n created = 0\r\n if name == None:\r\n name, ok = self.quickMsgAsk('Enter the folder name:')\r\n if not ok or name=='':\r\n return\r\n create_path = os.path.join(parentPath, name)\r\n if os.path.isdir(create_path):\r\n self.quickMsg('Already Exists')\r\n else:\r\n try: \r\n os.makedirs(create_path)\r\n created = 1\r\n except OSError:\r\n self.quickMsg('Error on creation user data folder')\r\n return created\r\n def getPathChild(self, scanPath, pattern='', isfile=0):\r\n resultList =[]\r\n scanPath = unicode(scanPath)\r\n if not os.path.isdir(scanPath):\r\n return resultList\r\n if isfile == 0:\r\n resultList = [x for x in os.listdir(scanPath) if os.path.isdir(os.path.join(scanPath,x))]\r\n elif isfile == 1:\r\n resultList = [x for x in os.listdir(scanPath) if os.path.isfile(os.path.join(scanPath,x))]\r\n else:\r\n resultList = os.listdir(scanPath)\r\n if pattern != '':\r\n cur_pattern = re.compile(pattern)\r\n resultList = [x for x in resultList if cur_pattern.match(x)]\r\n resultList.sort()\r\n return resultList\r\n \r\n #=======================================\r\n # qui functions\r\n #=======================================\r\n def ____qui_functions____():\r\n pass\r\n \r\n def setAsUI(self):\r\n # turn win to widget\r\n self.setWindowFlags(QtCore.Qt.Widget)\r\n self.statusBar().hide()\r\n self.uiList['main_layout'].setContentsMargins(0, 0, 0, 0)\r\n def qui_key(self, key_name, key_combo, func):\r\n self.hotkey[key_name] = QtWidgets.QShortcut(QtGui.QKeySequence(key_combo), self)\r\n self.hotkey[key_name].activated.connect( func )\r\n def qui_menubar(self, menu_list_str):\r\n if not isinstance(self, QtWidgets.QMainWindow):\r\n print(\"Warning: Only QMainWindow can have menu bar.\")\r\n return\r\n menubar = self.menuBar()\r\n create_opt_list = [ x.strip() for x in menu_list_str.split('|') ]\r\n for each_creation in create_opt_list:\r\n ui_info = [ x.strip() for x in each_creation.split(';') ]\r\n menu_name = ui_info[0]\r\n menu_title = ''\r\n if len(ui_info) > 1:\r\n menu_title = ui_info[1]\r\n if menu_name not in self.uiList.keys():\r\n self.uiList[menu_name] = QtWidgets.QMenu(menu_title)\r\n menubar.addMenu(self.uiList[menu_name])\r\n def qui_menu(self, action_list_str, menu_str):\r\n # qui menu creation\r\n # syntax: self.qui_menu('right_menu_createFolder_atn;Create Folder,Ctrl+D | right_menu_openFolder_atn;Open Folder', 'right_menu')\r\n if menu_str not in self.uiList.keys():\r\n self.uiList[menu_str] = QtWidgets.QMenu()\r\n create_opt_list = [ x.strip() for x in action_list_str.split('|') ]\r\n for each_creation in create_opt_list:\r\n ui_info = [ x.strip() for x in each_creation.split(';') ]\r\n atn_name = ui_info[0]\r\n atn_title = ''\r\n atn_hotkey = ''\r\n if len(ui_info) > 1:\r\n options = ui_info[1].split(',')\r\n atn_title = '' if len(options) < 1 else options[0]\r\n atn_hotkey = '' if len(options) < 2 else options[1]\r\n if atn_name != '':\r\n if atn_name == '_':\r\n self.uiList[menu_str].addSeparator()\r\n else:\r\n if atn_name not in self.uiList.keys():\r\n self.uiList[atn_name] = QtWidgets.QAction(atn_title, self)\r\n if atn_hotkey != '':\r\n self.uiList[atn_name].setShortcut(QtGui.QKeySequence(atn_hotkey))\r\n self.uiList[menu_str].addAction(self.uiList[atn_name])\r\n \r\n def qui_class(self,uiName,uiInfo=[]):\r\n if not isinstance(uiInfo, (list, tuple)):\r\n uiInfo = [uiInfo]\r\n \r\n uiClass = uiName.rsplit('_',1)[-1]\r\n if uiClass == 'layout' and len(uiInfo)>0:\r\n uiClass = uiInfo[0]\r\n if uiClass in self.qui_user_dict:\r\n uiClass = self.qui_user_dict[uiClass] # first, try user dict\r\n elif uiClass in self.qui_core_dict:\r\n uiClass = self.qui_core_dict[uiClass] # then, try default core dict\r\n # check\r\n if hasattr(QtWidgets, uiClass) or uiClass in sys.modules:\r\n return [uiClass,1]\r\n else:\r\n return [uiClass,0]\r\n\r\n def qui(self, ui_list_string, parent_ui_string='', insert_opt=''):\r\n # ui format: \r\n # 'process_label;Process Path: | process_file_input | process_file_btn;Process'\r\n # 'extra_check;Add Extra'\r\n # 'option_choice;(TypeA,TypeB) | file_tree;(Name,Path) | option_space;(5,5,5,3)'\r\n # parent format:\r\n # 'main_layout;vbox', 'main_hbox', 'main_form'\r\n # 'main_grid' \r\n # 'main_split;v', \r\n # 'main_grp;hbox;Process', \r\n # 'main_tab;v' <(Media,Edit,Publish)>\r\n ui_string_list = [ x.strip() for x in ui_list_string.split('|') if x.strip()!='']\r\n ui_data_list = []\r\n for ui_string in ui_string_list:\r\n creation_result = self.qui_data(ui_string)\r\n if creation_result is not None:\r\n ui_data_list.append(creation_result)\r\n # - ui parent\r\n if parent_ui_string == '':\r\n return ui_data_list\r\n else:\r\n parent_ui_data = self.qui_data(parent_ui_string)\r\n if parent_ui_data is not None:\r\n self.qui_insert(ui_data_list, parent_ui_data, insert_opt)\r\n return parent_ui_data['name']\r\n else:\r\n return\r\n \r\n def qui_data(self, ui_string):\r\n # ui_string to ui_data, if not created, create obj in ui_data\r\n # reference\r\n class_error_msg = \"WARNING: ({0}) is not defined in self.qui_user_dict and it is not a Qt widget class or User class; Item {1} Ignored.\"\r\n # process\r\n info_list = ui_string.split(';')\r\n uiName = info_list[0]\r\n uiLabel = ''\r\n uiInfo = []\r\n if '@' in uiName:\r\n uiName,uiLabel = uiName.split('@',1)\r\n if len(info_list) > 1:\r\n uiInfo = info_list[1:] # .split(',')\r\n \r\n if uiName in self.uiList.keys():\r\n # case 1: already created\r\n return {'name':uiName, 'obj':self.uiList[uiName], 'label':uiLabel}\r\n else:\r\n # case 2: create obj\r\n uiClass, isValid = self.qui_class(uiName, uiInfo)\r\n if not isValid:\r\n print(class_error_msg.format(uiClass, uiName))\r\n return None\r\n else:\r\n if len(uiInfo)==0 and uiClass in ('QPushButton','QLabel'):\r\n uiInfo.append(uiName) # give empty button and label a place holder name\r\n return self.qui_obj( {'name': uiName, 'class': uiClass, 'label':uiLabel, 'info': uiInfo} )\r\n \r\n def qui_obj(self, ui_data):\r\n # ui_data to obj generation\r\n # reference value\r\n policyList = ( \r\n QtWidgets.QSizePolicy.Fixed, \r\n QtWidgets.QSizePolicy.Minimum, \r\n QtWidgets.QSizePolicy.Maximum, \r\n QtWidgets.QSizePolicy.Preferred, \r\n QtWidgets.QSizePolicy.Expanding, \r\n QtWidgets.QSizePolicy.MinimumExpanding, \r\n QtWidgets.QSizePolicy.Ignored,\r\n )\r\n \r\n # case 1: already has obj created, just return\r\n if 'obj' in ui_data.keys():\r\n return ui_data\r\n \r\n # case 2: create obj\r\n uiName = ui_data['name']\r\n uiClass = ui_data['class']\r\n uiInfo = []\r\n if 'info' in ui_data.keys():\r\n uiInfo = ui_data['info']\r\n # -- 3rd part widget, create like UI_Class.UI_Class()\r\n if not hasattr(QtWidgets, uiClass):\r\n self.uiList[uiName] = getattr(sys.modules[uiClass], uiClass)(*uiInfo)\r\n ui_data['obj'] = self.uiList[uiName]\r\n return ui_data\r\n \r\n # -- QtWidgets\r\n if uiClass in ('QVBoxLayout', 'QHBoxLayout', 'QFormLayout', 'QGridLayout'):\r\n # --- Qt Layout creation preset func\r\n if uiClass == \"QFormLayout\":\r\n self.uiList[uiName] = QtWidgets.QFormLayout()\r\n self.uiList[uiName].setLabelAlignment(QtCore.Qt.AlignLeft)\r\n self.uiList[uiName].setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow) \r\n ui_data['obj'] = self.uiList[uiName]\r\n elif uiClass == \"QGridLayout\":\r\n self.uiList[uiName] = QtWidgets.QGridLayout()\r\n ui_data['obj'] = self.uiList[uiName]\r\n elif uiClass == \"QHBoxLayout\":\r\n self.uiList[uiName] = QtWidgets.QHBoxLayout()\r\n self.uiList[uiName].setAlignment(QtCore.Qt.AlignTop)\r\n ui_data['obj'] = self.uiList[uiName]\r\n else:\r\n self.uiList[uiName] = QtWidgets.QVBoxLayout()\r\n self.uiList[uiName].setAlignment(QtCore.Qt.AlignTop)\r\n ui_data['obj'] = self.uiList[uiName]\r\n elif uiClass in ('QSplitter', 'QTabWidget', 'QGroupBox'):\r\n # --- Qt container creation\r\n if uiClass == 'QSplitter':\r\n split_type = QtCore.Qt.Horizontal\r\n if 'v' in uiInfo:\r\n split_type = QtCore.Qt.Vertical\r\n self.uiList[uiName]=QtWidgets.QSplitter(split_type)\r\n ui_data['obj'] = self.uiList[uiName]\r\n elif uiClass == 'QTabWidget':\r\n self.uiList[uiName]=QtWidgets.QTabWidget()\r\n self.uiList[uiName].setStyleSheet(\"QTabWidget::tab-bar{alignment:center;}QTabBar::tab { min-width: 100px; }\")\r\n if 'v' in uiInfo:\r\n self.uiList[uiName].setTabPosition(QtWidgets.QTabWidget.West)\r\n ui_data['obj'] = self.uiList[uiName]\r\n elif uiClass == 'QGroupBox':\r\n grp_layout_class = 'QVBoxLayout'\r\n if len(uiInfo)>0:\r\n new_grp_layout_class, isValid = self.qui_class(uiName+\"_layout\", uiInfo[0])\r\n if isValid:\r\n grp_layout_class = new_grp_layout_class\r\n grp_title = uiName\r\n if len(uiInfo)== 2:\r\n grp_title = uiInfo[-1]\r\n grp_layout_obj = self.qui_obj({'name':uiName+\"_layout\", 'class': grp_layout_class })['obj']\r\n self.uiList[uiName] = QtWidgets.QGroupBox(grp_title)\r\n self.uiList[uiName].setLayout(grp_layout_obj)\r\n ui_data['obj'] = self.uiList[uiName]\r\n elif uiClass == 'QComboBox':\r\n self.uiList[uiName] = QtWidgets.QComboBox()\r\n if len(uiInfo)>0:\r\n item_list = uiInfo[0].replace('(','').replace(')','').split(',')\r\n self.uiList[uiName].addItems(item_list)\r\n ui_data['obj'] = self.uiList[uiName]\r\n elif uiClass == 'QTreeWidget':\r\n self.uiList[uiName] = QtWidgets.QTreeWidget()\r\n if len(uiInfo)>0:\r\n label_list = uiInfo[0].replace('(','').replace(')','').split(',')\r\n self.uiList[uiName].setHeaderLabels(label_list)\r\n ui_data['obj'] = self.uiList[uiName]\r\n elif uiClass == 'QSpacerItem':\r\n # 0 = fixed; 1 > min; 2 < max; 3 = prefered; 4 = ; 5 = expanding> Aggresive; 6=4 ignored size input\r\n # factors in fighting for space: horizontalStretch\r\n # extra space: setContentsMargins and setSpacing\r\n # ref: http://www.cnblogs.com/alleyonline/p/4903337.html\r\n val = [5,5,5,3]\r\n for i in range(len(uiInfo)):\r\n val[i] = int(uiInfo[i])\r\n self.uiList[uiName] = QtWidgets.QSpacerItem(val[0],val[1], policyList[val[2]], policyList[val[3]] )\r\n ui_data['obj'] = self.uiList[uiName]\r\n else:\r\n if len(uiInfo) == 0:\r\n self.uiList[uiName] = getattr(QtWidgets, uiClass)()\r\n ui_data['obj'] = self.uiList[uiName]\r\n else:\r\n self.uiList[uiName] = getattr(QtWidgets, uiClass)(*uiInfo)\r\n ui_data['obj'] = self.uiList[uiName]\r\n \r\n return ui_data\r\n \r\n def qui_insert(self, ui_data_list, parent_data, insert_opt=''):\r\n # get parentLayout inside parentObject\r\n parentObject = parent_data['obj']\r\n if isinstance(parentObject, QtWidgets.QGroupBox):\r\n parentObject = parentObject.layout()\r\n \r\n if isinstance(parentObject, QtWidgets.QBoxLayout):\r\n # layout\r\n for ui_data in ui_data_list:\r\n ui = ui_data['obj']\r\n if isinstance(ui, QtWidgets.QWidget):\r\n parentObject.addWidget(ui)\r\n elif isinstance(ui, QtWidgets.QSpacerItem):\r\n parentObject.addItem(ui)\r\n elif isinstance(ui, QtWidgets.QLayout):\r\n parentObject.addLayout(ui)\r\n elif isinstance(parentObject, QtWidgets.QGridLayout):\r\n # grid: one row/colume operation only\r\n insertRow = parentObject.rowCount()\r\n insertCol = parentObject.columnCount()\r\n for i in range(len(ui_data_list)):\r\n each_ui = ui_data_list[i]['obj']\r\n x = insertRow if insert_opt==\"h\" else i\r\n y = i if insert_opt==\"h\" else insertCol\r\n if isinstance(each_ui, QtWidgets.QWidget):\r\n parentObject.addWidget(each_ui,x,y)\r\n elif isinstance(each_ui, QtWidgets.QSpacerItem):\r\n parentObject.addItem(each_ui,x,y)\r\n elif isinstance(each_ui, QtWidgets.QLayout):\r\n parentObject.addLayout(each_ui,x,y)\r\n elif isinstance(parentObject, QtWidgets.QFormLayout):\r\n for ui_data in ui_data_list:\r\n ui = ui_data['obj']\r\n name = ui_data['name']\r\n label = '' if 'label' not in ui_data.keys() else ui_data['label']\r\n if isinstance(ui, QtWidgets.QWidget) or isinstance(ui, QtWidgets.QLayout):\r\n if label != '':\r\n self.uiList[name+'_label'] = QtWidgets.QLabel(label)\r\n parentObject.addRow(self.uiList[name+'_label'], ui)\r\n else:\r\n parentObject.addRow(ui)\r\n elif isinstance(parentObject, QtWidgets.QSplitter):\r\n # split\r\n for ui_data in ui_data_list:\r\n each_ui = ui_data['obj']\r\n if isinstance(each_ui, QtWidgets.QWidget):\r\n parentObject.addWidget(each_ui)\r\n else:\r\n tmp_holder = QtWidgets.QWidget()\r\n tmp_holder.setLayout(each_ui)\r\n parentObject.addWidget(tmp_holder)\r\n elif isinstance(parentObject, QtWidgets.QTabWidget):\r\n # tab\r\n tab_names = insert_opt.replace('(','').replace(')','').split(',')\r\n for i in range( len(ui_data_list) ):\r\n each_tab = ui_data_list[i]['obj']\r\n each_name = 'tab_'+str(i)\r\n if i < len(tab_names):\r\n if tab_names[i] != '':\r\n each_name = tab_names[i]\r\n if isinstance(each_tab, QtWidgets.QWidget):\r\n parentObject.addTab(each_tab, each_name)\r\n else:\r\n tmp_holder = QtWidgets.QWidget()\r\n tmp_holder.setLayout(each_tab)\r\n parentObject.addTab(tmp_holder, each_name)\r\n \r\n def qui_policy(self, ui_list, w, h):\r\n # reference value\r\n policyList = ( \r\n QtWidgets.QSizePolicy.Fixed, \r\n QtWidgets.QSizePolicy.Minimum, \r\n QtWidgets.QSizePolicy.Maximum, \r\n QtWidgets.QSizePolicy.Preferred, \r\n QtWidgets.QSizePolicy.Expanding, \r\n QtWidgets.QSizePolicy.MinimumExpanding, \r\n QtWidgets.QSizePolicy.Ignored,\r\n )\r\n # 0 = fixed; 1 > min; 2 < max; 3 = prefered; 4 = ; 5 = expanding> Aggresive; 6=4 ignored size input\r\n if not isinstance(ui_list, (list, tuple)):\r\n ui_list = [ui_list]\r\n for each_ui in ui_list:\r\n if isinstance(each_ui, str):\r\n each_ui = self.uiList[each_ui]\r\n each_ui.setSizePolicy(policyList[w],policyList[h])\r\n \r\n#############################################\r\n# User Class creation\r\n#############################################\r\nversion = '0.1'\r\ndate = '2019.07.05'\r\nlog = '''\r\n#------------------------------\r\nv0.1: (2019.07.05)\r\n * for start, you can replace UserClassUI to YourOwnClassName in template to quickly create your own class\r\n#------------------------------\r\n'''\r\nhelp = '''\r\nimport sys;myPath=r'/python_to_tool/UserClassUI/';myPath in sys.path or sys.path.append(myPath);import UserClassUI;UserClassUI.main()\r\n'''\r\n# --------------------\r\n# user module list\r\n# --------------------\r\n\r\nclass UserClassUI(UniversalToolUI):\r\n def __init__(self, parent=None, mode=0):\r\n UniversalToolUI.__init__(self, parent)\r\n \r\n # class variables\r\n self.version= version\r\n self.date = date\r\n self.log = log\r\n self.help = help\r\n \r\n # mode: example for receive extra user input as parameter\r\n self.mode = 0\r\n if mode in [0,1]:\r\n self.mode = mode # mode validator\r\n # Custom user variable\r\n #------------------------------\r\n # initial data\r\n #------------------------------\r\n self.memoData['data']=[]\r\n self.memoData['settingUI']=[]\r\n self.qui_user_dict = {} # e.g: 'edit': 'LNTextEdit',\r\n \r\n if isinstance(self, QtWidgets.QMainWindow):\r\n self.setupMenu()\r\n self.setupWin()\r\n self.setupUI()\r\n self.Establish_Connections()\r\n self.loadLang()\r\n self.loadData()\r\n \r\n #------------------------------\r\n # overwrite functions\r\n #------------------------------\r\n def setupMenu(self):\r\n self.qui_menubar('file_menu;&File | setting_menu;&Setting | help_menu;&Help')\r\n \r\n info_list = ['export', 'import','user']\r\n info_item_list = ['{0}Config_atn;{1} Config (&{2}),Ctrl+{2}'.format(info,info.title(),info.title()[0]) for info in info_list]+['_']\r\n self.qui_menu('|'.join(info_item_list), 'setting_menu')\r\n # toggle on top\r\n self.qui_menu('toggleTop_atn;Toggle Always-On-Top', 'setting_menu')\r\n # default help menu\r\n super(self.__class__,self).setupMenu()\r\n \r\n def setupWin(self):\r\n super(self.__class__,self).setupWin()\r\n # self.setGeometry(500, 300, 250, 110) # self.resize(250,250)\r\n if hostMode == \"desktop\":\r\n if qtMode > 1:\r\n QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create('fusion'))\r\n else:\r\n QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create('Cleanlooks'))\r\n self.setStyleSheet(\"QLineEdit:disabled{background-color: gray;}\")\r\n \r\n def setupUI(self):\r\n super(self.__class__,self).setupUI('grid')\r\n #------------------------------\r\n # user ui creation part\r\n #------------------------------\r\n self.qui('box_btn;Box | sphere_btn;Sphere | ring_btn;Ring', 'my_layout;grid', 'h')\r\n self.qui('box2_btn;Box2 | sphere2_btn;Sphere2 | ring2_btn;Ring2', 'my_layout', 'h')\r\n \r\n self.qui('cat_btn;Cat | dog_btn;Dog | pig_btn;Pig', 'pet_layout;grid', 'v')\r\n self.qui('cat2_btn;Cat2 | dog2_btn;Dog2 | pig2_btn;Pig2', 'pet_layout', 'v')\r\n \r\n self.qui('name_input@Name:;John | email_input@Email:;test@test.com', 'entry_form')\r\n \r\n self.qui('user2_btn;User2 | info2_btn;Info2', 'my_grp;vbox;Personal Data')\r\n \r\n self.qui('source_txt | process_btn;Process and Update', 'upper_vbox')\r\n self.qui('upper_vbox | result_txt', 'input_split;v')\r\n self.qui('filePath_input | fileLoad_btn;Load | fileExport_btn;Export', 'fileBtn_layout;hbox')\r\n self.qui('test_space;5;5;5;3 | testSpace_btn;Test Space', 'testSpace_layout;hbox')\r\n self.qui('my_layout | my_table | input_split | entry_form | fileBtn_layout | pet_layout | my_grp | testSpace_layout', 'main_layout')\r\n \r\n cur_table = self.uiList['my_table']\r\n cur_table.setRowCount(0)\r\n cur_table.setColumnCount(1)\r\n cur_table.insertColumn(cur_table.columnCount())\r\n cur_item = QtWidgets.QTableWidgetItem('ok') #QtWidgets.QPushButton('Cool') #\r\n cur_table.insertRow(0)\r\n cur_table.setItem(0,1, cur_item) #setCellWidget(0,0,cur_item)\r\n cur_table.setHorizontalHeaderLabels(('a','b'))\r\n '''\r\n self.qui('source_txt | process_btn;Process and Update', 'upper_vbox')\r\n self.qui('upper_vbox | result_txt', 'input_split;v')\r\n self.qui('filePath_input | fileLoad_btn;Load | fileExport_btn;Export', 'fileBtn_layout;hbox')\r\n self.qui('input_split | fileBtn_layout', 'main_layout')\r\n '''\r\n #------------------------------\r\n # user ui creation part END\r\n #------------------------------\r\n self.memoData['settingUI']=[]\r\n keep_margin_layout = ['main_layout']\r\n keep_margin_layout_obj = []\r\n # add tab layouts\r\n for each in self.uiList.values():\r\n if isinstance(each, QtWidgets.QTabWidget):\r\n for i in range(each.count()):\r\n keep_margin_layout_obj.append( each.widget(i).layout() )\r\n for name, each in self.uiList.items():\r\n if isinstance(each, QtWidgets.QLayout) and name not in keep_margin_layout and not name.endswith('_grp_layout') and each not in keep_margin_layout_obj:\r\n each.setContentsMargins(0, 0, 0, 0)\r\n self.quickInfo('Ready')\r\n # self.statusBar().hide()\r\n \r\n def Establish_Connections(self):\r\n super(self.__class__,self).Establish_Connections()\r\n # custom ui response\r\n # shortcut connection\r\n self.hotkey = {}\r\n # self.hotkey['my_key'] = QtWidgets.QShortcut(QtGui.QKeySequence( \"Ctrl+1\" ), self)\r\n # self.hotkey['my_key'].activated.connect(self.my_key_func)\r\n \r\n def loadData(self):\r\n print(\"Load data\")\r\n # load config\r\n \r\n #------------------------------\r\n # user config\r\n #------------------------------\r\n config = {}\r\n config['root_name'] = 'root_default_name'\r\n #------------------------------\r\n # user config END\r\n #------------------------------\r\n \r\n # overload config file if exists next to it\r\n # then, save merged config into self.memoData['config']\r\n prefix, ext = os.path.splitext(self.location)\r\n config_file = prefix+'_config.json'\r\n if os.path.isfile(config_file):\r\n external_config = self.readDataFile(config_file)\r\n print('info: External config file found.')\r\n if isinstance( external_config, dict ):\r\n self.memoData['config'] = self.dict_merge(config, external_config, addKey=1)\r\n print('info: External config merged.')\r\n else:\r\n self.memoData['config'] = config\r\n print('info: External config is not a dict and ignored.')\r\n else:\r\n self.memoData['config'] = config\r\n \r\n # load user setting\r\n user_setting = {}\r\n if self.mode == 0:\r\n # for standalone mode only\r\n user_dirPath = os.path.join(os.path.expanduser('~'), 'Tool_Config', self.__class__.__name__)\r\n user_setting_filePath = os.path.join(user_dirPath, 'setting.json')\r\n if os.path.isfile(user_setting_filePath):\r\n user_setting = self.readDataFile(user_setting_filePath)\r\n if 'sizeInfo' in user_setting:\r\n self.setGeometry(*user_setting['sizeInfo'])\r\n # custome setting loading here\r\n preset = {}\r\n for ui in self.memoData['settingUI']:\r\n if ui in user_setting:\r\n preset[ui]=user_setting[ui]\r\n #self.updateUI(preset)\r\n \r\n def closeEvent(self, event):\r\n if self.mode == 0:\r\n # for standalone mode only\r\n user_dirPath = os.path.join(os.path.expanduser('~'), 'Tool_Config', self.__class__.__name__)\r\n if not os.path.isdir(user_dirPath):\r\n try: \r\n os.makedirs(user_dirPath)\r\n except OSError:\r\n print('Error on creation user data folder')\r\n if not os.path.isdir(user_dirPath):\r\n print('Fail to create user dir.')\r\n return\r\n # save setting\r\n user_setting = {}\r\n geoInfo = self.geometry()\r\n user_setting['sizeInfo'] = [geoInfo.x(), geoInfo.y(), geoInfo.width(), geoInfo.height()]\r\n # custome setting saving here\r\n for ui in self.memoData['settingUI']:\r\n if ui.endswith('_choice'):\r\n user_setting[ui] = unicode(self.uiList[ui].currentText())\r\n elif ui.endswith('_check'):\r\n user_setting[ui] = self.uiList[ui].isChecked()\r\n elif ui.endswith('_input'):\r\n user_setting[ui] = unicode(self.uiList[ui].text())\r\n elif ui.endswith('_tab'):\r\n user_setting[ui] = self.uiList[ui].currentIndex()\r\n user_setting_filePath = os.path.join(user_dirPath, 'setting.json')\r\n self.writeDataFile(user_setting, user_setting_filePath)\r\n \r\n def updateUI(self, preset):\r\n for ui_name in preset:\r\n if ui_name.endswith('_choice'):\r\n if preset[ui_name] != '':\r\n the_idx = self.uiList[ui_name].findText(preset[ui_name])\r\n if the_idx != -1:\r\n self.uiList[ui_name].setCurrentIndex(the_idx)\r\n elif ui_name.endswith('_check'):\r\n self.uiList[ui_name].setChecked(preset[ui_name])\r\n elif ui_name.endswith('_input'):\r\n if preset[ui_name] != '':\r\n self.uiList[ui_name].setText(preset[ui_name])\r\n elif ui_name.endswith('_tab'):\r\n self.uiList[ui_name].setCurrentIndex(preset[ui_name])\r\n \r\n #=======================================\r\n # user functions\r\n #=======================================\r\n\r\n def process_action(self): # (optional)\r\n config = self.memoData['config']\r\n print(\"Process ....\")\r\n source_txt = unicode(self.uiList['source_txt'].toPlainText())\r\n # 2: update memory\r\n self.memoData['data'] = [row.strip() for row in source_txt.split('\\n')]\r\n print(\"Update Result\")\r\n txt=config['root_name']+'\\n'+'\\n'.join([('>>: '+row) for row in self.memoData['data']])\r\n self.uiList['result_txt'].setText(txt)\r\n \r\n \r\n #=======================================\r\n # user functions END\r\n #=======================================\r\n\r\n # - example file io function\r\n def exportConfig_action(self):\r\n file= self.quickFileAsk('export', {'json':'JSON data file', 'xdat':'Pickle binary file'})\r\n if file == \"\":\r\n return\r\n # export process\r\n ui_data = self.memoData['config']\r\n # file process\r\n if file.endswith('.xdat'):\r\n self.writeDataFile(ui_data, file, binary=1)\r\n else:\r\n self.writeDataFile(ui_data, file)\r\n self.quickInfo(\"File: '\"+file+\"' creation finished.\")\r\n def importConfig_action(self):\r\n file= self.quickFileAsk('import',{'json':'JSON data file', 'xdat':'Pickle binary file'})\r\n if file == \"\":\r\n return\r\n # import process\r\n ui_data = \"\"\r\n if file.endswith('.xdat'):\r\n ui_data = self.readDataFile(file, binary=1)\r\n else:\r\n ui_data = self.readDataFile(file)\r\n self.memoData['config'] = ui_data\r\n self.quickInfo(\"File: '\"+file+\"' loading finished.\")\r\n def userConfig_action(self):\r\n user_dirPath = os.path.join(os.path.expanduser('~'), 'Tool_Config', self.__class__.__name__)\r\n self.openFolder(user_dirPath)\r\n \r\n#=======================================\r\n# window instance creation\r\n#=======================================\r\n\r\nimport ctypes # for windows instance detection\r\nsingle_UserClassUI = None\r\napp_UserClassUI = None\r\ndef main(mode=0):\r\n # get parent window in Maya\r\n parentWin = None\r\n if hostMode == \"maya\":\r\n if qtMode in (0,2): # pyside\r\n parentWin = shiboken.wrapInstance(int(mui.MQtUtil.mainWindow()), QtWidgets.QWidget)\r\n elif qtMode in (1,3): # PyQt\r\n parentWin = sip.wrapinstance(int(mui.MQtUtil.mainWindow()), QtCore.QObject)\r\n # create app object for certain host\r\n global app_UserClassUI\r\n if hostMode in ('desktop', 'blender', 'unreal', 'unity', 'npp', 'fusion'):\r\n # single instance app mode on windows\r\n if osMode == 'win':\r\n # check if already open for single desktop instance\r\n from ctypes import wintypes\r\n order_list = []\r\n result_list = []\r\n top = ctypes.windll.user32.GetTopWindow(None)\r\n if top: \r\n length = ctypes.windll.user32.GetWindowTextLengthW(top)\r\n buff = ctypes.create_unicode_buffer(length + 1)\r\n ctypes.windll.user32.GetWindowTextW(top, buff, length + 1)\r\n class_name = ctypes.create_string_buffer(200)\r\n ctypes.windll.user32.GetClassNameA(top, ctypes.byref(class_name), 200)\r\n result_list.append( [buff.value, class_name.value, top ])\r\n order_list.append(top)\r\n while True:\r\n next = ctypes.windll.user32.GetWindow(order_list[-1], 2) # win32con.GW_HWNDNEXT\r\n if not next:\r\n break\r\n length = ctypes.windll.user32.GetWindowTextLengthW(next)\r\n buff = ctypes.create_unicode_buffer(length + 1)\r\n ctypes.windll.user32.GetWindowTextW(next, buff, length + 1)\r\n class_name = ctypes.create_string_buffer(200)\r\n ctypes.windll.user32.GetClassNameA(next, ctypes.byref(class_name), 200)\r\n result_list.append( [buff.value, class_name.value, next] )\r\n order_list.append(next)\r\n # result_list: [(title, class, hwnd int)]\r\n winTitle = 'UserClassUI' # os.path.basename(os.path.dirname(__file__))\r\n is_opened = 0\r\n for each in result_list:\r\n if re.match(winTitle+' - v[0-9.]* - host: desktop',each[0]) and each[1] == 'QWidget':\r\n is_opened += 1\r\n if is_opened == 1:\r\n ctypes.windll.user32.SetForegroundWindow(each[2])\r\n sys.exit(0) # 0: success, 1-127: bad error\r\n return\r\n if hostMode in ('npp','fusion'):\r\n app_UserClassUI = QtWidgets.QApplication([])\r\n else:\r\n app_UserClassUI = QtWidgets.QApplication(sys.argv)\r\n \r\n #--------------------------\r\n # ui instance\r\n #--------------------------\r\n # Keep only one copy of windows ui in Maya\r\n global single_UserClassUI\r\n if single_UserClassUI is None:\r\n if hostMode == 'maya':\r\n single_UserClassUI = UserClassUI(parentWin, mode)\r\n elif hostMode == 'nuke':\r\n single_UserClassUI = UserClassUI(QtWidgets.QApplication.activeWindow(), mode)\r\n elif hostMode == 'houdini':\r\n hou.session.mainWindow = hou.qt.mainWindow()\r\n single_UserClassUI = UserClassUI(hou.session.mainWindow, mode)\r\n elif hostMode == 'unreal':\r\n single_UserClassUI = UserClassUI()\r\n unreal.parent_external_window_to_slate(single_UserClassUI.winId())\r\n else:\r\n single_UserClassUI = UserClassUI()\r\n single_UserClassUI.show()\r\n ui = single_UserClassUI\r\n if hostMode != 'desktop':\r\n ui.activateWindow()\r\n \r\n # loop app object for certain host\r\n if hostMode in ('desktop'):\r\n sys.exit(app_UserClassUI.exec_())\r\n elif hostMode in ('npp','fusion'):\r\n app_UserClassUI.exec_()\r\n return ui\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"universal_tool_template_2020.py","file_name":"universal_tool_template_2020.py","file_ext":"py","file_size_in_byte":59032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"179877972","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'inz.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^accounts/', include('accounts.urls', namespace='accounts', app_name='accounts')),\n url(r'^clients/', include('clients.urls', namespace='clients', app_name='clients')),\n url(r'^products/', include('products.urls', namespace='products', app_name='products')),\n url(r'^transactions/', include('transactions.urls', namespace='transactions', app_name='transactions')),\n url(r'^$', TemplateView.as_view(template_name=\"base.html\"), name='home'),\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"inz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"222970787","text":"# Equalize the Array\n'''\n 숫자로 이루어진 배열이 있는데 최소한의 제거로 같은 숫자만 남게 만들기\n ex)\n 1 2 2 3\n 1, 3 제거 -> 2\n\n 1 <= n <= 100\n 1 <= arr[i] <= 100\n'''\n\ndef equalizeArray(arr):\n s = set(arr)\n\n maxCnt = 0\n \n ans = 0\n\n for e in s:\n if arr.count(e) > maxCnt:\n maxCnt = arr.count(e)\n maxCha = e\n\n for e in s:\n if e == maxCha:\n continue\n while arr.count(e) != 0:\n arr.remove(e)\n ans += 1\n\n return ans\n\nif __name__ == '__main__':\n n = int(input())\n arr = list(map(int, input().rstrip().split()))\n\n result = equalizeArray(arr)\n print(result)","sub_path":"Equalize the Array/Equalize_the_Array.py","file_name":"Equalize_the_Array.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"457475676","text":"import re\n\nfrom ..core import *\nfrom ..utils import *\nfrom ..vparsers import *\n\n\nclass FlatNumberParser(ValueParser):\n\n @attributeerror_wrapper(return_value=None)\n def parse(self, soup):\n return soup.find(\"span\").text\n\n\nclass NumberExtractor(ValueParser):\n\n @attributeerror_wrapper(return_value=None)\n def parse(self, text):\n return re.search(\"\\d+\", text).group(0)\n\n\nclass InvestmentParser(ValueParser):\n\n @attributeerror_wrapper(return_value=None)\n def parse(self, soup):\n soup.find(\"span\").extract()\n return soup.text.strip()\n\n\nclass PCGParser(ConditionalWebpageParser):\n middlewares = [ JSONMiddleware() ]\n bs4_parser = \"lxml\"\n\n url = \"http://pcg.pl/wp-admin/admin-ajax.php\"\n method = \"POST\"\n headers = {\n \"Host\": \"pcg.pl\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0\",\n \"Accept\": \"*/*\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Referer\": \"http://pcg.pl/wyszukiwarka/\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Connection\": \"keep-alive\",\n \"Pragma\": \"no-cache\",\n \"Cache-Control\": \"no-cache\"\n }\n\n schema = [\n DataUnit(pos=0, label=\"Plan\", parser=StringParser(), id=\"plan\"),\n DataUnit(pos=1, label=\"Numer\", parser=FlatNumberParser(), id=\"number\"),\n DataUnit(pos=1, label=\"Inwestycja\", parser=InvestmentParser(), id=\"_investment\"),\n DataUnit(pos=2, label=\"Piętro\", parser=IntParser(NumberExtractor(DOMTextExtractor())), id=\"floor\"),\n DataUnit(pos=3, label=\"Pokoje\", parser=IntParser(NumberExtractor(DOMTextExtractor())), id=\"rooms\"),\n DataUnit(pos=4, label=\"Pow.\", parser=AreaParser(DOMTextExtractor()), id=\"area\"),\n DataUnit(pos=5, label=\"Pow. balkonu\", parser=AreaParser(DOMTextExtractor()), id=\"balcony\"),\n DataUnit(pos=6, label=\"Pow. tarasu\", parser=AreaParser(DOMTextExtractor()), id=\"terrace\"),\n DataUnit(pos=-1, label=\"Status\", parser=StatusParser(DOMTextExtractor()), id=\"status\")\n ]\n\n @tryexcept_wrapper((KeyError, IndexError), return_value=True)\n def is_last_page(self, data):\n return \"sf-nav-current\" in data[\"nav\"][-1]\n\n def get_request_data(self):\n data = super().get_request_data()\n self._page = getattr(self, \"_page\", 0) + 1\n data[\"data[page]\"] = self._page\n data[\"data[search-id]\"] = \"inwestycje\"\n data[\"action\"] = \"sf-search\"\n if hasattr(self, \"investment_id\"):\n data[\"data[1]\"] = self.investment_id\n return data\n\n @keyerror_wrapper(return_value=[])\n def find_records(self, data):\n records = data[\"result\"]\n return [ self.extract_data(record) for record in records ]\n\n @typeerror_wrapper(return_value=None)\n def extract_data(self, content):\n return BeautifulSoup(content, self.bs4_parser)\\\n .find(\"div\", {\"class\": \"result-table-item\"})\n\n def split_record(self, soup):\n flat_attrs = soup.find(\"div\", {\"class\": \"result-box\"}).find_all(\"div\")\n return [soup.find(\"a\").get(\"href\", None)] + flat_attrs\n\n def modify_record(self, record, soup):\n record[\"fid\"] = record[\"number\"]\n if record[\"status\"] is None:\n record[\"status\"] = StatusParser.AVAILABLE\n return record\n\n def filter_records(self):\n records = [\n record for record in self.records\n if record[\"floor\"] is not None\n ]","sub_path":"parsers/pcg/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"395660258","text":"import pandas as pd\n\nclass PortfolioManager():\n def __init__(self, initialFunds, marginRequirement=3100, fee=2.36, spread=0.01, maintainceFunds = 2000, multiplier=1000):\n self.funds = initialFunds\n self.index = 0\n self.transactionHistory = pd.DataFrame()\n self.activeTransaction = pd.DataFrame()\n self.MARGINREQUIREMENT = marginRequirement\n self.MAINTAINCEFUNDS = maintainceFunds\n self.MUTIPLIER = multiplier\n self.FEE = fee\n self.SPREAD = spread\n\n self.directional_rewards = 0\n\n def get_position(self):\n pos = 0\n if len(self.activeTransaction) != 0:\n pos = self.activeTransaction[\"Position\"][0]\n return pos\n\n def proceedAction(self, action, currentState):\n ########################################################################################################\n date = currentState[\"Date\"]\n actPrice = currentState[\"Open\"]\n resultPrice = currentState[\"Close\"]\n\n realizedFunds = 0\n anticipatedRewards = 0\n ########################################################################################################\n\n if action != 0:\n\n actionFee = self.FEE * abs(action)\n\n self.directional_rewards = (resultPrice - actPrice) * action\n\n ########################################################################################################\n currentTransaction = pd.DataFrame({'PurchaseDate': date, 'Position': action, 'Price': actPrice, 'Fee': actionFee},\n index=[self.index], columns=['PurchaseDate', 'Position', 'Price', 'Fee'])\n self.transactionHistory = pd.concat([self.transactionHistory, currentTransaction])\n self.index += 1\n ########################################################################################################\n\n if len(self.activeTransaction) == 0:\n\n self.activeTransaction = pd.DataFrame(\n {'RecentDate': date, 'Position': action, 'Price': actPrice, 'Fee': actionFee},\n index=[0], columns=['RecentDate', 'Position', 'Price', 'Fee'])\n\n anticipatedRewards = (resultPrice - actPrice) * action * self.MUTIPLIER - self._getSpreadCost(action) - actionFee * 2\n else:\n historicalAveragePurchasedPrice = self.activeTransaction[\"Price\"][0]\n historicalPosition = self.activeTransaction[\"Position\"][0]\n historicalFee = self.activeTransaction[\"Fee\"][0]\n\n self.activeTransaction = self.activeTransaction[0: 0]\n\n ########################################################################################################\n\n if (historicalPosition / abs(historicalPosition)) * (action / abs(action)) == 1:\n newPosition = historicalPosition + action\n newFee = historicalFee + actionFee\n\n newAveragePurchasedPrice = (historicalAveragePurchasedPrice * historicalPosition + actPrice * action) / newPosition\n activeCurrentTransaction = pd.DataFrame({'RecentDate': date,\n 'Position': newPosition,\n 'Price': newAveragePurchasedPrice,\n 'Fee': newFee},\n index=[0], columns=['RecentDate', 'Position', 'Price', 'Fee'])\n self.activeTransaction = pd.concat([self.activeTransaction, activeCurrentTransaction])\n\n anticipatedRewards = (resultPrice - newAveragePurchasedPrice) * newPosition * self.MUTIPLIER - self._getSpreadCost(newPosition) - newFee * 2\n else:\n if abs(action) > abs(historicalPosition):\n newPosition = action + historicalPosition\n newFee = actionFee - historicalFee\n activeCurrentTransaction = pd.DataFrame({'RecentDate': date,\n 'Position': newPosition,\n 'Price': actPrice,\n 'Fee': newFee},\n index=[0], columns=['RecentDate', 'Position', 'Price', 'Fee'])\n self.activeTransaction = pd.concat([self.activeTransaction, activeCurrentTransaction])\n\n anticipatedRewards = (resultPrice - actPrice) * newPosition * self.MUTIPLIER - self._getSpreadCost(newPosition) - newFee * 2\n realizedFunds = (actPrice - historicalAveragePurchasedPrice) * historicalPosition * self.MUTIPLIER - self._getSpreadCost(historicalPosition) - historicalFee * 2\n self.funds += realizedFunds\n\n elif abs(action) == abs(historicalPosition):\n realizedFunds = (actPrice - historicalAveragePurchasedPrice) * historicalPosition * self.MUTIPLIER - self._getSpreadCost(historicalPosition) - historicalFee * 2\n self.funds += realizedFunds\n\n else:\n newPosition = action + historicalPosition\n newFee = historicalFee - actionFee\n activeCurrentTransaction = pd.DataFrame({'RecentDate': date,\n 'Position': newPosition,\n 'Price': historicalAveragePurchasedPrice,\n 'Fee': newFee},\n index=[0], columns=['RecentDate', 'Position', 'Price', 'Fee'])\n self.activeTransaction = pd.concat([self.activeTransaction, activeCurrentTransaction])\n\n anticipatedRewards = (resultPrice - historicalAveragePurchasedPrice) * newPosition * self.MUTIPLIER - self._getSpreadCost(newPosition) - newFee * 2\n realizedFunds = -(actPrice - historicalAveragePurchasedPrice) * action * self.MUTIPLIER - self._getSpreadCost(action) - actionFee * 2\n self.funds += realizedFunds\n\n else:\n\n self.directional_rewards = 0\n\n if len(self.activeTransaction) == 0:\n anticipatedRewards = 0\n realizedFunds = 0\n else:\n historicalAveragePurchasedPrice = self.activeTransaction[\"Price\"][0]\n historicalPosition = self.activeTransaction[\"Position\"][0]\n historicalFee = self.activeTransaction[\"Fee\"][0]\n\n anticipatedRewards = (resultPrice - historicalAveragePurchasedPrice) * historicalPosition * self.MUTIPLIER - self._getSpreadCost(historicalPosition) - historicalFee * 2\n\n return [self.funds, realizedFunds, anticipatedRewards], self.get_position()\n\n\n def nextAvailableActions(self, nextState):\n\n nextState = nextState.iloc[-1]\n actPrice = nextState[\"Open\"]\n\n if len(self.activeTransaction) == 0:\n availableStep = int(self.funds / self.MARGINREQUIREMENT)\n stepRange = range(-availableStep, availableStep + 1)\n\n else:\n\n historicalAveragePurchasedPrice = self.activeTransaction[\"Price\"][0]\n historicalPosition = self.activeTransaction[\"Position\"][0]\n historicalFee = self.activeTransaction[\"Fee\"][0]\n\n longShortPrefix = historicalPosition / abs(historicalPosition)\n\n unrealizedFunds = (actPrice - historicalAveragePurchasedPrice) * historicalPosition * self.MUTIPLIER - historicalFee\n\n positionSide = self.funds - abs(historicalPosition) * self.MARGINREQUIREMENT + unrealizedFunds\n nonPositionSide = self.funds + unrealizedFunds\n\n pSideAction = int(longShortPrefix * positionSide / self.MARGINREQUIREMENT)\n nPSideAction = -int(longShortPrefix * nonPositionSide / self.MARGINREQUIREMENT)\n\n left = min(pSideAction, nPSideAction)\n right = max(pSideAction, nPSideAction)\n\n stepRange = range(left, right + 1)\n\n return stepRange\n\n\n def _getSpreadCost(self, position):\n return self.SPREAD * self.MUTIPLIER * abs(position)\n","sub_path":"PortfolioManager.py","file_name":"PortfolioManager.py","file_ext":"py","file_size_in_byte":8541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"53850246","text":"class fraction:\n def __init__ (self, num, den):\n self.top = num\n self.bottom = den\n\n def __str__(self):\n return str(self.top)+\"/\"+str(self.bottom)\n\n def gcd(self,a,b):\n while a % b != 0:\n old_a = a\n old_b = b\n a = old_b\n b = old_a % old_b\n return b\n\n def __add__(self, other_fraction):\n global new_fraction\n global reduced_fraction\n global common_gcd\n new_num = self.top*other_fraction.bottom + self.bottom*other_fraction.top\n new_den = self.bottom*other_fraction.bottom\n new_fraction = fraction(new_num,new_den)\n common_gcd = new_fraction.gcd(new_num,new_den)\n reduced_fraction = fraction(new_num // common_gcd, new_den // common_gcd)\n return reduced_fraction\n\nnumerator1 = input(\"First Fraction: Please enter the numerator - \")\ndenominator1 = input(\"First Fraction: Please enter the denominator - \")\nnumerator2 = input(\"Second Fraction: Please enter the numerator - \")\ndenominator2 = input(\"Second Fraction: Please enter the denominator - \")\n\nF1 = fraction(numerator1,denominator1)\nprint (\"The First fraction is: \"),F1\n\nF2 = fraction(numerator2,denominator2)\nprint (\"The Second fraction is: \"),F2\n\nF3 = F1 + F2\nprint (\"The Greatest Common Divisor (GCD) of both the fractions is: \"),common_gcd\nprint (\"The Result of addition of both the fraction before GCD reduction is: \"),new_fraction\nprint (\"The Result of addition of both the fraction after GCD reduction is: \"),reduced_fraction","sub_path":"Fraction Reduction using GCD.py","file_name":"Fraction Reduction using GCD.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"504335720","text":"\n# coding: utf-8\n\n# # Testing MiniscoPy with true data\n# \n# MiniscopPy is a Python 3.0 implementation of the CNMF-E algorithm (Zhou et al., 2016). It has been optimized for the MiniScope (Cai et al., 2016), a portable microscope for calcium imaging in freely moving animals.\n# \n\n# ## BASIC IMPORTS\n\n## Designed to run as self contained script from command line on quest\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\nimport numpy as np\nfrom time import time\nfrom matplotlib.pyplot import *\nimport scipy\nimport glob\nimport yaml\nimport sys,os\nimport h5py as hd\nfrom time import time\nimport av\n#specific to miniscopy\nfrom motion_correction_jjm import *\nfrom miniscopy import setup_cluster, CNMFE, generate_data, get_default_parameters\nimport tables\n#import dview\n\n\n# In[2]:\n\n# ## LISTING THE MOVIES & LOADING THE PARAMETERS\n# \n# The miniscope recording system usually outputs a set of avi files in one folder. First, give the path of this folder and list all the avi files within it. Then, save a file that list all the parameters in a yaml format (see parameters.yaml in the miniscoPy/example_movies/). It's better to have one parameters.yaml per recording folder (the same for the entire session)\n\n# ### DOWNLOADING AN EXAMPLE FILE IF NOT ALREADY PRESENT\n\n# In[14]:\n\n\ndef load_movies(folder_name):\n\n\tfiles = glob.glob(folder_name+'/msCam*.avi')\n\tif len(files) == 0:\n\t\timport urllib.request\n\t\turl = \"https://www.dropbox.com/s/0x3twp8bidl9svu/msCam1.avi?dl=1\"\n\t\twith urllib.request.urlopen(url) as response, open(folder_name+\"/msCam1.avi\", 'wb') as out_file:\n\t\t\tdata = response.read()\n\t\t\tout_file.write(data)\n\t\tfiles = glob.glob(folder_name+'/*.avi')\n\t\tif len(files) == 0: print(\"No avi files found, please provide one at least\")\n\n\treturn(files) \t\n\n## for loading parameter file \n\nclass PrettySafeLoader(yaml.SafeLoader):\n\tdef construct_python_tuple(self, node):\n\t\treturn tuple(self.construct_sequence(node))\n\n\tdef construct_python_list(self, node):\n\t\treturn tuple(self.construct_sequence(node))\n\nPrettySafeLoader.add_constructor(\n\tu'tag:yaml.org,2002:python/tuple',\n\tPrettySafeLoader.construct_python_tuple)\n\nPrettySafeLoader.add_constructor(\n\tu'tag:yaml.org,2002:python/list',\n\tPrettySafeLoader.construct_python_list)\n\n\ndef run_normcorr(folder_name,files):\n\t\n\tparameters = yaml.load(open(folder_name+'/parameters.yaml', 'r'), Loader=PrettySafeLoader)\n\n# ## STARTING THE CLUSTER \n# For now, pool mapping is used only for the motion correction algorithm. Instantiating \"procs = None\" works as well, it all depends on your local configuration.\n\n\tc, procs, n_processes = setup_cluster(backend='local', n_processes=8, single_thread=False)\n\n# ## MOTION CORRECTION\n # This function implements Normcorre (see...). All the outputs and associated information are stored in one HDF5 per session that will eventually be used for detection of calcium transients. \n\n\tfiles_to_load = [str(file) for file in files[:]]\n\n\tprint('processing files')\n\tprint(files_to_load)\n\n\tdata, video_info = normcorre(files_to_load, procs, parameters['motion_correction'])\n\n\tdata.close()\n\n\tprint('finished motion correction')\n\tvideo_info # some information about the dataset\n\n\treturn()\n\ndef run_CNMFE(path_to_hdf5_file, folder_name):\n# ## WORKING WITH HDF5\n# \n# The HDF5 file (called data in this example) contains a Numpy array called 'movie' of size (number of frames, number of pixels). The cool thing about HDF5 format is that you can attach attributes (i.e. extra information) to every dataset or group it contains. Here, we attached the attributes of the frame dimension and the recording duration to the dataset 'movie'.\n# load hdf5 file with motion corrected data\n\tparameters = yaml.load(open(folder_name+'/parameters.yaml', 'r'), Loader=PrettySafeLoader)\n\n\tc, procs, n_processes = setup_cluster(backend='local', n_processes=8, single_thread=False)\n\n\tdata = hd.File(path_to_hdf5_file, 'r+')\n\n\t#print(data['movie'].attrs['dims']) # width and height of the frame\n\t#print(data['movie'].attrs['duration']) # number of frames\n\t#print(data.attrs['folder'])\n\t#print(data.attrs['filename'])\n\n\n# In the following example, the datasets contains additional attributes such as the animal's identity and frame rate. Both are located at the root of the HDF5 file.\n# Check the first frame of the movie to see if it's in correct order.\n\n\t#dims = data['movie'].attrs['dims']\n\t#frame_0 = data['movie'][0].reshape(dims)\n\t#figure()\n\t#imshow(frame_0)\n\t#show()\n\n\n# ## RUNNING CNMF-E \n\n\tparameters['cnmfe']['init_params']['thresh_init'] = 1.2\n\tparameters['cnmfe']['init_params']['min_corr'] = 0.8\n\tparameters['cnmfe']['init_params']['min_pnr'] = 1.5\n\n\tprint('starting cnmfe')\n\tcnm = CNMFE(data, parameters['cnmfe'])\n\tcnm.fit(procs)\n\n\n# # VISUALIZATION\n##Save A and C output before visualization\n\tdims = cnm.dims\n\tC = cnm.C.value.copy()\n\tA = cnm.A.value.copy()\n\n\t# A is normalized to 1 for display\n\tA -= np.vstack(A.min(1))\n\tA /= np.vstack(A.max(1))\n\tAtotal = A.sum(0).reshape(dims)\n\tout_path = folder_name +'/'\n\tpd.DataFrame(C).to_hdf(out_path+'C', key='df')\n\tpd.DataFrame(A).to_hdf(out_path+'A', key='df')\n\n\n\tprocs.terminate()\n\n\tcn, pnr = cnm.get_correlation_info()\n\n\n# Here all the spatial footprints (the A matrix) are normalized between 0 and 1 and the sum of all responses is then displayed.\n\n\tdims = cnm.dims\n\tC = cnm.C.value.copy()\n\tA = cnm.A.value.copy()\n\n\t# A is normalized to 1 for display\n\tA -= np.vstack(A.min(1))\n\tA /= np.vstack(A.max(1))\n\tAtotal = A.sum(0).reshape(dims)\n\n#plotting functions\n\n\tpd.DataFrame(C).to_hdf(out_path+'C', key='df')\n\tpd.DataFrame(A).to_hdf(out_path+'A', key='df')\n\tdata.close()\n\n\treturn()\n\n\n\n","sub_path":"main_cnmfe_e_jjm_module.py","file_name":"main_cnmfe_e_jjm_module.py","file_ext":"py","file_size_in_byte":5585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"475417192","text":"#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\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#\n\nfrom onnx_graphsurgeon.util import misc\n\n\ndef test_combine_dicts_second_overwrites_first():\n x = {\"a\": 1}\n y = {\"a\": 2}\n z = misc.combine_dicts(x, y)\n assert z[\"a\"] == 2\n","sub_path":"tools/onnx-graphsurgeon/tests/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"130859859","text":"import logging\nimport abc\nfrom functools import partial\n\nfrom .dispatcher import Dispatcher\nfrom .function import (\n promised_type_of as promised_type_of1,\n)\nfrom .type import (\n TypeMeta,\n promised_type_of as promised_type_of2,\n ComparableType,\n Union,\n PromisedList,\n PromisedTuple,\n PromisedDict,\n PromisedIterable,\n PromisedSequence,\n ptype,\n is_type,\n)\nfrom .util import multihash\n\n__all__ = [\n \"parametric\",\n \"type_parameter\",\n \"kind\",\n \"Kind\",\n \"List\",\n \"Tuple\",\n \"Dict\",\n \"Iterable\",\n \"Sequence\",\n \"type_of\",\n \"Val\",\n]\n\nlog = logging.getLogger(__name__)\n\n_dispatch = Dispatcher()\n\n\nclass ParametricTypeMeta(TypeMeta):\n \"\"\"Parametric types can be instantiated with indexing.\n\n A concrete parametric type can be instantiated by calling `Type[Par1, Par2]`.\n If `Type(Arg1, Arg2, **kw_args)` is called, this returns\n `Type[type(Arg1), type(Arg2)](Arg1, Arg2, **kw_args)`.\n \"\"\"\n\n def __getitem__(cls, p):\n if not cls.concrete:\n # `p` can be a tuple, in which case it must be splatted.\n return cls.__new__(cls, *(p if isinstance(p, tuple) else (p,)))\n else:\n raise TypeError(\"Cannot specify type parameters. This type is concrete.\")\n\n def __call__(cls, *args, **kw_args):\n # `Type(arg1, arg2, **kw_args)` will first construct the\n # parametric subtype `T = Type[type(arg1), type(arg2)]`\n # and then call the equivalent of `T(arg1, arg2, **kw_args)`.\n\n if hasattr(cls, \"parametric\") and cls.parametric:\n if not cls.concrete:\n type_parameter = cls.__infer_type_parameter__(*args, **kw_args)\n cls = cls[type_parameter]\n\n # Calls `__new__` and `__init__`.\n return TypeMeta.__call__(cls, *args, **kw_args)\n\n def __infer_type_parameter__(cls, *args, **kw_args):\n \"\"\"Function called when the constructor of this parametric type is called\n before the parameters have been specified.\n\n The default behaviour is to take as parameters the type of every argument,\n but this behaviour can be overridden by redefining this function on the\n metaclass.\n\n Args:\n *args: Positional arguments passed to the `__init__` method.\n *kw_args: Keyword arguments passed to the `__init__` method.\n\n Returns:\n type or tuple[type]: A type or tuple of types.\n \"\"\"\n # TODO: Use `type_of` instead of `type`.\n type_parameter = tuple(type(arg) for arg in args)\n if len(type_parameter) == 1:\n type_parameter = type_parameter[0]\n return type_parameter\n\n @property\n def parametric(cls):\n \"\"\"bool: Check whether the type is a parametric type.\"\"\"\n return hasattr(cls, \"_parametric\") and cls._parametric\n\n @property\n def concrete(cls):\n \"\"\"bool: Check whether the parametric type is instantiated or not.\"\"\"\n if cls.parametric:\n return hasattr(cls, \"_concrete\") and cls._concrete\n else:\n raise RuntimeError(\n \"Cannot check whether a non-parametric type is instantiated or not.\"\n )\n\n @property\n def type_parameter(cls):\n \"\"\"object: Get the type parameter. Parametric type must be instantiated.\"\"\"\n if cls.concrete:\n return cls._type_parameter\n else:\n raise RuntimeError(\n \"Cannot get the type parameter of non-instantiated parametric type.\"\n )\n\n @property\n def runtime_type_of(cls):\n \"\"\"bool: Check whether the type requires :func:`.parametric.type_of` at\n runtime\"\"\"\n return hasattr(cls, \"_runtime_type_of\") and cls._runtime_type_of\n\n\ndef is_concrete(t):\n \"\"\"Check if a type `t` is a concrete instance of a parametric type.\n\n Args:\n t (type): Type to check.\n\n Returns:\n bool: `True` if `t` is a concrete instance of a parametric type and `False`\n otherwise.\n \"\"\"\n return hasattr(t, \"parametric\") and t.parametric and t.concrete\n\n\nclass CovariantMeta(ParametricTypeMeta):\n \"\"\"A metaclass that implements *covariance* of parametric types.\"\"\"\n\n def __subclasscheck__(cls, subclass):\n if is_concrete(cls) and is_concrete(subclass):\n # Check that they are instances of the same parametric type.\n if all(issubclass(b, cls.__bases__) for b in subclass.__bases__):\n par_subclass = subclass.type_parameter\n par_cls = cls.type_parameter\n\n if not isinstance(par_subclass, tuple):\n par_subclass = (par_subclass,)\n if not isinstance(par_cls, tuple):\n par_cls = (par_cls,)\n\n return cls._is_sub_type_parameter(par_cls, subclass, par_subclass)\n\n # Default behaviour to `type`s subclass check.\n return type.__subclasscheck__(cls, subclass)\n\n def _is_sub_type_parameter(cls, par_cls, subclass, par_subclass):\n # Handle the case that the parameters are tuples of types.\n return len(par_subclass) == len(par_cls) and all(\n (\n # Type parameter could be a type.\n ptype(pi_subclass) <= ptype(pi_self)\n if (is_type(pi_subclass) and is_type(pi_self))\n # Type parameter could also be an object.\n else pi_subclass == pi_self\n )\n for pi_subclass, pi_self in zip(par_subclass, par_cls)\n )\n\n\ndef parametric(Class=None, runtime_type_of=False, metaclass=CovariantMeta):\n \"\"\"A decorator for parametric classes.\n\n When the constructor of this parametric type is called before the type parameter\n has been specified, the type parameters are inferred from the arguments of the\n constructor by calling the following function.\n\n The default implementation is shown here, but it is possible to override it.::\n\n @classmethod\n def __infer_type_parameter__(cls, *args, **kw_args) -> Tuple:\n return tuple(type(arg) for arg in args)\n\n Args:\n runtime_type_of (bool, optional): Require the use of :func:`.parametric.type_of`\n at runtime to determine the types of arguments at runtime. Defaults to\n `False`\n metaclass (type, optional): Metaclass of the parametric class. Defaults to\n :class:`.parametric.CovariantMeta`.\n \"\"\"\n\n # Allow the keyword arguments to be passed in without using `functools.partial`\n # explicitly.\n if Class is None:\n return partial(parametric, runtime_type_of=runtime_type_of, metaclass=metaclass)\n\n subclasses = {}\n\n if not issubclass(Class, object): # pragma: no cover\n raise RuntimeError(\n f\"To let {Class} be a parametric class, it must be a new-style class.\"\n )\n\n def __new__(cls, *ps):\n # Only create new subclass if it doesn't exist already.\n if ps not in subclasses:\n\n def __new__(cls, *args, **kw_args):\n return Class.__new__(cls)\n\n # Create subclass.\n name = Class.__name__ + \"[\" + \", \".join(str(p) for p in ps) + \"]\"\n SubClass = type.__new__(\n metaclass,\n name,\n (ParametricClass,),\n {\"__new__\": __new__},\n )\n SubClass._parametric = True\n SubClass._concrete = True\n SubClass._runtime_type_of = runtime_type_of\n SubClass._type_parameter = ps[0] if len(ps) == 1 else ps\n SubClass.__module__ = Class.__module__\n\n # Attempt to correct docstring.\n try:\n SubClass.__doc__ = Class.__doc__\n except AttributeError: # pragma: no cover\n pass\n\n subclasses[ps] = SubClass\n return subclasses[ps]\n\n def __init_subclass__(cls, **kw_args):\n cls._parametric = False\n cls._runtime_type_of = False\n if cls.__new__ is __new__:\n\n def resetted_new(cls, *args, **kw_args):\n return Class.__new__(cls)\n\n cls.__new__ = resetted_new\n Class.__init_subclass__(**kw_args)\n\n # Create parametric class.\n ParametricClass = metaclass(\n Class.__name__,\n (Class,),\n {\"__new__\": __new__, \"__init_subclass__\": __init_subclass__},\n )\n ParametricClass._parametric = True\n ParametricClass._concrete = False\n ParametricClass._runtime_type_of = runtime_type_of\n ParametricClass.__module__ = Class.__module__\n\n # Attempt to correct docstring.\n try:\n ParametricClass.__doc__ = Class.__doc__\n except AttributeError: # pragma: no cover\n pass\n\n return ParametricClass\n\n\n@_dispatch\ndef type_parameter(x):\n \"\"\"Get the type parameter of an instance of a parametric type.\n\n Args:\n x (object): Instance of a parametric type.\n\n Returns:\n object: Type parameter.\n \"\"\"\n return type(x).type_parameter\n\n\ndef kind(SuperClass=object):\n \"\"\"Create a parametric wrapper type for dispatch purposes.\n\n Args:\n SuperClass (type): Super class.\n\n Returns:\n object: New parametric type wrapper.\n \"\"\"\n\n @parametric\n class Kind(SuperClass):\n def __init__(self, *xs):\n self.xs = xs\n\n def get(self):\n return self.xs[0] if len(self.xs) == 1 else self.xs\n\n return Kind\n\n\nKind = kind() #: A default kind provided for convenience.\n\n\n@parametric\nclass _ParametricList(list):\n \"\"\"Parametric list type.\"\"\"\n\n @classmethod\n def __iter_el_type__(cls):\n return cls.type_parameter\n\n @classmethod\n def __getitem_el_type__(cls):\n return cls.__iter_el_type__()\n\n\nclass List(ComparableType):\n \"\"\"Parametric list Plum type.\n\n IMPORTANT:\n `List` should not be used to generically refer to a list! Use `list` instead.\n\n Args:\n el_type (type or ptype): Element type.\n \"\"\"\n\n def __init__(self, el_type):\n self._el_type = ptype(el_type)\n\n def __hash__(self):\n return multihash(List, self._el_type)\n\n def __repr__(self):\n return f\"List[{self._el_type}]\"\n\n def get_types(self):\n return (_ParametricList[self._el_type],)\n\n @property\n def parametric(self):\n return True\n\n @property\n def runtime_type_of(self):\n return True\n\n\n# Deliver `List`.\nPromisedList.deliver(List)\n\n\n@parametric\nclass _ParametricTuple(tuple):\n \"\"\"Parametric tuple type.\"\"\"\n\n @classmethod\n def __iter_el_type__(cls):\n p = cls.type_parameter\n return Union(*(p if isinstance(p, tuple) else (p,)))\n\n @classmethod\n def __getitem_el_type__(cls):\n return cls.__iter_el_type__()\n\n\nclass Tuple(ComparableType):\n \"\"\"Parametric tuple Plum type.\n\n IMPORTANT:\n `Tuple` should not be used to generically refer to a tuple! Use `tuple` instead.\n\n Args:\n *el_types (type or ptype): Element types.\n \"\"\"\n\n def __init__(self, *el_types):\n self._el_types = tuple(ptype(el_type) for el_type in el_types)\n\n def __hash__(self):\n return multihash(Tuple, *self._el_types)\n\n def __repr__(self):\n return f'Tuple[{\", \".join(map(str, self._el_types))}]'\n\n def get_types(self):\n return (_ParametricTuple[self._el_types],)\n\n @property\n def parametric(self):\n return True\n\n @property\n def runtime_type_of(self):\n return True\n\n\n# Deliver `Tuple`.\nPromisedTuple.deliver(Tuple)\n\n\n@parametric\nclass _ParametricDict(dict):\n \"\"\"Parametric dictionary type.\"\"\"\n\n @classmethod\n def __iter_el_type__(cls):\n key_type, value_type = cls.type_parameter\n return key_type\n\n @classmethod\n def __getitem_el_type__(cls):\n key_type, value_type = cls.type_parameter\n return value_type\n\n\nclass Dict(ComparableType):\n \"\"\"Parametric dictionary Plum type.\n\n IMPORTANT:\n `Dict` should not be used to generically refer to a dictionary! Use `dict` instead.\n\n Args:\n key_type (type or ptype): Type of the keys.\n value_type (type or ptype): Type of the values.\n \"\"\"\n\n def __init__(self, key_type, value_type):\n self._key_type = ptype(key_type)\n self._value_type = ptype(value_type)\n\n def __hash__(self):\n return multihash(Dict, self._key_type, self._value_type)\n\n def __repr__(self):\n return f\"Dict[{self._key_type}, {self._value_type}]\"\n\n def get_types(self):\n return (_ParametricDict[self._key_type, self._value_type],)\n\n @property\n def parametric(self):\n return True\n\n @property\n def runtime_type_of(self):\n return True\n\n\n# Deliver `Dict`.\nPromisedDict.deliver(Dict)\n\n\nclass ElementTypeMeta(CovariantMeta):\n \"\"\"Metaclass of containers of elements with certain magic methods.\"\"\"\n\n @property\n @abc.abstractmethod\n def required_methods(cls):\n \"\"\"list[str]: Required methods.\"\"\"\n\n @property\n @abc.abstractmethod\n def el_type_method(cls):\n \"\"\"str: Method to get the element type.\"\"\"\n\n def __subclasscheck__(cls, subclass):\n if all(hasattr(subclass, name) for name in cls.required_methods):\n if is_concrete(cls) and is_concrete(subclass):\n if hasattr(subclass, cls.el_type_method):\n subclass_el_type = getattr(subclass, cls.el_type_method)()\n else:\n return False\n return ptype(subclass_el_type) <= ptype(cls.type_parameter)\n elif is_concrete(subclass):\n # Case of `subclass[par] <= cls`. This is always true.\n return True\n elif is_concrete(cls):\n # Case of `subclass <= cls[par]`. This is never true.\n return False\n else:\n # Case of `subclass <= cls`. This is also always true.\n return True\n return CovariantMeta.__subclasscheck__(cls, subclass)\n\n\nclass IterableMeta(ElementTypeMeta):\n \"\"\"Metaclass of iterables.\"\"\"\n\n @property\n def required_methods(cls):\n return [\"__iter__\"]\n\n @property\n def el_type_method(cls):\n return \"__iter_el_type__\"\n\n\n@parametric(metaclass=IterableMeta)\nclass _ParametricIterable:\n \"\"\"Parametric iterable type.\"\"\"\n\n\nclass _NotSpecified:\n pass\n\n\nclass Iterable(ComparableType):\n \"\"\"Parametric iterable Plum type.\n\n Args:\n el_type (type or ptype, optional): Type of the elements.\n \"\"\"\n\n def __init__(self, el_type=_NotSpecified):\n if el_type is _NotSpecified:\n self._el_type = None\n else:\n self._el_type = ptype(el_type)\n\n def __hash__(self):\n if self._el_type is None:\n return hash(Iterable)\n else:\n return multihash(Iterable, self._el_type)\n\n def __repr__(self):\n if self._el_type is None:\n return \"Iterable\"\n else:\n return f\"Iterable[{self._el_type}]\"\n\n def get_types(self):\n if self._el_type is None:\n return (_ParametricIterable,)\n else:\n return (_ParametricIterable[self._el_type],)\n\n @property\n def parametric(self):\n return True\n\n @property\n def runtime_type_of(self):\n return self._el_type is not None\n\n\n# Deliver `Iterable`.\nPromisedIterable.deliver(Iterable)\n\n\nclass SequenceMeta(ElementTypeMeta):\n \"\"\"Metaclass of sequences.\"\"\"\n\n @property\n def required_methods(cls):\n return [\"__getitem__\", \"__len__\"]\n\n @property\n def el_type_method(cls):\n return \"__getitem_el_type__\"\n\n\n@parametric(metaclass=SequenceMeta)\nclass _ParametricSequence:\n \"\"\"Parametric sequence type.\"\"\"\n\n\nclass Sequence(ComparableType):\n \"\"\"Parametric iterable Plum type.\n\n Args:\n el_type (type or ptype, optional): Type of the elements.\n \"\"\"\n\n def __init__(self, el_type=_NotSpecified):\n if el_type is _NotSpecified:\n self._el_type = None\n else:\n self._el_type = ptype(el_type)\n\n def __hash__(self):\n if self._el_type is None:\n return hash(Sequence)\n else:\n return multihash(Sequence, self._el_type)\n\n def __repr__(self):\n if self._el_type is None:\n return \"Sequence\"\n else:\n return f\"Sequence[{self._el_type}]\"\n\n def get_types(self):\n if self._el_type is None:\n return (_ParametricSequence,)\n else:\n return (_ParametricSequence[self._el_type],)\n\n @property\n def parametric(self):\n return True\n\n @property\n def runtime_type_of(self):\n return self._el_type is not None\n\n\n# Deliver `Sequence`.\nPromisedSequence.deliver(Sequence)\n\n\ndef _types_of_iterable(xs):\n types = {type_of(x) for x in xs}\n if len(types) == 1:\n return list(types)[0]\n else:\n return Union(*types)\n\n\n@_dispatch\ndef type_of(obj):\n \"\"\"Get the Plum type of an object.\n\n Args:\n obj (object): Object to get type of.\n\n Returns\n ptype: Plum type of `obj`.\n \"\"\"\n return ptype(type(obj))\n\n\n@_dispatch\ndef type_of(obj: list):\n return List(_types_of_iterable(obj))\n\n\n@_dispatch\ndef type_of(obj: tuple):\n return Tuple(*(type_of(x) for x in obj))\n\n\n@_dispatch\ndef type_of(obj: dict):\n return Dict(_types_of_iterable(obj.keys()), _types_of_iterable(obj.values()))\n\n\n# Deliver `type_of`.\npromised_type_of1.deliver(type_of)\npromised_type_of2.deliver(type_of)\n\n\n@parametric\nclass Val:\n \"\"\"A parametric type used to move information from the value domain to the type\n domain.\"\"\"\n\n @classmethod\n def __infer_type_parameter__(cls, *arg):\n \"\"\"Function called when the constructor of `Val` is called to determine the type\n parameters.\"\"\"\n if len(arg) == 0:\n raise ValueError(\"The value must be specified.\")\n elif len(arg) > 1:\n raise ValueError(\"Too many values. `Val` accepts only one argument.\")\n return arg[0]\n\n def __init__(self, val=None):\n \"\"\"Construct a value object with type `Val(arg)` that can be used to dispatch\n based on values.\n\n Args:\n val (object): The value to be moved to the type domain.\n \"\"\"\n if type(self).concrete:\n if val is not None and type_parameter(self) != val:\n raise ValueError(\"The value must be equal to the type parameter.\")\n else:\n raise ValueError(\"The value must be specified.\")\n\n def __repr__(self):\n return f\"{repr(ptype(type(self)))}()\"\n\n def __eq__(self, other):\n return type(self) == type(other)\n","sub_path":"plum/parametric.py","file_name":"parametric.py","file_ext":"py","file_size_in_byte":18556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"594167687","text":"from rest_framework import routers\nfrom .viewsets import BotViewSet, TelegramUserViewSet, AuthorizationViewSet, WebhookViewSet\nfrom django.urls import re_path\n\napp_name = 'api_telegram_bots'\n\nrouter = routers.SimpleRouter()\nrouter.register(r'^(?P.+)/$', WebhookViewSet, base_name='webhook')\nrouter.register(r'bots', BotViewSet)\nrouter.register(r'users', TelegramUserViewSet)\nrouter.register(r'authorizations', AuthorizationViewSet)\nurlpatterns = router.urls","sub_path":"telegram_bots/api_urls.py","file_name":"api_urls.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"598283820","text":"'''\n@Author: Rashmi\n@Date: 2021-09-26 11:30\n@Last Modified by: Rashmi\n@Last Modified time: 2021-09-26 11:40\n@Title :Write a Python program to get an absolute file path.\n'''\nimport os\n\nif __name__ == '__main__': \n '''Description : to get an absolute file path using os.path.abspath(path)''' \n abs_pathname = os.path.abspath(\"Checkvalue.py\")\n print(abs_pathname)","sub_path":"DataStructures/Basic Python/Filepath.py","file_name":"Filepath.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"132072826","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport pymongo\n\nclass QschouPipeline(object):\n def process_item(self, item, spider):\n return item\n\n\nclass MongoPipeline(object):\n def __init__(self, uri, db, post, tb, auth=None):\n self.mongo_uri = uri\n self.mongo_db = db\n self.mongo_post = post\n self.tb = tb\n self.db_auth = auth\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n uri=crawler.settings.get(\"MONGO_URI\"),\n db=crawler.settings.get(\"MONGO_DB\"),\n post=crawler.settings.get(\"MONGO_POST\"),\n tb=crawler.settings.get(\"MONGO_TB\"),\n auth=crawler.settings.get(\"DB_AUTH\")\n )\n\n def open_spider(self, spider):\n self.client = pymongo.MongoClient(self.mongo_uri)\n if self.db_auth:\n self.db = self.client[self.mongo_db]\n self.db.authenticate(*self.db_auth)\n # self.Client = self.client[self.mongo_db]\n else:\n self.db = self.client[self.mongo_db]\n\n def process_item(self, item, spider):\n self.db[self.tb].insert(dict(item))\n return item\n\n def close_spider(self, spider):\n self.client.close()\n","sub_path":"qschou/qschou/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"379952480","text":"import boto3\nimport re\nfrom botocore import exceptions\nfrom multiprocessing import Lock, JoinableQueue\nfrom .worker import Worker\nfrom .subresource_factory import SubResourceFactory\n\ndef get_buckets():\n s3 = boto3.resource(\"s3\")\n\n try:\n buckets = list(s3.buckets.all())\n except exceptions.NoCredentialsError:\n print(\n \"Auth Error: Please, either set necessary environment variables, or create the credentials config at ~/.aws\"\n )\n exit(1)\n except exceptions.ClientError:\n print(\"Auth Error: Please, double check your credentials\")\n exit(1)\n\n return buckets\n\n\ndef fill_queue(queue, buckets, bucket_filter, subresources):\n\n for bucket in buckets:\n match = re.match(bucket_filter, bucket.name)\n if match:\n subresource_list = SubResourceFactory().create(bucket, subresources)\n queue.put((bucket.name, bucket.creation_date, subresource_list))\n\n\ndef add_sentinels(queue, workers_number):\n for i in range(0, workers_number):\n queue.put(None)\n\n\ndef start_workers(workers_number, filters, subresources):\n queue = JoinableQueue()\n workers = []\n\n buckets = get_buckets()\n fill_queue(queue, buckets, filters['bucket_filter'], subresources)\n add_sentinels(queue, workers_number)\n\n for i in range(0, workers_number):\n p = Worker(queue, filters['key_filter'])\n workers.append(p)\n p.start()\n\n queue.join()\n\n for worker in workers:\n worker.join()\n","sub_path":"s3_sat/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"103319726","text":"\"\"\"\nContent generators.\n\"\"\"\n\nimport os\nimport codecs\nfrom yozuch import logger\nfrom yozuch.utils import makedirs, path_from_url, is_external_url, import_module_member\n\n\nclass GeneratorManager(object):\n\n def __init__(self, context):\n self._context = context\n self._generators = []\n\n def _url_template_for(self, name, url_source=None):\n for url, _, route_params in self._generators:\n if 'name' in route_params and route_params['name'] == name:\n if url_source is not None:\n return route_params[url_source]\n else:\n return url\n\n def _url_for(self, name, url_source=None, **kwargs):\n url_template = self._url_template_for(name, url_source)\n if url_template is None:\n raise LookupError('Unable to resolve URL for {} {} {}'.format(name, url_source, kwargs))\n else:\n return url_template.format(**kwargs)\n\n def url_for(self, name_or_url, url_source=None, **kwargs):\n references = self._context.get('references', {})\n if name_or_url in references:\n return references[name_or_url]\n if name_or_url.startswith('/') or is_external_url(name_or_url):\n return name_or_url\n return self._url_for(name_or_url, url_source, **kwargs)\n\n def url_exists_for(self, name):\n return self._url_template_for(name) is not None\n\n def _initialize_generator(self, route):\n url_template, generator, params = route\n cls = import_module_member(generator)\n if cls is not None:\n generator_cls = cls()\n self._generators.append((url_template, generator_cls, params))\n else:\n raise LookupError('Unable to find generator with name \"{}\" for url \"{}\".'.format(generator, url_template))\n\n def init(self):\n for route in self._context['config']['ROUTES']:\n self._initialize_generator(route)\n\n def generate(self, env, output_dir):\n context = self._context\n\n for url_template, generator, params in self._generators:\n entries = generator.generate(self._context, url_template, **params)\n for entry, publisher, writer in entries:\n if entry.url in self._context['entries']:\n logger.warning('URL {} has been already registered {}'.format(entry.url,\n self._context['entries'][entry.url]))\n self._context['entries'][entry.url] = entry, publisher, writer\n\n for _, (entry, publisher, _) in context['entries'].items():\n if publisher is not None:\n publisher.publish(entry, context)\n\n logger.info('Writing content...')\n for _, (entry, _, writer) in context['entries'].items():\n writer.write(entry, context, env, output_dir)\n\n\nclass ContentGeneratorBase(object):\n\n def generate(self, context, url_template, **kwargs):\n raise NotImplementedError()\n\n\nclass WriterBase(object):\n\n def write(self, entry, context, env, output_dir):\n raise NotImplementedError()\n\n\nclass PublisherBase(object):\n\n def publish(self, entry, context):\n raise NotImplementedError()\n\n\nclass TemplatePageGenerator(ContentGeneratorBase):\n\n _template = None\n _entry = None\n\n def _register_document_reference(self, context, entry):\n context['references'] = context.get('references', {})\n context['references'][entry.id] = entry.url\n\n def __init__(self, template=None, **kwargs):\n self._template = template\n\n\nclass TemplateWriter(WriterBase):\n\n def __init__(self, page_id=None):\n self._page_id = page_id\n\n def _write_file(self, content, path):\n with codecs.open(path, 'w', 'utf-8') as f:\n f.write(content)\n\n def _write_page(self, entry, env, context, output_dir, template_vars=None):\n if entry.template is None:\n raise LookupError('Template is not specified for {} {}'.format(entry, self._page_id))\n path = os.path.join(output_dir, path_from_url(entry.url))\n template = env.get_template(entry.template)\n template_vars = template_vars or {}\n template_vars.update({\n 'site': context['site'],\n 'theme': context['theme'],\n 'config': context['config'],\n 'page_id': self._page_id,\n 'page_url': entry.url\n })\n content = template.render(**template_vars)\n makedirs(os.path.dirname(path))\n self._write_file(content, path)\n\n def write(self, entry, context, env, output_dir):\n self._write_page(entry, env, context, output_dir)\n\n\nclass TemplateEntryWriter(TemplateWriter):\n\n def __init__(self, page_id, entry_name):\n super().__init__(page_id)\n self._entry_name = entry_name\n\n def write(self, entry, context, env, output_dir):\n self._write_page(entry, env, context, output_dir, {self._entry_name: entry})\n","sub_path":"yozuch/generators/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"200559674","text":"import json\nfrom os import listdir\nfrom os.path import join\nfrom pathlib import Path\nfrom src.processing import processing_adm as adm\n\n\ndef read_project(path: Path) -> list:\n annotations = []\n files_paths = [join(str(path), f) for f in listdir(str(path))]\n print(\"{} files in project {}\".format(len(files_paths), str(path)))\n for file_path in [p for p in files_paths if p[-4:] == 'json']:\n with open(file_path, 'r') as f:\n annotated_json = json.load(f)\n annotations.append(annotated_json)\n return annotations\n\n\n# def remove_x_entities(annotations: dict) -> dict:\n# token_offsets, token_tags, token_items = adm.get_annotated_token_offsets(annotations)\n# entity_offsets, entity_types, entity_items = adm.get_annotated_entity_offsets(annotations)\n# entity_token_offsets = adm.get_entity_token_offsets(token_offsets, entity_offsets)\n# no_x_entity_items = []\n# for entity_start_offset in entity_token_offsets:\n# x_entity = False\n# for token_start_offset in entity_token_offsets[entity_start_offset]:\n# token_item = token_items[token_start_offset]\n# analysis = token_item['analyses'][0]\n# tag = analysis['partOfSpeech']\n# if tag == 'X':\n# x_entity = True\n# break\n# if not x_entity:\n# entity_item = entity_items[entity_start_offset]\n# no_x_entity_items.append(entity_item)\n# clean_annotations = {'data': annotations['data']}\n# clean_annotations['attributes'] = {'entities': {'type': 'list', 'itemType': 'entities', 'items': no_x_entity_items}}\n# clean_annotations['attributes']['token'] = annotations['attributes']['token']\n# return clean_annotations\n\n\ndef save_sentences(raw_annotations, clean_project_path: Path):\n annotated_sentences = []\n for annotation in raw_annotations:\n tokenized_annotation = adm.tokenize(annotation)\n annotated_sentences.extend(adm.split(tokenized_annotation))\n for sent_index, annotated_sent in enumerate(annotated_sentences):\n # clean_annotation = remove_x_entities(annotated_sent)\n with open('{}/{}.adm.json'.format(str(clean_project_path), sent_index + 1), 'w') as f:\n json.dump(annotated_sent, f)\n\n\nfor project_type in ['fin', 'news']:\n raw_annotations = read_project(Path('data/raw/project/{}'.format(project_type)))\n save_sentences(raw_annotations, Path('data/clean/project/{}'.format(project_type)))\n","sub_path":"src/cleaning/project_tokenize_split.py","file_name":"project_tokenize_split.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"600936842","text":"\n\ndef get_log_level(level):\n levels = {'CRITICAL': 50,\n 'ERROR': 40,\n 'WARNING': 30,\n 'INFO': 20,\n 'DEBUG': 10,\n 'NOTSET': 0,\n }\n level = level.upper()\n return levels[level] if level in levels else 0\n","sub_path":"common_utils.py","file_name":"common_utils.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"271195471","text":"'''\n在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行。\n在接下来的一年里,你要旅行的日子将以一个名为 days 的数组给出。每一项是一个从 1 到 365 的整数。\n火车票有三种不同的销售方式:\n 一张为期一天的通行证售价为 costs[0] 美元;\n 一张为期七天的通行证售价为 costs[1] 美元;\n 一张为期三十天的通行证售价为 costs[2] 美元。\n通行证允许数天无限制的旅行。 例如,如果我们在第 2 天获得一张为期 7 天的通行证,\n那么我们可以连着旅行 7 天:第 2 天、第 3 天、第 4 天、第 5 天、第 6 天、第 7 天和第 8 天。\n返回你想要完成在给定的列表 days 中列出的每一天的旅行所需要的最低消费。\n'''\n#解决方法: 动态规划dp\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dayset = set(days)\n durations = [1, 7, 30]\n\n @lru_cache(None)\n def dp(i):\n if i > 365:\n return 0\n elif i in dayset:\n return min(dp(i + d) + c for c, d in zip(costs, durations))\n else:\n return dp(i + 1)\n\n return dp(1)","sub_path":"02medium/py/动态规划/983.py","file_name":"983.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"208453398","text":"from flask import Flask\nfrom flask import request\nfrom flask import jsonify\nfrom flask import abort\n\nimport os\n\napp = Flask(__name__)\n\ndogs_db = [\n\t{'id' : '1', 'breed' : 'French bulldog', 'name' : 'Doggo', 'temporary guardian ID' : 'NONE'},\n\t{'id' : '2', 'breed' : 'Chow Chow', 'name' : 'Sir Pup', 'temporary guardian ID' : 'NONE'},\n\t{'id' : '3', 'breed' : 'Spaniel', 'name' : 'Coco', 'temporary guardian ID' : 'NONE'},\n\t{'id' : '4', 'breed' : 'French bulldog', 'name' : 'Olive', 'temporary guardian ID' : 'NONE'},\n\t{'id' : '5', 'breed' : 'German Shepherd', 'name' : 'Rex', 'temporary guardian ID' : 'NONE'}\n]\n\n@app.route('/')\ndef hello():\n\treturn'Welcome to the puppy shelter'\n\n# GET information about all dogs from database as JSON\n@app.route('/dogs', methods=['GET'])\ndef get_all_dogs():\n\treturn jsonify(dogs_db)\n\n# GET any dog by any parameter\n@app.route('/dogs/', methods=['GET'])\ndef get_dog(parameter):\n\tmy_dog = [ dog for dog in dogs_db if (dog['id'] == parameter or \n\t\tdog['breed'] == parameter or dog['name'] == parameter or\n\t\tdog['temporary guardian ID'] == parameter)]\n\tif len(my_dog) == 0:\n\t\tabort(404)\n\treturn jsonify(my_dog[0])\n\n\n\n# DELETE a dog from a database by ID (adopt)\n@app.route('/dogs/', methods=['DELETE'])\ndef adopt_dog(dog_id):\n\tadopted_dog = [ dog for dog in dogs_db if (dog['id'] == dog_id )]\n\tif len(adopted_dog) == 0:\n\t\tabort(404)\n\tdogs_db.remove(adopted_dog[0])\n\treturn jsonify(adopted_dog[0]), 200\n\n# POST a dog to a database (give away)\n# Name is in url, id and breed have to be provided as JSON\n@app.route('/dogs', methods=['POST'])\ndef give_away_dog():\n\tcurrent_id = int(dogs_db[len(dogs_db) - 1]['id']) + 1\n\tnew_dog = {\n\t'id' : str(current_id),\n\t'breed' : request.json['breed'],\n\t'temporary guardian ID' : request.json['temporary guardian ID'],\n\t'name' : request.json['name']\n\t}\n\tdogs_db.append(new_dog)\n\t\n\treturn jsonify(new_dog), 201\n\t\n\n# PUT change a dog\n# Any parameter in URL\n@app.route('/dogs/', methods = ['PUT'])\ndef change_dog(dog_id):\n\tchanged_dog = [ dog for dog in dogs_db if (dog['id'] == dog_id )]\n\tif len(changed_dog) == 0:\n\t\tabort(404)\n\tif 'name' in request.json:\n\t\tchanged_dog[0]['name'] = request.json['name']\n\tif 'breed' in request.json:\n\t\tchanged_dog[0]['breed'] = request.json['breed']\n\tif 'temporary guardian ID' in request.json:\n\t\tchanged_dog[0]['temporary guardian ID'] = request.json['temporary guardian ID']\n\n\treturn jsonify(changed_dog[0])\n\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True, host='0.0.0.0', port=81)\n","sub_path":"2_laboras/another_WS/dog_shelter.py","file_name":"dog_shelter.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"266062548","text":"\n\ndef parse_args_from_string(input_string):\n \"\"\"\n parse arguments from string\n return list and integer\n \"\"\"\n first, second = input_string.split(';')\n return int(first), [int(c) for c in second.split(' ')]\n\n\ndef find_answer(input_string):\n \"\"\"\n look at first n elements of list\n get max sum of that and add to a 'scores' list\n go to index 1\n repeat until out of range\n \"\"\"\n\n scores = []\n days, gains_losses = parse_args_from_string(input_string)\n tracker = 0\n while days + tracker <= len(gains_losses):\n scores.append(sum(gains_losses[tracker:days+tracker]))\n tracker += 1\n return max(scores)\n","sub_path":"easy/max_range_sum.py","file_name":"max_range_sum.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"18190510","text":"from pyspatiotemporalgeom import region as region_logic\nimport copy\n\n\ndef process_polygons(data):\n \"\"\"\n We now need to structure a data set that pyspatiotemporalgeom can parse.\n This is done by interacting through the coordinates and creating a 2D list.\n Where this list is the coordinates (x, y) of a line. This list is appended\n to another list. This proccess continues util the polygon is complete.\n Argument:\n data, dictionary of JSON data\n\n Returns:\n an ordered list of half segments with valid labels.\n \"\"\"\n seg_list = []\n coord_matrix = [[0 for j in range(2)] for i in range(2)]\n for i in range(len(data)):\n coord_matrix[0][0] = data[i].get(\"lat\")\n coord_matrix[0][1] = data[i].get(\"lng\")\n # If not last segment, else complete the shape\n if len(data) > i + 1:\n coord_matrix[1][0] = data[i + 1].get(\"lat\")\n coord_matrix[1][1] = data[i + 1].get(\"lng\")\n else:\n coord_matrix[1][0] = data[0].get(\"lat\")\n coord_matrix[1][1] = data[0].get(\"lng\")\n # Need to make a copy of the list. Else each element in seg_list will\n # be the last coord_matrix data set.\n seg_list.append(copy.deepcopy(coord_matrix))\n return region_logic.createRegionFromSegs(seg_list)\n\n\ndef process_intersections(regions):\n \"\"\"\n Iterates through the given regions. If there is an intersection\n between those two regions. That intersection is then used as the next\n region to be used to compare aganist the next region in the list. If there\n is no intersection then there is no common intersection and it is done.\n\n Arguments:\n regions: a list of regions shown on the map\n\n Returns:\n An intersection in region form.\n \"\"\"\n # This will be used to start the process\n region = regions[0].get(\"region\")\n # Compare with the rest of the regions\n for other_region in regions[1:]:\n region = region_logic.intersection(region, other_region.get(\"region\"))\n # If region is not empty, then there was an intersection.\n if not region:\n return []\n return region\n\n\ndef process_unions(regions):\n \"\"\"\n Iterates through the given regions. That union is then used as the next\n region to be used to union the next region in the list. If there\n is no union then the process is done, the region should be empty.\n\n Arguments:\n regions: a list of regions shown on the map\n\n Returns:\n A region unioned with all given regions.\n \"\"\"\n # This will be used to start the process\n region = regions[0].get(\"region\")\n # Compare with the rest of the regions\n for other_region in regions[1:]:\n region = region_logic.union(region, other_region.get(\"region\"))\n # If region is not empty, then there was a well-formed union.\n if not region:\n return []\n return region\n\n\ndef process_difference(regions):\n \"\"\"\n Iterates through the given regions. That difference is then used as the\n next region to be used to difference the next region in the list. If there\n is no difference then the process is done, the region should be empty.\n\n Arguments:\n regions: a list of regions shown on the map\n\n Returns:\n A region formed from the difference with all given regions.\n \"\"\"\n region = regions[0].get(\"region\")\n # Compare with the rest of the regions\n for other_region in regions[1:]:\n region = region_logic.difference(region, other_region.get(\"region\"))\n # If region is not empty, then there was a well-formed difference.\n if not region:\n return []\n return region\n\n\ndef hseg_to_coords(hseg):\n \"\"\"\n Iterates through the hsegs to find the cycles and returns the the\n coordinates of each cycle in its own dictionary. The key is the unique\n label given to the hseg and the value is the coordinates.\n\n Returns:\n A list of dictionary of coordinates.\n \"\"\"\n cycle_dict = {}\n # Sets up the cycle_dict to have dictionary for each cycle and its segments\n for seg in hseg:\n key = seg[1]\n # -1 is not a unique label for segment\n if key == -1:\n key = seg[2]\n if key not in cycle_dict:\n cycle_dict[key] = {}\n # The starting point of the hseg will be the key for its line segments.\n if seg[0][0] not in cycle_dict[key]:\n cycle_dict[key][seg[0][0]] = []\n # They key has a line segment to this coordinate.\n cycle_dict[key][seg[0][0]].append(seg[0][1])\n seg_dict = {}\n # For each cyle in the dictionary we will find its cycle path.\n for cycle_label in cycle_dict:\n curr_cord = None\n next_cord = None\n visited_cords = []\n for cord in cycle_dict[cycle_label]:\n # Checks to see if it is the first itteration of the loop.\n if curr_cord is None:\n next_cord = cord\n curr_cord = cord\n else:\n next_cord = cycle_dict[cycle_label][curr_cord][0]\n # If we already discovered this line segment then it will be in\n # visited_cords.\n if next_cord in visited_cords:\n next_cord = cycle_dict[cycle_label][curr_cord][1]\n visited_cords.append(next_cord)\n curr_cord = next_cord\n seg_dict[cycle_label] = []\n # After finding the path for the cycle we just need to put in\n # lat and lng for google maps to understand.\n for point in visited_cords:\n seg_dict[cycle_label].append({\"lat\": point[0], \"lng\": point[1]})\n return seg_dict\n","sub_path":"app/spatio_helper.py","file_name":"spatio_helper.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"403774673","text":"# -*- coding: utf-8 -*-\nfrom PyQt5 import QtWidgets\n\nclass ECVPlotSettingsDialog(QtWidgets.QDialog):\n \n def __init__(self, parent):\n super(QtWidgets.QDialog, self).__init__(parent)\n \n self.parent = parent \n \n self.setWindowTitle(self.tr(\"ECV plot settings\"))\n vbox = QtWidgets.QVBoxLayout()\n\n group_area = QtWidgets.QGroupBox()\n group_area.setFlat(True)\n group_vbox = QtWidgets.QVBoxLayout()\n\n self.grid_cb = QtWidgets.QCheckBox(self.tr(\"Grid\"))\n self.grid_cb.setChecked(self.parent.grid_enabled)\n group_vbox.addWidget(self.grid_cb)\n\n self.legend_cb = QtWidgets.QCheckBox(self.tr(\"Legend\"))\n self.legend_cb.setChecked(self.parent.legend_enabled)\n group_vbox.addWidget(self.legend_cb)\n \n self.dots_cb = QtWidgets.QCheckBox(self.tr(\"Dot markers\"))\n self.dots_cb.setChecked(self.parent.dots_enabled)\n group_vbox.addWidget(self.dots_cb)\n\n self.dots_sb = QtWidgets.QSpinBox()\n self.dots_sb.setAccelerated(True)\n self.dots_sb.setMaximum(99)\n self.dots_sb.setMinimum(0) \n self.dots_sb.setValue(self.parent.dotsize) \n hbox = QtWidgets.QHBoxLayout()\n description = QtWidgets.QLabel(self.tr(\"Dot marker size\"))\n hbox.addWidget(self.dots_sb)\n hbox.addWidget(description)\n hbox.addStretch(1)\n group_vbox.addLayout(hbox)\n\n self.lines_cb = QtWidgets.QCheckBox(self.tr(\"Lines\"))\n self.lines_cb.setChecked(self.parent.lines_enabled)\n group_vbox.addWidget(self.lines_cb)\n\n self.lines_sb = QtWidgets.QSpinBox()\n self.lines_sb.setAccelerated(True)\n self.lines_sb.setMaximum(99)\n self.lines_sb.setMinimum(0) \n self.lines_sb.setValue(self.parent.linewidth) \n hbox = QtWidgets.QHBoxLayout()\n description = QtWidgets.QLabel(self.tr(\"Linewidth\"))\n hbox.addWidget(self.lines_sb)\n hbox.addWidget(description)\n hbox.addStretch(1)\n group_vbox.addLayout(hbox)\n\n self.ntype_cb = QtWidgets.QCheckBox(self.tr(\"Show only n-type doping\"))\n self.ntype_cb.setChecked(self.parent.show_only_ndoping)\n group_vbox.addWidget(self.ntype_cb)\n\n self.ptype_cb = QtWidgets.QCheckBox(self.tr(\"Show only p-type doping\"))\n self.ptype_cb.setChecked(self.parent.show_only_pdoping)\n group_vbox.addWidget(self.ptype_cb)\n \n self.default_cb = QtWidgets.QCheckBox(self.tr(\"Keep settings for next data plots\"))\n self.default_cb.setChecked(True if self.parent.parent.plot_settings else False)\n group_vbox.addWidget(self.default_cb) \n\n group_area.setLayout(group_vbox)\n vbox.addWidget(group_area)\n\n ### Buttonbox for ok ###\n hbox = QtWidgets.QHBoxLayout()\n buttonbox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)\n buttonbox.accepted.connect(self.read)\n buttonbox.rejected.connect(self.reject)\n hbox.addStretch(1) \n hbox.addWidget(buttonbox)\n hbox.addStretch(1)\n hbox.setContentsMargins(0,0,0,4)\n vbox.addLayout(hbox)\n\n self.setLayout(vbox)\n self.setMinimumWidth(800) \n \n def read(self): \n self.parent.grid_enabled = self.grid_cb.isChecked()\n self.parent.legend_enabled = self.legend_cb.isChecked() \n self.parent.dots_enabled = self.dots_cb.isChecked()\n self.parent.dotsize = self.dots_sb.value()\n self.parent.lines_enabled = self.lines_cb.isChecked()\n self.parent.linewidth = self.lines_sb.value()\n self.parent.show_only_ndoping = self.ntype_cb.isChecked()\n self.parent.show_only_pdoping = self.ptype_cb.isChecked() \n\n if self.default_cb.isChecked():\n self.parent.parent.plot_settings = {}\n self.parent.parent.plot_settings['grid_enabled'] = self.grid_cb.isChecked()\n self.parent.parent.plot_settings['legend_enabled'] = self.legend_cb.isChecked()\n self.parent.parent.plot_settings['dots_enabled'] = self.dots_cb.isChecked()\n self.parent.parent.plot_settings['dotsize'] = self.dots_sb.value()\n self.parent.parent.plot_settings['lines_enabled'] = self.lines_cb.isChecked()\n self.parent.parent.plot_settings['linewidth'] = self.lines_sb.value()\n self.parent.parent.plot_settings['show_only_ndoping'] = self.ntype_cb.isChecked()\n self.parent.parent.plot_settings['show_only_pdoping'] = self.ptype_cb.isChecked()\n else:\n self.parent.parent.plot_settings = None\n\n self.parent.on_draw()\n self.close()","sub_path":"ctosc/ECVPlotSettingsDialog.py","file_name":"ECVPlotSettingsDialog.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"556101607","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nclass Solution:\n def minimumPerimeter(self, neededApples: int) -> int:\n # i, sum = 0, 0\n # while sum < neededApples:\n # i = i + 2\n # sum = sum + i * i * 3\n # return i * 4\n\n def f(i):\n return 2 * i * (i + 1) * (2 * i + 1)\n\n # f(62996) >= 10 ** 15\n left, right = 1, 63000\n while left < right:\n mid = left + right >> 1\n if f(mid) < neededApples:\n left = mid + 1\n else:\n right = mid\n return 8 * left\n\n\nif __name__ == '__main__':\n s = Solution()\n neededApples = 13\n print(s.minimumPerimeter(neededApples))\n","sub_path":"二分查找/1954.py","file_name":"1954.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"41036034","text":"import pygame\nfrom pygame.transform import scale2x\nfrom ghosts import Ghost\n\n\nSCREEN_WIDTH = (640/3+11)*2\nSCREEN_HEIGHT = 248*2\nWHITE = (255,255,255)\nGREEN = (0,255,0)\nBLACK = (0,0,0)\nBRIGHT_RED = (245,50,41)\nDOT_COLOR = (255,200,200)\nBLUE_WALL_COLOR = (33,33,255,255)\nDOT_SIZE = 3\n\nclock = pygame.time.Clock()\n\nscreen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))\npygame.display.set_caption('Ghosts in the Machine')\n\nspritesheet = pygame.image.load('spritesheet.png')\nblank_maze = scale2x(spritesheet.subsurface((228,0,224,248)))\n\ndef get_spritesheet_image(x,y,w=16,h=16):\n return scale2x(spritesheet.subsurface(x,y,w,h))\n\npacman_r1 = get_spritesheet_image(457,1,9,13)\npacman_r2 = get_spritesheet_image(473,1,12,13)\npacman_l1 = get_spritesheet_image(461,17,9,13)\npacman_l2 = get_spritesheet_image(474,17,12,13)\npacman_u1 = get_spritesheet_image(457,37,13,9)\npacman_u2 = get_spritesheet_image(473,34,13,12)\npacman_d1 = get_spritesheet_image(457,49,13,9)\npacman_d2 = get_spritesheet_image(473,49,13,12)\n\n\n\npacman_directions = {\n 'right' : (pacman_r1, pacman_r2),\n 'left' : (pacman_l1, pacman_l2),\n 'up' : (pacman_u1, pacman_u2),\n 'down' : (pacman_d1, pacman_d2)\n }\n\n\nclass Pacman:\n def __init__(self):\n self.x = 210\n self.y = 362\n self.direction = 'right'\n self.image = pacman_directions[self.direction][1]\n self.first_chomp = True\n def get_rect(self):\n return pygame.Rect(self.x, self.y, self.image.get_width(), self.image.get_height())\n def set_direction(self, direction):\n self.direction = direction\n index = int(self.first_chomp)\n self.image = pacman_directions[self.direction][index]\n def chomp(self):\n pacman.first_chomp = not pacman.first_chomp\n index = int(self.first_chomp)\n self.image = pacman_directions[self.direction][index]\n def get_dots_ahead(self, ahead=1):\n rect = self.get_rect()\n dots_ahead = []\n dots_ahead.append((rect.midright[0] + ahead, rect.midright[1]))\n dots_ahead.append((rect.midleft[0] - ahead, rect.midleft[1]))\n dots_ahead.append((rect.midtop[0], rect.midtop[1] - ahead))\n dots_ahead.append((rect.midbottom[0], rect.midbottom[1] + ahead))\n return dots_ahead\n def dots_corners(self):\n dots_corners = []\n def get_dots_xy(self, ahead=0):\n da = self.get_dots_ahead(ahead)\n out = {\n 'up' : da[2],\n 'right' : da[0],\n 'down' : da[3],\n 'left' : da[1],\n }\n return out\n\npacman = Pacman()\n\nblinky = Ghost('blinky', 205, 169)\npinky = Ghost('pinky', 50,50)\ninky = Ghost('inky', 50,50)\nclyde = Ghost('clyde', 50,50)\n\n\nMOVEMENT_RATE = 3\nmoving = False\n\nrunning = True\nwhile running:\n\n clock.tick(30)\n pygame.display.update()\n screen.blit(blank_maze, (0,0))\n #screen.blit(pacman.image, (pacman.x, pacman.y))\n screen.blit(blinky.image, (blinky.x, blinky.y))\n #screen.blit(blinky.image, (blinky.x, blinky.y))\n #screen.blit(blinky.image, (blinky.x, blinky.y))\n #screen.blit(blinky.image, (blinky.x, blinky.y))\n\n prect = pacman.get_rect()\n brect = blinky.get_rect()\n #pygame.draw.rect(screen, GREEN, brect, 2)\n\n #dots_xys = pacman.get_dots_ahead(5)\n #dots_xys = blinky.get_dots_xy(4).values()\n #for dxy in dots_xys:\n #pygame.draw.circle(screen, DOT_COLOR, dxy, 3)\n\n #interesting_dot = dots_xys[pacman.direction]\n #if screen.get_at(interesting_dot) == BLUE_WALL_COLOR:\n #moving = False\n\n\n\n\n\n all_directions = ['right','left','up','down']\n\n # find out with directions are valid\n valid_directions = []\n for direction in all_directions:\n direction_is_valid = True\n # get the color in that direction\n dotxy = blinky.get_dots_xy(direction)\n color_in_direction = screen.get_at(dotxy)\n if color_in_direction == BLUE_WALL_COLOR:\n direction_is_valid = False\n if direction_is_valid:\n valid_directions.append(direction)\n\n # now we have all the valid directions\n # generate a random number to choose one\n number_of_valid_directions = len(valid_directions)\n random_index = random.randint(0, number_of_valid_directions)\n new_direction = valid_directions[random_index]\n blinky.set_direction(new_direction)\n\n\n\n\n\n if moving:\n if pacman.direction == 'down':\n pacman.y += MOVEMENT_RATE\n if pacman.direction == 'up':\n pacman.y -= MOVEMENT_RATE\n if pacman.direction == 'left':\n pacman.x -= MOVEMENT_RATE\n if pacman.direction == 'right':\n pacman.x += MOVEMENT_RATE\n\n\n\n\n blinky.move()\n #aheadxy = blinky.get_dots_xy()[blinky.direction]\n #color_ahead = screen.get_at(aheadxy)\n #if color_ahead == BLUE_WALL_COLOR:\n #blinky.set_direction('up')\n # we'll be moving the other ghosts too.\n # some repetition here we might want to clean up, maybe with a SpriteGroup.\n #inky.move()\n #pinky.move()\n #clyde.move()\n\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n running = False\n if e.type == pygame.KEYUP:\n moving = False\n if e.type == pygame.KEYDOWN:\n kname = pygame.key.name(e.key)\n if kname == 'q':\n running = False\n if kname == 's':\n blinky.moving = False\n if kname in ('right', 'left', 'up', 'down'):\n blinky.moving = True\n blinky.set_direction(kname)\n\n\npygame.quit()\n","sub_path":"pygame/ghosts_in_the_machine/index_bug.py","file_name":"index_bug.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"445577237","text":"#!/usr/bin/env python3\n\"\"\"\n\n\"\"\"\n\nimport logging, sys\n#\nlogging.basicConfig(\n\tlevel\t= \tlogging.DEBUG,\n\t#level\t= \tlogging.INFO,\n\tformat\t= \t#\"%(asctime)s | \" + \n\t\t\t\t\"%(module)-15.15s | \" + \n\t\t\t\t\"%(name)-10s:\" +\n\t\t\t\t\"%(funcName)-15.15s | \" + \n\t\t\t\t\"%(levelname)-\" + \n\t\t\t\t\tstr(len(\"CRITICAL\")) + \"s | \" + \n\t\t\t\t\"%(message)s\",\n\tdatefmt\t= '%Y/%m/%d %H:%M:%S',\n\tstream = sys.stdout\n\t) #\nlog=logging.getLogger(__name__)\n\nif __name__ == \"__main__\":\n\tsave_stdout = sys.stdout\n\t#\n\t#\tloop over standard streams\n\t#\n\tfor stream in [ sys.stdin, sys.stdout, sys.stderr, save_stdout ]:\n\t\tlog.info(\"stream name: %s\", stream.name)\n\t\tlog.info(\"stream : %s\", stream)\n\t\t#\n\t\t#\twill fail on stdin\n\t\t#\n\t\ttry:\n\t\t\tstream.write(\"hello from %s \\n\" % stream.name)\n\t\texcept Exception as e:\n\t\t\tlog.error(e)\n\t\n\tlog.info(\"save_stdout is sys.stdout : %s\", save_stdout is sys.stdout)\n\tlog.info(\"save_stdout == sys.stdout : %s\", save_stdout == sys.stdout)\n\t#\n\t#\tuse first argument if provided or default if not\n\t#\n\toutputfile = sys.argv[1] if len(sys.argv) > 1 else \"default.txt\"\n\t\n\ttry:\n\t\tsys.stdout = open(outputfile, 'w')\n\t\tprint(\"theese should go to file %s\" % outputfile)\n\t\tprint(\"save_stdout is sys.stdout : %s\" % (save_stdout is sys.stdout))\n\t\tprint(\"save_stdout == sys.stdout : %s\" % (save_stdout == sys.stdout))\n\t\tsys.stdout.close()\n\texcept Exception as e:\n\t\tlog.error(e)\n\t\n\tsys.stdout = save_stdout\n\tprint(\"theese should go to file stdout\")\n\tprint(\"save_stdout is sys.stdout : %s\" % (save_stdout is sys.stdout))\n\tprint(\"save_stdout == sys.stdout : %s\" % (save_stdout == sys.stdout))\n\t\n\t\n\t","sub_path":"advanced/sys/redirect.py","file_name":"redirect.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"344474155","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.14-x86_64/egg/zk_rn_lib_maker/__main__.py\n# Compiled at: 2020-01-07 03:45:34\n# Size of source mod 2**32: 2242 bytes\nimport sys, re, os, ezutils.files\nlib_name_re = re.compile('^[a-z][a-z0-9|\\\\-]*[a-z|0-9]$')\n\ndef brother_path(file_name):\n return os.path.join(os.path.abspath(os.path.dirname(__file__)), file_name)\n\n\ndef check_lib_name(lib_name):\n return lib_name_re.match(lib_name)\n\n\ndef print_lib_name():\n print('组件名称要求:\\n 1. 非数字开头\\n 2. 小写字母或数字\\n 3. 以中横线作为单词间的分割。\\n ')\n\n\ndef print_using():\n print('\\n zk-rn-lib-maker lib-name\\n lib-name:\\n 1. 非数字开头\\n 2. 小写字母或数字\\n 3. 以中横线(-)作为单词间的分割。\\n\\n 例如:\\n \"zk-rn-lib-maker protocal-view\"\\n 将会在当前目录下创建名为protocal-view的lib库工程.\\n ')\n\n\ndef print_version():\n version_str = ezutils.files.readstr(brother_path('version.cfg'))\n print(f\"zk-rn-lib-maker:{version_str}\")\n\n\ndef result_of_cmd(cmd):\n r = os.popen(cmd)\n text = r.read()\n r.close()\n return text\n\n\ndef is_rn_create_lib_installed():\n result = result_of_cmd('npm ls react-native-create-library -g|grep empty')\n return len(result) == 0\n\n\ndef print_install_rn_create_lib():\n print('请先安装react-native-create-library:\\n\\n npm install -g react-native-create-library\\n ')\n\n\ndef main():\n if not is_rn_create_lib_installed():\n print_install_rn_create_lib()\n return\n else:\n arg_count = len(sys.argv)\n if arg_count < 2:\n print_using()\n return\n lib_name = sys.argv[1]\n if lib_name == '-h':\n print_using()\n return\n if lib_name == '-v':\n print_version()\n return\n check_lib_name(lib_name) or print_lib_name()\n return\n android_id = f\"com.smartstudy.{lib_name.replace('-', '')}\"\n cmd = f'react-native-create-library {lib_name} --module-prefix \"@zhike-private/rn\" --package-identifier \"{android_id}\" && rm -rf ./{lib_name}/windows'\n os.system(cmd)\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/zk_rn_lib_maker-1.0.3-py3.7/__main__.cpython-37.py","file_name":"__main__.cpython-37.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"319918638","text":"\nimport subprocess\nimport os.path\n\nPWD = os.path.dirname(os.path.abspath(__file__))\n\nLIST=['openexr', 'acl', 'attr', 'freetype', 'exosip', 'man-db', 'libpipeline']\n\nfor i in LIST:\n \n j = os.path.join(PWD, i)\n \n os.makedirs(j, exist_ok=True)\n \n p=subprocess.Popen(\n ['wrogts', 'simple', 'http://download.savannah.gnu.org/releases/{}/'.format(i)],\n cwd=j\n )\n p.wait()\n ","sub_path":"gnu.org/savannah/upp.py","file_name":"upp.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"26656004","text":"def make_great(magicians):\n for i in range(len(magicians)):\n magicians[i] = \"the Great \" + magicians[i].title()\n return magicians\n\n\ndef show_magicians(magicians):\n for magician in magicians:\n print(magician)\n\n\nmagicians = ['leo', 'jack', 'mark', 'tom']\nret = make_great(magicians[:])\nshow_magicians(ret)\nshow_magicians(magicians)\n","sub_path":"PythonProgram/chapter_08/8-11.py","file_name":"8-11.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"29889831","text":"from bs4 import BeautifulSoup\n\n\nwith open('text.txt', 'r', encoding='utf-8') as f:\n html = f.read()\n\nsoup = BeautifulSoup(html, 'html.parser')\nresult = soup.find_all('h4')\n# print(result)\nfor i, res in enumerate(result):\n # print(res['class'][0])\n if res['class'][0] == 'title':\n if res.string:\n print(i, res.string.strip())\n else:\n print(i, res.a.string)","sub_path":"BS_test/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"439344913","text":"import pyautogui\nimport time\nimport os.path\n#Evaluate = 974, 676\n#Download = 1276, 515\n#print(pyautogui.position())\n\ndef renaming():\n path = \"C:/Users/DSLR/Desktop/ELAB PYTHON/\"\n t = 0\n for i in range(1, 101):\n if t > 0:\n name = \"report (\"+str(t)+\").png\"\n else:\n name = \"report.png\"\n\n for c in avoid:\n if c == str(t+1):\n print(\"Q.no\"+str(c)+\" Not Found...\")\n t = t + 1\n\n FileName = \"Q. \"+str(t+1)+\".png\"\n\n\n if(check(name)):\n os.rename(os.path.join(path,name), os.path.join(path,FileName))\n print(\"Renamed \"+FileName)\n else:\n print(\"Skipped \"+name)\n t = t + 1\n\ndef elab():\n time.sleep(1)\n pyautogui.click(910, 594)\n time.sleep(1)\n pyautogui.click(1285, 651)\n\ndef check(name):\n time.sleep(2)\n if os.path.isfile(\"C:/Users/DSLR/Desktop/ELAB PYTHON/\" + name) == False:\n return False\n else:\n return True\navoid = []\nt = 0\ndisp = 0\nfor i in range(1,101):\n if t > 0:\n name = \"report (\"+str(t)+\").png\"\n else:\n name = \"report.png\"\n\n elab()\n n = 0\n while check(name) == False:\n n = n + 1\n if n <= 3:\n print(\"Rechecking \"+str(disp+1))\n if check(name) == False:\n elab()\n else:\n print(\"Skipped \"+str(disp+1))\n t = t - 1\n avoid.append(disp+1)\n break\n if n < 4:\n print(\"Q.no.\" + str(disp + 1)+\" Downloaded!!\")\n t = t + 1\n disp = disp + 1\n pyautogui.click(1313, 179)\n\nrenaming()\n#pyautogui.hotkey(\"ctrl\",\"a\")\n#pyautogui.typewrite(\"Abhijith Udayakumar\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"440291602","text":"suma_total = 0\ncontador = 0\nbandera = True\n\nprint(\"Ingrese las notas de los estudiantes de su materia\")\n\nwhile(bandera):\n calificaciones = float(input(\"Ingrese la calificación\\n> \"))\n suma_total = suma_total + calificaciones\n contador = contador + 1\n \n salir = input(\"Ingrese 'si' para salir del ciclo\\n> \")\n if(salir == \"si\"):\n bandera = False\n\npromedio = suma_total / contador\nprint(f\"El promedio final es: {promedio:.2f}\")","sub_path":"Semana6/ejercicios-clase-06-/ejerciciosCicloWhile/Ejercicio07.py","file_name":"Ejercicio07.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"618596559","text":"# Given an array nums of n integers, \n# are there elements a, b, c in nums such that \n# a + b + c = 0? Find all unique triplets in the \n# array which gives the sum of zero.\n\nnums = input()\n\ndef solve(nums):\n res = set()\n nums = sorted(nums)\n index = 0\n while index < len(nums):\n curr = nums[index]\n l = index + 1\n r = len(nums) - 1\n while l < r:\n left_val = nums[l]\n right_val = nums[r]\n \n _sum = curr + left_val + right_val\n if _sum == 0:\n res.add((curr, left_val, right_val))\n l += 1\n r -= 1\n elif _sum > 0:\n r -= 1\n else:\n l += 1\n index += 1\n return map(list, res)\n\nprint(solve(nums))","sub_path":"leetcode/3sum.py","file_name":"3sum.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"243837443","text":"#\n# @lc app=leetcode.cn id=14 lang=python3\n#\n# [14] 最长公共前缀\n#\nfrom typing import List\n\n\n# @lc code=start\nclass Solution:\n\n def longestCommonPrefix(self, strs: List[str]) -> str:\n \"\"\"\n 算法思路:\n 从第一个字符串 s0 的第 i 位置获取字符 c\n 判断后续字符串 s1, s2, ..., sn 的第 i 个字符是否为 c\n 如果是,则从 i + 1 继续迭代\n 否则,前 i 个字符组成公共前缀\n\n Args:\n strs(List[str]): 输入的字符串数组\n\n Returns:\n str: 返回所有字符串公共的前缀\n \"\"\"\n if len(strs) == 0:\n return ''\n\n res = []\n for i in range(0, min(len(s) for s in strs)):\n c = strs[0][i]\n for j in range(1, len(strs)):\n if c != strs[j][i]:\n return ''.join(res)\n\n res.append(c)\n\n return ''.join(res)\n# @lc code=end\n\n","sub_path":"14.最长公共前缀.py","file_name":"14.最长公共前缀.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"9633327","text":"# -*- coding: utf-8 -*-\n\nimport select\nimport socket\nimport datetime\n\nEOL1 = b'\\n\\n'\nEOL2 = b'\\n\\r\\n'\nresponse = b'HTTP/1.0 200 OK\\r\\nDate: Mon, 1 Jan 1996 01:01:01 GMT\\r\\n'\nresponse += b'Content-Type: text/plain\\r\\nContent-Length: 13\\r\\n\\r\\n'\nresponse += b'Hello, world!'\n\nsock = socket.socket()\nsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nsock.bind((\"localhost\", 10000))\nsock.listen(5)\nsock.setblocking(0)\n\nepoll = select.epoll()\nepoll.register(sock, select.EPOLLIN)\n\n# 为了针对长连接的情况,增加请求和响应操作\nconnections = {}\nrequests = {}\nresponses = {}\ntry:\n\n while True:\n print(datetime.datetime.now())\n events = epoll.poll(1)\n print(events)\n for fd, event in events:\n if fd == sock.fileno():\n # 接收请求\n con, addr = sock.accept()\n con.setblocking(0)\n epoll.register(con, select.EPOLLIN | select.EPOLLET)\n connections[con.fileno()] = con\n requests[con.fileno()] = b''\n responses[con.fileno()] = response\n elif event & select.EPOLLIN:\n print(\"ssssssssssssss\")\n con = connections[fd]\n requests[fd] += con.recv(1024)\n # 判断con是否已经完全发送完成\n if EOL1 in requests[fd] or EOL2 in requests[fd]:\n epoll.modify(fd, select.EPOLLOUT)\n print('-' * 40 + '\\n' + requests[fd].decode()[:-2])\n elif event & select.EPOLLOUT:\n # 发送完成,将fd挂起\n con = connections[fd]\n byteswritten = con.send(responses[fd])\n # 将已发送内容截取,并判断是否完全发送完毕,已发送完毕,epoll挂起fd,fdshutdown\n responses[fd] = responses[fd][byteswritten:]\n if len(responses[fd]) == 0:\n epoll.modify(fd, 0)\n con.shutdown(socket.SHUT_RDWR)\n\n elif event & select.EPOLLHUP:\n # 处理挂起fd, epoll注销fd, 关闭socket, connections移除fd\n epoll.unregister(fd)\n connections[fd].close()\n del connections[fd]\nfinally:\n epoll.unregister(sock)\n sock.close()\n","sub_path":"tmp/test_select/ch3.py","file_name":"ch3.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"48573313","text":"import logging\nfrom multiprocessing import freeze_support\n\nfrom src.full_node.full_node import FullNode\nfrom src.rpc.full_node_rpc_server import start_full_node_rpc_server\nfrom src.server.outbound_message import NodeType\nfrom src.server.start_service import run_service\nfrom src.util.config import load_config_cli\nfrom src.util.default_root import DEFAULT_ROOT_PATH\nfrom src.server.upnp import upnp_remap_port\n\nfrom src.types.peer_info import PeerInfo\n\n\nlog = logging.getLogger(__name__)\n\n\ndef service_kwargs_for_full_node(root_path):\n service_name = \"full_node\"\n config = load_config_cli(root_path, \"config.yaml\", service_name)\n\n api = FullNode(config, root_path=root_path)\n\n introducer = config[\"introducer_peer\"]\n peer_info = PeerInfo(introducer[\"host\"], introducer[\"port\"])\n\n async def start_callback():\n await api.start()\n if config[\"enable_upnp\"]:\n upnp_remap_port(config[\"port\"])\n\n def stop_callback():\n api._close()\n\n async def await_closed_callback():\n await api._await_closed()\n\n kwargs = dict(\n root_path=root_path,\n api=api,\n node_type=NodeType.FULL_NODE,\n advertised_port=config[\"port\"],\n service_name=service_name,\n server_listen_ports=[config[\"port\"]],\n on_connect_callback=api._on_connect,\n start_callback=start_callback,\n stop_callback=stop_callback,\n await_closed_callback=await_closed_callback,\n rpc_start_callback_port=(start_full_node_rpc_server, config[\"rpc_port\"]),\n periodic_introducer_poll=(\n peer_info,\n config[\"introducer_connect_interval\"],\n config[\"target_peer_count\"],\n ),\n )\n return kwargs\n\n\ndef main():\n kwargs = service_kwargs_for_full_node(DEFAULT_ROOT_PATH)\n return run_service(**kwargs)\n\n\nif __name__ == \"__main__\":\n freeze_support()\n main()\n","sub_path":"src/server/start_full_node.py","file_name":"start_full_node.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"509786792","text":"import os\nimport struct\nfrom elftools.elf.elffile import ELFFile\nfrom elftools.elf.constants import *\nfrom elftools.elf.enums import *\n\ndef build_payload(addr,srcpath):\n os.system('gcc -c -o \"%s.o\" \"%s\"'%(srcpath,srcpath))\n os.system('ld --script payload.lds -Ttext=0x%x -o \"%s.bin\" \"%s.o\"'%(addr,srcpath,srcpath))\n\n elf = ELFFile(open('%s.o'%srcpath,'rb'))\n for sec in elf.iter_sections():\n if sec.header['sh_type'] != 'SHT_SYMTAB':\n continue\n for sym in sec.iter_symbols():\n if sym.entry['st_info']['bind'] != 'STB_GLOBAL':\n continue\n base = elf.get_section(sym.entry['st_shndx']).header['sh_addr']\n off = sym.entry['st_value']\n print(sym.name,hex(addr + base + off))\n\n os.remove('%s.o'%srcpath)\n return '%s.bin'%srcpath\n","sub_path":"payload.py","file_name":"payload.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"199293916","text":"#### SYSTEM,OS, APPIUM, SELENIUM ####\nimport os,sys,time,datetime\nimport unittest\nimport random, string\nfrom unittest.case import skip\n\n#### OUR FRAMEWORK, CONFIGURATION ####\nfrom lib.core.webui.base import SeleniumWebdriverBase\nfrom lib.tools.timeout import timeout\nfrom settings.ui import UISettings\n\n#### TESTS ####\nfrom tests.webui.dashboard.account.assertions import AccountAssertions\n\nfrom tests.webui.dashboard.account.page import AccountPage\n#from tests.webui.dashboard.application.assertions import ApplicationAssertions\n#from tests.webui.dashboard.application.page import ApplicationPage\n#from tests.webui.dashboard.applicationDetails.assertions import ApplicationDetailsAssertions\n#from tests.webui.dashboard.applicationDetails.page import ApplicationDetailsPage\nfrom tests.webui.dashboard.campaigns.assertions import CampaignsAssertions\nfrom tests.webui.dashboard.campaigns.page import CampaignsPage\n\nclass TestCampaigns(unittest.TestCase):\n \n base = SeleniumWebdriverBase()\n account_page = AccountPage()\n settings = UISettings()\n prod_version = int(settings.PROD_VERSION)\n \n account_assertions = AccountAssertions()\n #app_page = ApplicationPage()\n #app_assertions = ApplicationAssertions()\n #appdetails_page = ApplicationDetailsPage()\n #appdetails_assertions = ApplicationDetailsAssertions()\n campaigns_page = CampaignsPage()\n campaigns_assertions = CampaignsAssertions()\n \n \n today_time = base.getUTC()\n dashboard_account_name = settings.dashboard_account_name \n campaign_name = \"%s_Campaign\"%dashboard_account_name\n\n @classmethod\n def setUpClass(self):\n 'only launch browser and login once for all test as default.'\n \n self.base.setup()\n username = self.settings.home_username\n password = self.settings.home_password\n status = self.account_page.emailSignIn(self, username, password) \n print(\"Class Setup and Login completed=%s\"%status)\n \n def setUp(self):\n print (\"\\n[info]Starting ...\" + self.__class__.__name__ +\".\"+ self._testMethodName)\n\n @classmethod\n def tearDownClass(self): #enable this for real test\n self.base.closeBrowser()\n print(\"done!\")\n \n @unittest.skipIf(prod_version < 1,\"Not support version %s\"%prod_version)\n def test_createNewCampaign_001(self):\n platform =\"iOS\"\n load_from_file= True\n want_to_save = \"yes\"\n campaign_name = self.campaign_name+\"_%s_%s\"%(platform,self.today_time)\n application_name = self.base.readVungleApplicationDetailsByKey(\"VUNGLE_APPLE_ADVERTISER_APPLICATION_NAME\")\n campaign_ad_type = \"Vungle ads\"\n total_spend_limit = 100\n end_time = self.campaigns_page.getTime(want_customize_time=\"yes\", year_plus=5)\n city_target = \"San Francisco\"\n country_target = \"USA\"\n rate = 20\n dict_params = {\"LOAD_FROM_FILE\":load_from_file,\"CAMPAIGN_NAME\":campaign_name,\"APPLICATION_NAME\":application_name,\"CAMPAIGN_AD_TYPE\":campaign_ad_type,\"PLATFORM\":platform,\"END_TIME\":end_time,\"TOTAL_SPENDING_LIMIT\":total_spend_limit,\"COUNTRY_TARGET\":country_target,\"RATE\":rate}\n self.campaigns_page.createCampaign(self, dict_params, want_to_save)\n \n @unittest.skipIf(prod_version > 1,\"Not support version %s\"%prod_version)\n def test_createNewCampaign_002(self):\n 'without file or save to file'\n platform =\"iOS\"\n load_from_file= True\n want_to_save = \"yes\"\n campaign_name = \"QA.Automation_Campaign_iOS_1522144321\"\n application_name = \"QA.Automation_Ad_iOS_App_1522144321\"\n campaign_ad_type = \"Vungle ads\"\n total_spend_limit = 100\n end_time = self.campaigns_page.getTime(want_customize_time=\"yes\", year_plus=5)\n city_target = \"San Francisco\"\n country_target = \"USA\"\n rate = 20\n dict_params = {\"CAMPAIGN_NAME\":campaign_name,\"APPLICATION_NAME\":application_name,\"CAMPAIGN_AD_TYPE\":campaign_ad_type,\"PLATFORM\":platform,\"END_TIME\":end_time,\"TOTAL_SPENDING_LIMIT\":total_spend_limit,\"COUNTRY_TARGET\":country_target,\"RATE\":rate}\n self.campaigns_page.createCampaign(self, dict_params, want_to_save)\n ","sub_path":"tests/webui/dashboard/campaigns/test_campaigns.py","file_name":"test_campaigns.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"558046256","text":"# https://www.hackerrank.com/challenges/array-left-rotation/problem\n\nfrom collections import deque\n\nd = 4\na = [1,2,3,4,5]\n\ni = deque(a)\nfor n in range(d):\n i.append(i.popleft())\n\n# print(*list(i))\n\n\nfrom collections import deque\n\n\nif __name__ == '__main__':\n nd = input().split()\n\n n = int(nd[0])\n\n d = int(nd[1])\n\n a = list(map(int, input().rstrip().split()))\n\n i = deque(a)\n for n in range(d):\n i.append(i.popleft())\n # print(*list(i))\n\n\n\n\n#\n# >>> from collections import deque\n# >>> d = deque('ghi') # make a new deque with three items\n# >>> for elem in d: # iterate over the deque's elements\n# ... print elem.upper()\n#\n# >>> d.append('j') # add a new entry to the right side\n# >>> d.appendleft('f') # add a new entry to the left side\n# >>> d # show the representation of the deque\n# deque(['f', 'g', 'h', 'i', 'j'])\n#\n# >>> d.pop() # return and remove the rightmost item\n# 'j'\n# >>> d.popleft() # return and remove the leftmost item\n# 'f'\n# >>> list(d) # list the contents of the deque\n# ['g', 'h', 'i']\n# >>> d[0] # peek at leftmost item\n# 'g'\n# >>> d[-1] # peek at rightmost item\n# 'i'\n#\n# >>> list(reversed(d)) # list the contents of a deque in reverse\n# ['i', 'h', 'g']\n# >>> 'h' in d # search the deque\n# True\n# >>> d.extend('jkl') # add multiple elements at once\n# >>> d\n# deque(['g', 'h', 'i', 'j', 'k', 'l'])\n# >>> d.rotate(1) # right rotation\n# >>> d\n# deque(['l', 'g', 'h', 'i', 'j', 'k'])\n# >>> d.rotate(-1) # left rotation\n# >>> d\n# deque(['g', 'h', 'i', 'j', 'k', 'l'])\n#\n# >>> deque(reversed(d)) # make a new deque in reverse order\n# deque(['l', 'k', 'j', 'i', 'h', 'g'])\n# >>> d.clear() # empty the deque\n# >>> d.pop() # cannot pop from an empty deque\n# Traceback (most recent call last):\n# File \"\", line 1, in -toplevel-\n# d.pop()\n# IndexError: pop from an empty deque\n#\n# >>> d.extendleft('abc') # extendleft() reverses the input order\n# >>> d\n# deque(['c', 'b', 'a'])","sub_path":"step2/2-5/leftRotation.py","file_name":"leftRotation.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"226586770","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport io\nimport os.path\n\nimport pytest\n\nfrom pre_commit_hooks.autopep8_wrapper import main\n\n\n@pytest.mark.parametrize(\n ('input_src', 'expected_ret', 'output_src'),\n (\n ('print(1 + 2)\\n', 1, 'print(1 + 2)\\n'),\n ('print(1 + 2)\\n', 0, 'print(1 + 2)\\n'),\n ),\n)\ndef test_main_failing(tmpdir, input_src, expected_ret, output_src):\n filename = os.path.join(tmpdir.strpath, 'test.py')\n with io.open(filename, 'w') as file_obj:\n file_obj.write(input_src)\n ret = main([filename, '-i', '-v'])\n assert ret == expected_ret\n assert io.open(filename).read() == output_src\n","sub_path":"tests/autopep8_wrapper_test.py","file_name":"autopep8_wrapper_test.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"432830390","text":"# 一个 句子 指的是一个序列的单词用单个空格连接起来,且开头和结尾没有任何空格。每个单词都只包含小写或大写英文字母。\n# 我们可以给一个句子添加 从 1 开始的单词位置索引 ,并且将句子中所有单词 打乱顺序 。\n# 比方说,句子 \"This is a sentence\" 可以被打乱顺序得到 \"sentence4 a3 is2 This1\" 或者 \"is2 sentence4 This1 a3\" 。\n# 给你一个 打乱顺序 的句子 s ,它包含的单词不超过 9 个,请你重新构造并得到原本顺序的句子。\n# \n# 示例 1:\n# 输入:s = \"is2 sentence4 This1 a3\"\n# 输出:\"This is a sentence\"\n# 解释:将 s 中的单词按照初始位置排序,得到 \"This1 is2 a3 sentence4\" ,然后删除数字。\n# \n# 示例 2:\n# 输入:s = \"Myself2 Me1 I4 and3\"\n# 输出:\"Me Myself and I\"\n# 解释:将 s 中的单词按照初始位置排序,得到 \"Me1 Myself2 and3 I4\" ,然后删除数字。\n# \n# 提示:\n# 2 <= s.length <= 200\n# s 只包含小写和大写英文字母、空格以及从 1 到 9 的数字。\n# s 中单词数目为 1 到 9 个。\n# s 中的单词由单个空格分隔。\n# s 不包含任何前导或者���缀空格。\n\nclass Solution:\n def sortSentence(self, s: str) -> str:\n arr = s.split(' ')\n res = [''] * len(arr)\n for st in s.split(\" \"):\n val = st[:-1]\n idx = int(st[-1])\n res[idx-1] = val\n return ' '.join(res)\n \nprint(Solution().sortSentence(s = \"is2 sentence4 This1 a3\")) # \"This is a sentence\"\nprint(Solution().sortSentence(s = \"Myself2 Me1 I4 and3\")) # \"Me Myself and I\"","sub_path":"Q1859.将句子排序.py","file_name":"Q1859.将句子排序.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"33692337","text":"import json\nimport xerox\nfrom .pyxhook import HookManager\nfrom .gui import clipboard\n\n# clipboard\nclips = []\n# number of active clix GUIs \nactive = 0\n# previously logged key\nprev_Key = None\n\ndef OnKeyPress(event):\n\tglobal prev_Key, active\n\tif event.Key == 'space' and prev_Key == 'Control_L' and active == 0:\n\t\tactive = 1\n\t\tclipboard(clips)\n\t\tactive = 0\n\t\tprev_Key = None\n\telif event.Key == 'c' and prev_Key == 'Control_L':\n\t\ttext = xerox.paste(xsel = True)\n\t\tclips.append(text)\n\t\tprint(\"You just copied: {}\".format(text))\n\telse:\n\t\tprev_Key = event.Key\n\ndef main():\n\tnew_hook = HookManager()\n\tnew_hook.KeyDown = OnKeyPress\n\tnew_hook.HookKeyboard()\n\tnew_hook.start()\n\n\nif __name__ == \"__main__\":\n\tmain()\n\t\n\n","sub_path":"clix/clix.py","file_name":"clix.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"529421489","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# -------------------------------------------#\n# author: sean lee #\n# email: xmlee97@gmail.com #\n#--------------------------------------------#\n\nfrom __future__ import absolute_import, unicode_literals\nimport io\nimport sys\nfrom ..utils import safe_input, filelist\nfrom ..config import path as C_PATH\n\nif sys.version_info[0] == 2:\n reload(sys)\n sys.setdefaultencoding('utf8')\n range = xrange\n\nclass Checker(object):\n\n \"\"\"\n Args:\n max_edit_distance:\n verbose:\n - 0 return best guession\n - 1 all guessions of smallest edit distance\n - 2 all guessions <= max_edit_distance\n \"\"\"\n def __init__(self, max_edit_distance=2, verbose=0):\n self.max_edit_distance = max_edit_distance\n self.verbose = verbose\n self.dict = {}\n self.longest_length = 0\n\n self.train(C_PATH.checker['corpus']['checker'])\n\n def userdict(self, fpath):\n \"\"\"set user dictionary\"\"\"\n\n print(\"loading...\")\n self.train(fpath)\n\n def load_data(self, fpath):\n \"\"\"load data from file\"\"\"\n\n for fname in filelist(fpath):\n with io.open(fname, 'r', encoding='utf-8') as f:\n for line in f:\n line = line.strip()\n arr = line.split()\n if arr:\n yield safe_input(arr[0])\n\n def train(self, fname):\n \"\"\"build dictionary\"\"\"\n\n print(\"start to build dictionary...\")\n for word in self.load_data(fname):\n if word in self.dict:\n self.dict[word] = (self.dict[word][0], self.dict[word][1] + 1)\n else:\n self.dict[word] = ([], 1)\n self.longest_length = max(self.longest_length, len(word))\n\n if self.dict[word][1] == 1:\n # first show of word in corpus\n deletes = self.get_deletes(word)\n for d in deletes:\n if d in self.dict:\n self.dict[d][0].append(word)\n else:\n self.dict[d] = ([word], 0)\n print(\"done !\")\n\n def get_deletes(self, word):\n \"\"\"get delete word\"\"\"\n dels = []\n queue = [word]\n for _ in range(self.max_edit_distance):\n tmp = []\n for word in queue:\n if len(word) > 1:\n for i in range(len(word)):\n except_char = word[:i] + word[i+1:]\n if except_char not in dels:\n dels.append(except_char)\n if except_char not in tmp:\n tmp.append(except_char)\n queue = tmp\n return dels\n\n def edit_distance(self, seq1, seq2):\n \"\"\"implement of dameraulevenshtein\"\"\"\n m, n = len(seq1), len(seq2)\n prev = None\n cnt = list(range(1, n + 1)) + [0]\n for i in range(m):\n pprev, prev, cnt = prev, cnt, [0]*n + [i+1]\n for j in range(n):\n cnt[j] = min(prev[j] + 1, cnt[j-1]+1, prev[j-1]+(seq1[i] != seq2[j]))\n if (i > 0 and j > 0 and seq1[i] == seq2[j-1] and\n seq1[i-1] == seq2[j] and seq1[i] != seq2[j]):\n cnt[j] = min(cnt[j], pprev[j-2]+1)\n return cnt[n-1]\n\n def best_match(self, word):\n \"\"\"get best match word\"\"\"\n\n return self.word_checker(word)[0]\n\n def word_checker(self, word):\n \"\"\"check word-level\"\"\"\n\n if len(word) - self.longest_length > self.max_edit_distance or not word.strip():\n return None\n min_guess_len = float('inf')\n queue = [word]\n guess_dict, tmp_dict = {}, {}\n while queue:\n # queue pop\n cnt = queue[0]\n queue = queue[1:]\n if (self.verbose < 2 and guess_dict and\n len(word) - len(cnt) > min_guess_len):\n break\n if cnt in self.dict and cnt not in guess_dict:\n if self.dict[cnt][1] > 0:\n guess_dict[cnt] = (self.dict[cnt][1], len(word) - len(cnt))\n if self.verbose < 2 and len(word) == len(cnt):\n break\n elif len(word) - len(cnt) < min_guess_len:\n min_guess_len = len(word) - len(cnt)\n for sc_item in self.dict[cnt][0]:\n if sc_item not in guess_dict:\n if len(cnt) == len(word):\n item_dist = len(sc_item) - len(cnt)\n item_dist = self.edit_distance(sc_item, word)\n if self.verbose < 2 and item_dist > min_guess_len:\n pass\n elif item_dist <= self.max_edit_distance:\n guess_dict[sc_item] = (self.dict[sc_item][1], item_dist)\n if item_dist < min_guess_len:\n min_guess_len = item_dist\n if self.verbose < 2:\n guess_dict = {k:v for k, v in guess_dict.items()\n if v[1] <= min_guess_len}\n if self.verbose < 2 and len(word) - len(cnt) > min_guess_len:\n pass\n elif len(word) - len(cnt) < self.max_edit_distance and len(cnt) > 1:\n for i in range(len(cnt)):\n # character index\n except_char = cnt[:i] + cnt[i+1:]\n if except_char not in tmp_dict:\n queue.append(except_char)\n tmp_dict[except_char] = None\n guess_list = guess_dict.items()\n ret = sorted(guess_list, key=lambda x: (x[1][0], -x[1][1]))\n if self.verbose == 0:\n try:\n return ret[0]\n except:\n return None\n else:\n return ret\n\n def doc_checker(self, doc):\n \"\"\"check document-level\"\"\"\n\n if len(doc) < 2:\n return [doc]\n\n cands = []\n cnt = doc[0]\n appear_times = 0\n for ch in doc[1:]:\n cnt += ch\n suggestion = self.best_match(cnt)\n\n if cands and suggestion == cands[-1]:\n appear_times += 1\n else:\n appear_times = 0\n if appear_times > 1:\n cnt = ch\n appear_times = 0\n continue\n if suggestion is not None:\n cands.append(suggestion)\n else:\n cands.append(ch)\n if len(cnt) > self.longest_length:\n cnt = ch\n\n cands = list(dict.fromkeys(cands))\n n = len(cands)\n i = 1\n while i < n:\n if cands[i-1] in cands[i]:\n cands.remove(cands[i-1])\n n = len(cands)\n i -= 2\n i += 1\n if len(cands) == 1:\n break\n return cands\n","sub_path":"xmnlp/checker/checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":7092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"89551544","text":"import random\r\nimport pygame\r\nimport time\r\nimport math\r\npygame.init()\r\n\r\nscreen = pygame.display.set_mode((1192,670))\r\nclock = pygame.time.Clock()\r\nblack = (0,0,0)\r\nwhite = (255,255,255)\r\nyellow = (255,255,0)\r\ngreen = (0,139,69)\r\nblue = (99,130,255)\r\nred = (238,0,0)\r\nimage0 = pygame.image.load(\"background.png\")\r\nimage1 = pygame.image.load(\"rocket.png\")\r\nimage2 = pygame.image.load(\"tank1_0.png\")\r\nimage3 = pygame.image.load(\"tank1_15.png\")\r\nimage4 = pygame.image.load(\"tank1_30.png\")\r\nimage5 = pygame.image.load(\"tank1_45.png\")\r\nimage6 = pygame.image.load(\"tank1_60.png\")\r\nimage7 = pygame.image.load(\"tank1_75.png\")\r\nimage8 = pygame.image.load(\"tank1_90.png\")\r\nimage9 = pygame.image.load(\"tank_explosion.png\")\r\nimage10 = pygame.image.load(\"tank2_0.png\")\r\nimage11 = pygame.image.load(\"tank2_15.png\")\r\nimage12 = pygame.image.load(\"tank2_30.png\")\r\nimage13 = pygame.image.load(\"tank2_45.png\")\r\nimage14 = pygame.image.load(\"tank2_60.png\")\r\nimage15 = pygame.image.load(\"tank2_75.png\")\r\nimage16 = pygame.image.load(\"tank2_90.png\")\r\npygame.mixer.music.load(\"bomb.mp3\")\r\n\r\n\r\ndef background():\r\n screen.blit(image0,(0,0))\r\ndef rocket():\r\n screen.blit(image1,(530,365))\r\ndef draw_tank1_0(screen):\r\n screen.blit(image2,(x1, y))\r\ndef draw_tank1_15(screen):\r\n screen.blit(image3,(x1 - 3, y - 9))\r\ndef draw_tank1_30(screen):\r\n screen.blit(image4,(x1 - 3, y - 21))\r\ndef draw_tank1_45(screen):\r\n screen.blit(image5,(x1 - 4, y - 31))\r\ndef draw_tank1_60(screen):\r\n screen.blit(image6,(x1 - 4, y - 39))\r\ndef draw_tank1_75(screen):\r\n screen.blit(image7,(x1 - 7, y - 43))\r\ndef draw_tank1_90(screen):\r\n screen.blit(image8,(x1 - 5, y - 45))\r\n\r\ndef draw_tank1(angle):\r\n if angle < 7.5:\r\n draw_tank1_0(screen)\r\n elif angle >= 7.5 and angle < 22.5:\r\n draw_tank1_15(screen)\r\n elif angle >= 22.5 and angle < 37.5:\r\n draw_tank1_30(screen)\r\n elif angle >= 37.5 and angle < 52.5:\r\n draw_tank1_45(screen)\r\n elif angle >= 52.5 and angle < 67.5:\r\n draw_tank1_60(screen)\r\n elif angle >= 67.5 and angle < 82.5:\r\n draw_tank1_75(screen)\r\n elif angle >= 82.5 and angle <= 90:\r\n draw_tank1_90(screen)\r\n \r\n\r\ndef draw_tank2_0(screen):\r\n screen.blit(image10,(x2, y))\r\ndef draw_tank2_15(screen):\r\n screen.blit(image11,(x2 + 3, y - 9))\r\ndef draw_tank2_30(screen):\r\n screen.blit(image12,(x2 + 2, y - 21))\r\ndef draw_tank2_45(screen):\r\n screen.blit(image13,(x2 + 3, y - 31))\r\ndef draw_tank2_60(screen):\r\n screen.blit(image14,(x2 + 4, y - 39))\r\ndef draw_tank2_75(screen):\r\n screen.blit(image15,(x2 + 7, y - 43))\r\ndef draw_tank2_90(screen):\r\n screen.blit(image16,(x2 + 5, y - 45))\r\n\r\ndef draw_tank2(angle):\r\n if angle < 7.5:\r\n draw_tank2_0(screen)\r\n elif angle >= 7.5 and angle < 22.5:\r\n draw_tank2_15(screen)\r\n elif angle >= 22.5 and angle < 37.5:\r\n draw_tank2_30(screen)\r\n elif angle >= 37.5 and angle < 52.5:\r\n draw_tank2_45(screen)\r\n elif angle >= 52.5 and angle < 67.5:\r\n draw_tank2_60(screen)\r\n elif angle >= 67.5 and angle < 82.5:\r\n draw_tank2_75(screen)\r\n elif angle >= 82.5 and angle <= 90:\r\n draw_tank2_90(screen)\r\n\r\n \r\ndef text_objects(text, font):\r\n textSurface = font.render(text, True, black)\r\n return textSurface, textSurface.get_rect()\r\ndef display_angle(angle):\r\n largeText = pygame.font.Font(\"freesansbold.ttf\",20)\r\n s = \"Angle: \" + str(angle)\r\n TextSurf, TextRect = text_objects(s, largeText)\r\n TextRect.center = (596,40)\r\n screen.blit(TextSurf, TextRect)\r\ndef display_power(power):\r\n largeText = pygame.font.Font(\"freesansbold.ttf\",20)\r\n s = \"Power: \" + str(round(power, 1))\r\n TextSurf, TextRect = text_objects(s, largeText)\r\n TextRect.center = (596,80)\r\n screen.blit(TextSurf, TextRect)\r\ndef display_tank1_hp(tank1_hp):\r\n largeText = pygame.font.Font(\"freesansbold.ttf\",20)\r\n TextSurf, TextRect = text_objects(\"Health\", largeText)\r\n TextRect.center = (83,38)\r\n screen.blit(TextSurf, TextRect)\r\n pygame.draw.rect(screen,green,(50,50,250,20))\r\n lost_hp = 250 - tank1_hp\r\n if tank1_hp < 250:\r\n pygame.draw.rect(screen,red,(50 + tank1_hp,50,lost_hp,20))\r\n\r\ndef display_tank2_hp(tank2_hp):\r\n largeText = pygame.font.Font(\"freesansbold.ttf\",20)\r\n TextSurf, TextRect = text_objects(\"Health\", largeText)\r\n TextRect.center = (925,38)\r\n screen.blit(TextSurf, TextRect)\r\n pygame.draw.rect(screen,green,(892,50,250,20))\r\n lost_hp = 250 - tank2_hp\r\n if tank2_hp < 250:\r\n pygame.draw.rect(screen,red,(892 + tank2_hp,50,lost_hp,20))\r\n\r\ndef check_game_over(tank1_hp, tank2_hp):\r\n if tank1_hp <= 0:\r\n screen.fill(white)\r\n game_over2()\r\n pygame.display.update()\r\n time.sleep(2)\r\n pygame.quit()\r\n quit()\r\n if tank2_hp <= 0:\r\n screen.fill(white)\r\n game_over1()\r\n pygame.display.update()\r\n time.sleep(2)\r\n pygame.quit()\r\n quit()\r\n\r\ndef game_over1():\r\n largeText = pygame.font.Font(\"freesansbold.ttf\",80)\r\n TextSurf, TextRect = text_objects(\"Player 1 Wins\", largeText)\r\n TextRect.center = (596,300)\r\n screen.blit(TextSurf, TextRect)\r\n\r\ndef game_over2():\r\n largeText = pygame.font.Font(\"freesansbold.ttf\",80)\r\n TextSurf, TextRect = text_objects(\"Player 2 Wins\", largeText)\r\n TextRect.center = (596,300)\r\n screen.blit(TextSurf, TextRect)\r\n \r\n \r\n \r\nx1 = 180\r\nx2 = 970\r\ny = 480\r\n\r\nx_change = 0\r\npower_change = 0\r\npower = 5.0\r\n\r\ntank1_hp = 250\r\ntank2_hp = 250\r\n\r\nspeed = 1.5\r\nshoot1 = False\r\nshoot2 = True\r\ndone = False\r\n###############################################################\r\nwhile done == False:\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n shoot1 = True\r\n done = True\r\n\r\n while shoot1 == False:\r\n \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n shoot1 = True\r\n done = True\r\n \r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n x_change = -speed\r\n elif event.key == pygame.K_RIGHT:\r\n x_change = speed\r\n\r\n if event.key == pygame.K_UP:\r\n power_change = +0.04\r\n elif event.key == pygame.K_DOWN:\r\n power_change = -0.04\r\n\r\n else:\r\n x_change = 0\r\n power_change = 0\r\n\r\n mousex1, mousey1 = pygame.mouse.get_pos()\r\n mousex1 -= x1 + 40\r\n mousey1 = (670 - mousey1) - 170\r\n \r\n if mousex1 > 0 and mousey1 > 0:\r\n angle = math.degrees(math.atan(mousey1/mousex1))\r\n angle = round(angle, 1)\r\n elif mousex1 < 0 and mousey1 > 0:\r\n angle = 90.0\r\n elif mousex1 > 0 and mousey1 < 0:\r\n angle = 0.0\r\n \r\n x1 += x_change\r\n power += power_change\r\n if power < 5:\r\n power = 5.0\r\n if power > 8:\r\n power = 8.0\r\n \r\n if x1 < 0:\r\n x1 = 0\r\n if x1 > 430:\r\n x1 = 430\r\n\r\n xpower = 12 * power * math.cos(math.radians(angle))\r\n ypower = 12 * power * math.sin(math.radians(angle))\r\n\r\n \r\n background()\r\n rocket()\r\n draw_tank1(angle)\r\n draw_tank2_0(screen)\r\n\r\n for i in range(1,7):\r\n if i > 1 or power > 6.5:\r\n pygame.draw.rect(screen,(255,0,0),(x1 + 40 + xpower * i, y + 12 + ((3 * i**2) - (ypower * i)),6,6))\r\n p = 1\r\n bally = 0\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_SPACE:\r\n \r\n while bally <= y + 25:\r\n \r\n ballx = round(x1 + 40 + (xpower * p))\r\n bally = round(y + 12 + ((3 * p**2) - (ypower * p)))\r\n \r\n background()\r\n rocket()\r\n draw_tank1(angle)\r\n draw_tank2_0(screen)\r\n display_tank1_hp(tank1_hp)\r\n display_tank2_hp(tank2_hp)\r\n pygame.draw.circle(screen, blue, (ballx, bally),5)\r\n pygame.display.update()\r\n p += 0.2\r\n time.sleep(0.002)\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n shoot1 = True\r\n done = True\r\n break\r\n break\r\n if ballx > 550 and ballx < 600 and bally > 360:\r\n break\r\n \r\n \r\n screen.blit(image9, (ballx - 35, bally - 30))\r\n pygame.mixer.music.play(0)\r\n time.sleep(0.2)\r\n pygame.display.update()\r\n time.sleep(0.6)\r\n for i in range(-50,50):\r\n if x1 + i == ballx - 35:\r\n tank1_hp -= 50\r\n if x2 + i == ballx - 35:\r\n tank2_hp -= 50\r\n \r\n shoot1 = True\r\n shoot2 = False\r\n \r\n \r\n \r\n \r\n display_angle(angle)\r\n display_power(power)\r\n display_tank1_hp(tank1_hp)\r\n display_tank2_hp(tank2_hp)\r\n pygame.display.update()\r\n check_game_over(tank1_hp, tank2_hp)\r\n clock.tick(60)\r\n\r\n#######################################################################\r\n\r\n\r\n while shoot2 == False:\r\n \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n shoot1 = True\r\n done = True\r\n \r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n x_change = -speed\r\n elif event.key == pygame.K_RIGHT:\r\n x_change = speed\r\n\r\n if event.key == pygame.K_UP:\r\n power_change = +0.04\r\n elif event.key == pygame.K_DOWN:\r\n power_change = -0.04\r\n\r\n else:\r\n x_change = 0\r\n power_change = 0\r\n\r\n mousex2, mousey1 = pygame.mouse.get_pos()\r\n mousex2 -= x2 + 40\r\n mousex2 = 0 - mousex2\r\n mousey1 = (670 - mousey1) - 170\r\n\r\n \r\n \r\n \r\n if mousex2 > 0 and mousey1 > 0:\r\n angle = math.degrees(math.atan(mousey1/mousex2))\r\n angle = round(angle, 1)\r\n elif mousex2 < 0 and mousey1 > 0:\r\n angle = 90.0\r\n elif mousex2 > 0 and mousey1 < 0:\r\n angle = 0.0\r\n \r\n x2 += x_change\r\n power += power_change\r\n if power < 5:\r\n power = 5.0\r\n if power > 8:\r\n power = 8.0\r\n \r\n if x2 < 620:\r\n x2 = 620\r\n if x2 > 1090:\r\n x2 = 1090\r\n\r\n xpower = -12 * power * math.cos(math.radians(angle))\r\n ypower = 12 * power * math.sin(math.radians(angle))\r\n\r\n \r\n background()\r\n rocket()\r\n draw_tank1_0(screen)\r\n draw_tank2(angle)\r\n\r\n for i in range(1,7):\r\n if i > 1 or power > 6.5:\r\n pygame.draw.rect(screen,(255,0,0),(x2 + 55 + xpower * i, y + 12 + ((3 * i**2) - (ypower * i)),6,6))\r\n p = 1\r\n bally = 0\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_SPACE:\r\n \r\n while bally <= y + 25:\r\n \r\n ballx = round(x2 + 40 + (xpower * p))\r\n bally = round(y + 12 + ((3 * p**2) - (ypower * p)))\r\n \r\n background()\r\n rocket()\r\n draw_tank2(angle)\r\n draw_tank1_0(screen)\r\n display_tank1_hp(tank1_hp)\r\n display_tank2_hp(tank2_hp)\r\n pygame.draw.circle(screen, blue, (ballx, bally),5)\r\n pygame.display.update()\r\n p += 0.2\r\n time.sleep(0.002)\r\n if ballx > 550 and ballx < 600 and bally > 360:\r\n break\r\n \r\n \r\n screen.blit(image9, (ballx - 35, bally - 30))\r\n pygame.mixer.music.play(0)\r\n time.sleep(0.2)\r\n pygame.display.update()\r\n time.sleep(0.6)\r\n for i in range(-60,60):\r\n if x1 + i == ballx - 35:\r\n tank1_hp -= 50\r\n if x2 + i == ballx - 35:\r\n tank2_hp -= 50\r\n \r\n \r\n shoot1 = False\r\n shoot2 = True\r\n \r\n \r\n \r\n display_angle(angle)\r\n display_power(power)\r\n display_tank1_hp(tank1_hp)\r\n display_tank2_hp(tank2_hp)\r\n pygame.display.update()\r\n check_game_over(tank1_hp, tank2_hp)\r\n clock.tick(60)\r\n \r\n \r\n#################################################################################\r\n \r\n\r\npygame.quit()\r\nquit()\r\n\r\n\r\n\r\n","sub_path":"Tank Game.py","file_name":"Tank Game.py","file_ext":"py","file_size_in_byte":13269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"105690702","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: build/bdist.linux-x86_64/egg/bind9_parser/isc_clause_dyndb.py\n# Compiled at: 2019-11-22 14:48:25\n\"\"\"\nFile: isc_clause_dyndb.py\n\nClause: dyndb\n\nTitle: Clause statement for Dynamic Database\n\nDescription:\n\"\"\"\nimport unittest\nfrom pyparsing import Group, Keyword, Word, ZeroOrMore, OneOrMore\nfrom bind9_parser.isc_utils import lbrack, rbrack, semicolon, isc_file_name, quoted_path_name, charset_filename_base\ndyndb_custom_driver_configuration = (lbrack + Word(charset_filename_base + ' \\t\\r\\n/;\"\"\\'')('driver_parameters') + rbrack)(None)\ndyndb_database_name = isc_file_name('db_name')\ndyndb_dynamic_module_name = quoted_path_name('module_filename')\nclause_stmt_dyndb_standalone = (Keyword('dyndb').suppress() + Group(dyndb_database_name - dyndb_dynamic_module_name - dyndb_custom_driver_configuration) + semicolon)('dyndb')\nclause_stmt_dyndb_series = OneOrMore(clause_stmt_dyndb_standalone)('dyndb')\nif __name__ == '__main__':\n unittest.main()","sub_path":"pycfiles/bind9_parser-0.9.8-py2.7/isc_clause_dyndb.py","file_name":"isc_clause_dyndb.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"602674145","text":"\r\nimport os,sys,re\r\ndef cleanExt(ext):\r\n while ext.startswith(\".\"):\r\n ext = ext[1:]\r\n return ext\r\ndef main():\r\n values = [(\"folder\", lux.DIALOG_FOLDER, \"Folder to import from:\", \"D:/tsdmnet/test\"),\r\n (\"output\", lux.DIALOG_FOLDER, \"Folder to outut:\", \"D:/tsdmnet/test\"),\r\n (\"iext\", lux.DIALOG_TEXT, \"Input file format to read:\", \"obj\"),\r\n (\"oext\", lux.DIALOG_TEXT, \"Output image format:\", \"png\"),\r\n (\"width\", lux.DIALOG_INTEGER, \"Output width:\", 1920),\r\n (\"height\", lux.DIALOG_INTEGER, \"Output height:\", 1080),\r\n (\"time\", lux.DIALOG_INTEGER, \"render time second:\", 1),\r\n (\"dis\", lux.DIALOG_INTEGER, \"distance:\", 3),\r\n (\"num\", lux.DIALOG_INTEGER, \"number of image:\", 1)\r\n ]\r\n\r\n opts = lux.getInputDialog(title = \"Render\",\r\n desc = \"Render model\",\r\n values = values)\r\n\r\n\r\n\r\n if not opts: \r\n return\r\n\r\n if len(opts[\"folder\"]) == 0:\r\n raise Exception(\"Folder cannot be empty!\")\r\n fld = opts[\"folder\"]\r\n if len(opts[\"iext\"]) == 0:\r\n raise Exception(\"Input extension cannot be empty!\")\r\n iext = cleanExt(opts[\"iext\"])\r\n reFiles = re.compile(\".*{}\".format(iext))\r\n found = False\r\n for f in os.listdir(fld):\r\n if reFiles.match(f):\r\n found = True\r\n break\r\n if not found:\r\n raise Exception(\"Could not find any input files matching the extension \\\"{}\\\" in \\\"{}\\\"!\"\r\n .format(iext, fld))\r\n\r\n if len(opts[\"oext\"]) == 0:\r\n raise Exception(\"Output extension cannot be empty!\")\r\n oext = cleanExt(opts[\"oext\"])\r\n\r\n width = opts[\"width\"]\r\n height = opts[\"height\"]\r\n time = opts[\"time\"]\r\n num = opts[\"num\"]\r\n output_path = opts['output']\r\n dis = opts[\"dis\"]\r\n idx = 0\r\n env = lux.getActiveEnvironment()\r\n env.setBackgroundColor((255,255,255))\r\n opts = lux.getRenderOptions()\r\n opts.setMaxTimeRendering(time)\r\n\r\n for f in [f for f in os.listdir(fld) if f.endswith(iext)]:\r\n path = fld + '/' + f\r\n opp = lux.getImportOptions()\r\n opp['retain_materials']=True\r\n opp['separate_materials']=True\r\n lux.importFile(path, showOpts = False, opts = opp)\r\n root = lux.getSceneTree()\r\n obj=root.find(name = f[:-4])[0]\r\n lux.setSphericalCamera(90,0,0)\r\n lux.setCameraDistance(dis)\r\n lux.setCameraLookAt(pt=(0,0.45,0))\r\n \r\n \r\n \r\n\r\n lux.renderImage(output_path+\"/\"+f[:-4]+'_'+str(0)+'.png', width = 1920, height = 1080, opts = opts)\r\n for i in range(1,num+1):\r\n mat = luxmath.Matrix().makeIdentity()\r\n mat = mat.rotateAroundAxis(luxmath.Vector((0, 1, 0)), 360/num)\r\n obj.applyTransform(mat)\r\n lux.renderImage(output_path+\"/\"+f[:-4]+'_'+str(i)+'.png', width = 1920, height = 1080, opts = opts)\r\n obj.hide()\r\nmain()\r\n","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"89180095","text":"def tracklist(**kwargs):\n for track in kwargs:\n print(track)\n for album in kwargs[track]:\n print(f\"ALBUM: {album} TRACK: {kwargs[track][album]}\")\n\n\n# tracklist(Woodkid={\"The Golden Age\": \"Run Boy Run\",\n# \"On the Other Side\": \"Samara\"},\n# Cure={\"Disintegration\": \"Lovesong\",\n# \"Wish\": \"Friday I'm in love\"})\n","sub_path":"Problems/Tracklist/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"626843623","text":"import keras\n#from keras.layers import Dense, Conv2D, BatchNormalization, Activation\n#from keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.models import load_model\n\nfrom snapshot import SnapshotCallbackBuilder\nfrom resnet_helper import lr_schedule,resnet_v2,resnet_v1,resnet_block\nimport numpy as np\nimport os\nimport sys\n\ndef prepare_data_for_resnet(substract_pixel_mean):\n # Load the CIFAR10 data.\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n num_classes = 10\n\n # We assume data format \"channels_last\".\n img_rows = x_train.shape[1]\n img_cols = x_train.shape[2]\n channels = x_train.shape[3]\n\n if K.image_data_format() == 'channels_first':\n # this branch is useless\n print(\"channels_first\")\n img_rows = x_train.shape[2]\n img_cols = x_train.shape[3]\n channels = x_train.shape[1]\n x_train = x_train.reshape(x_train.shape[0], channels, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], channels, img_rows, img_cols)\n input_shape = (channels, img_rows, img_cols)\n else:\n img_rows = x_train.shape[1]\n img_cols = x_train.shape[2]\n channels = x_train.shape[3]\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, channels)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, channels)\n input_shape = (img_rows, img_cols, channels)\n\n # Normalize data.\n x_train = x_train.astype('float32') / 255\n x_test = x_test.astype('float32') / 255\n\n # If subtract pixel mean is enabled\n if substract_pixel_mean:\n x_train_mean = np.mean(x_train, axis=0)\n x_train -= x_train_mean\n x_test -= x_train_mean\n\n print('x_train shape:', x_train.shape)\n print(x_train.shape[0], 'train samples')\n print(x_test.shape[0], 'test samples')\n print('y_train shape:', y_train.shape)\n\n # Convert class vectors to binary class matrices.\n y_train = keras.utils.to_categorical(y_train, num_classes)\n y_test = keras.utils.to_categorical(y_test, num_classes)\n return (x_train, y_train), (x_test, y_test), input_shape\n\n# build resnet model\ndef build_resnet(x_train, y_train, x_test, y_test, input_shape, batch_size, epochs, num_classes, n, version, data_augmentation):\n # prepare variables for snapshots ensemble\n # T = epochs\n # M = 3\n # alpha_zero = 0.001\n # snapshot = SnapshotCallbackBuilder(T, M, alpha_zero)\n\n # Computed depth from supplied model parameter n\n depth = n * 6 + 2\n\n # Model name, depth and version\n model_type = 'ResNet%d v%d' % (depth, version)\n\n if version == 2:\n model = resnet_v2(input_shape=input_shape, depth=depth)\n else:\n model = resnet_v1(input_shape=input_shape, depth=depth)\n\n model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=lr_schedule(0)),\n metrics=['accuracy'])\n # model.summary()\n # print(model_type)\n\n # Prepare model model saving directory.\n save_dir = os.path.join(os.getcwd(), 'saved_models')\n model_name = 'cifar10_resnet_model.{epoch:02d}.h5'\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n filepath = os.path.join(save_dir, model_name)\n # filepath = model_type + \"-{epoch:02d}-{val_acc:.2f}.hdf5\"\n checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True)\n\n # Prepare callbacks for model saving and for learning rate adjustment.\n checkpoint = ModelCheckpoint(filepath=filepath,\n monitor='val_acc',\n verbose=1,\n save_best_only=True)\n lr_scheduler = LearningRateScheduler(lr_schedule)\n\n lr_reducer = ReduceLROnPlateau(factor=np.sqrt(0.1),\n cooldown=0,\n patience=5,\n min_lr=0.5e-6)\n\n callbacks = [checkpoint, lr_reducer, lr_scheduler]\n\n # callbacks = snapshot.get_callbacks(model_prefix=\"ResNet-snap-\") # try snapshot callback\n\n # Run training, with or without data augmentation.\n if not data_augmentation:\n print('Not using data augmentation.')\n history = model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=(x_test, y_test),\n shuffle=True,\n callbacks=callbacks)\n else:\n print('Using real-time data augmentation.')\n # This will do preprocessing and realtime data augmentation:\n datagen = ImageDataGenerator(\n # set input mean to 0 over the dataset\n featurewise_center=False,\n # set each sample mean to 0\n samplewise_center=False,\n # divide inputs by std of dataset\n featurewise_std_normalization=False,\n # divide each input by its std\n samplewise_std_normalization=False,\n # apply ZCA whitening\n zca_whitening=False,\n # randomly rotate images in the range (deg 0 to 180)\n rotation_range=0,\n # randomly shift images horizontally\n width_shift_range=0.1,\n # randomly shift images vertically\n height_shift_range=0.1,\n # randomly flip images\n horizontal_flip=True,\n # randomly flip images\n vertical_flip=False)\n\n # Compute quantities required for featurewise normalization\n # (std, mean, and principal components if ZCA whitening is applied).\n datagen.fit(x_train)\n\n # Fit the model on the batches generated by datagen.flow().\n steps_per_epoch = int(np.ceil(x_train.shape[0] / float(batch_size)))\n history = model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size),\n steps_per_epoch=steps_per_epoch,\n validation_data=(x_test, y_test),\n epochs=epochs, verbose=1, workers=4,\n callbacks=callbacks)\n\n '''\n # Score trained model.\n scores = model.evaluate(x_test, y_test, verbose=1)\n # model.predict_proba(x_test).shape\n print('Test loss:', scores[0])\n print('Test accuracy:', scores[1])\n '''\n return model, history\n\ndef load_saved_resnet_model(filename):\n model = load_model(filename)\n return model\n\ndef evaluate_resnet_model(model, x_test, y_test, verbose=1):\n # Score trained model.\n scores = model.evaluate(x_test, y_test, verbose=1)\n # model.predict_proba(x_test).shape\n print('Test loss:', scores[0])\n print('Test accuracy:', scores[1])\n\n# Model parameter\n# ----------------------------------------------------------------------------\n# | | 200-epoch | Orig Paper| 200-epoch | Orig Paper| sec/epoch\n# Model | n | ResNet v1 | ResNet v1 | ResNet v2 | ResNet v2 | GTX1080Ti (GTX960)\n# | | %Accuracy | %Accuracy | %Accuracy | %Accuracy | v1 (v2) v1 (v2)\n# ----------------------------------------------------------------------------\n# ResNet20 | 3 | 92.16 | 91.25 | ----- | NA | 35 72 (105)\n# ResNet32 | 5 | 92.46 | 92.49 | ----- | NA | 50\n# ResNet44 | 7 | 92.50 | 92.83 | ----- | NA | 70\n# ResNet56 | 9 | 92.71 | 93.03 | 92.60 | NA | 90 (100)\n# ResNet110 | 18 | 92.65 | 93.39 | 93.03 | 93.63 | 165(180)\n# ---------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n # Training parameters\n batch_size = 64\n epochs = 2\n data_augmentation = True\n num_classes = 10\n\n # Subtracting pixel mean improves accuracy\n n = 3\n\n # Model version\n # Orig paper: version = 1 (ResNet v1), Improved ResNet: version = 2 (ResNet v2)\n version = 1\n substract_pixel_mean = True\n (x_train, y_train), (x_test, y_test), input_shape = prepare_data_for_resnet(substract_pixel_mean)\n # model = build_resnet(x_train, y_train, x_test, y_test, input_shape, batch_size, epochs, num_classes, n, version, data_augmentation)\n # filename = \"saved_models/cifar10_resnet_model.01.h5\"\n # filename = \"weights/ResNet-snap--6.h5\"\n # model = load_saved_resnet_model(filename)\n # evaluate_resnet_model(model, x_test, y_test)\n","sub_path":"cifar10_resnet/ensemble/saved_models/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":8631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"418671489","text":"import json\nimport tempfile\nfrom io import BytesIO\nfrom typing import List, Dict, Union\nfrom unittest import skip\n\nimport pandas as pd\nfrom libumccr import libgdrive\nfrom libumccr.aws import libssm\nfrom mockito import when\n\nfrom data_portal.models.limsrow import LIMSRow\nfrom data_processors import const\nfrom data_processors.lims.lambdas import google_lims\nfrom data_processors.lims.services import google_lims_srv\nfrom data_processors.lims.tests.case import LimsUnitTestCase, LimsIntegrationTestCase, logger\n\n# columns in LIMS CSV\nlims_csv_columns = [\n 'IlluminaID', 'Run', 'Timestamp', 'SubjectID', 'SampleID', 'LibraryID',\n 'ExternalSubjectID', 'ExternalSampleID', 'ExternalLibraryID', 'SampleName',\n 'ProjectOwner', 'ProjectName', 'Type', 'Assay', 'Phenotype', 'Source',\n 'Quality', 'Topup', 'SecondaryAnalysis', 'FASTQ', 'NumberFASTQS', 'Results', 'Trello', 'Notes', 'ToDo'\n]\n\n_mock_lims_sheet_content = b\"\"\"\nIlluminaID,Run,Timestamp,SubjectID,SampleID,LibraryID,ExternalSubjectID,ExternalSampleID,ExternalLibraryID,SampleName,ProjectOwner,ProjectName,ProjectCustodian,Type,Assay,OverrideCycles,Phenotype,Source,Quality,Topup,SecondaryAnalysis,Workflow,Tags,FASTQ,NumberFASTQS,Results,Trello,Notes,ToDo\n210331_A01052_0041_ABCDEFGHIJ,41,2021-03-31,SBJ00001,PRJ000001,L0000001,EXTS001,EXT099999-DNAD001-T,-,PRJ000001-EXT099999-DNAD001-T,UMCCR,CUP,John Doe ,WGS,TsqNano,Y151;I8;I8;Y151,tumor,FFPE,borderline,-,wgs_40,clinical,-,s3://fastq-bucket/Folder/Project/Sample/L2100220*.fastq.gz,2,s3://primary-bucket/project/SBJ00001/WGS/2021-04-08/ ,-,-,FALSE\n\"\"\"\n\n\ndef _generate_lims_csv_row_dict(id: str) -> dict:\n \"\"\"\n Generate LIMS csv row dict\n :param id: id of the row, to make this row distinguishable\n :return: row dict\n \"\"\"\n row = dict()\n for col in lims_csv_columns:\n if col == 'Run':\n row[col] = '1'\n elif col == 'Timestamp':\n row[col] = '2019-01-01'\n else:\n # Normal columns, just use column name as value + id\n row[col] = col + id\n return row\n\n\ndef _generate_lims_csv(rows: List[Dict[str, str]]):\n csv_data = ','.join(lims_csv_columns) + '\\n' # Generate header row\n\n for row in rows:\n csv_data += ','.join(row.values()) + '\\n'\n\n return csv_data\n\n\ndef _df(b: Union[bytes, BytesIO]):\n return pd.read_csv(b, dtype=str)\n\n\nclass LimsUnitTests(LimsUnitTestCase):\n\n def setUp(self) -> None:\n super(LimsUnitTests, self).setUp()\n\n def tearDown(self) -> None:\n super(LimsUnitTests, self).tearDown() # parent tear down should call last\n\n def test_scheduled_update_handler(self):\n \"\"\"\n python manage.py test data_processors.lims.lambdas.tests.test_google_lims.LimsUnitTests.test_scheduled_update_handler\n \"\"\"\n\n mock_lims_sheet = tempfile.NamedTemporaryFile(suffix='.csv', delete=True) # delete=False keep file in tmp dir\n mock_lims_sheet.write(_mock_lims_sheet_content.lstrip().rstrip())\n mock_lims_sheet.seek(0)\n mock_lims_sheet.flush()\n\n # print csv file in tmp dir -- if delete=False, you can see the mock csv content\n logger.info(f\"Path to mock lims sheet: {mock_lims_sheet.name}\")\n\n when(google_lims.libgdrive).download_sheet(...).thenReturn(_df(mock_lims_sheet))\n\n result = google_lims.scheduled_update_handler({'event': \"mock lims update event\"}, None)\n\n logger.info(\"-\" * 32)\n logger.info(\"Example google_lims.scheduled_update_handler lambda output:\")\n logger.info(json.dumps(result))\n self.assertEqual(result['lims_row_new_count'], 1)\n\n sbj = LIMSRow.objects.get(subject_id='SBJ00001')\n logger.info(sbj)\n self.assertIsNotNone(sbj)\n\n # clean up\n mock_lims_sheet.close()\n\n def test_lims_rewrite(self) -> None:\n \"\"\"\n python manage.py test data_processors.lims.lambdas.tests.test_google_lims.LimsUnitTests.test_lims_rewrite\n \"\"\"\n subject_id = 'subject_id'\n sample_id = 'sample_id'\n\n row_1 = _generate_lims_csv_row_dict('1')\n row_1['SampleID'] = sample_id\n row_1['SubjectID'] = subject_id\n\n process_results = google_lims_srv.persist_lims_data(_df(BytesIO(_generate_lims_csv([row_1]).encode())), True)\n\n self.assertEqual(process_results['lims_row_new_count'], 1)\n self.assertEqual(LIMSRow.objects.get(illumina_id='IlluminaID1', sample_id=sample_id).results, row_1['Results'])\n self.assertEqual(process_results['lims_row_update_count'], 0)\n\n def test_lims_update(self) -> None:\n \"\"\"\n python manage.py test data_processors.lims.lambdas.tests.test_google_lims.LimsUnitTests.test_lims_update\n \"\"\"\n row_1 = _generate_lims_csv_row_dict('1')\n google_lims_srv.persist_lims_data(_df(BytesIO(_generate_lims_csv([row_1]).encode())))\n\n new_results = 'NewResults'\n row_1['Results'] = new_results\n row_2 = _generate_lims_csv_row_dict('2')\n process_results = google_lims_srv.persist_lims_data(_df(BytesIO(_generate_lims_csv([row_1, row_2]).encode())))\n\n self.assertEqual(process_results['lims_row_new_count'], 1)\n self.assertEqual(process_results['lims_row_update_count'], 1)\n self.assertEqual(LIMSRow.objects.get(illumina_id='IlluminaID1', sample_id='SampleID1').results, new_results)\n\n def test_lims_row_duplicate(self) -> None:\n \"\"\"\n python manage.py test data_processors.lims.lambdas.tests.test_google_lims.LimsUnitTests.test_lims_row_duplicate\n \"\"\"\n row_duplicate = _generate_lims_csv_row_dict('3')\n process_results = google_lims_srv.persist_lims_data(_df(BytesIO(\n _generate_lims_csv([row_duplicate, row_duplicate]).encode()\n )))\n self.assertEqual(process_results['lims_row_invalid_count'], 1)\n\n def test_lims_non_nullable_columns(self) -> None:\n \"\"\"\n python manage.py test data_processors.lims.lambdas.tests.test_google_lims.LimsUnitTests.test_lims_non_nullable_columns\n\n Test to process non-nullable columns and rollback if one row doesn't have the required values\n \"\"\"\n row_1 = _generate_lims_csv_row_dict('1')\n row_2 = _generate_lims_csv_row_dict('2')\n\n # Use blank values for all non-nullable fields\n row_1['IlluminaID'] = '-'\n row_1['Run'] = '-'\n row_1['Timestamp'] = '-'\n row_1['SampleID'] = '-'\n row_1['LibraryID'] = '-'\n\n process_results = google_lims_srv.persist_lims_data(_df(BytesIO(_generate_lims_csv([row_1, row_2]).encode())))\n\n self.assertEqual(LIMSRow.objects.count(), 1)\n self.assertEqual(process_results['lims_row_new_count'], 1)\n self.assertEqual(process_results['lims_row_invalid_count'], 1)\n\n def test_lims_empty_subject_id(self) -> None:\n \"\"\"\n python manage.py test data_processors.lims.lambdas.tests.test_google_lims.LimsUnitTests.test_lims_empty_subject_id\n\n Test LIMS row with empty SubjectID\n \"\"\"\n row_1 = _generate_lims_csv_row_dict('1')\n\n row_1['SubjectID'] = '-'\n process_results = google_lims_srv.persist_lims_data(_df(BytesIO(_generate_lims_csv([row_1]).encode())))\n\n self.assertEqual(LIMSRow.objects.count(), 1)\n self.assertEqual(process_results['lims_row_new_count'], 1)\n\n\nclass LimsIntegrationTests(LimsIntegrationTestCase):\n # some test case to hit actual API endpoint\n # annotate @skip to make the test cast to run through manual mean\n\n @skip\n def test_scheduled_update_handler(self):\n \"\"\"\n python manage.py test data_processors.lims.lambdas.tests.test_google_lims.LimsIntegrationTests.test_scheduled_update_handler\n \"\"\"\n result = google_lims.scheduled_update_handler({'event': \"LimsIntegrationTests lims update event\"}, None)\n\n logger.info(\"-\" * 32)\n logger.info(\"Example google_lims.scheduled_update_handler lambda output:\")\n logger.info(json.dumps(result))\n self.assertGreater(result['lims_row_new_count'], 1)\n\n logger.info(f\"Total ingested rows into test db: {LIMSRow.objects.count()}\")\n\n @skip\n def test_scheduled_update_handler_crlf(self):\n \"\"\"\n python manage.py test data_processors.lims.lambdas.tests.test_google_lims.LimsIntegrationTests.test_scheduled_update_handler_crlf\n\n See https://github.com/umccr/data-portal-apis/issues/395\n \"\"\"\n\n lims_sheet_id = \"1EgqIxmoJxjmxuaBJP0NpRVJgUtPesON6knVXqQDSUMA\" # Google Sheet with a cell having Windows CRLF\n account_info = libssm.get_secret(const.GDRIVE_SERVICE_ACCOUNT)\n\n # bytes_data = libgdrive.download_sheet1_csv(account_info, lims_sheet_id)\n # with open(\"lims_mock.csv\", \"wb\") as out:\n # out.write(bytes_data)\n # result = google_lims_srv.persist_lims_data(BytesIO(bytes_data))\n\n df: pd.DataFrame = libgdrive.download_sheet(account_info, lims_sheet_id, \"Sheet1\")\n # df.to_csv(\"lims_mock2.csv\", index=False)\n # result = google_lims_srv.persist_lims_data(BytesIO(df.to_csv().encode()))\n result = google_lims_srv.persist_lims_data(df)\n\n logger.info(\"-\" * 32)\n logger.info(\"Example google_lims.scheduled_update_handler lambda output:\")\n logger.info(json.dumps(result))\n self.assertEqual(result['lims_row_new_count'], 3)\n\n logger.info(f\"Total ingested rows into test db: {LIMSRow.objects.count()}\")\n\n lib_79 = LIMSRow.objects.get(library_id='L2200079')\n logger.info(lib_79)\n logger.info(lib_79.external_subject_id)\n logger.info(lib_79.project_owner)\n self.assertIsNotNone(lib_79.external_subject_id)\n self.assertIsNotNone(lib_79.project_owner)\n","sub_path":"data_processors/lims/lambdas/tests/test_google_lims.py","file_name":"test_google_lims.py","file_ext":"py","file_size_in_byte":9700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"443662538","text":"\"\"\"\nAuthor: Travis Hammond\nVersion: 12_23_2019\n\"\"\"\n\n\nimport os\nimport datetime\nimport numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras.models import model_from_json\n\ntry:\n from utils.neural_network import (\n Trainner, Predictor, dense, conv2d, conv1d\n )\n from utils.util_funcs import (\n load_directory_dataset, load_h5py\n )\nexcept ImportError:\n from neural_network import (\n Trainner, Predictor, dense, conv2d, conv1d\n )\n from util_funcs import (\n load_directory_dataset, load_h5py\n )\n\n\nclass AutoencoderTrainner(Trainner):\n \"\"\"AutoencoderTrainner is used for loading, saving,\n and training keras autoencoder models.\n \"\"\"\n\n def __init__(self, model, data, file_loader=None,\n encoder_model=None, decoder_model=None):\n \"\"\"Initializes train, validation, and test data.\n params:\n model: A compiled full keras model\n data: A dictionary or string (path) containg train data,\n and optionally validation and test data.\n Ex. {'train_x': [...], 'validation_x: [...]}\n file_loader: A function for loading each file\n encoder_model: The encoder part of the full model\n decoder_model: The decoder part of the full model\n \"\"\"\n assert isinstance(data, (str, dict)), (\n 'data must be either in a dictionary or a file/folder path'\n )\n self.model = model\n self.encoder_model = encoder_model\n self.decoder_model = decoder_model\n self.train_data = None\n self.validation_data = None\n self.test_data = None\n\n if isinstance(data, str):\n if os.path.isdir(data):\n assert file_loader is not None\n data = load_directory_dataset(data, file_loader)\n else:\n assert data.split('.')[1] == 'h5'\n data = load_h5py(data)\n if isinstance(data, dict):\n if 'train_x' in data:\n self.train_data = data['train_x']\n self.train_data = (self.train_data, self.train_data)\n else:\n raise Exception('There must be a train dataset')\n if 'validation_x' in data:\n self.validation_data = data['validation_x']\n self.validation_data = (self.validation_data,\n self.validation_data)\n if 'test_x' in data:\n self.test_data = data['test_x']\n self.test_data = (self.test_data, self.test_data)\n else:\n raise ValueError('Invalid data')\n\n def train(self, epochs, batch_size=None, callbacks=None, verbose=True):\n \"\"\"Trains the keras model.\n params:\n epochs: An integer, which is the number of complete\n iterations to train\n batch_size: An integer, which is the number of samples\n per graident update\n callbacks: A list of keras Callback instances,\n which are called during training and validation\n verbose: A boolean, which determines the verbositiy level\n \"\"\"\n super().train(epochs, batch_size, callbacks, verbose)\n weights = self.model.get_weights()\n if self.encoder_model is not None:\n encoder_num_weights = len(self.encoder_model.get_weights())\n self.encoder_model.set_weights(weights[:encoder_num_weights])\n if self.decoder_model is not None:\n decoder_num_weights = len(self.decoder_model.get_weights())\n self.decoder_model.set_weights(weights[-decoder_num_weights:])\n\n def load(self, path, optimizer, loss, metrics=None):\n \"\"\"Loads a model and weights from a file.\n (overrides the inital provided model)\n params:\n path: A string, which is the path to a folder\n containing model.json, weights.h5, note.txt\n and maybe encoder/decoder parts\n optimizer: A string or optimizer instance, which will be\n the optimizer for the loaded model\n loss: A string or loss instance, which will be\n the loss function for the loaded model\n metrics: A list of metrics, which will be used\n by the loaded model\n \"\"\"\n super().load(path, optimizer, loss)\n if 'encoder_model.json' in os.listdir(path):\n with open(os.path.join(path, 'encoder_model.json'), 'r') as file:\n self.encoder_model = model_from_json(file.read())\n self.encoder_model.compile(optimizer=optimizer, loss=loss,\n metrics=metrics)\n self.encoder_model.load_weights(\n os.path.join(path, 'encoder_weights.h5')\n )\n if 'decoder_model.json' in os.listdir(path):\n with open(os.path.join(path, 'decoder_model.json'), 'r') as file:\n self.decoder_model = model_from_json(file.read())\n self.decoder_model.compile(optimizer=optimizer, loss=loss)\n self.decoder_model.load_weights(\n os.path.join(path, 'decoder_weights.h5')\n )\n\n def save(self, path, note=None):\n \"\"\"Saves the model and weights to a file.\n params:\n path: A string, which is the path to create a folder in\n containing model.json, weights.h5, note.txt, and\n maybe encoder/decoder parts\n return: A string, which is the given path + folder name\n \"\"\"\n time = datetime.datetime.now()\n path = os.path.join(path, time.strftime(r'%Y%m%d_%H%M%S_%f'))\n os.mkdir(path)\n self.model.save_weights(os.path.join(path, 'weights.h5'))\n with open(os.path.join(path, 'model.json'), 'w') as file:\n file.write(self.model.to_json())\n if self.encoder_model is not None:\n self.encoder_model.save_weights(\n os.path.join(path, 'encoder_weights.h5')\n )\n with open(os.path.join(path, 'encoder_model.json'), 'w') as file:\n file.write(self.encoder_model.to_json())\n if self.decoder_model is not None:\n self.decoder_model.save_weights(\n os.path.join(path, 'decoder_weights.h5')\n )\n with open(os.path.join(path, 'decoder_model.json'), 'w') as file:\n file.write(self.decoder_model.to_json())\n with open(os.path.join(path, 'note.txt'), 'w') as file:\n if note is None:\n self.model.summary(\n print_fn=lambda line: file.write(line+'\\n')\n )\n else:\n file.write(note)\n return path\n\n\nclass AutoencoderPredictor(Predictor):\n \"\"\"AutoenocderPredictor is used for loading and predicting keras models.\"\"\"\n\n def __init__(self, path, uses_encoder_model=False,\n uses_decoder_model=False):\n \"\"\"Initializes the model and weights.\n params:\n path: A string, which is the path to a folder containing\n model.json, weights.h5, note.txt, and maybe encoder/decoder\n parts\n uses_encoder_model: A boolean, which determines if encoder model\n should be used for predictions\n (cannot also enable uses_decoder_model)\n uses_decoder_model: A boolean, which determines if decoder model\n should be used for predictions\n (cannot also enable uses_encoder_model)\n \"\"\"\n if uses_encoder_model:\n super().__init__(path, 'encoder_weights.h5',\n 'encoder_model.json')\n elif uses_decoder_model:\n super().__init__(path, 'decoder_weights.h5',\n 'decoder_model.json')\n else:\n super().__init__(path)\n\n\ndef create_basic_dense_model(input_shape, units_list,\n activation='relu',\n output_activation='sigmoid',\n dropout=0, batch_norm=True,\n encoder_output_activation=None,\n encoder_output_batch_norm=None):\n \"\"\"Creates a basic dense model for mainly testing purposes.\n params:\n input_shape: A tuple of integers, which is the expected input shape\n units_list: A list of integers, which are the dimensionality of the\n output space\n activation: A string or keras/TF activation function\n output_activation: A string or keras/TF activation function\n dropout: A float, which is the dropout rate between inputs and\n first dense layer\n batch_norm: A boolean, which determines if batch\n normalization is enabled\n encoder_output_activation: A string or keras/TF activation function\n encoder_output_batch_norm: A boolean, which determines if batch\n normalization is enabled for the encoder\n output\n return: A tuple of the full model, the encoder model, and decoder model\n uncompiled\n \"\"\"\n if encoder_output_activation is None:\n encoder_output_activation = activation\n\n if encoder_output_batch_norm is None:\n encoder_output_batch_norm = batch_norm\n\n inputs = keras.layers.Input(shape=input_shape)\n x = inputs\n if len(input_shape) > 1:\n x = keras.layers.Flatten()(x)\n if dropout > 0:\n x = keras.layers.Dropout(dropout)(x)\n for units in units_list[:-1]:\n x = dense(units, activation=activation, batch_norm=batch_norm)(x)\n x = dense(units_list[-1], activation=encoder_output_activation,\n batch_norm=encoder_output_batch_norm)(x)\n encoder_model = keras.Model(inputs=inputs, outputs=x)\n decoder_inputs = keras.layers.Input(shape=(units_list[-1],))\n decoder_start_ndx = len(encoder_model.layers)\n for units in reversed(units_list):\n x = dense(units, activation=activation, batch_norm=batch_norm)(x)\n if len(input_shape) > 1:\n outputs = dense(np.prod(input_shape), activation=output_activation,\n batch_norm=False)(x)\n outputs = keras.layers.Reshape(input_shape)(outputs)\n else:\n outputs = dense(input_shape[0], activation=output_activation,\n batch_norm=False)(x)\n model = keras.Model(inputs=inputs, outputs=outputs)\n x = decoder_inputs\n for layer in model.layers[decoder_start_ndx:]:\n x = layer(x)\n decoder_model = keras.Model(inputs=decoder_inputs, outputs=x)\n return model, encoder_model, decoder_model\n\n\ndef create_basic_conv2d_model(input_shape, filters_list, kernel_sizes,\n max_pools, activation='relu',\n output_activation='sigmoid',\n dropout=0, batch_norm=True,\n encoder_output_activation=None,\n encoder_output_batch_norm=None):\n \"\"\"Creates a basic 2D convolution model for mainly testing purposes.\n params:\n input_shape: A tuple of integers, which is the expected input shape\n filters_list: A list of integers, which are the dimensionality of the\n output space\n kernel_sizes: An integer or tuple of 2 integers, which is the size of\n the convoluition kernel\n max_pools: A list of integers or tuples, which are the size of the\n pooling windows\n activation: A string or keras/TF activation function\n output_activation: A string or keras/TF activation function\n dropout: A float, which is the dropout rate between inputs and\n first dense layer\n batch_norm: A boolean, which determines if batch\n normalization is enabled\n encoder_output_activation: A string or keras/TF activation function\n encoder_output_batch_norm: A boolean, which determines if batch\n normalization is enabled for the encoder\n output\n return: A tuple of the full model, the encoder model, and decoder model\n uncompiled\n \"\"\"\n if encoder_output_activation is None:\n encoder_output_activation = activation\n if encoder_output_batch_norm is None:\n encoder_output_batch_norm = batch_norm\n inputs = keras.layers.Input(shape=input_shape)\n x = inputs\n if dropout > 0:\n x = keras.layers.Dropout(dropout)(x)\n for ndx in range(len(filters_list)-1):\n x = conv2d(filters_list[ndx], kernel_sizes[ndx], activation=activation,\n max_pool_size=max_pools[ndx], batch_norm=batch_norm)(x)\n x = conv2d(filters_list[-1], kernel_sizes[-1],\n activation=encoder_output_activation,\n max_pool_size=max_pools[-1],\n batch_norm=encoder_output_batch_norm)(x)\n encoder_model = keras.Model(inputs=inputs, outputs=x)\n decoder_inputs = keras.layers.Input(shape=[y for y in x.shape[1:]])\n decoder_start_ndx = len(encoder_model.layers)\n for ndx in reversed(range(len(filters_list))):\n x = conv2d(filters_list[ndx], kernel_sizes[ndx], activation=activation,\n batch_norm=batch_norm, upsampling_size=max_pools[ndx])(x)\n outputs = conv2d(input_shape[-1], activation=output_activation,\n batch_norm=False)(x)\n model = keras.Model(inputs=inputs, outputs=outputs)\n x = decoder_inputs\n for layer in model.layers[decoder_start_ndx:]:\n x = layer(x)\n decoder_model = keras.Model(inputs=decoder_inputs, outputs=x)\n return model, encoder_model, decoder_model\n\n\ndef create_basic_conv1d_model(input_shape, filters_list, kernel_sizes,\n max_pools, activation='relu',\n output_activation='sigmoid',\n dropout=0, batch_norm=True,\n encoder_output_activation=None,\n encoder_output_batch_norm=None):\n \"\"\"Creates a basic 1D convolution model for mainly testing purposes.\n params:\n input_shape: A tuple of integers, which is the expected input shape\n filters_list: A list of integers, which are the dimensionality of the\n output space\n kernel_sizes: An integer or tuple of 1 integers, which is the size of\n the convoluition kernel\n max_pools: A list of integers or tuples, which are the size of the\n pooling windows\n activation: A string or keras/TF activation function\n output_activation: A string or keras/TF activation function\n dropout: A float, which is the dropout rate between inputs and\n first dense layer\n batch_norm: A boolean, which determines if batch\n normalization is enabled\n encoder_output_activation: A string or keras/TF activation function\n encoder_output_batch_norm: A boolean, which determines if batch\n normalization is enabled for the encoder\n output\n return: A tuple of the full model, the encoder model, and decoder model\n uncompiled\n \"\"\"\n if encoder_output_activation is None:\n encoder_output_activation = activation\n if encoder_output_batch_norm is None:\n encoder_output_batch_norm = batch_norm\n inputs = keras.layers.Input(shape=input_shape)\n x = inputs\n if dropout > 0:\n x = keras.layers.Dropout(dropout)(x)\n for ndx in range(len(filters_list)-1):\n x = conv1d(filters_list[ndx], kernel_sizes[ndx], activation=activation,\n max_pool_size=max_pools[ndx], batch_norm=batch_norm)(x)\n x = conv1d(filters_list[-1], kernel_sizes[-1],\n activation=encoder_output_activation,\n max_pool_size=max_pools[-1],\n batch_norm=encoder_output_batch_norm)(x)\n encoder_model = keras.Model(inputs=inputs, outputs=x)\n decoder_inputs = keras.layers.Input(shape=[y for y in x.shape[1:]])\n decoder_start_ndx = len(encoder_model.layers)\n for ndx in reversed(range(len(filters_list))):\n x = conv1d(filters_list[ndx], kernel_sizes[ndx], activation=activation,\n batch_norm=batch_norm, upsampling_size=max_pools[ndx])(x)\n outputs = conv1d(input_shape[-1], activation=output_activation,\n batch_norm=False)(x)\n model = keras.Model(inputs=inputs, outputs=outputs)\n x = decoder_inputs\n for layer in model.layers[decoder_start_ndx:]:\n x = layer(x)\n decoder_model = keras.Model(inputs=decoder_inputs, outputs=x)\n return model, encoder_model, decoder_model\n\n\nif __name__ == '__main__':\n import image as img\n from time import sleep\n\n training = False\n uses_encoder_model = False\n uses_decoder_model = True\n uses_conv_model = True\n\n (tx, _), (vx, _) = keras.datasets.fashion_mnist.load_data()\n tx2, vx2 = [], []\n # Enlarge so that after downsamping and upsampling\n # the shape will be same as the input shape\n for x in tx:\n tx2.append(img.resize(x, (32, 32)))\n for x in vx:\n vx2.append(img.resize(x, (32, 32)))\n del tx, vx\n tx2 = np.expand_dims(np.array(tx2), axis=-1)\n vx2 = np.expand_dims(np.array(vx2), axis=-1)\n dataset = {'train_x': tx2, 'validation_x': vx2}\n\n path = 'conv_weights' if uses_conv_model else 'dense_weights'\n\n if training:\n if uses_conv_model:\n models = create_basic_conv2d_model(\n (32, 32, 1), [256, 128, 64, 32, 16],\n [3, 3, 3, 3, 3], [2, 2, 2, 2, 2],\n activation='relu', output_activation='linear',\n dropout=0, batch_norm=True,\n encoder_output_activation='sigmoid',\n encoder_output_batch_norm=False\n )\n else:\n models = create_basic_dense_model(\n (32, 32, 1), [512, 256, 128, 64, 32, 16],\n activation='relu', output_activation='linear',\n dropout=0, batch_norm=True,\n encoder_output_activation='sigmoid',\n encoder_output_batch_norm=False\n )\n model, encoder, decoder = models\n model.compile(optimizer=keras.optimizers.Adam(lr=.01, amsgrad=True),\n loss='mse')\n model.summary()\n\n trainner = AutoencoderTrainner(model, dataset, encoder_model=encoder,\n decoder_model=decoder)\n trainner.train(20, batch_size=32)\n path = trainner.save('')\n\n predictor = AutoencoderPredictor(\n path, uses_encoder_model=uses_encoder_model,\n uses_decoder_model=uses_decoder_model\n )\n\n ws = img.Windows()\n ws.start()\n w = ws.add('Image')\n\n if uses_encoder_model:\n for vx in dataset['validation_x']:\n out = predictor.predict(vx)\n real_img = np.squeeze(vx).astype(np.uint8)\n ws.set(w, real_img)\n print(out.round(3), out.shape)\n sleep(.01)\n elif uses_decoder_model:\n while True:\n shape = predictor.model.layers[0].input_shape[0][1:]\n inputs = np.random.random(shape)\n print(inputs.round(3))\n out = predictor.predict(inputs)\n out_img = np.clip(np.squeeze(out), 0, 255).astype(np.uint8)\n ws.set(w, out_img)\n sleep(.01)\n else:\n for vx in dataset['validation_x']:\n out = predictor.predict(vx)\n out_img = np.clip(np.squeeze(out), 0, 255).astype(np.uint8)\n real_img = np.squeeze(vx).astype(np.uint8)\n ws.set(w, np.hstack((out_img, real_img)))\n sleep(.01)\n\n ws.stop()\n","sub_path":"video11/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":19995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"138749748","text":"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\nfrom abc import ABC, abstractmethod\nfrom mephisto.core.utils import get_dir_for_run\nfrom mephisto.data_model.assignment_state import AssignmentState\nfrom mephisto.data_model.task import TaskRun, Task\nfrom mephisto.data_model.agent import Agent\nfrom mephisto.data_model.blueprint import AgentState\nfrom mephisto.data_model.requester import Requester\nfrom typing import List, Optional, Tuple, Mapping, Dict, Any, Type, TYPE_CHECKING, IO\n\nif TYPE_CHECKING:\n from mephisto.data_model.database import MephistoDB\n from mephisto.data_model.worker import Worker\n from mephisto.data_model.crowd_provider import CrowdProvider\n\nimport os\nimport json\nfrom dataclasses import dataclass\n\n\nASSIGNMENT_DATA_FILE = \"assign_data.json\"\n\n\n@dataclass\nclass InitializationData:\n shared: Dict[str, Any]\n unit_data: List[Dict[str, Any]]\n\n def dumpJSON(self, fp: IO[str]):\n return json.dump({\"shared\": self.shared, \"unit_data\": self.unit_data}, fp)\n\n @staticmethod\n def loadFromJSON(fp: IO[str]):\n as_dict = json.load(fp)\n return InitializationData(\n shared=as_dict[\"shared\"], unit_data=as_dict[\"unit_data\"]\n )\n\n\nclass Assignment:\n \"\"\"\n This class tracks an individual run of a specific task, and handles state management\n for the set of units within via abstracted database helpers\n \"\"\"\n\n def __init__(\n self, db: \"MephistoDB\", db_id: str, row: Optional[Mapping[str, Any]] = None\n ):\n self.db: \"MephistoDB\" = db\n if row is None:\n row = db.get_assignment(db_id)\n assert row is not None, f\"Given db_id {db_id} did not exist in given db\"\n self.db_id: str = row[\"assignment_id\"]\n self.task_run_id = row[\"task_run_id\"]\n self.sandbox = row[\"sandbox\"]\n self.task_id = row[\"task_id\"]\n self.requester_id = row[\"requester_id\"]\n self.task_type = row[\"task_type\"]\n self.provider_type = row[\"provider_type\"]\n\n # Deferred loading of related entities\n self.__task_run: Optional[\"TaskRun\"] = None\n self.__task: Optional[\"Task\"] = None\n self.__requester: Optional[\"Requester\"] = None\n\n def get_data_dir(self) -> str:\n \"\"\"Return the directory we expect to find assignment data in\"\"\"\n task_run = self.get_task_run()\n run_dir = task_run.get_run_dir()\n return os.path.join(run_dir, self.db_id)\n\n def get_assignment_data(self) -> InitializationData:\n \"\"\"Return the specific assignment data for this assignment\"\"\"\n assign_data_filename = os.path.join(self.get_data_dir(), ASSIGNMENT_DATA_FILE)\n assert os.path.exists(assign_data_filename), \"No data exists for assignment\"\n with open(assign_data_filename, \"r\") as json_file:\n return InitializationData.loadFromJSON(json_file)\n\n def write_assignment_data(self, data: InitializationData) -> None:\n \"\"\"Set the assignment data for this assignment\"\"\"\n assign_data_filename = os.path.join(self.get_data_dir(), ASSIGNMENT_DATA_FILE)\n os.makedirs(self.get_data_dir(), exist_ok=True)\n with open(assign_data_filename, \"w+\") as json_file:\n data.dumpJSON(json_file)\n\n def get_agents(self) -> List[Optional[\"Agent\"]]:\n \"\"\"\n Return all of the agents for this assignment\n \"\"\"\n units = self.get_units()\n return [u.get_assigned_agent() for u in units]\n\n def get_status(self) -> str:\n \"\"\"\n Get the status of this assignment, as determined by the status of\n the units\n \"\"\"\n units = self.get_units()\n statuses = set(unit.get_status() for unit in units)\n\n if len(statuses) == 1:\n return statuses.pop()\n\n if len(statuses) == 0:\n return AssignmentState.CREATED\n\n if AssignmentState.CREATED in statuses:\n # TODO(#99) handle the case where new units are created after\n # everything else is launched\n return AssignmentState.CREATED\n\n if any([s == AssignmentState.LAUNCHED for s in statuses]):\n # If any are only launched, consider the whole thing launched\n return AssignmentState.LAUNCHED\n\n if any([s == AssignmentState.ASSIGNED for s in statuses]):\n # If any are still assigned, consider the whole thing assigned\n return AssignmentState.ASSIGNED\n\n if all(\n [\n s in [AssignmentState.ACCEPTED, AssignmentState.REJECTED]\n for s in statuses\n ]\n ):\n return AssignmentState.MIXED\n\n if all([s in AssignmentState.final_agent() for s in statuses]):\n return AssignmentState.COMPLETED\n\n raise NotImplementedError(f\"Unexpected set of unit statuses {statuses}\")\n\n def get_task_run(self) -> TaskRun:\n \"\"\"\n Return the task run that this assignment is part of\n \"\"\"\n if self.__task_run is None:\n self.__task_run = TaskRun(self.db, self.task_run_id)\n return self.__task_run\n\n def get_task(self) -> Task:\n \"\"\"\n Return the task run that this assignment is part of\n \"\"\"\n if self.__task is None:\n if self.__task_run is not None:\n self.__task = self.__task_run.get_task()\n else:\n self.__task = Task(self.db, self.task_id)\n return self.__task\n\n def get_requester(self) -> Requester:\n \"\"\"\n Return the requester who offered this Assignment\n \"\"\"\n if self.__requester is None:\n if self.__task_run is not None:\n self.__requester = self.__task_run.get_requester()\n else:\n self.__requester = Requester(self.db, self.requester_id)\n return self.__requester\n\n def get_units(self, status: Optional[str] = None) -> List[\"Unit\"]:\n \"\"\"\n Get units for this assignment, optionally\n constrained by the specific status.\n \"\"\"\n assert (\n status is None or status in AssignmentState.valid_unit()\n ), \"Invalid assignment status\"\n units = self.db.find_units(assignment_id=self.db_id)\n if status is not None:\n units = [u for u in units if u.get_status() == status]\n return units\n\n def get_workers(self) -> List[\"Worker\"]:\n \"\"\"\n Get the list of workers that have worked on this specific assignment\n \"\"\"\n units = self.get_units()\n pos_agents = [s.get_assigned_agent() for s in units]\n agents = [a for a in pos_agents if a is not None]\n workers = [a.get_worker() for a in agents]\n return workers\n\n def get_cost_of_statuses(self, statuses: List[str]) -> float:\n \"\"\"\n Return the sum of all pay_amounts for every unit\n of this assignment with any of the given statuses\n \"\"\"\n units = [u for u in self.get_units() if u.get_status() in statuses]\n sum_cost = 0.0\n for unit in units:\n sum_cost += unit.get_pay_amount()\n return sum_cost\n\n # TODO(100) add helpers to manage retrieving results as well\n\n @staticmethod\n def new(\n db: \"MephistoDB\", task_run: TaskRun, assignment_data: Optional[Dict[str, Any]]\n ) -> \"Assignment\":\n \"\"\"\n Create an assignment for the given task. Initialize the folders for storing\n the results for this assignment. Can take assignment_data to save and\n load for this particular assignment.\n \"\"\"\n # TODO(101) consider offloading this state management to the MephistoDB\n # as it is data handling and can theoretically be done differently\n # in different implementations\n db_id = db.new_assignment(\n task_run.db_id,\n task_run.requester_id,\n task_run.task_type,\n task_run.provider_type,\n task_run.sandbox,\n )\n run_dir = task_run.get_run_dir()\n assign_dir = os.path.join(run_dir, db_id)\n os.makedirs(assign_dir)\n if assignment_data is not None:\n with open(\n os.path.join(assign_dir, ASSIGNMENT_DATA_FILE), \"w+\"\n ) as json_file:\n json.dump(assignment_data, json_file)\n return Assignment(db, db_id)\n\n\nclass Unit(ABC):\n \"\"\"\n This class tracks the status of an individual worker's contribution to a\n higher level assignment. It is the smallest 'unit' of work to complete\n the assignment, and this class is only responsible for checking\n the status of that work itself being done.\n\n It should be extended for usage with a specific crowd provider\n \"\"\"\n\n def __init__(\n self, db: \"MephistoDB\", db_id: str, row: Optional[Mapping[str, Any]] = None\n ):\n self.db: \"MephistoDB\" = db\n if row is None:\n row = db.get_unit(db_id)\n assert row is not None, f\"Given db_id {db_id} did not exist in given db\"\n self.db_id: str = row[\"unit_id\"]\n self.assignment_id = row[\"assignment_id\"]\n self.unit_index = row[\"unit_index\"]\n self.pay_amount = row[\"pay_amount\"]\n self.agent_id = row[\"agent_id\"]\n self.provider_type = row[\"provider_type\"]\n self.db_status = row[\"status\"]\n self.task_type = row[\"task_type\"]\n self.task_id = row[\"task_id\"]\n self.task_run_id = row[\"task_run_id\"]\n self.sandbox = row[\"sandbox\"]\n self.requester_id = row[\"requester_id\"]\n self.worker_id = row[\"worker_id\"]\n\n # Deferred loading of related entities\n self.__task: Optional[\"Task\"] = None\n self.__task_run: Optional[\"TaskRun\"] = None\n self.__assignment: Optional[\"Assignment\"] = None\n self.__requester: Optional[\"Requester\"] = None\n self.__agent: Optional[\"Agent\"] = None\n self.__worker: Optional[\"Worker\"] = None\n\n def __new__(\n cls, db: \"MephistoDB\", db_id: str, row: Optional[Mapping[str, Any]] = None\n ) -> \"Unit\":\n \"\"\"\n The new method is overridden to be able to automatically generate\n the expected Unit class without needing to specifically find it\n for a given db_id. As such it is impossible to create a Unit\n as you will instead be returned the correct Unit class according to\n the crowdprovider associated with this Unit.\n \"\"\"\n if cls == Unit:\n # We are trying to construct a Unit, find what type to use and\n # create that instead\n from mephisto.core.registry import get_crowd_provider_from_type\n\n if row is None:\n row = db.get_unit(db_id)\n assert row is not None, f\"Given db_id {db_id} did not exist in given db\"\n correct_class = get_crowd_provider_from_type(row[\"provider_type\"]).UnitClass\n return super().__new__(correct_class)\n else:\n # We are constructing another instance directly\n return super().__new__(cls)\n\n def get_crowd_provider_class(self) -> Type[\"CrowdProvider\"]:\n \"\"\"Get the CrowdProvider class that manages this Unit\"\"\"\n from mephisto.core.registry import get_crowd_provider_from_type\n\n return get_crowd_provider_from_type(self.provider_type)\n\n def get_assignment_data(self) -> Optional[Dict[str, Any]]:\n \"\"\"Return the specific assignment data for this assignment\"\"\"\n return self.get_assignment().get_assignment_data()\n\n def sync_status(self) -> None:\n \"\"\"\n Ensure that the queried status from this unit and the db status\n are up to date\n \"\"\"\n # TODO(102) this will need to be run periodically/on crashes\n # to sync any lost state\n self.set_db_status(self.get_status())\n\n def get_db_status(self) -> str:\n \"\"\"\n Return the status as currently stored in the database\n \"\"\"\n if self.db_status in AssignmentState.final_unit():\n return self.db_status\n row = self.db.get_unit(self.db_id)\n assert row is not None, f\"Unit {self.db_id} stopped existing in the db...\"\n return row[\"status\"]\n\n def set_db_status(self, status: str) -> None:\n \"\"\"\n Set the status reflected in the database for this Unit\n \"\"\"\n assert (\n status in AssignmentState.valid_unit()\n ), f\"{status} not valid Assignment Status, not in {AssignmentState.valid_unit()}\"\n self.db_status = status\n self.db.update_unit(self.db_id, status=status)\n\n def get_assignment(self) -> Assignment:\n \"\"\"\n Return the assignment that this Unit is part of.\n \"\"\"\n if self.__assignment is None:\n self.__assignment = Assignment(self.db, self.assignment_id)\n return self.__assignment\n\n def get_task_run(self) -> TaskRun:\n \"\"\"\n Return the task run that this assignment is part of\n \"\"\"\n if self.__task_run is None:\n if self.__assignment is not None:\n self.__task_run = self.__assignment.get_task_run()\n else:\n self.__task_run = TaskRun(self.db, self.task_run_id)\n return self.__task_run\n\n def get_task(self) -> Task:\n \"\"\"\n Return the task that this assignment is part of\n \"\"\"\n if self.__task is None:\n if self.__assignment is not None:\n self.__task = self.__assignment.get_task()\n elif self.__task_run is not None:\n self.__task = self.__task_run.get_task()\n else:\n self.__task = Task(self.db, self.task_id)\n return self.__task\n\n def get_requester(self) -> \"Requester\":\n \"\"\"\n Return the requester who offered this Unit\n \"\"\"\n if self.__requester is None:\n if self.__assignment is not None:\n self.__requester = self.__assignment.get_requester()\n elif self.__task_run is not None:\n self.__requester = self.__task_run.get_requester()\n else:\n self.__requester = Requester(self.db, self.requester_id)\n return self.__requester\n\n def clear_assigned_agent(self) -> None:\n \"\"\"Clear the agent that is assigned to this unit\"\"\"\n self.db.clear_unit_agent_assignment(self.db_id)\n self.agent_id = None\n self.__agent = None\n\n def get_assigned_agent(self) -> Optional[Agent]:\n \"\"\"\n Get the agent assigned to this Unit if there is one, else return None\n \"\"\"\n # In these statuses, we know the agent isn't changing anymore, and thus will\n # not need to be re-queried\n # TODO(#97) add test to ensure this behavior/assumption holds always\n if self.db_status in AssignmentState.final_unit():\n if self.agent_id is None:\n return None\n return Agent(self.db, self.agent_id)\n\n # Query the database to get the most up-to-date assignment, as this can\n # change after instantiation if the Unit status isn't final\n # TODO(#101) this may not be particularly efficient\n row = self.db.get_unit(self.db_id)\n assert row is not None, f\"Unit {self.db_id} stopped existing in the db...\"\n agent_id = row[\"agent_id\"]\n if agent_id is not None:\n return Agent(self.db, agent_id)\n return None\n\n @staticmethod\n def _register_unit(\n db: \"MephistoDB\",\n assignment: Assignment,\n index: int,\n pay_amount: float,\n provider_type: str,\n ) -> \"Unit\":\n \"\"\"\n Create an entry for this unit in the database\n \"\"\"\n db_id = db.new_unit(\n assignment.task_id,\n assignment.task_run_id,\n assignment.requester_id,\n assignment.db_id,\n index,\n pay_amount,\n provider_type,\n assignment.task_type,\n )\n return Unit(db, db_id)\n\n def get_pay_amount(self) -> float:\n \"\"\"\n Return the amount that this Unit is costing against the budget,\n calculating additional fees as relevant\n \"\"\"\n return self.pay_amount\n\n # Children classes may need to override the following\n\n def get_status(self) -> str:\n \"\"\"\n Get the status of this unit, as determined by whether there's\n a worker working on it at the moment, and any other possible states. Should\n return one of UNIT_STATUSES\n\n Accurate status is crowd-provider dependent, and thus this method should be\n defined in the child class to ensure that the local record matches\n the ground truth in the provider\n \"\"\"\n from mephisto.data_model.blueprint import AgentState\n\n db_status = self.db_status\n computed_status = AssignmentState.LAUNCHED\n\n agent = self.get_assigned_agent()\n if agent is None:\n row = self.db.get_unit(self.db_id)\n computed_status = row[\"status\"]\n else:\n agent_status = agent.get_status()\n if agent_status == AgentState.STATUS_NONE:\n computed_status = AssignmentState.LAUNCHED\n elif agent_status in [\n AgentState.STATUS_ACCEPTED,\n AgentState.STATUS_ONBOARDING,\n AgentState.STATUS_PARTNER_DISCONNECT,\n AgentState.STATUS_WAITING,\n AgentState.STATUS_IN_TASK,\n ]:\n computed_status = AssignmentState.ASSIGNED\n elif agent_status in [AgentState.STATUS_COMPLETED]:\n computed_status = AssignmentState.COMPLETED\n elif agent_status in [AgentState.STATUS_SOFT_REJECTED]:\n computed_status = AssignmentState.SOFT_REJECTED\n elif agent_status in [AgentState.STATUS_EXPIRED]:\n computed_status = AssignmentState.EXPIRED\n elif agent_status in [\n AgentState.STATUS_DISCONNECT,\n AgentState.STATUS_RETURNED,\n ]:\n computed_status = AssignmentState.ASSIGNED\n elif agent_status == AgentState.STATUS_APPROVED:\n computed_status = AssignmentState.ACCEPTED\n elif agent_status == AgentState.STATUS_REJECTED:\n computed_status = AssignmentState.REJECTED\n\n if computed_status != db_status:\n self.set_db_status(computed_status)\n\n return computed_status\n\n # Children classes should implement the below methods\n\n def launch(self, task_url: str) -> None:\n \"\"\"\n Make this Unit available on the crowdsourcing vendor. Depending on\n the task type, this could mean a number of different setup steps.\n\n Some crowd providers require setting up a configuration for the\n very first launch, and this method should call a helper to manage\n that step if necessary.\n \"\"\"\n raise NotImplementedError()\n\n def expire(self) -> float:\n \"\"\"\n Expire this unit, removing it from being workable on the vendor.\n Return the maximum time needed to wait before we know it's taken down.\n \"\"\"\n raise NotImplementedError()\n\n def is_expired(self) -> bool:\n \"\"\"Determine if this unit is expired as according to the vendor.\"\"\"\n raise NotImplementedError()\n\n @staticmethod\n def new(\n db: \"MephistoDB\", assignment: Assignment, index: int, pay_amount: float\n ) -> \"Unit\":\n \"\"\"\n Create a Unit for the given assignment\n\n Implementation should return the result of _register_unit when sure the unit\n can be successfully created to have it put into the db.\n \"\"\"\n raise NotImplementedError()\n","sub_path":"mephisto/data_model/assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":19806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"391367824","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.db.models import Q\nfrom .models import Crontab\nimport json\n\ndef index(request):\n\treturn HttpResponseRedirect('/api/')\n\ndef api(request, host):\n\tif not host:\n\t\thost = request.META.get('HTTP_X_REAL_IP') or request.META.get('REMOTE_ADDR')\n\tdata = {\n\t\t\"success\": False,\n\t\t\"code\": -1,\n\t\t\"message\": \"No task found\",\n\t\t'tasks': []\n\t}\n\n\t#obj = Crontab.objects.filter(f_server_ipaddr = host).filter(f_enable=True)\n\tobj = Crontab.objects.filter(Q(f_enable=True), Q(f_server_ipaddr = host) | Q(f_server_ipaddr = '0.0.0.0'))\n\tcount = obj.count()\n\ttasks = obj.values('f_task_name', 'f_task_user', 'f_minute', 'f_hour', 'f_monthday', 'f_month', 'f_weekday', 'f_command')\n\n\tif count > 0:\n\t\tdata['success'] = True\n\t\tdata['code'] = 0\n\t\tdata['message'] = ''\n\t\tdata['tasks'] = [x for x in tasks]\n\n\n\treturn HttpResponse(json.dumps(data, indent=4), content_type='application/json')\n","sub_path":"cron/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"407768358","text":"# 파일 입출력\n# 내장함수 open()\n\n# open()의 인자\n# path: 절대 / 상대경로\n# mode: 읽기(r) / 덮어쓰기(w) / 이어쓰기(a)\n# encoding: 인코딩 형식 ex) utf-8, cp949(windows default)\n\n# open(path, mode, encoding=encoding)\n\n# '.\\' 현재위치\ndefault = '.\\workspace\\\\kg_lecture\\\\'\nfo = open(default + 'data\\\\openSample.txt', 'r', encoding = 'utf-8')\n\n# print(fo.read()) # 전체 반환\n# print(fo.readline()) # 한줄만 반환\n# print(fo.readlines()) # 한줄씩 리스트화\n\nprint(fo.readlines()[0])\n\nfor line in fo.readlines():\n print(line)\n\nwhile True:\n line = fo.readline()\n if '\\n' not in line:\n break\n else:\n print(line)","sub_path":"workspace/kg_lecture/Ch01/02_open.py","file_name":"02_open.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"351769168","text":"# coding=utf-8\nimport requests\nimport re\nimport os\n\nheader = {'Referer': 'http://www.chsi.com.cn/cet/',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0',\n 'Host': 'www.chsi.com.cn'}\n\n\nurl = \"http://www.chsi.com.cn/cet/query\"\n\n\n\n# 添加参数\ndef test(num):\n name = \"高洪振\"\n param = {\n 'zkzh': num,\n 'xm': name\n }\n\n # 构造get\n responce = requests.get(url, headers=header, params=param)\n\n # 为了方便正则表达式找总分,去掉所有换行符\n newtext = responce.text.replace('\\n', '')\n\n try:\n # 正则表达式找到总分\n score = re.findall('.*?(\\d+)', newtext)\n\n # 输出“姓名+总分”字符串\n ans = num+name + \" \" + score[0]\n\n # 打印该字符串\n print(ans)\n f=open(\"grade.txt\",'a')\n f.write(ans)\n f.close()\n exit(0)\n except:\n\n # 打印未能成功爬取的人\n print(\"Error:\", num, \" \", name)\n\nfor room in range(0,200):\n for desk in range(0,31):\n num=370551172100000+room*100+desk\n test(num)\n","sub_path":"四级查询.py","file_name":"四级查询.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"520907481","text":"from django.contrib import admin\nfrom .models import book, contact\nfrom forum.models import discussion\n\n\n@admin.register(book)\nclass BookAdmin(admin.ModelAdmin):\n def save_model(self, request, obj, form, change):\n super().save_model(request, obj, form, change)\n base_discs = [\n (obj.book, 'General'),\n ('Reviews', 'A place to set your opinion about the topic.'),\n ('Discussion', 'Free talk,centered on the subject at hand.'),\n ('Recomendations',\n 'What could be better with the topic and your vision of the next one.'),\n ('Lost and found', 'Random comunity talk.'),\n ]\n for disc in base_discs:\n if not discussion.objects.filter(\n book__pk=obj.pk, discussion=disc[0]):\n discussion.objects.create(\n book=obj, discussion=disc[0], description=disc[1])\n\n\n@admin.register(contact)\nclass ContactsAdmin(admin.ModelAdmin):\n search_fields = (\"email__startswith\",)\n","sub_path":"topic_forum/books/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"346054948","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport hashlib\ndef md5(str):\n\n m = hashlib.md5()\n m.update(str.encode(encoding='utf-8'))\n #m.update(str)\n return m.hexdigest()\ndmfile = open('TOP1000.txt')\ndm = dmfile.read().splitlines()\n#dm= ''.join(dm).strip('\\n')\nmd5file = open('md5mima.txt','a+')\nfor d in dm:\n print (md5(d))\n md5file.write(d+'\\t\\t'+md5(d))\n md5file.write('\\n')\ndmfile.close()\nmd5file.close()\n\n\n\n","sub_path":"python脚本/MD5搜索/汶嘉鑫/md5.py","file_name":"md5.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"326366552","text":"# -*- coding: utf-8 -*-\nimport os\nimport pygame\nimport copy\nfrom sprites import LittleSprite\nfrom finitestatemachine import * \nfrom tileset import Tileset\n\ntileset = Tileset()\n\nclass Umgebung(LittleSprite):\n def update(self):\n\n self.rect.centerx = self.game.display.bgpos[0] + self.coords[0]\n self.rect.centery = self.game.display.bgpos[1] + self.coords[1]\n self.game.display.paint_sprite(self)\n\nclass Stein(Umgebung, BodenState):\n coords = None\n basename = \"Stein(solide)\"\n# alternate_image = tileset.mauer03\n image = tileset.mauer01 #brick\n rect = image.get_rect()\n\n def __init__(self, coords):\n self.coords = coords\n self.image = Stein.image\n self.rect = self.image.get_rect()\n LittleSprite.__init__(self, self.image)\n self.state = BodenState(self)\n\n\nclass Mauer14(Umgebung, BodenState):\n coords = None\n basename = \"Stein(solide)\"\n # alternate_image = tileset.mauer14\n image = tileset.mauer14 #brick\n rect = image.get_rect()\n\n def __init__(self, coords):\n self.coords = coords\n self.image = Mauer14.image\n self.rect = self.image.get_rect()\n LittleSprite.__init__(self, self.image)\n self.state = BodenState(self)\n\nclass Mauer(Umgebung):\n coords = None\n basename = \"Mauer(solide)\"\n image = tileset.mauer27\n\n def __init__(self, coords):\n self.coords = coords\n self.image = pygame.transform.scale2x(Mauer.image)\n self.rect = self.image.get_rect()\n LittleSprite.__init__(self, self.image)\n\nclass Leiter(Umgebung):\n coords = None\n basename = \"leiter\"\n def __init__(self, coords):\n self.coords = coords\n image = \"leiter001.png\"\n LittleSprite.__init__(self, image)\n\nclass Fass(Umgebung):\n coords = None\n\n def __init__(self, coords):\n self.coords = coords\n image = \"smallbarrel2.png\"\n LittleSprite.__init__(self, image)\n \nclass Pillar(Umgebung):\n coords = None\n image = tileset.pillar03\n basename = \"Pillar.png\"\n \n def __init__(self, coords):\n self.coords = coords\n self.image = Pillar.image\n self.rect = self.image.get_rect()\n LittleSprite.__init__( self, self.image )\n\n\nclass DeadlyTile(Umgebung):\n basename = \"Deadly\"\n coords = None\n image = pygame.image.load( os.path.abspath(os.path.join(\"..\", \"..\", \"data\", \"fire64x64.png\") ) )\n def __init__(self, coords):\n self.coords = coords\n self.image = DeadlyTile.image\n self.rect = self.image.get_rect()\n LittleSprite.__init__(self, self.image)\n\n def update(self):\n ary = pygame.surfarray.array2d(self.image)\n\n# print self.image.map_rgb(255,0,0)\n\n# print ary[0][0]\n# ary[:] +=1\n ary[:0,:1] = 96\n\n self.image = pygame.surfarray.make_surface(ary)\n Umgebung.update(self)\n pass\n \n\n\nclass SimpleElevator(Umgebung):\n basename = \"Aufzug\"\n coords = None\n\n def __init__( self, coords, movement, xbounds, ybounds ):\n self.setImage()\n self.rect = self.image.get_rect()\n self.coords = coords\n self.movement = movement\n self.xbounds = xbounds\n self.ybounds = ybounds\n LittleSprite.__init__(self, self.image)\n\n def setImage(self):\n sfc = pygame.Surface([64,16])\n sfc.fill([0,0,0])\n self.image = sfc\n\n def update(self):\n dirty_rect = copy.copy(self.rect)\n dirty_rect.inflate_ip(0,4)\n self.game.display.dirty_rects.append(dirty_rect)\n self.move_it()\n self.check_bounds()\n Umgebung.update(self)\n\n def move_it(self):\n if self.movement[0] != 0:\n self.coords[0] += self.movement[0]\n if self.movement[1] != 0:\n self.coords[1] += self.movement[1]\n\n def check_bounds(self):\n if self.movement[1] < 0 and self.coords[1] < self.ybounds[0] \\\n or self.movement[1] > 0 and self.coords[1] > self.ybounds[1]:\n self.movement[1] = - self.movement[1]\n \n if self.movement[0] > 0 and self.coords[0] > self.xbounds[1] \\\n or self.movement[0] < 0 and self.coords[0] < self.xbounds[0]:\n self.movement[0] = - self.movement[0]\n\n\n\n","sub_path":"src/umgebung.py","file_name":"umgebung.py","file_ext":"py","file_size_in_byte":4267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"332727941","text":"import glob\nimport numpy as np\nimport pandas as pd\nimport random\nimport os\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import load_img, img_to_array, array_to_img\nfrom sklearn.preprocessing import LabelEncoder \n\n# for resizing - use lanczos\n\n\n\n\nIMG_WIDTH=350\nIMG_HEIGHT=350\nIMG_DIM = (IMG_WIDTH, IMG_HEIGHT)\n\n\ndef create_lists(set):\n '''create arrays with image data and label data \n for training and validation sets'''\n if set == 'train':\n mine_files = glob.glob('/home/cdsw/datasets/train/mines/*.png')\n nonmine_files = glob.glob('/home/cdsw/datasets/train/non_mines/*.png')\n \n elif set == 'validation':\n mine_files = glob.glob('/home/cdsw/datasets/validation/mines/*.png')\n nonmine_files = glob.glob('/home/cdsw/datasets/validation/non_mines/*.png')\n \n mine_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in mine_files]\n nonmine_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in nonmine_files]\n imgs_org = np.array(mine_imgs + nonmine_imgs)\n #print(imgs_org[:6])\n labels_org = ['mine' for fn in mine_files] + ['nonmine' for fn in nonmine_files]\n\n # Shuffle lists with same order \n # Using zip() + * operator + shuffle() \n temp = list(zip(imgs_org,labels_org))\n #print(temp)\n random.shuffle(temp) \n images, labels = zip(*temp) \n \n return images, labels\n \n\ndef label_encode(train_labels, validation_labels):\n '''encode text category labels''' \n le = LabelEncoder()\n le.fit(train_labels) \n train_labels_enc = le.transform(train_labels) \n validation_labels_enc = le.transform(validation_labels)\n \n return train_labels_enc, validation_labels_enc\n\n \n\n\n\ndef main():\n trains_imgs, train_labels = create_lists('train')\n validation_imgs, validation_labels = create_lists('validation')\n\n # check the shapes of the training and validation sets\n # should be 5000 and 1000 200 X 200\n print('Train dataset shape:', train_imgs.shape, \n '\\tValidation dataset shape:', validation_imgs.shape)\n\n\n print(train_labels[5023:5024], train_labels_enc[5023:5024])","sub_path":"data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"548097754","text":"import adaptivefilter as af\nimport matplotlib.pyplot as mpl\n\nmpl.style.use(\"ggplot\")\n\nfor dzp in [500, 1000]:\n for mode in [\"zeros\", \"none\", \"linear\", \"linear-db\"]:\n figure = mpl.figure(figsize=(6, 3.7), tight_layout=True)\n axis = figure.gca()\n\n axis.set_xlabel(\"Filter Weight Index (n)\")\n axis.set_ylabel(\"Gain\")\n\n envelope = af.AmplitudeEnvelope(1001, decay_mode=mode, decay_zero_point=dzp, decay_start_point=250)\n weights = af.InitialWeights(1001, envelope=envelope)\n axis.plot(weights.weights)\n figure.savefig(\"initial_weights_{}_{}.pdf\".format(mode, dzp))\n","sub_path":"plot_envelopes.py","file_name":"plot_envelopes.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"256921148","text":"from ._collect import collect_story\nfrom ._failures import make_protocol\nfrom ._mounted import ClassMountedStory, MountedStory\n\n\nclass Story(object):\n def __init__(self, f):\n self.name = f.__name__\n self.arguments = getattr(f, \"arguments\", [])\n self.collected = collect_story(f)\n self.protocol = make_protocol(None)\n\n def __get__(self, obj, cls):\n if obj is None:\n return ClassMountedStory(cls, self.name, self.collected, self.failures)\n else:\n return MountedStory(\n cls, obj, self.name, self.arguments, self.collected, self.protocol\n )\n\n def failures(self, failures):\n self.protocol = make_protocol(failures)\n return failures\n","sub_path":"src/stories/_story.py","file_name":"_story.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"48927952","text":"import zipfile\nimport os\nimport base64\nimport argparse\nimport logging\n\nlog = logging.getLogger(\"ratdecoder.\" + __name__)\n\n\ndef extract_config(zip):\n \"\"\"\n This extracts the C&C information from Ratty.\n https://github.com/Sogomn/Ratty\n \"\"\"\n c2 = []\n bFile = False\n fh = open(zip, 'rb')\n z = zipfile.ZipFile(fh)\n for name in z.namelist():\n if name == \"data\":\n bFile = True\n data = z.read(name)\n try:\n data = base64.b64decode(data)\n for i in range(len(data)):\n c2.append(chr(ord(data[i]) ^ 0x38))\n\n log.debug(\"Found it: %s\" % zip)\n log.debug(\"C2: %s\" % ''.join(c2))\n except:\n log.debug(\"Probably corrupted Base64 string.\")\n if bFile is False:\n log.debug(\"No such file\")\n log.debug(\"Task Completed\\n\")\n fh.close()\n\n\ndef check_jar_classes(jar_file):\n \"\"\"\n Shitty Check whether file is a jar file.\n \"\"\"\n bJar = False\n try:\n zf = zipfile.ZipFile(jar_file, 'r')\n lst = zf.infolist()\n for zi in lst:\n fn = zi.filename\n if fn.endswith('.class'):\n bJar = True\n return bJar\n except:\n return False\n\n\ndef logo():\n \"\"\"\n Ascii Logos like the 90s. :P\n \"\"\"\n log.info('\\n')\n log.info(' ______ __ __ __ ______ ______ ______ ______ ______ __ __ ______ __ __ ')\n log.info('/\\ ___\\ /\\ \\_\\ \\ /\\ \\ /\\__ _\\ /\\ ___\\ /\\ == \\ /\\ == \\ /\\ __ \\ /\\ \\/ / /\\ ___\\ /\\ \"-.\\ \\ ')\n log.info('\\ \\___ \\ \\ \\ __ \\ \\ \\ \\ \\/_/\\ \\/ \\ \\___ \\ \\ \\ __< \\ \\ __< \\ \\ \\/\\ \\ \\ \\ _\"-. \\ \\ __\\ \\ \\ \\-. \\ ')\n log.info(' \\/\\_____\\ \\ \\_\\ \\_\\ \\ \\_\\ \\ \\_\\ \\/\\_____\\ \\ \\_____\\ \\ \\_\\ \\_\\ \\ \\_____\\ \\ \\_\\ \\_\\ \\ \\_____\\ \\ \\_\\\\\\\\\"\\_\\\\')\n log.info(' \\/_____/ \\/_/\\/_/ \\/_/ \\/_/ \\/_____/ \\/_____/ \\/_/ /_/ \\/_____/ \\/_/\\/_/ \\/_____/ \\/_/ \\/_/')\n log.info('\\n')\n log.info(' Find the C&C for this Ratty mallie!')\n log.info(' Jacob Soo')\n log.info(' Copyright (c) 2016\\n')\n\n\nif __name__ == \"__main__\":\n description = 'C&C Extraction tool for Ratty (https://github.com/Sogomn/Ratty).'\n parser = argparse.ArgumentParser(description=description,\n epilog='--file and --directory are mutually exclusive')\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument(\n '-f', '--file', action='store', nargs=1, dest='szFilename',\n help='filename', metavar=\"filename\")\n group.add_argument(\n '-d', '--directory', action='store', nargs=1, dest='szDirectory',\n help='Location of directory.', metavar='directory')\n\n args = parser.parse_args()\n Filename = args.szFilename\n Directory = args.szDirectory\n try:\n is_file = os.path.isfile(Filename[0])\n except:\n pass\n try:\n is_dir = os.path.isdir(Directory[0])\n except:\n pass\n logo()\n if Filename is not None and is_file:\n extract_config(Filename[0])\n else:\n log.error(\"You probably have supplied an invalid file.\")\n if Directory is not None and is_dir:\n for root, directories, filenames in os.walk(Directory[0]):\n for filename in filenames:\n szFile = os.path.join(root, filename)\n if check_jar_classes(szFile) is True:\n extract_config(szFile)\n else:\n log.error(\"This is not a valid Jar file: %s.\" % szFile)\n","sub_path":"ratdecoder_module/decoders/pyRattyExtractor.py","file_name":"pyRattyExtractor.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"495003204","text":"from server import api\n\n\nverify_vehicle_list_param = api.doc(params={\n \"mobile\": \"手机号\",\n \"vehicle_number\": \"车牌号码\",\n \"home_station_id\": \"常驻地id\",\n \"vehicle_length\": \"车长要求\",\n \"verify_start_time\": \"认证开始时间\",\n \"verify_end_time\": \"认证结束时间\",\n \"last_login_start_time\": \"最后登录开始时间\",\n \"last_login_end_time\": \"最后登录结束时间\",\n \"page\": \"页数\",\n \"limit\": \"条数\",\n}, description='运力列表查询参数')","sub_path":"server/document/verify_vehicle.py","file_name":"verify_vehicle.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"409824275","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom consts import COLORS\n\n\ndef show_loss(loss_lists, labels, title, step=1, save_path=None):\n length = len(loss_lists.iloc[0]) // step\n X = np.linspace(0, 10 * length * step, length)\n\n for n, (loss_list, label) in enumerate(zip(loss_lists, labels)):\n loss_list = loss_list[::step]\n plt.plot(X, loss_list, color=COLORS[n], label=label)\n\n plt.legend()\n plt.xlabel('steps')\n plt.ylabel('loss')\n plt.title(title)\n\n if save_path:\n plt.savefig(save_path)\n\n plt.show()\n\n\nif __name__ == '__main__':\n begin = 5\n end = 7\n\n records = pd.read_pickle('records.pkl')\n loss_lists = records.lost[begin:end]\n labels = records.optimizer[begin:end]\n\n print(labels)\n\n show_loss(loss_lists, labels, 'SGD', 3, 'images/sgd_momentum.png')\n","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"12"}
+{"seq_id":"473357354","text":"import sys\nfrom jinja2 import Environment, FileSystemLoader, Markup\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom collections import defaultdict, Counter\nfrom datetime import datetime as dt\nimport argparse\nimport gspread\nimport json\nimport csv\nimport yaml\nimport os\nimport urllib\nimport markdown\nimport time\nimport itertools\nimport re\nfrom feedgenerator import Rss201rev2Feed as Feed\n\n__version__ = \"0.2.0\"\nconfig_yaml = \"./conf/config.yaml\"\n\n\nclass Update:\n def __init__(self, wks_conf):\n self.wks = wks_conf\n\n def add_contents(self):\n template = self.wks['template']\n required = self.wks['require']\n wks_num = self.wks['num']\n wks_id = self.wks['id']\n static_file = self.wks['static_file']\n summary_file = self.wks['summary_file']\n name = self.wks['file_name_column']\n file_path = self.wks['file_path']\n\n # コンテンツ取得\n update_item_list = UpdateItemList()\n current_list = update_item_list.get_list(wks_num, required)\n\n # 更新対象のidリスト生成\n get_diffs = GetDiffs()\n list_diffs = get_diffs.update(current_list, wks_id, static_file)\n\n # コンテンツリストを最後に更新する\n update_file = UpdateFile()\n update_file.update(current_list, static_file, summary_file, required)\n\n \"\"\"\n # tagリストを取得\n get_pic_tagmember = GetPicTagMember()\n tag_list = get_pic_tagmember.get_create_taglist()\n pg_category_list = get_pic_tagmember.create_category_list()\n \"\"\"\n\n # レンダリングするコンテンツを生成\n contents = self.filter_contents(current_list, list_diffs)\n\n # コンテンツページをレンダリング&ファイルに保存\n render_page = RenderPage() # HTMLをレンダリング&ファイル生成\n render_page.render(contents, template, name, file_path)\n\n #render_page.render_gallery(item_list, list_diffs, tag_list)\n #render_page.render_list(pg_category_list)\n\n def filter_contents(self, contents, diffs):\n wks_id = self.wks['id']\n # 差分のIDリストを参照して差分のコンテンツリストを生成する\n new_contents = [x for x in contents if x[wks_id] in filter(lambda s:s != \"\", diffs)]\n return new_contents\n\n\nclass UpdateItemList:\n def get_list(self, wks_num, required):\n records = self.contentAsJson(conf[\"spreadsheet\"], wks_num)\n\n # 必須条件の設定\n # 必須条件を複数設定できる実装を検討する boolを返す関数を設定すれば良いかも\n records = [x for x in records if is_not_empty(x, required)]\n\n # tagなどリスト化する必要のある値はtemplateとtemplate filterで対応する\n '''\n for article in records:\n article['tag'] = convert_string2list(article['tag'])\n article['tax_id'] = str(article['tax_id'])\n '''\n return records\n\n def contentAsJson(self, title, ws):\n wks_num = ws\n scope = ['https://spreadsheets.google.com/feeds/']\n credentials = ServiceAccountCredentials.from_json_keyfile_name(conf['jsonkey'], scope)\n gc = gspread.authorize(credentials)\n sht = gc.open(title)\n wks = sht.get_worksheet(wks_num)\n li = wks.get_all_records()\n return li\n\n\nclass UpdateFile: #静的コンテンツリスト・コンテンツサマリの更新\n def update(self, pg_list, static_file, summary_file, required):\n with open(conf[\"static_list_path\"]+ \"/\" + static_file, \"w\") as f:\n json.dump(pg_list, f, ensure_ascii=False)\n\n summary_list = []\n for dct in pg_list:\n # 必要項目が空欄でないかチェック\n dct = {k: v for k, v in dct.items() if k in required}\n summary_list.append(dct)\n\n with open(conf[\"output_path\"]+ \"/\" + summary_file, \"w\") as f:\n json.dump(summary_list, f, ensure_ascii=False)\n\n\nclass GetDiffs:\n def update(self, current_list, wks_id, static_file):\n previous_list = []\n try:\n with open(conf[\"static_list_path\"]+ \"/\" + static_file, \"r\") as f:\n jsondata = json.load(f)\n previous_list = [] # 前回までに登録したitemのidリストを、前回の更新時保存済みのコンテンツJSONファイルより追加\n\n for item in jsondata:\n id = item[wks_id]\n previous_list.append(id)\n except IOError:\n previous_list = []\n\n\n new_list = [] # 新規に読み込んだidのリスト\n update_list = [] # update flag付きitemのid。この2つのidリストが更新対象\n for item in current_list:\n id = item[wks_id]\n new_list.append(id) # new_listに現在のspreadsheetの全idを追加\n if item['update']:\n update_list.append(id) # update_listに現在のspreadsheetのup dateフラグ付きのidを追加\n\n set_update = set(new_list) - (set(previous_list) - set(update_list)) # 新規に登録された行、またはフラグ付きの行のidセット\n list_diffs = list(set_update)\n list_diffs = filter(lambda s: s != \"\", list_diffs)\n return list(list_diffs)\n\n\nclass RenderPage:\n def __init__(self):\n # アノテーションする単語のリストを取得\n self.keywords = get_keywords(conf)\n # 正規表現パターンをコンパイル\n self.match_list = create_regex_pattern(self.keywords)\n\n def render(self, contents, template, name, path):\n env = Environment(loader=FileSystemLoader(conf[\"template_path\"], encoding=\"utf8\"))\n env.filters['format_tag'] = format_tag # 空白文字除去のためのテンプレートフィルターを定義\n\n if len(contents) != 0:\n for entry in contents:\n entry[\"filename\"] = entry[name]\n figs = {}\n for i in range(1,5):\n figs[\"fig\"+str(i)] = {\"caption\": entry[\"Fig{}_caption\".format(str(i))], \"img\": entry[\"Fig{}_jpg\".format(str(i))]}\n\n doc = split_entry(entry[\"Post_Content\"])\n txt = doc[2]\n pat = \"\\[hs_figure id=(\\d)\"\n match = re.findall(pat, txt)\n body = multiple_replace(txt, match, figs, path)\n\n # itemの本文にself.keywordsに一致する単語があればマークアップする。\n # マークアップ箇所のDOMのクラスは conf.annotation.class\n body = add_tag(body, self.match_list)\n\n # 分解した記事を結合\n entry[\"Post_Content\"] = doc[0] + doc[1] + body + doc[3] + doc[4]\n\n tmpl = env.get_template(template)\n htm = tmpl.render(item=entry)\n write_static_file(entry, htm)\n\n\n\"\"\"\ndef render_gallery(self, picture_list, list_diffs, tag_list):\n # pictures = [x[\"original_png\"]for x in picture_list]\n if len(list_diffs):\n picture_info = []\n for item in picture_list:\n picture_dict = {k: v for k, v in item.iteritems() if k in [\"original_png\", \"picture_id\", \"doi\", \"title_jp\", \"title_en\", \"tag\", \"apng\"]}\n # picture_dictに新規更新分のコンテンツであればnewフラグを追加する{is_new: true}\n if picture_dict[\"picture_id\"] in list_diffs:\n picture_dict[\"is_new\"] = True\n\n if picture_dict[\"apng\"] != '':\n picture_dict[\"apng\"] = True\n\n picture_info.append(picture_dict)\n\n env = Environment(loader=FileSystemLoader(conf[\"template_path\"], encoding=\"utf8\"))\n env.filters[\"list2string\"] = list2string\n template = conf[\"template\"][\"picture_gallery\"]\n tmpl = env.get_template(template)\n htm = tmpl.render(item=picture_info, tags=tag_list).encode(\"utf-8\") # コンテンツの情報とタグリストを渡す。\n gallery_info = {}\n gallery_info[\"filename\"] = \"pics\"\n WriteStaticFile(gallery_info, htm)\n\ndef render_list(self, pg_list):\n categories = conf[\"picture_category\"]\n env = Environment(loader=FileSystemLoader(conf[\"template_path\"], encoding=\"utf8\"))\n template = conf[\"template\"][\"picture_list\"]\n tmpl = env.get_template(template)\n htm = tmpl.render(item=pg_list, cats=categories).encode(\"utf-8\")\n picture_list = {}\n picture_list[\"filename\"] = \"picture_list\"\n WriteStaticFile(picture_list, htm)\n\"\"\"\n\n\nclass GetPicTagMember:\n def get_create_taglist(self):\n item_tags = []\n with open(conf['static_list_path'] + \"/\" + conf[\"picture_gallery_list\"], \"r\") as f:\n contentdata = json.load(f)\n for item in contentdata:\n if item:\n item_tags.append({\"picture_id\": item[\"picture_id\"], \"tags\": item[\"tag\"]})\n\n dct = defaultdict(list)\n tag_list = []\n tag_list_icon = []\n for item in item_tags:\n if item[\"picture_id\"] != \"\":\n if \"生物アイコン\" in item[\"tags\"]:\n for tag in item[\"tags\"]:\n if len(tag) > 1:\n tag = tag.strip()\n dct[tag].append({\"picture_id\": item[\"picture_id\"]})\n tag_list_icon.append(tag)\n else:\n for tag in item[\"tags\"]:\n if len(tag) > 1:\n tag = tag.strip()\n dct[tag].append({\"picture_id\": item[\"picture_id\"]})\n tag_list.append(tag)\n\n tag_list = list(set(tag_list))\n tag_list_icon = list(set(tag_list_icon))\n tag_list.extend(tag_list_icon)\n\n with open(conf[\"output_path\"] + \"/\" + conf[\"picture_tag\"], \"w\") as f:\n json.dump(dct, f, ensure_ascii=False)\n\n return tag_list\n\n def create_category_list(self):\n category_names = conf[\"picture_category\"]\n with open(conf[\"static_list_path\"] + \"/\" + conf[\"picture_gallery_list\"], \"r\") as f:\n jsondata = json.load(f)\n\n pg_category_list = {}\n for item in category_names:\n sub_list = [{\"title\": x[\"title_jp\"], \"uri\": x[\"doi\"]} for x in jsondata if item in x[\"tag\"]]\n pg_category_list[item] = sub_list\n\n return pg_category_list\n\n\ndef write_static_file(item, htm, path=\"output_path\"):\n FA_URL = item[\"FA_URL\"]\n filename = FA_URL.split(\"/\")[-1]\n # this line(if filename~) is necessary for togotv filename extraction\n '''\n if filename.find(\"http\") > -1:\n filename = filename.split(\"/\")[-1].replace(\".html#p01\", \"\")\n filename = filename.replace(\".html\",\"\")\n '''\n with open(conf[path] + \"/\" + str(filename) + \".html\", 'w') as f:\n f.write(htm)\n\n\n# feedformatterからfeedgeneratorに変更した\nclass CreateRss:\n def __init__(self):\n rss = []\n today = (dt.today()).strftime('%Y-%m-%d')\n feed = Feed(\n title = '記事タイトル',\n link = 'http://www.example.com/news/',\n feed_url = 'http://www.example.com/news/rss',\n description = '記事の説明'\n )\n feed.add_item()\n\n\ndef is_not_empty(item, lists):\n return all(item[k] != '' for k in lists)\n\n\ndef convert_string2list(s):\n l = [x.strip() for x in (s).split(\",\")]\n return l\n\n\ndef format_tag(str):\n return str.strip()\n\n\ndef format_datetime(date):\n ymd = str(date)\n dtymd = dt.strptime(ymd, '%Y%m%d')\n return dtymd.strftime('%Y-%m-%d')\n\n\ndef format_replace_period(id):\n id_uri = id.replace(\".\", \"\")\n return id_uri\n\n\ndef get_keywords(cf):\n update_item_list = UpdateItemList()\n wks_num = cf['annotation']['wks']['num']\n word_lst = update_item_list.contentAsJson(conf['spreadsheet'], wks_num)\n words = word_filter(word_lst)\n return words\n\n\n# タグ付けする単語リストを返す\ndef word_filter(lst):\n lst = [x['用語(FA見出し語)'] for x in lst if x['文字数'] != 1 and x['文字数'] != 2]\n return lst\n\n\n# アノテーションタグを付加する\ndef add_tag(txt, m_lst):\n for p in m_lst:\n rep = r'\\g<0>'\n cnt = conf[\"annotation\"][\"repl_count\"]\n txt = p.sub(rep, txt, count=cnt)\n return txt\n\n\ndef create_regex_pattern(lst):\n pttns = [re.compile(x) for x in lst]\n return pttns\n\n\ndef multiple_replace(st, match, fig, path):\n txt = st\n if match:\n for i in match:\n # group()を利用してidを抽出することができる。\n # 置き換えはidが一致する部分のみ\n pat = \"\\[hs_figure id={}.+fig{}-caption-text\\]\".format(i, i)\n\n tmp = '''\n