diff --git "a/4574.jsonl" "b/4574.jsonl" new file mode 100644--- /dev/null +++ "b/4574.jsonl" @@ -0,0 +1,703 @@ +{"seq_id":"8372362","text":"#regla de simpson compuesta\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x):\n return (1/4)*x*(10-x)+ np.sin(np.pi*x)\na=0\nb=5\nN=5\nh=(b-a)/N\n\ndef simpson(f,a,b,N, h):\n h = h / 2\n Xi=np.array([a+h*i for i in range(2*N+1)])\n Yi=f(Xi)\n suma1=sum(np.array([Yi[2*i] for i in range(1,N)]))\n suma2=sum(np.array([Yi[2*i+1] for i in range(N)]))\n simpson= (h/3)*(f(a)+2*suma1+4*suma2+f(b))\n print(simpson)\n \n return simpson\n\nprint(\"La aprox. de la integral por la regla de simpson compuesta es: \", simpson(f,a,b,N))\n\nXi= np.array([a+h*i for i in range(N)]) #para calcular la funcion\nYi= f(Xi)\n\nxi=np.linspace(a,b,100) #Para graficar muchos puntos para f(x) y sea suave\nyi=f(xi)\n\nplt.title(\"Funcion y funcion escalon usada para integrar\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.step(Xi,Yi,'r') #funcion escalon\nplt.plot(xi,yi,'b') #funcion f(x)\n\nfor j in range(len(Xi)):\n plt.plot(Xi[j], Yi[j],'go') #puntos (xi,yi)\n\nplt.savefig(\"EjReglaDeSimpson.png\")\nplt.show()\n\n\n\nN = 10\nx = [1 * i for i in range(2*N+1)]\nn1 = len(x)\nn2 = len([x[2*i] for i in range(1,N)])\nn3 = len([x[2*i+1] for i in range(N)])\n\n\n\n\n\n","sub_path":"codes/kondo/ej14-reglasimpson-.py","file_name":"ej14-reglasimpson-.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"66067425","text":"import bisect\nimport random\n\n\"\"\"\nreference: fluent python p.46\n\nSorting is expensive, so once you have a sorted sequence, it’s good to keep it that way. That is why bisect.insort was created.\ninsort(seq, item) inserts item into seq so as to keep seq in ascending order.\n\nnotes\n1. You could use the result of bisect(haystack, needle) as the index argument to haystack.insert(index, needle), but using insort does both steps, and is faster.\n2. Like bisect, insort takes optional lo , hi arguments to limit the search to a subsequence. There is also an insort_left variation that uses bisect_left to find insertion points. \n\"\"\"\n\nSIZE = 7\nrandom.seed(1729)\nmy_list = []\nfor i in range(SIZE):\n new_item = random.randrange(SIZE * 2)\n bisect.insort(my_list, new_item)\n print('%2d ->' % new_item, my_list)\n\n\"\"\"\noutput\n6 -> [6]\n10 -> [6, 10]\n12 -> [6, 10, 12]\n7 -> [6, 7, 10, 12]\n0 -> [0, 6, 7, 10, 12]\n9 -> [0, 6, 7, 9, 10, 12]\n4 -> [0, 4, 6, 7, 9, 10, 12]\n\"\"\"\n","sub_path":"src/library_ref/data_type/bisect/bisect_03_insort.py","file_name":"bisect_03_insort.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"57344537","text":"# 仮説\n\"\"\"\nお弁当のメインメニューによって人気のある・なしがあり、販売数に影響するのではないか\n\n気温が高すぎると、食欲がなくなって販売数が減ってしまうのではないか\n\nカロリーと販売数は関係があるのではないか(カロリーが高いと健康志向の人には敬遠されたり、逆にカロリーが高い揚げもの系が売れるなど)\n\n売れやすい曜日、売れにくい曜日があるのではないか(例えば休み明けの月曜日は自分でお弁当を持ってくる人が多くて売れないなど)\n\n「お楽しみメニュー」「料理長のこだわりメニュー」のように特別メニューの時には販売数が増えるのではないか\n\nお弁当持ち込み可の社内イベントがあると、販売数が減ってしまうのではないか\n\n給料日は外のレストランに行ってしまうため、販売数は減ってしまうのではないか\n\n雨が降っていると外のレストランに行かなくなり、販売数が増えるのではないか\n\"\"\"\n\n#気温は関係していそう。\n# kcalは微妙\n# 後半、金曜日が特に売れている日がある\n# remarksがお楽しみメニューのときは売れてそう→\n# eventはキャリアアップセミナーの日は少ない\n# paydayは関係なさそう\n# humidityは??\n# ヒントによるとprecipitationとcloud_amountで天気を作れるらしい。\n\n# 施策\n# 天気 雪と雷雨を雨に\n# remarksをお楽しみメニューかつカレー:1 それ以外0\n# year,monthの数字の列を追加\n# remarks,temperature,weather、更にmonthのみ使うことにし、\n# \"datetime\",\"week\",\"soldout\",\"name\",\"kcal\",\"event\",\"payday\",\"precipitation\",\"year\"は削除する\n# 以上実施しダミー変数化\n# y remarks temperature flag month weather_快晴 weather_晴れ weather_曇 weather_薄曇 weather_雨 となる\n# 100番目以降のデータに絞って予測モデル立てるので再度天気とsalesを評価すると雨の日が売れていることがわかる\n#\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nimport japanize_matplotlib\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\nimport plotly.express as px\nfrom pprint import pprint\n\ntrain_df = pd.read_csv(\n \"train.csv\",\n # **kwargs\n encoding=\"utf_8\",\n)\ntest_df = pd.read_csv(\n \"test.csv\",\n # **kwargs\n encoding=\"utf_8\",\n)\n\nprint(train_df.head())\nprint(\"\")\n\nprint(train_df.shape)\nprint(\"\")\n\nprint(\"info:\")\nprint(train_df.info())\nprint(\"\")\n\nprint(\"describe:\")\nprint(train_df.describe())\nprint(\"\")\n\nprint(\"describe(Object):\")\nprint(train_df.describe(include=[\"O\"]))\nprint(\"\")\n\nprint(\"missing value:\")\nprint(train_df.isnull().sum())\nprint(\"\")\n\nprint(\"相関係数:\")\nprint(train_df.corr())\nprint(\"\")\n\n# 名義尺度について出現数\nprint(\"\\nname:\")\nprint(train_df[\"name\"].value_counts())\nprint(\"\\nremarks:\")\nprint(train_df[\"remarks\"].value_counts())\nprint(\"\\nevent:\")\nprint(train_df[\"event\"].value_counts())\nprint(\"\\nprecipitation:\")\nprint(train_df[\"precipitation\"].value_counts())\n\n# お楽しみメニューかどうか\nprint(\"お楽しみメニュー:\")\nprint(train_df[train_df['remarks']=='お楽しみメニュー'])\n\n# お楽しみメニューかどうか\nprint(\"お楽しみメニュー:\")\nprint(train_df[train_df['remarks']=='お楽しみメニュー'])\n\ndef fill_missing_value(df):\n # remarksカラムの欠損値を埋める\n df[\"remarks\"]=df[\"remarks\"].fillna(\"特記なし\")\n # eventカラムの欠損値を埋める\n df[\"event\"]=df[\"event\"].fillna(\"イベントなし\")\n # paydayカラムの欠損値を埋める\n df[\"payday\"]=df[\"payday\"].fillna(0)\n\n return df\n\ntrain_df=fill_missing_value(train_df)\ntest_df=fill_missing_value(test_df)\n\nif False:\n plt.figure(figsize=(5,20))\n sns.boxplot(x=\"y\", y=\"name\", data=df)\n plt.tight_layout()\n plt.savefig(\"boxplot_name.png\")\n plt.clf()\n plt.close()\n\n sns.set_palette(\"Set2\") # グラフの色を指定する\n sns.boxplot(x=\"week\", y=\"y\", data=df, width=0.5)\n plt.savefig(\"boxplot_week.png\")\n plt.clf()\n plt.close()\n\n # train.csvを読み込み、変数trainにDataFrameとして格納されています。\n # グラフのサイズを指定して、折れ線グラフの描画\n sns.lineplot( x=train_df.index, y='y', hue='week', data=train_df)\n plt.xlabel(\"time step\")\n plt.ylabel(\"sales\")\n plt.title(\"sales of box lunch\")\n plt.savefig(\"scatter_weeks.png\")\n plt.clf()\n plt.close()\n\n sns.boxplot(x=\"y\", y=\"remarks\", data=df, width=0.5)\n plt.tight_layout()\n plt.savefig(\"boxplot_remarks.png\")\n plt.clf()\n plt.close()\n\n sns.boxplot(x=\"event\", y=\"y\", data=df, width=0.5)\n plt.savefig(\"boxplot_event.png\")\n plt.clf()\n plt.close()\n\n sns.boxplot(x=\"payday\", y=\"y\", data=df, width=0.5)\n plt.savefig(\"boxplot_payday.png\")\n plt.clf()\n plt.close()\n\n sns.boxplot(x=\"precipitation\", y=\"y\", data=df, width=0.5)\n plt.savefig(\"boxplot_precipitation.png\")\n plt.clf()\n plt.close()\n\n train_df.plot(x='datetime',y='y')\n plt.savefig(\"y.png\")\n plt.clf()\n plt.close()\n\n fig = px.histogram(train_df, x=\"y\")\n fig.write_image(\"hist_y.png\")\n\n # 相関係数の算出\n corr_matrix = train_df.corr()\n\n # heatmapの可視化\n sns.heatmap(corr_matrix)\n plt.tight_layout()\n plt.savefig(\"heatmap.png\")\n plt.clf()\n plt.close()\n\n # 散布図行列を作成\n pg = sns.pairplot(train_df)\n plt.savefig(\"pairplot.png\")\n plt.clf()\n plt.close()\n\n# 前処理\ndef preprocessing(df):\n # お楽しみメニューかどうか\n df['flag_otanosimi']=df['remarks']=='お楽しみメニュー'\n\n # 「お楽しみメニュー」かつ「カレー」を判定\n df[\"remarks\"] = df.apply(\n lambda x: 1 if x[\"remarks\"] == \"お楽しみメニュー\" and \"カレー\" in x[\"name\"] else 0, axis=1\n )\n\n \"\"\"\n # 「お楽しみメニュー」かつ「カレー」か「丼」を判定\n df[\"remarks\"] = df.apply(\n lambda x: 1 if (x[\"remarks\"] == \"お楽しみメニュー\" and \"カレー\" in x[\"name\"]) or \\\n (x[\"remarks\"] == \"お楽しみメニュー\" and \"丼\" in x[\"name\"]) else 0, axis=1\n )\n \"\"\"\n\n\n df['is_cu']=df['event']!='キャリアアップ支援セミナー'\n\n week_df=pd.get_dummies(df['week'])\n week_df.columns=['mo',\"th\",\"wd\",\"tu\",\"fr\"]\n df=pd.concat([df,week_df], axis=1)\n\n \"\"\"\n precipitation_df=pd.get_dummies(df['precipitation'])\n precipitation_df.columns=[ \"--\", \"0\", \"0.5\", \"1\", \"1.5\", \"2.5\" ,\"6\" ,\"6.5\"]\n df=pd.concat([df,precipitation_df], axis=1)\n \"\"\"\n\n event_df=pd.get_dummies(df['event'])\n event_df.columns=['no',\"ca\",\"ma\"]\n df=pd.concat([df,event_df], axis=1)\n\n df['kcal']=df['kcal'].fillna(df['kcal'].mean())\n\n # 年・月の情報を取得\n df[\"year\"] = df['datetime'].apply(lambda x: x.split(\"/\")[0] )\n df[\"month\"] = df['datetime'].apply(lambda x: x.split(\"/\")[1] )\n df[\"day\"] = df['datetime'].apply(lambda x: x.split(\"/\")[2] )\n\n # 整数に変換\n df[\"year\"] = df['year'].astype(int)\n df[\"month\"] = df['month'].astype(int)\n df[\"day\"] = df['day'].astype(int)\n\n # 対数化\n df[\"temperature_log\"] = np.log(df[\"temperature\"])\n df[\"kcal_log\"] = np.log(df[\"kcal\"])\n\n # 天気の情報が無くなりましたが、雲量と降水量を使えば同様の情報を作ることができます。\n # 降水量があれば雨、なければ雲量に着目。一般に雲量が8より大きいと「曇り」、\n # 2より小さいと「快晴」、2以上8以下で「晴れ」となります。\n weather_flag=[]\n for index, row in df.iterrows():\n if row['precipitation']=='0':\n weather_flag.append('clear_day')\n elif row['precipitation']=='--':\n if row['cloud_amount']>=8.0:\n weather_flag.append('cloudy')\n elif row['cloud_amount']<=2.0:\n weather_flag.append('clear_day')\n else:\n weather_flag.append('sunny')\n else:\n weather_flag.append('rain')\n\n weather=pd.DataFrame(weather_flag,columns=['weather'])\n weather=pd.get_dummies(weather)\n df=pd.concat([df,weather], axis=1)\n\n return df\n\ntrain_df=preprocessing(train_df)\ntest_df=preprocessing(test_df)\n\n# 相関係数の算出\ncorr_matrix = train_df.corr()\ncorr_matrix.to_csv(\"corr2.csv\")\n\n# feautures = [\"week\",\"soldout\",\"name\",\"kcal\",\"remarks\",\"event\",\"payday\",\"precipitation\",\"temperature\",\"cloud_amount\",\"humidity\"]\n#features = [\"month\",\"soldout\",\"temperature\",\"cloud_amount\",\"humidity\",'flag_otanosimi','mo',\"th\",\"wd\",\"tu\",\"fr\", \"--\",\"0\", \"0.5\", \"1\", \"1.5\", \"2.5\" ,\"6\" ,\"6.5\",'no',\"ca\",\"ma\",\"kcal\"]\n#features = [\"month\",\"soldout\",\"temperature\",\"cloud_amount\",\"humidity\",'flag_otanosimi','remarks','mo',\"th\",\"wd\",\"tu\",\"fr\", \"--\",\"0\", \"0.5\", \"1\", \"1.5\", \"2.5\" ,\"6\" ,\"6.5\",'no',\"ca\",\"ma\",\"kcal\"]\nfeatures = [\"month\",\"temperature\",\"cloud_amount\",\"humidity\",'flag_otanosimi','remarks','mo',\"th\",\"wd\",\"tu\",\"fr\",'no',\"ca\",\"ma\",\"kcal\"]\n#features = [\"remarks\",\"temperature\",\"month\",\"weather_clear_day\",\"weather_sunny\",\"weather_cloudy\",\"weather_rain\"]\n\nX = train_df[features]\ny = train_df[\"y\"]\n\nX_train, X_val, y_train, y_val = train_test_split(\n X,\n y,\n random_state=0,\n shuffle=False,\n # test_size=0.3\n)\n\nlm = LinearRegression()\nlm.fit(X[100:], y[100:])\nprint(pd.DataFrame(lm.coef_)) # , index=features, columns=[\"回帰係数\"])\n\ny_val_pred = lm.predict(X_val)\nmse = mean_squared_error(y_val, y_val_pred)\nrmse = np.sqrt(mse)\nprint(\"test MSE\", mse)\nprint(\"test RMSE:\", rmse)\n\n# 評価データの販売数でグラフを描く\nplt.plot(y_val.values, label=\"actual\")\n\n# 予測値でグラフを描く\nplt.plot(y_val_pred, label=\"forecast\")\n\nplt.title(\"sales of box lunch\")\nplt.xlabel(\"time step\")\nplt.ylabel(\"sales\")\nplt.legend()\nplt.savefig(\"pred.png\")\n\nX_test=test_df[features]\ny_test_pred = lm.predict(X_test)\nprint(y_test_pred)\n","sub_path":"sig_q/10002/train_eval.py","file_name":"train_eval.py","file_ext":"py","file_size_in_byte":10193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"158714811","text":"import collections\n\ndef minHour(row, col, grid):\n q = collections.deque()\n\n emptyServer = 0\n for i in range(row):\n for j in range(col):\n if grid[i][j] == 1:\n q.append((i, j))\n\n if grid[i][j] == 0:\n emptyServer += 1\n\n dirs = [(0, -1), (-1, 0), (0, 1), (1, 0)]\n\n hour = 0\n visitedServer = 0\n\n while visitedServer != emptyServer:\n hour += 1\n\n qSize = len(q)\n for i in range(qSize):\n x, y = q.popleft()\n\n for dx, dy in dirs:\n newX, newY = x + dx, y + dy\n if newX < 0 or newX >= row or newY < 0 or newY >= col:\n continue\n\n if grid[newX][newY] == 1:\n continue\n \n grid[newX][newY] = 1\n visitedServer += 1\n q.append((newX, newY))\n \n return hour\n\nrow = 4\ncol = 5\ngrid = [[0,1,1,0,1], [0,1,0,1,0], [0,0,0,0,1],[0,1,0,0,0]]\nprint(minHour(row, col, grid))","sub_path":"amazon/cloudfont.py","file_name":"cloudfont.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"351923256","text":"from flask import render_template, request, jsonify, url_for, redirect\nfrom flask_login import login_user, login_required, current_user, logout_user\n\nfrom app.models import db\nfrom app.libs.error_codes import Success\nfrom app.libs.redprint import Redprint\nfrom app.models import AppAccessLog\nfrom app.models import User\nfrom app.validators.cms_forms.user_forms import LoginForm, EditForm, ResetPwdForm\n\ncms = Redprint('user')\n\n\n@cms.route('/login', methods=['POST', 'GET'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('cms.index+index'))\n if request.method == 'POST':\n form = LoginForm().validate()\n user = User.verify(form.login_name.data, form.login_pwd.data)\n login_user(user)\n # 添加登录日志\n AppAccessLog.add_access_log()\n next_url = request.args.get('next')\n data = {'next': next_url}\n if not next_url or not next_url.startswith('/'):\n data['next'] = url_for('cms.index+index')\n return jsonify(data)\n return render_template('user/login.html')\n\n\n@cms.route('/edit', methods=['POST', 'GET'])\n@login_required\ndef edit():\n if request.method == 'POST':\n form = EditForm().validate()\n with db.auto_commit():\n current_user.nickname = form.nickname.data\n current_user.email = form.email.data\n db.session.add(current_user)\n return Success(msg='信息修改成功')\n return render_template('user/edit.html', current='edit')\n\n\n@cms.route('/reset_pwd', methods=['POST', 'GET'])\n@login_required\ndef reset_pwd():\n if request.method == 'POST':\n form = ResetPwdForm().validate()\n with db.auto_commit():\n current_user.password = form.new_password.data\n db.session.add(current_user)\n return Success(msg='密码修改成功')\n return render_template('user/reset_pwd.html', current='reset_pwd')\n\n\n@cms.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('cms.user+login'))\n","sub_path":"app/cms/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"636541009","text":"import os\nimport random\nimport string\nimport webapp2\nimport jinja2\n\njinja_environment = jinja2.Environment(\n\tloader=jinja2.FileSystemLoader(os.path.dirname(__file__)))\n\nurls = {}\ndef getRandomUrl():\n\tres = ''\n\tfor i in range(6):\n\t\tres += (string.lowercase + string.digits)[random.randint(0, 35)]\n\twhile res in urls:\n\t\tfor i in range(6):\n\t\t\tres += (string.lowercase + string.digits)[random.randint(0, 35)]\n\treturn res\n\n\nclass IndexHandler(webapp2.RequestHandler):\n\tdef get(self):\n\t\turl = getRandomUrl()\n\t\turls[url] = url\n\t\tself.redirect('/%s' % url)\n\nclass MainHandler(webapp2.RequestHandler):\n\tdef get(self, url):\n\t\turl = urls.get(url)\n\t\tif url:\n\t\t\ttemp = jinja_environment.get_template('index.html')\n\t\t\tself.response.out.write(temp.render({'url':url}))\n\t\telse:\n\t\t\tself.response.out.write('The requested asdf does not exist')\n\napp = webapp2.WSGIApplication([\n\t\t(r'^/(.{6})$', MainHandler),\n\t\t(r'^/$', IndexHandler),\n\t], debug=True)\n\n\n","sub_path":"webapp/asdfcoding.py","file_name":"asdfcoding.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"16425543","text":"\"\"\"\nTest for task 8 - beam profiles: Gaussian beam profile\nCompares the last calculated surface to a saved reference surface\n\n\"\"\"\nimport os, sys\n\n# Add code directory to search path\nfiledir = os.path.dirname(__file__)\ncodedir = os.path.join(filedir, '..', '..', 'code')\nsys.path.insert(0, codedir)\n\nimport miniTopSim\nfrom surface import Surface, load_last_from_srf\n\ndef test_gauss():\n \"\"\" Perform test for surface similarity of simulated and stored surface\n \n Test is utilizing the Gaussian beam \n \"\"\"\n \n # Execute simulation based on given config file\n thisSurface = miniTopSim.simulation(os.path.join(filedir,\"gauss.cfg\"),None)\n \n # Load stored surface data\n otherSurface = load_last_from_srf(os.path.join(filedir,\"gauss.srf_save\"))\n \n # Compare and assert in case of failure\n assert thisSurface.distance(otherSurface,0) < 0.003","sub_path":"work/Aufgabe8_beam/test_gauss.py","file_name":"test_gauss.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"267950593","text":"import scrapy\nfrom museum.items import exhibitionItem\n#scrapy crawl collection\n#scrapy crawl exhiition\n#scrapy genspider collection//www.xxx.com\n#scrapy genspider exhibition\n#scrapy genspider education\nclass Education9Spider(scrapy.Spider):\n name = 'exhibition160'\n # allowed_domains = ['www.xxx.com']\n start_urls = ['https://www.shmmc.com.cn/Home/CszgList']\n\n def parse(self, response):\n item = exhibitionItem()\n #scrapy crawl exhibition160\n div_list = response.xpath('/html/body/div[2]/div[2]/div/div[2]/div[2]/div/div')\n for li in div_list:\n name = li.xpath('.//b/text()').extract_first()\n if not name:\n break\n print(name)\n img=li.xpath('.//img/@src').extract_first()\n img='https://www.shmmc.com.cn'+img\n print(img)\n cont=response.xpath('//span//text()').extract()\n cont = ''.join(cont)\n print(cont)","sub_path":"museum/spiders/exhibition160.py","file_name":"exhibition160.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"14945593","text":"# ## Option 4: PyParagraph\n\n# ![Language](Images/language.jpg)\n\n# In this challenge, you get to play the role of chief linguist at a local learning academy. As chief linguist, you are responsible for assessing the complexity of various passages of writing, ranging from the sophomoric Twilight novel to the nauseatingly high-minded research article. Having read so many passages, you've since come up with a fairly simple set of metrics for assessing complexity.\n\n# Your task is to create a Python script to automate the analysis of any such passage using these metrics. Your script will need to do the following:\n\n# * Import a text file filled with a paragraph of your choosing.\n\n# * Assess the passage for each of the following:\n\n# * Approximate word count\n\n# * Approximate sentence count\n\n# * Approximate letter count (per word)\n\n# * Average sentence length (in words)\n\n# * As an example, this passage:\n\n# > “Adam Wayne, the conqueror, with his face flung back and his mane like a lion's, stood with his great sword point upwards, the red raiment of his office flapping around him like the red wings of an archangel. And the King saw, he knew not how, something new and overwhelming. The great green trees and the great red robes swung together in the wind. The preposterous masquerade, born of his own mockery, towered over him and embraced the world. This was the normal, this was sanity, this was nature, and he himself, with his rationality, and his detachment and his black frock-coat, he was the exception and the accident - a blot of black upon a world of crimson and gold.”\n\n# ...would yield these results:\n\n# ```\n# Paragraph Analysis\n# -----------------\n# Approximate Word Count: 122\n# Approximate Sentence Count: 5\n# Average Letter Count: 4.56557377049\n# Average Sentence Length: 24.4\n# ```\n\n# * **Special Hint:** You may find this code snippet helpful when determining sentence length (look into [regular expressions](https://en.wikipedia.org/wiki/Regular_expression) if interested in learning more):\n\n# ```python\n# import re\n# re.split(\"(?<=[.!?]) +\", paragraph)\n# ```\n\nimport os\nimport csv\n\nparagraph =\"\"\nwords =0\nsentences =0\nletter_count =0\navg_letter =0.0\navg_sentence = 0.0\n\nfilepath = os.path.join(\"raw_data\", \"paragraph_1.txt\") #input path\n\nwith open(filepath) as f:\n\n paragraph = f.read()\n\n #words = the same number of spaces plus 1\n words = paragraph.count(\" \") + 1 \n\n #sentences = the number of punctuation marks \n sentences = paragraph.count(\".\") + paragraph.count(\"?\") + paragraph.count(\"!\")\n\n #letters = all characters minus space and punctuation marks\n letter_count = len(paragraph) - (words -1) - sentences\n\n\n avg_letter = letter_count / words\n avg_sentence = words / sentences\n\n\n\n\n # Paragraph Analysis\n # -----------------\n # Approximate Word Count: 122\n # Approximate Sentence Count: 5\n # Average Letter Count: 4.56557377049\n # Average Sentence Length: 24.4\n print(\"Paragraph Analysis\")\n print(\"-\" * 28)\n print(f\"Approximate Word Count: {words}\")\n print(f\"Approximate Sentence Count: {sentences}\")\n print(f\"Average Letter Count: {avg_letter}\")\n print(f\"Average Sentence Length: {avg_sentence}\")\n\n\n #I think they wanted us to use (import re) and (re.split(\"(?<=[.!?]) +\", paragraph)) to split pargraph into sentence lists \n #then count sentences (len(sentence_list) and then maybe splitting into words words=senteces.split(\" \") but this way was easier\n\n\n\n\n\n\n","sub_path":"PyParagraph/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"636375695","text":"#!/usr/bin/env python3\n'''Multiple Kernels'''\n\nimport numpy as np\n\n\ndef convolve(images, kernels, padding='same', stride=(1, 1)):\n '''performs a valid convolution on grayscale images\n Args:\n images:array shape (m, h, w, c) containing multiple grayscale images\n m is the number of images\n h is the height in pixels of the images\n w is the width in pixels of the images\n c is the number of channels in the image\n kernels: array with shape (kh, kw, c, nc) containing the kernel\n kh is the height of the kernel\n kw is the width of the kernel\n nc is the number of kernels\n padding is a tuple of (ph, pw) ‘same’, or ‘valid’\n if ‘same’, performs a same convolution\n if ‘valid’, performs a valid convolution\n if a tuple:\n ph is the padding for the height of the image\n pw is the padding for the width of the image\n the image should be padded with 0’s\n stride is a tuple of (sh, sw)\n sh is the stride for the height of the image\n sw is the stride for the width of the image\n Return : a numpy.ndarray containing the convolved images\n '''\n m = images.shape[0]\n h = images.shape[1]\n w = images.shape[2]\n c = kernels.shape[2]\n kh = kernels.shape[0]\n kw = kernels.shape[1]\n sh = stride[0]\n sw = stride[1]\n nc = kernels.shape[3]\n # # calculate padding according to type\n if type(padding) is tuple:\n # padding\n padh = padding[0]\n padw = padding[1]\n elif padding == 'same':\n padh = int((((h - 1) * sh - h + kh) / 2)) + 1\n padw = int((((w - 1) * sw - w + kw) / 2)) + 1\n elif padding == 'valid':\n padh = padw = 0\n\n # new dimensions with stride\n nh = int(((h + (2 * padh) - kh) / sh)) + 1\n nw = int(((w + (2 * padw) - kw) / sw)) + 1\n # output\n # add amount of kernel\n conv = np.zeros((m, nh, nw, nc))\n # pad images add dimension at the for channels\n pad = ((0, 0), (padh, padh), (padw, padw), (0, 0))\n imagepaded = np.pad(images, pad_width=pad, mode='constant',\n constant_values=0)\n # Loop over every pixel of the output\n for i in range(nh):\n for j in range(nw):\n for k in range(nc):\n # apply strided\n x = i * sh\n y = j * sw\n # slice every image according to kernel size\n # add dimension at the end for channels\n image = imagepaded[:, x: x+kh, y: y+kw, :]\n # element-wise multiplication of the kernel and the image\n conv[:, i, j, k] = np.multiply(image, kernels[:, :, :, k]).\\\n sum(axis=(1, 2, 3))\n return conv\n","sub_path":"math/0x04-convolutions_and_pooling/5-convolve.py","file_name":"5-convolve.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"84564748","text":"import requests\nimport json\nimport pprint\nimport asyncio\n\n\"\"\"a Kraken orderbook data collector\"\"\"\nclass OrderBookCollector_Kraken:\n \"\"\"store the requested data\"\"\"\n data = {}\n\n def request_bid_or_ask(self, pair, action):\n pair = pair.lower()\n action = self.transform_action(action)\n\n if self.data:\n return self.data[action]\n elif not self.data:\n return self.request(pair)[action]\n else:\n print('error: data in orderbook class not properly populated')\n\n def request(self, pair):\n\n parameters = {\"pair\": pair, \"count\": 60}\n response = json.loads(requests.get(\"https://api.kraken.com/0/public/Depth\", params=parameters).text)\n\n if response['error']:\n print('error: ', response.error)\n\n self.data = next(iter(response['result'].values()))\n\n return self.data\n\n def transform_action(self, action):\n return action + \"s\"\n\n\nclass OrderBookCollector_Exmo:\n \"\"\"store the requested data\"\"\"\n data = {}\n\n def request_bid_or_ask(self, pair, action):\n pair = self.transform_pair(pair)\n\n if self.data:\n return self.data[action]\n elif not self.data:\n return self.request(pair)[action]\n else:\n print('error: data in orderbook class not properly populated')\n\n def request(self, pair):\n \"\"\"a Exmo orderbook data collector\"\"\"\n\n parameters = {\"pair\": pair, \"limit\": 60}\n response = json.loads(requests.get(\"https://api.exmo.com/v1/order_book\", params=parameters).text)\n\n self.data = response[pair]\n\n return self.data\n\n def transform_pair(self, pair):\n result = ''\n\n if (len(pair) == 6):\n result = pair[0:3].upper() + \"_\" + pair[3:6].upper()\n elif (len(pair) == 7):\n result = pair[0:4].upper() + \"_\" + pair[4:7].upper()\n elif (len(pair) == 8):\n result = pair[0:5].upper() + \"_\" + pair[5:8].upper()\n else:\n print(\"pair doesn't exist\")\n\n return result\n\n# d1 = DataCollector_Kraken()\n# pprint.pprint(d1.request(\"adaeth\", \"bid\"))\n\n# d2 = DataCollector_Exmo()\n# d2.request(\"adaeth\", \"bid\")\n","sub_path":"data_collector.py","file_name":"data_collector.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"611787165","text":"from flask_login import current_user\nfrom flask_wtf import FlaskForm\nfrom sqlalchemy import and_\nfrom wtforms import BooleanField\nfrom wtforms import IntegerField\nfrom wtforms import StringField\nfrom wtforms import SubmitField\nfrom wtforms.validators import DataRequired\nfrom wtforms.validators import NumberRange\nfrom wtforms.validators import ValidationError\n\nfrom flaskapp.models import Course\nfrom flaskapp.models import Unit\n\n\ndef validate_course_name(form, course_name):\n \"\"\"Validate Course name\n\n Args:\n form (Object): Description about course \n course_name (String): Name of course\n\n Raises:\n ValidationError: If coursename is already exist then give error of already course exist. Please choose different one.\n \"\"\"\n course = Course.query.filter(\n and_(Course.name == course_name.data,\n Course.teacher == current_user)).first()\n if course:\n raise ValidationError(\n \"That Course is already exist. Please choose a different one.\")\n\n\ndef validate_unit_name(form, unit_name):\n \"\"\"Validation of unit name\n\n Args:\n form (Object): [description of unit] \n unit_name (string): Name of unit \n\n Raises:\n ValidationError: If unit is already exist then give error for that.\n \"\"\" \n unit = Unit.query.filter(\n and_(Unit.name == unit_name.data, Unit.course == form.course)).first()\n if unit:\n raise ValidationError(\n \"That Unit is already exist. Please choose a different one.\")\n\n\ndef validate_chapter_no(form, chapter_no):\n \"\"\"Validation to chapter\n\n Args:\n form (object): form of description of chapter\n chapter_no (int): Chapter number from course\n\n Raises:\n ValidationError: This unit is alresady exist. Please choose different \n \"\"\" \n unit = Unit.query.filter(\n and_(Unit.chapter_no == chapter_no.data,\n Unit.course == form.course)).first()\n if unit:\n raise ValidationError(\n \"That Unit is already exist. Please choose a different one.\")\n\n\nclass CourseForm(FlaskForm):\n course = StringField(\"Course\",\n validators=[DataRequired(), validate_course_name])\n include_asked = BooleanField(\"Should paper include asked questions?\")\n submit = SubmitField(\"submit\")\n\n\nclass UnitForm(FlaskForm):\n chapter_no = IntegerField(\n \"Chapter No.\",\n validators=[\n DataRequired(),\n NumberRange(1, 101, \"Units can't be more than 100\"),\n validate_chapter_no,\n ],\n )\n name = StringField(\"Name\", validators=[DataRequired(), validate_unit_name])\n submit = SubmitField(\"submit\")\n\n def __init__(self, course):\n self.course = course\n super().__init__()\n","sub_path":"flaskapp/blueprints/courses/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"423318132","text":"import logging\nimport sys\nfrom datetime import datetime as dt\nfrom datetime import timedelta as td\n\nfrom freezegun import freeze_time\n\nfrom lib import biweeks_between_dates, weeks_between_dates, months_between_dates, semimonths_between_dates, \\\n create_invoice_for_period\nfrom rrg.lib.reminders import current_semimonth\nfrom rrg.lib.reminders import months_between_dates\nfrom rrg.lib.reminders import semimonths_between_dates\nfrom rrg.lib.reminders import weeks_between_dates\nfrom rrg.lib.reminders_generation import create_invoice_for_period\nfrom rrg.models import Citem\nfrom rrg.models import Client\nfrom rrg.models import ClientMemo\nfrom rrg.models import Contract\nfrom rrg.models import ContractItem\nfrom rrg.models import ContractItemCommItem\nfrom rrg.models import Employee\nfrom rrg.models import EmployeeMemo\nfrom rrg.models import EmployeePayment\nfrom rrg.models import Iitem\nfrom rrg.models import Invoice\nfrom rrg.models import Payroll\nfrom rrg.models import periods\nfrom rrg.models_api import session_maker\n\nlogging.basicConfig(filename='testing.log', level=logging.DEBUG)\nlogger = logging.getLogger('test')\n\nlogging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)\n\n\nclass Args(object):\n mysql_host = 'localhost'\n mysql_port = 3306\n db_user = 'root'\n db_pass = 'my_very_secret_password'\n db = 'rrg_test'\n\n\nclass Test:\n @freeze_time(\"2016-08-08\")\n def setup_class(self):\n\n assert sys._called_from_test\n\n self.payroll_run_date = dt(year=2016, month=8, day=8)\n self.common_contract_start = dt(year=2016, month=7, day=1)\n logger.debug('Setup test reminders test')\n self.args = Args()\n\n self.session = session_maker(self.args)\n\n self.session.begin_nested()\n with self.session.no_autoflush:\n objects = []\n client_active = Client(name='weekly', active=True, terms=30)\n client_inactive = Client(name='weekly-inactive', active=False, terms=30)\n objects.append(client_active)\n objects.append(client_inactive)\n\n self.session.bulk_save_objects(objects)\n\n clients = self.session.query(Client).all()\n cmemo0 = ClientMemo(client_id=clients[0].id, notes='cl1 memo', date=dt.now())\n cmemo1 = ClientMemo(client_id=clients[1].id, notes='cl2 memo', date=dt.now())\n objects = [cmemo0, cmemo1]\n\n self.session.bulk_save_objects(objects)\n objects = []\n\n employee_active = Employee(firstname='firstname', lastname='activelastname', active=True)\n employee_inactive = Employee(firstname='firstname', lastname='inactivelastname', active=False)\n employee_sales_person1 = Employee(firstname='sales', lastname='person1', active=True)\n employee_sales_person2 = Employee(firstname='sales', lastname='person2', active=True)\n\n objects.append(employee_active)\n objects.append(employee_inactive)\n objects.append(employee_sales_person1)\n objects.append(employee_sales_person2)\n\n self.session.bulk_save_objects(objects)\n\n employees = self.session.query(Employee).all()\n logger.debug('employees')\n for employee in employees:\n logger.debug(employee)\n\n ememo0 = EmployeeMemo(employee_id=employees[0].id, notes='emp1 memo', date=dt.now())\n ememo1 = EmployeeMemo(employee_id=employees[1].id, notes='emp2 memo', date=dt.now())\n ememo2 = EmployeeMemo(employee_id=employees[2].id, notes='emp3 memo', date=dt.now())\n ememo3 = EmployeeMemo(employee_id=employees[3].id, notes='emp4 memo', date=dt.now())\n objects = [ememo0, ememo1, ememo2, ememo3]\n\n self.session.bulk_save_objects(objects)\n\n objects = []\n\n # Active Contract\n objects.append(Contract(employee_id=employees[0].id,\n title='weekly-active-client-active-employee',\n client_id=clients[0].id,\n terms=clients[0].terms, active=True,\n period_id=periods['week'],\n startdate=self.common_contract_start))\n\n objects.append(Contract(employee_id=employees[0].id,\n title='biweekly-active-client-active-employee',\n client_id=clients[0].id,\n terms=clients[0].terms, active=True,\n period_id=periods['biweek'],\n startdate=self.common_contract_start))\n\n objects.append(Contract(employee_id=employees[0].id,\n title='semimonthly-active-client-active-employee',\n client_id=clients[0].id,\n terms=clients[0].terms, active=True,\n period_id=periods['semimonth'],\n startdate=self.common_contract_start))\n\n objects.append(Contract(employee_id=employees[0].id,\n title='monthly-active-client-active-employee',\n client_id=clients[0].id,\n terms=clients[0].terms, active=True,\n period_id=periods['month'],\n startdate=self.common_contract_start))\n\n # Active Contracts Inactive Employees\n objects.append(Contract(employee_id=employees[1].id,\n title='weekly-inactive-client-inactive-employee',\n client_id=clients[1].id,\n terms=clients[1].terms, active=True,\n period_id=periods['week'],\n startdate=self.common_contract_start))\n\n objects.append(Contract(employee_id=employees[1].id,\n title='biweekly-inactive-client-inactive-employee',\n client_id=clients[1].id,\n terms=clients[1].terms, active=True,\n period_id=periods['biweek'],\n startdate=self.common_contract_start))\n\n objects.append(Contract(employee_id=employees[1].id,\n title='semimonthly-inactive-client-inactive-employee',\n client_id=clients[1].id,\n terms=clients[1].terms, active=True,\n period_id=periods['semimonth'],\n startdate=self.common_contract_start))\n\n objects.append(Contract(employee_id=employees[1].id,\n title='monthly-inactive-client-inactive-employee',\n client_id=clients[1].id,\n terms=clients[1].terms, active=True,\n period_id=periods['month'],\n startdate=self.common_contract_start))\n\n objects.append(\n Contract(employee_id=employees[1].id, client_id=clients[1].id,\n terms=clients[1].terms, active=False,\n period_id=periods['week'], title='weekly-inactive',\n startdate=self.common_contract_start))\n\n objects.append(\n Contract(employee_id=employees[1].id,\n title='biweekly-inactive', client_id=clients[1].id,\n terms=clients[1].terms, active=False,\n period_id=periods['biweek'],\n startdate=self.common_contract_start))\n\n objects.append(Contract(employee_id=employees[1].id,\n title='semimonthly-inactive',\n client_id=clients[1].id,\n terms=clients[1].terms,\n active=False,\n period_id=periods['semimonth'],\n startdate=self.common_contract_start))\n\n objects.append(\n Contract(employee_id=employees[1].id, title='monthly-inactive',\n client_id=clients[1].id,\n terms=clients[1].terms, active=False,\n period_id=periods['month'],\n startdate=self.common_contract_start))\n\n self.session.bulk_save_objects(objects)\n\n contracts = self.session.query(Contract).all()\n logger.debug('contracts')\n logger.debug(contracts[0].id)\n for contract in contracts:\n logger.debug(contract)\n\n # contract items\n objects = []\n for i in xrange(0, 12):\n objects.append(\n ContractItem(contract_id=contracts[i].id,\n description='Regular', amt=10, active=True,\n cost=5))\n objects.append(\n ContractItem(contract_id=contracts[i].id,\n description='Double Time', amt=20,\n active=True, cost=10))\n\n self.session.bulk_save_objects(objects)\n contract_items = self.session.query(ContractItem).all()\n logger.debug('contract items')\n logger.debug(contract_items[0].id)\n for contract_item in contract_items:\n logger.debug(contract_item)\n\n # contract items commissions items\n objects = []\n for i in xrange(0, 24):\n objects.append(\n ContractItemCommItem(employee_id=employees[2].id,\n contract_item_id=contract_items[i].id,\n percent=38.5))\n\n objects.append(\n ContractItemCommItem(employee_id=employees[3].id,\n contract_item_id=contract_items[i].id,\n percent=61.5))\n\n self.session.bulk_save_objects(objects)\n\n # invoices\n weeks = weeks_between_dates(dt(year=2016, month=7, day=4),\n self.payroll_run_date)\n second_week_start, second_week_end = weeks[1]\n\n create_invoice_for_period(self.session, contracts[0],\n second_week_start.date(),\n second_week_end.date(),\n date=self.payroll_run_date.date())\n create_invoice_for_period(self.session, contracts[4],\n second_week_start.date(),\n second_week_end.date(),\n date=self.payroll_run_date.date())\n create_invoice_for_period(self.session, contracts[8],\n second_week_start.date(),\n second_week_end.date(),\n date=self.payroll_run_date.date())\n\n biweeks = biweeks_between_dates(dt(year=2016, month=7, day=4),\n self.payroll_run_date)\n\n start, end = biweeks[1]\n create_invoice_for_period(self.session, contracts[1], start.date(),\n end.date(),\n date=self.payroll_run_date.date())\n create_invoice_for_period(self.session, contracts[5], start.date(),\n end.date(),\n date=self.payroll_run_date.date())\n create_invoice_for_period(self.session, contracts[9], start.date(),\n end.date(),\n date=self.payroll_run_date.date())\n\n semimonths = semimonths_between_dates(\n dt(year=2016, month=7, day=4), self.payroll_run_date)\n\n start, end = semimonths[1]\n create_invoice_for_period(self.session, contracts[2], start.date(),\n end.date(),\n date=self.payroll_run_date.date())\n create_invoice_for_period(self.session, contracts[6], start.date(),\n end.date(),\n date=self.payroll_run_date.date())\n create_invoice_for_period(self.session, contracts[10],\n start.date(), end.date(),\n date=self.payroll_run_date.date())\n\n months = months_between_dates(dt(year=2016, month=7, day=4),\n self.payroll_run_date)\n\n start, end = months[1]\n create_invoice_for_period(self.session, contracts[3], start.date(),\n end.date(),\n date=self.payroll_run_date.date())\n create_invoice_for_period(self.session, contracts[7], start.date(),\n end.date(),\n date=self.payroll_run_date.date())\n create_invoice_for_period(self.session, contracts[11],\n start.date(), end.date(),\n date=self.payroll_run_date.date())\n\n invoices = self.session.query(Invoice).all()\n logger.debug('INVOICES CREATED')\n pr = Payroll(name='test pr', notes='bogus notes', amount=22.0, date=dt.now())\n self.session.bulk_save_objects([pr])\n payrolls = self.session.query(Payroll).all()\n for i in invoices:\n logger.debug(i)\n epay0 = EmployeePayment(employee_id=employees[0].id, amount=1.0, date=dt.now(), invoice_id=invoices[0].id,\n payroll_id=payrolls[0].id)\n epay1 = EmployeePayment(employee_id=employees[1].id, amount=2.0, date=dt.now(), invoice_id=invoices[1].id,\n payroll_id=payrolls[0].id)\n objects = [epay0, epay1]\n\n self.session.bulk_save_objects(objects)\n\n months_between_dates(self.payroll_run_date, self.payroll_run_date)\n\n current_semimonth(dt(year=self.payroll_run_date.year,\n month=self.payroll_run_date.month, day=16))\n\n assert not weeks_between_dates(self.payroll_run_date + td(days=1),\n self.payroll_run_date)\n\n def teardown_class(self):\n logger.debug('Teardown reminders')\n self.session.rollback()\n self.session.flush()\n\n def test_in_test(self):\n \"\"\"\n test _called_from_test\n :return:\n \"\"\"\n assert sys._called_from_test\n\n def test_client_delete_cascade(self):\n \"\"\"\n test delete cascade of client\n :return:\n \"\"\"\n\n assert 12 == self.session.query(Invoice).count()\n assert 24 == self.session.query(Iitem).count()\n assert 48 == self.session.query(Citem).count()\n assert 12 == self.session.query(Contract).count()\n assert 4 == self.session.query(Employee).count()\n assert 2 == self.session.query(Client).count()\n assert 2 == self.session.query(ClientMemo).count()\n assert 2 == self.session.query(EmployeePayment).count()\n assert 4 == self.session.query(EmployeeMemo).count()\n assert 48 == self.session.query(ContractItemCommItem).count()\n assert 1 == self.session.query(Payroll).count()\n logger.debug('DELETECLIENT')\n delcl = self.session.query(Client)[0]\n logger.debug(delcl)\n\n with self.session.no_autoflush:\n self.session.delete(self.session.query(Client)[0])\n assert 4 == self.session.query(Employee).count()\n assert 8 == self.session.query(Contract).count()\n assert 8 == self.session.query(Invoice).count()\n assert 16 == self.session.query(Iitem).count()\n assert 32 == self.session.query(Citem).count()\n assert 1 == self.session.query(Client).count()\n assert 1 == self.session.query(ClientMemo).count()\n assert 1 == self.session.query(EmployeePayment).count()\n assert 4 == self.session.query(EmployeeMemo).count()\n assert 32 == self.session.query(ContractItemCommItem).count()\n assert 1 == self.session.query(Payroll).count()\n","sub_path":"rrg/test/test_client_delete_cascade.py","file_name":"test_client_delete_cascade.py","file_ext":"py","file_size_in_byte":16917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"253075644","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread(\"test.jpg\", cv2.IMREAD_UNCHANGED)\n\ncv2.line(img, (0, 0), (150, 150), (255, 255, 255), 10) # 图像 起点 终点 颜色 粗细\ncv2.rectangle(img, (15, 15), (200, 300), (0, 255, 0), 5)\ncv2.circle(img, (50, 50), 30, (0, 0, 255), -1) # -1表示填充圆\n\npts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32)\ncv2.polylines(img, [pts], True, (0, 255, 255), 5) # 图像 点集 是否首尾相连 颜色 粗细\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\ncv2.putText(img, 'OpenCv Tuts!', (0, 130), font, 1, (200, 255, 255), 2, cv2.LINE_AA) # 图像 内容 位置 字体 字体大小 颜色 字体粗细 字间距\n\ncv2.imshow(\"img\", img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"Drawing and Writing on Image.py","file_name":"Drawing and Writing on Image.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"255087535","text":"import requests\nfrom requests_oauthlib import OAuth1\nimport json\n\nKEYS_FILE = 'KEYS.json'\nBASE_URL = 'https://api.twitter.com/1.1'\nFOLLOWERS_ID_PATH = '/followers/ids.json'\nFRIENDS_ID_PATH = '/friends/ids.json'\nBLOCK_IDS_PATH = '/blocks/ids.json'\nBLOCK_CREATE_PATH = '/blocks/create.json'\nBLOCK_DESTROY_PATH = '/blocks/destroy.json'\nFRIENDSHIP_CREATE_PATH = '/friendships/create.json'\n\n\ndef load_keys(key_name, file_name=KEYS_FILE):\n with open(file_name) as json_file:\n return json.load(json_file)[key_name]\n\n\nAPI_KEY = load_keys('API_KEY')\nAPI_SECRET_KEY = load_keys('API_SECRET_KEY')\nACCESS_TOKEN = load_keys('ACCESS_TOKEN')\nACCESS_TOKEN_SECRET = load_keys('ACCESS_TOKEN_SECRET')\nSCREEN_NAME = load_keys('SCREEN_NAME')\nAUTH = OAuth1(API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\n\n\ndef get_friends():\n ids = []\n next_cursor = -1\n screen_name_param = 'screen_name='\n cursor_param = 'cursor='\n while next_cursor != 0:\n url = BASE_URL + FRIENDS_ID_PATH + '?' + screen_name_param + SCREEN_NAME + '&' + cursor_param + str(next_cursor)\n response = requests.get(url, auth=AUTH)\n json_response = response.json()\n ids += json_response['ids']\n next_cursor = json_response['next_cursor']\n return ids\n\n\ndef get_followers():\n ids = []\n next_cursor = -1\n screen_name_param = 'screen_name='\n cursor_param = 'cursor='\n while next_cursor != 0:\n url = BASE_URL + FOLLOWERS_ID_PATH + '?' + screen_name_param + SCREEN_NAME + '&' + cursor_param + str(next_cursor)\n response = requests.get(url, auth=AUTH)\n json_response = response.json()\n ids += json_response['ids']\n next_cursor = json_response['next_cursor']\n return ids\n\n\ndef get_blocks():\n ids = []\n next_cursor = -1\n cursor_param = 'cursor='\n while next_cursor != 0:\n url = BASE_URL + BLOCK_IDS_PATH + '?' + cursor_param + str(next_cursor)\n response = requests.get(url, auth=AUTH)\n json_response = response.json()\n ids += json_response['ids']\n next_cursor = json_response['next_cursor']\n return ids\n\n\ndef create_block(id):\n user_id_param = 'user_id='\n url = BASE_URL + BLOCK_CREATE_PATH + '?' + user_id_param + str(id)\n requests.post(url, auth=AUTH)\n\n\ndef create_blocks(ids):\n for id in ids:\n create_block(id)\n\n\ndef destory_block(id):\n user_id_param = 'user_id='\n url = BASE_URL + BLOCK_DESTROY_PATH + '?' + user_id_param + str(id)\n requests.post(url, auth=AUTH)\n\n\ndef destroy_blocks(ids):\n for id in ids:\n destory_block(id)\n\n\ndef create_friend(id):\n user_id_param = 'user_id='\n url = BASE_URL + FRIENDSHIP_CREATE_PATH + '?' + user_id_param + str(id)\n requests.post(url, auth=AUTH)\n\n\ndef follow_back(new_friends, old_friends):\n friends_to_follow_back = list(set(old_friends) - set(new_friends))\n for friend in friends_to_follow_back:\n create_friend(friend)\n\n\ndef block(event, context):\n follower_ids = get_followers()\n old_friends = get_friends()\n create_blocks(follower_ids)\n blocked_ids = get_blocks()\n destroy_blocks(blocked_ids)\n new_friends = get_friends()\n follow_back(new_friends, old_friends)\n\n\nif __name__ == '__main__':\n block(1, 1)\n","sub_path":"block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"74865828","text":"import os \nfrom flask import Flask\n\n\ndef create_app(name, config_filename=None, **kwargs):\n app = Flask(name, static_url_path='')\n if config_filename:\n app.config.from_pyfile(config_filename)\n if 'VAPORATOR_SETTINGS' in os.environ:\n app.config.from_envvar('VAPORATOR_SETTINGS')\n app.config.update(\n **kwargs\n )\n # from nozzle.base import vap\n from nozzle.models import db\n # app.register_blueprint(vap)\n db.init_app(app)\n\n return app\n","sub_path":"nozzle/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"336543789","text":"from flask import Flask, render_template, redirect, request, url_for, session, escape\nimport data_manager\n\napp = Flask(__name__)\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\napp.config['UPLOAD_FOLDER'] = '/static/tmp'\n# Set the secret key to some random bytes. Keep this really secret!\napp.secret_key = b'_5#y2L\"F4Q8z\\n\\xec]/'\n\ndef check_login():\n if 'username' in session:\n login_data = {'okey': True,\n 'username': escape(session['username']),\n 'image': data_manager.get_user_pic(escape(session['username'])),\n 'id':data_manager.get_user_id_by_name(escape(session['username'])),\n 'permissions': data_manager.get_user_permission(escape(session['username']))}\n else:\n login_data = {'okey': False}\n if str(request.path) not in ('/login', '/register', '/logout'):\n session['last_page'] = request.path\n return login_data\n# ------------------------\n# main\n# ------------------------\n\n\n@app.route('/')\ndef route_index():\n login_data = check_login()\n sorting = {'direction': request.args.get('direction'),'sort': request.args.get('sort')}\n questions = data_manager.get_five_questions(sorting)\n tags = data_manager.get_tags_list()\n return render_template('list.html', questions=questions, tags=tags, index=True, sorting=sorting, login_data = login_data)\n\n@app.route('/list')\ndef route_list():\n login_data = check_login()\n sorting = {'direction': request.args.get('direction'),'sort': request.args.get('sort')}\n questions = data_manager.get_all_questions(sorting)\n tags = data_manager.get_tags_list()\n return render_template('list.html', questions = questions, tags=tags, sorting=sorting, login_data=login_data)\n\n@app.route('/search-result')\ndef route_search():\n login_data = check_login()\n sorting = {'direction': request.args.get('direction'),'sort': request.args.get('sort')}\n questions = data_manager.get_search_questions(request.args.get('search'),sorting)\n tags = data_manager.get_tags_list()\n return render_template('list.html',questions = questions, tags=tags, sorting=sorting, login_data=login_data)\n\n@app.route('/question/')\ndef route_question(question_id):\n login_data = check_login()\n question = data_manager.get_question_by_id(question_id)\n data_manager.page_view_counter('up', question_id)\n answers = data_manager.get_answers_by_question_id(question_id)\n question_comments = data_manager.get_comments('question',question_id)\n tags = data_manager.get_tags_by_question_id(question_id)\n answer_comments = []\n for answer in answers:\n answer_comments.append(data_manager.get_comments('answer', answer['id']))\n return render_template('question.html', question=question, answers = answers, question_comments=question_comments, answer_comments=answer_comments, tags=tags, login_data=login_data, moderators=['Admin','Moderator'])\n\n# ----------------------------------------------------------\n# user\n# ----------------------------------------------------------\n\n@app.route('/user/')\ndef route_user_profile(user_id):\n login_data = check_login()\n question, answers, comments = data_manager.get_user_activity(user_id)\n user = data_manager.get_user_details(user_id)\n for comment in comments:\n if comment['question_id'] is None:\n print('ID:',data_manager.get_question_id_by_answer_id(comment['answer_id']))\n comment['question_id'] = data_manager.get_question_id_by_answer_id(comment['answer_id'])\n return render_template('user.html', user=user, question=question, answers=answers, comments=comments, login_data=login_data)\n\n@app.route('/users')\ndef route_user_list():\n login_data = check_login()\n users = data_manager.get_all_user()\n return render_template('users.html', login_data=login_data, users=users)\n\n@app.route('/register', methods=('GET','POST'))\ndef route_user_register():\n login_data = check_login()\n if request.method == 'POST':\n success = data_manager.user_register(request.form['username'],request.form['password'],request.files)\n if success:\n return render_template('registration.html', login_data=login_data, mode='register', success=success)\n session['username'] = request.form['username']\n if escape(session['last_page']) != '/':\n return redirect(escape(session['last_page']))\n return redirect('/')\n return render_template('registration.html', login_data=login_data, mode='register')\n\n@app.route('/login', methods=('GET','POST'))\ndef route_user_login():\n success=False\n login_data = check_login()\n if request.method == 'POST':\n if data_manager.user_login(request.form['username'],request.form['password']):\n session['username'] = request.form['username']\n if escape(session['last_page']) != '/':\n return redirect(escape(session['last_page']))\n return redirect('/')\n else:\n success=True\n return render_template('registration.html', login_data=login_data, mode='login', success=success)\n\n@app.route('/logout')\ndef route_user_logout():\n session.pop('username', None)\n if escape(session['last_page']) != '/':\n return redirect(escape(session['last_page']))\n return redirect('/')\n\n# ----------------------------------------------------------\n# tags\n# ----------------------------------------------------------\n@app.route('/tags')\ndef route_get_tags():\n login_data = check_login()\n tags = data_manager.get_tags_with_question_number()\n return render_template('tags.html', tags=tags, login_data=login_data)\n\n@app.route('/question//edit-tag', methods=['GET','POST'])\ndef route_edit_tags(question_id):\n login_data = check_login()\n if request.method == 'POST':\n data_manager.manage_tags(request.form.getlist('tag'), question_id)\n return redirect(url_for('route_question', question_id=question_id))\n tags = data_manager.get_tags_checked(question_id)\n return render_template('add_tag.html', tags=tags, login_data=login_data)\n\n@app.route('/new-tag', methods=['GET','POST'])\ndef route_add_tag():\n login_data = check_login()\n if request.method == 'POST':\n data_manager.add_tag(request.form)\n return redirect(url_for('route_add_tag'))\n return render_template('new_tag.html', login_data=login_data)\n\n@app.route('/tag//edit', methods=['GET','POST'])\ndef route_edit_tag(tag_id):\n login_data = check_login()\n if request.method == 'POST':\n data_manager.edit_tag(request.form, tag_id)\n return redirect('/')\n return render_template('new_tag.html', login_data=login_data)\n\n@app.route('/tag//delete')\ndef route_delete_tag(tag_id):\n data_manager.delete_tag(tag_id)\n return redirect('/')\n\n# ----------------------------------------------------------\n# question\n# ----------------------------------------------------------\n\n@app.route('/add-question', methods=['GET', 'POST'])\ndef route_add_question():\n login_data = check_login()\n if request.method == 'POST':\n userid = data_manager.get_user_id_by_name(login_data['username'])\n question_id = data_manager.new_question(request.form, userid)\n return redirect('/question/' + str(question_id))\n return render_template('new_question.html', question = None, login_data=login_data)\n\n@app.route('/question//edit', methods=['GET', 'POST'])\ndef route_question_edit(question_id):\n login_data = check_login()\n if request.method == 'POST':\n data_manager.edit_question(request.form, question_id)\n return redirect('/question/'+question_id)\n question = data_manager.get_question_by_id(question_id)\n return render_template('new_question.html', question = question, login_data=login_data)\n\n@app.route('/question//delete')\ndef route_question_delete(question_id):\n data_manager.delete_question(question_id)\n return redirect('/')\n\n@app.route('/answer//mark')\ndef route_question_mark(answer_id):\n user_id = data_manager.get_user_id_by_answer_id(answer_id)\n data_manager.question_mark(answer_id, user_id['user_id'])\n question_id = data_manager.get_question_id_by_answer_id(answer_id)\n return redirect('/question/'+str(question_id))\n\n# ----------------------------------------------------------\n# answer\n# ----------------------------------------------------------\n\n@app.route('/question//new-answer', methods=['GET','POST'])\ndef route_new_answer(question_id):\n login_data = check_login()\n if request.method == 'POST':\n data_manager.new_answer(request.form, question_id, login_data['id'])\n return redirect('/question/'+str(question_id))\n return render_template('new_answer.html', question_id = question_id, answer=None, login_data=login_data)\n\n@app.route('/answer//edit', methods=['GET', 'POST'])\ndef route_answer_edit(answer_id):\n login_data = check_login()\n if request.method == 'POST':\n question_id = data_manager.edit_answer(request.form, answer_id)\n return redirect('/question/'+str(question_id))\n answer = data_manager.get_answer(answer_id)\n return render_template('new_answer.html',answer=answer, login_data=login_data)\n\n@app.route('/answer//delete')\ndef route_answer_delete(answer_id):\n question_id = data_manager.delete_answer(answer_id)\n return redirect('/question/'+ str(question_id))\n\n# ----------------------------------------------------------\n# comments\n# ----------------------------------------------------------\n\n@app.route('/question//new-comment', methods=['GET','POST'])\ndef route_new_comment_question(question_id):\n login_data = check_login()\n if request.method == 'POST':\n data_manager.new_comment('question', request.form, question_id, login_data['id'])\n return redirect('/question/'+str(question_id))\n return render_template('new_comment.html', comment=None, login_data=login_data)\n\n@app.route('/answer//new-comment', methods=['GET','POST'])\ndef route_new_comment_answer(answer_id):\n login_data = check_login()\n if request.method == 'POST':\n data_manager.new_comment('answer', request.form, answer_id, login_data['id'])\n return redirect('/question/'+str(data_manager.get_question_id_by_answer_id(answer_id)))\n return render_template('new_comment.html', comment=None, login_data=login_data)\n\n@app.route('/comment//edit', methods=['GET', 'POST'])\ndef route_comment_edit(comment_id):\n login_data = check_login()\n if request.method == 'POST':\n question_id = data_manager.edit_comment(request.form, comment_id)\n return redirect('/question/'+str(question_id))\n comment = data_manager.get_comment_by_id(comment_id)\n return render_template('new_comment.html', comment=comment, login_data=login_data)\n\n@app.route('/comment//delete')\ndef route_comment_delete(comment_id):\n question_id = data_manager.delete_comment(comment_id)\n return redirect('/question/'+ str(question_id))\n\n# ----------------------------------------------------------\n# vote\n# ----------------------------------------------------------\n\n@app.route('/answer//vote-up')\ndef route_vote_up(answer_id):\n user_id = data_manager.get_user_id_by_answer_id(answer_id)\n question_id = data_manager.vote('answer','up',answer_id)\n data_manager.answer_reputation(user_id['user_id'],'up')\n return redirect(url_for('route_question', question_id=question_id))\n\n@app.route('/answer//vote-down')\ndef route_vote_down(answer_id):\n user_id = data_manager.get_user_id_by_answer_id(answer_id)\n question_id = data_manager.vote('answer','down',answer_id)\n data_manager.answer_reputation(user_id['user_id'],'down')\n return redirect(url_for('route_question', question_id=question_id))\n\n@app.route('/question//vote-up')\ndef route_vote_up_question(question_id):\n user_id = data_manager.get_user_id_by_question_id(question_id)\n data_manager.vote('question', 'up', question_id)\n data_manager.question_reputation(user_id['user_id'], 'up')\n return redirect('/question/' + question_id)\n\n\n@app.route('/question//vote-down')\ndef route_vote_down_question(question_id):\n user_id = data_manager.get_user_id_by_question_id(question_id)\n data_manager.vote('question','down',question_id)\n data_manager.question_reputation(user_id['user_id'], 'down')\n return redirect('/question/'+question_id)\n\n# ----------------------------------------------------------\n# server\n# ----------------------------------------------------------\n\nif __name__ == '__main__':\n app.run(\n debug=True, # Allow verbose error reports\n port=5111 # Set custom port\n )\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":12924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"11342987","text":"import uiScriptLocale\n\nWINDOW_WIDTH = 184\nWINDOW_HEIGHT = 328 + 26\nif ENABLE_OFFLINE_PRIVATE_SHOP:\n\tWINDOW_WIDTH += 161\n\tWINDOW_HEIGHT += 58\n\nwindow = {\n\t\"name\" : \"PrivateShopBuilder\",\n\n\t\"x\" : 0,\n\t\"y\" : 0,\n\n\t\"style\" : [\"movable\", \"float\",],\n\n\t\"width\" : WINDOW_WIDTH,\n\t\"height\" : WINDOW_HEIGHT,\n\n\t\"children\" :\n\t[\n\t\t{\n\t\t\t\"name\" : \"board\",\n\t\t\t\"type\" : \"board\",\n\t\t\t\"style\" : [\"attach\",],\n\n\t\t\t\"x\" : 0,\n\t\t\t\"y\" : 0,\n\n\t\t\t\"width\" : WINDOW_WIDTH,\n\t\t\t\"height\" : WINDOW_HEIGHT,\n\n\t\t\t\"children\" :\n\t\t\t[\n\t\t\t\t## Title\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"TitleBar\",\n\t\t\t\t\t\"type\" : \"titlebar\",\n\t\t\t\t\t\"style\" : [\"attach\",],\n\n\t\t\t\t\t\"x\" : 8,\n\t\t\t\t\t\"y\" : 8,\n\n\t\t\t\t\t\"width\" : WINDOW_WIDTH - 15,\n\t\t\t\t\t\"color\" : \"gray\",\n\n\t\t\t\t\t\"children\" :\n\t\t\t\t\t[\n\t\t\t\t\t\t{ \"name\":\"TitleName\", \"type\":\"text\", \"x\":WINDOW_WIDTH / 2, \"y\":4, \"text\":uiScriptLocale.PRIVATE_SHOP_TITLE, \"text_horizontal_align\":\"center\" },\n\t\t\t\t\t],\n\t\t\t\t},\n\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"NameSlot\",\n\t\t\t\t\t\"type\" : \"slotbar\",\n\t\t\t\t\t\"x\" : 13,\n\t\t\t\t\t\"y\" : 35,\n\t\t\t\t\t\"width\" : 90 + 67,\n\t\t\t\t\t\"height\" : 18,\n\n\t\t\t\t\t\"children\" :\n\t\t\t\t\t[\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"NameLine\",\n\t\t\t\t\t\t\t\"type\" : \"text\",\n\t\t\t\t\t\t\t\"x\" : 3,\n\t\t\t\t\t\t\t\"y\" : 3,\n\t\t\t\t\t\t\t\"width\" : 157,\n\t\t\t\t\t\t\t\"height\" : 15,\n\t\t\t\t\t\t\t\"input_limit\" : 25,\n\t\t\t\t\t\t\t\"text\" : \"1234567890123456789012345\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\n\t\t\t\t## Item Slot\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"ItemSlot\",\n\t\t\t\t\t\"type\" : \"grid_table\",\n\n\t\t\t\t\t\"x\" : 12,\n\t\t\t\t\t\"y\" : 34 + 26,\n\n\t\t\t\t\t\"start_index\" : 0,\n\t\t\t\t\t\"x_count\" : 5,\n\t\t\t\t\t\"y_count\" : 8,\n\t\t\t\t\t\"x_step\" : 32,\n\t\t\t\t\t\"y_step\" : 32,\n\n\t\t\t\t\t\"image\" : \"d:/ymir work/ui/public/Slot_Base.sub\",\n\t\t\t\t},\n\n\t\t\t\t## Ok\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"OkButton\",\n\t\t\t\t\t\"type\" : \"button\",\n\n\t\t\t\t\t\"x\" : 21,\n\t\t\t\t\t\"y\" : 295 + 26,\n\n\t\t\t\t\t\"width\" : 61,\n\t\t\t\t\t\"height\" : 21,\n\n\t\t\t\t\t\"text\" : uiScriptLocale.OK,\n\n\t\t\t\t\t\"default_image\" : \"d:/ymir work/ui/public/middle_button_01.sub\",\n\t\t\t\t\t\"over_image\" : \"d:/ymir work/ui/public/middle_button_02.sub\",\n\t\t\t\t\t\"down_image\" : \"d:/ymir work/ui/public/middle_button_03.sub\",\n\t\t\t\t},\n\n\t\t\t\t## Close\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"CloseButton\",\n\t\t\t\t\t\"type\" : \"button\",\n\n\t\t\t\t\t\"x\" : 104,\n\t\t\t\t\t\"y\" : 295 + 26,\n\n\t\t\t\t\t\"width\" : 61,\n\t\t\t\t\t\"height\" : 21,\n\n\t\t\t\t\t\"text\" : uiScriptLocale.CLOSE,\n\n\t\t\t\t\t\"default_image\" : \"d:/ymir work/ui/public/middle_button_01.sub\",\n\t\t\t\t\t\"over_image\" : \"d:/ymir work/ui/public/middle_button_02.sub\",\n\t\t\t\t\t\"down_image\" : \"d:/ymir work/ui/public/middle_button_03.sub\",\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t],\n}\n\n\nif ENABLE_OFFLINE_PRIVATE_SHOP:\n\twindow[\"children\"][0][\"children\"][1][\"width\"] += 160\n\twindow[\"children\"][0][\"children\"][1][\"children\"][0][\"width\"] += 155\n\twindow[\"children\"][0][\"children\"][2][\"y\"] += 26\n\twindow[\"children\"][0][\"children\"][2][\"x_count\"] = 10\n\twindow[\"children\"][0][\"children\"][2][\"y_count\"] = 9\n\twindow[\"children\"][0][\"children\"][3][\"x\"] += 43\n\twindow[\"children\"][0][\"children\"][3][\"y\"] -= 288\n\twindow[\"children\"][0][\"children\"][3][\"vertical_align\"] = \"bottom\"\n\twindow[\"children\"][0][\"children\"][4][\"x\"] += 121\n\twindow[\"children\"][0][\"children\"][4][\"y\"] -= 288\n\twindow[\"children\"][0][\"children\"][4][\"vertical_align\"] = \"bottom\"\n\twindow[\"style\"].pop(1)\n\twindow[\"children\"][0][\"children\"][1][\"children\"][0][\"type\"] = \"editline\"\n\twindow[\"children\"][0][\"children\"][1][\"children\"][0][\"text\"] = \"\"\n\n\twindow[\"height\"] += 35\n\twindow[\"children\"][0][\"height\"] += 35\n\twindow[\"children\"][0][\"children\"] += [\n\t\t{\n\t\t\t\"name\" : \"Page1Button\",\n\t\t\t\"type\" : \"radio_button\",\n\n\t\t\t\"x\" : 82 - 25,\n\t\t\t\"y\" : 295 + 35 + 26 + 26,\n\n\t\t\t\"default_image\" : \"d:/ymir work/ui/game/shopsearchp2p/pageone.dds\",\n\t\t\t\"over_image\" : \"d:/ymir work/ui/game/shopsearchp2p/pageone_hover.dds\",\n\t\t\t\"down_image\" : \"d:/ymir work/ui/game/shopsearchp2p/pageone_active.dds\",\n\t\t},\n\t\t{\n\t\t\t\"name\" : \"Page2Button\",\n\t\t\t\"type\" : \"radio_button\",\n\n\t\t\t\"x\" : 242 + 25,\n\t\t\t\"y\" : 295 + 35 + 26 + 26,\n\n\t\t\t\"default_image\" : \"d:/ymir work/ui/game/shopsearchp2p/pagetwo.dds\",\n\t\t\t\"over_image\" : \"d:/ymir work/ui/game/shopsearchp2p/pagetwo_hover.dds\",\n\t\t\t\"down_image\" : \"d:/ymir work/ui/game/shopsearchp2p/pagetwo_active.dds\",\n\t\t},\n\t\t{\n\t\t\t\"name\" : \"Position\",\n\t\t\t\"type\" : \"text\",\n\t\t\t\"x\" : window[\"width\"] / 2,\n\t\t\t\"y\" : 34 + 29,\n\t\t\t\"text\" : \"\",\n\t\t\t\"text_horizontal_align\" : \"center\",\n\t\t},\n\t\t{\n\t\t\t\"name\" : \"time_window\",\n\t\t\t\"type\" : \"window\",\n\t\t\t\n\t\t\t\"x\" : 0,\n\t\t\t\"y\" : 295 + 35 + 35,\n\t\t\t\"width\" : 184,\n\t\t\t\"height\" : 22 + 20,\n\t\t\t\"horizontal_align\" : \"center\",\n\t\t\t\"children\" :\n\t\t\t(\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"time_select_img\",\n\t\t\t\t\t\"type\" : \"expanded_image\",\n\t\t\t\t\t\"x\" : 13,\n\t\t\t\t\t\"y\" : 20,\n\t\t\t\t\t\"x_scale\" : 0.759,\n\t\t\t\t\t\"y_scale\" : 1.0,\n\t\t\t\t\t\"image\" : \"d:/ymir work/ui/quest_re/button_one.sub\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"cur_time_text_window\",\n\t\t\t\t\t\"type\" : \"window\",\n\t\t\t\t\t\n\t\t\t\t\t\"x\" : 13,\n\t\t\t\t\t\"y\" : 20,\n\t\t\t\t\t\"width\" : 175-16,\n\t\t\t\t\t\"height\" : 16,\n\t\t\t\t\t\n\t\t\t\t\t\"children\" :\n\t\t\t\t\t(\n\t\t\t\t\t\t{\"name\":\"cur_time_text\", \"type\":\"text\", \"x\":0, \"y\":0, \"text\": \"-\", \"all_align\" : \"center\"},\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"time_select_button\",\n\t\t\t\t\t\"type\" : \"button\",\n\n\t\t\t\t\t\"x\" : 13 + 143,\n\t\t\t\t\t\"y\" : 20,\n\n\t\t\t\t\t\"default_image\" : \"d:/ymir work/ui/game/party_match/arrow_default.sub\",\n\t\t\t\t\t\"over_image\" : \"d:/ymir work/ui/game/party_match/arrow_over.sub\",\n\t\t\t\t\t\"down_image\" : \"d:/ymir work/ui/game/party_match/arrow_down.sub\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"time_select_pivot_window\",\n\t\t\t\t\t\"type\" : \"window\",\n\n\t\t\t\t\t\"x\" : 13,\n\t\t\t\t\t\"y\" : 16+20,\n\t\t\t\t\t\"width\" : 175,\n\t\t\t\t\t\"height\" : 0,\n\t\t\t\t},\n\t\t\t),\n\t\t},]\n\n","sub_path":"Client/Pack/root/uiscript/privateshopbuilder.py","file_name":"privateshopbuilder.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"272078126","text":"from timeit import default_timer as timer\nimport math\nimport time\n\ndef measure_time(func):\n def inner(*args,**kwargs):\n start = timer()\n\n func(*args, **kwargs)\n\n end = timer()\n\n print(f'function {func.__name__} took {round(end - start, 4)} for execution')\n return inner\n\n@measure_time\ndef factorial(num):\n time.sleep(3)\n print(math.factorial(num))\n\nfactorial(10)\n\n ","sub_path":"wrap_measure_time.py","file_name":"wrap_measure_time.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"427374740","text":"import numpy as np\nimport cv2\nimport os\nimport sys\nimport time\nfrom src.ViolenceDetector import *\nimport settings.DeploySettings as deploySettings\nimport settings.DataSettings as dataSettings\nimport src.data.ImageUtils as ImageUtils\nimport numpy as np\nimport operator\nimport random\nimport glob\nimport os.path\nfrom data import DataSet\nfrom processor import process_image\nfrom keras.models import load_model\n\n\n\ncap = cv2.VideoCapture(0)\nviolenceDetector = ViolenceDetector()\n\ncount=0\nbaslangicsn=list()\nbitissn=list()\n\t\n\t\nwhile(True):\n # Capture frame-by-frame\n ret, currentImage = cap.read()\n # do what you want with frame\n # and then save to file\n cv2.imwrite('/home/furkan/Desktop/image.png', currentImage)\n count +=1\n netInput = ImageUtils.ConvertImageFrom_CV_to_NetInput(currentImage)\n startDetectTime = time.time()\n isFighting = violenceDetector.Detect(netInput)\n endDetectTime = time.time()\n \n\n targetSize = deploySettings.DISPLAY_IMAGE_SIZE - 2*deploySettings.BORDER_SIZE\n currentImage = cv2.resize(currentImage, (targetSize, targetSize))\n\n if isFighting:#şiddet tespit edildi\n p=0\n font = cv2.FONT_HERSHEY_SIMPLEX\n bottomLeftCornerOfText = (10,50)\n fontScale = 1\n fontColor = (255,255,255)\n lineType = 2\n if len(baslangicsn)==len(bitissn):\n baslangicsn.append(count/25)\n\n cv2.putText(currentImage,\"Siddet tespit edildi\",bottomLeftCornerOfText,font,fontScale,fontColor,lineType)\n bottomLeftCornerOfText = (10,450)\n\n else:\n\n if len(baslangicsn)!=len(bitissn):\n bitissn.append(count/25)\n\t\t\n font = cv2.FONT_HERSHEY_SIMPLEX\n bottomLeftCornerOfText = (10,450)\n fontScale = 1\n fontColor = (255,255,255)\n lineType = 2\n cv2.putText(currentImage,\"Siddet tespit edilmedi\",bottomLeftCornerOfText,font,fontScale,fontColor,lineType)\n \n if cv2.waitKey(30) & 0xFF == ord('q'): # you can increase delay to 2 seconds here\n break\n\n\n\nbitissn.append(count/25)\nprint(len(baslangicsn),\"-------\",len(bitissn))\nfor index in range(len(baslangicsn)):\n try:\n print(\"tespit edilen sureler\",baslangicsn.pop(index),\"------\",bitissn.pop(index))\n except IndexError:\n print (\"----son----\")\n\n\n\n\ndef PrintUnsmoothedResults(unsmoothedResults_):\n\tprint(\"Unsmoothed results:\")\n\tprint(\"\\t [ \")\n\tprint(\"\\t \", end='')\n\tfor i, eachResult in enumerate(unsmoothedResults_):\n\t\tif i % 10 == 9:\n\t\t\tprint( str(eachResult)+\", \" )\n\t\t\tprint(\"\\t \", end='')\n\n\t\telse:\n\t\t\tprint( str(eachResult)+\", \", end='')\n\n\tprint(\"\\n\\t ]\")\n\t\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"RealTimeTesting.py","file_name":"RealTimeTesting.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"605153333","text":"\"\"\"\nDefines create, delete, get, list servers and get images and flavors.\n\"\"\"\nimport json\nfrom random import randrange\nfrom twisted.web.server import Request\nfrom mimic.canned_responses.nova import (get_server, list_server, get_limit,\n create_server, delete_server,\n get_image, get_flavor, list_addresses)\nfrom mimic.rest.mimicapp import MimicApp\n\nRequest.defaultContentType = 'application/json'\n\n\nclass NovaApi():\n \"\"\"\n Rest endpoints for mocked Nova Api.\n \"\"\"\n app = MimicApp()\n\n @app.route('/v2//servers', methods=['POST'])\n def create_server(self, request, tenant_id):\n \"\"\"\n Returns a generic create server response, with status 'ACTIVE'.\n \"\"\"\n server_id = 'test-server{0}-id-{0}'.format(str(randrange(9999999999)))\n content = json.loads(request.content.read())\n response_data = create_server(tenant_id, content['server'], server_id)\n request.setResponseCode(response_data[1])\n return json.dumps(response_data[0])\n\n @app.route('/v2//servers/', methods=['GET'])\n def get_server(self, request, tenant_id, server_id):\n \"\"\"\n Returns a generic get server response, with status 'ACTIVE'\n \"\"\"\n response_data = get_server(server_id)\n request.setResponseCode(response_data[1])\n return json.dumps(response_data[0])\n\n @app.route('/v2//servers', methods=['GET'])\n def list_servers(self, request, tenant_id):\n \"\"\"\n Returns list of servers that were created by the mocks, with the given name.\n \"\"\"\n server_name = ''\n if 'name' in request.args:\n server_name = request.args['name'][0]\n response_data = list_server(tenant_id, server_name, details=False)\n request.setResponseCode(response_data[1])\n return json.dumps(response_data[0])\n\n @app.route('/v2//servers/detail', methods=['GET'])\n def list_servers_with_details(self, request, tenant_id):\n \"\"\"\n Returns list of servers that were created by the mocks, with details such as the metadata.\n \"\"\"\n response_data = list_server(tenant_id)\n request.setResponseCode(response_data[1])\n return json.dumps(response_data[0])\n\n @app.route('/v2//servers/', methods=['DELETE'])\n def delete_server(self, request, tenant_id, server_id):\n \"\"\"\n Returns a 204 response code, for any server id'\n \"\"\"\n response_data = delete_server(server_id)\n request.setResponseCode(response_data[1])\n return json.dumps(response_data[0])\n\n @app.route('/v2//images/', methods=['GET'])\n def get_image(self, request, tenant_id, image_id):\n \"\"\"\n Returns a get image response, for any given imageid\n \"\"\"\n response_data = get_image(image_id)\n request.setResponseCode(response_data[1])\n return json.dumps(response_data[0])\n\n @app.route('/v2//flavors/', methods=['GET'])\n def get_flavor(self, request, tenant_id, flavor_id):\n \"\"\"\n Returns a get flavor response, for any given flavorid\n \"\"\"\n response_data = get_flavor(flavor_id)\n request.setResponseCode(response_data[1])\n return json.dumps(response_data[0])\n\n @app.route('/v2//limits', methods=['GET'])\n def get_limit(self, request, tenant_id):\n \"\"\"\n Returns a get flavor response, for any given flavorid\n \"\"\"\n request.setResponseCode(200)\n return json.dumps(get_limit())\n\n @app.route('/v2//servers//ips', methods=['GET'])\n def get_ips(self, request, tenant_id, server_id):\n \"\"\"\n Returns a get flavor response, for any given flavorid.\n (currently the GET ips works only after a GET server after the server is created)\n \"\"\"\n response_data = list_addresses(server_id)\n request.setResponseCode(response_data[1])\n return json.dumps(response_data[0])\n","sub_path":"mimic/rest/nova_api.py","file_name":"nova_api.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"288265142","text":"\r\n\r\ndef sum_digits(num):\r\n tot_sum = 0\r\n while num > 0:\r\n tot_sum += int(num % 10)\r\n num //= 10\r\n return tot_sum\r\n\r\ndef fact(num):\r\n if num == 0: return 1\r\n else:\r\n return num*fact(num-1)\r\n\r\nprint(sum_digits(fact(100)))","sub_path":"Prob_20.py","file_name":"Prob_20.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"152135337","text":"import logging\nimport datetime\n\nfrom flask import request\n\n\nclass CustomFormatter(logging.Formatter):\n converter=datetime.datetime.utcfromtimestamp\n def formatTime(self, record, datefmt=None):\n ct = self.converter(record.created)\n if datefmt:\n s = ct.strftime(datefmt)\n else:\n t = ct.strftime('%Y-%m-%dT%H:%M:%S')\n s = \"%s.%03dZ\" % (t, record.msecs)\n return s\n\ndef create_stream_handler():\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(\n CustomFormatter('[%(levelname)s] %(asctime)s %(message)s')\n )\n return stream_handler\n\ndef create_file_handler(out_path):\n file_handler = logging.FileHandler(out_path)\n file_handler.setFormatter(\n CustomFormatter('[%(levelname)s] %(asctime)s %(message)s')\n )\n return file_handler\n\ndef log_requests(app):\n @app.after_request\n def after_request(response):\n app.logger.info('{code} {latency} {clientip} {method} {path}'.format(\n code=response.status_code,\n latency=\"100ms\",\n clientip=request.remote_addr,\n method=request.method,\n path=request.full_path\n ))\n return response","sub_path":"pastes-api/pastes_api/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"479280775","text":"from mobile.api.MonthlyFeeApi import app\nimport json\nimport pytest\n\n@pytest.mark.parametrize(\"plan, entame_free\",\n [\n (\"g1\", \"true\"),\n ])\ndef test_1ギガプランでエンタメフリーありならエラー(plan, entame_free):\n response = app.test_client().get(\n \"/monthly-fee?plan={plan}&entame_free={entame_free}\".format(\n plan=plan, entame_free=entame_free\n )\n )\n\n assert response.status_code >= 400\n\n\n@pytest.mark.parametrize(\"plan, entame_free, monthly_fee\",\n [\n (\"g1\", \"false\", 1000),\n (\"g3\", \"false\", 2000),\n (\"g30\", \"false\", 6000),\n (\"g3\", \"true\", 2000 + 1200),\n (\"g30\", \"true\", 6000 + 1200),\n ])\ndef test_プランとエンタメフリーオプション(plan, entame_free, monthly_fee):\n response = app.test_client().get(\n \"/monthly-fee?plan={plan}&entame_free={entame_free}\".format(\n plan=plan, entame_free=entame_free\n )\n )\n\n data_dict = response.get_data(as_text=True)\n data = json.loads(data_dict)\n\n assert response.status_code == 200\n assert data[\"monthly_fee\"] == monthly_fee\n","sub_path":"src/test/python/api/TestMonthlyFeeApiSpec.py","file_name":"TestMonthlyFeeApiSpec.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"433163268","text":"# Copyright 2017 Neural Networks and Deep Learning lab, MIPT\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 itertools\nfrom typing import List, Iterable\n\nimport numpy as np\n\nfrom deeppavlov.core.common.metrics_registry import register_metric\n\n\n@register_metric('accuracy')\ndef accuracy(y_true: [list, np.ndarray], y_predicted: [list, np.ndarray]) -> float:\n \"\"\"\n Calculate accuracy in terms of absolute coincidence\n\n Args:\n y_true: array of true values\n y_predicted: array of predicted values\n\n Returns:\n fraction of absolutely coincidental samples\n \"\"\"\n examples_len = len(y_true)\n # if y1 and y2 are both arrays, == can be erroneously interpreted as element-wise equality\n\n def _are_equal(y1, y2):\n answer = (y1 == y2)\n if isinstance(answer, np.ndarray):\n answer = answer.all()\n return answer\n\n equalities = [_are_equal(y1, y2) for y1, y2 in zip(y_true, y_predicted)]\n correct = sum(equalities)\n return correct / examples_len if examples_len else 0\n\n\n@register_metric('multitask_accuracy')\ndef multitask_accuracy(*args) -> float:\n \"\"\"\n Accuracy for multiple simultaneous tasks.\n\n Args:\n *args: a list of `2n` inputs. The first `n` inputs are the correct answers for `n` tasks,\n and the last `n` are the predicted ones.\n\n Returns:\n The percentage of inputs where the answers for all `n` tasks are correct.\n \"\"\"\n n = len(args)\n y_true_by_tasks, y_predicted_by_tasks = args[:n // 2], args[n // 2:]\n y_true, y_predicted = list(zip(*y_true_by_tasks)), list(zip(*y_predicted_by_tasks))\n return accuracy(y_true, y_predicted)\n\n\n@register_metric('multitask_sequence_accuracy')\ndef multitask_sequence_accuracy(*args) -> float:\n \"\"\"\n Accuracy for multiple simultaneous sequence labeling (tagging) tasks.\n For each sequence the model checks whether all its elements\n are labeled correctly for all the individual taggers.\n\n Args:\n *args: a list of `2n` inputs. The first `n` inputs are the correct answers for `n` tasks,\n and the last `n` are the predicted ones. For each task an\n\n Returns:\n The percentage of sequences where all the items has correct answers for all `n` tasks.\n\n \"\"\"\n n = len(args)\n y_true_by_tasks, y_predicted_by_tasks = args[:n // 2], args[n // 2:]\n y_true_by_sents = list(zip(*y_true_by_tasks))\n y_predicted_by_sents = list(zip(*y_predicted_by_tasks))\n y_true = list(list(zip(*elem)) for elem in y_true_by_sents)\n y_predicted = list(list(zip(*elem)) for elem in y_predicted_by_sents)\n return accuracy(y_true, y_predicted)\n\n\n@register_metric('multitask_token_accuracy')\ndef multitask_token_accuracy(*args) -> float:\n \"\"\"\n Per-item accuracy for multiple simultaneous sequence labeling (tagging) tasks.\n\n Args:\n *args: a list of `2n` inputs. The first `n` inputs are the correct answers for `n` tasks\n and the last `n` are the predicted ones. For each task an\n\n Returns:\n The percentage of sequence elements for which the answers for all `n` tasks are correct.\n\n \"\"\"\n n = len(args)\n y_true_by_tasks, y_predicted_by_tasks = args[:n // 2], args[n // 2:]\n y_true_by_sents = list(zip(*y_true_by_tasks))\n y_predicted_by_sents = list(zip(*y_predicted_by_tasks))\n y_true = list(list(zip(*elem)) for elem in y_true_by_sents)\n y_predicted = list(list(zip(*elem)) for elem in y_predicted_by_sents)\n return per_token_accuracy(y_true, y_predicted)\n\n\n@register_metric('sets_accuracy')\ndef sets_accuracy(y_true: [list, np.ndarray], y_predicted: [list, np.ndarray]) -> float:\n \"\"\"\n Calculate accuracy in terms of sets coincidence\n\n Args:\n y_true: true values\n y_predicted: predicted values\n\n Returns:\n portion of samples with absolutely coincidental sets of predicted values\n \"\"\"\n examples_len = len(y_true)\n correct = sum([set(y1) == set(y2) for y1, y2 in zip(y_true, y_predicted)])\n return correct / examples_len if examples_len else 0\n\n\n@register_metric('slots_accuracy')\ndef slots_accuracy(y_true, y_predicted):\n y_true = [{tag.split('-')[-1] for tag in s if tag != 'O'} for s in y_true]\n y_predicted = [set(s.keys()) for s in y_predicted]\n return accuracy(y_true, y_predicted)\n\n\n@register_metric('per_token_accuracy')\ndef per_token_accuracy(y_true, y_predicted):\n y_true = list(itertools.chain(*y_true))\n y_predicted = itertools.chain(*y_predicted)\n examples_len = len(y_true)\n correct = sum([y1 == y2 for y1, y2 in zip(y_true, y_predicted)])\n return correct / examples_len if examples_len else 0\n\n\n# region go-bot metrics\n\n@register_metric('per_item_dialog_accuracy')\ndef per_item_dialog_accuracy(y_true, y_predicted: List[List[str]]):\n # todo metric classes???\n y_true = [y['text'] for dialog in y_true for y in dialog]\n y_predicted = itertools.chain(*y_predicted)\n examples_len = len(y_true)\n correct = sum([y1.strip().lower() == y2.strip().lower() for y1, y2 in zip(y_true, y_predicted)])\n return correct / examples_len if examples_len else 0\n\n\n@register_metric('acc')\ndef round_accuracy(y_true, y_predicted):\n \"\"\"\n Rounds predictions and calculates accuracy in terms of absolute coincidence.\n\n Args:\n y_true: list of true values\n y_predicted: list of predicted values\n\n Returns:\n portion of absolutely coincidental samples\n \"\"\"\n if isinstance(y_predicted[0], np.ndarray):\n predictions = [np.round(x) for x in y_predicted]\n else:\n predictions = [round(x) for x in y_predicted]\n examples_len = len(y_true)\n correct = sum([y1 == y2 for y1, y2 in zip(y_true, predictions)])\n return correct / examples_len if examples_len else 0\n\n\n@register_metric('kbqa_accuracy')\ndef kbqa_accuracy(y_true, y_predicted):\n total_correct = 0\n for answer_true, answer_predicted in zip(y_true, y_predicted):\n if answer_predicted in answer_true:\n total_correct += 1\n\n return total_correct / len(y_true) if len(y_true) else 0\n","sub_path":"deeppavlov/metrics/accuracy.py","file_name":"accuracy.py","file_ext":"py","file_size_in_byte":6582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"108776037","text":"\"\"\"add labels table\n\nRevision ID: 719dd2aacc9a\nRevises: a6b00ae45279\nCreate Date: 2020-08-05 22:41:30.611193\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\nfrom bentoml.yatai.label_store import Label\n\n# revision identifiers, used by Alembic.\nrevision = '719dd2aacc9a'\ndown_revision = 'a6b00ae45279'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n bind = op.get_bind()\n Label.__table__.create(bind)\n with op.batch_alter_table('deployments') as batch_op:\n batch_op.drop_column('labels')\n\n\ndef downgrade():\n op.add_column('deployments', sa.Column('labels', sa.JSON, default={}))\n op.drop_table('labels')\n","sub_path":"bentoml/yatai/migrations/versions/719dd2aacc9a_add_labels_table.py","file_name":"719dd2aacc9a_add_labels_table.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"274866431","text":"import codecs\nimport datetime\nimport fnmatch\nimport logging\nimport operator\nimport os\nimport polib\nimport shutil\nimport silme.core\nimport silme.format.properties\nimport silme.format.dtd\nimport silme.format.ini\nimport StringIO\nimport urllib2\nimport zipfile\n\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom pontoon.administration.vcs import update_from_vcs\nfrom translate.storage import xliff\n\nfrom l20n.format import (\n parser as L20nParser,\n serializer as L20nSerializer,\n ast as L20nast\n)\n\nfrom pontoon.base import MOZILLA_REPOS\nfrom pontoon.base.models import (\n Entity,\n Locale,\n Resource,\n Stats,\n Translation,\n save_entity,\n save_translation,\n update_entity_count,\n update_stats,\n)\n\nlog = logging.getLogger('pontoon')\n\n\ndef get_locale_paths(project, locale, source_paths, source_directory):\n \"\"\"Get paths to locale files.\"\"\"\n\n locale_paths = []\n locale_directory = get_locale_directory(project, locale)[\"name\"]\n\n for path in source_paths:\n locale_path = path.replace(\n '/' + source_directory + '/', '/' + locale_directory + '/')\n\n if locale_path.endswith('.pot'):\n locale_path = locale_path[:-1]\n\n if os.path.exists(locale_path):\n locale_paths.append(locale_path)\n\n return locale_paths\n\n\ndef get_locale_directory(project, locale):\n \"\"\"\n Get path to the directory with locale files.\n\n Args:\n project: Project instance\n locale: Locale instance\n Returns:\n Dict with directory name and path as keys.\n \"\"\"\n\n path = project.repository_path\n\n for root, dirnames, filenames in os.walk(path):\n # Ignore hidden folders\n dirnames[:] = [d for d in dirnames if not d[0] == '.']\n\n for dirname in fnmatch.filter(dirnames, locale.code):\n return {\n 'name': dirname,\n 'path': os.path.join(root, dirname),\n }\n\n # Also check for locale variants with underscore, e.g. de_AT\n for dirname in fnmatch.filter(dirnames, locale.code.replace('-', '_')):\n return {\n 'name': dirname,\n 'path': os.path.join(root, dirname),\n }\n\n # Projects not using locale directories (format=file)\n if project.repository_type == 'file':\n return {\n 'name': '',\n 'path': path,\n }\n\n error = \"Directory for locale %s not found.\" % locale.code\n log.error(error)\n raise Exception(error)\n\n\ndef detect_format(path):\n \"\"\"Detect file format from source directory path.\"\"\"\n\n for root, dirnames, filenames in os.walk(path):\n # Ignore hidden files\n filenames = [f for f in filenames if not f[0] == '.']\n\n for extension in ['pot'] + [i[0] for i in Resource.FORMAT_CHOICES]:\n for filename in fnmatch.filter(filenames, '*.' + extension):\n return 'po' if extension == 'pot' else extension\n\n\ndef get_format(path):\n \"\"\"Get file format from file path based on extension.\"\"\"\n\n return os.path.splitext(path)[1][1:].lower()\n\n\ndef get_source_paths(path):\n \"\"\"Get paths to source files.\"\"\"\n\n source_paths = []\n\n for root, dirnames, filenames in os.walk(path):\n # Ignore hidden files\n filenames = [f for f in filenames if not f[0] == '.']\n\n for extension in ['pot'] + [i[0] for i in Resource.FORMAT_CHOICES]:\n for filename in fnmatch.filter(filenames, '*.' + extension):\n source_paths.append(os.path.join(root, filename))\n\n return source_paths\n\n\ndef get_source_directory(path):\n \"\"\"Get name and path of the directory with source files.\"\"\"\n\n for root, dirnames, filenames in os.walk(path):\n # Ignore hidden folders\n dirnames[:] = [d for d in dirnames if not d[0] == '.']\n\n for directory in ('templates', 'en-US', 'en'):\n for dirname in fnmatch.filter(dirnames, directory):\n source_directory_path = os.path.join(root, dirname)\n if detect_format(source_directory_path):\n return {\n 'name': dirname,\n 'path': source_directory_path,\n }\n\n # Projects not using locale directories (format=file)\n return {\n 'name': '',\n 'path': path,\n }\n\n\ndef get_repository_path_master(project):\n \"\"\"Get path to master project folder containing repository files.\"\"\"\n\n return os.path.join(\n settings.MEDIA_ROOT, project.repository_type, project.slug)\n\n\ndef get_relative_path(path, locale):\n \"\"\"Get relative path to repository file.\"\"\"\n\n locale_directory = locale.code\n if 'templates' in path:\n locale_directory = 'templates'\n\n # Also check for locale variants with underscore, e.g. de_AT\n underscore = locale.code.replace('-', '_')\n if '/' + underscore + '/' in path:\n locale_directory = underscore\n\n return path.split('/' + locale_directory + '/')[-1]\n\n\ndef copy_from_source(file_path, repository_path, relative_path):\n \"\"\"Create folders and copy files from source\"\"\"\n\n basedir = os.path.dirname(file_path)\n source_directory = get_source_directory(repository_path)\n\n if not os.path.exists(basedir):\n os.makedirs(basedir)\n\n try:\n shutil.copy(\n os.path.join(source_directory['path'], relative_path), file_path)\n\n # Obsolete files\n except Exception as e:\n log.debug(e)\n return\n\n\ndef parse_lang(path):\n \"\"\"Parse a dotlang file and return a dict of translations.\"\"\"\n trans = {}\n\n if not os.path.exists(path):\n return trans\n\n with codecs.open(path, 'r', 'utf-8', errors='replace') as lines:\n source = None\n comment = ''\n tags = []\n counter = 0\n\n for line in lines:\n line = line.strip()\n if not line:\n continue\n\n if line[0] == '#' and line[1] != '#':\n comment = line.lstrip('#').strip()\n continue\n\n if line[0] == ';':\n source = line[1:]\n\n elif source:\n for tag in ('{ok}', '{l10n-extra}'):\n if line.lower().endswith(tag):\n line = line[:-len(tag)]\n tags.append(tag)\n line = line.strip()\n trans[source] = [counter, comment, line, tags]\n comment = ''\n tags = []\n counter += 1\n\n # Sort by counter\n trans = sorted(trans.iteritems(), key=operator.itemgetter(1))\n return trans\n\n\ndef extract_po(project, locale, path, entities=False):\n \"\"\"Extract .po (gettext) file with path and save or update in DB.\"\"\"\n\n try:\n po = polib.pofile(path)\n\n relative_path = get_relative_path(path, locale)\n if relative_path[-1] == 't':\n relative_path = relative_path[:-1]\n\n resource, created = Resource.objects.get_or_create(\n project=project, path=relative_path, format='po')\n\n if entities:\n for order, entry in enumerate(po):\n if not entry.obsolete:\n save_entity(resource=resource,\n string=entry.msgid,\n string_plural=entry.msgid_plural,\n comment=entry.comment,\n order=order,\n source=entry.occurrences)\n\n update_entity_count(resource)\n\n else:\n for entry in (po.translated_entries() + po.fuzzy_entries()):\n if not entry.obsolete:\n\n # Entities without plurals\n if len(entry.msgstr) > 0:\n try:\n e = Entity.objects.get(\n resource=resource,\n string=entry.msgid)\n save_translation(\n entity=e,\n locale=locale,\n string=entry.msgstr,\n fuzzy='fuzzy' in entry.flags)\n\n except Entity.DoesNotExist:\n continue\n\n # Pluralized entities\n elif len(entry.msgstr_plural) > 0:\n try:\n e = Entity.objects.get(\n resource=resource,\n string=entry.msgid)\n for k in entry.msgstr_plural:\n save_translation(\n entity=e,\n locale=locale,\n string=entry.msgstr_plural[k],\n plural_form=k,\n fuzzy='fuzzy' in entry.flags)\n\n except Entity.DoesNotExist:\n continue\n\n update_stats(resource, locale)\n\n log.debug(\"[\" + locale.code + \"]: \" + path + \" saved to DB.\")\n except Exception as e:\n log.critical('PoExtractError for %s: %s' % (path, e))\n\n\ndef extract_xliff(project, locale, path, entities=False):\n \"\"\"Extract .xliff file with path and save or update in DB.\"\"\"\n\n with open(path) as f:\n xf = xliff.xlifffile(f)\n\n relative_path = get_relative_path(path, locale)\n resource, created = Resource.objects.get_or_create(\n project=project, path=relative_path, format='xliff')\n\n if entities:\n for order, unit in enumerate(xf.units):\n save_entity(\n resource=resource,\n string=unicode(unit.get_rich_source()[0]),\n key=unit.getid(),\n comment=unit.getnotes(),\n order=order)\n\n update_entity_count(resource)\n\n else:\n for unit in xf.units:\n translation = unicode(unit.get_rich_target()[0])\n if translation:\n try:\n e = Entity.objects.get(\n resource=resource, key=unit.getid())\n save_translation(\n entity=e, locale=locale, string=translation)\n\n except Entity.DoesNotExist:\n continue\n\n update_stats(resource, locale)\n\n log.debug(\"[\" + locale.code + \"]: \" + path + \" saved to DB.\")\n\n\ndef extract_silme(parser, project, locale, path, entities=False):\n \"\"\"Extract file with path using silme and save or update in DB.\"\"\"\n\n with codecs.open(path, 'r', 'utf-8') as f:\n structure = parser.get_structure(f.read())\n format = str(parser).split('.')[2]\n\n comment = \"\"\n order = 0\n relative_path = get_relative_path(path, locale)\n resource, created = Resource.objects.get_or_create(\n project=project, path=relative_path, format=format)\n\n for obj in structure:\n if isinstance(obj, silme.core.entity.Entity):\n if entities:\n save_entity(resource=resource, string=obj.value,\n key=obj.id, comment=comment, order=order)\n comment = \"\"\n order += 1\n else:\n try:\n e = Entity.objects.get(resource=resource, key=obj.id)\n save_translation(\n entity=e,\n locale=locale,\n string=obj.value)\n\n except Entity.DoesNotExist:\n continue\n\n elif isinstance(obj, silme.core.structure.Comment):\n if entities:\n comment = ''.join(unicode(i) for i in obj)\n\n if entities:\n update_entity_count(resource)\n else:\n update_stats(resource, locale)\n\n log.debug(\"[\" + locale.code + \"]: \" + path + \" saved to DB.\")\n\n\ndef extract_properties(project, locale, path, entities=False):\n \"\"\"Extract .properties file with path and save or update in DB.\"\"\"\n\n parser = silme.format.properties.FormatParser\n extract_silme(parser, project, locale, path, entities)\n\n\ndef extract_dtd(project, locale, path, entities=False):\n \"\"\"Extract .dtd file with path and save or update in DB.\"\"\"\n\n parser = silme.format.dtd.FormatParser\n extract_silme(parser, project, locale, path, entities)\n\n\ndef extract_ini(project, locale, path, entities=False):\n \"\"\"Extract .ini file with path and save or update in DB.\"\"\"\n\n parser = silme.format.ini.FormatParser\n extract_silme(parser, project, locale, path, entities)\n\n\ndef extract_lang(project, locale, path, entities=False):\n \"\"\"Extract .lang file with path and save or update in DB.\"\"\"\n\n lang = parse_lang(path)\n relative_path = get_relative_path(path, locale)\n\n resource, created = Resource.objects.get_or_create(\n project=project, path=relative_path, format='lang')\n\n if entities:\n for order, (key, value) in enumerate(lang):\n save_entity(\n resource=resource, string=key, comment=value[1], order=order)\n\n update_entity_count(resource)\n\n else:\n for key, value in lang:\n if key != value[2] or '{ok}' in value[3]:\n try:\n e = Entity.objects.get(resource=resource, string=key)\n save_translation(\n entity=e, locale=locale, string=value[2])\n\n except Entity.DoesNotExist:\n continue\n\n update_stats(resource, locale)\n\n log.debug(\"[\" + locale.code + \"]: \" + path + \" saved to DB.\")\n\n\ndef store_l20n(\n entities, resource, key, string, comment, locale, order,\n string_plural=\"\", plural_form=None):\n \"\"\"Store .l20n entity or translation.\"\"\"\n\n if entities:\n save_entity(\n resource=resource, string=string, string_plural=string_plural,\n comment=comment, key=key, order=order)\n\n else:\n try:\n e = Entity.objects.get(resource=resource, key=key)\n save_translation(\n entity=e, locale=locale, string=string,\n plural_form=plural_form)\n except Entity.DoesNotExist:\n pass\n\n\ndef extract_l20n(project, locale, path, entities=False):\n \"\"\"Extract .l20n file with path and save or update in DB.\"\"\"\n\n parser = L20nParser.L20nParser()\n\n with codecs.open(path, 'r', 'utf-8') as f:\n structure = parser.parse(f.read())\n\n comment = \"\"\n order = 0\n\n relative_path = get_relative_path(path, locale)\n resource, created = Resource.objects.get_or_create(\n project=project, path=relative_path, format='l20n')\n\n for obj in structure.body:\n # Entities\n if obj.type == \"Entity\":\n\n # Simple\n if obj.value.type == \"String\":\n key = obj.id.name\n string = obj.value.source\n\n store_l20n(\n entities, resource, key, string, comment, locale,\n order)\n\n comment = \"\"\n order += 1\n\n # Plurals\n elif obj.value.type == \"Hash\":\n key = obj.id.name\n string_plural = \"\"\n plural_form = None\n\n # Get strings\n for item in obj.value.items:\n if entities:\n if item.id.name == \"one\":\n string = item.value.source\n\n elif item.id.name == \"many\":\n string_plural = item.value.source\n\n else:\n string = item.value.source\n idx = Locale.cldr_plural_to_id(item.id.name)\n plural_form = locale.cldr_plurals_list().index(idx)\n\n store_l20n(\n entities, resource, key, string, comment, locale,\n order, string_plural, plural_form)\n\n comment = \"\"\n order += 1\n\n # Attributes\n for attr in obj.attrs:\n key = \".\".join([obj.id.name, attr.id.name])\n string = attr.value.source\n\n store_l20n(\n entities, resource, key, string, comment, locale,\n order)\n\n comment = \"\"\n order += 1\n\n # Comments\n elif obj.type == \"Comment\":\n comment = obj.body\n\n if entities:\n update_entity_count(resource)\n else:\n update_stats(resource, locale)\n\n log.debug(\"[\" + locale.code + \"]: \" + path + \" saved to DB.\")\n\n\ndef extract_inc(project, locale, path, entities=False):\n \"\"\"Extract .inc file with path and save or update in DB.\"\"\"\n\n with codecs.open(path, 'r', 'utf-8', errors='replace') as inc_file:\n\n comment = []\n order = 0\n relative_path = get_relative_path(path, locale)\n resource, created = Resource.objects.get_or_create(\n project=project, path=relative_path, format='inc')\n\n for line in inc_file:\n\n # Uncomment MOZ_LANGPACK_CONTRIBUTORS (commented out)\n # http://hg.mozilla.org/releases/mozilla-aurora/file/572c8f4c8fed/browser/locales/en-US/defines.inc#l10\n if entities and line.startswith('# #define'):\n line = line.lstrip('#').strip()\n\n # Comments\n if entities and line.startswith('# '):\n comment.append(line.lstrip('# ').strip())\n\n # Strings\n elif line.startswith('#define'):\n parts = line.lstrip('#define').strip().split(None, 1)\n\n if not parts:\n continue\n if len(parts) == 1:\n key, string = parts[0], \"\"\n else:\n key, string = parts\n\n if entities:\n save_entity(resource=resource, string=string, key=key,\n comment=\" \".join(comment), order=order)\n comment = []\n order += 1\n\n else:\n try:\n e = Entity.objects.get(resource=resource, key=key)\n save_translation(\n entity=e, locale=locale, string=string)\n except Entity.DoesNotExist:\n continue\n\n elif entities:\n comment = []\n\n if entities:\n update_entity_count(resource)\n else:\n update_stats(resource, locale)\n\n log.debug(\"[\" + locale.code + \"]: \" + path + \" saved to DB.\")\n\n\ndef extract_to_database(project, locales=None):\n \"\"\"Extract data from project files and save or update in DB.\"\"\"\n log.debug(\"Extract data from project files and save or update in DB.\")\n\n repository_path_master = project.repository_path\n source_directory = get_source_directory(repository_path_master)\n\n source_locale = 'en-US'\n if not source_directory['name'] in ('', 'templates'):\n source_locale = source_directory['name']\n\n if not locales:\n # Mark all existing project entities as obsolete\n resources = Resource.objects.filter(project=project)\n Entity.objects.filter(resource__in=resources).update(obsolete=True)\n\n # Empty resources to avoid displaying obsolete ones in part menu\n resources.update(entity_count=0)\n\n # Empty stats to avoid dumping obsolete files\n stats = Stats.objects.filter(resource__in=resources)\n stats.update(approved_count=0)\n\n # Remove Stats for removed locales\n project_locales = project.locales.all()\n stats.exclude(locale__in=project_locales).delete()\n\n locales = [Locale.objects.get(code__iexact=source_locale)]\n locales.extend(project_locales)\n\n isFile = project.repository_type == 'file'\n source_paths = get_source_paths(source_directory['path'])\n format = detect_format(source_directory['path'])\n\n # Ignore specific files from Mozilla repos\n if project.repository_url in MOZILLA_REPOS:\n source_paths = \\\n [x for x in source_paths if not x.endswith('region.properties')]\n\n for index, locale in enumerate(locales):\n if locale.code == source_locale:\n paths = source_paths\n entities = True\n else:\n paths = get_locale_paths(project, locale, source_paths, source_directory['name'])\n entities = isFile\n\n for path in paths:\n format = get_format(path)\n format = 'po' if format == 'pot' else format\n globals()['extract_%s' % format](project, locale, path, entities)\n\n\ndef update_from_repository(project):\n \"\"\"\n Update project files from remote repository.\n\n Args:\n project: Project instance\n \"\"\"\n log.debug(\"Update project files from remote repository.\")\n\n repository_type = project.repository_type\n repository_url = project.repository_url\n repository_path = repository_path_master = project.repository_path\n\n # If one-locale repo, set repository_url_master and update repository_path\n repository_url_master = False\n ending = os.path.basename(os.path.normpath(repository_url))\n\n if ending in ('templates', 'en-US', 'en'):\n repository_url_master = repository_url.rsplit(ending, 1)[0]\n repository_path = os.path.join(repository_path_master, ending)\n\n # If Mozilla repo, set paths\n elif project.repository_url in MOZILLA_REPOS:\n base = 'ssh://hg.mozilla.org/releases/l10n/mozilla-'\n repository_url_master = base + ending.split(\"-\")[-1]\n repository_path = os.path.join(repository_path_master, 'en-US')\n\n # Save file to server\n if repository_type == 'file':\n u = urllib2.urlopen(repository_url)\n file_name = repository_url.rstrip('/').rsplit('/', 1)[1]\n file_path = os.path.join(repository_path_master, file_name)\n\n if not os.path.exists(repository_path_master):\n os.makedirs(repository_path_master)\n\n try:\n with open(file_path, 'w') as f:\n f.write(u.read().decode(\"utf-8-sig\").encode(\"utf-8\"))\n except IOError as e:\n log.debug(\"IOError: \" + str(e))\n\n # Save files to server\n else:\n update_from_vcs(repository_type, repository_url, repository_path)\n\n # If one-locale repo, also update locale repositorites\n if repository_url_master:\n for l in project.locales.all():\n update_from_vcs(\n repository_type,\n os.path.join(repository_url_master, l.code),\n os.path.join(repository_path_master, l.code))\n\n\ndef dump_po(project, locale, relative_path):\n \"\"\"Dump .po (gettext) file with relative path from database.\"\"\"\n\n locale_directory_path = get_locale_directory(project, locale)[\"path\"]\n path = os.path.join(locale_directory_path, relative_path)\n po = polib.pofile(path)\n date = timezone.make_aware(datetime.min)\n newest = Translation()\n resource = Resource.objects.filter(project=project, path=relative_path)\n entities = Entity.objects.filter(resource=resource, obsolete=False)\n\n for entity in entities:\n entry = po.find(entity.string)\n if entry:\n if not entry.msgid_plural:\n try:\n translation = Translation.objects.filter(\n entity=entity, locale=locale, approved=True) \\\n .latest('date')\n entry.msgstr = translation.string\n\n if translation.date > date:\n date = translation.date\n newest = translation\n if 'fuzzy' in entry.flags:\n entry.flags.remove('fuzzy')\n\n except Translation.DoesNotExist:\n pass\n\n else:\n for i in range(0, 6):\n if i < (locale.nplurals or 1):\n try:\n translation = Translation.objects.filter(\n entity=entity, locale=locale,\n plural_form=i, approved=True).latest('date')\n entry.msgstr_plural[i] = translation.string\n\n if translation.date > date:\n date = translation.date\n newest = translation\n if 'fuzzy' in entry.flags:\n entry.flags.remove('fuzzy')\n\n except Translation.DoesNotExist:\n pass\n\n # Remove obsolete plural forms if exist\n else:\n if i in entry.msgstr_plural:\n del entry.msgstr_plural[i]\n\n # Update PO metadata\n if newest.id:\n if newest.user:\n po.metadata['PO-Revision-Date'] = newest.date\n po.metadata['Last-Translator'] = '%s <%s>' \\\n % (newest.user.first_name, newest.user.email)\n po.metadata['Language'] = locale.code.replace('-', '_')\n po.metadata['X-Generator'] = 'Pontoon'\n\n if locale.nplurals:\n po.metadata['Plural-Forms'] = 'nplurals=%s; plural=%s;' \\\n % (str(locale.nplurals), locale.plural_rule)\n\n po.save()\n log.debug(\"File updated: \" + path)\n\n\ndef dump_xliff(project, locale, relative_path):\n \"\"\"Dump .xliff file with relative path from database.\"\"\"\n\n locale_directory_path = get_locale_directory(project, locale)[\"path\"]\n path = os.path.join(locale_directory_path, relative_path)\n resource = Resource.objects.filter(project=project, path=relative_path)\n\n with open(path, 'r+') as f:\n xf = xliff.xlifffile(f)\n\n # Update target-language attribute in file nodes\n for node in xf.document.getroot().iterchildren(xf.namespaced(\"file\")):\n node.set(\"target-language\", locale.code)\n\n for unit in xf.units:\n key = unit.getid()\n\n try:\n entity = Entity.objects.get(resource=resource, key=key)\n except Entity.DoesNotExist:\n log.error('%s: Entity \"%s\" does not exist' % (path, key))\n continue\n\n try:\n translation = Translation.objects.filter(\n entity=entity, locale=locale, approved=True) \\\n .latest('date').string\n unit.settarget(translation)\n\n except Translation.DoesNotExist:\n # Remove \"approved\" attribute\n try:\n del unit.xmlelement.attrib['approved']\n except KeyError:\n pass\n\n # Remove \"target\" element\n target = unit.xmlelement.find(unit.namespaced(\"target\"))\n if target:\n unit.xmlelement.remove(target)\n\n # Erase file and then write, otherwise content gets appended\n f.seek(0)\n f.truncate()\n f.writelines(xf.__str__())\n log.debug(\"File updated: \" + path)\n\n\ndef dump_silme(parser, project, locale, relative_path):\n \"\"\"Dump file with relative path from database using silme. Generate files\n from source files, but only ones with translated strings.\"\"\"\n\n locale_directory_path = get_locale_directory(project, locale)[\"path\"]\n path = os.path.join(locale_directory_path, relative_path)\n\n copy_from_source(path, project.repository_path, relative_path)\n\n with codecs.open(path, 'r+', 'utf-8') as f:\n structure = parser.get_structure(f.read())\n resource = Resource.objects.filter(project=project, path=relative_path)\n entities_with_path = Entity.objects.filter(\n resource=resource, obsolete=False)\n\n for entity in entities_with_path:\n key = entity.key\n\n try:\n try:\n # Modify translated entities\n translation = Translation.objects.filter(\n entity=entity, locale=locale, approved=True) \\\n .latest('date')\n structure.modify_entity(key, translation.string)\n\n except Translation.DoesNotExist:\n # Remove untranslated and following newline\n pos = structure.entity_pos(key)\n structure.remove_entity(key)\n\n try:\n line = structure[pos]\n except IndexError:\n # No newline at end of file\n continue\n\n if type(line) == unicode and line.startswith('\\n'):\n line = line[len('\\n'):]\n structure[pos] = line\n if len(line) is 0:\n structure.remove_element(pos)\n\n # Obsolete entities\n except KeyError:\n pass\n\n # Erase file and then write, otherwise content gets appended\n f.seek(0)\n f.truncate()\n content = parser.dump_structure(structure)\n f.write(content)\n\n log.debug(\"File updated: \" + path)\n\n\ndef dump_properties(project, locale, relative_path):\n \"\"\"Dump .properties file with relative path from database.\"\"\"\n\n parser = silme.format.properties.FormatParser\n dump_silme(parser, project, locale, relative_path)\n\n\ndef dump_dtd(project, locale, relative_path):\n \"\"\"Dump .dtd file with relative path from database.\"\"\"\n\n parser = silme.format.dtd.FormatParser\n dump_silme(parser, project, locale, relative_path)\n\n\ndef dump_ini(project, locale, relative_path):\n \"\"\"Dump .ini file with relative path from database.\"\"\"\n\n parser = silme.format.ini.FormatParser\n dump_silme(parser, project, locale, relative_path)\n\n\ndef dump_lang(project, locale, relative_path):\n \"\"\"Dump .lang file with relative path from database.\"\"\"\n\n locale_directory_path = get_locale_directory(project, locale)[\"path\"]\n path = os.path.join(locale_directory_path, relative_path)\n\n if not os.path.exists(path):\n log.info(\"File does not exist: \" + path)\n return\n\n try:\n resource = Resource.objects.get(project=project, path=relative_path)\n except Resource.DoesNotExist:\n log.info(\"Resource does not exist\")\n return\n\n with codecs.open(path, 'r+', 'utf-8', errors='replace') as lines:\n content = []\n translation = None\n\n for line in lines:\n if translation:\n # Keep newlines in line if present\n trans_line = line.replace(line.rstrip('\\r\\n'), translation)\n content.append(trans_line)\n translation = None\n continue\n\n content.append(line)\n line = line.strip()\n\n if not line:\n continue\n\n if line[0] == ';':\n original = line[1:].strip()\n\n try:\n entity = Entity.objects.get(\n resource=resource, string=original)\n except Entity.DoesNotExist:\n log.error('%s: Entity \"%s\" does not exist' %\n (path, original))\n continue\n\n try:\n translation = Translation.objects.filter(\n entity=entity, locale=locale, approved=True) \\\n .latest('date').string\n\n if translation == original:\n translation += ' {ok}'\n\n except Translation.DoesNotExist:\n translation = original\n\n # Erase file and then write, otherwise content gets appended\n lines.seek(0)\n lines.truncate()\n lines.writelines(content)\n log.debug(\"File updated: \" + path)\n\n\ndef dump_l20n(project, locale, relative_path):\n \"\"\"Dump .l20n file with relative path from database. Generate files\n from source files, but only ones with translated strings.\"\"\"\n\n locale_directory_path = get_locale_directory(project, locale)[\"path\"]\n path = os.path.join(locale_directory_path, relative_path)\n\n copy_from_source(path, project.repository_path, relative_path)\n\n with codecs.open(path, 'r+', 'utf-8') as f:\n parser = L20nParser.L20nParser()\n structure = parser.parse(f.read())\n ast = L20nast\n\n for obj in structure.body:\n if obj.type == \"Entity\":\n\n # Attributes\n for attr in obj.attrs:\n key = \".\".join([obj.id.name, attr.id.name])\n\n try:\n # Modify translated attributes\n translation = Translation.objects.filter(\n entity__key=key, locale=locale, approved=True) \\\n .latest('date')\n attr.value.content[0] = translation.string\n\n except Translation.DoesNotExist:\n # Remove untranslated\n obj.attrs.remove(attr)\n\n key = obj.id.name\n\n # Simple entities\n if obj.value.type == \"String\":\n try:\n # Modify translated entities\n translation = Translation.objects.filter(\n entity__key=key, locale=locale, approved=True) \\\n .latest('date')\n obj.value.content[0] = translation.string\n\n except Translation.DoesNotExist:\n # Remove untranslated\n obj.value = None\n\n # Remove entity\n if not obj.attrs:\n structure.body.remove(obj)\n\n # Plurals\n elif obj.value.type == \"Hash\":\n obj.value.items = []\n plurals = locale.cldr_plurals_list()\n\n for i in range(0, (len(plurals) or 1)):\n try:\n # Modify translated plural forms\n translation = Translation.objects.filter(\n entity__key=key,\n locale=locale,\n plural_form=i,\n approved=True).latest('date')\n\n idx = plurals[i]\n hashItem = ast.HashItem(\n ast.Identifier(Locale.CLDR_PLURALS[idx][1]),\n ast.String(\n [translation.string],\n translation.string),\n False,\n )\n obj.value.items.append(hashItem)\n\n except Translation.DoesNotExist:\n # Untranslated already removed on empty items\n pass\n\n # Remove entity\n if not obj.value.items and not obj.attrs:\n structure.body.remove(obj)\n\n # Erase file and then write, otherwise content gets appended\n f.seek(0)\n f.truncate()\n serializer = L20nSerializer.Serializer()\n content = serializer.serialize(structure)\n f.write(content)\n\n log.debug(\"File updated: \" + path)\n\n\ndef dump_inc(project, locale, relative_path):\n \"\"\"Dump .inc file with relative path from database. Generate files\n from source files, but only ones with translated strings.\"\"\"\n\n locale_directory_path = get_locale_directory(project, locale)[\"path\"]\n path = os.path.join(locale_directory_path, relative_path)\n\n copy_from_source(path, project.repository_path, relative_path)\n\n with codecs.open(path, 'r+', 'utf-8') as inc_file:\n content = []\n resource = Resource.objects.filter(project=project, path=relative_path)\n\n for line in inc_file:\n original = line\n\n # Uncomment MOZ_LANGPACK_CONTRIBUTORS (commented out)\n # http://hg.mozilla.org/releases/mozilla-aurora/file/572c8f4c8fed/browser/locales/en-US/defines.inc#l10\n if line.startswith('# #define'):\n line = line.lstrip('#').strip()\n\n if line.startswith('#define'):\n key = line.lstrip('#define').strip().split(None, 1)[0]\n\n try:\n e = Entity.objects.get(resource=resource, key=key)\n except Entity.DoesNotExist:\n log.error('%s: Entity \"%s\" does not exist' % (path, key))\n line = original\n pass\n\n try:\n translation = Translation.objects.filter(\n entity=e, locale=locale, approved=True) \\\n .latest('date').string\n line = '#define %s %s\\n' % (key, translation)\n except Translation.DoesNotExist as e:\n line = original\n pass\n\n content.append(line)\n\n # Erase file and then write, otherwise content gets appended\n inc_file.seek(0)\n inc_file.truncate()\n inc_file.writelines(content)\n log.debug(\"File updated: \" + path)\n\n\ndef dump_from_database(project, locale):\n \"\"\"Dump project files from database.\"\"\"\n log.debug(\"Dump project files from database.\")\n\n # Check if locale directory even exist\n locale_directory_path = get_locale_directory(project, locale)[\"path\"]\n if not locale_directory_path:\n return False\n\n # Get relative paths to translated files only\n stats = Stats.objects.filter(locale=locale).exclude(approved_count=0) \\\n .values(\"resource\")\n resources = Resource.objects.filter(project=project, id__in=stats)\n relative_paths = resources.values_list('path', flat=True).distinct()\n\n # Asymmetric formats: Remove l10n files from locale repository\n project_resources = Resource.objects.filter(project=project)\n if all(r.is_asymmetric for r in project_resources):\n for root, dirnames, filenames in os.walk(\n locale_directory_path, topdown=False):\n for extension in Resource.ASYMMETRIC_FORMATS:\n for filename in fnmatch.filter(filenames, '*.' + extension):\n\n # Ignore specific files from Mozilla repos\n if filename != 'region.properties' \\\n or project.repository_url not in MOZILLA_REPOS:\n os.remove(os.path.join(root, filename))\n\n # Remove empty directories\n if not os.listdir(root) and locale_directory_path != root:\n shutil.rmtree(os.path.join(locale_directory_path, root))\n\n # If directory empty, make sure Git and Mercurial don't remove it\n if not os.listdir(locale_directory_path):\n open(os.path.join(locale_directory_path, '.keep'), 'a').close()\n\n # Dump files based on format\n for path in relative_paths:\n format = get_format(path)\n format = 'po' if format == 'pot' else format\n globals()['dump_%s' % format](project, locale, path)\n\n return locale_directory_path\n\n\ndef generate_zip(project, locale):\n \"\"\"\n Generate .zip of all project files for the specified locale.\n\n Args:\n project: Project instance\n locale: Locale code\n Returns:\n A string for generated ZIP content.\n \"\"\"\n log.debug(\"Generate .zip of all project files for the specified locale.\")\n\n try:\n locale = Locale.objects.get(code__iexact=locale)\n except Locale.DoesNotExist as e:\n log.error(e)\n\n path = dump_from_database(project, locale)\n if not path:\n return False\n\n s = StringIO.StringIO()\n zf = zipfile.ZipFile(s, \"w\")\n\n # ZIP empty root directory to avoid corrupt archive if no file translated\n root = os.path.split(path)[-1]\n zf.write(path, root)\n\n for root, dirs, filenames in os.walk(path):\n for f in filenames:\n file_path = os.path.join(root, f)\n zip_path = os.path.relpath(file_path, os.path.join(path, '..'))\n zf.write(file_path, zip_path)\n\n zf.close()\n return s.getvalue()\n","sub_path":"pontoon/administration/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":40486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"609520235","text":"from network import WLAN\nimport urequests as requests\nimport machine\nimport time\nfrom LTR329ALS01 import LTR329ALS01\nfrom SI7006A20 import SI7006A20\nfrom MPL3115A2 import MPL3115A2\n\n# Light Sensor\nl = LTR329ALS01()\n# Temperature and Humidity Sensor\nt = SI7006A20()\n# Pressure Sensor\np = MPL3115A2()\n\n# Your WiFi network credentials\nWIFI_SSID = 'your-wifi-ssid'\nWIFI_KEY = 'your-wifi-key'\n\n# Get this from the Wia dashboard (it should begin with d_sk)\nDEVICE_SECRET_KEY = 'your-device-secret-key'\n\n# Delay between each event\nDELAY = 3\n\nwlan = WLAN(mode=WLAN.STA)\nnets = wlan.scan()\n\n# Connect to the WiFi network\nfor net in nets:\n if net.ssid == WIFI_SSID:\n print('Network found!')\n wlan.connect(net.ssid, auth=(net.sec, WIFI_KEY), timeout=5000)\n # while not wlan.isconnected():\n # machine.idle() # save power while waiting\n print('WLAN connection succeeded!')\n break\n\nprint(\"Connected to Wifi\\n\")\n\n# Post an Event to the Wia cloud\ndef post_event(name, data):\n try:\n url = \"https://api.wia.io/v1/events\"\n headers = {\"Authorization\": \"Bearer \" + DEVICE_SECRET_KEY, \"Content-Type\": \"application/json\"}\n json_data = {\"name\": name, \"data\": data}\n if json_data is not None:\n print(json_data)\n req = requests.post(url=url, headers=headers, json=json_data)\n print(req.json())\n return req.json()\n else:\n pass\n except:\n pass\n\n# Run this loop continuously\nwhile True:\n light = l.light()\n # temperature = t.temperature()\n # humidity = t.humidity()\n # pressure = p.pressure()\n\n post_event(\"light\", light[0])\n # post_event(\"temperature\", temperature)\n # post_event(\"humidity\", humidity)\n # post_event(\"pressure\", pressure)\n time.sleep(DELAY)\n","sub_path":"Pycom/LoPy/PublishPysenseWifi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"304415421","text":"import six\n\nfrom .typespec_pb2 import Typespec, Primitive, MapFieldEntry, Map, CompositeType\nfrom .cereal import types\n\n\nPRIMITIVES = (int, float, bool, str)\n\n\ndef deserialize_typespec(spec):\n set_field = spec.WhichOneof(\"spec\")\n if set_field == \"prim\":\n return getattr(spec.prim, spec.prim.WhichOneof(\"value\"))\n elif set_field == \"type\":\n try:\n return types[spec.type]\n except KeyError:\n raise ValueError(\"No known type {!r}\".format(spec.type))\n elif set_field == \"map\":\n return {\n deserialize_typespec(param.key): deserialize_typespec(param.val)\n for param in spec.map.items\n }\n elif set_field == \"comp\":\n generic = deserialize_typespec(Typespec(type=spec.comp.type))\n params = tuple(deserialize_typespec(param) for param in spec.comp.params)\n return generic.__class_getitem__(params)\n\n\ndef serialize_typespec(cls):\n if isinstance(cls, int):\n return Typespec(prim=Primitive(int_=cls))\n if isinstance(cls, float):\n return Typespec(prim=Primitive(float_=cls))\n if isinstance(cls, bool):\n return Typespec(prim=Primitive(bool_=cls))\n if isinstance(cls, str):\n return Typespec(prim=Primitive(string_=cls))\n\n if getattr(cls, \"_named_concrete_type\", False):\n # ^ cls doesn't have that attribute, or it does and the value is falsey\n name = cls.__name__\n else:\n try:\n name = cls._generictype.__name__\n except AttributeError:\n name = cls.__name__\n\n try:\n expected_cls = types[name]\n except KeyError:\n raise ValueError(\n \"{!r} is not in the types registry; cannot serialize it\".format(name)\n )\n\n if not issubclass(cls, expected_cls):\n raise ValueError(\n \"{} is not a subclass of {}, even though it has the same `__name__`\".format(\n cls, expected_cls\n )\n )\n\n if not hasattr(cls, \"_type_params\") or getattr(cls, \"_named_concrete_type\", False):\n return Typespec(type=name)\n else:\n type_params = cls._type_params\n if type_params is None:\n raise TypeError(\n \"Can only serialize concrete types, not the generic type {}\".format(cls)\n )\n\n serialized_params = [\n Typespec(\n map=Map(\n items=[\n MapFieldEntry(\n key=serialize_typespec(key), val=serialize_typespec(val)\n )\n for key, val in six.iteritems(param)\n ]\n )\n )\n if isinstance(param, dict)\n else serialize_typespec(param)\n for param in type_params\n ]\n\n return Typespec(comp=CompositeType(type=name, params=serialized_params))\n","sub_path":"descarteslabs/workflows/cereal/proto_cereal.py","file_name":"proto_cereal.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"112866545","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport time\nimport codecs\nimport os\nfrom preprocess import Preprocess_Text\n\nclass Preprocess_Crawl_Text(Preprocess_Text):\n def __init__(self,directory_name='../../Data',temp_results='../../temp_results',raw_file_name='crawled_news_text.txt'):\n Preprocess_Text.__init__(self,directory_name,temp_results,raw_file_name)\n \n def generate_crawl_raw_file(self,):\n count = 0 \n start_time = time.time()\n with codecs.open(self.raw_file_name, \"w\", encoding=\"utf-8\") as f:\n for root, subdirs, files in os.walk(self.directory_name):\n for file_name in files:\n #Mac file system file\n if file_name==\".DS_Store\":\n continue\n print (\"Working on file \",file_name)\n file_path = os.path.join(root, file_name)\n with codecs.open(file_path, encoding=\"utf-8\") as each_file_pointer:\n for each_line in each_file_pointer:\n headline_tokens = self.tokenize(each_line)\n single_news = u\" \".join(headline_tokens) + u\"\\n\"\n f.write(single_news)\n count = count + 1\n if count%10000==0:\n print (\"Processing done till \",count, \"time took \",time.time()-start_time)\n\ndef main():\n process_crawl_data = Preprocess_Crawl_Text()\n process_crawl_data.generate_crawl_raw_file()\n \nif __name__ == \"__main__\":\n main()","sub_path":"word2vec/crawl_data_preprocess.py","file_name":"crawl_data_preprocess.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47475441","text":"\"\"\" Package constants \"\"\"\n\n__author__ = \"Vince Reuter\"\n__email__ = \"vreuter@virginia.edu\"\n\n\n# Compute-related\nCOMPUTE_SETTINGS_VARNAME = \"PEPENV\"\nDEFAULT_COMPUTE_RESOURCES_NAME = \"default\"\nSAMPLE_NAME_COLNAME = \"sample_name\"\nCOMPUTE_CONSTANTS = [\"COMPUTE_SETTINGS_VARNAME\",\n \"DEFAULT_COMPUTE_RESOURCES_NAME\",\n \"SAMPLE_NAME_COLNAME\"]\n\n# Project-related\nDATA_SOURCES_SECTION = \"data_sources\"\nDERIVATIONS_DECLARATION = \"derived_attributes\"\nIMPLICATIONS_DECLARATION = \"implied_attributes\"\nSAMPLE_INDEPENDENT_PROJECT_SECTIONS = \\\n [\"metadata\", DERIVATIONS_DECLARATION, IMPLICATIONS_DECLARATION, \"trackhubs\"]\nPROJECT_CONSTANTS = [\"DATA_SOURCES_SECTION\", \"IMPLICATIONS_DECLARATION\",\n \"SAMPLE_INDEPENDENT_PROJECT_SECTIONS\"]\n\n# Sample-related\nDATA_SOURCE_COLNAME = \"data_source\"\nSAMPLE_ANNOTATIONS_KEY = \"sample_annotation\"\nSAMPLE_EXECUTION_TOGGLE = \"toggle\"\nVALID_READ_TYPES = [\"single\", \"paired\"]\nREQUIRED_INPUTS_ATTR_NAME = \"required_inputs_attr\"\nALL_INPUTS_ATTR_NAME = \"all_inputs_attr\"\nSAMPLE_CONSTANTS = [\"ALL_INPUTS_ATTR_NAME\", \"DATA_SOURCE_COLNAME\",\n \"REQUIRED_INPUTS_ATTR_NAME\", \"SAMPLE_ANNOTATIONS_KEY\",\n \"SAMPLE_EXECUTION_TOGGLE\", \"VALID_READ_TYPES\"]\n\n# Other\nFLAGS = [\"completed\", \"running\", \"failed\", \"waiting\", \"partial\"]\nGENERIC_PROTOCOL_KEY = \"*\"\nOTHER_CONSTANTS = [\"FLAGS\", \"GENERIC_PROTOCOL_KEY\"]\n\n\n__all__ = COMPUTE_CONSTANTS + PROJECT_CONSTANTS + \\\n SAMPLE_CONSTANTS + OTHER_CONSTANTS\n","sub_path":"peppy/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"290474876","text":"import sys, json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfrom scipy.interpolate import interp1d\nfrom ast import literal_eval\n\nratingField = 'imdb_rating' + 's'\n\nresolution = 0.4\n\nnum_test_movies = 0\nwith open('data/stats.txt', 'r') as stats_file:\n num_test_movies = json.loads(stats_file.read())['num_test_movies']\n\ndef round_to(n, decimal):\n n *= 1.0/decimal\n n = round(n)\n return round(n*decimal, 1)\n\n # round_diff = n % decimal\n # correction = round_diff if round_diff > decimal/2.0 else -round_diff\n # return n + (decimal - correction)\n\ndef get_counts_from_list(list):\n counts = {}\n for el in list:\n el = round_to(float(el), resolution)\n if el not in counts:\n counts[el] = 0\n counts[el] += 1\n\n for k,v in counts.items():\n counts[k] = float(v)/num_test_movies\n return counts\n\ndef plot_distribution(counts, label):\n xs = np.arange(0, 10 + resolution, resolution)\n ys = [0] * int(10/resolution + 1)\n\n for i, val in enumerate(xs):\n if val in counts:\n ys[i] = counts[val]\n \n f = interp1d(xs, ys, kind='cubic')\n \n xsnew = np.arange(0, 10.01, 0.01)\n ysnew = f(xsnew)\n\n ysnew = map(lambda el: el if el > 0 else 0, ysnew)\n\n plt.xlim(0, 10)\n plt.xlabel('Imdb Rating')\n plt.ylabel('Probability')\n plt.title('Movie Rating Probability Distribution')\n plt.plot(xsnew, ysnew, label=label)\n\n# plot test set distribution\nwith open('data/stats.txt', 'r') as stats_file:\n stats = json.loads(stats_file.read())\n ys = stats['testset_rating_distribution'][ratingField]\n counts = get_counts_from_list(ys)\n plot_distribution(counts, 'Actual ratings')\n\n# plot the given list file if applicable\nfor f, name in [('data/ridge_binary_results', 'Ridge'), ('data/lasso_binary_results', 'Lasso'),\\\n ('data/linear_binary_predictions', 'Linear'), ('data/logistic_binary_results', 'Logistic')]:\n with open(f, 'r') as listfile:\n ys = literal_eval(listfile.read())\n counts = get_counts_from_list(ys)\n plot_distribution(counts, name)\n\nplt.legend(loc='upper left')\nplt.show()\n","sub_path":"plot_distributions.py","file_name":"plot_distributions.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"423559760","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport site\n\nUPGRADING = False\n\nproject_dir = '/var/www/bcis_site_cms'\n#site.addsitedir('/var/www/virtualenvs/bcis_site_cms_test/lib/python2.7/site-packages')\n# Prepend path so as mptt in virtualenv take precedence over system one\n#sys.path.insert(0, '/var/www/virtualenvs/bcis_site_cms_test/lib/python2.7/site-packages')\n#sys.path.append('/var/www')\n#sys.path.append(project_dir)\n\ndef upgrade_in_progress(environ, start_response):\n upgrade_file = os.path.join(project_dir, 'templates', '503.html')\n if os.path.exists(upgrade_file):\n response_headers = [('Content-type','text/html')]\n response = open(upgrade_file).read()\n else:\n response_headers = [('Content-type','text/plain')]\n response = \"Mise à jour de l'application en cours... revenez dans quelques minutes.\"\n\n if environ['REQUEST_METHOD'] == 'GET':\n status = '200 OK'\n else:\n status = '403 Forbidden'\n start_response(status, response_headers)\n return [response]\n\nif UPGRADING:\n application = upgrade_in_progress\nelse:\n os.environ['DJANGO_SETTINGS_MODULE'] = 'bcis_site_web.settings'\n from django.core.wsgi import get_wsgi_application\n application = get_wsgi_application()\n \n #import django.core.handlers.wsgi\n #application = django.core.handlers.wsgi.WSGIHandler()\n\n","sub_path":"apache/django.wsgi","file_name":"django.wsgi","file_ext":"wsgi","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"366610224","text":"import os\nfrom setuptools import setup\n\nhere = os.path.abspath(os.path.dirname(__file__))\nabout = {}\nwith open(os.path.join(here, 'slocust', '__version__.py'),\n 'r', encoding='utf-8') as f:\n exec(f.read(), about)\n\npackages = ['slocust']\n\nwith open('requirements.txt') as f:\n requires = f.read().splitlines()\n\nsetup(\n name=about['__title__'],\n version=about['__version__'],\n description=about['__description__'],\n license=about['__license__'],\n url=about['__url__'],\n author=about['__author__'],\n author_email=about['__author_email__'],\n packages=packages,\n include_package_data=True,\n platforms='any',\n install_requires=requires,\n classifiers=[\n 'Development Status :: 1 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Topic :: Software Development :: Testing',\n 'Topic :: Utilities',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Testers',\n ] + [\n ('Programming Language :: Python :: %s' % x)\n for x in '3.5 3.6'.split()\n ],\n entry_points={\n 'console_scripts': [\n 'slocust = slocust:main',\n ]\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"249880414","text":"\"\"\"Use a neural network to mimic images.\"\"\"\n\nimport argparse\nimport os\n\nimport numpy as np\nfrom PIL import Image\nfrom tinynn.core.layer import Dense\nfrom tinynn.core.layer import ReLU\nfrom tinynn.core.layer import Sigmoid\nfrom tinynn.core.loss import MSE\nfrom tinynn.core.model import Model\nfrom tinynn.core.net import Net\nfrom tinynn.core.optimizer import Adam\nfrom tinynn.utils.data_iterator import BatchIterator\nfrom tinynn.utils.metric import mean_square_error\nfrom tinynn.utils.seeder import random_seed\n\n\ndef prepare_dataset(img_path):\n if not os.path.isfile(img_path):\n raise FileExistsError(\"Image %s not exist\" % img_path)\n img = np.asarray(Image.open(img_path), dtype=\"float32\") / 255.0\n\n train_x, train_y = [], []\n h, w, _ = img.shape\n for r in range(h):\n for c in range(w):\n train_x.append([(r - h / 2.0) / h, (c - w / 2.0) / w])\n train_y.append(img[r][c])\n return np.asarray(train_x), np.asarray(train_y), (h, w)\n\n\ndef main(args):\n if args.seed >= 0:\n random_seed(args.seed)\n\n # data preparing\n train_x, train_y, img_shape = prepare_dataset(args.img)\n\n net = Net([\n Dense(30),\n ReLU(),\n Dense(100),\n ReLU(),\n Dense(100),\n ReLU(),\n Dense(30),\n ReLU(),\n Dense(3),\n Sigmoid()\n ])\n\n model = Model(net=net, loss=MSE(), optimizer=Adam())\n iterator = BatchIterator(batch_size=args.batch_size)\n for epoch in range(args.num_ep):\n for batch in iterator(train_x, train_y):\n preds = model.forward(batch.inputs)\n loss, grads = model.backward(preds, batch.targets)\n model.apply_grads(grads)\n\n # evaluate\n preds = net.forward(train_x)\n mse = mean_square_error(preds, train_y)\n print(\"Epoch %d %s\" % (epoch, mse))\n\n # generate painting\n if epoch % 5 == 0:\n preds = preds.reshape(img_shape[0], img_shape[1], -1)\n preds = (preds * 255.0).astype(\"uint8\")\n name, ext = os.path.splitext(args.img)\n filename = os.path.basename(name)\n out_filename = filename + \"-paint-epoch\" + str(epoch) + ext\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n out_path = os.path.join(args.output_dir, out_filename)\n Image.fromarray(preds).save(out_path)\n print(\"save painting to %s\" % out_path)\n\n\nif __name__ == \"__main__\":\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--img\", type=str,\n default=os.path.join(curr_dir, \"test-img.jpg\"))\n parser.add_argument(\"--output_dir\", type=str,\n default=os.path.join(curr_dir, \"output\"))\n parser.add_argument(\"--seed\", default=-1, type=int)\n parser.add_argument(\"--batch_size\", default=32, type=int)\n parser.add_argument(\"--num_ep\", default=100, type=int)\n main(parser.parse_args())\n","sub_path":"examples/nn_paint/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"341739194","text":"import read, copy\nfrom util import *\nfrom logical_classes import *\n\nverbose = 1\n\nclass KnowledgeBase(object):\n def __init__(self, facts=[], rules=[]):\n self.facts = facts\n self.rules = rules\n self.ie = InferenceEngine()\n\n def __repr__(self):\n return 'KnowledgeBase({!r}, {!r})'.format(self.facts, self.rules)\n\n def __str__(self):\n string = \"Knowledge Base: \\n\"\n string += \"\\n\".join((str(fact) for fact in self.facts)) + \"\\n\"\n string += \"\\n\".join((str(rule) for rule in self.rules))\n return string\n\n def _get_fact(self, fact):\n \"\"\"INTERNAL USE ONLY\n Get the fact in the KB that is the same as the fact argument\n\n Args:\n fact (Fact): Fact we're searching for\n\n Returns:\n Fact: matching fact\n \"\"\"\n for kbfact in self.facts:\n if fact == kbfact:\n return kbfact\n\n def _get_rule(self, rule):\n \"\"\"INTERNAL USE ONLY\n Get the rule in the KB that is the same as the rule argument\n\n Args:\n rule (Rule): Rule we're searching for\n\n Returns:\n Rule: matching rule\n \"\"\"\n for kbrule in self.rules:\n if rule == kbrule:\n return kbrule\n\n def kb_add(self, fact_rule):\n \"\"\"Add a fact or rule to the KB\n Args:\n fact_rule (Fact|Rule) - the fact or rule to be added\n Returns:\n None\n \"\"\"\n printv(\"Adding {!r}\", 1, verbose, [fact_rule])\n if isinstance(fact_rule, Fact):\n if fact_rule not in self.facts:\n self.facts.append(fact_rule)\n for rule in self.rules:\n self.ie.fc_infer(fact_rule, rule, self)\n else:\n if fact_rule.supported_by:\n ind = self.facts.index(fact_rule)\n for f in fact_rule.supported_by:\n self.facts[ind].supported_by.append(f)\n else:\n ind = self.facts.index(fact_rule)\n self.facts[ind].asserted = True\n elif isinstance(fact_rule, Rule):\n if fact_rule not in self.rules:\n self.rules.append(fact_rule)\n for fact in self.facts:\n self.ie.fc_infer(fact, fact_rule, self)\n else:\n if fact_rule.supported_by:\n ind = self.rules.index(fact_rule)\n for f in fact_rule.supported_by:\n self.rules[ind].supported_by.append(f)\n else:\n ind = self.rules.index(fact_rule)\n self.rules[ind].asserted = True\n\n def kb_assert(self, fact_rule):\n \"\"\"Assert a fact or rule into the KB\n\n Args:\n fact_rule (Fact or Rule): Fact or Rule we're asserting\n \"\"\"\n printv(\"Asserting {!r}\", 0, verbose, [fact_rule])\n self.kb_add(fact_rule)\n\n def kb_ask(self, fact):\n \"\"\"Ask if a fact is in the KB\n\n Args:\n fact (Fact) - Statement to be asked (will be converted into a Fact)\n\n Returns:\n listof Bindings|False - list of Bindings if result found, False otherwise\n \"\"\"\n print(\"Asking {!r}\".format(fact))\n if factq(fact):\n f = Fact(fact.statement)\n bindings_lst = ListOfBindings()\n # ask matched facts\n for fact in self.facts:\n binding = match(f.statement, fact.statement)\n if binding:\n bindings_lst.add_bindings(binding, [fact])\n\n return bindings_lst if bindings_lst.list_of_bindings else []\n\n else:\n print(\"Invalid ask:\", fact.statement)\n return []\n\n def kb_retract(self, fact):\n \"\"\"Retract a fact from the KB\n\n Args:\n fact (Fact) - Fact to be retracted\n\n Returns:\n None\n \"\"\"\n printv(\"Retracting {!r}\", 0, verbose, [fact])\n ####################################################\n # Student code goes here\n if factq(fact):\n f_ind = self.facts.index(fact)\n fact = self.facts[f_ind]\n fact.asserted = False\n if (fact.supported_by == []):\n self.facts.remove(fact)\n for f in fact.supports_facts:\n self.recursive_remove_support(f, fact)\n self.kb_retract(f)\n for r in fact.supports_rules:\n self.recursive_remove_support(r, fact)\n self.kb_retract_rule(r)\n\n def kb_retract_rule(self, rule):\n r_ind = self.rules.index(rule)\n rule = self.rules[r_ind]\n if (rule.asserted == False and rule.supported_by == []):\n self.rules.remove(rule)\n for f in rule.supports_facts:\n self.recursive_remove_support(f, rule)\n self.kb_retract(f)\n for r in rule.supports_rules:\n self.recursive_remove_support(r,rule)\n self.kb_retract_rule(r)\n\n def recursive_remove_support(self, target, to_remove):\n if factq(target):\n f_ind = self.facts.index(target)\n target = self.facts[f_ind]\n else:\n r_ind = self.rules.index(target)\n target =self.rules[r_ind]\n breakpoint()\n for support in target.supported_by:\n if to_remove in support:\n target.supported_by.remove(support)\n for f in target.supports_facts:\n self.recursive_remove_support(f, to_remove)\n for r in target.supports_rules:\n self.recursive_remove_support(r, to_remove)\n\n\nclass InferenceEngine(object):\n def fc_infer(self, fact, rule, kb):\n \"\"\"Forward-chaining to infer new facts and rules\n\n Args:\n fact (Fact) - A fact from the KnowledgeBase\n rule (Rule) - A rule from the KnowledgeBase\n kb (KnowledgeBase) - A KnowledgeBase\n\n Returns:\n Nothing \n \"\"\"\n printv('Attempting to infer from {!r} and {!r} => {!r}', 1, verbose,\n [fact.statement, rule.lhs, rule.rhs])\n ####################################################\n # Student code goes here\n\n r_ind = kb.rules.index(rule)\n f_ind = kb.facts.index(fact)\n first_rule = rule.lhs[0]\n binding = match(fact.statement, first_rule)\n #breakpoint()\n if binding:\n if( len(rule.lhs) == 1 ):\n instantiated_rhs = instantiate(rule.rhs, binding)\n \n new_fact = Fact( instantiated_rhs, [[kb.facts[f_ind], kb.rules[r_ind]]])\n kb.facts[f_ind].supports_facts.append(new_fact)\n kb.rules[r_ind].supports_facts.append(new_fact)\n kb.kb_add(new_fact) \n else:\n instantiated_lst = []\n for state in rule.lhs[1:]:\n instantiated_lst.append(instantiate(state, binding))\n instantiated_rhs = instantiate(rule.rhs, binding)\n\n new_rule = Rule( [instantiated_lst, instantiated_rhs], [[kb.facts[f_ind], kb.rules[r_ind]]] )\n kb.facts[f_ind].supports_rules.append(new_rule)\n kb.rules[r_ind].supports_rules.append(new_rule)\n kb.kb_add(new_rule)\n\n\n\n\n","sub_path":"student_code.py","file_name":"student_code.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"232728689","text":"import fasttext\n\nmodel = fasttext.load_model(\"model_stkhelp.bin\")\n\nmodel.quantize(input=None,\n qout=False,\n cutoff=0,\n retrain=False,\n epoch=None,\n lr=None,\n thread=None,\n verbose=None,\n dsub=2,\n qnorm=False,\n )\n\n# Save Quantized model\nmodel.save_model('model_stkhelp_q3.bin')","sub_path":"stkhelp/quantize_model.py","file_name":"quantize_model.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"435198162","text":"import json\nimport sys\n\nfrom datetime import datetime\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.management.base import BaseCommand\nfrom time import sleep\nfrom tqdm import tqdm\n\nfrom aploader.celery import (\n bake_bop,\n call_race_in_slack,\n call_race_in_slackchat,\n call_race_on_twitter,\n)\nfrom aploader.conf import settings as app_settings\nfrom aploader.models import APElectionMeta, ChamberCall\nfrom election.models import CandidateElection, ElectionEvent\nfrom geography.models import Division, DivisionLevel\nfrom vote.models import Votes\n\nfrom .utils.notifications.formatters import (\n format_office_label,\n short_format_office_label,\n)\n\nPENNSYLVANIA_INCUMBENCY_MAP = {\n \"01\": \"gop\",\n \"02\": \"dem\",\n \"03\": \"dem\",\n \"04\": \"dem\",\n \"05\": \"gop\",\n \"06\": \"gop\",\n \"07\": \"gop\",\n \"08\": \"dem\",\n \"09\": \"gop\",\n \"10\": \"gop\",\n \"11\": \"gop\",\n \"12\": \"gop\",\n \"13\": \"gop\",\n \"14\": \"dem\",\n \"15\": \"gop\",\n \"16\": \"gop\",\n \"17\": \"gop\",\n \"18\": \"dem\",\n}\n\nLOUISIANA_INCUMBENCY_MAP = {\n \"01\": \"gop\",\n \"02\": \"dem\",\n \"03\": \"gop\",\n \"04\": \"gop\",\n \"05\": \"gop\",\n \"06\": \"gop\",\n}\n\n\nclass Command(BaseCommand):\n help = (\n \"Ingests master results JSON file from Elex and updates the results \"\n \"models in Django.\"\n )\n\n def load_results(self, level):\n data = None\n while data is None:\n try:\n data = json.load(open(\"reup_{}.json\".format(level)))\n except json.decoder.JSONDecodeError:\n print(\"Waiting for file to be available.\")\n sleep(5)\n return data\n\n def get_current_party(self, race):\n historical_results = race.dataset.all()[0].data[\"historicalResults\"][\n \"seat\"\n ]\n\n if not race.office.body:\n return None\n\n if race.office.body.slug == \"house\":\n if race.office.division.parent.slug == \"pennsylvania\":\n return PENNSYLVANIA_INCUMBENCY_MAP[race.office.division.code]\n\n if race.office.division.parent.slug == \"louisiana\":\n return LOUISIANA_INCUMBENCY_MAP[race.office.division.code]\n\n last_election_year = \"2016\"\n elif race.office.body.slug == \"senate\" and not race.special:\n last_election_year = \"2012\"\n # all specials this year are class 2\n elif race.office.body.slug == \"senate\" and race.special:\n last_election_year = \"2014\"\n\n last_result = next(\n result\n for result in historical_results\n if result[\"year\"] == last_election_year\n )\n\n # bernie and angus caucus with dems\n if (\n race.office.body.slug == \"senate\"\n and race.office.division.slug in [\"vermont\", \"maine\"]\n ):\n return \"dem\"\n\n dem = last_result.get(\"dem\")\n gop = last_result.get(\"gop\")\n\n if not gop:\n return \"dem\"\n if not dem:\n return \"gop\"\n\n if dem[\"votes\"] > gop[\"votes\"]:\n return \"dem\"\n\n if gop[\"votes\"] > dem[\"votes\"]:\n return \"gop\"\n\n def bop_calculations(self):\n house = self.bop[\"house\"]\n house_win_threshold = 218\n\n house[\"undecided\"] = 435 - (\n house[\"dem\"][\"total\"]\n + house[\"gop\"][\"total\"]\n + house[\"other\"][\"total\"]\n )\n house[\"dem\"][\"net\"] = house[\"dem\"][\"flips\"] - house[\"gop\"][\"flips\"]\n house[\"gop\"][\"net\"] = house[\"gop\"][\"flips\"] - house[\"dem\"][\"flips\"]\n\n if house[\"dem\"][\"total\"] >= house_win_threshold:\n house[\"call\"] = \"dem\"\n\n if house[\"gop\"][\"total\"] >= house_win_threshold:\n house[\"call\"] = \"gop\"\n\n senate = self.bop[\"senate\"]\n\n senate[\"undecided\"] = 100 - (\n senate[\"dem\"][\"total\"]\n + senate[\"gop\"][\"total\"]\n + senate[\"other\"][\"total\"]\n )\n senate[\"dem\"][\"net\"] = senate[\"dem\"][\"flips\"] - senate[\"gop\"][\"flips\"]\n senate[\"gop\"][\"net\"] = senate[\"gop\"][\"flips\"] - senate[\"dem\"][\"flips\"]\n\n if senate[\"dem\"][\"total\"] >= 51:\n senate[\"call\"] = \"dem\"\n\n if senate[\"gop\"][\"total\"] >= 50:\n senate[\"call\"] = \"gop\"\n\n def get_chamber_call(self, body):\n chamber_call = ChamberCall.objects.get(body__slug=body)\n\n if not chamber_call.party:\n return None\n else:\n return chamber_call.party.ap_code.lower()\n\n def deconstruct_result(self, result):\n keys = [\n \"id\",\n \"raceid\",\n \"is_ballot_measure\",\n \"electiondate\",\n \"level\",\n \"statepostal\",\n \"reportingunitname\",\n \"last\",\n \"officename\",\n \"racetype\",\n \"winner\",\n \"uncontested\",\n \"runoff\",\n \"votecount\",\n \"votepct\",\n \"precinctsreporting\",\n \"precinctsreportingpct\",\n \"precinctstotal\",\n \"party\",\n ]\n return [result[key] for key in keys]\n\n def process_result(self, result, tabulated, no_bots, election_slug):\n \"\"\"\n Processes top-level (state) results for candidate races, loads data\n into the database and sends alerts for winning results.\n \"\"\"\n # Deconstruct result in variables\n (\n ID,\n RACE_ID,\n IS_BALLOT_MEASURE,\n ELEX_ELECTION_DATE,\n LEVEL,\n STATE_POSTAL,\n REPORTING_UNIT,\n LAST_NAME,\n OFFICE_NAME,\n RACE_TYPE,\n WINNER,\n UNCONTESTED,\n RUNOFF,\n VOTE_COUNT,\n VOTE_PERCENT,\n PRECINCTS_REPORTING,\n PRECINCTS_REPORTING_PERCENT,\n PRECINCTS_TOTAL,\n PARTY,\n ) = self.deconstruct_result(result)\n\n # Skip ballot measures on non-state-level results\n if IS_BALLOT_MEASURE or LEVEL != DivisionLevel.STATE:\n return\n\n try:\n ap_meta = APElectionMeta.objects.get(\n ap_election_id=RACE_ID,\n election__election_day__slug=election_slug,\n )\n except ObjectDoesNotExist:\n print(\n \"No AP Meta found for {0} {1} {2}\".format(\n LAST_NAME, OFFICE_NAME, REPORTING_UNIT\n )\n )\n return\n\n id_components = ID.split(\"-\")\n CANDIDATE_ID = \"{0}-{1}\".format(id_components[1], id_components[2])\n if LAST_NAME == \"None of these candidates\":\n CANDIDATE_ID = \"{0}-{1}\".format(id_components[0], CANDIDATE_ID)\n\n try:\n candidate_election = CandidateElection.objects.get(\n election=ap_meta.election,\n candidate__ap_candidate_id=CANDIDATE_ID,\n )\n except ObjectDoesNotExist:\n print(\n \"No Candidate found for {0} {1} {2}\".format(\n LAST_NAME, OFFICE_NAME, PARTY\n )\n )\n return\n\n candidate = candidate_election.candidate\n\n division = Division.objects.get(\n level__name=DivisionLevel.STATE,\n code_components__postal=STATE_POSTAL,\n )\n\n filter_kwargs = {\n \"candidate_election\": candidate_election,\n \"division\": division,\n }\n\n vote_update = {}\n\n if not ap_meta.override_ap_votes:\n vote_update[\"count\"] = VOTE_COUNT\n vote_update[\"pct\"] = VOTE_PERCENT\n\n if not ap_meta.override_ap_call:\n vote_update[\"winning\"] = WINNER\n vote_update[\"runoff\"] = RUNOFF\n\n if WINNER:\n ap_meta.called = True\n\n if ap_meta.precincts_reporting != PRECINCTS_REPORTING:\n ap_meta.precincts_reporting = PRECINCTS_REPORTING\n ap_meta.precincts_total = PRECINCTS_TOTAL\n ap_meta.precincts_reporting_pct = PRECINCTS_REPORTING_PERCENT\n\n if PRECINCTS_REPORTING_PERCENT == 1 or UNCONTESTED or tabulated:\n ap_meta.tabulated = True\n else:\n ap_meta.tabulated = False\n\n ap_meta.save()\n\n votes = Votes.objects.filter(**filter_kwargs)\n\n if (WINNER or RUNOFF) and not candidate_election.uncontested:\n # If new call on contested race, send alerts\n first = votes.first()\n\n if not (first.winning or first.runoff) and not no_bots:\n if ap_meta.election.party:\n PRIMARY_PARTY = ap_meta.election.party.label\n else:\n PRIMARY_PARTY = None\n\n # construct page URL for payload\n if app_settings.AWS_S3_BUCKET == \"interactives.politico.com\":\n base_url = \"https://www.politico.com/election-results/2018\"\n end_path = \"\"\n else:\n base_url = \"https://s3.amazonaws.com/staging.interactives.politico.com/election-results/2018\" # noqa\n end_path = \"index.html\"\n\n if RACE_TYPE == \"Runoff\":\n state_path = \"{}/runoff\".format(division.slug)\n elif \"Special\" in RACE_TYPE:\n # first check to see if this special is on a state page\n events = ElectionEvent.objects.filter(\n division=division,\n election_day__slug=ELEX_ELECTION_DATE,\n )\n print(events, division, ELEX_ELECTION_DATE)\n\n if len(events) > 0:\n state_path = division.slug\n else:\n parsed = datetime.strptime(\n ELEX_ELECTION_DATE, \"%Y-%m-%d\"\n )\n month = parsed.strftime(\"%b\").lower()\n day = parsed.strftime(\"%d\")\n\n state_path = \"{}/special-election/{}-{}\".format(\n division.slug, month, day\n )\n else:\n state_path = division.slug\n\n url = \"{}/{}/{}\".format(base_url, state_path, end_path)\n\n payload = {\n \"race_id\": RACE_ID,\n \"division\": division.label,\n \"division_slug\": division.slug,\n \"office\": format_office_label(\n candidate.race.office, division.label\n ),\n \"office_short\": short_format_office_label(\n candidate.race.office, division.label\n ),\n \"candidate\": \"{} {}\".format(\n candidate.person.first_name, candidate.person.last_name\n ),\n \"election_date\": ELEX_ELECTION_DATE,\n \"candidate_party\": candidate.party.ap_code,\n \"primary_party\": PRIMARY_PARTY,\n \"vote_percent\": VOTE_PERCENT,\n \"vote_count\": VOTE_COUNT,\n \"runoff\": RUNOFF,\n \"precincts_reporting_percent\": PRECINCTS_REPORTING_PERCENT,\n \"jungle\": RACE_TYPE == \"Open Primary\",\n \"runoff_election\": RACE_TYPE == \"Runoff\",\n \"special_election\": \"Special\" in RACE_TYPE,\n \"page_url\": url,\n }\n\n call_race_in_slack.delay(payload)\n call_race_in_slackchat.delay(payload)\n call_race_on_twitter.delay(payload)\n\n votes.update(**vote_update)\n\n if OFFICE_NAME == \"U.S. House\":\n bop_body = self.bop[\"house\"]\n elif OFFICE_NAME == \"U.S. Senate\":\n bop_body = self.bop[\"senate\"]\n else:\n return\n\n if not PARTY:\n return\n\n if (WINNER and not ap_meta.override_ap_call) or votes.first().winning:\n party_slug = PARTY.lower()\n incumbent = self.get_current_party(ap_meta.election.race)\n\n if PARTY not in [\"Dem\", \"GOP\"]:\n if (\n STATE_POSTAL in [\"VT\", \"ME\"]\n and OFFICE_NAME == \"U.S. Senate\"\n ):\n bop_body[\"dem\"][\"total\"] += 1\n else:\n bop_body[\"other\"][\"total\"] += 1\n else:\n bop_body[party_slug][\"total\"] += 1\n if party_slug != incumbent:\n print(result, votes.first().winning)\n print(LAST_NAME, candidate.race.office)\n bop_body[party_slug][\"flips\"] += 1\n\n def main(self, options):\n TABULATED = options[\"tabulated\"]\n PASSED_ELECTION_DATE = options[\"election_date\"]\n LEVEL = options[\"level\"]\n RUN_ONCE = options[\"run_once\"]\n NO_BOTS = options[\"no_bots\"]\n INTERVAL = app_settings.DATABASE_UPLOAD_DAEMON_INTERVAL\n\n while True:\n results = self.load_results(LEVEL)\n self.bop = {\n \"house\": {\n \"dem\": {\"total\": 0, \"flips\": 0},\n \"gop\": {\"total\": 0, \"flips\": 0},\n \"other\": {\"total\": 0},\n \"undecided\": 0,\n \"projected\": self.get_chamber_call(\"house\"),\n },\n \"senate\": {\n \"dem\": {\"total\": 23, \"flips\": 0},\n \"gop\": {\"total\": 42, \"flips\": 0},\n \"other\": {\"total\": 0},\n \"undecided\": 0,\n \"projected\": self.get_chamber_call(\"senate\"),\n },\n }\n\n for result in tqdm(results):\n self.process_result(\n result, TABULATED, NO_BOTS, PASSED_ELECTION_DATE\n )\n\n # self.bop_calculations()\n\n # print(self.bop)\n # bake_bop(self.bop)\n\n if RUN_ONCE:\n print(\"Run once specified, exiting.\")\n sys.exit(0)\n\n sleep(INTERVAL)\n\n def add_arguments(self, parser):\n parser.add_argument(\"election_date\", type=str)\n parser.add_argument(\"level\", type=str)\n parser.add_argument(\"--run_once\", dest=\"run_once\", action=\"store_true\")\n parser.add_argument(\n \"--tabulated\", dest=\"tabulated\", action=\"store_true\"\n )\n parser.add_argument(\"--nobots\", dest=\"no_bots\", action=\"store_true\")\n\n def handle(self, *args, **options):\n self.main(options)\n","sub_path":"aploader/management/commands/reup_to_db.py","file_name":"reup_to_db.py","file_ext":"py","file_size_in_byte":14563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"158895914","text":"# -*- coding: utf-8 -*-\n\n# @Date : 2018-10-26\n# @Author : Peng Shiyu\nimport sys\nsys.path.append(\"..\")\nfrom gking.plugin.creatart import git_post\n# from runscrapy import run_scrapy\nimport os\nimport subprocess\nfrom flask import (\n Flask,\n render_template,\n request,\n jsonify,\n)\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/gkingcrawl\")\ndef gkingcrawl():\n\n print('begin to scrapy crawl gking')\n # # bellow is ok\n rs=subprocess.check_output(['python','runspider.py','gking'])\n return \"ok\"\n pass\n\n@app.route(\"/gkingpost\")\ndef gkingpost():\n res=git_post()\n data={\"postnum\":str(res)}\n return jsonify(data)\n pass\n\n@app.route(\"/get\")\ndef get():\n headers = dict(request.headers)\n data = {}\n data[\"headers\"] = headers\n data[\"url\"] = request.url\n data[\"args\"] = request.args\n data[\"remote_addr\"] = request.remote_addr\n\n return jsonify(data)\n\n\n@app.route(\"/post\", methods=[\"POST\"])\ndef post():\n headers = dict(request.headers)\n data = {}\n data[\"headers\"] = headers\n data[\"url\"] = request.url\n data[\"form\"] = request.form\n data[\"remote_addr\"] = request.remote_addr\n\n return jsonify(data)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"579038116","text":"import os\nimport sys\nfrom unittest.mock import Mock\n\nimport numpy as np\nimport pytest\nimport xarray as xr\nfrom roocs_utils.exceptions import InvalidParameterValue, MissingParameterValue\nfrom roocs_utils.parameter import area_parameter, time_parameter\nfrom roocs_utils.utils.common import parse_size\n\nimport clisops\nfrom clisops import CONFIG\nfrom clisops.ops.subset import _subset, subset\nfrom clisops.utils import map_params, output_utils\nfrom clisops.utils.file_namers import get_file_namer\nfrom clisops.utils.output_utils import _format_time, get_output, get_time_slices\n\nfrom .._common import CMIP5_RH, CMIP5_TAS, CMIP5_TAS_FILE, CMIP5_ZOSTOGA, CMIP6_O3\n\n\ndef _check_output_nc(result, fname=\"output_001.nc\"):\n assert fname in [os.path.basename(_) for _ in result]\n\n\ndef _load_ds(fpath):\n return xr.open_mfdataset(fpath)\n\n\ndef test_subset_no_params(tmpdir):\n \"\"\" Test subset without area param.\"\"\"\n result = subset(\n ds=CMIP5_TAS_FILE,\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_subset_time(tmpdir):\n \"\"\" Tests clisops subset function with a time subset.\"\"\"\n result = subset(\n ds=CMIP5_TAS_FILE,\n time=(\"2005-01-01T00:00:00\", \"2020-12-30T00:00:00\"),\n area=(0, -90.0, 360.0, 90.0),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_subset_args_as_parameter_classes(tmpdir):\n \"\"\"Tests clisops subset function with a time subset\n with the arguments as parameter classes from roocs-utils.\"\"\"\n\n time = time_parameter.TimeParameter((\"2000-01-01T00:00:00\", \"2020-12-30T00:00:00\"))\n area = area_parameter.AreaParameter((0, -90.0, 360.0, 90.0))\n\n result = subset(\n ds=CMIP5_TAS_FILE,\n time=time,\n area=area,\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_subset_invalid_time(tmpdir):\n \"\"\" Tests subset with invalid time param.\"\"\"\n with pytest.raises(InvalidParameterValue):\n subset(\n ds=CMIP5_TAS_FILE,\n time=(\"yesterday\", \"2020-12-30T00:00:00\"),\n area=(0, -90.0, 360.0, 90.0),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n\n\ndef test_subset_ds_is_none(tmpdir):\n \"\"\" Tests subset with ds=None.\"\"\"\n with pytest.raises(MissingParameterValue):\n subset(\n ds=None,\n time=(\"2020-01-01T00:00:00\", \"2020-12-30T00:00:00\"),\n area=(0, -90.0, 360.0, 90.0),\n output_dir=tmpdir,\n )\n\n\ndef test_subset_no_ds(tmpdir):\n \"\"\" Tests subset with no dataset provided.\"\"\"\n with pytest.raises(TypeError):\n subset(\n time=(\"2020-01-01T00:00:00\", \"2020-12-30T00:00:00\"),\n area=(0, -90.0, 360.0, 90.0),\n output_dir=tmpdir,\n )\n\n\ndef test_subset_area_simple_file_name(tmpdir):\n \"\"\" Tests clisops subset function with a area subset (simple file name).\"\"\"\n result = subset(\n ds=CMIP5_TAS_FILE,\n area=(0.0, 10.0, 10.0, 65.0),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_subset_area_project_file_name(tmpdir):\n \"\"\" Tests clisops subset function with a area subset (derived file name).\"\"\"\n result = subset(\n ds=CMIP5_TAS_FILE,\n area=(0.0, 10.0, 10.0, 65.0),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"standard\",\n )\n _check_output_nc(result, \"tas_mon_HadGEM2-ES_rcp85_r1i1p1_20051216-20301116.nc\")\n\n\ndef test_subset_invalid_area(tmpdir):\n \"\"\" Tests subset with invalid area param.\"\"\"\n with pytest.raises(InvalidParameterValue):\n subset(\n ds=CMIP5_TAS_FILE,\n area=(\"zero\", 49.0, 10.0, 65.0),\n output_dir=tmpdir,\n )\n\n\n@pytest.mark.xfail(reason=\"cross the 0 degree meridian not implemented.\")\ndef test_subset_area_with_meridian(tmpdir):\n \"\"\" Tests clisops subset function with a area subset.\"\"\"\n result = subset(\n ds=CMIP5_TAS_FILE,\n area=(-10.0, 49.0, 10.0, 65.0),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_subset_with_time_and_area(tmpdir):\n \"\"\" Tests clisops subset function with time, area, level subsets.\"\"\"\n result = subset(\n ds=CMIP5_TAS_FILE,\n time=(\"2019-01-01T00:00:00\", \"2020-12-30T00:00:00\"),\n area=(0.0, 0.0, 10.0, 65.0),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_subset_with_multiple_files_tas(tmpdir):\n \"\"\" Tests with multiple tas files\"\"\"\n result = subset(\n ds=CMIP5_TAS,\n time=(\"2001-01-01T00:00:00\", \"2020-12-30T00:00:00\"),\n area=(0.0, 0.0, 10.0, 65.0),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_subset_with_multiple_files_zostoga(tmpdir):\n \"\"\" Tests with multiple zostoga files\"\"\"\n result = subset(\n ds=CMIP5_ZOSTOGA,\n time=(\"2000-01-01T00:00:00\", \"2020-12-30T00:00:00\"),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_subset_with_multiple_files_rh(tmpdir):\n \"\"\" Tests with multiple rh files\"\"\"\n result = subset(\n ds=CMIP5_RH,\n time=(\"2005-01-01T00:00:00\", \"2020-12-30T00:00:00\"),\n area=(0, -90.0, 360.0, 90.0),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_subset_with_tas_series(tmpdir, tas_series):\n \"\"\" Test with tas_series fixture\"\"\"\n result = subset(\n ds=tas_series([\"20\", \"22\", \"25\"]),\n time=(\"2000-07-01T00:00:00\", \"2020-12-30T00:00:00\"),\n output_dir=tmpdir,\n output_type=\"nc\",\n file_namer=\"simple\",\n )\n _check_output_nc(result)\n\n\ndef test_time_slices_in_subset_tas():\n start_time, end_time = \"2001-01-01T00:00:00\", \"2200-12-30T00:00:00\"\n\n time_slices = [\n (\"2005-12-16\", \"2040-03-16\"),\n (\"2040-04-16\", \"2074-07-16\"),\n (\"2074-08-16\", \"2108-10-16\"),\n (\"2108-11-16\", \"2143-02-16\"),\n (\"2143-03-16\", \"2177-06-16\"),\n (\"2177-07-16\", \"2199-12-16\"),\n ]\n\n config_max_file_size = CONFIG[\"clisops:write\"][\"file_size_limit\"]\n temp_max_file_size = \"10KB\"\n CONFIG[\"clisops:write\"][\"file_size_limit\"] = temp_max_file_size\n\n outputs = subset(\n ds=CMIP5_TAS,\n time=(start_time, end_time),\n area=(0.0, 5.0, 50.0, 90.0),\n output_type=\"xarray\",\n file_namer=\"simple\",\n )\n CONFIG[\"clisops:write\"][\"file_size_limit\"] = config_max_file_size\n\n assert _format_time(outputs[0].time.values.min()) >= start_time\n assert _format_time(outputs[-1].time.values.max()) <= end_time\n\n count = 0\n for _ in outputs:\n assert _format_time(outputs[count].time.values.min()) >= time_slices[count][0]\n assert _format_time(outputs[count].time.values.max()) >= time_slices[count][1]\n count += 1\n\n\ndef test_time_slices_in_subset_rh():\n start_time, end_time = \"2001-01-01T00:00:00\", \"2200-12-30T00:00:00\"\n\n time_slices = [\n (\"2001-01-16\", \"2002-09-16\"),\n (\"2002-10-16\", \"2004-06-16\"),\n (\"2004-07-16\", \"2005-11-16\"),\n ]\n\n config_max_file_size = CONFIG[\"clisops:write\"][\"file_size_limit\"]\n temp_max_file_size = \"10KB\"\n CONFIG[\"clisops:write\"][\"file_size_limit\"] = temp_max_file_size\n outputs = subset(\n ds=CMIP5_RH,\n time=(start_time, end_time),\n area=(0.0, 5.0, 50.0, 90.0),\n output_type=\"xarray\",\n file_namer=\"simple\",\n )\n CONFIG[\"clisops:write\"][\"file_size_limit\"] = config_max_file_size\n\n assert _format_time(outputs[0].time.values.min()) >= start_time\n assert _format_time(outputs[-1].time.values.max()) <= end_time\n\n count = 0\n for _ in outputs:\n assert _format_time(outputs[count].time.values.min()) >= time_slices[count][0]\n assert _format_time(outputs[count].time.values.max()) >= time_slices[count][1]\n count += 1\n\n\n# area can be a few degrees out\ndef test_area_within_area_subset():\n area = (0.0, 10.0, 175.0, 90.0)\n\n outputs = subset(\n ds=CMIP5_TAS,\n time=(\"2001-01-01T00:00:00\", \"2200-12-30T00:00:00\"),\n area=area,\n output_type=\"xarray\",\n file_namer=\"simple\",\n )\n\n ds = outputs[0]\n assert area[0] <= ds.lon.data <= area[2]\n assert area[1] <= ds.lat.data <= area[3]\n\n\ndef test_area_within_area_subset_chunked():\n\n start_time, end_time = \"2001-01-01T00:00:00\", \"2200-12-30T00:00:00\"\n area = (0.0, 10.0, 175.0, 90.0)\n\n config_max_file_size = CONFIG[\"clisops:write\"][\"file_size_limit\"]\n temp_max_file_size = \"10KB\"\n CONFIG[\"clisops:write\"][\"file_size_limit\"] = temp_max_file_size\n outputs = subset(\n ds=CMIP5_TAS,\n time=(start_time, end_time),\n area=area,\n output_type=\"xarray\",\n file_namer=\"simple\",\n )\n CONFIG[\"clisops:write\"][\"file_size_limit\"] = config_max_file_size\n\n for ds in outputs:\n assert area[0] <= ds.lon.data <= area[2]\n assert area[1] <= ds.lat.data <= area[3]\n\n\ndef test_subset_level(tmpdir):\n \"\"\" Tests clisops subset function with a level subset.\"\"\"\n # Levels are: 100000, ..., 100\n ds = _load_ds(CMIP6_O3)\n\n result1 = subset(ds=CMIP6_O3, level=\"100000/100\", output_type=\"xarray\")\n\n np.testing.assert_array_equal(result1[0].o3.values, ds.o3.values)\n\n result2 = subset(ds=CMIP6_O3, level=\"100/100\", output_type=\"xarray\")\n\n np.testing.assert_array_equal(result2[0].o3.shape, (1200, 1, 2, 3))\n\n result3 = subset(ds=CMIP6_O3, level=\"101/-23.234\", output_type=\"xarray\")\n\n np.testing.assert_array_equal(result3[0].o3.values, result2[0].o3.values)\n","sub_path":"tests/ops/test_subset.py","file_name":"test_subset.py","file_ext":"py","file_size_in_byte":9958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"625751818","text":"import csv\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef openCSVfile(path):\n with open(path, 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n return reader\n\ndef main():\n path = \"data/resultsnightloop_jordanrandom.csv\"\n nms = [\"Type\",\"Num of Itters\", \"Current Sample Size\", \"Total Sample Size\", \"Number in the Mandel Set\"]\n pandasdata = pd.read_csv(path, delimiter=',', names=nms)\n random_data = pandasdata[pandasdata.Type == 'random1']\n antithetic_data = pandasdata[pandasdata.Type == 'random2']\n del random_data['Type']\n del antithetic_data['Type']\n\n #print(random_data)\n #mydata = np.genfromtxt(path, delimiter=',')\n #mydata = np.delete(mydata, 0,axis =1)\n\n #randomdata = mydata\n #antitheticdata = mydata\n #print(randomdata)\n #print(mydata[0,:])\n # for i in range(mydata.shape[0], 0, -1):\n # if i%2 == 0:\n # randomdata = np.delete(randomdata, i, axis=0)\n # else:\n # antitheticdata = np.delete(antitheticdata, i, axis=0)\n\n #np.savetxt(\"randomsampleR.csv\", randomdata, delimiter=\",\")\n #np.savetxt(\"randomsampleA.csv\", antitheticdata, delimiter=\",\")\n #print(randomdata)\n #print(antitheticdata)\n\n #print(randomdata)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"boxplot_backup.py","file_name":"boxplot_backup.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"349554658","text":"#输出函数\ndef showdata(data):\n for i in range(len(data)):\n print(\"%3d\"%data[i],end=\" \")\n\n#选择函数\ndef xuanze(data):\n for i in range(len(data)):\n for j in range(i+1,len(data),+1):\n if data[i]>data[j]:\n data[i],data[j]=data[j],data[i]\n print(\"第%d次选择排序的结果为:\"%int(i+1),end=\" \")\n print()\n for i in range(len(data)):\n print(\"%3d\"%data[i],end=\" \")\n print()\n print(\"排序后的结果为:\")\n showdata(data)\n\nif __name__ == '__main__':\n data=[5,9,8,7,6,2,8]\n xuanze(data)\n\n\n\n","sub_path":"第八章 排序——自己写/选择排序——自己练习.py","file_name":"选择排序——自己练习.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"634172389","text":"import datetime\nimport hashlib\nimport math\nimport pytz\nimport re\nimport time\n\nfrom django.conf import settings\nfrom django.db import connection\nfrom django.utils.timezone import localtime\n\n\ndef api_auth():\n epoch = int(math.floor(time.time()))\n hash_str = '%s.%s.%s' % (\n settings.SALEBOX['API']['KEY'],\n settings.SALEBOX['API']['LICENSE'],\n epoch\n )\n\n return {\n 'pos': settings.SALEBOX['API']['KEY'],\n 'epoch': epoch,\n 'hash': hashlib.sha256(hash_str.encode('utf-8')).hexdigest(),\n 'software_type': 'salebox_django',\n 'software_version': '0.0.219'\n }\n\ndef dictfetchall(sql):\n with connection.cursor() as cursor:\n cursor.execute(sql)\n columns = [col[0] for col in cursor.description]\n return [\n dict(zip(columns, row))\n for row in cursor.fetchall()\n ]\n\ndef fetchflatlist(sql):\n with connection.cursor() as cursor:\n cursor.execute(sql)\n return [row[0] for row in cursor.fetchall()]\n\ndef fetchsinglevalue(sql):\n return fetchflatlist(sql)[0]\n\ndef get_rating_display(score, vote_count):\n if vote_count > 0:\n return {\n '100': score,\n '5': round(score / 20),\n '10': round(score / 10)\n }\n else:\n return {'100': 0, '5': 0, '10': 0}\n\ndef json_to_datetime_local(value):\n return localtime(json_to_datetime_utc(value))\n\ndef json_to_datetime_utc(value):\n return datetime.datetime(*value, tzinfo=pytz.UTC)\n\ndef update_natural_sort(model, str_column, sort_column):\n # retrieve all rows\n rows = list(model.objects.values('id', str_column, sort_column))\n\n # update string to be sortable\n for row in rows:\n row[str_column] = row[str_column].lower()\n row[str_column] = row[str_column].strip()\n row[str_column] = re.sub(r'^the\\s+', '', row[str_column])\n row[str_column] = re.sub(r'\\d+', lambda x: '%08d' % (int(x.group(0)),), row[str_column])\n\n # sort the values\n rows = sorted(rows, key=lambda k: k[str_column])\n\n # update the database records that need it\n for i, row in enumerate(rows):\n if i != row[sort_column]:\n model.objects.filter(id=row['id']).update(**{sort_column: i})\n","sub_path":"saleboxdjango/lib/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"117229192","text":"# EP 2019-1: Escape Insper\n#\n# Alunos: \n# - aluno A: Henrique Mualem Marti, henriquemm3@al.insper.edu.br\n# - aluno B: Thiago Lopes, thiagod@al.insper.edu.br\n\n\n\"\"\"\nNKO Enterprises Presents: Escape Insper\n\nCreated on Tue Apr 16 16:32:14 2019\n\n@author: Maulem and ThiagoD\n\nObjetivos do jogo: Juntar medalhoes do fogo, da agua e da neve, transformando em um medalhao dos 3 elementos,\ndepois entrar no portal(pulando da cobertura do insper).\n\"\"\"\n###Imports:\n\nimport time\nimport random\n\n\n###CONTROLADORES DO JOGO PARA USO DO PROFESSOR (DESATIVE TEMPO DAS ANIMACOES E DAS ACOES DO JOGO AQUI!)\n\nt02 = 0.2 #Tempo de 0.2 segundos no time sleep |ANIMACOES|\nt05 = 0.5 #Tempo de 0.5 segundos no time sleep |ANIMACOES|\nt1 = 0.1 #Tempo de 0.1 segundos no time sleep |ANIMACOES|\nt10 = 1 #Tempo de 1 segundo no time sleep |ANIMACOES|\n\ntx1 = 1 #Tempo de 1 segundo no time sleep |INICIO DO JOGO|\n\nty1 = 1 #Tempo de 1 segundo no time sleep |QUANDO VC VIAJA DE CENARIO EM CENARIO|\n\n\n###Variaveis iniciais:\n\ngame_win = 0 #500 para vencer o jogo\nplayer = \"*****\" #nome inicial para evitar bugs\ngame_over = False #fim de jogo\ncomeu = False #feature sorte e itens magicos\naspas = '\"' #escrever aspas no .format\nmedalhao_fogo = 0\nmedalhao_agua = 0 #os medalhoes estavam dando bug com True e False por isso ficou 0 e 1\nmedalhao_neve = 0\nmedalhao_3_elementos = False ###medalhao da vitoria!\ncontador = 0 ###Contador de erros de digitacao\nvida_player = 100\nvida_boneco = 20\nvida_EL_RAUL = 100\nmedalha_EL_RAUL = False #medalha ganha ao derrotar EL RAUL\n\n###Animação de entrada:\n\ntime.sleep(t02)\nprint(\"Initializing...\")\ntime.sleep(t05)\nprint(\" ______ ______ ______ ___ ___ ______\")\ntime.sleep(t02)\nprint(\"| | | | | | | | | | | \")\ntime.sleep(t02)\nprint(\"| | | | | | | | | | | \")\ntime.sleep(t02)\nprint(\"| | | |---- | | | | | | | |---- \")\ntime.sleep(t02)\nprint(\"| | | | | | | | | | | \")\ntime.sleep(t02)\nprint(\"|___|___| |______ |_____ |______ |______| | | |______\")\ntime.sleep(t02)\n\n\n\n###Animacão da morte:\n\n\ndef death(game_over): ###Raul perdao por botar print dentro de funcao mas nao sei como fazer para a animacao\n if game_over == True:###funcionar só usando return.\n time.sleep(t10)\n print()\n print(' uuuuuuu')\n time.sleep(t1)\n print(' uu$$$$$$$$$$$uu')\n time.sleep(t1)\n print(' uu$$$$$$$$$$$$$$$$$uu')\n time.sleep(t1)\n print(' u$$$$$$$$$$$$$$$$$$$$$u ')\n time.sleep(t1)\n print(' u$$$$$$$$$$$$$$$$$$$$$$$u ')\n time.sleep(t1)\n print(' u$$$$$$$$$$$$$$$$$$$$$$$$$u ')\n time.sleep(t1)\n print(' u$$$$$$$$$$$$$$$$$$$$$$$$$u ')\n time.sleep(t1)\n print(' u$$$$$$\" \"$$$\" \"$$$$$$u ')\n time.sleep(t1)\n print(' \"$$$$\" u$u $$$$\" ')\n time.sleep(t1)\n print(' $$$u u$u u$$$ ')\n time.sleep(t1)\n print(' $$$u u$$$u u$$$ ')\n time.sleep(t1)\n print(' \"$$$$uu$$$ $$$uu$$$$\" ')\n time.sleep(t1)\n print(' \"$$$$$$$\" \"$$$$$$$\" ')\n time.sleep(t1)\n print(' u$$$$$$$u$$$$$$$u')\n time.sleep(t1)\n print(' u$\"$\"$\"$\"$\"$\"$u')\n time.sleep(t1)\n print(' uuu $$u$ $ $ $ $u$$ uuu')\n time.sleep(t1)\n print(' u$$$$ $$$$$u$u$u$$$ u$$$$')\n time.sleep(t1)\n print(' $$$$$uu \"$$$$$$$$$\" uu$$$$$$')\n time.sleep(t1)\n print(' u$$$$$$$$$$$uu \"\"\"\"\" uuuu$$$$$$$$$$')\n time.sleep(t1)\n print(' $$$$\"\"\"$$$$$$$$$$uuu uu$$$$$$$$$\"\"\"$$$\"')\n time.sleep(t1)\n print(' \"\"\" \"\"$$$$$$$$$$$uu \"\"$\"\"\"')\n time.sleep(t1)\n print(' uuuu \"\"$$$$$$$$$$uuu')\n time.sleep(t1)\n print(' u$$$uuu$$$$$$$$$uu \"\"$$$$$$$$$$$uuu$$$')\n time.sleep(t1)\n print(' $$$$$$$$$$\"\"\"\" \"\"$$$$$$$$$$$\"')\n time.sleep(t1)\n print(' \"$$$$$\" \"\"$$$$\"\"')\n time.sleep(t1)\n print(' $$$\" $$$$\"')\n print()\n time.sleep(t10)\n \n return \" Game over!\"\n\n###Animação de vencer o jogo:\n\n\ndef win(game): ###Raul perdao por botar print dentro de funcao mas nao sei como fazer para a animacao\n if game == True: ###funcionar só usando return.\n time.sleep(t02)\n print(\" \") \n time.sleep(t02)\n print(\" \\ / ____ | | | |\\ | |\")\n time.sleep(t02)\n print(\" \\ / | | | | | | | | \\ | |\")\n time.sleep(t02) \n print(\" | | | | | | | | | | \\ | |\")\n time.sleep(t02)\n print(\" | | | | | | | | | | \\ | |\")\n time.sleep(t02)\n print(\" | |____| |___| |___|___| | | \\| o\") \n time.sleep(t02)\n print(\"\")\n return \"Parabens!\"\n\n###Introdução ao game:\n\n\nprint(\"Bem vindo ao Escape Insper\")\nprint(\"Digite o nome do seu jogador:\")\nplayer = input(\"Nome:\")\n\n'''print(\"\\x1b[2J\\x1b[1;1H\") '''###Esse comando limpa a tela do console do usuario ##decidi nao usar porque nao sei se vc gostaria\n\nprint(\"\") ###Esse comando pula uma linha para ficar organizado apos usar o comando acima.\nprint(\"Bem vindo {0} ao Escape Insper!\".format(player))\ntime.sleep(tx1)\nprint(\"\")\nprint(\"Descrição do jogo:\")\ntime.sleep(tx1)\nprint(\"Você é um aluno do Insper que teve uma crise de insonia e dormiu alguns dias seguidos perdendo aulas e chegando no dia da entrega do EP.\")\nprint(\"\")\ntime.sleep(tx1)\nprint(\"Você então vai tentar pedir para o professor adiar a entrega, mas para isso primeiro vai ter que achar ele. \")\nprint(\"\")\ntime.sleep(tx1)\nprint(\"Então boa sorte na sua jornada {0}!\".format(player))\nprint(\"\")\ntime.sleep(tx1)\n\n###Sistema de inventarios dos medalhoes:\n\ndef medalhoes(fogo, agua, neve):\n if fogo == 1 and agua == 1 and neve == 1:\n return True\n else:\n return False\n\n###Cenarios gerais:\n\ndef carregar_cenarios():\n cenarios = {\n \"inicio\": {\n \"titulo\": \"Rua da perdição\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": \"Voce esta na frente dos dois predios do Insper. \"\n \"Para qual predio voce quer ir?\",\n \"opcoes\": {\n \"predio 1\": \"entrar no predio 1\",\n \"predio 2\": \"entrar no predio 2\"\n }\n },\n \"predio 1\": {\n \"titulo\": \"Predio velhão\",\n \"descricao\": \"Voce esta no saguao de entrada do predio 1\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"opcoes\": {\n \"inicio\": \"voltar pra rua\",\n \"biblioteca\": \"ir para a biblioteca buscar pistas\",\n \"elevador\": \"ir pro elevador para procurar o professor\"\n }\n },\n \"predio 2\": {\n \"titulo\": \"A grande inundação\",\n \"descricao\": \"Na entrada do predio 2 vc percebe que esta tudo inundado\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": {},### MEDALHAO DE AGUA ATIVADO\n \"opcoes\": {\"inicio\": \"voltar pra rua\"}###Opcoes nunca podem estar em branco senao eh game over!\n }, \n \"biblioteca\": {\n \"titulo\": \"A casa dos livros\",\n \"descricao\": \"Voce sente um cheiro misterioso e quente vindo de uma das salas do fundao!\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"opcoes\": {\n \"sala misteriosa\": \"ir investigar o cheiro misterioso\",\n \n \"predio 1\": \"voltar para o saguao de entrada do predio 1\"\n }\n },\n \"sala misteriosa\": {\n \"titulo\": \"O cachorro quente magico\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": \"Voce ve um cachorro quente cheiroso e quentinho em cima da mesa. \"\n \"Voce pode come-lo para ganhar alguma habilidade especial... \"\n \"ou talvez deixa-lo la ja que ele nao é seu... \",\n \"opcoes\": {\n \"comer\": \"encher a pança com esse delicioso cachorro quente\",\n \"biblioteca\": \"voltar para a Biblioteca\"\n }\n },\n \"comer\": {#O que acontecera a seguir depende do randint por isso nao importa descricao e opcoes.\n \"titulo\": \"Sorte ou Azar?\",\n \"descricao\": \"whatever\",\n \"key\": {},### |ATIVA A SALA SECRETA|\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"opcoes\": {\n \"biblioteca\": \"voltar para a Biblioteca\"###Opcoes nunca podem estar em branco senao eh game over!\n }\n },\n \"5 andar\": {\n \"titulo\": \"O andar da comida cara\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": \"Voce sente um cheiro maravilhoso de comida ao sair do elevador. \"\n \"Voce avista alguem de costas que parece ser o seu professor... \"\n \"Mas não dá pra você enxergar direito, talvez se vc chegar mais perto... \",\n \"opcoes\": {\n \"prof\": \"ir falar o professor\",\n \"elevador\": \"voltar para o elevador\"\n }\n },\n\n \"prof\": {\n\n \"titulo\": \"O comilão\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": \"Voce se aproxima do professor rapidamente. \"\n \"Voce escorrega em um cubo de gelo e sai deslizando pelo chão... \"\n \"Ao se aproximar do professor voce percebe que na verdade é só mais um gordinho almoçando!\"\n \"Voce entao cai no prato de comida do comilão e ele literalmente te come! \",\n \"opcoes\": {}\n },\n \"morrer\": {\n\n \"titulo\": \"Morte certa\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": \"Voce se esborracha no chao. \"\n \"Voce tem uma recordacao de toda a sua vida... \"\n \"E percebe que talvez devesse ter pulado com os 3 medalhoes no portal! \"\n \"Voce morre! \",\n \"opcoes\": {}\n },\n\n \"cobertura\": {\n \"titulo\": \"A vista dos ceus\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": \"Voce observa uma linda vista daqui de cima... \"\n \"Da uma vontadezinha de pular... \"\n \"Mas não, isso seria loucura... \",\n \"opcoes\": {\n \"pular\": \"se jogar de cabeça pelo precipicio\",\n \"elevador\": \"voltar para o elevador\"\n }\n },\n \"pular\": {\n \"titulo\": \"O voo setentrional\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": \"Um jato de vento subitamente rasga voçê por dentro. \"\n \"O que era para durar segundos dura uma eternidade... \"\n \"Você percebe um portal se formando... \",\n \"opcoes\": {\n \"morrer\": \"morrer estatelado no chão\",\n \"portal\": \"se encolher e atravessar o portal\"\n }\n },\n \"portal\": {\n \"titulo\": \"Voo interdimensional\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": {},### |DESCRICAO VAZIA PARA ATIVAR O PORTAL|\n \"opcoes\": {\n \"prof\": \"ir falar o professor\",###Opcoes nunca podem estar em branco senao eh game over!\n \"elevador\": \"voltar para o elevador\"###Opcoes nunca podem estar em branco senao eh game over!\n }\n },\n \"Fim\": {#O que acontecera a seguir depende do tcha por isso nao importa descricao e opcoes.\n \"titulo\": \"Parabens vc encontrou o Easter Egg escondido!\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": {},### |ATIVA O FIM DO JOGO|\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": \"Voce sente um cheiro maravilhoso de comida ao sair do elevador. ###Descricao nunca podem estar em branco senao ativa uma feature! \",\n \"opcoes\": {\n \"prof\": \"ir falar o professor\",###Opcoes nunca podem estar em branco senao eh game over!\n \"elevador\": \"voltar para o elevador\"###Opcoes nunca podem estar em branco senao eh game over!\n }\n },\n\n \"elevador\": {\n \"titulo\": \"Caixote de metal\",\n \"key\": \"whatever\",###quando o len(key)=0 ativa a feature da sala secreta na biblioteca(hot dog)\n \"tcha\": \"whatever\",###quando o len(tcha)=0 ativa a feature do easter egg\n \"aqua\": \"whatever\",###quando o len(aqua)=0 ativa a feature do medalhao de agua\n \"descricao\": \"Voce esta no elevador\",\n \"opcoes\": {\n \"inicio\": \"voltar para o saguao de entrada\",\n \"5 andar\": \"ir para o andar da comida\",\n \"cobertura\": \"observar a vista\"\n \n }\n }\n }\n nome_cenario_atual = \"inicio\"\n return cenarios, nome_cenario_atual \n\n\ncenarios, cenario_atual = carregar_cenarios()\n\n\n###Jogo central:\n\n\nwhile not game_over and game_win != 500:\n \n medalhao_3_elementos = medalhoes(medalhao_fogo, medalhao_agua, medalhao_neve)#checa se vc conseguiu os 3 medalhoes\n \n cenario_atual = cenarios[cenario_atual]\n \n sala_key = cenario_atual[\"key\"]#parte da feature de sorte e azar\n \n descricao = cenario_atual[\"descricao\"]#parte da feature do portal\n \n sala_fim = cenario_atual[\"tcha\"]#parte da feature do easter egg\n \n aqua_medalhao = cenario_atual[\"aqua\"]#parte da feature do medalhao de agua\n\n spawn_monster = random.randint(0, 1001)\n \n#Feature de um chefao que oferece uma dica se vc o vencer\n\n if spawn_monster < 60 and medalha_EL_RAUL == False:\n print(\"A wild mexican EL RAUL appears!\")\n print(\"O que você pretende fazer em relação a esse mexicano que parece seu professor?\")\n print('Opções: \"enfrentar\" ou \"fugir\"')\n luta = input(\"-\")\n if luta == \"enfrentar\":\n print(\"\")\n print(\"El RAUL tem 100 pontos de vida!\")\n print(\"Você tem {0} pontos de vida!\".format(vida_player))\n print(\"\")\n time.sleep(2)\n while vida_player > 0 and vida_EL_RAUL >0:\n atq_player = random.randint(5, 30)\n print(\"\")\n print(\"Você deu {0} de ataque!\".format(atq_player))\n print(\"\")\n time.sleep(2)\n vida_EL_RAUL -= atq_player\n if vida_EL_RAUL < 0:\n vida_EL_RAUL = 0\n print(\"EL RAUL tem {0} pontos de vida!\".format(vida_EL_RAUL))\n time.sleep(4)\n print(\"\")\n print(\"\")\n atq_EL_RAUL = random.randint(1, 20)\n print(\"Ele te deu {0} de dano!\".format(atq_EL_RAUL))\n print(\"\")\n time.sleep(2)\n vida_player -= atq_EL_RAUL\n if vida_player < 0:\n vida_player = 0\n print(\"Você tem {0} pontos de vida!\".format(vida_player))\n print(\"\")\n time.sleep(2)\n if vida_player > 0:\n print(\"Após vencer EL RAUL ele decide adiar o ep e te conta uma coisa interessante!\")\n print(\"\")\n time.sleep(5)\n print(\"Juntando os medalhoes do Fogo, da Agua e da Neve e pulando da cobertura do insper você vera algo interessante!\")\n print(\"\")\n time.sleep(5)\n print(\"Apos fala isso EL RAUL some que nem fumaça!\")\n print(\"\")\n print(\"Voce volta misteriosamente para o inicio!\")\n print(\"\")\n time.sleep(5)\n cenario_atual = \"inicio\"\n medalha_EL_RAUL = True\n else:\n game_over = True\n else:\n print(\"Voce volta misteriosamente para o inicio!\")\n print(\"\")\n cenario_atual = \"inicio\"\n\n#Feature de monstros aleatorios e combate\n elif spawn_monster < 120 and medalhao_neve == False:\n print(\"Um boneco de neve doidão apareceu!\")\n print(\"Você quer enfrenta-lo ou fugir?\")\n print('Opções: \"enfrentar\" ou \"fugir\"')\n luta = input(\"-\")\n if luta == \"enfrentar\":\n print(\"\")\n print(\"O boneco de neve tem 20 pontos de vida!\")\n print(\"Você tem {0} pontos de vida!\".format(vida_player))\n print(\"\")\n time.sleep(2)\n while vida_player > 0 and vida_boneco >0:\n atq_player = random.randint(5, 16)\n print(\"\")\n print(\"Você deu {0} de ataque!\".format(atq_player))\n print(\"\")\n time.sleep(2)\n vida_boneco -= atq_player\n if vida_boneco < 0:\n vida_boneco = 0\n print(\"O boneco de neve tem {0} pontos de vida!\".format(vida_boneco))\n time.sleep(4)\n print(\"\")\n print(\"\")\n atq_boneco = random.randint(1, 6)\n print(\"Ele te deu {0} de dano!\".format(atq_boneco))\n print(\"\")\n time.sleep(2)\n vida_player -= atq_boneco\n if vida_player < 0:\n vida_player = 0\n print(\"Você tem {0} pontos de vida!\".format(vida_player))\n print(\"\")\n time.sleep(2)\n print(\"No seu ataque final vc escorrega na agua deixada pelo boneco e cai de bunda no chao!\")\n print(\"\")\n time.sleep(2)\n print(\"Esse pequeno tremor faz haver um disturbio na rede eletrica que torna as luzes mais intensas...\")\n print(\"\")\n time.sleep(2)\n print(\"O boneco de neve acaba derretendo!\")\n print(\"\")\n time.sleep(2)\n print(\"Fatality!\")\n print(\"\")\n time.sleep(3)\n print(\"Voce volta misteriosamente para o inicio com um medalhao de neve como recompensa pela sua batalha!\")\n time.sleep(4)\n cenario_atual = \"inicio\"\n medalhao_neve = 1\n else:\n print(\"Voce volta misteriosamente para o inicio!\")\n print(\"\")\n cenario_atual = \"inicio\"\n\n#Feature sorte/azar\n\n elif len(sala_key) == 0 and comeu == False:###Primeira feature(Sorte ou Azar?)\n sorte = random.randint(0, 1001)\n if sorte < 801:\n print('Nome da sala:\"comer\"')\n print(\"Ao comer o cahorro quente vc sente uma gosma se formar no fundo do seu estomago!\")\n print(\"Você então cospe essa gosma e um pedaço atinge sua camisa se tornando um simbolo de fogo\")\n print(\"\")\n print(\"Parabens {0}!\".format(player))\n print(\"Você adiquiriu o medalhão do fogo!\")\n cenario_atual = \"biblioteca\"\n del cenarios[\"biblioteca\"][\"descricao\"]\n cenarios[\"biblioteca\"][\"descricao\"] = \"Uma biblioteca agora vazia e monotona!\"\n del cenarios[\"biblioteca\"][\"opcoes\"]\n cenarios[\"biblioteca\"][\"opcoes\"] = {\"predio 1\": \"voltar para o saguao de entrada do predio 1\"}\n comeu = True\n medalhao_fogo = 1\n\n else:\n print(\"Inspetora: É proibido comer na biblioteca!\")\n print(\"Inspetora: Vá agora para o Multiinsper!\")\n print(\"Você fica preso lá por 4 horas o que te faz não encontrar o professor!\")\n time.sleep(1)\n game_over = True\n\n#Sala que só curiosos vao encontrar(Easter Egg!)\n\n elif len(sala_key) == 0 and comeu == True: \n print(\"Olha só temos um espertinho por aqui!\")#A unica maneira de se chegar aqui é com o portal! (Digite \"comer\")\n time.sleep(2)\n print(\"Parabens vc achou o Easter Egg secreto!\")\n time.sleep(2)\n print(\"Esse jogo foi criado pelo Maulem e pelo ThiagoD!\")\n time.sleep(2)\n print(\"Obrigado por jogar o nosso jogo {0}!\".format(player))\n time.sleep(2)\n print(\"Parabenizamos voce pela sua inteligencia!\")\n time.sleep(5)\n print(death(True))\n print(\"\")\n print(\"Zoeira o jogo ainda não acabou!\")\n time.sleep(2)\n print(\"Parabens {0}, vc ganhou o medalhao dos 3 elementos completo!\".format(player))\n print(\"Sugestão: pule novamente {0}!\".format(player))\n time.sleep(3)\n cenario_atual = \"biblioteca\"\n medalhao_agua = 1 \n medalhao_neve = 1 \n medalaho_fogo = 1 ###Para nao bugar o inventario\n\n#Portal:\n\n elif len(descricao) == 0:\n \n if medalhao_3_elementos == True:\n cenario_atual = \"Fim\"\n else:\n print(\"Você percebe que pode ir pra qualquer lugar desde que saiba o nome dele!\")\n print(\"Pra onde você quer ir?\")\n destino = input(\"-\")\n while destino not in cenarios:\n print(\"Destino invalido\")\n destino = input(\"-\")\n cenario_atual = destino\n\n#Fim do jogo(Vitoria):\n\n elif len(sala_fim) == 0:\n print(\"Parabens vc terminou o jogo!\")\n print(\"Esse jogo foi criado pelo Maulem e pelo ThiagoD!\")\n print(\"Obrigado por jogar o nosso jogo {0}!\".format(player))\n time.sleep(5)\n print(death(True))\n print(\"\")\n print(\"Zoeira o jogo ainda não acabou!\")\n time.sleep(3)\n print(\"\")\n print(\"Agora acabou!\")\n time.sleep(3)\n print(win(True))\n game_win = 500 #condicao pra vencer o jogo\n\n#Quando vc entra no predio 2\n\n elif len(aqua_medalhao) == 0:\n print(\"\")\n print(\"Você entra no predio e percebe uma inundacao!\")\n time.sleep(2)\n print(\"Um monstro sobe no seu peito formando um simbolo de agua\")\n time.sleep(2)\n print(\"Você adiquiriu o medalhão de agua!\")\n time.sleep(2)\n cenario_atual = \"inicio\"\n del cenarios[\"inicio\"][\"opcoes\"]\n cenarios[\"inicio\"][\"opcoes\"] = {\"predio 1\": \"entrar no predio 1\"}\n del cenarios[\"inicio\"][\"descricao\"]\n cenarios[\"inicio\"][\"descricao\"] = \"Ja que o predio 2 ta inundado só resta o predio 1!\"\n medalhao_agua = 1\n\n#Jogo normal qdo nao acontece nada de diferente\n\n else:\n print(\"\")\n print(\"Medalhões:\") ###|INVENTARIO|\n print(\"Agua:{0}\".format(medalhao_agua))\n print(\"Neve:{0}\".format(medalhao_neve))\n print(\"Fogo:{0}\".format(medalhao_fogo))\n print(\"\")\n print(\"{0}.\".format(cenario_atual[\"titulo\"]))\n print(\"-\" * len(cenario_atual[\"titulo\"]))\n time.sleep(ty1)\n print(cenario_atual[\"descricao\"])\n time.sleep(ty1)\n print(\"\")\n print(\"Suas opcoes são:\")\n for chave in cenario_atual[\"opcoes\"]:\n print(\"Digite: {0}{1}{2} para {3}.\".format(aspas, chave, aspas, cenario_atual[\"opcoes\"][chave]))\n\n opcoes = cenario_atual[\"opcoes\"] \n if len(opcoes) == 0:\n print(\"Acabaram-se suas opções {0}!\".format(player))\n time.sleep(ty1)\n game_over = True\n else:\n escolha = input(\"-\")\n\n while escolha not in opcoes and contador < 4:\n if contador < 5:\n print(\"Escolha invalida!\")\n escolha = input(\"-\")\n contador+=1\n else:\n print(\"Que pena {0}! Acabaram as suas chances!\".format(player))\n game_over = True\n if contador >= 4:\n print(\"Que pena {0}! Você perdeu!\".format(player))\n time.sleep(ty1)\n game_over = True\n else:\n cenario_atual = escolha\n contador = 0\n\n#Animacao de morte \n\nif game_over == True:\n print(death(True))\n","sub_path":"ep1.py","file_name":"ep1.py","file_ext":"py","file_size_in_byte":28083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"458751290","text":"# -*- coding: utf-8 -*-\r\nfrom datetime import datetime\r\n\r\nfrom banki_ru.helpers import gen_id\r\nfrom banki_ru.object_types import ObjectType, DiscussionType\r\nfrom common.helpers import time_helper\r\nfrom common.helpers.convert import to_int\r\nfrom common.items import Profile, Post, MergedPost, PostView\r\n\r\n\r\ndef profile_from_user(user):\r\n user_id = user['id']\r\n profile = Profile()\r\n profile['_id'] = gen_id.user(user_id)\r\n profile['sm_id'] = user_id\r\n profile['source'] = gen_id.SOURCE\r\n profile['object_type'] = ObjectType.USER\r\n profile['href'] = user['url']\r\n profile['name'] = user['name']\r\n profile['fetch_time'] = time_helper.utc_now()\r\n profile['attrs'] = user\r\n return profile\r\n\r\n\r\ndef post_from_forum_message(message):\r\n message_id = message['id']\r\n\r\n post = Post()\r\n post['_id'] = gen_id.forum_message(message_id)\r\n post['sm_id'] = message_id\r\n post['source'] = 'banki'\r\n post['owner_id'] = gen_id.user(message['author_id'])\r\n post['author_id'] = gen_id.user(message['author_id'])\r\n post['href'] = message['url']\r\n post['discussion_type'] = DiscussionType.FORUM\r\n post['object_type'] = ObjectType.FORUM_TOPIC if message['is_topic'] else ObjectType.FORUM_MESSAGE\r\n topic_id = message.get('topic_id')\r\n post['parent_post_id'] = gen_id.forum_message(topic_id) if topic_id else ''\r\n # naive_post_date = time_helper.to_date(message['date'], parserinfo=time_helper.RU_PARSER_INFO)\r\n naive_post_date = datetime.strptime(message['date'], \"%d.%m.%Y %H:%M\")\r\n msk_post_date = time_helper.localize(naive_post_date, tz=time_helper.TZ_MSK)\r\n post['post_date'] = time_helper.convert(msk_post_date, tz=time_helper.TZ_UTC)\r\n post['fetch_time'] = time_helper.utc_now()\r\n post['attrs'] = message\r\n\r\n return post\r\n\r\n\r\ndef post_from_review(review):\r\n review_id = review['id']\r\n\r\n post = Post()\r\n post['_id'] = gen_id.review(review_id)\r\n post['sm_id'] = review_id\r\n post['source'] = 'banki'\r\n post['owner_id'] = gen_id.user(review['author_id'])\r\n post['author_id'] = gen_id.user(review['author_id'])\r\n post['href'] = review['url']\r\n post['discussion_type'] = DiscussionType.BANK_REVIEW\r\n post['object_type'] = ObjectType.REVIEW\r\n post['parent_post_id'] = ''\r\n naive_post_date = datetime.strptime(review['date'], \"%Y-%m-%d %H:%M:%S\")\r\n msk_post_date = time_helper.localize(naive_post_date, tz=time_helper.TZ_MSK)\r\n post['post_date'] = time_helper.convert(msk_post_date, tz=time_helper.TZ_UTC)\r\n post['fetch_time'] = time_helper.utc_now()\r\n post['attrs'] = review\r\n\r\n return post\r\n\r\n\r\ndef post_from_review_comment(comment):\r\n comment_id = comment['id']\r\n review_id = comment['review_id']\r\n\r\n post = Post()\r\n post['_id'] = gen_id.review_comment(review_id, comment_id)\r\n post['sm_id'] = comment_id\r\n post['source'] = 'banki'\r\n post['owner_id'] = gen_id.user(comment['author_id'])\r\n post['author_id'] = gen_id.user(comment['author_id'])\r\n post['href'] = comment['url']\r\n post['discussion_type'] = DiscussionType.BANK_REVIEW\r\n post['object_type'] = ObjectType.REVIEW_COMMENT\r\n post['parent_post_id'] = gen_id.review(review_id)\r\n naive_post_date = datetime.strptime(comment['date'], \"%Y-%m-%d %H:%M:%S\")\r\n msk_post_date = time_helper.localize(naive_post_date, tz=time_helper.TZ_MSK)\r\n post['post_date'] = time_helper.convert(msk_post_date, tz=time_helper.TZ_UTC)\r\n post['fetch_time'] = time_helper.utc_now()\r\n post['attrs'] = comment\r\n\r\n return post\r\n\r\n\r\ndef merge_post_and_profile(profile, post):\r\n \"\"\"\r\n :type profile: common.items.Profile\r\n :type post: common.items.Post\r\n \"\"\"\r\n result = MergedPost()\r\n result['_id'] = post['_id']\r\n result['source'] = post['source']\r\n result['discussion_type'] = post['discussion_type']\r\n result['object_type'] = post['object_type']\r\n result['fetch_time'] = post['fetch_time']\r\n result['profile'] = dict(profile)\r\n result['post'] = dict(post)\r\n return result\r\n\r\n\r\ndef post_view_from_merged_post(merged_post):\r\n # assert isinstance(merged_post, dict)\r\n\r\n discussion_type = merged_post['discussion_type']\r\n object_type = merged_post['object_type']\r\n profile = merged_post['profile']\r\n post = merged_post['post']\r\n\r\n if discussion_type == DiscussionType.FORUM:\r\n return _post_view_from_forum_message(post, profile)\r\n\r\n if discussion_type == DiscussionType.BANK_REVIEW:\r\n if object_type == ObjectType.REVIEW:\r\n return _post_view_from_review(post, profile)\r\n if object_type == ObjectType.REVIEW_COMMENT:\r\n return _post_view_from_review_comment(post, profile)\r\n\r\n\r\ndef _post_view_from_forum_message(post, profile):\r\n post_view = PostView()\r\n post_view['id'] = post['_id']\r\n post_view['source'] = post['source']\r\n post_view['profile_id'] = profile['_id']\r\n post_view['sm_profile_id'] = profile['sm_id']\r\n # post_view['profile_name'] = '{0} ({1})'.format(profile['name'], profile['attrs'].get('nick_name'))\r\n post_view['profile_name'] = profile['name']\r\n\r\n post_view['profile_href'] = profile['href']\r\n post_view['post_href'] = post['href']\r\n post_view['sm_post_id'] = post['sm_id']\r\n post_view['parent_post_id'] = post['parent_post_id']\r\n post_view['post_date'] = post['post_date']\r\n post_view['fetch_time'] = post['fetch_time']\r\n post_view['post_body'] = post['attrs']['text']\r\n post_view['discussion_type'] = DiscussionType.FORUM\r\n post_view['object_type'] = post['object_type']\r\n\r\n post_view['reach'] = to_int(post['attrs'].get('views', 0))\r\n profile_rating = sum([to_int(s) for s in profile['attrs'].get('ratings', [])])\r\n profile_reputation = to_int(profile['attrs'].get('reputation', 0))\r\n post_view['profile_reach'] = profile_rating + profile_reputation\r\n\r\n post_view['engagement_replies'] = to_int(post['attrs'].get('replies', 0))\r\n post_view['engagement_likes'] = to_int(post['attrs'].get('likes', 0))\r\n post_view['engagement'] = post_view['engagement_replies'] + post_view['engagement_likes']\r\n\r\n post_view['is_comment'] = False\r\n\r\n return post_view\r\n\r\n\r\ndef _post_view_from_review(post, profile):\r\n post_view = PostView()\r\n post_view['id'] = post['_id']\r\n post_view['source'] = post['source']\r\n post_view['profile_id'] = profile['_id']\r\n post_view['sm_profile_id'] = profile['sm_id']\r\n post_view['profile_name'] = profile['name']\r\n\r\n post_view['profile_href'] = profile['href']\r\n post_view['post_href'] = post['href']\r\n post_view['sm_post_id'] = post['sm_id']\r\n post_view['parent_post_id'] = post['parent_post_id']\r\n post_view['post_date'] = post['post_date']\r\n post_view['fetch_time'] = post['fetch_time']\r\n post_view['post_body'] = post['attrs']['text']\r\n post_view['discussion_type'] = post['discussion_type']\r\n post_view['object_type'] = post['object_type']\r\n\r\n post_view['reach'] = to_int(post['attrs'].get('views', 0))\r\n profile_rating = sum([to_int(s) for s in profile['attrs'].get('ratings', [])])\r\n profile_reputation = to_int(profile['attrs'].get('reputation', 0))\r\n post_view['profile_reach'] = profile_rating + profile_reputation\r\n\r\n comments = to_int(post['attrs'].get('comments', 0))\r\n post_view['engagement_comments'] = comments\r\n post_view['engagement'] = comments\r\n\r\n post_view['is_comment'] = False\r\n\r\n post_view['bank_rating'] = to_int(post['attrs']['rating'])\r\n post_view['bank_name'] = post['attrs']['bank_name']\r\n\r\n return post_view\r\n\r\n\r\ndef _post_view_from_review_comment(post, profile):\r\n post_view = PostView()\r\n post_view['id'] = post['_id']\r\n post_view['source'] = post['source']\r\n post_view['profile_id'] = profile['_id']\r\n post_view['sm_profile_id'] = profile['sm_id']\r\n post_view['profile_name'] = profile['name']\r\n\r\n post_view['profile_href'] = profile['href']\r\n post_view['post_href'] = post['href']\r\n post_view['sm_post_id'] = post['sm_id']\r\n post_view['parent_post_id'] = post['parent_post_id']\r\n post_view['post_date'] = post['post_date']\r\n post_view['fetch_time'] = post['fetch_time']\r\n post_view['post_body'] = post['attrs']['text']\r\n post_view['discussion_type'] = post['discussion_type']\r\n post_view['object_type'] = post['object_type']\r\n\r\n post_view['reach'] = to_int(post['attrs'].get('views', 0))\r\n profile_rating = sum([to_int(s) for s in profile['attrs'].get('ratings', [])])\r\n profile_reputation = to_int(profile['attrs'].get('reputation', 0))\r\n post_view['profile_reach'] = profile_rating + profile_reputation\r\n\r\n post_view['engagement'] = 0\r\n post_view['is_comment'] = True\r\n\r\n return post_view\r\n","sub_path":"banki_ru/item_helper.py","file_name":"item_helper.py","file_ext":"py","file_size_in_byte":8682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377147104","text":"#!/usr/bin/env python3\n\nimport os\nfrom xml.etree import ElementTree\nimport sys\nfrom clarity import Clarity\n\n__author__ = 'rf9'\n\nDIRECTORY_NAME = \"backfill2\"\nFILE_DIR = os.path.dirname(os.path.realpath(__file__))\nCONCENTRATION = \"WTSI Library Concentration\"\nMOLARITY = \"WTSI Library Molarity\"\nFIELD = \"{http://genologics.com/ri/userdefined}field\"\nCONCENTRATION_COLUMN_HEADER = 'Total Conc. (ng/ul)'\nMOLARITY_COLUMN_HEADER = 'Region[200-700] Molarity (nmol/l)'\n\n\ndef get_rows(file):\n headers = [header.strip() for header in next(file).split(',')]\n for line in file:\n yield {header: cell.strip() for (header, cell) in zip(headers, line.split(',')) if cell.strip()}\n\n\ndef change_xml(xml, field_name, value):\n for field in sample_xml.findall(FIELD):\n if field.get(\"name\") == field_name:\n field.text = value\n break\n else:\n builder = ElementTree.TreeBuilder()\n builder.start(FIELD, {\n \"type\": \"String\",\n \"name\": field_name\n })\n element = builder.close()\n element.text = value\n\n xml.append(element)\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 2:\n root_url = sys.argv[1]\n else:\n sys.stderr.write(\"usage: python backfill_caliper.py \\n\")\n sys.exit(1)\n\n clarity = Clarity(root_url)\n\n for (directory, subdirectories, filenames) in os.walk(os.path.join(FILE_DIR, DIRECTORY_NAME)):\n for filename in filenames:\n signature = filename.split(\"_\")[1]\n signature = signature.replace('+', '%2B').replace('l', '%2F')\n\n molarities = {}\n concentrations = {}\n for row in get_rows(open(os.path.join(directory, filename))):\n well = row['Sample Name'].split(\"_\")[0]\n\n if MOLARITY_COLUMN_HEADER in row:\n molarity = float(row[MOLARITY_COLUMN_HEADER]) * 5\n\n if well not in molarities:\n molarities[well] = molarity\n else:\n molarities[well] = (molarities[well] + molarity) / 2\n\n if CONCENTRATION_COLUMN_HEADER in row:\n concentration = float(row[CONCENTRATION_COLUMN_HEADER]) * 5\n\n if well not in concentrations:\n concentrations[well] = concentration\n else:\n concentrations[well] = (concentrations[well] + concentration) / 2\n\n search_xml = clarity.get_xml(clarity.root + \"containers?udf.WTSI%20Container%20Signature=\" + signature)\n container_uri = search_xml.find(\"container\").get('uri')\n\n container_xml = clarity.get_xml(container_uri)\n placement_uris = {placement.get('uri') for placement in container_xml.findall('placement')}\n artifact_xmls = clarity.get_xml(placement_uris)\n sample_uris = {artifact.find('sample').get('uri') for artifact in artifact_xmls}\n sample_xmls = clarity.get_xml(sample_uris)\n\n post_xmls = []\n\n for placement_uri in placement_uris:\n artifact_xml = \\\n [artifact for artifact in artifact_xmls if artifact.get('uri').startswith(placement_uri)][0]\n sample_uri = artifact_xml.find('sample').get('uri')\n sample_xml = [sample for sample in sample_xmls if sample.get('uri') == sample_uri][0]\n\n well = artifact_xml.find('location').find('value').text.replace(':', '')\n\n molarity = str(molarities[well])\n change_xml(sample_xml, MOLARITY, molarity)\n\n concentration = str(concentrations[well])\n change_xml(sample_xml, CONCENTRATION, concentration)\n\n post_xmls.append(sample_xml)\n\n clarity.batch_post_xml('samples', post_xmls)\n","sub_path":"src/python/backfill_caliper.py","file_name":"backfill_caliper.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"291996478","text":"#happy product\ni=True\nwhile i:\n choice=input(\"Menu:\\n(I)nstructions\\n(C)alculate\\n(Q)uit\")\n if choice=='I':\n print(\"Enter the number of products you want to buy and your chosen price\")\n choice2=input(\"Menu:\\n(I)nstructions\\n(C)alculate\\n(Q)uit\")\n\n j=True\n while j:\n if choice2==\"C\":\n number=int(input(\"number of product :\"))\n price=int(input(\"price of product \"))\n if 0 Preparing data (cifar10)')\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n \n trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True, num_workers=2)\n\n\n testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)\n testloader = torch.utils.data.DataLoader(testset, batch_size=args.batch_size, shuffle=False, num_workers=2)\n\n\n #classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n # Model\n print('==> Building quantized model ResNet18 for cifar10')\n net = resnet18(pretrained = True, pretrained_checkpoint=args.pretrained_checkpoint, num_classes=10, quantize = True)\n net = net.to(device)\n \n if device == 'cuda':\n # net = torch.nn.DataParallel(net)\n cudnn.benchmark = True\n print('==> using cuda')\n \n criterion = nn.CrossEntropyLoss()\n\n if args.optimizer == 'SGD':\n optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=args.weight_decay)\n elif args.optimizer == 'Adadelta':\n optimizer = optim.Adadelta(net.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n elif args.optimizer == 'Adagrad':\n optimizer = optim.Adagrad(net.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n elif args.optimizer == 'Adam':\n optimizer = optim.Adam(net.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n elif args.optimizer == 'Adamax':\n optimizer = optim.Adam(net.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n else:\n print('Unknown optimizer')\n\n scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer,T_0=20)\n\n# Training\ndef train(epoch, batches=-1):\n global trainloader\n global testloader\n global net\n global criterion\n global optimizer\n global scheduler\n\n print('\\nEpoch: %d' % epoch)\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer.zero_grad()\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n acc = 100.*correct/total\n\n # progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n # % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\n if batches > 0 and (batch_idx+1) >= batches:\n return\n scheduler.step(epoch)\n\n\ndef test(save_checkpoint):\n global best_acc\n global testloader\n global net\n global criterion\n\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n acc = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n acc = 100.*correct/total\n\n# progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)' % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n \n # Save checkpoint.\n if acc > best_acc:\n best_acc = acc\n \n if not os.path.isdir('checkpoint'):\n os.mkdir('checkpoint')\n\n print('Saving the quantized network using jit')\n net=net.cpu()\n net.eval()\n net_int8 = torch.quantization.convert(net)\n\n example_forward_input = torch.rand(1, 3, 32, 32)\n example_forward_input=example_forward_input.cpu()\n\n net_trace = torch.jit.trace(net_int8,example_forward_input)\n torch.jit.save(net_trace,save_checkpoint)\n net=net.to(device)\n \n return acc, best_acc\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--epochs\", type=int, default=200)\n\n # Maximum mini-batches per epoch, for code testing purpose\n parser.add_argument(\"--batches\", type=int, default=-1)\n \n # Maximum mini-batches per epoch, for code testing purpose\n parser.add_argument('--batch_size', type=int, default=256)\n \n # Optimizer\n parser.add_argument('--optimizer', default='SGD')\n \n # Learning rate\n parser.add_argument('--lr', type=float, default=0.1)\n \n # Weight decay\n parser.add_argument('--weight_decay', type=float, default=0.00000001)\n \n # Checkpoint file\n parser.add_argument('--pretrained_checkpoint', default='./checkpoint/resnet18-cifar10-fp.pth')\n\n # Checkpoint file\n parser.add_argument('--save_checkpoint', default='./checkpoint/resnet18-cifar10-int8.pth')\n\n args, _ = parser.parse_known_args()\n \n try:\n\n _logger.debug(args)\n \n prepare(args)\n acc = test(args.save_checkpoint)\n best_acc = 0.0\n print('Initial accuracy: ',acc)\n for epoch in range(start_epoch, start_epoch+args.epochs):\n train(epoch, args.batches)\n acc, best_acc = test(args.save_checkpoint)\n print(acc,best_acc)\n \n except Exception as exception:\n _logger.exception(exception)\n raise\n","sub_path":"loadPretrainedFPQuantizeAndTrain.py","file_name":"loadPretrainedFPQuantizeAndTrain.py","file_ext":"py","file_size_in_byte":7060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"162918159","text":"# LineLoader.py\n#\n# Waits until there is a stack of PCB's at its input\n# then picks up one PCB at a time from the stack \n# and places it on the conveyor belt.\n#\n# parameters: \n# delay: time (in seconds) required to push a single PCB from the stack onto the conveyor belt\n# \n# Author: Neha Karanjkar\n\nimport random,simpy,math\nfrom BaseOperator import BaseOperator\n\nclass LineLoader(BaseOperator):\n \n def __init__(self, env, name, inp, outp):\n BaseOperator.__init__(self,env,name)\n self.inp=inp\n self.outp=outp\n self.delay=1\n \n #states\n self.define_states(states=[\"idle\",\"loading\"],start_state=\"idle\")\n self.process=env.process(self.behavior())\n\n \n def behavior(self):\n assert( isinstance(self.delay,int))\n assert( isinstance(self.start_time,int))\n assert(self.delay>=1)\n \n #wait until the start time \n yield (self.env.timeout(self.start_time))\n\n while True:\n #wait until there's a stack of PCBs at the input\n pcb_stack=None\n while(not pcb_stack):\n if self.inp.can_get():\n pcb_stack = self.inp.get_copy()\n break\n else:\n yield (self.env.timeout(1))\n \n #got a stack.\n print(\"T=\",self.env.now+0.0,self.name,\"started unloading stack\")\n\n while (len(pcb_stack)!=0):\n \n #pick up a PCB from the stack in First-In-First-Out order:\n pcb = pcb_stack.pop(0)\n\n # wait until there's place at the output\n while not self.outp.can_put():\n yield (self.env.timeout(1))\n \n #change state\n self.change_state(\"loading\")\n\n # wait for an integer amount of delay\n yield (self.env.timeout(self.delay-1.0))\n yield (self.env.timeout(0.5))\n\n #place the PCB at the output\n yield self.outp.put(pcb)\n print(\"T=\",self.env.now+0.0,self.name,\"placed\",pcb,\"on\",self.outp)\n yield (self.env.timeout(0.5))\n \n #change state\n self.change_state(\"idle\")\n \n # Now remove the empty tray from the inp\n # so that the next job can arrive.\n s = yield self.inp.get()\n\n","sub_path":"model_2/LineLoader.py","file_name":"LineLoader.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"496229369","text":"\"\"\"\nTwo words are anagrams if you can rearrange the letters of one to spell the second. \nFor example, the following words are anagrams:\n\n ['abets', 'baste', 'bates', 'beast', 'beats', 'betas', 'tabes']\n\nHint: How can you tell quickly if two words are anagrams? \nDictionaries allow you to find a key quickly. \n\n\"\"\"\n\n\nstr1=input(\"Enter first string\")\nstr2=input(\"Enter second string\")\ncount=0\n\nif len(str1)==len(str2):\n for i in str1:\n if i in str2:\n count=count+1\n continue\n else:\n print(\"not panagrma\")\n \n if count==len(str1):\n print(\"True\")\n \nelse:\n print(\"False\")\n \n ","sub_path":"DAY3/anagrams.py","file_name":"anagrams.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"280023251","text":"MONTH = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12}\n\n\n#genrator that yields dictionaries\n#D = {'name':string, 'date':list of ints [day,month,year],'show':string}\ndef parser1():\n\n DATE_B = 27\n DATE_E = 37\n\n GUESTS_B = 39\n\n filenames = ['Jimmy_Kimmel_Live.txt',\n 'Late_Night_with_Jimmy_Fallon.txt',\n 'conan_from_2014.txt',\n 'Late_Night_with_Seth_Meyers.txt',\n 'The_Daily_Show_with_Trevor_Noah.txt',\n 'The_Ellen_DeGeneres_Show.txt',\n 'The_Late_Late_Show_with_James_Corden.txt']\n\n\n show_names = ['Jimmy Kimmel Live',\n 'Late Night with Jimmy Fallon',\n 'Conan',\n 'Late Night with Seth Meyers',\n 'The Daily Show with Trevor Noah',\n 'The Ellen DeGeneres Show',\n 'The Late Late Show with James Corden']\n\n for i in range(len(filenames)):\n\n data = open(filenames[i])\n show_name = show_names[i]\n #skip first lines in the files (show names and columns types)\n for k in range(4):\n line = data.readline()\n while line != None:\n\n #stop at the last line\n if len(line) == 0:\n break\n\n date = line[DATE_B:DATE_E]\n date = date.split()\n date = [int(date[0]), MONTH[date[1]], int(date[2]) + 2000]\n\n guests = line[GUESTS_B : -1]\n guests = guests.lower()\n guests = guests.split(',')\n for i in range(len(guests)):\n\n #clear backspaces before and after the name\n guests[i] = guests[i].strip()\n\n #remove nicknames\n nick_left = guests[i].find('\"')\n nick_right = guests[i].rfind('\"')\n if nick_left != -1 and nick_right != -1:\n guests[i] = guests[i].replace(guests[i][nick_left:nick_right+1],'')\n\n for guest in guests:\n guest_app = {'name':guest, 'date':date, 'show':show_name}\n yield guest_app\n\n line = data.readline()\n\n","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"567684317","text":"import sys\nimport re\n\n# diacritics = FATHATAN, DAMMATAN, KASRATAN, FATHA, DAMMA, KASRA, SHADDA, SUKUN, TATWEEL, DAGGER ALIF\ndiac_utf8 = re.compile(\"[\\u064b\\u064c\\u064d\\u064e\\u064f\\u0650\\u0651\\u0652\\u0640\\u0670]\")\ndiac_bw = re.compile(\"[aiuo~`FKN_]\")\ndiac_sbw = re.compile(\"[aiuoXeFKN_]\")\ndiac_hsb = re.compile(\"[aiu.~áãũĩ_]\")\n\nrewrite_rules_re1 = re.compile(r'^((wa|fa)?(bi|ka)?Al)\\+([tvd*rzs$SDTZln])')\nrewrite_rules_re2 = re.compile(r'^((wa|fa)?lil)\\+([tvd*rzs$SDTZln])')\nrewrite_rules_re3 = re.compile(r'A\\+a([pt])')\nrewrite_rules_re4 = re.compile(r'{')\nrewrite_rules_re5 = re.compile(r'\\+')\n\nrewrite_rules_caphi_re1 = re.compile(r'^((w_a_|f_a_|2_a_)?(b_i_|k_a_|l_i_)?l)\\+(t_|th_|d_|th._|r_|z_|s_|sh_|s\\._|d\\._|t\\._|dh\\._|l_|n_|)')\nrewrite_rules_caphi_re2 = re.compile(r'(\\S)\\+~')\nrewrite_rules_caphi_re3 = re.compile(r'\\+')\nrewrite_rules_caphi_re4 = re.compile(r'(^_|_$)')\n\nsplit_lemma = re.compile('([_-])')\n\nBW_tag_re1 = re.compile('(.*)\\/(.*)')\nBW_tag_re2 = re.compile('CONJ|CONNEC\\_PART|DEM\\_PRON|DET|EMPHATIC\\_PART|FUT\\_PART|PROG\\_PART|INTERROG\\_PART|JUS\\_'\n 'PART|NEG\\_PART|PART|PREP|PSEUDO\\_VERB|RC\\_PART|REL\\_PRON|SUB\\_CONJ|VOC\\_PART|'\n '[PIC]VSUFF\\_DO:|POSS\\_PRON\\_|PRON\\_[123][MF]?[SDP]|NEG\\_PART|REL\\_PRON|SUB\\_CONJ|'\n 'VOC\\_PART|INTERROG\\_PRON|PREP$/')\nBW_tag_re3 = re.compile('.*\\/')\nBW_tag_re4 = re.compile('^\\+')\nBW_tag_re5 = re.compile('\\+$')\n\ndef encode(input_enc, output_enc, word):\n\n if input_enc == output_enc:\n return word\n\n encoding_values = ['utf8', 'bw', 'sbw', 'hsb']\n mode = input_enc + '_' + output_enc\n\n utf8 = u'\\u0621\\u0622\\u0623\\u0624\\u0625\\u0626\\u0627\\u0628\\u0629\\u062A\\u062B\\u062C\\u062D\\u062E\\u062F\\u0630\\u0631\\u0632\\u0633\\u0634\\u0635\\u0636\\u0637\\u0638\\u0639\\u063A\\u0640\\u0641\\u0642\\u0643\\u0644\\u0645\\u0646\\u0647\\u0648\\u0649\\u064A\\u064B\\u064C\\u064D\\u064E\\u064F\\u0650\\u0651\\u0652\\u0670\\u0671'\n bw = \"'|>&<}AbptvjHxd*rzs$SDTZEg_fqklmnhwYyFNKaui~o`{\"\n sbw = \"CMOWIQAbptvjHxdVrzscSDTZEg_fqklmnhwYyFNKauiXoeL\"\n hsb = \"'ĀÂŵӐŷAbħtθjHxdðrzsšSDTĎςɣ_fqklmnhwýyãũĩaui~.áÄ\"\n arabtex = [\"'\", \"'A\", \"'\", \"U'\", \"'i\", \"'i\", 'A', 'b', 'T', 't', '_t', 'j', '.h', 'x', 'd', '_d', 'r',\n 'z', 's', '^s', '.s', '.d', '.t', '.z', '`', '.g', '--', 'f', 'q', 'k', 'l', 'm', 'n', 'h', 'w',\n 'Y', 'y', 'aN', 'uN', 'iN', 'a', 'u', 'i', 'xx', '\"', '_a', '\"']\n\n if mode == 'utf8_bw':\n utf8_bw = str.maketrans(utf8, bw)\n return word.translate(utf8_bw)\n elif mode == 'utf8_sbw':\n utf8_sbw = str.maketrans(utf8, sbw)\n return word.translate(utf8_sbw)\n elif mode == 'utf8_hsb':\n utf8_hsb = str.maketrans(utf8, hsb)\n return word.translate(utf8_hsb)\n elif mode == 'bw_utf8':\n bw_utf8 = str.maketrans(bw, utf8)\n return word.translate(bw_utf8)\n elif mode == 'bw_sbw':\n bw_sbw = str.maketrans(bw, sbw)\n return word.translate(bw_sbw)\n elif mode == 'bw_hsb':\n bw_hsb = str.maketrans(bw, hsb)\n return word.translate(bw_hsb)\n elif mode == 'sbw_utf8':\n sbw_utf8 = str.maketrans(sbw, utf8)\n return word.translate(sbw_utf8)\n elif mode == 'sbw_bw':\n sbw_bw = str.maketrans(sbw, bw)\n return word.translate(sbw_bw)\n elif mode == 'sbw_hsb':\n sbw_hsb = str.maketrans(sbw, hsb)\n return word.translate(sbw_hsb)\n elif mode == 'hsb_utf8':\n hsb_utf8 = str.maketrans(hsb, utf8)\n return word.translate(hsb_utf8)\n elif mode == 'hsb_bw':\n hsb_bw = str.maketrans(hsb, bw)\n return word.translate(hsb_bw)\n elif mode == 'hsb_sbw':\n hsb_sbw = str.maketrans(hsb, sbw)\n return word.translate(hsb_sbw)\n\n elif mode == 'utf8_arabtex':\n utf8_list = list(utf8)\n char_list = list(word)\n output = ''\n for char in char_list:\n if char in utf8_list:\n if arabtex[utf8_list.index(char)] == 'xx':\n output = output + output[-1]\n else:\n output = output + arabtex[utf8_list.index(char)]\n else:\n output = output + char\n return output\n elif mode == 'bw_arabtex':\n bw_list = list(bw)\n char_list = list(word)\n output = ''\n for char in char_list:\n if char in bw_list:\n if arabtex[bw_list.index(char)] == 'xx':\n output = output + output[-1]\n else:\n output = output + arabtex[bw_list.index(char)]\n else:\n output = output + char\n return output\n elif mode == 'sbw_arabtex':\n sbw_list = list(sbw)\n char_list = list(word)\n output = ''\n for char in char_list:\n if char in sbw_list:\n if arabtex[sbw_list.index(char)] == 'xx':\n output = output + output[-1]\n else:\n output = output + arabtex[sbw_list.index(char)]\n else:\n output = output + char\n return output\n elif mode == 'hsb_arabtex':\n hsb_list = list(hsb)\n char_list = list(word)\n output = ''\n for char in char_list:\n if char in hsb_list:\n if arabtex[hsb_list.index(char)] == 'xx':\n output = output + output[-1]\n else:\n output = output + arabtex[hsb_list.index(char)]\n else:\n output = output + char\n return output\n else:\n if input_enc not in encoding_values:\n print('Input encoding ' + input_enc + ' is not valid.')\n if output_enc not in encoding_values and output_enc != 'arabtex':\n print('Output encoding ' + output_enc + ' is not valid.')\n sys.exit(2)\n\n\ndef encode_file(input_enc, output_enc, input_file):\n try:\n text_file = open(input_file, 'r').read()\n out_text = open(input_file + '.' + output_enc, 'w')\n out_text.write(encode(input_enc, output_enc, text_file))\n out_text.close()\n except IOError as err:\n print(\"File cannot be opened!\")\n sys.exit(2)\n\n\n# apply different rewrite rules on words including:\n# the addition of $dp after sun letters\n# removing of ftHp after Alf followed with the suffix tA or tA mrbwTp\n# changing non-hamzated starting Alf to Alf hmzp wSl\n# removing pluses\n# adding ftHp before Alf and Alf mqSwrY\n# modifying the orthography of tnwyn ftH before or after Alf\ndef rewrite_rules(word):\n word = rewrite_rules_re1.sub(r'\\1\\4~', word)\n word = rewrite_rules_re2.sub(r'\\1\\3~', word)\n word = rewrite_rules_re3.sub(r'A\\1', word)\n word = rewrite_rules_re4.sub(r'A', word)\n word = rewrite_rules_re5.sub(r'', word)\n\n return word\n\n\ndef rewrite_rules_caphi(word):\n word = rewrite_rules_caphi_re1.sub(r'\\2\\3\\4\\4', word)\n word = rewrite_rules_caphi_re2.sub(r'\\1_\\1', word)\n word = rewrite_rules_caphi_re3.sub(r'_', word)\n word = rewrite_rules_caphi_re4.sub('', word)\n\n return word\n\n# return a string with all the features in feature_order list, ordered, and separated by spaces\ndef printer(analysis, output_encoding, feature_order, tokenization):\n output_string = ''\n\n if 'diac' in analysis:\n analysis['diac'] = encode('bw', output_encoding, analysis['diac'])\n if 'stem' in analysis:\n analysis['stem'] = encode('bw', output_encoding, analysis['stem'])\n if 'lex' in analysis:\n lemma_toks = split_lemma.split(analysis['lex'])\n lemma_stripped = encode('bw', output_encoding, lemma_toks[0].rstrip())\n analysis['lex'] = lemma_stripped + ''.join(lemma_toks[1:])\n\n if 'bw' in analysis:\n bw_encoded = ''\n bw_toks = analysis['bw'].split('+')\n bw_tok = bw_toks[0]\n if not bw_tok:\n pass\n else:\n morpheme = encode('bw', output_encoding, bw_tok.split('/')[0])\n bw = bw_tok.split('/')[1]\n bw_encoded = morpheme + '/' + bw\n\n\n for bw_tok in bw_toks[1:]:\n if not bw_tok:\n pass\n else:\n morpheme = encode('bw', output_encoding, bw_tok.split('/')[0])\n bw = bw_tok.split('/')[1]\n\n bw_encoded = bw_encoded + '+' + morpheme + '/' + bw\n\n if len(bw_encoded.split(\"+\")) < 3:\n bw_encoded = bw_encoded + \"+\"\n\n analysis['bw'] = bw_encoded\n\n for order in feature_order:\n if order in analysis:\n # todo: test with extended db\n # if (order == 'seg' or order == 'tok') and order in tokenization:\n # for ttype in tokenization[order]:\n # output_string = output_string + order + '_' + ttype + analysis[order + '_' + ttype] + ' '\n # else:\n output_string = output_string + order + \":\" + analysis[order] + \" \"\n\n return output_string.rstrip()\n\ndef get_BW_semi_lex(bw_tag):\n bw_tag = BW_tag_re4.sub('', bw_tag)\n bw_tag = BW_tag_re5.sub('', bw_tag)\n\n semi_tag = bw_tag.split('+')\n\n for i in range(len(semi_tag)):\n\n match = BW_tag_re1.match(semi_tag[i])\n temp = BW_tag_re2.match(match.group(2))\n if temp:\n semi_tag[i] = semi_tag[i]\n else:\n semi_tag[i] = BW_tag_re3.sub('',semi_tag[i])\n\n semi_tag = '+'.join(semi_tag)\n return semi_tag\n\n\n# return the word without the diacritics (aiuo~`FKN_)\ndef dediac(diac_word, encoding):\n if encoding == 'bw':\n return diac_bw.sub(r'', diac_word)\n elif encoding == 'utf8':\n return diac_utf8.sub(r'', diac_word)\n elif encoding == 'safebw':\n return diac_sbw.sub(r'', diac_word)\n elif encoding == 'hsb':\n return diac_hsb.sub(r'', diac_word)\n\ndef gen_normalize_re(normalization):\n normalization_re = {}\n for char in normalization:\n normalization_re[char] = re.compile(re.escape(char))\n return normalization_re\n\ndef normalize(match_word, normalization, norm_re):\n for char in normalization:\n # orig = re.compile(re.escape(char))\n match_word = norm_re[char].sub(normalization[char], match_word)\n return match_word\n\n\ndef clean_line(input_text):\n processed_line = []\n processed_line.extend(list(filter(None, re.split(r\"(\\.|,|\\'|`|\\\"|!|/|\\\\|\\?|-|\\(|\\)|;|:|،|٫|؟|…|‘|’)\", input_text))))\n return \" \".join(processed_line)\n\n\ndef generate_lmm(lemma, encoding):\n lemma_toks = re.split('([_-])', lemma)\n lemma_stripped = dediac(lemma, encoding)\n lemma = lemma_stripped + ''.join(lemma_toks[1:])\n return lemma\n\n\ndef clean_utf8(map_file, input_file, output_file):\n try:\n map_reader = open(map_file, 'r')\n except IOError as err:\n print(\"MAP file is not found!\")\n sys.exit(2)\n try:\n input_text = open(input_file, 'r').readlines()\n output = open(output_file, 'w')\n except IOError as err:\n print(\"Input file is not found!\")\n sys.exit(2)\n\n # hash the map\n utf8_map = {}\n lines = map_reader.readlines()\n for line in lines:\n line = line.rstrip()\n if not line or line.startswith('#'):\n continue\n else:\n elements = re.split('\\t+', line)\n char = elements[0]\n action = elements[1]\n # comment = elements[2]\n\n if re.search(r'^(u....)$',char) is not None:\n char = char + '-' + char\n if re.search(r'^u(....)-u(....)$', char) is not None:\n start = int(re.search(r'^u(....)-u(....)$', char).group(1), 16)\n end = int(re.search(r'^u(....)-u(....)$', char).group(2), 16)\n if end < start:\n print(\"Error: Wrong range: \" + char + \" start = \" + start + \" end = \" + end)\n sys.exit(2)\n for i in range(start, end+1, 1):\n if action == 'OK':\n print(chr(i) + \"\\t\" + chr(i))\n utf8_map[chr(i)] = chr(i)\n elif action == 'DEL':\n print(chr(i) + \"\\t\" + \"DEL\")\n utf8_map[chr(i)] = ''\n elif action == 'SPC':\n print(chr(i) + \"\\t\" + \"SPC\")\n utf8_map[chr(i)] = ' '\n elif action.startswith('u'):\n value = ''\n uni_chars = action.split('u')\n for uni_char in uni_chars:\n if uni_char:\n value = value + chr(int(uni_char, 16))\n print(chr(i) + \"\\t\" + value)\n utf8_map[chr(i)] = value\n else:\n print(chr(i) + \"\\t\" + action)\n utf8_map[chr(i)] = action\n else:\n if action == 'OK':\n utf8_map[char] = char\n elif action == 'DEL':\n utf8_map[char] = ''\n elif action == 'SPC':\n utf8_map[char] = ' '\n elif action.startswith('u'):\n value = ''\n uni_chars = action.split('u')\n for uni_char in uni_chars:\n value = value + chr(int(uni_char, 16))\n utf8_map[char] = value\n else:\n utf8_map[char] = action\n\n # covfefe\n output_string = ''\n for line in input_text:\n new_line = ''\n for char in line:\n if not isinstance(char, str) and 'INVALID' in utf8_map:\n new_line = new_line + (utf8_map['INVALID'])\n else:\n if char in utf8_map:\n new_line = new_line + (utf8_map[char])\n else:\n if 'ELSE' in utf8_map:\n new_line = new_line + (utf8_map['ELSE'])\n output_string = output_string + new_line.strip() + \"\\n\"\n\n output_string = re.sub(r' +', r' ', output_string)\n output_string = output_string.rstrip()\n output.write(output_string)\n\n output.close()\n\n\nif __name__ == \"__main__\":\n # encode_file('utf8', 'hsb', 'example.txt')\n\n # print(encode('utf8', 'bw', 'يُنْفِقُ الْخَلِيجِيُّونَ أَمْوَالًا طَائِلَةً عَلَى الْعُطُورِ، وَخَاصَّةً الشَّرْقِيَّةَ مِنْهَا الَّتِي تُعَدُّ أَغْلَى عُطُورِ الْعَالَمِ. '))\n # print(encode('utf8', 'arabtex', 'يُنْفِقُ الْخَلِيجِيُّونَ أَمْوَالًا طَائِلَةً عَلَى الْعُطُورِ، وَخَاصَّةً الشَّرْقِيَّةَ مِنْهَا الَّتِي تُعَدُّ أَغْلَى عُطُورِ الْعَالَمِ. '))\n\n # print(dediac('يُنْفِقُ الْخَلِيجِيُّونَ أَمْوَالًا طَائِلَةً عَلَى الْعُطُورِ، وَخَاصَّةً الشَّرْقِيَّةَ مِنْهَا الَّتِي تُعَدُّ أَغْلَى عُطُورِ الْعَالَمِ. ', 'utf8'))\n clean_utf8('clean-utf8-map', 'cleanUtf8.test.txt', 'cleanUtf8.test.txt.cln')\n","sub_path":"web-player-four-avatars/CalimaStarUtils.py","file_name":"CalimaStarUtils.py","file_ext":"py","file_size_in_byte":15163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"110232233","text":"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"This package flattens image metadata into a single tarball.\"\"\"\n\n\n\nimport argparse\nimport logging\nimport tarfile\n\nfrom containerregistry.client.v2_2 import docker_image as v2_2_image\nfrom containerregistry.tools import logging_setup\n\nparser = argparse.ArgumentParser(description='Flatten container images.')\n\n# The name of this flag was chosen for compatibility with docker_pusher.py\nparser.add_argument('--tarball', action='store',\n help='An optional legacy base image tarball.')\n\nparser.add_argument('--config', action='store',\n help='The path to the file storing the image config.')\n\nparser.add_argument('--digest', action='append',\n help='The list of layer digest filenames in order.')\n\nparser.add_argument('--layer', action='append',\n help='The list of layer filenames in order.')\n\n# Output arguments.\nparser.add_argument('--filesystem', action='store',\n help='The name of where to write the filesystem tarball.')\n\nparser.add_argument('--metadata', action='store',\n help=('The name of where to write the container '\n 'startup metadata.'))\n\n_THREADS = 8\n\n\ndef main():\n logging_setup.DefineCommandLineArgs(parser)\n args = parser.parse_args()\n logging_setup.Init(args=args)\n\n if not args.config and (args.layer or args.digest):\n raise Exception(\n 'Using --layer or --digest requires --config to be specified.')\n\n if not args.filesystem or not args.metadata:\n raise Exception(\n '--filesystem and --metadata are required flags.')\n\n if not args.config and not args.tarball:\n raise Exception('Either --config or --tarball must be specified.')\n\n # If config is specified, use that. Otherwise, fall back on reading\n # the config from the tarball.\n if args.config:\n logging.info('Reading config from %r', args.config)\n with open(args.config, 'r') as reader:\n config = reader.read()\n elif args.tarball:\n logging.info('Reading config from tarball %r', args.tarball)\n with v2_2_image.FromTarball(args.tarball) as base:\n config = base.config_file()\n else:\n config = args.config\n\n if len(args.digest or []) != len(args.layer or []):\n raise Exception('--digest and --layer must have matching lengths.')\n\n logging.info('Loading v2.2 image from disk ...')\n with v2_2_image.FromDisk(config, zip(args.digest or [], args.layer or []),\n legacy_base=args.tarball) as v2_2_img:\n with tarfile.open(args.filesystem, 'w') as tar:\n v2_2_image.extract(v2_2_img, tar)\n\n with open(args.metadata, 'w') as f:\n f.write(v2_2_img.config_file())\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/fast_flatten_.py","file_name":"fast_flatten_.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"141827137","text":"# -*-coding:utf8-*-\n\nimport requests\nimport re\nimport time\nimport datetime\nimport pymysql\nfrom bs4 import BeautifulSoup\nimport traceback\nimport json\n\n\ndef get_page_source(url):\n try:\n r = requests.get(url, timeout=30)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n return r.text\n except:\n return \"failed\"\n\n\ndef getViewInfo(url, fpath):\n html = get_page_source(url)\n\n try:\n # soup = BeautifulSoup(html, 'html.parser')\n # viewInfo = soup.find_all('div', attrs={'class': 'online'})[0]\n # viewInfo = soup.find_all('div', attrs={'class':'ebox'})[0]\n # title = viewInfo.p.string\n # print(title)\n\n # numberStr = viewInfo.a.string\n # number = numberStr.split(':')[1]\n # print(number)\n\n # 使用python来解析json\n\n json_data = json.loads(html)\n number = (json_data['data']['web_online'])\n nowTime = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M'))\n # 保存文件\n # with open(fpath, 'a', encoding='utf-8') as f:\n # nowTime = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M'))\n # f.write(nowTime + \" \" + str(number) + '\\n')\n try:\n # Please write your MySQL's information.\n conn = pymysql.connect(\n host='localhost', user='root', passwd='root', db='bilibili', charset='utf8')\n cur = conn.cursor()\n cur.execute('INSERT INTO bilibili_web_online(web_online, time) \\\n VALUES (\"%s\",\"%s\")'\n %\n (number, nowTime))\n conn.commit()\n except Exception as e:\n print(e)\n\n\n except:\n traceback.print_exc()\n\n\ndef main():\n count = 0\n while 1:\n url = \"https://api.bilibili.com/x/web-interface/online\"\n # 文件路径\n output_path = \"F:\\\\PythonWork\\\\bilibili-user-master\\\\bilibiliInfo.txt\"\n\n getViewInfo(url, output_path)\n # 打印进度\n count = count + 1\n print(count)\n # 延时一分钟\n time.sleep(60)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bilibili-user-master/online.py","file_name":"online.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"522606607","text":"#Sean Kim\n#Unit 3\n\ndef loadDict (file_name):\n text_file = open (file_name, \"r\")\n \n myDict = {}\n \n for line in text_file:\n line = line.strip()\n row = line.split(\":\")\n \n \n myDict[row[0]] = row[1].strip()\n \n return myDict\n\n\ndef getNextChoice (keys):\n print (\"What definition would you like? (Enter quit to exit)\")\n for k in keys:\n print (k, end = \" \")\n return input()\n\n\ndef main ():\n \n myd = loadDict(\"definitions.txt\")\n \n keyList = list(myd.keys())\n keyList.sort()\n choice = getNextChoice (keyList)\n \n while choice.lower() != \"quit\":\n definition = myd.get(choice, \"Your choice is not in the dictionary!\")\n print (definition, \"\\n\\n\")\n \n choice = getNextChoice (keyList)\n \n print (\"Goodbye!\")\nmain() ","sub_path":"Python/Unit3/Definition.py","file_name":"Definition.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"8401064","text":"import json, difflib\nfrom difflib import SequenceMatcher\nfrom difflib import get_close_matches\n\ndata=json.load(open('data.json'))\nprint(data)\nprint(data['name'])\n\nscore = SequenceMatcher(None, 'rainn', 'rain').ratio()\nprint(score)\n\nmatch = get_close_matches(\"rainn\", ['python', 'house', 'block', 'rain', 'ghost'])\nprint(match)","sub_path":"json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"164677122","text":"import torch\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\n# Load model\r\ndef load_model(model_path):\r\n print('Loading model...')\r\n model = torch.load(model_path)\r\n return model\r\n\r\n\r\ndef my_DepthNorm(x, maxDepth):\r\n return maxDepth / x\r\n\r\n\r\ndef my_predict(model, images, minDepth=10, maxDepth=1000):\r\n\r\n with torch.no_grad():\r\n # Compute predictions\r\n predictions = model(images)\r\n\r\n # Put in expected range\r\n return np.clip(my_DepthNorm(predictions.numpy(), maxDepth=maxDepth), minDepth, maxDepth) / maxDepth\r\n\r\n\r\n# Input images\r\ndef input_images(image):\r\n pytorch_input = torch.from_numpy(image).permute(2, 0, 1).unsqueeze(0)\r\n print(pytorch_input.shape)\r\n print('\\nLoaded (1) image of size{0}.'.format(image.shape))\r\n return pytorch_input\r\n\r\n\r\n# Compute results\r\ndef compute_results(pytorch_input, model):\r\n output = my_predict(model, pytorch_input[0, :, :, :].unsqueeze(0))\r\n return output[0, 0, :, :]\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n pytorch_model = load_model('torch_model.pkl')\r\n pytorch_model.eval()\r\n x = np.clip(np.asarray(Image.open('./examples/11_image.png'),\r\n dtype=float) / 255, 0, 1).astype('float32')\r\n torch_inp = input_images(x)\r\n depth_img = compute_results(torch_inp, pytorch_model)\r\n plt.imshow(depth_img)\r\n plt.show()\r\n","sub_path":"SANET/depth_info.py","file_name":"depth_info.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6464972","text":"# Copyright (c) 2001-2016, Canal TP and/or its affiliates. All rights reserved.\n#\n# This file is part of Navitia,\n# the software to build cool stuff with public transport.\n#\n# Hope you'll enjoy and contribute to this project,\n# powered by Canal TP (www.canaltp.fr).\n# Help us simplify mobility and open public transport:\n# a non ending quest to the responsive locomotion way of traveling!\n#\n# LICENCE: This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU Affero 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# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n# Stay tuned using\n# twitter @navitia\n# IRC #navitia on freenode\n# https://groups.google.com/d/forum/navitia\n# www.navitia.io\nimport json\nimport os\nimport tempfile\nfrom zipfile import ZipFile\nfrom io import BytesIO\nfrom datetime import datetime\nfrom requests.models import Response\nimport pytest\n\nfrom tartare import app\nfrom tartare.core.constants import (\n DATA_FORMAT_RUSPELL_CONFIG,\n DATA_FORMAT_BANO_FILE,\n DATA_TYPE_GEOGRAPHIC,\n DATA_FORMAT_DIRECTION_CONFIG,\n DATA_FORMAT_TR_PERIMETER,\n DATA_FORMAT_LINES_REFERENTIAL,\n DATA_FORMAT_SANITIZE_CONFIG,\n DATETIME_FORMAT_IS0_8601,\n)\nfrom tartare.core.gridfs_handler import GridFsHandler\nfrom tartare.exceptions import RuntimeException\nfrom tartare.helper import get_dict_from_zip\nfrom tartare.processes.contributor.scrap_piv_stop_referential import get_next_link\nfrom tests.integration.test_mechanism import TartareFixture\nfrom tests.utils import (\n _get_file_fixture_full_path,\n assert_files_equals,\n assert_zip_contains_only_txt_files,\n assert_zip_contains_only_files_with_extensions,\n assert_in_memory_zip_equals_ref_zip_file,\n)\n\n\nclass TestSanitzeGtfsProcess(TartareFixture):\n @staticmethod\n def __contributor_creator(\n data_set_url, data_config_url, contrib_id=\"contrib_id\", data_source_id=\"id2\", data_config_id=\"id3\"\n ):\n contrib_payload = {\n \"id\": contrib_id,\n \"name\": \"name_test\",\n \"data_prefix\": \"AAA\",\n \"data_sources\": [\n {\n \"input\": {\"type\": \"auto\", \"url\": data_set_url, \"frequency\": {\"type\": \"daily\", \"hour_of_day\": 20}},\n \"id\": data_source_id,\n \"name\": \"data_source_to_process_name\",\n \"data_format\": \"gtfs\",\n },\n {\n \"input\": {\n \"type\": \"auto\",\n \"url\": data_config_url,\n \"frequency\": {\"type\": \"daily\", \"hour_of_day\": 20},\n },\n \"id\": data_config_id,\n \"name\": \"data_config_to_process_name\",\n \"data_format\": \"sanitize_config\",\n },\n ],\n \"processes\": [\n {\n \"id\": \"agency_process\",\n \"sequence\": 0,\n \"input_data_source_ids\": [data_source_id],\n \"target_data_source_id\": \"export_id\",\n \"type\": \"SanitizeGTFS\",\n \"configuration_data_sources\": [{\"name\": \"sanitize_config\", \"ids\": [data_config_id]}],\n }\n ],\n }\n return contrib_payload\n\n def test_gtfs_without_agency_file_and_no_agency_id_in_params(self, wiremock_server):\n url = self.format_url(ip=wiremock_server.ip_addr, path=\"agency\", filename=\"gtfs_without_agency_file.zip\")\n url_config = self.format_url(\n ip=wiremock_server.ip_addr, path=\"sanitize_gtfs\", filename=\"sanitize_agency_without_id_config.json\"\n )\n contrib_payload = self.__contributor_creator(url, url_config)\n\n self.post(\"/contributors\", self.dict_to_json(contrib_payload))\n job = self.get_job_from_export_response(self.contributor_export(\"contrib_id\", check_done=False))\n assert job[\"state\"] == \"failed\", print(job)\n assert job[\"error_message\"] == '[process \"agency_process\"] agency_id should be provided', print(job)\n\n def assert_agency_data_equals(self, expected_data):\n data_set = self.get_last_data_set_from_data_source(\"contrib_id\", \"export_id\")\n assert data_set[\"validity_period\"]\n\n with app.app_context():\n new_gridfs_file = GridFsHandler().get_file_from_gridfs(data_set[\"gridfs_id\"])\n with ZipFile(new_gridfs_file, \"r\") as gtfs_zip:\n assert_zip_contains_only_txt_files(gtfs_zip)\n assert gtfs_zip.filename == \"export_id.zip\"\n assert \"agency.txt\" in gtfs_zip.namelist()\n data = get_dict_from_zip(gtfs_zip, \"agency.txt\")\n assert len(data) == 1\n assert len(data[0]) == len(expected_data)\n for key, value in expected_data.items():\n assert value == data[0][key]\n\n def test_gtfs_without_agency_file_but_agency_id_in_params(self, wiremock_server):\n filename = \"gtfs_without_agency_file.zip\"\n url = self.format_url(ip=wiremock_server.ip_addr, path=\"agency\", filename=filename)\n url_config = self.format_url(\n ip=wiremock_server.ip_addr, path=\"sanitize_gtfs\", filename=\"sanitize_agency_id_config.json\"\n )\n contrib_payload = self.__contributor_creator(url, url_config)\n\n self.post(\"/contributors\", json.dumps(contrib_payload))\n self.contributor_export(\"contrib_id\")\n\n self.assert_agency_data_equals(\n {\n \"agency_id\": \"112\",\n \"agency_name\": \"\",\n \"agency_url\": \"https://www.navitia.io/\",\n \"agency_timezone\": \"Europe/Paris\",\n }\n )\n\n @pytest.mark.parametrize(\"agency_file\", [\"gtfs_without_agency_file.zip\", \"gtfs_header_only_in_agency_file.zip\"])\n def test_gtfs_without_or_empty_agency_file(self, wiremock_server, agency_file):\n url = self.format_url(ip=wiremock_server.ip_addr, path=\"agency\", filename=agency_file)\n url_config = self.format_url(\n ip=wiremock_server.ip_addr,\n path=\"sanitize_gtfs\",\n filename=\"sanitize_without_or_empty_agency_file_config.json\",\n )\n contrib_payload = self.__contributor_creator(url, url_config)\n\n self.post(\"/contributors\", json.dumps(contrib_payload))\n self.contributor_export(\"contrib_id\")\n\n self.assert_agency_data_equals(\n {\n \"agency_id\": \"112\",\n \"agency_name\": \"stif\",\n \"agency_url\": \"https://www.navitia.io/\",\n \"agency_timezone\": \"Europe/Paris\",\n \"agency_email\": \"agency@email.com\",\n \"agency_phone\": \"0612345678\",\n }\n )\n\n def test_gtfs_with_agency_file_and_two_agencies(self, wiremock_server):\n url = self.format_url(ip=wiremock_server.ip_addr, path=\"agency\", filename=\"gtfs_with_two_agencies.zip\")\n url_config = self.format_url(\n ip=wiremock_server.ip_addr, path=\"sanitize_gtfs\", filename=\"sanitize_agency_id_config.json\"\n )\n contrib_payload = self.__contributor_creator(url, url_config)\n\n self.post(\"/contributors\", json.dumps(contrib_payload))\n job = self.get_job_from_export_response(self.contributor_export(\"contrib_id\", check_done=False))\n assert job[\"state\"] == \"failed\", print(job)\n assert (\n job[\"error_message\"] == '[process \"agency_process\"] agency.txt should not have more than 1 agency'\n ), print(job)\n\n def test_gtfs_with_agency_file_but_no_agency_id_in_file(self, wiremock_server):\n filename = \"gtfs_with_no_agency_id.zip\"\n url = self.format_url(ip=wiremock_server.ip_addr, path=\"agency\", filename=filename)\n url_config = self.format_url(\n ip=wiremock_server.ip_addr,\n path=\"sanitize_gtfs\",\n filename=\"sanitize_agency_file_but_no_agency_id_in_file.json\",\n )\n\n contrib_payload = self.__contributor_creator(url, url_config)\n\n self.post(\"/contributors\", json.dumps(contrib_payload))\n job = self.contributor_export(\"contrib_id\")\n assert job[\"state\"] == \"done\", print(job)\n\n self.assert_agency_data_equals(\n {\n \"agency_id\": \"112\",\n \"agency_name\": \"AEROCAR\",\n \"agency_url\": \"http://an.url.com\",\n \"agency_timezone\": \"Europe/Madrid\",\n \"agency_email\": \"agency@email.com\",\n }\n )\n\n\nclass TestComputeDirectionsProcess(TartareFixture):\n #\n # Test that:\n # - direction_id not filled and present in config file are filled with corresponding values\n # - missing direction_id column case is handled\n # - if rows in stop_times.txt are not sorted by stop_sequence for each trip_id, the case is handled\n # - if trips line is not present in config file, old direction_id values are kept\n # - 0 is normal direction and 1 is reverse\n # - if not enough stops found to determine direction_id from config and stop_times, nothing is done\n #\n @pytest.mark.parametrize(\n \"data_set_filename, expected_trips_file_name\",\n [\n # stop_sequence not in order\n (\"unsorted_stop_sequences.zip\", \"compute_directions/expected_trips.txt\"),\n # missing column, stop_sequence in order\n (\"missing_column.zip\", \"compute_directions/expected_trips_missing_column.txt\"),\n ],\n )\n def test_compute_directions(self, wiremock_server, data_set_filename, expected_trips_file_name):\n self.init_contributor(\n \"cid\", \"dsid\", self.format_url(wiremock_server.ip_addr, data_set_filename, path=\"compute_directions\")\n )\n self.add_data_source_to_contributor(\n \"cid\",\n \"config_ds_id\",\n self.format_url(wiremock_server.ip_addr, \"config.json\", path=\"compute_directions\"),\n DATA_FORMAT_DIRECTION_CONFIG,\n )\n self.add_process_to_contributor(\n {\n \"type\": \"ComputeDirections\",\n \"input_data_source_ids\": [\"dsid\"],\n \"target_data_source_id\": \"export_id\",\n \"configuration_data_sources\": [{\"name\": \"directions\", \"ids\": [\"config_ds_id\"]}],\n \"sequence\": 0,\n },\n \"cid\",\n )\n self.contributor_export(\"cid\")\n\n original_gridfs_id = self.get_gridfs_id_from_data_source(\"cid\", \"dsid\")\n resp = self.get(\"/files/{}/download\".format(original_gridfs_id), follow_redirects=True)\n assert resp.status_code == 200\n assert_in_memory_zip_equals_ref_zip_file(resp.data, \"compute_directions/\" + data_set_filename)\n\n data_set = self.get_last_data_set_from_data_source(\"cid\", \"export_id\")\n assert data_set[\"validity_period\"]\n with app.app_context():\n new_zip_file = GridFsHandler().get_file_from_gridfs(data_set[\"gridfs_id\"])\n with ZipFile(new_zip_file, \"r\") as new_zip_file:\n with tempfile.TemporaryDirectory() as tmp_dir_name:\n assert_zip_contains_only_txt_files(new_zip_file)\n new_zip_file.extractall(tmp_dir_name)\n assert_files_equals(\n os.path.join(tmp_dir_name, \"trips.txt\"), _get_file_fixture_full_path(expected_trips_file_name)\n )\n\n\nclass TestComputeExternalSettings(TartareFixture):\n def test_prepare_external_settings(self, wiremock_server):\n valid_process = {\n \"type\": \"ComputeExternalSettings\",\n \"input_data_source_ids\": [\"dsid\"],\n \"target_data_source_id\": \"target_id\",\n \"sequence\": 0,\n \"configuration_data_sources\": [\n {\"name\": \"perimeter\", \"ids\": [\"perimeter_id\"]},\n {\"name\": \"lines_referential\", \"ids\": [\"lines_referential_id\"]},\n ],\n }\n self.init_contributor(\n \"cid\",\n \"dsid\",\n self.format_url(wiremock_server.ip_addr, \"fr-idf-custo-post-fusio-sample.zip\", \"prepare_external_settings\"),\n data_prefix=\"OIF\",\n )\n self.add_data_source_to_contributor(\n \"cid\",\n \"perimeter_id\",\n self.format_url(wiremock_server.ip_addr, \"tr_perimeter_id.json\", \"prepare_external_settings\"),\n DATA_FORMAT_TR_PERIMETER,\n )\n self.add_data_source_to_contributor(\n \"cid\",\n \"lines_referential_id\",\n self.format_url(wiremock_server.ip_addr, \"lines_referential_id.json\", \"prepare_external_settings\"),\n DATA_FORMAT_LINES_REFERENTIAL,\n )\n self.add_process_to_contributor(valid_process, \"cid\")\n self.contributor_export(\"cid\")\n target_data_set = self.get_last_data_set_from_data_source(\"cid\", \"target_id\")\n assert target_data_set[\"validity_period\"]\n\n with app.app_context():\n fusio_settings_zip_file = GridFsHandler().get_file_from_gridfs(target_data_set[\"gridfs_id\"])\n with ZipFile(fusio_settings_zip_file, \"r\") as fusio_settings_zip_file:\n with tempfile.TemporaryDirectory() as tmp_dir_name:\n assert_zip_contains_only_files_with_extensions(fusio_settings_zip_file, [\"txt\"])\n fusio_settings_zip_file.extractall(tmp_dir_name)\n assert_files_equals(\n os.path.join(tmp_dir_name, \"fusio_object_codes.txt\"),\n _get_file_fixture_full_path(\"prepare_external_settings/expected_fusio_object_codes.txt\"),\n )\n assert_files_equals(\n os.path.join(tmp_dir_name, \"fusio_object_properties.txt\"),\n _get_file_fixture_full_path(\"prepare_external_settings/expected_fusio_object_properties.txt\"),\n )\n\n\nclass TestHeadsignShortNameProcess(TartareFixture):\n def __contributor_creator(self, data_set_url, data_source_id=\"id2\"):\n contrib_payload = {\n \"id\": \"id_test\",\n \"name\": \"name_test\",\n \"data_prefix\": \"AAA\",\n \"data_sources\": [\n {\n \"input\": {\"type\": \"auto\", \"url\": data_set_url, \"frequency\": {\"type\": \"daily\", \"hour_of_day\": 20}},\n \"id\": data_source_id,\n \"name\": \"data_source_to_process_name\",\n \"data_format\": \"gtfs\",\n }\n ],\n \"processes\": [\n {\n \"id\": \"headsign_short_name\",\n \"sequence\": 0,\n \"input_data_source_ids\": [data_source_id],\n \"target_data_source_id\": \"export_id\",\n \"type\": \"HeadsignShortName\",\n }\n ],\n }\n\n raw = self.post(\"/contributors\", json.dumps(contrib_payload))\n self.assert_sucessful_create(raw)\n\n resp = self.contributor_export(\"id_test\", check_done=False)\n return self.get_job_from_export_response(resp)\n\n def test_expected_files(self, wiremock_server):\n contributor = self.init_contributor(\"cid\", \"dsid\", self.format_url(wiremock_server.ip_addr, \"minimal_gtfs.zip\"))\n contributor[\"processes\"].append(\n {\"id\": \"plop\", \"sequence\": 0, \"input_data_source_ids\": [\"dsid\"], \"type\": \"HeadsignShortName\"}\n )\n self.put(\"/contributors/cid\", self.dict_to_json(contributor))\n resp = self.contributor_export(\"cid\", check_done=False)\n job = self.get_job_from_export_response(resp)\n assert job[\"state\"] == \"failed\"\n assert job[\"error_message\"] == \"data source dsid does not contains required files routes.txt, trips.txt\"\n\n def test_headsign_short_name(self, wiremock_server):\n url = self.format_url(\n ip=wiremock_server.ip_addr, path=\"headsign_short_name\", filename=\"headsign_short_name.zip\"\n )\n job = self.__contributor_creator(url)\n\n assert job[\"state\"] == \"done\"\n assert job[\"step\"] == \"save_contributor_export\"\n assert job[\"error_message\"] == \"\"\n\n original_gridfs_id = self.get_gridfs_id_from_data_source(\"id_test\", \"id2\")\n resp = self.get(\"/files/{}/download\".format(original_gridfs_id), follow_redirects=True)\n assert resp.status_code == 200\n assert_in_memory_zip_equals_ref_zip_file(resp.data, \"headsign_short_name/headsign_short_name.zip\")\n\n with app.app_context():\n data_set = self.get_last_data_set_from_data_source(\"id_test\", \"export_id\")\n assert data_set[\"validity_period\"]\n new_zip_file = GridFsHandler().get_file_from_gridfs(data_set[\"gridfs_id\"])\n with ZipFile(new_zip_file, \"r\") as new_zip_file:\n with tempfile.TemporaryDirectory() as tmp_dir_name:\n assert_zip_contains_only_txt_files(new_zip_file)\n new_zip_file.extractall(tmp_dir_name)\n assert_files_equals(\n os.path.join(tmp_dir_name, \"trips.txt\"),\n _get_file_fixture_full_path(\"headsign_short_name/ref_trips.txt\"),\n )\n\n def test_headsign_short_name_missing_column(self, wiremock_server):\n url = self.format_url(\n ip=wiremock_server.ip_addr,\n path=\"headsign_short_name\",\n filename=\"headsign_short_name_without_trip_short_name.zip\",\n )\n job = self.__contributor_creator(url)\n\n assert job[\"state\"] == \"failed\"\n assert (\n job[\"error_message\"]\n == '[process \"headsign_short_name\"] error in file \"trips.txt\": column \"trip_short_name\" missing'\n )\n\n\nclass TestRuspellGtfsProcess(TartareFixture):\n def test_ruspell_error_message_contributor_geographic_not_exported(self, wiremock_server):\n url_gtfs = self.format_url(ip=wiremock_server.ip_addr, filename=\"gtfs.zip\", path=\"ruspell\")\n\n url_ruspell_config = self.format_url(ip=wiremock_server.ip_addr, filename=\"config-fr_idf.yml\", path=\"ruspell\")\n url_bano = self.format_url(ip=wiremock_server.ip_addr, filename=\"bano-75.csv\", path=\"ruspell\")\n self.init_contributor(\"cid\", \"dsid\", url_gtfs)\n self.add_data_source_to_contributor(\"cid\", \"ruspell_config_ds\", url_ruspell_config, DATA_FORMAT_RUSPELL_CONFIG)\n self.init_contributor(\"geo\", \"bano_75\", url_bano, DATA_FORMAT_BANO_FILE, data_type=DATA_TYPE_GEOGRAPHIC)\n self.add_process_to_contributor(\n {\n \"type\": \"RuspellGtfs\",\n \"input_data_source_ids\": [\"dsid\"],\n \"sequence\": 0,\n \"configuration_data_sources\": [\n {\"name\": \"ruspell_config\", \"ids\": [\"ruspell_config_ds\"]},\n {\"name\": \"geographic_data\", \"ids\": [\"bano_75\"]},\n ],\n },\n \"cid\",\n )\n resp = self.contributor_export(\"cid\", check_done=False)\n job = self.get_job_from_export_response(resp)\n assert job[\"state\"] == \"failed\"\n assert job[\"error_message\"] == \"data source 'bano_75' has no data sets\"\n\n\nclass TestMultiProcess(TartareFixture):\n def test_contributor_export_compute_directions_and_agency(self, wiremock_server):\n self.init_contributor(\n \"cid\", \"dsid\", self.format_url(wiremock_server.ip_addr, \"before_compute_directions_and_agency.zip\")\n )\n\n self.add_data_source_to_contributor(\n \"cid\",\n \"config_ds_id\",\n self.format_url(wiremock_server.ip_addr, \"config.json\", path=\"compute_directions\"),\n DATA_FORMAT_DIRECTION_CONFIG,\n )\n self.add_data_source_to_contributor(\n \"cid\",\n \"dcid\",\n self.format_url(\n wiremock_server.ip_addr, \"sanitize_compute_directions_and_agency_config.json\", path=\"sanitize_gtfs\"\n ),\n DATA_FORMAT_SANITIZE_CONFIG,\n )\n self.add_process_to_contributor(\n {\n \"type\": \"ComputeDirections\",\n \"input_data_source_ids\": [\"dsid\"],\n \"configuration_data_sources\": [{\"name\": \"directions\", \"ids\": [\"config_ds_id\"]}],\n \"sequence\": 0,\n },\n \"cid\",\n )\n self.add_process_to_contributor(\n {\n \"type\": \"SanitizeGTFS\",\n \"input_data_source_ids\": [self.get_output_of_process(self.get_contributor(\"cid\"), \"ComputeDirections\")],\n \"configuration_data_sources\": [{\"name\": \"sanitize_config\", \"ids\": [\"dcid\"]}],\n \"target_data_source_id\": \"export_id\",\n \"sequence\": 0,\n },\n \"cid\",\n )\n self.contributor_export(\"cid\")\n\n resp = self.get(\n \"/files/{}/download\".format(self.get_gridfs_id_from_data_source(\"cid\", \"export_id\")), follow_redirects=True\n )\n\n assert resp.status_code == 200\n assert_in_memory_zip_equals_ref_zip_file(resp.data, \"gtfs/after_compute_directions_and_agency.zip\")\n\n\nclass TestScrapPivCirculationsProcess(TartareFixture):\n def test_scrap_piv(self, wiremock_server):\n url_gtfs = self.format_url(ip=wiremock_server.ip_addr, filename=\"gtfs.zip\", path=\"ruspell\")\n url_piv = self.format_url(ip=wiremock_server.ip_addr, path=\"\")\n\n self.init_contributor(\"cid\", \"dsid\", url_gtfs)\n self.add_process_to_contributor(\n {\n \"type\": \"ScrapPivCirculations\",\n \"input_data_source_ids\": [],\n \"sequence\": 0,\n \"target_data_source_id\": \"piv\",\n \"parameters\": {\n \"piv_url\": url_piv,\n \"api_key\": \"abcd\",\n \"user\": \"myusername\",\n \"password\": \"1234\",\n \"concurrent_calls\": 2,\n },\n },\n \"cid\",\n )\n current_dt = datetime.strptime(\"2020-09-01T00:00:00Z\", DATETIME_FORMAT_IS0_8601)\n resp = self.contributor_export(\n \"cid\", check_done=False, current_date=current_dt.strftime(DATETIME_FORMAT_IS0_8601)\n )\n job = self.get_job_from_export_response(resp)\n assert job[\"state\"] == \"done\"\n assert job[\"step\"] == \"save_contributor_export\"\n assert job[\"error_message\"] == \"\"\n\n resp = self.get(\n \"/files/{}/download\".format(self.get_gridfs_id_from_data_source(\"cid\", \"piv\")), follow_redirects=True\n )\n assert resp.status_code == 200\n binary_stream = BytesIO()\n binary_stream.write(resp.data)\n mget_zip_file = ZipFile(binary_stream)\n assert len(mget_zip_file.filelist) == 3\n dir_names = [name for name in mget_zip_file.namelist() if name.endswith(\"/\")]\n assert len(dir_names) == 1\n assert dir_names[0].rstrip(\"/\") == current_dt.date().isoformat()\n file_names = [name for name in mget_zip_file.namelist() if not name.endswith(\"/\")]\n assert len(file_names) == 2\n assert file_names[0] == \"current_datetime.txt\"\n assert file_names[1] == \"{}/0.json\".format(current_dt.date().isoformat())\n with mget_zip_file.open(\"current_datetime.txt\", \"r\") as date_file:\n date = date_file.read()\n assert date == b\"2020-09-01T00:00:00Z\"\n\n\nclass TestScrapPivStopReferentialProcess(TartareFixture):\n def test_no_headers_links(self):\n response = Response()\n response.code = \"OK\"\n response.status_code = 200\n response.headers = {\"Content-Type\": \"application/xml\"}\n response._content = b\"\"\n\n with pytest.raises(RuntimeException) as excinfo:\n get_next_link(response)\n assert excinfo.value == \"the response has no header 'links'\"\n\n @pytest.mark.parametrize(\n \"header_link,next\",\n [\n (\"/foo,/bar\", None),\n (\"/first/;first,/next;next,/last;last\", None),\n (';rel=\"first\",;rel=\"last\"', None),\n (';rel=\"first\",;rel=\"prev\",;rel=\"last\"', None),\n (';rel=\"first\",;rel=\"prev\",;rel=\"next\",;rel=\"last\"', \"/next\"),\n (';rel=\"first\",;rel=\"next\",;rel=\"last\"', \"/next\"),\n ],\n )\n def test_get_next_link(self, header_link, next):\n response = Response()\n response.code = \"OK\"\n response.status_code = 200\n response.headers = {\"Content-Type\": \"application/xml\", \"links\": header_link}\n response._content = b\"\"\n\n assert get_next_link(response) == next\n\n def test_scrap_piv_stop_referential(self, wiremock_server):\n url_gtfs = self.format_url(ip=wiremock_server.ip_addr, filename=\"gtfs.zip\", path=\"ruspell\")\n url_piv = self.format_url(ip=wiremock_server.ip_addr, path=\"\")\n\n self.init_contributor(\"cid\", \"dsid\", url_gtfs)\n self.add_process_to_contributor(\n {\n \"type\": \"ScrapPivStopReferential\",\n \"input_data_source_ids\": [],\n \"sequence\": 0,\n \"target_data_source_id\": \"piv\",\n \"parameters\": {\n \"piv_url\": url_piv,\n \"api_key\": \"abcd\",\n \"user\": \"user\",\n \"password\": \"pass\",\n \"per_page\": 2,\n },\n },\n \"cid\",\n )\n current_dt = datetime.strptime(\"2020-09-01T00:00:00Z\", DATETIME_FORMAT_IS0_8601)\n resp = self.contributor_export(\n \"cid\", check_done=False, current_date=current_dt.strftime(DATETIME_FORMAT_IS0_8601)\n )\n job = self.get_job_from_export_response(resp)\n assert job[\"state\"] == \"done\"\n assert job[\"step\"] == \"save_contributor_export\"\n assert job[\"error_message\"] == \"\"\n\n resp = self.get(\n \"/files/{}/download\".format(self.get_gridfs_id_from_data_source(\"cid\", \"piv\")), follow_redirects=True\n )\n assert resp.status_code == 200\n binary_stream = BytesIO()\n binary_stream.write(resp.data)\n zip_file = ZipFile(binary_stream)\n assert len(zip_file.filelist) == 2\n filenames = [name for name in zip_file.namelist()]\n filenames.sort()\n assert filenames[0] == \"0.xml\"\n assert filenames[1] == \"1.xml\"\n","sub_path":"tests/integration/mongo/contributor_processes_test.py","file_name":"contributor_processes_test.py","file_ext":"py","file_size_in_byte":26723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"51325213","text":"# -*- coding: utf-8 -*-\n# © 2016 Cristian Salamea \n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom odoo import api, fields, models\nfrom odoo.exceptions import ValidationError\nfrom . import amount_to_text_es\n\n\nclass AccountJournal(models.Model):\n _inherit = 'account.journal'\n\n check_report_id = fields.Many2one(\n 'ir.actions.report',\n 'Formato de Cheque'\n )\n\n\nclass AccountPayment(models.Model):\n\n _inherit = 'account.payment'\n\n third_party_name = fields.Char(\n 'A nombre de Tercero',\n readonly=True,\n states={'draft': [('readonly', False)]}\n )\n to_third_party = fields.Boolean(\n 'A nombre de terceros ?',\n readonly=True,\n states={'draft': [('readonly', False)]}\n )\n date_to = fields.Date('Fecha Cobro')\n number = fields.Integer('Numero de Cheque')\n bank = fields.Many2one('res.bank','Banco del Cheque')\n check_type = fields.Selection([('posfechado','Posfechado'),\n ('dia','Al dia')], string=\"Tipo\" , default='dia')\n\n @api.onchange('payment_date')\n def onchange_payment_date(self):\n if self.payment_date:\n self.date_to = self.payment_date\n\n @api.onchange('date_to')\n def onchange_date_to(self):\n if self.date_to and self.date_to > self.payment_date:\n self.check_type = 'posfechado'\n\n @api.onchange('check_number')\n def onchange_check_number(self):\n if self.check_number:\n self.number = self.check_number\n\n @api.onchange('amount')\n def _onchange_amount(self):\n if hasattr(super(AccountPayment, self), '_onchange_amount'):\n super(AccountPayment, self)._onchange_amount()\n check_amount_in_words = amount_to_text_es.amount_to_text(self.amount)# noqa\n self.check_amount_in_words = check_amount_in_words\n\n def do_print_checks(self):\n \"\"\"\n Validate numbering\n Print from journal check template\n \"\"\"\n for payment in self:\n report = payment.journal_id.check_report_id\n if payment.env.context.get('active_model') == 'account.cheque':\n modelo = 'account.payment'\n else:\n modelo = payment._name\n report.write({'model': modelo})\n payment.write({'state':'sent'})\n\n return report.report_action(payment)\n\n def post(self):\n for rec in self:\n super(AccountPayment,rec).post()\n account_check = rec.env['account.cheque']\n if rec.payment_method_id.code in ['check_printing','batch_payment'] and not rec.payment_type == 'transfer':\n types = 'outgoing'\n date = 'cheque_given_date'\n name = rec.partner_id.name\n if rec.payment_type == 'inbound':\n types = 'incoming'\n date = 'cheque_receive_date'\n if rec.to_third_party:\n name = rec.third_party_name\n last_printed_check = rec.search([\n ('journal_id', '=', rec[0].journal_id.id),\n ('check_number', '!=', 0)], order=\"check_number desc\", limit=1)\n if types == 'outgoing':\n debit = rec.destination_account_id.id\n credit = rec.journal_id.default_debit_account_id.id\n date_check = rec.payment_date\n bank_account = rec.journal_id.default_debit_account_id.id\n if not rec.check_number:\n next_check_number = last_printed_check and int(last_printed_check.check_number) + 1 or 1\n \n else:\n next_check_number = rec.check_number\n else :\n bank_account = ''\n date_check = rec.date_to\n credit = rec.partner_id.property_account_receivable_id.id\n debit = rec.journal_id.default_credit_account_id.id\n next_check_number = rec.number\n # next_check_number = last_printed_check and last_printed_check.check_number + 1 or 1\n check_id = account_check.create({\n 'name':rec.name,\n 'company_id':rec.company_id.id,\n 'bank_account_id':bank_account,\n 'amount':rec.amount,\n 'payee_user_id':rec.partner_id.id,\n 'cheque_date':date_check,\n 'cheque_receive_date':rec.payment_date,\n 'cheque_given_date':rec.date_to,\n 'credit_account_id':credit,\n 'debit_account_id':debit,\n 'journal_id':rec.journal_id.id,\n 'account_cheque_type': types,\n 'status':'registered',\n 'status1':'registered',\n 'cheque_number':next_check_number,\n 'third_party_name':name,\n 'payment_id': rec.id,\n # 'date' : rec.date_to,\n #'invoice_ids': rec.invoice_ids,\n })\n for move in rec.move_line_ids:\n move.move_id.account_cheque_id = check_id.id\n # check_id._count_account_invoice()","sub_path":"l10n_ec_check_printing/models/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":5347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317398571","text":"import curses\nimport time\n\ndef TUI_main(tui_q, player_q):\n\n # Initialize Terminal User Interface\n stdscr = curses.initscr()\n curses.noecho()\n curses.cbreak()\n stdscr.keypad(True)\n stdscr.nodelay(True)\n win = curses.newwin(32, 12, 0, 0)\n curses.curs_set(False)\n\n # Initialize colors\n curses.start_color()\n curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_WHITE)\n curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK)\n curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)\n curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK)\n curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n\n run_app=True\n while(run_app):\n char = stdscr.getch()\n if char == 261: # RIGTH ARROW\n player_q.put(['seek_up',None])\n stdscr.clear()\n if char == 260: # LEFT ARROW\n player_q.put(['seek_down',None])\n stdscr.clear()\n if char == 259: # UP ARROW\n player_q.put(['vol_up',None])\n stdscr.clear()\n if char == 258: # DOWN ARROW\n player_q.put(['vol_down',None])\n stdscr.clear()\n if char == ord('q'): # QUIT\n player_q.put(['quit',None])\n run_app = False\n\n while tui_q.empty() is False:\n [msg, radio, volume]= tui_q.get()\n if msg == 'radiovol':\n refresh_TUI(stdscr, radio, volume)\n if msg == 'quit':\n run_app = False\n\n time.sleep(0.1)\n\n # End APP\n stdscr.keypad(False)\n stdscr.nodelay(False)\n curses.nocbreak()\n curses.echo()\n curses.endwin()\n\ndef refresh_TUI(screen, radio, volume):\n blankline = \" \"\n screen.addstr(0, 0, \" Si4731 Radio Receiver \", curses.A_REVERSE)\n\n if (radio is not None):\n screen.addstr(2, 6, \"<<\", curses.A_NORMAL)\n screen.addstr(2, 24, \">>\", curses.A_NORMAL)\n screen.addstr(2, 11, ' ' + str(radio.station.Frequency) + ' MHz ', curses.color_pair(1) + curses.A_REVERSE)\n\n if(radio.rds.PS.string.isprintable()):\n screen.addstr(4,0,blankline,curses.A_NORMAL)\n screen.addstr(4, 16-int(len(radio.rds.PS.string)/2), radio.rds.PS.string, curses.color_pair(3) + curses.A_ITALIC)\n if(radio.rds.RadioTextA.string.isprintable()):\n screen.addstr(5,0,blankline,curses.A_NORMAL)\n screen.addstr(6,0,blankline,curses.A_NORMAL)\n if (len(radio.rds.RadioTextA.string) < 32):\n screen.addstr(5, 16-int(len(radio.rds.RadioTextA.string)/2), radio.rds.RadioTextA.string, curses.color_pair(2) + curses.A_NORMAL)\n else:\n RText = radio.rds.RadioTextA.string.split(maxsplit=2)\n screen.addstr(5, 16-int(len(RText[0])/2), RText[0], curses.color_pair(2) + curses.A_NORMAL)\n screen.addstr(6, 16-int(len(RText[1])/2), RText[1], curses.color_pair(2) + curses.A_NORMAL)\n screen.addstr(8, 5, \"RSSI: \" + str(radio.station.RSSI).zfill(2), curses.A_NORMAL)\n screen.addstr(8, 20, \"SNR: \" + str(radio.station.SNR).zfill(2), curses.A_NORMAL)\n screen.addstr(10, 0, \" by iz2k \", curses.color_pair(4) + curses.A_NORMAL)\n screen.addstr(11, 0, \" \" + chr(9650) + chr(9660) + \" use arrows \" + chr(9668) + \" \" + chr(9658) + \" (q)quit\", curses.A_REVERSE)\n print_vol(screen, volume)\n screen.refresh()\n\ndef get_vol_color_index(vol):\n idx = 4 # Green\n if vol > 4:\n idx = 5 # YELLOW\n if vol > 8:\n idx = 3 # RED\n return idx\n\ndef print_vol(screen, volume):\n # Print volume squares\n for i in range(1, 11):\n if volume/10 > (10-i):\n screen.addstr(i, 31, '#', curses.color_pair(get_vol_color_index(11-i)) + curses.A_NORMAL)\n\n # Print volume number\n # Caluclate vertical position\n volposv = int(11-volume/10)\n # Fix position for 0%\n if(volposv>10):\n volposv=10\n # Calculate horizontal position\n volposh = 32 - len(str(volume))\n # Print volume\n screen.addstr(volposv, volposh, str(volume), curses.color_pair(get_vol_color_index(volume/10)) + curses.A_NORMAL)\n","sub_path":"sw/radiotuner/frontend/tui.py","file_name":"tui.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"624214919","text":"from fabric.api import local, env, execute, run\nfrom fabric.tasks import Task\nfrom fabric.context_managers import cd\n\nclass AddGitRemote(Task):\n \"\"\"\n Adds a remote to your git repo.\n\n Requires two arguments:\n\n * **remote_name**: The name this remote should have in your repo.\n\n * **user_and_host**: The connection string for this remote. admin@10.0.1.1\n for example. This should not include the path to the\n repo\n\n This is a serial task, that should not be called\n with any remote hosts as it performs no remote actions.\n\n \"\"\"\n\n name = 'add_remote'\n serial = True\n\n def run(self, remote_name=None, user_and_host=None):\n if not remote_name:\n raise Exception(\"You must provide a name for the new remote\")\n\n ssh_path = \"ssh://%s/~/%s\" % (user_and_host, env.git_repo_name)\n local('git remote add %s %s' % (remote_name, ssh_path))\n env.git_remotes[remote_name] = user_and_host\n env.git_reverse[user_and_host] = remote_name\n\nclass RemoveGitRemote(Task):\n \"\"\"\n Removes a remote from your git repo.\n\n Requires one argument:\n\n * **remote_name**: The name that you want to remove from your git repo.\n\n This is a serial task, that should not be called\n with any remote hosts as it performs no remote actions.\n \"\"\"\n\n name = 'rm_remote'\n serial = True\n\n def run(self, remote_name=None):\n local('git remote rm %s' % remote_name)\n\nclass GitPush(Task):\n \"\"\"\n Pushes your repo to remotes specified by hosts\n\n Takes one optional argument:\n\n * **branch**: The branch that you would like to push.\n If it is not provided 'master' will be used.\n\n Will raise an error if a specified host isn't in your git\n remotes.\n \"\"\"\n\n name = 'push'\n\n def run(self, branch=None, hosts=[]):\n if not branch:\n branch = 'master'\n\n remote_name = env.git_reverse[env.host_string]\n local('git push %s %s' % (\n remote_name, branch))\n\nclass GitResetRemoteHead(Task):\n \"\"\"\n Deletes the remote head making the next push\n look like a fresh update.\n \"\"\"\n name = 'reset_remote'\n\n def run(self, hosts=[]):\n with cd(env.git_repo_name):\n run('git update-ref -d HEAD')\n\npush = GitPush()\nadd_remote = AddGitRemote()\nrm_remote = RemoveGitRemote()\nreset_remote = GitResetRemoteHead()\n","sub_path":"fab_deploy/local/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"336498098","text":"#coding=utf-8\nfrom netzob.all import *\nimport struct\nimport math\nimport os\nimport sys\n\nclass series_num:\n def __init__(self,sessions):\n self.sessions = sessions\n self.consession = []\n self.locate = []\n self.group = None\n\n def group_byoff(data_L):\n i = 0\n t_result = {}\n t_count = {}\n while (i < 100):\n t_result[i] = []\n t_count[i] = 0\n i = i + 1\n for data_l in data_L:\n for key, value in data_l.iteritems():\n t_result[key].append(value)\n t_count[key] = t_count[key] + 1\n return t_result, t_count\n\n def r_length(da_str, gap, leixing, encoding):\n \"\"\"\n :param gap:\n :param leixing:\n :param encoding:\n :return:\n \"\"\"\n length = len(da_str)\n i = 0\n t_co = {}\n while (i < length - gap):\n t_str = da_str[i:i + gap + 1]\n t_len = struct.unpack(encoding + leixing, t_str)\n offset = i\n left = length - i\n if (t_len[0] <= left):\n t_co[i] = [i, t_len[0]]\n # if i in t_co.keys():\n # t_co[i].append([i,t_len[0],left])\n # else:\n # t_co[i] = []\n # t_co[i].append([i, t_len[0], left])\n i = i + gap + 1\n return t_co\n\n def get_multisession(self):\n \"\"\"\n split mix sessions by ip and port\n :return:\n \"\"\"\n src = self.sessions[0].source\n des = self.sessions[0].destination\n s_lo = 0\n t_lo = 0\n t_src = []\n t_des = []\n for session in self.sessions:\n if session.source == src:\n t_src.append(session)\n else:\n t_des.append(session)\n\n return t_src,t_des\n\n def r_length(self,da_str,gap,leixing,encoding):\n \"\"\"\n :param da_str:original data\n :param gap:bytes num\n :param leixing:big edian or little indian\n :param encoding:number type\n :return:t_co location info\n \"\"\"\n length = len(da_str)\n i = 0\n t_co = {}\n while (i < length - gap):\n t_str = da_str[i:i + gap + 1]\n t_len = struct.unpack(encoding + leixing, t_str)\n offset = i\n left = length - i\n t_co[i] = [i, t_len[0]]\n i = i + gap + 1\n return t_co\n\n def group_byoff(self,data_L):\n i = 0\n t_result = {}\n t_count = {}\n while (i < 100):\n t_result[i] = []\n t_count[i] = 0\n i = i + 1\n for data_l in data_L:\n for key, value in data_l.iteritems():\n if key >= 100:\n continue\n t_result[key].append(value)\n t_count[key] = t_count[key] + 1\n return t_result, t_count\n\n def vote_lo(self,T_result,t_vote):\n t_lo = []\n t_selo = []\n for key in T_result:\n t_value = T_result[key]\n t_length = len(t_value)\n i = 0\n t_num = 0\n t_tans = {}\n while(i < t_length -1):\n t_temp = t_value[i+1][1] - t_value[i][1]\n if t_temp not in t_tans:\n t_tans[t_temp] = 1\n else:\n t_tans[t_temp] = t_tans[t_temp] + 1\n i = i + 1\n t_most = max(zip(t_tans.values(),t_tans.keys()))[0]\n t_value = max(zip(t_tans.values(),t_tans.keys()))[1]\n if(float(t_most)/float(t_length) > t_vote):\n t_lo.append(key)\n if(t_value != 0):\n t_selo.append(key)\n return t_lo,t_selo\n\n\n\n\n\n\n def get_location(self,t_rate,t_vote):\n series_lo = []\n for t_session in self.consession:\n T_con = []\n data_T = t_session\n T_length = len(t_session)\n for data_s in data_T:\n t_con = self.r_length(data_s.data, 0, 'B', '>')\n T_con.append(t_con)\n T_group, T_count = self.group_byoff(T_con)\n T_group_two = {}\n T_count_two = {}\n for t_key in T_count:\n if (T_count[t_key] / T_length > t_rate):\n T_group_two[t_key] = T_group[t_key]\n T_count_two[t_key] = T_count[t_key]\n\n t_r,t_s = self.vote_lo(T_group_two,t_vote)\n series_lo.append(t_s)\n self.locate = series_lo\n return series_lo\n\n\n\"\"\"\nMessageList = PCAPImporter.readFile('/home/wxw/data/iec104/10.55.37.310.55.218.2.pcap').values()\npp = series_num(MessageList)\nsrc,des = pp.get_multisession()\nprint(src)\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"classify_6/frequent_find/series_find.py","file_name":"series_find.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"28537291","text":"from __future__ import print_function\nfrom simtk import unit, openmm\nfrom simtk.openmm import app\nfrom protons import *\nimport logging\n\n\ntry:\n openmm.Platform.getPlatformByName('CUDA')\n hasCUDA = True\nexcept Exception:\n logging.info(\"CUDA unavailable on this system.\")\n hasCUDA = False\n\nclass SystemSetup:\n \"\"\"Empty class for storing systems and relevant attributes\"\"\"\n pass\n\ndef make_method(func, input):\n # http://blog.kevinastone.com/generate-your-tests.html\n def test_input(self):\n func(self, input)\n test_input.__name__ = 'test_{func}_{input}'.format(func=func.__name__, input=input)\n return test_input\n\n\ndef generate(func, *inputs):\n \"\"\"\n Take a TestCase and add a test method for each input\n \"\"\"\n # http://blog.kevinastone.com/generate-your-tests.html\n def decorator(testcase):\n for input in inputs:\n test_input = make_method(func, input)\n setattr(testcase, test_input.__name__, test_input)\n return testcase\n\n return decorator\n\n\ndef make_xml_explicit_tyr(inpcrd_filename='constph/examples/calibration-explicit/tyr.inpcrd',\n prmtop_filename='constph/examples/calibration-explicit/tyr.prmtop',\n outfile='tyrosine_explicit'):\n\n temperature = 300.0 * unit.kelvin\n pressure = 1.0 * unit.atmospheres\n outfile1=open('{}.sys.xml'.format(outfile), 'w')\n outfile2=open('{}.state.xml'.format(outfile), 'w')\n platform_name = 'CPU'\n pH = 9.6\n inpcrd = app.AmberInpcrdFile(inpcrd_filename)\n prmtop = app.AmberPrmtopFile(prmtop_filename)\n positions = inpcrd.getPositions()\n system = prmtop.createSystem(implicitSolvent=None, nonbondedMethod=app.CutoffPeriodic, constraints=app.HBonds)\n system.addForce(openmm.MonteCarloBarostat(pressure, temperature))\n context = minimizer(platform_name, system, positions)\n outfile1.write(openmm.XmlSerializer.serialize(system))\n outfile2.write(openmm.XmlSerializer.serialize(context.getState(getPositions=True)))\n\ndef make_xml_implicit_tyr(inpcrd_filename='constph/examples/calibration-implicit/tyr.inpcrd',\n prmtop_filename='constph/examples/calibration-implicit/tyr.prmtop',\n outfile='tyrosine_implicit'):\n\n temperature = 300.0 * unit.kelvin\n outfile1=open('{}.sys.xml'.format(outfile), 'w')\n outfile2=open('{}.state.xml'.format(outfile), 'w')\n platform_name = 'CPU'\n pH = 9.6\n inpcrd = app.AmberInpcrdFile(inpcrd_filename)\n prmtop = app.AmberPrmtopFile(prmtop_filename)\n positions = inpcrd.getPositions()\n system = prmtop.createSystem(implicitSolvent=app.OBC2, nonbondedMethod=app.NoCutoff, constraints=app.HBonds)\n context = minimizer(platform_name, system, positions)\n outfile1.write(openmm.XmlSerializer.serialize(system))\n outfile2.write(openmm.XmlSerializer.serialize(context.getState(getPositions=True)))\n\n\ndef compute_potential_components(context):\n \"\"\"\n Compute potential energy, raising an exception if it is not finite.\n\n Parameters\n ----------\n context : simtk.openmm.Context\n The context from which to extract, System, parameters, and positions.\n\n \"\"\"\n import copy\n system = context.getSystem()\n system = copy.deepcopy(system)\n positions = context.getState(getPositions=True).getPositions(asNumpy=True)\n parameters = context.getParameters()\n for index in range(system.getNumForces()):\n force = system.getForce(index)\n force.setForceGroup(index)\n\n integrator = openmm.VerletIntegrator(1.0 * unit.femtoseconds)\n platform = openmm.Platform.getPlatformByName('Reference')\n context = openmm.Context(system, integrator, platform)\n context.setPositions(positions)\n for (parameter, value) in parameters.items():\n context.setParameter(parameter, value)\n energy_components = list()\n for index in range(system.getNumForces()):\n force = system.getForce(index)\n forcename = force.__class__.__name__\n groups = 1</\",\n CmsDeleteUser.as_view(),\n name=\"cms_delete_user\",\n ),\n path(\"godmode/invites/\", CmsInvites.as_view(), name=\"invites\"),\n path(\n \"godmode/invites/delete//\",\n CmsDeleteCategory.as_view(),\n name=\"cms_delete_invite\",\n ),\n # CMS Blog\n path(\"godmode/articles\", CmsArticles.as_view(), name=\"articles\"),\n path(\n \"godmode/articles/edit//\",\n CmsEditArticle.as_view(),\n name=\"cms_edit_article\",\n ),\n path(\n \"godmode/articles/delete//\",\n CmsDeleteArticle.as_view(),\n name=\"cms_delete_article\",\n ),\n path(\n \"godmode/articles/new/\",\n CmsNewArticle.as_view(),\n name=\"cms_new_article\",\n ),\n path(\"godmode/authors\", CmsAuthors.as_view(), name=\"authors\"),\n path(\n \"godmode/authors/edit//\",\n CmsEditAuthor.as_view(),\n name=\"cms_edit_author\",\n ),\n path(\n \"godmode/authors/delete//\",\n CmsDeleteAuthor.as_view(),\n name=\"cms_delete_author\",\n ),\n path(\n \"godmode/authors/new/\",\n CmsNewAuthor.as_view(),\n name=\"cms_new_author\",\n ),\n path(\"godmode/categories\", CmsCategories.as_view(), name=\"categories\"),\n path(\n \"godmode/categories/edit//\",\n CmsEditCategory.as_view(),\n name=\"cms_edit_category\",\n ),\n path(\n \"godmode/categories/delete//\",\n CmsDeleteCategory.as_view(),\n name=\"cms_delete_category\",\n ),\n path(\n \"godmode/categories/new/\",\n CmsNewCategory.as_view(),\n name=\"cms_new_category\",\n ),\n # Auth\n path(\"accounts/\", include(\"allauth.urls\")),\n # Pages\n path(\"\", index, name=\"home\"),\n # Blog\n path(\"blog/\", blog, name=\"blog\"),\n path(\"blog//\", post_detail, name=\"post_detail\"),\n path(\"blog/category/\", category, name=\"category\"),\n # Django-Invites\n # Override url for django-invatations.SendInvite\n path(\"invitations/send-invite/\", SendInvite.as_view(), name=\"send-invite\"),\n path(\"invitations/\", include(\"invitations.urls\", namespace=\"invitations\")),\n]\n","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"259203167","text":"import os\n\nfrom core.base_class.BaseClass import BaseClass\nfrom core.osutils.file import File\nfrom core.osutils.folder import Folder\nfrom core.settings.settings import IOS_RUNTIME_PATH\nfrom core.tns.tns import Tns\nfrom core.xcode.xcode import Xcode\nfrom core.settings.strings import *\n\n\nclass BuildiOSNGTests(BaseClass):\n @classmethod\n def setUpClass(cls):\n logfile = os.path.join(\"out\", cls.__name__ + \".txt\")\n BaseClass.setUpClass(logfile)\n\n Xcode.cleanup_cache()\n\n Tns.create_app_ng(app_name=cls.app_name)\n Tns.platform_add_ios(attributes={\"--path\": cls.app_name, \"--frameworkPath\": IOS_RUNTIME_PATH})\n\n @classmethod\n def tearDownClass(cls):\n BaseClass.tearDownClass()\n Folder.cleanup(cls.app_name)\n\n def test_100_build_ios_ng_project(self):\n output = Tns.build_ios(attributes={\"--path\": self.app_name})\n assert \"build/emulator/TestApp.app\" in output\n assert File.exists(self.app_name + \"/platforms/ios/build/emulator/TestApp.app\")\n\n def test_200_build_ios_ng_project_release_fordevice(self):\n output = Tns.build_ios(attributes={\"--path\": self.app_name,\n \"--for-device\": \"\",\n \"--release\": \"\"})\n assert config_release in output\n assert codesign in output\n assert \"build/device/TestApp.app\" in output\n assert File.exists(self.app_name + \"/platforms/ios/build/device/TestApp.ipa\")\n","sub_path":"tests/build/ios/build_ios_ng_tests.py","file_name":"build_ios_ng_tests.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"299639063","text":"#!/bin/python\n'''\nDate:20180306\n@author: xiexk\n'''\nimport numpy as np\nimport random \n\n## download the user-item data\ndef load_data(path):\n f = open(path)\n data = []\n for line in f.readlines():\n arr = []\n lines = line.strip().split(\",\")\n for x in lines:\n if x != \"-\":\n arr.append(float(x))\n else:\n arr.append(float(0))\n data.append(arr)\n return data\n\n## stochastic gradient ascent based method\ndef gradAscent(data, K):\n dataMat = np.mat(data)\n print (dataMat)\n m, n = np.shape(dataMat)\n p = np.mat(np.random.random((m, K)))\n q = np.mat(np.random.random((K, n)))\n\n alpha = 0.0002\n beta = 0.02\n maxCycles = 10000\n e = []\n\n for step in range(maxCycles):\n for i in range(m):\n for j in range(n):\n #print dataMat[i,j]\n if dataMat[i,j] != 0:\n error = dataMat[i,j]\n for k in range(K):\n error = error - p[i,k]*q[k,j]\n for k in range(K):\n p[i,k] = p[i,k] + alpha * (2 * error * q[k,j] - beta * p[i,k])\n q[k,j] = q[k,j] + alpha * (2 * error * p[i,k] - beta * q[k,j])\n\n loss = 0.0\n for i in range(m):\n for j in range(n):\n if dataMat[i,j] != 0:\n error = 0.0\n for k in range(K):\n error = error + p[i,k]*q[k,j]\n loss = (dataMat[i,j] - error) * (dataMat[i,j] - error)\n for k in range(K):\n loss = loss + beta * (p[i,k] * p[i,k] + q[k,j] * q[k,j]) / 2\n \n e.append(loss)\n if loss < 0.001:\n break\n #print step\n if step % 1000 == 0:\n print (loss)\n\n return p, q, e\n\n\nif __name__ == \"__main__\":\n dataMatrix = load_data(\"./IntelligenceRecommendation/data\")\n p, q, loss = gradAscent(dataMatrix, 5)\n result = p * q\n print (p)\n print (q)\n print (result)\n np.save('error.npy',loss)\n \n \n \n \n'''\nDate:20180306\n@author: xiexk\n'''\n\nfrom pylab import *\nimport numpy as np\n\ndata = np.load('error.npy')\n# data = data[0:20000]\n\nn = len(data)\nx = range(n)\nplot(x, data, color='r',linewidth=1)\nplt.title('Convergence curve')\nplt.xlabel('generation')\nplt.ylabel('loss')\nshow()\n \n","sub_path":"MatrixFactorisation.py","file_name":"MatrixFactorisation.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"562117661","text":"#add a new problem\n# For Hydrogen\n#%pwd\n#%cd src\n\nfrom collections import namedtuple\nfrom main import print_set, print_tree, savedbfile, loaddbfile\n\ndef add_problem(problem_id, p_meta, problem_text):\n \"\"\" Appends and saves to pickle files new problem_meta\n\n prob_id: taken as starting point, if duplicate, increments\n p_meta: tuple of \"topic, standard, calc_type, difficulty, level, source\"\n prob_text: TeX format problem text (add solution and workspace)\n return actual problem_id number\n \"\"\"\n while problem_id in problem.keys():\n problem_id += 1\n problem[problem_id] = [problem_text] #solution and workspace add later\n #p_meta = (lookup_list[tmp], lookup_ccss(lookup_list[tmp]), 1, 3, 1, \"cjh\")\n problem_meta[problem_id] = p_meta\n skill[p_meta[0]].append(problem_id)\n return problem_id\n\ndef ccss_lookup(topic):\n for i in range(299, 305):\n if standards[i][2] == topic:\n return standards[i][3]\n return None\n\n\nstandards = loaddbfile(\"standards_tree_jmap\")\nstandards_desc = loaddbfile(\"standards_text_jmap\")\nproblem = loaddbfile(\"problem\")\nproblem_meta = loaddbfile(\"problem_meta\")\nskill = loaddbfile(\"skill\")\n\np_meta_names = \"topic, standard, calc_type, difficulty, level, source\"\np_meta = namedtuple(\"p_meta\", p_meta_names)\n\ntopic = \"Inverse of Functions\"\n\nstandard = ccss_lookup(topic)\n\np_meta = (\"Inverse of Functions\", standard, 1, 3, 1, \"cjh\")\nproblem_id = 1200\n\nnew_ids = []\nindir = \"/Users/chris/GitHub/mathai/in/\"\nfilename = indir + \"add.txt\"\nwith open(filename, \"r\") as add_file:\n problemlist = []\n for line in add_file:\n l = line.lstrip(\"\\\\item \")\n #Careful! This will strip any of these letters, not just the prefix\n problemlist.append(l)\n\nfor problem_text in problemlist:\n n = add_problem(problem_id, p_meta, problem_text)\n print(n)\n new_ids.append(n)\n\nprint(new_ids)\n\n#p = [problem_id for problem_id in problem.keys()]\ntitle = (\"new_probs\", \"ids in margin\", \"Inventory: New Problems\")\nprint_set(new_ids, title, idflag=2)\n\n\nsavedbfile(problem, \"problem3\")\nsavedbfile(problem_meta, \"problem_meta3\")\nsavedbfile(skill, \"skill3\")\n","sub_path":"src/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"340980475","text":"def solution(A):\n # Since S could be 1 or -1, it does not matter that\n # each element in A is positive or negative.\n A = [abs(item) for item in A]\n sumOfA = sum(A)\n # Get the number distribution. So we do not need to try\n # each number for multiple times.\n numbers = {}\n for item in A: numbers[item] = numbers.get(item, 0) + 1\n # This is the KEY point.\n # Typically, we will use possible = [False] * len to track, which numbers\n # could be the result by summing up subsets of A.\n # For a number, appeared for many times, there will be multiple attempts\n # for it. But in this way, when we are trying number n,\n # possible[i] == -1 means it is impossible.\n # possible[i] == i >= 0 means it is possible and there are i n(s) left to use.\n # So for ALL number n(s), we only need ONE scan over the record.\n possible = [-1] * (sumOfA // 2 + 1)\n possible[0] = 0\n for number in numbers: # Try each distinct number\n for trying in xrange(sumOfA//2+1):\n if possible[trying] >= 0:\n # Can be reached with previous numbers\n possible[trying] = numbers[number]\n elif trying >= number and possible[trying-number] > 0:\n # Cannot be reached with only previous numbers.\n # But could be achieved with previous numbers AND current one.\n possible[trying] = possible[trying-number] - 1\n # Divide the A into two parts: P and Q, with restriction P <= Q.\n # So P <= sumOfA // 2 <= Q. We want the largest possible P, so that\n # Q-P is minimized.\n for halfSum in xrange(sumOfA//2, -1, -1):\n if possible[halfSum] >= 0:\n return sumOfA - halfSum - halfSum\n raise Exception(\"Should never be here!\")\n return 0","sub_path":"17_dynamic_programming/min_abs_sum.py","file_name":"min_abs_sum.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"288896829","text":"#!/usr/bin/env python\nimport argparse\nimport os\nfrom glob import glob\nimport lfmViz as lfmv\n\nif __name__ == \"__main__\":\n\t#Set defaults\n\ttabDef = [\"ebtab.txt\"]\n\n\tparser = argparse.ArgumentParser(description=\"Generates EB table for LFMTP from input VTI files\")\n\n\tparser.add_argument('-o',nargs=1,type=str,default=tabDef,metavar='ebtab.txt',help=\"File to output table to (default: %(default)s)\")\n\tparser.add_argument('vtis',nargs='+',metavar='data.vti',help=\"List of files to add to table\")\n\n\t#Finished getting arguments, parse and move on\n\targs = parser.parse_args()\n\toutTab = args.o[0]\n\tvtis = list()\n\tfor arg in args.vtis:\n\t\tvtis += glob(arg)\n\n\tTscl = 1.0 #Don't scale, leave in seconds\n\tfnames = []\n\tTs = []\n\n\tfor vti in vtis:\n\t\tpre,ext = os.path.splitext(vti)\n\t\tif (ext != '.vti'):\n\t\t\tprint(\"Skipping %s\"%(vti))\n\t\t\tcontinue\n\t\t#Otherwise, get time from VTI\n\t\tfnames.append(vti)\n\t\tt = lfmv.getVTI_Time(vti)\n\t\tTs.append(t)\n\n\t#Now scale times and translate to zero\n\tTmin = min(Ts)\n\tTscls = [(ti-Tmin)*Tscl for ti in Ts]\n\n\t#Re-sort\n\tTabV = sorted(zip(Tscls,fnames))\n\twith open(outTab,'w') as f:\n\t\tfor tF in TabV:\n\t\t\tf.write('%16.4f %s\\n'%(tF[0],tF[1]))\n\n","sub_path":"bin/genTab.py","file_name":"genTab.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"69873087","text":"#!/usr/bin/env python\n#Time-stamp:\n\"\"\"\nDescription:\n\n\"\"\"\n\n# ------------------------------------\n# Python Modual\n# ------------------------------------\n\nimport os,sys,re\nfrom optparse import OptionParser\nimport logging\nimport string\nimport copy,time\nimport numpy\nimport twobitreader\nimport gzip\n# ------------------------------------\n# error and warning\n# ------------------------------------\n\n\n# ------------------------------------\n# Misc functions\n# ------------------------------------\n\ndef splitATACfq(inputname,folder,startpos,barcodeLen):\n\n fq1 = \"%s/%s/%s_R1.fastq.gz\"%(folder,inputname,inputname)\n fq2 = \"%s/%s/%s_R2.fastq.gz\"%(folder,inputname,inputname)\n inf1 = gzip.open(fq1,\"rb\")\n inf2 = gzip.open(fq2,\"rb\")\n\n line_count = 0\n reads_count = {}\n\n #outf1 = open(\"%s_R1.fastq\"%(outname),\"w\")\n #outf2 = open(\"%s_R2.fastq\"%(outname),\"w\")\n\n while 1:\n line_count += 1\n p1 = inf1.readline()\n p2 = inf2.readline()\n\n if line_count%4 == 1:\n p1l1 = p1\n p2l1 = p2\n elif line_count%4 == 2:\n p1l2 = p1[startpos:]\n p2l2 = p2[startpos:]\n line_p5 = p1[:barcodeLen]\n line_p7 = p2[:barcodeLen] \n #print \"p1\",p1,line_p5\n #print \"p2\",p2,line_p7 \n elif line_count%4 == 3:\n p1l3 = p1\n p2l3 = p2\n else:\n p1l4 = p1[startpos:]\n p2l4 = p2[startpos:]\n\n barcode_key = line_p5 + \"_\" + line_p7\n if not reads_count.has_key(barcode_key):\n reads_count[barcode_key] = 0\n reads_count[barcode_key] += 1\n\n #if line_p5 == p5 and line_p7 == p7:\n # outf1.write(p1l1)\n # outf1.write(p1l2)\n # outf1.write(p1l3)\n # outf1.write(p1l4)\n # outf2.write(p2l1)\n # outf2.write(p2l2)\n # outf2.write(p2l3)\n # outf2.write(p2l4)\n\n if p1.strip() == \"\" and p2.strip() == \"\":\n break\n inf1.close()\n inf2.close()\n #outf1.close()\n #outf2.close()\n\n outf = open(\"%s_BCcount.txt\"%inputname,'w')\n for BC,count in sorted(reads_count.iteritems(),key=lambda x:x[1],reverse=True):\n outf.write(\"%s\\t%s\\n\"%(BC,count))\n outf.close()\n\n\n# ------------------------------------\n# Main function\n# ------------------------------------\n\ndef main():\n usage = \"python %prog >.< \"\n description = \"\"\">.<\"\"\"\n\n optparser = OptionParser(version=\"%prog 1\",description=description,usage=usage,add_help_option=False)\n optparser.add_option(\"-h\",\"--help\",action=\"help\",help=\"Show this help message and exit.\")\n\n#========major options=============\n\n\n optparser.add_option(\"-i\",dest=\"inputname\",type=\"str\",\n help=\"\")\n optparser.add_option(\"--startpos\",dest=\"startpos\",type=\"int\",default=27,\n help=\"\")\n optparser.add_option(\"--barcodeLen\",dest=\"barcodeLen\",type=\"int\",default=8,\n help=\"\")\n optparser.add_option(\"-f\",\"--folder\",dest=\"folder\",type=\"str\",default=\"/nm/vol190/zanglab/sh8tv/Project/scATAC/Data/scATAC/Tanglab_scATAC/fastq/05_20181030_mESC_tagmentation_CAbeads/combined_ATAC/\",\n help=\"\")\n\n#========minor options=============\n\n (options,args) = optparser.parse_args()\n\n inputname = options.inputname\n if not inputname:\n optparser.print_help()\n sys.exit(1)\n splitATACfq(inputname,options.folder,options.startpos,options.barcodeLen)\n\nif __name__== '__main__':\n try:\n main()\n\n except KeyboardInterrupt:\n sys.stderr.write(\"User interrupt me ^_^ \\n\")\n sys.exit(0)\n\n\n","sub_path":"single_cell/Tanglab/summaryBarcode_ATACfq.py","file_name":"summaryBarcode_ATACfq.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"182289468","text":"\n# 命令行选项、参数和子命令解析器\nimport argparse\n# 使用多线程、多进程\nimport concurrent.futures as futuresObj\nimport util\nimport logger\n\n\nclass HostScanner:\n \"\"\"\n num: 并发数\n mode: 扫描方式 ping/tcp\n host: 指定地址\n store: 保存结果为json\n future: 使用运行方式 多线程/多进程\n runtime: 计算运行耗时\n \"\"\"\n def __init__(self, num, mode, host, store, future, runtime): \n try:\n ip_range = util.parse_ip_range(host)\n\n self.ip_start = ip_range[0]\n self.ip_end = ip_range[1]\n self.num = num\n self.mode = mode\n self.future = future\n self.runtime = runtime\n \n self.logger = logger.Logger(store > 0)\n\n self.task_gen = self.task_generator()\n except Exception as e:\n self.logger.rp_logger.error(e)\n def task_generator(self):\n if self.mode == 'tcp':\n for int32_ip in range(self.ip_start, self.ip_end + 1):\n str_ip = util.int2ip(int32_ip)\n for port in range(1, 65535 + 1):\n yield util.is_port_open, str_ip, port\n else:\n for int32_ip in range(self.ip_start, self.ip_end + 1):\n yield util.ping_host, util.int2ip(int32_ip)\n\n def run(self):\n try:\n pool = futuresObj.ProcessPoolExecutor\n if self.future == 'thread':\n pool = futuresObj.ThreadPoolExecutor\n\n with pool(max_workers=self.num) as executor:\n futures = {}\n for t in self.task_gen:\n func = t[0]\n args = list(t)\n args.pop(0)\n # 记录耗时\n if self.runtime:\n future = executor.submit(util.measure_time, func, *args)\n else:\n future = executor.submit(func, *args)\n\n futures[future] = t\n\n for f in futuresObj.as_completed(futures):\n tt = futures[f]\n ip = tt[1]\n port = 0\n if len(tt) == 3:\n port = tt[2]\n r = f.result()\n self.logger.log(ip, port, r[0], r[1])\n except Exception as e:\n self.logger.rp_logger.error(e)\n\ndef create_parser():\n \"\"\"定义接收命令的参数\"\"\"\n parser = argparse.ArgumentParser(description='using the host scanner')\n parser.add_argument('-n', type=int, default=2, help='specify the number of concurrent')\n parser.add_argument('-f', type=str, choices=['ping', 'tcp'], default='ping', help='specify test mode')\n parser.add_argument('-ip', type=str, help='ip address supports 192.168.0.1-192.168.0.100', required=True)\n parser.add_argument('-w', action='count', default=0, help='store scan results')\n parser.add_argument('-m', type=str, choices=['proc', 'thread'], default='proc', help='specifies to use the multi process or multi thread model')\n parser.add_argument('-v', action='count', default=0, help='print scanner takes time to run', required=False)\n args = parser.parse_args()\n return args\n \nif __name__ == '__main__':\n parser = create_parser()\n scanner = HostScanner(parser.n, parser.f, parser.ip, parser.w, parser.m, parser.v)\n scanner.run()\n \n\n","sub_path":"week03/work1/pmap.py","file_name":"pmap.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"624021225","text":"from rest_framework import serializers\nfrom .models import *\n\nclass CollegeSerializer(serializers.ModelSerializer):\n class Meta:\n model = College\n fields = ('id','name','location','acronym','contact')\n\nclass StudentSerializer(serializers.ModelSerializer):\n class Meta:\n model = Student\n fields = ('id','name','dob','email','db_folder','dropped_out','college')\n\nclass MockTest1Serializer(serializers.ModelSerializer):\n class Meta:\n model = MockTest1\n fields = ('problem1','problem2','problem3','problem4','total')\n\nclass StudentDetailsSerializer(serializers.ModelSerializer):\n mocktest1 = MockTest1Serializer(read_only=False, many=False)\n\n class Meta:\n model = Student\n fields = ('id', 'name', 'dob', 'email', 'db_folder', 'dropped_out','college','mocktest1')\n\n def create(self, validated_data):\n mock_data = validated_data.pop('mocktest1')\n student = Student.objects.create(**validated_data)\n MockTest1.objects.create(student=student, **mock_data) ############instance\n return student\n\n def update(self, instance, validated_data):\n instance.name = validated_data.get(\"name\", instance.name)\n instance.dob = validated_data.get(\"dob\", instance.dob)\n instance.email = validated_data.get(\"email\", instance.email)\n instance.db_folder = validated_data.get(\"db_folder\", instance.db_folder)\n instance.dropped_out = validated_data.get(\"dropped_out\", instance.dropped_out)\n instance.college_id = validated_data.get(\"college_id\", instance.college_id) ############\n\n mockdata = validated_data[\"mocktest\"]\n print('md ', mockdata)\n if not hasattr(instance, \"mocktest\"):\n mocktestdata = {'problem1': 0, 'problem2': 0, 'problem3': 0, 'problem4': 0}\n mock = MockTest1.objects.create(Student=instance, **mocktestdata)\n setattr(instance, \"mocktest\", mock)\n\n instance.mocktest.problem1 = mockdata.get('problem1', instance.mocktest.problem1)\n instance.mocktest.problem2 = mockdata.get('problem2', instance.mocktest.problem2)\n instance.mocktest.problem3 = mockdata.get('problem3', instance.mocktest.problem3)\n instance.mocktest.problem4 = mockdata.get('problem4', instance.mocktest.problem4)\n instance.mocktest.totals = instance.mocktest.problem1 + instance.mocktest.problem2 + instance.mocktest.problem3 + instance.mocktest.problem4\n instance.mocktest.save()\n instance.save()\n return instance\n\n","sub_path":"onlineapp/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"332138286","text":"# SetNodeDatum.py\n# (C)2015\n# Kent A. Stevens\n\nfrom __future__ import print_function, absolute_import, unicode_literals, division\n\nfrom nimble import cmds\nfrom nimble import NimbleScriptBase\n\n#___________________________________________________________________________________________________ SetNodeDatum\nclass SetNodeDatum(NimbleScriptBase):\n \"\"\" A remote script class for setting the prev and next links for a given set of nodes, passed\n in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode).\n --- RETURNS ---\n success: True if at least one track node is processed else False \"\"\"\n\n#===================================================================================================\n# P U B L I C\n\n#___________________________________________________________________________________________________ run\n\n def run(self, *args, **kwargs):\n \"\"\" Sets the prev and next links for a list of node-value pairs that provide information\n about the prev and next to each specified node. \"\"\"\n\n nodeValuePairs = self.fetch('nodeValuePairs', None)\n\n for nodeValuePair in nodeValuePairs:\n node = nodeValuePair[0]\n value = nodeValuePair[1]\n self.setNodeDatum(node, value)\n\n self.puts(success=True)\n return\n\n#___________________________________________________________________________________________________ setNodeDatum\n def setNodeDatum(self, node, value):\n \"\"\" Sets the node's datum value, creating the attribute if not already defined. \"\"\"\n\n if not cmds.attributeQuery('datum', node=node, exists=True):\n cmds.addAttr(node, longName='cadence_datum', shortName='datum', niceName='Datum')\n\n cmds.setAttr(node + '.datum', value)\n\n","sub_path":"src/cadence/mayan/trackway/SetNodeDatum.py","file_name":"SetNodeDatum.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"443335543","text":"#coding:utf-8\n\nfrom tornado.web import RequestHandler\nfrom util.exception import ParamExist\nfrom util.convert import is_user_name, is_mobile, bs2utf8\nimport logging\nimport json\nfrom operation import plot, node, person\n\nLOG = logging.getLogger(__name__)\n\n\nclass PersonHandler(RequestHandler):\n def initialize(self, **kwds):\n pass\n\n def get(self):\n try:\n plot_id = self.get_argument('plot_id', '')\n if not plot_id:\n self.finish(json.dumps({'state': 1, 'message': 'Plot id is None'}))\n return\n person_op = person.PersonOp()\n data = person_op.data(plot_id=plot_id)\n self.finish({'state': 0, 'data': data, \"message\": \"query success\"})\n except ParamExist as ex:\n LOG.error(\"Get person info error:%s\" % ex)\n self.finish(json.dumps({'state': 9, 'message': 'params exit'}))\n except Exception as ex:\n LOG.error(\"Get person error:%s\" % ex)\n self.finish(json.dumps({'state': 10, 'message': 'get person error'}))\n\n\n\n","sub_path":"api/plot/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"132005613","text":"def main(j, args, params, tags, tasklet):\n\n id = args.getTag('id')\n if not id:\n out = 'Missing workflow id param \"id\"'\n params.result = (out, args.doc)\n return params\n\n ossclient = j.core.osis.getClientForNamespace('oss')\n\n workflow = ossclient.workflow.simpleSearch({'id':int(id)})\n\n if not workflow:\n params.result = ('Workflow with id %s not found' % id, args.doc)\n return params\n\n workflow = workflow[0]\n\n for step in workflow['steps']:\n step['nextsteps'] = ', '.join(step['nextsteps'])\n step['nextsteps_error'] = ', '.join(step['nextsteps_error'])\n\n args.doc.applyTemplate(workflow)\n\n params.result = (args.doc, args.doc)\n return params\n\ndef match(j, args, params, tags, tasklet):\n return True","sub_path":"apps/portal_space/OSS/.macros/wiki/workflow/3_workflow.py","file_name":"3_workflow.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"288823638","text":"# -*- coding: utf-8 -*-\nfrom contextlib import contextmanager\nfrom collections import namedtuple\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.engine.url import make_url\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.pool import NullPool\n\nimport sbds.logging\n\nlogger = sbds.logging.getLogger(__name__)\n\n\n# pylint: disable=too-many-arguments, broad-except, protected-access\ndef _unique(session, cls, hashfunc, queryfunc, constructor, args, kwargs):\n cache = getattr(session, '_unique_cache', None)\n cls_name = cls.__name__\n if cache is None:\n session._unique_cache = cache = {}\n logger.debug('_unique created session cache')\n key = (cls, hashfunc(*args, **kwargs))\n if key in cache:\n logger.debug('_unique key %s found in session cache', key)\n return cache[key]\n else:\n logger.debug('_unique key %s not found in session cache', key)\n with session.no_autoflush:\n q = session.query(cls)\n q = queryfunc(q, *args, **kwargs)\n logger.debug('_unique query %s', q)\n obj = q.one_or_none()\n if not obj:\n logger.debug('_unique query found no existing %s instance',\n cls_name)\n obj = constructor(*args, **kwargs)\n\n # prevent race condition by using savepoint (begin_nested)\n session.begin(subtransactions=True)\n logger.debug('_unique beginning nested transaction')\n try:\n logger.debug(\n '_unique while in nested transaction: attempting to create %s',\n obj)\n session.add(obj)\n session.commit()\n logger.debug(\n '_unique while in nested transaction: created %s', obj)\n except IntegrityError as e:\n logger.debug(\n '_unique IntegrityError while creating %s instance',\n cls_name)\n session.rollback()\n logger.debug(\n '_unique while handling IntegrityError: rollback transaction'\n )\n q = session.query(cls)\n q = queryfunc(q, *args, **kwargs)\n obj = q.one()\n logger.debug(\n '_unique while handling IntegrityError: query found %s',\n obj)\n except Exception as e:\n logger.error('_unique error creating %s instance: %s',\n cls_name, e)\n raise e\n else:\n logger.debug('_unique %s instance created', cls_name)\n else:\n logger.debug('_unique query found existing %s instance',\n cls_name)\n cache[key] = obj\n return obj\n\n\nclass UniqueMixin(object):\n\n @classmethod\n def unique_hash(cls, *arg, **kw):\n raise NotImplementedError()\n\n @classmethod\n def unique_filter(cls, query, *arg, **kw):\n raise NotImplementedError()\n\n @classmethod\n def as_unique(cls, session, *arg, **kw):\n return _unique(session, cls, cls.unique_hash, cls.unique_filter, cls,\n arg, kw)\n\n\ndef dump_tags(tree, tag):\n return tree.findall('.//%s' % tag)\n\n\n# Testing / Dev helper funtions\ndef gzblocks_gen(filename):\n import gzip\n with gzip.open(filename, mode='rt', encoding='utf8') as f:\n for block in f.readlines():\n yield block\n\n\ndef gzblocks(filename):\n import gzip\n with gzip.open(filename, mode='rt', encoding='utf8') as f:\n return f.readlines()\n\n\ndef random_blocks(blocks, size=1000):\n import random\n return random.sample(blocks, size)\n\n\ndef new_session(session=None, session_factory=None):\n session = session or session_factory()\n session.rollback()\n session.close_all()\n return session_factory()\n\n\ndef filter_tables(metadata, table_names):\n filtered = [t for t in metadata.sorted_tables if t.name not in table_names]\n return filtered\n\n\ndef reset_tables(engine, metadata, exclude_tables=None):\n exclude_tables = exclude_tables or tuple()\n for table in exclude_tables:\n if table not in [tbl.name for tbl in metadata.tables]:\n raise ValueError(\n 'excluding non-existent table %s, is this a typo?', table)\n drop_tables = filter_tables(metadata, exclude_tables)\n try:\n metadata.drop_all(bind=engine, tables=drop_tables)\n except Exception as e:\n logger.error(e)\n metadata.create_all(bind=engine)\n\n\ndef is_duplicate_entry_error(error):\n code, msg = error.orig.args\n msg = msg.lower()\n return all([code == 1062, \"duplicate entry\" in msg])\n\n\n# pylint: disable=too-many-branches, too-many-statements\n@contextmanager\ndef session_scope(session=None,\n session_factory=None,\n bind=None,\n close=False,\n expunge=False,\n _raise=False):\n \"\"\"Provide a transactional scope around a series of db operations.\"\"\"\n\n # configure and create new session if none exists\n\n if not session:\n if bind:\n logger.debug(\n 'configuring session factory before creating new session')\n session_factory.configure(bind)\n logger.debug('creating new session')\n session = session_factory()\n\n logger.debug('initial session.info: %s', session.info)\n logger.debug('initial session.dirty count: %s', len(session.dirty))\n logger.debug('initial session.new count: %s', len(session.new))\n logger.debug('initial session.is_active: %s', session.is_active)\n logger.debug('initial sesssion.transaction.parent: %s',\n session.transaction.parent)\n # rollback passed session if required\n if not session.is_active:\n logger.debug('rolling back passed session')\n session.rollback()\n logger.debug('after rollback session.dirty count: %s',\n len(session.dirty))\n logger.debug('after rollback session.new count: %s', len(session.new))\n try:\n session.info['err'] = None\n session.begin(subtransactions=True)\n yield session\n logger.debug('after yield session.dirty count: %s', len(session.dirty))\n logger.debug('after yield session.new count: %s', len(session.new))\n session.commit()\n except IntegrityError as e:\n session.rollback()\n session.info['err'] = e\n if is_duplicate_entry_error(e):\n logger.debug('duplicate entry error caught')\n else:\n logger.exception('non-duplicate IntegrityError, unable to commit')\n if _raise:\n raise e\n except Exception as e:\n session.rollback()\n session.info['err'] = e\n logger.exception('unable to commit')\n if _raise:\n raise e\n finally:\n logger.debug('final session.info: %s', session.info)\n logger.debug('final session.dirty count: %s', len(session.dirty))\n logger.debug('final session.new count: %s', len(session.new))\n logger.debug('final session.is_active: %s', session.is_active)\n if close:\n logger.debug('calling session.close')\n session.close()\n elif expunge:\n logger.debug('calling session.expunge_all')\n session.expunge_all()\n if not session.is_active:\n logger.debug('second session.rollback required')\n session.rollback()\n\n\ndef row_to_json(row):\n return sbds.json.dumps(dict(row.items()))\n\n\nEngineConfig = namedtuple('EngineConfig',\n ['database_url', 'url', 'engine_kwargs', 'engine'])\n\n\ndef configure_engine(database_url, **kwargs):\n if kwargs:\n base_engine_kwargs = kwargs\n else:\n base_engine_kwargs = dict()\n\n url = make_url(database_url)\n logger.debug('configuring engine using %s', url.__repr__())\n backend = url.get_backend_name()\n\n if backend == 'sqlite':\n logger.debug('configuring sqlite backend')\n engine_kwargs = base_engine_kwargs\n if backend == 'mysql':\n logger.debug('configuring mysql backend')\n if 'charset' not in url.query:\n logger.debug('adding `charset=utf8mb4` to mysql engine config')\n url.query.update(charset='utf8mb4')\n\n engine_kwargs = base_engine_kwargs\n engine_kwargs.update(server_side_cursors=True, encoding='utf8')\n else:\n logger.debug('configuring %s backend', backend)\n engine_kwargs = base_engine_kwargs\n logger.debug('engine_kwargs: %s', engine_kwargs)\n\n engine = create_engine(url, **engine_kwargs)\n return EngineConfig(database_url, url, engine_kwargs, engine)\n\n\ndef configure_isolated_engine(database_url, **kwargs):\n if kwargs:\n kwargs.pop('poolclass', None)\n return configure_engine(database_url, poolclass=NullPool, **kwargs)\n\n\n@contextmanager\ndef isolated_engine(database_url, **kwargs):\n engine_config = configure_isolated_engine(database_url, **kwargs)\n engine = engine_config.engine\n try:\n yield engine\n except Exception as e:\n logger.info(e)\n finally:\n del engine_config\n engine.dispose()\n\n\ndef get_db_processes(database_url, **kwargs):\n with isolated_engine(database_url, **kwargs) as engine:\n if engine.url.get_backend_name() != 'mysql':\n raise TypeError('unsupported function for %s database' %\n engine.url.get_backend_name())\n return engine.execute('SHOW PROCESSLIST')\n\n\ndef kill_db_processes(database_url, db_name=None, db_user_name=None):\n processes = get_db_processes(database_url)\n\n all_procs = []\n killed_procs = []\n with isolated_engine(database_url) as engine:\n for process in processes:\n logger.debug(\n 'process: Id:%s User:%s db:%s Command:%s State:%s Info:%s',\n process.Id, process.User, process.db, process.Command,\n process.State, process.Info)\n all_procs.append(process)\n if process.db == db_name and process.User == db_user_name:\n if process.Info != 'SHOW PROCESSLIST':\n logger.debug('killing process %s on db %s owned by %s',\n process.Id, process.db, process.User)\n\n engine.execute('KILL %s' % process.Id)\n killed_procs.append(process)\n return all_procs, killed_procs\n","sub_path":"sbds/storages/db/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"164222096","text":"# this files overloads most of ../../framework/python/icf/config.py, if interested in a specific setting not found below please look the included file\n## Calo and PF jet exchange is NOT just a matter of changing the Jet collection. CALO and PF treat muons in jets differntly, you have to look at the x-cleaning parameters. Also the residual corrections (if applied) do have to be changed !!!\n\nimport setupSUSY\nfrom libFrameworkSUSY import *\nfrom copy import deepcopy\nfrom icf.core import PSet,Analysis\nfrom icf.config import defaultConfig\nimport icf.utils as utils\n\n#q2_scales = [\"2.0\",\"0.5\",\"1.0\"]\nq2_scales = [\"1.0\"]\n\nconf=defaultConfig.copy()\nconf.Common.Jets.PtCut = 40.0\nconf.Common.Jets.EtaCut = 2.4\nconf.Common.Jets.TightID=False\nconf.Common.Jets.ApplyID=False\n# muons\nconf.Common.Muons.EtaCut = 2.1\nconf.Common.Muons.PtCut = 20.0\nconf.Common.Muons.TrkIsoCut=999999.\nconf.Common.Muons.CombIsoCut=0.1\nconf.Common.Muons.TightID=False\nconf.Common.Muons.ApplyID=False\n# electrons\nconf.Common.Electrons.PtCut = 15.0 #it was 15 put it so again\nconf.Common.Electrons.EtaCut = 2.5\nconf.Common.Electrons.TrkIsoCut=5.\nconf.Common.Electrons.CombIsoCut=0.15\nconf.Common.Electrons.TightID=False\nconf.Common.Electrons.ApplyID=False\n# photons\nconf.Common.Photons.EtCut = 25.0\nconf.Common.Photons.EtaCut = 2.5\nconf.Common.Photons.TrkIsoRel=0.\nconf.Common.Photons.TrkIsoCut=99999.\nconf.Common.Photons.EcalIsoRel=0.\nconf.Common.Photons.EcalIsoCut=99999.\nconf.Common.Photons.HcalIsoRel=0.\nconf.Common.Photons.HcalIsoCut=99999.\nconf.Common.Photons.HadOverEmCut=0.5\nconf.Common.Photons.SigmaIetaIetaCut=0.5\n#conf.Common.Photons.CaloIsoCut=0.2\nconf.Common.Photons.IDReq=2\nconf.Common.ApplyXCleaning=False\n# If you use calo jets be aware that muons in jets ARE not added to the jet. For PFjets they are already in the jets, to steer the xcleaning, do default_cc = deepcopy(defaultConfig.XCleaning) and overload stuff\n\nconf.Ntuple.Weight=\"User\"\nconf.Ntuple.Electrons.Prefix=\"electron\"\nconf.Ntuple.Electrons.Suffix=\"Pat\"\nconf.Ntuple.Electrons.LooseID=\"EIDLoose\"\nconf.Ntuple.Electrons.TightID=\"EIDTight\"\nconf.Ntuple.Muons.Prefix=\"muon\"\nconf.Ntuple.Muons.Suffix=\"Pat\"\nconf.Ntuple.Muons.LooseID=\"IsGlobalMuon\"\nconf.Ntuple.Muons.TightID=\"IDGlobalMuonPromptTight\"\nconf.Ntuple.Jets.Prefix=\"ak5JetPF\"\n# if you switch to CaloJets, check that care about how muons are added to jets. Read also comment at top of page\nconf.Ntuple.Jets.Suffix=\"Pat\"\nconf.Ntuple.Jets.Uncorrected=False\nconf.Ntuple.Jets.UseGenJets=False\nconf.Ntuple.SecMuons.Prefix=\"muon\"\nconf.Ntuple.SecMuons.Suffix=\"PF\"\nconf.Ntuple.TerJets.Prefix=\"ak5JetPF2PAT\"\nconf.Ntuple.TerJets.Suffix=\"Pat\"\n\n# note that these corrections are presumably outdated once you read this!!!\nfrom icf.JetCorrections import *\n#corPset = CorrectionPset(\"ResidualJetEnergyCorrections.txt\") # Calo Jets (pre CMSSW_4_1_X)\ncorPset = CorrectionPset(\"Spring10DataV2_L2L3Residual_AK5PF.txt\") # PF Jets (pre CMSSW_4_1_X)\n\n## lepton definitions ######\n## Muon definition\nMus = PSet(\n MuID = \"Tight\",\n MinPt = 20.,\n MaxEta = 2.1,\n MaxIsolation = 0.1,\n DRMuJet = 0.3,\n MaxGlbTrkDxy = 0.02,\n MinGlbTrkNumOfValidHits = 11,\n SegMatch2GlbMu = 1,\n PixelHitsOnInrTrk = 1,\n MaxInrTrkDz = 1.\n )\n\n\n## Electron definition\nimport wpol.electron_id as eid\nid_sig = eid.eff_80\n\nEls_Sig = PSet(\n Cuts = id_sig,\n PtMin = 20.,\n Isolation = 1,\n HoverE = 1,\n DeltaEtaAtVtx = 1,\n DeltaPhiAtVtx = 1,\n SigmaIEtaIEta = 1,\n Conversions = 1,\n ConversionsExtra = 1,\n SupressErrors = True,\n D0BS = 0.02\n )\n\n# Anti-selection electron ID\n# The convention below is\n# 1 -> apply criterion\n# 0 -> invert criterion\n# -1 -> ignore criterion\n\nid_qcd = eid.eff_custom\n\nEls_QCD = PSet(\n Cuts = id_qcd,\n PtMin = 20.,\n # Apply Isolation and HoE cuts\n Isolation = 1,\n HoverE = 1,\n # Invert DeltaEta/DeltaPhi\n DeltaEtaAtVtx = 0,\n DeltaPhiAtVtx = 0,\n # Ignore the rest\n SigmaIEtaIEta = -1,\n Conversions = -1,\n ConversionsExtra = -1,\n SupressErrors = True,\n d0dzCutApplied = False,\n DetaOrDphi = True,\n D0BS = 0.02\n )\n\n\nid_veto = eid.eff_95\n\nEls_Veto = PSet(\n Cuts = id_veto,\n PtMin = 15.,\n Isolation = 1,\n HoverE = 1,\n DeltaEtaAtVtx = 1,\n DeltaPhiAtVtx = 1,\n SigmaIEtaIEta = 1,\n Conversions = 1,\n ConversionsExtra = 1,\n SupressErrors = 1,\n D0BS = 0.1\n )\n\n","sub_path":"onelepton/scripts/onelepton_settings.py","file_name":"onelepton_settings.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"255769123","text":"\n# -*- coding: utf-8 -*-\n\nfrom odoo import api, fields, models\nfrom datetime import date, timedelta, datetime\nfrom odoo.exceptions import ValidationError\nfrom odoo.exceptions import Warning\n\n\nclass DiGenTarWiz(models.TransientModel):\n _name = \"di.gen.tar.wiz\"\n _description = \"Wizard de génération de Tarifs de vente\"\n \n di_tarif_orig_id = fields.Many2one(\"di.code.tarif\", string=\"Code tarif origine\", required=True)\n di_date_effet_orig = fields.Date(string=\"Date d'effet\", required=True)\n di_date_effet = fields.Date(string=\"Date d'effet\", required=True)\n di_date_fin = fields.Date(string=\"Date de fin\")\n di_tarifs_dest_ids = fields.Many2many(\"di.code.tarif\")\n \n @api.multi\n def generer_tarifs(self):\n # parcours des codes tarifs destinationsélectionnés\n for tarifdest in self.di_tarifs_dest_ids:\n if tarifdest.id != self.di_tarif_orig_id.id: # on vérifie que le code tarif destination n'est pas le tarif d'origine\n for tarif_origine in self.env[\"di.tarifs\"].search(['&',('di_code_tarif_id', '=', self.di_tarif_orig_id.id),('di_date_effet','=',self.di_date_effet_orig)]): \n #parcours de tarifs origine correspondants au code tarif et à la date d'effet sélectionnée \n #chargement des données du nouveau tarif \n data = {\n 'di_product_id': tarif_origine.di_product_id.id,\n 'di_code_tarif_id': tarifdest.id,\n 'di_partner_id': tarif_origine.di_partner_id.id,\n 'di_un_prix': tarif_origine.di_un_prix,\n 'di_type_colis_id': tarif_origine.di_type_colis_id.id,\n 'di_type_palette_id': tarif_origine.di_type_palette_id.id,\n 'di_prix': tarif_origine.di_prix * tarifdest.di_coef,\n 'di_qte_seuil': tarif_origine.di_qte_seuil,\n 'di_date_effet': self.di_date_effet,\n 'di_date_fin': self.di_date_fin \n } \n #recherche si tarif existant \n tarif_existant = self.env[\"di.tarifs\"].search(['&',('di_code_tarif_id', '=', tarifdest.id),\n ('di_date_effet','=',self.di_date_effet),\n ('di_company_id','=',self.env.user.company_id.id),\n ('di_product_id','=',tarif_origine.di_product_id.id),\n ('di_partner_id','=',tarif_origine.di_partner_id.id), \n ('di_un_prix','=',tarif_origine.di_un_prix),\n ('di_type_colis_id','=', tarif_origine.di_type_colis_id.id),\n ('di_type_palette_id','=', tarif_origine.di_type_palette_id.id),\n ('di_qte_seuil','=',tarif_origine.di_qte_seuil)\n ])\n \n if tarif_existant:\n # si il existe, on le met à jour\n tarif_existant.update(data) \n else:\n #sinon on le créé\n self.env[\"di.tarifs\"].create(data) \n # raise Warning(\"Traitement terminé\") \n return self.env['di.popup.wiz'].afficher_message(\"Traitement terminé.\",True,False,False,False) \n \n \n @api.model\n def default_get(self, fields):\n res = super(DiGenTarWiz, self).default_get(fields) \n if self.env.context.get('active_model'): # on vérifie si on est dans un model\n active_model=self.env.context['active_model'] #récup du model courant\n else:\n active_model=''\n if active_model : \n if active_model == 'di.code.tarif': # si lancé à partir des codes tarifs\n tarif_id = self.env.context[\"active_id\"]\n Tarif = self.env[\"di.code.tarif\"].browse(tarif_id)\n res[\"di_tarif_orig_id\"] = Tarif.id\n elif active_model=='di.tarifs': # si lancé à partir des tarifs\n tarif_id = self.env.context[\"active_id\"]\n Tarif = self.env[\"di.tarifs\"].browse(tarif_id)\n res[\"di_tarif_orig_id\"] = Tarif.di_code_tarif_id.id \n res[\"di_date_effet_orig\"] = Tarif.di_date_effet\n res[\"di_date_effet\"] = Tarif.di_date_effet\n res[\"di_date_fin\"] = Tarif.di_date_fin \n else: # lancé à partir du menu\n res[\"di_date_effet_orig\"] = datetime.today() # je charge la date à aujourd'hui car si rien n'est envoyé, le wizard ne s'ouvre pas \n return res ","sub_path":"addons_gesprim/difodoo_fichiers_base/wizard/di_generer_tarifs_wizard.py","file_name":"di_generer_tarifs_wizard.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"355458367","text":"#!/usr/bin/env python\n\n# Copyright (c) 2019 Computer Vision Center (CVC) at the Universitat Autonoma de\n# Barcelona (UAB).\n#\n# This work is licensed under the terms of the MIT license.\n# For a copy, see .\n\"\"\"This file does the following:\n1. Create a World and a client\n2. Spawn an actor (vehicle)\n3. Attach a camera to the vehicles\n4. Spawn 10 more vehicles\n5. Destroy them All\n\"\"\"\n\n\nimport glob # Header file for pattern matching\nimport os # Header file to use Operating system dependent functionality\nimport sys # Header file for Python to interact with the host system\n\ntry: # Exception catcher for Python try this else pass\n sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (\n sys.version_info.major,\n sys.version_info.minor,\n 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])\nexcept IndexError: # If you get an exception of an Index error you do nothing\n pass\n\nimport carla # Header file for importing carla modules\n# Classes available under carla module can be found here: https://carla.readthedocs.io/en/latest/python_api/\nimport random # Header file for randomly choosing objects\nimport time # Header file for sleep\n\n\ndef main():\n actor_list = [] # Empty list to host various actors\n\n # In this tutorial script, we are going to add a vehicle to the simulation\n # and let it drive in autopilot. We will also create a camera attached to\n # that vehicle, and save all the images generated by the camera to disk.\n\n try:\n # First of all, we need to create the client that will send the requests\n # to the simulator. Here we'll assume the simulator is accepting\n # requests in the localhost(IP address) at port 2000.\n client = carla.Client('localhost', 2000) # This is a class offering various methods\n client.set_timeout(2.0) # Avoiding blocking of networking operations\n\n # Once we have a client we can retrieve the world that is currently\n # running.\n world = client.get_world() # Get the world currently active in the simulation.\n # -- Return: carla.World\n\n\n # The world contains the list blueprints that we can use for adding new\n # actors into the simulation.\n blueprint_library = world.get_blueprint_library()\n #get_blueprint_library(self)\n #Return the list of blueprints available in this world. These blueprints can be used to spawn actors into the world.\n # -- Return: carla.BlueprintLibrary\n\n\n # Now let's filter all the blueprints of type 'vehicle' and choose one\n # at random.\n bp = random.choice(blueprint_library.filter('vehicle'))\n # filter(self, wildcard_pattern)\n #Filters a list of ActorBlueprint with id or tags matching wildcard_pattern. The pattern is matched against each blueprint's id and tags.\n # -- Return: carla.BlueprintLibrary\n\n # A blueprint contains the list of attributes that define a vehicle's\n # instance, we can read them and modify some of them. For instance,\n # let's randomize its color.\n if bp.has_attribute('color'): # Because we had filtered vehicle blueprint\n color = random.choice(bp.get_attribute('color').recommended_values)\n # get_attribute(self, id)\n # Returns the current actor attribute through its id.\n # Return: carla.ActorAttribute\n bp.set_attribute('color', color) # Sets an existing attribute to the actor's blueprint.\n\n # Now we need to give an initial transform to the vehicle. We choose a\n # random transform from the list of recommended spawn points of the map.\n \"\"\"carla.Transform class\n Class that defines a transformation without scaling.\n \"\"\"\n transform = random.choice(world.get_map().get_spawn_points())\n # get_map() returns carla.Maphttps://www.hongkiat.com/blog/manage-git-github-atom/\n # get_spawn_points returns Return: list(carla.Transform)\n\n\n # So let's tell the world to spawn the vehicle.\n vehicle = world.spawn_actor(bp, transform)\n # Spawn an actor into the world based on the blueprint provided at transform. If a parent is provided, the actor is attached to parent.\n # Return: carla.Actor\n\n # It is important to note that the actors we create won't be destroyed\n # unless we call their \"destroy\" function. If we fail to call \"destroy\"\n # they will stay in the simulation even after we quit the Python script.\n # For that reason, we are storing all the actors we create so we can\n # destroy them afterwards.\n actor_list.append(vehicle) # Append carla.Actor to an epty list\n print('created %s' % vehicle.type_id)\n\n # Let's put the vehicle to drive around.\n vehicle.set_autopilot(True)\n\n # Let's add now a \"depth\" camera attached to the vehicle. Note that the\n # transform we give here is now relative to the vehicle.\n camera_bp = blueprint_library.find('sensor.camera.semantic_segmentation')\n camera_bp.set_attribute('image_size_x', '1920')\n camera_bp.set_attribute('image_size_y', '1080')\n camera_bp.set_attribute('fov', '110')\n camera_transform = carla.Transform(carla.Location(x=-3, z=10.0)) #1.5, 2.4\n camera = world.spawn_actor(camera_bp, camera_transform, attach_to=vehicle)\n actor_list.append(camera)\n print('created %s' % camera.type_id)\n\n # Now we register the function that will be called each time the sensor\n # receives an image. In this example we are saving the image to disk\n # converting the pixels to gray-scale.\n cc = carla.ColorConverter.CityScapesPalette\n camera.listen(lambda image: image.save_to_disk('_out/%06d.png' % image.frame, cc))\n\n # Oh wait, I don't like the location we gave to the vehicle, I'm going\n # to move it a bit forward.\n location = vehicle.get_location()\n location.x += 40\n vehicle.set_location(location)\n print('moved vehicle to %s' % location)\n\n # But the city now is probably quite empty, let's add a few more\n # vehicles.\n transform.location += carla.Location(x=40, y=-3.2)\n transform.rotation.yaw = -180.0\n for _ in range(0, 10):\n transform.location.x += 8.0\n\n bp = random.choice(blueprint_library.filter('vehicle'))\n\n # This time we are using try_spawn_actor. If the spot is already\n # occupied by another object, the function will return None.\n npc = world.try_spawn_actor(bp, transform)\n if npc is not None:\n actor_list.append(npc)\n npc.set_autopilot()\n print('created %s' % npc.type_id)\n\n time.sleep(10)\n\n finally:\n\n print('destroying actors')\n for actor in actor_list:\n actor.destroy()\n print('done.')\n\n\nif __name__ == '__main__':\n\n main()\n","sub_path":"PythonAPI/examples/tutorial.py","file_name":"tutorial.py","file_ext":"py","file_size_in_byte":7129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"568827892","text":"\"\"\"\n改变类的实例对象在print()等方法下的输出\n\n通过定义类的__str__()方法和__repr__()方法,如果没有定义__str__()方法,\n 会转而调用__repr__()方法进行替代,所以最好至少定义一个__repr__()\n\n__str__():将实例转换成字符串,是str()方法和print()方法的输出\n__repr__():是实例的代码展示,通常和创建一个类的实例对象所需要编写的代码相同\n 比如说你创建一个对象是Person('Jack'),\n 你的__repr__()方法的返回值最好也如此定义\n\n\n\"\"\"\n\n\nclass Pair:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __repr__(self):\n # '!r'是指定x属性使用x属性的类中定义的__repr__()方法的格式进行输出\n return 'Pair({0.x!r}, {0.y!r})'.format(self)\n\n def __str__(self):\n # '!s'是指定x属性使用x属性的类中定义的__str__()方法的格式进行输出\n return '({0.x!s}, {0.y!s})'.format(self)\n\n\np = Pair(3, 4)\n# print()和str()方法根据__str__()进行输出\nprint(p, str(p))\n# repr()方法会根据__repr__()方法输出\nprint(repr(p))\n\n# 验证'!r', '!s'的作用:\nprint('p is {!r}'.format(p)) # 输出p is Pair(3, 4)\nprint('p is {!s}'.format(p)) # 输出p is (3, 4)\n\np1 = Pair(3, 4)\np2 = p\n# 两个对象的相等判定的是指针是否相等,输出:False True\nprint(p == p1, p == p2)\n# eval()方法的作用是将参数字符串作为代码运行,然后获取其返回值,这里是生成了一个Pair(3, 4),\n# 但是由于对象的'=='判定是基于引用的,所以不相等,输出:False\nprint(eval(repr(p)) == p)\nx = 3\n# 基本类型的相等可以用'=='来进行判定,输出:True\nprint(eval(repr(x)) == x)\n\ny = [1, 2]\nz = [1, 2]\n# 内置容器类型的相等也可以用'=='来进行判定,输出:True True\nprint(eval(repr(y)) == y, y == z)\ndel y[0]\n# 并且一个容器变动了,另外的容器不会受到影响,输出:[2] [1, 2]\nprint(y, z)\n\n# 对于无法用__repr__()和__str__()进行展示的类,比如generator,通常使用'<...>'进行代替,比如\nf = open('cls_obj_8_1_the_tostring_method.py')\n# 输出<_io.TextIOWrapper name='cls_obj_8_1_the_tostring_method.py' mode='r' encoding='UTF-8'>\nprint('{!r}'.format(f))\nf.close()\n","sub_path":"class_obj_8/cls_obj_8_1_the_tostring_method.py","file_name":"cls_obj_8_1_the_tostring_method.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"180206074","text":"def mergeSort(arr,cal):\n if len(arr) >1:\n mid = len(arr)//2\n L = arr[:mid]\n R = arr[mid:]\n mergeSort(L,cal)\n mergeSort(R,cal)\n \n i = j = k = 0\n while i < len(L) and j < len(R):\n if cal[L[i][1]] < cal[R[j][1]]:\n arr[k] = L[i]\n i+=1\n elif cal[L[i][1]] == cal[R[j][1]] and L[i][0] < R[j][0]:\n arr[k] = L[i]\n i+=1\n else:\n arr[k] = R[j]\n j+=1\n k+=1\n\n while i < len(L):\n arr[k] = L[i]\n i+=1\n k+=1\n while j < len(R): \n arr[k] = R[j] \n j+=1\n k+=1\n\ncal = {\"común\":1, \"especial\":2, \"épica\":3, \"legendaria\":4}\n\ncards = []\n\nfor i in range(int(input())):\n cards.append(input().split())\n\nmergeSort(cards,cal)\n\nfor i in cards:\n print(i)\n\n\n'''\n14\ngolem épica\nmegaesbirro especial\nverdugo épica\nesqueletos común\nbruja épica\nbolaDeFuego especial\ncaballero común\nballesta épica\nprincesa legendaria\ntornado épica\nmontapuercos especial\nbárbaros común\nveneno épica\nleñador legendaria\n\nbárbaros\ncaballero\nesqueletos\nbolaDeFuego\nmegaesbirro\nmontapuercos\nballesta\nbruja\ngolem\ntornado\nveneno\nverdugo\nleñador\nprincesa\n'''","sub_path":"ago-dic-2019/Jose Fernando Perez Arroyo/OrdinarioCorregido/problema2ordi.py","file_name":"problema2ordi.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"137431469","text":"from MTADelayPredict.utils.utils import grouper, gtfs_datetime\nfrom MTADelayPredict.data_processing.merged_entity import MergedEntity\nimport pandas as pd\n\n# Load in the protobuf APIs\ntry:\n import MTADelayPredict.protobuf.nyct_subway_pb2 as nyct_subway_pb2\nexcept ImportError:\n raise ImportError('nyct_subway_pb2 not found, make sure protobuf is compiled, see DataExploration.ipynb')\ntry:\n import MTADelayPredict.protobuf.gtfs_realtime_pb2 as gtfs_realtime_pb2\nexcept ImportError:\n raise ImportError('gtfs_realtime_pb2 not found, make sure protobuf is compiled, see DataExploration.ipynb')\n \n# There is a problem where the vehicle entites don't provide an easily discernable stop name, just an ID\n# However, the entities are paired up in as trip_entity and vehicle entity\n# We can just iterate through the entities in groups of 2, and we always know what stop we are actually stopped at\n\n# TODO: Examine cases where this isn't well broken up into trip_update/vehicle pairings, maybe there are some other fun messages there\ndef get_entities(msg, verbose=False):\n for trip_entity,vehicle_entity in grouper(msg.entity, 2):\n \n try:\n assert trip_entity.HasField('trip_update')\n assert vehicle_entity.HasField('vehicle')\n assert trip_entity.trip_update.trip.trip_id == vehicle_entity.vehicle.trip.trip_id\n except Exception as e:\n if verbose:\n print(\"Skipping entity pairing @ {}\".format(pd.to_datetime(msg.header.timestamp, unit='s', utc=True).tz_convert('US/Eastern')))\n continue \n \n yield(MergedEntity(trip_entity, vehicle_entity))\n \ndef build_stop_id_index(data_dir, stop_filter='*'):\n try:\n stop_ids = pd.read_csv(data_dir+'/google_transit/stops.txt')\n return pd.Index(stop_ids[stop_ids['stop_id'].str.match(stop_filter)]['stop_id'], name='stop_id')\n except:\n raise Exception(\"stops.txt not found, Requires MTA Google transit files downloaded and extracted from http://web.mta.info/developers/data/nyct/subway/google_transit.zip to /google_transit\")\n \n\n\nclass GTFSLoader: \n \"\"\"\n Class to iterate through gtfs files across a date range for a given train_line, loading and parsing\n \"\"\"\n def __init__(self, data_dir, train_line):\n \"\"\"\n data_dir: Toplevel directory containing the date directory tree of gtfs files\n data_dir is expected to be a directory formatted like so:\n 201901/\n 20190101/\n \n 201902/\n ...\n \n train_line: specify which train line to use, such as nqrw, j etc...\n e.g. gtfs_nqrw_20181209_064712.gtfs would have \"nqrw\" as the train_line\n \"\"\"\n from collections import defaultdict\n import os\n\n if not os.path.isdir(data_dir):\n raise ValueError(\"data_dir {} does not exist, cannot load gtfs files\".format(data_dir))\n\n self.data_dir = data_dir\n self.train_line = train_line\n\n self.stopped_at_df = pd.DataFrame()\n self.next_train_df = pd.DataFrame()\n self.next_scheduled_arrival_df = pd.DataFrame()\n \n def list_files(self, start_date, end_date):\n \"\"\"\n Helper to enumerate all file paths for a date range\n \"\"\"\n import glob\n import os\n \n drange = pd.date_range(start_date, end_date, freq='D')\n \n file_list = []\n \n for date in drange:\n yyyymm = str(date.year * 100 + date.month)\n yyyymmdd = str(date.year * 10000 + date.month * 100 + date.day)\n filename = 'gtfs_{}_{}_*.gtfs'.format(self.train_line, yyyymmdd)\n gtfs_dir = os.path.join(self.data_dir, yyyymm, yyyymmdd)\n daily_files = glob.glob( os.path.join(gtfs_dir,filename))\n daily_files = [f for f in daily_files if (start_date <= gtfs_datetime(os.path.basename(f)) <= end_date)]\n# if len(daily_files) == 0:\n# print(\"WARNING: no files found for {} in {}\".format(yyyymmdd, os.path.join(self.data_dir, yyyymm, yyyymmdd, filename)))\n file_list += daily_files\n \n return file_list\n\n def load_range(self, start_date, end_date, stop_filter='.*', route_filter='.*', verbose=False, schedule=False):\n \"\"\"\n Load files for a given date range and return the resulting dataframe.\n This new data replaces any existing loaded data.\n \n If verbose, it will display a progress bar\n \"\"\"\n import re\n import os\n import google.protobuf.message as message\n import numpy as np\n from collections import defaultdict\n from collections import OrderedDict\n\n from MTADelayPredict.subway_line import N_STOP_LIST\n\n start_min = (start_date - pd.Timestamp(\"1970-01-01\").tz_localize('UTC').astimezone('US/Eastern')) // pd.Timedelta('1s') // 60\n end_min = (end_date - pd.Timestamp(\"1970-01-01\").tz_localize('UTC').astimezone('US/Eastern')) // pd.Timedelta('1s') // 60\n # Add a few minutes, since sometimes we get updates from the futures\n print(end_min)\n end_min += 120\n print(end_min)\n stop_id_index = N_STOP_LIST\n new_stop_ids = set()\n stop_id_dict = {s:i for i,s in enumerate(stop_id_index)}\n stopped_at_np = np.zeros((end_min-start_min, len(stop_id_index)))\n stopped_at_np[:] = np.nan\n next_train_np = np.zeros((end_min-start_min, len(stop_id_index)))\n next_train_np[:] = np.nan\n\n # Keep track of when every train thinks it is going to arrive at each station\n def new_scheduled_arrival():\n next_scheduled_arrival_np = np.zeros((end_min-start_min, len(stop_id_index)))\n next_scheduled_arrival_np[:] = np.nan\n return next_scheduled_arrival_np\n train_schedule_np_dict = defaultdict(new_scheduled_arrival)\n \n if schedule:\n self.stop_dict = defaultdict(list)\n self.time_dict = defaultdict(list)\n\n\n if verbose:\n import progressbar\n \n # Get list of files\n gtfs_files = self.list_files(start_date, end_date)\n gtfs_files.sort()\n \n if verbose:\n widgets = [progressbar.Percentage(), progressbar.Bar(), progressbar.Variable('entries'), progressbar.Variable('decode_errors')]\n bar = progressbar.ProgressBar(widgets=widgets, max_value=len(gtfs_files), min_poll_interval=.4).start()\n fails = 0\n\n msg = gtfs_realtime_pb2.FeedMessage()\n\n for i,file in enumerate(gtfs_files):\n try:\n with open(os.path.join(file),'rb') as fh:\n msg.ParseFromString(fh.read())\n except message.DecodeError as e:\n # Sometimes there are decode errors, OK if we miss a few, just keep an eye on it\n fails+=1\n continue\n\n if verbose:\n bar.update(i+1, entries=self.stopped_at_df.shape[0], decode_errors=fails)\n\n for merged_entity in get_entities(msg):\n # Ignore late night wrapround into the next day\n if merged_entity.time_raw >= end_min or merged_entity.time_raw < 1:\n continue\n \n if not merged_entity.route_id or not re.match(route_filter, merged_entity.route_id):\n continue\n \n # If the train is specified as not assigned, don't bother processing\n if not merged_entity.is_assigned:\n continue\n \n # If the train is stopped at a station we're looking for, set that\n if merged_entity.is_stopped and merged_entity.is_stop_match(stop_filter, merged_entity.current_stop_id) and\\\n merged_entity.current_stop_id in stop_id_dict:\n time_idx = merged_entity.time_raw - start_min\n stop_idx = stop_id_dict.get(merged_entity.current_stop_id, -1)\n if stop_idx >= 0:\n self.stop_dict[merged_entity.train_id_str].append(merged_entity.current_stop_id)\n self.time_dict[merged_entity.train_id_str].append(merged_entity.current_stop_time.tz_convert('US/Eastern'))\n else:\n new_stop_ids.add(merged_entity.current_stop_id)\n\n next_scheduled_arrival_np = train_schedule_np_dict[merged_entity.train_id_str]\n time_idx = merged_entity.time_raw - start_min\n stop_idx = stop_id_dict.get(merged_entity.current_stop_id, -1)\n\n if stop_idx >= 0:\n next_scheduled_arrival_np[time_idx, stop_idx] = \\\n merged_entity.current_stop_time_raw\n else:\n new_stop_ids.add(merged_entity.current_stop_id)\n\n # Iterate through next stops and see when then next train is scheduled to arrive\n if merged_entity.n_upcoming_stops > 0:\n for upcoming_idx in range(merged_entity.n_upcoming_stops):\n if merged_entity.is_stop_match(stop_filter, merged_entity.upcoming_stop_id(upcoming_idx)):\n stop_idx = stop_id_dict.get(merged_entity.upcoming_stop_id(upcoming_idx), -1)\n\n if stop_idx >= 0:\n next_scheduled_arrival_np[time_idx, stop_idx] = \\\n merged_entity.upcoming_stop_time_raw(upcoming_idx)\n else:\n new_stop_ids.add(merged_entity.upcoming_stop_id(upcoming_idx))\n\n if verbose:\n bar.finish()\n print(\"New stops:\\n{}\".format(new_stop_ids))\n \n self.next_train_df = pd.DataFrame(next_train_np, index=range(start_min, end_min), columns=stop_id_index)\n\n self.next_train_df = self.next_train_df.sort_index()\n self.next_train_df.index = self.next_train_df.index.map(lambda x: pd.to_datetime(x, unit='m', utc=True)).tz_convert('US/Eastern')\n\n # Create a dataframe describing each train's expected arrival time at a given station\n self.train_schedule_dict = dict()\n for train_id, train_schedule_np in train_schedule_np_dict.items():\n train_schedule_df = pd.DataFrame(train_schedule_np, index=range(start_min, end_min), columns=stop_id_index)\n train_schedule_df = train_schedule_df.sort_index()\n self.train_schedule_dict[train_id] = train_schedule_df\n\n self.next_scheduled_arrival_df = pd.concat(self.train_schedule_dict.values(), axis=1,\n keys=self.train_schedule_dict.keys()).stack()\n\n\n# if schedule:\n# ret_dict['schedule_df'] = pd.DataFrame.from_dict(self.train_dict)\n\n return None\n\n\n\n","sub_path":"MTADelayPredict/data_processing/gtfs_loader.py","file_name":"gtfs_loader.py","file_ext":"py","file_size_in_byte":10918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"480678692","text":"\"\"\"\nПроверить наличие элемента в папке\nЗаданы:\nПуть с элементами\nПуть к элементу для проверки\n\"\"\"\n\ndef file_search(folder, file_path):\n for path in file_path:\n for element in folder:\n if path == element:\n i = 1\n break\n else:\n i = 0\n if i:\n print(\"OK\")\n else:\n print(\"Error\")\n\n\nfirst_folder = ['C:','r','backup.log','ideas.txt','hu5.txt']\nneeded_path = 'C:/r/ideas.txt'.split('/')\n\n\nfile_search(first_folder,needed_path)","sub_path":"danylenkoka/second/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"415019515","text":"def do_queens_beat_each_other(queens):\n '''Returns the conclusion if at least two queens beat each other.'''\n x = [queen[0] for queen in queens]\n y = [queen[1] for queen in queens]\n sums = [sum(queen) for queen in queens]\n diffs = [queen[1] - queen[0] for queen in queens]\n\n # If they are at the same line, they do\n if len(x) != len(set(x)) or len(y) != len(set(y)):\n return 'YES'\n # If they are at the same diagonals, they do\n elif len(sums) != len(set(sums)) or len(diffs) != len(set(diffs)):\n return 'YES'\n else:\n return 'NO'\n\nif __name__ == '__main__':\n\n queens = []\n for i in range(8):\n queens.append([int(c) for c in input().split()])\n print(do_queens_beat_each_other(queens))\n","sub_path":"lab_17/Task_4.py","file_name":"Task_4.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"633919844","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\nimport pymysql.cursors\n\nclass VilloDatabase:\n\t\"\"\"\n\tClasse qui gère l'interaction avec la base de donnée.\n\t\"\"\"\n\n\tdef __init__(self):\n\t\t\"\"\" Constructeur \"\"\"\n\t\tself.connection = pymysql.connect(host=\"localhost\",\n\t\t\t\t\t\t\t\t\t\tuser=\"villodb\",\n\t\t\t\t\t\t\t\t\t\tpasswd=\"villodb\",\n\t\t\t\t\t\t\t\t\t\tdb=\"villo\",\n\t\t\t\t\t\t\t\t\t\tcursorclass=pymysql.cursors.DictCursor)\n\n\tdef disconnect(self):\n\t\t\"\"\" Déconnecte de la base de donnée \"\"\"\n\t\tself.connection.close()\n\n\tdef checkAccount(self, id, passwd):\n\t\t\"\"\" Vérifie si le compte existe et que le mot de passe est bon \"\"\"\n\t\tsql = \"SELECT `uid` FROM `Utilisateur` WHERE `uid`=\"+str(id)+\" AND `MotDePasse`=\"+passwd+\" \"\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql)\n\t\tresult = cursor.fetchone()\n\t\tif result != None :\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef getStationNameList(self):\n\t\t\"\"\" Renvoie la liste de nom des stations \"\"\"\n\t\tsql = \"SELECT `Nom` FROM `Station` ORDER BY `Nom`\"\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql)\n\t\tresult = cursor.fetchall()\n\n\t\tnamelist = list()\n\t\tfor station in result:\n\t\t\tnamelist.append(station['Nom'])\n\t\treturn namelist\n\n\tdef isUserUsingVillo(self, uid):\n\t\t\"\"\" Vérifie si un utilisateur utilise un villo \"\"\"\n\t\tsql = \"SELECT `VID`,`DateDépart` FROM `Trajet` WHERE `UID`=\"+uid+\" AND `StationRetour` IS NULL\"\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql)\n\t\tresult = cursor.fetchall()\n\n\t\treturn len(result) == 1\n\n\tdef getUserHistory(self, uid):\n\t\t\"\"\" Renvoie l'historique des déplacement d'un utilisateur \"\"\"\n\n\t\tsql = \"SELECT t.DateDépart, t.DateRetour, s1.Nom, s2.Nom \\\n\t\t\tFROM `Trajet` t, `Station` s1, `Station` s2 \\\n\t\t\tWHERE t.UID = \"+str(uid)+\" \\\n\t\t\tAND t.StationDépart = s1.SID \\\n\t\t\tAND t.StationRetour = s2.SID \\\n\t\t\tAND t.StationRetour IS NOT NULL \\\n\t\t\tAND t.StationDépart IS NOT NULL \\\n\t\t\tORDER BY t.DateDépart DESC\"\n\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql)\n\t\tresult = cursor.fetchall()\n\n\t\thistory = list()\n\t\tfor r in result:\n\t\t\tstring = \"\"\n\t\t\t\"Départ: JJ/MM/AA hh:mm:ss - Station / Arrivée: JJ/MM/AA hh:mm:ss - Station\"\n\t\t\tstring += \"Départ: \"+str(r['DateDépart'])+\" - \" + r['Nom'] +\" / \"\n\t\t\tstring += \"Arrivée: \"+ str(r['DateRetour'])+\" - \" + r[\"s2.Nom\"]\n\t\t\thistory.append(string)\n\t\treturn history\n\n\tdef getVilloInStation(self, stationName,ignoreBroken=False):\n\t\t\"\"\" Renvoie la liste des villos dans une station \"\"\"\n\n\t\tsql1 = \"SELECT Trajet.VID, Trajet.DateDépart, Trajet.StationRetour FROM `Trajet`,\\\n\t\t\t\t(SELECT tr.VID as vid, max(tr.DateDépart) as dr FROM `Trajet` as tr GROUP BY tr.VID) as t\\\n\t\t\t\tWHERE Trajet.VID = t.vid \\\n\t\t\t\tAND Trajet.DateDépart = t.dr\\\n\t\t\t\tORDER BY Trajet.VID\"\n\n\t\tsql2 = \"SELECT r.VID \\\n\t\t\tFROM (\"+sql1+\") r, Station s \\\n\t\t\tWHERE r.StationRetour = s.SID \\\n\t\t\tAND s.Nom = \\\"\"+stationName+\"\\\" \"\n\n\n\t\tsql3 = \"SELECT v.VID, v.Modèle, v.EnEtat \\\n\t\t\tFROM (\"+sql2+\") res, Villo v \\\n\t\t\tWHERE res.VID = v.VID\"\n\n\t\tif ignoreBroken:\n\t\t\tsql3 += \" AND v.EnEtat = 1\"\n\t\t\n\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql3)\n\t\tresult = cursor.fetchall()\n\n\t\treturn result\n\n\tdef putVillo(self, uid, dateReturn, stationName):\n\t\t\"\"\" Rend un villo à la date et à la station passer en paramètre. \"\"\"\n\t\tcursor = self.connection.cursor()\n\n\t\tsql1 = \"SELECT `VID`,`DateDépart` FROM `Trajet` WHERE `UID`=\"+uid+\" AND `StationRetour` IS NULL\"\n\t\tcursor.execute(sql1)\n\t\ttrip = cursor.fetchone()\n\n\t\tsql2 = \"UPDATE `Trajet` \\\n\t\t\t\tSET `StationRetour` = (SELECT `SID` FROM `Station` WHERE `Nom`=\\\"\"+stationName+\"\\\" ), \\\n\t\t\t\t`DateRetour` = '\"+dateReturn+\"' \\\n\t\t\t\tWHERE `DateDépart` = '\"+str(trip['DateDépart'])+\"' \\\n\t\t\t\tAND `VID` = \"+str(trip['VID'])+\" \"\n\n\t\tcursor.execute(sql2)\n\t\tself.connection.commit()\n\n\tdef takeVillo(self, uid, stationName, dateStart, vid):\n\t\t\"\"\" Donner un villo. Provient de la station à la date pour l'utilisateur passer en paramètre. \"\"\"\n\t\tcursor = self.connection.cursor()\n\n\t\tsql1= \"SELECT `SID` FROM Station WHERE `Nom`=\\\"\"+stationName+\"\\\" \"\n\n\t\tcursor.execute(sql1)\n\n\t\tstation = cursor.fetchone()\n\n\t\tsql2 = \"INSERT INTO `Trajet` (`VID`,`DateDépart`,`UID`, `StationDépart`) \\\n\t\t\t\t\tVALUES (\"+str(vid)+\",'\"+str(dateStart)+\"',\"+str(uid)+\",\"+str(station['SID'])+\")\"\n\n\t\tcursor.execute(sql2)\n\t\tself.connection.commit()\n\n\tdef getVilloIDFromUser(self, uid):\n\t\t\"\"\" Renvoie l'id du Villo qu'utilise un utilisateur. \"\"\"\n\t\tsql = \"SELECT `VID` FROM `Trajet` WHERE `UID`=\"+uid+\" AND `StationRetour` IS NULL\"\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql)\n\t\tresult = cursor.fetchone()\n\n\t\treturn result['VID']\n\n\tdef signalProblem(self, vid):\n\t\t\"\"\" Signal un problème sur le villo passé en paramètre \"\"\"\n\t\tsql = \"UPDATE `Villo` \\\n\t\t\t\tSET `EnEtat` = 0 \\\n\t\t\t\tWHERE `VID`= \"+str(vid)+\" \"\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql)\n\t\tself.connection.commit()\n\n\tdef getNewUserID(self):\n\t\t\"\"\" Récupère un nouvel id Utilisateur \"\"\"\n\n\t\tsql = \"SELECT max(`UID`) as id FROM `Utilisateur`\"\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql)\n\t\tresult = cursor.fetchone()\n\t\t\n\t\treturn result['id']+1\n\n\tdef isRFIDfree(self,rfid):\n\t\t\"\"\" Vérifie si un RFID est libre \"\"\"\n\n\t\tsql = \"SELECT * FROM `Abonné` WHERE `RFID`=\"+str(rfid)+\" \"\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql)\n\t\tresult = cursor.fetchall()\n\n\t\treturn len(result) == 0\n\n\tdef createSubscriber(self,uid,rfid,passwd,name,phone,city,cp,street,number,card,dateSub,dateExp):\n\t\t\"\"\" Crée un utilisateur abonné \"\"\"\n\t\tsql = \"INSERT INTO `Utilisateur` (`UID`,`MotDePasse`,`CarteDeCredit`,`DateExpiration`) \\\n\t\tVALUES (\"+uid+\",\"+passwd+\",\"+card+\",'\"+dateExp+\"')\"\n\t\tself.connection.cursor().execute(sql)\n\t\tself.connection.commit()\n\n\t\tsql = \"INSERT INTO `Abonné` (`UID`,`RFID`,`Nom`,`Rue`,`Numéro`,`CodePostal`,`Ville`,`Téléphone`,`DateInscription`) \\\n\t\tVALUES (\"+uid+\",\"+rfid+\",\\\"\"+name+\"\\\",\\\"\"+street+\"\\\",\"+number+\",\"+cp+\",\\\"\"+city+\"\\\", \\\"\"+phone+\"\\\",'\"+dateSub+\"')\"\n\t\tself.connection.cursor().execute(sql)\n\t\tself.connection.commit()\n\n\tdef getUserExpiryDate(self, uid):\n\t\t\"\"\" Renvoie la date d'expiration d'un utilisateur \"\"\"\n\t\tsql = \"SELECT `DateExpiration` FROM `Utilisateur` WHERE `UID` = \"+str(uid)+\" \"\n\t\tcursor = self.connection.cursor()\n\t\tcursor.execute(sql)\n\t\tresult = cursor.fetchone()\n\t\tif result != None:\n\t\t\treturn result['DateExpiration']\n\t\telse:\n\t\t\treturn None\n\n\tdef getStationCapacity(self, stationName):\n\t\t\"\"\" Retourne la capacité d'une station \"\"\"\n\t\tcursor = self.connection.cursor()\n\t\tsql1 = \"SELECT Capacité FROM Station WHERE Nom=\\\"\"+stationName+\"\\\" \"\n\n\t\tcursor.execute(sql1)\n\t\tstation = cursor.fetchone()\n\t\treturn station['Capacité']\n\n\n","sub_path":"solution/15-05-15/VilloDatabase.py","file_name":"VilloDatabase.py","file_ext":"py","file_size_in_byte":6541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"550919758","text":"import numpy as np\nimport tensorflow as tf\nfrom keras import keras_parameterized\nfrom keras.applications import resnet\nfrom ..encoder import MMFusionEncoder\nfrom ....testing_utils import layer_multi_io_test\n\n\n@keras_parameterized.run_all_keras_modes\nclass TestMMFusionEncoder(keras_parameterized.TestCase):\n def test_layer(self):\n layer_multi_io_test(\n MMFusionEncoder,\n kwargs={},\n input_shapes=[(2, 256, 256, 3), (2, 256, 256, 1)],\n input_dtypes=['uint8', 'uint16'],\n expected_output_shapes=[\n (None, 128, 128, 64),\n (None, 64, 64, 256),\n (None, 32, 32, 512),\n (None, 16, 16, 1024),\n (None, 8, 8, 2048)],\n expected_output_dtypes=['float32'] * 5\n )\n\n def test_rgb_slice(self):\n source = np.random.randint(0, 64, (2 * 224, 224 * 3), 'uint8')\n np.fill_diagonal(source, 128)\n source = np.rot90(source)\n np.fill_diagonal(source, 256)\n source = np.reshape(source, (2, 224, 224, 3))\n\n expected = resnet.preprocess_input(source)\n expected = resnet.ResNet50(input_shape=[224, 224, 3], include_top=False, weights='imagenet')(expected)\n expected = self.evaluate(expected)\n\n layer = MMFusionEncoder()\n layer.build([(None, None, None, 3), (None, None, None, 1)])\n\n result = tf.cast(source, 'float32')\n result = result[..., ::-1] # 'RGB'->'BGR'\n result = tf.nn.bias_add(result, [-103.939, -116.779, -123.680])\n result = layer.rgb_bone2(result)\n result = layer.rgb_bone4(result)\n result = layer.rgb_bone8(result)\n result = layer.rgb_bone16(result)\n result = layer.rgb_bone32(result)\n result = self.evaluate(result)\n\n self.assertTrue(np.all(expected == result))\n\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"segme/model/tri_trans/tests/test_encoder.py","file_name":"test_encoder.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"277833071","text":"from lol_request.exceptions import ApiInvalidValueException, ApiNotFoundException, ApiBadRequestException, ApiUnauthorizedException, ApiForbiddenException, ApiRateLimitExceededException\n\nclass LolApi:\n\tdef __init__(self, base_url, lol_key, requests):\n\t\t\"\"\"Recieves the lol api url and the token for making requests\n\n\t\tParameters\n\t\t----------\n\t\tbase_url : str\n\t\tlol_key : str\n\t\trequests : requests\n\t\t\tPython default requests library\n\t\t\"\"\"\n\t\tself._base_url = base_url\n\t\tself._lol_key = lol_key\n\t\tself._requests = requests\n\t\n\tdef _handle_get_request(self, url, on_success):\n\t\t\"\"\"Handle the get requests of the api\n\n\t\tParameters\n\t\t----------\n\t\turl : str\n\t\t\tThe league of legends endpoint\n\t\ton_success : function\n\t\t\tThe callback function when the request is successful.\n\t\t\tThis callback handles the response of the api\n\n\t\tReturns\n\t\t-------\n\t\tfunction\n\t\t\tA callback function passing the api response\n\t\t\"\"\"\n\t\tr = self._requests.get(url)\n\n\t\tprint('status code {} for the url {}'.format(r.status_code, url))\n\n\t\tif (r.status_code == 200):\n\t\t\treturn on_success(r)\n\t\telif (r.status_code == 400):\n\t\t\traise ApiBadRequestException(r.json())\n\t\telif (r.status_code == 401):\n\t\t\traise ApiUnauthorizedException(r.json())\n\t\telif (r.status_code == 403):\n\t\t\traise ApiForbiddenException(r.json())\n\t\telif (r.status_code == 404):\n\t\t\traise ApiNotFoundException(r.json())\n\t\telif (r.status_code == 429):\n\t\t\traise ApiRateLimitExceededException(r.json())\n\n\tdef _get_request_returning_json(self, url):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\turl : str\n\t\t\n\t\tReturns\n\t\t-------\n\t\tdict\n\t\t\tThe response of the request json as a dict\n\t\t\"\"\"\n\t\tdef on_success(r):\n\t\t\treturn r.json()\n\n\t\treturn self._handle_get_request(url, on_success)\n\n\tdef search_summoner_by_nick(self, nick):\n\t\t\"\"\"Get basic info about a player with his nickname\n\n\t\tParameters\n\t\t----------\n\t\tnick : str\n\n\t\tReturns\n\t\t-------\n\t\tdict\n\t\t\"\"\"\n\n\t\tif nick == '':\n\t\t\traise ApiInvalidValueException('Nick cannot be empty')\n\n\t\turl = \"{}/summoner/v4/summoners/by-name/{}?api_key={}\".format(self._base_url, nick, self._lol_key)\n\n\t\treturn self._get_request_returning_json(url)\n\n\tdef search_league_by_summoner_id(self, lol_id):\n\t\t\"\"\"Get ranked infos about a player with his league of legends id\n\n\t\tParameters\n\t\t----------\n\t\tlol_id : str\n\n\t\tReturns\n\t\t-------\n\t\tdict\n\t\t\"\"\"\n\t\turl = '{}/league/v4/entries/by-summoner/{}?api_key={}'.format(self._base_url, lol_id, self._lol_key)\n\n\t\treturn self._get_request_returning_json(url)\n\n\tdef search_matches_by_account_id(self, account_id, begin_index=0, end_index=100):\n\t\t\"\"\"Get matches by the account id\n\n\t\tParameters\n\t\t----------\n\t\taccount_id : str\n\t\tbegin_index : int, optional\n\t\t\tThe default is 0 \n\t\tend_index : int, optional\n\t\t\tThe default is 100\n\n\t\tReturns\n\t\t-------\n\t\tdict\n\t\t\"\"\"\n\t\tif type(begin_index) is not int or type(end_index) is not int:\n\t\t\traise ApiInvalidValueException('begin_index and end_index must be integer')\n\t\telif begin_index < 0 or end_index < 0:\n\t\t\traise ApiInvalidValueException('begin_index and end_index must be higher than 0')\n\n\t\turl = '{}/match/v4/matchlists/by-account/{}?beginIndex={}&endIndex={}&api_key={}'.format(self._base_url, account_id, begin_index, end_index, self._lol_key)\n\n\t\treturn self._get_request_returning_json(url)\n\n\tdef search_matches_by_match_id(self, game_id):\n\t\t\"\"\"Get matches by game id\n\n\t\tParameters\n\t\t----------\n\t\tgame_id : int\n\n\t\tReturns \n\t\t-------\n\t\tdict\n\t\t\"\"\"\n\t\turl = '{}/match/v4/matches/{}?api_key={}'.format(self._base_url, game_id, self._lol_key)\n\n\t\treturn self._get_request_returning_json(url)\n\n","sub_path":"lol_request/services/LolApi.py","file_name":"LolApi.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"147669153","text":"\"\"\"\nListagem 6.22\nPilha de pratos\n\"\"\"\n\npratos = 5\npilha = list(range(1, pratos + 1))\n\nwhile True:\n print('Existem {} pratos na pilha'.format(len(pilha)))\n print('Pilha atual: {}'.format(pilha))\n print('Selecione:')\n print('(E)mpilhar um novo prato')\n print('(D)esempilhar ou\\n(S)air')\n operacao = input('Operação: E, D ou S: ')\n if operacao == 'D':\n if len(pilha) > 0:\n lavado = pilha.pop(-1)\n print('Prato {} lavado.'.format(lavado))\n else:\n print('Pilha vazia! Nada para lavar.')\n elif operacao == 'E':\n pratos += 1\n pilha.append(pratos)\n elif operacao == 'S':\n break\n else:\n print('Opção errada! Digite apenas D, E ou S')\n","sub_path":"listagem_10.py","file_name":"listagem_10.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"12898945","text":"import tensorflow as tf\nimport tensorlayer as tl\nimport numpy as np\nimport argparse\nfrom utils.tokenizer import *\nfrom weightLightModels.transformer import Transformer\nfrom weightLightModels import model_params\nfrom utils.pipeline_dataset import train_input_fn\nfrom utils import metrics\nfrom models import optimizer\nfrom translate_file import translate_file\nfrom utils import tokenizer\nfrom compute_bleu import bleu_wrapper\n\n\n_TARGET_VOCAB_SIZE = 32768 # Number of subtokens in the vocabulary list.\n_TARGET_THRESHOLD = 327 # Accept vocabulary if size is within this threshold\nVOCAB_FILE = \"vocab.ende.%d\" % _TARGET_VOCAB_SIZE\n\nclass CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\n def __init__(self, d_model, warmup_steps=5):\n super(CustomSchedule, self).__init__()\n \n self.d_model = d_model\n self.d_model = tf.cast(self.d_model, tf.float32)\n\n self.warmup_steps = warmup_steps\n \n def __call__(self, step):\n arg1 = tf.math.rsqrt(step)\n arg2 = step * (self.warmup_steps ** -1.5)\n \n return tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)\n\n\n\n\ndef train_model(input_params):\n print(\"NOW BEGINS TRAINING\")\n params = model_params.EXAMPLE_PARAMS\n dataset = train_input_fn(input_params)\n subtokenizer = tokenizer.Subtokenizer(\"data/data/\"+VOCAB_FILE)\n input_file = \"data/mock/mock.en\"\n output_file = \"./output/dev.de\"\n\n ref_filename = \"data/mock/mock.de\"\n trace_path = \"checkpoints_light/logging/\"\n num_epochs = 100\n \n\n def train_step(inputs, targets):\n model.train()\n with tf.GradientTape() as tape:\n #print(inputs)\n \n logits = model(inputs=inputs, targets=targets)\n logits = metrics.MetricLayer(params.vocab_size)([logits, targets])\n logits, loss = metrics.LossLayer(params.vocab_size, 0.1)([logits, targets])\n\n \n gradients = tape.gradient(loss, model.all_weights)\n optimizer_.apply_gradients(zip(gradients, model.all_weights))\n return loss\n\n \n model = Transformer(params)\n load_weights = tl.files.load_npz(name='./checkpoints_light/model.npz')\n tl.files.assign_weights(load_weights, model)\n learning_rate = CustomSchedule(params.hidden_size, warmup_steps=params.learning_rate_warmup_steps)\n optimizer_ = optimizer.LazyAdam(learning_rate, beta_1=0.9, beta_2=0.98, epsilon=1e-9)\n \n \n for epoch in range(num_epochs):\n total_loss, n_iter = 0, 0\n # translate the evaluation file and calculate bleu scores\n model.eval()\n translate_file(model, subtokenizer, input_file=input_file, output_file=output_file)\n insensitive_score = bleu_wrapper(ref_filename, output_file, False)\n sensitive_score = bleu_wrapper(ref_filename, output_file, True)\n with tf.io.gfile.GFile(trace_path+\"bleu_insensitive\", \"ab+\") as trace_file:\n trace_file.write(str(insensitive_score)+'\\n')\n with tf.io.gfile.GFile(trace_path+\"bleu_sensitive\", \"ab+\") as trace_file:\n trace_file.write(str(sensitive_score)+'\\n') \n for i, [inputs, targets] in enumerate(dataset):\n loss = train_step(inputs, targets)\n with tf.io.gfile.GFile(trace_path+\"loss\", \"ab+\") as trace_file:\n trace_file.write(str(loss.numpy())+'\\n')\n if (i % 100 == 0):\n print('Batch ID {} at Epoch [{}/{}]: loss {:.4f}'.format(i, epoch + 1, num_epochs, loss))\n \n \n total_loss += loss\n n_iter += 1\n\n # printing average loss after every epoch\n print('Epoch [{}/{}]: loss {:.4f}'.format(epoch + 1, num_epochs, total_loss / n_iter))\n # save model weights after every epoch\n tl.files.save_npz(model.all_weights, name='./checkpoints_light/model.npz')\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\n params = {}\n params[\"batch_size\"] = 2048\n params[\"max_length\"] = 256\n params[\"num_parallel_calls\"] = 1\n params[\"repeat_dataset\"] = 1\n params[\"static_batch\"] = False\n params[\"num_gpus\"] = 1\n params[\"use_synthetic_data\"] = False\n params[\"data_dir\"] = './data/data/wmt32k-train-00001*'\n train_model(params)\n","sub_path":"lightweight_tutorial.py","file_name":"lightweight_tutorial.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"59682871","text":"#!/usr/bin/python3\n#\n# Signs out the user\n#\n# @author Brian Hession\n# @email hessionb@gmail.com\n#\n\nfrom env import *\nimport datetime\nimport sessions, sshttp\n\ntry:\n\tsessions.delete_session()\n\n\targs = sshttp.get_parameters()\n\tredirect = sshttp.get_redirect()\n\n\tif redirect:\n\t\tsshttp.send302(redirect, headers={\n\t\t\t\t'Set-Cookie' : 'ssid=expired; Secure; Expires=\"{}\"'.format(datetime.datetime.utcfromtimestamp(0))\n\t\t})\n\telse:\n\t\tsshttp.send302('/', headers={\n\t\t\t\t'Set-Cookie' : 'ssid=expired; Secure; Expires=\"{}\"'.format(datetime.datetime.utcfromtimestamp(0))\n\t\t})\n\nexcept:\n\tsshttp.senderror(500)\n\timport sys, traceback\n\ttraceback.print_exc(file=sys.stderr)\n\n","sub_path":"html/signout.py","file_name":"signout.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"221664524","text":"from PySide import QtGui, QtCore\nimport sys\n\nclass MainWindow(QtGui.QWidget):\n def __init__(self):\n super(MainWindow,self).__init__()\n self.setWindowTitle('My Application')\n\n layout = QtGui.QHBoxLayout(self)\n\n chk_demo = QtGui.QCheckBox('This is a checkbox')\n chk_demo.setCheckState(QtCore.Qt.Checked)\n print(chk_demo.checkState())\n\n layout.addWidget(chk_demo)\n\napp = QtGui.QApplication([])\nMyWindow = MainWindow()\nMyWindow.show()\napp.exec_()\n","sub_path":"src/s6s26_QCheckBox.py","file_name":"s6s26_QCheckBox.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"145991055","text":"# CMPT 145 Course material\n# Copyright (c) 2017-2020 Michael C Horsch\n# All rights reserved.\n#\n# This document contains resources for homework assigned to students of\n# CMPT 145 and shall not be distributed without permission. Posting this \n# file to a public or private website, or providing this file to a person \n# not registered in CMPT 145, constitutes Academic Misconduct, according \n# to the University of Saskatchewan Policy on Academic Misconduct.\n# \n# Synopsis:\n# Defines simple traversals for treenode (primitive) trees.\n#\n# A primitive tree is is like a node-chain; treenodes linked together\n# We will build different kinds of Trees using primitive trees,\n# just as we built Stacks, QUeues and LLists out of node-chains\n#\n# These traversals print the data values stored in a primitive tree.\n\nimport treenode as tn\nimport Queue as Q\n\ndef in_order(tnode):\n \"\"\"\n Display the nodes of a tree in pre-order.\n :param tnode: a primitive tree\n :return: nothing\n \"\"\"\n if tnode is None:\n return\n else:\n in_order(tnode.left)\n print(tnode.data, end=\" \")\n in_order(tnode.right)\n\n\ndef pre_order(tnode):\n \"\"\"\n Display the nodes of a tree in pre-order.\n :param tnode: a primitive tree\n :return: nothing\n \"\"\"\n if tnode is None:\n return\n else:\n print(tnode.data, end=\" \")\n pre_order(tnode.left)\n pre_order(tnode.right)\n\n\ndef post_order(tnode):\n \"\"\"\n Display the nodes of a tree in pre-order.\n :param tnode: a primitive tree\n :return: nothing\n \"\"\"\n if tnode is None:\n return\n else:\n post_order(tnode.left)\n post_order(tnode.right)\n print(tnode.data, end=\" \")\n\n\ndef breadth_order(tnode):\n \"\"\"\n Display the nodes of a tree in breadth-order.\n :param tnode: a primitive tree\n :return: nothing\n \"\"\"\n explore = Q.Queue()\n explore.enqueue(tnode)\n\n while explore.size() > 0:\n current = explore.dequeue()\n print(current.data, end=\" \")\n if current.left is not None:\n explore.enqueue(current.left)\n if current.right is not None:\n explore.enqueue(current.right)\n\n","sub_path":"a9/traversals.py","file_name":"traversals.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"604969308","text":"# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport os\n\nfrom flask import Flask\nimport yaml\n\nimport nl_server.loader as loader\nimport nl_server.routes as routes\n\n\ndef create_app():\n app = Flask(__name__)\n app.register_blueprint(routes.bp)\n\n flask_env = os.environ.get('FLASK_ENV')\n\n embeddings_config_path = '/datacommons/nl/embeddings.yaml'\n if flask_env in ['local', 'test', 'integration_test', 'webdriver']:\n embeddings_config_path = os.path.join(\n os.path.dirname(os.path.dirname(os.path.abspath(__file__))),\n 'deploy/nl/embeddings.yaml')\n app.config['EMBEDDINGS_CONFIG_PATH'] = embeddings_config_path\n\n # Initialize the NL module.\n with open(app.config['EMBEDDINGS_CONFIG_PATH']) as f:\n embeddings_map = yaml.full_load(f)\n if not embeddings_map:\n logging.error(\"No configuration found for embeddings\")\n return\n\n loader.load_embeddings(app, embeddings_map)\n\n return app\n","sub_path":"nl_server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"204259637","text":"\"\"\" Unit tests for inventory management. \"\"\"\n\nimport unittest\nimport io\nimport sys\nfrom unittest.mock import MagicMock, patch\n\nfrom inventory_class import Inventory\nfrom furniture_class import Furniture\nfrom electric_appliances_class import ElectricAppliances\nimport main\nimport market_prices\n\n\nclass InventoryClassTests(unittest.TestCase):\n \"\"\" Tests for inventory_class module. \"\"\"\n\n def test_inventory_initialization(self):\n \"\"\" Tests for successful, accurate initalization of Inventory. \"\"\"\n\n new_product = Inventory(1, 'Chair', 100, 20)\n new_product_dict = new_product.return_as_dictionary()\n\n self.assertEqual(1, new_product_dict['product_code'])\n self.assertEqual('Chair', new_product_dict['description'])\n self.assertEqual(100, new_product_dict['market_price'])\n self.assertEqual(20, new_product_dict['rental_price'])\n\n\nclass FurnitureClasstests(unittest.TestCase):\n \"\"\" Tests for furniture_class module. \"\"\"\n\n def test_furniture_initalization(self):\n \"\"\" Test for succesful, accurate initialization of Furniture. \"\"\"\n\n new_product = Furniture(2, 'Sofa', 600, 175, 'leather', 'l')\n new_product_dict = new_product.return_as_dictionary()\n\n self.assertEqual(2, new_product_dict['product_code'])\n self.assertEqual('Sofa', new_product_dict['description'])\n self.assertEqual(600, new_product_dict['market_price'])\n self.assertEqual(175, new_product_dict['rental_price'])\n self.assertEqual('leather', new_product_dict['material'])\n self.assertEqual('l', new_product_dict['size'])\n\n\nclass ElectricAppliancesTests(unittest.TestCase):\n \"\"\" Tests for electric_appliances_class module. \"\"\"\n\n def test_electric_appliances_initialization(self):\n \"\"\"\n Tests for successful, accurate initalization of ElectricAppliances.\n \"\"\"\n\n new_product = ElectricAppliances(3, 'Blender', 200, 20, 'Krups', 110)\n new_product_dict = new_product.return_as_dictionary()\n\n self.assertEqual(3, new_product_dict['product_code'])\n self.assertEqual('Blender', new_product_dict['description'])\n self.assertEqual(200, new_product_dict['market_price'])\n self.assertEqual(20, new_product_dict['rental_price'])\n self.assertEqual('Krups', new_product_dict['brand'])\n self.assertEqual(110, new_product_dict['voltage'])\n\n\nclass MarketPricesTests(unittest.TestCase):\n \"\"\" Tests for market_prices module. \"\"\"\n\n def test_get_latest_price(self):\n \"\"\"\n Test to ensure get_latest_price is called with expected argument.\n \"\"\"\n\n self.assertEqual(100, market_prices.get_latest_price(100))\n\n market_prices.get_latest_price = MagicMock(return_value=24)\n market_prices.get_latest_price(100)\n\n market_prices.get_latest_price.assert_called_with(100)\n\n\nclass MainTests(unittest.TestCase):\n \"\"\" Tests for the main module. \"\"\"\n\n def test_main_menu(self):\n \"\"\" \n Tests main.main_menu in a couple different ways.\n\n First by passing in a menu option as an argument.\n And second by using simulated user input to navigate the menu.\n\n Both tests verify that the proper function is called based on the menu\n input provided.\n \"\"\"\n\n self.assertEqual(main.main_menu('1'), main.add_new_item)\n self.assertEqual(main.main_menu('2'), main.item_info)\n self.assertEqual(main.main_menu('q'), main.exit_program)\n\n inputs = (user_in for user_in in ['What?', '1'])\n def mock_input(prompt):\n return next(inputs)\n\n with patch('builtins.input', mock_input):\n main_menu_output = main.main_menu()\n\n self.assertEqual(main.add_new_item, main_menu_output)\n\n\n inputs2 = (user_in2 for user_in2 in ['Yes', 'NO', '2'])\n def mock_input2(prompt):\n return next(inputs2)\n\n with patch('builtins.input', mock_input2):\n main_menu_output2 = main.main_menu()\n\n self.assertEqual(main.item_info, main_menu_output2)\n\n def test_get_price(self):\n \"\"\"\n Calls main.get_price and verifies the content of its print statement.\n \"\"\"\n expected_output = \"Get price\\n\"\n\n captured_output = io.StringIO()\n sys.stdout = captured_output\n\n main.get_price()\n sys.stdout = sys.__stdout__\n\n self.assertEqual(expected_output, captured_output.getvalue())\n\n def test_add_new_item(self):\n \"\"\" Tests main.add_new_item with simulated user input. \"\"\"\n\n main.FULL_INVENTORY = {}\n\n inputs = (user_in for user_in in [999, 'Vase', 1400, 'n', 'n'])\n\n def mock_input(prompt):\n return next(inputs)\n\n with patch('builtins.input', mock_input):\n main.add_new_item()\n\n test_dict = {'product_code': 999, 'description': 'Vase', 'market_price': 24,\n 'rental_price': 1400}\n\n self.assertEqual(test_dict, main.FULL_INVENTORY[999])\n\n def test_add_new_item_furniture(self):\n \"\"\"\n Tests main.add_new_item with simulated user input by populating\n FULL_INVENTORY with a sample product and verifying that product is stored\n with the expected keys and values.\n \"\"\"\n\n main.FULL_INVENTORY = {}\n\n inputs = (user_in for user_in in [123, 'Desk', 125, 'y', 'wood', 'l'])\n\n def mock_input(prompt):\n return next(inputs)\n\n with patch('builtins.input', mock_input):\n main.add_new_item()\n\n test_dict = {'product_code': 123, 'description': 'Desk', 'market_price': 24,\n 'rental_price': 125, 'material': 'wood', 'size': 'l'}\n\n self.assertEqual(test_dict, main.FULL_INVENTORY[123])\n\n def test_add_new_item_electric_appliance(self):\n \"\"\" Tests main.add_new_item with simulated user input. \"\"\"\n\n main.FULL_INVENTORY = {}\n\n inputs = (user_in for user_in in [\n 246, 'Blender', 75, 'n', 'y', 'Krups', 110])\n\n def mock_input(prompt):\n return next(inputs)\n\n with patch('builtins.input', mock_input):\n main.add_new_item()\n\n test_dict = {'product_code': 246, 'description': 'Blender', 'market_price': 24,\n 'rental_price': 75, 'brand': 'Krups', 'voltage': 110}\n\n self.assertEqual(test_dict, main.FULL_INVENTORY[246])\n\n def test_item_info(self):\n \"\"\" \n Testing main.item_info by adding an item to FULL_INVENTORY, calling\n item_info with its item_code, and capturing item_info's print statements\n to verify their accuracy.\n \"\"\"\n\n main.FULL_INVENTORY = {}\n inputs = (user_in for user_in in [999, 'Vase', 1400, 'n', 'n'])\n\n def mock_input(prompt):\n return next(inputs)\n\n with patch('builtins.input', mock_input):\n main.add_new_item()\n\n expected_output = ('product_code:999\\n'\n 'description:Vase\\n'\n 'market_price:24\\n'\n 'rental_price:1400\\n')\n\n expected_output2 = \"Item not found in inventory\\n\"\n\n captured_output = io.StringIO()\n sys.stdout = captured_output\n\n main.item_info(999)\n sys.stdout = sys.__stdout__\n\n self.assertEqual(expected_output, captured_output.getvalue())\n\n captured_output2 = io.StringIO()\n sys.stdout = captured_output2\n\n main.item_info(432)\n sys.stdout = sys.__stdout__\n\n self.assertEqual(expected_output2, captured_output2.getvalue())\n\n def test_system_exit(self):\n \"\"\" Tests main.exit_program. \"\"\"\n\n with self.assertRaises(SystemExit):\n main.exit_program()\n","sub_path":"students/jeremy_monroe/lesson01/assignment/tests/test_unit.py","file_name":"test_unit.py","file_ext":"py","file_size_in_byte":7712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"581491247","text":"import requests\nimport time\nimport os\n\n\ndef analyze_salary(this_vacancies_dict):\n\n currency = this_vacancies_dict['currency']\n salary_from = this_vacancies_dict['payment_from']\n salary_to = this_vacancies_dict['payment_to']\n\n correction_factor_for_average_salary = 1.1\n correction_factor_for_lowest_salary = 1.33\n\n if salary_from == 0 and salary_to == 0:\n return None\n\n currency_rate = 1\n if currency == 'eur':\n currency_rate = 70\n elif currency == 'usd':\n currency_rate = 60\n\n if salary_from != 0 and salary_to != 0:\n expected_salary = (salary_from + salary_to) / 2 * (\n currency_rate * correction_factor_for_average_salary\n )\n\n elif salary_from == 0:\n expected_salary = salary_to * currency_rate\n\n elif salary_to == 0:\n expected_salary = salary_from * (\n currency_rate * correction_factor_for_lowest_salary\n )\n\n return expected_salary\n\n\ndef download_vacancies(language_name):\n\n #superjob_secretkey = os.environ.get['SUPERJOB_SECRET_KEY']\n superjob_secretkey = 'v3.r.130562317.f32d34e6598e400784c163be15b047287094cd76.976987d93c83b3e2239377d0800b8305b97160ba'\n url = 'https://api.superjob.ru/2.0/vacancies/'\n headers = {'X-Api-App-Id':superjob_secretkey}\n time_now = int(time.time())\n one_month = 30 * 24 * 60 * 60\n time_from = time_now - one_month\n development_and_programming = 48\n moscow = 4\n\n params = {\n 'keyword': language_name,\n 'catalogues': development_and_programming,\n 'date_published_from': time_from,\n 'date_published_to': time_now,\n 'town': moscow\n }\n\n response = requests.get(url, headers=headers, params=params)\n response.raise_for_status()\n unpacked_response= response.json()\n\n found_vacancies = unpacked_response['total']\n vacancies_list = unpacked_response['objects']\n return vacancies_list, found_vacancies\n\n\ndef main(language_name='python'):\n\n vacancies_list, found_vacancies = download_vacancies(language_name)\n processed_vacancies = 0\n overall_salary_fund = 0\n\n for vacancy in vacancies_list:\n expected_salary = analyze_salary(vacancy)\n if expected_salary is not None:\n processed_vacancies = processed_vacancies + 1\n overall_salary_fund = overall_salary_fund + expected_salary\n\n try:\n average_salary = round(overall_salary_fund / processed_vacancies)\n except ZeroDivisionError:\n average_salary = None\n return {\n 'found_vacancies': found_vacancies,\n 'processed_vacancies': processed_vacancies,\n 'average_salary': average_salary\n }\n","sub_path":"super_job.py","file_name":"super_job.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"402059501","text":"#\n# Collective Knowledge (dealing with table)\n#\n# See CK LICENSE.txt for licensing details\n# See CK COPYRIGHT.txt for copyright details\n#\n# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net\n#\n\ncfg={} # Will be updated by CK (meta description of this module)\nwork={} # Will be updated by CK (temporal data)\nck=None # Will be updated by CK (initialized CK kernel) \n\n# Local settings\n\n##############################################################################\n# Initialize module\n\ndef init(i):\n \"\"\"\n\n Input: {}\n\n Output: {\n return - return code = 0, if successful\n > 0, if error\n (error) - error text if return > 0\n }\n\n \"\"\"\n return {'return':0}\n\n##############################################################################\n# draw table\n\ndef draw(i):\n \"\"\"\n Input: {\n table - table to draw [[],[],[]...], [[],[],[]...] ...]\n\n (out) - txt (default) or html\n }\n\n Output: {\n return - return code = 0, if successful\n > 0, if error\n (error) - error text if return > 0\n\n string - output\n }\n\n \"\"\"\n\n o=i.get('out','')\n\n table=i.get('table',[])\n\n s=''\n\n if len(table)>0:\n lx=len(table[0])\n\n lwidth=[]\n for l in range(0, lx):\n lwidth.append(-1)\n\n # If 'txt', check length of all entries\n if o=='txt':\n for t in table:\n for l in range(0, lx):\n sx=str(t[l])\n lw=lwidth[l]\n if lw==-1 or len(sx)>lw: \n lwidth[l]=len(sx)\n\n\n for t in table:\n for l in range(0, lx):\n sx=str(t[l])\n lw=lwidth[l]\n\n s+=sx.ljust(lw+2)\n s+='\\n'\n else:\n s='\\n'\n s+=' \\n'\n s+=' \\n'\n for t in table:\n s+=' \\n'\n for l in range(0, lx):\n sx=str(t[l])\n s+=' \\n'\n s+=' \\n'\n s+='
'+sx+'
\\n'\n s+=' \\n'\n s+='\\n'\n\n return {'return':0, 'string':s}\n","sub_path":"module/table/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"193308777","text":"import os\nimport pickle\nfrom glob import glob\n\nfrom moviepy.editor import ImageSequenceClip\nfrom tensorflow.python.keras.preprocessing.image import load_img, img_to_array\nfrom tqdm import tqdm\n\nfrom tf2deeplab.deeplab import DeepLabV3Plus\nfrom tf2deeplab.utils import pipeline\n\nh, w = 800, 1600\nwith open('../notebooks/cityscapes_dict.pkl', 'rb') as f:\n id_to_color = pickle.load(f)['color_map']\n\nmodel = DeepLabV3Plus(h, w, 34)\nmodel.load_weights('top_weights.h5')\n\nimage_dir = '/home/mia/backup/research/autonomous_driving/cityscapes/dataset/val_images'\nimage_list = os.listdir(image_dir)\nimage_list.sort()\nprint(f'{len(image_list)} frames found')\n\ntest = load_img(f'{image_dir}/{image_list[1]}')\ntest = img_to_array(test)\npipeline(test, video=False)\n\nfor image_dir in ['stuttgart_00', 'stuttgart_01', 'stuttgart_02']:\n os.mkdir(f'outputs/{image_dir}')\n image_list = os.listdir(image_dir)\n image_list.sort()\n print(f'{len(image_list)} frames found')\n for i in tqdm(range(len(image_list))):\n try:\n test = load_img(f'{image_dir}/{image_list[i]}')\n test = img_to_array(test)\n segmap = pipeline(test, video=False,\n fname=f'{image_list[i]}', folder=image_dir)\n if segmap == False:\n break\n except Exception as e:\n print(str(e))\n clip = ImageSequenceClip(\n sorted(glob(f'outputs/{image_dir}/*')), fps=18, load_images=True)\n clip.write_videofile(f'{image_dir}.mp4')\n","sub_path":"tf2deeplab/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"111120480","text":"\"\"\"\nError classes for ebox_checkup\n\"\"\"\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass TableNotFoundError(Exception):\n \"\"\"\n Exception which is thrown when a table cannot be found.\n \"\"\"\n\n def __init__(self):\n super(TableNotFoundError, self).__init__()\n self.message = 'An enclosing table could not be found.'\n\n\nclass MalformedDocumentError(Exception):\n \"\"\"\n Exception which is thrown when a document is malformed.\n \"\"\"\n\n def __init__(self):\n super(MalformedDocumentError, self).__init__()\n self.message = 'The document could not be parsed because it is malformed.'\n","sub_path":"ebox_checkup/errors/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47007935","text":"# -*- codint: utf-8 -*-\nfrom sklearn import datasets\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 手書き数字のデータをロードし、変数digitsに格納\ndigits = datasets.load_digits()\n\n# 特徴量のセットを変数Xに、ターゲットを変数yに格納\nX = digits.data\ny = digits.target\n\n# 手書き数字の画像表現を変数imagesに各k濃\nimages = digits.images\n\n# 表示エリアの背景をシルバーにセット\nfig = plt.figure()\nfig.patch.set_facecolor('silver')\n\n# 0-9の10舞の画像をそれぞれ3枚ずつ、計30枚描写\nfor i in range(10):\n for j in range(3):\n # 数字iの画像のうち、j枚目を取り出す\n img = images[y==i][j]\n # ランダムに取り出したい場合は下記を有効に\n img = images[y==i][np.random.randint(0, len(images[y==i]))]\n # 縦5x横6の画像表示エリアのうち、3*i+j+1番目に描写\n plt.subplot(5,6,3*i + j + 1)\n # グラフとしての軸は描写しない\n plt.axis('off')\n # 白黒を反転した状態で描写\n plt.imshow(img, cmap=plt.cm.gray_r, interpolation='nearest')\n # 各画像にタイトルを描写\n plt.title('Data {0}'.format(i))\n\n# 画像間に余裕を持たせて描写\nplt.tight_layout()\n\n# 描写した内容を画面表示\nplt.show()\n\n","sub_path":"blueback/ml-06-02-images.py","file_name":"ml-06-02-images.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"462587836","text":"from django.conf.urls import url\nfrom django.contrib import admin\nfrom . import views\n\napp_name = 'stock'\n\nurlpatterns = [\n url(r'^varer/$', views.VarerAll, name = 'allevarer'),\n url(r'^varer/(?P.*)/$', views.EnkeltVare, name = 'enkeltvare'),\n url(r'^varer/skift$', views.Skift, name = 'skift'),\n url(r'^udlejning/$', views.UdlejningVarerAll, name = 'udlejning'),\n url(r'^udlejning/skift$', views.Skift1, name = 'skift1'),\n]","sub_path":"cafe/stock/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"592044235","text":"import falcon\nimport json\nimport docker\n\n\nclass Resource(object):\n def on_get(self, request, response):\n body = 'OK'\n response.body = json.dumps(body)\n response.status = falcon.HTTP_200\n\n\ndef containerize(image):\n client = docker.from_env()\n client.images.pull(image)\n\n container = client.containers.run(image, detach=True, hostname='localhost',\n ports={'80/tcp': ('127.0.0.1', 8000)})\n\n\n return container\n\n\napi = falcon.API()\napi.add_route('/healthcheck', Resource())\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"422718311","text":"#jogo de advinha\nfrom random import randint\nnumram = randint(0, 10)\nnumjo = \"\"\ntentativas = 0\nprint(\"Vou pensar em um numero entre 0 e 10. Tente advinhar!\")\nwhile numjo != numram:\n numjo = int(input(\"Seu palpite: \"))\n tentativas = tentativas + 1\n if numjo < numram:\n print(\"Mais.. Tente mais uma vez!\")\n elif numjo > numram:\n print(\"Menos.. Tente mais uma vez!\")\nprint(\"Acertou! O numero que eu pensei foi {}.\".format(numram))\nprint(\"Total de tentativas: {}\".format(tentativas))","sub_path":"Mini Projetos/exec58.py","file_name":"exec58.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"534871535","text":"def prog3(a):\n \"\"\" (int)-> bool\n Firstly checks wether the given number, a,\n is a prime number or not, then returns True and False.\n Ex)if a is less than 2, the answer is \"False\".\n input: 1\n output: False\n Ex) if a==2 the answer is \"True\". \n input:2\n output:True\n Ex)for more than 2, it uses the Trial division\n to findout wether a is a prime number or not.\n input: 5\n output:True\n Ex) \n input:50\n output:False\n \"\"\" \n if a<2:\n return False\n if a==2:\n return True\n sqa = a**0.5\n i = 2\n while i <= sqa:\n if a % i == 0:\n return False\n i += 1\n return True\n\nprint(prog3(int(input(\"Enter number a:\"))))\n","sub_path":"ex2/prog3.py","file_name":"prog3.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"336445634","text":"__author__ = 'andrejsapoznikov'\nfrom View.MainWindow import MainWindow\nfrom PyQt5.QtGui import QStandardItem, QStandardItemModel\nfrom PyQt5.QtCore import QModelIndex\nfrom Model.DataManageModel import Key_Object\nfrom Controller.DataManage import DataManage\nfrom Controller.UserManage import UserManage\nfrom Controller.TAAC import TAAC_controller\nfrom Controller.EncryptedSearch import EncryptedSearch\nfrom Controller.PDP import PDP\nfrom Controller.SecureChannel import SecureChannel\nfrom Controller.Utils import Utils\nfrom Model.pirmap import pir_server\nfrom Model.pirmap import pir_user\nfrom charm.toolbox.pairinggroup import GT\nfrom Crypto.Cipher import AES\nfrom base64 import b64encode, b64decode\nimport pickle\nfrom copy import deepcopy\n# from Controller.google import GoogleDrive\nclass Controllers():\n def __init__(self):\n # False если нужно запустить без загрузки из сохранения\n # True если нужно запустить с загрухкой их сохранения\n self.from_save = False\n # -------------------------------------SAVE-------------------------------------\n # Имя файла из которого будут загружены данные\n self.save_file_name = 'save1'\n # Структура словаря в который сохряняются данные\n self.to_pickle = {\n 'taac': {},\n 'users': {},\n 'data': {},\n 'aa': {},\n 'cloud': {}\n }\n\n # Создание в программе объекта данных (БД)\n #self.dataObj = Data_Object()\n # Создание в программе объекта ключей (БД)\n self.keyObj = Key_Object()\n # Создание в системе объекта схемы TAAC\n # self.taacObj = TAAC()\n # Инициализация схемы TAAC (генерация GPP)\n # self.GPP = self.taacObj.GlobalSetup()\n # База данных АЦ-ов\n self.AAs = dict()\n\n self.dat = DataManage(self)\n\n # Передача по защищенному каналу\n # self.secChannel = SecureChannelModel()\n\n # База данных пользователей программы\n #self.users = dict()\n\n self.users = UserManage(self)\n\n self.taac_obj = TAAC_controller(self)\n\n self.currentUser = ''\n\n # База данных сервера\n # self.server = GoogleDrive() # Раскоментировать при использовании GoogleDrive\n self.cloudStorage = dict()\n\n # Поиск по шированным данным\n # self.enc_search = encrypted_search_with_pk_sk()\n # self.enc_search_params = self.enc_search.mk_setup()\n self.enc_search = EncryptedSearch(self)\n\n self.pdp_obj = PDP(self)\n\n self.sec_ch = SecureChannel(self)\n\n self.pir_server = pir_server()\n self.pir_user = pir_user()\n\n self.utils = Utils(self)\n\n # Создание и отображение главного окна\n self.mView = MainWindow(self)\n self.mView.show()\n\n\n # Загрузка из файла\n if self.from_save is True:\n self.load_from_save2()\n\n # self.save_to_file()\n\n # Установка выбранного пользователя\n # Отображение его в главном меню пользователя\n def set_current_user(self):\n current_name = self.mView.choiceUser.choiceUserListViewModel.itemFromIndex(self.mView.choiceUser.choiceUserListView.currentIndex())\n self.currentUser = current_name.text()\n self.mView.cabinet.cabinetLabel3.setText('Текущий пользовтаель: ' + self.currentUser)\n self.mView.cloudWindow.cloudWindowLabel4.setText('Текущий пользовтаель: ' + self.currentUser)\n\n self.mView.dataMan.dataManageListViewModel.clear()\n\n # Отображение на форме данных выбранного пользователя\n for data_name in self.dat.data_object.user_data[self.currentUser]:\n self.mView.dataMan.dataManageListViewModel.appendRow(QStandardItem(data_name))\n\n self.mView.cabinet.cabinetPushButton1.setEnabled(True)\n self.mView.cabinet.cabinetPushButton2.setEnabled(True)\n self.mView.cabinet.cabinetPushButton3.setEnabled(True)\n self.mView.cabinet.cabinetPushButton4.setEnabled(True)\n self.mView.cabinet.cabinetPushButton5.setEnabled(True)\n self.mView.cabinet.cabinetPushButton7.setEnabled(True)\n self.mView.cabinet.cabinetPushButton8.setEnabled(True)\n self.mView.cabinet.cabinetPushButton9.setEnabled(True)\n\n\n self.mView.currentWindow[0] = 0\n self.mView.stackedLayout.setCurrentIndex(self.mView.currentWindow[0])\n\n def preview(self):\n name = self.mView.dataMan.dataManageListViewModel.itemFromIndex(self.mView.dataMan.dataManageListView.currentIndex())\n name = name.text()\n\n self.mView.dataMan.dataText.clear()\n\n for key in self.dat.data_object.user_data[self.currentUser][name]:\n self.mView.dataMan.dataText.insertPlainText('-------------------------------------------\\n')\n self.mView.dataMan.dataText.insertPlainText(str(key) + ' ')\n try:\n self.mView.dataMan.dataText.insertPlainText(self.dat.data_object.user_data[self.currentUser][name][key].decode())\n except:\n self.mView.dataMan.dataText.insertPlainText(str(self.dat.data_object.user_data[self.currentUser][name][key]))\n self.mView.dataMan.dataText.insertPlainText('\\n')\n\n\n def change_data(self):\n # Индекс в списке выбранного файла для отправки по защищенному каналу\n i_d = self.mView.cloudWindow.cloudWindowListView1.currentIndex()\n # Получение имени файла из списка по индексу\n d_name = self.mView.cloudWindow.cloudWindowListViewModel.itemFromIndex(i_d)\n d_name = d_name.text()\n\n\n self.cloudStorage[d_name]['CipherText'] = b'0' + self.cloudStorage[d_name]['CipherText'][1:]\n\n def pir_get_data(self):\n i_d = self.mView.cloudWindow.cloudWindowListView1.currentIndex()\n d_name = self.mView.cloudWindow.cloudWindowListViewModel.itemFromIndex(i_d)\n d_name = d_name.text()\n rec_num = 0\n for i in self.cloudStorage:\n if d_name == i:\n break\n rec_num += 1\n\n # self.mView.cloudWindow.cloudWindowListView1.\n print(rec_num)\n v = self.pir_user.start_req(rec_num, self.mView.cloudWindow.cloudWindowListViewModel.rowCount())\n r = self.pir_server.get_record(v, self.cloudStorage)\n data = self.pir_user.ext(r)\n if d_name not in self.dat.data_object.user_data[self.currentUser]:\n self.dat.data_object.user_data[self.currentUser][d_name] = {'PlainText': ''}\n self.dat.data_object.user_data[self.currentUser][d_name]['PlainText'] = data\n self.mView.dataMan.dataManageListViewModel.appendRow(QStandardItem(d_name))\n\n\n\n def download_data(self):\n # Индекс в списке выбранного файла для отправки по защищенному каналу\n i_d = self.mView.cloudWindow.cloudWindowListView1.currentIndex()\n # Получение имени файла из списка по индексу\n d_name = self.mView.cloudWindow.cloudWindowListViewModel.itemFromIndex(i_d)\n d_name = d_name.text()\n\n u_name = self.currentUser\n\n if 'taacKey' in self.cloudStorage[d_name]:\n uk = {}\n for aa in self.AAs:\n uk.update(self.AAs[aa]['UK'])\n\n self.users.users[u_name]['DK'] = dict()\n\n for aa in self.users.users[u_name]['taacKey']:\n for attr in self.users.users[u_name]['taacKey'][aa]:\n self.users.users[u_name]['DK'][attr.upper()] = self.taac_obj.taac_obj.DKeyCom(self.users.users[u_name]['taacKey'][aa][attr], uk[attr])\n\n print(self.cloudStorage[d_name]['taacKey'])\n\n key = self.taac_obj.taac_obj.Decrypt(self.cloudStorage[d_name]['taacKey'], self.taac_obj.GPP, self.users.users[u_name]['DK'], u_name)\n\n if not key:\n self.mView.openMessageBox('Ваши атрибуты не соответсвуют политике доступа')\n return None\n\n key = self.taac_obj.taac_obj.group.serialize(key)\n\n auth_key = '1234567891234567'\n\n keyObj = {'key2': {}}\n\n keyObj['key2'] = {'EncryptionKey': key[:16], 'AuthKey': auth_key}\n\n if d_name not in self.dat.data_object.user_data[self.currentUser]:\n self.dat.data_object.user_data[self.currentUser][d_name] = {}\n\n if 'MAC' in self.dat.data_object.user_data[self.currentUser][d_name] and 'iv' in self.dat.data_object.user_data[self.currentUser][d_name]:\n a = self.sec_ch.sec_ch_obj.DownloadData(self.cloudStorage[d_name]['CipherText'], keyObj['key2'],\n self.dat.data_object.user_data[self.currentUser][d_name]['MAC'],\n self.dat.data_object.user_data[self.currentUser][d_name]['iv'])\n self.mView.messageBox('Результат скачивания по защищенному каналу ' + str(a[0]))\n else:\n\n\n dec = AES.new(key[:16], AES.MODE_CFB, key[:16])\n\n self.dat.data_object.user_data[self.currentUser][d_name]['PlainText'] = self.cloudStorage[d_name]['CipherText']\n\n self.dat.data_object.user_data[self.currentUser][d_name]['PlainText'] = b64decode(self.dat.data_object.user_data[self.currentUser][d_name]['PlainText'])\n\n # self.dataObj.user_data[self.currentUser][d_name]['PlainText'] = self.dataObj.user_data[self.currentUser][d_name]['PlainText'].decode()\n\n self.dat.data_object.user_data[self.currentUser][d_name]['PlainText'] = dec.decrypt(self.dat.data_object.user_data[self.currentUser][d_name]['PlainText'])\n\n self.mView.dataMan.dataManageListViewModel.appendRow(QStandardItem(d_name))\n\n\n # a = self.secChannel.DownloadData(self.cloudStorage[name_of_file.text()]['CipherText'], keyObj['key2'],\n # self.dataObj.user_data[name_of_file.text()]['MAC'],\n # self.dataObj.user_data[name_of_file.text()]['iv'])\n else:\n\n keyObj = {'key2': {}}\n\n keyObj['key2'] = {'EncryptionKey': '1234567891234567', 'AuthKey': '1234567891234567'}\n\n a = self.sec_ch.sec_ch_obj.DownloadData(self.cloudStorage[d_name]['CipherText'], keyObj['key2'],\n self.dat.data_object.user_data[self.currentUser][d_name]['MAC'],\n self.dat.data_object.user_data[self.currentUser][d_name]['iv'])\n print(a)\n\n self.mView.openMessageBox('Файл скачен успешно')\n\n def get_list_attr(self):\n self.mView.taacWindow.taacWindowListView2Model.clear()\n for aa in self.AAs:\n for attr in self.AAs[aa]['attr']:\n item = QStandardItem(attr)\n # item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)\n # item.setData(QtCore.QVariant(QtCore.Qt.Unchecked), QtCore.Qt.CheckStateRole)\n self.mView.taacWindow.taacWindowListView2Model.appendRow(item)\n\n def get_list_data(self):\n # Расскомментировать при использовании GoogleDrive\n # res = self.server.retrieve_all_files()\n #\n self.mView.cloudWindow.cloudWindowListViewModel.clear()\n # for i in res:\n # # url = i['downloadUrl']\n # if i['mimeType'] != 'text/plain':\n # continue\n #\n # self.mView.cloudWindow.cloudWindowListViewModel.appendRow(QStandardItem(i['originalFilename']))\n for i in self.cloudStorage.keys():\n self.mView.cloudWindow.cloudWindowListViewModel.appendRow(QStandardItem(i))\n\n def set_current_data_meta(self, name):\n\n self.mView.cloudWindow.textedit.clear()\n\n policy = self.cloudStorage[name]['Policy']\n owner = self.cloudStorage[name]['Owner']\n\n for key in self.cloudStorage[name]:\n self.mView.cloudWindow.textedit.insertPlainText('-------------------------------------------\\n')\n self.mView.cloudWindow.textedit.insertPlainText(str(key) + ' ')\n try:\n self.mView.cloudWindow.textedit.insertPlainText(self.cloudStorage[name][key].decode('latin-1'))\n except:\n self.mView.cloudWindow.textedit.insertPlainText(str(self.cloudStorage[name][key]))\n self.mView.cloudWindow.textedit.insertPlainText('\\n')\n\n self.mView.cloudWindow.cloudWindowLabel3.setText('

Владелец файла:' + owner +\n '

Политика доступа:' +\n policy + '

')\n\n def pre_send_file(self):\n self.mView.sendfile.textbrowser1.clear()\n\n i_file = self.mView.sendfile.listView.currentIndex()\n name_file = self.mView.dataMan.dataManageListViewModel.itemFromIndex(i_file)\n name_file = name_file.text()\n\n key = self.taac_obj.taac_obj.group.random(GT)\n\n self.users.users[self.currentUser]['sym_key'][name_file] = {'Key': key,\n 'EncryptionKey': self.taac_obj.taac_obj.group.serialize(key)[:16],\n 'AuthKey': '1234567891234567'}\n\n for_send = {'Owner': self.currentUser, 'Policy': 'Без политики'}\n\n # Use encryption\n if self.mView.sendfile.checkBox.isChecked():\n if self.mView.sendfile.checkBox_4.isChecked():\n pass\n else:\n enc = AES.new(self.users.users[self.currentUser]['sym_key'][name_file]['EncryptionKey'], AES.MODE_CFB, self.users.users[self.currentUser]['sym_key'][name_file]['EncryptionKey'])\n for_send['CipherText'] = enc.encrypt(self.dat.data_object.user_data[self.currentUser][name_file]['PlainText'])\n\n # Use enc_search\n if self.mView.sendfile.checkBox_3.isChecked():\n words = self.mView.sendfile.lineEdit_2.text().split(',')\n users = self.mView.sendfile.lineEdit_6.text().split(',')\n\n doc_key = self.enc_search.enc_search_obj.mk_keygen(self.enc_search.enc_search_params)['SK']\n self.users.users[self.currentUser]['encSearchKey'][name_file] = doc_key\n\n for_send['delta'] = {}\n\n for user in users:\n for_send['delta'][user] = []\n for_send['delta'][user].append(self.enc_search.enc_search_obj.mk_delta(doc_key, self.users.users[user]['encSearchKey']['PK'], self.enc_search.enc_search_params))\n\n for_send['searchWords'] = []\n for word in words:\n for_send['searchWords'].append(self.enc_search.enc_search_obj.mk_enc(doc_key, word, self.enc_search.enc_search_params))\n\n\n # Use secure channel\n if self.mView.sendfile.checkBox_4.isChecked():\n self.dat.data_object.user_data[self.currentUser][name_file].update(self.sec_ch.sec_ch_obj.secure_channel(self.dat.data_object.user_data[self.currentUser][name_file],\n self.users.users[self.currentUser]['sym_key'][name_file]))\n\n for_send['CipherText'] = self.dat.data_object.user_data[self.currentUser][name_file]['CipherText']\n\n # Use TAAC\n if self.mView.sendfile.checkBox_2.isChecked():\n policy_str = self.mView.sendfile.lineEdit.text()\n access_policy = self.taac_obj.taac_obj.Encrypt(key, self.taac_obj.time, policy_str, self.taac_obj.GPP, self.AAs)\n for_send['taacKey'] = access_policy\n for_send['Policy'] = policy_str\n\n # Use integrity control\n if self.mView.sendfile.checkBox_5.isChecked():\n d = int(self.mView.sendfile.lineEdit_3.text())\n r = int(self.mView.sendfile.lineEdit_4.text())\n t = int(self.mView.sendfile.lineEdit_5.text())\n\n res = self.pdp_obj.pdp_obj.setup_phase(d, t, r, for_send['CipherText'])\n self.users.users[self.currentUser]['integr_control'][name_file] = res\n\n for_send['integr_control'] = res[1]\n\n print(for_send)\n\n # Send PlainText\n if not self.mView.sendfile.checkBox_4.isChecked() and not self.mView.sendfile.checkBox.isChecked():\n for_send['PlainText'] = self.dat.data_object.user_data[self.currentUser][name_file]['PlainText']\n\n self.dat.data_object.user_data[self.currentUser][name_file]['for_send'] = for_send\n\n for k in for_send:\n self.mView.sendfile.textbrowser1.insertPlainText(k + '\\n')\n if k == 'CipherText':\n self.mView.sendfile.textbrowser1.insertPlainText(\"Зашифрованный текст\" + '\\n')\n if k == 'Policy':\n self.mView.sendfile.textbrowser1.insertPlainText(\"Политика доступа\" + '\\n')\n if k == 'integr_control':\n self.mView.sendfile.textbrowser1.insertPlainText(\"Токены для контроля целостности\" + '\\n')\n for tok in for_send[k]:\n self.mView.sendfile.textbrowser1.insertPlainText(' ' + str(tok) + '\\n')\n continue\n self.mView.sendfile.textbrowser1.insertPlainText(' ' + str(for_send[k]) + '\\n')\n\n\n def send_file(self):\n i_file = self.mView.sendfile.listView.currentIndex()\n name_file = self.mView.dataMan.dataManageListViewModel.itemFromIndex(i_file)\n name_file = name_file.text()\n for_send = self.dat.data_object.user_data[self.currentUser][name_file]['for_send']\n self.cloudStorage[name_file] = for_send\n # self.save_to_file()\n # Смена окна\n self.mView.currentWindow[0] = 0\n self.mView.stackedLayout.setCurrentIndex(0)","sub_path":"Controller/Controllers.py","file_name":"Controllers.py","file_ext":"py","file_size_in_byte":18650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"142341660","text":"#this is the file containing the function to train the selected model namely 'densenet121' or 'alexnet'\n\nimport numpy as np\nimport pandas as pd\nimport time\nimport torch\nfrom torch.autograd import variable\nimport seaborn as sb\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch import optim\nfrom torchvision import datasets, transforms\nimport torchvision.models as models\nimport time\nfrom os import listdir\n\n\n\n# Implement a function for the validation pass\ndef validation(model, validloader, criterion):\n test_loss = 0\n accuracy = 0\n for images, labels in validloader:\n\n images, labels = images.to('cuda'), labels.to('cuda')\n output = model.forward(images)\n test_loss += criterion(output, labels).item()\n\n ps = torch.exp(output)\n equality = (labels.data == ps.max(dim=1)[1])\n accuracy += equality.type(torch.FloatTensor).mean()\n\n return test_loss, accuracy\n\n\ndef do_deep_learning(model, data_dir, save_dir, learning_rate, num_epochs, hidden_units, processor):\n if model == 'densenet121':\n model = models.densenet121(pretrained = True)\n for param in model.parameters():\n param.requires_grad = False\n\n from collections import OrderedDict\n classifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(1024, 512)),\n ('relu1', nn.ReLU()),\n ('fc2', nn.Linear(512, 2)) ,\n ('output', nn.LogSoftmax(dim = 1))]))\n\n model.classifier = classifier\n\n elif model == 'alexnet':\n model = models.alexnet(pretrained=True)\n for param in model.parameters():\n param.requires_grad = False\n\n from collections import OrderedDict\n classifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(9216, hidden_units)),\n ('relu1', nn.ReLU()),\n ('fc2', nn.Linear(hidden_units, 2)) ,\n ('output', nn.LogSoftmax(dim = 1))]))\n\n model.classifier = classifier\n\n else:\n print(\"Please select from densenet121 or alexnet only\")\n\n train_dir = data_dir + '/train'\n valid_dir = data_dir + '/valid'\n\n train_transform = transforms.Compose([transforms.Resize(255),\n transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n #transforms.RandomVerticalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])])\n valid_transform = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])])\n\n # Load the datasets with ImageFolder\n trainset = datasets.ImageFolder(train_dir, transform = train_transform)\n validset = datasets.ImageFolder(valid_dir, transform = valid_transform)\n\n # Using the image datasets and the trainforms, define the dataloaders\n trainloader = torch.utils.data.DataLoader(trainset, batch_size = 64, shuffle = True)\n validloader = torch.utils.data.DataLoader(validset, batch_size = 32, shuffle = True)\n\n\n criterion = nn.NLLLoss()\n optimizer = optim.Adam(model.classifier.parameters(), lr=learning_rate)\n\n epochs = num_epochs\n print_every = 42\n steps = 0\n\n # change to cuda\n model.cuda()\n\n for e in range(epochs):\n running_loss = 0\n for ii, (inputs, labels) in enumerate(trainloader):\n steps += 1\n\n inputs, labels = inputs.to('cuda'), labels.to('cuda')\n\n optimizer.zero_grad()\n\n # Forward and backward passes\n outputs = model.forward(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n if steps % print_every == 0:\n model.eval()\n with torch.no_grad():\n test_loss, accuracy = validation(model, validloader, criterion)\n\n print(\"Epoch: {}/{}.. \".format(e+1, epochs),\n \"Training Loss: {:.3f}.. \".format(running_loss/print_every),\n \"Test Loss: {:.3f}.. \".format(test_loss/len(validloader)),\n \"Test Accuracy: {:.3f}\".format(accuracy/len(validloader)))\n running_loss = 0\n # TODO: Save the checkpoint\n checkpoint = {'state_dict': model.state_dict(),\n 'optimizer' : optimizer.state_dict,\n 'classIndex' : trainset.class_to_idx,\n 'epoch' : 5,\n 'hidden' : hidden_units,\n 'model' : model}\n\n torch.save(checkpoint, save_dir)\n print('\\nModel Saved')\n\n return model\n","sub_path":"my_functions.py","file_name":"my_functions.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"654383565","text":"'''\nCreated on 2016年3月10日\n\n@author: lin_jiang_yi\n'''\nimport sys\nfrom PyQt5.QtWidgets import QMainWindow, QLabel, QApplication\n\nclass Example(QMainWindow):\n def __init__(self):\n super().__init__()\n self.initUI()\n \n def initUI(self):\n lbl1 = QLabel('First Label',self)\n lbl1.move(15,10) #x,y y是竖线\n \n lbl1 = QLabel('Second Label',self)\n lbl1.move(35,40)\n \n lbl1 = QLabel('Last Label',self)\n lbl1.move(100,70)\n \n self.setGeometry(300,300,250,150)\n self.setWindowTitle('Absolute')\n self.show()\n\nif __name__ == '__main__':\n app= QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())","sub_path":"PyQt/Test/test11_absolute_positioning.py","file_name":"test11_absolute_positioning.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"48109213","text":"list1 = []\r\nlist2 = []\r\nn = int(input('Enter no. of elements you want to enter in a list : '))\r\nfor i in range(0, n):\r\n x = int(input())\r\n list1.append(x)\r\nprint('Original list {}'.format(list1))\r\nlist1.sort()\r\nfor i in range(len(list1) - 1):\r\n if list1[i] == list1[i + 1]:\r\n list2.append(list1[i])\r\nprint(\"list containing duplicate elements {}\".format(list2))\r\n\r\n","sub_path":"duplicate.py","file_name":"duplicate.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"442704082","text":"'''\ngiven a non-empty string s, may delete at most 1 character, \njudge if you can make it a palindrome.\nnaively using single loop to test removal each element will have timeexceed error\n'''\ndef validPalindrome(s):\n #think it as an onion, at some layer there might be a non-symmetry element\n #use 2 pointers to track elements to compare\n left_p, right_p = 0, len(s)-1\n s_list = list(s)\n while left_p < right_p:\n #do compare 2 elements\n if s_list[left_p]==s_list[right_p]:\n left_p+=1\n right_p-=1\n #then moved to inner substring\n else:\n #found the non-symmetric place, can remove either place\n test1 = s_list[:left_p]+s_list[left_p+1:]\n test2 = s_list[:right_p]+s_list[right_p+1:]\n return test1[::-1]==test1 or test2[::-1]==test2\n \n return True\n \n ","sub_path":"680. Valid Palindrome II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"131174625","text":"import os\nimport sys\nimport string\n\n#This function is to print usage of this script\ndef usage():\n\tsys.stderr.write('Usage of this script:\\n')\n\tsys.stderr.write('install.py init\\n')\n\tsys.stderr.write('install.py add [interface] [IP address] [path ID 1] [path ID 2] ... [path ID N]\\n')\n\n#main function\n#global variables\npath='/home/wei/rox3'\ndevice='/dev/rox'\nmajor_num=100\n\nif len(sys.argv)==2: \t\t\t\n\t#install RoX \n\t# 1. Compile and insert RoX kernel module\n\t# 2. Compile user-space control program\n\t# 3. Install virtual character device (rox, major number: 100)\n\t# 4. Start end_host.py\n\tif sys.argv[1]=='init':\n\t\t#Compile rox kernel module\n\t\tos.system('make\\n') \n\t\t#Compule user-space control program (a.out)\n\t\tos.system('gcc ioctl.c\\n') \n\t\t#Install character device \n\t\tos.system('mknod '+device+' c '+str(major_num)+' 1\\n') \n\t\t#Insert kernel module\n\t\tos.system('insmod rox.ko\\n') \n\t\t#Start communication script\n\t\tos.system('nohup python end_host.py &') \n\telse:\n\t\tusage()\n\t\t\nelif len(sys.argv)>=5: \n\t#add NIC and related path IDs\n\t# 1. Add NAT rules\n\t# 2. Start farpd on specific interfaces\n\tif sys.argv[1]=='add':\n\t\t#Initialize Linux Traffic Control on specific interface\n\t\tos.system('python tc.py init '+sys.argv[2]+'\\n') \n\t\tcmd='farpd -i '+sys.argv[2]+' '+sys.argv[3]+' '\n\t\tfor i in range(4,len(sys.argv)):\n\t\t\tcmd=cmd+sys.argv[i]+' '\n\t\t\t#Add first-class rule\n\t\t\tos.system('./a.out insert 1 0.0.0.0 '+sys.argv[i]+' 0 0 0 '+sys.argv[3]+' 0 0\\n') \n\t\tcmd=cmd+'\\n'\n\t\t#Start farpd\n\t\tos.system(cmd) \n\telse:\n\t\tusage()\nelse:\n\tusage()","sub_path":"rox4/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"31852169","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n'''\nsudo python sendArpReply.py -i eth0 -sip 1.1.1.2 -dip 2.2.0.33 -smac 18:66:da:85:f9:ed -dmac cc:37:ab:a0:a8:41\n'''\n\nimport time\n\nfrom scapy.all import *\n\nfrom sam.base.argParser import *\n\n\nclass ArgParser(ArgParserBase):\n def __init__(self, *args, **kwargs):\n super(ArgParser, self).__init__(*args, **kwargs)\n self.parser = argparse.ArgumentParser(description='send Arp frame.', add_help=False)\n self.parser.add_argument('-i', metavar='outIntf', type=str, nargs='?', const=1, default='toClassifier',\n help=\"output interface\")\n self.parser.add_argument('-sip', metavar='psrc', type=str, nargs='?', const=1, default=\"192.168.123.1\",\n help=\"arp source ip\")\n self.parser.add_argument('-dip', metavar='replyIP', type=str, nargs='?', const=1, default=\"0.0.0.0\",\n help=\"reply dest IP\")\n self.parser.add_argument('-smac', metavar='hwsrc', type=str, nargs='?', const=1, default=\"fe:54:00:05:4d:7d\",\n help=\"hw src mac\")\n self.parser.add_argument('-dmac', metavar='hwdst', type=str, nargs='?', const=1, default=\"fe:54:00:05:4d:7d\",\n help=\"hw dst mac\")\n self.parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,\n help='Example usage: python sendArpReply.py -i eno2 -sip 2.2.0.36 -dip 2.2.0.33 -smac 18:66:da:86:4c:16 -dmac cc:37:ab:a0:a8:41')\n self.args = self.parser.parse_args()\n\n\ndef sendArpReply(outIntf, psrc, replyIP, hwsrc, hwdst):\n arp = ARP(op=2, psrc=psrc, pdst=replyIP, hwsrc=hwsrc)\n frame = Ether(src=hwsrc , dst=hwdst) / arp\n sendp(frame, iface=outIntf, verbose=0)\n print(\"send an arp reply frame\")\n # frame.show()\n\n\nif __name__==\"__main__\":\n argParser = ArgParser()\n outIntf = argParser.getArgs()['i']\n psrc = argParser.getArgs()['sip']\n replyIP = argParser.getArgs()['dip']\n hwsrc = argParser.getArgs()['smac']\n hwdst = argParser.getArgs()['dmac']\n while True:\n time.sleep(1)\n sendArpReply(outIntf=outIntf, psrc=psrc,\n replyIP=replyIP, hwsrc=hwsrc, hwdst=hwdst)\n","sub_path":"autoProfiler/fixtures/sendArpReply.py","file_name":"sendArpReply.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"603278540","text":"#! /usr/bin/env python3\n\n\"\"\"\nCe module contient des fonctions qui sélectionnent\nles donneurs et les accepteurs potentiels de LH,\npuis calculent leur distance.\n\"\"\"\n\ndef Select_HbondD(ListAtom, ATOM_Dnn):\n \"\"\"\n Sélectionne la liste des atomes donneurs de LH\n\n Argument(s): (1) Liste des objets \"atome\"\n (2) Liste des atomes donneurs\n \"\"\"\n List_HbondD = []\n for atome in ListAtom:\n if atome.Nom in ATOM_Dnn:\n if atome.Resid==\"PRO\" and atome.Nom==\"N\":\n continue\n List_HbondD.append(atome)\n\n return List_HbondD\n\ndef Select_HbondA(ListAtom, ATOM_Acc):\n \"\"\"\n Sélectionne la liste des atomes accepteurs de LH\n\n Argument(s): (1) Liste des objets \"atome\"\n (2) Liste des atomes accepteurs\n \"\"\"\n List_HbondA = []\n for atome in ListAtom:\n if atome.Nom in ATOM_Acc:\n if atome.Resid==\"PRO\" and atome.Nom==\"N\":\n continue\n List_HbondA.append(atome)\n\n return List_HbondA\n\n\ndef Calcul_LH(List_HbondD, List_HbondA):\n \"\"\"\n Calcule la distance entre un atome donneur et un atome accepteur.\n Renvoie une liste des atomes qui interagissent et leur distance.\n\n Argument(s): (1) Liste des potentiels donneurs\n (2) Liste des potentiels accepteurs\n \"\"\"\n LH=[]\n for at1 in List_HbondD:\n for at2 in List_HbondA:\n if at1.Resid==\"PRO\" and at1.Nom==\"N\":\n continue\n \n elif round(((float(at1.x)-float(at2.x))**2 + (float(at1.y)-float(at2.y))**2 + \\\n (float(at1.z)-float(at2.z))**2)**0.5, 2)==0.00:\n continue\n\n elif at1.Nom == at2.Nom or at1.Num == at2.Num:\n continue\n\n elif round(((float(at1.x)-float(at2.x))**2 + (float(at1.y)-float(at2.y))**2 + \\\n (float(at1.z)-float(at2.z))**2)**0.5, 2) < 3.00 \\\n and (at1.Nom!=\"SG\" or at2.Nom!=\"SG\"):\n Dist = round(((float(at1.x)-float(at2.x))**2 + (float(at1.y)-float(at2.y))**2 + \\\n (float(at1.z)-float(at2.z))**2)**0.5, 2)\n LH.append([at1, at2, Dist])\n\n elif round(((float(at1.x)-float(at2.x))**2 + (float(at1.y)-float(at2.y))**2 + \\\n (float(at1.z)-float(at2.z))**2)**0.5, 2) < 4.00 \\\n and (at1.Nom==\"SG\" or at2.Nom==\"SG\"):\n Dist = round(((float(at1.x)-float(at2.x))**2 + (float(at1.y)-float(at2.y))**2 + \\\n (float(at1.z)-float(at2.z))**2)**0.5, 2)\n LH.append([at1, at2, Dist])\n return LH\n\n\n","sub_path":"Programme/LiaisonsHydg.py","file_name":"LiaisonsHydg.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"620229773","text":"from django.db import models\nfrom apps.funcionario.models import funcionario\nfrom apps.empresa.models import empresa\nfrom apps.contas_pagar.models import contas_pagar\n\nclass pagamento_func(models.Model):\n\n conta_func = models.ForeignKey(funcionario, on_delete=models.CASCADE, null=True, blank=True)\n localidade = models.ForeignKey(empresa, on_delete=models.CASCADE, verbose_name='Empresa')\n valor_pago_func = models.DecimalField('Valor pago ao funcionario', max_digits=7, decimal_places=2)\n data_pagamento = models.DateField('Data do pagamento')\n pago = models.BooleanField(default=False)\n\n def __str__(self):\n return str(self.conta_func)\n\n objects = models\n\n\nclass pagamento_cont(models.Model):\n\n conta_pag = models.ForeignKey(contas_pagar, on_delete=models.CASCADE, null=True, blank=True,verbose_name='Conta a pagar')\n localidade = models.ForeignKey(empresa, on_delete=models.CASCADE, verbose_name='Empresa')\n valor_pago_conta = models.DecimalField('Valor pago da conta', max_digits=7, decimal_places=2)\n data_pagamento = models.DateField('Data do pagamento')\n\n def __str__(self):\n return self.conta_pag\n\n objects = models","sub_path":"apps/pagamento/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"413257688","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\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/drqascripts/retriever/prep_wikipedia.py\n# Compiled at: 2019-08-29 06:03:42\n# Size of source mod 2**32: 1135 bytes\n\"\"\"Preprocess function to filter/prepare Wikipedia docs.\"\"\"\nimport regex as re\nfrom html.parser import HTMLParser\nPARSER = HTMLParser()\nBLACKLIST = set(['23443579', '52643645'])\n\ndef preprocess(article):\n for k, v in article.items():\n article[k] = PARSER.unescape(v)\n\n if article['id'] in BLACKLIST:\n return\n if '(disambiguation)' in article['title'].lower():\n return\n if '(disambiguation page)' in article['title'].lower():\n return\n else:\n if re.match('(List of .+)|(Index of .+)|(Outline of .+)', article['title']):\n return\n return {'id':article['title'], 'text':article['text']}","sub_path":"pycfiles/fever_drqa-1.0.11-py3.6/prep_wikipedia.cpython-36.py","file_name":"prep_wikipedia.cpython-36.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"502102701","text":"def partition(numbers,start,end):\n pivot=numbers[end] \n i = start \n for j in range(start , end): \n if numbers[j] <= pivot: \n numbers[i],numbers[j] = numbers[j],numbers[i] \n i = i+1\n numbers[i],numbers[end] = numbers[end],numbers[i] \n return ( i ) \n \ndef quick_sort(numbers, start, end):\n while start < end:\n pi = partition(numbers, start, end)\n if(pi - 1 - start0\n self.current_pocketed = []\n self.pocketed_striker = False\n self.striker.velocity = Vector2()\n if change:\n self.player_turn = (self.player_turn + 1) % 2\n\n def current_player(self):\n return \"WHITE\" if self.player_turn == 0 else \"BLACK\"\n\n @staticmethod\n def get_player(player):\n return \"WHITE\" if player == 0 else \"BLACK\"\n\n def apply_rules(self):\n if self.first_collision:\n coin1, coin2 = self.first_collision\n assert isinstance(coin1, Striker) or isinstance(coin2, Striker)\n coin = coin2 if isinstance(coin1, Striker) else coin1\n if not isinstance(coin, Queen):\n if self.player_turn != coin.get_player():\n self.foul_count[self.player_turn] += 1\n self.first_collision = None\n if self.pocketed_striker:\n if self.pocketed_queen and not self.has_queen[0] and not self.has_queen[1]:\n self.queen_on_hold = False\n self.pocketed_queen = False\n self.queen.reset()\n for coin in self.current_pocketed:\n if coin.get_player() == self.player_turn:\n self.player_coins[coin.get_player()].append(coin)\n self.pocketed_coins[coin.get_player()].remove(coin)\n coin.reset()\n self.foul_count[self.player_turn] += 1\n self.__update_turn__(change=True)\n\n elif self.pocketed_queen and not self.has_queen[0] and not self.has_queen[1]:\n for coin in self.current_pocketed:\n if coin.get_player() == self.player_turn:\n self.has_queen[self.player_turn] = True\n self.queen_on_hold = False\n self.__update_turn__(change=False)\n break\n else:\n if self.queen_on_hold:\n self.queen_on_hold = False\n self.pocketed_queen = False\n self.queen.reset()\n self.__update_turn__(change=True)\n else:\n self.queen_on_hold = True\n self.__update_turn__(change=False)\n\n else:\n for coin in self.current_pocketed:\n if coin.get_player() == self.player_turn:\n self.__update_turn__(change=False)\n break\n else:\n self.__update_turn__(change=True)\n\n def draw(self, win):\n self.board.draw(win)\n \"\"\"\n Temporary Changes\n \"\"\"\n b=0\n w=0\n for c in self.players_coins[0]:\n if c.color==black:\n b+=1\n else:\n w+=1\n \n count_player_one=b*10+w*20\n b=0\n w=0\n for c in self.players_coins[1]:\n if c.color==black:\n b+=1\n else:\n w+=1\n \n count_player_two=b*10+w*20\n\n # coins = self.player_coins[0] + self.player_coins[1]\n if not self.pocketed_striker:\n coins.append(self.striker)\n if not self.pocketed_queen:\n coins.append(self.queen)\n for coin in coins:\n coin.draw(win)\n if self.has_queen[0]:\n captured_coins_0.append(self.queen)\n \n captured_coins_0 = self.pocketed_coins[0].copy()\n if self.has_queen[0]:\n \"\"\"\n Temporary Changes\n \"\"\"\n count_player_one=count_player_one+50\n\n # captured_coins_0.append(self.queen)\n else:\n count_player_two=count_player_two+50\n\n\n captured_coins_1 = self.pocketed_coins[1].copy()\n if self.has_queen[1]:\n captured_coins_1.append(self.queen)\n self.board.draw_captured_coins(win, 0, captured_coins_0)\n self.board.draw_captured_coins(win, 1, captured_coins_1)\n","sub_path":"carom.py","file_name":"carom.py","file_ext":"py","file_size_in_byte":9784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"450360372","text":"from bs4 import BeautifulSoup\nimport time\nfrom requests import get\nimport csv\nimport pandas as pd\n\nlinks = []\npages = [str(i) for i in range(1,100)]\nq = \"gravity\"\n\nfor page in pages:\n print(\"Page\", page)\n time.sleep(2)\n response = get(\n 'https://nasasearch.nasa.gov/search?affiliate=nasa&page=' + str(page) + '&query=q&utf8=%E2%9C%93')\n print(response)\n time.sleep(2)\n html_soup = BeautifulSoup(response.text, 'html.parser')\n\n movie_containers = html_soup.find_all('div', class_='content-block-item result')\n\n for container in movie_containers:\n link = container.h4.a\n if link and 'href' in link.attrs:\n all_links = link.get('href')\n links.append(all_links)\n print(links)\n\ndata = pd.DataFrame({'Urls': links})\ndata.to_csv('links.csv')\nprint(len(links))\n\n","sub_path":"webscraper.py","file_name":"webscraper.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"241967649","text":"# -*- coding: utf-8 -*-\n# @Author: wujiyu\n# @Date: 2017-08-11 23:03:05\n# @Last Modified by: wujiyu\n# @Last Modified time: 2017-08-30 17:09:34\n\nfrom _request import request_soup\n\nmarkets = [\n \"bitstamp\", \"coinbase\", \"okcoin\", \"okcoincom\", \"huobi\", \"yunbi\",\n \"binance\", \"bter\", \"cnbtc\", \"jubi\", \"btc9\", \"btc38\", \"yuanbaohui\"\n]\n\n\ndef do_coin_price(coin, bot, contact, cost_datas):\n coins = \"\"\n for market in markets:\n coins = \"%s|%s_%s\" % (coins, coin, market)\n url = \"http://static2.sosobtc.com/plugin/market?others=%s&short_tip=1&show_tip=1&td_height=&row=price|buy|sell|high|low|vol\" % coins\n soup, text = request_soup(url)\n\n rs = None\n item = cost_datas.get(coin)\n if item:\n rs = \"%s众筹价格为:%s\\n\" % (coin, item[\"price\"])\n else:\n rs = \"\"\n\n if not soup:\n if len(rs) == 0:\n rs = \"未找到对应的币种\"\n bot.SendTo(contact, rs)\n return\n\n trs = soup.table.find_all(\"tr\")\n\n for tr in trs:\n exchange = tr.get(\"data-id\")\n row_price = tr.find(\"td\", class_=\"row-price\").get(\"data-price\")\n # row_sell = tr.find(\"td\", class_=\"row-sell\").font.text\n # row_buy = tr.find(\"td\", class_=\"row-buy\").font.text.font.text\n row_high = tr.find(\"td\", class_=\"row-high\").font.text\n row_low = tr.find(\"td\", class_=\"row-low\").font.text\n row_vol = tr.find(\"td\", class_=\"row-vol\").find(\"span\", class_=\"vol\").text\n\n rs = \"%s%s,新:[%s],高:[%s],低:[%s],量:[%s]\\n\" % (rs, exchange, row_price, row_high, row_low, row_vol)\n # rs = \"%s%s, 最新价:%s\\n\" % (rs, exchange, row_price)\n if len(rs) == 0:\n rs = \"未找到对应的币种\"\n if bot and contact:\n bot.SendTo(contact, rs)\n else:\n print(rs)\n\n\nif __name__ == '__main__':\n do_coin_price(\"eos\", None, None, {})\n","sub_path":"qq/plugins/util/_market.py","file_name":"_market.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"319297998","text":"import logging\nimport os\nimport sys\nimport tempfile\n\nimport pytest\n\nfrom generic_parser.dict_parser import ParameterError, ArgumentError\nfrom generic_parser.entry_datatypes import get_multi_class, DictAsString, BoolOrString, BoolOrList\nfrom generic_parser.entrypoint_parser import (EntryPointParameters,\n entrypoint, EntryPoint,\n OptionsError, split_arguments,\n create_parameter_help, save_options_to_config\n )\nfrom generic_parser.tools import silence, print_dict_tree, TempStringLogger\n\nLOG = logging.getLogger(__name__)\n\n\n# Tests ########################################################################\n\n\n# Options Tests\n\n\ndef test_strict_wrapper_fail():\n with pytest.raises(OptionsError):\n @entrypoint(get_simple_params(), strict=True)\n def strict(opt, unknown): # too many option-structures\n pass\n\n\ndef test_class_wrapper_fail():\n with pytest.raises(OptionsError):\n class MyClass(object):\n @entrypoint(get_simple_params())\n def fun(self, opt): # too few option-structures\n pass\n\n\ndef test_normal_wrapper_fail():\n with pytest.raises(OptionsError):\n @entrypoint(get_simple_params())\n def fun(opt, unknown, more): # too many option-structures\n pass\n\n\ndef test_class_functions():\n class MyClass(object):\n @classmethod\n @entrypoint(get_simple_params())\n def fun(cls, opt, unknown):\n pass\n\n\ndef test_instance_functions():\n class MyClass(object):\n @entrypoint(get_simple_params())\n def fun(self, opt, unknown):\n pass\n\n\n# Parameter Tests\n\n\ndef test_wrong_param_creation_name():\n with pytest.raises(ParameterError):\n EntryPoint([{\"flags\": \"--flag\"}])\n\n\ndef test_wrong_param_creation_other():\n with pytest.raises(TypeError):\n EntryPoint([{\"name\": \"test\", \"flags\": \"--flag\", \"other\": \"unknown\"}])\n\n\ndef test_choices_not_iterable():\n with pytest.raises((ParameterError, ValueError)):\n # Value error comes from argparse (would be caught in dict_parser as well)\n EntryPoint([{\"name\": \"test\", \"flags\": \"--flag\",\n \"choices\": 3,\n }])\n\n\ndef test_missing_flag_replaced_by_name():\n ep = EntryPoint([{\"name\": \"test\"}])\n\n assert len(ep.parameter[0]) == 2\n assert ep.parameter[0]['flags'] == ['--test']\n assert ep.parameter[0]['name'] == 'test'\n\n\ndef test_missing_flag_replaced_by_name_in_multiple_lists():\n ep = EntryPoint([{\"name\": \"test\"},\n {\"name\": \"thermos_coffee\"},\n {\"name\": \"tee_kessel\", \"flags\": ['--tee_kessel']}])\n\n assert len(ep.parameter[0]) == 2\n assert ep.parameter[0]['flags'] == ['--test']\n assert ep.parameter[0]['name'] == 'test'\n\n assert len(ep.parameter[1]) == 2\n assert ep.parameter[1]['flags'] == ['--thermos_coffee']\n assert ep.parameter[1]['name'] == 'thermos_coffee'\n\n assert len(ep.parameter[2]) == 2\n assert ep.parameter[2]['flags'] == ['--tee_kessel']\n assert ep.parameter[2]['name'] == 'tee_kessel'\n\n\n# Argument Tests\n\n\ndef test_strict_pass():\n strict_function(accel=\"LHCB1\", anint=3)\n\n\ndef test_strict_fail():\n with pytest.raises(ArgumentError):\n strict_function(accel=\"LHCB1\", anint=3, unkown=\"not_found\")\n\n\ndef test_as_kwargs():\n opt, unknown = paramtest_function(\n name=\"myname\",\n int=3,\n list=[4, 5, 6],\n unknown=\"myfinalargument\"\n )\n assert opt.name == \"myname\"\n assert opt.int == 3\n assert len(opt.list) == 3\n assert opt.list[1] == 5\n assert len(unknown) > 0\n\n\ndef test_as_string():\n opt, unknown = paramtest_function(\n [\"--name\", \"myname\",\n \"--int\", \"3\",\n \"--list\", \"4\", \"5\", \"6\",\n \"--other\"]\n )\n assert opt.name == \"myname\"\n assert opt.int == 3\n assert len(opt.list) == 3\n assert opt.list[1] == 5\n assert len(unknown) > 0\n\n\ndef test_as_config():\n with tempfile.TemporaryDirectory() as cwd:\n cfg_file = os.path.join(cwd, \"config.ini\")\n with open(cfg_file, \"w\") as f:\n f.write(\"\\n\".join([\n \"[Section]\",\n \"name = 'myname'\",\n \"int = 3\",\n \"list = [4, 5, 6]\",\n \"unknown = 'other'\",\n ]))\n\n # test config as kwarg\n opt1, unknown1 = paramtest_function(\n entry_cfg=cfg_file, section=\"Section\"\n )\n\n # test config as commandline args\n opt2, unknown2 = paramtest_function(\n [\"--entry_cfg\", cfg_file, \"--section\", \"Section\"]\n )\n\n assert opt1.name == \"myname\"\n assert opt1.int == 3\n assert len(opt1.list) == 3\n assert opt1.list[1] == 5\n assert len(unknown1) > 0\n\n assert opt2.name == \"myname\"\n assert opt2.int == 3\n assert len(opt2.list) == 3\n assert opt2.list[1] == 5\n assert len(unknown2) > 0\n\n\ndef test_all_missing():\n with pytest.raises(SystemExit):\n with silence():\n some_function()\n\n\ndef test_required_missing():\n with pytest.raises(ArgumentError):\n some_function(accel=\"LHCB1\")\n\n\ndef test_wrong_choice():\n with pytest.raises(ArgumentError):\n some_function(accel=\"accel\", anint=3)\n\n\ndef test_wrong_type():\n with pytest.raises(ArgumentError):\n some_function(accel=\"LHCB1\", anint=3.)\n\n\ndef test_wrong_type_in_list():\n with pytest.raises(ArgumentError):\n some_function(accel=\"LHCB1\", anint=3, alist=[\"a\", \"b\"])\n\n\ndef test_not_enough_length():\n with pytest.raises(ArgumentError):\n some_function(accel=\"LHCB1\", anint=3, alist=[])\n\n\n# Config Saver Test\n\ndef test_save_options():\n opt, unknown = paramtest_function(\n name=\"myname\",\n int=3,\n list=[4, 5, 6],\n unknown=\"myfinalargument\",\n unknoown=10,\n )\n with tempfile.TemporaryDirectory() as cwd:\n cfg_file = os.path.join(cwd, \"config.ini\")\n save_options_to_config(cfg_file, opt, unknown)\n opt_load, unknown_load = paramtest_function(entry_cfg=cfg_file)\n\n _assert_dicts(opt, opt_load)\n _assert_dicts(unknown, unknown_load)\n\n\ndef test_save_cli_options():\n opt, unknown = paramtest_function(\n [\"--name\", \"myname\",\n \"--int\", \"3\",\n \"--list\", \"4\", \"5\", \"6\",\n \"--other\"]\n )\n with tempfile.TemporaryDirectory() as cwd:\n cfg_file = os.path.join(cwd, \"config.ini\")\n save_options_to_config(cfg_file, opt, unknown)\n opt_load, unknown_load = paramtest_function(entry_cfg=cfg_file)\n\n _assert_dicts(opt, opt_load)\n assert len(unknown_load) == 0\n\n\ndef _assert_dicts(d1, d2):\n for key in d1:\n assert d1[key] == d2[key]\n assert len(d2) == len(d1)\n\n\n# Test Special Datatypes\n\n\ndef test_multiclass_class():\n float_str = get_multi_class(float, str)\n assert isinstance(1., float_str)\n assert isinstance(\"\", float_str)\n assert isinstance(float_str(1.), float)\n assert isinstance(float_str(1), float)\n assert not isinstance(float_str(1), int)\n assert float_str(\"myString\") == \"myString\"\n assert issubclass(str, float_str)\n assert issubclass(float, float_str)\n\n\ndef test_dict_as_string_class():\n assert isinstance({}, DictAsString)\n assert isinstance(\"\", DictAsString)\n assert isinstance(DictAsString(\"{}\"), dict)\n assert issubclass(dict, DictAsString)\n assert issubclass(str, DictAsString)\n\n with pytest.raises(ValueError):\n DictAsString(\"1\")\n\n\ndef test_bool_or_str_class():\n assert isinstance(True, BoolOrString)\n assert isinstance(\"myString\", BoolOrString)\n assert BoolOrString(\"True\") is True\n assert BoolOrString(\"1\") is True\n assert BoolOrString(True) is True\n assert BoolOrString(1) is True\n assert BoolOrString(\"myString\") == \"myString\"\n assert issubclass(bool, BoolOrString)\n assert issubclass(str, BoolOrString)\n assert not issubclass(list, BoolOrString)\n\n\ndef test_bool_or_list_class():\n assert isinstance(True, BoolOrList)\n assert isinstance([], BoolOrList)\n assert BoolOrList(\"False\") is False\n assert BoolOrList(\"0\") is False\n assert BoolOrList(False) is False\n assert BoolOrList(0) is False\n assert BoolOrList(\"[1, 2]\") == [1, 2]\n assert issubclass(bool, BoolOrList)\n assert issubclass(list, BoolOrList)\n assert not issubclass(str, BoolOrList)\n\n\ndef test_multiclass():\n IntOrStr = get_multi_class(int, str)\n\n @entrypoint([dict(flags=\"--ios\", name=\"ios\", type=IntOrStr)], strict=True)\n def fun(opt):\n return opt\n\n opt = fun(ios=3)\n assert opt.ios == 3\n\n opt = fun(ios='3')\n assert opt.ios == '3'\n\n opt = fun([\"--ios\", \"3\"])\n assert opt.ios == 3\n\n opt = fun([\"--ios\", \"'3'\"])\n assert opt.ios == \"'3'\"\n\n\ndef test_dict_as_string():\n @entrypoint([dict(flags=\"--dict\", name=\"dict\", type=DictAsString)], strict=True)\n def fun(opt):\n return opt\n\n opt = fun(dict={'int': 5, 'str': 'hello'})\n assert opt.dict['int'] == 5\n assert opt.dict['str'] == 'hello'\n\n opt = fun([\"--dict\", \"{'int': 5, 'str': 'hello'}\"])\n assert opt.dict['int'] == 5\n assert opt.dict['str'] == 'hello'\n\n\ndef test_bool_or_str():\n @entrypoint([dict(flags=\"--bos\", name=\"bos\", type=BoolOrString)], strict=True)\n def fun(opt):\n return opt\n\n opt = fun(bos=True)\n assert opt.bos is True\n\n opt = fun(bos='myString')\n assert opt.bos == 'myString'\n\n opt = fun([\"--bos\", \"False\"])\n assert opt.bos is False\n\n opt = fun([\"--bos\", \"1\"])\n assert opt.bos is True\n\n opt = fun([\"--bos\", \"myString\"])\n assert opt.bos == \"myString\"\n\n with tempfile.TemporaryDirectory() as cwd:\n cfg_file = os.path.join(cwd, \"bos.ini\")\n with open(cfg_file, \"w\") as f:\n f.write(\"[Section]\\nbos = 'myString'\")\n opt = fun(entry_cfg=cfg_file)\n assert opt.bos == \"myString\"\n\n\ndef test_bool_or_str_cfg():\n @entrypoint([dict(flags=\"--bos1\", name=\"bos1\", type=BoolOrString),\n dict(flags=\"--bos2\", name=\"bos2\", type=BoolOrString)], strict=True)\n def fun(opt):\n return opt\n\n with tempfile.TemporaryDirectory() as cwd:\n cfg_file = os.path.join(cwd, \"bos.ini\")\n with open(cfg_file, \"w\") as f:\n f.write(\"[Section]\\nbos1 = 'myString'\\nbos2 = True\")\n opt = fun(entry_cfg=cfg_file)\n assert opt.bos1 == 'myString'\n assert opt.bos2 is True\n\n\ndef test_bool_or_list():\n @entrypoint([dict(flags=\"--bol\", name=\"bol\", type=BoolOrList)], strict=True)\n def fun(opt):\n return opt\n\n opt = fun(bol=True)\n assert opt.bol is True\n\n opt = fun(bol=[1, 2])\n assert opt.bol == [1, 2]\n\n opt = fun([\"--bol\", \"[1, 2]\"])\n assert opt.bol == [1, 2]\n\n opt = fun([\"--bol\", \"0\"])\n assert opt.bol is False\n\n opt = fun([\"--bol\", \"True\"])\n assert opt.bol is True\n\n\ndef test_bool_or_list_cfg():\n @entrypoint([dict(flags=\"--bol1\", name=\"bol1\", type=BoolOrList),\n dict(flags=\"--bol2\", name=\"bol2\", type=BoolOrList)], strict=True)\n def fun(opt):\n return opt\n\n with tempfile.TemporaryDirectory() as cwd:\n cfg_file = os.path.join(cwd, \"bol.ini\")\n with open(cfg_file, \"w\") as f:\n f.write(\"[Section]\\nbol1 = 1,2\\nbol2 = True\")\n opt = fun(entry_cfg=cfg_file)\n assert opt.bol1 == [1, 2]\n assert opt.bol2 is True\n\n\n# Test the Helpers #################################################################\n\n\ndef test_split_listargs():\n args = [\"--a1\", \"1\", \"--a2\", \"2\", \"--a3\", \"3\"]\n split = split_arguments(args, get_simple_params())\n assert split[0].pop(\"arg1\", None) == \"1\"\n assert split[0].pop(\"arg2\", None) == \"2\"\n assert len(split[0]) == 0\n assert split[1] == args[-2:]\n\n\ndef test_split_dictargs():\n args = {\"arg1\": \"1\", \"arg2\": 2, \"arg3\": 3}\n split = split_arguments(args, get_simple_params())\n assert split[0].pop(\"arg1\", None) == \"1\"\n assert split[0].pop(\"arg2\", None) == 2\n assert len(split[0]) == 0\n assert split[1].pop(\"arg3\") == 3\n\n\ndef test_create_param_help():\n this_module = sys.modules[__name__]\n entrypoint_module = sys.modules[create_parameter_help.__module__].__name__\n with TempStringLogger(entrypoint_module) as log:\n create_parameter_help(this_module)\n text = log.get_log()\n for name in get_params().keys():\n assert name in text\n\n\ndef test_create_param_help_other():\n this_module = sys.modules[__name__]\n entrypoint_module = sys.modules[create_parameter_help.__module__].__name__\n with TempStringLogger(entrypoint_module) as log:\n create_parameter_help(this_module, \"get_other_params\")\n text = log.get_log()\n for name in get_other_params().keys():\n assert name in text\n\n\n# Example Parameter Definitions ################################################\n\n\ndef get_simple_params():\n \"\"\" Parameters as a list of dicts, to test this behaviour as well.\"\"\"\n return [{\"name\": \"arg1\", \"flags\": \"--a1\", },\n {\"name\": \"arg2\", \"flags\": \"--a2\", }\n ]\n\n\ndef get_testing_params():\n \"\"\" Parameters as a dict of dicts, to test this behaviour as well.\"\"\"\n return {\n \"name\": dict(flags=\"--name\", type=str),\n \"int\": dict(flags=\"--int\", type=int),\n \"list\": dict(flags=\"--list\", type=int, nargs=\"+\")\n }\n\n\ndef get_params():\n \"\"\" Parameters defined with EntryPointArguments (which is a dict *cough*) \"\"\"\n args = EntryPointParameters()\n args.add_parameter(name=\"accel\",\n flags=[\"-a\", \"--accel\"],\n help=\"Which accelerator: LHCB1 LHCB2 LHCB4? SPS RHIC TEVATRON\",\n choices=[\"LHCB1\", \"LHCB2\", \"LHCB5\"],\n required=True,\n )\n args.add_parameter(name=\"anint\",\n flags=[\"-i\", \"--int\"],\n help=\"Just a number.\",\n type=int,\n required=True,\n )\n args.add_parameter(name=\"alist\",\n flags=[\"-l\", \"--lint\"],\n help=\"Just a number.\",\n type=int,\n nargs=\"+\",\n )\n args.add_parameter(name=\"anotherlist\",\n flags=[\"-k\", \"--alint\"],\n help=\"list.\",\n type=str,\n nargs=3,\n default=[\"a\", \"c\", \"f\"],\n choices=[\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"],\n ),\n return args\n\n\ndef get_other_params():\n \"\"\" For testing the create_param_help()\"\"\"\n args = EntryPointParameters({\n \"arg1\": dict(flags=\"--arg1\", help=\"A help.\", default=1,),\n \"arg2\": dict(flags=\"--arg2\", help=\"More help.\", default=2,),\n \"arg3\": dict(flags=\"--arg3\", help=\"Even more...\", default=3,),\n \"arg4\": dict(flags=\"--arg4\", help=\"...heeeeeeeeelp.\", default=4,),\n })\n return args\n\n\n# Example Wrapped Functions ####################################################\n\n\n@entrypoint(get_params())\ndef some_function(options, unknown_options):\n LOG.debug(\"Some Function\")\n print_dict_tree(options, print_fun=LOG.debug)\n LOG.debug(\"Unknown Options: \\n {:s}\".format(str(unknown_options)))\n LOG.debug(\"\\n\")\n\n\n@entrypoint(get_params(), strict=True)\ndef strict_function(options):\n LOG.debug(\"Strict Function\")\n print_dict_tree(options, print_fun=LOG.debug)\n LOG.debug(\"\\n\")\n\n\n@entrypoint(get_testing_params())\ndef paramtest_function(opt, unknown):\n return opt, unknown\n","sub_path":"tests/test_entrypoint.py","file_name":"test_entrypoint.py","file_ext":"py","file_size_in_byte":15594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6123631","text":"'''\r\n第一步. 把字符串6个一组折叠起来,比如wangximing则变为:\r\nwangxi\r\nming\r\n\r\n第二步. 把所有垂直在同一个位置的字符的ascii码值相加,得出6个数字,如上面的例子,则得出:\r\n228 202 220 206 120 105\r\n\r\n第三步. 再把每个数字“缩位”处理:就是把每个位的数字相加,得出的数字如果不是一位数字,就再缩位,直到变成一位数字为止。例如: 228 => 2+2+8=12 => 1+2=3\r\n\r\n'''\r\nn = int(input())\r\nfor k in range(n):\r\n name = input()\r\n n = len(name)//6\r\n m = len(name)%6\r\n mat = [[name[6*i+j]for j in range(6)]for i in range(n)]\r\n mat.append(list(name[-m:]))\r\n asc = [0,0,0,0,0,0]\r\n for i in range(n):\r\n for j in range(6):\r\n asc[j] += ord(mat[i][j])\r\n for i in range(m):\r\n asc[i] += ord(mat[-1][i])\r\n for i in range(6):\r\n while asc[i]>=10:\r\n a = 0\r\n for j in str(asc[i]):\r\n a += int(j)\r\n asc[i] = a\r\n for i in range(6):\r\n if(i == 5):\r\n print(asc[i])\r\n else:\r\n print(asc[i], end='')","sub_path":"0820.py","file_name":"0820.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"221619624","text":"class Node: \n \n # Function to initialise the node object \n def __init__(self, data): \n self.data = data # Assign data \n self.next = None # Initialize next as null \n \n# Linked List class contains a Node object \nclass LinkedList: \n \n # Function to initialize head \n def __init__(self): \n self.head = None\n\n def push(self, new_data): \n new_node = Node(new_data) \n new_node.next = self.head \n self.head = new_node\n \n def CountNum(self, num):\n print('abc')\n temp = self.head\n count1 = 0\n while(temp is not None):\n if temp.data == num:\n count1 = count1 + 1\n temp = temp.next\n return(count1)\n\n\nllist = LinkedList() \nllist.push(1) \nllist.push(3) \nllist.push(1) \nllist.push(2) \nllist.push(1) \n \n# Check for the count function \nprint (llist.CountNum(3))\n","sub_path":"llist/CountNum.py","file_name":"CountNum.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"523213413","text":"from csv_to_json.transforms.column_transforms import *\n\n\ndef test_item_generator():\n mapping = {\n 'foo': {\n 'lookup_key': 'foo'\n },\n 'bar': [\n {\n 'lookup_key': 'foo'\n },\n {\n 'false_key': 'bar'\n }\n ],\n 'baz': {\n 'false_key': 'baz'\n }\n }\n sub_maps = list(item_generator(mapping, 'lookup_key'))\n assert len(sub_maps) == 2\n for sub_map in sub_maps:\n if 'foo' in sub_map:\n assert 'lookup_key' in sub_map['foo']\n else:\n assert 'lookup_key' in sub_map\n","sub_path":"test/transform-tests/column_transforms_test.py","file_name":"column_transforms_test.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"164730613","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, absolute_import, division, print_function\n\nimport logging\nimport retrying\nimport requests\nfrom fake_useragent import UserAgent\n\nlogger = logging.getLogger(__name__)\n\n\nclass Proxy(object):\n def __init__(self):\n self.txt_list = [\n 'http://pubproxy.com/api/proxy?limit=5&format=txt&type=http',\n 'http://pubproxy.com/api/proxy?limit=5&format=txt&type=https',\n 'http://ab57.ru/downloads/proxylist.txt',\n # 'http://www.proxylists.net/http_highanon.txt',\n # 'http://www.proxylists.net/https_highanon.txt',\n # 'http://www.proxylists.net/http.txt',\n # 'http://api.xicidaili.com/free2016.txt',\n # 'http://static.fatezero.org/tmp/proxy.txt',\n # 'http://comp0.ru/downloads/proxylist.txt',\n # 'https://www.rmccurdy.com/scripts/proxy/good.txt'\n ]\n self.user_agent = UserAgent()\n\n self.proxies = []\n self.result = []\n\n @property\n def _get_headers(self):\n return {\"User-Agent\": self.user_agent.random}\n\n @property\n def _get_proxies(self):\n if self.proxies:\n proxy = self.proxies.pop()\n return {proxy['type']: proxy[\"hash\"]}\n\n @retrying.retry(stop_max_attempt_number=5)\n def parse_url(self, url):\n response = requests.get(url, headers=self._get_headers, proxies=self._get_proxies, timeout=10)\n assert response.status_code == 200\n return response\n\n def extract_proxy(self, url):\n try:\n resp = self.parse_url(url)\n except Exception as e:\n logger.error(\"[-] Request url {url} error: {error}\".format(url=url, error=str(e)))\n return []\n\n proxies_list = resp.text.splitlines()\n return [{'host': proxy.split(\":\")[0], 'port': int(proxy.split(\":\")[1]), 'from': 'txt'} for proxy in proxies_list]\n\n def start(self):\n for url in self.txt_list:\n proxies_list = self.extract_proxy(url)\n self.result.extend(proxies_list)\n\n\nif __name__ == '__main__':\n p = Proxy()\n p.start()\n\n for i in p.result:\n print(i)\n\n print(len(p.result))\n","sub_path":"getproxy/plugin/txt.py","file_name":"txt.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"351547460","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields\n\n\nclass GDPRBase(models.AbstractModel):\n _name = \"gdpr.base\"\n\n gdpr_accepted = fields.Boolean(string=\"GDPR accepted\",\n help=\"This field can be used on webforms to collect the gdpr consent of the\"\n \"partner\")\n","sub_path":"addons-own/fso_gdpr/models/gdpr_base_abstract.py","file_name":"gdpr_base_abstract.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"237368357","text":"import json\nimport unittest\n\nfrom config import config\nfrom app import create_app, db\n\nclass TestAPI(unittest.TestCase):\n def setUp(self):\n enviroment = config['test']\n self.app = create_app(enviroment)\n self.client = self.app.test_client()\n self.content_type = 'application/json'\n self.path = 'http://localhost:5000/api/v1/tasks'\n self.path_first_task = self.path + '/1'\n self.path_fake_task = self.path + '/1000'\n self.data = {\"title\": \"Nueva tarea 2\", \"description\": \"Nueva Descripcion 2\", \"deadline\": \"2020-12-12 12:00:00\"}\n self.data_to_update = {\"title\": \"Nuevo titulo\"}\n\n def tearDown(self):\n with self.app.app_context():\n db.drop_all()\n\n def get_task_id(self, response):\n data = json.loads(response.data.decode('utf-8'))\n task_id = data['data']['id']\n\n return task_id\n \n\n def test_one_equals_one(self):\n self.assertEqual(1,1)\n\n def test_get_all_tasks(self):\n response = self.client.get(path=self.path)\n self.assertEqual(response.status_code, 200)\n \n def test_get_first_task(self):\n response = self.client.get(path=self.path_first_task, content_type=self.content_type)\n self.assertEqual(response.status_code, 200)\n\n task_id = self.get_task_id(response) \n self.assertEqual(task_id, 1)\n\n def test_not_found(self):\n response = self.client.get(path=self.path_fake_task, content_type=self.content_type)\n self.assertEqual(response.status_code, 404)\n \n def test_create_task(self):\n \n response = self.client.post(path=self.path, data=json.dumps(self.data), content_type=self.content_type)\n self.assertEqual(response.status_code, 200)\n\n task_id = self.get_task_id(response) \n self.assertEqual(task_id, 3)\n\n def test_update_task(self):\n \n response = self.client.put(path=self.path_first_task, data=json.dumps(self.data_to_update), content_type=self.content_type)\n self.assertEqual(response.status_code, 200)\n\n data = json.loads(response.data.decode('utf-8'))\n title= data['data']['title']\n self.assertEqual(title, self.data_to_update['title'])\n\n def test_delete_task(self):\n response = self.client.delete(path=self.path_first_task, content_type=self.content_type)\n self.assertEqual(response.status_code, 200)\n\n response = self.client.get(path=self.path_first_task, content_type=self.content_type)\n self.assertEqual(response.status_code, 404)\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"464747377","text":"import json\nimport os\n\njson_files_dir = os.path.join(\n\tos.path.dirname(__file__), 'json_files', ''\n)\n\ndados = os.path.join(json_files_dir, 'dados', '')\n\n# https://www.whatismybrowser.com/guides/the-latest-user-agent/\nuser_agents = open(os.path.join(json_files_dir, 'user_agents.json')).read()\nuser_agents = json.loads(user_agents)\n\n# https://github.com/soimort/translate-shell/wiki/Languages\nlanguages = open(os.path.join(json_files_dir, 'language_codes.json')).read()\nlanguages = json.loads(languages)\n\ndns_cache = {\n\t'lojaonline.vivo.com.br': '177.79.246.169'\n}\n\nallowed_cookies = [\n\t'JSESSIONID'\n]\n\nallowed_domains = [\n\t'lojaonline.vivo.com.br'\n]\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"25609393","text":"from django.shortcuts import render,get_object_or_404,redirect\nfrom .models import Comment\nfrom blog.models import Post\nfrom .form import CommentForm\n\n#判断数据是否有效 有效就加入对应文章的外键中去 然后再由文章逆向取出所有关联的评论\n\ndef post_comment(request,post_id):\n\n post=get_object_or_404(Post,pk=post_id)\n if request.method=='POST':\n form=CommentForm(request.POST)\n if form.is_valid():\n\n comment=form.save(commit=False)\n comment.post_id=post.id\n comment.save()\n return redirect(post)\n\n else:\n #错误信息\n comment_list=post.comment_set.all()\n context={'post':post,'form':form,'comment_list':comment_list}\n return render(request, 'blog/detail.html', context=context)\n return redirect(post)\n\n\n\n\n\n","sub_path":"comments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"51522184","text":"from Products.Five.browser import BrowserView\nfrom zope.component import getUtility\nfrom plone.registry.interfaces import IRegistry\nfrom urlparse import urlparse\n\nclass JavaScript(BrowserView):\n \n def __call__(self, request=None, response=None):\n \"\"\"Returns configurations.\"\"\"\n self.registry = getUtility(IRegistry)\n self.request.response.setHeader(\"Content-type\", \"text/javascript\")\n \n return \"\"\"\\\n var mobile_domain = \"%(hostname)s\";\n var ipad = \"%(ipad)s\";\n var other_tablets = \"%(tablets)s\";\n document.write(unescape(\"%%3Cscript src='\"+location.protocol+\"//s3.amazonaws.com/me.static/js/me.redirect.min.js' type='text/javascript'%%3E%%3C/script%%3E\"));\n \"\"\" % {\n 'hostname': self.hostname,\n 'ipad': self.ipad,\n 'tablets': self.tablets,\n }\n \n @property\n def hostname(self):\n registry = getUtility(IRegistry)\n hostnames = registry[ 'zettwerk.mobile.interfaces.IMobileSettings.hostnames']\n url = hostnames[0] or 'mylocalhost'\n o = urlparse(url)\n return o.hostname\n \n @property\n def tablets(self):\n return self.registry['zettwerk.mobile.interfaces.IMobileSettings.tablets']\n\n @property\n def ipad(self):\n return self.registry['zettwerk.mobile.interfaces.IMobileSettings.ipad']\n","sub_path":"zettwerk/mobile/browser/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"582238150","text":"\"\"\"\nSimple \"Hello, World\" application using Flask\n\"\"\"\nfrom mbta_helper import *\n\nfrom flask import Flask\n\napp = Flask(__name__)\n\napp.config['DEBUG'] = True\n\n\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\n@app.route('/find')\ndef find_stop():\n place_name = 'Babson College'\n url = GMAPS_BASE_URL + '?address=' + place\n return get_json(url)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"43553482","text":"from abc import ABC, abstractmethod\nimport copy\nimport attr\nfrom nameparser import HumanName\nfrom lxml import html\nfrom models import Candidate, Report, Office\nimport logging.config\nimport os\n\nloginipath = os.path.abspath(os.path.join(os.path.dirname(__file__), 'logging_config.ini'))\nlogging.config.fileConfig(loginipath)\nlogger = logging.getLogger('sLogger')\n\n\n@attr.s\nclass AbstractParser(ABC):\n page_content = attr.ib()\n\n @abstractmethod\n def parse(self):\n pass\n\n\nclass CandidateProfileParser(AbstractParser):\n\n def status_to_int(self, status):\n if status.lower == r'n\\a':\n return 0\n elif status.lower == 'active':\n return 1\n elif status.lower == 'terminated':\n return 2\n else:\n return 3\n\n def parse(self, candidate):\n xpath_ = \"//*[@id='ctl00_ContentPlaceHolder1_NameInfo1_dlDOIs']/tbody/tr[@class!='gridviewheader']\" \n tree = html.fromstring(self.page_content)\n # Body being generated with this xpath is empty list.\n body = tree.xpath(xpath_)\n dropdowns_list = []\n candidates_list = []\n offices_list = []\n # This condition is specifically to handle Account, Deleted profiles.\n if not body:\n candidate['FilerId'] = 'No filer ID'\n candidate['CandidateStatus'] = 0\n candidate['ElectionType'] = 0\n candidate['ElectionYear'] = 0\n return [(None, Office(Name='No Office.'), candidate)]\n for tr in body:\n try:\n candidate_copy = copy.copy(candidate)\n filer = tr.xpath('.//td[1]/text()').pop()\n office_name = tr.xpath('.//td[2]/span/text()').pop()\n dropdown = tr.xpath('.//td[3]/a/@id').pop()\n status = tr.xpath('.//td[4]/span/text()').pop()\n dropdowns_list.append(dropdown)\n candidate_copy['FilerId'] = filer\n candidate_copy['CandidateStatus'] = self.status_to_int(status)\n candidates_list.append(candidate_copy)\n office = Office(Name=office_name)\n offices_list.append(office)\n except Exception as e:\n logging.info(e)\n\n return ((dropdown, office, candidate) for dropdown, office, candidate \n in zip(dropdowns_list, offices_list, candidates_list))\n\n\nclass DropdownParser(AbstractParser):\n\n def parse(self): \n xpath_ = '//*[@id=\"ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel1_Label2\"]'\n tree = html.fromstring(self.page_content)\n body = tree.xpath(xpath_)\n if not body:\n return None\n return 1\n\n\nclass SearchResultsParser(AbstractParser):\n\n def parse(self):\n candidate = {\n 'FilerId': 'No filer ID',\n 'OfficeId': 0,\n 'CandidateStatus': 0,\n 'ElectionType': 0,\n 'ElectionYear': 0\n }\n xpath_ = \"//*[@id='ctl00_ContentPlaceHolder1_Search_List']/tbody/tr[@class!='gridviewheader']\"\n # returns a list of parsed links containing the ids of candidate profile links\n tree = html.fromstring(self.page_content)\n body = tree.xpath(xpath_)\n candidates = []\n link_ids = []\n if body is None:\n return [(None, None)]\n for tr in body:\n try:\n js_id = tr.xpath('.//td/a/@id').pop()\n candidate_name = tr.xpath('.//td[2]/span/text()').pop()\n name = HumanName(candidate_name)\n candidate = copy.copy(candidate)\n candidate['Firstname'] = name.first\n candidate['Middlename'] = name.middle\n candidate['Lastname'] = name.last\n candidate['Suffix'] = name.suffix\n candidates.append(candidate)\n link_ids.append(js_id)\n except Exception as e:\n logging.info(e)\n return [(cand, link_id) for cand, link_id in zip(candidates, link_ids)] \n\n\nclass CandidateRegistrationParser(AbstractParser):\n\n def parse(self, candidate):\n base = 'ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel2_lbl'\n tree = html.fromstring(self.page_content)\n street = base+'Address'\n csz = base+'CSZ'\n party = base+'PartyAffiliation'\n committee = base+'ComName'\n committee_info = tree.xpath(f'//*[@id=\"{committee}\"]/text()')\n party_info = tree.xpath(f\"//*[@id='{party}']/text()\")\n street_info = tree.xpath(f\"//*[@id='{street}']/text()\")\n csz_info = tree.xpath(f\"//*[@id='{csz}']/text()\")\n party_text = 'No party given.'\n street_text = 'No street given.'\n csz_text = 'No city, state, or zip given.'\n committee_text = 'No committee name given.'\n try:\n if party_info:\n party_text = party_info.pop()\n if street_info:\n street_text = street_info.pop()\n if csz_info:\n csz_text = csz_info.pop()\n if committee_info:\n committee_text = committee_info.pop()\n except Exception as e:\n logging.info(e)\n candidate['Party'] = party_text\n candidate['CandidateAddress'] = street_text + ' ' + csz_text\n candidate['CommitteeName'] = committee_text\n return candidate\n\n\nclass ReportsTableParser(AbstractParser):\n\n def parse(self):\n report = {\n 'ReportType': 'No report type listed',\n 'Year': 0,\n 'ReportFiledDate': 'No date listed.',\n 'ReportReceivedDate': 'No date listed.',\n 'CandidateId': None,\n 'Url': 'No url listed.'\n }\n xpath_ = \"//*[@id='ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel1_dgReports']/tbody/tr[@class!='gridviewheader']\"\n tree = html.fromstring(self.page_content)\n body = tree.xpath(xpath_)\n links = []\n reports = []\n if not body:\n return [(None, None)]\n for tr in body:\n try:\n link = tr.xpath('.//td[1]/a/@id').pop()\n report_type = tr.xpath('.//td[2]/span/text()').pop()\n year = tr.xpath('.//td[3]/text()').pop()\n report_filed_date = tr.xpath('.//td[4]/text()').pop()\n report_received_by = tr.xpath('.//td[5]/span/text()').pop()\n report_received_date = tr.xpath('.//td[6]/span/text()').pop()\n links.append(link)\n report = copy.copy(report)\n report['ReportType'] = report_type\n report['Year'] = year\n report['ReportFiledDate'] = report_filed_date\n report['ReportReceivedDate'] = report_received_date\n reports.append(report)\n except Exception as e:\n logging.info(e)\n return ((link, report) for link, report in zip(links, reports))\n\n\nclass ContributionsViewParser(AbstractParser):\n \n def parse(self):\n id_ = 'ctl00_ContentPlaceHolder1_Name_Reports1_dgReports_ctl02_ViewCont'\n xpath_ = \"//*[@id='ctl00_ContentPlaceHolder1_Name_Reports1_dgReports_ctl02_ViewCont']\"\n tree = html.fromstring(self.page_content)\n body = tree.xpath(xpath_)\n if not body:\n return None\n return id_ \n\n\nclass CSVLinkParser(AbstractParser):\n \n def parse(self):\n id_ = \"ctl00_ContentPlaceHolder1_Campaign_ByContributions_RFResults2_Export\"\n xpath_ = \"//*[@id='ctl00_ContentPlaceHolder1_Campaign_ByContributions_RFResults2_Export']\"\n tree = html.fromstring(self.page_content)\n body = tree.xpath(xpath_)\n if not body:\n return None\n return id_\n\n","sub_path":"WebScraper/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":7826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"107281435","text":"#########################\n# 幅優先探索 BFS\n#########################\n\nr,c = map(int,input().split())\nsy,sx = map(int,input().split())\ngy,gx = map(int,input().split())\nsy,sx,gy,gx = sy-1,sx-1,gy-1,gx-1\n\n# Field読み込み\nfield = [list(input()) for _ in range(r)]\n\n# 探索待ちノードを保持するキュー\nqueue = [[sy,sx]]\n# ノードが訪問済みか否かを保持するリスト 0-> 未訪問 1~> 訪問済み(数値:深さ)\nvisited = [[-1]*c for _ in range(r)]\nvisited[sy][sx] = 0\n\n# ゴールにつくまで続ける\n# ※類例:キューがなくなるまで\nwhile 1:\n # キューから探索する座標を取り出す\n y,x = queue.pop(0)\n for i,j in ([1,0],[0,1],[-1,0],[0,-1]):\n # Fieldの外\n # 今回は壁に囲まれているため不要\n # if x+i < 0 or x+i >= w or y+j < 0 or y+j >= h:\n # continue\n # 探索先にゴールマスがあったとき\n if y+j == gy and x+i == gx:\n print(visited[y][x]+1)\n exit()\n # 探索先が'.'で、visitedに記載されていないなら探索スタックとvisitedに追加\n elif field[y+j][x+i] == '.' and visited[y+j][x+i] == -1:\n queue.append([y+j,x+i])\n visited[y+j][x+i] = visited[y][x] + 1\n","sub_path":"AtCoder/ABC007C.py","file_name":"ABC007C.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"136876511","text":"import dpkt\nimport sys\nimport socket\nimport urllib2 \nfrom StringIO import StringIO\nimport gzip\nimport sqlite3\n\nsnaplen = 1516\ni = 0\nc = 0\ncount = 0\nsize_payload = 0\nreq = []\nres = []\npayload = []\n\nresult = open('result.txt', 'w')\nf = open('kan.pcap', 'rb')\n\ncon = sqlite3.connect('newdb.db')\ncur = con.cursor()\ncur.execute('''DROP TABLE http''')\n## Create table and push data\ncur.execute('''CREATE TABLE if not exists http(Request_Method text, Request text, Request_Payload text, Response text, Response_Payload text)''')\ncur.execute('''CREATE INDEX packet ON http(Request)''')\n\npcap = dpkt.pcap.Reader(f)\n\nfor ts, buf in pcap:\n eth = dpkt.ethernet.Ethernet(buf)\n if eth.type!=2048: ## For ipv4, dpkt.ethernet.Ethernet(buf).type =2048 \n continue\n ip = eth.data\n\n if ip.p!=6:\n continue\n tcp=ip.data\n size_payload = ip.len - 40\n src = socket.inet_ntoa(ip.src)\n dst = socket.inet_ntoa(ip.dst)\n\n## print \"%s ---> %s\" % (src, dst)\n## print len(tcp.data)\n## print tcp.sport, \"--->\", tcp.dport\n if tcp.sport == 80 or tcp.dport == 80 and len(tcp.data) > 0: ##filter tcp port == 80\n if tcp.dport == 80: ## Parse HTTP request\n try:\n http = dpkt.http.Request(tcp.data)\n \n if http.method == \"GET\":\n rqst = [\"GET\", http.headers['host']+http.uri, tcp.sport, tcp.dport, src, dst, tcp.seq, tcp.ack, http.body]\n if 'accept-encoding' in http.headers:\n rqst.append(http.headers['accept-encoding'])\n req.append(rqst)\n\n elif http.method == \"POST\":\n rqst = [\"POST\", http.headers['host']+http.uri, tcp.sport, tcp.dport, src, dst, tcp.seq, tcp.ack, http.body]\n if 'accept-encoding' in http.headers:\n rqst.append(http.headers['accept-encoding'])\n req.append(rqst)\n except:\n pass\n elif tcp.sport == 80: ## Parse HTTP response\n try:\n http2 = dpkt.http.Response(tcp.data)\n \n if http2.status == str(200):\n a = http2.body\n pload = gzip.GzipFile(fileobj=StringIO(a)).read()\n for j in range(0, len(req)):\n if (tcp.dport == req[j][2]) and (src == req[j][5]) and (dst == req[j][4]) and (tcp.seq == req[j][7]):\n result.write(\"\\nRequest: \" + req[j][0] + \" \" + req[j][1])\n requests = req[j][1]\n result.write(\"\\nRequest Payload: \"+req[j][8])\n result.write(\"\\nResponse: HTTP/1.1 200 OK\")\n result.write(\"\\nResponse Payload: \"+pload)\n result.write(\"\\n_________________\\n\")\n cur.execute('''INSERT INTO http(Request_Method, Request, Request_Payload, Response, Response_Payload) VALUES(?, ?, ?, ?, ?)''', (req[j][0], requests, req[j][8], \"HTTP/1.1 200 OK\", pload))\n \n\n \n \n except:\n pass\n\ncon.commit()\n\ncur.execute('''SELECT * FROM http''')\nfor row in cur:\n # row[0] returns the first column in the query (name), row[1] returns email column.\n print('{0}, {1}, {2}, {3}, {4}'.format(row[0], row[1], row[2], row[3], row[4]))\n print(\"********************************************************************************************************************\")\nresult.close()\ncon.close()\n","sub_path":"flaskr/server/capture.py","file_name":"capture.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"231819808","text":"import json\nimport httprequests\nimport datetime\nimport utils\nimport sys\nfrom tzwhere import tzwhere\nimport pytz\nimport pandas as pd\nfrom geopy.distance import great_circle\nfrom sklearn.cluster import DBSCAN\nimport numpy as np\nimport csv\nfrom shapely.geometry import MultiPoint\nimport utils\n\n\nnumber_name_dict = {}\n\nblockgroup_stays_dict = {}\ntotal_stays = 0\np1a_sum = 0\np2a_sum = 0\np3a_sum = 0\np4a_sum = 0\nseg_sum = 0\n\n\ndef calculate_seg_score(place_time_dict, place_info_dict):\n for place_id, times in place_time_dict.items():\n place_info = place_info_dict[place_id]\n place_name = place_info['name']\n p1a = place_info['p1a']\n p2a = place_info['p2a']\n p3a = place_info['p3a']\n p4a = place_info['p4a']\n seg = place_info['segregation']\n\n total_stays += times\n p1a_sum += p1a * times\n p2a_sum += p2a * times\n p3a_sum += p3a * times\n p4a_sum += p4a * times\n seg_sum += seg * times\n\n print('Place %s %d times' % (place_name, times))\n\n if total_stays > 0:\n avg_p1a = p1a_sum / total_stays\n avg_p2a = p2a_sum / total_stays\n avg_p3a = p3a_sum / total_stays\n avg_p4a = p4a_sum / total_stays\n avg_seg = seg_sum / total_stays\n\n print('P1A Score %f P2A Score %f P3A Score %f P4A Score %f Seg Score %f' % (\n avg_p1a, avg_p2a, avg_p3a, avg_p4a, avg_seg))\n\n# Extract stays from location history data point\n# stay is of type ((lat, long), start_time, end_time)\n\n\ndef extract_stays(locations, t_dur=5, l_roam=5):\n # The same algorithm as in LNCS 3234\n i = 0\n s = []\n while i < len(locations) - 1:\n # print(i)\n j = i + 1\n if j < len(locations):\n time_i = int(locations[i]['timestampMs'])\n while j < len(locations) and utils.time_diff(locations, i, j) < 5:\n # Find the next record with time difference larger than t_dur\n j += 1\n if j >= len(locations):\n j -= 1\n if i == j:\n i = i + 1\n continue\n if utils.time_diff(locations, i, j) > 60:\n # The difference is too big, we consider it as a new stay\n i = j\n continue\n if utils.diameter(locations, i, j) > l_roam:\n i = i + 1\n else:\n while j < len(locations) and utils.diameter(locations, i, j) <= l_roam and utils.time_diff(locations, i, j) <= 24 * 60:\n j += 1\n j -= 1\n time_j = int(locations[j]['timestampMs'])\n s.append((utils.medoid(locations, i, j), time_i, time_j))\n i = j + 1\n else:\n break\n # extract_home_from_stays(s)\n get_places(s)\n\n\ndef is_stay_overnight(stay):\n start_of_stay = datetime.datetime.fromtimestamp(\n stay[1] / 1000, tz=pytz.timezone('America/New_York'))\n cond = start_of_stay.hour <= 6 or start_of_stay.hour >= 20\n return cond\n\n\ndef extract_home_from_stays(stays):\n home_stays = dict()\n number_name_dict = dict()\n with open('blockgroup.csv') as block_group_data:\n rows = csv.DictReader(block_group_data)\n for row in rows:\n group_number = row['state'] + row['county'] + \\\n row['tract'] + row['block group']\n name = row['NAME']\n number_name_dict[group_number] = name\n for stay in stays:\n if is_stay_overnight(stay):\n (lat, long) = stay[0]\n census_block = httprequests.getCensusBlock(lat, long)\n census_block_group = census_block[:12]\n block_group_name = number_name_dict[census_block_group]\n if block_group_name in home_stays:\n home_stays[block_group_name] += 1\n else:\n home_stays[block_group_name] = 1\n\n for name, stay in home_stays.items():\n print('The home is in %s, you spent %d nights there' %\n (name, stay))\n\n # location = httprequests.getLocation(lat / (10 ** 7), long / (10 ** 7))\n # if location:\n # print (location[0]['name'])\n # length_of_stay = (stay[2] - stay[1]) / 60000 / 60\n # if (length_of_stay > 5):\n # (lat, long) = stay[0]\n # print (httprequests.getLocation(lat / (10 ** 7), long / (10 ** 7)))\n\n\ndef get_places(stays):\n place_stay = dict()\n fsq_info = dict()\n for stay in stays:\n (lat, long) = stay[0]\n found_places = httprequests.getLocation(lat, long)\n if found_places:\n most_likely_place = found_places[0]\n place_info = {'lat': most_likely_place['lat'], 'long': most_likely_place['lon'],\n 'id': most_likely_place['_id'], 'name': most_likely_place['name']}\n place_id = found_places[0]['_id']\n fsq_info[place_id] = place_info\n start = datetime.datetime.fromtimestamp(\n stay[1] / 1000.0, tz=pytz.timezone('America/New_York'))\n end = datetime.datetime.fromtimestamp(\n stay[2] / 1000.0, tz=pytz.timezone('America/New_York'))\n duration = end - start\n if place_id not in place_stay:\n place_stay[place_id] = duration\n else:\n place_stay[place_id] = place_stay[place_id] + duration\n\n sorted_by_stay = sorted(\n place_stay.items(), key=lambda kv: kv[1], reverse=True)\n with open('stay.csv', 'w') as f:\n filed_names = ['id', 'lat', 'long', 'name', 'time']\n writer = csv.DictWriter(f=f, fieldnames=filed_names)\n writer.writeheader()\n for row in sorted_by_stay:\n id = row[0]\n time = row[1]\n place_info = fsq_info[id]\n place_info['time'] = time\n writer.writerow(place_info)\n\n for place, stay in place_stay.items():\n print(\"%s at %s\" % (stay, place))\n\n\ndef is_stay(location):\n # If the velocity is 0 or Google feels confident the user is still, we consider it to be a 'stay'\n if 'velocity' in location and location['velocity'] == 0:\n return True\n if 'activity' in location:\n for outer_activity in location['activity']:\n for activity in outer_activity['activity']:\n if activity['type'] == 'STILL' and activity['confidence'] > 50:\n return True\n\n\ndef analyse_location_history(file_path):\n last_location_name = \"\"\n last_location_recorded = False\n # A 'total' dict, the key is the place ID and the value is the number of visits\n place_time_dict = dict()\n place_stay_length_dict = dict()\n # A dict for each day\n place_time_dict_by_date = dict()\n place_stay_length_dict_by_date = dict()\n place_info_dict = dict()\n\n # Only consider the last 30 days\n # time_threshold = datetime.datetime.today() - datetime.timedelta(days=30)\n\n time_threshold = datetime.datetime(2019, 7, 1)\n time_upper_limit = datetime.datetime(2019, 7, 30)\n last_timestamp = None\n with open(file_path) as json_file:\n data = json.load(json_file)\n for location in data['locations']:\n # Only consider it if it's a stay\n if is_stay(location):\n timestamp = int(location['timestampMs'])\n if not last_timestamp:\n last_timestamp = timestamp\n date_time = datetime.datetime.fromtimestamp(\n timestamp // 1000.0)\n if date_time > time_threshold and date_time < time_upper_limit:\n date = date_time.date()\n if not (date in place_time_dict_by_date):\n place_time_dict_by_date[date] = dict()\n place_stay_length_dict_by_date[date] = dict()\n lat = location['latitudeE7'] / (10 ** 7)\n long = location['longitudeE7'] / (10 ** 7)\n found_places = httprequests.getLocation(lat, long)\n if found_places:\n most_confident_place = found_places[0]\n print(most_confident_place['confidence'])\n found_place_name = most_confident_place['name']\n print(found_place_name)\n found_place_id = most_confident_place['_id']\n if not (found_place_id in place_info_dict):\n place_info_dict[found_place_id] = most_confident_place\n if (found_place_name == last_location_name):\n if not last_location_recorded:\n # The user is still at the same place and the place is not recorded yet\n # so we consider the user stays there for a while\n if found_place_id in place_time_dict:\n place_time_dict[found_place_id] += 1\n else:\n place_time_dict[found_place_id] = 1\n if found_place_id in place_time_dict_by_date[date]:\n place_time_dict_by_date[date][found_place_id] += 1\n else:\n place_time_dict_by_date[date][found_place_id] = 1\n last_location_recorded = True\n else:\n # The user spends more time at the place\n duration = timestamp - last_timestamp\n if found_place_id in place_stay_length_dict:\n place_stay_length_dict[found_place_id] += duration\n else:\n place_stay_length_dict[found_place_id] = 0\n if found_place_id in place_stay_length_dict_by_date[date]:\n place_stay_length_dict_by_date[date][found_place_id] += duration\n else:\n place_stay_length_dict_by_date[date][found_place_id] = 0\n else:\n if found_place_name != last_location_name:\n last_location_recorded = False\n last_location_name = most_confident_place['name']\n last_timestamp = timestamp\n # for found_place in found_places:\n # print (found_place['confidence'])\n # found_place_name = found_place['name']\n # print (found_place_name)\n # found_place_id = found_place['_id']\n # if not (found_place_id in place_info_dict):\n # place_info_dict[found_place_id] = found_place\n # if (found_place_name == last_location_name) and (last_location_recorded == False):\n # # The user is still at the same place and the place is not recorded yet\n # # so we consider the user stays there for a while\n # if found_place_id in place_time_dict:\n # place_time_dict[found_place_id] += 1\n # else:\n # place_time_dict[found_place_id] = 1\n # if found_place_id in place_time_dict_by_date[date]:\n # place_time_dict_by_date[date][found_place_id] += 1\n # else:\n # place_time_dict_by_date[date][found_place_id] = 1\n # last_location_recorded = True\n # else:\n # if (found_place_name != last_location_name):\n # last_location_recorded = False\n # last_location_name = found_place['name']\n # return\n\n # Sort the places by the degree of segregation\n sorted_places = sorted(place_info_dict.items(),\n key=lambda x: x[1]['segregation'])\n\n for (place_id, duration) in place_stay_length_dict.items():\n time = datetime.timedelta(milliseconds=duration)\n print(\"You spent %s time at %s\" %\n (time, place_info_dict[place_id]['name']))\n\n # for (place_id, place_info) in sorted_places:\n # if (place_id in place_time_dict):\n # place_name = place_info['name']\n # place_segscore = place_info['segregation']\n # visit_times = place_time_dict[place_id]\n # print('You visited %s %d times, it has a segregation score of %f' % (\n # place_name, visit_times, place_segscore))\n #\n # calculate_seg_score(place_time_dict, place_info_dict)\n #\n # for date, place_time_dict_on_date in place_time_dict_by_date.items():\n # if place_time_dict_on_date:\n # print(date)\n # calculate_seg_score(place_time_dict_on_date, place_info_dict)\n\n\ndef analyse_location_history(json_file):\n last_location_name = \"\"\n last_location_recorded = False\n # A 'total' dict, the key is the place ID and the value is the number of visits\n place_time_dict = dict()\n place_stay_length_dict = dict()\n # A dict for each day\n place_time_dict_by_date = dict()\n place_stay_length_dict_by_date = dict()\n place_info_dict = dict()\n\n # Only consider the last 30 days\n # time_threshold = datetime.datetime.today() - datetime.timedelta(days=30)\n\n time_threshold = datetime.datetime(2019, 7, 1)\n time_upper_limit = datetime.datetime(2019, 7, 30)\n last_timestamp = None\n data = json.load(json_file)\n for location in data['locations']:\n # Only consider it if it's a stay\n if is_stay(location):\n timestamp = int(location['timestampMs'])\n if not last_timestamp:\n last_timestamp = timestamp\n date_time = datetime.datetime.fromtimestamp(\n timestamp // 1000.0)\n if date_time > time_threshold and date_time < time_upper_limit:\n date = date_time.date()\n if not (date in place_time_dict_by_date):\n place_time_dict_by_date[date] = dict()\n place_stay_length_dict_by_date[date] = dict()\n lat = location['latitudeE7'] / (10 ** 7)\n long = location['longitudeE7'] / (10 ** 7)\n found_places = httprequests.getLocation(lat, long)\n if found_places:\n most_confident_place = found_places[0]\n print(most_confident_place['confidence'])\n found_place_name = most_confident_place['name']\n print(found_place_name)\n found_place_id = most_confident_place['_id']\n if not (found_place_id in place_info_dict):\n place_info_dict[found_place_id] = most_confident_place\n if (found_place_name == last_location_name):\n if not last_location_recorded:\n # The user is still at the same place and the place is not recorded yet\n # so we consider the user stays there for a while\n if found_place_id in place_time_dict:\n place_time_dict[found_place_id] += 1\n else:\n place_time_dict[found_place_id] = 1\n if found_place_id in place_time_dict_by_date[date]:\n place_time_dict_by_date[date][found_place_id] += 1\n else:\n place_time_dict_by_date[date][found_place_id] = 1\n last_location_recorded = True\n else:\n # The user spends more time at the place\n duration = timestamp - last_timestamp\n if found_place_id in place_stay_length_dict:\n place_stay_length_dict[found_place_id] += duration\n else:\n place_stay_length_dict[found_place_id] = 0\n if found_place_id in place_stay_length_dict_by_date[date]:\n place_stay_length_dict_by_date[date][found_place_id] += duration\n else:\n place_stay_length_dict_by_date[date][found_place_id] = 0\n else:\n if found_place_name != last_location_name:\n last_location_recorded = False\n last_location_name = most_confident_place['name']\n last_timestamp = timestamp\n # for found_place in found_places:\n # print (found_place['confidence'])\n # found_place_name = found_place['name']\n # print (found_place_name)\n # found_place_id = found_place['_id']\n # if not (found_place_id in place_info_dict):\n # place_info_dict[found_place_id] = found_place\n # if (found_place_name == last_location_name) and (last_location_recorded == False):\n # # The user is still at the same place and the place is not recorded yet\n # # so we consider the user stays there for a while\n # if found_place_id in place_time_dict:\n # place_time_dict[found_place_id] += 1\n # else:\n # place_time_dict[found_place_id] = 1\n # if found_place_id in place_time_dict_by_date[date]:\n # place_time_dict_by_date[date][found_place_id] += 1\n # else:\n # place_time_dict_by_date[date][found_place_id] = 1\n # last_location_recorded = True\n # else:\n # if (found_place_name != last_location_name):\n # last_location_recorded = False\n # last_location_name = found_place['name']\n # return\n\n # Sort the places by the degree of segregation\n sorted_places = sorted(place_info_dict.items(),\n key=lambda x: x[1]['segregation'])\n\n for (place_id, duration) in place_stay_length_dict.items():\n time = datetime.timedelta(milliseconds=duration)\n print(\"You spent %s time at %s\" %\n (time, place_info_dict[place_id]['name']))\n\n # for (place_id, place_info) in sorted_places:\n # if (place_id in place_time_dict):\n # place_name = place_info['name']\n # place_segscore = place_info['segregation']\n # visit_times = place_time_dict[place_id]\n # print('You visited %s %d times, it has a segregation score of %f' % (\n # place_name, visit_times, place_segscore))\n #\n # calculate_seg_score(place_time_dict, place_info_dict)\n #\n # for date, place_time_dict_on_date in place_time_dict_by_date.items():\n # if place_time_dict_on_date:\n # print(date)\n # calculate_seg_score(place_time_dict_on_date, place_info_dict\n\n\ndef is_night(date_time):\n # print (date_time.hour)\n return date_time.hour <= 6 or date_time.hour >= 20\n\n\ndef get_center_point(cluster):\n # print (cluster)\n MultiPoint(points=cluster)\n centroid = (MultiPoint(cluster).centroid.x, MultiPoint(cluster).centroid.y)\n centermost_point = min(\n cluster, key=lambda point: great_circle(point, centroid).m)\n # print (centermost_point)\n return tuple(centermost_point)\n\n\ndef cluster_location(coordinates_list):\n global number_name_dict\n global blockgroup_stays_dict\n print(len(number_name_dict))\n db = DBSCAN(eps=0.3, min_samples=5).fit(coordinates_list)\n cluster_labels = db.labels_\n num_clusters = len(set(cluster_labels)) - \\\n (1 if -1 in cluster_labels else 0)\n clusters = pd.Series([coordinates_list[cluster_labels == n]\n for n in range(num_clusters)])\n if num_clusters > 0:\n for cluster in clusters:\n lat, long = get_center_point(cluster)\n census_block = httprequests.getCensusBlock(lat, long)\n if census_block:\n # Not null\n census_block_group = census_block[:12]\n print(census_block)\n if str(census_block_group) in number_name_dict:\n name = number_name_dict[census_block_group]\n if name in blockgroup_stays_dict:\n blockgroup_stays_dict[name] += 1\n else:\n blockgroup_stays_dict[name] = 1\n\n\ndef extract_home(file_path):\n global number_name_dict\n with open('blockgroup.csv') as block_group_data:\n rows = csv.DictReader(block_group_data)\n for row in rows:\n group_number = row['state'] + row['county'] + \\\n row['tract'] + row['block group']\n name = row['NAME']\n number_name_dict[group_number] = name\n\n coordinates = []\n night_places = dict()\n with open(file_path) as json_file:\n data = json.load(json_file)\n locations = data['locations']\n for location in locations:\n lat = location['latitudeE7'] / (10 ** 7)\n long = location['longitudeE7'] / (10 ** 7)\n coordinates.append([lat, long])\n timestamp = int(location['timestampMs'])\n date_time = datetime.datetime.fromtimestamp(\n timestamp / 1000, tz=pytz.timezone('America/New_York'))\n if date_time < datetime.datetime(2019, 7, 5, tzinfo=pytz.timezone('America/New_York')):\n continue\n date = date_time.date()\n if is_night(date_time):\n if date not in night_places:\n night_places[date] = [[lat, long]]\n else:\n night_places[date].append([lat, long])\n for date, places in night_places.items():\n print(date)\n cluster_location(np.array(places))\n\n global blockgroup_stays_dict\n\n sorted_homes = sorted(blockgroup_stays_dict.items(),\n key=lambda x: x[1], reverse=True)\n num = 0\n for blockgroup, stays in sorted_homes:\n if num < 5:\n print('The home is in %s, you spent %d nights there' %\n (blockgroup, stays))\n num += 1\n\n with open('home.csv', 'w') as f:\n csv_out = csv.writer(f)\n for row in sorted_homes:\n csv_out.writerow(row)\n\n\ndef time_gap(file_path):\n with open(file_path) as json_file:\n data = json.load(json_file)\n locations = data['locations']\n gap = 0\n last_timestamp = int(locations[0]['timestampMs'])\n for location in locations:\n timestamp = int(location['timestampMs'])\n gap = max(gap, timestamp - last_timestamp)\n print(gap)\n\n\nif __name__ == \"__main__\":\n file_path = sys.argv[1]\n if (file_path):\n location_history = utils.preprocess_location_history(file_path)\n extract_stays(location_history)\n # print(\"----------------\")\n # extract_home(file_path)\n","sub_path":"location_history.py","file_name":"location_history.py","file_ext":"py","file_size_in_byte":23399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"200505448","text":"################################################################################\n# Helper and utility functions\n# \n# Code and images by Aaron Penne\n# https://github.com/aaronpenne/generative_art\n#\n# Released under the MIT license (https://opensource.org/licenses/MIT)\n################################################################################\n\nimport os\nimport logging\nimport sys\nfrom datetime import datetime\nimport ConfigParser\nimport shutil\n\nfrom setup_logging import log\n\nclass ConfigUtils(object):\n def cast_dict(self, dictionary):\n \"\"\"\n Tries to convert the values in a dict to int, then float\n \"\"\"\n for key in dictionary:\n try:\n dictionary[key] = int(dictionary[key])\n except:\n try:\n dictionary[key] = float(dictionary[key])\n except:\n pass\n return dictionary\n\n def config_to_dict(self, config_path, config_section='default'):\n \"\"\"\n Grabs section from config file and converts it to a dict\n \"\"\"\n config = ConfigParser.ConfigParser()\n config.read(config_path)\n section_list = config.items(config_section)\n log.info('Args pulled from config file:')\n for pair in section_list:\n log.info(' {}: {}'.format(pair[0], pair[1]))\n section_dict = dict(section_list)\n section_dict = self.cast_dict(section_dict)\n return section_dict\n\n\nclass OpsUtils(object):\n def __init__(self, script_path, seed=1138):\n self.script_path = script_path\n self.script_name = os.path.basename(script_path)\n self.script_dir = os.path.dirname(script_path)\n self.sketch_name = os.path.splitext(self.script_name)[0]\n self.seed = seed\n self.timestamp = self.get_timestamp_string()\n\n def print_seed(self):\n log.info(self.seed)\n\n def get_timestamp_string(self):\n timestamp = datetime.now()\n timestamp = timestamp.strftime('%Y%m%d_%H%M%S')\n return timestamp\n\n def get_filename(self, counter):\n filename = '{}_{}_{}_{:03d}.png'.format(self.sketch_name, self.seed, self.timestamp, counter)\n return filename\n\n def make_dir(self, path):\n try:\n os.makedirs(path)\n except OSError:\n if not os.path.isdir(path):\n raise\n\n def save_graphic(self, pg, path, counter):\n self.make_dir(path)\n output_file = self.get_filename(counter)\n output_path = os.path.join(path, output_file)\n pg.save(output_path)\n log.info('Saved to {}'.format(output_path))\n if counter == 0:\n self.make_dir('archive')\n src = self.script_path \n dst = os.path.join('archive',output_file + '.py')\n shutil.copy(src, dst)\n\n def get_ext_agnostic_file(self, directory, name):\n for f in os.listdir(directory):\n if os.path.splitext(f)[0] == name:\n out = os.path.join(directory, f)\n return out\n\n\nclass DrawUtils(OpsUtils):\n def __init__(self, script_path, width, height, seed=1138):\n super(DrawUtils, self).__init__(script_path, seed) # Calls init from inherited class to get those variables first\n log.info(self.timestamp)\n self.width = width\n self.height = height\n\n def draw_test(self, pg, num_circles): \n for i in range(num_circles):\n pg.fill(random(255),50,50,10)\n pg.ellipse(random(pg.width),random(pg.height),random(pg.width*0.2),random(pg.height*0.2))\n\n\n def circle_point(self, cx, cy, rx, ry, a):\n \"\"\"\n Translates polar coords to cartesian\n \"\"\"\n x = cx + rx * cos(a)\n y = cy + ry * sin(a)\n return x, y\n \n def noise_loop(self, a, r, min_val, max_val, x_c=0, y_c=0):\n \"\"\"\n Samples 2D Perlin noise in a circle to make smooth noise loops\n Adapted from https://github.com/CodingTrain/website/blob/master/CodingChallenges/CC_136_Polar_Noise_Loop_2/P5/noiseLoop.js\n \"\"\"\n xoff = map(cos(a), -1, 1, x_c, x_c + 2*r)\n yoff = map(sin(a), -1, 1, y_c, y_c + 2*r)\n r = noise(xoff, yoff)\n return map(r, 0, 1, min_val, max_val)\n\n def frange(self, start, end=None, increment=None):\n \"\"\"\n Adapted from http://code.activestate.com/recipes/66472\n \"\"\"\n if end == None:\n end = start + 0.0\n start = 0.0\n if increment == None:\n increment = 1.0\n L = []\n while 1:\n next = start + len(L) * increment\n if increment > 0 and next >= end:\n break\n elif increment < 0 and next <= end:\n break\n L.append(next)\n return L\n\n def line_canvas(self, \n c,\n bg_color,\n fill_color,\n stroke_color,\n step=10):\n c.beginDraw()\n c.colorMode(HSB, 360, 100, 100, 100)\n c.background(*bg_color)\n c.fill(*fill_color)\n c.stroke(*stroke_color)\n c.rotate(random(PI))\n for i in range(-self.width, self.width*2, step):\n c.strokeWeight(random(1,step*0.5))\n c.line(i, -self.height, i, self.height*2)\n c.endDraw()\n return c\n\n def mask_ellipse(self):\n c = createGraphics(self.width, self.height)\n c.beginDraw()\n c.noStroke()\n c.translate(self.width/2, self.height/2)\n c.rotate(random(PI))\n c.ellipse(0,\n 0, \n random(self.width*0.3, self.width*0.9), \n random(self.height*0.1, self.height*0.7))\n c.endDraw()\n return c\n","sub_path":"ppy_terminal/imports/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":5740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"86081760","text":"import os\nimport json\nimport pyargos.thingsboard as tb\n\n\nclass Experiment(object):\n\n _experimentDataPath = None\n _trialPath = None\n\n def getWindows(self,type):\n \"\"\"\n Return the windows of the type.\n\n if does not exist, return empty list.\n\n :param type:\n :return:\n \"\"\"\n return self._experimentDataJSON['properties']['calculationWindows'][type]\n\n\n def __init__(self, JSON):\n \"\"\"\n Initialize home.\n read the experiment JSON.\n\n \"\"\"\n currentDirectory = os.getcwd()\n if os.path.exists(os.path.join(currentDirectory, 'experimentData', 'ExperimentData.json')):\n self._experimentDataPath = os.path.join(currentDirectory, 'experimentData')\n self._trialPath = os.path.join(self._experimentDataPath, 'trials')\n with open(os.path.join(self._experimentDataPath, 'ExperimentData.json'), 'r') as experimentDataJSON:\n self._experimentDataJSON = json.load(experimentDataJSON)\n self._home = tb.tbHome(JSON['connection'])\n else:\n raise EnvironmentError('Current directory is not an experiment directory')\n\n\n def setup(self):\n \"\"\"\n Loads all the devices with the ids to the TB.\n\n that is, prepare an experiment.\n\n and save the trial template to the directory in the json.\n\n make sure the trials direcotry is git repository (check if .git exists).\n\n :return:\n \"\"\"\n trialTemplate = {}\n trialTemplate['properties'] = self._experimentDataJSON['properties']\n trialTemplate['Entities'] = []\n for entitiesCreation in self._experimentDataJSON['Entities']:\n entityType = entitiesCreation['entityType']\n for entityNum in range(entitiesCreation['Number']):\n if entitiesCreation['Number'] == 1:\n entityName = entitiesCreation['nameFormat']\n id = None\n else:\n id = entityNum + 1\n entityName = entitiesCreation['nameFormat'].format(id=id)\n entityHome = getattr(self._home, \"%sHome\" % (entitiesCreation['entityType'].lower()))\n entityHome.createProxy(entityName, entitiesCreation['Type'])\n windowEntitiesNames = []\n try:\n for window in trialTemplate['properties']['calculationWindows'][entitiesCreation['Type']]:\n windowEntityName = self._getWindowEntityName(entityName, window)\n windowEntityType = 'calculated_%s' % entitiesCreation['Type']\n entityHome.createProxy(windowEntityName, windowEntityType)\n windowEntitiesNames.append(['DEVICE', windowEntityName])\n trialTemplate['Entities'].append({'Name': windowEntityName,\n 'entityType': entityType,\n 'Type': windowEntityType,\n 'attributes': {'longitude': 0, 'latitude': 0, 'id': id},\n 'contains': []})\n except KeyError:\n pass\n trialTemplate['Entities'].append({'Name': entityName,\n 'entityType': entityType,\n 'Type': entitiesCreation['Type'],\n 'attributes': {'longitude': 0, 'latitude': 0, 'id': id},\n 'contains': windowEntitiesNames})\n with open(os.path.join(self._trialPath ,'trialTemplate.json'), 'w') as trialTemplateJSON:\n json.dump(trialTemplate, trialTemplateJSON, indent=4, sort_keys=True)\n\n\n def _getWindowEntityName(self,entityName,window):\n \"\"\"\n creates the name of the device with the window.\n\n i.e. [devicename]_[window in seconds]s\n :param entityName:\n :param window:\n :return:\n \"\"\"\n return '%s_%ds' % (entityName, window)\n\n\n def getTrialList(self):\n \"\"\"\n Return the list of trials. actually the list of file names. without the extension\n\n trial directory is given in the JSON\n\n :return:\n A pandas series. | list\n \"\"\"\n return [x.split('.')[0] for x in os.listdir(os.path.join(self._trialPath, 'design'))]\n\n\n def getTrialJSON(self, trialName):\n \"\"\"\n Load and return the JSON of the trial\n :param trialName: The name of the trial\n :param trialType: 'design' / 'execution'\n :return:\n \"\"\"\n if os.path.exists(os.path.join(self._trialPath, 'execution', '%s.json' % trialName)):\n with open(os.path.join(self._trialPath, 'execution', '%s.json' % trialName), 'r') as trialJSON:\n trialJson = json.load(trialJSON)\n else:\n try:\n with open(os.path.join(self._trialPath, 'design', '%s.json' % trialName), 'r') as trialJSON:\n trialJson = json.load(trialJSON)\n except FileNotFoundError:\n raise FileNotFoundError('A trial named \"%s\" does not exist' % trialName)\n with open(os.path.join(self._trialPath, 'execution', '%s.json' % trialName), 'w') as trialJSON:\n json.dump(trialJson, trialJSON, indent=4, sort_keys=True)\n return trialJson\n\n\n def getTrialJSON_from_design(self, trialName):\n try:\n with open(os.path.join(self._trialPath, 'design', '%s.json' % trialName), 'r') as trialJSON:\n trialJson = json.load(trialJSON)\n except FileNotFoundError:\n raise FileNotFoundError('A trial named \"%s\" does not exist' % trialName)\n return trialJson\n\n\n def setAttributeInTrial(self, trialName, entityType, entityName, attrMap, updateLevel=0):\n \"\"\"\n Also updates the JSON of the trial\n Set the attribute for the required entity and all the entities it contains.\n\n :param entityType:\n :param entityName:\n :param attrMap:\n :param updateLevel: how much recursive steps to update\n :return:\n \"\"\"\n pass\n\n\n def getTrial(self, trialName=None):\n \"\"\"\n Return a pandas with the definition of the trial.\n\n The pandas columns are:\n\n trialName, entityType, entityName, type attributeName attributeValue\n\n :param trialName: if NOne, return the pandas for all trials.\n :return:\n a pandas.\n \"\"\"\n pass\n\n\n def loadTrial(self, trialName):\n \"\"\"\n Loads the trial to the TB server.\n\n Loads the JSON from the disk and then load the\n entities to the server.\n\n commits the changes to git.\n\n :param name:\n :return:\n \"\"\"\n trialJSON = self.getTrialJSON(trialName)\n for entityJSON in trialJSON['Entities']:\n entityTypeHome = getattr(self._home, '%sHome' % entityJSON['entityType'].lower())\n entityProxy = entityTypeHome.createProxy(entityJSON['Name'])\n self._setEntityForTrialInTB(entityProxy, entityJSON)\n # try:\n # for window in self.getWindows(entityJSON[\"Type\"]):\n # windowEntityJSON = entityJSON.copy()\n # windowEntityJSON['Type'] = 'calculated_%s' % entityJSON['Type']\n # windowEntityJSON['Name'] = self._getWindowEntityName(entityJSON['Name'], window)\n # windowEntityProxy = entityTypeHome.createProxy(windowEntityJSON['Name'])\n # self._setEntityForTrialInTB(windowEntityProxy, windowEntityJSON)\n # except KeyError:\n # pass\n\n def loadTrialFromDesign(self, trialName):\n \"\"\"\n Loads the trial to the TB server.\n\n Loads the JSON from the disk and then load the\n entities to the server.\n\n commits the changes to git.\n\n :param name:\n :return:\n \"\"\"\n trialJSON = self.getTrialJSON_from_design(trialName)\n\n for entityJSON in trialJSON['Entities']:\n entityTypeHome = getattr(self._home, '%sHome' % entityJSON['entityType'].lower())\n entityProxy = entityTypeHome.createProxy(entityJSON['Name'])\n self._setEntityForTrialInTB(entityProxy, entityJSON)\n try:\n for window in self.getWindows(entityJSON[\"Type\"]):\n windowEntityJSON = entityJSON.copy()\n windowEntityJSON['Type'] = 'calculated_%s' % entityJSON['Type']\n windowEntityJSON['Name'] = self._getWindowEntityName(entityJSON['Name'], window)\n windowEntityProxy = entityTypeHome.createProxy(windowEntityJSON['Name'])\n self._setEntityForTrialInTB(windowEntityProxy, windowEntityJSON)\n except KeyError:\n pass\n\n def _setEntityForTrialInTB(self, entityProxy, JSON):\n self._prepareEntity(entityProxy, JSON)\n self._loadEntity(entityProxy, JSON)\n\n\n def _loadEntity(self, entityProxy ,JSON):\n entityProxy.setAttributes(JSON['attributes'])\n for containedEntity in JSON['contains']:\n containedEntityHome = getattr(self._home, \"%sHome\" % (containedEntity[0].lower()))\n containedEntityProxy = containedEntityHome.createProxy(containedEntity[1])\n entityProxy.addRelation(containedEntityProxy)\n # try:\n # entityTypeHome = getattr(self._home, '%sHome' % JSON['entityType'].lower())\n # for window in self.getWindows(JSON[\"Type\"]):\n # windowEntityName = self._getWindowEntityName(JSON['Name'], window)\n # windowEntityProxy = entityTypeHome.createProxy(windowEntityName)\n # entityProxy.addRelation(windowEntityProxy)\n # except KeyError:\n # pass\n\n\n def _prepareEntity(self, entityProxy, JSON):\n \"\"\"\n Delete relations and attributes (that are in the JSON).\n\n :param entityName:\n :return:\n \"\"\"\n entityProxy.delRelations()\n for attributeKey, attributeValue in JSON['attributes'].items():\n entityProxy.delAttributes(attributeKey)\n","sub_path":"experimentManagement.py","file_name":"experimentManagement.py","file_ext":"py","file_size_in_byte":10353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"617986411","text":"#!/usr/bin/env python\n\"\"\"\nUsage: python move.py \n\nThis program tells the specified controller to move the stage by the specified\ndistance in mm\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\nimport pyAPT\nimport pylibftdi\n\n\ndef main(args):\n if len(args) < 3:\n print(__doc__)\n return 1\n else:\n serial = args[1]\n dist = float(args[2])\n\n try:\n with pyAPT.MTS50(serial_number=serial) as con:\n print(\"\\tMoving stage by %.2fmm...\" % (dist), end=\" \")\n con.move(dist)\n print(\"OK\")\n print(\"\\tNew position: %.2f %s\" % (con.position(), con.unit))\n return 0\n except pylibftdi.FtdiError:\n print(\"\\tCould not find APT controller S/N of\", serial)\n return 1\n\n\nif __name__ == \"__main__\":\n import sys\n\n sys.exit(main(sys.argv))\n","sub_path":"scripts/move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"367233769","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom git_code_debt.file_diff_stat import FileDiffStat\nfrom git_code_debt.metric import Metric\nfrom git_code_debt.metrics.base import SimpleLineCounterBase\nfrom git_code_debt.repo_parser import Commit\n\n\ndef test_simple_base_counter():\n \"\"\"Smoke test for SimpleLineCounterBase\"\"\"\n class TestCounter(SimpleLineCounterBase):\n def should_include_file(self, file_diff_stat):\n return True\n\n def line_matches_metric(self, line, file_diff_stat):\n return True\n\n parser = TestCounter()\n assert parser.get_possible_metric_ids() == ['TestCounter']\n\n input_stats = [\n FileDiffStat(\n 'test.py',\n ['a', 'b', 'c'],\n ['d'],\n 'this_should_be_ignored'\n ),\n ]\n\n metrics = list(parser.get_metrics_from_stat(Commit.blank, input_stats))\n assert metrics == [Metric('TestCounter', 2)]\n\n\ndef test_includes_file_by_default():\n counter = SimpleLineCounterBase()\n assert counter.should_include_file(None)\n","sub_path":"tests/metrics/base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"372830767","text":"import os\n\n# GLOBAL\nPROD = os.getenv(\"PROD\", \"False\") == \"True\"\nDOCKER = os.getenv(\"DOCKER\", \"False\") == \"True\"\nPROJECT_ID = \"github-298920\"\nBACKEND_URL = \"https://api.githubtrends.io\" if PROD else \"http://localhost:8000\"\n\n# API\n# https://docs.github.com/en/rest/reference/rate-limit\n# https://docs.github.com/en/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits\n# https://docs.github.com/en/graphql/overview/resource-limitations\nTIMEOUT = 10 # max seconds to wait for api response\nNODE_CHUNK_SIZE = 100 # number of nodes (commits) to query (max 100)\nNODE_THREADS = 10 # number of node queries simultaneously (avoid blacklisting)\nCUTOFF = 500 # if > cutoff lines, assume imported, don't count\n\n# CUSTOMIZATION\nBLACKLIST = [\"Jupyter Notebook\", \"HTML\"] # languages to ignore\n\n# OAUTH\nOAUTH_CLIENT_ID = os.getenv(\"OAUTH_CLIENT_ID\", \"\") # client ID for GitHub OAuth App\nOAUTH_CLIENT_SECRET = os.getenv(\"OAUTH_CLIENT_SECRET\", \"\") # client secret for App\nOAUTH_REDIRECT_URI = os.getenv(\"OAUTH_REDIRECT_URI\", \"\") # redirect uri for App\n\n# PUBSUB\nPUBSUB_PUB = os.getenv(\"PUBSUB_PUB\", \"False\") == \"True\"\nPUBSUB_TOKEN = os.getenv(\"PUBSUB_TOKEN\", \"\")\nLOCAL_SUBSCRIBER = ( # based on name of Docker container\n \"http://\" + (\"subscriber\" if DOCKER else \"localhost\") + \":8001/pubsub/sub/\"\n)\n\n\n# MONGODB\nMONGODB_PASSWORD = os.getenv(\"MONGODB_PASSWORD\", \"\")\n\n# SVG\nDEFAULT_COLOR = \"#858585\"\n\n# SENTRY\nSENTRY_DSN = os.getenv(\"SENTRY_DSN\", \"\")\n\n# TESTING\nTEST_USER_ID = \"AshishGupta938\" # for testing, previously \"avgupta456\"\nTEST_TOKEN = os.getenv(\"AUTH_TOKEN\", \"\") # for authentication\n","sub_path":"backend/src/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"358933733","text":"VERSION = (0, 0, 1,)\n__version__ = '.'.join(map(str, VERSION))\ndefault_app_config = 'vendors.django_liqpay.apps.DjangoLiqpayConfig'\n\nimport base64\nimport hashlib\nimport json\nfrom urllib.parse import urljoin\n\nfrom .forms import ApiForm, CheckoutForm\nfrom .exceptions import LiqPayValidationError\nfrom .settings import \\\n LIQPAY_DEFAULT_CURRENCY, \\\n LIQPAY_DEFAULT_LANGUAGE,\\\n LIQPAY_DEFAULT_ACTION,\\\n LIQPAY_PUBLIC_KEY,\\\n LIQPAY_PRIVATE_KEY\n\n\nclass LiqPay(object):\n\n host = 'https://www.liqpay.ua/api/'\n\n checkout_url = urljoin(host, '3/checkout/')\n\n def __init__(self, public_key, private_key):\n self._public_key = public_key\n self._private_key = private_key\n\n def get_checkout_form(self, **kwargs):\n\n params = self._clean_api_params(**kwargs)\n\n data = base64.b64encode(json.dumps(params).encode())\n\n return CheckoutForm(self.checkout_url, data={\n 'data': data,\n 'signature': self._make_signature(data)\n }) \n\n def _clean_api_params(self, **kwargs):\n\n params = {\n 'version': 3,\n 'currency': settings.LIQPAY_DEFAULT_CURRENCY,\n 'language': settings.LIQPAY_DEFAULT_LANGUAGE,\n 'action': settings.LIQPAY_DEFAULT_ACTION,\n 'public_key': self._public_key\n }\n\n params.update(kwargs)\n\n form = ApiForm(data=params)\n\n if not form.is_valid():\n raise LiqPayValidationError(\n 'Invalid params: %s' % ', '.join(form.errors.keys()))\n\n return form.cleaned_data\n\n def _make_signature(self, data):\n params = [self._private_key, data.decode(), self._private_key]\n fields = ''.join(params)\n return base64.b64encode(hashlib.sha1(fields.encode()).digest())\n\nliqpay = LiqPay(settings.LIQPAY_PUBLIC_KEY, settings.LIQPAY_PRIVATE_KEY)\n","sub_path":"app/vendors/django_liqpay/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"383116114","text":"from .base import *\n\nALLOWED_HOSTS = ['127.0.0.1']\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',\n }\n}\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'dev',\n 'USER': 'dev',\n 'PASSWORD': 'dev',\n 'HOST': '192.168.1.100',\n 'PORT': '5432',\n },\n}\n\nDEBUG = True\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\nEMAIL_HOST = 'localhost'\nEMAIL_PORT = 25\n\nSECRET_KEY = 'jr7)nuw^&47$z@+h7^yd-np22p)8e_2e)i&3y#z8br_ae_yr(c'\n","sub_path":"config/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"334700976","text":"# S2Data_Hander\n\nimport numpy as np\nfrom scipy.fftpack import rfft, irfft\nimport os\nimport re\nimport xml.etree.ElementTree as ET\nfrom scipy.signal import savgol_filter, butter, bessel, filtfilt\n\nfrom PyQt5 import QtCore, QtGui\nimport pyqtgraph as pg\nimport sys\n\nclass S2Data(object):\n def __init__(self, fpath):\n self.fpath = fpath\n self.ri = self.get_recording_info()\n\n def get_recording_info(self):\n ri = {}\n ri['fpath'] = self.fpath\n root = ET.parse(self.fpath + 'descriptor.xml').getroot()[0]\n ri['RawDataLength'] = int(root.find('Data_Length').text)\n ri['StartFreq'] = float(root.find('StartFreq').text)\n ri['Bandwidth'] = float(root.find('Bandwidth').text)\n ri['RecordsPerBuffer'] = int(root.find('RecordsPerBuffer').text)\n ri['Channels'] = root.find('Channels').text\n ri['ChirpRate'] = float(root.find('Chirp_Rate').text)\n ri['FDigitizer'] = float(root.find('FDigitizer').text)\n ri['DDSTime'] = float(root.find('DDSTime').text)\n ri['recordsPerFile'] = os.path.getsize(self.fpath + '0.dat') // ri['RawDataLength'] // 2\n ri['ts'] = ''#root.find('GPSInfo').find('TimeStamp').text\n\n bytes_recorded = 0\n p = re.compile('^\\d+\\.dat')\n for file in os.listdir(self.fpath):\n if p.match(file):\n bytes_recorded += os.path.getsize(self.fpath + file)\n\n channelBuffersPerFile = ri['recordsPerFile'] // ri['RecordsPerBuffer']\n channelBuffersRecorded = bytes_recorded // 2 // ri['RawDataLength'] // ri['RecordsPerBuffer']\n\n if(ri['Channels'] == 'AB'):\n channelBuffersPerFile //= 2\n channelBuffersRecorded //= 2\n ri['channelBuffersPerFile'] = channelBuffersPerFile\n ri['channelBuffersRecorded'] = channelBuffersRecorded\n ri['numberOfFrames'] = ri['RecordsPerBuffer'] * ri['channelBuffersRecorded']\n # get bg and recovery arrays\n for ch in ri['Channels']:\n ri['bg' + ch] = np.fromfile(ri['fpath'] + ch + '_bkg.dat', dtype=np.float32)\n bgMat = np.outer(ri['bg' + ch], np.ones(ri['RecordsPerBuffer']))\n\n ri['freq'] = np.linspace(ri['StartFreq'], ri['StartFreq'] + ri['Bandwidth'], ri['RawDataLength'])\n rec_freq = np.hstack((range(ri['RawDataLength']//2), [0]))/ri['RawDataLength'] * ri['FDigitizer']\n ri['rec_factor'] = np.exp(1j*np.pi*np.sign(rec_freq)*rec_freq**2 / ri['ChirpRate'])\n\n rec_factor_mat = np.outer(ri['rec_factor'][:ri['RawDataLength']//2+1], np.ones(ri['RecordsPerBuffer']))\n\n\n return ri\n #%%\n\n def recover(self, DataBuffer):\n Zf_cpx = np.empty((self.ri['RecordsPerBuffer'], len(self.ri['rec_factor'])), dtype=np.complex128)\n Zf_cpx.view(np.double)[:, 1:-1] = rfft(DataBuffer)\n Zf_cpx[:, 0] = np.imag(Zf_cpx[:, 0])\n Zf_cpx[:, -1] = np.real(Zf_cpx[:, -1])\n Zf_cpx *= self.ri['rec_factor']\n Zf_cpx[:, 0] = 1j * np.real(Zf_cpx[:, 0])\n\n return np.real(irfft(Zf_cpx.view(np.double)[:, 1:-1]))\n\n def recoverFrame(self, DataBuffer):\n Zf_cpx = np.empty((len(self.ri['rec_factor'])), dtype=np.complex128)\n Zf_cpx.view(np.double)[ 1:-1] = rfft(DataBuffer)\n Zf_cpx[0] = np.imag(Zf_cpx[ 0])\n Zf_cpx[-1] = np.real(Zf_cpx[ -1])\n Zf_cpx *= self.ri['rec_factor']\n Zf_cpx[ 0] = 1j * np.real(Zf_cpx[ 0])\n\n return np.real(irfft(Zf_cpx.view(np.double)[ 1:-1]))\n\n\n\n def UInt16ToRaw(self,DataUInt16):\n RawData = []\n for d16, ch in zip(DataUInt16, self.ri['Channels']):\n RawData.append((d16.reshape(-1, self.ri['RawDataLength'],).squeeze().astype(np.float) - 2**15) / 2**16 * 1.25 - self.ri['bg' + ch] )\n return RawData\n\n\n def getRawDataBuffer(self, bufferNum):\n return self.UInt16ToRaw(self.getUInt16DataBuffer(bufferNum))\n\n\n def getRecDataBuffer(self, bufferNum):\n return [self.recover(data) for data in self.getRawDataBuffer(bufferNum)]\n\n\n def getRawData(self, frameNum):\n buffNum = frameNum // self.ri['RecordsPerBuffer']\n frameInBuff = frameNum % self.ri['RecordsPerBuffer']\n UInt16DataBuffer = self.getUInt16DataBuffer(buffNum)\n Data16 = []\n for d16 in UInt16DataBuffer:\n Data16.append(d16[frameInBuff, :])\n return self.UInt16ToRaw(Data16)\n\n\n def getRecData(self, frameNum):\n return [self.recoverFrame(data) for data in self.getRawData(frameNum)]\n\n def getAvgData(self, frameNum, avgs):\n temp = [self.recoverFrame(data) for data in self.getRawData(frameNum)]\n for i in range(avgs):\n temp += [self.recoverFrame(data) for data in self.getRawData(frameNum + i)]\n temp /= avgs\n return temp\n\n def getMaxHold(self, frameNum, frames):\n temp1 = [self.recoverFrame(data) for data in self.getRawData(frameNum)]\n for j in range(frames):\n temp2 = [self.recoverFrame(data) for data in self.getRawData(frameNum + j)]\n temp1 = [max(temp1[i],temp2[i]) for i in range(len(x))]\n return temp1\n\n def getUInt16DataBuffer(self, bufferNum):\n bufferInFile = bufferNum % self.ri['channelBuffersPerFile']\n fileNum = bufferNum // self.ri['channelBuffersPerFile']\n DataUInt16 = []\n recordsPerFile = os.path.getsize(self.ri['fpath'] + str(fileNum) + '.dat') // self.ri['RawDataLength'] // 2\n disk_arr = np.memmap(self.ri['fpath'] + str(fileNum) + '.dat', np.uint16, 'r', shape=(recordsPerFile, self.ri['RawDataLength']))\n buffLen = self.ri['RecordsPerBuffer']\n if 'AB' in self.ri['Channels']:\n buffStart0 = 2*bufferInFile*buffLen\n buffStart1 = 2*bufferInFile*buffLen + buffLen\n DataUInt16.append(disk_arr[buffStart0:buffStart0 + buffLen, :])\n DataUInt16.append(disk_arr[buffStart1:buffStart1 + buffLen, :])\n else:\n DataUInt16.append(disk_arr[(bufferInFile*buffLen):(bufferInFile*buffLen+self.ri['RecordsPerBuffer']), :])\n return DataUInt16\n\n\n def getDataBufferSeg(self, bufferNum, i1, seg_len):\n bufferInFile = bufferNum % self.ri['channelBuffersPerFile']\n fileNum = bufferNum // self.ri['channelBuffersPerFile']\n\n disk_arr = np.memmap(self.fpath + str(fileNum) + '.dat', np.uint16, 'r', shape=(self.ri['recordsPerFile'], self.ri['RawDataLength']))\n frame_start = 2*self.ri['RecordsPerBuffer']*self.ri['bufferInFile']\n Data1 = (disk_arr[frame_start:frame_start+self.ri['RecordsPerBuffer'], i1:i1+seg_len].copy().T.astype(np.float) - 2**15) / 2**16 * 1.25\n frame_start = 2*self.ri['RecordsPerBuffer']*bufferInFile + self.ri['RecordsPerBuffer']\n Data2 = (disk_arr[frame_start:frame_start + self.ri['RecordsPerBuffer'], i1:i1+seg_len].copy().T.astype(np.float) - 2**15) / 2**16 * 1.25\n\n Rec1 = np.real(np.fft.ifft(ri['rec_factor_seg_mat'] * np.fft.fft((Data1 - self.ri['bgAMat'][i1:i1+seg_len]), axis=0), axis=0))\n Rec2 = np.real(np.fft.ifft(ri['rec_factor_seg_mat'] * np.fft.fft((Data2 - self.ri['bgBMat'][i1:i1+seg_len]), axis=0), axis=0))\n return (Rec1, Rec2)\n\nclass S2Functions(object):\n def __init__(self):\n pass\n\n def dB(self, x):\n return 10*np.log10(np.abs(x))\n\n def smoother(self, data, points = 7, order = 3):\n \"\"\"\n Example call: smoother(data, points = 7, order = 3)\n \"\"\"\n return savgol_filter(data, points, order)\n\n def bkg_filt_data_highpass(self, data, order = 1, freq = .0001, type = 'highpass'):\n \"\"\"\n Example call: bkg_filt_data_highpass(data, order = 1, freq = .0001, type = 'highpass')\n \"\"\"\n b,a = bessel(order,freq, btype = type)\n return filtfilt(b, a, data)\n\n def bkg_filt_data_poly(self, data, order = 19):\n \"\"\"\n Example call: bkg_filt_data_poly(data, order = 19)\n \"\"\"\n x = np.arange(len(data))\n p = np.poly1d(np.polyfit(x, data, order))\n data -= p(x)\n return data\n\n def detect_peaks(self, x, mph=None, mpd=1, threshold=0, edge='rising',\n kpsh=False, valley=False, show=False):\n\n \"\"\"Detect peaks in data based on their amplitude and other features.\n Parameters\n ----------\n x : 1D array_like\n data.\n mph : {None, number}, optional (default = None)\n detect peaks that are greater than minimum peak height.\n mpd : positive integer, optional (default = 1)\n detect peaks that are at least separated by minimum peak distance (in\n number of data).\n threshold : positive number, optional (default = 0)\n detect peaks (valleys) that are greater (smaller) than `threshold`\n in relation to their immediate neighbors.\n edge : {None, 'rising', 'falling', 'both'}, optional (default = 'rising')\n for a flat peak, keep only the rising edge ('rising'), only the\n falling edge ('falling'), both edges ('both'), or don't detect a\n flat peak (None).\n kpsh : bool, optional (default = False)\n keep peaks with same height even if they are closer than `mpd`.\n valley : bool, optional (default = False)\n if True (1), detect valleys (local minima) instead of peaks.\n show : bool, optional (default = False)\n if True (1), plot data in matplotlib figure.\n Returns\n -------\n ind : 1D array_like\n indeces of the peaks in `x`.\n Notes\n -----\n The function can handle NaN's\n See this IPython Notebook [1]_.\n References\n ----------\n .. [1] http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/DetectPeaks.ipynb\n\n \"\"\"\n\n x = np.atleast_1d(x).astype('float64')\n if x.size < 3:\n return np.array([], dtype=int)\n if valley:\n x = -x\n # find indices of all peaks\n dx = x[1:] - x[:-1]\n # handle NaN's\n indnan = np.where(np.isnan(x))[0]\n if indnan.size:\n x[indnan] = np.inf\n dx[np.where(np.isnan(dx))[0]] = np.inf\n ine, ire, ife = np.array([[], [], []], dtype=int)\n if not edge:\n ine = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) > 0))[0]\n else:\n if edge.lower() in ['rising', 'both']:\n ire = np.where((np.hstack((dx, 0)) <= 0) & (np.hstack((0, dx)) > 0))[0]\n if edge.lower() in ['falling', 'both']:\n ife = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) >= 0))[0]\n ind = np.unique(np.hstack((ine, ire, ife)))\n # handle NaN's\n if ind.size and indnan.size:\n # NaN's and values close to NaN's cannot be peaks\n ind = ind[np.in1d(ind, np.unique(np.hstack((indnan, indnan-1, indnan+1))), invert=True)]\n # first and last values of x cannot be peaks\n if ind.size and ind[0] == 0:\n ind = ind[1:]\n if ind.size and ind[-1] == x.size-1:\n ind = ind[:-1]\n # remove peaks < minimum peak height\n if ind.size and mph is not None:\n ind = ind[x[ind] >= mph]\n # remove peaks - neighbors < threshold\n if ind.size and threshold > 0:\n dx = np.min(np.vstack([x[ind]-x[ind-1], x[ind]-x[ind+1]]), axis=0)\n ind = np.delete(ind, np.where(dx < threshold)[0])\n # detect small peaks closer than minimum peak distance\n if ind.size and mpd > 1:\n ind = ind[np.argsort(x[ind])][::-1] # sort ind by peak height\n idel = np.zeros(ind.size, dtype=bool)\n for i in range(ind.size):\n if not idel[i]:\n # keep peaks with the same height if kpsh is True\n idel = idel | (ind >= ind[i] - mpd) & (ind <= ind[i] + mpd) \\\n & (x[ind[i]] > x[ind] if kpsh else True)\n idel[i] = 0 # Keep current peak\n # remove the small peaks and sort back the indices by their occurrence\n ind = np.sort(ind[~idel])\n\n return ind\n\nclass Window(QtGui.QMainWindow):\n def __init__(self,folder ='TestData/Test/ch1and2/', **kwargs):\n super(Window, self).__init__(None)\n\n # S2 Data Handling Options\n self.options = {\n 'select': 'AB',\n 'bkg_filt': 'highpass',\n 'SG_filt':True }\n\n print(\"Default Options\")\n print(self.options)\n self.options.update(kwargs)\n print(\"Given Options\")\n print(self.options)\n\n self.folder = folder\n self.a = 1\n self.bkg_filt = self.options['bkg_filt']\n self.select = self.options['select']\n self.SG_filt = self.options['SG_filt']\n\n self.S2F = S2Functions()\n\n #Create PyQT window\n self.window = pg.GraphicsWindow()\n self.window.setBackground('w')\n self.setCentralWidget(self.window)\n\n # Create plot\n self._plot = self.window.addPlot(title='')\n self._plot.showGrid(x=True, y=True, alpha=0.5)\n self._plot.setLabel('left', 'Power (dB)')\n self._plot.setLabel('bottom', 'Frequency (GHz)')\n self._plot.setYRange(-100,0)\n\n # Create GUI Items\n self.max_slider = 10000000#S2DataDirectory(self.folder).ChannelFramesPerFile * S2DataDirectory(self.folder).DataDescriptor.FileCount[3]\n self.slider = pg.SpinBox(value=0,step=1, bounds=[0,self.max_slider-1])\n self.spin = pg.SpinBox(value=3e-3,step=1e-3, bounds=[1e-8,.2])\n self.spin_poly = pg.SpinBox(value=15,step=1, bounds=[1,35])\n self.SavGolWindow = pg.SpinBox(value=7,step=2, bounds=[3,23])\n self.SavGolPoly = pg.SpinBox(value=3,step=2, bounds=[1,int(self.SavGolWindow.value()-2)])\n self.button = QtGui.QPushButton('Select Data Directory',self)\n self.button1 = QtGui.QRadioButton(\"1x\"); self.button1.setChecked(True)\n self.button2 = QtGui.QPushButton('Toggle Dual Channel',self)\n self.button3 = QtGui.QRadioButton(\"100x\")\n self.button4 = QtGui.QRadioButton(\"1000x\")\n self.button5 = QtGui.QRadioButton(\"10000x\")\n self.button6 = QtGui.QPushButton(\"SG Filter\")\n self.labelframe = \"Frame Number\"\n self.labelspin = \"Highpass Filter Setting\"\n self.labelSavGol1 = \"SavGol Filter Window\"\n self.labelSavGol2 = \"SavGol Filter Poly Order\"\n self.labelPoly = \"Poly Order\"\n self.crosshair = \"\"\n\n self.createMenuBar()\n self.createDockWidget()\n\n # Handle GUI interaction\n self.slider.sigValueChanging.connect(self.sliderValueChanged)\n self.spin.sigValueChanging.connect(self.spinValueChanged)\n self.spin_poly.sigValueChanging.connect(self.spinPolyValueChanged)\n self.SavGolWindow.sigValueChanging.connect(self.SavGolWindowValueChanged)\n self.SavGolPoly.sigValueChanging.connect(self.SavGolPolyValueChanged)\n self.button.clicked.connect(self.handleButton)\n self.button1.clicked.connect(self.handleButton3)\n self.button2.clicked.connect(self.handleButton2)\n self.button3.clicked.connect(self.handleButton3)\n self.button4.clicked.connect(self.handleButton3)\n self.button5.clicked.connect(self.handleButton3)\n self.button6.clicked.connect(self.handleButton6)\n # # Cross Hair creation\n self.vLine = pg.InfiniteLine(angle=90, movable=False)\n self.hLine = pg.InfiniteLine(angle=0, movable=False)\n self.label = pg.LabelItem(justify='center')\n\n self._plot.addItem(self.vLine, ignoreBounds=True)\n self._plot.addItem(self.hLine, ignoreBounds=True)\n self._plot.setTitle(self.crosshair)\n self.proxy = pg.SignalProxy(self._plot.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)\n\n # Make First Plot\n self.drawCurve()\n\n\n def createMenuBar(self):\n # Creates Menu\n exit_action = QtGui.QAction('&Exit', self)\n exit_action.triggered.connect(self.close)\n menubar = self.menuBar()\n file_menu = menubar.addMenu('&File')\n file_menu.addAction(exit_action)\n\n def createDockWidget(self):\n # Creates GUI interactions in plot\n my_dock_widget = QtGui.QDockWidget()\n my_dock_widget.setObjectName('Control Panel')\n my_dock_widget.setAllowedAreas(QtCore.Qt.TopDockWidgetArea | QtCore.Qt.BottomDockWidgetArea)\n my_house_widget = QtGui.QWidget()\n my_house_layout = QtGui.QHBoxLayout()\n my_house_layout.addWidget(QtGui.QLabel(self.labelframe))\n my_house_layout.addWidget(self.slider)\n my_house_layout.addWidget(self.button1)\n my_house_layout.addWidget(self.button3)\n my_house_layout.addWidget(self.button4)\n my_house_layout.addWidget(self.button5)\n if self.bkg_filt == 'highpass':\n my_house_layout.addWidget(QtGui.QLabel(self.labelspin))\n my_house_layout.addWidget(self.spin)\n elif self.bkg_filt == 'poly':\n my_house_layout.addWidget(QtGui.QLabel(self.labelPoly))\n my_house_layout.addWidget(self.spin_poly)\n\n my_house_layout.addWidget(QtGui.QLabel(self.labelSavGol1))\n my_house_layout.addWidget(self.SavGolWindow)\n my_house_layout.addWidget(QtGui.QLabel(self.labelSavGol2))\n my_house_layout.addWidget(self.SavGolPoly)\n my_house_layout.addWidget(self.button6)\n my_house_layout.addWidget(self.button)\n my_house_layout.addWidget(self.button2)\n my_house_widget.setLayout(my_house_layout)\n my_dock_widget.setWidget(my_house_widget)\n self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, my_dock_widget)\n\n def sliderValueChanged(self, int_value):\n # Handles Slider (spin) Movements\n self.a = int(int_value.value())\n self.drawCurve()\n\n def SavGolWindowValueChanged(self, int_value):\n # Handles Slider (spin) Movements\n self.SavGolPoly.setMaximum( int_value.value() - 2 )\n self.drawCurve()\n\n def SavGolPolyValueChanged(self, int_value):\n # Handles Slider (spin) Movements\n self.drawCurve()\n\n def spinValueChanged(self,sb):\n #Handles Spin Movements\n self.drawCurve()\n\n def spinPolyValueChanged(self,sb):\n #Handles Spin Movements\n self.drawCurve()\n\n def handleButton(self):\n #HAndles button press\n directory_temp = QtGui.QFileDialog.getExistingDirectory(self, 'Select Data Directory')\n self.folder = directory_temp+'/'\n self.max_slider = 1000000#S2DataDirectory(self.folder).ChannelFramesPerFile * S2DataDirectory(self.folder).DataDescriptor.FileCount[3]\n self.slider.setOpts(bounds=[0,self.max_slider-1])\n print(self.folder)\n\n self.drawCurve()\n\n def handleButton2(self):\n #Handles button press\n if self.select == 'AB':\n self.select ='A'\n\n elif self.select == 'A':\n self.select = 'B'\n\n elif self.select == 'B':\n self.select = 'AB'\n\n self.drawCurve()\n\n def handleButton3(self):\n if self.button3.isChecked():\n self.slider.setOpts(step=100)\n elif self.button4.isChecked():\n self.slider.setOpts(step=1000)\n elif self.button1.isChecked():\n self.slider.setOpts(step=1)\n elif self.button5.isChecked():\n self.slider.setOpts(step=10000)\n else:\n self.slider.setOpts(step=1)\n\n def handleButton6(self):\n #Handles button press\n if self.SG_filt == True:\n self.SG_filt = False\n\n elif self.SG_filt == False:\n self.SG_filt = True\n\n self.drawCurve()\n\n def mouseMoved(self, evt):\n # Handles Crosshair Movement\n pos = evt[0] ## using signal proxy turns original arguments into a tuple\n if self._plot.sceneBoundingRect().contains(pos):\n mousePoint = self._plot.vb.mapSceneToView(pos)\n self.crosshair = \"Frequency=%0.5f GHz, Power=%0.1f dB\" % (mousePoint.x(), mousePoint.y())\n self._plot.setTitle(self.crosshair)\n self.vLine.setPos(mousePoint.x())\n self.hLine.setPos(mousePoint.y())\n\n def drawCurve(self):\n # Main part of program, creates, updates, and manipulates the plot.\n self._plot.clear()\n self._plot.addItem(self.vLine, ignoreBounds=True)\n self._plot.addItem(self.hLine, ignoreBounds=True)\n self.proxy = pg.SignalProxy(self._plot.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)\n self._plot.setTitle(self.crosshair)\n\n SG1 = int(self.SavGolWindow.value())\n SG2 = int(self.SavGolPoly.value())\n spinval = self.spin.value()\n polyval = self.spin_poly.value()\n\n def dB(x):\n return 10*np.log10(abs(x))\n\n # dB0 = S2DataDirectory(self.folder)\n dB0 = S2Data(self.folder)\n start = dB0.ri[\"StartFreq\"]\n stop = start + dB0.ri[\"Bandwidth\"]\n\n self.f = np.linspace(start/1e3, stop/1e3, dB0.ri[\"RawDataLength\"])\n self.max_slider = 1000000# dB0.ChannelFramesPerFile * dB0.DataDescriptor.FileCount[3]\n\n channel = dB0.ri[\"Channels\"]\n\n if channel == 'AB':\n dat = dB0.getRecData(int(self.a))\n ch1 = dat[0]\n ch2 = dat[1]\n if self.SG_filt == True:\n ch1 = self.S2F.smoother(ch1, SG1, SG2)\n ch2 = self.S2F.smoother(ch2, SG1, SG2)\n if self.SG_filt == False:\n pass\n if self.bkg_filt == 'poly':\n ch1 = self.S2F.bkg_filt_data_poly(ch1, polyval)\n ch2 = self.S2F.bkg_filt_data_poly(ch2, polyval)\n self.setWindowTitle(str(int(self.a)) + ' / ' + str(self.max_slider-1) + ' ' + self.select + ', ' +str(np.floor(dB0.ri[\"DDSTime\"])) + ' us read')\n if self.select == 'A':\n self._plot.plot(self.f, dB(ch1), pen='b', name = 'A')\n elif self.select == 'B':\n self._plot.plot(self.f, dB(ch2), pen='r', name = 'B')\n else:\n self._plot.plot(self.f, dB(ch1), pen='b', name = 'A')\n self._plot.plot(self.f, dB(ch2), pen='r', name = 'B')\n elif self.bkg_filt == 'highpass':\n ch1 = self.S2F.bkg_filt_data_highpass(ch1, order = 1, freq = spinval, type = 'highpass')\n ch2 = self.S2F.bkg_filt_data_highpass(ch2, order = 1, freq = spinval, type = 'highpass')\n self.setWindowTitle(str(int(self.a)) + ' / ' + str(self.max_slider-1) + ' ' + self.select + ', ' +str(np.floor(dB0.ri[\"DDSTime\"])) + ' us read')\n if self.select == 'A':\n self._plot.plot(self.f, dB(ch1), pen='b', name = 'A')\n elif self.select == 'B':\n self._plot.plot(self.f, dB(ch2), pen='r', name = 'B')\n else:\n self._plot.plot(self.f, dB(ch1), pen='b', name = 'A')\n self._plot.plot(self.f, dB(ch2), pen='r', name = 'B')\n else:\n if self.select == 'A':\n self._plot.plot(self.f, dB(ch1), pen='b', name = 'A')\n elif self.select == 'B':\n self._plot.plot(self.f, dB(ch2), pen='r', name = 'B')\n else:\n self._plot.plot(self.f, dB(ch1), pen='b', name = 'A')\n self._plot.plot(self.f, dB(ch2), pen='r', name = 'B')\n\n elif channel == 'A':\n ch1 = dB0.getRecData(int(self.a))[0]\n if self.SG_filt == True:\n ch1 = self.S2F.smoother(ch1, SG1, SG2)\n if self.SG_filt == False:\n pass\n if self.bkg_filt == 'poly':\n ch1 = self.S2F.bkg_filt_data_poly(ch1, polyval)\n self.setWindowTitle(str(int(self.a)) + ' / ' + str(self.max_slider-1) + ' ' + self.select + ', ' +str(np.floor(dB0.ri[\"DDSTime\"])) + ' us read')\n self._plot.plot(self.f, dB(ch1), pen='b', name = 'A')\n elif self.bkg_filt == 'highpass':\n ch1 = self.S2F.bkg_filt_data_highpass(ch1, order = 1, freq = spinval, type = 'highpass')\n self.setWindowTitle(str(int(self.a)) + ' / ' + str(self.max_slider-1) + ' ' + self.select + ', ' +str(np.floor(dB0.ri[\"DDSTime\"])) + ' us read')\n self._plot.plot(self.f, dB(ch1), pen='b', name = 'A')\n else:\n self.setWindowTitle(str(int(self.a)) + ' / ' + str(self.max_slider-1) + ' ' + self.select + ', ' +str(np.floor(dB0.ri[\"DDSTime\"])) + ' us read')\n self._plot.plot(self.f, dB(ch1), pen='b', name = 'A')\n\n elif channel == 'B':\n ch2 = dB0.getRecData(int(self.a))[ 1]\n if self.SG_filt == True:\n ch2 = self.S2F.smoother(ch2, SG1, SG2)\n if self.SG_filt == False:\n pass\n if self.bkg_filt == 'poly':\n ch2 = self.S2F.bkg_filt_data_poly(ch2, polyval)\n self.setWindowTitle(str(int(self.a)) + ' / ' + str(self.max_slider-1) + ' ' + self.select + ', ' +str(np.floor(dB0.ri[\"DDSTime\"])) + ' us read')\n self._plot.plot(self.f, dB(ch2), pen='b', name = 'B')\n elif self.bkg_filt == 'highpass':\n ch2 = self.S2F.bkg_filt_data_highpass(ch2, order = 1, freq = spinval, type = 'highpass')\n self.setWindowTitle(str(int(self.a)) + ' / ' + str(self.max_slider-1) + ' ' + self.select + ', ' +str(np.floor(dB0.ri[\"DDSTime\"])) + ' us read')\n self._plot.plot(self.f, dB(ch2), pen='b', name = 'B')\n else:\n self.setWindowTitle(str(int(self.a)) + ' / ' + str(self.max_slider-1) + ' ' + self.select + ', ' +str(np.floor(dB0.ri[\"DDSTime\"])) + ' us read')\n self._plot.plot(self.f, dB(ch2), pen='b', name = 'B')\n\n\n\ndef S2Viewer(folder, **kwargs):\n \"\"\"\n Eample:\n S2viewer('Y:\\\\S2\\\\160916\\\\noextrafiber\\\\', select = 'B', bkg_filt = 'poly', SG_filt = True)\n\n Options:\n select = 'A', 'B', 'AB'\n bkg_filt = 'poly', 'highpass'\n SG_filt = Bool\n \"\"\"\n app = QtGui.QApplication(sys.argv)\n app.setApplicationName('Frame Plotter')\n window = Window(folder, **kwargs)\n window.showMaximized()\n app.exec_()\n","sub_path":"S2_SignalCat/S2Data_Handler.py","file_name":"S2Data_Handler.py","file_ext":"py","file_size_in_byte":26323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6301352","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nfrom stanfordcorenlp import StanfordCoreNLP\nfrom random import shuffle, seed\nimport string\nimport torch\nimport torchvision.models as models\nfrom PIL import Image\nimport skimage.io\n\nimport json\nimport numpy as np\nimport operator\nfrom unidecode import unidecode\nimport h5py\nimport os\nfrom glob import glob\nimport time\nfrom tqdm import tqdm\nfrom relation_to_adj_matrix import head_to_tree, tree_to_adj\n\npath = 'stanford-corenlp-4.2.2'\nnlp = StanfordCoreNLP(path)\n\ndef story_pro(annotations, params):\n print('len_annotations: ', len(annotations))\n\n image_feat_num = params['image_features']\n img_feat_num = json.load(open(image_feat_num, 'r'))\n print('len_feat_num', len(img_feat_num))\n count = 0\n story = []\n\n for i in tqdm(range(0, len(annotations), 5)):\n # for i in tqdm(range(0, 500, 5)):\n try:\n story_id = annotations[i][0]['story_id']\n\n img_id1, order1 = int(annotations[i][0][\"photo_flickr_id\"]), annotations[i][0][\n \"worker_arranged_photo_order\"]\n img_id2, order2 = int(annotations[i + 1][0][\"photo_flickr_id\"]), annotations[i + 1][0][\n \"worker_arranged_photo_order\"]\n img_id3, order3 = int(annotations[i + 2][0][\"photo_flickr_id\"]), annotations[i + 2][0][\n \"worker_arranged_photo_order\"]\n img_id4, order4 = int(annotations[i + 3][0][\"photo_flickr_id\"]), annotations[i + 3][0][\n \"worker_arranged_photo_order\"]\n img_id5, order5 = int(annotations[i + 4][0][\"photo_flickr_id\"]), annotations[i + 4][0][\n \"worker_arranged_photo_order\"]\n\n # if not (str(img_id1) in img_feat_num):\n # count += 1\n # print('img_id1:', img_id1)\n # continue\n # else:\n # img_str_id1 = str(img_id1)\n #\n # if not (str(img_id2) in img_feat_num):\n # count += 1\n # print('img_id2', img_id2)\n # continue\n # else:\n # img_str_id2 = str(img_id2)\n #\n # if not (str(img_id3) in img_feat_num):\n # count += 1\n # print('img_id3', img_id3)\n # continue\n # else:\n # img_str_id3 = str(img_id3)\n #\n # if not (str(img_id4) in img_feat_num):\n # count += 1\n # print('img_id4', img_id4)\n # continue\n # else:\n # img_str_id4 = str(img_id4)\n\n if not (str(img_id5) in img_feat_num):\n # print(str(img_id5))\n # print()\n count += 1\n print('img_id5', img_id5)\n print(count)\n continue\n else:\n img_str_id5 = str(img_id5)\n\n story1 = annotations[i][0]['text']\n # print('story1: ', story1)\n story2 = annotations[i + 1][0]['text']\n story3 = annotations[i + 2][0]['text']\n story4 = annotations[i + 3][0]['text']\n story5 = annotations[i + 4][0]['text']\n\n story1_rep = story1.replace(' .', '').replace(' !', '').replace(\" ?\", '').replace(\" '\", ' ').replace('[', '[ ').replace(']', ' ]')\n story2_rep = story2.replace(' .', '').replace(' !', '').replace(\" ?\", '').replace(\" '\", ' ').replace('[', '[ ').replace(']', ' ]')\n story3_rep = story3.replace(' .', '').replace(' !', '').replace(\" ?\", '').replace(\" '\", ' ').replace('[', '[ ').replace(']', ' ]')\n story4_rep = story4.replace(' .', '').replace(' !', '').replace(\" ?\", '').replace(\" '\", ' ').replace('[', '[ ').replace(']', ' ]')\n story5_rep = story5.replace(' .', '').replace(' !', '').replace(\" ?\", '').replace(\" '\", ' ').replace('[', '[ ').replace(']', ' ]')\n\n # print('story1_rep: ', story1_rep)\n\n story1_taken = nlp.word_tokenize(story1)\n story2_taken = nlp.word_tokenize(story2)\n story3_taken = nlp.word_tokenize(story3)\n story4_taken = nlp.word_tokenize(story4)\n story5_taken = nlp.word_tokenize(story5)\n # print(story1_taken)\n\n if len(story1_taken) > params['max_length']:\n count += 1\n continue\n if len(story2_taken) > params['max_length']:\n count += 1\n continue\n if len(story3_taken) > params['max_length']:\n count += 1\n continue\n if len(story4_taken) > params['max_length']:\n count += 1\n continue\n if len(story5_taken) > params['max_length']:\n count += 1\n continue\n\n sent1 = nlp.dependency_parse(story1_rep)\n # print('sent1: ', sent1)\n sent2 = nlp.dependency_parse(story2_rep)\n sent3 = nlp.dependency_parse(story3_rep)\n sent4 = nlp.dependency_parse(story4_rep)\n sent5 = nlp.dependency_parse(story5_rep)\n\n depen_list = [(sent1, order1), (sent2, order2), (sent3, order3), (sent4, order4), (sent5, order5)]\n depen_list = sorted(depen_list, key=operator.itemgetter(1))\n\n depen_list = [depen_list[0][0], depen_list[1][0], depen_list[2][0], depen_list[3][0]]\n # print('depen_list: ', depen_list)\n\n # label = annotations[i]['split']\n\n story_rep_list = [(story1_rep, order1), (story2_rep, order2), (story3_rep, order3),\n (story4_rep, order4), (story5, order5)]\n story_rep_list = sorted(story_rep_list, key=operator.itemgetter(1))\n story_rep_four = [story_rep_list[0][0], story_rep_list[1][0], story_rep_list[2][0], story_rep_list[3][0]]\n story_rep_last = [story_rep_list[4][0]]\n # print('story_rep_last:', story_rep_last)\n\n story_list = [(story1, order1), (story2, order2), (story3, order3), (story4, order4), (story5, order5)]\n story_list = sorted(story_list, key=operator.itemgetter(1))\n\n story_token_list = [(story1_taken, order1), (story2_taken, order2), (story3_taken, order3),\n (story4_taken, order4), (story5_taken, order5)]\n story_token_list = sorted(story_token_list, key=operator.itemgetter(1))\n\n story_token_list = [story_token_list[0][0], story_token_list[1][0], story_token_list[2][0],\n story_token_list[3][0], story_token_list[4][0]]\n\n img_id_list = [(img_id1, order1), (img_id2, order2), (img_id3, order3), (img_id4, order4), (img_str_id5, order5)]\n img_id_list = sorted(img_id_list, key=operator.itemgetter(1))\n\n ordered_stories_four = [story_list[0][0], story_list[1][0], story_list[2][0], story_list[3][0]]\n ordered_stories_last = story_list[4][0]\n # print(ordered_stories_last)\n order_last_img_id = img_id_list[4][0]\n # print(order_last_img_id)\n story.append({'story_id': story_id,\n 'story_token_list': story_token_list,\n 'stories_four': story_rep_four,\n # 'sent_rep': story_rep_four,\n 'sent_depen': depen_list,\n 'stories_last': ordered_stories_last,\n 'last_img_id': order_last_img_id,\n 'split': annotations[i][0]['split']})\n except json.decoder.JSONDecodeError:\n continue\n # print(story[1])\n nlp.close()\n with open('story10.json', 'w') as ff:\n json.dump(story, ff)\n # json.dump(story, open('story.json', 'w'))\n ff.close()\n\n return story\n\n\ndef build_vocab(storys, params):\n count_thr = params['word_count_threshold_test']\n\n counts = {}\n # for story in storys:\n # print(\"*\"*50)\n # token = story['story_token_list'][:4]\n # for sentence in token:\n # print(\"#\"*50)\n # print('sentence', sentence)\n # for w in sentence:\n # print('w', w)\n # counts[w] = counts.get(w, 0) + 1\n\n for story in storys:\n last_token = story['story_token_list'][4]\n # print('last_token: ', last_token)\n for w in last_token:\n # print('w: ', w)\n counts[w] = counts.get(w, 0) + 1\n cw = sorted([(count, w) for w, count in counts.items()], reverse=True)\n # print('top words and their counts')\n # print('\\n'.join(map(str, cw[:20])))\n\n # print some stats\n total_words = sum(counts.values())\n # print('total_words:', total_words)\n bad_words = [w for w, n in counts.items() if n <= count_thr]\n vocab = [w for w, n in counts.items() if n > count_thr]\n bad_count = sum(counts[w] for w in bad_words)\n # print('number of bad words: %d/%d = %.2f%%' % (len(bad_words), len(counts), len(bad_words)*100.0/len(counts)))\n # print('number of words in vocab would be %d' % (len(vocab), ))\n # print('number of UNKs: %d/%d = %.2f%%' % (bad_count, total_words, bad_count*100.0/total_words))\n\n # lets look at the distribution of lengths as well\n sent_lengths = {}\n for story in storys:\n token = story['story_token_list']\n txt = token[-1]\n nw = len(txt)\n sent_lengths[nw] = sent_lengths.get(nw, 0) + 1\n max_len = max(sent_lengths.keys())\n # print('max length sentence in raw data: ', max_len)\n # print('sentence length distribution (count, numbers of words):')\n sum_len = sum(sent_lengths.values())\n # for i in range(max_len+1):\n # print('%2d: %10d %f%%' % (i, sent_lengths.get(i, 0),sent_lengths.get(i, 0)*100.0/sum_len))\n\n # lets now produce the final annotations\n if bad_count > 0:\n vocab.append('UNK')\n # vocab['PADDING'] = 0\n\n # print('vocab: ', vocab)\n for story in storys:\n story['story_end'] = []\n txt = story['story_token_list'][-1]\n last = [w if counts.get(w, 0) > count_thr else 'UNK' for w in txt]\n story['story_end'].append(last)\n\n return vocab\n\ndef build_src_vocab(storys, params):\n count_thr = params['word_count_threshold']\n\n counts = {}\n for story in storys:\n # print(\"*\"*50)\n token = story['story_token_list'][:4]\n for sentence in token:\n # print(\"#\"*50)\n # print('sentence', sentence)\n for w in sentence:\n # print('w', w)\n counts[w] = counts.get(w, 0) + 1\n\n # for story in storys:\n # last_token = story['story_token_list'][4]\n # print('last_token: ', last_token)\n # for w in last_token:\n # print('w: ', w)\n # counts[w] = counts.get(w, 0) + 1\n cw = sorted([(count, w) for w, count in counts.items()], reverse=True)\n # print('top words and their counts')\n # print('\\n'.join(map(str, cw[:20])))\n\n # print some stats\n total_words = sum(counts.values())\n # print('total_words:', total_words)\n\n\n bad_words = [w for w, n in counts.items() if n <= count_thr]\n vocab = [w for w, n in counts.items() if n > count_thr]\n bad_count = sum(counts[w] for w in bad_words)\n # print('number of bad words: %d/%d = %.2f%%' % (len(bad_words), len(counts), len(bad_words) * 100.0 / len(counts)))\n # print('number of words in vocab would be %d' % (len(vocab),))\n # print('number of UNKs: %d/%d = %.2f%%' % (bad_count, total_words, bad_count * 100.0 / total_words))\n\n # lets look at the distribution of lengths as well\n sent_lengths = {}\n for story in storys:\n token = story['story_token_list']\n txt = token[-1]\n nw = len(txt)\n sent_lengths[nw] = sent_lengths.get(nw, 0) + 1\n max_len = max(sent_lengths.keys())\n # print('max length sentence in raw data: ', max_len)\n # print('sentence length distribution (count, numbers of words):')\n sum_len = sum(sent_lengths.values())\n # for i in range(max_len + 1):\n # print('%2d: %10d %f%%' % (i, sent_lengths.get(i, 0), sent_lengths.get(i, 0) * 100.0 / sum_len))\n\n # lets now produce the final annotations\n if bad_count > 0:\n vocab.append('UNK')\n\n # vocab['PADDING'] = 0\n\n # print('vocab: ', vocab)\n # for story in storys:\n # story['story_end'] = []\n # txt = story['story_token_list'][-1]\n # last = [w if counts.get(w, 0) > count_thr else 'UNK' for w in txt]\n # story['story_end'].append(last)\n\n return vocab\n\ndef encode_story_four(storys, params, src_wtoi):\n max_length = 40\n first = []\n second = []\n third = []\n four = []\n\n for i, story in enumerate(storys):\n\n # max_length = params['max_length']\n max_length = 40\n sent_insts = story['stories_four']\n # print('word_insts: ', sent_insts)\n\n for j, sents in enumerate(sent_insts):\n\n if j == 0:\n sent_lsit = np.zeros((40), dtype='uint32')\n for i, word in enumerate(sents.split(' ')):\n # print('word: ', word)\n # print('src_wtoi: ', src_wtoi)\n if word in src_wtoi:\n if i < max_length:\n sent_lsit[i] = (src_wtoi[word])\n else:\n continue\n # print('sent_insts_len:', len(sent_insts))\n # sent_lsit = np.array(sent_lsit)\n first.append(sent_lsit)\n # print('first_encoder: ', first[0])\n # print('first_len: ', len(first[0]))\n\n elif j == 1:\n sent_lsit = np.zeros((41), dtype='uint32')\n for i, word in enumerate(sents.split(' ')):\n # print('word: ', word)\n # print('src_wtoi: ', src_wtoi)\n if word in src_wtoi:\n if i < max_length:\n sent_lsit[i] = (src_wtoi[word])\n else:\n continue\n # print('sent_insts_len:', len(sent_insts))\n # sent_lsit = np.array(sent_lsit)\n second.append(sent_lsit)\n # print('second_encoder: ', second[0])\n # print('second_len: ', len(second[0]))\n elif j == 2:\n sent_lsit = np.zeros((42), dtype='uint32')\n for i, word in enumerate(sents.split(' ')):\n # print('word: ', word)\n # print('src_wtoi: ', src_wtoi)\n if word in src_wtoi:\n if i < max_length:\n sent_lsit[i] = (src_wtoi[word])\n else:\n continue\n # print('sent_insts_len:', len(sent_insts))\n sent_lsit = np.array(sent_lsit)\n third.append(sent_lsit)\n # print('third_encoder: ', third[0])\n # print('third_len: ', len(third[0]))\n else:\n sent_lsit = np.zeros((43), dtype='uint32')\n for i, word in enumerate(sents.split(' ')):\n # print('word: ', word)\n # print('src_wtoi: ', src_wtoi)\n if word in src_wtoi:\n if i < max_length:\n sent_lsit[i] = (src_wtoi[word])\n else:\n continue\n # print('sent_insts_len:', len(sent_insts))\n # sent_lsit = np.array(sent_lsit)\n four.append(sent_lsit)\n # print('four_encoder: ', four[0])\n # print('four_len: ', len(four[0]))\n\n\n # print('first: ', first)\n return first, second, third, four\n\n\ndef encode_story_last(storys, params, wtoi):\n # print(\"*\"*50)\n\n max_length = 40\n N = len(storys)\n M = len(storys)\n # print('M', M)\n\n label_arrays = []\n label_start_ix = np.zeros(N, dtype='uint32')\n label_end_ix = np.zeros(N, dtype='uint32')\n label_length = np.zeros(M, dtype='uint32')\n story_counter = 0\n counter = 1\n\n for i, story in enumerate(storys):\n # print('#'*50)\n\n n = 1\n Li = np.zeros((n, max_length), dtype='uint32')\n for j, s in enumerate(story['story_end']):\n # print('s', s)\n label_length[story_counter] = min(max_length, len(s))\n story_counter += 1\n for k, w in enumerate(s):\n # print('w_last ', w)\n if k < max_length:\n Li[j, k] = wtoi[w]\n\n\n label_arrays.append(Li)\n # print('label_arrays: ', label_arrays)\n label_start_ix[i] = counter\n label_end_ix[i] = counter + n - 1\n\n counter += n\n\n L = np.concatenate(label_arrays, axis=0)\n # print(\"%\"*50)\n # print('type_L: ', type(L))\n # print('M: ', M)\n # print('L.shape[0]: ', L.shape[0])\n assert L.shape[0] == M, 'length don\\'t match that\\'s weird'\n assert np.all(label_length > 0), 'error: some caption had no words?'\n\n # print('encoded story to array of size', L.shape)\n return L, label_start_ix, label_end_ix, label_length\n\ndef relation_to_adj_matrix(relation, sent):\n\n # depend = storys['sent_depen']\n\n head = head_to_tree(relation)\n\n if sent == 'sent1':\n adj_mat = tree_to_adj(40, head, sent)\n if sent == 'sent2':\n adj_mat = tree_to_adj(41, head, sent)\n if sent == 'sent3':\n adj_mat = tree_to_adj(42, head, sent)\n if sent == 'sent4':\n adj_mat = tree_to_adj(43, head, sent)\n\n return adj_mat\n\ndef adj_matrix(storys):\n\n adj1, adj2, adj3, adj4 = [], [], [], []\n\n for i, story in enumerate(storys):\n # print('%'*50)\n\n depend = story['sent_depen']\n # print('depend_0: ', depend[0])\n\n sent1 = depend[0]\n sent2 = depend[1]\n sent3 = depend[2]\n sent4 = depend[3]\n\n # print('sent1: ', sent1)\n adj1.append(relation_to_adj_matrix(sent1, 'sent1'))\n # print('adj1: ', len(adj1))\n adj2.append(relation_to_adj_matrix(sent2, 'sent2'))\n adj3.append(relation_to_adj_matrix(sent3, 'sent3'))\n adj4.append(relation_to_adj_matrix(sent4, 'sent4'))\n\n return adj1, adj2, adj3, adj4\n\ndef main(params):\n file = open(params['input_json'], 'r')\n data = json.load(file)\n anno = data\n print(len(data))\n print(anno[1])\n story = story_pro(anno, params)\n file.close()\n # file = open('story5.json', 'r')\n # story = json.load(file)\n # file.close()\n\n vocab = build_vocab(story, params)\n itow = {i: w for i, w in enumerate(vocab)}\n wtoi = {w: i for i, w in enumerate(vocab)}\n\n src_vocab = build_src_vocab(story, params)\n src_itow = {i: w for i, w in enumerate(src_vocab)}\n src_wtoi = {w: i for i, w in enumerate(src_vocab)}\n\n first, second, third, four = encode_story_four(story, params, src_wtoi)\n # print('first_len: ', len(first))\n f_fe = h5py.File(params['output_h5_fe'] + '_label1.h5', 'w')\n f_fe.create_dataset('sent1', dtype='uint32', data=first)\n\n f_fe.create_dataset('sent2', dtype='uint32', data=second)\n f_fe.create_dataset('sent3', dtype='uint32', data=third)\n f_fe.create_dataset('sent4', dtype='uint32', data=four)\n f_fe.close()\n print('Down f_fe')\n\n adj1, adj2, adj3, adj4 = adj_matrix(story)\n # # print('adj1_len: ', len(adj1))\n #\n f_adj = h5py.File(params['output_h5_adj'] + '_label1.h5', 'w')\n f_adj.create_dataset('adj1', dtype='uint32', data=adj1)\n f_adj.create_dataset('adj2', dtype='uint32', data=adj2)\n f_adj.create_dataset('adj3', dtype='uint32', data=adj3)\n f_adj.create_dataset('adj4', dtype='uint32', data=adj4)\n f_adj.close()\n print('Down f_adj')\n\n\n\n L, label_start_ix, label_end_ix, label_length = encode_story_last(story, params, wtoi)\n # print('L: ', L)\n\n\n # print('first_len: ', len(first))\n print('L_len:', len(L))\n # N = len(anno)\n f_lb = h5py.File(params['output_h5']+'_label1.h5', 'w')\n f_lb.create_dataset('labels', dtype='uint32', data=L)\n f_lb.create_dataset('label_start_ix', dtype='uint32', data=label_start_ix)\n f_lb.create_dataset('label_end_ix', dtype='uint32', data=label_end_ix)\n f_lb.create_dataset('label_length', dtype='uint32', data=label_length)\n f_lb.close()\n print('Down f_lb')\n\n story_four=[]\n for i, imgs in enumerate(story):\n story_four.append(imgs['stories_four'])\n with open(params['output_story_four'], 'w') as f_four:\n json.dump(story_four, f_four)\n f_four.close()\n print('Down f_four')\n\n out = {}\n out['src_word_to_ix'] = src_wtoi\n out['src_ix_to_word'] = src_itow\n out['tgt_word_to_ix'] = wtoi\n out['tgt_ix_to_word'] = itow\n\n out['images'] = []\n for i, img in enumerate(story):\n jimg = {}\n jimg['split'] = img['split']\n jimg['id'] = img['last_img_id']\n jimg['story_id'] = img['story_id']\n jimg['story_end'] = img['stories_last']\n # jimg['story_four'] = img['stories_four']\n # jimg['sent_rep'] = img['sent_rep']\n # jimg['sent_depen'] = img['sent_depen']\n out['images'].append(jimg)\n\n with open(params['output_json'], 'w') as ff:\n json.dump(out, ff)\n ff.close()\n\n # json.dump(out, open(params['output_json'], 'w'))\n print('wrote', params['output_json'])\n file.close()\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--input_json', default='annotation.json', help='')\n parser.add_argument('--output_json', default='data_res10.json', help='')\n parser.add_argument('--output_h5', default='data_tgt10', help='')\n parser.add_argument('--output_story_four', default='data_four10.json', help='')\n parser.add_argument('--output_h5_fe', default='data_src10', help='')\n parser.add_argument('--output_h5_adj', default='data_adj10', help='')\n parser.add_argument('--image_root', default='/home/chuan/HC/AREL-master', help='')\n parser.add_argument('--image_features', default='feat_num.json', help='')\n\n parser.add_argument('--max_length', default=40, type=int, help='')\n parser.add_argument('--word_count_threshold', default=0, type=int, help='')\n parser.add_argument('--word_count_threshold_test', default=1, type=int, help='')\n\n args = parser.parse_args()\n params = vars(args)\n\n main(params)\n\n# nlp.close()","sub_path":"data/pro_label.py","file_name":"pro_label.py","file_ext":"py","file_size_in_byte":22437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"177928643","text":"import os\nimport subprocess\nimport os\nimport shutil\n\n__here__ = os.path.dirname(os.path.abspath(__file__))\n\n\ndef test_apply_classifier(tmpdir):\n\n os.chdir(tmpdir.strpath)\n data_path = os.path.join(__here__, \"test_data.txt\")\n shutil.copy(data_path, tmpdir.strpath)\n stdout = subprocess.check_output(\"pyprophet test_data.txt\", shell=True,\n stderr=subprocess.STDOUT)\n\n # collect m score stats\n m_score_stat = [l for l in stdout.split(\"\\n\") if \"mean m_score\" in l]\n assert len(m_score_stat) == 1\n\n # split away log time etc:\n __, __, interesting_m_score_output = m_score_stat[0].partition(\"mean m_score\")\n\n # collect s value stats\n s_value_stat = [l for l in stdout.split(\"\\n\") if \"mean s_value\" in l]\n assert len(s_value_stat) == 1\n\n # split away log time etc:\n __, __, interesting_s_value_output = s_value_stat[0].partition(\"mean s_value\")\n\n stdout = subprocess.check_output(\n \"pyprophet test_data.txt --apply_scorer=test_data_scorer.bin --target.overwrite\",\n shell=True,\n stderr=subprocess.STDOUT)\n\n # collect m score stats\n m_score_stat = [l for l in stdout.split(\"\\n\") if \"mean m_score\" in l]\n assert len(m_score_stat) == 1\n\n # split away log time etc:\n __, __, interesting_m_score_output2 = m_score_stat[0].partition(\"mean m_score\")\n\n # collect s value stats\n s_value_stat = [l for l in stdout.split(\"\\n\") if \"mean s_value\" in l]\n assert len(s_value_stat) == 1\n\n # split away log time etc:\n __, __, interesting_s_value_output2 = s_value_stat[0].partition(\"mean s_value\")\n\n assert interesting_m_score_output == interesting_m_score_output2\n assert interesting_s_value_output == interesting_s_value_output2\n\n\nif __name__ == \"__main__\":\n pass\n\n","sub_path":"tests/test_apply_classifier.py","file_name":"test_apply_classifier.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"455139614","text":"from flask import Flask, request, flash, jsonify, session, make_response\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\nimport pymysql\n\n\n\n# Flask Instance, Database connection Engine and some vars.\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:BHU*nji9@192.168.0.11/validator'\ndb = SQLAlchemy(app)\ntransactionAmount = 0\n\n\n\n\n\n################################ Database Tables ################################\n\n\n#Implements an ORM Object called merchant that contains values: Transaction Amount, Blacklisted or not and his name.\nclass merchant(db.Model):\n __tablename__ = 'merchant'\n id = db.Column('id', db.Integer, primary_key=True)\n name = db.Column('name', db.Unicode)\n isBlakcListed = db.Column('isBlackListed', db.Boolean)\n transactionAmount = db.Column('transactionAmount', db.Integer)\n\n def __init__(self, id, name, isBlakcListed, transactionAmount):\n self.id = id\n self.name = name\n self.isBlakcListed = isBlakcListed\n self.transactionAmount = transactionAmount\n\n\n\n############################## //Database Tables// ##############################\n\n\n#Function to validate transaction using [\"Transaction Amount\", \"Last All Transactions Value\", \"Limit\"] values. (1)\ndef funcValidateTransaction(amount,limit,lastAllTransactionsAmount):\n return ((int(amount)) + int(lastAllTransactionsAmount)) > int(limit)\n\n#Function to check if card is blocked (2)\ndef funcCardIsActive(cardIsActive):\n return cardIsActive == \"False\"\n\n#Check if first transaction is above of 90% of the limit (3)\ndef funcCheckFirstTransaction(amount, limit, transactionAmount):\n return (int(amount) >= ((int(limit) * 90) / 100)) and (transactionAmount == 1)\n\n\n#Check if the same merchant has more than 10 transactions (4)\ndef funcMoreThanTen(merchantName, totalTransactionsUser):\n aboveLimitTransaction = merchant.query.filter_by(name=merchantName)\n for transaction in aboveLimitTransaction:\n totalTransactions = transaction.transactionAmount\n return totalTransactionsUser > 10\n\n#Check if transaction amount value was negative\ndef funcCheckIfNegative(amount):\n return int(amount) < 0\n\n#Check if Account is whitelisted.\ndef funcCheckWhitelisted(isWhitelisted):\n return isWhitelisted == \"False\"\n\n\n\n@app.route('/api/v1.0/validate/transaction', methods=['POST'])\ndef validator():\n\n\n global transactionAmount\n transactionAmount += 1\n lastAllTransactionsAmount = 0\n if request.method == 'POST':\n\n dataFromJson = request.data\n inputData = json.loads(dataFromJson)\n\n #Populate Variables with key Account values at JSON data\n for accountObjects in inputData['Account']:\n cardIsActive = accountObjects['cardIsActive']\n limit = accountObjects['limit']\n blacklist = accountObjects['blacklist']\n isWhitelisted = accountObjects['isWhitelisted']\n\n #Populate Variables with key Transaction values at JSON data\n for transactionObjects in inputData['Transaction']:\n merchantName = transactionObjects['merchant']\n amount = transactionObjects['amount']\n transactionTime = transactionObjects['time']\n\n #Populate Variables with key LastTransactions values at JSON data\n for lastTransactionsObject in inputData['LastTransactions']:\n lastTransactionsValues = lastTransactionsObject['Transactions']\n for i in range(0, len(lastTransactionsValues)):\n lastAllTransactionsAmount += lastTransactionsValues[i]\n\n nameInDB = []\n #If merchant name doesn't exist in DB, insert a new merchant.\n objectMerchant = merchant.query.all()\n for name in objectMerchant:\n nameInDB.append(name.name)\n\n if merchantName in nameInDB:\n updateTransactionAmount = merchant.query.filter_by(name=merchantName).first()\n updateTransactionAmount.transactionAmount += 1\n db.session.commit()\n totalTransactionsUser = updateTransactionAmount.transactionAmount\n else:\n newMerchant = merchant(None, merchantName, False, 1)\n db.session.add(newMerchant)\n db.session.commit()\n updateTransactionAmount = merchant.query.filter_by(name=merchantName).first()\n totalTransactionsUser = updateTransactionAmount.transactionAmount\n\n\n############ Running Functions to check the results and return a HTTP response based on JSON Post ############\n\n if funcCheckWhitelisted(isWhitelisted):\n return jsonify({'Invalid Transaction': 'The card is not in whitelist'}), 400\n\n if funcCardIsActive(cardIsActive):\n return jsonify({'Invalid Transaction' : 'Card is Blocked'}),400\n\n if funcValidateTransaction(amount, limit, lastAllTransactionsAmount):\n return jsonify({'Invalid Transaction' : 'The transaction value is greater than the limit.'}), 400\n\n if funcCheckFirstTransaction(amount, limit, transactionAmount):\n return jsonify({'Invalid Transaction' : 'The first transaction can\\'t be greater than 90% of the limit.'}), 400\n\n if funcMoreThanTen(merchantName, totalTransactionsUser):\n return jsonify({'Invalid Transaction': 'The same merchant has more than 10 transactions.'}), 400\n\n if funcCheckIfNegative(amount):\n return jsonify({'Invalid Transaction' : 'The transaction amount can\\'t be negative'}), 400\n\n return jsonify({'Transaction Status:' : 'Authorized'},\n {'Available Limit:' : (limit-lastAllTransactionsAmount) - amount})\n\n############ // Running Functions to check the results and return a HTTP response based on JSON Post // ############\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)\n\n","sub_path":"FlaskAPP/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"571209825","text":"import glob#import glob lib\r\nfrom datetime import datetime\r\n\r\nfilenames = glob.glob(\"*.txt\")# create a variable named filenames and save the files who have .txt...\r\n\r\nwith open(datetime.now().strftime(\"%Y-%m-%d-%H\")+\".txt\" , \"w\") as file:#create a new file which names as the \r\n #current time stamp with formatted and asign the value in the \"file\" variable..\r\n\r\n for filename in filenames:# start loop in which the value of all .txt files iterates \r\n with open(filename , \"r\")as content:#creates a new variable \"content\" which is readable \r\n # file that only read the values of iterables..\r\n file.write(content.read() + \"\\n\")#uses write() to write the ","sub_path":"basics_/file processing/merge files.py","file_name":"merge files.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207886258","text":"import pygame, sys\nimport random\nimport threading\nimport time\n\nWhite = (255,255,255)\nwid = 512\nhei = 512\n\npygame.init()\ndisplay = pygame.display.set_mode((wid, hei))\ndisplay.fill(White)\npygame.display.set_caption(\"how_to_move\")\n\nclass Charactor:\n def __init__(self,inputx,inputy):\n self.imagename1=\"C:/Users/user/Desktop/pyproimage/image\"+(str)(random.randrange(0,10)+1)+\".png\"\n self.frog1 = pygame.image.load(self.imagename1) # 사진파일\n self.frog1 = pygame.transform.scale(self.frog1, (100,100))\n self.x1 = inputx\n self.y1 = inputy\n self.imagename2 = \"C:/Users/user/Desktop/pyproimage/image\" + (str)(random.randrange(0, 10) + 1) + \".png\"\n self.frog2 = pygame.image.load(self.imagename2) # 사진파일\n self.frog2 = pygame.transform.scale(self.frog2, (100, 100))\n self.x2 = inputx+50\n self.y2 = inputy+50\n\n def printloop(self):\n while True:\n '''\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n '''\n display.blit(self.frog1, (self.x1, self.y1))\n display.blit(self.frog2, (self.x2, self.y2))\n pygame.display.update()\n time.sleep(0.001)\n display.blit(self.frog1, (self.x1, self.y1))\n display.blit(self.frog2, (self.x2, self.y2))\n\n def print_char(self):\n thread_char = threading.Thread(target=self.printloop, args=())\n thread_char.start()\n\nRanger=Charactor(216,216)\nRanger.print_char()\n\nRanger=Charactor(400,400)\nRanger.print_char()\n\nwallpaper=\"C:/Users/user/Desktop/pyproimage/image\"+(str)(random.randrange(0,10)+1)+\".png\"\nfrog2 = pygame.image.load(wallpaper) # 사진파일\nfrog2 = pygame.transform.scale(frog2, (100,100))\nx2 = 0\ny2 = 0\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n pygame.display.update()\n display.blit(frog2, (x2, y2))\n\n\n# https://blog.naver.com/rsj0908/221007425974 에서 가져옴","sub_path":"stackimage.py","file_name":"stackimage.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"409530117","text":"\n\n#calss header\nclass _LANDLORD():\n\tdef __init__(self,): \n\t\tself.name = \"LANDLORD\"\n\t\tself.definitions = [u'a person or organization that owns a building or an area of land and is paid by other people for the use of it: ', u'a man who is in charge of a pub or bar']\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/_landlord.py","file_name":"_landlord.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"95912092","text":"import io\nimport base64\nfrom PIL import Image\nimport numpy as np\nimport cv2\nimport math\n\n\ndef str64_to_cv2(str64):\n imgdata = base64.b64decode(str64)\n img = Image.open(io.BytesIO(imgdata))\n return cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)\n\n\ndef to_cv2(image):\n if isinstance(image, np.ndarray):\n return image\n if image.mode == 'RGB':\n return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)\n if image.mode == 'RGBA':\n return cv2.cvtColor(np.array(image), cv2.COLOR_RGBA2BGR)\n\n\ndef rgba_split(pil_image):\n return cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGBA2BGR), \\\n np.array(pil_image)[:, :, 3]\n\n\ndef cv2_paste(obj, bg, mask, upper_left, inplace=False):\n (x1, y1) = upper_left\n y2 = y1 + obj.shape[0]\n x2 = x1 + obj.shape[1]\n\n alpha_s = mask / 255.0\n alpha_l = 1.0 - alpha_s\n\n if not inplace:\n bg = bg.copy()\n\n if len(bg.shape) == 3: # RGB-like\n for c in range(0, 3):\n bg[y1:y2, x1:x2, c] = (alpha_s * obj[:, :, c] + alpha_l * bg[y1:y2, x1:x2, c])\n elif len(bg.shape) == 2: # Single channel\n bg[y1:y2, x1:x2] = (alpha_s * obj[:, :] + alpha_l * bg[y1:y2, x1:x2])\n\n return bg\n\n\ndef blend(src_image, dst_image, upper_left, blending_type=\"normal\", smooth=True):\n src, src_mask = rgba_split(src_image)\n dst = to_cv2(dst_image)\n\n center = (upper_left[0] + src.shape[1] / 2, upper_left[1] + src.shape[0] / 2)\n\n # Clone seamlessly.\n if blending_type == \"mixed\":\n option = cv2.MIXED_CLONE \n elif blending_type == \"normal\":\n option = cv2.NORMAL_CLONE\n elif blending_type == \"monochrome\":\n option = cv2.MONOCHROME_TRANSFER\n else: \n raise ValueError(\"Unexpected `blending_type` parameter value: {}\".format(blending_type))\n # cv2.NORMAL_CLONE -- without bg\n # cv2.MIXED_CLONE -- with bg\n\n # clone_mask = 255 * np.ones(src_mask.shape[:2], src_mask.dtype)\n if smooth:\n dst = cv2.seamlessClone(src, dst, src_mask.copy(), center, option)\n \n kernel = np.ones((3, 3), np.uint8) \n src_mask = cv2.erode(src_mask, kernel)\n src_mask = cv2.GaussianBlur(src_mask, (3, 3), 1.0)\n\n dst = cv2_paste(src, dst, src_mask, upper_left, inplace=True)\n\n return dst\n\n\ndef paste_obj(bg_image, obj_image, new_size=None, upper_left=None, lower_middle=None, smooth=False):\n if (upper_left is None) == (lower_middle is None):\n raise ValueError(\"One of arguments `upper_left` and `lower_middle` shouldn't be None\")\n\n bg_image = bg_image.copy()\n if new_size is not None:\n obj_image = obj_image.resize(new_size)\n\n if upper_left is None:\n upper_left = (int(lower_middle[0] - float(obj_image.size[0]) / 2), \\\n int(lower_middle[1] - obj_image.size[1]))\n\n return blend(obj_image, bg_image, upper_left, smooth=smooth)\n\n\n# Source: https://github.com/PPPW/poisson-image-editing\nimport scipy.sparse\nfrom scipy.sparse.linalg import spsolve\n\ndef laplacian_matrix(n, m): \n mat_D = scipy.sparse.lil_matrix((m, m))\n mat_D.setdiag(-1, -1)\n mat_D.setdiag(4)\n mat_D.setdiag(-1, 1)\n \n mat_A = scipy.sparse.block_diag([mat_D] * n).tolil()\n \n mat_A.setdiag(-1, 1*m)\n mat_A.setdiag(-1, -1*m)\n \n return mat_A\n\n\ndef blend_alt(src_image, dst_image, upper_left):\n src, src_mask = rgba_split(src_image)\n dst = to_cv2(dst_image)\n src = cv2_paste(src, np.zeros(dst.shape, dst.dtype), src_mask, upper_left=upper_left)\n mask = cv2_paste(src_mask, np.zeros(dst.shape[:2], dst.dtype), src_mask, upper_left=upper_left)\n\n print(src.shape)\n\n y_max, x_max = dst.shape[:-1]\n y_min, x_min = 0, 0\n x_range = x_max - x_min\n y_range = y_max - y_min\n\n mat_A = laplacian_matrix(y_range, x_range)\n laplacian = mat_A.tocsc()\n\n for y in range(1, y_range - 1):\n for x in range(1, x_range - 1):\n if mask[y, x] == 0:\n k = x + y * x_range\n mat_A[k, k] = 1\n mat_A[k, k + 1] = 0\n mat_A[k, k - 1] = 0\n mat_A[k, k + x_range] = 0\n mat_A[k, k - x_range] = 0\n mat_A = mat_A.tocsc()\n\n mask_flat = mask.flatten() \n for channel in range(src.shape[2]):\n source_flat = src[y_min:y_max, x_min:x_max, channel].flatten()\n target_flat = dst[y_min:y_max, x_min:x_max, channel].flatten() \n\n # inside the mask:\n # \\Delta f = div v = \\Delta g \n alpha = 1\n mat_b = laplacian.dot(source_flat)*alpha\n\n # outside the mask:\n # f = t\n mat_b[mask_flat == 0] = target_flat[mask_flat == 0]\n \n x = spsolve(mat_A, mat_b) \n x = x.reshape((y_range, x_range))\n x[x > 255] = 255\n x[x < 0] = 0\n x = x.astype('uint8')\n \n dst[y_min:y_max, x_min:x_max, channel] = x\n\n return dst\n\n\n# obj_img = Image.open(\"./input/obj/cat.png\")\n# bg_img = Image.open(\"./input/bg/field.jpg\")\n\n# img = blend(obj_img, bg_img, (0, 0), blending_type=\"mixed\")\n\n# cv2.imwrite('./output/test/tmp.jpg', img)","sub_path":"server/api/graphics.py","file_name":"graphics.py","file_ext":"py","file_size_in_byte":5059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"485858596","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2019‎年‎11‎月‎6‎日,‏‎14:54:42\n此模块为前置规范管理模块,用于管理前置规范,并生成出主规范管理模块所需要的参数。\n@author: hejieheng\n\"\"\"\nimport json\nimport os\nimport copy\nimport math\nfrom standard.pre_cal_space import PreCalSpace\nfrom standard.cal_overlop import cal_overlop\n\n\nclass PreManagement:\n def __init__(self, updata_flag, rule_name):\n # 是否需要更新json的标志位 \n self.updata_flag = updata_flag\n # 需要读取的规范的城市名\n self.rule_name = rule_name\n # self.updateConfiguration()\n self.configurationRead()\n \n\n def updateConfiguration(self):\n if self.updata_flag == True:\n pass\n\n def configurationRead(self):\n with open(\"standard/Excel/\"+self.rule_name+\"pre.json\",'r',encoding='UTF-8') as load_f:\n # 前置规范读取的json数据\n self.pre_data = json.load(load_f)\n\n # def shadowAnalysis(self):\n\n def attributeJudgment(self,build_inf1,build_inf2):\n result = {}\n attribute_list = [\"居住\", \"住宅\"]\n notatrr_list = [\"非\", \"老年人\"]\n for i in range(len(list(self.pre_data[\"建筑属性\"].keys()))):\n for attribute in attribute_list:\n if attribute in list(self.pre_data[\"建筑属性\"].keys())[i]:\n key_flag = True\n for notatrr in notatrr_list:\n if notatrr in list(self.pre_data[\"建筑属性\"].keys())[i]:\n key_flag = False\n break\n if key_flag == True:\n key = list(self.pre_data[\"建筑属性\"].keys())[i]\n\n # 建筑属性——————————————————————————————————————————————————————————————————————————\n # 暂时只提取跟居住相关的属性放入建筑属性,后续修改成放入所有符合的属性\n result[\"建筑属性-建筑一\"] = []\n build_1_attribute = \"非\" + key\n for i in range(len(build_inf1[\"type\"])):\n if build_inf1[\"type\"][i] in self.pre_data[\"建筑属性\"][key]:\n result[\"建筑属性-建筑一\"].append(key)\n build_1_attribute = key\n\n result[\"建筑属性-建筑二\"] = []\n build_2_attribute = \"非\" + key\n for i in range(len(build_inf2[\"type\"])):\n if build_inf2[\"type\"][i] in self.pre_data[\"建筑属性\"][key]:\n result[\"建筑属性-建筑二\"].append(key)\n build_2_attribute = key\n # 添加“所有类型建筑”\n for allhouse in list(self.pre_data[\"建筑属性\"].keys()):\n if self.pre_data[\"建筑属性\"][allhouse] == [\"所有类型建筑\"]:\n result[\"建筑属性-建筑一\"].append(allhouse)\n result[\"建筑属性-建筑二\"].append(allhouse)\n\n # 高度分类特性——————————————————————————————��———————————————————————————————————————————\n # 建筑一\n height = build_inf1[\"storey_height\"] * build_inf1[\"layers\"]\n floor = build_inf1[\"layers\"]\n if build_1_attribute == key:\n H_class = copy.deepcopy(self.pre_data[\"居住建筑高度分类特性\"])\n else:\n H_class = copy.deepcopy(self.pre_data[\"非居住建筑高度分类特性\"])\n result[\"高度分类特性-建筑一\"] = []\n for i in range(len(list(H_class.values()))):\n if list(H_class.values())[i] != \"\":\n if eval(list(H_class.values())[i]):\n result[\"高度分类特性-建筑一\"].append((list(H_class.keys()))[i])\n # 建筑二\n height = build_inf2[\"storey_height\"] * build_inf2[\"layers\"]\n floor = build_inf2[\"layers\"]\n if build_2_attribute == key:\n H_class = copy.deepcopy(self.pre_data[\"居住建筑高度分类特性\"])\n else:\n H_class = copy.deepcopy(self.pre_data[\"非居住建筑高度分类特性\"])\n result[\"高度分类特性-建筑二\"] = []\n for i in range(len(list(H_class.values()))):\n if list(H_class.values())[i] != \"\":\n if eval(list(H_class.values())[i]):\n result[\"高度分类特性-建筑二\"].append((list(H_class.keys()))[i])\n\n # 建筑朝向——————————————————————————————————————————————————————————————————————————\n A_class = copy.deepcopy(self.pre_data[\"建筑朝向\"])\n # 建筑一\n result[\"建筑朝向-建筑一\"] = []\n angle = (build_inf1[\"main_direction\"] + 270) % 360\n for i in range(len(list(A_class.values()))):\n if list(A_class.values())[i] != \"\":\n if eval(list(A_class.values())[i]):\n result[\"建筑朝向-建筑一\"].append((list(A_class.keys()))[(list(A_class.values())).index(list(A_class.values())[i])])\n # 建筑二\n result[\"建筑朝向-建筑二\"] = []\n angle = (build_inf2[\"main_direction\"] + 270) % 360\n for i in range(len(list(A_class.values()))):\n if list(A_class.values())[i] != \"\":\n if eval(list(A_class.values())[i]):\n result[\"建筑朝向-建筑二\"].append((list(A_class.keys()))[(list(A_class.values())).index(list(A_class.values())[i])])\n\n # 建筑位置——————————————————————————————————————————————————————————————————————————\n # 建筑一外轮廓旋转(顺时针)\n wall_b1 = copy.deepcopy(build_inf1[\"walls\"])\n for i in range(len(wall_b1)//2):\n x = copy.deepcopy(wall_b1[2*i])\n y = copy.deepcopy(wall_b1[2*i+1])\n wall_b1[2*i] = x*math.cos(math.radians(build_inf1[\"main_direction\"])) + y*math.sin(math.radians(build_inf1[\"main_direction\"])) + build_inf1[\"coordinate\"][0]\n wall_b1[2*i+1] = y*math.cos(math.radians(build_inf1[\"main_direction\"])) - x*math.sin(math.radians(build_inf1[\"main_direction\"])) + build_inf1[\"coordinate\"][1]\n # 建筑二外轮廓旋转(顺时针)\n wall_b2 = copy.deepcopy(build_inf2[\"walls\"])\n for i in range(len(wall_b2)//2):\n x = copy.deepcopy(wall_b2[2*i])\n y = copy.deepcopy(wall_b2[2*i+1])\n wall_b2[2*i] = x*math.cos(math.radians(build_inf2[\"main_direction\"])) + y*math.sin(math.radians(build_inf2[\"main_direction\"])) + build_inf2[\"coordinate\"][0]\n wall_b2[2*i+1] = y*math.cos(math.radians(build_inf2[\"main_direction\"])) - x*math.sin(math.radians(build_inf2[\"main_direction\"])) + build_inf2[\"coordinate\"][1]\n # 测东西向是否重叠\n # 依照设计师逻辑,除东西向重叠为东西摆放,其他可当南北摆放\n overlap = PreCalSpace().pre_cal_space(wall_b1, wall_b2, 90, [0,0], sign = \"平行\") #怡珺\n if overlap == True:\n if build_inf1[\"coordinate\"][0] > build_inf2[\"coordinate\"][0]:\n result[\"建筑位置-建筑一\"] = \"东\"\n result[\"建筑位置-建筑二\"] = \"西\"\n else:\n result[\"建筑位置-建筑一\"] = \"西\"\n result[\"建筑位置-建筑二\"] = \"东\"\n else:\n if build_inf1[\"coordinate\"][1] < build_inf2[\"coordinate\"][1]:\n result[\"建筑位置-建筑一\"] = \"北\"\n result[\"建筑位置-建筑二\"] = \"南\"\n else:\n result[\"建筑位置-建筑一\"] = \"南\"\n result[\"建筑位置-建筑二\"] = \"北\" \n \n # 区域类型—————���——————————————————————————————————————————————————————————————————————————————————\n region_class = copy.deepcopy(self.pre_data[\"区域类型\"])\n region = build_inf1[\"area\"]\n for i in range(len(list(region_class.values()))):\n if region == list(region_class.values())[i]:\n result[\"区域类型\"] = (list(region_class.keys()))[(list(region_class.values())).index(list(region_class.values())[i])]\n\n\n # 投影方式————————————————————————————————————————————————————————————————————————————————————————\n\n # 布置方式————————————————————————————————————————————————————————————————————————————————————————\n # 投影方式——1:垂直投影\n # 投影方式——2:北侧楼栋法线投影\n # 投影方式——3:北侧楼栋法线+垂直投影\n # 投影方式——4:南侧楼栋法线投影\n result[\"布置方式\"] = \"无适配布置方式\"\n if result[\"建筑位置-建筑一\"] == \"北\":\n # 若建筑一在北侧\n overlap = False\n if self.pre_data[\"投影方式\"][\"1\"] == \"Y\" or self.pre_data[\"投影方式\"][\"3\"] == \"Y\": # 北侧建筑投影\n overlap = PreCalSpace().pre_cal_space(wall_b1, wall_b2, -build_inf1[\"main_direction\"], [0,0], sign = \"平行\") #怡珺\n if overlap == False and self.pre_data[\"投影方式\"][\"2\"] == \"Y\" or self.pre_data[\"投影方式\"][\"3\"] == \"Y\": # 垂直投影\n overlap = PreCalSpace().pre_cal_space(wall_b1, wall_b2, 0, [0,0], sign = \"平行\") #怡珺\n if overlap == False and self.pre_data[\"投影方式\"][\"4\"] == \"Y\": # 南侧建筑法线投影\n overlap = PreCalSpace().pre_cal_space(wall_b1, wall_b2, -build_inf2[\"main_direction\"], [0,0], sign = \"平行\") #怡珺\n if overlap != False:\n inc_angle = abs(build_inf1[\"main_direction\"]-build_inf2[\"main_direction\"])\n if self.pre_data[\"布置方式\"][\"平行\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"平行\"]):\n result[\"布置方式\"] = \"平行\"\n if self.pre_data[\"布置方式\"][\"垂直\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"垂直\"]):\n result[\"布置方式\"] = \"垂直\"\n if self.pre_data[\"布置方式\"][\"非平行非垂直\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"非平行非垂直\"]):\n result[\"布置方式\"] = \"非平行非垂直\" \n else:\n result[\"布置方式\"] = \"山墙相对\"\n if result[\"建筑位置-建筑二\"] == \"北\":\n # 若建筑二在北侧\n overlap = False\n if self.pre_data[\"投影方式\"][\"1\"] == \"Y\" or self.pre_data[\"投影方式\"][\"3\"] == \"Y\": # 北侧建筑投影\n overlap = PreCalSpace().pre_cal_space(wall_b1, wall_b2, -build_inf2[\"main_direction\"], [0,0], sign = \"平行\") #怡珺\n if overlap == False and self.pre_data[\"投影方式\"][\"2\"] == \"Y\" or self.pre_data[\"投影方式\"][\"3\"] == \"Y\": # 垂直投影\n overlap = PreCalSpace().pre_cal_space(wall_b1, wall_b2, 0, [0,0], sign = \"平行\") #怡珺\n if overlap == False and self.pre_data[\"投影方式\"][\"4\"] == \"Y\": # 南侧建筑法线投影\n overlap = PreCalSpace().pre_cal_space(wall_b1, wall_b2, -build_inf1[\"main_direction\"], [0,0], sign = \"平行\") #怡珺\n if overlap != False:\n inc_angle = abs(build_inf1[\"main_direction\"]-build_inf2[\"main_direction\"])\n if self.pre_data[\"布置方式\"][\"平行\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"平行\"]):\n result[\"布置方式\"] = \"平行\"\n if self.pre_data[\"布置方式\"][\"垂直\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"垂直\"]):\n result[\"布置方式\"] = \"垂直\"\n if self.pre_data[\"布置方式\"][\"非平行非垂直\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"非平行非垂直\"]):\n result[\"布置方式\"] = \"非平行非垂直\" \n else:\n result[\"布置方式\"] = \"山墙相对\"\n if result[\"建筑位置-建筑一\"] == \"东\" or result[\"建筑位置-建筑一\"] == \"西\":\n overlap = False\n overlap = PreCalSpace().pre_cal_space(wall_b1, wall_b2, -build_inf1[\"main_direction\"], [0,0], sign = \"平行\") #怡珺\n if overlap != False:\n inc_angle = abs(build_inf1[\"main_direction\"]-build_inf2[\"main_direction\"])\n if self.pre_data[\"布置方式\"][\"平行\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"平行\"]):\n result[\"布置方式\"] = \"平行\"\n if self.pre_data[\"布置方式\"][\"垂直\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"垂直\"]):\n result[\"布置方式\"] = \"垂直\"\n if self.pre_data[\"布置方式\"][\"非平行非垂直\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"非平行非垂直\"]):\n result[\"布置方式\"] = \"非平行非垂直\" \n else:\n result[\"布置方式\"] = \"山墙相对\"\n if result[\"布置方式\"] == \"无适配布置方式\":\n overlap = PreCalSpace().pre_cal_space(wall_b1, wall_b2, -build_inf2[\"main_direction\"], [0,0], sign = \"平行\") #怡珺\n if overlap == True:\n inc_angle = abs(build_inf1[\"main_direction\"]-build_inf2[\"main_direction\"])\n if self.pre_data[\"布置方式\"][\"平行\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"平行\"]):\n result[\"布置方式\"] = \"平行\"\n if self.pre_data[\"布置方式\"][\"垂直\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"垂直\"]):\n result[\"布置方式\"] = \"垂直\"\n if self.pre_data[\"布置方式\"][\"非平行非垂直\"] != \"\":\n if eval(self.pre_data[\"布置方式\"][\"非平行非垂直\"]):\n result[\"布置方式\"] = \"非平行非垂直\" \n # 正向重叠长度————————————————————————————————————————————————————————————————————————————————————————\n result[\"正向重叠长度\"] = 0\n if self.pre_data[\"布置方式\"][\"正向无重叠\"] != '' and result[\"布置方式\"] == \"平行\":\n if self.pre_data[\"重叠方式\"][\"2\"] == \"Y\":\n length = cal_overlop(wall_b1, wall_b2, 0)\n if eval(self.pre_data[\"布置方式\"][\"正向无重叠\"]):\n result[\"布置方式\"] = \"正向无重叠\"\n result[\"正向重叠长度\"] = length\n else:\n if result[\"建筑位置-建筑一\"] == \"北\":\n if self.pre_data[\"重叠方式\"][\"1\"] == \"Y\":\n length = cal_overlop(wall_b1, wall_b2, -build_inf1[\"main_direction\"])\n if eval(self.pre_data[\"布置方式\"][\"正向无重叠\"]):\n result[\"布置方式\"] = \"正向无重叠\"\n result[\"正向重叠长度\"] = length\n if result[\"建筑位置-建筑二\"] == \"北\":\n if self.pre_data[\"重叠方式\"][\"1\"] == \"Y\":\n length = cal_overlop(wall_b1, wall_b2, -build_inf2[\"main_direction\"])\n if eval(self.pre_data[\"布置方式\"][\"正向无重叠\"]):\n result[\"布置方式\"] = \"正向无重叠\"\n result[\"正向重叠长度\"] = length \n # 建筑形态————————————————————————————————————————————————————————————————————————————————————————\n # 暂时先默认都是条式建筑,后续根据实际情况进行判断\n result[\"建筑形态-建筑一\"] = \"条式建筑\"\n result[\"建筑形态-建筑二\"] = \"条式建筑\"\n return result\n\nif __name__ == \"__main__\":\n PreMG = PreManagement(True)","sub_path":"multiagent-particle-envs-master/multiagent/standard/distance/PreMG.py","file_name":"PreMG.py","file_ext":"py","file_size_in_byte":17213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"396786744","text":"import logging\nimport os\nimport pathlib\nimport shutil\nimport tempfile\n\nTEST_DIR = tempfile.mkdtemp(prefix=\"cached_path_tests\")\n\n\nclass BaseTestClass:\n \"\"\"\n A custom testing class that disables some of the more verbose\n logging and that creates and destroys a temp directory as a test fixture.\n \"\"\"\n\n PROJECT_ROOT = (pathlib.Path(__file__).parent / \"..\").resolve()\n MODULE_ROOT = PROJECT_ROOT / \"cached_path\"\n TOOLS_ROOT = MODULE_ROOT / \"tools\"\n TESTS_ROOT = PROJECT_ROOT / \"tests\"\n FIXTURES_ROOT = PROJECT_ROOT / \"test_fixtures\"\n\n def setup_method(self):\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\", level=logging.DEBUG\n )\n # Disabling some of the more verbose logging statements that typically aren't very helpful\n # in tests.\n logging.getLogger(\"urllib3.connectionpool\").disabled = True\n\n self.TEST_DIR = pathlib.Path(TEST_DIR)\n\n os.makedirs(self.TEST_DIR, exist_ok=True)\n\n def teardown_method(self):\n shutil.rmtree(self.TEST_DIR)\n","sub_path":"cached_path/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"426459924","text":"import numpy as np\nimport sys\nfrom mpi4py import MPI\nimport schwimmbad \nimport itertools\nimport time\nimport pdb\n\ndef dummy_task(task):\n time.sleep(5)\n return None\n\nif __name__ == '__main__':\n # Test the time needed for communications (bcast, send, receive)\n\n config_str = sys.argv[1]\n print(config_str)\n comm = MPI.COMM_WORLD\n\n rank = comm.rank\n size = comm.size\n\n print('Comm size: %d' % size)\n\n if rank == 0:\n data = list(np.zeros((10000, 10000)))\n else:\n data = None\n\n t0 = time.time()\n data = comm.bcast(data)\n \n bcast_time = time.time() - t0\n\n print('Data broadcast time: %f' % bcast_time)\n comm.barrier()\n\n # Time sends from root to all other ranks\n if rank == 0:\n data2 = list(np.zeros((1000, 1000)))\n for i in range(1, size):\n t0 = time.time()\n comm.send(data2, dest=i, tag=i)\n print('Data send to rank %d time: %f' % (i, time.time() - t0))\n else:\n t0 = time.time()\n data = comm.recv(source=0, tag=rank)\n print('Rank %d took %f s to receive' % (rank, time.time() - t0))\n\n comm.barrier()\n\n\n # Arrange subcommunicators and test their internal communication times\n numproc = comm.Get_size()\n\n comm_splits = 4\n\n # Use array split to do comm.split\n\n # Take the root node and set it aside - this is what schwimmbad will use to coordinate\n # the other groups\n\n ranks = np.arange(numproc)\n split_ranks = np.array_split(ranks, comm_splits)\n # if rank == 0:\n # color = 0\n # else:\n color = [i for i in np.arange(comm_splits) if rank in split_ranks[i]][0]\n subcomm_roots = [split_ranks[i][0] for i in np.arange(comm_splits)]\n subcomm = comm.Split(color, rank)\n\n nchunks = comm_splits\n subrank = subcomm.rank\n numproc = subcomm.Get_size()\n\n # Create a group including the root of each subcomm (unused at the moment)\n global_group = comm.Get_group()\n root_group = MPI.Group.Incl(global_group, subcomm_roots)\n root_comm = comm.Create(root_group)\n\n # Broadcast data from root of each subcommunicator\n if subcomm.rank == 0:\n data = list(np.zeros((10000, 10000)))\n else:\n data = None\n\n t0 = time.time()\n data = subcomm.bcast(data)\n print('Color %d subcomm data broadcast time: %f' % (color, time.time() - t0))\n comm.barrier()\n\n # How long does it take for schwimmbad to do its stuff? Is this longer than the usual comm bcast operations?\n pool = schwimmbad.MPIPool(comm)\n\n task_dicts = [{'x' : np.random.random(size=(100,)), 'y' : np.random.random(size=(100,))} for i in range(2 * size)]\n\n pool.map(dummy_task, task_dicts)\n\n pool.close()\n \n\n","sub_path":"mpi_tests/comm_timing.py","file_name":"comm_timing.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"156407944","text":"# This file is part of the Reproducible Open Benchmarks for Data Analysis\n# Platform (ROB).\n#\n# Copyright (C) [2019-2020] NYU.\n#\n# ROB is free software; you can redistribute it and/or modify it under the\n# terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Collection of helper functions for handling web server requests.\"\"\"\n\nfrom flowserv.util import validate_doc\n\nimport robflask.error as err\n\n\ndef jsonbody(request, mandatory=None, optional=None):\n \"\"\"Get Json object from the body of an API request. Validates the object\n based on the given (optional) lists of mandatory and optional labels.\n\n Returns the JSON object (dictionary). Raises an error if an invalid request\n or body is given.\n\n Parameters\n ----------\n request: flask.request\n HTTP request\n mandatory: list(string)\n List of mandatory labels for the dictionary serialization\n optional: list(string), optional\n List of optional labels for the dictionary serialization\n\n Returns\n -------\n dict\n\n Raises\n ------\n robflask.error.InvalidRequest\n \"\"\"\n try:\n return validate_doc(\n request.json,\n mandatory=mandatory,\n optional=optional\n )\n except (AttributeError, TypeError, ValueError) as ex:\n raise err.InvalidRequestError(str(ex))\n","sub_path":"robflask/api/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"307923621","text":"#!/usr/bin/env python3\n\"\"\"\nFile Name : Problem010.py\nDate started : Unknown\nDate solved : Unknown\nRun Time : 0.10323 seconds\n\nThe sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n\nFind the sum of all the primes below two million.\n\n\"\"\"\n\nimport project_euler\nimport project_euler.primes\n\nPROBLEM_NUMBER = 10\nSOLVED = 1\n\n\ndef problem010(input_=None):\n return sum(project_euler.primes.rwh_primes(2000000))\n\n\ndef run():\n print(project_euler.print_timing(problem010))\n\n\nif __name__ == \"__main__\":\n run()\n\n","sub_path":"problems/Problem010.py","file_name":"Problem010.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"293691041","text":"__author__ = 'br'\n\n\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2014 Ben Russell\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\n\nclass docblock_lua:\n\tdocblocks = {}\n\tdocblocks_filenames = {}\n\n\tdef scan(self, target_filename, blob):\n\n\t\tlines = blob.split(\"\\n\")\n\n\t\tdoc_block_open = False\n\t\tdoc_line_counter = 0\n\n\t\tline_x = 1\n\n\t\ttmp_last_signature = \"\"\n\n\t\tfor line in lines:\n\n\t\t\t# Output raw function sig for debug..\n\t\t\tif( line.find(\"function\") >= 0 ):\n\t\t\t\t#print(line)\n\t\t\t\tpass\n\n\n\t\t\t# Scan for doc blocks.\n\t\t\tif( doc_block_open ):\n\t\t\t\tif( line.strip() == \"*/]]\" ):\n\t\t\t\t\tdoc_block_open = False\n\t\t\t\t\t#print(\"doc block closed\")\n\n\t\t\t\telse:\n\t\t\t\t\tif( doc_line_counter == 0 ):\n\t\t\t\t\t\t#first line of doc block is the actual API call.\n\t\t\t\t\t\ttmp_last_signature = line.strip() #assign line to tmp var for documentation hooks a few lines down\n\t\t\t\t\t\tself.docblocks[ tmp_last_signature ] = \"\" #init key:value binding in dict\n\n\t\t\t\t\t\t#filename data is stored here.\n\t\t\t\t\t\tself.docblocks_filenames[ tmp_last_signature ] = target_filename + \"#L\" + str(line_x)\n\t\t\t\t\telse:\n\t\t\t\t\t\t#second line of doc block is the API call documentation data.\n\t\t\t\t\t\t#print( \"last sig: \" + tmp_last_signature )\n\t\t\t\t\t\tself.docblocks[ tmp_last_signature ] = self.docblocks[ tmp_last_signature ] + (\"%s\\n\" %(line))\n\n\t\t\t\t#print(\"dump dox data: %s\" %(line))\n\t\t\t\tdoc_line_counter = doc_line_counter + 1\n\n\t\t\telse:\n\t\t\t\tif( line.strip() == \"--[[/**\" ):\n\t\t\t\t\tdoc_line_counter = 0\n\t\t\t\t\tdoc_block_open = True\n\t\t\t\t\t#print(\"doc block opened\")\n\n\t\t\tline_x = line_x + 1\n\n\n\t\t# No return is value is required, collected data in member vars is accessed directly.\n\t\t#return \"lua docblock\"\n","sub_path":"source_scanner_lua.py","file_name":"source_scanner_lua.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"152776409","text":"import csv\nimport sys\n\nif __name__ == \"__main__\":\n\t\n\tif len(sys.argv) != 2:\n\t\tprint(\"Helper script to convert original cmp file to list used in VHDL test benches\")\n\t\tprint(\"Usage: python convert-test.py file.cmp\")\n\telse:\t\n\t\twith open(sys.argv[1], newline='') as csvfile:\n\t\t\tcsvreader = csv.reader(csvfile, delimiter='|', quotechar='#')\n\t\t\trow_count = sum(1 for row in csvreader)\n\t\t\tcsvfile.seek(0, 0)\n\n\t\t\tfor i, row in enumerate(csvreader):\n\t\t\t\tif i == 0:\n\t\t\t\t\tcontinue\n\n\t\t\t\tprint('(', end = '')\n\t\t\t\tfor j, value in enumerate(row):\n\t\t\t\t\tif j == 0:\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\tif j != (len(row)-1):\n\t\t\t\t\t\tvalue = value.strip()\n\t\t\t\t\t\t\n\t\t\t\t\t\tif j == 1:\n\t\t\t\t\t\t\tif '+' in value:\n\t\t\t\t\t\t\t\tvalue = '0'\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tvalue = '1'\n\n\t\t\t\t\t\tif j == 2 or j == 5:\t\t\t\t\t\t\n\t\t\t\t\t\t\tif value[0:1] == \"-\":\n\t\t\t\t\t\t\t\tvalue = ((bin(int(value)+(1<<16)))[2:]).zfill(16)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tvalue = ((bin(int(value)))[2:]).zfill(16)\n\n\t\t\t\t\t\tif j == 4:\t\t\t\n\t\t\t\t\t\t\tvalue = ((bin(int(value)))[2:]).zfill(3)\n\n\n\t\t\t\t\t\tif len(value) == 1:\n\t\t\t\t\t\t\tprint('\\'', end = '')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint('\\\"', end = '')\n\n\t\t\t\t\t\tprint (value, end = '')\n\n\t\t\t\t\t\tif len(value) == 1:\n\t\t\t\t\t\t\tprint('\\'', end = '')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint('\\\"', end = '')\n\n\t\t\t\t\t\tif j != (len(row)-2):\n\t\t\t\t\t\t\tprint (\", \", end = '')\n\t\t\t\t\t\t\n\t\t\t\tprint(')', end = '')\n\n\t\t\t\tif i == (row_count-1):\n\t\t\t\t\tprint('')\n\t\t\t\telse:\n\t\t\t\t\tprint(',')\n","sub_path":"util/convert-test-3-ram8.py","file_name":"convert-test-3-ram8.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"450013533","text":"# URLs\nfrom django.conf.urls import patterns, url\n\n# Views\nfrom django.views.generic import TemplateView\nfrom app import views\n\nurlpatterns = patterns('',\n # Site\n # + Root\n url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'), # / (root)\n # + Actions - Forms\n url(r'^changelog/(?P\\w+)/add/$', views.changelog_add, name='changelog_add'), # changelog/add/ (new changelog)\n url(r'^report/$', views.report_add, name='report_add'), # report/ (new report)\n url(r'^timeline/(?P\\w+)/add/$', views.timeline_add, name='timeline_add'), # timeline/add (new timeline)\n # + AJAX URLs\n url(r'^changelog/delete/(?P\\d+)/$', views.changelog_delete, name='changelog_delete'), # changelog/delete/ID (delete changelog)\n url(r'^timeline/delete/(?P\\d+)/$', views.timeline_delete, name='timeline_delete'), # timeline/delete/ID (delete timeline)\n # + Nav\n url(r'^nav/$', TemplateView.as_view(template_name='site/nav/index.html'), name='nav'), # nav/ (root)\n url(r'^nav/admin/$', TemplateView.as_view(template_name='site/nav/admin.html'), name='nav_admin'), # nav/admin/ (admin)\n url(r'^nav/holdings/$', TemplateView.as_view(template_name='site/nav/holdings.html'), name='nav_holdings'), # nav/holdings/ (holdings)\n url(r'^nav/lookup/$', TemplateView.as_view(template_name='site/nav/lookup.html'), name='nav_lookup'), # nav/lookup/ (lookup)\n url(r'^nav/settings/$', TemplateView.as_view(template_name='site/nav/settings.html'), name='nav_settings'), # nav/settings/ (settings)\n # + Pages\n url(r'^changelog/$', views.changelog, name='changelog'), # changelog/ (changelog)\n url(r'^help/$', TemplateView.as_view(template_name='site/help/index.html'), name='help'), # help/ (help)\n url(r'^timeline/$', views.timeline, name='timeline'), # timeline/ (timeline)\n # + Variable URLs\n url(r'^changelog/(?P\\d+)/$', views.changelog, name='changelog'), # changelog/ID (changelog id)\n url(r'^timeline/(?P\\d+)/$', views.timeline, name='timeline'), # timeline/ID (timeline id)\n url(r'^timeline/(?P\\w+)/$', views.timeline, name='timeline'), # timeline/UPDATE_TYPE (timeline type)\n url(r'^timeline/(?P\\w+)/(?P\\d+)/$', views.timeline_check, name='timeline_check'), # timeline/CHECK/ID (check/uncheck timeline action)\n\n # Account\n # + Account\n url(r'^account/profile/$', views.profile, name='profile'), # account/profile/ (profile)\n # + Actions - Forms\n url(r'^account/(?P\\w+)/signin/$', views.signin, name='signin'), # account/signin/ (signin)\n url(r'^account/(?P\\w+)/signup/$', views.signup, name='signup'), # account/signup/ (signup)\n # + Action URLs\n url(r'^account/signout/$', views.signout, name='signout'), # account/signout/ (signout action)\n # + Pages\n url(r'^account/recovery/$', views.account_recovery, name='account_recovery'), # account/recovery/ (account recovery)\n\n # Lookups\n # + Lookups\n url(r'^currencies/$', views.currencies, name='currencies'), # currencies/ (currencies)\n url(r'^exchanges/$', views.exchanges, name='exchanges'), # exchanges/ (exchanges)\n # + Actions - Forms\n url(r'^currencies/(?P\\w+)/add/(?P\\w+)/?$', views.currency_add, name='currency_add'), # currencies/add (new currency)\n url(r'^exchanges/(?P\\w+)/add/(?P\\w+)/?$', views.exchange_add, name='exchange_add'), # exchanges/add (new exchange)\n # + AJAX URLs\n url(r'^currencies/delete/(?P\\w+)/(?P\\d+)/?$', views.currency_delete, name='currency_delete'), # currencies/delete (delete currency)\n url(r'^exchanges/delete/(?P\\w+)/(?P\\d+)/?$', views.exchange_delete, name='exchange_delete'), # exchanges/delete (delete exchange)\n # + Variable URLs\n url(r'^currencies/(?P\\d+)/$', views.currencies, name='currencies'), # currencies/ID (currency id)\n url(r'^exchanges/(?P\\d+)/$', views.exchanges, name='exchanges'), # exchanges/ID (exchange id)\n\n\n # Holdings\n # + Holdings\n url(r'^holdings/$', views.holdings, name='holdings'), # holdings/ (holdings)\n # + Actions - Simple Actions - Forms\n url(r'^holdings/(?P[-\\w]+)/borrow-margin/$', views.holding_borrow_margin, name='holding_borrow_margin'), # holdings/TYPE/borrow-margin/ (holding borrow)\n url(r'^holdings/(?P[-\\w]+)/deposit/$', views.holding_deposit, name='holding_deposit'), # holdings/TYPE/deposit/ (holding deposit)\n url(r'^holdings/(?P[-\\w]+)/deposit/(?P[-\\w]+)/(?P[-\\w]+)/$', views.holding_deposit, name='holding_deposit'), # holdings/TYPE/deposit/EXCHANGE/CURRENCY/ (simple holding deposit)\n url(r'^holdings/(?P[-\\w]+)/return-margin/$', views.holding_return_margin, name='holding_return_margin'), # holdings/TYPE/return-margin/ (holding return)\n url(r'^holdings/(?P[-\\w]+)/trade/$', views.holding_trade, name='holding_trade'), # holdings/TYPE/trade/ (holding trade)\n url(r'^holdings/(?P[-\\w]+)/transfer/$', views.holding_transfer, name='holding_transfer'), # holdings/TYPE/transfer/ (holding transfer)\n url(r'^holdings/(?P[-\\w]+)/transfer/(?P[-\\w]+)/(?P[-\\w]+)/$', views.holding_transfer, name='holding_transfer'), # holdings/TYPE/transfer/EXCHANGE/CURRENCY/ (holding transfer)\n url(r'^holdings/(?P[-\\w]+)/withdraw/$', views.holding_withdraw, name='holding_withdraw'), # holdings/TYPE/withdraw/ (holding withdraw)\n url(r'^holdings/(?P[-\\w]+)/withdraw/(?P[-\\w]+)/(?P[-\\w]+)/$', views.holding_withdraw, name='holding_withdraw'), # holdings/TYPE/withdraw/EXCHANGE/CURRENCY/ (simple holding withdraw)\n # + Data\n url(r'^holdings/data/fields/(?P
\\w+)/$', views.holding_data_fields, name='holding_data_fields'), # holdings/data/fields/ (holding fields data)\n url(r'^holdings/data/graphs/currency/(?P\\w+)/$', views.holding_data_graphs, name='holding_data_graphs'), # holdings/data/graphs/CURRENCY/ (holding graph data)\n # + Sort\n url(r'^holdings/currencies/$', views.holding_currencies, name='holding_currencies'), # holdings/currency/ (currencies)\n url(r'^holdings/currency/(?P[-\\w]+)/$', views.holding_currencies, name='holding_currencies'), # holdings/CURRENCY (currency page)\n url(r'^holdings/exchanges/$', views.holding_exchanges, name='holding_exchanges'), # holdings/exchange/ (exchanges)\n url(r'^holdings/exchange/(?P[-\\w]+)/$', views.holding_exchanges, name='holding_exchanges'), # holdings/EXCHANGE (exchange page)\n # + Variable URLs\n url(r'^holdings/(?P[-\\w]+)/(?P[-\\w]+)/$', views.holdings, name='holdings'), # holdings/EXCHANGE/CURRENCY (holding page)\n\n\n # Candle\n # + Data\n url(r'^candle/data/graphs/currency/(?P\\w+)/$', views.candle_data_graphs, name='candle_data_graphs'), # candle/data/graphs/CURRENCY/ (candle graph data)\n url(r'^candle/data/graphs/holding/(?P\\w+)/$', views.candle_data_graphs, name='candle_data_graphs'), # candle/data/graphs/HOLDING/ (candle graph data)\n\n\n # Obligation\n # + Obligation\n url(r'^obligations/$', views.obligations, name='obligations'), # obligations/ (obligations)\n url(r'^obligations/(?P\\d+)/$', views.obligations, name='obligations'), # obligations/ID/ (obligations)\n\n\n # Ledger\n # + Ledger\n url(r'^ledger/$', views.ledger, name='ledger'), # ledger/ (ledger)\n url(r'^ledger/filter/(?P\\w+)/$', views.ledger, name='ledger'), # ledger/filter/FILTER (ledger)\n # + Data\n url(r'^ledger/data/graphs/$', views.ledger_data_graphs, name='ledger_data_graphs'), # ledger/data/graphs/ (ledger graph data)\n # + Variable URLs\n url(r'^ledger/(?P\\d+)/$', views.ledger, name='ledger'), # ledger/ID (ledger)\n)","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":7849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"140631931","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"Q1mi\"\n\n\"\"\"\nlogging配置\n\"\"\"\n\nimport os\nimport logging.config\nfrom conf import settings\n# from day26.ftp_server.conf import settings\n\n# 定义三种日志输出格式 开始\n\nstandard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \\\n '[%(levelname)s][%(message)s]'\n\nsimple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'\n\nid_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'\n\n# 定义日志输出格式 结束\n\nlogfile_dir = os.path.join(settings.BASE_DIR,'log') # log文件的目录\n\nlogfile_name = 'Josenph.log' # log文件名\n\n# 如果不���在定义的日志目录就创建一个\nif not os.path.isdir(logfile_dir):\n os.mkdir(logfile_dir)\n\n# log文件的全路径\nlogfile_path = os.path.join(logfile_dir, logfile_name)\n\n# log配置字典\nLOGGING_DIC = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'standard': {\n 'format': simple_format\n },\n 'simple': {\n 'format': simple_format\n },\n },\n 'filters': {},\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler', # 打印到屏幕\n 'formatter': 'simple'\n },\n 'default': {\n 'level': 'DEBUG',\n 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件\n 'filename': logfile_path, # 日志文件\n 'maxBytes': 1024*1024*5, # 日志大小 5M\n 'backupCount': 5,\n 'formatter': 'standard',\n 'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕\n 'level': 'DEBUG',\n 'propagate': True, # 向上(更高level的logger)传递\n },\n },\n}\n# logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置\n# logger = logging.getLogger(__name__) # 生成一个log实例\n#\n#\n# def write_log(fn,addr,data):\n# def wrapper(self, *args, **kwargs):\n# try:\n# logger.info(str(self.addr)+':::'+fn.__name__+str(args)) # 记录该文件的运行状态\n# ret = fn(self, *args, **kwargs)\n# except ValueError:\n# logger.error('值错误')\n# except TypeError:\n# logger.error('类型错误')\n# except TimeoutError:\n# logger.error('连接超时错误')\n# except Exception:\n# logger.error(str(self.addr)+':::'+fn.__name__)\n# return ret\n# return wrapper\n#\n# addr = ('127.0.0.1',1234)\n# def log_write(func,addr,data):\n# if hasattr(logger,func):\n# func = getattr(logger,func)\n# func(str(addr)+':::'+data)\n# if __name__ == '__main__':\n# log_write('warning',addr,'hahahaha')\ndef load_logging_cfg():\n logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置\n\nif __name__ == '__main__':\n load_logging_cfg()","sub_path":"D20170714FtpHomeWork/FTP/server/lib/my_loggingme.py","file_name":"my_loggingme.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"270576180","text":"import unittest\r\nimport hangman\r\n#-------------------------------------------------------------------------------\r\n# Name: hangman_test\r\n# Purpose:\r\n#\r\n# Author: iestyn\r\n#\r\n# Created: 28/07/2019\r\n# Copyright: (c) iestyn 2019\r\n# Licence: MIT\r\n#-------------------------------------------------------------------------------\r\n\r\nclass TestHint(unittest.TestCase):\r\n def test_hint(self):\r\n #Tests the hint function to see if it produces the correct hint\r\n word = \"TheWord\"\r\n expected = [\"_\",\"_\",\"_\",\"_\",\"_\",\"_\",\"_\"]\r\n actual = hangman.setHint(word)\r\n\r\n self.assertEqual(expected, actual)\r\n\r\n\r\nunittest.main()","sub_path":"Hangman/hangman_test.py","file_name":"hangman_test.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"37473927","text":"from __future__ import absolute_import\nimport os,sys\nimport numpy as np\nfrom Bio.PDB.Polypeptide import is_aa \nfrom computeFeatures.structStep.myPDBParser import myPDBParser as PDBParser\n#from Bio.PDB.HSExposure import HSExposureCA, HSExposureCB, ExposureCN\nfrom .HSEExposureFixed import HSExposureCA, HSExposureCB, ExposureCN\n\nfrom ..StructFeatComputer import StructFeatComputer\nfrom utils import myMakeDir, tryToRemove #utils is at the root of the package\n\n\nclass HalfSphereComputer(StructFeatComputer):\n '''\n Extends StructFeatComputer class. Computes half exposure for each residue\n '''\n def __init__(self, rFname, lFname, computedFeatsRootDir=None, statusManager=None):\n '''\n @param statusManager: class that implements .setStatus(msg) to communicate\n '''\n\n StructFeatComputer.__init__(self, rFname, lFname, computedFeatsRootDir, statusManager=statusManager)\n\n self.outPath= myMakeDir(self.computedFeatsRootDir, \"halfSphereExpos\")\n self.parser= PDBParser(QUIET=True)\n\n\n def computeOneFile(self, fileName):\n '''\n Computes DSSP for a given pdb file\n @param fileName: str. fname to pdb file\n '''\n \n prefixAndChainTypeId = (fileName.split(\"/\")[-1]).split(\".pdb\")[0]\n prefixAndChainTypeId= \"_\".join( prefixAndChainTypeId.split(\"_\")[:2])\n structure= self.parser.get_structure(prefixAndChainTypeId, fileName)\n model = structure[0]\n outNames= {}\n for chain in structure[0]:\n chainId= chain.get_id()\n nResidues= sum( (1 for res in chain if is_aa(res)) )\n if chainId==\" \": chainId=\"*\"\n outName= os.path.join(self.outPath,prefixAndChainTypeId+\"_\"+chainId+\"_u.hse\")\n if nResidues>5 and not os.path.isfile(outName):\n outNames[chainId]= outName\n if len(outNames)==0:\n print( \"HalfSphere already computed\")\n return 0\n \n featuresDict= {}\n hse = HSExposureCA(model)\n for aa, feat in hse:\n featuresDict[aa]= [elem if elem!= None else -1 for elem in feat]\n hseDict={ aa: [elem if elem!= None else -1 for elem in feat] for aa,feat in HSExposureCB(model) }\n## print(len(hseDict))\n## raw_input(\"press enter\")\n for aa in set(featuresDict.keys()).union(set(hseDict.keys())):\n try:\n prevFeatures= featuresDict[aa]\n except KeyError:\n prevFeatures= [-1, -1, -1.0]\n try:\n newFeatures= hseDict[aa]\n except KeyError:\n newFeatures= [-1, -1, -1.0] \n featuresDict[aa]= prevFeatures + newFeatures\n \n hseDict={ aa: [feat] if feat!= None else -1 for aa,feat in ExposureCN(model) } \n \n for aa in set(featuresDict.keys()).union(set(hseDict.keys())):\n try:\n prevFeatures= featuresDict[aa]\n except KeyError:\n prevFeatures= [-1, -1, -1.0, -1, -1, -1.0]\n try:\n newFeatures= hseDict[aa]\n except KeyError:\n newFeatures= [-1 ] \n featuresDict[aa]= prevFeatures + newFeatures\n \n filesHandlers={ chainId:open( outNames[chainId],\"w\") for chainId in outNames.keys()}\n for fHand in filesHandlers.values():\n fHand.write(\"chainId structResId resName HSExposureCA1 HSExposureCA2 HSExposureCA3\"+\n \" HSExposureCB1 HSExposureCB2 HSExposureCB3 ExposureCN\\n\")\n\n resuisduesList= [res for chain in structure[0] for res in chain if is_aa(res)]\n badExample= [-1 for elem in list(featuresDict.values())[0]]\n for res in resuisduesList:\n# for res in featuresDict:\n# print(res.get_full_id())\n# print(filesHandlers, res, is_aa(res))\n# raw_input(\"press enter to continue\")\n# \n structId,modelId,chainId, resId= res.get_full_id()\n resId= list(resId)\n resId[1]=str(resId[1])\n resId= \"\".join(resId[1:])\n resName= self.threeLetterAA_to_one(res.resname)\n\n if chainId==\" \":\n chainId=\"*\"\n try: \n if chainId not in filesHandlers: continue #small chains\n try:\n valuesForRes= featuresDict[res]\n except KeyError:\n valuesForRes= badExample\n filesHandlers[chainId].write(chainId+\" \"+resId+\" \"+resName+\" \"+\" \".join([str(val) for val in valuesForRes])+\"\\n\")\n except (KeyboardInterrupt, Exception):\n for outName in outNames.values():\n print(\"Exception happend computing %s\"%outName) \n tryToRemove(outName) \n raise \n for outFile in filesHandlers.values():\n outFile.close()\n \n return 0\n\ndef testModule():\n rFname=\"/home/rsanchez/Tesis/rriPredMethod/data/bench5Data/b5structures/1GRN_r_u.pdb\"\n lFname=\"/home/rsanchez/Tesis/rriPredMethod/data/bench5Data/b5structures/1GRN_l_u.pdb\"\n \n# rFname=\"/home/rsanchez/Tesis/managePDB/data/dimersAndTrimersRawPDBs/1A22.pdb\"\n# lFname=\"/home/rsanchez/Tesis/managePDB/data/dimersAndTrimersRawPDBs/1ABR.pdb\"\n \n# computedFeatsRootDir=\"/home/rsanchez/Tesis/rriPredMethod/data/ppdockingBenchData/tmpComputedFeatures\"\n computedFeatsRootDir=\"/home/rsanchez/tmp/computedFeats\"\n hfsComp= HalfSphereComputer(rFname, lFname, computedFeatsRootDir)\n hfsComp.computeFun()\n raise ValueError(\"Debug Mode. Comment out testModule() line 128\") \n \n\nif __name__==\"__main__\":\n testModule()\n pdbsIndir= \"/home/rsanchez/Tesis/rriPredMethod/data/ppdockingBenchData/BenchmarkData/rawBenchmark3\"\n computedFeatsRootDir= \"/home/rsanchez/Tesis/rriPredMethod/data/ppdockingBenchData/computedFeatures\"\n\n\n# pdbsIndir= \"/home/rsanchez/Tesis/rriPredMethod/data/bench5Data/b5structures/\"\n# computedFeatsRootDir= \"/home/rsanchez/Tesis/rriPredMethod/data/bench5Data/computedFeatures/structStep/halfSphereExpos\"\n\n StructFeatComputer.computeFeaturesAllComplexes(HalfSphereComputer,pdbsIndir= pdbsIndir ,computedFeatsRootDir= computedFeatsRootDir)\n\n\n","sub_path":"computeFeatures/structStep/HALF_SPHERE_EXPOS/computeHalfSphere.py","file_name":"computeHalfSphere.py","file_ext":"py","file_size_in_byte":5702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"420935299","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# ---------------------------------------------------------------------\n# Copyright (c) 2012 Michael Hull.\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# - Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# - Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# 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# HOLDER 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\nimport re\nfrom os.path import join as Join\n\nfrom morphforge.core import LocMgr, LogMgr\nfrom morphforge.core.misc import StrUtils\n\n\nclass ModFile(object):\n\n @classmethod\n def extract_nrn_suffix_from_text(cls, txt):\n\n r = re.compile(\n r\"\"\".* ^[^:]* SUFFIX \\s* (?P[a-zA-Z0-9_]+) (\\s+:.*)? $ .*\"\"\",\n re.VERBOSE | re.MULTILINE | re.DOTALL)\n match_obj = r.match(txt)\n assert match_obj, \"Can't extract suffix from mod-file\"\n nrnsuffix = match_obj.groupdict()['suffix']\n return nrnsuffix\n\n def __init__(\n self,\n modtxt,\n name=None,\n additional_compile_flags='',\n additional_link_flags='',\n additional_ld_library_path='',\n strict_modlunit=True,\n ):\n \n # if no name is provided:\n if name == None:\n name = ModFile.extract_nrn_suffix_from_text(modtxt)\n\n self.name = name\n self.modtxt = modtxt\n\n self.additional_compile_flags = additional_compile_flags\n self.additional_link_flags = additional_link_flags\n self.additional_ld_library_path = additional_ld_library_path\n\n self.strict_modlunit = strict_modlunit\n\n def ensure_built(self):\n LogMgr.info('Ensuring Modfile is built')\n from morphforge.simulation.neuron.biophysics.modfilecompiler import ModFileCompiler\n ModFileCompiler().build_modfile(self, self.strict_modlunit)\n\n def get_md5_hash(self):\n return StrUtils.get_hash_md5(self.modtxt)\n\n def get_built_filename_short(self, ensure_built=True):\n if ensure_built:\n self.ensure_built()\n return 'mod_' + self.get_md5_hash() + '.so'\n\n def get_built_filename_full(self, ensure_built=True):\n if ensure_built:\n self.ensure_built()\n return Join(LocMgr.get_default_mod_outdir(),\n self.get_built_filename_short(ensure_built=ensure_built))\n\n\n","sub_path":"src/morphforge/simulation/neuron/biophysics/modfile.py","file_name":"modfile.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"230129170","text":"def run():\n N, M = [int(x) for x in input().split()]\n matrix = []\n for _ in range(N):\n tmp = [int(x) for x in input().split()]\n matrix.append(tmp)\n blanks = []\n for i in range(N):\n for j in range(M):\n if matrix[i][j] == 0:\n blanks.append((i, j))\n if len(blanks) <= 1 or len(blanks) >= N*M-1:\n print(N*M-len(blanks))\n return \n else:\n total = N * M - len(blanks)\n maxT = 1\n tmp = [[0]*M for _ in range(N)]\n for i in range(N):\n for j in range(M):\n tmp[i][j] = matrix[i][j]\n dx = [0, 0, 1, -1]\n dy = [1, -1, 0, 0]\n while blanks:\n tmp = [[0]*M for _ in range(N)]\n for i in range(N):\n for j in range(M):\n tmp[i][j] = matrix[i][j]\n curblank = blanks.pop(0)\n queue = []\n tmp[curblank[0]][curblank[1]] = 1\n queue.append(curblank)\n team = 0\n while queue:\n cur = queue.pop(0)\n x, y = cur[0], cur[1]\n tmp[x][y] = 0\n team += 1\n for i in range(4):\n nxt_x, nxt_y = x + dx[i], y+dy[i]\n if 0 <= nxt_x < N and 0 <= nxt_y < M and tmp[nxt_x][nxt_y] == 1:\n queue.append((nxt_x, nxt_y))\n if team <= total:\n maxT = max(maxT, team)\n else:\n team -= 1\n maxT = max(maxT, team)\n print(maxT)\n return\n\nrun()\n \n","sub_path":"拼多多笔试/PDD_9-1-2.py","file_name":"PDD_9-1-2.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"150882496","text":"#-------------------------------------------------------------------------------\r\n# Name: Email Validation\r\n# Purpose: For CodeEval's Email Validation challenge. Takes file name, then reads file. Prints whether each line in the file is a valid email or isn't.\r\n#\r\n# Author: Winston\r\n#\r\n# Created: 16/04/2013\r\n# Copyright: (c) Winston 2013\r\n#-------------------------------------------------------------------------------\r\n\r\nimport sys\r\nimport re\r\n\r\ndef main():\r\n p = re.compile(\"^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$\") #compile the regex pattern\r\n\r\n file = open(sys.argv[1], 'r')\r\n for line in file:\r\n #sys.stderr.write(line)\r\n if line == \"\\n\":\r\n continue\r\n m = p.match(line) #create matcher object from pattern and line\r\n if m:\r\n print(\"true\")\r\n else:\r\n print(\"false\")\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"CodeEval/email_validation.py","file_name":"email_validation.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"463581194","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 2 23:05:11 2018\n\nhttps://www.kaggle.com/uciml/electric-power-consumption-data-set\nを解くスクリプト\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport pickle\nfrom datetime import datetime\nimport os\nfrom sklearn.preprocessing import MinMaxScaler\nfrom glob import glob\nfrom hyperopt import hp, tpe, Trials, fmin, space_eval\n\nfrom keras.models import Sequential \nfrom keras.layers.core import Dense, Activation \nfrom keras.layers.recurrent import LSTM\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.callbacks import EarlyStopping\nfrom keras.callbacks import History\nfrom keras.models import load_model\n\nhyperopt_parameters_def = {\n 'length_of_sequences':5,\n 'batch_size': 3,\n 'hidden_neurons': 100,\n}\n\nhyperopt_parameters = {\n 'length_of_sequences' : hp.quniform('length_of_sequences',50, 150, 10),\n 'batch_size': hp.quniform('batch_size', 2, 32, 2),\n 'hidden_neurons': hp.quniform('hidden_neurons', 100, 800,100),\n# 'kernel': hp.choice('kernel', ['rbf', 'poly', 'sigmoid'])\n}\n\ndef _load_data(data, n_prev = 30): \n \"\"\"\n data should be pd.DataFrame()\n \"\"\"\n docX, docY = [], []\n for i in range(len(data)-n_prev):\n docX.append(data.iloc[i:i+n_prev].as_matrix())\n docY.append(data.iloc[i+n_prev][0])\n# docX.append(data.iloc[i:i+n_prev])\n# docY.append(data.iloc[i+n_prev])\n alsX = np.array(docX)\n alsY = np.array(docY)\n\n return alsX, alsY\n\ndef train_test_split(_df, test_size=0.1, n_prev = 100):\n \"\"\"\n This just splits data to training and testing parts\n \"\"\"\n ntrn = round(len(_df) * (1 - test_size))\n ntrn = int(ntrn)\n\n X_train, y_train = _load_data(_df.iloc[0:ntrn], n_prev)\n X_test, y_test = _load_data(_df.iloc[ntrn:], n_prev)\n\n return (X_train, y_train), (X_test, y_test)\n\ndef objective(args):\n print(args)\n batch_size = int(args['batch_size'])\n length_of_sequences = int(args['length_of_sequences'])\n hidden_neurons = int(args['hidden_neurons'])\n\n (X_train, y_train), (X_test, y_test) = train_test_split(df, test_size=0.2, n_prev =length_of_sequences)\n \n in_out_neurons = X_train.shape[2]\n\n model = Sequential()\n model.add(LSTM(hidden_neurons, batch_input_shape=(None, length_of_sequences, in_out_neurons), return_sequences=False))\n model.add(Dense(in_out_neurons)) \n model.add(Activation(\"linear\")) \n model.add(Dense(1)) \n model.compile(loss=\"mean_squared_error\", optimizer=\"Adam\")#\"rmsprop\")\n\n es = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=1, mode='auto')\n filepath = dir_name + os.sep + str(trial_num) + '_weights.{epoch:03d}-{loss:.4f}_{val_loss:.4f}.hdf5'\n mcp = ModelCheckpoint(filepath, monitor='val_loss', verbose=0, save_best_only=True, save_weights_only=False, mode='auto')\n \n history = model.fit(X_train, y_train, batch_size=batch_size, epochs=30, callbacks=[es, mcp], validation_split=0.05) \n unnecessary_filenames = glob(dir_name + os.sep + str(trial_num) + \"*weights*\")[0:-1]\n for filename in unnecessary_filenames:\n os.remove(filename)\n obj = np.min(history.history['val_loss'])\n return obj \n\n\nif __name__ == '__main__':\n\n csv_filename = r\"C:\\Users\\kodama\\Documents\\github\\compe_kag\\HouseholdElectricPowerConsumption\\household_power_consumption.txt\"\n df = pd.read_csv(csv_filename, sep = \";\")\n df = df.iloc[:,2:]\n df = df.dropna()\n df = df[df.columns].astype(float)\n \n df = df.head(int(df.shape[0]/1000))\n \n ms = MinMaxScaler()\n data_norm = ms.fit_transform(df)\n \n# df_obj = df[\"Global_active_power\"]\n \n# df_obj=df_obj / df_obj.max()\n\n df = pd.DataFrame(data_norm)\n \n dir_name = datetime.now().strftime('%Y%m%d_%H%M%S')\n os.mkdir(dir_name)\n \n #length_of_sequences = 100\n \n in_out_neurons = 1\n #hidden_neurons = 600\n\n # iterationする回数\n max_evals = 5\n # 試行の過程を記録するインスタンス\n trials = Trials()\n \n trial_num = 0\n while trial_num < max_evals:\n best = fmin(\n # 最小化する値を定義した関数\n objective,\n # 探索するパラメータのdictもしくはlist\n hyperopt_parameters_def,\n # どのロジックを利用するか、基本的にはtpe.suggestでok\n algo=tpe.suggest,\n max_evals=trial_num+1,\n trials=trials,\n # 試行の過程を出力\n verbose=1\n )\n \n with open(dir_name + os.sep + \"trials.pkl\",\"wb\") as f: \n pickle.dump(trials, f)\n \n trial_num += 1\n \n best_id = np.argmin(trials.losses())\n best_filename = glob(dir_name + os.sep + str(best_id) + \"*.hdf5\")[0]\n model = load_model(best_filename)\n \n (X_train, y_train), (X_test, y_test) = train_test_split(df, test_size=0.2, n_prev =5)\n\n predicted = model.predict(X_test) \n \n dataf = pd.DataFrame(predicted[:200])\n dataf.columns = [\"predict\"]\n dataf[\"input\"] = y_test[:200]\n dataf.plot(figsize=(15, 5))\n \n \n","sub_path":"HouseholdElectricPowerConsumption/train_hp.py","file_name":"train_hp.py","file_ext":"py","file_size_in_byte":5089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"262065086","text":"from enum import Enum\n\n__author__ = 'blackecho'\n\n\nclass PrimitiveSubtask(object):\n\n \"\"\"Primitive Subtask in the task hierarchy. It represents a leaf node in the hierarchy tree.\n \"\"\"\n\n transition_type = Enum('TransitionType', 'stochastic deterministic')\n\n def __init__(self,\n task_id,\n desc,\n v_func,\n apply_func):\n \"\"\"Instantiate a new Primitive Subtask in the hierarchy.\n :param task_id: unique identifier for this subtask.\n :param desc: string description of the subtask.\n :param v_func: states set is needed to define the Value function for this subtask.\n :param apply_func: apply the action defined by this subtask and return new state and reward.\n \"\"\"\n self.task_id = task_id\n self.desc = desc\n self.v_func = v_func\n self.apply_func = apply_func\n\n def apply(self, s, transition_type):\n \"\"\"Apply the primitive action defined by this subtask and return new state ns and reward r\n :param s: starting state for this subtask.\n :param transition_type: specify between stochastic transition or deterministic transition\n :return: (ns, r)\n \"\"\"\n return self.apply_func(s, transition_type)\n\n\nclass CompositeSubtask(object):\n\n \"\"\"Composite Subtask in the task hierarchy. It represents an internal node in the hierarchy tree, and has a\n local policy. The set of the policies for all the CompositeSubtasks in the MaxQGraph gives the\n hierarchical policy for the root task.\n \"\"\"\n\n def __init__(self,\n task_id,\n desc,\n active_states,\n exit_states,\n actions,\n pseudo_reward,\n policy=None,\n start_state=None,\n int_c_values=None,\n ext_c_values=None,\n order=False,\n params=None):\n \"\"\"Instantiate a new Composite Subtask in the hierarchy.\n :param task_id: unique identifier for this subtask.\n :param desc: string description of the subtask.\n :param start_state: starting state for this subtask.\n :param active_states: set of active states for this subtask.\n :param exit_states: set of exit states for this subtask.\n :param actions: possible action in this subtask, either composite or primitive.\n :param policy: the policy for this subtasks.\n :param pseudo_reward: pseudo-reward function.\n :param int_c_values: internal completion function for the subtask.\n :param ext_c_values: external completion function for the subtask.\n :param order: if True, then the policy should respect the order in actions. Used for root task.\n :param params: extra parameters.\n \"\"\"\n self.task_id = task_id\n self.desc = desc\n self.start_state = start_state\n self.current_state = start_state # current state of the subtask\n self.active_states = active_states\n self.exit_states = exit_states\n self.actions = actions\n self.policy = policy\n self.pseudo_reward = pseudo_reward\n self.order = order\n self.last_called = None # use for ordered_policy\n self.params = params\n # int_c values for active and exit states\n if int_c_values is None:\n self.int_c_values = {(s, a): 0 for a in actions for s in list(set(active_states) | set(exit_states))}\n else:\n self.int_c_values = int_c_values\n # ext_c values for active and exit states\n if ext_c_values is None:\n self.ext_c_values = {(s, a): 0 for a in actions for s in list(set(active_states) | set(exit_states))}\n else:\n self.ext_c_values = ext_c_values\n\n def is_terminated(self, s):\n \"\"\"Termination predicate for this subtask.\n :param s: state\n :return: true if s is in the exit states set of this subtask, false otherwise\n \"\"\"\n return s in self.exit_states\n\n def ordered_policy(self, _):\n \"\"\"Ordered policy, return the next subtask w.r.t. the last called subtask.\n :param _: state\n :return: next subtask\n \"\"\"\n if not self.last_called:\n return self.actions[0]\n else:\n last_index = self.actions.index(self.last_called)\n return self.actions[last_index+1]\n\n def random_policy(self, _):\n \"\"\"Random policy.\n :param _: state\n :return: for each state, return a random action\n \"\"\"\n self.current_state = _\n import random\n return random.choice(self.actions)\n\n","sub_path":"subtask.py","file_name":"subtask.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"629398404","text":"#!/usr/bin/env python\nimport numpy as np\nimport batman\nimport time\nimport argparse\n\n\n\nif __name__=='__main__':\n\n parser = argparse.ArgumentParser(description='Test the multithreading of batman')\n\n parser.add_argument('nthreads',help='the number of threads used to evaluate batman')\n args = parser.parse_args()\n nthreads = int(args.nthreads)\n\n\n\n params = batman.TransitParams()\n params.t0 = 0. #time of inferior conjunction\n params.per = 1. #orbital period\n params.rp = 0.1 #planet radius (in units of stellar radii)\n params.a = 15. #semi-major axis (in units of stellar radii)\n params.inc = 87. #orbital inclination (in degrees)\n params.ecc = 0. #eccentricity\n params.w = 90. #longitude of periastron (in degrees)\n params.u = [0.1, 0.3] #limb darkening coefficients\n params.limb_dark = \"quadratic\" #limb darkening model\n\n\n\n t = np.linspace(-0.05, 0.05, 10000)\n texp = 1626./86400\n\n\n start = time.time()\n for i in range(1000):\n m = batman.TransitModel(params,t,nthreads=nthreads,supersample_factor=15.,exp_time=texp) #initializes model\n flux = m.light_curve(params) #calculates light curve\n end = time.time()\n print(end-start)\n","sub_path":"basictime.py","file_name":"basictime.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"566428894","text":"# coding:utf-8\nimport wx\n\nclass PopupWindow(wx.Frame):\n def __init__(self, parent=None, id=-1, title=\"\"):\n wx.Frame.__init__(self, parent=parent, id=id, title=title, style=wx.CAPTION | wx.CLOSE_BOX | wx.FRAME_FLOAT_ON_PARENT)\n self.parent = parent\n self.bitmap = None\n self.Centre()\n # キャプションなどのサイズ考慮\n # self.SetSize(wx.Size(800, 480))\n self.SetClientSize(wx.Size(800, 480))\n\n self.Bind(wx.EVT_LEFT_DOWN, self.onClick)\n self.Bind(wx.EVT_KEY_DOWN, self.onKeyDown)\n self.Bind(wx.EVT_PAINT, self.onPaint)\n\n def onClick(self, e):\n self.parent.popupWindow = None\n self.Close()\n\n def onKeyDown(self, e):\n self.parent.popupWindow = None\n self.Close()\n\n def onPaint(self, e):\n if self.bmp is None:\n return\n dc = wx.PaintDC(self)\n dc.DrawBitmap(self.bmp, 0, 0)\n pass\n\n def setBitmap(self, bmp):\n self.bmp = bmp\n\n","sub_path":"popupwindow.py","file_name":"popupwindow.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"295474889","text":"from setuptools import setup, find_packages\n\nwith open('requirements.txt') as f:\n required = f.read().splitlines()\n\n\nsetup(\n name='jira-sync',\n version=\"1.0\",\n description=\"Track and Sync github Issues, PR, PR_Reviews as Jira Tasks\",\n author=\"Omkar Khatavkar\",\n author_email=\"okhatavkar007@gmail.com\",\n url=\"https://github.com/omkarkhatavkar/jirasync\",\n py_modules=['jirasync'],\n install_requires=required,\n dependency_links=[\n 'git+ssh://github.com/omkarkhatavkar/did/tarball/master#egg=did'\n ],\n packages=find_packages(\"jirasync\"),\n entry_points='''\n [console_scripts]\n jirasync=jirasync:cli\n ''',\n license='MIT',\n classifiers=[\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.6',\n ],\n)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13855838","text":"# Copyright (c) 2014 Bull.\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\n\nfrom blazarclient import command\nfrom blazarclient import exception\n\n# Matches integers or UUIDs\nHOST_ID_PATTERN = r'^([0-9]+|([0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}))$'\n\n\nclass ListHosts(command.ListCommand):\n \"\"\"Print a list of hosts.\"\"\"\n resource = 'host'\n log = logging.getLogger(__name__ + '.ListHosts')\n list_columns = ['id', 'hypervisor_hostname', 'vcpus', 'memory_mb',\n 'local_gb']\n\n def get_parser(self, prog_name):\n parser = super(ListHosts, self).get_parser(prog_name)\n parser.add_argument(\n '--sort-by', metavar=\"\",\n help='column name used to sort result',\n default='hypervisor_hostname'\n )\n return parser\n\n\nclass ShowHost(command.ShowCommand):\n \"\"\"Show host details.\"\"\"\n resource = 'host'\n json_indent = 4\n name_key = 'hypervisor_hostname'\n id_pattern = HOST_ID_PATTERN\n log = logging.getLogger(__name__ + '.ShowHost')\n\n\nclass CreateHost(command.CreateCommand):\n \"\"\"Create a host.\"\"\"\n resource = 'host'\n json_indent = 4\n log = logging.getLogger(__name__ + '.CreateHost')\n\n def get_parser(self, prog_name):\n parser = super(CreateHost, self).get_parser(prog_name)\n parser.add_argument(\n 'name', metavar=self.resource.upper(),\n help='Name of the host to add'\n )\n parser.add_argument(\n '--extra', metavar='=',\n action='append',\n dest='extra_capabilities',\n default=[],\n help='Extra capabilities key/value pairs to add for the host'\n )\n return parser\n\n def args2body(self, parsed_args):\n params = {}\n if parsed_args.name:\n params['name'] = parsed_args.name\n extras = {}\n if parsed_args.extra_capabilities:\n for capa in parsed_args.extra_capabilities:\n key, _sep, value = capa.partition('=')\n # NOTE(sbauza): multiple copies of the same capability will\n # result in only the last value to be stored\n extras[key] = value\n params.update(extras)\n return params\n\n\nclass UpdateHost(command.UpdateCommand):\n \"\"\"Update attributes of a host.\"\"\"\n resource = 'host'\n json_indent = 4\n log = logging.getLogger(__name__ + '.UpdateHost')\n name_key = 'hypervisor_hostname'\n id_pattern = HOST_ID_PATTERN\n\n def get_parser(self, prog_name):\n parser = super(UpdateHost, self).get_parser(prog_name)\n parser.add_argument(\n '--extra', metavar='=',\n action='append',\n dest='extra_capabilities',\n default=[],\n help='Extra capabilities key/value pairs to update for the host'\n )\n return parser\n\n def args2body(self, parsed_args):\n params = {}\n extras = {}\n if parsed_args.extra_capabilities:\n for capa in parsed_args.extra_capabilities:\n key, _sep, value = capa.partition('=')\n # NOTE(sbauza): multiple copies of the same capability will\n # result in only the last value to be stored\n extras[key] = value\n params['values'] = extras\n return params\n\n\nclass UnsetAttributesHost(UpdateHost):\n \"\"\"Unset attributes of a host.\"\"\"\n log = logging.getLogger(__name__ + '.UnsetAttributesHost')\n\n def get_parser(self, prog_name):\n parser = super(UpdateHost, self).get_parser(prog_name)\n parser.add_argument(\n '--extra', metavar='',\n action='append',\n dest='extra_capabilities',\n default=[],\n help='Extra capability keys which should be unset from the host.',\n )\n return parser\n\n def args2body(self, parsed_args):\n if parsed_args.extra_capabilities:\n return {\n 'values': {\n cap: None for cap in parsed_args.extra_capabilities\n }\n }\n else:\n return {}\n\nclass DeleteHost(command.DeleteCommand):\n \"\"\"Delete a host.\"\"\"\n resource = 'host'\n log = logging.getLogger(__name__ + '.DeleteHost')\n name_key = 'hypervisor_hostname'\n id_pattern = HOST_ID_PATTERN\n\n\nclass ShowHostAllocation(command.ShowAllocationCommand):\n \"\"\"Show host allocation details.\"\"\"\n resource = 'host'\n json_indent = 4\n id_pattern = HOST_ID_PATTERN\n log = logging.getLogger(__name__ + '.ShowHostAllocation')\n\n\nclass ListHostAllocations(command.ListAllocationCommand):\n \"\"\"List host allocations.\"\"\"\n resource = 'host'\n log = logging.getLogger(__name__ + '.ListHostAllocations')\n list_columns = ['resource_id', 'reservations']\n\n def get_parser(self, prog_name):\n parser = super(ListHostAllocations, self).get_parser(prog_name)\n parser.add_argument(\n '--sort-by', metavar=\"\",\n help='column name used to sort result',\n default='resource_id'\n )\n return parser\n\n\nclass ReallocateHost(command.ReallocateCommand):\n \"\"\"Reallocate host from current allocations.\"\"\"\n resource = 'host'\n json_indent = 4\n log = logging.getLogger(__name__ + '.ReallocateHost')\n name_key = 'hypervisor_hostname'\n id_pattern = HOST_ID_PATTERN\n\n def get_parser(self, prog_name):\n parser = super(ReallocateHost, self).get_parser(prog_name)\n parser.add_argument(\n '--lease-id',\n help='Lease ID to reallocate host from.')\n parser.add_argument(\n '--reservation-id',\n help='Reservation ID to reallocate host from')\n return parser\n\n def args2body(self, parsed_args):\n params = {}\n\n if parsed_args.reservation_id:\n params['reservation_id'] = parsed_args.reservation_id\n elif parsed_args.lease_id:\n params['lease_id'] = parsed_args.lease_id\n\n return params\n\n\nclass ShowHostCapability(command.ShowCapabilityCommand):\n \"\"\"Show host capability.\"\"\"\n resource = 'host'\n json_indent = 4\n log = logging.getLogger(__name__ + '.ShowHostCapability')\n\n\nclass ListHostCapabilities(command.ListCommand):\n \"\"\"List host capabilities.\"\"\"\n resource = 'host'\n log = logging.getLogger(__name__ + '.ListHostCapabilities')\n list_columns = ['property', 'private', 'capability_values']\n\n def args2body(self, parsed_args):\n params = {'detail': parsed_args.detail}\n if parsed_args.sort_by:\n if parsed_args.sort_by in self.list_columns:\n params['sort_by'] = parsed_args.sort_by\n else:\n msg = 'Invalid sort option %s' % parsed_args.sort_by\n raise exception.BlazarClientException(msg)\n\n return params\n\n def retrieve_list(self, parsed_args):\n \"\"\"Retrieve a list of resources from Blazar server.\"\"\"\n blazar_client = self.get_client()\n body = self.args2body(parsed_args)\n resource_manager = getattr(blazar_client, self.resource)\n data = resource_manager.list_capabilities(**body)\n return data\n\n def get_parser(self, prog_name):\n parser = super(ListHostCapabilities, self).get_parser(prog_name)\n parser.add_argument(\n '--detail',\n action='store_true',\n help='Return capabilities with values and attributes.',\n default=False\n )\n parser.add_argument(\n '--sort-by', metavar=\"\",\n help='column name used to sort result',\n default='property'\n )\n return parser\n\n\nclass UpdateHostCapability(command.UpdateCapabilityCommand):\n \"\"\"Update attributes of a host capability.\"\"\"\n resource = 'host'\n json_indent = 4\n log = logging.getLogger(__name__ + '.UpdateHostCapability')\n name_key = 'capability_name'\n","sub_path":"blazarclient/v1/shell_commands/hosts.py","file_name":"hosts.py","file_ext":"py","file_size_in_byte":8526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"74712251","text":"import sys, pygame\npygame.init()\n\nsize = width, height = 480, 476\nscreen = pygame.display.set_mode(size)\nbackground = pygame.image.load('taulell.bmp').convert()\nscreen.blit(background, (0, 0))\n\nwhile 1:\n for event in pygame.event.get():\n if event.type == pygame.QUIT: sys.exit()\n\t\n pygame.display.update()\n pygame.time.delay(100)\n\n","sub_path":"2048.py","file_name":"2048.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"341277550","text":"#\n# example5B.py [version 1.0]\n# CoSniWa: COde SNIppet stopWAtch [Python port] - example 5B\n#\n# Example5A: Using Cosniwa with classes (versionB)\n#\n# read more on: www.speedupcode.com\n#\n# (c) Jacek Pierzchlewski, 2017 jacek@pierzchlewski.com\n# license: BSD-2-Clause.\n#\ntry:\n import cCosniwa as csw\nexcept ImportError:\n print(\"\\nERROR: cCosniwa was not found! \\n\")\n\n\nclass Fibonacci():\n \"\"\"\n 'Fibonacci': Class which computes n-th element\n of the Fibonacci sequence.\n \"\"\"\n\n def __init__(self, iIndex_, Cosniwa_):\n \"\"\"\n INITIALISATION METHOD.\n\n Arguments:\n iIndex_: [int] Index of a class\n Cosniwa_: [Cosniwa handle] Handle to Cosniwa object\n\n \"\"\"\n\n # Store the index of the class and the handle to Cosniwa\n self.iIndex = iIndex_\n self.hCsw = Cosniwa_\n\n # Create a class name\n self.strName = 'Fibonacci'\n\n # Register the class in Cosniwa\n self.iCswReg = csw.xreg_code(self.hCsw, self.strName)\n\n def run(self, iNEl):\n \"\"\"\n run: COMPUTE THE n-TH ELEMENT OF THE FIBONACCI SEQUENCE.\n\n Function computes the n-th element of the Fibonacci sequence by\n iterating through all the sequence until n-th elements.\n It is preassumed that the 1st (index 0) and the 2nd (index 1)\n elements of the sequence equal 1.\n\n Arguments:\n iNLen: [int] Index of the element to be computed\n\n Returns:\n iFibo: [int] n-th element of the Fibonacci sequence\n \"\"\"\n\n iFibo = 1\n iFiboPrev = 1\n iFiboPrevPrev = 1\n\n # Start the Cosniwa stopwatch\n csw.xcall_start(self.hCsw, self.iCswReg)\n\n # 1st and 2nd element equals 1\n if (iNEl < 2):\n return 1\n\n # Loop unitl n-th element\n for inxFib in range(iNEl - 2):\n iFiboPrevPrev = iFiboPrev\n iFiboPrev = iFibo\n iFibo = iFiboPrev + iFiboPrevPrev\n\n # Stop the Cosniwa stopwatch\n csw.xcall_stop(self.hCsw, self.iCswReg)\n\n return iFibo\n\n\ndef main():\n\n # Get handle to Cosniwa module\n hCsw = csw.get_handle()\n\n # Start the main CoSniWa time\n csw.start()\n\n # Generate 10 Fibonacci classes\n f0 = Fibonacci(0, hCsw)\n f1 = Fibonacci(1, hCsw)\n f2 = Fibonacci(2, hCsw)\n f3 = Fibonacci(3, hCsw)\n f4 = Fibonacci(4, hCsw)\n f5 = Fibonacci(5, hCsw)\n f6 = Fibonacci(6, hCsw)\n f7 = Fibonacci(7, hCsw)\n f8 = Fibonacci(8, hCsw)\n f9 = Fibonacci(9, hCsw)\n\n # Compute Fibonacci sequences with different number of elements\n f0.run(100000)\n f1.run(90000)\n f2.run(80000)\n f3.run(70000)\n f4.run(60000)\n f5.run(50000)\n f6.run(40000)\n f7.run(30000)\n f8.run(20000)\n f9.run(1000)\n\n # Stop the main CoSniWa time\n csw.stop()\n\n # Print out the timing results\n csw.resultc()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/examples/example5B.py","file_name":"example5B.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"116940984","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\nfrom mephisto.data_model.requester import Requester\nfrom mephisto.providers.mock.provider_type import PROVIDER_TYPE\nfrom mephisto.core.argparse_parser import str2bool\n\nfrom typing import Optional, Dict, List, Mapping, Any, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from mephisto.data_model.database import MephistoDB\n from mephisto.data_model.task import TaskRun\n from mephisto.providers.mock.mock_datastore import MockDatastore\n from argparse import _ArgumentGroup as ArgumentGroup\n\nMOCK_BUDGET = 100000.0\n\n\nclass MockRequester(Requester):\n \"\"\"\n High level class representing a requester on some kind of crowd provider. Sets some default\n initializations, but mostly should be extended by the specific requesters for crowd providers\n with whatever implementation details are required to get those to work.\n \"\"\"\n\n def __init__(\n self, db: \"MephistoDB\", db_id: str, row: Optional[Mapping[str, Any]] = None\n ):\n super().__init__(db, db_id, row=row)\n self.datastore: \"MockDatastore\" = db.get_datastore_for_provider(PROVIDER_TYPE)\n\n def register(self, args: Optional[Dict[str, str]] = None) -> None:\n \"\"\"Mock requesters don't actually register credentials\"\"\"\n if args is not None:\n if args.get(\"force_fail\") is True:\n raise Exception(\"Forced failure test exception was set\")\n else:\n self.datastore.set_requester_registered(self.db_id, True)\n\n @classmethod\n def add_args_to_group(cls, group: \"ArgumentGroup\") -> None:\n \"\"\"\n Add mock registration arguments to the argument group.\n \"\"\"\n super(MockRequester, cls).add_args_to_group(group)\n\n group.description = \"\"\"\n MockRequester: Arguments for mock requester add special\n control and test functionality.\n \"\"\"\n group.add_argument(\n \"--force-fail\",\n dest=\"force_fail\",\n type=str2bool,\n default=False,\n help=\"Trigger a failed registration\",\n )\n return None\n\n def is_registered(self) -> bool:\n \"\"\"Return the registration status\"\"\"\n return self.datastore.get_requester_registered(self.db_id)\n\n def get_available_budget(self) -> float:\n \"\"\"MockRequesters have $100000 to spend\"\"\"\n return MOCK_BUDGET\n\n def is_sandbox(self) -> bool:\n \"\"\"MockRequesters are for testing only, and are thus treated as sandbox\"\"\"\n return True\n\n @staticmethod\n def new(db: \"MephistoDB\", requester_name: str) -> \"Requester\":\n return MockRequester._register_requester(db, requester_name, PROVIDER_TYPE)\n","sub_path":"mephisto/providers/mock/mock_requester.py","file_name":"mock_requester.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"292876368","text":"from tensorflow.keras.layers import Input, Dense, Flatten, Reshape, Activation, Add, LSTM, Permute, multiply, concatenate\nfrom tensorflow.keras.layers import TimeDistributed, MaxPooling1D\nfrom tensorflow.keras.layers import Dropout, Multiply, Conv1D, AveragePooling1D, BatchNormalization\nfrom tensorflow.keras.layers import GlobalAveragePooling1D, Masking, PReLU\nfrom tensorflow.keras.layers import ConvLSTM2D\nfrom layers import Attention\nfrom tensorflow.keras.models import Model\nfrom activations import Mish\n\n'''\nConvolutional Models\n------------------------\n Here we have a lovely collection of convolutional models.\n Please use them!\n\n'''\n\nclass WaveNet:\n '''\n wavenet: build a wavenet model\n -----------------------------\n init args:\n input_shape,\n output_shape\n kernel_size=2,\n filters=40,\n dilation_depth=9\n outputs:\n use the build_model method to build the model. Note the model isnt compiled\n '''\n def __init__(self, input_shape, output_shape, kernel_size=2, filters=40, dilation_depth=9):\n self.out_act = 'softmax'\n\n if len(input_shape) != 2:\n print(\"are you sure this is a time series..\")\n return\n if len(output_shape) !=1:\n print(\"wrong output shape! Should be 1D\")\n\n self.input_shape = input_shape\n self.output_shape = output_shape\n self.kernel_size = kernel_size\n self.dilation = dilation_depth\n self.filters = filters\n self.model = self.build_model()\n\n\n def _make_tanh(self, dilation_rate):\n tanh = Conv1D(self.filters,\n self.kernel_size,\n dilation_rate = dilation_rate,\n padding='causal',\n name = 'dilated_conv_{}_tanh'.format(dilation_rate),\n activation='tanh')\n return tanh\n\n\n def _make_signmoid(self, dilation_rate):\n sigmoid = Conv1D(self.filters,\n self.kernel_size,\n dilation_rate = dilation_rate,\n padding='causal',\n name = 'dilated_conv_{}_sigmoid'.format(dilation_rate),\n activation='sigmoid')\n return sigmoid\n\n\n def residual_block(self, x, i):\n dr = self.kernel_size**i\n tanh = self._make_tanh(dr)\n sigm = self._make_signmoid(dr)\n z = Multiply(name='gated_activation_{}'.format(i))([fn(x) for fn in [tanh, sigm]])\n skip = Conv1D(self.filters, 1, name = 'skip_{}'.format(i))(z)\n res = Add(name = 'residual_{}'.format(i))([skip, x])\n return res, skip\n\n\n def get_model(self):\n return self.model\n\n\n def build_model(self):\n inp = Input(shape = self.input_shape)\n skips = []\n x = Conv1D(self.filters, 2, dilation_rate=1, padding='causal', name = 'dilate_1')(inp)\n x = BatchNormalization()(x)\n for i in range(1, self.dilation + 1):\n x, skip = self.residual_block(x, i)\n skips.append(skip)\n x = Add(name='skips')(skips)\n x = Activation('relu')(x)\n x = Conv1D(self.filters, 3, strides=1, padding='same', name = 'conv_5ms', activation='relu')(x)\n x = BatchNormalization()(x)\n x = AveragePooling1D(3, padding='same', name='downsample')(x)\n x=Dropout(0.5)(x)\n x=Conv1D(self.filters, 3, padding='same', activation='relu', name='upsample')(x)\n x = Conv1D(self.output_shape[0], 3, padding='same', activation='relu', name='target')(x)\n x = BatchNormalization()(x)\n x = AveragePooling1D(3, padding='same', name = 'downsample_2')(x)\n x=Dropout(0.5)(x)\n x = Conv1D(self.output_shape[0], self.input_shape[0] //10, padding='same', name = 'final')(x)\n x = BatchNormalization()(x)\n x = AveragePooling1D(self.input_shape[0] // 10, name = 'final_pool')(x)\n x=Dropout(0.5)(x)\n x = Reshape(self.output_shape)(x)\n out = Activation(self.out_act)(x)\n mod = Model(inp, out)\n return mod\n\n\ndef squeeze_excite_block(input):\n ''' Create a squeeze-excite block\n Args:\n input: input tensor\n filters: number of output filters\n k: width factor\n Returns: a keras tensor\n '''\n filters = input.shape[-1] # channel_axis = -1 for TF\n\n se = GlobalAveragePooling1D()(input)\n se = Reshape((1, filters))(se)\n se = Dense(filters // 16, activation=Mish(), kernel_initializer='he_normal', use_bias=False)(se)\n se = Dense(filters, activation='sigmoid', kernel_initializer='he_normal', use_bias=False)(se)\n se = multiply([input, se])\n return se\n\n\ndef build_fcnn_lstm(n_time, n_classes, n_cells=8):\n '''\n build_fcnn_lstm:\n -----------------\n builds a fully connected convolutional lstm, following some paper and\n medium article. Probably not correct. But runs\n args:\n n_time: number of timesteps\n n_classes: number of classes\n n_cells: number of lstm cells\n outputs:\n non compiled model\n '''\n ip = Input(shape=(n_time,16))\n\n x = Masking()(ip)\n x = LSTM(n_cells, recurrent_dropout=0.8, return_sequences=True)(x)\n x = Attention()(x)\n x = Dropout(0.8)(x)\n y = Permute((2,1))(ip)\n\n y = Conv1D(128,8, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Mish()(y)\n y = squeeze_excite_block(y)\n\n\n y = Conv1D(256,5, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Mish()(y)\n y = squeeze_excite_block(y)\n\n\n y = Conv1D(128,3, padding='same', kernel_initializer='he_uniform')(y)\n y = BatchNormalization()(y)\n y = Mish()(y)\n\n y = GlobalAveragePooling1D()(y)\n\n x = concatenate([x,y])\n\n out = Dense(n_classes, activation='softmax')(x)\n\n model = Model(ip, out)\n model.summary()\n\n return model\n\n\ndef build_conv_rnn(n_time, n_classes, filters=[20, 64, 64, 64],\n kernels=[7,5,5,5], lstm=[52,52]):\n '''\n build_conv_rnn\n ----------------\n builds a conv_rnn\n args:\n n_time: timesteps,\n n_classesL num classes\n filters: list of filters to use\n kernels=list of kernels to use\n lstm: list of lstm sizes\n outputs:\n not compiled model\n '''\n inputs = Input((n_time, 16))\n x = inputs\n for f, k in zip(filters, kernels):\n x = TimeDistributed(Conv1D(filters=f, kernel_size=k, activation='relu'))(x)\n x = TimeDistributed(Dropout(0.5))(x)\n x = TimeDistributed(MaxPooling1D(pool_size=2))(x)\n x = TimeDistributed(Flatten())(x)\n for l in range(len(lstm)):\n seq = True if (l != len(lstm)-1) else False\n x = LSTM(lstm[l], dropout=0.2, return_sequences=seq)\n x = Dropout(0.5)(x)\n x = Dense(100, activation='relu')(x)\n outputs = Dense(n_classes, activation='relu')(x)\n return Model(inputs, outputs)\n\n\ndef build_cnn(n_time, n_classes, filters=[20, 64, 64, 64],\n kernels=[7,5,5,5]):\n '''\n build_cnn\n ----------------\n builds a cnn\n args:\n n_time: timesteps,\n n_classesL num classes\n filters: list of filters to use\n kernels=list of kernels to use\n outputs:\n not compiled model\n '''\n inputs = Input((n_time, 16))\n x = inputs\n for f, k in zip(filters, kernels):\n x = Conv1D(filters=f, kernel_size=k, activation=Mish())(x)\n x = Dropout(0.5)(x)\n x = MaxPooling1D(pool_size=2)(x)\n x = Flatten()(x)\n x = Dropout(0.5)(x)\n x = Dense(100, activation=Mish())(x)\n outputs = Dense(n_classes, activation='softmax')(x)\n return Model(inputs, outputs)\n\n\ndef build_convlstm(n_time, n_classes,\n filters=[12,24,24],\n kernels=[(1,5), (1,3), (1,3)],\n dense=512):\n '''\n build_convlstm\n --------------\n args:\n n_time: timesteps\n n_classes: classes\n filters: list of filters\n kernels: list of tuple kernels\n dense: size of dense layer\n '''\n inputs = Input((None, 1, n_time, 16))\n x = inputs\n i = 1\n for f,k in zip(filters, kernels):\n seq = True if (i!=len(filters)) else False\n x = ConvLSTM2D(filters=f, kernel_size=k,\n data_format='channels_last',\n padding='same', return_sequences=seq)(x)\n if seq:\n x = BatchNormalization()(x)\n i += 1\n x = Flatten()(x)\n x = Dense(dense, activation='relu')(x)\n x = Dropout(0.5)(x)\n outputs = Dense(n_classes, activation='softmax')(x)\n return Model(inputs, outputs)\n\n","sub_path":"src/builders/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":8580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"257847248","text":"import discord\nfrom discord.ext import commands\n\nfrom cogs.utils import checks, text_formatter\n\n\nclass Admin:\n \"\"\"\n Misc owner functions\n \"\"\"\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(hidden=True)\n @checks.is_owner()\n async def get_ids(self, ctx):\n with open(\"data_files/userids.txt\", 'r+') as file:\n for user in ctx.guild.members:\n row = \"{0.name} -- ID: {0.id}\".format(user)\n file.write(str(row.encode('utf8'))+\"\\n\")\n await ctx.channel.send(\"Done\")\n\n @commands.command(hidden=True)\n @checks.is_owner()\n async def get_channel(self, ctx):\n channel = ctx.channel.id\n server = ctx.guild.id\n await ctx.channel.send(\"channel: \" + str(channel))\n await ctx.channel.send(\"server: \" + str(server))\n\n @commands.command(hidden=True)\n @checks.is_owner()\n async def log(self, ctx, log_name: str):\n try:\n log = discord.File(fp='logs/' + log_name + '.log')\n await ctx.channel.send(file=log)\n except FileNotFoundError:\n message = 'No log found with name {}'.format(log_name)\n await ctx.channel.send(text_formatter.inline(message))\n\n @commands.command(hidden=True)\n @checks.is_owner()\n async def status(self, ctx, *args):\n t = \" \".join(str(e) for e in args)\n await self.bot.change_presence(game=discord.Game(name=str(t), type=2))\n await ctx.channel.send(text_formatter.inline('Status updated to \"{}\"'.format(t)))\n\n\ndef setup(bot):\n bot.add_cog(Admin(bot))\n","sub_path":"cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"433442707","text":"import json\r\nimport math\r\n\r\n#this function reads content from the json file 'customers.json'. Could easily be modified to parse json data queried from an API.\r\ndef get_json_contents():\r\n customers={}\r\n try:\r\n f = open(input('Please enter filename: '), 'r')\r\n s = f.read()\r\n customers = json.loads(s)\r\n f.close()\r\n if(len(customers['customers']) < 1):\r\n print('There are no customers in this file!')\r\n except ValueError:\r\n print('Please try again with a valid JSON file.')\r\n except IOError as e:\r\n print(e)\r\n except KeyError as e:\r\n pass\r\n return customers\r\n\r\n#Calculates and returns the distance in km between target and search origin. Uses the central subtended angle method for increased accurcy due to the curvature of the earth.\r\n#can easily be modified for other spherical planets.\r\ndef calculate_distance(phi1, phi2, deltaLambda):\r\n pRadius = 6371\r\n a = math.degrees(math.acos(math.sin(math.radians(phi1))*math.sin(math.radians(phi2))+math.cos(math.radians(phi1))*math.cos(math.radians(phi2))*math.cos(math.radians(deltaLambda))))\r\n distance = 2*math.pi*pRadius*(a/360)\r\n return distance\r\n\r\n#Generates a python dictionary containing all customers within 100km of search origin.\r\ndef generate_available_customers(customers, searchOriginLatitude, searchOriginLongitude):\r\n availableCustomers = {}\r\n try:\r\n for element in customers['customers']:\r\n distance = calculate_distance(float(element['latitude']), searchOriginLatitude, abs(float(element['longitude']) - searchOriginLongitude))\r\n if(distance < 100):\r\n availableCustomers.update({element['name']:element['user_id']})\r\n except KeyError as e:\r\n pass\r\n return availableCustomers\r\n \r\n#Executes the program when called.\r\n#Prints out customer names and connected userID's, sorted by userID in ascending order.\r\n#Can easily be made to take a user input to set the coordinates of the search origin.\r\ndef main():\r\n listof = []\r\n while(True):\r\n i = input('Press 1 to begin, press 2 to exit: ')\r\n if (i == '1'):\r\n a = get_json_contents()\r\n b = generate_available_customers(a, 53.339428, -6.257664)\r\n bSortedKeys = sorted(b, key=b.get, reverse=False)\r\n for element in bSortedKeys:\r\n print (element,',', b[element])\r\n listof.extend([element, b[element]])\r\n elif (i == '2'):\r\n return listof\r\n","sub_path":"customerLocator/unitTest/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"368767541","text":"# -*- coding: utf-8 -*-\nfrom flask import Blueprint, render_template\nfrom .models import Novel\n\nnovel_bp = Blueprint('novel', __name__, template_folder='templates')\n\n\n@novel_bp.route('/')\ndef home():\n template_name = 'home.html'\n novels = Novel.query.all()\n return render_template(template_name, novels=novels)\n\n\n@novel_bp.route('/')\ndef novel(novel_id=None):\n template_name = 'novel.html'\n single_novel = Novel.query.get_or_404(novel_id)\n return render_template(template_name, novel=single_novel)\n","sub_path":"sNvl/novel/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"536303331","text":"import numpy as np\nimport os\nfrom visual_mpc.agent.benchmarking_agent import BenchmarkAgent\nfrom visual_mpc.envs.robot_envs.autograsp_env import AutograspEnv\nfrom visual_mpc.policy.cem_controllers.pixel_cost_controller import PixelCostController\nfrom visual_mpc.envs.robot_envs.util.topic_utils import IMTopic\nfrom visual_mpc.policy.cem_controllers.samplers import CorrelatedNoiseSampler\n\n\nenv_params = {\n 'camera_topics': [IMTopic('/other/image_raw', flip=False)], #, IMTopic('/bot/image_raw'), IMTopic('/bot2/image_raw')],\n 'cleanup_rate': -1,\n 'save_video': True\n\n}\n\nagent = {'type' : BenchmarkAgent,\n 'env': (AutograspEnv, env_params),\n 'T': 14, #number of commands per episodes (issued at control_rate / substeps HZ)\n 'image_height': 48,\n 'image_width': 64,\n 'make_final_recording': ''\n}\n\npolicy = {\n 'type': PixelCostController,\n 'replan_interval': 13,\n 'verbose_every_iter': True,\n 'zeros_for_start_frames': False,\n 'num_samples': 600,\n 'selection_frac': 2./3,\n 'predictor_propagation': True, # use the model get the designated pixel for the next step!\n 'nactions': 13,\n \"sampler\": CorrelatedNoiseSampler,\n 'context_action_weight': [2, 2, 0.05, 2],\n 'initial_std': [0.05, 0.05, 0.2, np.pi / 10, 1],\n\n \"model_params_path\": \"~/models/sawyer_only/experiment_state-2019-06-26_01-33-31.json\",\n \"model_restore_path\": \"~/models/sawyer_only/checkpoint_210000/model-210000\",\n}\n\nconfig = {\n \"experiment_name\": \"all_views_heldout\",\n 'traj_per_file':128,\n 'save_data': True,\n 'save_raw_images' : True,\n 'start_index':0,\n 'end_index': 30000,\n 'agent': agent,\n 'policy': policy,\n 'ngroup': 1000,\n 'nshuffle' : 200\n}\n","sub_path":"experiments/robonet/view_generalization/all_views.py","file_name":"all_views.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"435448800","text":"import sys, pygame, random\nfrom pygame.locals import *\nfrom shortest_path import *\n\n\nclass Player:\n '''\n move_x: moves player by a specified no. of pixels in x direction\n\n move_y: moves player by a specified no. of pixels in y direction\n\n onScreen: check if player is within the borders of the screen\n\n movePlayer: update player position, making sure the player is in valid\n positions depending on where it is located\n\n isWall: check if player's next position is valid i.e. not into a maze wall\n\n drawPlayer: draw the player to the screen\n '''\n def __init__(self,screen,color,startx,starty,scale,score):\n self.display = screen\n self.color = color\n self.x = startx\n self.y = starty\n self.scale = scale\n\n self.points = score\n\n self.powers = {\"invisible\":None, \"slowdown\":None, \"speedup\":None, \"exitpath\":None,\"double\":None}\n self.state = \"Ready\" # Ready, Inside, Outside, Caught\n\n def move_x(self,dist):\n self.x += dist\n\n def move_y(self,dist):\n self.y += dist\n\n def onScreen(self,max_x,max_y):\n if self.x < 0:\n self.x = 0\n if self.x > max_x - self.scale:\n self.x = max_x - self.scale\n if self.y < 0:\n self.y = 0\n if self.y > max_y - self.scale:\n self.y = max_y - self.scale\n\n def movePlayer(self,width,height,maze):\n # checking all pressed keys\n keys = pygame.key.get_pressed()\n # update position of player based on which key is presed\n if (keys[pygame.K_UP] or keys[pygame.K_w]):\n if self.powers['invisible'] is None:\n if not self.isWall(1,-self.scale,maze):\n self.move_y(-self.scale)\n else: self.move_y(-self.scale)\n elif (keys[pygame.K_DOWN] or keys[pygame.K_s]):\n if self.powers['invisible'] is None:\n if not self.isWall(1,self.scale,maze):\n self.move_y(self.scale)\n else: self.move_y(self.scale)\n elif (keys[pygame.K_RIGHT] or keys[pygame.K_d]):\n if self.powers['invisible'] is None:\n if not self.isWall(0,self.scale,maze):\n self.move_x(self.scale)\n else: self.move_x(self.scale)\n elif (keys[pygame.K_LEFT] or keys[pygame.K_a]):\n if self.powers['invisible'] is None:\n if not self.isWall(0,-self.scale,maze):\n self.move_x(-self.scale)\n else: self.move_x(-self.scale)\n\n # keep player on screen\n if self.powers['invisible']:\n self.onScreen(width,maze.height)\n else: self.onScreen(width,height)\n\n def isWall(self,dir,dist,maze):\n '''Check if the player's current position and end position\n exits in the maze's path'''\n # 0 --> x\n # 1 --> y\n if dir == 0:\n next_pos = (self.x+dist,self.y)\n elif dir == 1:\n next_pos = (self.x,self.y+dist)\n\n next_cellx = next_pos[0]//self.scale\n next_celly = next_pos[1]//self.scale\n next_cell = maze.cells_x*next_celly + next_cellx\n\n curr_cellx = self.x//self.scale\n curr_celly = self.y//self.scale\n curr_cell = maze.cells_x*curr_celly + curr_cellx\n\n #print('next cell', next_cell)\n\n # if we're not in the maze yet...\n if self.y >= maze.height:\n if dir == 0 or next_cell > len(maze.grid)-1: # moving horizontally or not in maze yet\n return False\n elif self.x == maze.width//2: # valid move into the maze only through entrance\n self.state = \"Inside\" # update the state of the player so we now he's inside\n return False\n else: return True # invalid move into the maze\n\n # else, if we are in the maze...\n elif self.y < maze.height:\n if next_cell > len(maze.grid) - 1 or next_cell < 0: # above the maze makes next cell negative\n if self.x == maze.width//2 and next_cell > 0:\n self.state = 'Outside' # update player state so we know he has left the maze\n return False\n else: return True\n else:\n try:\n if curr_cell in maze.path[next_cell] or next_cell in maze.path[curr_cell]: # valid move inside maze\n return False\n else:\n return True # invalid move in or out of the maze\n except KeyError:\n return False\n\n def drawPlayer(self):\n pygame.draw.rect(self.display,self.color,(self.x,self.y,\n self.scale,self.scale))\n\n\nclass Computer:\n def __init__(self,screen,color,startx,starty,scale):\n self.x = startx\n self.y = starty\n self.display = screen\n self.color = color\n self.scale = scale\n self.shape = 0\n\n def moveComputer(self,x,y):\n self.x = x\n self.y = y\n\n def draw(self):\n '''Alternate between what shape the computer player is drawn as\n to make it look cool'''\n if self.shape is 0:\n pygame.draw.rect(self.display,self.color,(self.x,self.y,\n self.scale,self.scale))\n self.shape = 1\n\n elif self.shape is 1:\n r = self.scale//2\n pygame.draw.circle(self.display,self.color,(self.x+r,self.y+r),r//2)\n self.shape = 2\n\n else:\n v1 = [self.x,self.y+self.scale]\n v2 = [self.x+self.scale//2,self.y]\n v3 = [self.x+self.scale,self.y+self.scale]\n poly = [v1,v2,v3]\n pygame.draw.polygon(self.display,self.color,poly)\n self.shape = 0\n\n\nclass MazePowerUp:\n '''\n draw: draw Power Up on the screen\n '''\n\n def __init__(self,maze,cell,display):\n self.display = display\n self.scale = maze.scale\n\n #self.time = None # how long the effects of the power up last\n\n powers = [\"invisible\", \"slowdown\", \"speedup\", \"exitpath\",\"double\"]\n rand_state = random.randint(0, len(powers)-1)\n self.type = powers[rand_state]\n\n # Invisible: You get to go through walls.\n if self.type == \"invisible\":\n self.defaultColor = (104,221,229) # color when object has not been obtained\n self.time = 5 # only lasts 5 seconds\n self.descriptor = \"Invisibility\"\n # Slowdown time\n elif self.type == \"slowdown\":\n self.defaultColor = (255,255,213) # color when object has not been\n self.time = 5 # only lasts 5 seconds\n self.descriptor = \"Slow Down Time\"\n # Speedup time\n elif self.type == \"speedup\":\n self.defaultColor = (146,243,172) # color when object has not been obtained\n self.time = 5 # only lasts 5 seconds\n self.descriptor = \"Speed Up Time\"\n # show exit path\n elif self.type == \"exitpath\":\n self.defaultColor = (255,102,113) # color when object has not been obtained\n self.time = 100000\n self.descriptor = \"Press F for ExitPath\"\n elif self.type == \"double\":\n self.defaultColor = (255,250,87) # color when object has not been obtained\n self.time = 10 # only lasts 5 seconds\n self.descriptor = \"POINTS x2 !!!\"\n\n\n self.color = self.defaultColor\n\n self.cell = cell # cell on maze grid of the object\n\n self.x = (self.cell%maze.cells_x)*maze.scale+maze.scale\n self.y = (self.cell//maze.cells_x)*maze.scale+maze.scale\n\n\n def draw(self):\n '''Draw the object to the screen'''\n num = self.scale//10\n num2 = self.scale//2\n pygame.draw.circle(self.display,self.color,(self.x+num2,self.y+num2), num2//2)\n\n\nclass Menu:\n '''\n addItem: add an item to the menu with an idx\n\n selectTarget: selects the specified item\n\n shift: shift the display in a direction\n\n update: updates the display of the menu\n\n draw: draw the menu to the screen\n '''\n\n def __init__(self,x,y,display_size,color,title='Title'):\n # position of selection on screen (middle)\n self.x = x\n self.y = y\n self.display_x = display_size[0]\n self.display_y = display_size[1]\n\n self.items = [] # list of the selections\n\n self.title = title\n self.title_color = color\n self.title_font = pygame.font.Font(None,50)\n self.title_image = self.title_font.render(self.title, True, self.title_color)\n\n self.target = None\n self.targetidx = 0\n self.center = len(self.items)//2\n\n def selectTarget(self,item_idx):\n if item_idx > len(self.items)-1:\n item_idx = 0\n if item_idx < 0:\n item_idx = len(self.items)-1\n if self.target != None:\n # index of previous target\n prev = self.items.index(self.target)\n # deselect the current target\n self.target.deselect()\n # update the target\n self.target = self.items[item_idx]\n # select the new target\n self.target.select()\n\n def addItem(self,item):\n # append the item to the list of items\n self.items.append(item)\n if len(self.items) == 1:\n self.target = item\n pass\n\n def shift(self):\n pop_height = self.display_x//13\n # basically defining where item.x and item.y are\n for idx,item in enumerate(self.items):\n #print('idx, item',idx,item)\n item.x = self.x - (self.center - idx)*100\n #print('item.x for item[',idx,'] = ',item.x)\n if item == self.target:\n item.y = self.y - pop_height\n else: item.y = self.y\n\n def update(self):\n '''Update to the new nature of the menu'''\n self.shift()\n\n def draw(self,display):\n ''' Draw the title and items '''\n display.blit(self.title_image,(20,10))\n for item in self.items:\n item.draw(display)\n\n\nclass MenuItem:\n\n def __init__(self,item=\"Item\"):\n self.item = item\n self.default_color = (191,193,195) # silver-ish\n self.color = (191,193,195) # starts as default color\n self.highlight_color = (55,180,253) # bright blue\n # these are needed for the Menu class\n self.x = 0\n self.y = 0\n self.font = pygame.font.Font(None, 20)\n self.image = self.font.render(self.item, True, self.color)\n\n def select(self):\n self.color = self.highlight_color\n # have to redraw the text with new color\n self.font = pygame.font.Font(None, 20)\n self.image = self.font.render(self.item, True, self.color)\n\n def deselect(self):\n self.color = self.default_color\n # have to redraw the text with new color\n self.font = pygame.font.Font(None, 20)\n self.image = self.font.render(self.item, True, self.color)\n\n def draw(self, display):\n display.blit(self.image,(self.x,self.y))\n\n\nclass Maze:\n '''\n update: this is where all the maze generation takes place. Upon Continually\n calling this method, the maze is updated and shaped to the screen\n until all maze cells have been accounted for and are used in the maze\n\n drawMaze: maze is drawn by calling the update method until all cells have\n been visited. Borders are then drawn and a screenshot of the Maze\n is saved.\n\n onMaze: check if coordinate is within the field of the maze boundaries\n\n '''\n\n def __init__(self,screen,size,move_size,color): # maybe also difficulty????\n\n self.state = 'unfinished'\n\n self.grid = [] # our maze grid, like a directed graph\n self.display = screen\n self.image = None\n self.color = color\n #self.display.fill((0,0,0,0))\n\n self.width = size[0] # in pixels\n self.height = size[1]# in pixels\n self.scale = move_size\n self.cells_x = self.width//self.scale\n self.cells_y = self.height//self.scale\n\n self.total_cells = self.cells_x*self.cells_y # total number of cells in the grid\n\n #self.current_cell = random.randint(0,self.total_cells-1)\n\n # the current visited cell\n self.current_cell = (self.cells_y)*(self.cells_x)-self.cells_x//2 # gross\n self.visited_cells = 1 # start with only the starting cell as visited\n self.todo = [] # used to keep track of cells which need to be revisited\n\n self.directions = [(-1,0),(0,1),(1,0),(0,-1)] # used for finding neighbouring cells\n\n self.path = {} # stores valid moves withing the maze (unirected graph)\n self.objects = [] # to be filled with 'MazeObject'\n\n def update(self,color):\n '''This is a DFS implementation of maze generation with multiple\n random generation elements mixed in. The first aspect of randomness\n allows for there to be a much more widespread search rather than a\n long hallway with small rooms. The second random aspect allows\n for loops in the maze and somoetimes square areas which are 2x2 cells.\n\n A BFS implementation of the maze generation would most likely result in\n a maze which has many long hallways, and this is definetly not what we\n wanted for our maze game.\n\n Note: this can be done recursivley but we're doing it with a todo list\n instead with a while loop. It just happened to be that way, no\n particular reason why.'''\n\n #print('visited', self.visited_cells)\n #print('total', self.total_cells+1800//self.scale)\n\n #\n if self.visited_cells >= self.total_cells + 1800//self.scale:\n self.current_cell = 0\n self.todo = 0\n self.state = 'finished'\n return\n\n # position according to the grid i.e which cell number in each direction\n x_pos = self.current_cell % self.cells_x # the x position on the grid\n y_pos = self.current_cell // self.cells_x # this gives us the y...seriously\n\n # first, we want to make a list of neighbouring cells!\n neighbours = []\n\n # search cells in every direction from the current cell\n for direction in self.directions:\n neighb_x = x_pos + direction[0]\n neighb_y = y_pos - direction[1]\n\n # make sure neighbouring cell is on the maze\n if self.onMaze(neighb_x,neighb_y):\n # have to check to make sure the neighbouring node hasn't\n # already been visited\n # Note: cell on the grid of the pixel coordinate x,y will be\n # (self.cells_x*y)+x\n neighb_cell = self.cells_x*neighb_y + neighb_x # gives cell number\n\n if self.grid[neighb_cell] == 0:\n # we have found an unvisited neighbour!\n neighbours.append((neighb_cell,direction))\n else:\n # attempt at generating more loops in the maze by\n # rechecking neighbouring cells which have already been\n # visited\n num2 = random.randint(0,50)\n if num2 is 1:\n neighbours.append((neighb_cell,direction))\n\n # if the cell has neighbours, choose a random one!\n if len(neighbours) > 0:\n rand_int = random.randint(0,len(neighbours)-1)\n neighb_cell, direction = neighbours[rand_int] # cell number\n\n # cell to pixel conversion\n y_pixel = y_pos*self.scale\n x_pixel = x_pos*self.scale\n ny_pixel = (neighb_cell//self.cells_x)*self.scale\n nx_pixel = (neighb_cell%self.cells_x)*self.scale\n\n # Break down the wall like a white walker\n if direction == (0,1): # Up, break wall below\n pygame.draw.line(self.display,color,(x_pixel+1,y_pixel),(x_pixel+self.scale-1,y_pixel))\n if direction == (0,-1): # Down, break wall above\n pygame.draw.line(self.display,color,(x_pixel+1,y_pixel+self.scale),(x_pixel+self.scale-1,y_pixel+self.scale))\n if direction == (1,0): # Right, break wall to the left\n pygame.draw.line(self.display,color,(x_pixel+self.scale,y_pixel+1),(x_pixel+self.scale,y_pixel+self.scale-1))\n if direction == (-1,0): # Left, break wall to the right\n pygame.draw.line(self.display,color,(x_pixel,y_pixel+1),(x_pixel,y_pixel+self.scale-1))\n\n # if path for this cell has not yet been established,\n # initialize its list of neighbours in the maze path\n if self.current_cell not in self.path:\n self.path[self.current_cell] = []\n # add the valid move to the path\n if neighb_cell not in self.path[self.current_cell]:\n self.path[self.current_cell].append(neighb_cell)\n\n # must have an undirected graph so the player can move back and forth\n if neighb_cell not in self.path:\n self.path[neighb_cell] = []\n # add the valid move to the path\n if self.current_cell not in self.path[neighb_cell]:\n self.path[neighb_cell].append(self.current_cell)\n\n self.grid[neighb_cell] = 1 # mark neighbouring cell as visited\n\n self.todo.append(self.current_cell) # add the current cell to stack so it can be revisited\n\n # This randomizes which cell we move from\n # Without this randomization, we get a maze with basically\n # one long path through it and a bunch of tiny sub-paths\n # This is because of the nature of a Depth First Search!\n # So if we instead search from random cells each time, the maze\n # will be much more diverse and spread out :)\n num = random.randint(0,1)\n if num == 0 and len(self.todo) > 0:\n #random.shuffle(self.todo)\n #self.current_cell = self.todo.pop()\n\n p = random.randint(0,len(self.todo)-1)\n self.current_cell = self.todo[p]\n\n self.todo.append(neighb_cell)\n\n else:\n self.current_cell = neighb_cell # update the current cell to be the random neighbour\n\n self.visited_cells += 1 # add to visited cells\n\n # else, if there are no neighbours for the current cell...\n else:\n try:\n # search the next cell in the todo list!\n self.current_cell = self.todo.pop()\n except IndexError: # when there are no more cells to search from\n self.current_cell = -1\n\n def drawMaze(self,screen,window_color):\n ''' Continually updates until entire maze is drawn to the screen\n A screenshot of the maze is then captured to be blitted in the\n main game loop '''\n\n screen.fill(window_color)\n #FPSClock = pygame.time.Clock()\n\n # first, draw the maze grid with all walls attached\n for y in range(self.cells_y): # 0 to 390 pixels\n # horizontal lines\n pygame.draw.line(self.display, self.color, (0, y*self.scale), (self.width, y*self.scale))\n for x in range(self.cells_x): # 0 to 630 pixels\n if y == 0:\n # vertical lines\n pygame.draw.line(self.display, self.color, (x*self.scale,0), (x*self.scale,self.height-1))\n self.grid.append(0) # fill maze grid with 0's\n\n self.grid[self.current_cell] = 1 # mark starting cell as visited\n\n while self.state != 'finished':\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n self.update(window_color) # update the maze and draw it\n pygame.display.update()\n #FPSClock.tick(30)\n\n # Edges of the maze (looks neater)\n # draw right border\n pygame.draw.line(self.display, self.color, (self.width-1,0), (self.width-1,self.height))\n # draw bottom border\n pygame.draw.line(self.display,self.color,(0,self.height),(self.width,self.height))\n # draw top border\n pygame.draw.line(self.display,self.color,(0,0),(self.width,0))\n # draw single entrance\n pygame.draw.line(self.display,window_color,(self.width//2,self.height),(self.width//2+self.scale,self.height))\n\n\n pygame.image.save(screen,\"maze.jpg\") # save a screenshot of maze\n self.image = pygame.image.load(\"maze.jpg\")\n self.image = self.image.convert() # clean up the screenshot\n\n def onMaze(self,x,y):\n ''' Check if coordinate is within the bounds of the maze '''\n if x >= 0 and y >= 0 and x < self.cells_x and y < self.cells_y:\n return True\n\n\nclass MazeObject:\n '''\n Point objects on the Maze\n\n '''\n\n def __init__(self,maze,cell,display):\n self.display = display\n self.size = maze.scale\n self.scale = maze.scale\n\n self.state = \"Idle\"\n\n self.defaultColor = (222,145,242) # color when object has not been obtained\n self.gotColor = (63,63,63) # color when player obtains object\n self.color = self.defaultColor\n\n self.cell = cell # cell on maze grid of the object\n\n self.x = (self.cell%maze.cells_x)*maze.scale\n self.y = (self.cell//maze.cells_x)*maze.scale\n\n # how much each object is worth, related to how far away it is\n try: self.points = maze.total_cells//(self.cell//maze.cells_x)\n except ZeroDivisionError: self.points = maze.total_cells//2\n\n def obtained(self):\n ''' Alter the object such that it has been obtained by the player'''\n self.color = self.gotColor\n self.state = \"Obtained\"\n\n def draw(self):\n '''Draw the object to the screen'''\n num = self.scale//10\n num2 = self.scale//2\n pygame.draw.circle(self.display,self.color,(self.x+num2,self.y+num2),num2//2)\n","sub_path":"game_classes.py","file_name":"game_classes.py","file_ext":"py","file_size_in_byte":22074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"111607288","text":"import requests\nimport sys\nimport json\n\n\nclass BaiduTranslate(object):\n def __init__(self, query_string):\n self.query_string = query_string\n self.basetrans_url = \"http://fanyi.baidu.com/basetrans\"\n self.langdetect_url = \"http://fanyi.baidu.com/langdetect\"\n self.headers = {\n \"User-Agent\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1\"}\n\n def parse_url(self, url, data): # 发送请求,获取响应\n response = requests.post(url, headers=self.headers, data=data)\n return json.loads(response.content.decode())\n\n def prepare_data(self):\n data = {\"query\": self.query_string} # 语言检测 post数据\n dict_ret = self.parse_url(self.langdetect_url, data)\n if dict_ret['lan'] == \"zh\":\n post_data = {\n \"query\": query_string,\n \"from\": \"zh\",\n \"to\": \"en\",\n }\n else:\n post_data = {\n \"query\": query_string,\n \"from\": \"en\",\n \"to\": \"zh\",\n }\n return post_data\n\n def run(self):\n # 1 语言检测\n # 1.1 准备post数据 url data\n # 1.2 发送语言检测的请求 获取响应\n # 2 准备待翻译的请求数据\n post_data = self.prepare_data()\n # 3 发送post请求获取响应\n tran_dict = self.parse_url(self.basetrans_url, post_data)\n # 4 提取数据\n ret = tran_dict[\"trans\"][0][\"dst\"]\n print(\"<{}>的翻译结果是:{}\".format(self.query_string, ret))\n\n\nif __name__ == '__main__':\n query_string = sys.argv[1]\n trans = BaiduTranslate(query_string)\n trans.run()\n","sub_path":"fanyi.py","file_name":"fanyi.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"516899748","text":"from os import listdir\nfrom os.path import isfile, join\nfrom subprocess import run, PIPE\nfrom typing import List\n\nfrom .... import R\n\nimport kfp\n\nimport pytest\n\n\"\"\"\nTo run these tests from your terminal, go to the tests directory and run: \n`python -m pytest -s -n 3 run_integration_tests.py`\n\nThis script runs all the flows in the `flows` directory. It creates\neach kfp run, waits for the run to fully complete, and prints whether\nor not the run was successful. It also checks to make sure the logging\nfunctionality works.\n\nMore specifically, the tests spawn KFP runs and ensure the spawning processes\nhave a returncode of 0. If any test fails within KFP, an exception\nis raised, the test fails, and the user can access the run link to the failed\nKFP run.\n\nParameters:\n-n: specifies the number of parallel processes used by PyTest.\n\nSometimes, the tests may fail on KFP due to resource quota issues. If they do,\ntry reducing -n (number of parallel processes) so less simultaneous\nKFP runs will be scheduled.\n\n\"\"\"\n\n\ndef _python():\n if R.use_r():\n return \"python3\"\n else:\n return \"python\"\n\n\ndef obtain_flow_file_paths(flow_dir_path: str) -> List[str]:\n file_paths = [\n file_name\n for file_name in listdir(flow_dir_path)\n if isfile(join(flow_dir_path, file_name)) and not file_name.startswith(\".\")\n ]\n return file_paths\n\n\n@pytest.mark.parametrize(\"flow_file_path\", obtain_flow_file_paths(\"flows\"))\ndef test_flows(pytestconfig, flow_file_path: str) -> None:\n full_path = join(\"flows\", flow_file_path)\n # In the process below, stdout=PIPE because we only want to capture stdout.\n # The reason is that the click echo function prints to stderr, and contains\n # the main logs (run link, graph validation, package uploading, etc). We\n # want to ensure these logs are visible to users and not captured.\n # We use the print function in kfp_cli.py to print a magic token containing the\n # run id and capture this to correctly test logging. See the\n # `check_valid_logs_process` process.\n\n test_cmd = (\n f\"{_python()} {full_path} --datastore=s3 kfp run \"\n f\"--wait-for-completion --workflow-timeout 1800 \"\n f\"--max-parallelism 3 --experiment metaflow_test --tag test_t1 \"\n )\n if pytestconfig.getoption(\"image\"):\n test_cmd += (\n f\"--no-s3-code-package --base-image {pytestconfig.getoption('image')}\"\n )\n\n run_and_wait_process = run(\n test_cmd,\n universal_newlines=True,\n stdout=PIPE,\n shell=True,\n )\n assert run_and_wait_process.returncode == 0\n\n return\n","sub_path":"metaflow/plugins/kfp/tests/run_integration_tests.py","file_name":"run_integration_tests.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"405262199","text":"def AddNewRecords():\n\twith open(\"FriendsData\", \"a\") as fd:\n\t\tprint(\"Please enter additional details.\")\n\t\tprint(\"When no more records are to be added, enter 'xxx' for first name\")\n\n\t\tfname = input(\"First Name: \")\n\t\twhile fname != \"xxx\":\n\t\t\tsname = input(\"Second Name: \")\n\t\t\temailaddr = input(\"Email Address: \")\n\t\t\tmobile = input(\"Mobile Number: \")\n\t\t\tfd.write(fname + \", \" + sname + \", \" + emailaddr + \", \" + mobile + \"\\n\")\n\t\t\tfname = input(\"First Name: \")\n\t\tfd.write(\"xxx\")\n\nAddNewRecords()\n","sub_path":"11 AddNewRecords.py","file_name":"11 AddNewRecords.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"218430657","text":"from django.conf.urls import url\nfrom .views import CoursesListView, CourseDetailView, CourseVideoView, FinishLessonView, QuestionsView\nfrom Exam.views import ExamView\n\nurlpatterns = [\n url(r'^$', CoursesListView.as_view(), name='list'),\n url(r'^detail/(?P\\d+)/$', CourseDetailView.as_view(), name='detail'),\n url(r'^video/(?P\\d+)/$', CourseVideoView.as_view(), name='video'),\n url(r'^finish_lesson/$', FinishLessonView.as_view(), name='finish_lesson'),\n url(r'^question/(?P.*)/$', QuestionsView.as_view(), name='questions'),\n url(r'^exam/(?P\\d+)/$', ExamView.as_view(), name='exam'),\n]\n","sub_path":"Courses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"185414493","text":"''' Gene page tests. '''\nfrom django.test import TestCase\nfrom django.core.urlresolvers import reverse\nfrom pydgin.tests.tests_pydgin import PydginTestUtils\n\n\nclass RegionPageTest(TestCase):\n\n def test_url(self):\n ''' Test the region page 404. '''\n url = reverse('region_page_params')\n self.assertEqual(url, '/region/')\n resp = self.client.get(url)\n self.assertEqual(resp.status_code, 404)\n\n def test_url2(self):\n ''' Test the region page 404. '''\n url = reverse('region_page_params')\n resp = self.client.get(url, {'r': 'ABC'})\n self.assertEqual(resp.status_code, 404)\n\n def test_url_region_id(self):\n ''' Test the region page. '''\n url = reverse('region_page_params')\n resp = self.client.get(url, {'r': '1p13.2_019'})\n self.assertEqual(resp.status_code, 200)\n self.assertIn(b'1p13.2', resp.content)\n self.assertContains(resp, '1p13.2')\n\n def test_hyperlinks(self):\n ''' Test example hyperlinks. '''\n PydginTestUtils.test_links_in_page(self, reverse('region_page_params'), data={'r': '1p13.2_019'})\n","sub_path":"pydgin/local_apps/region/tests/tests_region_page.py","file_name":"tests_region_page.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"85536062","text":"# SPDX-License-Identifier: WTFPL\n\nfrom __future__ import print_function\nimport sys\nimport os\nfrom pathlib import Path\n\nimport bottle\nimport webp3.conf\nimport webp3.app\n\n\ndef read_conf(environ):\n\tpath = environ.get('webp3.conf', os.environ.get('WEBP3_CONF', '/etc/webp3.conf'))\n\tif not os.path.exists(path):\n\t\traise RuntimeError('missing config file')\n\n\twith open(path) as conf:\n\t\troots = {}\n\t\tfor line in conf:\n\t\t\tline = line.rstrip()\n\n\t\t\ttry:\n\t\t\t\tkey, dest = line.split('=', 1)\n\t\t\texcept ValueError:\n\t\t\t\traise RuntimeError('lines must be in format NAME=PATH')\n\n\t\t\tif key in roots:\n\t\t\t\traise RuntimeError('duplicate key %r' % key)\n\n\t\t\troots[key] = Path(dest)\n\t\twebp3.conf.ROOTS = roots\n\n\twebp3.conf.BASE_URL = os.environ.get(\"WEBP3_BASEURL\")\n\n\ndef decorate(func):\n\tdef wrapper(environ, starter):\n\t\tread_conf(environ)\n\t\treturn func(environ, starter)\n\n\treturn wrapper\n\n\napplication = webp3.app.bapp\napplication.wsgi = decorate(application.wsgi)\n","sub_path":"webp3/webp3.wsgi","file_name":"webp3.wsgi","file_ext":"wsgi","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13679412","text":"# specify id\ny_id = 2\ntrack_id = 1\nfile_id = 53\nprefix = './'\n\n# import modules\nfrom xgboost import XGBRegressor\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport sys\nsys.path.insert(0, '../utils/')\nfrom training_utils import *\n\n# load files\ntest_x = np.load('../../X_test.npz')['arr_0']\ntrain_x = np.load('../../X_train.npz')['arr_0']\ntrain_y = np.load('../../Y_train.npz')['arr_0'][:, y_id]\nall_x = train_x.copy()\nall_y = train_y.copy()\nprint(test_x.shape, train_x.shape, train_y.shape)\n\n# pick only important data\nidx = {}\nwith open('../29/adaboost' + str(y_id) + '_feature.csv', 'r') as f:\n i = 0\n for lines in f:\n importance = float(lines.replace('\\n', '').split(',')[y_id])\n if i not in idx:\n idx[i] = 0\n idx[i] += importance\n i += 1\nwith open('../28/adaboost' + str(y_id) + '_feature.csv', 'r') as f:\n i = 0\n for lines in f:\n importance = float(lines.replace('\\n', '').split(',')[y_id])\n if i not in idx:\n idx[i] = 0\n idx[i] += importance\n i += 1\n\nwith open('../32/adaboost' + str(y_id) + '_feature.csv', 'r') as f:\n i = 0\n for lines in f:\n importance = float(lines.replace('\\n', '').split(',')[y_id])\n if i not in idx:\n idx[i] = 0\n idx[i] += importance\n i += 1\nwith open('../35/random_forest' + str(y_id) + '_feature.csv', 'r') as f:\n i = 0\n for lines in f:\n importance = float(lines.replace('\\n', '').split(',')[y_id])\n if i not in idx:\n idx[i] = 0\n idx[i] += importance\n i += 1\n \nidxx = [i[0] for i in idx.items() if i[1] > 1e-3]\nprint(len(idxx))\ntrain_x = train_x[:, idxx]\ntest_x = test_x[:, idxx]\nall_x = all_x[:, idxx]\nprint(train_x.shape, all_x.shape, test_x.shape)\n\n# split data\ntrain_x, mytest_x, train_y, mytest_y = train_test_split(train_x, train_y, test_size=0.052631578947368, random_state=1126)\n# train_x, val_x, train_y, val_y = train_test_split(train_x, train_y, test_size=0.055555555555554, random_state=1126)\n# print(train_x.shape, val_x.shape, mytest_x.shape, train_y.shape, val_y.shape, mytest_y.shape)\nprint(train_x.shape, mytest_x.shape, train_y.shape, mytest_y.shape)\n\n# define my own scorer for t2\n# actually it should be called error function here\nw = [300.0, 1.0, 200.0]\ndef scorer2(y_pred, y_true):\n return 'error', 1.0 * np.sum(np.abs(y_true.get_label() - y_pred) / y_true.get_label()) / len(y_pred)\n\n# define my own scorer for t1\ndef scorer(y_pred, y_true):\n return 'error', w[y_id] * np.sum(np.abs(y_true.get_label() - y_pred)) / len(y_pred)\n \n# define my own error function\ndef mae(y_true, y_pred): # ln(cosh(x))\n grad = np.tanh(y_pred - y_true)\n hess = 1 - grad * grad\n return grad, hess\n\ndef mae2(y_true, y_pred): # 2/k*ln(1+exp(kx))-x-2/k*ln(2), k=10\n grad = (np.exp(10 * (y_pred - y_true)) - 1) / (np.exp(10 * (y_pred - y_true)) + 1)\n hess = (20 * np.exp(10 * (y_pred - y_true))) / (np.exp(10 * (y_pred - y_true)) + 1) ** 2\n return grad, hess\n \nparams = {\n 'objective': mae,\n 'max_depth': 6,\n 'learning_rate': 0.1,\n 'verbosity': 20,\n 'tree_method': 'hist',\n 'predictor': 'cpu_predictor',\n 'n_estimators': 12000,\n 'n_jobs': -1,\n 'subsample': 0.75,\n 'booster': 'dart'\n}\nparams2 = {\n 'max_depth': 6,\n 'learning_rate': 0.1,\n 'verbosity': 20,\n 'tree_method': 'hist',\n 'predictor': 'cpu_predictor',\n 'n_estimators': 500,\n 'n_jobs': 1,\n 'subsample': 0.75,\n 'booster': 'dart'\n}\n\n# fit\nmodel = XGBRegressor(**params)\n# model.fit(scaled_x, scaled_y, eval_set=[(val_x, val_y)], eval_metric=scorer, early_stopping_rounds=None)\n# model.fit(train_x, train_y, eval_set=[(val_x, val_y)], eval_metric=scorer, early_stopping_rounds=None)\nmodel.fit(train_x, train_y)\n# model.fit(scaled_x, scaled_y)\n\n# write result\n\nf = open(f'{prefix}{file_id}_result_y{y_id}_{track_id}.txt', 'w')\n\nprint(\"ein1:\", err1_calc(model.predict(train_x), train_y, y_id), file=f)\n# print(\"eval1:\", err1_calc(model.predict(val_x), val_y, y_id), file=f)\nprint(\"etest1:\", err1_calc(model.predict(mytest_x), mytest_y, y_id), file=f)\nprint(\"eall1:\", err1_calc(model.predict(all_x), all_y, y_id), file=f)\n\nprint(\"ein2:\", err2_calc(model.predict(train_x), train_y), file=f)\n# print(\"eval2:\", err2_calc(model.predict(val_x), val_y), file=f)\nprint(\"etest2:\", err2_calc(model.predict(mytest_x), mytest_y), file=f)\nprint(\"eall2:\", err2_calc(model.predict(all_x), all_y), file=f)\n\nf.close()\n\n# write files\nwrite_prediction(f'{prefix}{file_id}_train_y{y_id}_{track_id}.txt', 'w', model.predict(all_x).reshape((47500, 1)).astype('str'))\nwrite_prediction(f'{prefix}{file_id}_test_y{y_id}_{track_id}.txt', 'w', model.predict(test_x).reshape((2500, 1)).astype('str'))\nmodel.save_model(f'{prefix}{file_id}_model_y{y_id}_{track_id}.model')\n\n\n","sub_path":"53/code_2.py","file_name":"code_2.py","file_ext":"py","file_size_in_byte":4837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"91303277","text":"from bs4 import BeautifulSoup\nfrom bookparser import set_details_from\nimport os\n\ndef extract(n):\n \"\"\"Extract books from n HTML files. Returns list of books.\"\"\"\n data_dir = os.environ.get('DATA_DIR')\n books = []\n for i in range(1, n+1):\n # Parse HTML file\n html_doc = open('%s/book%d.html' % (data_dir, i))\n parsed_html = BeautifulSoup(html_doc, 'html.parser')\n book = set_details_from(parsed_html) # Dictionary with key, value pairs of book details\n books.append(book) # List of dictionaries. List of books\n return books\n","sub_path":"src/app/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"56634354","text":"from socket import *\nimport Calculate #\nimport Trilateration\ndef Setting(ip,port):\n serverSock = socket(AF_INET, SOCK_STREAM)\n print(\"소켓시작\")\n serverSock.bind((ip, port))\n print(\"bind\")\n serverSock.listen(1)\n print(\"listen\")\n\n while(1):\n connectionSock, addr = serverSock.accept()\n\n print(str(addr),'에서 접속이 확인되었습니다.')\n \n data = connectionSock.recv(1024).decode()\n data_2 = Calculate.in_data(data)\n data_2 = data_2.split(\",\")\n data_3 = Trilateration.Trilateration(data_2) # 삼변측량알고리즘 적용\n return data_3 #위치좌표 X,Y반\n\n","sub_path":"민수part/위치좌표도출/위치좌표계산 알고리즘/Simple_server.py","file_name":"Simple_server.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"527667528","text":"import colorlog\n\nlogger_format = \"%(white)s[%(asctime)s] %(bold_blue)s%(name)-15s%(white)s %(log_color)s%(levelname)-10s%(white)s %(message)s\"\nlogger_datefmt = \"%Y-%m-%d %H:%M:%S\"\nlogger_level = \"DEBUG\"\n\n\ndef create_logger(name):\n handler = colorlog.StreamHandler()\n handler.setFormatter(colorlog.ColoredFormatter(\n logger_format,\n datefmt=logger_datefmt,\n log_colors={\n 'DEBUG': 'cyan',\n 'INFO': 'green',\n 'WARNING': 'yellow',\n 'ERROR': 'red',\n 'CRITICAL': 'bold_red',\n },\n ))\n\n logger = colorlog.getLogger(name)\n logger.addHandler(handler)\n logger.setLevel(logger_level)\n\n return logger\n","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"645157673","text":"#! /usr/bin/env python\n\nfrom curtsies import Input\n\ndef main():\n with Input(keynames='curses') as input_generator:\n for e in input_generator:\n if e=='w': print(\"go front\")\n if e=='s': print(\"go back\")\n print()\n\nif __name__ == '__main__':\n main()","sub_path":"catkin_ws/src/control/src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"389250474","text":"import sys\nfrom utils import build_msg\n\n\nclass Compiler:\n name = \"\"\n path = \"\"\n bin = \"\"\n dlink = \"\"\n slink = \"\"\n toolsValues = {}\n coptions = {}\n cflags = {}\n lflags = {}\n debug_flags = {}\n\n def __init__(self, name, path=0, bin=0, dlink=0, slink=0, coptions=0,\n cflags=0, lflags=0, libs=0, toolsValues=0, debug_flags=0):\n self.name = name\n self.path = path\n self.bin = bin\n self.dlink = slink\n self.cflags = cflags\n self.lflags = lflags\n self.libs = libs\n self.toolsValues = toolsValues\n self.coptions = coptions\n self.debug_flags = debug_flags\n\n# Defining the compilers\ncompilers = {}\n# GCC\ncompilers['gcc'] = Compiler(\n name='gcc',\n coptions={\n 'all': [\n '-static-libgcc',\n '-std=gnu99' # gnu99 for c99 + gcc extensions (e.g: typeof)\n ],\n 'Windows': [],\n 'Linux': []},\n cflags={'all': {}, 'Windows': {}, 'Linux': {'_GNU_SOURCE': None}},\n lflags={'all': [], 'Windows': [], 'Linux': []},\n libs={'all': [], 'Windows': [], 'Linux': ['rt', 'pthread', 'm']},\n toolsValues={'Windows': ['mingw'], 'Linux': ['gcc']},\n debug_flags={'all': [\"-g\"], 'Windows': [], 'Linux': []}\n)\n\n\ndef add_compiler_field(env, os, compiler_name, attribute, compiler_field):\n \"\"\"\n Adds a particular compiler options field to the build environment\n Depending on the build environment attribute that this affects\n the function either updates a dictionary or extends a list.\n\n --env: The build environment to extend/update\n --os: The operating system the library compiles in\n --compiler_name: The name of the compiler\n --attribute: The environment attribute we are changing. For example\n 'CCFLAGS' or 'CPPDEFINES'\n --compiler_field: The compiler field we are using. For example\n 'debug_flags' or 'libs'\n \"\"\"\n cdict = compilers[compiler_name].__dict__\n l = ['all', os]\n for v in l:\n if cdict[compiler_field][v] != []:\n if isinstance(env[attribute], dict):\n env[attribute].update(cdict[compiler_field][v])\n else:\n env[attribute].extend(cdict[compiler_field][v])\n\n\ndef remove_envvar_values(env, var, names):\n \"\"\"\n Removes a list of defined variable values (e.g. CPPDEFINES)\n from an environment\n \"\"\"\n defines = env[var]\n if isinstance(defines, dict):\n for n in names:\n try:\n defines.pop(n)\n except:\n pass\n else: # should be a list\n for n in names:\n try: # if it's simply a list element remove it\n defines.remove(n)\n except:\n pass\n\n for i, d in enumerate(defines):\n # lists can also contain tuples and dicts of defines\n if isinstance(d, tuple):\n if d[0] == n:\n defines.pop(i)\n break\n elif isinstance(d, dict):\n try:\n d.pop(n)\n except:\n pass\n\n env.Replace(var=defines)\n\n\ndef set_debug_mode(env, is_debug):\n if is_debug:\n env.Append(CCFLAGS=[\"-g\"])\n env.Append(CPPDEFINES={'RF_OPTION_DEBUG': None})\n remove_envvar_values(env, 'CPPDEFINES', ['NDEBUG'])\n # no optimizations\n env.Append(CCFLAGS=[\"-O0\"])\n remove_envvar_values(env, 'CCFLAGS', ['-O3', '-O2', '-O1'])\n else:\n env.Append(CPPDEFINES={'NDEBUG': None})\n remove_envvar_values(env, 'CPPDEFINES', ['RF_OPTION_DEBUG'])\n remove_envvar_values(env, 'CCFLAGS', ['-g'])\n\n # if is_debug:\n # env.AppendUnique(CCFLAGS=[\"-g\"])\n # env.AppendUnique(CPPDEFINES={'RF_OPTION_DEBUG': None})\n # remove_envvar_values(env, 'CPPDEFINES', ['NDEBUG'])\n # else:\n # env.Append(CPPDEFINES={'NDEBUG': None})\n # remove_envvar_values(env, 'CPPDEFINES', ['RF_OPTION_DEBUG'])\n # remove_envvar_values(env, 'CCFLAGS', ['-g'])\n","sub_path":"build_extra/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"318448008","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jul 03 2015\r\n\r\nPotential Fields navigtion\r\n\r\n\r\n@author: S. Bertrand\r\n\"\"\"\r\n\r\nimport math\r\nimport Robot as rob\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nimport Timer as tmr\r\nimport Potentials as pot\r\nimport matplotlib.patches as patches\r\n\r\n# robot\r\nx0 = -4\r\ny0 = 1.2\r\ntheta0 = 0.0\r\nrobot = rob.Robot(x0, y0, theta0)\r\n\r\n# position control loop timer\r\npositionCtrlPeriod = 0.2\r\ntimerPositionCtrl = tmr.Timer(positionCtrlPeriod)\r\n\r\n# orientation control loop timer\r\norientationCtrlPeriod = 0.05\r\ntimerOrientationCtrl = tmr.Timer(orientationCtrlPeriod)\r\n\r\n\r\n# goal way point\r\nxr = 4.0\r\nyr = 1.0\r\nka = 0.04\r\ngoal = pot.Goal(xr, yr, ka)\r\n\r\nWPlist = [ [goal.xr, goal.yr] ] \r\n#threshold for change to next WP\r\nepsilonWP = 0.2\r\n# init WPManager\r\nWPManager = rob.WPManager(WPlist, epsilonWP)\r\n\r\n# obstacle 1\r\n#!!!!!!!!!!\r\n# A COMPLETER EN TD\r\n#!!!!!!!!!!\r\n\r\n# obstacle 2\r\n#!!!!!!!!!!\r\n# A COMPLETER EN TD\r\n#!!!!!!!!!!\r\n\r\n\r\n# duration of scenario and time step for numerical integration\r\nt0 = 0.0\r\ntf = 30.0\r\ndt = 0.01\r\nsimu = rob.RobotSimulation(robot, t0, tf, dt)\r\n\r\n#class Obstacle:\r\n# def _init_(self,xo,yo,do,sigmaX,signaY):\r\n# self.xo = xo\r\n# self.yo = yo\r\n# self.do = do \r\n# self.sigmaX = sigmaX\r\n# self.sigmaY = sigmaY\r\n# \r\n# def evalRepulsionGaussianPtential(self,x,y):\r\n# U = 0.0\r\n# return U \r\n# \r\n# def evalRepulsionGaussianForce(self,x,y):\r\n# Fx = 0\r\n# Fy = 0\r\n\r\n# initialize control inputs\r\nVr = 0.0\r\nthetar = 0.0\r\nomegar = 0.0\r\n\r\n\r\n# loop on simulation time\r\nfor t in simu.t: \r\n \r\n\r\n # position control loop\r\n if timerPositionCtrl.isEllapsed(t):\r\n\r\n #!!!!!!!!!!\r\n # A COMPLETER EN TD\r\n # calcul de Vr\r\n Vr = 0.0\r\n #!!!!!!!!!!\r\n \r\n #!!!!!!!!!!\r\n # A COMPLETER EN TD \r\n # reference orientation\r\n thetar = 0.0\r\n #!!!!!!!!!!\r\n \r\n \r\n # orientation control loop\r\n if timerOrientationCtrl.isEllapsed(t):\r\n\r\n #!!!!!!!!!!\r\n # A COMPLETER EN TD \r\n # angular velocity control input \r\n omegar = 0.0\r\n #!!!!!!!!!!\r\n \r\n \r\n # assign control inputs to robot\r\n robot.setV(Vr)\r\n robot.setOmega(omegar) \r\n \r\n # integrate motion\r\n robot.integrateMotion(dt)\r\n\r\n # store data to be plotted \r\n simu.addData(robot, WPManager, Vr, thetar, omegar)\r\n \r\n# end of loop on simulation time\r\n\r\n\r\n# close all figures\r\nplt.close(\"all\")\r\n\r\n# generate plots\r\nsimu.plotXY(1)\r\nsimu.plotXYTheta(2)\r\nsimu.plotVOmega(3)\r\n\r\n#simu.runAnimation(WPManager.epsilonWP, 5)\r\n\r\n# show plots\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n# Animation *********************************\r\nfig = plt.figure()\r\nax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-5, 5), ylim=(-5, 5))\r\nax.grid()\r\nax.set_xlabel('x (m)')\r\nax.set_ylabel('y (m)')\r\n\r\n'''\r\n# !!!!!!!!!!!!!!!!!!!!\r\n# A DECOMMENTER EN TD POUR AFFICHER LES OBSTACLES\r\nax.add_patch(patches.Circle((obstacle1.xo, obstacle1.yo), obstacle1.do, alpha = 0.08, color='red'))#, color='none', linewidth=1, linecolor='blue'))\r\nplt.plot(obstacle1.xo, obstacle1.yo, 'o', color='r', lw=2, markersize=10)\r\nax.add_patch(patches.Circle((obstacle2.xo, obstacle2.yo), obstacle2.do, alpha = 0.08, color='red'))#, color='none', linewidth=1, linecolor='blue'))\r\nplt.plot(obstacle2.xo, obstacle2.yo, 'o', color='r', lw=2, markersize=10)\r\n# !!!!!!!!!!!!!!!!!!!!\r\n'''\r\n\r\n\r\nrobotBody, = ax.plot([], [], 'o-', lw=2)\r\nrobotDirection, = ax.plot([], [], '-', lw=1, color='k')\r\nwayPoint, = ax.plot([], [], 'o-', lw=2, color='b')\r\ntime_template = 'time = %.1fs'\r\ntime_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)\r\nWPArea, = ax.plot([], [], ':', lw=1, color='b')\r\n\r\nthetaWPArea = np.arange(0.0,2.0*math.pi+2*math.pi/30.0, 2.0*math.pi/30.0)\r\nxWPArea = WPManager.epsilonWP*np.cos(thetaWPArea)\r\nyWPArea = WPManager.epsilonWP*np.sin(thetaWPArea)\r\n\r\ndef initAnimation():\r\n robotDirection.set_data([], [])\r\n robotBody.set_data([], [])\r\n wayPoint.set_data([], [])\r\n WPArea.set_data([], [])\r\n robotBody.set_color('r')\r\n robotBody.set_markersize(20) \r\n time_text.set_text('')\r\n return robotBody,robotDirection, wayPoint, time_text, WPArea \r\n \r\ndef animate(i): \r\n robotBody.set_data(simu.x[i], simu.y[i]) \r\n wayPoint.set_data(simu.xr[i], simu.yr[i])\r\n WPArea.set_data(simu.xr[i]+xWPArea.transpose(), simu.yr[i]+yWPArea.transpose()) \r\n thisx = [simu.x[i], simu.x[i] + 0.5*math.cos(simu.theta[i])]\r\n thisy = [simu.y[i], simu.y[i] + 0.5*math.sin(simu.theta[i])]\r\n robotDirection.set_data(thisx, thisy)\r\n time_text.set_text(time_template%(i*simu.dt))\r\n return robotBody,robotDirection, wayPoint, time_text, WPArea\r\n\r\nani = animation.FuncAnimation(fig, animate, np.arange(1, len(simu.t)),\r\n interval=4, blit=True, init_func=initAnimation, repeat=False)\r\n#interval=25\r\n\r\n#ani.save('robot.mp4', fps=15)\r\n\r\n","sub_path":"TD_Commande/TD_2/RobotNavPotFields.py","file_name":"RobotNavPotFields.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"383899351","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport sorl.thumbnail.fields\nimport trippie.utils\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0005_auto_20160629_1314'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='category',\n name='image',\n field=sorl.thumbnail.fields.ImageField(default=1, upload_to=trippie.utils.image_path, verbose_name='Image'),\n preserve_default=False,\n ),\n ]\n","sub_path":"apps/trips/migrations/0006_category_image.py","file_name":"0006_category_image.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"127147366","text":"import operator\n\n\nclass Node(object):\n \"\"\" Node class to store data in KDTree \"\"\"\n\n def __init__(self, value, axis, lchild=None, rchild=None):\n self.value = value\n self.axis = axis\n self.lchild = lchild\n self.rchild = rchild\n\n\nclass KDTree(object):\n \"\"\" KDTree with recursive add method \"\"\"\n\n def __init__(self, axes_count):\n self.root = None\n self.axes_count = axes_count\n self.current_axis = 0\n self.nodes_count = 0\n self.path_lengths = []\n\n def add(self, value):\n if self.root is None:\n self.root = Node(value, self.current_axis)\n self.nodes_count += 1\n self.__increment_axis()\n else:\n self.fadd(Node(value, self.current_axis), self.root)\n self.__increment_axis()\n\n def fadd(self, node, parent):\n if node.value[node.axis] < parent.value[node.axis]:\n if parent.lchild is None:\n parent.lchild = node\n self.nodes_count += 1\n else:\n self.fadd(node, parent.lchild)\n else:\n if parent.rchild is None:\n parent.rchild = node\n self.nodes_count += 1\n else:\n self.fadd(node, parent.rchild)\n\n def __increment_axis(self):\n if self.current_axis == self.axes_count - 1:\n self.current_axis = 0\n else:\n self.current_axis += 1\n\n # damn inefficient but easy to implement (sorry for that)\n def median_insertion(self, data):\n if not data:\n return\n sorted_values_for_axis = sorted(dict(enumerate([d[self.current_axis] for d in data])).items(), key=operator.itemgetter(1))\n median = sorted_values_for_axis[(len(sorted_values_for_axis)//2)-1]\n self.add(data[median[0]])\n self.__increment_axis()\n self.median_insertion(data[:median[0]])\n self.median_insertion(data[median[0]+1:])\n\n def calculate_path_lengths(self):\n self.__go_deeper(self.root, 0)\n return self.path_lengths\n\n def __go_deeper(self, node, path_length):\n\n # node parent was a leaf (and it's not a node :D)\n if node is None:\n return\n\n # incrementing path length\n path_length += 1\n\n # is it a leaf?\n if node.lchild is None and node.rchild is None:\n self.path_lengths.append(path_length)\n else: # it's not a lead so proceed deeper\n self.__go_deeper(node.lchild, path_length)\n self.__go_deeper(node.rchild, path_length)\n\n # TODO: it's not a search but a DFT - fix it\n def search(self, data_entry):\n return self.__search(self.root, data_entry)\n\n def __search(self, node, data_entry):\n\n if node is None:\n return False\n\n if node.value[0] == data_entry[0] and node.value[1] == data_entry[1]:\n return True\n else:\n if self.__search(node.lchild, data_entry):\n return True\n if self.__search(node.rchild, data_entry):\n return True\n\n return False\n\n\n\n\n\n\n\n","sub_path":"dstruct/kdtree.py","file_name":"kdtree.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"59916793","text":"import argparse\nimport curses\nimport random\nimport time\n\nimport gym\nimport torch\n\nimport env\n\nWEIGHTS_PATH = 'weights.pt'\nMAX_EPISODES = 10 ** 5\nVISUAL_INTERVAL = 10 ** 2\n\nargs_parser = argparse.ArgumentParser()\nargs_parser.add_argument('--load', dest='load', type=bool)\nargs = args_parser.parse_args()\n\n\ne = gym.make('SimpleEnv-v0')\n\n\nclass Net(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.l1 = torch.nn.Linear(100, 16)\n # self.l2 = torch.nn.Linear(32, 16)\n self.l3 = torch.nn.Linear(16, e.action_space.n)\n\n def forward(self, state):\n x = torch.Tensor(state.map)\n px, py = state.player_position\n tx, ty = state.target_position\n\n x[px, py] = -1\n x[tx, ty] = 1\n\n x = x.view(-1)\n x = torch.nn.functional.relu(self.l1(x))\n # x = torch.nn.functional.relu(self.l2(x))\n x = torch.nn.functional.relu(self.l3(x))\n\n return x\n\n\nnet = Net()\nprint(net)\nif args.load:\n print('Loading weights')\n net.load_state_dict(torch.load(WEIGHTS_PATH))\n net.eval()\n\n\n# Hypers\nalpha = 3e-2 # learning rate\ngamma = 7e-1 # discount\nepsilon = 1.5e-1 # greedyness\n\noptimizer = torch.optim.SGD(net.parameters(), lr=alpha)\n\n\ndef main(scr):\n epochs = 0\n wins = 0\n for t in range(1, MAX_EPISODES):\n visualize_episode = t != 0 and t % VISUAL_INTERVAL == 0\n\n state = e.reset()\n penalties, reward, done = 0, 0, False\n\n while not done:\n optimizer.zero_grad()\n\n if random.uniform(0, 1) < epsilon:\n action = e.action_space.sample()\n else:\n action = torch.argmax(net(state)).item()\n\n next_state, reward, done, info = e.step(action)\n\n if not done:\n old_value = net(state)\n next_max = torch.max(net(next_state))\n\n cost = (old_value - (reward + gamma * next_max)) ** 2\n cost.mean().backward()\n optimizer.step()\n\n if reward == -1:\n penalties += 1\n\n state = next_state\n epochs += 1\n\n if visualize_episode:\n e.render(scr)\n scr.addstr(14, 0, '=' * 40)\n scr.addstr(15, 0,\n 'Epochs: {epoch} / Episodes: {episode} / Wins: {wins} ({win_rate:2.2f}%)'.format(\n epoch=epochs, episode=t, wins=wins, win_rate=(wins/VISUAL_INTERVAL)*100))\n\n # p = curses.newpad(200, 500)\n # p.addstr(0, 0, '{}'.format(list(net.parameters())[3]))\n # p.refresh(0, 0, 4, 14, 12, curses.COLS-1)\n\n scr.refresh()\n time.sleep(0.25)\n\n if reward > 0:\n wins += 1\n\n if visualize_episode:\n if reward <= 0:\n scr.addstr(3, 14, '---- LOSE ----')\n else:\n scr.addstr(3, 14, '++++ WIN +++++')\n scr.refresh()\n wins = 0\n\n torch.save(net.state_dict(), WEIGHTS_PATH)\n\n\nif __name__ == '__main__':\n curses.wrapper(main)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"594217695","text":"#!/usr/bin/env python3\n\nimport sqlite3\nimport scrapy\nfrom selenium import webdriver\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\nimport time\nimport urllib.request\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath('database_query'))))\n\n\ndef sql_fetch_recipe_db(url):\n print(\"\\n\\nHELLO: \", url)\n recipe_connection = sqlite3.connect('/home/leander/Desktop/automatic_KB/recipes/recipes1.db')\n recipe_cursor = recipe_connection.cursor()\n if url == \"all\":\n recipe_cursor.execute(\"SELECT * FROM Recipes;\")\n else:\n query = \"SELECT * FROM Recipes WHERE URL = \" + url + \";\"\n print(query)\n recipe_cursor.execute(query)\n return recipe_cursor.fetchall()\n\n\nclass RecipeI:\n URL = 0\n TITLE = 1\n RATING = 2\n SERVING = 3\n TIME = 4\n CATEGORY = 5\n INGREDIENTS = 6\n PREPARATION = 7\n NUTRITION = 8\n\n\nclass SeleniumVideoSpider(scrapy.Spider):\n name = 'selenium_video'\n allowed_domains = ['tasty.co', 'vid.tasty.co']\n\n def start_requests(self):\n recipe_rows = sql_fetch_recipe_db(\"'https://tasty.co/recipe/ghanaian-jollof-rice-as-made-by-tei-hammond'\")\n for recipe in recipe_rows:\n print(recipe)\n driver = webdriver.Chrome('/home/leander/Documents/chromedriver')\n print(\"\\n\\n\\n\\n: \", driver)\n print(\"CHECKING NEW URL: \", recipe[RecipeI.URL], \"\\n\\n\")\n time.sleep(5)\n tmp = driver.get(recipe[RecipeI.URL])\n print(tmp)\n time.sleep(15)\n\n src_code = Selector(text=driver.page_source)\n print(\"SRC_CODE: \", src_code)\n video_urls = src_code.xpath('//video/@src').extract()\n print(\"VIDEO_URL: \", video_urls)\n\n for video_url in video_urls:\n print(video_url)\n yield Request(video_url, callback=self.parse)\n driver.quit()\n\n def parse(self, response):\n print(\"\\n\\n\\n RESPONSE: \", response, \"\\n\\n\\n\")\n for string in str(response).split(\" \"):\n if \"://vid.tasty.co\" in string:\n if string[len(string)-1] == '>':\n file_name = \"../data/videos/\" + string[:-1].replace('/', '|') + \".mp4\"\n urllib.request.urlretrieve(string[:-1], file_name)\n yield {'VID_URL': string[:-1]}\n else:\n file_name = \"../data/videos/\" + string + \".mp4\"\n urllib.request.urlretrieve(string, file_name)\n yield {'VID_URL': string}\n","sub_path":"scrape_tasty_web/scrape_tasty_site/spiders/selenium_video.py","file_name":"selenium_video.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"350915381","text":"import os\nimport re\nimport threading\nfrom datetime import date\nfrom ftplib import FTP\nfrom queue import Queue\n\nimport config\n\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\n# ---------------------------------------------------------\nclass DownloadFromFTP(threading.Thread):\n \"\"\"Потоковый загрузчик файлов\"\"\"\n\n def __init__(self, queue):\n \"\"\"Инициализация потока\"\"\"\n threading.Thread.__init__(self)\n self.queue = queue\n\n def run(self):\n \"\"\"Запуск потока\"\"\"\n while True:\n # Получаем url из очереди\n params = self.queue.get()\n\n # Скачиваем файл\n self.FunDownloadFromFTP(params)\n\n # Отправляем сигнал о том, что задача завершена\n self.queue.task_done()\n\n def FunDownloadFromFTP(self, params):\n print(f'{bcolors.OKBLUE}FTP. Download :{params.get(\"ftp_file_name\")}')\n\n # \"\"\"Connect to an FTP server and bring down files to a local directory\"\"\"\n try:\n ftp = FTP(config.HOST, timeout=400)\n print(f\"{bcolors.OKBLUE}FTP. Login to FTP: {config.HOST}, try goto {config.HOSTDir}. {ftp.login()}\")\n ftp.cwd(config.HOSTDir)\n try:\n # open a the local file\n with open(f'{WorkFolder}\\\\{params.get(\"local_file_name\")}_WIN1251'.upper(), 'wb') as _local_file:\n ftp.retrbinary('RETR ' + params.get(\"ftp_file_name\"), _local_file.write)\n print(f'{bcolors.OKGREEN} FTP. {params.get(\"ftp_file_name\")}>>>{params.get(\"local_file_name\")}')\n except:\n print(f\"{bcolors.FAIL} FTP: Connection Error {config.HOST}\")\n ftp.close() # Close FTP connection\n except:\n print(f\"{bcolors.FAIL} FTP: Couldn't find server {config.HOST}\")\n\n\n# --------------------------------------------------------\nclass DecodeLocalFile(threading.Thread):\n \"\"\"Потоковый загрузчик файлов\"\"\"\n\n def __init__(self, queue):\n \"\"\"Инициализация потока\"\"\"\n threading.Thread.__init__(self)\n self.queue = queue\n\n def run(self):\n \"\"\"Запуск потока\"\"\"\n while True:\n # Получаем url из очереди\n params = self.queue.get()\n\n # Скачиваем файл\n self.FunDecodeLocalFile(params)\n\n # Отправляем сигнал о том, что задача завершена\n self.queue.task_done()\n\n def FunDecodeLocalFile(self, params):\n _codec_page = 'windows-1251'\n print(f'{bcolors.OKBLUE}File: {params.get(\"path_file_from\")}, codepage = {_codec_page}')\n try:\n decode_test = ''\n with open(params.get(\"path_file_from\"), 'r', encoding='windows-1251') as fr:\n for code_text in fr.readlines():\n if code_text[0] != '№':\n decode_test += code_text[:-1] + '\\n' # \\r\\n\n with open(params.get(\"path_file_to\"), 'w', encoding='UTF-8') as fw:\n fw.write(decode_test)\n\n print(f'{bcolors.OKGREEN} {params.get(\"path_file_from\")}>>>{params.get(\"path_file_to\")}')\n except:\n print(f'{bcolors.FAIL} Ошибка файла: {params.get(\"path_file_from\")}')\n\n\n# --------------------------------------------------------\n# Получаем список файлов на FTP\ndef getftplistfile():\n ListFTPFile = []\n ftp = FTP(config.HOST)\n print(f\"{bcolors.OKBLUE}Login to FTP: {config.HOST}, try goto {config.HOSTDir}. {ftp.login()}\")\n ftp.cwd(config.HOSTDir)\n list_ftp_file = ftp.nlst()\n for ftp_file in list_ftp_file: # кореневые каталоги\n if ftp_file.find('.txt') != -1:\n # Чтобы свернуть исторю файла убераем из его мени версию\n local_file = re.sub('_(\\d)+\\.', '.',\n ftp_file) # регулярное выражение '_'+ 'несколько цифр' + '.'\n\n _row = {\"ftp_file_path\": f'{config.HOST}/{config.HOSTDir}/{ftp_file}', \"ftp_file_name\": ftp_file,\n \"local_file_name\": local_file.upper()}\n ListFTPFile.append(_row)\n print(f\"{bcolors.OKGREEN} ftp: {_row}\")\n ftp.close()\n return ListFTPFile\n\n# --------------------------------------------------------\n\n\n# ------------------------------------------------------------------------\ndef main():\n _useConv = {'IBM866', 'windows-1251', 'ascii', 'MacCyrillic'}\n\n if _useDowloadFTP:\n # удалить все файлы, проще выкачать заново\n print(f'{bcolors.HEADER}Delete old file')\n for path, subdirs, files in os.walk(WorkFolder):\n for _local_file in files:\n if _local_file.find(\".txt\") != -1:\n print(f'{bcolors.OKBLUE} Удалить: {path}{_local_file}')\n os.remove(os.path.join(path, _local_file).lower())\n\n print(f'{bcolors.HEADER}Starting create download list')\n ListParamsFTP = getftplistfile() # список файлов с FTP\n\n with open(f'{curdir}\\JRN_{date.today()}.txt', 'w') as f:\n for item in ListParamsFTP:\n f.write(\"%s\\n\" % item)\n\n # скачиваем FTP\n print(f'{bcolors.HEADER}Starting download FTP file')\n queue_ftpfile = Queue()\n # Запускаем потом и очередь\n for i in range(10):\n t = DownloadFromFTP(queue_ftpfile)\n t.setDaemon(True)\n t.start()\n # Даем очереди нужные нам ссылки для скачивания\n for _el in ListParamsFTP:\n queue_ftpfile.put(_el)\n\n # Ждем завершения работы очереди\n queue_ftpfile.join()\n\n if _useDecodeFile:\n print(f'{bcolors.HEADER}Starting get list encode file')\n ListParamsDecodeFile = [] # Файлы для перкодировки\n for path, subdirs, files in os.walk(WorkFolder):\n for _local_file in files:\n if _local_file.find(\"_WIN1251\") != -1:\n row = {\"path\": path, \"filename\": _local_file, \"path_file_from\": f'{path}{_local_file}',\n \"path_file_to\": f'{path}{_local_file.replace(\"_WIN1251\", \"\")}'}\n ListParamsDecodeFile.append(row)\n print(row)\n print(f'{bcolors.HEADER}Starting encode file')\n queue_decodefile = Queue()\n # Запускаем потом и очередь\n for i in range(10):\n t = DecodeLocalFile(queue_decodefile)\n t.setDaemon(True)\n t.start()\n # Даем очереди нужные нам ссылки для скачивания\n for _el in ListParamsDecodeFile:\n queue_decodefile.put(_el)\n\n # Ждем завершения работы очереди\n queue_decodefile.join()\n\n # Удаляем не перекодированные файлы\n if _UseDeleteFileAfter:\n for _el in ListParamsDecodeFile:\n os.remove(os.path.join(_el.get(\"path\"), _el.get(\"filename\")).lower())\n\n\n# ------------------------------------------------------------------------\nif __name__ == \"__main__\":\n curdir = os.getcwd()\n WorkFolder = f'{curdir}\\Download\\\\'\n _useDowloadFTP = True # скачивать файлы с FTP\n _useDecodeFile = True # перекодировать файлы\n _UseDeleteFileAfter = True # удалять файлы\n main()\n","sub_path":"DownLoadGalDescr.py","file_name":"DownLoadGalDescr.py","file_ext":"py","file_size_in_byte":7953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"523166371","text":"from flask import Flask, render_template, url_for\n\napp=Flask(__name__)\n\n\n@app.route('/')\ndef home():\n context = {\n 'title': 'HOME',\n 'stylesheet': url_for('static', filename='css/cover.css')\n }\n return render_template(\"home.html\", context=context)\n\n@app.route('/info')\ndef info():\n context = {\n 'title': 'LANDING',\n 'stylesheet': url_for('static', filename='css/carousel.css')\n }\n return render_template(\"info.html\", context=context)\n\n\n\nif __name__==\"__main__\":\n app.run(debug=True)\n","sub_path":"bethesda/bethesda.py","file_name":"bethesda.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"160444397","text":"\"\"\"\r\nAutor:\r\n Jorge Casillas\r\nFecha:\r\n Noviembre/2018\r\nContenido:\r\n Uso simple de XGB y LightGBM para competir en DrivenData:\r\n https://www.drivendata.org/competitions/7/pump-it-up-data-mining-the-water-table/\r\n Inteligencia de Negocio\r\n Grado en Ingeniería Informática\r\n Universidad de Granada\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport time\r\n\r\nfrom sklearn.datasets import samples_generator\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn import preprocessing\r\nimport xgboost as xgb\r\nimport lightgbm as lgb\r\nimport matplotlib.pyplot as plt\r\n\r\nle = preprocessing.LabelEncoder()\r\n\r\n'''\r\nlectura de datos\r\n'''\r\n\r\ndata_x_nan = pd.read_csv('data_x_preproces.csv')\r\ndata_y = pd.read_csv('water_pump_tra_target.csv')\r\ndata_y.drop(labels=['id'], axis=1, inplace=True)\r\ndata_x_tst_nan = pd.read_csv('data_x_tst_preproces.csv')\r\n\r\n\r\n# Guardamos el resultado en listas para el entrenamiento\r\nX_filtered = data_x_nan.values\r\nX_tst_filtered = data_x_tst_nan.values\r\ny = np.ravel(data_y.values)\r\n\r\n\r\n#------------------------------------------------------------------------\r\n'''\r\nValidación cruzada con particionado estratificado y control de la aleatoriedad fijando la semilla\r\n'''\r\n\r\nskf = StratifiedKFold(n_splits=5, shuffle=True)\r\nle = preprocessing.LabelEncoder()\r\n\r\ndef validacion_cruzada(modelo, X, y, cv, name=None):\r\n y_test_all = []\r\n\r\n if name!=None:\r\n f = open('salidas/'+name+'.csv','w')\r\n i = 0\r\n f.write('it,acc,tiempo\\n')\r\n for train, test in cv.split(X, y):\r\n t = time.time()\r\n modelo = modelo.fit(X[train],y[train])\r\n tiempo = time.time() - t\r\n y_pred = modelo.predict(X[test])\r\n print(\"Score: {:.4f}, tiempo: {:6.2f} segundos\".format(accuracy_score(y[test],y_pred) , tiempo))\r\n if name != None:\r\n f.write('%d,%0.4f,%6.2f\\n' % (i,accuracy_score(y[test],y_pred),tiempo))\r\n i += 1\r\n y_test_all = np.concatenate([y_test_all,y[test]])\r\n\r\n if name != None:\r\n f.close()\r\n print(\"\")\r\n\r\n return modelo, y_test_all\r\n\r\n#------------------------------------------------------------------------\r\n\r\n\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn.svm import SVC\r\n\r\n'''\r\nprint(\"------ XGB...\")\r\nclf = xgb.XGBClassifier(n_estimators = 500,objective='multi:softmax',n_jobs=8,max_depth=11,num_class=4)\r\nclfb, y_test_clf = validacion_cruzada(clf,X_filtered,y,skf)\r\n#'''\r\n\r\n\r\nprint(\"------ LightGBM...\")\r\nlgbmb = lgb.LGBMClassifier(objective='multiclass',n_estimators=1000,num_threads=8,max_depth=-1)\r\n#lgbmb, y_test_lgbm = validacion_cruzada(lgbm,X_filtered,y,skf,'salida7lgb')\r\n#'''\r\n\r\n'''\r\nprint(\"------ MLPNN...\")\r\nX_filtered = preprocessing.normalize(X_filtered)\r\nnn = MLPClassifier()\r\nnnb, y_test_nn = validacion_cruzada(nn,X_filtered,y,skf,'salida5nn')\r\n#'''\r\n\r\n'''\r\nprint(\"------ SVC...\")\r\nsvc = SVC()\r\nsvcb, y_test_svc = validacion_cruzada(svc,X_filtered,y,skf,'salida5svc')\r\n#'''\r\n\r\n'''\r\nprint(\"------ RandomForest...\")\r\nrf = RandomForestClassifier(n_estimators=1000,min_samples_split=10,oob_score=True,n_jobs=-1)\r\nrfb, y_test_svc = validacion_cruzada(rf,X_filtered,y,skf)\r\n#'''\r\n\r\n\r\n\r\n'''\r\nUsamos el modelo que mejor nos convenga para guardar los datos finales\r\n'''\r\ncolumnas = data_x_nan.columns.values\r\ncolumnas = columnas[0:21].tolist()\r\n\r\nlgbm = lgbmb.fit(X_filtered,y,feature_name=data_x_nan.columns.tolist(),categorical_feature=columnas)\r\ny_pred_tra = lgbm.predict(X_filtered)\r\nprint(\"Score clf: {:.4f}\".format(accuracy_score(y,y_pred_tra)))\r\ny_pred_tst_clf = lgbm.predict(X_tst_filtered)\r\n#'''\r\n\r\nlgb.plot_importance(lgbm)\r\n\r\nplt.show()\r\n\r\n\r\ndf_submission = pd.read_csv('water_pump_submissionformat.csv')\r\ndf_submission['status_group'] = y_pred_tst_clf\r\ndf_submission.to_csv(\"submission7lgmb.csv\", index=False)\r\n#'''","sub_path":"Practica 3/ejemplo_water_pump.py","file_name":"ejemplo_water_pump.py","file_ext":"py","file_size_in_byte":3858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"335157514","text":"import numpy as np\nimport os\n\nshot = 1 \nprev = 0\nwith open('buffy_s05e01.txt','r') as f:\n\tfor line in f:\n\t\tprint('shot:',shot)\n\t\toutput_list = []\n\t\timage_list = []\n\t\ttopic_list = []\n\t\tif shot == 22 or shot == 674:\n\t\t\tprint('skipping')\n\t\t\tprev = int(line.split()[0])\n\t\t\tshot += 1\n\t\t\tcontinue\n\t\tcurrent = int(line.split()[0])\n\t\tfor i in range(prev, current,10):\n\t\t\timage_name = '/mnt/nfs/scratch1/souyoungjin/datasets/BBT/last_buffy_s05e01/all_frames/images%06d.jpg'%int(i)\n\t\t\ttry:\t\n\t\t\t\timage_list.append(image_name)\n\t\t\texcept Exception as e:\n\t\t\t\tprint('Error', str(e))\n\t\tos.system('mkdir buffy_shots_10_output/shot_'+str(shot))\n\t\tnp.save('buffy_shots_10_output/shot_'+str(shot)+'/image_list',np.array(image_list))\n\t\tprev = current\n\t\tshot += 1\n","sub_path":"construct_cooc.py","file_name":"construct_cooc.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"66096862","text":"import sys\n\nfd = open('hung.conllu')\nfreq = {} #frequency list for parts of speech\nform_tag = {} #matrix to store correspondences form as a token and part of speech\nforms = {}\ny = 0 #counter for total number of tokens\nfor line in fd.readlines():\n\tif '\\t' not in line:\n\t\tcontinue\n\t#print(line)\n\tx = line.split()\n\ty = y + 1\n\tpos = x [3]\n\tif pos not in freq:\n\t\tfreq[pos] = 0 #add pos to the feq list with value 0\n\tfreq[pos] = freq[pos] + 1\n\ttoken = x [1]\n\tif token not in forms:\n\t\tforms[token] = 0 #add pos to the feq list with value 0\n\tforms[token] = forms[token] + 1\n\tif token not in form_tag:\n\t\tform_tag[token] = {}\n\tif pos not in form_tag[token]:\n\t\tform_tag[token][pos] = 0\n\tform_tag[token][pos] = form_tag[token][pos] + 1\n\t#print(x)\nfor pos in freq:\n\tprint('%.4f\\t%d\\t%s\\t%s' % (freq[pos]/y, freq[pos] , pos, '_'))#P, count, tag, form\nfor token in form_tag:\n\tfor tag in form_tag[token]:\n\t\tprint('%.4f\\t%d\\t%s\\t%s' % (form_tag[token][tag]/forms[token], form_tag[token][tag] , tag, token))#P, count, tag, form\n\t\t\n#print(freq)\n#print(forms)\n#print(y)\n\n\n\n","sub_path":"practicals/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"511195233","text":"import os\nimport re\nimport ssl\nimport time\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nfrom urllib.parse import urlparse\nfrom urllib.request import urlopen\n\nPROXY_PATH = \"proxy.txt\"\nUSER_AGENT = \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \\\n Chrome/64.0.3282.186 Safari/537.36\"\n\n\ndef update_proxies(path=PROXY_PATH):\n # Getting proxy list from address if file is old\n proxies = load_proxies_from_file(path)\n if not proxies:\n download_proxies(path)\n older = 3600 * 6 # 6h\n try:\n os.path.getmtime(path)\n except OSError:\n download_proxies(path)\n diff = time.time() - os.path.getmtime(path)\n if diff > older:\n download_proxies(path)\n\n\ndef download_proxies(path=PROXY_PATH):\n # found = ip_adress_proxies()\n found = free_proxies()\n dump_proxies_to_file(found[:20], path) # 20 top proxies\n\n\ndef ip_adress_proxies(url=\"https://www.ip-adress.com/proxy_list/\"):\n # Downloading without proxy\n opener = urllib.request.build_opener(urllib.request.ProxyHandler())\n urllib.request.install_opener(opener)\n request = urllib.request.Request(url)\n request.add_header(\"user-agent\", USER_AGENT)\n parsed_uri = urlparse(url)\n host = \"{uri.scheme}://{uri.netloc}/\".format(uri=parsed_uri)\n request.add_header(\"referer\", host)\n s = False\n try:\n context = ssl._create_unverified_context()\n with urlopen(request, context=context, timeout=3000) as response:\n s = response.read().decode(\"utf-8\")\n except Exception as er:\n print(\"Download proxies error\")\n raise er\n pattern = r\"\\d*\\.\\d*\\.\\d*\\.\\d*\\:\\d*\"\n found = [i.replace(\"\", \"\") + \"\\n\" for i in re.findall(pattern, s)]\n return found\n\n\ndef free_proxies(url=\"https://free-proxy-list.net/\"):\n # Downloading without proxy\n opener = urllib.request.build_opener(urllib.request.ProxyHandler())\n urllib.request.install_opener(opener)\n request = urllib.request.Request(url)\n request.add_header(\"user-agent\", USER_AGENT)\n parsed_uri = urlparse(url)\n host = \"{uri.scheme}://{uri.netloc}/\".format(uri=parsed_uri)\n request.add_header(\"referer\", host)\n f = urllib.request.urlopen(request)\n pattern = r\"\\d*\\.\\d*\\.\\d*\\.\\d*\\\\d*\"\n s = f.read().decode(\"utf-8\")\n found = [i.replace(\"\", \":\") + \"\\n\" for i in re.findall(pattern, s)]\n return found\n\n\ndef load_proxies(path=PROXY_PATH):\n if not os.path.exists(PROXY_PATH):\n with open(PROXY_PATH, \"w\"):\n pass\n update_proxies(path)\n return load_proxies_from_file(path)\n\n\ndef load_proxies_from_file(path=PROXY_PATH):\n try:\n with open(path) as outfile:\n return outfile.readlines()\n except Exception:\n return None\n\n\ndef dump_proxies_to_file(proxies, path=PROXY_PATH):\n with open(path, \"w\") as outfile:\n for proxy in proxies:\n outfile.write(proxy)\n","sub_path":"rosreestr2coord/proxy_handling.py","file_name":"proxy_handling.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"182361204","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-i686/egg/qtalchemy/dialogs/auth_settings.py\n# Compiled at: 2012-06-23 08:27:12\nfrom qtalchemy import ModelObject, UserAttr\nfrom PySide import QtCore, QtGui\n\nclass AuthSettings(ModelObject):\n \"\"\"\n :class:`AuthSettings` contains the attributes for the model to \n attach to the authentication dialogs.\n \"\"\"\n classEvents = ModelObject.Events()\n remember_server = UserAttr(bool, 'Remember Data Source')\n remember_user = UserAttr(bool, 'Remember User')\n server = UserAttr(str, 'Server')\n database = UserAttr(str, 'Database')\n user = UserAttr(str, 'User')\n password = UserAttr(str, 'Password')\n server_string = UserAttr(str, 'Server Configuration', readonly=True)\n\n def __init__(self):\n self.remember_server = True\n self.remember_user = True\n self.server_type = 'postgresql'\n self.server = None\n self.database = None\n self.user = None\n self.password = None\n return\n\n @classEvents.add('set', 'server')\n @classEvents.add('set', 'database')\n def server_string_config_change(self, attr, oldvalue):\n self.server_string = '%s://%s/%s' % (self.server_type, self.server, self.database)\n\n def loadSettings(self):\n settings = QtCore.QSettings()\n settings.beginGroup('Data Settings (Authentication)')\n self.remember_server = settings.value('remember_server', self.remember_server)\n self.remember_user = settings.value('remember_user', self.remember_user)\n if self.remember_server:\n self.server_type = settings.value('server_type', self.server_type)\n self.server = settings.value('server', self.server)\n self.database = settings.value('database', self.database)\n if self.remember_user:\n self.user = settings.value('user', self.user)\n settings.endGroup()\n\n def saveSettings(self):\n settings = QtCore.QSettings()\n settings.beginGroup('Data Settings (Authentication)')\n settings.setValue('remember_server', self.remember_server)\n settings.setValue('remember_user', self.remember_user)\n settings.setValue('server_type', self.server_type if self.remember_server else '')\n settings.setValue('server', self.server if self.remember_server else '')\n settings.setValue('database', self.database if self.remember_server else '')\n settings.setValue('user', self.user if self.remember_user else '')\n settings.endGroup()","sub_path":"pycfiles/qtalchemy-0.8.3-py2.7/auth_settings.py","file_name":"auth_settings.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"390487900","text":"from setuptools import setup\n\nrequirements = []\nwith open('requirements.txt') as f:\n\trequirements = f.read().splitlines()\n\nsetup(\n\tname='judicatorAPI',\n\tauthor='Vacneyelk',\n\turl='https://github.com/Vacneyelk/JudicatorAPI',\n\tversion='0.1a',\n\tpackages=['judicatorAPI'],\n\tlicense='MIT',\n\tdescription='Python wrapper for Riot Games League of Legends API',\n\tinstall_requires=requirements,\n\tpython_requries='>=3.6'\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"414227050","text":"'''\nby:wangyongkang\nautoencoder\n'''\nimport logging\nimport datetime\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom Theroy_minist_noiid.detection import AutoEncoder\n\nclass Attention(object):\n \n def __init__(self, model = 'autoencoder', epochs=50):\n\n self.epochs = epochs\n # self.model = None\n # self.scaler_ = StandardScaler()\n self.model_path = os.path.join(\"ae_model.h5\")\n if model == 'autoencoder':\n self.ae = AutoEncoder(epochs=self.epochs)\n\n if os.path.exists(\"attention.log\"):\n os.remove('attention.log')\n\n def cal_weights(self, input_weights, num_of_features = 3000, y = -2):\n features = []\n for input_weight in input_weights:\n features.append(np.hstack(np.array([ item.ravel() for item in input_weight ]))) \n features = np.asarray(features)\n\n feature_selector = range(num_of_features)\n # if not os.path.isfile(self.model_path):\n # self.ae.fit(feature_selector)\n\n # if len(features[0]) > num_of_features:\n # features = np.array([ item[:num_of_features] for item in features ])\n\n feature_selected = []\n for idx in range(len(features)):\n feature_selected.append( features[idx][feature_selector] ) \n feature_selected = np.asarray(feature_selected)\n\n with open('attention.log', 'a') as fw:\n fw.write( \"{} [INFO] Calculating attention...\\n\".format(datetime.datetime.now()) )\n \n session = tf.Session()\n with session.as_default():\n with session.graph.as_default():\n decision_scores_ = self.ae.detect(feature_selected)\n weights = np.power( decision_scores_, y)\n \n # weights = np.array(weights) * len(features)\n \n fw.write( \"{} [INFO] Calculating completed!\\n\".format(datetime.datetime.now()) )\n fw.write( '{} [Scores]: {}\\n'.format(datetime.datetime.now(), decision_scores_) )\n fw.write( '{} [Weights]: {}\\n'.format(datetime.datetime.now(), weights) )\n fw.write( '------------------------\\n')\n \n return weights\n \n def train_AE(self, feature_selector):\n print(\"[Begin Training AE] {}\".format( datetime.datetime.now().strftime('%m-%d %H:%M:%S') ))\n\n data_dir = \"../saved_weights_for_AE\"\n files = [ f for f in os.listdir(data_dir) if os.path.isfile(os.path.join(data_dir, f)) ]\n weights = []\n for f in files:\n weights.append( np.load( os.path.join(data_dir, f), allow_pickle=True ) )\n features = []\n for input_weight in weights:\n features.append( np.hstack( np.array([ item.ravel() for item in input_weight ])) )\n features = np.asarray(features)\n print(features.shape)\n\n feature_selected = []\n for idx in range(len(features)):\n feature_selected.append( features[idx][feature_selector] ) \n feature_selected = np.asarray(feature_selected)\n\n session = tf.Session()\n with session.as_default():\n with session.graph.as_default():\n self.model.fit(feature_selected)\n self.model.save(self.model_path)\n session.close()\n print(\"[End Training AE] {}\".format( datetime.datetime.now().strftime('%m-%d %H:%M:%S') ) )\n\n def zero_out(self, weights, threshold = 0.8):\n \n print( \"[INFO] Shape of the calculated attention\", weights.shape )\n average = np.average(weights)\n print( \"[INFO] Mean value of the calculated attention\", average, \"SHAPE:\", average.shape)\n print( \"[INFO] threshold * average =\", str(threshold * average) )\n for i in range(len(weights)):\n if weights[i] < ( threshold * average ):\n weights[i] = 0\n \n return weights\n\nif __name__ == '__main__':\n # test_attention = Attention()\n # attention = test_attention.cal_weights(np.random.rand(10,3000))\n # # print(np.random.rand(10,3000).shape)\n # print(attention)\n input_weights = np.random.rand(4,6)\n # print(input_weights)\n features = []\n for input_weight in input_weights:\n features.append(np.hstack(np.array([item for item in input_weight])))\n features = np.asarray(features)\n feature_selector = range(4)\n print(features)\n feature_selected = []\n for idx in range(len(features)):\n feature_selected.append(features[idx][feature_selector])\n feature_selected = np.asarray(feature_selected)\n print(feature_selected)\n # attention[0] = 0.00001\n # attention[1] = 0.001\n # print( test_attention.zero_out(attention), test_attention.zero_out(attention).shape )","sub_path":"Theroy_DetectAcc/Theroy_minist_noiid/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":4737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"223744851","text":"# The websocket_client is part of the core agent code and is above the integration tests\nimport websocket_client\nimport base64\nimport json\nimport socket\n\ndef get_my_ip():\n\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ts.connect(('8.8.8.8', 80))\n\tmy_ip = s.getsockname()[0]\n\ts.close()\n\treturn my_ip\n\nclass WebSocket():\n\tdef __init__(self,port):\n\t\tself.ws = websocket_client.WebSocket()\n\t\tmy_ip = get_my_ip()\n\t\turl = \"wss://\"+my_ip+\":\"+str(port)\n\t\tself.ws.connect( url )\n\n\tdef send(self, obj):\n\t\treturn self.ws.send(base64.b64encode(json.dumps(obj)))\n\n\tdef recv(self):\n\t\tdata = self.ws.recv()\n\t\tif data:\n\t\t\tdecoded = json.loads(base64.b64decode(data))\n\t\t\t#print \"WSRECV\", decoded\n\t\t\treturn decoded\n\t\treturn None\n\n\tdef close(self):\n\t\treturn self.ws.close()\n\n","sub_path":"node/integration/helper_websocket.py","file_name":"helper_websocket.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"215246643","text":"# Author:马肖\n# E-mail:maxiaoscut@aliyun.com\n# Github:https://github.com/Albertsr\n\n# 出处:蚂蚁金服-风险大脑-支付风险识别大赛(第一赛季) \n# https://dc.cloud.alipay.com/index#/topic/data?id=4\n# TPR1:当FPR等于0.001时的TPR; TPR2:当FPR等于0.005时的TPR; TPR3:当FPR等于0.01时的TPR\n# 模型成绩 = 0.4 * TPR1 + 0.3 * TPR2 + 0.3 * TPR3\n\n\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix, make_scorer\n\ndef weighted_coverage(y_true, y_prob, thresholds_num=1000): \n thresholds = np.linspace(np.min(y_prob), np.max(y_prob), thresholds_num)\n \n # get_tpr_fpr根据给定的阈值,返回TPR、FPR\n def get_tpr_fpr(threshold):\n y_pred = np.array([int(i > threshold) for i in y_prob])\n tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()\n tpr = tp / (tp + fn)\n fpr = fp / (fp + tn)\n return tpr, fpr\n \n # 根据不同的阈值生成对应的一系列TPR、FPR\n # sklearn.metrics自带的roc_curve返回的tprs, fprs个数较少,最终的加权覆盖率不精准,不予采纳\n tprs, fprs = np.vectorize(get_tpr_fpr)(thresholds) \n \n # min_delta_index返回与target_fpr最接近的阈值索引\n def min_delta_index(target_fpr):\n delta = np.array([np.abs(fpr - target_fpr) for fpr in fprs])\n return np.argmin(delta)\n \n # 获取FPR与目标值0.001、0.005、0.01最接近时对应的索引及其对应的TPR\n min_indices = [min_delta_index(i) for i in [0.001, 0.005, 0.01]]\n target_tprs = np.array([tprs[index] for index in min_indices])\n \n # 获取最终的加权TPR\n weights = np.array([0.4, 0.3, 0.3])\n return np.dot(weights, target_tprs)\n","sub_path":"5. Appropriate Metrics/coverage.py","file_name":"coverage.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"119734201","text":"#!/usr/bin/python\r\n# -*- encoding: utf-8 -*-\r\nimport datetime\r\nimport requests\r\nimport json\r\nfrom sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import sessionmaker, scoped_session\r\nimport logging\r\nfrom applicant_db import applicant_info\r\n# database info\r\nengine = create_engine('mysql://root:harpio2018@54.227.200.177:3306/HARPIOBI?charset=utf8',echo=True)\r\nSession = sessionmaker(bind=engine)\r\nsession = Session()\r\nscoped_session = scoped_session(Session)\r\ntoday = datetime.datetime.today().strftime('%Y-%m-%d')\r\nfields = [\"lastExperience\",\"updatedAt\",\"email\",\"user\",\"createdAt\",\"name\",\"evaluationAverage\",\"languages\"]\r\n\r\nheaders = {\r\n 'Accept': 'application/json',\r\n 'pageSize':'30',\r\n 'x-tenant':'54f61e0a33fa47fba4d8afdb',\r\n 'x-version': '3.0.0',\r\n 'Authorization':'Basic dml0b3IuYXJhdWpvQGhhcnBpby5jb20uYnI6SGF2aWtAMjAxOEA=',\r\n 'orderBy':'createdAt',\r\n 'charset':'utf-8',\r\n 'connection':'keep-alive'\r\n }\r\nurl = 'https://api.kenoby.com/applicants'\r\nsession = requests.Session()\r\nMAX_PAGES = 1000000\r\nfor i in range(1, MAX_PAGES):\r\n print(\"loop number: \"+str(i))\r\n session_api_response = session.get(\r\n \turl,\r\n \theaders=headers,\r\n \tparams={'filterBy[createdAt][from]':'2018-05-07T00:00:01.000Z','filterBy[createdAt][to]':'2050-01-01T02:00:00.000Z','page':i})\r\n #(Vitor) we need to load the API response json in a text format to iterate it\r\n if session_api_response is not None:\r\n page_data = json.loads(session_api_response.text)\r\n else:\r\n break\r\n #(Vitor) We iterate each element to extract the info and insert the info into a variable to then push it to the applicant_info table\r\n for applicant in page_data:\r\n applicant_id = applicant.get('_id', None)\r\n name = applicant.get('name',None)\r\n createdAt = applicant.get('createdAt',None)\r\n print(createdAt)\r\n updatedAt = applicant.get('updatedAt',None)\r\n email = applicant.get('email',None)\r\n evaluationAverage = applicant.get('evaluationAverage',None)\r\n ratingAverage = applicant.get('ratingAverage',None)\r\n source = applicant.get('source', None)\r\n lastExp = applicant.get('lastExperience',None)\r\n\r\n if lastExp is not None:\r\n last_company = lastExp.get('company',None)\r\n last_position = lastExp.get('position',None)\r\n languages_sublist = applicant.get('languages',None)\r\n \" \".join(str(x) for x in languages_sublist)\r\n graduations = applicant.get('graduations', None)\r\n custom_fields = applicant.get('customFields',None)\r\n # (Vitor) Graduations is a list so we need \r\n for element in graduations:\r\n graduations_course = element.get('school', None)\r\n graduations_school = element.get('course', None)\r\n graduations_current = element.get('current', None)\r\n for element in custom_fields:\r\n if element[\"code\"] == \"phones\":\r\n phone_list = element.get('value', None)\r\n phone_sublist = phone_list\r\n phone = \" \".join(str(x) for x in phone_sublist) \r\n if element[\"code\"] == \"segments\":\r\n segments_list = element.get('value', None)\r\n segments_sublist = segments_list\r\n segments = \" \".join(str(x) for x in segments_sublist)\r\n print(segments)\r\n if element[\"code\"] == \"maritalStatus\":\r\n maritalStatus = element.get('value', None)\r\n print(maritalStatus)\r\n if element[\"code\"] == \"58b98a5f01f3797c0b69e749\":\r\n role = element.get('value', None)\r\n print(role)\r\n if element[\"code\"] == \"gender\":\r\n gender = element.get('value', None)\r\n print(gender)\r\n try:\r\n name\r\n except NameError:\r\n name = None\r\n try:\r\n applicant_id\r\n except NameError:\r\n applicant_id = None\r\n try:\r\n createdAt\r\n except NameError:\r\n createdAt = None\r\n try:\r\n updatedAt\r\n except NameError:\r\n updatedAt = None\r\n try:\r\n evaluationAverage\r\n except NameError:\r\n evaluationAverage = None\r\n try:\r\n ratingAverage\r\n except NameError:\r\n ratingAverage = None\r\n try:\r\n source\r\n except NameError:\r\n source = None\r\n try:\r\n last_position\r\n except NameError:\r\n last_position = None\r\n try:\r\n languages\r\n except NameError:\r\n languages = None\r\n try:\r\n phone\r\n except NameError:\r\n phone = None\r\n try:\r\n segments\r\n except NameError:\r\n segments = None\r\n try:\r\n maritalStatus\r\n except NameError:\r\n maritalStatus = None\r\n try:\r\n role\r\n except NameError:\r\n role = None \r\n try:\r\n gender\r\n except NameError:\r\n gender = None\r\n try:\r\n graduations_course\r\n except NameError:\r\n graduations_course = None\r\n try:\r\n graduations_school\r\n except NameError:\r\n graduations_school = None\r\n try:\r\n graduations_current\r\n except NameError:\r\n graduations_current = None\r\n\r\n \r\n new_applicant = applicant_info(name=name,applicant_id=applicant_id,created_at=createdAt,updated_at=updatedAt,rating_average=ratingAverage,source_downloaded=source,last_position=last_position,languages=languages,phone=phone,segments=segments,marital_status=maritalStatus,applicant_role=role,gender=gender, graduations_course=graduations_course,graduations_school=graduations_school, graduations_current=graduations_current)\r\n print(\"criado o objeto\")\r\n scoped_session.add(new_applicant)\r\n print(\"adicionado o objeto a sessão\")\r\n scoped_session.commit()\r\n print(\"enviado para o servidor\")\r\n \r\n if(len(page_data) == 0):\r\n break\r\n","sub_path":"applicant.py","file_name":"applicant.py","file_ext":"py","file_size_in_byte":6199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"17620252","text":"import streamlit as st\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.ensemble import ExtraTreesClassifier\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom PIL import Image\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nimport seaborn as sns\r\n\r\ndef app():\r\n\r\n df = pd.read_csv('jantungg.csv')\r\n df.drop('Unnamed: 0', axis='columns', inplace=True)\r\n X = df[['ejection_fraction',\r\n 'serum_creatinine',\r\n 'time'\r\n ]]\r\n Y = df['DEATH_EVENT']\r\n\r\n col, coll = st.columns(2)\r\n x = df.iloc[:, :-1]\r\n\r\n model = ExtraTreesClassifier()\r\n model.fit(x, Y)\r\n feat_importances = pd.Series(model.feature_importances_, index=x.columns)\r\n with col:st.write(feat_importances)\r\n\r\n image = Image.open('fi.jpg')\r\n coll.image(image,\r\n caption='Feature Selection merupakan kegiatan pemodelan atau penganalisaan data yang dilakukan secara preprocessing dan bertujuan untuk memilih fitur optimal dan mengesampingkan fitur yang tidak berpengaruh terhadap target',\r\n use_column_width=True\r\n )\r\n\r\n image = Image.open('imp.png')\r\n st.image(image,\r\n caption='Histogram Feature Selection',\r\n use_column_width=True\r\n )\r\n\r\n col1, col2 = st.columns(2)\r\n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=2)\r\n\r\n sc = StandardScaler()\r\n X_train = sc.fit_transform(X_train)\r\n X_test = sc.transform(X_test)\r\n\r\n dtc = DecisionTreeClassifier(max_leaf_nodes=3)\r\n dtc.fit(X_train, y_train)\r\n\r\n acc = dtc.score(X_test, y_test)*100\r\n acc = acc.astype(int)\r\n with col1: st.subheader(\"Model DecisionTree\"), st.write('**Accuracy: **', acc,'%')\r\n\r\n fig5 = plt.figure(figsize=(8, 5))\r\n conf_matrix = confusion_matrix(dtc.predict(X_test), y_test)\r\n sns.heatmap(conf_matrix, cmap='coolwarm', annot=True)\r\n with col2: st.subheader(\"Confusion Matrix\"), st.pyplot(fig5)\r\n\r\n col3, col4 = st.columns(2)\r\n with col3: st.text(\"\"), \\\r\n st.text(\"\"), \\\r\n st.text(\"\"), \\\r\n st.text(\"\"), \\\r\n st.text(\"\"), \\\r\n st.text(\"\"), \\\r\n st.text(\"\"), \\\r\n st.text(\"\"), \\\r\n st.text(\"\"), \\\r\n st.text('M.Randy Anugerah'), \\\r\n st.text(\"\"), \\\r\n st.text(\"\"), \\\r\n st.text('This Page Still in Beta Test')\r\n\r\n image = Image.open('fic.png')\r\n col4.image(image,\r\n caption='',\r\n use_column_width=True\r\n )\r\n","sub_path":"app/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"556015287","text":"\"\"\"Main GUI class\"\"\"\nimport sys\nimport pygame\nimport random\nfrom GuiLine import *\nfrom GuiCross import *\nfrom GuiCrossControl import *\nimport GuiConstants\nfrom pgu import gui\n\ndef log_constant_change(constant, value):\n \"\"\"Logs a constant change\"\"\"\n GuiConstants.LOGSFILE.write('CHANGE;' + constant + ':' + str(value) + '\\n')\n GuiConstants.LOGSFILE.flush()\n os.fsync(GuiConstants.LOGSFILE.fileno())\n\ndef toggle_run_control():\n \"\"\"Toggle run control callback\"\"\"\n if GuiConstants.RUN_CONTROL == 1:\n GuiConstants.RUN_CONTROL = 0\n else:\n GuiConstants.RUN_CONTROL = 1\n\ndef toggle_trlight(toggle_in):\n \"\"\"Change toggle traffic light\"\"\"\n if toggle_in.value:\n GuiConstants.USE_TRAFFIC_LIGHT = 1\n else:\n GuiConstants.USE_TRAFFIC_LIGHT = 0\n \n log_constant_change('TR_LIGHT', toggle_in.value)\n\ndef chg_ant_number(sliderin, labelin):\n \"\"\"Change ant number callback\"\"\"\n GuiConstants.ANT_NUMBER = sliderin.value\n labelin.value = str(GuiConstants.ANT_NUMBER)\n log_constant_change('ANT_NUMBER', GuiConstants.ANT_NUMBER)\n\ndef chg_iter_number(sliderin, labelin):\n \"\"\"Change iterations number callback\"\"\"\n GuiConstants.ITERATIONS_NUMBER = sliderin.value\n labelin.value = str(GuiConstants.ITERATIONS_NUMBER)\n log_constant_change('ITERATIONS_NUMBER', GuiConstants.ITERATIONS_NUMBER)\n\ndef chg_q_value(sliderin, labelin):\n \"\"\"Change q value callback\"\"\"\n GuiConstants.Q_VALUE = sliderin.value / 10.0\n labelin.value = str(GuiConstants.Q_VALUE)\n log_constant_change('Q_VALUE', GuiConstants.Q_VALUE)\n\ndef chg_a_value(sliderin, labelin):\n \"\"\"Change a value callback\"\"\"\n GuiConstants.A_VALUE = sliderin.value / 10.0\n labelin.value = str(GuiConstants.A_VALUE)\n log_constant_change('A_VALUE', GuiConstants.A_VALUE)\n\ndef chg_p_value(sliderin, labelin):\n \"\"\"Change p value callback\"\"\"\n GuiConstants.P_VALUE = sliderin.value / 10.0\n labelin.value = str(GuiConstants.P_VALUE)\n log_constant_change('P_VALUE', GuiConstants.P_VALUE)\n\ndef chg_b_value(sliderin, labelin):\n \"\"\"Change b value callback\"\"\"\n GuiConstants.B_VALUE = sliderin.value\n labelin.value = str(GuiConstants.B_VALUE)\n log_constant_change('B_VALUE', GuiConstants.B_VALUE)\n\ndef chg_interval(sliderin, labelin):\n \"\"\"Change the interval callback\"\"\"\n GuiConstants.INTERVAL = sliderin.value * 1000\n labelin.value = str(sliderin.value)\n log_constant_change('INTERVAL', GuiConstants.INTERVAL)\n\ndef chg_random_value(sliderin, labelin):\n \"\"\"Change random rate callback\"\"\"\n GuiConstants.RANDOM_RATE = sliderin.value / 10.0\n labelin.value = str(GuiConstants.RANDOM_RATE)\n log_constant_change('RANDOM_V', GuiConstants.RANDOM_RATE)\n\ndef main():\n \"\"\"Main function\"\"\"\n current_id = 0\n size = width, height = 1280, 1024\n green = (0, 250, 0)\n fps = 30\n timewarp = 1.0\n\n #init\n pygame.init()\n screen = pygame.display.set_mode(size)\n pygame.display.set_caption('Crossroads test')\n\n #init GUI\n appgui = ini_gui()\n\n #Fill background\n background = pygame.Surface(screen.get_size())\n background = background.convert()\n background.fill(green)\n\n #Blit everything to the screen\n screen.blit(background, (0, 0))\n pygame.display.flip()\n\n #Init lines\n lines = ini_lines(width / 2.0, height / 2.0, width / 4.0, 0)\n lines2 = ini_lines(width / 2.0, height /2.0, (width - (width / 4.0)), 0)\n lines3 = ini_lines(width / 2.0, height / 2.0, width / 4.0, height - (height / 2.0))\n lines4 = ini_lines(width / 2.0, height / 2.0, (width - (width / 4.0)), height - (height / 2.0))\n\n #Init crossroad and controller\n crossroad = GuiCross((width / 4.0, height / 4.0))\n crossroad2 = GuiCross((width - (width / 4.0), height / 4.0))\n crossroad3 = GuiCross((width / 4.0, height - (height / 4.0)))\n crossroad4 = GuiCross((width - (width / 4.0), height - (height / 4.0)))\n cross_control = GuiCrossControl(crossroad)\n cross_control2 = GuiCrossControl(crossroad2)\n cross_control3 = GuiCrossControl(crossroad3)\n cross_control4 = GuiCrossControl(crossroad4)\n\n # Initialise clock\n clock = pygame.time.Clock()\n carsclock = pygame.time.Clock()\n carstime = 0\n appgui.paint()\n\n #Event loop\n while 1:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n GuiConstants.LOGSFILE.close()\n return\n if event.type == pygame.USEREVENT:\n add_car_event([lines, lines2, lines3, lines4], event.car)\n else:\n appgui.event(event)\n\n if GuiConstants.RUN_CONTROL == 0:\n continue\n\n #time operations\n clock.tick(fps)\n dt = timewarp / fps\n\n carstime += carsclock.tick()\n if carstime > 200:\n select_cross = random.random()\n\n if select_cross < 0.25:\n current_id += check_add_car(lines, current_id, [1, 2])\n elif select_cross < 0.5:\n current_id += check_add_car(lines2, current_id, [1, 3])\n elif select_cross < 0.75:\n current_id += check_add_car(lines3, current_id, [0, 2])\n else:\n current_id += check_add_car(lines4, current_id, [0, 3])\n\n carstime = 0\n\n #Update logic\n for current_line in lines:\n current_line.update(dt)\n for current_line in lines2:\n current_line.update(dt)\n for current_line in lines3:\n current_line.update(dt)\n for current_line in lines4:\n current_line.update(dt)\n\n #Cross control\n cross_control.check_control_entries(lines)\n cross_control2.check_control_entries(lines2)\n cross_control3.check_control_entries(lines3)\n cross_control4.check_control_entries(lines4)\n\n #Draw objects\n for current_line in lines:\n current_line.draw()\n for current_line in lines2:\n current_line.draw()\n for current_line in lines3:\n current_line.draw()\n for current_line in lines4:\n current_line.draw()\n\n #Draw crossroad\n crossroad.draw()\n crossroad2.draw()\n crossroad3.draw()\n crossroad4.draw()\n\n for current_line in lines:\n current_line.render()\n for current_line in lines2:\n current_line.render()\n for current_line in lines3:\n current_line.render()\n for current_line in lines4:\n current_line.render()\n\n appgui.update()\n pygame.display.flip()\n\ndef ini_lines(width, height, posw, posh):\n \"\"\"Initialize the lines\"\"\"\n lines = []\n lines.append(GuiLine('N', height, (posw, posh)))\n lines.append(GuiLine('S', height, (posw - LINE_WIDTH, posh)))\n lines.append(GuiLine('E', width, (posw - (width / 2.0), posh + (height / 2.0))))\n lines.append(GuiLine('W', width, (posw - (width / 2.0), (posh + (height / 2.0)) - LINE_WIDTH)))\n\n return lines\n\ndef check_add_car(lines, current_id, allow_add):\n \"\"\"Random car adder\"\"\"\n\n if GuiConstants.CAR_ADD_MODE == 'R':\n return check_add_car_random(lines, current_id, allow_add)\n else:\n return check_add_car_time(lines, current_id)\n\ndef check_add_car_random(lines, current_id, allow_add):\n \"\"\"Random car adder\"\"\"\n chk_car = random.random()\n\n if chk_car > GuiConstants.RANDOM_RATE:\n select_line = random.random()\n allow_nbr = len(allow_add)\n mult_rdm = 1.0 / allow_nbr\n iter_nbr = 1\n\n for current_line in allow_add:\n if select_line < (mult_rdm * iter_nbr):\n lines[current_line].add_car(current_id)\n return 1\n\n iter_nbr += 1\n\n return 0\n\ndef check_add_car_time(lines, current_id):\n \"\"\"Checks if a car form the rep file should be added\"\"\"\n\n current_time = pygame.time.get_ticks()\n check_next = True\n added_cars = 0\n\n while check_next: \n if GuiConstants.CURRENT_LINE >= len(GuiConstants.REPFILE_LINES):\n return 0\n\n current_car = GuiConstants.REPFILE_LINES[GuiConstants.CURRENT_LINE]\n\n if not current_car.startswith('INI') and not current_car.startswith('CHANGE'):\n car_time = current_car.split(':')[2]\n car_id = current_car.split(':')[0]\n\n if int(car_time) <= current_time:\n car_dir = current_car.split(':')[3]\n car_dir = car_dir.replace('\\n', '')\n\n if car_dir == 'N':\n lines[0].add_car(car_id)\n elif car_dir == 'S':\n lines[1].add_car(car_id)\n elif car_dir == 'E':\n lines[2].add_car(car_id)\n elif car_dir == 'W':\n lines[3].add_car(car_id)\n\n GuiConstants.CURRENT_LINE += 1\n else:\n check_next = False\n\n else:\n GuiConstants.CURRENT_LINE += 1\n\n return 0\n\ndef add_car_event(group_lines, car_inn):\n \"\"\"Checks if an exit car is in the cars queue and adds it if needed\"\"\"\n\n for group in group_lines:\n for current_line in group:\n if current_line.rect.colliderect(car_inn.rect):\n current_line.add_car(car_inn.ident, car_inn)\n return\n\n #If the code reaches this line, the car is out\n timespent = car_inn.tickcarclock()\n GuiConstants.LOGSFILE.write(str(car_inn.ident) + ':' + str(timespent) + ':' + str(car_inn.entry_time) + ':' + car_inn.direction + '\\n')\n\ndef ini_gui():\n \"\"\"Initalizes GUI controls\"\"\"\n appgui = gui.App()\n appgui.connect(gui.QUIT, appgui.quit, None)\n #GUI container\n gui_container = gui.Container(align=-1, valign=-1)\n gui_table = gui.Table()\n #GIO STOP/RUN button\n gui_table.tr()\n btn_run = gui.Button(\"STOP/RUN\")\n btn_run.connect(gui.CLICK, toggle_run_control)\n gui_table.td(btn_run)\n\n create_check(gui_table, \"Traffic light\", toggle_trlight)\n\n if GuiConstants.USE_TRAFFIC_LIGHT == 0:\n #GUI iterations number slider\n create_slider(gui_table, \"Iterations number: \", GuiConstants.ITERATIONS_NUMBER, chg_iter_number, 5, 50)\n #GUI ants number slider\n create_slider(gui_table, \"Ants number: \", GuiConstants.ANT_NUMBER, chg_ant_number, 5, 25)\n #GUI q value slider\n create_slider(gui_table, \"q value: \", GuiConstants.Q_VALUE, chg_q_value, 0, 9, 10)\n #GUI a value slider\n create_slider(gui_table, \"a value: \", GuiConstants.A_VALUE, chg_a_value, 0, 9, 10)\n #GUI p value slider\n create_slider(gui_table, \"p value: \", GuiConstants.P_VALUE, chg_p_value, 0, 9, 10)\n #GUI b value slider\n create_slider(gui_table, \"b value: \", GuiConstants.B_VALUE, chg_p_value, 0, 5)\n else:\n #Traffic light interval\n create_slider(gui_table, \"Interval: \", GuiConstants.INTERVAL / 1000, chg_interval, 1, 20)\n\n #RANDOM RATE SLIDER\n create_slider(gui_table, \"Car frecuency: \", GuiConstants.RANDOM_RATE, chg_random_value, 0, 9, 10)\n\n #Add table to GUI\n gui_container.add(gui_table, 0, 0)\n appgui.init(gui_container)\n\n return appgui\n\ndef create_slider(gui_table, ctrl_label, ctrl_value, ctrl_callback, ctrl_min, ctrl_max, ctrl_mult = 1):\n \"\"\"Creates a slider to control a value\"\"\"\n gui_table.tr()\n gui_table.td(gui.Label(ctrl_label))\n txt = gui.Input(value=str(ctrl_value), width=30)\n gui_table.td(txt)\n slider = gui.HSlider(value=ctrl_value * ctrl_mult, min=ctrl_min, max=ctrl_max, size=20, width=120)\n slider.connect(gui.CHANGE, ctrl_callback, slider, txt)\n gui_table.td(slider)\n\ndef create_check(gui_table, ctrl_label, ctrl_callback):\n \"\"\"Creates a checkbox to control a value\"\"\"\n\n cb1 = gui.Switch()\n cb1.connect(gui.CHANGE, ctrl_callback, cb1)\n cb1l = gui.Label(ctrl_label)\n gui_table.add(cb1)\n gui_table.add(cb1l)\n gui_table.tr()\n\nif __name__ == '__main__':\n main()\n","sub_path":"pythonProject/gui/GuiMainMulti4.py","file_name":"GuiMainMulti4.py","file_ext":"py","file_size_in_byte":11922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"572989092","text":"import re\n\n\nclass WordTrie:\n def __init__(self):\n # 初始化词表。\n self.root = dict()\n\n def __repr__(self):\n # console的字符串显示。\n return str(self.root)\n\n def insert(self, string):\n # 添加词语到此词表中。\n index, node = self.findLastNode(string)\n if 're' in string:\n char = string\n new_node = dict()\n node[char] = new_node\n new_node = new_node\n else:\n for char in string[index:]:\n new_node = dict()\n node[char] = new_node\n node = new_node\n\n def sep(self, string, build=None):\n # 用于分割字符串,然后进行字符串的操作。\n index, node = self.findLastNode(string)\n tmp_node_key = list(node.keys())\n if tmp_node_key:\n tmp_node_key = tmp_node_key[0]\n else:\n tmp_node_key = ''\n if not build and 're' in tmp_node_key:\n tmp_node_key = tmp_node_key.replace('re', '')\n result = re.findall(tmp_node_key, string[index:])\n if result:\n result = result[0]\n else:\n result = string[:index]\n return result, string[index:]\n else:\n return string[:index], string[index:]\n\n def findLastNode(self, string):\n '''\n 寻找最后的节点,然后进行对应的操作。\n @param string: string to be searched\n @return: (index, node).\n index: int. first char(string[index]) of string not found in Trie tree. Otherwise, the length of string\n node: dict. node doesn't have string[index].\n '''\n node = self.root\n index = 0\n if 're' in string:\n char = string\n if char in node:\n node = node[char]\n else:\n while index < len(string):\n char = string[index]\n if char in node:\n node = node[char]\n else:\n break\n index += 1\n return (index, node)\n\n\ndef build_sentence_word_dict(word_dict=None):\n if word_dict is None:\n word_dict = {}\n if not (word_dict and isinstance(word_dict, dict)):\n raise Exception('word_dict must be dict')\n sentence_word_dict = {}\n for k, v in word_dict.items():\n tmp_trie = WordTrie()\n for i in v:\n tmp_trie.insert(i)\n sentence_word_dict[k] = tmp_trie\n return sentence_word_dict\n","sub_path":"pmnlp/word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"188016666","text":"from proteus import *\nfrom proteus.default_n import *\nfrom pressureincrement_p import *\n\nmesh = domain.MeshOptions\ntriangleOptions = triangleOptions\nnLayersOfOverlapForParallel = mesh.nLayersOfOverlapForParallel\n\nfemSpaces = {0:pbasis}\n\nstepController=FixedStep\n\n#numericalFluxType = PresInc.NumericalFlux\nnumericalFluxType = NumericalFlux.ConstantAdvection_exterior\nmatrix = LinearAlgebraTools.SparseMatrix\n\n#if openTop:\n# linearSmoother = None\n# multilevelLinearSolver = LinearSolvers.LU\n# levelLinearSolver = LinearSolvers.LU\n#else:\n# linearSmoother = LinearSolvers.NavierStokesPressureCorrection # pure neumann laplacian solver\n# multilevelLinearSolver = LinearSolvers.KSP_petsc4py\n# levelLinearSolver = LinearSolvers.KSP_petsc4py\n\nlinear_solver_options_prefix = 'phi_'\n\nif ct.useSuperlu:\n multilevelLinearSolver = LinearSolvers.LU\n levelLinearSolver = LinearSolvers.LU\nelse:\n multilevelLinearSolver = KSP_petsc4py\n levelLinearSolver = KSP_petsc4py\n parallelPartitioningType = parallelPartitioningType\n nLayersOfOverlapForParallel = nLayersOfOverlapForParallel\n nonlinearSmoother = None\n linearSmoother = None\n\n\nmultilevelNonlinearSolver = NonlinearSolvers.Newton\nlevelNonlinearSolver = NonlinearSolvers.Newton\n\n#linear solve rtolerance\n\nlinTolFac = 0.0\nl_atol_res = 0.01*phi_nl_atol_res\ntolFac = 0.0\nnl_atol_res = phi_nl_atol_res\nnonlinearSolverConvergenceTest = 'r'\nlevelNonlinearSolverConvergenceTest = 'r'\nlinearSolverConvergenceTest = 'r-true'\nmaxLineSearches=0\nperiodicDirichletConditions=None\n\nconservativeFlux = {0:'point-eval'} #'point-eval','pwl-bdm-opt'\n#conservativeFlux=None\n","sub_path":"2d/sediment/friction_angle_dambrek_sediment/pressureincrement_n.py","file_name":"pressureincrement_n.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"199280056","text":"#!/usr/bin/python\r\n#-*- coding: utf-8 -*-\r\nimport sys\r\nimport traceback\r\n\r\nfrom itsbox.operator import Config\r\nfrom itsbox.operator.Manager import ManagerProcess\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) == 1:\r\n manager = ManagerProcess(worker_count=Config.WORKER_COUNT)\r\n try:\r\n pid = manager.lock()\r\n if pid is None:\r\n try:\r\n manager.start()\r\n except BaseException as e:\r\n print('Failed to start operator manager : Exception=\"%s\"' % e)\r\n traceback.print_exc()\r\n finally:\r\n manager.release()\r\n else:\r\n print('Another manager is running. Please stop the booted manager first : PID=%d' % pid)\r\n except BaseException as e:\r\n print('Exception occurred during starting up the manager : Exception=\"%s\"' % e)\r\n else:\r\n print('Unknown argument or Too many arguments')\r\n print('USAGE : python %s' % sys.argv[0])\r\n\r\n","sub_path":"itsbox/operator/launcher/Startup.py","file_name":"Startup.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"524372457","text":"import copy\nfrom typing import Optional\n\nimport sqlalchemy\nfrom sqlalchemy.pool import NullPool\n\nfrom snowshu.core.models.credentials import (DATABASE, HOST, PASSWORD, USER,\n Credentials)\nfrom snowshu.logger import Logger\n\nlogger = Logger().logger\n\n\nclass BaseSQLAdapter:\n\n def __init__(self):\n self.CLASSNAME = self.__class__.__name__ # noqa pylint: disable=invalid-name\n for attr in ('REQUIRED_CREDENTIALS', 'ALLOWED_CREDENTIALS',\n 'MATERIALIZATION_MAPPINGS',):\n if not hasattr(self, attr):\n raise NotImplementedError(\n f'SQL adapter requires attribute {attr} but was not set.')\n\n @property\n def credentials(self) -> dict:\n return self._credentials\n\n @credentials.setter\n def credentials(self, value: Credentials) -> None:\n for cred in self.REQUIRED_CREDENTIALS:\n if value.__dict__[cred] is None:\n raise KeyError(\n f\"{self.CLASSNAME} requires missing credential {cred}.\")\n ALL_CREDENTIALS = self.REQUIRED_CREDENTIALS + self.ALLOWED_CREDENTIALS # noqa pylint: disable=invalid-name\n for val in [val for val in value.__dict__.keys() if (\n val not in ALL_CREDENTIALS and value.__dict__[val] is not None)]:\n raise KeyError(\n f\"{self.CLASSNAME} received extra argument {val} this is not allowed\")\n\n self._credentials = value\n\n def get_connection(\n self,\n database_override: Optional[str] = None,\n schema_override: Optional[str] = None) -> sqlalchemy.engine.base.Engine:\n \"\"\"Creates a connection engine without transactions.\n\n By default uses the instance credentials unless database or\n schema override are provided.\n \"\"\"\n if not self._credentials:\n raise KeyError(\n 'Adapter.get_connection called before setting Adapter.credentials')\n\n logger.debug(f'Aquiring {self.CLASSNAME} connection...')\n overrides = dict(\n (k,\n v) for (\n k,\n v) in dict(\n database=database_override,\n schema=schema_override).items() if v is not None)\n\n engine = sqlalchemy.create_engine(self._build_conn_string(\n overrides), poolclass=NullPool, isolation_level=\"AUTOCOMMIT\")\n logger.debug(f'engine aquired. Conn string: {repr(engine.url)}')\n return engine\n\n def _build_conn_string(self, overrides: dict = None) -> str:\n \"\"\"This is the most basic implementation of a connection string\n possible and is intended to be extended.\n\n generates a database url per https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls\n passes any overrides via override object\n \"\"\"\n if not hasattr(self, 'dialect'):\n # attempt to infer the dialect\n raise KeyError(\n 'base_sql_adapter unable to build connection string; required param `dialect` to infer.')\n if not overrides:\n overrides = dict()\n\n self._credentials.urlencode()\n conn_string, used_credentials = self._build_conn_string_partial(\n self.dialect, overrides.get('database'))\n instance_creds = copy.deepcopy(self._credentials)\n for key in overrides.keys():\n instance_creds.__dict__[key] = overrides[key]\n get_args = '&'.join([f\"{arg}={instance_creds.__dict__[arg]}\"\n for arg in (set(self.ALLOWED_CREDENTIALS) - used_credentials)\n if arg in vars(instance_creds) and instance_creds.__dict__[arg] is not None])\n return conn_string + get_args\n\n def _build_conn_string_partial(\n self, dialect: str, database: Optional[str] = None) -> tuple:\n \"\"\"abstracted to make this easier to override.\n\n RETURNS: a tuple with the conn string and a tuple of credential args used in that string\n \"\"\"\n database = database if database is not None else self._credentials.database\n return (\n f\"{dialect}://{self._credentials.user}:{self._credentials.password}@{self._credentials.host}/{database}?\",\n {USER, PASSWORD, HOST, DATABASE, }\n )\n","sub_path":"snowshu/adapters/base_sql_adapter.py","file_name":"base_sql_adapter.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"622723239","text":"from basic import db, Puppy\n\n########## create\nmy_puppy = Puppy('Rufus', 10)\ndb.session.add(my_puppy)\ndb.session.commit()\n\nmy_puppy = Puppy('Gogo', 1)\ndb.session.add(my_puppy)\ndb.session.commit()\n\n########## read\n# This returns a list of the puppy objects in the table\nall_puppies = Puppy.query.all()\nprint(all_puppies)\n\n# select by id\npuppy_one = Puppy.query.get(1)\nprint(puppy_one.name)\n\npuppy_three = Puppy.query.get(3)\nprint(puppy_three.name)\n\n# Filters\npuppy_sam = Puppy.query.filter_by(name='Sammy') # Returns list\nprint(puppy_sam.all())\nprint('\\n')\n\n# produce some sql code for us\npuppy_age_one = Puppy.query.filter_by(age=10)\n# this prints out the list of all the puppies where the name is Frankie\nprint(puppy_age_one.all())\n\n########## update\n# first grab the data\nfirst_puppy = Puppy.query.get(1)\n# edit the attribute you want\nfirst_puppy.age = 10\n# update it\ndb.session.add(first_puppy)\n# commit it\ndb.session.commit()\n\n########## delete\nsecond_pup = Puppy.query.get(2)\ndb.session.delete(second_pup)\ndb.session.commit()\n\n\n########## print out\nall_puppies = Puppy.query.all()\nprint(all_puppies)","sub_path":"python/courses/jose_portilla/flask/sandbox/10_databases/10_1_flask_and_databases_practice/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"636788049","text":"#!/usr/bin/env python\n# coding: utf-8\nimport requests,re\nimport json\nimport sys\nfrom bs4 import BeautifulSoup as bs\nstate_index = (sys.argv[1])\nprint (state_index)\nfilename = sys.argv[2]+\".jsonl\"\nopen(filename,\"w\").write(\"\")\nlastPageFromCli = int(sys.argv[3]) or 0\ndef get_data(ngoid,token):\n cookie = f'ci_session=qra1cna4ijclvtem2hlr7k7v7ej98fe6; csrf_cookie_name={token}'\n print (cookie)\n headers = {\n 'Connection': 'keep-alive',\n 'sec-ch-ua': '\"Google Chrome\";v=\"87\", \" Not;A Brand\";v=\"99\", \"Chromium\";v=\"87\"',\n 'Accept': '*/*',\n 'DNT': '1',\n 'X-Requested-With': 'XMLHttpRequest',\n 'sec-ch-ua-mobile': '?0',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Origin': 'https://ngodarpan.gov.in',\n 'Sec-Fetch-Site': 'same-origin',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Dest': 'empty',\n 'Referer': 'https://ngodarpan.gov.in/index.php/home/statewise_ngo/116/35/1',\n 'Accept-Language': 'en-US,en;q=0.9,hi-IN;q=0.8,hi;q=0.7,da;q=0.6',\n 'Cookie': f'ci_session=qra1cna4ijclvtem2hlr7k7v7ej98fe6; csrf_cookie_name={token}',\n \n }\n data = {\n 'id': ngoid,\n 'csrf_test_name': token,\n }\n response = requests.post('https://ngodarpan.gov.in/index.php/ajaxcontroller/show_ngo_info', headers=headers,data=data)\n return response\ndef get_cookie():\n headers = {\n 'Connection': 'keep-alive',\n 'sec-ch-ua': '\"Google Chrome\";v=\"87\", \" Not;A Brand\";v=\"99\", \"Chromium\";v=\"87\"',\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'DNT': '1',\n 'X-Requested-With': 'XMLHttpRequest',\n 'sec-ch-ua-mobile': '?0',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',\n 'Sec-Fetch-Site': 'same-origin',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Dest': 'empty',\n 'Referer': 'https://ngodarpan.gov.in/index.php/home/statewise_ngo/8046/19/1',\n 'Accept-Language': 'en-US,en;q=0.9,hi-IN;q=0.8,hi;q=0.7,da;q=0.6',\n \n }\n\n response = requests.get('https://ngodarpan.gov.in/index.php/ajaxcontroller/get_csrf', headers=headers)\n return response\n\ndef store_data(ngoid,state):\n c = get_cookie()\n active_token = c.json().get('csrf_token')\n data=get_data(ngoid,active_token).json()\n open(f\"{filename}\",\"a\").write(json.dumps(data)+\"\\n\")\n\ndef gotopage(homepage,pagenum):\n root = \"https://ngodarpan.gov.in/index.php/home/statewise_ngo/\"\n numsections = homepage.replace(root,\"\").split(\"/\")\n numsections[-1] = str(pagenum)\n newHomePage = root+\"/\".join(numsections)\n return newHomePage\n\ndef process_state(state):\n last_page = None\n statehtml = requests.get(state)\n try:\n for link in bs(statehtml.content).select(\"a\"):\n if link.text == \"Last\":\n last_page=link.attrs[\"data-ci-pagination-page\"]\n except:\n pass\n if not last_page:\n last_page = lastPageFromCli\n for i in range(1,int(last_page)+1):\n pagetovisit = gotopage(state,i)\n pagehtml = requests.get(pagetovisit,timeout=10).content\n bspagehtml = bs(pagehtml)\n tbl = bspagehtml.select(\".ibox-content tbody tr\")\n for tr in tbl:\n tds = tr.select(\"a\")[0].attrs[\"onclick\"]\n number = re.sub(r\"\\D\", \"\", tds)\n print (int(number))\n try:\n store_data(int(number),state_index)\n except Exception as e:\n print (e)\n pass\n\nprocess_state(state_index)\n\n","sub_path":"ngo.py","file_name":"ngo.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"652772195","text":"import pandas as pd\nimport os\nfrom shutil import copy\n\nmainDir = \"C:/Users/mostafaosama2/Desktop/Kaggle-Data\"\nregressionDir = \"C:/Users/mostafaosama2/Desktop/regressionSet\"\n\n# read labels into df\ncsvfile = mainDir + \"/train_labels.csv\"\ndf = pd.read_csv(csvfile)\n\n# get the first 1000 train images\nimgList = []\nfor file in os.listdir(mainDir + \"/train\")[0:80000]:\n\tif file.endswith('.tif'):\n\t\timgList.append(file.split('.')[0])\n\n\nfor image in imgList:\n\tcopy(os.path.join(mainDir + '/train', image + '.tif'), regressionDir + \"/train\")\n\tprint(image)\n\nimgtestList = []\nfor file in os.listdir(mainDir + \"/test\")[0:20000]:\n\tif file.endswith('.tif'):\n\t\timgtestList.append(file.split('.')[0])\n\t\t\nfor image in imgtestList:\n\tcopy(os.path.join(mainDir + '/test', image + '.tif'), regressionDir + \"/test\")\n\tprint(image)\n\n# adjust the df to contain the same images\nlabels_true = []\nfor image in imgList:\n\tlabel_index = df[df[\"id\"] == image.split(\".\")[0]].index[0]\n\tlabels_true.append(df[\"label\"][label_index])\n\n\nd = {'id': imgList, 'label': labels_true}\ndf_new = pd.DataFrame(data=d)\n\ndf = df[(df.id.isin(imgList))]\n\nprint(df_new)\ndf_new.to_csv(r'C:/Users/mostafaosama2/Desktop/regressionSet/first1000New.csv')\n\nprint(imgList == df_new[\"id\"].values)","sub_path":"scripts/first_1000.py","file_name":"first_1000.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"292395565","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse, Http404, JsonResponse,response\nfrom django.contrib import messages\nfrom django.db.models import Count, Q\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Song, Rate, Play\nfrom core.models import MyUser\nfrom .forms import SongForm, RateForm\nfrom .filters import SongFilter\nfrom music.conf import anti_spider\n\n\n@login_required\ndef song_list(request):\n\n if anti_spider(request):\n return response.HttpResponseNotFound(\n content=\"

Not Found

The requested URL \" +\n request.path_info +\n \" was not found on this server.

\"\n )\n\n f = SongFilter(request.GET, queryset=Song.objects.all())\n\n context = {\n \"filter\": f,\n }\n\n return render(request, \"songs/song_list.html\", context)\n\n\n@login_required\ndef song_detail(request, id):\n\n if anti_spider(request):\n return response.HttpResponseNotFound(\n content=\"

Not Found

The requested URL \" +\n request.path_info +\n \" was not found on this server.

\"\n )\n\n song = get_object_or_404(Song, pk=id)\n\n try:\n rate = Rate.objects.get(user=request.user.myuser, song=song)\n scores = [False for i in range(5)]\n scores[rate.score-1] = True\n except Rate.DoesNotExist:\n scores = [False for i in range(5)]\n scores[0] = True\n\n context = {\n \"song\": song,\n \"scores\": scores,\n }\n\n # return HttpResponse(\"song details!\")\n return render(request, \"songs/song_detail.html\", context)\n\n\n@login_required\ndef song_play(request, id, ptype, sid):\n try:\n song = Song.objects.get(pk=id)\n except Song.DoesNotExist:\n raise Http404\n\n if ptype == '1' or ptype == '0':\n play = Play(user=request.user.myuser,\n song=song,\n ptype=ptype,\n sourceid=sid)\n play.save()\n song.play_count=song.play_count+1\n song.save()\n elif ptype == '2':\n play = Play(user=request.user.myuser,\n song=song,\n ptype=ptype)\n play.save()\n song.play_count = song.play_count + 1\n song.save()\n else:\n raise Http404\n\n context = {\n \"song\": song,\n \"artist\": song.artists,\n }\n return render(request, \"songs/song_play.html\", context)\n\n\n@login_required\ndef play_list(request, id):\n\n try:\n user = MyUser.objects.get(pk=id)\n except MyUser.DoesNotExist:\n raise Http404\n\n plays = Play.objects.filter(user_id=id)\n\n context = {\n \"plays\": plays,\n \"user\": user,\n }\n\n return render(request, \"songs/play_list.html\", context)\n\n\n@login_required\ndef song_torate(request):\n user = request.user.myuser\n if request.method == 'POST':\n songid = request.POST.get('songid', '')\n score = request.POST.get('score', '')\n try:\n rate = Rate.objects.get(user=user, song_id=songid)\n diff = int(score) - rate.score\n cnt = 0\n except Rate.DoesNotExist:\n rate = Rate(user=user, song_id=songid, score=1)\n diff = score\n cnt = 1\n song = Song.objects.get(pk=songid)\n song.score = song.score + int(diff)\n song.count = song.count + int(cnt)\n song.save()\n rate.score = score\n rate.save()\n\n return JsonResponse({'state': 1})\n\n return JsonResponse({'state': -1})\n\n\n@login_required\ndef play_history(request):\n if anti_spider(request):\n return response.HttpResponseNotFound(\n content=\"

Not Found

The requested URL \" +\n request.path_info +\n \" was not found on this server.

\"\n )\n\n user = request.user.myuser\n play = Play.objects.filter(user=user)\n song = [p.song for p in play]\n timestamp = [p.timestamp for p in play]\n context = {\n \"song\": song,\n \"timestamp\": timestamp,\n }\n return render(request, \"core/play_history.html\", context)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"songs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"391774979","text":"import os\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation, Conv2D, BatchNormalization, Flatten, GlobalAveragePooling2D\n\nclass MobileNetV2():\n def __init__(self, config):\n self.input_shape = (config.input_shape, config.input_shape, 3)\n\n def build_model(self):\n base_model = tf.keras.applications.mobilenet_v2.MobileNetV2(\n input_shape=self.input_shape, include_top=False, weights=None)\n output = GlobalAveragePooling2D()(base_model.output)\n# output = Conv2D(64, 3, padding = 'same')(base_model.output)\n# output = BatchNormalization()(output)\n# output = Activation(\"relu\")(output)\n # output = Conv2D(256, 3, padding = 'same')(output)\n # output = BatchNormalization()(output)\n # output = Activation(\"relu\")(output)\n box = Dense(10,name=\"box\")(output)\n box_prob = box[:,:2]\n box_coords = box[:,2:]\n box_coords = tf.keras.layers.Lambda(lambda box_coords: tf.keras.activations.relu(box_coords,max_value=224))(box_coords)\n box_prob = tf.keras.layers.Lambda(lambda box_prob: tf.keras.activations.sigmoid(box_prob))(box_prob)\n \n\n\n# loc_layer_dense = Dense(10, activation = 'relu')(output)\n# conf_layer_dense = Dense(2, activation = 'sigmoid')(output)\n out= tf.keras.layers.concatenate(inputs = [box_prob,box_coords],axis = 1)\n# output = tf.keras.layers.concatenate([conf_layer_dense, loc_layer_dense], axis = -1)\n model = tf.keras.models.Model(base_model.input, out)\n return model\n\n\n\n","sub_path":"model/MobileNetV2.py","file_name":"MobileNetV2.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"241184141","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\"\"\"\nxopt MPI driver\n\nBasic usage:\n\nmpirun -n 4 python -m mpi4py.futures -m xopt.mpi.run xopt.yaml\n\n\n\"\"\"\n\nfrom xopt import Xopt, xopt_logo\n\nfrom mpi4py.futures import MPIPoolExecutor\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nmpi_rank = comm.Get_rank()\nmpi_size = comm.Get_size()\n\nimport argparse\nimport os\nimport sys\nfrom pprint import pprint\n\n\nARGS = [sys.argv[-1]]\n#ARGS = 'xopt.in'.split()\n\nparser = argparse.ArgumentParser(description='Configure xopt')\nparser.add_argument('input_file', help='input_file')\nargs = parser.parse_args(ARGS)\ninfile = args.input_file\n\nassert os.path.exists(infile), f'Input file does not exist: {infile}'\n\n\nif __name__ == \"__main__\":\n print(xopt_logo)\n print('_________________________________')\n print('Parallel execution with', mpi_size, 'workers') \n\n X = Xopt(infile)\n print(X)\n sys.stdout.flush() \n with MPIPoolExecutor() as executor:\n X.run(executor=executor)\n","sub_path":"xopt/mpi/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"256840315","text":"#!/bin/python\n\ntry:\n import copy\n import json\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\n\nclass Parser():\n def get_name( self, node ):\n return node.attrib.get( 'name' )\n\n def get_path( self, node ):\n return node.attrib.get( 'path' )\n\n def get_type( self, node ):\n return node.attrib.get( 'type' )\n\n def get_tag( self, node ):\n return node.tag\n\n def get_value( self, node ):\n return node.attrib.get( 'value' )\n\n def __init__( self, xmlfile ):\n self.net = {}\n\n self.xmltopology = xmlfile\n tree = ET.ElementTree( file=self.xmltopology )\n\n self.root = tree.getroot()\n\n for child in self.root:\n self.net.update( { self.get_name( child ): {}} )\n self.root = child\n\n self.topnet = self.net['topnet']\n \n def parse_model( self, root, top ):\n for child in root:\n if self.get_name( child ) == 'routing':\n top.update( {'routing': self.get_type( child )} )\n continue\n\n if self.get_type( child ) == 'Net':\n if top.has_key( 'subnets' ) == False:\n top.update( {'subnets': []} )\n\n newsubnet = {'name': self.get_name( child )}\n top['subnets'].append( newsubnet )\n subnetindex = top['subnets'].index( newsubnet )\n self.parse_model( child, top['subnets'][subnetindex] )\n continue\n\n if self.get_tag( child ) == 'replica':\n for i in range( len( top['subnets'] ) ):\n if top['subnets'][i].get( 'name' ) == self.get_path( child ):\n break\n break\n top['subnets'].append( copy.deepcopy( top['subnets'][i] ) )\n top['subnets'][i+1].update( {'name': self.get_name( child )} )\n continue\n\n if self.get_type ( child ) == 'Host':\n if top.has_key( 'hosts' ) == False:\n top.update( {'hosts': []} )\n\n newhost = {'name': self.get_name( child )} \n newhost.update( {'interfaces': []} )\n\n for interface in child:\n if self.get_type( interface ) == 'Interface':\n newhost['interfaces'].append( {'name': self.get_name( interface )} )\n hostindex = newhost['interfaces'].index( {'name': self.get_name( \n interface )} )\n\n for attribute in interface:\n if self.get_name( attribute ) == 'latency' or 'bit_rate' or 'emu':\n newhost['interfaces'][hostindex].update( {self.get_name( attribute ):\n self.get_value( attribute )} )\n\n top['hosts'].append( newhost )\n continue\n\n if self.get_type ( child ) == 'Router':\n if top.has_key( 'routers' ) == False:\n top.update( {'routers': []} )\n \n newrouter = {'name': self.get_name( child )}\n newrouter.update( {'interfaces': []} )\n\n for interface in child:\n newrouter['interfaces'].append( {'name': self.get_name( interface )} )\n routerindex = newrouter['interfaces'].index( {'name': self.get_name(\n interface )} ) \n\n for attribute in interface:\n if self.get_name( attribute ) == 'latency' or 'bit_rate' or 'emu':\n newrouter['interfaces'][routerindex].update( {self.get_name( \n attribute ): self.get_value( attribute )} )\n\n top['routers'].append( newrouter )\n continue\n\n if self.get_type ( child ) == 'Link':\n if top.has_key( 'links' ) == False:\n top.update( {'links': []} )\n\n newlink = {'name': self.get_name( child )}\n linkpath = ''\n\n for subchild in child:\n if self.get_tag( subchild ) == 'attribute':\n newlink.update( {self.get_name( subchild ): self.get_value( subchild )} )\n\n if self.get_tag( subchild ) == 'ref':\n linkpath += self.get_path( subchild )\n\n newlink.update( {'path': linkpath} )\n\n top['links'].append( newlink )\n continue\n\n def xml_to_json( self ):\n self.parse_model( self.root, self.topnet )\n \n return self.net\n\n def write_json( self ):\n jsonfile = self.xmltopology.replace( 'xml', 'json' )\n\n with open( jsonfile, 'w') as jsonout:\n json.dump( self.net, jsonout )\n","sub_path":"symbiosim-study/src/downscaler/vis/temp/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"323001727","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.urls import path\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n url(r'^api/', include('horses.api')),\n url(\n r'^api-auth/',\n include('rest_framework.urls', namespace='rest_framework')\n ),\n]\n","sub_path":"horsetrader/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"599703343","text":"from MovieLens_preProcessing import MovieLens_preProcessing\r\nfrom RBMAlgorithm import RBMAlgorithm\r\nfrom HybridAlgorithm import HybridAlgorithm\r\nfrom Evaluator import Evaluator\r\nfrom surprise import SVD\r\nfrom surprise.model_selection import GridSearchCV\r\n\r\nimport random\r\nimport numpy as np\r\n\r\n\r\n\r\ndef LoadMovieLensData():\r\n ml = MovieLens_preProcessing()\r\n print(\"Loading movie ratings...\")\r\n data = ml.loadMovieLensLatestSmall()\r\n print(\"\\nComputing movie popularity ranks so we can measure novelty later...\")\r\n rankings = ml.getPopularityRanks()\r\n return (ml, data, rankings)\r\n\r\nnp.random.seed(0)\r\nrandom.seed(0)\r\n\r\n\r\n(ml, evaluationData, rankings) = LoadMovieLensData()\r\n\r\n\r\nevaluator = Evaluator(evaluationData, rankings)\r\n\r\n\r\nSimpleRBM = RBMAlgorithm(epochs=40)\r\n\r\n\r\nprint(\"Searching for best parameters...\")\r\nparam_grid = {'n_epochs': [20, 30], 'lr_all': [0.005, 0.010],\r\n 'n_factors': [50, 100]}\r\ngs = GridSearchCV(SVD, param_grid, measures=['rmse', 'mae'], cv=3)\r\n\r\ngs.fit(evaluationData)\r\n\r\n\r\nprint(\"Best RMSE score attained: \", gs.best_score['rmse'])\r\n\r\n\r\nprint(gs.best_params['rmse'])\r\n\r\n\r\nevaluator = Evaluator(evaluationData, rankings)\r\n\r\nparams = gs.best_params['rmse']\r\nSVDtuned = SVD(n_epochs = params['n_epochs'], lr_all = params['lr_all'], n_factors = params['n_factors'])\r\n\r\n\r\nHybrid = HybridAlgorithm([SimpleRBM, SVDtuned], [0.5, 0.5])\r\n\r\nevaluator.AddAlgorithm(SimpleRBM, \"RBM\")\r\nevaluator.AddAlgorithm(SVDtuned, \"SVD - Tuned\")\r\nevaluator.AddAlgorithm(Hybrid, \"Hybrid\")\r\n\r\nevaluator.Evaluate(False)\r\n\r\nevaluator.SampleTopNRecs(ml)\r\n","sub_path":"HybridStarter.py","file_name":"HybridStarter.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"77810404","text":"__author__ = 'Mohamed Morsy'\nfrom django.forms import ModelForm\nfrom django import forms\nfrom crispy_forms import *\nfrom crispy_forms.layout import *\nfrom crispy_forms.bootstrap import *\nfrom hs_modelinstance.models import *\nfrom hs_core.forms import BaseFormHelper\nfrom hs_core.hydroshare import users\n\nclass MetadataField(layout.Field):\n def __init__(self, *args, **kwargs):\n kwargs['css_class'] = 'form-control input-sm'\n super(MetadataField, self).__init__(*args, **kwargs)\n\nclass ModelOutputFormHelper(BaseFormHelper):\n def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None, *args, **kwargs):\n # the order in which the model fields are listed for the FieldSet is the order these fields will be displayed\n # for ModelOutput we have only one field includes_output\n layout = Layout(\n MetadataField('includes_output'),\n )\n kwargs['element_name_label'] = 'Includes output files?'\n super(ModelOutputFormHelper, self).__init__(allow_edit, res_short_id, element_id, element_name, layout, *args,\n **kwargs)\n\n\nclass ModelOutputForm(ModelForm):\n includes_output = forms.TypedChoiceField(choices=((True, 'Yes'), (False, 'No')), widget=forms.RadioSelect(attrs={'style': 'width:auto;margin-top:-5px'}))\n\n def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):\n super(ModelOutputForm, self).__init__(*args, **kwargs)\n self.helper = ModelOutputFormHelper(allow_edit, res_short_id, element_id, element_name='ModelOutput')\n\n class Meta:\n model = ModelOutput\n fields = ('includes_output',) \n\nclass ModelOutputValidationForm(forms.Form):\n includes_output = forms.TypedChoiceField(choices=((True, 'Yes'), (False, 'No')))\n\n def clean_includes_output(self):\n data = self.cleaned_data['includes_output']\n if data == u'False':\n return False\n else:\n return True\n\n\n# ExecutedBy element forms\nclass ExecutedByFormHelper(BaseFormHelper):\n def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None, *args, **kwargs):\n # the order in which the model fields are listed for the FieldSet is the order these fields will be displayed\n layout = Layout(\n MetadataField('model_name'),\n HTML(\"\"\"\n
\n \n \n \n \n \n \n \n
Description:
Release Date:
Version:
Language:
Operating System:
Url:
\n
\n \"\"\"),\n )\n\n kwargs['element_name_label'] = 'Model Program used for execution'\n super(ExecutedByFormHelper, self).__init__(allow_edit, res_short_id, element_id, element_name, layout, *args,\n **kwargs)\n\n\nclass ExecutedByForm(ModelForm):\n def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):\n super(ExecutedByForm, self).__init__(*args, **kwargs)\n self.helper = ExecutedByFormHelper(allow_edit, res_short_id, element_id, element_name='ExecutedBy')\n\n # get all model program resources\n mp_resource = users.get_resource_list(type=['ModelProgramResource'])\n\n # set model programs resources in choice list\n CHOICES = (('Unspecified', 'Unspecified'),) + tuple((r.short_id, r.title) for r in mp_resource.values()[0])\n\n # Set the choice lists as the file names in the content model\n self.fields['model_name'].choices = CHOICES\n\n class Meta:\n model = ExecutedBy\n exclude = ('content_object', 'model_program_fk',)\n\n\nclass ExecutedByValidationForm(forms.Form):\n model_name = forms.CharField(max_length=200)\n model_program_fk = forms\n\n","sub_path":"hs_modelinstance/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"111539794","text":"from flask import Flask\n\nfrom candleCharts.candle_crawling import candleController\nfrom new_magic_formula.model import Recommendation_Stock_Model\nimport json\nfrom flask_cors import CORS\n\nfrom news.Read_csv import Read_csv_create_wordcloud\n\napp = Flask(__name__)\n\n\n@app.route('/recommendation//', methods=['GET'])\ndef recommend_stock(period, propensity):\n period = period\n propensity = propensity\n print(period, propensity)\n recommend_stock_model = Recommendation_Stock_Model()\n return json.dumps(recommend_stock_model.recommendation_listing(period=period, propensity=propensity))\n\n\n@app.route('/cloud', methods=['GET'])\ndef create_wordcloud_using_csv():\n C = Read_csv_create_wordcloud()\n result = C.read()\n print(result)\n return result\n\n\n@app.route('/stocks/candle/', methods=['GET'])\ndef getCandle(symbol):\n symbol = symbol\n a = candleController()\n app_result = a.candle_crawling(symbol=symbol)\n return json.dumps(app_result)\n\n\nCORS(app)\nif __name__ == '__main__':\n app.run()\n","sub_path":"backend_python/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"238426910","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\n\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\n\ndef accuracy(model, dataloader, batch_size, gpu=False):\n if gpu and torch.cuda.is_available():\n model.cuda()\n model.eval()\n\n # number of total (context_heroes, center_hero)\n length = len(dataloader)*batch_size\n count = 0\n for teams, targets in dataloader:\n if gpu and torch.cuda.is_available():\n teams = teams.cuda()\n targets = targets.cuda()\n inputs = autograd.Variable(teams)\n targets = autograd.Variable(targets.view(-1))\n out = model(inputs)\n\n # idx is the index of the maximum value\n val, idx = torch.max(out, dim=1)\n\n # count how many predictions are right and convert to python int\n count += idx.eq(targets).sum().cpu().data[0]\n return count/length\n\ndef make_plot_color(x, y, hero2ix):\n\n # divide heroes to their own categories/roles\n tank = set(['dva', 'orisa', 'reinhardt', 'roadhog', 'winston', 'zarya'])\n supporter = set(['ana', 'lucio', 'mercy', 'moira', 'symmetra', 'zenyatta'])\n tanks, supporters, dps = [], [], []\n for name, idx in hero2ix.items():\n if name in tank:\n tanks.append(idx)\n elif name in supporter:\n supporters.append(idx)\n else:\n dps.append(idx)\n\n # plot tank, dps, and supporters respectively\n att_x, att_y = x[tanks], y[tanks]\n den_x, den_y = x[supporters], y[supporters]\n con_x, con_y = x[dps], y[dps]\n fig = plt.figure(figsize=(16, 12), dpi = 100)\n ax = plt.subplot(111)\n marker_size = 200\n ax.scatter(att_x, att_y, c= 'tomato', s=marker_size)\n ax.scatter(den_x, den_y, c = 'darkcyan', s=marker_size)\n ax.scatter(con_x, con_y, c = 'royalblue', s=marker_size)\n\n # annotate each hero's name\n for name, i in hero2ix.items():\n ax.annotate(name, (x[i], y[i]), fontsize=18)\n plt.show()\n fig.savefig('./output/hero/hero_embddings_2d.png')\n\ndef make_plot_color_map(x, y, map2ix):\n\n # divide maps to their own categories\n attacks, defenses, controls = [], [], []\n for name, idx in map2ix.items():\n name = name.split('_')\n if name[1] == 'Attack':\n attacks.append(idx)\n elif name[1] == 'Defense':\n defenses.append(idx)\n else:\n controls.append(idx)\n\n # plot attack, defense, controls map respectively\n att_x, att_y = x[attacks], y[attacks]\n den_x, den_y = x[defenses], y[defenses]\n con_x, con_y = x[controls], y[controls]\n\n fig = plt.figure(figsize=(16, 12), dpi = 100)\n ax = plt.subplot(111)\n marker_size = 200\n ax.scatter(att_x, att_y, c= 'tomato', s=marker_size)\n ax.scatter(den_x, den_y, c = 'darkcyan', s=marker_size)\n ax.scatter(con_x, con_y, c = 'royalblue', s=marker_size)\n\n # annotate each map's name\n for name, i in map2ix.items():\n ax.annotate(name, (x[i], y[i]))\n\n plt.show()\n fig.savefig('./output/map/map_embddings_2d.png')\n\ndef plot_embeddings(model, names):\n embeddings = model.embeddings.weight.cpu().data.numpy()\n\n #makes mean at 0\n embeddings -= np.mean(embeddings, axis=0)\n\n # run pca to reduce to 2 dimensions\n pca = PCA(n_components=2)\n embeddings_2d = pca.fit_transform(embeddings)\n x, y = embeddings_2d[:, 0], embeddings_2d[:, 1]\n make_plot_color(x, y, names)\n\ndef plot_embeddings_map(model, names):\n embeddings = model.map_embeddings.weight.cpu().data.numpy()\n\n #makes mean at 0\n embeddings -= np.mean(embeddings, axis=0)\n\n # run pca to reduce to 2 dimensions\n pca = PCA(n_components=2)\n embeddings_2d = pca.fit_transform(embeddings)\n x, y = embeddings_2d[:, 0], embeddings_2d[:, 1]\n make_plot_color_map(x, y, names)\n\ndef plot_loss(losses, directory):\n fig = plt.figure(figsize=(8, 6), dpi=100)\n ax = plt.subplot(111)\n ax.plot(losses)\n ax.set_xlabel('Epochs', fontsize=24)\n ax.set_ylabel('Train_loss', fontsize=24)\n fig.savefig(directory)\n plt.close()\n","sub_path":"utils/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"272257329","text":"import numpy as np\nfrom sklearn.model_selection import train_test_split\n\n# keras imports\nimport keras\nfrom keras.models import Model\nfrom keras.layers import Input, Conv1D, Dropout, Flatten, Dense, MaxPooling1D, Activation, GlobalAveragePooling1D, BatchNormalization\nfrom keras.callbacks import EarlyStopping\nfrom keras.optimizers import Adam\nfrom keras import backend as K\nfrom keras.callbacks import Callback,warnings\nimport keras.utils as np_utils\n\nclass AdvancedLearnignRateScheduler(Callback): \n def __init__(self, monitor='val_loss', patience=0,verbose=0, mode='auto', decayRatio=0.1):\n super(Callback, self).__init__() \n self.monitor = monitor\n self.patience = patience\n self.verbose = verbose\n self.wait = 0\n self.decayRatio = decayRatio\n \n if mode not in ['auto', 'min', 'max']:\n warnings.warn('Mode %s is unknown, '\n 'fallback to auto mode.'\n % (self.mode), RuntimeWarning)\n mode = 'auto'\n \n if mode == 'min':\n self.monitor_op = np.less\n self.best = np.Inf\n elif mode == 'max':\n self.monitor_op = np.greater\n self.best = -np.Inf\n else:\n if 'acc' in self.monitor:\n self.monitor_op = np.greater\n self.best = -np.Inf\n else:\n self.monitor_op = np.less\n self.best = np.Inf\n \n def on_epoch_end(self, epoch, logs={}):\n current = logs.get(self.monitor)\n current_lr = K.get_value(self.model.optimizer.lr)\n print(\"\\nLearning rate:\", current_lr)\n if current is None:\n warnings.warn('AdvancedLearnignRateScheduler'\n ' requires %s available!' %\n (self.monitor), RuntimeWarning)\n \n if self.monitor_op(current, self.best):\n self.best = current\n self.wait = 0\n else:\n if self.wait >= self.patience:\n if self.verbose > 0:\n print('\\nEpoch %05d: reducing learning rate' % (epoch))\n assert hasattr(self.model.optimizer, 'lr'), \\\n 'Optimizer must have a \"lr\" attribute.'\n current_lr = K.get_value(self.model.optimizer.lr)\n new_lr = current_lr * self.decayRatio\n K.set_value(self.model.optimizer.lr, new_lr)\n self.wait = 0 \n self.wait += 1\n\ndef cnn_net(window_size):\n\t# parameters\n\tinput_feat = 1\n\toutput_feat = 4\n\n\tconvfilt = 128 \t\t# number of neurons\n\tconvstr = 1 \t\t# no idea what it does \n\tksize = 5\t\t\t# kernel width\t\n\tdropout = 0.20\t\t# dropout probability\n\n\tpoolsize = 2\n\tpoolstr = 2\n\n\t# input layer\n\tinput1 = Input(shape=(window_size, input_feat), name='input1')\n\n\t# first convolution layer conv(relu)->maxpooling->dropout\n\tx = Conv1D(filters=convfilt,\n\t\t\t\t kernel_size=ksize,\n\t\t\t\t padding='same',\n\t\t\t\t strides=convstr,\n\t\t\t\t kernel_initializer='he_normal')(input1)\n\tx = BatchNormalization()(x)\n\tx = Activation('relu')(x)\n\tx = MaxPooling1D(pool_size=poolsize,\n\t\t\t\t\t\tstrides=poolstr)(x)\n\t#x = Dropout(dropout)(x)\n\n\t# other 6 convolution layers conv(relu)->maxpooling->dropout\n\tfor i in range(6):\n\t\tx = Conv1D(filters=convfilt,\n\t\t\t\t\t kernel_size=ksize,\n\t\t\t\t\t padding='same',\n\t\t\t\t\t strides=convstr,\n\t\t\t\t\t kernel_initializer='he_normal')(x)\n\t\tx = BatchNormalization()(x)\n\t\tx = Activation('relu')(x)\n\t\tx = MaxPooling1D(pool_size=poolsize,\n\t\t\t\t\t\t\tstrides=poolstr)(x)\n\t\t#x = Dropout(dropout)(x)\n\n\tx = GlobalAveragePooling1D()(x)\n\n\t# not sure about this step\n\t#x = Flatten()(x)\n\n\t# dense layers\n\tx = Dense(256, activation='relu')(x)\n\tx = Dropout(dropout)(x)\n\tx = Dense(128, activation='relu')(x)\n\tx = Dropout(dropout)(x)\n\tx = Dense(64, activation='relu')(x)\n\tx = Dropout(dropout)(x)\n\n\t# output\n\tout = Dense(output_feat, activation='softmax')(x)\n\tmodel = Model(inputs=input1, outputs=out)\n\n\tmodel.compile(optimizer='adam',\n\t\t\t\t loss='categorical_crossentropy',\n\t\t\t\t metrics=['accuracy'])\n\treturn model\n\n#####################\n### MAIN FUNCTION ###\n#####################\n\nX_train = np.load('./data/X_bw.npy')\nX_test = np.load('./data/Xt_bw.npy')\n\ny_train = np.loadtxt('./data/train_labels.csv', dtype='int')\n\nWINDOW_SIZE = 300*30\nX_train = X_train[:,0:WINDOW_SIZE]\nX_test = X_test[:,0:WINDOW_SIZE]\n\n# add dimensions for training\n#X_tr, y_tr, X_val, y_val = train_test_split(X_train, y_labels, test_size=0.20)\n\nX_tr = np.expand_dims(X_train, axis=2)\ny_tr = np_utils.to_categorical(y_train, num_classes=4)\nX_test = np.expand_dims(X_test, axis=2)\n\n#X_val = np.expand_dims(X_val, axis=2)\n#y_val = np_utils.to_categorical(y_val, num_classes=4)\n\n# initiate model\nmodel = cnn_net(WINDOW_SIZE)\nepochs = 25\nbatch = 64\ncallbacks = [\n \tEarlyStopping(monitor='val_loss', patience=3, verbose=1),\n \tAdvancedLearnignRateScheduler(monitor='val_loss', patience=1, verbose=1, mode='auto', decayRatio=0.1), \n \t]\nprint(model.count_params())\nmodel.fit(X_tr, y_tr, validation_split=0.1, epochs=epochs, batch_size=batch, verbose=1, callbacks=callbacks)\nprint('applying model')\ny_pred = model.predict(X_test)\nnp.savetxt('./data/y_train_conv.csv', y_pred, fmt='%d')\n","sub_path":"project3_test/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"240155248","text":"__author__ = 'Konstantin Kolokolov'\n\nimport numpy as np\nimport pandas as pd\n\n\ndef train_preprocessing(data_x, data_y, feature_names):\n \"\"\"process of train input data: transform to numpy matrix, transpose etc\"\"\"\n\n if isinstance(data_x, pd.DataFrame):\n data_x = data_x.as_matrix()\n\n if isinstance(data_y, pd.DataFrame) or isinstance(data_y, pd.Series):\n data_y = data_y.as_matrix()\n\n if not isinstance(data_y, (np.ndarray, np.generic)):\n data_y = np.asarray(data_y)\n if len(data_y.shape) != 1:\n if data_y.shape[0] == 1:\n data_y = data_y[0, :]\n elif data_y.shape[1] == 1:\n data_y = data_y[:, 0]\n else:\n raise ValueError('data_y dimension should be 1 or (n, 1) or (1, n)')\n data_len = data_y.shape[0]\n\n if not isinstance(data_x, (np.ndarray, np.generic)):\n data_x = np.asarray(data_x)\n\n if len(data_x.shape) != 2:\n raise ValueError('data_x dimension has to be 2. it has to be a 2D numpy array: number of features x '\n 'number of observations')\n\n if data_x.shape[0] != data_len:\n # try to check if transpose matrix is suitable\n if data_x.shape[1] == data_len:\n # ok, need to transpose data_x\n data_x = data_x.transpose()\n else:\n raise ValueError('number of examples in data_x is not equal to number of examples in data_y')\n\n if data_x.shape[1] < 2:\n raise ValueError('Error: number of features should be not less than two')\n\n if data_x.shape[0] < 2:\n raise ValueError('Error: number of samples should be not less than two')\n\n if feature_names is not None:\n feature_names_len = len(feature_names)\n if feature_names_len > 0 and feature_names_len != data_x.shape[1]:\n raise ValueError('Error: size of feature_names list is not equal to number of features')\n\n return data_x, data_y, data_len\n\n\ndef predict_preprocessing(data_x, n_features):\n \"\"\"process of predict input data: transform to numpy matrix, transpose etc\"\"\"\n\n if isinstance(data_x, pd.DataFrame):\n data_x = data_x.as_matrix()\n\n if not isinstance(data_x, (np.ndarray, np.generic)):\n data_x = np.asarray(data_x)\n\n if len(data_x.shape) != 2:\n raise ValueError('data_x dimension has to be 2. it has to be a 2D numpy array: number of features x '\n 'number of observations')\n\n if data_x.shape[1] != n_features:\n # try to check if transpose matrix is suitable\n if data_x.shape[0] == n_features:\n # ok, need to transpose data_x\n data_x = data_x.transpose()\n else:\n raise ValueError('number of features in data_x is not equal to number of features in trained model')\n\n data_len = data_x.shape[0]\n return data_x, data_len\n","sub_path":"gmdhpy/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"492777530","text":"# --------------------------------------------------------\r\n# Practical Machine Learning in Python Full Course Part 3: Model evaluation\r\n# --------------------------------------------------------\r\n# Predicting the price of a house, base of a linear model\r\nimport pandas as pd \r\nimport numpy as np \r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt \r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn import metrics\r\n\r\nhouse=pd.read_csv(\"C:/Users/Client/Documents/Quant/Machine Learning/Notes-master/home_data.csv\")\r\n# print(house.head())\r\n\r\n# Model 1: with 10 covariates\r\n# ----------------------------------\r\n\r\nX1=house[[ 'bedrooms', 'bathrooms', 'sqft_living','sqft_lot', 'floors', 'condition', 'sqft_above', 'yr_built', 'zipcode', 'sqft_lot15']]\r\ny=house['price']\r\nX_train, X_test, y_train, y_test=train_test_split(X1,y,test_size=0.3, random_state=7)\r\nmodel=LinearRegression()\r\nmodel.fit(X_train,y_train)\r\nprediction=model.predict(X_test)\r\n\r\n# ----Model 2 with less covariates\r\nX2=house[[ 'bedrooms', 'bathrooms', 'sqft_living','sqft_lot','yr_built', 'zipcode' ]]\r\nX_train, X_test, y_train, y_test=train_test_split(X2,y,test_size=0.3, random_state=7)\r\nmodel2=LinearRegression()\r\nmodel2.fit(X_train,y_train)\r\nprediction2=model2.predict(X_test)\r\n\r\n# Full model, with all the covariates\r\nX3=house[['bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors', 'waterfront', 'view', 'condition', 'grade', 'sqft_above', 'sqft_basement', 'yr_built', 'yr_renovated', 'zipcode', 'lat', 'long', 'sqft_living15', 'sqft_lot15']]\r\nX_train, X_test, y_train, y_test=train_test_split(X3,y,test_size=0.3, random_state=7)\r\nFullmodel=LinearRegression()\r\nFullmodel.fit(X_train,y_train)\r\nFullprediction=Fullmodel.predict(X_test)\r\n\r\n# Parameter estimate\r\nbetta=model.coef_\r\nbetta0=model.intercept_\r\nbetta2=model2.coef_\r\nbetta02=model2.intercept_\r\nFullbetta=Fullmodel.coef_\r\nFullbetta0=Fullmodel.intercept_\r\n\r\n\r\ndframe_coef=pd.DataFrame(betta,X1.columns,columns=['m1 Coeff Value'])\r\ndframe_coef2=pd.DataFrame(betta2,X2.columns,columns=['m2 Coeff Value'])\r\nFulldframe_coef=pd.DataFrame(Fullbetta,X3.columns,columns=['Full Coeff Value'])\r\n\r\nmse=metrics.mean_squared_error(y_test,prediction)\r\nmse2=metrics.mean_squared_error(y_test,prediction2)\r\nFullmse=metrics.mean_squared_error(y_test,Fullprediction)\r\n\r\nRMSE=np.sqrt(mse)\r\nRMSE2=np.sqrt(mse2)\r\nFullRMSE=np.sqrt(Fullmse)\r\n\r\nhouse1=house[house['id']==6414100192]\r\nprint('House price: ',house['price'][1],'; House prediction price: ',prediction[1])\r\nprint('House price: ',house['price'][1],'; House prediction price: ',prediction2[1])\r\nprint('House price: ',house['price'][1],'; House prediction price: ',Fullprediction[1])\r\n\r\nmdframe_coef=Fulldframe_coef.join(dframe_coef2).join(dframe_coef)\r\nprint('----------------Comparison of operators------------')\r\nprint(mdframe_coef)\r\nprint('-----------Root mean square comparison--------------')\r\nprint('RMSE :','m0: ',RMSE,'m2: ',RMSE2,'Full: ',FullRMSE)\r\nprint('-------------Intercept comparison-------------------')\r\nprint('intercept: ','m0: ', betta0, 'm2: ',betta02, 'Full: ',Fullbetta0)\r\n\r\nfig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3)\r\nax1.scatter(y_test,prediction)\r\nax1.set_title('Model with 10 covariates')\r\nax2.scatter(y_test,prediction2)\r\nax2.set_title('Model with 8 covariates')\r\nax3.scatter(y_test,Fullprediction)\r\nax3.set_title('Full model')\r\nplt.legend()\r\nplt.show()","sub_path":"Supervised-Learning/Part3.py","file_name":"Part3.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"549127457","text":"# coding=UTF-8\nimport pandas as pd\nfrom time import time\nimport jieba\nimport os\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n\nclass Dataset(): # 括号里写父类\n \"\"\"\n get_trainset0:获取原始训练集(匹配id)\n get_testset0:获取原始测试集\n cutword_list:分词(类内调用)\n save_txt:保存数据到txt文件\n 0表示没分词的句子\n \"\"\"\n\n def __init__(self, path):\n self.path = path\n\n df_train = pd.read_csv(path + '/new_trainset.csv').dropna(axis=0, how='any') # 在0这个维度上(也就是列,即删除一行\n df_train[\"content\"] = df_train[[\"title\", \"content\"]].apply(lambda x: \"\".join([str(x[0]), str(x[1])]), axis=1)\n # label = pd.read_csv(path + '/Train_DataSet_Label.csv')\n # self.df_train = pd.merge(df_train, label, how='inner', on='id')\n self.df_train = df_train\n\n df_test = pd.read_csv(path + '/new_testset.csv')\n df_test[\"content\"] = df_test[[\"title\", \"content\"]].apply(lambda x: \"\".join([str(x[0]), str(x[1])]), axis=1)\n self.df_test = df_test\n self.stopwords = {}\n with open(path + '/stopwords', encoding='utf-8') as f:\n for line in f.readlines():\n self.stopwords[line.strip()] = 1 # 直接读取末尾有换行符,要去除\n\n def get_trainset0(self):\n # trainset0 = []\n # label = []\n # label_id = {}\n # for i in range(len(self.label)): #list:6.7s,dict:0.4s!\n # label_id[self.label['id'][i]] = 1\n # for x in self.df_train.iterrows():\n # if(x[1]['id'] in label_id):\n # trainset0.append(str(x[1]['title'])+';'+str(x[1]['content']))\n # label.append(self.label['label'][i])\n # trainset0 = pd.merge(self.df_train, self.label, how='inner', on='id')\n # print(trainset0.columns)\n return ((self.df_train['content']), self.df_train['label'])\n\n def get_testset0(self):\n return (self.df_test['label'], self.df_test['content']) #原本是id和content\n\n def cutword_list(self, dataset0):\n # 传入必须是list/Series等容器\n a = time()\n cutword = []\n for sentence in dataset0[0:]:\n sentence = sentence.replace('\\n', ' ').replace('\\r', ' ')\n words, sente_Chinese = '', ''\n for uchar in sentence:\n if uchar >= u'\\u4e00' and uchar <= u'\\u9fa5':#只保留汉字\n sente_Chinese += uchar\n for word in jieba.cut(sente_Chinese):\n # if word not in self.stopwords:#list:197.4s,dict:51s,不去停用词:50s\n words += word + ' '\n cutword.append(words)\n print('分词耗时:%.1fs' % (time() - a))\n return cutword\n\n def save_txt(self, data, file):\n with open(self.path + file, 'w', encoding='utf-8') as f:\n for sente in data:\n f.write(sente.replace('\\n', '') + '\\n')\n\n def read_txt(self, file):\n if os.path.exists(self.path + file):\n with open(self.path + file, 'r', encoding='utf-8') as f:\n return f.readlines()\n else:\n print('%s不存在'%(self.path + file))\n\nclass Feature():\n def __init__(self, data_fit):\n self.data_fit = data_fit\n\n def tfidf_fit(self):\n a = time()\n vect = TfidfVectorizer(ngram_range=(1, 1), min_df=5, max_df=0.95, use_idf=1, smooth_idf=1, sublinear_tf=1)\n vect.fit(self.data_fit)\n print('tfidf_fit耗时:%.1fs' % (time() - a))\n return vect\n\n def tfidf_trans(self, vect, data_trans):\n a = time()\n tfidf = vect.transform(data_trans)\n print('tfidf_trans耗时:%.1fs' % (time() - a))\n return tfidf","sub_path":"CCF_sentiment_analysis/PreProsess.py","file_name":"PreProsess.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"404921398","text":"\"\"\"Модуль производит парсер сайта регард, раздел видеокард и отправляет все новые позиции на почту\nДля настройки фильтров можете выбрать необходимые фильтры на сайте и вставить в переменную FIRST_PARSING_PAGE\"\"\"\nimport re\nimport logging\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pony.orm import db_session\nfrom models import RegardURL\nfrom send_messang import send_massage\nfrom fake_useragent import UserAgent\nimport time\n\nUSER_AGENT = UserAgent().chrome\nMAIN_URL = \"https://www.regard.ru\"\nFIRST_PARSING_PAGE = 'https://www.regard.ru/catalog/filter/?id=NDAwMDsyLDMwMDAwLTYwMDAwLA=='\n\n\nclass Parser:\n def __init__(self, first_parsing_page):\n self.main_url = first_parsing_page\n\n def run(self):\n while True:\n self.parsing()\n time.sleep(30)\n\n @db_session\n def parsing(self):\n responce = requests.get(self.main_url, headers={'user-agent': USER_AGENT})\n html_doc = BeautifulSoup(responce.content, features=\"html.parser\")\n video_cards_info = html_doc.find_all(\"div\", {\"class\": \"block\"})\n self.parsing_page(video_cards_info=video_cards_info)\n\n def parsing_page(self, video_cards_info):\n for video_card_info in video_cards_info:\n teg_a = video_card_info.find(\"a\")\n teg_price = video_card_info.find(\"div\", {\"class\": \"price\"})\n price = teg_price.text\n price = re.findall(f'\\d+', price)\n price = price[0] + price[1]\n teg_img = teg_a.find('img')\n name = teg_img.get(\"alt\")\n href = teg_a.get(\"href\")\n url = MAIN_URL + href\n video_card_in_bd = RegardURL.get(url=url)\n if not video_card_in_bd:\n self.send_mail(url, name, price)\n RegardURL(url=url, name=name, price=price)\n\n def send_mail(self, url, name, price):\n massage = f\"NEW {name}, по цене {price}, адрес {url}\"\n topic_name = f'{name} - {price}'\n send_massage(massage, topic_name)\n log.info(f'отправлено сообщение {massage}')\n\n def chek_next_page(self, html_doc):\n info_page = html_doc.find(\"div\", {\"class\": \"PaginationWidget__wrapper-pagination\"})\n teg_a = None\n if info_page:\n teg_a = info_page.find(\"a\", {\"class\": \"PaginationWidget__arrow PaginationWidget__arrow_right\"})\n if teg_a:\n self.next_page = \"p=\" + teg_a.get('data-page')\n print(self.next_page)\n else:\n self.next_page = \"p=1\"\n\n\nlog = logging.getLogger('log_parsing')\n\n\ndef logging_configurate():\n file_handler = logging.FileHandler(filename=\"log_messege.txt\", encoding=\"utf-8\", mode=\"a\")\n formater_for_file_write = logging.Formatter(\"%(asctime)s %(levelname)s %(message)s\", \"%d-%m-%Y %H:%M\")\n file_handler.setFormatter(formater_for_file_write)\n file_handler.setLevel(logging.INFO)\n log.addHandler(file_handler)\n log.setLevel(logging.INFO)\n\n\nif __name__ == \"__main__\":\n logging_configurate()\n parser = Parser(FIRST_PARSING_PAGE)\n parser.run()\n","sub_path":"parsing_regard.py","file_name":"parsing_regard.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"255390342","text":"\"\"\"\nThis file contains the common tools\n\"\"\"\nimport base64\nimport importlib\nimport json\nimport mimetypes\nimport os\nimport traceback\nfrom http import HTTPStatus\nfrom logging import getLogger\nfrom typing import Union\n\nimport requests\nfrom flask import Response, current_app\n\nerror_logger = getLogger(\"error\")\n\n\ndef discover_blueprints(path: str) -> list: # pragma: no cover\n \"\"\"\n This method used to load blueprints from given path\n\n Arguments:\n path {str} -- [The path that contains blueprints module]\n\n Returns:\n list -- [The list of blueprints object]\n \"\"\"\n blueprints = list()\n dir_name = os.path.basename(path)\n packages = os.listdir(f\"{path}/blueprints\")\n\n for package in packages:\n if str(package).endswith(\".py\") and str(package) != \"__init__.py\":\n package = str(package).replace(\".py\", \"\")\n module_name = f\"{dir_name}.blueprints.{package}\"\n module = importlib.import_module(module_name)\n module_blueprints = [bp for bp in dir(module) if bp.endswith(\"_blueprint\")]\n\n for mb in module_blueprints:\n blueprints.append(getattr(module, mb))\n\n return blueprints\n\n\ndef make_json_response(\n http_status: Union[HTTPStatus, int], data: dict\n) -> Response: # pragma: no cover\n \"\"\"\n This method used to make flask Response object from given http status and response data\n\n Arguments:\n http_status {Union[HTTPStatus, int]} -- [The HTTP status to be returned]\n data {dict} -- [The response data]\n\n Returns:\n Response -- [flask Response object]\n \"\"\"\n return Response(\n response=json.dumps(data), status=http_status, mimetype=\"application/json\"\n )\n\n\ndef descripted_exception_logger(e: Exception) -> None: # pragma: no cover\n \"\"\"\n This method used to log an exception with description\n\n Arguments:\n e {Exception} -- [The raised exception]\n \"\"\"\n tb_frames = traceback.extract_tb(e.__traceback__)\n message = list()\n pardir_name = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\n\n for tb in tb_frames:\n if tb.filename.startswith(pardir_name):\n message.append(f\"{e} in {tb.filename} line number {tb.lineno}\")\n error_logger.error(\",\".join(message))\n\n\ndef camelcase(s: str) -> str:\n parts = iter(s.split(\"_\"))\n return next(parts) + \"\".join(i.title() for i in parts)\n\n\ndef enum_comprehensions(enum):\n return [str(key.value) for key in enum]\n","sub_path":"rental_app/tools/commons.py","file_name":"commons.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"14855040","text":"from sklearn import linear_model\nfrom sklearn.linear_model import Ridge\nfrom sklearn.feature_extraction.text import TfidfTransformer\nimport pandas as pd\nimport math\nimport numpy as np\nimport pickle\nimport json\n\nimport read_data as rd\n\n\nX0 = rd.items.values\nX_train_counts = X0[:, -19:]\n\ncategory = np.array(['unknown ', 'Action ', 'Adventure ',\n 'Animation ', 'Children\\'s ', 'Comedy ', 'Crime ', 'Documentary ', 'Drama ', 'Fantasy ',\n 'Film-Noir ', 'Horror ', 'Musical ', 'Mystery ', 'Romance ', 'Sci-Fi ', 'Thriller ', 'War ', 'Western'])\n\n# lấy thể loại phim\n\n\ndef get_category(id):\n category_item = []\n switcher = {\n 0: \"608651be44f3f49f3baae6aa\",\n 1: \"60865ca43e301f1ec22a6ed2\",\n 2: \"60865ca53e301f1ec22a6ed3\",\n 3: \"60865ca53e301f1ec22a6ed4\",\n 4: \"60865ca63e301f1ec22a6ed5\",\n 5: \"60865ca73e301f1ec22a6ed6\",\n 6: \"60865ca83e301f1ec22a6ed7\",\n 7: \"60865ca83e301f1ec22a6ed8\",\n 8: \"60865ca93e301f1ec22a6ed9\",\n 9: \"60865caa3e301f1ec22a6eda\",\n 10: \"60865cab3e301f1ec22a6edb\",\n 11: \"60865cab3e301f1ec22a6edc\",\n 12: \"60865cac3e301f1ec22a6edd\",\n 13: \"60865cad3e301f1ec22a6ede\",\n 14: \"60865cae3e301f1ec22a6edf\",\n 15: \"60865cae3e301f1ec22a6ee0\",\n 16: \"60865caf3e301f1ec22a6ee1\",\n 17: \"60865cb03e301f1ec22a6ee2\",\n 18: \"60865cb13e301f1ec22a6ee3\",\n }\n for index in range(len(X_train_counts[id])):\n if(X_train_counts[id][index] == 1):\n category_item.append(switcher.get(index))\n # category_item = category.dot(X_train_counts[id]).strip()\n return category_item\n\n\n# tfidf\ntransformer = TfidfTransformer(smooth_idf=True, norm='l2')\ntfidf = transformer.fit_transform(X_train_counts.tolist()).toarray()\n\n# print(tfidf[[0, 1, 2, 3, 4], :])\n\n\ndef get_items_rated_by_user(rate_matrix, user_id):\n \"\"\"\n in each line of rate_matrix, we have infor: user_id, item_id, rating (scores), time_stamp\n we care about the first three values\n return (item_ids, scores) rated by user user_id\n \"\"\"\n y = rate_matrix[:, 0] # all users\n # item indices rated by user_id\n # we need to +1 to user_id since in the rate_matrix, id starts from 1\n # while index in python starts from 0\n ids = np.where(y == user_id + 1)[0]\n item_ids = rate_matrix[ids, 1] - 1 # index starts from 0\n scores = rate_matrix[ids, 2]\n return (item_ids, scores)\n\n# train model cho tung user\n\n\nfilename = 'models/user_model_'\n\n\ndef trainModel():\n # Tìm mô hình cho mỗi user\n d = tfidf.shape[1] # data dimension\n W = np.zeros((d, rd.n_users))\n b = np.zeros((1, rd.n_users))\n\n for n in range(rd.n_users):\n ids, scores = get_items_rated_by_user(rd.rate_train, n)\n clf = Ridge(alpha=0.01, fit_intercept=True)\n Xhat = tfidf[ids, :]\n\n clf.fit(Xhat, scores)\n\n # lưu model\n tuple_objects = (clf, Xhat, scores)\n pickle.dump(tuple_objects, open(filename + str(n+1) + '.pkl', 'wb'))\n\n W[:, n] = clf.coef_\n b[0, n] = clf.intercept_\n\n\ndef precision(user_id):\n ids, ratings = get_items_rated_by_user(rd.rate_test, user_id-1)\n\n movie_title = rd.items.values[:, 1]\n release_date = rd.items.values[:, 2]\n IMDb_URL = rd.items.values[:, 4]\n category_list = get_category(X0[:, 0]-1)\n\n # print('user_id:', user_id)\n\n pickled_model, pickled_Xhat, pickled_scores = pickle.load(\n open(filename + str(user_id) + '.pkl', 'rb'))\n\n predict = pickled_model.predict(tfidf[:, :])\n\n # print('predict:', pickled_scores)\n\n # hiển thị theo dataframe pandas\n table_user_item = pd.DataFrame(\n {'movie_id': X0[:, 0], \"movie_title\": movie_title, \"release_date\": release_date, \"IMDb_URL\": IMDb_URL, 'category': category_list, 'predict_rating': predict})\n\n # Sort theo predict rating\n table_sorted = table_user_item.sort_values(\n by='predict_rating', ascending=False)\n\n result = table_sorted.head(10).to_json(orient='records')\n parsed = json.loads(result)\n\n return json.dumps(parsed, indent=2)\n\n\ndef evaluate(Yhat, rates, W, b):\n se = 0\n cnt = 0\n for n in xrange(n_users):\n ids, scores_truth = get_items_rated_by_user(rates, n)\n scores_pred = Yhat[ids, n]\n e = scores_truth - scores_pred\n se += (e*e).sum(axis=0)\n cnt += e.size\n return sqrt(se/cnt)\n\n\nif __name__ == '__main__':\n print('predict---------------------------')\n # print(precision(10))\n print(get_category(10))\n","sub_path":"content_base_filter.py","file_name":"content_base_filter.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"227249363","text":"import json\nimport cgi\nimport RPi.GPIO as GPIO #import RPi.GPIO module\nfrom time import sleep # import time.sleep()\nGPIO.setwarnings(False)\n\nGPIO.setmode(GPIO.BCM)\npins = {}\np1 = 4\np2 = 17\np3 = 13\nGPIO.setup(p1, GPIO.OUT) \nGPIO.setup(p2, GPIO.OUT) \nGPIO.setup(p3, GPIO.OUT)\nfr = 1000 # frequency (Hz)\n#dc = 50 # duty cycle (%)\npwm1 = GPIO.PWM(p1,fr)\npwm2 = GPIO.PWM(p2,fr)\npwm3 = GPIO.PWM(p3,fr)\n\npwm1.start(0) # start with LED off\npwm2.start(0)\npwm3.start(0)\nwhile True:\n with open(\"led-pwm-multiple.txt\", 'r') as f:\n data = json.load(f) # read duty cycle value from file\n dc = int(data['slider1'])\n led = int(data['LED'])\n if led == 1: \n pwm1.ChangeDutyCycle(dc)\n elif led == 2:\n pwm2.ChangeDutyCycle(dc)\n elif led == 3:\n pwm3.ChangeDutyCycle(dc)\n \n sleep(0.1)","sub_path":"pwmBackground.py","file_name":"pwmBackground.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"632516167","text":"\"\"\"\nconverge.py\n\nFunctions and objects for extracting and predicting convergence of \nSEEKR2 simulation outputs and results.\n\"\"\"\n\nimport os\nimport argparse\n\nimport seekr2.modules.common_base as base\nimport seekr2.modules.common_analyze as common_analyze\nimport seekr2.modules.common_converge as common_converge\n\nN_IJ_DIR = \"N_ij/\"\nR_I_DIR = \"R_i/\"\n\ndef converge(model, k_on_state=None, image_directory=None, \n pre_equilibrium_approx=False, verbose=False):\n \"\"\"\n Perform all convergence steps: a generic analysis of convergence \n of quantities such as N_ij, R_i, k_off, and k_on.\n \"\"\"\n \n k_on_conv, k_off_conv, N_ij_conv, R_i_conv, max_step_list, \\\n timestep_in_ns, data_sample_list \\\n = common_converge.check_milestone_convergence(\n model, k_on_state=k_on_state, \n pre_equilibrium_approx=pre_equilibrium_approx, verbose=verbose)\n \n if image_directory is None or image_directory == \"\":\n return data_sample_list\n \n k_off_fig, ax = common_converge.plot_scalar_conv(\n k_off_conv, max_step_list[0,:], title=\"k_{off} Convergence\", \n label=\"k_{off} (s^{-1})\", timestep_in_ns=timestep_in_ns)\n k_on_fig, ax = common_converge.plot_scalar_conv(\n k_on_conv, max_step_list[0,:], title=\"k_{on} Convergence\", \n label=\"k_{on} (s^{-1} M^{-1})\", timestep_in_ns=timestep_in_ns)\n N_ij_fig_list, ax, N_ij_title_list, N_ij_name_list \\\n = common_converge.plot_dict_conv(\n N_ij_conv, max_step_list[0,:], label_base=\"N\", \n timestep_in_ns=timestep_in_ns)\n R_i_fig_list, ax, R_i_title_list, R_i_name_list \\\n = common_converge.plot_dict_conv(\n R_i_conv, max_step_list[0,:], label_base=\"R\", \n timestep_in_ns=timestep_in_ns)\n \n k_off_fig.savefig(os.path.join(image_directory, \"k_off_convergence.png\"))\n k_on_fig.savefig(os.path.join(image_directory, \"k_on_convergence.png\"))\n for i, (name, title) in enumerate(zip(N_ij_name_list, N_ij_title_list)):\n N_ij_fig = N_ij_fig_list[i]\n N_ij_filename = os.path.join(image_directory, N_IJ_DIR, name+\".png\")\n N_ij_fig.savefig(N_ij_filename)\n for i, (name, title) in enumerate(zip(R_i_name_list, R_i_title_list)):\n R_i_fig = R_i_fig_list[i]\n R_i_filename = os.path.join(image_directory, R_I_DIR, name+\".png\")\n R_i_fig.savefig(R_i_filename)\n \n print(\"All plots have been saved to:\", image_directory)\n \n return data_sample_list\n\ndef print_convergence_results(model, convergence_results, cutoff, \n transition_results, minimum_anchor_transitions,\n bd_transition_counts):\n \"\"\"Print the results of a convergence test.\"\"\"\n \n print(\"Molecular dynamics results:\")\n for alpha, anchor in enumerate(model.anchors):\n if anchor.bulkstate:\n continue\n if convergence_results[alpha] < cutoff \\\n and min(transition_results[alpha].values()) \\\n > minimum_anchor_transitions:\n is_converged = True\n else:\n is_converged = False\n transition_detail = transition_results[alpha]\n transition_string = \"\"\n for key in transition_detail:\n transition_string += \" {}->{} : {}\".format(\n key[0],key[1],transition_detail[key])\n anchor_string = \" - Anchor {}: \".format(anchor.index) \\\n +\"\\n Milestone transitions:{}. \".format(transition_string) \\\n +\"\\n Convergence value: \" \\\n +\"{:.4e}. \".format(convergence_results[alpha]) \\\n +\"\\n Converged? {}\".format(is_converged)\n print(anchor_string)\n \n if \"b_surface\" in bd_transition_counts:\n print(\"Brownian dynamics results:\")\n print(\" - b-surface reaction counts:\")\n for bd_milestone_id in bd_transition_counts[\"b_surface\"]:\n if bd_milestone_id in [\"escaped\", \"stuck\"]:\n print(\" to %s:\" % bd_milestone_id, \n bd_transition_counts[\"b_surface\"][bd_milestone_id])\n else:\n print(\" to milestone %d:\" % bd_milestone_id, \n bd_transition_counts[\"b_surface\"][bd_milestone_id])\n \n bd_transition_counts.pop(\"b_surface\")\n \n for bd_milestone in model.k_on_info.bd_milestones:\n if bd_milestone.index in bd_transition_counts:\n key = bd_milestone.index\n print(\" - BD milestone {} reaction counts:\".format(key))\n for bd_milestone_id in bd_transition_counts[key]:\n if bd_milestone_id in [\"escaped\", \"stuck\"]:\n print(\" to %s:\" % bd_milestone_id, \n bd_transition_counts[key][bd_milestone_id])\n else:\n print(\" to milestone %d:\" % bd_milestone_id, \n bd_transition_counts[key][bd_milestone_id])\n else:\n print(\"No results found for BD milestone {}.\".format(\n bd_milestone.index))\n else:\n print(\"No BD results found.\")\n \n return\n\nif __name__ == \"__main__\":\n argparser = argparse.ArgumentParser(description=__doc__)\n argparser.add_argument(\n \"input_file\", metavar=\"INPUT_FILE\", type=str, \n help=\"name of input file for OpenMMVT calculation. This would be the \"\\\n \"XML file generated in the prepare stage.\")\n argparser.add_argument(\n \"-s\", \"--k_on_state\", dest=\"k_on_state\", default=None, type=int,\n help=\"Define the bound state that will be used to compute k-on. If \"\\\n \"left blank, and k-on statistics exist, then the first end state will \"\\\n \"be chosen by default.\")\n argparser.add_argument(\n \"-d\", \"--image_directory\", dest=\"image_directory\", \n default=None, type=str,\n help=\"Define the directory where all plots and images will be saved. \"\\\n \"By default, graphics will be saved to the \"\\\n \"'%s' directory in the model's anchor root directory.\"\\\n % common_analyze.DEFAULT_IMAGE_DIR)\n argparser.add_argument(\n \"-c\", \"--cutoff\", dest=\"cutoff\", default=0.1, type=float, \n help=\"\")\n argparser.add_argument(\n \"-m\", \"--minimum_anchor_transitions\", dest=\"minimum_anchor_transitions\",\n default=100, type=int, help=\"Enter a minimum number of transitions \"\\\n \"that must be observed per milestone in a given anchor as a criteria \"\\\n \"for the simulations.\")\n argparser.add_argument(\n \"-p\", \"--pre_equilibrium_approx\", dest=\"pre_equilibrium_approx\", \n default=False, help=\"Optionally use the pre-equilibrium approximation\"\\\n \"when computing system kinetics. This setting may be desirable for \"\\\n \"very long-timescale kinetic processes, which would cause the typical\"\\\n \"SEEKR2 analysis approach to fail.\", action=\"store_true\")\n \n args = argparser.parse_args() # parse the args into a dictionary\n args = vars(args)\n input_file = args[\"input_file\"]\n k_on_state = args[\"k_on_state\"]\n image_directory = args[\"image_directory\"]\n cutoff = args[\"cutoff\"]\n minimum_anchor_transitions = args[\"minimum_anchor_transitions\"]\n pre_equilibrium_approx = args[\"pre_equilibrium_approx\"]\n \n model = base.Model()\n model.deserialize(input_file)\n if model.anchor_rootdir == \".\":\n model_dir = os.path.dirname(input_file)\n model.anchor_rootdir = os.path.abspath(model_dir)\n \n if image_directory is None:\n image_directory = os.path.join(model.anchor_rootdir, \n common_analyze.DEFAULT_IMAGE_DIR)\n \n if image_directory != \"\" and not os.path.exists(image_directory):\n os.mkdir(image_directory)\n \n if not os.path.exists(os.path.join(image_directory, N_IJ_DIR)):\n os.mkdir(os.path.join(image_directory, N_IJ_DIR))\n \n if not os.path.exists(os.path.join(image_directory, R_I_DIR)):\n os.mkdir(os.path.join(image_directory, R_I_DIR))\n \n if model.k_on_info is None:\n assert k_on_state is None, \"--k_on_state cannot be defined for \"\\\n \"this model. The model was not initialized to compute k-on \"\\\n \"quantities.\"\n print(\"This model has no information for computing k-on - therefore \"\\\n \"k-on convergence will be skipped.\")\n else:\n end_milestones = []\n for anchor in model.anchors:\n if anchor.endstate:\n for milestone_id in anchor.get_ids():\n if model.get_type() == \"mmvt\":\n end_milestones.append(milestone_id)\n else:\n if anchor.milestones[milestone_id].is_source_milestone:\n end_milestones.append(milestone_id)\n continue\n assert len(end_milestones) > 0, \"No end-state milestones for this \"\\\n \"model: k-on convergence cannot be computed.\"\n print(\"All available options for --k_on_state include:\", end_milestones)\n if k_on_state is None:\n k_on_state = end_milestones[0]\n print(\"No milestone has been provided for k_on_state. \"\\\n \"The milestone %d has been chosen by default.\" % k_on_state)\n else:\n assert k_on_state in end_milestones, \"The provided \"\\\n \"milestone of %d for k_on_state is not available.\" % k_on_state\n \n data_sample_list = converge(model, k_on_state, image_directory, \n verbose=True)\n \n rmsd_convergence_results = common_converge.calc_RMSD_conv_amount(\n model, data_sample_list)\n transition_minima, transition_details \\\n = common_converge.calc_transition_steps(\n model, data_sample_list[-1])\n print_convergence_results(model, rmsd_convergence_results, cutoff, \n transition_details, minimum_anchor_transitions,\n data_sample_list[-1].bd_transition_counts)","sub_path":"seekr2/converge.py","file_name":"converge.py","file_ext":"py","file_size_in_byte":10049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"193883622","text":"from statistics import mean\n\nclass RunResult:\n \"\"\"\n Collection of all results for a single run configuration.\n \"\"\"\n\n def __init__(self):\n self.file_to_result = {}\n self.file_to_sorted_result = {}\n self.file_to_result_avg = {}\n self.n_measurements = 0\n self.n_timeouts = 0\n self.n_errors = 0\n\n def add_results(self, single_results):\n for result in single_results:\n self.n_measurements += 1\n if result.timeout_occurred:\n self.n_timeouts += 1\n # if result.return_code:\n # self.n_errors += 1\n\n if result.input_file not in self.file_to_result:\n self.file_to_result[result.input_file] = []\n\n self.file_to_result[result.input_file].append(result)\n\n def process_timings(self):\n # calculate per config timings and avg.\n for file_name, data in self.file_to_result.items():\n config_to_avg_time = {}\n config_to_time = {}\n\n # collect all timings required\n for res in data:\n if res.config_name not in config_to_avg_time:\n config_to_avg_time[res.config_name] = []\n config_to_time[res.config_name] = []\n config_to_time[res.config_name].append(res)\n if not res.timeout_occurred: # and not res.return_code:\n config_to_avg_time[res.config_name].append(res.time_elapsed)\n\n self.file_to_sorted_result[file_name] = config_to_time\n # take the average\n for config_name in config_to_avg_time:\n if config_to_avg_time[config_name]:\n processed_result = mean(config_to_avg_time[config_name])\n else:\n processed_result = \"No valid data.\"\n config_to_avg_time[config_name] = processed_result\n self.file_to_result_avg[file_name] = config_to_avg_time\n\n\nclass SingleRunResult:\n \"\"\"\n Small value object to store the result of a single run.\n \"\"\"\n\n def __init__(self, config_name, file_name):\n self.config_name = config_name\n self.input_file = file_name\n\n self.timeout_occurred = None\n self.return_code = None\n self.time_elapsed = None\n","sub_path":"src/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"316985871","text":"import keyboard\nfrom time import sleep\n\n\nfile = input(\"File:\")\n\nsleep(2)\n\nwith open(file) as f:\n people = f.readlines()\n\n for person in people:\n keyboard.write(\"!kick @{}\".format(person))\n keyboard.send('enter')\n sleep(2)\n keyboard.write(\"!dump -f %u -r @CRU 1 @CRU 2 @CRU 3 @CRU 4 @CRU 5 @CRU 6\")\n keyboard.send('enter')","sub_path":"discord_hacks.py","file_name":"discord_hacks.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"342863214","text":"# coding: utf-8\n\nimport datetime, copy\nfrom tasks.models import BasicSetting, TaskSetting, Task\nfrom . import util\n\n\nclass TaskMgr():\n def __init__(self):\n setting = BasicSetting.objects.all()[0]\n\n def _create_new_task(self, settings, exist_tasks_title, schedule):\n for setting in settings:\n if setting.title in exist_tasks_title:\n continue\n task = Task.objects.create(\n user=setting.user,\n title=setting.title,\n cycle=setting.cycle,\n assignee=setting.assignee,\n priority=setting.priority,\n slot=setting.slot,\n duration=setting.duration,\n order=setting.order,\n status=False,\n schedule=schedule,\n )\n\n def daily_task_create(self):\n exist_tasks_title = []\n print('create today\\'s task')\n settings = TaskSetting.objects.filter(cycle='d')\n tasks = Task.objects.filter(cycle='d', schedule=util.today())\n for t in tasks:\n exist_tasks_title.append(t.title)\n self._create_new_task(settings, exist_tasks_title, util.today())\n\n def weekly_task_create(self):\n exist_tasks_title = []\n print('create this week\\'s task')\n settings = TaskSetting.objects.filter(cycle='w')\n tasks = Task.objects.filter(cycle='w', schedule=util.this_week())\n for t in tasks:\n exist_tasks_title.append(t.title)\n self._create_new_task(settings, exist_tasks_title, util.this_week())\n\n def monthly_task_create(self):\n exist_tasks_title = []\n print('create this month\\'s task')\n settings = TaskSetting.objects.filter(cycle='m')\n tasks = Task.objects.filter(cycle='m', schedule=util.this_month())\n for t in tasks:\n exist_tasks_title.append(t.title)\n self._create_new_task(settings, exist_tasks_title, util.this_month())\n","sub_path":"tasks/service/task_manager.py","file_name":"task_manager.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"129833606","text":"# -*- coding:utf-8 -*-\nimport unittest\n\nfrom app import create_app, db\nfrom app.models.account import Role, User\nfrom app.models.tomato import Tomato\nfrom app.models.todo import Todo\nfrom app.models.tag import Tag\n\n\nclass TagModelTestCase(unittest.TestCase):\n def setUp(self):\n self.app = create_app('testing')\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all()\n Role.insert_roles()\n User.add_admin()\n User.add_test_user()\n u = User.query.first()\n Tomato(user=u)\n Todo(user=u)\n Tag(user=u)\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def test_new(self):\n u = User.query.first()\n tag = Tag(name='study', user=u)\n self.assertEquals([tag.name, tag.user],\n ['study', u])\n\n def test_tag(self):\n tag = Tag.query.first()\n toma = Tomato.query.first()\n todo = Todo.query.first()\n self.assertFalse(tag.tomatoes.all())\n self.assertFalse(tag.todoes.all())\n self.assertFalse(toma.tags)\n self.assertFalse(todo.tags)\n tag.tag(toma)\n self.assertTrue(tag.tomatoes.all())\n self.assertTrue(toma.tags)\n self.assertIn(tag, toma.tags)\n self.assertIn(toma, tag.tomatoes.all())\n tag.tag(todo)\n self.assertTrue(tag.todoes.all())\n self.assertTrue(todo.tags)\n self.assertIn(tag, todo.tags)\n self.assertIn(todo, tag.todoes.all())\n tag.remove_all()\n self.assertFalse(tag.tomatoes.all())\n self.assertFalse(tag.todoes.all())\n self.assertFalse(toma.tags)\n self.assertFalse(todo.tags)","sub_path":"tests/test_models/test_04_tag.py","file_name":"test_04_tag.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"462262300","text":"import asyncio\nimport csv\nfrom multiprocessing import Process\n\nfrom app.terminal.mode import Mode\n\n\nclass Operation(Mode):\n\n def __init__(self, services, logger):\n super().__init__(services, logger)\n self.options = [\n dict(name='name', required=1, value=None, doc='1-word name for operation'),\n dict(name='group', required=1, value=1, doc='group ID'),\n dict(name='adversary', required=1, value=1, doc='adversary ID'),\n dict(name='jitter', required=0, value='2/5', doc='seconds each agent will check in'),\n dict(name='cleanup', required=0, value=1, doc='run cleanup for each ability'),\n dict(name='stealth', required=0, value=0, doc='obfuscate the ability commands'),\n dict(name='seed', required=0, value=None, doc='absolute path to a facts csv')\n ]\n\n async def execute(self, cmd):\n await self.execute_mode(cmd)\n\n async def info(self):\n print('OPERATION allows you to build and run operations')\n print('-> search: list all started operations')\n print('-> pick [id]: show all commands for a specified operation ID')\n print('-> show options: show all configurable options an operation uses')\n print('-> show missing: show all options required to run an operation but not set')\n print('-> set [name] [value]: change an option value by name')\n print('-> unset: change all option values to None')\n print('-> run: start a new operation using the options set')\n print('-> dump [id]: view raw shell output from a specific link ID')\n\n async def search(self):\n operations = await self.data_svc.explode_operation()\n for op in operations:\n op.pop('host_group')\n op.pop('adversary')\n op.pop('chain')\n self.log.console_table(operations)\n\n async def pick(self, i):\n for op in await self.data_svc.explode_operation(criteria=dict(id=i)):\n links = []\n for link in op['chain']:\n links.append(dict(link_id=link['id'], score=link['score'], status=link['status'],\n collect=link['collect'], command=self.utility_svc.decode_bytes(link['command'])))\n self.log.console_table(links)\n\n async def run(self):\n operation = {o['name']: o['value'] for o in self.options}\n seed_file = operation.pop('seed')\n op_id = await self.data_svc.create_operation(**operation)\n if seed_file:\n with open(seed_file, 'r') as f:\n next(f)\n reader = csv.reader(f, delimiter=',')\n for line in reader:\n fact = dict(op_id=op_id, fact=line[0], value=line[1], score=line[2], link_id=0, action=line[3])\n await self.data_svc.dao.create('dark_fact', fact)\n self.log.console('Pre-seeding %s' % line[0], 'blue')\n Process(target=lambda: asyncio.run(self.operation_svc.run(op_id))).start()\n\n async def dump(self, i):\n result = await self.data_svc.explode_results(criteria=dict(link_id=i))\n self.log.console(self.utility_svc.decode_bytes(result[0]['output']), 'yellow')\n","sub_path":"app/terminal/modes/operation.py","file_name":"operation.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"338074940","text":"from setuptools import setup\n\nVERSION = \"1.0.3\"\n\nrequirements = [\"websocket-client!=0.49\"]\n\n\ndef readme():\n with open('README.md') as f:\n return f.read()\n\nsetup(\n name=\"inscribe-Pysher\",\n version=VERSION,\n description=\"Pusher websocket client for python, based on Erik Kulyk's PythonPusherClient\",\n long_description=readme(),\n long_description_content_type='text/markdown',\n keywords=\"pusher websocket client\",\n author=\"Nils Diefenbach\",\n author_email=\"nlsdfnbch.foss@kolabnow.com\",\n license=\"MIT\",\n url=\"https://github.com/InscribeAI/Pysher\",\n install_requires=requirements,\n packages=[\"pysher\"],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Topic :: Internet',\n 'Topic :: Software Development :: Libraries ',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"643047583","text":"import time, sys, operator\nimport pandas as pd\nfrom datetime import date, datetime\nfrom functools import reduce\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\noption = webdriver.ChromeOptions()\noption.add_argument(\" — incognito\")\nbrowser = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', chrome_options=option)\nbrowser.get(\"https://www.eleadcrm.com/evo2/fresh/login.asp\")\nbrowser.implicitly_wait(10)\nbrowser.maximize_window()\nbrowser.get(\"https://www.eleadcrm.com/evo2/fresh/login.asp\")\nusername = browser.find_element_by_id(\"user\")\npassword = browser.find_element_by_id(\"password\")\nusername.send_keys(\"Dealerfox\")\npassword.send_keys(\"2017eldf1\")\nlogin_attempt = browser.find_element_by_xpath(\"//*[@type='submit']\")\nlogin_attempt.click()\ntime.sleep(4)\nif len(browser.window_handles) == 2:\n browser.switch_to.window(browser.window_handles[-1])\n browser.close()\ntime.sleep(2)\nbrowser.switch_to.window(browser.window_handles[0])\ndesklog_click = browser.find_element_by_xpath(\"//span[@id='tdDeskLogImage']\")\ndesklog_click.click()\niframe_child = browser.find_element_by_xpath('//iframe[contains(@id, \"Main\")]')\nbrowser.switch_to.frame(iframe_child)\ndate_input = sys.argv[1] # '3/31/18'\nmonth = int(date_input.split('/')[0])\nday = int(date_input.split('/')[1])\nyear = int(date_input.split('/')[2])\ndate_input_final = \"{}/{}/{}\".format(month, day, year)\nWebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'Calendar')))\nbrowser.execute_script(\n \"var date_start = document.getElementById('Calendar'); date_start.readOnly = false; date_start.value = '{}'\".format(\n date_input_final))\nWebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'Calendar2')))\nbrowser.execute_script(\n \"var date_end = document.getElementById('Calendar2'); date_end.readOnly = false; date_end.value = '{}'\".format(\n date_input_final))\nWebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'btnRefresh')))\nrefresh = browser.find_element_by_id('btnRefresh')\nrefresh.click()\ntime.sleep(2)\nWebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'Filters_chkWebUps')))\ncheck_internet = browser.find_element_by_xpath(\"//input[@id='Filters_chkWebUps']\")\ncheck_internet.click()\nWebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'Filters_chkPhoneUps')))\ncheck_phone = browser.find_element_by_xpath(\"//input[@id='Filters_chkPhoneUps']\")\ncheck_phone.click()\nWebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'Filters_chkCampaignUps')))\ncheck_campaign = browser.find_element_by_xpath(\"//input[@id='Filters_chkCampaignUps']\")\ncheck_campaign.click()\ntime.sleep(2)\nnum_customers = 0\ntable_var = \"results\"\nWebDriverWait(browser, 20).until(EC.presence_of_element_located((By.XPATH, '//table[@id=\"results\"]/tbody/tr')))\ntime.sleep(10)\nnum_customers = browser.find_elements_by_xpath('//table[@id=\"results\"]/tbody/tr')\nnum_customers = len(num_customers)\nprint(num_customers)\nresult = {}\nunique_customers = []\nfor record in range(0, num_customers):\n if record > 0:\n WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.ID, 'Main')))\n iframe_child = browser.find_element_by_xpath('//iframe[contains(@id, \"Main\")]')\n browser.switch_to.frame(iframe_child)\n WebDriverWait(browser, 10).until(\n EC.presence_of_element_located((By.ID, 'DataPanel_ContentMain_CustomerName_{}'.format(record))))\n script = \"document.getElementById('DataPanel_ContentMain_CustomerName_{}').scrollIntoView();\".format(record)\n browser.execute_script(script)\n temp_table = WebDriverWait(browser, 10).until(\n EC.element_to_be_clickable((By.XPATH, \"//a[@id='DataPanel_ContentMain_CustomerName_{}']\".format(record))))\n temp_table.click()\n browser.switch_to.window(browser.window_handles[1])\n time.sleep(3)\n try:\n wait = WebDriverWait(browser, 10)\n opn_panel = wait.until(EC.presence_of_element_located((By.ID, 'OpportunityPanel_ViewPrevOpptyLink')))\n opn_panel.click()\n time.sleep(2)\n except:\n pass\n time.sleep(2)\n WebDriverWait(browser, 40).until(EC.presence_of_element_located((By.ID, 'OpportunityPanel_ActiveOpptyPanel')))\n WebDriverWait(browser,40).until(EC.presence_of_element_located((By.ID,'CustomerInfoPanel_lblPersonID')))\n customer_id = browser.find_element_by_id('CustomerInfoPanel_lblPersonID').text\n if customer_id in unique_customers:\n browser.close()\n browser.switch_to.window(browser.window_handles[0])\n continue\n unique_customers.append(customer_id)\n source_type_panel = browser.find_elements_by_xpath(\n \"//*[@id='OpportunityPanel_ActiveOpptyPanel']/table/tbody/tr[6]/td\")\n rep_row = browser.find_elements_by_xpath(\n \"//*[@id='OpportunityPanel_ActiveOpptyPanel']/table/tbody/tr[5]/td\")\n source_type = source_type_panel[1].text.strip()\n source_detail_panel = browser.find_elements_by_xpath(\n \"//*[@id='OpportunityPanel_ActiveOpptyPanel']/table/tbody/tr[7]/td\")\n source_detail = source_detail_panel[1].text.strip()\n if 'Online Shopper' in source_detail:\n source_detail = 'Online Shopper'.lower()\n if 'Repeat' in source_detail:\n source_detail = 'Previous Customer'.lower()\n elif '|' in source_detail:\n source_detail = source_detail.split('|')\n source_detail = source_detail[0].strip().replace(' com', '.com').lower()\n if source_type not in result.keys():\n result[source_type] = {}\n if source_detail not in result[source_type].keys():\n result[source_type][source_detail] = {'L': 1, 'A': 0, 'S': 0, 'C': 0}\n else:\n result[source_type][source_detail]['L'] += 1\n iframe1 = browser.find_element_by_id('tabsTargetFrame')\n browser.switch_to.frame(iframe1)\n oddRows = browser.find_elements_by_class_name(\"odd\")\n evenRows = browser.find_elements_by_class_name(\"even\")\n for i in oddRows:\n s = i.text\n s = s.split('\\n')\n s = [x for x in s if x]\n t = [i.split(' ') for i in s]\n if len(t) > 0:\n flat_list = reduce(operator.add, t)\n flat_list = [x for x in flat_list if x]\n if date_input in flat_list and 'Appointment' in s[1]:\n result[source_type][source_detail]['A'] += 1\n if 'Show' in s[2] and 'No Show' not in s[2]:\n result[source_type][source_detail]['S'] += 1\n for i in evenRows:\n s = i.text\n s = s.split('\\n')\n s = [x for x in s if x]\n t = [i.split(' ') for i in s]\n if len(t) > 0:\n flat_list = reduce(operator.add, t)\n flat_list = [x for x in flat_list if x]\n if date_input in flat_list and 'Appointment' in s[1]:\n result[source_type][source_detail]['A'] += 1\n if 'Show' in s[2] and 'No Show' not in s[2]:\n result[source_type][source_detail]['S'] += 1\n WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'gvOpptyHistory')))\n div_comp_contacts = browser.find_element_by_id('gvOpptyHistory')\n headerRows = browser.find_elements_by_class_name('PageHeader')\n for rows_cch in headerRows:\n if ('Sold - CRM Sold' in rows_cch.text or 'Sold - DMS Sold' in rows_cch.text) and date_input in rows_cch.text:\n #print(\"Sold\")\n result[source_type][source_detail]['C'] += 1\n browser.close()\n browser.switch_to.window(browser.window_handles[0])\nbrowser.quit()\nformat_str = '%m/%d/%y'\ndatetime_obj = datetime.strptime(date_input, format_str)\nday_of_week = datetime_obj.date().strftime(\"%a\")\nmonth_of_year = datetime_obj.date().strftime(\"%b\")\ncount = -1\ndf = pd.DataFrame(columns=['Date', 'month', 'Day of week', 'source_type', 'source_detail', 'L', 'A', 'S', 'C'])\nfor src_type in result:\n for src in result[src_type]:\n count += 1\n df.loc[count] = [datetime_obj.date().strftime('%Y-%m-%d'), month_of_year, day_of_week, src_type.strip(),\n src.strip(),\n result[src_type][src]['L'],\n result[src_type][src]['A'], result[src_type][src]['S'], result[src_type][src]['C']]\ndate_input_final = date_input_final.replace('/', '-')\nprint('inserted {} succesfully'.format(date_input))\n# df.to_csv('LASC_{}.csv'.format(date_input_final))\n# import boto3\n# s3 = boto3.resource('s3')\n# data = open('LASC_{}.csv'.format(date_input_final), 'rb')\n# s3.Bucket('eleads-scraper-data').put_object(Key='LASC/LASC_{}.csv'.format(date_input_final), Body=data)\nfrom sqlalchemy import create_engine\nengine = create_engine(\n \"mysql+mysqldb://Dealerfox:\" + 'Temp1234' + \"@dealerfox-mysql.czieat2fjonp.us-east-2.rds.amazonaws.com/CRM\")\ndf.to_sql(con=engine, name='Eleads1', if_exists='append', index=False)\n","sub_path":"Eleads/Eleads-history.py","file_name":"Eleads-history.py","file_ext":"py","file_size_in_byte":8955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"285834793","text":"from __future__ import division\nfrom sc_desktop import handler\nfrom steamcontroller.events import Pos\nimport math\n\n\nclass Handler(handler.Handler):\n def __init__(self, *args, **kwargs):\n self.sensitivity = 0.75 + kwargs.pop('sensitivity') / 4\n self.haptic = kwargs.pop('haptic', None)\n self.actions = ((), kwargs.pop('scrollup'), kwargs.pop('scrolldown'))\n\n kwargs.pop('wnd')\n super(Handler, self).__init__(*args, **kwargs)\n\n def _pad_touch(self, pad, x, y):\n r = x**2 + y**2\n if r < 11000000:\n return\n r = math.sqrt(r)\n x /= r\n y /= r\n dot = x * self.ix + y * self.iy\n if dot > self.sensitivity:\n return\n\n cross_z = y * self.ix - x * self.iy\n\n self.do_action(self.actions[int(math.copysign(1, cross_z))])\n if self.haptic is not None:\n self.haptic_fb(pad, self.haptic['amplitude'])\n\n self.ix, self.iy = x, y\n\n def pad_touch_right(self, x, y):\n self._pad_touch(Pos.RIGHT, x, y)\n\n def pad_touch_left(self, x, y):\n self._pad_touch(Pos.LEFT, x, y)\n\n def _first_padtouch(self, x, y):\n self.ix, self.iy = x, y\n\n def first_pad_touch_right(self, x, y):\n self._first_padtouch(x, y)\n\n def first_pad_touch_left(self, x, y):\n self._first_padtouch(x, y)\n","sub_path":"sc_desktop/handlers/scrollpad.py","file_name":"scrollpad.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"192400292","text":"from esdlvalidator.core.esdl import utils\r\n\r\nfrom esdlvalidator.validation.validator_esdl import EsdlValidator\r\nfrom esdlvalidator.validation.validator_xsd import XsdValidator\r\nfrom esdlvalidator.validation.validator_result import ValidatorResult\r\n\r\n\r\nclass Validator:\r\n \"\"\"Validator to check ESDL files\"\"\"\r\n\r\n def __init__(self):\r\n self.__esdlValidator = EsdlValidator()\r\n self.__xsdValidator = XsdValidator()\r\n\r\n def validate(self, file, schemas: list[str], validateXsd: bool):\r\n \"\"\"Validator to ESDL against xsd and user schemas\r\n\r\n Args:\r\n file : Loaded ESDL file\r\n schemas list[str]: Schemas in string format to check against\r\n validateXsd bool: If the validator should check against xsd\r\n\r\n Returns:\r\n result ValidatorResult: containing the validator results\r\n \"\"\"\r\n\r\n esdlString = self.__get_esdl_string(file)\r\n esdl = self.__load_esdl(esdlString)\r\n\r\n xsdResult = None if validateXsd == False else self.__xsdValidator.validate(esdlString)\r\n esdlResult = self.__esdlValidator.validate(esdl, schemas)\r\n result = ValidatorResult(xsdResult, esdlResult)\r\n return result\r\n\r\n def __get_esdl_string(self, file):\r\n \"\"\"Get a string from the uploaded file\"\"\"\r\n\r\n fileBytes = file.read()\r\n esdlString = fileBytes.decode(\"utf-8\")\r\n return esdlString\r\n\r\n def __load_esdl(self, esdlString: str):\r\n \"\"\"Get the string of the uploaded file, load it as energy system handler and return the resource\"\"\"\r\n\r\n esh = utils.get_esh_from_string(esdlString)\r\n return esh.resource\r\n","sub_path":"esdlvalidator/validation/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"1432939","text":"'''\r\n% [statvec] = kepel_statvec (kepel)\r\n%\tThe function kepel_statvec transforms the keplerian\r\n%\telements kepel into the corresponding state vector in\r\n%\tthe same reference system.\r\n%\r\n% Input:\r\n%\tkepel\r\n% \t\tvector containing the keplerian elements:\r\n%\t\t(1) - semimajor axis of the orbit in meters.\r\n%\t\t(2) - eccentricity.\r\n%\t\t(3) - inclination in radians.\r\n%\t\t(4) - right ascension of ascending node in radians.\r\n%\t\t(5) - argument of perigee in radians.\r\n%\t\t(6) - mean anomaly in radians.\r\n%\r\n% Output:\r\n%\tstatvec\r\n% \t\tstate vector in meters and meters/second.\r\n%\r\n% Authors:\r\n%\tHelio K. Kuga;\r\n%\tValder M. Medeiros;\r\n%\tValdemir Carrara\t\tfebruary/80\t\tversion 1.0\r\n%\tValdemir Carrara\t\tjuly 2005\t\t(C version)\r\n% Valdemir Carrara March/09 Matlab\r\n'''\r\n\r\nimport math\r\nimport numpy as np\r\nfrom rotmax import rotmax\r\nfrom rotmaz import rotmaz\r\nfrom rotmay import rotmay\r\nfrom kepler import kepler\r\n\r\ndef kepel_statvec(kepel):\r\n\r\n\tnp.set_printoptions(precision=4)\r\n\r\n\tEARTH_GRAVITY = 3.9860064e+14 #Earth's gravitational constant (m^3/s^2)\r\n\r\n\ta = kepel[0] # Semi-major axis\r\n\texc = kepel[1] # Eccentricity\r\n\tc1 = math.sqrt(1.0 - exc**2)\r\n\r\n\t# Rotation matrix\r\n\torb2iner = (rotmaz(-kepel[3]).dot(rotmax(-kepel[2]))).dot(rotmaz(-kepel[4]))\r\n\t#print('orb2iner :\\n{0}'.format(orb2iner))\r\n\r\n\t# Kepler's equation\r\n\tE = kepler(kepel[5], exc)\r\n\r\n\tsE = math.sin(E)\r\n\tcE = math.cos(E)\r\n\tc3 = (math.sqrt(EARTH_GRAVITY/a))/(1.0 - exc*cE)\r\n\r\n\t#print('sE : {0}'.format(sE))\r\n\t#print('cE : {0}'.format(cE))\r\n\t#print('c3 : {0:5E}'.format(c3))\r\n\r\n\t# State vector\r\n\taux1 = np.array([ a*(cE - exc), a*c1*sE, 0])\r\n\taux2 = np.array([-c3*sE, c1*c3*cE, 0])\r\n\tT1 = aux1.dot(orb2iner.T)\r\n\tT2 = aux2.dot(orb2iner.T)\r\n\r\n\tstat_vec = np.hstack((T1, T2))\r\n\treturn stat_vec\r\n\r\nif __name__ == \"__main__\":\r\n\trad = math.pi/180.0\r\n\tkepel = np.array([ 7000000, 0.01, 98*rad, 0, 0, 0])\r\n\tstat = kepel_statvec(kepel)","sub_path":"Propat/kepel_statvec.py","file_name":"kepel_statvec.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"136865994","text":"\"\"\"soyzniki URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/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, include\n# from django.views.generic.base import RedirectView\nfrom django.contrib import admin\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^user/', include('user.urls')),\n url(r'^map/', include('map.urls')),\n url(r'^async/', include('async.urls')),\n url(r'^news/', include('news.urls')),\n url(r'^partner/', include('partner.urls')),\n url(r'^view/', include('partner.urls')),\n url(r'^comments/', include('comments.urls')),\n url(r'^licens/', include('project.urls')),\n url(r'^project/', include('project.urls')),\n url(r'^forum/', include('forum.urls')),\n url(r'^$', include('home.urls'))\n]\n","sub_path":"soyzniki/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"253008497","text":"from datetime import datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\nf=open(\"states.tsv\")\nlines=f.readlines()\nf.close()\n\nopen_time=[]\n\nprint(\"Read data\")\nfor line in lines:\n line = line.split(\"\\t\")\n open_date = datetime.strptime(line[0], \"%d/%b/%Y:%H:%M:%S %z\")\n open_time.append(int(round(open_date.timestamp())))\n\nopen_time=np.array(open_time)\n\nprint(\"Create Output arrays\")\ntime_diff = np.diff(open_time)\n\nplot_list_open_y = np.linspace(5,5,num=int(round((open_time[-1] - open_time[0])/60)))\nplot_list_lit_dt = np.linspace(4,4,num=int(round((open_time[-1] - open_time[0])/60)))\nplot_list_lit_dt.fill(None)\nplot_list_open_x = np.linspace(open_time[0],open_time[-1],num=int(round((open_time[-1] - open_time[0])/60)))\nplot_list_open_x_label = []\n\nprint(\"Create X Labels\")\nfor timestamp in plot_list_open_x:\n plot_list_open_x_label.append( datetime.fromtimestamp(int(round(timestamp))) )\n\ndef find_nearest_above(my_array, target):\n diff = my_array - target\n mask = np.ma.less_equal(diff, 0)\n # We need to mask the negative differences and zero\n # since we are looking for values above\n if np.all(mask):\n return None # returns None if target is greater than any value\n masked_diff = np.ma.masked_array(diff, mask)\n return masked_diff.argmin()\n\ndef set_array_space(from_timestamp, to_timestamp, set_to, array):\n i_from = find_nearest_above(plot_list_open_x, from_timestamp)\n i_to = find_nearest_above(plot_list_open_x, to_timestamp)\n for i in range(i_from, i_to):\n array[i] = set_to\n\n#to_range_limit=len(open_time)\nto_range_limit=10000\nprint(\"Fill open array\")\nfor i in range(0,to_range_limit-1):\n if (open_time[i+1]-open_time[i]) <= 40:\n set_array_space(open_time[i],open_time[i+1],4,plot_list_lit_dt)\n if (open_time[i+1]-open_time[i]) < 180:\n pass\n else:\n set_array_space(open_time[i],open_time[i+1],None,plot_list_open_y)\n sys.stdout.write(\"\\r{}/{}\".format(i,to_range_limit))\n\nprint(\"\")\n\nprint(\"Create Plots\")\nplt.hold(False)\nplt.plot_date(plot_list_open_x_label[0:to_range_limit],plot_list_lit_dt[0:to_range_limit],'x')\nplt.hold(True)\nplt.plot_date(plot_list_open_x_label[0:to_range_limit],plot_list_open_y[0:to_range_limit],'b-')\nplt.show()\n","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"358475451","text":"'''\n# for windows laptop\nrootPath = 'jiangnan2020_Simple\\\\'\ntrainImage = rootPath + 'train\\\\train\\\\'\ntestImage = rootPath + 'test\\\\test\\\\'\nmodelPath = 'model\\\\AlexNet8.pkl'\ntrainBatch = 50\npredictBatch = 50\n'''\n\nrootPath = 'jiangnan2020/'\ntrainImage = rootPath + 'train/train/'\ntestImage = rootPath + 'test/test/'\nmodelPath = 'model/AlexNet8.pkl'\ntrainBatch = 900\npredictBatch = 500\n\n\ntrainCSV = rootPath + 'train.csv'\ntestCSV = rootPath + 'test.csv'\nsubmitCSV = rootPath + 'submit.csv'\n\nimageW = 227\nimageH = 227\nglobalSeed = 233\n\n# for training\ntrainEpochs = 600\noneTotal = 18000 / trainBatch\nneedTrain = True\nneedPredict = True\nnewModel = False\n\ntrainProportion = 0.7\nlearningRate = 0.00001\ninitialMomentum = 0.9\nweightDecay = 1e-4\n","sub_path":"History_Edition/6_AlexNet8/constant/constPath.py","file_name":"constPath.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"8802980","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nimport facenet\nimport lfw\nimport os\nimport sys\nimport math\nfrom sklearn import metrics\nfrom scipy.optimize import brentq\nfrom scipy import interpolate\n\ndef get_image_paths(facedir):\n image_paths = []\n if os.path.isdir(facedir):\n images = os.listdir(facedir)\n image_paths = [os.path.join(facedir,img) for img in images]\n return image_paths\n\ndef main(input_path, output_path, batch_size, model, image_size):\n with tf.Graph().as_default():\n with tf.Session() as sess:\n\n #for filename in os.listdir(input_path):\n # x = filename.split('_')[0]\n #directory = (output_path + \"/\" + x)\n\n # Read the file containing the pairs used for testing\n # pairs = lfw.read_pairs(os.path.expanduser(args.lfw_pairs))\n\n # Get the paths for the corresponding images\n # paths, actual_issame = lfw.get_paths(os.path.expanduser(args.lfw_dir), pairs, args.lfw_file_ext)\n\n # Load the model\n facenet.load_model(model)\n\n # Get input and output tensors\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n\n # image_size = images_placeholder.get_shape()[1] # For some reason this doesn't work for frozen graphs\n image_size = image_size\n embedding_size = embeddings.get_shape()[1]\n\n # Run forward pass to calculate embeddings\n print('Runnning forward pass on images')\n #batch_size = batch_size\n nrof_images = len(os.listdir(input_path))\n nrof_batches = 1 # int(math.ceil(1.0 * nrof_images / batch_size))\n emb_array = np.zeros((nrof_images, embedding_size))\n for i in range(nrof_batches):\n start_index = i * batch_size\n print(start_index)\n end_index = min((i + 1) * batch_size, nrof_images)\n print(end_index)\n #paths_batch = paths[start_index:end_index]\n images = facenet.load_data(image_paths, False, False, image_size)\n print(\"I got this far!\")\n feed_dict = {images_placeholder: images, phase_train_placeholder: False}\n emb_array[start_index:end_index, :] = sess.run(embeddings, feed_dict=feed_dict)\n # ValueError: Cannot feed value of shape (3, 182, 182, 3) for Tensor u'input:0', which has shape '(?, 160, 160, 3)'\n #do I need to specify the shapt of the imput tensor somewhere?\n np.savetxt('/home/iolie/tensorflow/THORN/crop/TEST', emb_array, delimiter=\",\")\n\n ### emb array is all the image vectors in the order they were run,\n ### but how to ensure they went in in the same order? since list.os takes files randomly??\n ### additional column in emb array??\n ###\n\n\n\ninput_path = ('/home/iolie/tensorflow/THORN/Minisample') #+ \"/\" + \"0A0A937C-016C-49E6-A9CA-480292B491BC\")\noutput_path = ('/home/iolie/tensorflow/THORN/Minisample') #+ \"/\" + \"0A0A937C-016C-49E6-A9CA-480292B491BC\")\n\nbatch_size = len(os.listdir(input_path))\nmodel = \"/home/iolie/tensorflow/THORN/msft-cfs-face-recognition/analysis/analysis/facenet/temp_models/20170512-110547\"\nimage_size = 160\n\nimage_paths = get_image_paths(input_path)\n\nmain(input_path, output_path, batch_size, model, image_size)\n## this should output a TEST.txt file to the crop folder, with the few test images all contained within\n## how big should my batch be??\n","sub_path":"src/temp_featurizer.py","file_name":"temp_featurizer.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"260131522","text":"#!/usr/local/bin/python3\n\ndef fib(n):\n if n < 1:\n print('Invalid input')\n result -1\n\n if n == 1 or n == 2:\n return 1\n else:\n return fib(n-1) + fib(n-2)\n\nif __name__ == '__main__':\n result = fib(35)\n if result != -1:\n print('There are totally %d rabbits' %result)\n\n# The End\n","sub_path":"fibonacci/fibrecursion.py","file_name":"fibrecursion.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"592571763","text":"from glLibLocals import *\nfrom glLibMath import *\nclass glLibPathFinder:\n def __init__(self,data=None):\n self.connections = {}\n if data == None:\n pass\n elif type(data) == type(\"\"):\n file = open(data,\"r\")\n data = file.readlines()\n for line in data:\n line = line.strip()\n if line == \"\" or line.startswith(\"#\"): continue\n node_name,line = line.split(\":\")\n node_name = node_name.strip()\n line = line.split(\"|\")\n line = [a.strip() for a in line]\n connection_list = []\n for connection in line:\n name,cost = connection.split(\" \")\n if cost.startswith(\"s\"):\n cost = float(cost[1:])**0.5\n elif cost == \"inf\":\n cost = \"inf\"\n try: cost = float(cost)\n except: raise glLibError(\"Cost value \"+str(cost)+\" not recognized!\")\n if cost < 0.0:\n raise glLibError(\"Cost value \"+str(cost)+\" must be positive or zero!\")\n \n connection_list.append([name,cost])\n self.connections[node_name] = connection_list\n elif hasattr(data,\"raw_vertices\"):\n for vertex in data.raw_vertices:\n self.connections[\"Node__\"+str(tuple(vertex))] = []\n for edge in data.raw_polygons:\n n1 = str(tuple(edge[0]))\n n2 = str(tuple(edge[1]))\n dist = length(vec_subt(*edge))\n self.connections[\"Node__\"+n1].append([\"Node__\"+n2,dist])\n self.connections[\"Node__\"+n2].append([\"Node__\"+n1,dist])\n \n def glLibInternal_path_length(self,path_names):\n distance = 0.0\n for index in xrange(0,len(path_names)-1,1):\n for conn in self.connections[path_names[index]]:\n if conn[0] == path_names[index+1]:\n if conn[1] == \"inf\": return None\n distance += conn[1]\n break\n return distance\n def set_all_distances(self,new_distance):\n for node in self.connections.values():\n for conn in node:\n conn[1] = new_distance\n def find_path(self,from_name,to_name):\n #http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\n node_names = self.connections.keys()\n distance_register = {}\n previous_node_register = {}\n for node_name in node_names: #Initializations\n distance_register[node_name] = \"inf\" #Unknown distance function from source to v\n previous_node_register[node_name] = None #Previous node in optimal path from source\n distance_register[from_name] = 0.0 #Distance from source to source\n Q = node_names\n #All nodes in the graph are unoptimized - thus are in Q\n while len(Q) != 0: #The main loop\n## distances = []\n## for key in Q:\n## distances.append([distance_register[key],key])\n distances = [[distance_register[key],key] for key in Q]\n distances.sort() #strings get placed last, so \"inf\" goes last too\n u = distances[0][1]\n if distance_register[u] == \"inf\":\n return False #all remaining vertices are inaccessible from source\n if u == to_name:\n S = []\n while previous_node_register[u] != None:\n S = [u]+S\n u = previous_node_register[u]\n S = [from_name]+S\n if len(S) == 1:\n return True\n return S,self.glLibInternal_path_length(S)\n Q.remove(u)\n for node_name,distance_to in self.connections[u]:\n if distance_to == \"inf\": continue\n alt = distance_register[u] + distance_to\n if alt < distance_register[node_name]: #Relax (u,v,a)\n distance_register[node_name] = alt\n previous_node_register[node_name] = u\n def save_network(self,name,write_inf=False):\n string = \"\"\"#This is a network file automatically generated by glLib.\n#Use \"#\" to specify comments. Nodes are listed by name.\n#Each line specifies a single node and its connections to\n#other nodes and their distances. The node is the first\n#name, then a \":\" character, then, connections are\n#specified by new node names and distances to them along\n#a direct route (if a node is not directly connected to\n#another node, then it should not be listed under the\n#node's connections. The connections to individual nodes\n#are separated by a \"|\" symbol.\n\n\"\"\"\n node_strings = []\n for nodename in self.connections.keys():\n node_string = nodename+\": \"\n connections = self.connections[nodename]\n connection_strings = []\n for connection in connections:\n if connection[1] == \"inf\":\n dist = \"inf\"\n if write_inf:\n connection_strings.append(\" | \"+connection[0]+\" \"+dist)\n else:\n dist = float(connection[1])\n if float(int(connection[1])) == connection[1]:\n dist = int(connection[1])\n for x in xrange(2,10):\n if dist == float(x)**0.5:\n dist = \"s\"+str(x)\n connection_strings.append(\" | \"+connection[0]+\" \"+str(dist))\n connection_strings.sort()\n connection_strings[0] = connection_strings[0][3:]\n for connection_string in connection_strings:\n node_string += connection_string\n node_string += \"\\n\"\n node_strings.append(node_string)\n node_strings.sort()\n for node_string in node_strings:\n string += node_string\n file = open(name,\"w\")\n file.write(string)\n file.close()\n","sub_path":"glLib/glLibPaths.py","file_name":"glLibPaths.py","file_ext":"py","file_size_in_byte":6086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"225785050","text":"n = list(input())\n\nresult = []\nsum = 0\nfor i in n:\n if i.isalpha():\n result.append(i)\n else:\n sum += int(i)\n\nresult.sort()\n\nif sum !=0:\n print(\"\".join(result)+str(sum))\nelse:\n print(result)","sub_path":"책/문제/문자열재정렬2.py","file_name":"문자열재정렬2.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"585338525","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.parameter import Parameter\n\nimport dgl\nimport dgl.nn.pytorch as dglnn\nimport dgl.function as fn\n\n\nclass WeightedSAGEConv(nn.Module):\n def __init__(self, input_dims, output_dims, act=F.relu, dropout=0.5, bias=True):\n super().__init__()\n\n self.act = act\n self.Q = nn.Linear(input_dims, output_dims)\n self.W = nn.Linear(input_dims + output_dims, output_dims)\n if bias:\n self.bias = Parameter(torch.FloatTensor(output_dims))\n else:\n self.register_parameter('bias', None)\n # self.dropout = nn.Dropout(dropout)\n self.reset_parameters()\n\n def reset_parameters(self):\n gain = nn.init.calculate_gain('relu')\n nn.init.xavier_uniform_(self.Q.weight, gain=gain)\n nn.init.xavier_uniform_(self.W.weight, gain=gain)\n nn.init.constant_(self.Q.bias, 0)\n nn.init.constant_(self.W.bias, 0)\n if self.bias is not None:\n nn.init.zeros_(self.bias)\n\n def forward(self, g, h, weights=None):\n \"\"\"\n g : graph\n h : node features\n weights : scalar edge weights\n \"\"\"\n h_src, h_dst = h\n with g.local_scope():\n if weights:\n g.srcdata['n'] = self.act(self.Q(self.dropout(h_src)))\n g.edata['w'] = weights.float()\n g.update_all(fn.u_mul_e('n', 'w', 'm'), fn.sum('m', 'n'))\n g.update_all(fn.copy_e('w', 'm'), fn.sum('m', 'ws'))\n n = g.dstdata['n']\n ws = g.dstdata['ws'].unsqueeze(1).clamp(min=1)\n z = self.act(self.W(self.dropout(torch.cat([n / ws, h_dst], 1))))\n z_norm = z.norm(2, 1, keepdim=True)\n z_norm = torch.where(z_norm == 0, torch.tensor(1.).to(z_norm), z_norm)\n z = z / z_norm\n else:\n # a= self.Q(h_src)\n g.srcdata['n'] = self.Q(h_src)\n g.update_all(fn.copy_src('n', 'm'), fn.mean('m', 'neigh')) # aggregation\n n = g.dstdata['neigh']\n z = self.act(self.W(torch.cat([n, h_dst], 1))) + self.bias\n z_norm = z.norm(2, 1, keepdim=True)\n z_norm = torch.where(z_norm == 0, torch.tensor(1.).to(z_norm), z_norm)\n z = z / z_norm\n return z\n\n\nclass SAGENet(nn.Module):\n def __init__(self, input_dim, hidden_dims, output_dims,\n n_layers, act=F.relu, dropout=0.5):\n super().__init__()\n self.convs = nn.ModuleList()\n self.convs.append(WeightedSAGEConv(input_dim, hidden_dims, act, dropout))\n for _ in range(n_layers - 2):\n self.convs.append(WeightedSAGEConv(hidden_dims, hidden_dims,\n act, dropout))\n self.convs.append(WeightedSAGEConv(hidden_dims, output_dims,\n act, dropout))\n self.dropout = nn.Dropout(dropout)\n self.act = act\n\n def forward(self, blocks, h):\n for l, (layer, block) in enumerate(zip(self.convs, blocks)):\n h_dst = h[:block.number_of_nodes('DST/' + block.ntypes[0])] # 这只取dst点,从下往上aggregate,得到头结点\n h = layer(block, (h, h_dst))\n if l != len(self.convs) - 1:\n h = self.dropout(h)\n return h\n","sub_path":"graphsage/node_classification/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"548208624","text":"import argparse\nimport os\nimport signal\nimport subprocess\nimport time\n\nall_device_cpu_list = []\nsystem_server_cpu_list = []\nCPU_COUNT = 8\n\n\n# get cpu info\ndef get_all_cpu_info(system_server_pid=0, frequency=5, times=20):\n # pid : pid of system_server , default = 0\n\n all_device_total_list = []\n all_device_idle_list = []\n system_server_total_list = []\n system_server_idle_list = []\n timeout_seconds = 30\n\n pcpu = '-1'\n\n range_times = int(times) / int(frequency)\n print(\"get_cpuinfo start\" + \" times = \" + str(range_times))\n\n try:\n for k in range(int(range_times + 1)):\n ## all devices cpu info get\n data = []\n cpu_cmd = 'adb shell \"cat /proc/stat | grep -w cpu\"'\n res = timeout_Popen(cpu_cmd, timeout=timeout_seconds)\n res = res.stdout.read().split()\n print(str(res))\n\n if not res:\n print('ssh %s get cpu info failed , Please check if the adb environment is configured')\n return pcpu\n\n for i in res:\n try:\n if isinstance(eval(i), int):\n data.append(i)\n except:\n continue\n\n total_cpu_time = sum([int(i) for i in data])\n all_device_total_list.append(total_cpu_time)\n all_device_idle_list.append(int(data[3]))\n\n ## system server cpu info get\n if int(system_server_pid) > 0:\n system_data = []\n cpu_cmd = 'adb shell \"cat /proc/%s/stat\"' % system_server_pid\n\n res = timeout_Popen(cpu_cmd, timeout=timeout_seconds)\n res = res.stdout.read().split()\n print(str(res))\n\n if not res:\n print('get cpu info failed, Please check if the adb environment is configured')\n return pcpu\n\n for i in res:\n try:\n if isinstance(eval(i), int):\n system_data.append(i)\n except:\n continue\n\n system_server_total_list.append(int(res[14]) + int(res[15]) + int(res[16]) + int(res[17]))\n print(str(system_server_total_list))\n\n # slepp frequency(s) to take\n time.sleep(int(frequency))\n except:\n pass\n\n index = 0\n for total_index in all_device_total_list:\n if index == 0:\n index += 1\n continue\n\n total = total_index - all_device_total_list[index - 1]\n idle = all_device_idle_list[index] - all_device_idle_list[index - 1]\n\n pcpu = str(round(100 * (total - idle) / total, 2))\n all_device_cpu_list.append(pcpu)\n\n if int(system_server_pid) > 0:\n system_server_time = system_server_total_list[index] - system_server_total_list[index - 1]\n sys = str(round(100 * system_server_time * CPU_COUNT / total, 2))\n system_server_cpu_list.append(sys)\n\n index += 1\n return all_device_cpu_list\n\n\n# handle popen timeout:\ndef timeout_Popen(cmd, timeout=30):\n start = time.time()\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n while process.poll() is None:\n now = time.time()\n if now - start >= timeout:\n os.kill(process.pid, signal.SIGKILL)\n os.waitpid(-1, os.WNOHANG)\n return None\n return process\n\n\ndef getPidByName(process_name):\n if process_name is None:\n return 0\n timeout_seconds = 30\n cpu_cmd = \"adb shell pidof %s\" % process_name\n\n res = timeout_Popen(cpu_cmd, timeout=timeout_seconds)\n res = res.stdout.read().split()\n print(process_name + \" pid = \" + str(res[0].decode('ascii')))\n return res[0].decode('ascii')\n\n\n# get_all_cpu_info(pid , device) : get cpu info , if pid is not null , get system_server cpu info either\n# pid : pid of system_server , default = 0\n# device : 0-oppo , 1-huawei\n\nparser = argparse.ArgumentParser(description='Process cpuinfo')\nparser.add_argument('-p', '--process_name', dest='process',\n help='process to parse')\nparser.add_argument('-f', '--frequency', dest='frequency',\n help='time frequency , how long to take data ')\nparser.add_argument('-t', '--time', dest='time',\n help='how long')\nargs = parser.parse_args()\nfreq = args.frequency\ntimes = args.time\n\npid = getPidByName(args.process)\nall_cpu_usages = get_all_cpu_info(pid, freq, times)\n\ntime_index = 0\nprint('------------------------------------------------')\nprint(\"All devices cpuinfo\")\nfor cpu_usage in all_cpu_usages:\n print(str(time_index) + \"s to \" + str(time_index + int(freq)) + \"s\" + \" cpu usage :\" + str(cpu_usage))\n time_index += int(freq)\n\nprint('------------------------------------------------')\ntime_index = 0\nif int(pid) > 0:\n print(\"%s cpuinfo\" % args.process)\n for cpu_usage in system_server_cpu_list:\n print(str(time_index) + \"s to \" + str(time_index + int(freq)) + \"s\" + \" cpu usage :\" + str(cpu_usage))\n time_index += int(freq)\n","sub_path":"cpu_usage_calculation_python3.py","file_name":"cpu_usage_calculation_python3.py","file_ext":"py","file_size_in_byte":5136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"321302526","text":"#!/usr/bin/env python3\n\n# For consistency with TypeScript code, `cdk` is the preferred import name for\n# the CDK's core module. The following line also imports it as `core` for use\n# with examples from the CDK Developer's Guide, which are in the process of\n# being updated to use `cdk`. You may delete this import if you don't need it.\nimport os\n\nfrom aws_cdk import core\nfrom cdk.common.pipeline.pipeline_stack import PipelineStack\n\napp = core.App()\nPipelineStack(\n app,\n 'PipelineStack',\n env=core.Environment(\n account=os.environ['CDK_DEFAULT_ACCOUNT'],\n region=os.environ['CDK_DEFAULT_REGION']\n )\n)\napp.synth()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"238001015","text":"# -*- coding: UTF-8 -*-\n# Copyright 2009-2015 Luc Saffre\n# License: BSD (see file COPYING for details)\n\n\"\"\"Views for `lino.modlib.bootstrap3`.\n\n\"\"\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom django import http\nfrom django.conf import settings\nfrom django.views.generic import View\n\nfrom lino.utils.jsgen import py2js\nfrom lino.core.views import requested_actor\n\n\nfrom jinja2 import Template as JinjaTemplate\n\nfrom lino.api import dd, rt\n\n\nclass Templates(View):\n\n \"\"\"\n Called by TinyMCE (`template_external_list_url\n `_)\n to fill the list of available templates.\n\n \"\"\"\n\n def get(self, request,\n app_label=None, actor=None,\n pk=None, fldname=None, tplname=None, **kw):\n\n if request.method == 'GET':\n\n rpt = requested_actor(app_label, actor)\n elem = rpt.get_row_by_pk(None, pk)\n if elem is None:\n raise http.Http404(\"%s %s does not exist.\" % (rpt, pk))\n\n TextFieldTemplate = rt.modules.tinymce.TextFieldTemplate\n if tplname:\n tft = TextFieldTemplate.objects.get(pk=int(tplname))\n if settings.SITE.trusted_templates:\n #~ return http.HttpResponse(tft.text)\n template = JinjaTemplate(tft.text)\n context = dict(request=request,\n instance=elem, **rt.modules)\n return http.HttpResponse(template.render(**context))\n else:\n return http.HttpResponse(tft.text)\n\n qs = TextFieldTemplate.objects.all().order_by('name')\n\n templates = []\n for obj in qs:\n url = dd.plugins.tinymce.build_plain_url(\n 'templates',\n app_label, actor, pk, fldname, unicode(obj.pk))\n templates.append([\n unicode(obj.name), url, unicode(obj.description)])\n js = \"var tinyMCETemplateList = %s;\" % py2js(templates)\n return http.HttpResponse(js, content_type='text/json')\n raise http.Http404(\"Method %r not supported\" % request.method)\n\n","sub_path":"lino/modlib/tinymce/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"270659760","text":"import sys\nfrom ants import Ant\nfrom random import uniform\n\n\ndef input_in_matrix(matrix):\n \n '''Перевод введенной последовательности в массив, элементы которого (i,j), где i - вес ребра, j - концентрация феромона на ребре'''\n \n matrix = matrix.split('\\n')\n while matrix[-1] == '':matrix.pop()\n\n for i in range(0, len(matrix)):\n # Чтобы вывод с numpy.random.randint(1, 50, size=(20, 20)) можно было передавать на вход программе без преобразований\n matrix[i] = matrix[i].replace(' ', ' ').replace('[', ' ').replace('[[', ' ').replace(']', ' ').replace(']]', ' ').strip().split(' ')\n for j in range(0, len(matrix[i])):\n if i == j: \n matrix[i][j] = [0, 0] # Обнуление диагонали\n continue\n matrix[i][j] = [int(matrix[i][j]), uniform(0, 1)] # Случайная концетрация на ребрах\n\n return matrix\n\n\ndef create_dT(colony):\n \n '''Создание матрицы для изменения концетрации феромонов'''\n \n dT = [[0 for i in range(0, len(matrix))] for j in range(0, len(matrix))]\n\n Lk = [] # Выбор наименьшего значения длины пути среди всех муравьев\n for ant in colony:\n Lk.append(ant.Lk)\n\n elite = Lk.index(min(Lk)) + 1 # Выбор элитного муравья (муравей с кратчайшим путем)\n \n for ant in colony:\n for i in range(0, len(matrix)):\n for j in range(0, len(matrix)):\n if [i, j] in ant.way:\n dT[i][j] += 1 / ant.Lk\n if ant.number == elite:dT[i][j] += 1 / ant.Lk # Дополнительный феромон для пути элитного муравья\n return dT\n\n\ndef evaporate(matrix, dT, p):\n\n '''Испарение феромонов с ребер и обновление с учетом новой итерации'''\n \n for i in range(0, len(matrix)):\n for j in range(0, len(matrix)):\n matrix[i][j][1] = (1 - p) * matrix[i][j][1] # Испарение феромона\n matrix[i][j][1] = matrix[i][j][1] + dT[i][j]\n \n return matrix\n\n\ndef same_way(colony):\n \n '''Проверка на то, идут ли все муравьи одинаковым или равным путем'''\n \n route = 1\n Lk = colony[0].Lk\n for ant in colony:\n if Lk != ant.Lk:\n route += 1\n if route > Ant.numbers:return True\n else:return False\n \n\ndef main_cycle(colony, matrix, T, p):\n\n '''Основной цикл программы'''\n\n while True:\n \n for ant in colony: # цикл по муравьям\n \n ant.path = [ant.first_node] # Сброс аттрибута\n ant.point = ant.first_node # Точка, в которой находится муравей\n ant.way = [] # Сброс списка\n ant.taboo = [ant.first_node] # Сброс списка табу\n ant.Lk = 0 # Обнуление длины пройденного пути\n \n while True:\n ant.choice(matrix) # Метод выбора следующей точки\n ant.path.append(ant.next_node)\n ant.way.append([ant.point, ant.next_node])\n ant.point = ant.next_node\n if set(ant.path) == set(range(0, len(matrix))): break # Если пройдены все вершины.\n \n for i in range(0, len(ant.path) - 1): # Высчитывание длины пройденного пути\n ant.Lk += matrix[ant.path[i]][ant.path[i + 1]][0]\n ant.Lk+=matrix[ant.point][ant.first_node][0] # Возвращение в начальную точку\n \n dT = create_dT(colony)\n \n matrix = evaporate(matrix, dT, p)\n \n T -= 1\n \n equal_mark = same_way(colony) # Точка останова, если все муравьи идут одним либо равным по длине путем\n \n if T == 0 or equal_mark:return colony # условия выхода\n\n\nmatrix = sys.stdin.read() # Считывание матрицы\nmatrix = input_in_matrix(matrix) # str(matrix) -> list(matrix), включая концентрацию феромонов\n\nT = 50 # Количество итераций для прохождения\np = 0.5 # Коэф. испарения\n\nresult = [] # Минимальные пути, найденные различными колониями\n\nfor i in range(10): # максимальное число колоний, которые можно развернуть для матрицы 20x20 и 50 итераций в 30 сек\n colony = [] # Создание колонии\n for i in range(0, len(matrix)):\n colony.append(Ant())\n colony[i].first_node = i # Расположение муравьев по вершинам\n \n colony = main_cycle(colony, matrix, T, p) # Вызов основного цикла для отдельной колонии\n \n Lk = [] # Выбор наименьшего пути, найденного колонией\n for ant in colony:\n Lk.append(ant.Lk)\n del ant # Вычищение колонии\n \n result.append(min(Lk))\n\nprint(min(result)) # Вывод минимального пути, который смогли найти колонии\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"190511550","text":"import string\nimport requests\nimport demjson\nimport pickle\nimport os\nimport time\nimport logging\nfrom pathlib import Path\n\nimport lupupy.devices.alarm as ALARM\nimport lupupy.constants as CONST\nfrom lupupy.devices.binary_sensor import LupusecBinarySensor\nfrom lupupy.devices.switch import LupusecSwitch\nfrom lupupy.exceptions import LupusecException\n\n_LOGGER = logging.getLogger(__name__)\nhome = str(Path.home())\n\nclass Lupusec():\n \"\"\"Interface to Lupusec Webservices.\"\"\"\n\n def __init__(self, username, password, ip_address, get_devices=False):\n \"\"\"LupsecAPI constructor requires IP and credentials to the\n Lupusec Webinterface.\n \"\"\"\n self.session = requests.Session()\n self.session.auth = (username, password)\n self.api_url = \"http://{}/action/\".format(ip_address)\n self._request_post('login')\n\n self._mode = None\n self._devices = None\n\n try:\n self._history_cache = pickle.load(open(home + \"/\" + CONST.HISTORY_CACHE_NAME, \"rb\"))\n except (OSError, IOError) as e:\n self._history_cache = []\n pickle.dump(self._history_cache, open(home + \"/\" + CONST.HISTORY_CACHE_NAME, \"wb\"))\n\n self._panel = self.get_panel()\n self._cacheSensors = None\n self._cacheStampS = time.time()\n self._cachePss = None\n self._cacheStampP = time.time()\n\n if get_devices or self._devices == None:\n self.get_devices()\n\n def _request_get(self, action):\n response = self.session.get(self.api_url + action, timeout=15)\n _LOGGER.debug('Action and statuscode of apiGET command: %s, %s',\n action, response.status_code)\n return response\n\n def _request_post(self, action, params={}):\n return self.session.post(self.api_url + action, data=params)\n\n def clean_json(self, textdata):\n _LOGGER.debug('Input for clean json' + textdata)\n textdata = textdata.replace(\"\\t\", \"\")\n i = textdata.index('\\n')\n textdata = textdata[i+1:-2]\n textdata = demjson.decode(textdata)\n return textdata\n\n def get_power_switches(self):\n stampNow = time.time()\n length = len(self._devices)\n if self._cachePss is None or stampNow - self._cacheStampP > 2.0:\n self._cacheStamp_p = stampNow\n response = self._request_get('pssStatusGet')\n response = self.clean_json(response.text)['forms']\n powerSwitches = []\n counter = 1\n for pss in response:\n powerSwitch = {}\n if response[pss]['ready'] == 1:\n powerSwitch['status'] = response[pss]['pssonoff']\n powerSwitch['device_id'] = counter + length\n powerSwitch['type'] = CONST.TYPE_POWER_SWITCH\n powerSwitch['name'] = response[pss]['name']\n powerSwitches.append(powerSwitch)\n else:\n _LOGGER.debug('Pss skipped, not active')\n counter += 1\n self._cachePss = powerSwitches\n\n return self._cachePss\n\n def get_sensors(self):\n stamp_now = time.time()\n if self._cacheSensors is None or stamp_now - self._cacheStampS > 2.0:\n self._cacheStampS = stamp_now\n response = self._request_get('sensorListGet')\n response = self.clean_json(response.text)['senrows']\n sensors = []\n for device in response:\n device['status'] = device['cond']\n device['device_id'] = device['no']\n device.pop('cond')\n device.pop('no')\n if not device['status']:\n device['status'] = 'Geschlossen'\n else:\n device['status'] = None\n sensors.append(device)\n self._cacheSensors = sensors\n\n return self._cacheSensors\n\n def get_panel(self): # we are trimming the json from Lupusec heavily, since its bullcrap\n response = self._request_get('panelCondGet')\n if response.status_code != 200:\n print(response.text)\n raise Exception('Unable to get panel')\n panel = self.clean_json(response.text)['updates']\n panel['mode'] = panel['mode_st']\n panel.pop('mode_st')\n panel['device_id'] = CONST.ALARM_DEVICE_ID\n panel['type'] = CONST.ALARM_TYPE\n panel['name'] = CONST.ALARM_NAME\n\n history = self.get_history()\n\n for histrow in history:\n if histrow not in self._history_cache:\n if CONST.MODE_ALARM_TRIGGERED in histrow[CONST.HISTORY_ALARM_COLUMN]:\n panel['mode'] = CONST.STATE_ALARM_TRIGGERED\n self._history_cache.append(histrow)\n pickle.dump(self._history_cache, open(home + \"/\" + CONST.HISTORY_CACHE_NAME, \"wb\"))\n\n return panel\n\n def get_history(self):\n response = self._request_get(CONST.HISTORY_REQUEST)\n return self.clean_json(response.text)[CONST.HISTORY_HEADER]\n\n def refresh(self):\n \"\"\"Do a full refresh of all devices and automations.\"\"\"\n self.get_devices(refresh=True)\n\n def get_devices(self, refresh=False, generic_type=None):\n \"\"\"Get all devices from Lupusec.\"\"\"\n _LOGGER.info(\"Updating all devices...\")\n if refresh or self._devices is None:\n if self._devices is None:\n self._devices = {}\n\n responseObject = self.get_sensors()\n if (responseObject and\n not isinstance(responseObject, (tuple, list))):\n responseObject = responseObject\n\n for deviceJson in responseObject:\n # Attempt to reuse an existing device\n device = self._devices.get(deviceJson['name'])\n\n # No existing device, create a new one\n if device:\n device.update(deviceJson)\n else:\n device = newDevice(deviceJson, self)\n\n if not device:\n _LOGGER.info('Device is unknown')\n continue\n\n self._devices[device.device_id] = device\n\n # We will be treating the Lupusec panel itself as an armable device.\n panelJson = self.get_panel()\n _LOGGER.debug(\"Get the panel in get_devices: %s\", panelJson)\n\n self._panel.update(panelJson)\n\n alarmDevice = self._devices.get('0')\n\n if alarmDevice:\n alarmDevice.update(panelJson)\n else:\n alarmDevice = ALARM.create_alarm(panelJson, self)\n self._devices['0'] = alarmDevice\n\n # Now we will handle the power switches\n switches = self.get_power_switches()\n _LOGGER.debug(\n 'Get active the power switches in get_devices: %s', switches)\n\n for deviceJson in switches:\n # Attempt to reuse an existing device\n device = self._devices.get(deviceJson['name'])\n\n # No existing device, create a new one\n if device:\n device.update(deviceJson)\n else:\n device = newDevice(deviceJson, self)\n if not device:\n _LOGGER.info('Device is unknown')\n continue\n self._devices[device.device_id] = device\n\n if generic_type:\n devices = []\n for device in self._devices.values():\n if (device.type is not None and\n device.type in generic_type[0]):\n devices.append(device)\n return devices\n\n return list(self._devices.values())\n\n def get_device(self, device_id, refresh=False):\n \"\"\"Get a single device.\"\"\"\n if self._devices is None:\n self.get_devices()\n refresh = False\n\n device = self._devices.get(device_id)\n\n if device and refresh:\n device.refresh()\n\n return device\n\n def get_alarm(self, area='1', refresh=False):\n \"\"\"Shortcut method to get the alarm device.\"\"\"\n if self._devices is None:\n self.get_devices()\n refresh = False\n\n return self.get_device(CONST.ALARM_DEVICE_ID, refresh)\n\n def set_mode(self, mode):\n r = self._request_post(\n \"panelCondPost\",\n {\n 'mode': mode,\n }\n )\n responseJson = self.clean_json(r.text)\n return responseJson\n\n\ndef newDevice(deviceJson, lupusec):\n \"\"\"Create new device object for the given type.\"\"\"\n type_tag = deviceJson.get('type')\n\n if not type_tag:\n _LOGGER.info('Device has no type')\n\n if type_tag in CONST.TYPE_OPENING:\n return LupusecBinarySensor(deviceJson, lupusec)\n elif type_tag in CONST.TYPE_SENSOR:\n return LupusecBinarySensor(deviceJson, lupusec)\n elif type_tag in CONST.TYPE_SWITCH:\n return LupusecSwitch(deviceJson, lupusec)\n else:\n _LOGGER.info('Device is not known')\n return None\n","sub_path":"lupupy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"20819262","text":"# python3\nfrom sys import stdin\nfrom itertools import combinations\n \n\nEPS = 1e-6\nPRECISION = 20\n\nclass Equation:\n def __init__(self, a, b):\n self.a = [list(r) for r in a]\n self.b = list(b)\n\nclass Position:\n def __init__(self, column, row):\n self.column = column\n self.row = row\n\ndef ReadEquation():\n size = int(input())\n a = []\n b = []\n for row in range(size):\n line = list(map(float, input().split()))\n a.append(line[:size])\n b.append(line[size])\n return Equation(a, b)\n\ndef SelectPivotElement(a, used_rows, used_columns):\n # This algorithm selects the first free element.\n # You'll need to improve it to pass the problem.\n pivot_element = Position(0, 0)\n while used_rows[pivot_element.row]:\n pivot_element.row += 1\n while used_columns[pivot_element.column] or a[pivot_element.row][pivot_element.column] == 0:\n pivot_element.column += 1\n if pivot_element.column >= len(a[pivot_element.row]): return None\n return pivot_element\n\ndef SwapLines(a, b, used_rows, pivot_element):\n a[pivot_element.column], a[pivot_element.row] = a[pivot_element.row], a[pivot_element.column]\n b[pivot_element.column], b[pivot_element.row] = b[pivot_element.row], b[pivot_element.column]\n used_rows[pivot_element.column], used_rows[pivot_element.row] = used_rows[pivot_element.row], used_rows[pivot_element.column]\n pivot_element.row = pivot_element.column;\n\ndef ProcessPivotElement(a, b, pivot_element):\n c = pivot_element.column\n r = pivot_element.row\n prow = a[r]\n d = prow[c]\n\n b[r] /= d\n for j in range(len(prow)):\n prow[j] /= d\n\n for i in range(len(a)):\n if i == r: continue\n row = a[i]\n m = row[c]\n b[i] -= m * b[r]\n for j in range(len(row)):\n row[j] -= m * prow[j]\n\n\n\ndef MarkPivotElementUsed(pivot_element, used_rows, used_columns):\n used_rows[pivot_element.row] = True\n used_columns[pivot_element.column] = True\n\ndef SolveEquation(equation):\n a = equation.a\n b = equation.b\n size = len(a)\n\n used_columns = [False] * size\n used_rows = [False] * size\n for step in range(size):\n pivot_element = SelectPivotElement(a, used_rows, used_columns)\n if pivot_element == None: return None\n SwapLines(a, b, used_rows, pivot_element)\n ProcessPivotElement(a, b, pivot_element)\n MarkPivotElementUsed(pivot_element, used_rows, used_columns)\n\n return b\n\ndef PrintColumn(column):\n size = len(column)\n for row in range(size):\n print(\"%.20lf\" % column[row])\n\n\n\ndef dot(a, b):\n return sum([a[i] * b[i] for i in range(len(a))])\n\ndef is_inequation_valid(a, r, x):\n return dot(a, x) <= r + EPS\n\ndef is_valid_solution(a, b, x):\n if x == None: return False\n for i in range(len(a)):\n if not is_inequation_valid(a[i], b[i], x): return False\n return True\n\n\n\n\ndef solve_diet_problem(n, m, A, b, c): \n\n # extend by X >= 0\n A = list(A)\n B = list(b)\n for i in range(m):\n row = [0] * m\n row[i] = -1\n A.append(row)\n B.append(0)\n\n A.append([1] * m)\n B.append(m * 1000000 * 1.1)\n\n # find possible solutions for combinations\n vertices = []\n for select in combinations(range(len(A)), m):\n sa = [A[i] for i in select]\n sb = [B[i] for i in select]\n eq = Equation(sa, sb)\n x = SolveEquation(eq)\n\n if is_valid_solution(A, B, x):\n vertices.append((x, dot(c, x), len(A)-1 in select))\n\n if len(vertices) == 0: return -1, []\n ox, op, invalid = max(vertices, key = lambda v: v[1])\n\n return [1 if invalid else 0, ox]\n\nn, m = list(map(int, stdin.readline().split()))\nA = []\nfor i in range(n):\n A += [list(map(int, stdin.readline().split()))]\nb = list(map(int, stdin.readline().split()))\nc = list(map(int, stdin.readline().split()))\n\nanst, ansx = solve_diet_problem(n, m, A, b, c)\n\nif anst == -1:\n print(\"No solution\")\nif anst == 0: \n print(\"Bounded solution\")\n print(' '.join(list(map(lambda x : '%.18f' % x, ansx))))\nif anst == 1:\n print(\"Infinity\")\n \n\n","sub_path":"coursera_AlgC/5_advanced/week2/diet/diet.py","file_name":"diet.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"590572325","text":"from ctypes import *\nimport platform\nfrom time import sleep\nfrom usb_device import *\nfrom usb2iic import *\n\nif __name__ == '__main__': \n DevHandles = (c_uint * 20)()\n DevIndex = 0\n IICIndex = 0\n # Scan device\n ret = USB_ScanDevice(byref(DevHandles))\n if(ret == 0):\n print(\"No device connected!\")\n exit()\n else:\n print(\"Have %d device connected!\"%ret)\n # Open device\n ret = USB_OpenDevice(DevHandles[DevIndex])\n if(bool(ret)):\n print(\"Open device success!\")\n else:\n print(\"Open device faild!\")\n exit()\n # Get device infomation\n LuceroInfo = DEVICE_INFO()\n LuceroFunctionString = (c_char * 256)()\n ret = DEV_GetDeviceInfo(DevHandles[DevIndex],byref(LuceroInfo),byref(LuceroFunctionString))\n if(bool(ret)):\n print(\"Lucero device infomation:\")\n print(\"--Firmware Name: %s\"%bytes(LuceroInfo.FirmwareName).decode('ascii'))\n print(\"--Firmware Version: v%d.%d.%d\"%((LuceroInfo.FirmwareVersion>>24)&0xFF,(LuceroInfo.FirmwareVersion>>16)&0xFF,LuceroInfo.FirmwareVersion&0xFFFF))\n print(\"--Hardware Version: v%d.%d.%d\"%((LuceroInfo.HardwareVersion>>24)&0xFF,(LuceroInfo.HardwareVersion>>16)&0xFF,LuceroInfo.HardwareVersion&0xFFFF))\n print(\"--Build Date: %s\"%bytes(LuceroInfo.BuildDate).decode('ascii'))\n print(\"--Serial Number: \",end='')\n for i in range(0, len(LuceroInfo.SerialNumber)):\n print(\"%08X\"%LuceroInfo.SerialNumber[i],end='')\n print(\"\")\n print(\"--Function String: %s\"%bytes(LuceroFunctionString.value).decode('ascii'))\n else:\n print(\"Get device infomation faild!\")\n exit()\n # 设置GPIO输入输出电压,只针对带可变电压输出版本的适配器有用,其他适配器默认是3.3V\n DEV_SetPowerLevel(DevHandles[DevIndex],POWER_LEVEL_3V3)\n # Initialize i2c\n IICConfig = IIC_CONFIG()\n IICConfig.ClockSpeed = 400000\n IICConfig.Master = 1\n IICConfig.AddrBits = 7\n IICConfig.EnablePu = 1\n # 初始化IIC\n ret = IIC_Init(DevHandles[DevIndex],IICIndex,byref(IICConfig));\n if ret != IIC_SUCCESS:\n print(\"Initialize iic faild!\")\n exit()\n else:\n print(\"Initialize iic sunccess!\")\n # 扫描IIC总线上能正常应答的设备\n SlaveAddr = (c_ushort * 128)()\n SlaveAddrNum = IIC_GetSlaveAddr(DevHandles[DevIndex],IICIndex,byref(SlaveAddr))\n if SlaveAddrNum <= 0:\n print(\"Get iic address faild!\")\n exit()\n else:\n print(\"Get iic address sunccess!\")\n print(\"IIC addr:\")\n for i in range(0,SlaveAddrNum):\n print(\"%02X \"%SlaveAddr[i],end='')\n print(\"\")\n # 向0x08地址开始连续写8字节数据\n WriteBuffer = (c_byte * 9)()\n WriteBuffer[0] = 0x08\n for i in range(0,8):\n WriteBuffer[1+i] = i\n ret = IIC_WriteBytes(DevHandles[DevIndex],IICIndex,0x50,byref(WriteBuffer),9,100)\n if ret != IIC_SUCCESS:\n print(\"Write iic faild!\")\n exit()\n else:\n print(\"Write iic sunccess!\")\n sleep(0.01)\n # 从0x08地址开始读取8字节数据\n ReadBuffer = (c_byte * 8)()\n WriteBuffer[0] = 0x08\n for i in range(0,8):\n WriteBuffer[1+i] = i\n ret = IIC_WriteReadBytes(DevHandles[DevIndex],IICIndex,0x50,byref(WriteBuffer),1,byref(ReadBuffer),8,100)\n if ret != IIC_SUCCESS:\n print(\"WriteRead iic faild!\")\n exit()\n else:\n print(\"WriteRead iic sunccess!\")\n print(\"Read Data:\")\n for i in range(0,len(ReadBuffer)):\n print(\"%02X \"%ReadBuffer[i],end='')\n print(\"\")\n # Close device\n ret = USB_CloseDevice(DevHandles[DevIndex])\n if(bool(ret)):\n print(\"Close device success!\")\n else:\n print(\"Close device faild!\")\n exit()\n","sub_path":"SDK & Exmaples/examples/python/USB2IIC/USB2IIC_AT24C02/USB2IIC_AT24C02.py","file_name":"USB2IIC_AT24C02.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"96549336","text":"import msgpack, logging, os, os.path\nfrom collections import deque\nfrom threading import Condition, Lock\nfrom mixins import mixins\nfrom util import VimError, VimExit, VimTimeout\nimport cProfile, pstats, StringIO\n\nlogger = logging.getLogger(__name__)\ndebug, info, warn = (logger.debug, logger.info, logger.warn,)\n\nclass Promise(object):\n def __init__(self, client, request_id, expected_type=None):\n def process_response(message):\n if message.error:\n # error\n raise VimError(message.error)\n if expected_type and hasattr(client.vim, expected_type):\n # result should be a handle, wrap in it's specialized class\n klass = getattr(client.vim, expected_type)\n rv = klass(client.vim, message.result)\n klass.initialize(rv)\n return rv\n return message.result\n\n def wait(timeout=None):\n interrupted = False\n while True:\n if interrupted:\n with client.interrupt_lock:\n pass\n client.invoke_message_cb()\n with client.stream_lock:\n if self.message:\n return process_response(self.message)\n interrupted = client.queue_message(timeout)\n\n self.message = None\n self.wait = wait\n\nclass Message(object):\n def __init__(self, client, name=None, arg=None, result=None, error=None,\n request_id=None, response_id=None, ):\n def reply(value, error=False):\n if error:\n resp = msgpack.packb([1, request_id, value, None])\n else:\n resp = msgpack.packb([1, request_id, None, value])\n client.stream.write(resp)\n self.name = name\n self.arg = arg\n self.result = result\n self.error = error\n self.type = 'event'\n if request_id:\n self.type = 'request'\n self.reply = reply\n elif response_id:\n self.type = 'response'\n self.response_id = response_id\n\nclass Remote(object):\n \"\"\"\n Base class for all remote objects(Buffer, Window...).i\n \"\"\"\n def __init__(self, vim, handle):\n \"\"\"\n This is the only initializer remote objects need\n \"\"\"\n self._vim = vim\n self._handle = handle\n\n def __eq__(self, other):\n return hasattr(other, '_handle') and self._handle == other._handle\n\n\n# FIFO Mutex algorithm to ensure there's no lock starvation. Adapted from\n# this SO answer: http://stackoverflow.com/a/12703543/304141\nclass FifoLock(object):\n def __init__(self):\n self.inner = Condition(Lock())\n self.head = self.tail = 0\n\n def acquire(self, steal=False):\n with self.inner:\n position = self.tail\n self.tail += 1\n while position != self.head:\n self.inner.wait()\n\n def release(self):\n with self.inner:\n self.head += 1\n self.inner.notify_all()\n\n def __enter__(self):\n self.acquire()\n\n def __exit__(self, type, value, traceback):\n self.release()\n\nclass Client(object):\n \"\"\"\n Neovim client. It depends on a stream, an object that implements three\n methods:\n - read(): Returns any amount of data as soon as it's available\n - write(chunk): Writes data\n - interrupt(): Interrupts a blocking `read()` call from another thread.\n\n Both methods should be fully blocking.\n \"\"\"\n def __init__(self, stream, vim_compatible=False):\n self.next_request_id = 1\n self.stream = stream\n self.unpacker = msgpack.Unpacker()\n self.pending_messages = deque()\n self.pending_requests = {}\n self.vim_compatible = vim_compatible\n self.vim = None\n self.stream_lock = FifoLock()\n self.interrupt_lock = Lock()\n self.message_cb = None\n self.loop_running = False\n\n def unpack_message(self, timeout=None):\n \"\"\"\n Unpacks the next message from the input stream. This blocks until\n `timeout` or forever if timeout=None\n \"\"\"\n while True:\n try:\n debug('waiting for message...')\n msg = self.unpacker.next()\n debug('received message: %s', msg)\n name = arg = error = result = request_id = response_id = None\n msg_type = msg[0]\n if msg_type == 0:\n request_id = msg[1]\n name = msg[2]\n arg = msg[3]\n elif msg_type == 1:\n response_id = msg[1]\n error = msg[2]\n result = msg[3]\n elif msg_type == 2:\n name = msg[1]\n arg = msg[2]\n else:\n raise Exception('Received invalid message type')\n return Message(self, name=name, arg=arg, result=result,\n error=error, request_id=request_id,\n response_id=response_id)\n except StopIteration:\n debug('unpacker needs more data...')\n chunk = self.stream.read(timeout)\n if not chunk:\n if chunk == False:\n raise VimTimeout()\n return\n debug('feeding data to the unpacker')\n self.unpacker.feed(chunk)\n\n def queue_message(self, timeout=None):\n message = self.unpack_message(timeout)\n if not message:\n # interrupted\n return True\n if message.type is 'response':\n promise = self.pending_requests.pop(message.response_id)\n promise.message = message\n else:\n self.pending_messages.append(message)\n return False\n\n def msgpack_rpc_request(self, method_id, args, expected_type=None):\n \"\"\"\n Sends a msgpack-rpc request to Neovim and return a Promise for the\n response\n \"\"\"\n with self.interrupt_lock:\n self.stream.interrupt() # interrupt ongoing reads \n with self.stream_lock:\n request_id = self.next_request_id\n # Update request id\n self.next_request_id = request_id + 1\n # Send the request\n data = msgpack.packb([0, request_id, method_id, args])\n self.stream.write(data)\n rv = Promise(self, request_id, expected_type)\n self.pending_requests[request_id] = rv\n return rv\n\n def next_message(self, timeout=None):\n \"\"\"\n Returns the next server message\n \"\"\"\n interrupted = False\n while True:\n if interrupted:\n with self.interrupt_lock:\n pass\n self.invoke_message_cb()\n with self.stream_lock:\n if self.pending_messages:\n return self.pending_messages.popleft()\n interrupted = self.queue_message(timeout)\n\n def invoke_message_cb(self):\n cb = self.message_cb\n debug('registered callback: %s', self)\n if cb:\n try:\n # If there's a callback registered for messages, invoke it\n # immediately\n cb(self.pending_messages.popleft())\n except IndexError:\n pass\n\n def message_loop(self, message_cb):\n profiling = 'NEOVIM_PYTHON_PROFILE' in os.environ\n try:\n assert not self.loop_running\n info('starting message loop')\n self.message_cb = message_cb\n self.loop_running = True\n if profiling:\n info('starting profiler')\n pr = cProfile.Profile()\n pr.enable()\n while True:\n try:\n self.next_message()\n except VimExit:\n break\n finally:\n if profiling:\n pr.disable()\n report = os.path.abspath('.nvim-python-client.profile')\n info('stopped profiler, writing report to %s', report)\n s = StringIO.StringIO()\n ps = pstats.Stats(pr, stream=s)\n ps.strip_dirs().sort_stats('tottime').print_stats(30)\n with open(report, 'w') as f:\n f.write(s.getvalue())\n info('exiting message loop')\n self.message_cb = None\n self.loop_running = False\n\n\n def push_message(self, name, arg):\n \"\"\"\n Pushes a \"virtual message\" that will be returned by `next_message`.\n This method can called from other threads for integration with event\n loops, such as those provided by GUI libraries.\n \"\"\"\n with self.interrupt_lock:\n self.stream.interrupt()\n self.pending_messages.append(Message(self, name, arg))\n\n def discover_api(self):\n \"\"\"\n Discovers the remote API using the special method '0'. After this\n the client will have a `vim` attribute containing an object\n that implements an interface similar to the one found in the\n python-vim module(legacy python->vim bridge)\n \"\"\"\n if self.vim:\n # Only need to do this once\n return\n channel_id, api = self.msgpack_rpc_request(0, []).wait()\n api = msgpack.unpackb(api)\n # The 'Vim' class is the main entry point of the api\n classes = {'vim': type('Vim', (), {})}\n setattr(classes['vim'], 'next_message',\n lambda s, *args, **kwargs: self.next_message(*args, **kwargs))\n setattr(classes['vim'], 'message_loop',\n lambda s, *args, **kwargs: self.message_loop(*args, **kwargs))\n setattr(classes['vim'], 'push_message',\n lambda s, *args, **kwargs: self.push_message(*args, **kwargs))\n # Build classes for manipulating the remote structures, assigning to a\n # dict using lower case names as keys, so we can easily match methods\n # in the API.\n for cls in api['classes']:\n klass = type(cls + 'Base', (Remote,), {})\n # Methods of this class will pass an integer representing the\n # remote object as first argument\n classes[cls.lower()] = klass\n # now build function wrappers\n for function in api['functions']:\n # Split the name on underscores, the first part is the class name,\n # the remaining is the function name\n class_name, method_name = function['name'].split('_', 1)\n generate_wrapper(self,\n classes[class_name],\n method_name,\n function['id'],\n function['return_type'],\n function['parameters'])\n if self.vim_compatible:\n make_vim_compatible(classes['vim'])\n # Now apply all available mixins to the generated classes\n for name, mixin in mixins.items():\n classes[name] = type(mixin.__name__, (classes[name], mixin,), {})\n # Create the 'vim object', which is a singleton of the 'Vim' class\n self.vim = classes['vim']()\n # Initialize with some useful attributes\n classes['vim'].initialize(self.vim, classes, channel_id)\n # Add attributes for each other class\n for name, klass in classes.items():\n if name != 'vim':\n setattr(self.vim, klass.__name__, klass)\n\ndef generate_wrapper(client, klass, name, fid, return_type, parameters):\n \"\"\"\n Generate an API call wrapper\n \"\"\"\n # Build a name->pos map for the parameters \n parameter_names = {}\n parameter_count = 0\n for param in parameters:\n parameter_names[param[1]] = parameter_count\n parameter_count += 1\n async_name = 'send_' + name\n # These are the actual functions\n @fname(async_name)\n def async_func(*args, **kwargs):\n if isinstance(args[0], client.vim.__class__):\n # functions of the vim object don't need 'self'\n args = args[1:]\n argv = []\n # fill with positional arguments\n for i, arg in enumerate(args):\n if hasattr(client.vim, parameters[i][0]):\n # If the type is a remote object class, we use it's remote\n # handle instead\n arg = arg._handle\n # Add to the argument vector \n argv.append(arg)\n return client.msgpack_rpc_request(fid, argv, return_type)\n @fname(name)\n def func(*args, **kwargs):\n return async_func(*args, **kwargs).wait()\n\n setattr(klass, async_name, async_func)\n setattr(klass, name, func)\n\ndef fname(name):\n \"\"\"\n Helper for renaming generated functions\n \"\"\"\n def dec(f):\n f.__name__ = name\n return f\n return dec\n\ndef process_eval_result(obj):\n def process_dict(d):\n for k, v in d.items():\n d[k] = process_value(v)\n return d\n\n def process_list(l):\n for i, v in enumerate(l):\n l[i] = process_value(v)\n return l\n\n def process_value(v):\n if isinstance(v, (int, long, float)):\n return str(v)\n if isinstance(v, dict):\n return process_dict(v)\n if isinstance(v, list):\n return process_list(v)\n return v\n\n return process_value(obj)\n\ndef make_vim_compatible(vim_class):\n eval_orig = vim_class.eval\n vim_class.eval = lambda *a, **ka: process_eval_result(eval_orig(*a, **ka))\n","sub_path":"neovim/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":13711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"453591580","text":"# Copyright (c) 2015 Red Hat, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy\n# of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\nimport functools\n\nfrom oslo_log import log as logging\n\nimport zaqar.common.api.response as response\nfrom zaqar.i18n import _\n\nLOG = logging.getLogger(__name__)\n\n\ndef raises_conn_error(func):\n \"\"\"Handles generic Exceptions\n\n This decorator catches generic Exceptions and returns a generic\n Response.\n \"\"\"\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except Exception as ex:\n LOG.exception(ex)\n error = _(\"Unexpected error.\")\n req = kwargs.get('req')\n return error_response(req, ex, error)\n\n return wrapper\n\n\ndef error_response(req, exception, headers=None, error=None):\n body = {'exception': str(exception), 'error': error}\n resp = response.Response(req, body, headers)\n return resp\n","sub_path":"zaqar/common/api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"304642227","text":"\ndef twoSum(nums, target):\n #首先定义一个hashMap key为值,value为索引进行保存\n hashMap = {}\n for idx, num in enumerate(nums):\n hashMap[num] = idx\n # 再循坏一次\n for i,val in enumerate(nums):\n j = hashMap.get(target - val)\n # j 不为空 且 i,j 的索引不相等\n if i != j and j is not None:\n return [i,j]\n\n#复杂度分析\n# 时间复杂度:O(N),其中 N 是数组中的元素数量。对于每一个元素 x,我们可以 O(1) 地寻找 target - x。\n# 空间复杂度:O(N),其中 N 是数组中的元素数量。主要为哈希表的开销。\n\nprint(twoSum([2,7,11,15],9))","sub_path":"Week_02/Algo/twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"221863685","text":"import unittest\nimport neathgeohash as ngh\nimport numpy as np\n\n\nclass TestGeohash(unittest.TestCase):\n \"\"\"\n The furmulas for the calculations of distance can be\n found: https://www.movable-type.co.uk/scripts/latlong.html\n \"\"\"\n\n def test_encode(self):\n gh = ngh.encode(42.6, -5.6)\n self.assertEqual('ezs42e44yx96', gh)\n\n def test_decode(self):\n b32 = list('0123456789bcdefghjkmnpqrstuvwxyz')\n L = 1000\n lens = np.random.randint(1,12,L)\n hashes = [''.join(np.random.choice(b32,size=sz)) for sz in lens]\n roundtrip = []\n for h in hashes:\n dc = ngh.decode(h)\n roundtrip.append(ngh.encode(float(dc[0]),float(dc[1]),len(h)))\n # if this fails, we want to recover the hash:\n bads = [a for a,b in zip(hashes,roundtrip) if a != b]\n if len(bads):\n print(bads)\n self.assertEqual(len(bads),0)\n\n def test_decode_exactly(self):\n ll_e = ngh.decode_exactly('ezs42')\n self.assertEqual((42.60498046875, -5.60302734375, 0.02197265625, 0.02197265625), ll_e)\n\n def test_fast_encode_check_array_dims(self):\n gh_fe = ngh.fast_encode([[42.6, -5.6]])\n self.assertEqual((1,), gh_fe.shape)\n gh_fe = ngh.fast_encode([[42.6, -5.6], [42.6, -5.6], [42.6, -5.6]])\n self.assertEqual((3,), gh_fe.shape)\n\n def test_fast_encode(self):\n gh_1 = ngh.encode(42.6, -5.6)\n gh_fe = ngh.fast_encode([[42.6, -5.6]])\n self.assertEqual(gh_fe[0].decode(), gh_fe[0].decode())\n gh_2 = ngh.encode(49.471244, 22.551950)\n gh_fe = ngh.fast_encode([[42.6, -5.6],\n [49.471244, 22.551950]])\n self.assertEqual(\n [gh_1.encode(encoding='UTF-8'),gh_2.encode(encoding='UTF-8')],\n gh_fe.tolist()\n )\n \n def test_get_neighbor_collection(self):\n tiles = ['bbc123','bbc124','bbc128','ccd345']\n all_neighbor = set([n for e in tiles for n in ngh.get_neighbors(e)]) - set(tiles)\n n2 = ngh.get_neighbor_collection(tiles)\n self.assertEqual(sorted(all_neighbor),sorted(n2))\n self.assertListEqual(ngh.get_neighbor_collection(tiles[0]),ngh.get_neighbors(tiles[0]))\n with self.assertRaises(ValueError):\n ngh.get_neighbor_collection(['bbq','bbq2','bbq8'])\n \n def test_get_neighbor_collection_basecase(self):\n tiles = ['bbc123']\n nn = ngh.get_neighbor_collection(tiles)\n self.assertEqual(nn,ngh.get_neighbors(tiles[0]))\n\n def test_atomizer(self):\n tile = ngh.encode(42.0,69.3,7)\n res = ngh.atomize_geohash(tile,9)\n self.assertEqual(len(res),len(set(res)))\n self.assertTrue(all(len(e)==9 for e in res))\n self.assertTrue(all(e[:7] == tile for e in res))\n\n def test_to_geojson(self):\n gh = \"z8675309z\"\n box = ngh.geohash_to_geojson(gh)\n coords = box['coordinates'][0]\n allC = [e[0] for e in coords] + [e[1] for e in coords]\n self.assertEqual(coords[0],coords[4])\n self.assertEqual(len(set(allC)),4)\n \n def test_snap_to_grid(self):\n p0 = np.random.uniform(-60,60,size=2)\n p1 = p0 + np.random.uniform(-1e-6,1e-6,size=2)\n enc = ngh.encode(*p0,8)\n sg1 = ngh.snap_to_grid(*p0,8)\n sg2 = ngh.snap_to_grid(*p1,8)\n self.assertEqual(sg1,sg2)\n self.assertEqual(ngh.decode_exactly(enc),sg1)\n\n def test_group_children(self):\n ghs = ['duudeeduuh','fruufruu33']\n gh = ngh.atomize_geohash(ghs[0],11) + ngh.atomize_geohash(ghs[1],11)\n self.assertEqual(ghs,ngh.group_children(gh))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_geohash.py","file_name":"test_geohash.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"579635846","text":"import argparse\nimport cv2 as cv\nfrom cv2 import imread\nimport numpy as np\nfrom skimage.color import rgb2gray, gray2rgb\nfrom skimage.transform import resize\nfrom model import Model\nimport tensorflow as tf\nfrom add_filter import ashhat_filter, james_filter\nfrom add_bow import bow_filter\nfrom add_dog_filter import dog_filter\nfrom add_toast import toast_filter\n\ndef preprocess(image):\n # Change to gray scale\n image = rgb2gray(image)\n\n # Pad to square (pad bottom and right side only)\n max_dim = np.max(image.shape)\n new_image = np.zeros((max_dim, max_dim))\n new_image[0:image.shape[0], 0:image.shape[1]] = image\n\n # Resize to 224 x 224\n new_image = resize(new_image, (224, 224))\n new_image = gray2rgb(new_image) / 255.\n\n scaling_factor = max_dim / 224\n\n return np.reshape(new_image, (1, 224, 224, 3)), scaling_factor\n\n\n\ndef main():\n\n model = Model(224,224)\n model.compile_model()\n model.load_trained_model()\n\n #cap = cv.VideoCapture(0)\n cap = cv.VideoCapture('kitkat4.mp4')\n\n while(cap.isOpened()):\n ret, frame = cap.read()\n img, scaling_factor = preprocess(frame)\n gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n predicted = model.model.predict(img)\n predicted = tf.reshape(predicted, (9,2))\n predicted = predicted.numpy()\n\n coords = np.floor(predicted * scaling_factor).astype(np.int)\n #new_im = james_filter(frame, coords)\n new_im = toast_filter(frame, coords)\n\n new_image_chan = np.copy(new_im[:,:,0])\n new_im[:,:,0] = new_im[:,:,2]\n new_im[:,:,2] = new_image_chan\n\n #new_im = bow_filter(frame, coords)\n # new_im *= 255\n # new_im = new_im.astype(np.int)\n\n cv.imshow('frame', new_im)\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n\n cap.release()\n cv.destroyAllWindows()\n\nmain()\n","sub_path":"process_video.py","file_name":"process_video.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"258792402","text":"\n\nfrom torch.utils.data import DataLoader\nfrom sentence_transformers import losses, util\nfrom sentence_transformers import SentencesDataset, LoggingHandler, SentenceTransformer, evaluation\nfrom sentence_transformers.readers import InputExample\nimport logging\nfrom datetime import datetime\nimport csv\nimport os\nfrom zipfile import ZipFile\nimport random\n\ncur_dir = os.path.split(os.path.realpath(__file__))[0]\n#### Just some code to print debug information to stdout\nlogging.basicConfig(format='%(asctime)s - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO,\n handlers=[LoggingHandler()])\n#### /print debug information to stdout\n\n\n# As base model, we use DistilBERT-base that was pre-trained on NLI and STSb data\nmodel = SentenceTransformer('distilbert-base-nli-stsb-mean-tokens')\n\n# Training for multiple epochs can be beneficial, as in each epoch a mini-batch is sampled differently\n# hence, we get different negatives for each positive\nnum_epochs = 10\n\n# Increasing the batch size improves the performance for MultipleNegativesRankingLoss. Choose it as large as possible\n# I achieved the good results with a batch size of 300-350 (requires about 30 GB of GPU memory)\ntrain_batch_size = 64\n\ndataset_path = os.path.join(cur_dir, 'quora-IR-dataset')\nmodel_save_path = os.path.join(cur_dir,'output/training_MultipleNegativesRankingLoss-'+datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\n\nos.makedirs(model_save_path, exist_ok=True)\n\n# Check if the dataset exists. If not, download and extract\nif not os.path.exists(dataset_path):\n logging.info(\"Dataset not found. Download\")\n zip_save_path = os.path.join(cur_dir, 'quora-IR-dataset.zip')\n util.http_get(url='https://public.ukp.informatik.tu-darmstadt.de/reimers/sentence-transformers/datasets/quora-IR-dataset.zip', path=zip_save_path)\n with ZipFile(zip_save_path, 'r') as zip:\n zip.extractall(dataset_path)\n\n\n######### Read train data ##########\ntrain_samples = []\nwith open(os.path.join(dataset_path, \"classification/train_pairs.tsv\"), encoding='utf8') as fIn:\n reader = csv.DictReader(fIn, delimiter='\\t', quoting=csv.QUOTE_NONE)\n for row in reader:\n if row['is_duplicate'] == '1':\n train_samples.append(InputExample(texts=[row['question1'], row['question2']], label=1))\n train_samples.append(InputExample(texts=[row['question2'], row['question1']], label=1)) #if A is a duplicate of B, then B is a duplicate of A\n\n\n# After reading the train_samples, we create a SentencesDataset and a DataLoader\ntrain_dataset = SentencesDataset(train_samples, model=model)\ntrain_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=train_batch_size)\ntrain_loss = losses.MultipleNegativesRankingLoss(model)\n\n\n###### Duplicate Questions Information Retrieval ######\nevaluators = []\n# Given a question and a large corpus of thousands questions, find the most relevant (i.e. duplicate) question\n# in that corpus.\n\n# For faster processing, we limit the development corpus to only 10,000 sentences.\nmax_corpus_size = 100000\n\nir_queries = {} #Our queries (qid => question)\nir_needed_qids = set() #QIDs we need in the corpus\nir_corpus = {} #Our corpus (qid => question)\nir_relevant_docs = {} #Mapping of relevant documents for a given query (qid => set([relevant_question_ids])\n\nwith open(os.path.join(dataset_path, 'information-retrieval/dev-queries.tsv'), encoding='utf8') as fIn:\n next(fIn) # Skip header\n for line in fIn:\n qid, query, duplicate_ids = line.strip().split('\\t')\n duplicate_ids = duplicate_ids.split(',')\n ir_queries[qid] = query\n ir_relevant_docs[qid] = set(duplicate_ids)\n\n for qid in duplicate_ids:\n ir_needed_qids.add(qid)\n\n# First get all needed relevant documents (i.e., we must ensure, that the relevant questions are actually in the corpus\ndistraction_questions = {}\nwith open(os.path.join(dataset_path, 'information-retrieval/corpus.tsv'), encoding='utf8') as fIn:\n next(fIn) # Skip header\n for line in fIn:\n qid, question = line.strip().split('\\t')\n\n if qid in ir_needed_qids:\n ir_corpus[qid] = question\n else:\n distraction_questions[qid] = question\n\n# Now, also add some irrelevant questions to fill our corpus\nother_qid_list = list(distraction_questions.keys())\nrandom.shuffle(other_qid_list)\n\nfor qid in other_qid_list[0:max(0, max_corpus_size-len(ir_corpus))]:\n ir_corpus[qid] = distraction_questions[qid]\n\n# Given queries, a corpus and a mapping with relevant documents, the InformationRetrievalEvaluator computes different IR\n# metrices. For our use case MRR@k and Accuracy@k are relevant.\nir_evaluator = evaluation.InformationRetrievalEvaluator(ir_queries, ir_corpus, ir_relevant_docs)\nevaluators.append(ir_evaluator)\n\n# Create a SequentialEvaluator. This SequentialEvaluator runs all three evaluators in a sequential order.\n# We optimize the model with respect to the score from the last evaluator (scores[-1])\nseq_evaluator = evaluation.SequentialEvaluator(evaluators, main_score_function=lambda scores: scores[-1])\n\nlogging.info(\"Evaluate model without training\")\nseq_evaluator(model, epoch=0, steps=0, output_path=model_save_path)\n\n# Train the model\nmodel.fit(train_objectives=[(train_dataloader, train_loss)],\n evaluator=seq_evaluator,\n epochs=num_epochs,\n warmup_steps=1000,\n output_path=model_save_path,\n output_path_ignore_not_empty=True\n )","sub_path":"examples/training/quora_duplicate_questions/training_RankingLoss.py","file_name":"training_RankingLoss.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"400702349","text":"# fmt: off\nimport sys\n\ntry:\n from functools import cache\nexcept ImportError: # pragma: no cover\n from functools import lru_cache\n\n cache = lru_cache(maxsize=None)\n\ntry:\n from ast import unparse as ast_unparse\nexcept ImportError: # pragma: no cover\n from astunparse import unparse as _unparse\n\n def ast_unparse(t): # type: ignore\n return _unparse(t).strip(\"\\t\\n \\\"'\")\n\ntry:\n from types import GenericAlias\nexcept ImportError: # pragma: no cover\n from typing import _GenericAlias as GenericAlias # type: ignore\n\n\ndef removesuffix(x: str, suffix: str):\n try:\n return x.removesuffix(suffix)\n except AttributeError: # pragma: no cover\n if x.endswith(suffix):\n x = x[: -len(suffix)]\n return x\n\n\nif sys.version_info >= (3, 9):\n from typing import ForwardRef\nelse: # pragma: no cover\n from typing import _Final, _type_check, _GenericAlias\n\n # https://github.com/python/cpython/blob/4db8988420e0a122d617df741381b0c385af032c/Lib/typing.py#L298-L314\n # ✂ start ✂\n def _eval_type(t, globalns, localns, recursive_guard=frozenset()):\n \"\"\"Evaluate all forward references in the given type t.\n For use of globalns and localns see the docstring for get_type_hints().\n recursive_guard is used to prevent prevent infinite recursion\n with recursive ForwardRef.\n \"\"\"\n if isinstance(t, ForwardRef):\n return t._evaluate(globalns, localns, recursive_guard)\n if isinstance(t, (_GenericAlias, GenericAlias)):\n ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__)\n if ev_args == t.__args__:\n return t\n if isinstance(t, GenericAlias):\n return GenericAlias(t.__origin__, ev_args)\n else:\n return t.copy_with(ev_args)\n return t\n # ✂ end ✂\n\n # https://github.com/python/cpython/blob/4db8988420e0a122d617df741381b0c385af032c/Lib/typing.py#L569-L629\n # ✂ start ✂\n class ForwardRef(_Final, _root=True):\n \"\"\"Internal wrapper to hold a forward reference.\"\"\"\n\n __slots__ = ('__forward_arg__', '__forward_code__',\n '__forward_evaluated__', '__forward_value__',\n '__forward_is_argument__')\n\n def __init__(self, arg, is_argument=True):\n if not isinstance(arg, str):\n raise TypeError(f\"Forward reference must be a string -- got {arg!r}\")\n\n # Double-stringified forward references is a result of activating\n # the 'annotations' future by default. This way, we eliminate them in\n # the runtime.\n if arg.startswith((\"'\", '\\\"')) and arg.endswith((\"'\", '\"')):\n arg = arg[1:-1]\n\n try:\n code = compile(arg, '', 'eval')\n except SyntaxError:\n raise SyntaxError(f\"Forward reference must be an expression -- got {arg!r}\")\n self.__forward_arg__ = arg\n self.__forward_code__ = code\n self.__forward_evaluated__ = False\n self.__forward_value__ = None\n self.__forward_is_argument__ = is_argument\n\n def _evaluate(self, globalns, localns, recursive_guard):\n if self.__forward_arg__ in recursive_guard:\n return self\n if not self.__forward_evaluated__ or localns is not globalns:\n if globalns is None and localns is None:\n globalns = localns = {}\n elif globalns is None:\n globalns = localns\n elif localns is None:\n localns = globalns\n type_ = _type_check(\n eval(self.__forward_code__, globalns, localns),\n \"Forward references must evaluate to types.\",\n is_argument=self.__forward_is_argument__,\n )\n self.__forward_value__ = _eval_type(\n type_, globalns, localns, recursive_guard | {self.__forward_arg__}\n )\n self.__forward_evaluated__ = True\n return self.__forward_value__\n\n def __eq__(self, other):\n if not isinstance(other, ForwardRef):\n return NotImplemented\n if self.__forward_evaluated__ and other.__forward_evaluated__:\n return (self.__forward_arg__ == other.__forward_arg__ and\n self.__forward_value__ == other.__forward_value__)\n return self.__forward_arg__ == other.__forward_arg__\n\n def __hash__(self):\n return hash(self.__forward_arg__)\n\n def __repr__(self):\n return f'ForwardRef({self.__forward_arg__!r})'\n # ✂ end ✂\n\n__all__ = [\n \"cache\",\n \"ast_unparse\",\n \"GenericAlias\",\n \"removesuffix\",\n \"ForwardRef\",\n]\n","sub_path":"pdoc/_compat.py","file_name":"_compat.py","file_ext":"py","file_size_in_byte":4882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"56733064","text":"import RPi.GPIO as GPIO \nimport time \nGPIO.cleanup() \nGPIO_IN=22\ndef init(): \n GPIO.setmode(GPIO.BOARD) \n GPIO.setup(GPIO_IN,GPIO.IN)\n GPIO.setup(8,GPIO.OUT)\ndef run(): \n while True: \n inValue=GPIO.input(GPIO_IN) \n if inValue!=0: \n print(\"警告:有人!\")\n GPIO.output(8,True)\n time.sleep(1) \n else: \n print(\"安全:沒人。\")\n GPIO.output(8,False)\n time.sleep(1)\n \ninit() \nrun() \nGPIO.cleanup() \n","sub_path":"Raspberry Pi TXT/python/rthw.py","file_name":"rthw.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"486863053","text":"\n\nfrom xai.brain.wordbase.nouns._suffix import _SUFFIX\n\n#calss header\nclass _SUFFIXES(_SUFFIX, ):\n\tdef __init__(self,): \n\t\t_SUFFIX.__init__(self)\n\t\tself.name = \"SUFFIXES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"suffix\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_suffixes.py","file_name":"_suffixes.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"615626186","text":"#!/usr/bin/env python\n\nimport platt\nimport numpy\nimport numpy.random\nfrom matplotlib import pyplot as plt\nimport itertools\nimport math\n\nnumpy.random.seed(seed=0)\n\ndef sigmoid(f):\n return 1.0/(1.0 + numpy.exp(-2.0*f + -1.0))\n\nfs = numpy.arange(-5, 5, 0.001)\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.plot(fs, sigmoid(fs))\n\nout = numpy.random.uniform(-5, 5, 100000)\nsigmoid_out = sigmoid(out)\n\ntarget = numpy.array([numpy.random.uniform() < p for p in sigmoid_out])\n\nbinwidth = 0.2\nbinmin = numpy.min(out)\nbinmax = numpy.max(out)\n\nbin_pos = numpy.zeros(((binmax - binmin)/binwidth + 1, 1), dtype=int)\nbin_neg = numpy.zeros(((binmax - binmin)/binwidth + 1, 1), dtype=int)\n\nfor o, t in itertools.izip(out, target):\n binid = math.floor((o - binmin)/binwidth)\n if t:\n bin_pos[binid] += 1\n else:\n bin_neg[binid] += 1\n\nbins = numpy.array([float(p)/(p+n) for p, n in itertools.izip(bin_pos, bin_neg)])\nbin_f = numpy.arange(binmin+0.5*binwidth, binmax+0.5*binwidth, binwidth)\nax.scatter(bin_f, bins)\n\nplt.show()\nA, B = platt.platt_calibrate(out, target)\nprint (A, B) \n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"241944607","text":"from os import environ\n\nimport onnxruntime as ort\nfrom onnxruntime import InferenceSession, SessionOptions, get_all_providers\nfrom psutil import cpu_count\nfrom transformers import AutoTokenizer\n\n# Constants from the performance optimization available in onnxruntime\n# It needs to be done before importing onnxruntime\nenviron[\"OMP_NUM_THREADS\"] = str(cpu_count(logical=True))\nenviron[\"OMP_WAIT_POLICY\"] = \"ACTIVE\"\n\n\ndef create_model_for_provider(model_path: str, provider: str) -> InferenceSession:\n\n assert (\n provider in get_all_providers()\n ), f\"provider {provider} not found, {get_all_providers()}\"\n\n # Few properties than might have an impact on performances (provided by MS)\n options = SessionOptions()\n options.intra_op_num_threads = 1\n\n # Load the model as a graph and prepare the CPU backend\n return InferenceSession(model_path, options, providers=[provider])\n\n\nclass BertServer:\n def __init__(self) -> None:\n super().__init__()\n self.session = ort.InferenceSession(\"bert-base-cased.onnx\")\n\n self.tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n\n def predict(self, text):\n onnx_in = self.tokenizer.encode_plus(text, return_tensors=\"np\")\n inputs_onnx = {k: v for k, v in onnx_in.items()}\n _, pooled = self.session.run(None, inputs_onnx)\n return pooled\n # print(sequence.shape, pooled.shape)\n","sub_path":"sapp/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"630293068","text":"\"\"\"Common helper utilities for use with mixcoatl\"\"\"\n\ndef uncamel(val):\n \"\"\"Return the snake case version of :attr:`str`\n\n >>> uncamel('deviceId')\n 'device_id'\n >>> uncamel('dataCenterName')\n 'data_center_name'\n \"\"\"\n import re\n s = lambda val: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\\\1', val).lower().strip('_')\n return s(val)\n\ndef uncamel_keys(d1):\n \"\"\"Return :attr:`d1` with all keys converted to snake case\n\n >>> d = {'myThings':[{'thingId':1,'someThings':{'firstThing':'a_thing'}}]}\n >>> uncamel_keys(d)\n {'my_things': [{'thing_id': 1, 'some_things': {'first_thing': 'a_thing'}}]}\n \"\"\"\n d2 = dict()\n if not isinstance(d1, dict):\n return d1\n for k, v in d1.iteritems():\n new_key = uncamel(k)\n if isinstance(v, dict):\n d2[new_key] = uncamel_keys(v)\n elif isinstance(v, list):\n d2[new_key] = [uncamel_keys(item) for item in v]\n else:\n d2[new_key] = v\n return d2\n\ndef camelize(val):\n \"\"\"Return the camel case version of a :attr:`str`\n\n >>> camelize('this_is_a_thing')\n 'thisIsAThing'\n \"\"\"\n s = ''.join([t.title() for t in val.split('_')])\n return s[0].lower()+s[1:]\n\ndef camel_keys(d1):\n \"\"\"Return :attr:`d1` with all keys converted to camel case\n\n >>> b = {'my_things': [{'thing_id': 1, 'some_things': {'first_thing': 'a_thing'}}]}\n >>> camel_keys(b)\n {'myThings': [{'thingId': 1, 'someThings': {'firstThing': 'a_thing'}}]}\n \"\"\"\n d2 = dict()\n if not isinstance(d1, dict):\n return d1\n for k, v in d1.iteritems():\n new_key = camelize(k)\n if isinstance(v, dict):\n d2[new_key] = camel_keys(v)\n elif isinstance(v, list):\n d2[new_key] = [camel_keys(item) for item in v]\n else:\n d2[new_key] = v\n return d2\n\ndef convert(val):\n \"\"\"Return :attr:`input` converted from :class:`unicode` to :class:`str`\n\n >>> convert(u'bob')\n 'bob'\n >>> convert([u'foo', u'bar'])\n ['foo', 'bar']\n >>> convert({u'foo':u'bar'})\n {'foo': 'bar'}\n \"\"\"\n if isinstance(val, dict):\n return dict((convert(key), convert(value)) for key, value in val.iteritems())\n elif isinstance(val, list):\n return [convert(element) for element in val]\n elif isinstance(val, unicode):\n return val.encode('utf-8')\n else:\n return val\n","sub_path":"mixcoatl/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"447525996","text":"import logging\n\nfrom django.views.generic import ListView, UpdateView\nfrom django.contrib.auth import login\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib import messages\n\nfrom mama_cas.views import LoginView\nfrom mama_cas.utils import redirect\nfrom mama_cas.utils import to_bool\nfrom mama_cas.models import ServiceTicket\n\nfrom mc2.controllers.base.views import ControllerViewMixin\nfrom mc2.models import UserSettings\nfrom mc2.forms import UserSettingsForm\nfrom mc2.organizations.utils import active_organization\n\nlogger = logging.getLogger(__name__)\n\n\nclass HomepageView(ControllerViewMixin, ListView):\n template_name = 'mc2/home.html'\n\n def get_context_data(self, *args, **kwargs):\n context = super(HomepageView, self).get_context_data(*args, **kwargs)\n active_org = active_organization(self.request)\n if active_org:\n context.update(\n {'is_admin': active_org.has_admin(self.request.user)})\n return context\n\n def get_queryset(self):\n return self.get_controllers_queryset(self.request).order_by('name')\n\n\nclass UserSettingsView(UpdateView):\n model = UserSettings\n form_class = UserSettingsForm\n\n def get_object(self, *args, **kwargs):\n return UserSettings.objects.get(user=self.request.user)\n\n def form_valid(self, form):\n form.instance.user = self.request.user\n return super(UserSettingsView, self).form_valid(form)\n\n def get_success_url(self):\n return self.request.GET.get('next', '/')\n\n\nclass MC2LoginView(LoginView):\n\n def get(self, request, *args, **kwargs):\n self.request.session['service'] = self.request.GET.get('service')\n\n service = request.GET.get('service')\n renew = to_bool(request.GET.get('renew'))\n gateway = to_bool(request.GET.get('gateway'))\n\n if renew:\n logger.debug(\"Renew request received by credential requestor\")\n elif gateway and service:\n logger.debug(\"Gateway request received by credential requestor\")\n if request.user.is_authenticated():\n\n st = ServiceTicket.objects.create_ticket(service=service,\n user=request.user)\n if self.warn_user():\n\n return redirect('cas_warn', params={'service': service,\n 'ticket': st.ticket})\n return redirect(service, params={'ticket': st.ticket})\n\n else:\n return redirect(service)\n elif request.user.is_authenticated():\n if service:\n logger.debug(\"Service ticket request received by \"\n \"credential requestor\")\n st = ServiceTicket.objects.create_ticket(service=service,\n user=request.user)\n if self.warn_user():\n return redirect('cas_warn', params={'service': service,\n 'ticket': st.ticket})\n return redirect(service, params={'ticket': st.ticket})\n else:\n msg = _(\"You are logged in as %s\") % request.user\n messages.success(request, msg)\n return redirect('home')\n return super(LoginView, self).get(request, *args, **kwargs)\n\n def get_context_data(self, *args, **kwargs):\n context = super(LoginView, self).get_context_data(*args, **kwargs)\n context.update({'service': self.request.session['service']})\n return context\n\n def form_valid(self, form):\n login(self.request, form.user)\n logger.info(\"Single sign-on session started for %s\" % form.user)\n\n if form.cleaned_data.get('warn'):\n self.request.session['warn'] = True\n\n service = self.request.GET.get('service')\n if service:\n st = ServiceTicket.objects.create_ticket(service=service,\n user=self.request.user,\n primary=True)\n return redirect(service, params={'ticket': st.ticket})\n return redirect('home')\n","sub_path":"mc2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"539338227","text":"\n#Reads text from keyboard and stores into a text file. \n\ndef KeyboardToFileCopy():\n # Iterate over the lines of the File\n file = open(\"Test.txt\",\"w\") #Open a file\n text=input('Enter your meeage = ')\n\n while(text!=\"quit\"):\n file.write(text)\n file.write(\" \")\n text=input('')\n file.close() # Close a file\n\nKeyboardToFileCopy()\n","sub_path":"11-IO/KeyboardToFileCopy.py","file_name":"KeyboardToFileCopy.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"240889227","text":"from flask import Flask, render_template, json, request, Response\nfrom flaskext.mysql import MySQL\n\nimport urllib\nimport urllib2\nimport requests\nimport os\n\nnodes = [\"node1\",\"node2\",\"node3\"]\nthis_node = os.environ['C_NAME'] # container name is docker address\n\nnodes.remove(this_node)\n\napp = Flask(__name__)\nmysql = MySQL()\napp.config['MYSQL_DATABASE_USER'] = 'root'\napp.config['MYSQL_DATABASE_PASSWORD'] = ''\napp.config['MYSQL_DATABASE_DB'] = 'phasetwo'\napp.config['MYSQL_DATABASE_HOST'] = 'localhost'\nmysql.init_app(app)\n\n\n@app.route('/')\ndef main():\n return render_template('index.html')\n\n@app.route('/advertiseform')\ndef pre_create_channel():\n return render_template('advert.html')\n\n\n@app.route('/advertise',methods=['POST'])\ndef create_channel():\n try:\n uuid = request.form['id']\n _name = request.form['name']\n\n # validate the received values\n if _name and uuid:\n \n # All Good, call MySQL\n conn = mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT * FROM `client` WHERE `uuid` LIKE '{}'\".format(uuid))\n data = cursor.fetchone()\n\n if data is None:\n cursor.execute(\"INSERT INTO `client` (`id`, `uuid`) VALUES (NULL, '{}')\".format(uuid))\n conn.commit()\n cursor.execute(\"SELECT * FROM `client` WHERE `uuid` LIKE '{}'\".format(uuid))\n data = cursor.fetchone()\n\n cursor.execute(\"INSERT INTO `chanel` (`id`, `client_id`, `name`) VALUES (NULL, '{}', '{}')\".format(data[0], _name))\n conn.commit()\n\n # broadcast to other nodes\n global nodes\n data = urllib.urlencode(request.form)\n for node in nodes:\n url = node + \"/advertise\"\n req = urllib2.Request(url, data)\n response = urllib2.urlopen(req)\n\n return json.dumps({'message':'Channel created successfully !'})\n else:\n return json.dumps({'message':'All fields are required'})\n\n except Exception as e:\n return json.dumps({'error':str(e)})\n finally:\n cursor.close() \n conn.close()\n\n@app.route('/adverts_form', methods=['GET'])\ndef adverts_form():\n return render_template('adverts_form.html')\n\n@app.route('/adverts', methods=['GET'])\ndef adverts_get():\n try:\n conn = mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT chanel.id, chanel.name, client.uuid FROM chanel INNER JOIN client ON chanel.client_id = client.id\")\n data = cursor.fetchall()\n # return json.dumps(data)\n return Response(json.dumps(data), mimetype='application/json')\n\n except Exception as e:\n return json.dumps({'error':str(e)})\n finally:\n cursor.close() \n conn.close()\n\n@app.route('/create_event', methods=['POST', 'GET'])\ndef create_event():\n if request.method == 'GET':\n return render_template('creat_event_form.html')\n if request.method == 'POST':\n # broadcast to other nodes\n global nodes\n data = urllib.urlencode(request.values)\n for node in nodes:\n url = node + \"/create_event\"\n req = urllib2.Request(url, data)\n response = urllib2.urlopen(req)\n\n chanel_id = request.values['chanel_id']\n description = request.values['event_description']\n\n conn = mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute(\"INSERT INTO `event` (`id`, `chanel_id`, `description`) VALUES (NULL, '{}', '{}')\".format(chanel_id, description))\n conn.commit()\n\n event_id = cursor.lastrowid\n\n # create notification for all subscribers of that channel\n cursor.execute(\"SELECT client_id FROM subscription WHERE chanel_id LIKE '{}'\".format(chanel_id))\n data = cursor.fetchall()\n\n if data is not None:\n for subscription in data:\n cursor.execute(\"INSERT INTO notification (id, event_id, client_id) VALUES (NULL, '{}', '{}')\".format(event_id, subscription[0]))\n conn.commit()\n \n return Response(json.dumps(data), mimetype='application/json')\n\n@app.route('/my_chanels')\ndef my_chanels():\n uuid = request.args['uuid']\n\n conn = mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT chanel.id, chanel.name, client.uuid FROM client INNER JOIN chanel ON chanel.client_id = client.id WHERE client.uuid LIKE '{}'\".format(uuid)) \n\n data = cursor.fetchall()\n\n return Response(json.dumps(data), mimetype='application/json')\n\n@app.route('/subscribe', methods=['POST'])\ndef subscribe():\n try:\n chanel_id = request.json['chanel_id']\n uuid = request.json['uuid']\n\n # broadcast to other nodes\n global nodes\n for node in nodes:\n url = node + \"/subscribe\"\n r = requests.post(url, json=request.json)\n\n conn = mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT id FROM client WHERE uuid LIKE '{}'\".format(uuid))\n data = cursor.fetchone()\n\n if data is None:\n cursor.execute(\"INSERT INTO `client` (`id`, `uuid`) VALUES (NULL, '{}')\".format(uuid))\n conn.commit()\n cursor.execute(\"SELECT * FROM `client` WHERE `uuid` LIKE '{}'\".format(uuid))\n data = cursor.fetchone()\n\n cursor.execute(\"INSERT INTO `subscription` (`id`, `client_id`, `chanel_id`) VALUES (NULL, '{}', '{}')\".format(data[0], chanel_id))\n conn.commit()\n\n return json.dumps({'message':'Subscribed successfully !'})\n\n\n except Exception as e:\n return json.dumps({'error':str(e)})\n\n@app.route('/notifications')\ndef render_notification_form():\n return render_template('notifications.html')\n\n@app.route('/notify', methods=['GET'])\ndef notify():\n\n uuid = request.args['uuid']\n\n conn = mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT * FROM client WHERE uuid LIKE '{}'\".format(uuid))\n data = cursor.fetchone()\n\n\n if data is not None:\n notifications = []\n cursor.execute(\"SELECT event_id FROM notification WHERE client_id LIKE '{}'\".format(data[0]))\n data = cursor.fetchall()\n\n if data is not None:\n for n in data:\n cursor.execute(\"SELECT event.description,chanel.name FROM event INNER JOIN chanel ON chanel.id=event.chanel_id WHERE event.id='{}'\".format(n[0]))\n d = cursor.fetchone()\n\n notifications.append(d)\n return Response(json.dumps(notifications), mimetype='application/json')\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"phase3/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"641705624","text":"import sys\nimport tornado\nfrom tornado.web import Application\nimport urls\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handler = urls.urlpattern\n super(Application, self).__init__(handler)\n\ndef main(port):\n app = Application()\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(port)\n tornado.ioloop.IOLoop.instance().start()\n\n\n\nif __name__ == \"__main__\":\n try:\n port = sys.argv[1]\n except IndexError:\n port = 8888\n main(port)","sub_path":"server/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"184797590","text":"import json\nimport functools\n\ndef to_json(func):\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n result = json.dumps(func(*args, **kwargs))\n return result\n return wrapped\n\n@to_json\ndef get_data():\n return {'data': 42}\n\n@to_json\ndef get_list():\n return [1, 2, 4] \n\nif __name__ == '__main__':\n print(get_data()) # вернёт '{\"data\": 42}'\n print(get_data == str({'data': 42}))\n print(get_list())\n\n with open('test.txt', 'w') as f:\n f.write(get_data())\n\n with open('test.txt', 'r') as f:\n d = json.load(f)\n print(d)","sub_path":"1. Diving in Python/Week 2/to_json.py","file_name":"to_json.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"329690169","text":"# TODO DOCUMENTATION AND AUTOMODE\n\n# Left click to next frame, right click to plot a graph\n\nimport tkinter as tk\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nINITIAL_FOREST_DENSITY, INITIAL_FIRE_DENSITY = (0.55, 0.0004)\nSPREAD_DIRECT_PROB, SPREAD_DIAGONAL_PROB = (0.92, 0.82)\nNEW_FIRE_PROB, NEW_TREE_PROB = (0, 0)\nTREE, FIRE, EMPTY = ('green', 'red', 'white')\n\n\nclass ForestFireWindow:\n def __init__(self, master, canvas_dimensions=(960, 960),\n box_count=(120, 120)):\n self.canvas_width, self.canvas_height = canvas_dimensions\n self.box_count = box_count\n self.box_dimensions = (canvas_dimensions[0] // box_count[0],\n canvas_dimensions[1] // box_count[1])\n self.current_frame = 1\n self.data = {\n 'Frame': [0],\n 'Trees': [0],\n 'Burning': [0],\n 'Burned': [0],\n 'Empty': [0]\n }\n\n self.master = master\n self.frame = tk.Frame(self.master)\n self.canvas = tk.Canvas(self.master, width=self.canvas_width,\n height=self.canvas_height)\n self.canvas.bind('', self.next_frame)\n self.canvas.bind('', self.plot_data)\n self.canvas.pack()\n self.frame.pack()\n\n self.grid = self.init_grid()\n self.data_update()\n\n def init_box(self, coords, color):\n \"\"\" Create rectangle on canvas. \"\"\"\n x, y = coords\n width, height = self.box_dimensions\n x2 = x + width\n y2 = y + height\n\n box = self.canvas.create_rectangle(x, y, x2, y2, fill=color)\n return box\n\n def init_grid(self):\n \"\"\" Turn canvas into grid of boxes. \"\"\"\n horizontal_count, vertical_count = self.box_count\n width, height = self.box_dimensions\n\n grid = [[None for _ in range(vertical_count)]\n for _ in range(horizontal_count)]\n\n for x in range(horizontal_count):\n for y in range(vertical_count):\n coords = (x * width, y * height)\n if np.random.rand() <= INITIAL_FOREST_DENSITY:\n if np.random.rand() <= INITIAL_FIRE_DENSITY:\n grid[x][y] = self.init_box(coords, FIRE)\n else:\n grid[x][y] = self.init_box(coords, TREE)\n else:\n grid[x][y] = self.init_box(coords, EMPTY)\n return grid\n\n def get_status(self):\n \"\"\" Return state of the grid. \"\"\"\n horizontal_count, vertical_count = self.box_count\n trees = burning = empty = 0\n\n for x in range(horizontal_count):\n for y in range(vertical_count):\n status = self.canvas.itemcget(self.grid[x][y], 'fill')\n\n if status == TREE:\n trees += 1\n elif status == FIRE:\n burning += 1\n else:\n empty += 1\n return trees, burning, empty\n\n def data_update(self):\n \"\"\"Update dataframe and print current state.\"\"\"\n t, b, e = self.get_status()\n self.data['Frame'].append(self.current_frame)\n self.data['Trees'].append(t)\n self.data['Burning'].append(b)\n self.data['Burned'].append(self.data['Burned'][-1] + b)\n self.data['Empty'].append(e)\n\n print('{} trees, {} burning and {} empty '\n 'in frame {}'.format(t, b, e, self.current_frame))\n\n def next_frame(self, _):\n \"\"\"Generate next frame of the simulation.\"\"\"\n self.current_frame += 1\n\n horizontal_count, vertical_count = self.box_count\n new_grid = [[None for _ in range(vertical_count)]\n for _ in range(horizontal_count)]\n\n for x in range(horizontal_count):\n for y in range(vertical_count):\n current_box = self.grid[x][y]\n def status(box): return self.canvas.itemcget(box, 'fill')\n\n # This is kinda dumb. There has to be a better way of doing this.\n if status(current_box) == TREE:\n if (x > 0 and y > 0\n and status(self.grid[x - 1][y - 1]) == FIRE\n and np.random.rand() <= SPREAD_DIAGONAL_PROB):\n new_grid[x][y] = FIRE\n elif (y > 0 and status(self.grid[x][y - 1]) == FIRE\n and np.random.rand() <= SPREAD_DIRECT_PROB):\n new_grid[x][y] = FIRE\n elif (y > 0 and x < horizontal_count - 1\n and status(self.grid[x + 1][y - 1]) == FIRE\n and np.random.rand() <= SPREAD_DIAGONAL_PROB):\n new_grid[x][y] = FIRE\n elif (x > 0 and status(self.grid[x - 1][y]) == FIRE\n and np.random.rand() <= SPREAD_DIRECT_PROB):\n new_grid[x][y] = FIRE\n elif (x < horizontal_count - 1\n and status(self.grid[x + 1][y]) == FIRE\n and np.random.rand() <= SPREAD_DIRECT_PROB):\n new_grid[x][y] = FIRE\n elif (x > 0 and y < vertical_count - 1\n and status(self.grid[x - 1][y + 1]) == FIRE\n and np.random.rand() <= SPREAD_DIAGONAL_PROB):\n new_grid[x][y] = FIRE\n elif (y < vertical_count - 1\n and status(self.grid[x][y + 1]) == FIRE\n and np.random.rand() <= SPREAD_DIRECT_PROB):\n new_grid[x][y] = FIRE\n elif (x < horizontal_count - 1 and y < vertical_count - 1\n and status(self.grid[x + 1][y + 1]) == FIRE\n and np.random.rand() <= SPREAD_DIAGONAL_PROB):\n new_grid[x][y] = FIRE\n elif np.random.rand() <= NEW_FIRE_PROB:\n new_grid[x][y] = FIRE\n elif status(current_box) == FIRE:\n new_grid[x][y] = EMPTY\n elif np.random.rand() <= NEW_TREE_PROB:\n new_grid[x][y] = TREE\n\n for x in range(horizontal_count):\n for y in range(vertical_count):\n self.canvas.itemconfig(self.grid[x][y], fill=new_grid[x][y])\n\n self.data_update()\n\n def plot_data(self, _):\n \"\"\"Make a plot of current data on right-click.\"\"\"\n df = pd.DataFrame(self.data)\n\n ax = df.plot(kind='line', x='Frame', y='Trees', color='green')\n df.plot(kind='line', x='Frame', y='Burning', color='red', ax=ax)\n df.plot(kind='line', x='Frame', y='Burned', color='black', ax=ax)\n plt.show()\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n forest = ForestFireWindow(root)\n root.mainloop()\n","sub_path":"fire_simulation_mc.py","file_name":"fire_simulation_mc.py","file_ext":"py","file_size_in_byte":6935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"43733091","text":"from marketsim.types import *\r\nfrom marketsim import (parts, orderbook, observable, order, mathutils, types, meta, \r\n event,registry, signal, bind, ops, _)\r\nfrom .. import _wrap\r\nfrom .._generic import Generic\r\n\r\nclass TrendFollower(types.ISingleAssetStrategy):\r\n \r\n def getImpl(self):\r\n return Generic( \r\n self.orderFactory(\r\n parts.side.TrendFollower(\r\n self.ewma_alpha, \r\n self.threshold)),\r\n self.eventGen)\r\n\r\n_wrap.strategy(TrendFollower, ['Periodic', 'TrendFollower'], \r\n \"\"\" Trend follower can be considered as a sort of a signal strategy \r\n where the *signal* is a trend of the asset. \r\n Under trend we understand the first derivative of some moving average of asset prices. \r\n If the derivative is positive, the trader buys; if negative - it sells.\r\n Since moving average is a continuously changing signal, we check its\r\n derivative at random moments of time given by *creationIntervalDistr*. \r\n \r\n It has following parameters:\r\n \r\n |ewma_alpha| \r\n parameter |alpha| for exponentially weighted moving average\r\n (default: 0.15.)\r\n \r\n |threshold| \r\n threshold when the trader starts to act (default: 0.)\r\n \r\n |creationIntervalDistr|\r\n defines intervals of time between order creation\r\n (default: exponential distribution with |lambda| = 1)\r\n \r\n |volumeDistr| \r\n defines volumes of orders to create \r\n (default: exponential distribution with |lambda| = 1)\r\n \"\"\",\r\n [\r\n ('eventGen', 'event.Every(mathutils.rnd.expovariate(1.))', 'IEvent'),\r\n (\"orderFactory\", \"order.factory.side.Market()\", 'IFunction[Side] -> IOrderGenerator'), \r\n ('ewma_alpha', '0.15', 'non_negative'),\r\n ('threshold', '0.', 'non_negative'),\r\n ], globals())\r\n","sub_path":"marketsim/strategy/side/_trend.py","file_name":"_trend.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"537919981","text":"import abjad\nimport baca\nimport quicktions\n\n\ndef visualize(eighths, staves):\n pairs = [(_, 8) if _ == int(_) else (int(_ * 2), 16) for _ in eighths]\n durations = [quicktions.Fraction(*p) for p in pairs]\n directives = [r\"\\time %s/%s\" % (p[0], p[1]) for p in pairs]\n measuresPerLine = baca.sequence(eighths).group_by_weights(\n [10], fill=\"less\", cyclic=True, overhang=False\n )\n measuresPerLine = [len(x) for x in measuresPerLine]\n measuresWithBreaks = [m - 1 for m in abjad.math.cumulative_sums(measuresPerLine)]\n measuresWithSpacing = [0] + [m + 1 for m in measuresWithBreaks][:-1]\n pageHeight = 240\n systemsPerPage = 2\n systemHeight = pageHeight / systemsPerPage\n # staffSep = 10\n curSystem = 1\n breaks = []\n for i, duration in enumerate(durations):\n new = abjad.Skip(duration)\n if i in measuresWithSpacing:\n new.before.append(r'\\overrideProperty #\"Score.NonMusicalPaperColumn\" ')\n new.before.append(\"#'line-break-system-details\")\n systemOffset = systemHeight * (curSystem % systemsPerPage)\n # staffOffsets = ' '.join([\n # str(-staffSep * _) for _ in range(len(staves))])\n staffOffsets = \"0 -15 -39 -57 -81 -96\"\n text = \"#'((Y-offset . %s)\" % systemOffset\n new.before.append(text)\n text = \"(alignment-offsets . (%s)))\" % staffOffsets\n new.before.append(text)\n if i in measuresWithBreaks:\n if curSystem % systemsPerPage == systemsPerPage - 1:\n new.right.append(r\"\\pageBreak\")\n else:\n new.right.append(r\"\\break\")\n curSystem += 1\n breaks.append(new)\n breaks[-1].right.append(r'\\bar \"|.\" ')\n breaksVoice = abjad.Voice(breaks, name=\"breaks voice\")\n\n mm = [abjad.Container([abjad.Skip(*p)]) for p in pairs]\n for i, m in enumerate(mm):\n m.music[0].left.append(directives[i])\n measures_voice = abjad.Voice(mm, name=\"measures voice\")\n mm = abjad.select(measures_voice).components(abjad.Skip)\n\n r\"\"\"\n barText = r\"\\once \\override Score.BarLine #'color = #red\"\n spanBarText = r\"\\once \\override Score.SpanBar #'color = #red\"\n\n for (i, start, stop, description) in sections:\n sectionText = r'^ \\markup \\fontsize #2 \\with-color #red \\italic '\n sectionText += '{ %s. %s }' % (i, description)\n try:\n mm[start - 1].before.extend([barText, spanBarText])\n instances(mm[start - 1], '_Leaf')[0].right.append(sectionText)\n except:\n pass\n \"\"\"\n\n flute = abjad.GrandStaff([staves[0], staves[1]], name=\"flute group\")\n violin = abjad.GrandStaff([staves[2], staves[3]], name=\"violin group\")\n piano = abjad.PianoStaff([staves[4], staves[5]], name=\"piano group\")\n\n flute.during.extend(\n [\n r'instrumentName = \\markup { \\fontsize #3 \\hcenter-in #18 \"Flauta\" }',\n r'shortInstrumentName = \\markup { \\fontsize #3 \\hcenter-in #8 \"Fl.\" }',\n ]\n )\n violin.during.extend(\n [\n r'instrumentName = \\markup { \\fontsize #3 \\hcenter-in #18 \"Violino\" }',\n r'shortInstrumentName = \\markup { \\fontsize #3 \\hcenter-in #8 \"Vn.\" }',\n ]\n )\n piano.during.extend(\n [\n r'instrumentName = \\markup { \\fontsize #3 \\hcenter-in #18 \"Pianoforte\" }',\n r'shortInstrumentName = \\markup { \\fontsize #3 \\hcenter-in #8 \"Pf.\" }',\n ]\n )\n\n sc = abjad.Score([flute, violin, piano], name=\"score\")\n sc.instances(\"Staff\")[0].music.insert(0, measures_voice)\n sc.instances(\"Staff\")[0].music.insert(0, breaksVoice)\n\n ly = abjad.LilyPondFile([sc], name=\"file\")\n ly.includes.append(\"/Users/trevorbaca/work/lidercfeny/layout-rhythm.ly\")\n\n return ly\n","sub_path":"lidercfeny/etc/layout/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"338905837","text":"# -*- coding: utf-8 -*-\n\n#No need feature scaling since co-efficients compensate for that\n# y = b0 + b1x1 + b2x2 + b3x3 + ...\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset.\ndataset = pd.read_csv('Train Data with UPDRS.csv')\nX = dataset.iloc[:, 1: 27].values #matrix of independent features\ny = dataset.iloc[:, 27].values #dependent variable\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\n\n# Fitting Multiple Linear Regression to the Training set\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train) #trains the machine \n\n# Predicting the Test set results\ny_pred = regressor.predict(X_test) #returns a vector of predictions for X_test \n\n# Predicting the Training set results\ny_pred_train = regressor.predict(X_train)\nnp.set_printoptions(precision=0)\nprint(np.concatenate((y_pred.reshape(len(y_pred), 1),y_test.reshape(len(y_test), 1)),1 ))\n\n\n#module evaluation\nfrom sklearn.metrics import mean_squared_error\nrmse = np.sqrt(mean_squared_error(y_test, y_pred))\nrmse_train = np.sqrt(mean_squared_error(y_train, y_pred_train ))\n\nprint(\"RMSE(Root mean square error) for testing set = \", rmse )\nprint(\"RMSE(Root mean square error) for training set = \", rmse_train )\n","sub_path":"Machine Learning/ml_rajeev/Turkish Dataset Models/updrs_score_prediction/multiple_linear_regression.py","file_name":"multiple_linear_regression.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"201542988","text":"#!/usr/bin/env python3\n\nimport sys\nfrom matplotlib import pylab as plt\nfrom mpl_toolkits.mplot3d import axes3d\nimport numpy as np\nimport gausslobatto\nimport flash, flexi, hopr\nimport flash_to_flexi as flfl\nimport scipy.misc\nimport ulz\n\ncase = 4\n\nif case == 0:\n casename = 'plane'\n fillby = 'planeX'\n stride = 1\n zlim = (0,1)\n\nelif case == 1:\n casename = 'plane+wiggle'\n fillby = 'plane+wiggle'\n stride = 2\n zlim = (0,3)\n\nelif case == 2:\n casename = 'gaussian'\n fillby = 'gaussianXYZ'\n stride = 1\n zlim = (0,1)\n\nelif case == 3:\n casename = 'steps'\n fillby = casename+'XYZ'\n stride = 2\n zlim = (0,5)\n\nelif case == 4:\n casename = 'turb-unit-128'\n fillby = 'file'\n stride = 2\n zlim = (0,40)\n\n\nrms = lambda Fs: np.sqrt(np.sum(Fs**2)/len(Fs.ravel()))\nrmse = lambda Fs,fs: np.sqrt(np.sum((Fs-fs)**2)/len(Fs.ravel()))\nestr = lambda rms,rmse: \"rms = %f | rms error = %f | relative rms error = %f%%\" % (rms,rmse,rmse/rms * 100)\n\nsys.argv.reverse()\nsys.argv.pop()\noutpath = sys.argv.pop()\n\nflexfilepath = \"/home/jmark/data/projects/stirturb/flexi-sims/whirlpool/%s/sim_State_0000000.000000000.h5\" % casename\nhoprfilepath = \"/home/jmark/data/projects/stirturb/flexi-sims/whirlpool/%s/sim_mesh.h5\" % casename\nflshfilepath = \"/home/jmark/data/projects/stirturb/flexi-sims/whirlpool/%s/flash_hdf5_chk_0050.h5\" % casename\n\nflx = flexi.File(flexfilepath, hopr.CartesianMeshFile(hoprfilepath))\n\nif 'file' in fillby:\n fls = flash.File(flshfilepath)\nelse:\n fls = flfl.FakeFlashFile(flx.mesh.domain,flx.mesh.gridsize.astype(int)*(flx.npoly+1),fillby=fillby)\n\n\nflsdata = fls.data('dens')\n\n## INTERPOLATION ##\n\nnpoly = flx.npoly\nntype = flx.nodetype\nnvisu = 4\n\nRGcube = ulz.mk_cartesian_product_3d(*[ulz.mk_body_centered_linspace(-1,1,nvisu)]*3)\nRGgrid = np.array([ll + (tr-ll)*(RGcube+1)/2 for ll,tr in zip(*flx.mesh.get_cell_coords())]).reshape(-1, *[nvisu]*3, 3)\nipl = gausslobatto.mk_lagrange_interpolator_3d(*[gausslobatto.mk_nodes(npoly, ntype)]*3, RGcube)\n\nflxdata = np.array([ipl(f).reshape((nvisu,)*3) for f in flx.data[:,:,:,:,0].transpose(0,3,2,1)])\nflxgrid, flxdata = ulz.sort_unstructured_grid(RGgrid, flxdata)\n\nprint(estr(rms(flsdata),rmse(flsdata,flxdata)))\n\n## PLOTTING ##\n\nfig = plt.figure(figsize=(12, 5))\n\nlin1d = ulz.mk_body_centered_linspace(0,1, len(flsdata))\ngrid2d = np.meshgrid(lin1d,lin1d)\n\nax = fig.add_subplot(1,2,1, projection='3d')\nax.set_title('FLASH data: x,y,(z1-z0)/2 slice', y=1.04)\nif zlim: ax.set_zlim(*zlim)\nax.plot_wireframe(*grid2d, flsdata[:,:,flsdata.shape[2]//2], rstride=stride, cstride=stride)\n\nlin1d = flxgrid.T[0,0,0] \ngrid2d = np.meshgrid(lin1d,lin1d)\n\nax = fig.add_subplot(1,2,2, projection='3d')\nax.set_title('FLEXI data: x,y,(z1-z0)/2 slice', y=1.04)\nif zlim: ax.set_zlim(*zlim)\nax.plot_wireframe(*grid2d, flxdata[:,:,flxdata.shape[2]//2], rstride=stride, cstride=stride)\n\nplt.savefig(outpath,bbox_inches='tight')\n","sub_path":"sandbox/plot/lagrange-interpolation-3d-slice.py","file_name":"lagrange-interpolation-3d-slice.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"463411015","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.welcome, name = \"welcome\"),\n path('login', views.login, name = \"login\"),\n path('register', views.register, name = \"register\"),\n path('userprofile', views.userprofile, name = \"userprofile\"),\n path('user_logout', views.user_logout, name = \"user_logout\"),\n \n]","sub_path":"index/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"290397285","text":"\"\"\"\n检验相关。\n\"\"\"\nimport re\n\nONLY_DIGITS = \"^[0-9]*$\"\nONLY_HEXDIGITS = \"^[0-9abcdefABCDEF]*$\"\nNUMERIC = \"^[+-]?[0-9]+[.]?[0-9]*$\"\nONLY_LETTERS = \"^[a-zA-Z]*$\"\nONLY_LOWERCASE_LETTERS = \"^[a-z]*$\"\nONLY_UPPERCASE_LETTERS = \"^[A-Z]*$\"\nMOBILE = \"^1\\d{10}$\"\nDOTKEY = \"^[a-zA-Z]+[a-zA-Z0-9\\.]*$\"\n\n\ndef validate(pattern, text):\n if re.match(pattern, text):\n return True\n return False\n","sub_path":"src/zencore/utils/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"23943497","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport initExample\n\nfrom lase.core import KClient\nfrom lase.drivers import Oscillo\n\nimport matplotlib.pyplot as plt\nimport time\n\n# Connect to Lase\nhost = '192.168.1.12'\nclient = KClient(host)\ndriver = Oscillo(client)\n\n# Enable laser\ndriver.start_laser()\n\nlaser_current = [0,5,10,15,20,25,30,35,40] #mA\nlaser_power = []\n\nfor current in laser_current:\n driver.set_laser_current(current)\n time.sleep(0.1)\n laser_power.append(driver.get_laser_power())\n\n\nplt.plot(laser_current, laser_power)\nplt.xlabel('Laser current (mA)')\nplt.ylabel('Laser power (u.a.)')\nplt.show()\n\ndriver.stop_laser()\ndriver.close()\n","sub_path":"examples/power_vs_current.py","file_name":"power_vs_current.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"116648297","text":"__author__ = 'yongkang'\n#coding=utf-8\n\nimport unittest\nimport os\nimport HTMLTestRunner\nimport time\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport smtplib\n\n#遍历测试用例\ndef creatsuite():\n testunit = unittest.TestSuite()\n test_dir = 'F:\\\\git_test\\\\Appium\\\\APP1.3\\\\TestCase'\n discover = unittest.defaultTestLoader.discover(test_dir,pattern='test*.py',top_level_dir=None)\n for testcase in discover:\n testunit.addTests(testcase)\n return testunit\n\n#生成测试报告\nnow = time.strftime('%Y-%m-%d_%H-%M-%S')\nfilename = 'F:\\\\appium\\\\report\\\\report_' + now + '.html'\nfp = open(filename,'wb')\nrunner = HTMLTestRunner.HTMLTestRunner(stream=fp,title=u'测试报告' + now,description=u'测试结果')\n\n#发送邮件\ndef sendmail(file_new):\n #读取报告内容\n f = open(file_new,'rb')\n mail_body = f.read()\n f.close()\n\n mail_host = 'smtp.126.com'\n mail_user = 'yongkang1987@126.com'\n mail_pass = 'yongkang496'\n\n #发送附件\n nowtime = time.strftime('%Y-%m-%d')\n msg = MIMEMultipart()\n part = MIMEText(open(file_new,'rb').read(),'base64','utf-8')\n part.add_header('Content-Disposition','attachment',filename=\"测试报告\" + nowtime + \".html\")\n msg.attach(part)\n\n #设置收发件人信息和邮件主题\n msg.attach(MIMEText(mail_body,'html','utf-8'))\n msg['From'] = 'yongkang1987@126.com'\n msg['To'] = '443929830@qq.com'\n msg['Subject'] = \"APP1.3测试报告\" + nowtime\n smtp = smtplib.SMTP()\n smtp.connect(mail_host)\n smtp.login(mail_user,mail_pass)\n smtp.sendmail(msg['From'],msg['To'],msg.as_string())\n smtp.quit()\n\ndef sendreport():\n #获取最新的报告\n report_dir = 'F:\\\\appium\\\\report'\n lists = os.listdir(report_dir)\n lists.sort()\n file_new = os.path.join(report_dir,lists[-1])\n sendmail(file_new)\n\nif __name__ == '__main__':\n runner.run(creatsuite())\n fp.close()\n time.sleep(3)\n sendreport()","sub_path":"APP1.3/TestSuite/TestSuite.py","file_name":"TestSuite.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"344543043","text":"import torch.nn as nn\n\nimport unsup_it.module.losses as losses\nfrom .closure import *\n\n\nclass UnsupervisedImageReconstruction(Closure):\n def __init__(self, mods: dict, optims: dict, device: str, backloss_measurements: float = 0., measurement=None,\n dict_scheduler=None):\n\n assert (measurement is not None)\n self.measurement = measurement\n self.netG = mods['gen']\n self.netD = mods['dis']\n self.netG_optim = optims['gen']\n self.netD_optim = optims['dis']\n self.backloss_measurements = backloss_measurements\n self.likelihood_loss = nn.MSELoss()\n self.prior_loss = losses.GANLoss().to(device)\n self.device = device\n self.dict_scheduler = dict_scheduler\n self.lr_gen = self.dict_scheduler['gen'].get_lr()[0]\n self.lr_dis = self.dict_scheduler['dis'].get_lr()[0]\n self._register_metrics(['loss_*', 'lr_*'])\n\n def _forward(self, input: dict):\n self.sample = input[\"sample\"]\n self.theta = input[\"theta\"]\n self.measured_sample = input[\"measured_sample\"]\n self.fake_sample = self.netG(self.measured_sample)\n measure_dict = self.measurement.measure(self.fake_sample, device=self.device)\n self.measured_fake_sample = measure_dict[\"measured_sample\"]\n\n if self.backloss_measurements > 0:\n self.fake_sample_back = self.netG(self.measured_fake_sample)\n self.fake_measured_sample_back = self.measurement.measure(self.fake_sample_back, device=self.device,\n theta=measure_dict[\"theta\"])[\"measured_sample\"]\n\n self.loss_MSE = self.likelihood_loss(self.fake_sample, self.sample)\n return input\n\n def _backward_G(self):\n set_requires_grad(self.netD, False)\n self.netG_optim.zero_grad()\n\n # First, G(A) should fake the discriminator\n pred_fake = self.netD(self.fake_sample)\n self.loss_G = self.prior_loss(pred_fake, True)\n\n if self.backloss_measurements > 0:\n loss_back_measurements = self.likelihood_loss(self.fake_measured_sample_back,\n self.measured_fake_sample.detach())\n self.loss_G = self.loss_G + self.backloss_measurements * loss_back_measurements\n\n self.loss_G.backward()\n self.netG_optim.step()\n return self.loss_G\n\n def _step(self):\n self.lr_gen = self.dict_scheduler['gen'].get_lr()[0]\n self.lr_dis = self.dict_scheduler['dis'].get_lr()[0]\n self.dict_scheduler['gen'].step()\n self.dict_scheduler['dis'].step()\n\n def _backward_D(self):\n\n set_requires_grad(self.netD, True)\n self.netD_optim.zero_grad()\n\n pred_real = self.netD(self.measured_sample)\n pred_fake = self.netD(self.fake_sample.detach())\n\n # Real\n loss_D_real = self.prior_loss(pred_real, True)\n # Fake\n loss_D_fake = self.prior_loss(pred_fake, False)\n # Combined loss\n self.loss_D = (loss_D_real + loss_D_fake) * 0.5\n # backward\n self.loss_D.backward()\n self.netD_optim.step()\n\n return self.loss_D\n\n def _backward(self):\n self._backward_G()\n self._backward_D()\n","sub_path":"unir/closures/unsupervised_image_reconstruction.py","file_name":"unsupervised_image_reconstruction.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"70847929","text":"#Given an array of integers, return indices of the two numbers such that they add up to a specific target.\r\n\r\nclass Solution(object):\r\n def twoSum(self, nums, target):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type target: int\r\n :rtype: List[int]\r\n \"\"\"\r\n\r\n for i,num in enumerate(nums):\r\n rem=target-num\r\n if rem in nums and nums.index(rem)!=i:\r\n return [i,nums.index(rem)]\r\n\r\n\r\n\r\nsol=Solution()\r\n\r\n\r\nprint(sol.twoSum([2, 7, 11, 15],9))\r\n","sub_path":"TwoSum.py","file_name":"TwoSum.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"200715691","text":"'''\n32. https://leetcode.com/problems/longest-valid-parentheses/\n\nStack (great insight)\nhttps://leetcode.com/problems/longest-valid-parentheses/discuss/14278/Two-Java-solutions-with-explanation.-Stack-and-DP.-Short-and-easy-to-understand.\n\nBetter DP (and smarter)\nhttps://leetcode.com/problems/longest-valid-parentheses/discuss/14133/My-DP-O(n)-solution-without-using-stack\n\nMy Original idea of DP failed 1/3 of the tests, time limit exceeded.\n'''\n\nclass Solution:\n def longestValidParentheses_Stack(self, s):\n '''\n Stack. Passed!\n '''\n if not s or len(s) < 2: return 0\n\n st = [-1] # good trick using guard value\n res = 0\n for i, c in enumerate(s):\n if st[-1] != -1 and s[st[-1]] == '(' and c == ')':\n st.pop()\n\n # distance from the current char to the last invalid char (that cant be neutralized yet)\n res = max(res, i - st[-1])\n else:\n st.append(i)\n\n return res\n\n def longestValidParentheses_DP(self, s):\n '''\n DP. Passed!\n '''\n if not s or len(s) < 2: return 0\n \n dp = [0] * len(s) # longest valid substring ends at i\n for i in range(1, len(s)):\n # for dp[i] to be valid, s[i] has to be ')'\n if s[i] == ')':\n if s[i-1] == '(':\n dp[i] = 2 + (dp[i-2] if i >= 2 else 0)\n elif dp[i-1] > 0:\n # ignore the section that makes up dp[i-1]\n # try to match s[i] and s[begin]\n begin = i - dp[i-1] - 1\n if begin >= 0 and s[begin] == '(':\n dp[i] = 2 + dp[i-1] + (dp[begin - 1] if begin >= 1 else 0)\n\n res = 0\n for i in range(1, len(s)):\n res = max(res, dp[i])\n\n return res\n\n def longestValidParentheses_Original(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n def isValid(i, j):\n # has calculated this before\n if valid[i][j] != -1:\n return valid[i][j]\n\n #print(i, j)\n if j - i == 1:\n return s[i:j + 1] == '()'\n\n res = False\n if s[i] == '(' and s[j] == ')':\n res = isValid(i + 1, j - 1)\n\n valid[i][j] = res or any(isValid(i, k) and isValid(k + 1, j) for k in range(i + 1, j, 2))\n return valid[i][j]\n\n if not s:\n return 0\n\n n = len(s)\n res = 0\n\n valid = [[-1] * n for i in range(n)]\n\n for i in range(n - 1):\n for j in range(i + 1, n, 2):\n if isValid(i, j):\n res = max(res, j - i + 1)\n\n return res\n\n\ns = Solution()\ntests = [\n ')()())'\n , '()()()()()()()'\n , ''\n , '()'\n , '('\n , ')('\n , ')))((())()()((('\n , \")(()(()(((())(((((()()))((((()()(()()())())())()))()()()())(())()()(((()))))()((()))(((())()((()()())((())))(())))())((()())()()((()((())))))((()(((((()((()))(()()(())))((()))()))())\"\n , \"())())))))))))()(()))(()))())(()))()))(((())))()))(((())()())()(()))(()((())))((()(())))(())(()()))))())((())())))()()(()))())(((())((()((()(()()))(()(()((()())((())(()(()((((())())()(()()()\"\n]\n\nfor t in tests:\n print(s.longestValidParentheses_DP(t), '<--', t)\n","sub_path":"2018/lc_LongestValidParentheses.py","file_name":"lc_LongestValidParentheses.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"460934084","text":"#!/usr/bin/env python3\n\nimport pytest\nimport datetime\nimport os\n\nfrom metplus.wrappers.point2grid_wrapper import Point2GridWrapper\nfrom metplus.util import time_util\n\ninput_dir = '/some/path/input'\ninput_name = 'TMP'\n\n# grid to use if grid is not set with command line argument\ngrid_dir = '/some/path/grid'\ngrid_template = os.path.join(grid_dir, '{valid?fmt=%Y%m%d}.nc')\n\n\ndef set_minimum_config_settings(config):\n # set config variables to prevent command from running and bypass check\n # if input files actually exist\n config.set('config', 'DO_NOT_RUN_EXE', True)\n config.set('config', 'INPUT_MUST_EXIST', False)\n\n # set process and time config variables\n config.set('config', 'PROCESS_LIST', 'Point2Grid')\n config.set('config', 'LOOP_BY', 'INIT')\n config.set('config', 'INIT_TIME_FMT', '%Y%m%d%H')\n config.set('config', 'INIT_BEG', '2017060100')\n config.set('config', 'INIT_END', '2017060300')\n config.set('config', 'INIT_INCREMENT', '24H')\n config.set('config', 'LEAD_SEQ', '12H')\n\n # required variables for input/output, to grid, and input field\n config.set('config', 'POINT2GRID_INPUT_DIR', input_dir)\n config.set('config', 'POINT2GRID_INPUT_TEMPLATE',\n 'input.{init?fmt=%Y%m%d%H}_f{lead?fmt=%2H}.nc')\n config.set('config', 'POINT2GRID_OUTPUT_DIR', '{OUTPUT_BASE}/out')\n config.set('config', 'POINT2GRID_OUTPUT_TEMPLATE',\n 'output.{valid?fmt=%Y%m%d%H}.nc')\n config.set('config', 'POINT2GRID_REGRID_TO_GRID', grid_template)\n config.set('config', 'POINT2GRID_INPUT_FIELD', input_name)\n\n\n@pytest.mark.parametrize(\n 'config_overrides, optional_args', [\n ({}, {}),\n ({'POINT2GRID_REGRID_METHOD': 'UW_MEAN'}, ['-method UW_MEAN']),\n ({'POINT2GRID_REGRID_METHOD': 'UW_MEAN',\n 'POINT2GRID_GAUSSIAN_DX': '2',},\n ['-method UW_MEAN', '-gaussian_dx 2']),\n ({'POINT2GRID_GAUSSIAN_RADIUS': '81.231'},\n ['-gaussian_radius 81.231']),\n ({'POINT2GRID_PROB_CAT_THRESH': '1'}, ['-prob_cat_thresh 1']),\n ({'POINT2GRID_VLD_THRESH': '0.5'}, ['-vld_thresh 0.5']),\n ({'POINT2GRID_QC_FLAGS': '0,1'}, ['-qc 0,1']),\n ({'POINT2GRID_ADP': '{valid?fmt=%Y%m}.nc'}, ['-adp 201706.nc']),\n ({'POINT2GRID_REGRID_TO_GRID': 'G212'}, []),\n ({'POINT2GRID_INPUT_LEVEL': '(*,*)'}, []),\n ]\n)\n@pytest.mark.wrapper\ndef test_point2grid_run(metplus_config, config_overrides, optional_args):\n config = metplus_config\n set_minimum_config_settings(config)\n\n # set config variable overrides\n for key, value in config_overrides.items():\n config.set('config', key, value)\n\n wrapper = Point2GridWrapper(config)\n assert wrapper.isOK\n\n app_path = os.path.join(config.getdir('MET_BIN_DIR'), wrapper.app_name)\n verbosity = f\"-v {wrapper.c_dict['VERBOSITY']}\"\n out_dir = wrapper.c_dict.get('OUTPUT_DIR')\n input_files = (\n f'{input_dir}/input.2017060100_f12.nc',\n f'{input_dir}/input.2017060200_f12.nc',\n f'{input_dir}/input.2017060300_f12.nc',\n )\n output_files = (\n f'{out_dir}/output.2017060112.nc',\n f'{out_dir}/output.2017060212.nc',\n f'{out_dir}/output.2017060312.nc',\n )\n\n if 'POINT2GRID_REGRID_TO_GRID' in config_overrides:\n grids = (\n config_overrides['POINT2GRID_REGRID_TO_GRID'],\n config_overrides['POINT2GRID_REGRID_TO_GRID'],\n config_overrides['POINT2GRID_REGRID_TO_GRID']\n )\n else:\n grids = (\n os.path.join(grid_dir, '20170601.nc'),\n os.path.join(grid_dir, '20170602.nc'),\n os.path.join(grid_dir, '20170603.nc')\n )\n\n if 'POINT2GRID_INPUT_LEVEL' in config_overrides:\n level = config_overrides['POINT2GRID_INPUT_LEVEL']\n else:\n level = ''\n\n extra_args = \" \".join(optional_args) + \" \" if optional_args else \"\"\n expected_cmds = []\n for idx in range(0, 3):\n expected_cmds.append(\n f'{app_path} {input_files[idx]} \"{grids[idx]}\" {output_files[idx]}'\n f' -field \\'name=\"{input_name}\"; level=\"{level}\";\\''\n f' {extra_args}{verbosity}'\n )\n\n all_cmds = wrapper.run_all_times()\n print(f\"ALL COMMANDS: {all_cmds}\")\n\n for (cmd, env_vars), expected_cmd in zip(all_cmds, expected_cmds):\n # ensure commands are generated as expected\n assert cmd == expected_cmd\n","sub_path":"internal/tests/pytests/wrappers/point2grid/test_point2grid.py","file_name":"test_point2grid.py","file_ext":"py","file_size_in_byte":4376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"127877200","text":"from flask import Flask\r\nfrom flask import request\r\nfrom flask import Response\r\n\r\nimport datetime\r\nimport json\r\n\r\napp = Flask(__name__)\r\n\r\n# When running locally\r\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://:@localhost:5432/'\r\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://elves:elves@localhost:5432/rwfruns' \r\n\r\n# When running within a container\r\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://elves:elves@runsdb:5432/rwfruns'\r\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True \r\n\r\nfrom dbmodels import db, Challenge, Challenge_Opponents\r\nfrom endpoints_handler import *\r\n\r\n\r\n@app.route(\"/\")\r\ndef root():\r\n dataDict = request.get_json()\r\n return \"Reached Challenges Service!\" + endpointtest()\r\n\r\n\r\n################################\r\n# Challenges (with challengeid)\r\n################################\r\n\r\n@app.route(\"/challenges/\", methods=['GET', 'DELETE'])\r\ndef handle_challenges(challengeid):\r\n if (request.method == 'GET'):\r\n return handle_get_challenge(request, challengeid)\r\n elif (request.method == 'DELETE'):\r\n return handle_delete_challange(request, challengeid)\r\n\r\n#######################################################\r\n# Retriving All Challenges where a User is an opponent\r\n#######################################################\r\n\r\n@app.route(\"/challenges\", methods=['GET'])\r\ndef handle_challanges_opponent_lookup():\r\n if (request.method == 'GET'):\r\n return handle_get_challenge_by_opponent(request)\r\n\r\n#################################################\r\n# Challenge's Opponents (adding and retrieving)\r\n#################################################\r\n\r\n@app.route(\"/challenges//opponents\", methods=['GET', 'POST', 'DELETE'])\r\ndef handle_challenge_opponents_operations(challengeid):\r\n if (request.method == 'GET'):\r\n return handle_get_challenge_opponents(request, challengeid)\r\n elif (request.method == 'POST'):\r\n return handle_add_challenge_opponents(request, challengeid)\r\n elif (request.method == 'DELETE'):\r\n return handle_delete_challenge_opponents(request, challengeid) \r\n\r\n@app.route(\"/challenges//opponents/\", methods=['POST', 'DELETE'])\r\ndef handle_challange_opponent_operations(challengeid, opponentid):\r\n if (request.method == 'DELETE'):\r\n return handle_remove_challenge_opponent(request, challengeid, opponentid)\r\n\r\n##################################\r\n# User's Challenges (with userid)\r\n##################################\r\n\r\n@app.route(\"/users//challenges\", methods=['GET', 'POST', 'DELETE'])\r\ndef handle_user_challenges(userid):\r\n if (request.method == 'GET'):\r\n return handle_get_user_challenges(request, userid)\r\n elif (request.method == 'POST'):\r\n return handle_add_new_challenge_by_user(request, userid)\r\n\r\n##################\r\n# Maintenance\r\n##################\r\n\r\n@app.route(\"/status\")\r\ndef status_check():\r\n return \"Challenge Service is UP!\"\r\n\r\n##################\r\n# Debug\r\n##################\r\n\r\n@app.route(\"/reflect/string\", methods=['GET', 'POST'])\r\ndef reflect_as_string():\r\n dataDict = request.get_json()\r\n return \"HTTP POST JSON data: \" + str(dataDict);\r\n\r\n@app.route(\"/reflect/JSON\", methods=['GET', 'POST'])\r\ndef reflect_as_JSON():\r\n dataDict = request.get_json()\r\n response = Response(json.dumps(dataDict))\r\n response.headers['Content-Type'] = 'application/json'\r\n return response;\r\n\r\n##################\r\n# Admin\r\n##################\r\n@app.route(\"/admin/database\")\r\ndef admin_get_database_entry():\r\n displayValue = ''\r\n displayValue += '# Rows in \"Challenge\" table: %d' % len(Challenge.query.all())\r\n displayValue += '# Rows in \"Challenge_Opponents\" table: %d' % len(Challenge_Opponents.query.all()) \r\n return displayValue\r\n\r\n@app.route(\"/admin/database/wipe\")\r\ndef admin_wipe_database():\r\n db.drop_all()\r\n return \"Database Wiped\"\r\n\r\n@app.route(\"/admin/database/create\")\r\ndef admin_create_database():\r\n db.create_all()\r\n return \"Database Tables Created\"\r\n\r\n@app.route(\"/admin/database/wipe-and-create\")\r\ndef admin_wipe_and_create_database():\r\n db.drop_all()\r\n db.create_all()\r\n return \"Database Tables Wipe & Created\" \r\n\r\nif __name__ == \"__main__\":\r\n app.run(host='0.0.0.0', debug=True, port=80)\r\n print(\"App run @ 80\")\r\n\r\n","sub_path":"ChallengesService/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"228384440","text":"\nfrom tkinter import *\nimport re\nimport urllib.request\nimport base64\nimport pymysql\nfrom tkinter import messagebox\nimport datetime as clock\n\n\nclass Gateway:\n def __init__(self, root):\n\n\n self.root = root\n self.username = StringVar()\n self.password = StringVar()\n self.confirmpassword = StringVar()\n self.currentuser = ''\n\n #-----CreateProfileVariables-----#\n self.dob = StringVar()\n self.dob.set('YYYY-MM-DD')\n self.email = StringVar()\n self.address = StringVar()\n self.lastname = StringVar()\n self.firstname= StringVar()\n self.gender = StringVar()\n self.faculty = StringVar()\n self.department = StringVar()\n\n #Download and prep the IMAGE\n self.image = None\n response = urllib.request.urlopen(\"http://www.cc.gatech.edu/classes/AY2015/cs2316_fall/codesamples/techlogo.gif\")\n data = response.read()\n response.close()\n img = base64.encodebytes(data)\n self.image = PhotoImage(data=img)\n\n #---------LOGIN PAGE---------#\n self.root.title(\"Login\")\n l = Label(self.root, image=self.image)\n l.pack()\n\n #USERNAME\n frame1 = Frame(self.root)\n frame1.pack()\n Label(frame1,text=\"Username:\").pack(side=LEFT, anchor=E)\n self.loginusername = Entry(frame1, width=30, textvariable=self.username)\n self.loginusername.pack(side=LEFT)\n Label(frame1,text=\" \").pack(side=LEFT, anchor=E)\n\n #PASSWORD\n frame2 = Frame(self.root)\n frame2.pack()\n Label(frame2,text=\"Password:\").pack(side=LEFT, anchor=E)\n self.loginpassword = Entry(frame2, width=30, textvariable=self.password)\n self.loginpassword.pack(side=LEFT)\n Label(frame2,text=\" \").pack(side=LEFT, anchor=E)\n\n #LOGIN BUTTONS\n frame3 = Frame(self.root)\n frame3.pack(fill=BOTH, expand=True)\n Button(frame3,text=\"Exit\", command=self.root.destroy).pack(side=RIGHT)\n Button(frame3,text=\"Login\", command=self.LoginCheck).pack(side=RIGHT)\n Button(frame3,text=\"Register\", command=self.switch).pack(side=RIGHT)\n\n\n #----------New User Registration Page------------#\n self.root21 = Toplevel()\n self.root21.title(\"New User Registration\")\n\n # url = \"http://www.or.gatech.edu/images/isye-icon.gif\"\n #\n #\n #\n # response = urllib.request.urlopen(url)\n # data = response.read()\n # response.close()\n #\n # img = base64.encodebytes(data)\n # image = PhotoImage(data=img)\n\n #image\n L = Label(self.root21, image=self.image)\n L.pack()\n\n #USERNAME\n framez = Frame(self.root21)\n framez.pack(fill=BOTH, expand=True)\n Label(framez,text=\"Username: \").pack(side=LEFT)\n self.regusername = Entry(framez, width=30, textvariable=self.username)\n self.regusername.pack(side=LEFT)\n\n #PASSWORD\n framec = Frame(self.root21)\n framec.pack(fill=BOTH, expand=True)\n Label(framec,text=\"Password: \").pack(side=LEFT)\n self.regpassword = Entry(framec, width=30, textvariable=self.password)\n self.regpassword.pack(side=LEFT)\n\n #CONFIRMPASSWORD\n framed = Frame(self.root21)\n framed.pack(fill=BOTH, expand=True)\n Label(framed,text=\"Confirm Password:\").pack(side=LEFT, anchor=E)\n self.regconfirmpassword = Entry(framed, width=30, textvariable=self.confirmpassword)\n self.regconfirmpassword.pack(side=LEFT)\n\n #BUTTONS\n framee = Frame(self.root21)\n framee.pack(fill=BOTH, expand=True)\n Button(framee,text=\"Register\", command=self.RegisterNew).pack(side=RIGHT)\n Button(framee,text=\"Cancel\", command=self.switch2122).pack(side=RIGHT)\n self.root21.withdraw()\n\n #------Create Profile Page------#\n self.root22 = Toplevel()\n self.root22.title('Create Profile')\n\n\n L = Label(self.root22, image=self.image)\n L.pack()\n framet = Frame(self.root22)\n framet.pack()\n frametl = Frame(framet)\n frametl.pack(side=RIGHT)\n frametr =Frame(framet)\n frametr.pack(side=RIGHT)\n\n frametl1 = Frame(frametl)\n frametl1.pack(fill=BOTH, expand=True)\n self.regfirstname = Entry(frametl1, width=30, textvariable=self.firstname)\n self.regfirstname.pack(side=RIGHT)\n Label(frametl1,text=\"First Name:\").pack(side=RIGHT)\n\n\n frametl2 = Frame(frametl)\n frametl2.pack(fill=BOTH, expand=True)\n self.regdob = Entry(frametl2, width=30, textvariable=self.dob)\n self.regdob.pack(side=RIGHT)\n Label(frametl2,text=\"D.O.B:\").pack(side=RIGHT)\n\n\n frametl3 = Frame(frametl)\n frametl3.pack(fill=BOTH, expand=True)\n self.regemail = Entry(frametl3, width=30, textvariable=self.email)\n self.regemail.pack(side=RIGHT)\n Label(frametl3,text=\"Email:\").pack(side=RIGHT)\n\n\n frametl4 = Frame(frametl)\n frametl4.pack(fill=BOTH, expand=True)\n self.regaddress = Entry(frametl4, width=30, textvariable=self.address)\n self.regaddress.pack(side=RIGHT)\n Label(frametl4,text=\"Address:\").pack(side=RIGHT)\n\n\n\n frametr1 = Frame(frametr)\n frametr1.pack(fill=BOTH, expand=True)\n self.reglastname = Entry(frametr1, width=30, textvariable=self.lastname)\n self.reglastname.pack(side=RIGHT)\n Label(frametr1,text=\"Last Name:\").pack(side=RIGHT)\n\n\n frametr2 = Frame(frametr)\n frametr2.pack(fill=BOTH, expand=True)\n Radiobutton(frametr2, text='MALE', variable=self.gender,value='M').pack(side=RIGHT)\n Radiobutton(frametr2, text='FEMALE', variable=self.gender,value='F').pack(side=RIGHT)\n Label(frametr2,text=\" Gender:\").pack(side=RIGHT)\n\n frametr3 = Frame(frametr)\n frametr3.pack(fill=BOTH, expand=True)\n Radiobutton(frametr3, text = \"Yes\", variable=self.faculty, value = \"Y\").pack(side=RIGHT)\n Radiobutton(frametr3, text = \"No\", variable=self.faculty, value = \"N\").pack(side=RIGHT)\n Label(frametr3,text=\" Faculty:\").pack(side=RIGHT)\n\n\n\n frametr4 = Frame(frametr)\n frametr4.pack(fill=BOTH, expand=True)\n self.department.set(\"\") # default value\n self.regdepartment= OptionMenu(frametr4, self.department,\"\",\"CS\",\"Chem\",\"Math\",\"Engineering\",\"Physics\")\n self.regdepartment.pack(side=RIGHT,expand=True,fill=BOTH)\n Label(frametr4,text=\"Department:\").pack(side=RIGHT)\n\n\n\n\n def createProfile():\n dob = self.dob.get()\n email = self.email.get()\n address = self.address.get()\n username = self.username.get()\n lastname = self.lastname.get()\n firstname = self.firstname.get()\n gender = self.gender.get()\n faculty = self.faculty.get()\n department = self.department.get()\n\n if dob == '' or \\\n email == '' or \\\n address == '' or \\\n lastname == '' or \\\n firstname == '' or \\\n gender == '' or \\\n faculty == '':\n\n valid = False\n messagebox.showerror(\"Missing items.\", \"Please fill out all forms\")\n\n else:\n if faculty == 'Y' and department == '':\n valid=False\n messagebox.showerror(\"Department is null\",\"Since you are a faculty, please specify a department.\")\n else:\n valid = True\n\n if len(re.findall('([0-9]{4}-[01][0-9]-[0123][0-9])',dob))!=1:\n valid=False\n messagebox.showerror(\"Invalid Date\",\"Date of birth must be formatted as YYYY-MM-DD.\")\n\n #Insert info into database, remember .commit()\n if valid:\n c = self.Connect()\n sql = \"INSERT INTO Student_Faculty (username, name, email, address, dob, gender, faculty, department) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\"\n c.execute(sql,(username, firstname + \" \" + lastname, email, address, dob, gender, faculty, department))\n self.db.commit()\n c.close()\n\n #confirm registration, hide reg window and present create profile window\n messagebox.showinfo(\"Success\",\"You have successfully created your profile, please log in.\")\n self.clear()\n self.root22.withdraw()\n self.root.deiconify()\n\n\n\n frametr5 = Frame(self.root22)\n frametr5.pack(expand=True,fill=BOTH)\n Button(frametr5,text='Submit',command=createProfile).pack(side=RIGHT)\n Button(frametr5,text='Cancel',command=self.switch22).pack(side=RIGHT)\n\n self.root22.withdraw()\n\n def Homepage(self):\n\n #---variables---#\n self.isbn=StringVar()\n self.title=StringVar()\n self.author=StringVar()\n\n self.root3 = Toplevel() #creates the 'Homepage' window.\n self.root3.title(\"GT Library Management System\")\n\n #---menu---#\n self.root3.left = Frame(self.root3,relief=GROOVE,bd=4,pady=2,padx=2) #creates a frame and grounds the frame inside the 'Homepage' window(self.root3)\n self.root3.left.pack(side=LEFT,expand=True,fill=BOTH) #builds it\n\n self.root3.right = Frame(self.root3)\n self.root3.right.pack(side=LEFT,anchor=N,expand=True,fill=BOTH)\n\n self.root3.topright=Frame(self.root3.right,relief=GROOVE,bd=4,padx=2,pady=2,)\n self.root3.topright.pack(expand=True,fill=X,anchor=N)\n self.root3.bottomright=Frame(self.root3.right,relief=GROOVE,bd=4,padx=2,pady=2,)\n self.root3.bottomright.pack(side=BOTTOM,expand=True,fill=BOTH)\n\n Label(self.root3.left,text='CHECK IN/OUT',bg='blue',fg='yellow',font='Helvetica 16').pack(expand=True,fill=X)\n\n self.root3.one = Frame(self.root3.left)\n self.root3.one.pack()\n Button(self.root3.one, text= 'Return Book',width=20, command=self.switch38).pack(expand=True, fill=BOTH,side=LEFT)\n Button(self.root3.one, text= 'Checkout',width=20, command=self.switch37).pack(expand=True, fill=BOTH,side=LEFT)\n\n Label(self.root3.left,text='OPTIONS',bg='blue',fg='yellow',font='Helvetica 16').pack(expand=True,fill=X)\n\n self.root3.two = Frame(self.root3.left)\n self.root3.two.pack()\n Button(self.root3.two, text= 'Request Book Extension',width=20, command=self.switch34).pack(expand=True, fill=BOTH,side=LEFT)\n Button(self.root3.two, text= 'Track Book Location',width=20, command=self.switch36).pack(expand=True, fill=BOTH,side=LEFT)\n\n self.root3.three = Frame(self.root3.left)\n self.root3.three.pack()\n Button(self.root3.three, text= 'Lost/Damaged Book',width=20, command=self.switch39).pack(expand=True, fill=BOTH,side=LEFT)\n Button(self.root3.three, text= 'Future Hold Request',width=20, command=self.switch35).pack(expand=True, fill=BOTH,side=LEFT)\n\n Label(self.root3.left,text='REPORTS',bg='blue',fg='yellow',font='Helvetica 16').pack(expand=True,fill=X)\n\n self.root3.five = Frame(self.root3.left)\n self.root3.five.pack()\n Button(self.root3.five, text= 'Popular Books',width=20, command=self.switch312).pack(expand=True, fill=BOTH,side=LEFT)\n Button(self.root3.five, text= 'Frequent Users', width=20,command=self.switch313).pack(expand=True, fill=BOTH,side=LEFT)\n\n self.root3.six = Frame(self.root3.left)\n self.root3.six.pack(expand=True,fill=BOTH)\n Button(self.root3.six, text= 'Damaged Books',width=20, command=self.switch314).pack(expand=True, fill=BOTH,side=LEFT)\n Button(self.root3.six, text= 'Popular Subjects',width=20, command=self.switch315).pack(expand=True, fill=BOTH,side=LEFT)\n\n ##--------------[ SEARCH ]---------------##\n ##-------------[ BOX ]----------------##\n\n self.searchField=StringVar()\n self.searchField.set('')\n self.searchValue=StringVar()\n self.searchValue.set('')\n\n def bookSearch():\n field = self.searchField.get()\n value = self.searchValue.get()\n\n if field !='':\n if value !='':\n c = self.Connect()\n\n ##------[ GET (isbn, title, edition, is_book_on_reserve) of every book that matches the search parameters ]-----##\n sql=\"SELECT DISTINCT isbn, title, edition, is_book_on_reserve FROM Book NATURAL JOIN Authors WHERE \"+field+\" LIKE %s\"\n c.execute(sql, (\"%\" + value + \"%\",))\n\n books = c.fetchall()\n self.db.commit()\n c.close()\n\n if len(books)==0:\n messagebox.showinfo('No Results', 'Your search returned no results, please try again.')\n else:\n\n ##-----[ Check Availability for the books, Pack those results in a tuple of tuples for displaying ]-----##\n self.allresults = []\n for book in books:\n c=self.Connect()\n sql = 'SELECT COUNT(*) FROM BookCopy NATURAL JOIN Book WHERE isbn = %s AND is_on_hold = %s AND is_checked_out = %s AND is_damaged = %s'\n c.execute(sql,(str(book[0]),'N','N','0'))\n self.db.commit()\n copies_available=c.fetchone()\n c.close()\n self.allresults.append((book[0],book[1],book[2],book[3],copies_available[0]))\n\n ##----[build the gui to display hold results]----##\n self.rootsearchresults = Toplevel()\n gui=self.rootsearchresults\n\n #--variables--#\n gui.sql =self.allresults\n gui.selection = StringVar()\n\n def placehold():\n\n #--data grab--#\n sql =\"SELECT copy_num FROM BookCopy NATURAL JOIN Book WHERE isbn = %s AND is_on_hold = 'N' AND is_checked_out = 'N' AND is_damaged = '0' AND is_book_on_reserve = 'N' LIMIT 1;\"\n c = self.Connect()\n print('gui.selection.get()= '+gui.selection.get())\n c.execute(sql,(gui.selection.get()))\n gui.copynum = c.fetchone()\n gui.copynum = gui.copynum[0]\n print(gui.copynum)\n\n sql=\"UPDATE BookCopy SET is_on_hold = 'Y' WHERE isbn = %s AND copy_num = %s LIMIT 1;\"\n c.execute(sql,(gui.selection.get(),gui.copynum))\n self.db.commit()\n\n sql=\"INSERT INTO Issues ( username, isbn, copy_num, date_of_issue, return_date) VALUES (%s,%s, %s, %s, %s)\"\n\n c.execute(sql,(self.username.get(),gui.selection.get(),gui.copynum, gui.holddate.get(),gui.returndate.get()))\n self.db.commit()\n\n sql=\"SELECT issue_id FROM Issues WHERE username = %s AND isbn = %s AND copy_num=%s AND date_of_issue = %s\"\n c.execute(sql,(self.username.get(),gui.selection.get(),gui.copynum, gui.holddate.get()))\n gui.id = c.fetchone()\n gui.id = gui.id[0]\n c.close()\n\n messagebox.showinfo(\"Hold Placed!\",\"You have successfully placed a hold on your book. Please record your issues ID for future use: \"+str(gui.id))\n\n gui.destroy()\n\n\n\n\n\n\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='HOLD REQUEST FOR A BOOK',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.topframe=Frame(gui,pady=15,padx=15,bd=2,relief=FLAT)\n gui.topframe.pack(expand=True,fill=BOTH)\n\n gui.bottomframe=Frame(gui,pady=15,padx=15,bd=2,relief=FLAT)\n gui.bottomframe.pack(expand=True,fill=BOTH)\n\n\n\n gui.topheader = Frame(gui.topframe)\n gui.topheader.pack()\n gui.headerselect=Label(gui.topheader,width=5,text='SELECT',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headerselect.pack(side=LEFT)\n gui.headerisbn=Label(gui.topheader,width=18,text='ISBN',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headerisbn.pack(side=LEFT)\n gui.headertitle=Label(gui.topheader,width=30,text='TITLE',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headertitle.pack(side=LEFT)\n gui.headeredition=Label(gui.topheader,width=10,text='EDITION',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headeredition.pack(side=LEFT)\n gui.headercopiesavailable=Label(gui.topheader,width=10,text='# AVAILABLE',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headercopiesavailable.pack(side=LEFT)\n\n created=False;\n\n for item in gui.sql:\n\n\n\n if item[3]=='N':\n gui.frame=Frame(gui.topframe)\n gui.frame.pack()\n Radiobutton(gui.frame,value = item[0],anchor=E,variable=gui.selection,padx=10).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=18,text=str(item[0]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=30,text=str(item[1]),justify=CENTER,wraplength=250,relief=SUNKEN).pack(side=LEFT)\n Label(gui.frame,width=10,text=str(item[2]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=10,text=str(item[4]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n else:\n if created==False:\n gui.bottomheader = Frame(gui.bottomframe)\n gui.bottomheader.pack()\n Label(gui.bottomheader,text='BOOKS ON RESERVE',bg='blue',fg='yellow',font='Helvetica 16',width=60).pack(expand=True,fill=X)\n Label(gui.bottomheader,width=18,text='ISBN',justify=CENTER,bg='grey',relief=SUNKEN).pack(side=LEFT)\n Label(gui.bottomheader,width=30,text='TITLE',justify=CENTER,bg='grey',relief=SUNKEN).pack(side=LEFT)\n Label(gui.bottomheader,width=10,text='EDITION',justify=CENTER,bg='grey',relief=SUNKEN).pack(side=LEFT)\n Label(gui.bottomheader,width=10,text='# AVAILABLE',justify=CENTER,bg='grey',relief=SUNKEN).pack(side=LEFT)\n created = True\n\n gui.frame = Frame(gui.bottomframe)\n gui.frame.pack()\n\n Label(gui.frame,width=18,text=str(item[0]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=30,text=str(item[1]),justify=CENTER,wraplength=250,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=10,text=str(item[2]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=10,text=str(item[4]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n\n\n gui.entryframe = Frame(gui.topframe)\n gui.entryframe.pack()\n\n gui.holddate = StringVar()\n gui.returndate=StringVar()\n\n gui.currentdate = clock.datetime.today()\n gui.holddate.set(str(clock.datetime.strftime(gui.currentdate,'%Y-%m-%d'))) #a string with current date as 'YYYY-MM-DD'\n\n gui.currentdateplus17 = clock.datetime.today() + clock.timedelta(days=17)\n gui.returndate.set(str(clock.datetime.strftime(gui.currentdateplus17,'%Y-%m-%d')))\n\n\n Label(gui.entryframe,text='Hold Request Date :').pack(side=LEFT)\n gui.holddateentry = Entry(gui.entryframe,bg='grey',textvariable=gui.holddate,width=10)\n gui.holddateentry.pack(side=LEFT)\n\n Label(gui.entryframe,text='Estimated Return Date :').pack(side=LEFT)\n gui.returndateentry = Entry(gui.entryframe,bg='grey',textvariable=gui.returndate,width=10)\n gui.returndateentry.pack(side=LEFT)\n\n\n gui.buttonframe = Frame(gui.topframe)\n gui.buttonframe.pack()\n gui.cancelButton=Button(gui.buttonframe,text='Return To LMS',pady=15,command=gui.destroy)\n gui.cancelButton.pack(side=LEFT)\n gui.submitButton=Button(gui.buttonframe,text='Submit',pady=15,command=placehold)\n gui.submitButton.pack(side=LEFT)\n\n\n else:\n messagebox.showerror('Input Required','You must enter a search input.')\n else:\n messagebox.showerror('Selection Required','You must select a search field.')\n\n\n topone = Frame(self.root3.topright)\n topone.pack(expand=True,fill=BOTH)\n Label(topone,text='SEARCH FOR A BOOK',bg='blue',fg='yellow',font='Helvetica 16').pack(expand=True,fill=X)\n\n toptwo = Frame(self.root3.topright)\n toptwo.pack(expand=True,fill=BOTH)\n self.getsearchValue = Entry(toptwo, width=30, textvariable=self.searchValue)\n self.getsearchValue.pack()\n\n topthree = Frame(self.root3.topright)\n topthree.pack(expand=True,fill=BOTH)\n\n Radiobutton(topthree, text = \"ISBN\", variable=self.searchField, value = \"isbn\").pack(side=RIGHT)\n Radiobutton(topthree, text = \"TITLE\", variable=self.searchField, value = \"title\").pack(side=RIGHT)\n Radiobutton(topthree, text = \"AUTHOR\", variable=self.searchField, value = \"author_name\").pack(side=RIGHT)\n self.searchField.set('ISBN')\n\n topfour = Frame(self.root3.topright)\n topfour.pack(expand=True,fill=BOTH)\n Button(topfour,text='Search',font='20',command=bookSearch).pack(expand=True,fill=BOTH)\n\n ##--------------[ LOG OFF ]---------------##\n ##-------------[ AREA ]----------------##\n\n bottomone = Frame(self.root3.bottomright)\n bottomone.pack(expand=True,fill=BOTH,side=BOTTOM)\n Button(bottomone,text='Close LMS',command=self.root.destroy).pack(side=RIGHT,expand=True,fill=BOTH)\n Label(bottomone, image=self.image).pack(side=RIGHT)\n Button(bottomone,text='Log Off',command=self.logoff).pack(side=RIGHT,expand=True,fill=BOTH)\n\n def Logout(self):\n #closes the Homepage window and returns the\n self.root3.destroy()\n\n self.root.deiconify()\n pass\n\n def LoginCheck(self):\n usrname = self.username.get()#get credentials from the login entries\n passwrd = self.password.get()\n self.currentuser = self.username.get()\n\n #clear out credentials after retrieval\n self.clear2()\n\n c=self.Connect()#create the database connection object\n sql = \"SELECT username, password FROM User WHERE username= %s AND password= %s\"\n a = c.execute(sql, (usrname, passwrd))\n\n contains = False\n if a != 0:\n for item in c:#check all the possible matches for\n if item[0]==usrname:\n if item[1]==passwrd:\n contains=True\n\n if contains:\n messagebox.showinfo(\"Login Successful\", \"Welcome to the Library Management System.\")\n self.root.withdraw()\n self.Homepage()\n\n else:\n messagebox.showerror(\"Login Unsuccessful\",\"Not found, please enter a different username/password\")\n c.close()\n\n #-------GUI Switches-------#\n def switch2122(self):\n self.root21.withdraw()\n self.root22.deiconify()\n\n def switch22(self):\n self.eraseUser(self.username.get())\n self.clear()\n self.root22.withdraw()\n self.root.deiconify()\n\n def switch34(self):\n self.root4 = Toplevel()\n gui=self.root4\n\n #--variables--#\n gui.issueID = StringVar()\n gui.originalcheckoutDate = StringVar()\n gui.currentextensionDate=StringVar()\n gui.currentreturnDate=StringVar()\n gui.newextensionDate=StringVar()\n gui.newestimatedreturnDate = StringVar()\n\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='REQUEST EXTENSION ON A BOOK',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.frame1=Frame(gui,pady=20,padx=160)\n gui.frame1.pack(expand=True,fill=BOTH)\n gui.submitissueID = Button(gui.frame1,text='Submit',command=gui.issueID.get)\n gui.submitissueID.pack(side=RIGHT)\n gui.getissueID = Entry(gui.frame1,width=18, textvariable=gui.issueID)\n gui.getissueID.pack(side=RIGHT)\n gui.issueIDlabel = Label(gui.frame1,text=\"Enter your issue ID :\")\n gui.issueIDlabel.pack(side=RIGHT)\n\n\n gui.line = Label(gui,bg='blue',width=60)\n gui.line.pack(expand=True,fill=X)\n\n gui.frame2=Frame(gui,pady=5,padx=15)\n gui.frame2.pack(expand=True,fill=BOTH)\n gui.originalcheckoutDatelabel = Label(gui.frame2,text=\"Original Checkout Date :\")\n gui.originalcheckoutDatelabel.pack(side=LEFT)\n gui.getoriginalcheckoutDate = Entry(gui.frame2,width=18, textvariable=gui.originalcheckoutDate)\n gui.getoriginalcheckoutDate.pack(side=LEFT)\n\n gui.frame3=Frame(gui,pady=5,padx=15)\n gui.frame3.pack(expand=True,fill=BOTH)\n gui.getcurrentreturnDate = Entry(gui.frame3, width=18, textvariable=gui.currentreturnDate)\n gui.getcurrentreturnDate.pack(side=RIGHT)\n gui.currentreturnDatelabel = Label(gui.frame3,text=\"Current Return Date :\")\n gui.currentreturnDatelabel.pack(side=RIGHT)\n gui.currentextensionDatelabel = Label(gui.frame3,text=\"Current Extension Date :\")\n gui.currentextensionDatelabel.pack(side=LEFT)\n gui.getcurrentextensionDate = Entry(gui.frame3, width=18, textvariable=gui.currentextensionDate)\n gui.getcurrentextensionDate.pack(side=LEFT)\n\n gui.frame4=Frame(gui,pady=5,padx=15)\n gui.frame4.pack(expand=True,fill=BOTH)\n gui.getnewestimatedreturnDate = Entry(gui.frame4, width=13, textvariable=gui.newestimatedreturnDate)\n gui.getnewestimatedreturnDate.pack(side=RIGHT)\n gui.newestimatedreturnDatelabel = Label(gui.frame4,text=\"New Estimated Return Date :\")\n gui.newestimatedreturnDatelabel.pack(side=RIGHT)\n gui.getnewextensionDate = Entry(gui.frame4, width=18, textvariable=gui.newextensionDate)\n gui.getnewextensionDate.pack(side=RIGHT)\n gui.newextensionDatelabel = Label(gui.frame4,text=\"New Extension Date :\")\n gui.newextensionDatelabel.pack(side=RIGHT)\n\n\n gui.frame4=Frame(gui,pady=5,padx=15)\n gui.frame4.pack(expand=True,fill=BOTH)\n gui.cancelbutton = Button(gui.frame4,text='Cancel',width=16,command=gui.destroy)\n gui.cancelbutton.pack(side=RIGHT)\n gui.submitbutton = Button(gui.frame4,text='Submit',width=16,command=print(gui.issueID.get()))\n gui.submitbutton.pack(side=RIGHT)\n\n def switch35(self):\n self.root5 = Toplevel()\n gui=self.root5\n\n #--variables--#\n gui.isbn = StringVar()\n gui.copyNumber = StringVar()\n gui.expectedAvailableDate=StringVar()\n\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='FUTURE HOLD REQUEST FOR A BOOK',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.frame1=Frame(gui,pady=15,padx=160)\n gui.frame1.pack(expand=True,fill=BOTH)\n gui.locateIsbn = Button(gui.frame1,text='Request',command=gui.isbn.get)\n gui.locateIsbn.pack(side=RIGHT)\n gui.getIsbn = Entry(gui.frame1,width=18, textvariable=gui.isbn)\n gui.getIsbn.pack(side=RIGHT)\n gui.isbnLabel = Label(gui.frame1,text=\"ISBN :\")\n gui.isbnLabel.pack(side=RIGHT)\n\n\n gui.line = Label(gui,bg='blue',width=60)\n gui.line.pack(expand=True,fill=X)\n\n gui.frame2=Frame(gui,pady=5,padx=15)\n gui.frame2.pack(expand=True,fill=BOTH)\n gui.getcopyNumber = Entry(gui.frame2,width=18,state='readonly',readonlybackground='grey', textvariable=gui.copyNumber)\n gui.getcopyNumber.pack(side=RIGHT)\n gui.copyNumberlabel = Label(gui.frame2,text=\"Copy Number :\")\n gui.copyNumberlabel.pack(side=RIGHT)\n gui.getexpectedAvailableDate = Entry(gui.frame2, width=18,state='readonly',readonlybackground='grey', textvariable=gui.expectedAvailableDate)\n gui.getexpectedAvailableDate.pack(side=RIGHT)\n gui.expectedAvailableDatelabel = Label(gui.frame2,text=\"Expected Available Date :\")\n gui.expectedAvailableDatelabel.pack(side=RIGHT)\n\n gui.frame3=Frame(gui,pady=5,padx=15)\n gui.frame3.pack(expand=True,fill=BOTH)\n gui.confirmbutton = Button(gui.frame3,text='Confirm',width=16,command=gui.destroy)\n gui.confirmbutton.pack(side=RIGHT)\n gui.cancelbutton = Button(gui.frame3,text='Cancel',width=16,command=gui.destroy)\n gui.cancelbutton.pack(side=RIGHT)\n\n def switch36(self):\n self.root6 = Toplevel()\n gui=self.root6\n\n #--variables--#\n gui.isbn = StringVar()\n gui.floorNumber = StringVar()\n gui.shelfNumber=StringVar()\n gui.aisleNumber=StringVar()\n gui.subject=StringVar()\n\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='TRACK BOOK LOCATION',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.frame1=Frame(gui,pady=15,padx=160)\n gui.frame1.pack(expand=True,fill=BOTH)\n gui.locateIsbn = Button(gui.frame1,text='Locate',command=gui.isbn.get)\n gui.locateIsbn.pack(side=RIGHT)\n gui.getIsbn = Entry(gui.frame1,width=18, textvariable=gui.isbn)\n gui.getIsbn.pack(side=RIGHT)\n gui.isbnLabel = Label(gui.frame1,text=\"ISBN :\")\n gui.isbnLabel.pack(side=RIGHT)\n\n\n gui.line = Label(gui,bg='blue',width=60)\n gui.line.pack(expand=True,fill=X)\n\n gui.frame2=Frame(gui,pady=5,padx=15)\n gui.frame2.pack(expand=True,fill=BOTH)\n gui.floorNumberlabel = Label(gui.frame2,text=\"Floor Number :\")\n gui.floorNumberlabel.pack(side=LEFT)\n gui.getfloorNumber = Entry(gui.frame2,width=18, textvariable=gui.floorNumber)\n gui.getfloorNumber.pack(side=LEFT)\n gui.getshelfNumber = Entry(gui.frame2, width=18, textvariable=gui.shelfNumber)\n gui.getshelfNumber.pack(side=RIGHT)\n gui.shelfNumberlabel = Label(gui.frame2,text=\"Shelf Number :\")\n gui.shelfNumberlabel.pack(side=RIGHT)\n\n\n gui.frame3=Frame(gui,pady=5,padx=15)\n gui.frame3.pack(expand=True,fill=BOTH)\n gui.getSubject = Entry(gui.frame3, width=18, textvariable=gui.subject)\n gui.getSubject.pack(side=RIGHT)\n gui.subjectlabel = Label(gui.frame3,text=\"Subject :\")\n gui.subjectlabel.pack(side=RIGHT)\n gui.aisleNumberlabel = Label(gui.frame3,text=\"Aisle Number :\")\n gui.aisleNumberlabel.pack(side=LEFT)\n gui.getaisleNumber = Entry(gui.frame3, width=18, textvariable=gui.aisleNumber)\n gui.getaisleNumber.pack(side=LEFT)\n\n\n\n gui.frame4=Frame(gui,pady=5,padx=15)\n gui.frame4.pack(expand=True,fill=BOTH)\n gui.cancelbutton = Button(gui.frame4,text='Cancel/Back',width=16,command=gui.destroy)\n gui.cancelbutton.pack(side=RIGHT)\n\n def switch37(self):\n self.root7 = Toplevel()\n gui=self.root7\n\n #--variables--#\n gui.isbn = StringVar()\n gui.copyNumber = StringVar()\n gui.userName=StringVar()\n gui.checkoutDate=StringVar()\n gui.estimatedreturnDate=StringVar()\n\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='Book Checkout',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.frame1=Frame(gui,pady=5,padx=15)\n gui.frame1.pack(expand=True,fill=BOTH)\n gui.getcopyNumber = Entry(gui.frame1, width=15, textvariable=gui.copyNumber)\n gui.getcopyNumber.pack(side=RIGHT)\n gui.copynumberlabel = Label(gui.frame1,text=\"Copy Number :\").pack(side=RIGHT)\n gui.isbnlabel = Label(gui.frame1,text=\" ISBN :\").pack(side=LEFT)\n gui.getisbn = Entry(gui.frame1, width=20, textvariable=gui.isbn)\n gui.getisbn.pack(side=LEFT)\n\n\n gui.frame2=Frame(gui,pady=5,padx=15)\n gui.frame2.pack(expand=True,fill=BOTH)\n gui.getuserName = Entry(gui.frame2, width=15, textvariable=gui.userName)\n gui.getuserName.pack(side=RIGHT)\n gui.usernamelabel = Label(gui.frame2,text=\"Username :\").pack(side=RIGHT)\n\n gui.frame3=Frame(gui,pady=5,padx=15)\n gui.frame3.pack(expand=True,fill=BOTH)\n gui.getestimatedreturnDate = Entry(gui.frame3, width=15, textvariable=gui.checkoutDate)\n gui.getestimatedreturnDate.pack(side=RIGHT)\n gui.estimatedreturnDatelabel = Label(gui.frame3,text=\" Estimated Return Date :\").pack(side=RIGHT)\n gui.checkoutDate = Label(gui.frame3,text=\"Checkout Date :\").pack(side=LEFT)\n gui.getcheckoutDate = Entry(gui.frame3, width=20, textvariable=gui.checkoutDate)\n gui.getcheckoutDate.pack(side=LEFT)\n\n gui.frame4=Frame(gui,pady=5,padx=15)\n gui.frame4.pack(expand=True,fill=BOTH)\n gui.cancelbutton = Button(gui.frame4,text='Cancel',width=16,command=gui.destroy).pack(side=RIGHT)\n gui.returnbutton = Button(gui.frame4,text='Checkout',width=16,command=print(gui.isbn.get())).pack(side=RIGHT)\n\n def switch38(self):\n self.root8 = Toplevel()\n gui=self.root8\n\n #--variables--#\n gui.isbn = StringVar()\n gui.copyNumber = StringVar()\n gui.damaged=StringVar()\n gui.userName=StringVar()\n\n def query():\n sql1='UPDATE Issues SET return_date=GETDATE() WHERE isbn=%s AND copynumber=%s AND username=%s'\n sql2='UPDATE BookCopy SET is_checked_out=%s WHERE isbn=%s AND copy=%s'\n\n\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='RETURN BOOK',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.frame1=Frame(gui,pady=5,padx=15)\n gui.frame1.pack(expand=True,fill=BOTH)\n gui.getcopyNumber = Entry(gui.frame1, width=15, textvariable=gui.copyNumber)\n gui.getcopyNumber.pack(side=RIGHT)\n gui.copynumberlabel = Label(gui.frame1,text=\"Copy Number :\").pack(side=RIGHT)\n gui.isbnlabel = Label(gui.frame1,text=\"ISBN :\").pack(side=LEFT)\n gui.getisbn = Entry(gui.frame1, width=20, textvariable=gui.isbn)\n gui.getisbn.pack(side=LEFT)\n\n gui.frame2=Frame(gui,pady=5,padx=15)\n gui.frame2.pack(expand=True,fill=BOTH)\n gui.getdamaged = Entry(gui.frame2, width=15, textvariable=gui.damaged)\n gui.getdamaged.pack(side=RIGHT)\n gui.damagedlabel = Label(gui.frame2,text=\"Damaged ? :\").pack(side=RIGHT)\n\n gui.frame3=Frame(gui,pady=5,padx=15)\n gui.frame3.pack(expand=True,fill=BOTH)\n gui.getuserName = Entry(gui.frame3, width=15, textvariable=gui.userName)\n gui.getuserName.pack(side=RIGHT)\n gui.usernamelabel = Label(gui.frame3,text=\"Username :\").pack(side=RIGHT)\n\n gui.frame4=Frame(gui,pady=5,padx=15)\n gui.frame4.pack(expand=True,fill=BOTH)\n gui.cancelbutton = Button(gui.frame4,text='Cancel',width=16,command=gui.destroy).pack(side=RIGHT)\n gui.returnbutton = Button(gui.frame4,text='Return',width=16,command=print(gui.query())).pack(side=RIGHT)\n\n def switch39(self):\n self.root9 = Toplevel()\n gui=self.root9\n\n #--variables--#\n gui.isbn = StringVar()\n gui.copyNumber = StringVar()\n gui.currentTime=StringVar()\n gui.lastUser = StringVar()\n gui.amount = StringVar()\n\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='LOST/DAMAGED BOOK',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.frame1=Frame(gui,pady=15,padx=15)\n gui.frame1.pack(expand=True,fill=BOTH)\n\n gui.getcopyNumber = Entry(gui.frame1,width=10, textvariable=gui.copyNumber)\n gui.getcopyNumber.pack(side=RIGHT)\n gui.copyNumberlabel = Label(gui.frame1,text=\" Copy Number :\")\n gui.copyNumberlabel.pack(side=RIGHT)\n gui.getIsbn = Entry(gui.frame1,width=18, textvariable=gui.isbn)\n gui.getIsbn.pack(side=RIGHT)\n gui.isbnLabel = Label(gui.frame1,text=\"ISBN :\")\n gui.isbnLabel.pack(side=RIGHT)\n\n gui.frame2=Frame(gui,padx=15)\n gui.frame2.pack(expand=True,fill=BOTH)\n gui.isbnLabel = Label(gui.frame2,text=' Current Time :')\n gui.isbnLabel.pack(side=LEFT)\n gui.getcurrentTime = Entry(gui.frame2,width=18, textvariable=gui.currentTime,state='readonly',readonlybackground='grey')\n gui.getcurrentTime.pack(side=LEFT)\n\n gui.frame3=Frame(gui,pady=15)\n gui.frame3.pack()\n gui.lastUserButton = Button(gui.frame3,text='Get Last User',command=gui.lastUser.get)\n gui.lastUserButton.pack()\n\n\n gui.line = Label(gui,bg='blue',width=60)\n gui.line.pack(expand=True,fill=X)\n\n gui.frame4=Frame(gui,pady=5,padx=15)\n gui.frame4.pack(expand=True,fill=BOTH)\n gui.getlastUserlabel = Label(gui.frame4,text=\" Last User of the Book :\")\n gui.getlastUserlabel.pack(side=LEFT)\n gui.getlastUser = Entry(gui.frame4, width=18,state='readonly',readonlybackground='grey', textvariable=gui.lastUser)\n gui.getlastUser.pack(side=LEFT)\n\n gui.frame5=Frame(gui,pady=5,padx=15)\n gui.frame5.pack(expand=True,fill=BOTH)\n gui.getamountlabel = Label(gui.frame5,text=\"Amount to be charged :\")\n gui.getamountlabel.pack(side=LEFT)\n gui.getamount = Entry(gui.frame5, width=18, textvariable=gui.amount)\n gui.getamount.pack(side=LEFT)\n\n gui.frame6=Frame(gui,pady=5,padx=15)\n gui.frame6.pack(expand=True,fill=BOTH)\n gui.submitbutton = Button(gui.frame6,text='Submit',width=16,command=gui.destroy)\n gui.submitbutton.pack(side=RIGHT)\n gui.cancelbutton = Button(gui.frame6,text='Cancel',width=16,command=gui.destroy)\n gui.cancelbutton.pack(side=RIGHT)\n\n def switch312(self):\n self.root12 = Toplevel()\n gui=self.root12\n\n #--variables--#\n gui.sql =\"SELECT * FROM PopularBookReport WHERE Month = '1' OR Month = '2' ORDER BY Month ASC, number DESC LIMIT 6\"\n\n c = self.Connect()\n c.execute(gui.sql)\n gui.report = c.fetchall()\n c.close()\n\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='POPULAR BOOKS REPORT',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.mainframe=Frame(gui,pady=15,padx=15)\n gui.mainframe.pack(expand=True,fill=BOTH)\n\n gui.header = Frame(gui.mainframe)\n gui.header.pack()\n gui.headermonth=Label(gui.header,width=10,text='MONTH',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headermonth.pack(side=LEFT)\n gui.headertitle=Label(gui.header,width=30,text='TITLE',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headertitle.pack(side=LEFT)\n gui.headercheckouts=Label(gui.header,width=10,text='# CHECKOUTS',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headercheckouts.pack(side=LEFT)\n\n for item in gui.report:\n gui.frame=Frame(gui.mainframe)\n gui.frame.pack()\n Label(gui.frame,width=10,text=str(item[0]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=30,text=str(item[1]),justify=CENTER,wraplength=250,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=10,text=str(item[2]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n\n gui.cancelButton=Button(gui.mainframe,text='Return To LMS',pady=15,command=gui.destroy)\n gui.cancelButton.pack(side=BOTTOM)\n\n def switch313(self):\n\n #--data grab--#\n sql =\"SELECT * FROM FrequentUserReport WHERE (Month = '1' OR Month = '2')AND numCheckout>=10 ORDER BY Month ASC, numCheckout DESC LIMIT 10\"\n\n c = self.Connect()\n c.execute(sql)\n report = c.fetchall()\n print(report)\n c.close()\n print(len(report))\n\n if len(report)==0:\n messagebox.showwarning('Report Unavailable','There are no frequent users to report.')\n else:\n self.root13 = Toplevel()\n gui=self.root13\n gui.report=report\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='FREQUENT USERS REPORT',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.mainframe=Frame(gui,pady=15,padx=15)\n gui.mainframe.pack(expand=True,fill=BOTH)\n\n gui.header = Frame(gui.mainframe)\n gui.header.pack()\n gui.headermonth=Label(gui.header,width=10,text='MONTH',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headermonth.pack(side=LEFT)\n gui.headertitle=Label(gui.header,width=30,text='USERNAME',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headertitle.pack(side=LEFT)\n gui.headercheckouts=Label(gui.header,width=10,text='# CHECKOUTS',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headercheckouts.pack(side=LEFT)\n\n for item in gui.report:\n gui.frame=Frame(gui.mainframe)\n gui.frame.pack()\n Label(gui.frame,width=10,text=str(item[0]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=30,text=str(item[1]),justify=CENTER,wraplength=250,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=10,text=str(item[2]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n\n gui.cancelButton=Button(gui.mainframe,text='Return To LMS',pady=15,command=gui.destroy)\n gui.cancelButton.pack(side=BOTTOM)\n\n def switch314(self):\n self.root14 = Toplevel()\n gui=self.root14\n\n\n\n def showReport():\n report = [];\n\n #--data grab--#\n gui.m = self.month2num(gui.month.get());\n\n sql =\"SELECT (Subject,number) FROM DamagedBookReport WHERE Month = %s AND Subject = %s\"\n\n print(gui.m)\n print(gui.subject1.get())\n\n c = self.Connect()\n c.execute(sql,(gui.m,gui.subject1.get()))\n report.append(c.fetchall())\n\n c.execute(sql,(gui.m,gui.subject2.get()))\n report.append(c.fetchall())\n\n c.execute(sql,(gui.m,gui.subject3.get()))\n report.append(c.fetchall())\n\n print(report)\n c.close()\n print(len(report))\n\n gui.mainframebottom=Frame(gui,pady=15,padx=15)\n gui.mainframebottom.pack(expand=True,fill=BOTH)\n\n gui.header = Frame(gui.mainframebottom)\n gui.header.pack()\n gui.headermonth=Label(gui.header,width=10,text='MONTH',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headermonth.pack(side=LEFT)\n gui.headertitle=Label(gui.header,width=10,text='SUBJECT',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headertitle.pack(side=LEFT)\n gui.headercheckouts=Label(gui.header,width=10,text='# DAMAGED',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headercheckouts.pack(side=LEFT)\n\n for item in report:\n gui.frame=Frame(gui.mainframebottom)\n gui.frame.pack()\n\n Label(gui.frame,width=10,text=str(item[0]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=10,text=str(item[1]),justify=CENTER,wraplength=250,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=10,text=str(item[2]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n\n gui.cancelButton=Button(gui.mainframebottom,text='Return To LMS',pady=15,command=gui.destroy)\n gui.cancelButton.pack(side=BOTTOM)\n\n\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='DAMAGED BOOKS REPORT',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.mainframetop=Frame(gui,pady=15,padx=15)\n gui.mainframetop.pack(expand=True,fill=BOTH)\n\n gui.mainframemiddle=Frame(gui,pady=15,padx=15)\n gui.mainframemiddle.pack(expand=True,fill=BOTH)\n\n gui.topframe1 = Frame(gui.mainframetop)\n gui.topframe1.pack()\n\n Label(gui.topframe1,text=\"SUBJECT\",padx=5).pack(side=LEFT)\n gui.subject1 = StringVar()\n gui.subject1.set(\"\")# default value\n gui.selectsubject1 = OptionMenu(gui.topframe1, gui.subject1,\" \",\"Business\",\"Children\",\"Computer\",\"Law\",\"Science\")\n gui.selectsubject1.config(width=10)\n gui.selectsubject1.pack(side=LEFT,expand=True,fill=BOTH)\n\n Label(gui.topframe1,text=\"SUBJECT\",padx=5).pack(side=LEFT)\n gui.subject2 = StringVar()\n gui.subject2.set(\"\")# default value\n gui.selectsubject2 = OptionMenu(gui.topframe1, gui.subject2,\" \",\"Business\",\"Children\",\"Computer\",\"Law\",\"Science\")\n gui.selectsubject2.config(width=10)\n gui.selectsubject2.pack(side=LEFT,expand=True,fill=BOTH)\n\n Label(gui.topframe1,text=\"SUBJECT\",padx=5).pack(side=LEFT)\n gui.subject3 = StringVar()\n gui.subject3.set(\"\")# default value\n gui.selectsubject3 = OptionMenu(gui.topframe1, gui.subject3,\" \",\"Business\",\"Children\",\"Computer\",\"Law\",\"Science\")\n gui.selectsubject3.config(width=10)\n gui.selectsubject3.pack(side=LEFT,expand=True,fill=BOTH)\n\n gui.topframe2 = Frame(gui.mainframetop)\n gui.topframe2.pack()\n\n Label(gui.topframe2,text=\"MONTH\",padx=5).pack(side=LEFT)\n gui.month = StringVar()\n gui.month.set(\"\")# default value\n gui.selectmonth = OptionMenu(gui.topframe2, gui.month,' ','Janurary','February','March','April','May','June','July','August','September','October','November','December')\n gui.selectmonth.config(width=10)\n gui.selectmonth.pack(side=LEFT,expand=True,fill=BOTH)\n\n Button(gui.mainframemiddle,text='Show Report',pady=15,command=showReport).pack(side=BOTTOM)\n\n def switch315(self):\n #--data grab--#\n sql =\"SELECT * FROM PopularSubjectReport WHERE Month = '1' OR Month = '2' ORDER BY Month ASC, num_checkout DESC LIMIT 6\"\n\n c = self.Connect()\n c.execute(sql)\n report = c.fetchall()\n c.close()\n if len(report)==0:\n messagebox.showwarning('Report Unavailable','There is not enough data to compile a report.')\n else:\n self.root15 = Toplevel()\n gui=self.root15\n gui.report=report\n gui.title('GT Library Management System')\n gui.header = Label(gui,text='POPULAR SUBJETS REPORT',bg='blue',fg='yellow',font='Helvetica 16',width=60)\n gui.header.pack(expand=True,fill=X)\n\n gui.mainframe=Frame(gui,pady=15,padx=15)\n gui.mainframe.pack(expand=True,fill=BOTH)\n\n gui.header = Frame(gui.mainframe)\n gui.header.pack()\n gui.headermonth=Label(gui.header,width=20,text='MONTH',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headermonth.pack(side=LEFT)\n gui.headertitle=Label(gui.header,width=20,text='SUBJECT',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headertitle.pack(side=LEFT)\n gui.headercheckouts=Label(gui.header,width=20,text='# CHECKOUTS',justify=CENTER,bg='grey',relief=SUNKEN)\n gui.headercheckouts.pack(side=LEFT)\n\n for item in gui.report:\n gui.frame=Frame(gui.mainframe)\n gui.frame.pack()\n Label(gui.frame,width=20,text=str(item[0]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=20,text=str(item[1]),justify=CENTER,wraplength=250,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n Label(gui.frame,width=20,text=str(item[2]),justify=CENTER,relief=SUNKEN).pack(side=LEFT,expand=True,fill=Y)\n\n gui.cancelButton=Button(gui.mainframe,text='Return To LMS',pady=15,command=gui.destroy)\n gui.cancelButton.pack(side=BOTTOM)\n\n #-------random functions------#\n\n def clear(self):\n self.lastname.set(\"\")\n self.username.set(\"\")\n self.password.set(\"\")\n self.confirmpassword.set(\"\")\n\n def clear2(self):\n self.lastname.set(\"\")\n self.password.set(\"\")\n self.confirmpassword.set(\"\")\n\n def RegisterNew(self):\n\n valid = True\n #get register entries and put them into database\n username = self.username.get()\n password = self.password.get()\n confirmpassword = self.confirmpassword.get()\n\n\n\n #make sure username/password entries have values\n if username=='' or password=='' or confirmpassword=='':\n valid = False\n messagebox.showerror(\"Missing items.\", \"You must specify a username, password, and confirm password. \")\n\n else:\n if len(username)>30:\n valid=False\n messagebox.showerror(\"Invalid Username\",\"Username too long. Must be 30 characters or less.\")\n else:\n #make sure password has one upper case letter and one number\n if True:\n #check to make sure passwords match\n if password != confirmpassword:\n valid = False\n messagebox.showerror(\"Password error\", \"Password and confirm password must match.\")\n else:\n #check for a duplicate username in the database\n c=self.Connect()\n sql = \"SELECT * FROM User WHERE Username= %s\"\n a= c.execute(sql,username)\n if a>0:\n valid=False\n messagebox.showerror(\"Username taken\", \"Please select another username...\")\n #Insert info into database, remember .commit()\n if valid:\n c = self.Connect()\n sql = \"INSERT INTO User (username, password) VALUES (%s, %s)\"\n c.execute(sql,(username, password))\n self.db.commit()\n c.close()\n\n #confirm registration, hide reg window and present create profile window\n messagebox.showinfo(\"Success\",\"You have successfully registered you must now create a profile.\")\n self.root21.withdraw()\n self.root22.deiconify()\n\n def switch(self):\n self.clear2()\n self.root.withdraw()\n self.root21.deiconify()\n\n def Connect(self):\n #this points to the connection object, this way we can get a cursor from db.cursor()\n try:\n self.db = pymysql.connect(\n db='cs4400_Group_60',\n user='cs4400_Group_60',\n passwd='XoYOzC_l',\n host='academic-mysql.cc.gatech.edu'\n )\n c=self.db.cursor()\n return c\n except:\n messagebox.showerror(\"No connection!\", \"Can't connect to the database. Please check the internet connection.(If you're not on GTwifi, is your VPN running?)\")\n return None\n def logoff(self):\n self.root3.destroy()\n self.clear()\n\n def eraseUser(self,x):\n username = x\n c = self.Connect()\n sql = \"DELETE FROM User WHERE Username = %s\"\n c.execute(sql,(username))\n print(c.fetchone)\n self.db.commit()\n c.close()\n\n def month2num(self,x):\n table = (('1','January'),('2','February'),('3','March'),('4','April'),('5','May'),('6','June'),('7','July'),('8','August'),('9','September'),('10','October'),('11','November'),('12','December'));\n for item in table:\n if x==item[1]:\n return item[0];\n\nwin = Tk()\napp = Gateway(win)\nwin.mainloop()\n","sub_path":"LMSMain.py","file_name":"LMSMain.py","file_ext":"py","file_size_in_byte":53611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"293587591","text":"import _PyPacwar\nimport numpy as np\nimport time\nimport argparse\n\ndef get_score(g1,g2):\n # score of g1 vs g2\n # return score 1 score 2\n (r, c1,c2) = _PyPacwar.battle(g1,g2)\n if( c1 ==0 or c2 ==0):\n if( r < 100 ): sh, sl = 20,0\n elif(r <200): sh,sl = 19,1\n elif(r < 300): sh,sl = 18,2\n else: sh,sl = 17,3\n else:\n ratio = min(c1,c2)/max(c1,c2)\n if( ratio <= 0.1 ): sh, sl = 13,7\n elif( ratio <= 1.0/3.0): sh,sl = 12,8\n elif( ratio <= 1.0/1.5): sh,sl = 11,9\n else: sh, sl = 10, 10\n\n if (c1 < c2 ):\n return sl, sh\n else:\n return sh, sl\n\ndef get_score_matrix(rep_list):\n \"\"\"\n get score matrix\n score[i][j] = score of rep[i] ( rep[i] vs rep[j] )\n :param rep_list:\n :return:\n \"\"\"\n gene_list = [rep_to_gene(rep) for rep in rep_list]\n score = np.zeros((len(gene_list), len(gene_list)))\n\n for i in range(0, len(gene_list)):\n for j in range(i + 1, len(gene_list)):\n si, sj = get_score(gene_list[i], gene_list[j])\n score[i, j] = si\n score[j, i] = sj\n return score\n\ndef fitness( rep, enemy_list ):\n # rep vs all the enemey\n score = sum([ get_score(gene, rep)[1] for gene in enemy_list ])/len(enemy_list)\n return score\n\ndef read_gene(filename):\n \"\"\"\n read gene to poolss from filename\n :param filename:\n :return:\n \"\"\"\n\n file = open(filename)\n gene_list = []\n while(1):\n line = file.readline()\n if not line:\n break\n line = line.rstrip('\\n')\n gene = [int(x) for x in line]\n gene_list.append(gene)\n file.close()\n return gene_list\n\ndef neighbour(rep,enemy_list):\n rep_initial = rep[:]\n neighbors = [rep_initial]\n for i in range(0, len(rep)): #Each digit in the gene\n for plus in range(1, 4): # Change for each digit\n temp = rep[:]\n temp[i] = (temp[i] + plus) % 4\n neighbors.append(temp)\n for i in range(0,len(rep)-1):\n for j in range(i+1,len(rep)):\n for plus1 in range(1, 4):\n for plus2 in range(1,4):\n temp = rep[:]\n temp[i] = (temp[i] + plus1) % 4\n temp[j] = (temp[j] + plus2) % 4\n neighbors.append(temp)\n print(len(neighbors))\n score = [fitness(rep, enemy_list) for rep in neighbors]\n score = np.asarray(score)\n print(score)\n idx = np.argmax(score)\n\n return idx, score[idx], neighbors[int(idx)]\n\ndef crossover(gene1, gene2,enemy_list):\n children = [gene1,gene2]\n population_size = 400\n segment_len = [4, 16, 3, 3, 12, 12] # U,V,W,X,Y,Z\n for i in range(population_size):\n par_1 = gene1\n par_2 = gene2\n if np.random.rand()<= 1: # crossover for each bit\n child = [0] * len(par_1)\n for digit in range(0, len(par_1)):\n if (np.random.rand() < 0.5):\n child[digit] = par_1[digit]\n else:\n child[digit] = par_2[digit]\n else: # pit a whole segement, such as U segment, X segment ,...\n child = [0] * len(par_1)\n pt = 0\n for len_ in (segment_len):\n if (np.random.rand() < 0.5):\n child[pt:pt + len_] = par_1[pt:pt + len_]\n else:\n child[pt:pt + len_] = par_2[pt:pt + len_]\n pt += len_\n children.append(child)\n print(len(children))\n score = [fitness(rep, enemy_list) for rep in children]\n score = np.asarray(score)\n # print(score)\n idx = np.argmax(score)\n return idx, score[idx], children[int(idx)]\n\n\nif __name__ == \"__main__\":\n # parser = argparse.ArgumentParser()\n # parser.add_argument('--type', type=str, default='polish', help='polish or crossover')\n # opt = parser.parse_args()\n\n start = time.time()\n gene_list = read_gene('test_pool.txt')\n # gene_to_polish1 = '03130000000303230333112122111121122122121130121131'\n gene_to_polish1 = '03130000300303230333112122111121122122121130120131' # after polish from the first\n # gene_to_polish2 = '00020000010020220030121123123123123323223313113313'\n rep1 = [int(x) for x in gene_to_polish1]\n # rep2 = [int(x) for x in gene_to_polish2]\n idx, score, best_gene = neighbour(rep1,gene_list) #search 2 neigbours\n # idx, score, best_gene=crossover(rep1,rep2,gene_list) #cross over 2 diversity good genes\n print(score)\n best_gene = \"\".join([str(i) for i in best_gene])\n print(best_gene)\n end = time.time()\n print(end-start)\n","sub_path":"code/improvement.py","file_name":"improvement.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"4014270","text":"# -*- coding: utf-8 -*-\n\n'''\nNeste problema, deve-se ler o código de uma peça 1, o número de peças 1, o valor unitário de cada peça 1, o código de uma peça 2, o número de peças 2 e o valor unitário de cada peça 2. Após, calcule e mostre o valor a ser pago.\n\nEntrada\nO arquivo de entrada contém duas linhas de dados. Em cada linha haverá 3 valores, respectivamente dois inteiros e um valor com 2 casas decimais.\n\nSaída\nA saída deverá ser uma mensagem conforme o exemplo fornecido abaixo, lembrando de deixar um espaço após os dois pontos e um espaço após o \"R$\". O valor deverá ser apresentado com 2 casas após o ponto.\n\nExemplos de Entrada\t Exemplos de Saída\n12 1 5.30 VALOR A PAGAR: R$ 15.50\n16 2 5.10\n\n13 2 15.30 VALOR A PAGAR: R$ 51.40\n161 4 5.20\n\n1 1 15.10 VALOR A PAGAR: R$ 30.20\n2 1 15.10\n'''\n\nentrada = input()\nentrada2 = input()\nnumerosStr = entrada.split(\" \")\nnumerosStr2 = entrada2.split(\" \")\nnumeros = [float(num) for num in numerosStr]\nnumeros2 = [float(num) for num in numerosStr2]\n\ncod, qtd, val = numeros\ncod1, qtd1, val1 = numeros2\n\nvalf = (qtd * val) + (qtd1 * val1)\n\nprint (\"VALOR A PAGAR: R$ {:.2f}\".format(valf))\n","sub_path":"1010 - URI Online Judge - Solved.py","file_name":"1010 - URI Online Judge - Solved.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"542901603","text":"import grequests\nfrom openpyxl import load_workbook\n\nfrom utils.utils import save_pickle, load_pickle, read_file_lines\n\nheaders = {\n 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'}\n\ngoogle_start_page = \"https://www.google.com.ua/search?q=wordpress+leave+comment+students&ei=dGC8W8GBNIO4sQG0to64CQ&start={}&sa=N&biw=1307&bih=395\"\n\nstart_pages = [\n 'https://unlocktheteacher.wordpress.com/2012/07/22/100-positive-comments-to-utilize-when-speaking-on-students-behaviorr/'\n]\n\n\n# for i in range(20, 80, 10):\n# start_pages.append(google_start_page.format(i))\n\n\ntmp_file = 'domains.pkl'\n\nprocessed_domains = []\nprocessed_links = []\nlinks_to_process = []\nlinks_with_comments_form = []\nforbidden = read_file_lines('forbidden.txt')\n\ntotal = 0\ncurrent = 0\n\ntry:\n from BeautifulSoup import BeautifulSoup\nexcept ImportError:\n from bs4 import BeautifulSoup\n\n\ndef response_callback(response, **kwargs):\n global processed_links, links_to_process, links_with_comments_form, total, current, processed_domains\n current += 1\n print('Got {} of {}'.format(current, total))\n\n if current and current % 500 == 0:\n save_data()\n\n processed_links.append(response.url)\n\n text = response.text.lower()\n\n parsed_html = BeautifulSoup(text, \"lxml\")\n\n for a in parsed_html.body.find_all('a'):\n href = a.get('href')\n print(href)\n\n if not href: continue\n\n domain = get_domain(href)\n\n if 'http' in domain and domain not in processed_domains and domain not in forbidden:\n processed_domains.append(domain)\n links_to_process.append(domain)\n raise Exception\n return response\n\n\ndef exception_handler(request, exception):\n global current\n current += 1\n print('Exception', request.url, exception)\n\n\n\ndef get_domain(link):\n n = link.find('/', 8)\n return link[:n]\n\ndef grequests_links():\n global links_to_process, grequest_stack, total\n\n print('get pages links_to_process', len(links_to_process))\n total = len(links_to_process)\n\n for i in range(len(links_to_process)):\n link = links_to_process.pop()\n\n if 'http' not in link:\n print('There are not http in {}'.format(link))\n continue\n\n grequest_stack.append(grequests.get(link, headers=headers,\n hooks={'response': response_callback},\n timeout=10))\n\n\ndef save_data():\n global processed_links, links_to_process, links_with_comments_form, processed_domains\n stage = {\n 'processed_links': processed_links,\n 'links_to_process': links_to_process,\n 'links_with_comments_form': links_with_comments_form,\n 'processed_domains': processed_domains,\n }\n print(\"Saved Data, links_with_comments_form: {}, processed_links: {}, links_to_process: {}, processed_domains: {}\".format(\n len(links_with_comments_form), len(processed_links), len(links_to_process), len(processed_domains)))\n save_pickle(tmp_file, stage)\n\n with open('domains.txt', 'w') as file:\n for link in processed_domains:\n file.write(\"{}\\n\".format(link))\n\n\nif __name__ == '__main__':\n links_to_process += start_pages\n grequest_stack = []\n\n try:\n data = load_pickle(tmp_file)\n processed_links = data['processed_links']\n links_to_process = data['links_to_process']\n links_with_comments_form = data['links_with_comments_form']\n processed_domains = data['processed_domains']\n except Exception:\n pass\n\n while len(links_to_process):\n grequests_links()\n\n results = grequests.map(grequest_stack, exception_handler=exception_handler, size=20)\n\n save_data()\n","sub_path":"find_comments/find_domains.py","file_name":"find_domains.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"50950296","text":"from flask import Flask, jsonify, render_template, request, json\nfrom flask import redirect, url_for\nfrom flask_cors import CORS\nimport pandas as pd\nimport glob\nimport os\nfrom os import listdir\nfrom dotenv import load_dotenv\nimport flask\n\nload_dotenv()\n\nfilepath = os.getenv(\"repo_filepath\")\n\ncity_df = pd.read_csv(filepath + 'findurcity/src/datasets/reference.csv')\nphotos = pd.read_csv(filepath + 'findurcity/src/extraneous_datasets/photos_big.csv')\neconomy = pd.read_csv(filepath + 'findurcity/src/datasets/economy_data.csv')\nheart_disease = pd.read_csv(filepath + 'findurcity/src/datasets/heart_data.csv')\nhousing = pd.read_csv(filepath + 'findurcity/src/datasets/housing_data.csv')\njobs = pd.read_csv(filepath + 'findurcity/src/datasets/job_data.csv')\nlocation = pd.read_csv(filepath + 'findurcity/src/datasets/location_data.csv')\npeople_stats = pd.read_csv(filepath + 'findurcity/src/datasets/people_stats_data.csv')\noriginal = pd.read_csv(filepath + 'findurcity/src/extraneous_datasets/final_0427.csv') \n\napp = Flask(__name__)\nCORS(app)\n\n# when using 'Global', we need to have the variable exist in the namespace\nstate = None\npop = None\npop_ch = None\nmed_age = None\nhdti = None\nrti = None\npop_dense = None\ncol = None\ndrive = None\naqi = None\nheart_health = None\n\n@app.route(\"/\")\ndef root():\n return (\"hi\")\n\n\n@app.route('/name', methods=['GET', 'POST'])\ndef id_name_only():\n id = request.args['id']\n city = city_df[city_df['id'] == int(id)]\n output = city.to_dict('records')\n name = output[0]['City_Name']\n return jsonify(name)\n \n\n\n@app.route('/about', methods=['GET', 'POST'])\ndef about_the_app():\n return render_template('about.html')\n\n\n@app.route('/recommend', methods=['GET', 'POST'])\ndef desc_and_livability():\n def recommend_cities():\n global state\n state = request.args['state']\n global pop\n pop = request.args['population']\n global pop_ch\n pop_ch = request.args['population_change']\n global med_age\n med_age = request.args['median_age']\n global hdti\n hdti = request.args['house_cost']\n global rti\n rti = request.args['rental_cost']\n global pop_dense\n pop_dense = request.args['population_density']\n global col\n col = request.args['cost_of_living']\n global drive\n drive = request.args['average_commute']\n global aqi\n aqi = request.args['air_quality']\n\n\n state = list(state.split(', '))\n pop = int(pop)\n pop_ch = int(pop_ch)\n med_age = int(med_age)\n hdti = int(hdti)\n rti = int(rti)\n pop_dense = int(pop_dense)\n col = int(col)\n drive = int(drive)\n aqi = int(aqi)\n\n\n def filter_dfs():\n # Create \"states\" dataframe\n multiple = []\n\n if state != ['None']:\n for item in state:\n frame = original[original['state'] == item]\n multiple.append(frame)\n\n states = pd.concat(multiple[0:], ignore_index=True)\n else:\n states = original\n\n # Create dataframe with filtered data\n if pop != 0:\n one = original[original['pop_rank'] == pop]\n else:\n one = original\n\n if pop_ch != 0:\n two = one[one['pop_ch_rank'] == pop_ch]\n else:\n two = one\n\n if med_age != 0:\n three = two[two['med_age_rank'] == med_age]\n else:\n three = two\n\n if hdti != 0:\n four = three[three['house_cost'] == hdti]\n else:\n four = three\n\n if rti != 0:\n five = four[four['rent_cost'] == rti]\n else:\n five = four\n\n if pop_dense != 0:\n six = five[five['pop_density'] == pop_dense]\n else:\n six = five\n\n if col != 0:\n seven = six[six['cli_index'] == col]\n else:\n seven = six\n\n if drive != 0:\n eight = seven[seven['avg_commute'] == drive]\n else:\n eight = seven\n\n if aqi != 0:\n nine = eight[eight['air'] == aqi]\n else:\n nine = eight\n\n # Create list of dataframes for use in case of no Top 5\n dataframes = [one, two, three, four, five, six, seven, eight, nine]\n\n # Merge dataframes to get fully filtered result\n all = pd.merge(nine, states, on='city', how='inner')\n\n # Sort by livability score and convert to a dictionary\n sort = all.sort_values(by='LivabilityScore_y', ascending=False)\n dict = sort.to_dict('records')\n\n # Allow less than 5 results if necessary\n all_cities = []\n for item in range(len(dict)):\n all_cities.append(dict[item]['city'])\n\n top_5 = all_cities[0:5]\n\n return top_5, dataframes\n\n def generate_cities():\n # Check that precise matches are available. If not, get imprecise matches.\n shapes = []\n variables = [pop, pop_ch, med_age, hdti, rti, pop_dense, col, drive, aqi]\n\n output, dataframes = filter_dfs()\n\n if output != []:\n return output\n else:\n for dataframe in dataframes:\n shape = dataframe.shape\n shapes.append(shape[0])\n #Get the position number of the first dataframe that has zero rows\n val = next((index for index, value in enumerate(shapes) if value == 0), None)\n variables[val] = 0\n return variables\n\n def close_match():\n\n something = generate_cities()\n\n if len(something) > 5:\n\n # Variables get updated to reflect \"something\"\n global pop\n pop = something[0]\n global pop_ch\n pop_ch = something[1]\n global med_age\n med_age = something[2]\n global hdti\n hdti = something[3]\n global rti\n rti = something[4]\n global pop_dense\n pop_dense = something[5]\n global col\n col = something[6]\n global drive\n drive = something[7]\n global aqi\n aqi = something[8]\n\n # Run generate_cities again with updated variable values\n full_output = generate_cities()\n\n return full_output\n\n else:\n return something\n\n # Run close_match until a top 5 list is generated\n def get_results():\n info = close_match()\n if len(info) > 5:\n again = close_match()\n if len(again) > 5:\n final = close_match()\n return final\n else:\n return again\n else:\n return info\n\n return get_results()\n\n # Return descriptions, id, and city name\n top_cities = recommend_cities()\n\n place_here = []\n\n for x in top_cities:\n\n copy = pd.DataFrame()\n\n city = original[original['city'] == x]\n output = city.to_dict('records')\n data = output[0]\n\n # Basic\n id = data['id']\n name = data['City_Name']\n name_and_state = data['city']\n score = data['LivabilityScore']\n\n # Population\n pop = data['population']\n change = data['population_change']\n density = data['Population_Density']\n age = data['Median_Age']\n\n # Economy\n houseinc = data['Median_Income']\n capitainc = data['per_capita_Income']\n poverty = data['Percent_below_Poverty']\n industry = data['Most_Common_Industries']\n\n # Climate\n aqi = data['AQI']\n cold = data['Coldday_Count']\n hot = data['Hotday_Count']\n rain = data['Rainday_Count']\n\n # Cost of Living\n cli = data['Cost_of_Living_Index']\n house = data['Median_House_Value']\n hdti = data['HDTI']\n tax = data['Property_taxes']\n rent = data['Median_Rent']\n rti = data['RTI']\n drive = data['Average_Commute_Time']\n\n # When relative words are needed\n if change < 0:\n growth = 'decrease'\n else:\n growth = 'increase'\n\n if density < 1304:\n rise = 'lower'\n elif density == 1304:\n rise = 'equal to'\n else:\n rise = 'higher'\n\n if cli < 51:\n cli_rel = 'low'\n else:\n cli_rel = 'high'\n\n # Descriptions\n copy['id'] = [f'{id}']\n copy['name'] = [f'{name}']\n copy['name_and_state'] = [f'{name_and_state}']\n copy['livability_score'] = f'{score}'\n copy['population_desc'] = f'The population is {pop} as of 2017, which is a {change}% {growth} since 2000. The population density is {density} people per square mile, which is {rise} than the optimal population density of 1304. Finally, the average resident age in {name} is {age} years old.'\n copy['economy_desc'] = f'In {name}, the median household income is ${houseinc}. This means that, per person in the city, the average annual income is ${capitainc}. {poverty}% of people live below the poverty line. The most common industries are the following: {industry}.'\n copy['climate_desc'] = f'{name} has an air quality score of {aqi} - remember, lower is better! Last year, there were {cold} cold days, {hot} hot days, and {rain} rainy days.'\n copy['living_cost_desc'] = f\"On a national scale, {name}'s cost of living is relatively {cli_rel}, with a score of {cli}. The median home value is ${house}, with a housing debt to income ratio of {hdti}. That includes the cost of property taxes, which is ${tax} on average. If you're a renter, you can expect a median cost of ${rent}, and the rent to income ratio is {rti}. Last but not least to consider, the average commute time is {drive} minutes.\"\n \n output2 = copy.to_dict('records')\n descriptions = output2[0]\n\n place_here.append(descriptions)\n\n return jsonify(place_here)\n\n\n@app.route('/data', methods=['GET', 'POST'])\ndef all_data():\n name = request.args['data']\n city = original[original['city'] == name]\n output = city.to_dict('records')\n data = output[0]\n return jsonify(data)\n\n\n@app.route('/top25', methods=['GET', 'POST'])\ndef top_25_data():\n output = photos.to_dict('records')\n return jsonify(output)\n\n\n@app.route('/search', methods=['GET', 'POST'])\ndef search_names():\n input = request.args['search']\n input = input.title()\n cities = city_df[city_df['City_Name'].str.startswith(input)]\n\n ids = []\n for index, row in cities.iterrows():\n ids.append(index)\n\n output = cities.to_dict('records')\n\n length = len(ids)\n all = []\n for item in range(length):\n city = output[item]['City_Name']\n all.append(city)\n\n return jsonify(all)\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"LAMBDA_LABS/juxta-city-data-ds/findurcity/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"615599742","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom pandas import DataFrame\n\nbase_url = \"http://www.pyclass.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/t=0&s=\"\nl = []\nr = requests.get(base_url+\"0.html\", \n headers={'User-agent': 'Mozilla/5.0' \n '(X11; Ubuntu; Linux x86_64; rv:61.0)'\n 'Gecko/20100101 Firefox/61.0'})\ncontent = r.content\nsoup = BeautifulSoup(content, \"html.parser\")\nlast_page_nr = soup.find_all(\"a\", {\"class\": \"Page\"})[-1].text\n\n\nfor page in range(0, (int(last_page_nr)*10), 10):\n r = requests.get(base_url + str(page) + \".html\", \n headers={'User-agent': 'Mozilla/5.0' \n '(X11; Ubuntu; Linux x86_64; rv:61.0)'\n 'Gecko/20100101 Firefox/61.0'})\n\n content = r.content\n soup = BeautifulSoup(content, \"html.parser\")\n property_rows = soup.find_all(\"div\",{\"class\": \"propertyRow\"})\n\n \n for row in property_rows:\n d = {}\n d[\"Price\"] = row.find(\"h4\", {\"class\": \"propPrice\"}).text.strip()\n d[\"Address\"] = row.find_all(\"span\", {\"class\": \"propAddressCollapse\"})[0].text\n d[\"Location\"] = row.find_all(\"span\", {\"class\": \"propAddressCollapse\"})[1].text\n try:\n d[\"Beds\"] = row.find(\"span\", {\"class\": \"infoBed\"}).find(\"b\").text\n except AttributeError:\n d[\"Beds\"] = \"N/A\"\n try:\n d[\"Area\"] = row.find(\"span\", {\"class\": \"infoSqFt\"}).find(\"b\").text\n except AttributeError:\n d[\"Area\"] = \"N/A\"\n try:\n d[\"Full baths\"] = row.find(\"span\", {\"class\": \"infoValueFullBath\"}).find(\"b\").text\n except AttributeError:\n d[\"Full baths\"] = \"N/A\"\n try:\n d[\"Half baths\"] = row.find(\"span\", {\"class\": \"infoValueHalfBath\"}).find(\"b\").text\n except AttributeError:\n d[\"Half baths\"] = \"N/A\"\n\n for column_group in row.find_all(\"div\", {\"class\": \"columnGroup\"}):\n for feature_group, feature_name in zip(column_group.find_all(\n \"span\", {\"class\": \"featureGroup\"}), \n column_group.find_all(\n \"span\", {\"class\": \"featureName\"})):\n if \"Lot Size\" in feature_group.text:\n d[\"Lot size\"] = feature_name.text\n l.append(d)\n\ndf = DataFrame(l)\ndf.to_csv(\"./App7_Webscraping/Output.csv\")","sub_path":"App7_Webscraping/realEstate.py","file_name":"realEstate.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"587445646","text":"import numpy as np\nimport os\nfrom PIL import Image\n\n# Set the parameters\n\n# path ti the directory where the images are saved\n\npath = \"path\\to\\images\"\n\t \n\nimage_width , image_height = 201, 201\t\t\t\t\t\t\t#size of the images\nmax_files = 1300\ndatset_name = \"Non_Defect_Data\"\t\t\t\t\t\t\n\n# Scan for the files in the folder and attached the filename to make full path for the files\nonlyfiles = [f\n for f in os.listdir(path)\n if os.path.isfile(os.path.join(path, f))]\n\nprint(\"Number of Image in the specified directory: \",len(onlyfiles))\n\n# Display random files from the list\n\nfor i in range(120 , 122):\n print(onlyfiles[i])\n #img = Image.open(path + \"/\" + onlyfiles[i])\n #img.show()\n\n\n\ndataset = np.ndarray((max_files, image_height , image_width),dtype=np.float32)\n\nprint(\"Writing Images to the dataset...\")\n\nindex = 0;\t\t\t\t\t# variable to keep track of loop count\n\nfor file in onlyfiles:\n file_path = path + \"/\" + file\n # open Image and convert it to numpy array\n img = np.asarray(Image.open(file_path))\n img = img.reshape((image_height , image_width))\n\n # add image array to the dataset ndarray\n dataset[index] = img\n index +=1\n if (index == max_files ): # Write only maximum 1300 images\n break\n\nprint(\"Done writing all images\")\n\n# Show any random image from the dataset\nimg = Image.fromarray(np.uint8(dataset[200]))\nimg.show();\n\n# save the data to numpy file\nnp.save(\"Data/\"+datset_name, dataset)\n\n# load the file and check the data\n\ndataset_read = np.load(\"Data/\"+datset_name+\".npy\")\nprint(dataset_read.shape)\nimg = Image.fromarray(dataset_read[200])\nimg.show()\n\n","sub_path":"images_to_numpy_dataset.py","file_name":"images_to_numpy_dataset.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"320901921","text":"\"\"\"\n1406. Stone Game III\nHard\n\nAlice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.\n\nAlice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row.\n\nThe score of each player is the sum of values of the stones taken. The score of each player is 0 initially.\n\nThe objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.\n\nAssume Alice and Bob play optimally.\n\nReturn \"Alice\" if Alice will win, \"Bob\" if Bob will win or \"Tie\" if they end the game with the same score.\n\nExample 1:\n\nInput: values = [1,2,3,7]\nOutput: \"Bob\"\nExplanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.\n\nExample 2:\n\nInput: values = [1,2,3,-9]\nOutput: \"Alice\"\nExplanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win.\n\nExample 3:\n\nInput: values = [1,2,3,6]\nOutput: \"Tie\"\nExplanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.\n\nExample 4:\n\nInput: values = [1,2,3,-1,-2,-3,7]\nOutput: \"Alice\"\n\nExample 5:\n\nInput: values = [-1,-2,-3]\nOutput: \"Tie\"\n \nConstraints:\n\n1 <= values.length <= 50000\n-1000 <= values[i] <= 1000\n\n\"\"\"\n\nfrom typing import List\nimport collections\n\n###############################################################################\n\"\"\"\nSolution: minmax game, DP using memoized recursion.\n\nTLE w/o memoization.\n\nRuntime: 2896 ms, faster than 86.26% of Python3 online submissions\nMemory Usage: 220.7 MB, less than 100.00% of Python3 online submissions\n\"\"\"\nimport functools\nclass Solution:\n #def stoneGameIII(self, stoneValue: List[int]) -> str:\n def stoneGameIII(self, arr: List[int]) -> str:\n @functools.lru_cache(None)\n def play(i=0):\n if i >= n:\n return 0\n\n return max(\n arr[i] - play(i+1),\n sum(arr[i:i+2]) - play(i+2),\n sum(arr[i:i+3]) - play(i+3)\n )\n\n n = len(arr)\n s = play()\n\n if s > 0:\n return \"Alice\"\n if s < 0:\n return \"Bob\"\n\n return \"Tie\"\n\n\"\"\"\nSolution1b: same but avoid array slicing.\n\nRuntime: 2752 ms, faster than 90.04% of Python3 online submissions\nMemory Usage: 220.8 MB, less than 100.00% of Python3 online submissions\n\"\"\"\nimport functools\nclass Solution1b:\n #def stoneGameIII(self, stoneValue: List[int]) -> str:\n def stoneGameIII(self, arr: List[int]) -> str:\n @functools.lru_cache(None)\n def play(i=0):\n if i >= n:\n return 0\n\n if i < n - 2:\n return max(\n arr[i] - play(i+1),\n arr[i] + arr[i+1] - play(i+2),\n arr[i] + arr[i+1] + arr[i+2] - play(i+3)\n )\n\n elif i == n - 2:\n return max(\n arr[-2] - arr[-1],\n arr[-2] + arr[-1]\n )\n\n elif i == n - 1:\n return arr[-1]\n\n n = len(arr)\n s = play()\n\n if s > 0:\n return \"Alice\"\n if s < 0:\n return \"Bob\"\n\n return \"Tie\"\n\n\"\"\"\nSolution 1c: memoized recursion using suffix sums.\n\nplay(i) = how many total stones the current player can get starting from now \nto the end of the game if he has to choose starting from pile i.\n(ie, pretend the game starts now at pile i).\n\n\"\"\"\nimport functools\nclass Solution1c:\n #def stoneGameIII(self, stoneValue: List[int]) -> str:\n def stoneGameIII(self, arr: List[int]) -> str:\n @functools.lru_cache(None)\n def play(i=0):\n if i >= n:\n return 0\n\n # return max(\n # sums[i] - play(i+1),\n # sums[i] - play(i+2),\n # sums[i] - play(i+3)\n # )\n return sums[i] - min(\n play(i+1),\n play(i+2),\n play(i+3)\n )\n\n n = len(arr)\n sums = [0] * (n+1) # suffix sums\n\n for i in range(n-1, -1, -1):\n sums[i] = sums[i+1] + arr[i]\n\n s = play()\n\n # dp[0] = number of stones Alice has\n # sums[0] = total number of stones\n if s * 2 > sums[0]: # Alice has more than half the stones\n return \"Alice\"\n if s * 2 < sums[0]:\n return \"Bob\"\n\n return \"Tie\"\n\n###############################################################################\n\"\"\"\nSolution 2: tabulation using 1d table.\n\nRuntime: 2340 ms, faster than 94.67% of Python3 online submissions\nMemory Usage: 17.5 MB, less than 100.00% of Python3 online submissions\n\"\"\"\nclass Solution2:\n #def stoneGameIII(self, stoneValue: List[int]) -> str:\n def stoneGameIII(self, arr: List[int]) -> str:\n n = len(arr)\n neg_inf = float('-inf')\n dp = [neg_inf] * (n+1)\n\n dp[n] = 0 # dummy value\n dp[n-1] = arr[-1]\n if n > 1:\n dp[n-2] = max(arr[-2] - arr[-1], arr[-2] + arr[-1])\n\n for i in range(n-1, -1, -1):\n dp[i] = max(\n arr[i] - dp[i+1],\n sum(arr[i:i+2]) - dp[i+2],\n sum(arr[i:i+3]) - dp[i+3]\n )\n\n if dp[0] > 0:\n return \"Alice\"\n if dp[0] < 0:\n return \"Bob\"\n\n return \"Tie\"\n\n\"\"\"\nSolution 2b: same, but use inner loop.\n\nBased on:\nhttps://leetcode.com/problems/stone-game-iii/discuss/564260/JavaC%2B%2BPython-DP-O(1)-Space\n\nO(n) time\nO(n) extra space\n\"\"\"\nclass Solution2b:\n #def stoneGameIII(self, stoneValue: List[int]) -> str:\n def stoneGameIII(self, arr: List[int]) -> str:\n n = len(arr)\n neg_inf = float('-inf')\n dp = [neg_inf] * n + [0]\n\n for i in range(n-1, -1, -1):\n take = 0\n\n ### Want k < 3 and \n ### k < end = n - i is same as i + k < n\n # end = min(3, n - i)\n\n # for k in range(end): \n # take += arr[i+k]\n # dp[i] = max(dp[i], take - dp[i+k+1])\n\n ###\n # i + k < i + 3 and i + k < n\n end = min(i+3, n)\n\n for k in range(i, end):\n take += arr[k]\n dp[i] = max(dp[i], take - dp[k+1])\n\n\n if dp[0] > 0:\n return \"Alice\"\n if dp[0] < 0:\n return \"Bob\"\n\n return \"Tie\"\n\n\"\"\"\nSolution 3c: use suffix sums.\n\nCon: the sums can become very big (pos or neg).\n\ndp[i] = how many total stones the current player can get starting from now \nto the end of the game if he has to choose starting from pile i.\n(ie, pretend the game starts now at pile i).\n\nBased on:\nhttps://leetcode.com/problems/stone-game-iii/discuss/564342/JavaC%2B%2BPython-Dynamic-Programming\n\nO(n) time\nO(n) extra space\n\"\"\"\nclass Solution3c:\n #def stoneGameIII(self, stoneValue: List[int]) -> str:\n def stoneGameIII(self, arr: List[int]) -> str:\n n = len(arr)\n neg_inf = float('-inf')\n dp = [neg_inf] * n + [0]\n sums = [0] * (n+1) # suffix sums\n\n for i in range(n-1, -1, -1):\n sums[i] = sums[i+1] + arr[i]\n\n for i in range(n-1, -1, -1):\n end = min(i+3, n)\n\n for k in range(i, end):\n dp[i] = max(dp[i], sums[i] - dp[k+1])\n #dp[i] = max(dp[i], (sums[i] - sums[k+1]) - (dp[k+1] - sums[k+1]))\n\n # dp[0] = number of stones Alice has\n # sums[0] = total number of stones\n if dp[0] * 2 > sums[0]: # Alice has more than half the stones\n return \"Alice\"\n if dp[0] * 2 < sums[0]:\n return \"Bob\"\n\n return \"Tie\"\n\n###############################################################################\n\"\"\"\nSolution 3: tabulation using O(1) space.\n\nTo calculate dp[i], only need dp[i+1], dp[i+2], and dp[i+3].\nUse 4 dp variables for readibility, although can be reduced to 3.\n\nO(n) time\nO(1) extra space\n\n\"\"\"\nclass Solution3:\n #def stoneGameIII(self, stoneValue: List[int]) -> str:\n def stoneGameIII(self, arr: List[int]) -> str:\n n = len(arr)\n\n if n == 1:\n dp = arr[0]\n else:\n dp3 = 0 # dummy value\n dp2 = arr[-1]\n dp1 = max(arr[-2] - arr[-1], arr[-2] + arr[-1])\n\n for i in range(n-3, -1, -1):\n dp = max(\n arr[i] - dp1,\n sum(arr[i:i+2]) - dp2,\n sum(arr[i:i+3]) - dp3\n )\n\n dp1, dp2, dp3 = dp, dp1, dp2\n\n if dp > 0:\n return \"Alice\"\n if dp < 0:\n return \"Bob\"\n\n return \"Tie\"\n\n\"\"\"\nSolution 3b: same, but use dp array of length 3.\n\"\"\"\nclass Solution3b:\n #def stoneGameIII(self, stoneValue: List[int]) -> str:\n def stoneGameIII(self, arr: List[int]) -> str:\n n = len(arr)\n dp = [0] * 3\n\n for i in range(n-1, -1, -1):\n dp[i % 3] = max(sum(arr[i:i+k]) - dp[(i+k) % 3] for k in (1,2,3) )\n\n def cmp(a,b): return (a>b)-(a= ProblemThread.WRONG_MAX:\n conn.sendall('Game Over'.encode('utf-8'))\n print('Game over. Disconnected for', conn.getpeername())\n conn.close()\n return\n conn.sendall(encoded)\n\n conn.sendall('complete'.encode('utf-8'))\n\n def fetchProblemWords(self):\n db_conn = sqlite3.connect(ProblemThread.DB_FILE)\n db_cursor = db_conn.cursor()\n\n query = 'select word from words order by random() limit 10'\n db_cursor.execute(query)\n words = db_cursor.fetchall()\n db_conn.close()\n\n ret_list = [w[0] for w in words]\n return ','.join(ret_list)\n\n def createAnswer(self, string):\n words = string.strip().split(',')\n words.sort()\n return ''.join(words)\n","sub_path":"ProblemThread.py","file_name":"ProblemThread.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"127398225","text":"import pandas as pd\n\n#Define primary data path\nDATADIR = '/Users/oghosa/Google Drive/1 - School/4th Year : Industrial Engineering/1 - Fall 2017/MIE 490 | Capstone Design/Capstone 2017-2018/Pickle Files/'\n\nbook_shelf_df = pd.read_pickle(DATADIR + 'book_shelf_df.pickle')\nshelf_df = pd.read_pickle(DATADIR + 'shelf_df.pickle')\ntop_1k_books_df = pd.read_pickle(DATADIR + 'top_books_df.pickle')\n### FOOLOW-UP: I'm finding that top 10k books is returning 9828 unique book_ids instead of 10k as expected. Not sure why\n\nshelf = pd.merge(book_shelf_df, shelf_df, on='shelf_id')\ntop_books_shelf = pd.merge(shelf, top_1k_books_df, on='book_id')\n\nbook_shelf = top_books_shelf[['book_id','shelf_name']]\n\n#convert dataframe to binary matrix\nprint(\"START\")\nbook_shelf_binary_matrix = pd.get_dummies(book_shelf.shelf_name).groupby(book_shelf.book_id).apply(max)\n\nprint(\"CONVERT\")\nbook_shelf_binary_matrix.to_csv(DATADIR + 'book_shelf_binary_matrix2.csv')\nprint(\"END\")","sub_path":"Archive/shelves.py","file_name":"shelves.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"23732897","text":"import os\nimport shutil\nfrom collections.abc import Callable\nfrom typing import Optional\n\n\ndef find_files(orig_root: str, new_root: str, handler: Callable[[str, str], None], restrict_orig_file_type: str, new_file_type: str, exception_directory_names: Optional[list[str]] = None) -> None:\n \"\"\"\n 每个文件都处理后保存到新位置 orig_root/directory_name/file_name -- 处理文件 --> new_root/directory_name/file_name\n 原始和处理后文件夹一致的\n :param new_file_type:\n :param restrict_orig_file_type: 限制 file 后缀(这里 js 包括了 *.js.example 文件)\n :param exception_directory_names: 排除\n :param handler:\n :param orig_root: 原始文件夹隶属于哪个目录\n :param new_root: 处理后文件夹隶属于哪个目录\n :return:\n \"\"\"\n if exception_directory_names is None:\n exception_directory_names = []\n\n for directory_name in os.listdir(orig_root):\n orig_directory_path = os.path.join(orig_root, directory_name)\n assert os.path.isdir(orig_directory_path) # 是个存在的文件夹\n\n if directory_name in exception_directory_names:\n continue\n\n new_directory_path = os.path.join(new_root, directory_name)\n\n # 如果没有 new_directory_path,就创建一个出来;否则使用 shutil.rmtree 确保此文件夹内数据清空\n if os.path.isdir(new_directory_path):\n shutil.rmtree(new_directory_path)\n os.makedirs(new_directory_path) # Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.\n\n for orig_file_name in os.listdir(orig_directory_path):\n orig_file_path = os.path.join(orig_directory_path, orig_file_name)\n split_file_name = orig_file_name.split('.')\n assert os.path.isfile(orig_file_path) # 是个存在的文件\n if split_file_name[1] == restrict_orig_file_type:\n split_file_name[1] = new_file_type\n new_file_path = os.path.join(new_directory_path, '.'.join(split_file_name))\n handler(orig_file_path, new_file_path)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"136047608","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\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: /home/ag239446/git/nsap/doc/source/sphinxext/hidden_technical_block.py\n# Compiled at: 2014-05-12 03:27:30\nimport logging\nfrom docutils import nodes\nfrom docutils.parsers.rst import directives\nfrom docutils.parsers.rst.directives.admonitions import BaseAdmonition\nfrom docutils.statemachine import ViewList\nHTB_COUNTER = 0\njs_showhide = '\\n\\n'\n\ndef nice_bool(arg):\n tvalues = ('true', 't', 'yes', 'y')\n fvalues = ('false', 'f', 'no', 'n')\n arg = directives.choice(arg, tvalues + fvalues)\n return arg in tvalues\n\n\nclass hidden_technical_block(nodes.Admonition, nodes.Element):\n \"\"\"Node for inserting hidden technical block.\"\"\"\n\n\nclass MyError(Exception):\n\n def __init__(self, value):\n self.value = value\n\n def __str__(self):\n return repr(self.value)\n\n\nclass HiddenTechnicalBlock(BaseAdmonition):\n \"\"\"Hidden technical block\"\"\"\n node_class = hidden_technical_block\n has_content = True\n required_arguments = 0\n optional_arguments = 2\n final_argument_whitespace = False\n option_spec = {'starthidden': nice_bool, \n 'label': str}\n\n def run(self):\n new_content = ViewList()\n for item in self.content:\n if item.startswith('.. include:: '):\n resource_path = item.replace('.. include:: ', '')\n try:\n fo = open(resource_path, 'r')\n item_content = [ x.replace('\\n', '') for x in fo.readlines()\n ]\n for string_content in item_content:\n new_content.append(unicode(string_content), source=self.content)\n\n fo.close()\n except MyError as e:\n item_content = (\"Can't open the resource file '{0}'\").format(resource_path)\n logging.error(item_content + e.value)\n new_content.append(item_content, source=self.content)\n\n else:\n new_content.append(item, source=self.content)\n\n self.content = new_content\n return super(HiddenTechnicalBlock, self).run()\n\n\ndef visit_htb_html(self, node):\n \"\"\"Visit hidden code block\"\"\"\n global HTB_COUNTER\n HTB_COUNTER += 1\n self.visit_admonition(node)\n technical_block = self.body[(-1)]\n fill_header = {'divname': ('hiddencodeblock{0}').format(HTB_COUNTER), \n 'startdisplay': 'none' if node['starthidden'] else 'block', \n 'label': node.get('label', '[+ show/hide technical details]')}\n divheader = ('\\n{label}
\\n
').format(**fill_header)\n technical_block = js_showhide + divheader + technical_block\n self.body[-1] = technical_block\n\n\ndef depart_htb_html(self, node):\n \"\"\"Depart hidden technical block\"\"\"\n self.depart_admonition(node)\n self.depart_admonition(node)\n\n\ndef setup(app):\n app.add_directive('hidden-technical-block', HiddenTechnicalBlock)\n app.add_node(hidden_technical_block, html=(\n visit_htb_html, depart_htb_html))","sub_path":"pycfiles/caps-cli-0.3.0.tar/hidden_technical_block.py","file_name":"hidden_technical_block.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"535451825","text":"import random, string \n\ndef generator():\n letter1 = random.choice(string.ascii_lowercase)\n letter2 = random.choice(string.ascii_lowercase)\n letter3 = random.choice(string.ascii_lowercase)\n letter4 = random.choice(string.ascii_lowercase)\n letter5 = random.choice(string.ascii_lowercase)\n name = letter1+letter2+letter3+letter4+letter5\n return(name)\n\nprint(generator())\n\nvowels = 'aeiouy' \nconsonants = 'bcdfghjklmnpqrstvwxz'\nletter = string.ascii_lowercase \n\n\nletter_input_1 = input(\"Choose a letter, 'v' for vowels, 'c' for consonants, 'l' for other.\")\nletter_input_2 = input(\"Choose a letter, 'v' for vowels, 'c' for consonants, 'l' for other.\")\nletter_input_3 = input(\"Choose a letter, 'v' for vowels, 'c' for consonants, 'l' for other.\")\nletter_input_4 = input(\"Choose a letter, 'v' for vowels, 'c' for consonants, 'l' for other.\")\nletter_input_5 = input(\"Choose a letter, 'v' for vowels, 'c' for consonants, 'l' for other.\")\n\nif letter_input_1 == \"v\":\n letter1 = random.choice(vowels)\nelif letter_input_2 == \"c\": \n letter1 = random.choice(consonants)\nelif letter_input_1 == \"l\":\n letter1 = random.choice(letter)\nelse:\n letter1 = letter_input_1\n","sub_path":"projects/baby_name_generator/bn2.py","file_name":"bn2.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"85354428","text":"from threading import Thread\nimport serial\nfrom time import sleep\n\nserialPort1 = serial.Serial(\"COM4\", 9600)\n\nclass Receiver1(Thread):\n\t\tdef __init__(self, serialPort1): \n\t\t\tThread.__init__(self) \n\t\t\tself.serialPort = serialPort1\n\t\tdef run(self):\n\t\t\tglobal serialPort1\n\t\t\tglobal strBuilder1\n\t\t\ttext = \"\" \n\t\t\twhile (text != \"exitReceiverThread\\n\"): \n\t\t\t\ttext = serialPort1.readline()\n\t\t\t\tprint(\"serial output: \" + text.decode())\n\t\t\t\n\t\t\tself.serialPort.close()\n\t\t\t\nreceive = Receiver1(serialPort1) \nreceive.start()\n\ndef Sender():\n\tglobal serialPort1\n\t\n\twhile True:\n\t\tserialPort1.flushInput()\n\t\ttext = input(\"\") + \"\\n\"\n\t\tserialPort1.write(text.encode('utf-8'))\n\t\tbytes_to_read = serialPort1.inWaiting()\n\t\tsleep(.2)\n\nsSend = Thread(target=Sender)\nsSend.start()\n","sub_path":"serial test.py","file_name":"serial test.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"415997765","text":"from curve import EllipticCurve\r\n\r\nclass Point(object):\r\n\r\n \"\"\"\r\n This class represents a point on the given Elliptic Curve\r\n \"\"\"\r\n\r\n def __init__(self, curve, x, y):\r\n self.curve = curve # the curve containing this point\r\n self.x = x\r\n self.y = y\r\n\r\n if not curve.testPoint(x, y):\r\n raise Exception(\"The point %s is not on the given curve %s\" % (self, curve))\r\n\r\n def __add__(self, other):\r\n if isinstance(other, Ideal):\r\n return self\r\n\r\n x_1, y_1, x_2, y_2 = self.x, self.y, other.x, other.y\r\n\r\n if (x_1, y_1) == (x_2, y_2):\r\n # use the tangent method\r\n ...\r\n else:\r\n if x_1 == x_2:\r\n return Ideal(self.curve) # vertical line\r\n\r\n # Using Vieta's formula for the sum of the roots\r\n m = (y_2 - y_1) / (x_2 - x_1)\r\n x_3 = m * m - x_2 - x_1\r\n y_3 = m * (x_3 - x_1) + y_1\r\n\r\n return Point(self.curve, x_3, -y_3)\r\n","sub_path":"point.py","file_name":"point.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"151872616","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Dialog',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Message',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('text', models.TextField(max_length=2000)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('dialog', models.ForeignKey(related_name='messages', to='dialogs.Dialog')),\n ('sender', models.ForeignKey(related_name='+', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ('-created',),\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='dialog',\n name='last_message',\n field=models.ForeignKey(related_name='+', blank=True, to='dialogs.Message', null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='dialog',\n name='user1',\n field=models.ForeignKey(related_name='+', to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='dialog',\n name='user2',\n field=models.ForeignKey(related_name='+', to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n migrations.AlterUniqueTogether(\n name='dialog',\n unique_together=set([('user1', 'user2')]),\n ),\n ]\n","sub_path":"dialogs/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"288108074","text":"# pylint: disable=invalid-name,too-few-public-methods,too-many-arguments,too-many-locals\nimport random\nfrom copy import deepcopy\nfrom typing import NamedTuple\n\nfrom raiden.constants import EMPTY_HASH, MAXIMUM_PENDING_TRANSFERS\nfrom raiden.settings import DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS\nfrom raiden.tests.utils import events, factories\nfrom raiden.tests.utils.factories import (\n ADDR,\n EMPTY,\n UNIT_REGISTRY_IDENTIFIER,\n UNIT_SECRET,\n UNIT_TOKEN_ADDRESS,\n UNIT_TOKEN_NETWORK_ADDRESS,\n UNIT_TRANSFER_AMOUNT,\n UNIT_TRANSFER_IDENTIFIER,\n UNIT_TRANSFER_INITIATOR,\n UNIT_TRANSFER_TARGET,\n make_transfer_description,\n)\nfrom raiden.transfer import channel\nfrom raiden.transfer.architecture import State\nfrom raiden.transfer.events import (\n EventInvalidReceivedLockExpired,\n EventPaymentSentFailed,\n EventPaymentSentSuccess,\n SendProcessed,\n)\nfrom raiden.transfer.mediated_transfer import initiator, initiator_manager\nfrom raiden.transfer.mediated_transfer.events import (\n CHANNEL_IDENTIFIER_GLOBAL_QUEUE,\n EventUnlockFailed,\n EventUnlockSuccess,\n SendBalanceProof,\n SendLockedTransfer,\n SendLockExpired,\n SendSecretReveal,\n)\nfrom raiden.transfer.mediated_transfer.state import InitiatorPaymentState\nfrom raiden.transfer.mediated_transfer.state_change import (\n ActionCancelRoute,\n ActionInitInitiator,\n ReceiveLockExpired,\n ReceiveSecretRequest,\n ReceiveSecretReveal,\n ReceiveTransferRefundCancelRoute,\n)\nfrom raiden.transfer.state import (\n EMPTY_MERKLE_ROOT,\n HashTimeLockState,\n NettingChannelState,\n RouteState,\n message_identifier_from_prng,\n)\nfrom raiden.transfer.state_change import ActionCancelPayment, Block, ContractReceiveSecretReveal\nfrom raiden.utils import random_secret, typing\n\n\ndef make_initiator_manager_state(\n routes,\n transfer_description,\n channel_map,\n pseudo_random_generator,\n block_number,\n):\n\n init_state_change = ActionInitInitiator(\n transfer_description,\n routes,\n )\n\n inital_state = None\n iteration = initiator_manager.state_transition(\n inital_state,\n init_state_change,\n channel_map,\n pseudo_random_generator,\n block_number,\n )\n\n return iteration.new_state\n\n\nclass InitiatorSetup(NamedTuple):\n current_state: State\n block_number: typing.BlockNumber\n channel: NettingChannelState\n channel_map: typing.ChannelMap\n available_routes: typing.List[RouteState]\n prng: random.Random\n lock: HashTimeLockState\n\n\ndef setup_initiator_tests(\n amount=UNIT_TRANSFER_AMOUNT,\n partner_balance=EMPTY,\n our_address=EMPTY,\n partner_address=EMPTY,\n block_number=1,\n) -> InitiatorSetup:\n \"\"\"Commonly used setup code for initiator manager and channel\"\"\"\n prng = random.Random()\n\n channel1 = factories.make_channel(\n our_balance=amount,\n partner_balance=partner_balance,\n our_address=our_address,\n partner_address=partner_address,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n channel_map = {channel1.identifier: channel1}\n available_routes = [factories.route_from_channel(channel1)]\n current_state = make_initiator_manager_state(\n available_routes,\n factories.UNIT_TRANSFER_DESCRIPTION,\n channel_map,\n prng,\n block_number,\n )\n\n lock = channel.get_lock(\n channel1.our_state,\n current_state.initiator.transfer_description.secrethash,\n )\n setup = InitiatorSetup(\n current_state=current_state,\n block_number=block_number,\n channel=channel1,\n channel_map=channel_map,\n available_routes=available_routes,\n prng=prng,\n lock=lock,\n )\n return setup\n\n\ndef test_next_route():\n amount = UNIT_TRANSFER_AMOUNT\n channel1 = factories.make_channel(\n our_balance=amount,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n channel2 = factories.make_channel(\n our_balance=0,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n channel3 = factories.make_channel(\n our_balance=amount,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n pseudo_random_generator = random.Random()\n\n channel_map = {\n channel1.identifier: channel1,\n channel2.identifier: channel2,\n channel3.identifier: channel3,\n }\n\n available_routes = [\n factories.route_from_channel(channel1),\n factories.route_from_channel(channel2),\n factories.route_from_channel(channel3),\n ]\n\n block_number = 10\n state = make_initiator_manager_state(\n available_routes,\n factories.UNIT_TRANSFER_DESCRIPTION,\n channel_map,\n pseudo_random_generator,\n block_number,\n )\n\n msg = 'an initialized state must use the first valid route'\n assert state.initiator.channel_identifier == channel1.identifier, msg\n assert not state.cancelled_channels\n\n state_change = ActionCancelRoute(\n UNIT_REGISTRY_IDENTIFIER,\n channel1.identifier,\n available_routes,\n )\n iteration = initiator_manager.state_transition(\n state,\n state_change,\n channel_map,\n pseudo_random_generator,\n block_number,\n )\n\n # HOP3 should be ignored because it doesnt have enough balance\n assert iteration.new_state.cancelled_channels == [channel1.identifier]\n\n\ndef test_init_with_usable_routes():\n channel1 = factories.make_channel(\n our_balance=UNIT_TRANSFER_AMOUNT,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n channel_map = {channel1.identifier: channel1}\n available_routes = [factories.route_from_channel(channel1)]\n pseudo_random_generator = random.Random()\n\n init_state_change = ActionInitInitiator(\n factories.UNIT_TRANSFER_DESCRIPTION,\n available_routes,\n )\n\n block_number = 1\n transition = initiator_manager.state_transition(\n None,\n init_state_change,\n channel_map,\n pseudo_random_generator,\n block_number,\n )\n\n assert isinstance(transition.new_state, InitiatorPaymentState)\n assert transition.events, 'we have a valid route, the mediated transfer event must be emitted'\n\n payment_state = transition.new_state\n assert payment_state.initiator.transfer_description == factories.UNIT_TRANSFER_DESCRIPTION\n\n mediated_transfers = [e for e in transition.events if isinstance(e, SendLockedTransfer)]\n assert len(mediated_transfers) == 1, 'mediated_transfer should /not/ split the transfer'\n\n send_mediated_transfer = mediated_transfers[0]\n transfer = send_mediated_transfer.transfer\n expiration = initiator.get_initial_lock_expiration(block_number, channel1.reveal_timeout)\n\n assert transfer.balance_proof.token_network_identifier == channel1.token_network_identifier\n assert transfer.lock.amount == factories.UNIT_TRANSFER_DESCRIPTION.amount\n assert transfer.lock.expiration == expiration\n assert transfer.lock.secrethash == factories.UNIT_TRANSFER_DESCRIPTION.secrethash\n assert send_mediated_transfer.recipient == channel1.partner_state.address\n\n\ndef test_init_without_routes():\n block_number = 1\n routes = []\n pseudo_random_generator = random.Random()\n\n init_state_change = ActionInitInitiator(\n factories.UNIT_TRANSFER_DESCRIPTION,\n routes,\n )\n\n channel_map = dict()\n iteration = initiator_manager.state_transition(\n None,\n init_state_change,\n channel_map,\n pseudo_random_generator,\n block_number,\n )\n\n assert iteration.new_state is None\n\n assert len(iteration.events) == 1\n assert isinstance(iteration.events[0], EventPaymentSentFailed)\n assert iteration.new_state is None\n\n\ndef test_state_wait_secretrequest_valid():\n setup = setup_initiator_tests()\n\n state_change = ReceiveSecretRequest(\n UNIT_TRANSFER_IDENTIFIER,\n setup.lock.amount,\n setup.lock.expiration,\n setup.lock.secrethash,\n UNIT_TRANSFER_TARGET,\n )\n\n iteration = initiator_manager.state_transition(\n setup.current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n\n assert len(iteration.events) == 1\n assert isinstance(iteration.events[0], SendSecretReveal)\n assert iteration.new_state.initiator.received_secret_request is True\n\n state_change_2 = ReceiveSecretRequest(\n UNIT_TRANSFER_IDENTIFIER,\n setup.lock.amount,\n setup.lock.expiration,\n setup.lock.secrethash,\n UNIT_TRANSFER_TARGET,\n )\n\n iteration2 = initiator_manager.state_transition(\n iteration.new_state,\n state_change_2,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n\n assert len(iteration2.events) == 0\n\n\ndef test_state_wait_secretrequest_invalid_amount():\n setup = setup_initiator_tests()\n\n state_change = ReceiveSecretRequest(\n UNIT_TRANSFER_IDENTIFIER,\n setup.lock.amount + 1,\n setup.lock.expiration,\n setup.lock.secrethash,\n UNIT_TRANSFER_TARGET,\n )\n\n iteration = initiator_manager.state_transition(\n setup.current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n\n assert len(iteration.events) == 1\n assert isinstance(iteration.events[0], EventPaymentSentFailed)\n assert iteration.new_state.initiator.received_secret_request is True\n\n state_change_2 = ReceiveSecretRequest(\n UNIT_TRANSFER_IDENTIFIER,\n setup.lock.amount,\n setup.lock.expiration,\n setup.lock.secrethash,\n UNIT_TRANSFER_TARGET,\n )\n\n iteration2 = initiator_manager.state_transition(\n iteration.new_state,\n state_change_2,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n\n assert len(iteration2.events) == 0\n\n\ndef test_state_wait_secretrequest_invalid_amount_and_sender():\n setup = setup_initiator_tests()\n\n state_change = ReceiveSecretRequest(\n UNIT_TRANSFER_IDENTIFIER,\n setup.lock.amount + 1,\n setup.lock.expiration,\n setup.lock.secrethash,\n UNIT_TRANSFER_INITIATOR,\n )\n\n iteration = initiator_manager.state_transition(\n setup.current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n\n assert len(iteration.events) == 0\n assert iteration.new_state.initiator.received_secret_request is False\n\n # Now the proper target sends the message, this should be applied\n state_change_2 = ReceiveSecretRequest(\n UNIT_TRANSFER_IDENTIFIER,\n setup.lock.amount,\n setup.lock.expiration,\n setup.lock.secrethash,\n UNIT_TRANSFER_TARGET,\n )\n\n iteration2 = initiator_manager.state_transition(\n iteration.new_state,\n state_change_2,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n\n assert iteration2.new_state.initiator.received_secret_request is True\n assert isinstance(iteration2.events[0], SendSecretReveal)\n\n\ndef test_state_wait_unlock_valid():\n setup = setup_initiator_tests()\n\n # setup the state for the wait unlock\n setup.current_state.initiator.revealsecret = SendSecretReveal(\n recipient=UNIT_TRANSFER_TARGET,\n channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,\n message_identifier=UNIT_TRANSFER_IDENTIFIER,\n secret=UNIT_SECRET,\n )\n\n state_change = ReceiveSecretReveal(\n secret=UNIT_SECRET,\n sender=setup.channel.partner_state.address,\n )\n iteration = initiator_manager.state_transition(\n setup.current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n\n assert len(iteration.events) == 3\n assert any(isinstance(e, SendBalanceProof) for e in iteration.events)\n assert any(isinstance(e, EventPaymentSentSuccess) for e in iteration.events)\n assert any(isinstance(e, EventUnlockSuccess) for e in iteration.events)\n\n balance_proof = next(e for e in iteration.events if isinstance(e, SendBalanceProof))\n complete = next(e for e in iteration.events if isinstance(e, EventPaymentSentSuccess))\n\n assert balance_proof.recipient == setup.channel.partner_state.address\n assert complete.identifier == UNIT_TRANSFER_IDENTIFIER\n assert iteration.new_state is None, 'state must be cleaned'\n\n\ndef test_state_wait_unlock_invalid():\n setup = setup_initiator_tests()\n identifier = setup.channel.identifier\n target_address = factories.HOP2\n\n # setup the state for the wait unlock\n setup.current_state.initiator.revealsecret = SendSecretReveal(\n recipient=target_address,\n channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,\n message_identifier=identifier,\n secret=UNIT_SECRET,\n )\n\n before_state = deepcopy(setup.current_state)\n\n state_change = ReceiveSecretReveal(\n secret=UNIT_SECRET,\n sender=factories.ADDR,\n )\n iteration = initiator_manager.state_transition(\n setup.current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n\n assert not iteration.events\n assert iteration.new_state == before_state\n\n\ndef test_refund_transfer_next_route():\n amount = UNIT_TRANSFER_AMOUNT\n our_address = factories.ADDR\n refund_pkey, refund_address = factories.make_privkey_address()\n pseudo_random_generator = random.Random()\n\n channel1 = factories.make_channel(\n our_balance=amount,\n partner_balance=amount,\n our_address=our_address,\n partner_address=refund_address,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n channel2 = factories.make_channel(\n our_balance=0,\n our_address=our_address,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n channel3 = factories.make_channel(\n our_balance=amount,\n our_address=our_address,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n\n channel_map = {\n channel1.identifier: channel1,\n channel2.identifier: channel2,\n channel3.identifier: channel3,\n }\n\n available_routes = [\n factories.route_from_channel(channel1),\n factories.route_from_channel(channel2),\n factories.route_from_channel(channel3),\n ]\n\n block_number = 10\n current_state = make_initiator_manager_state(\n available_routes,\n factories.UNIT_TRANSFER_DESCRIPTION,\n channel_map,\n pseudo_random_generator,\n block_number,\n )\n\n original_transfer = current_state.initiator.transfer\n\n refund_transfer = factories.make_signed_transfer(\n amount,\n our_address,\n original_transfer.target,\n original_transfer.lock.expiration,\n UNIT_SECRET,\n payment_identifier=original_transfer.payment_identifier,\n channel_identifier=channel1.identifier,\n pkey=refund_pkey,\n sender=refund_address,\n )\n assert channel1.partner_state.address == refund_address\n\n state_change = ReceiveTransferRefundCancelRoute(\n routes=available_routes,\n transfer=refund_transfer,\n secret=random_secret(),\n )\n\n iteration = initiator_manager.state_transition(\n current_state,\n state_change,\n channel_map,\n pseudo_random_generator,\n block_number,\n )\n assert iteration.new_state is not None\n\n route_cancelled = next(e for e in iteration.events if isinstance(e, EventUnlockFailed))\n new_transfer = next(e for e in iteration.events if isinstance(e, SendLockedTransfer))\n\n assert route_cancelled, 'The previous transfer must be cancelled'\n assert new_transfer, 'No mediated transfer event emitted, should have tried a new route'\n msg = 'the new transfer must use a new secret / secrethash'\n assert new_transfer.transfer.lock.secrethash != refund_transfer.lock.secrethash, msg\n assert iteration.new_state.initiator is not None\n\n\ndef test_refund_transfer_no_more_routes():\n amount = UNIT_TRANSFER_AMOUNT\n refund_pkey, refund_address = factories.make_privkey_address()\n setup = setup_initiator_tests(\n amount=amount,\n partner_balance=amount,\n our_address=UNIT_TRANSFER_INITIATOR,\n partner_address=refund_address,\n )\n\n original_transfer = setup.current_state.initiator.transfer\n refund_transfer = factories.make_signed_transfer(\n amount,\n original_transfer.initiator,\n original_transfer.target,\n original_transfer.lock.expiration,\n UNIT_SECRET,\n payment_identifier=original_transfer.payment_identifier,\n channel_identifier=setup.channel.identifier,\n pkey=refund_pkey,\n sender=refund_address,\n )\n\n state_change = ReceiveTransferRefundCancelRoute(\n routes=setup.available_routes,\n transfer=refund_transfer,\n secret=random_secret(),\n )\n\n iteration = initiator_manager.state_transition(\n setup.current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n current_state = iteration.new_state\n # As per the description of the issue here:\n # https://github.com/raiden-network/raiden/issues/3146#issuecomment-447378046\n # We can fail the payment but can't delete the payment task if there are no\n # more routes, but we have to wait for the lock expiration\n assert iteration.new_state is not None\n\n unlocked_failed = next(e for e in iteration.events if isinstance(e, EventUnlockFailed))\n sent_failed = next(e for e in iteration.events if isinstance(e, EventPaymentSentFailed))\n\n assert unlocked_failed\n assert sent_failed\n\n invalid_balance_proof = factories.make_signed_balance_proof(\n nonce=2,\n transferred_amount=original_transfer.balance_proof.transferred_amount,\n locked_amount=0,\n token_network_address=original_transfer.balance_proof.token_network_identifier,\n channel_identifier=setup.channel.identifier,\n locksroot=EMPTY_MERKLE_ROOT,\n extra_hash=original_transfer.lock.secrethash,\n sender_address=refund_address,\n )\n balance_proof = factories.make_signed_balance_proof(\n nonce=2,\n transferred_amount=original_transfer.balance_proof.transferred_amount,\n locked_amount=0,\n token_network_address=original_transfer.balance_proof.token_network_identifier,\n channel_identifier=setup.channel.identifier,\n locksroot=EMPTY_MERKLE_ROOT,\n extra_hash=original_transfer.lock.secrethash,\n sender_address=refund_address,\n private_key=refund_pkey,\n )\n invalid_lock_expired_state_change = ReceiveLockExpired(\n invalid_balance_proof,\n secrethash=original_transfer.lock.secrethash,\n message_identifier=5,\n )\n lock_expired_state_change = ReceiveLockExpired(\n balance_proof,\n secrethash=original_transfer.lock.secrethash,\n message_identifier=5,\n )\n before_expiry_block = original_transfer.lock.expiration - 1\n expiry_block = original_transfer.lock.expiration + DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS * 2\n\n # a block before lock expiration, no events should be emitted\n current_state = iteration.new_state\n state_change = Block(\n block_number=before_expiry_block,\n gas_limit=1,\n block_hash=factories.make_transaction_hash(),\n )\n iteration = initiator_manager.state_transition(\n current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n expiry_block,\n )\n assert not iteration.events\n assert iteration.new_state, 'payment task should not be deleted at this block'\n\n # process an invalid lock expired message before lock expiration\n current_state = iteration.new_state\n iteration = initiator_manager.state_transition(\n current_state,\n invalid_lock_expired_state_change,\n setup.channel_map,\n setup.prng,\n before_expiry_block,\n )\n assert iteration.new_state, 'payment task should not be deleted at this lock expired'\n # should not be accepted\n assert not events.must_contain_entry(iteration.events, SendProcessed, {})\n assert events.must_contain_entry(iteration.events, EventInvalidReceivedLockExpired, {})\n\n # process a valid lock expired message before lock expiration\n current_state = iteration.new_state\n iteration = initiator_manager.state_transition(\n current_state,\n lock_expired_state_change,\n setup.channel_map,\n setup.prng,\n before_expiry_block,\n )\n assert iteration.new_state, 'payment task should not be deleted at this lock expired'\n # should not be accepted\n assert not events.must_contain_entry(iteration.events, SendProcessed, {})\n\n # now we get to the lock expiration block\n current_state = iteration.new_state\n state_change = Block(\n block_number=expiry_block,\n gas_limit=1,\n block_hash=factories.make_transaction_hash(),\n )\n iteration = initiator_manager.state_transition(\n current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n expiry_block,\n )\n assert events.must_contain_entry(iteration.events, SendLockExpired, {})\n # Since there was a refund transfer the payment task must not have been deleted\n assert iteration.new_state is not None\n\n # process the lock expired message after lock expiration\n current_state = iteration.new_state\n iteration = initiator_manager.state_transition(\n current_state,\n lock_expired_state_change,\n setup.channel_map,\n setup.prng,\n expiry_block,\n )\n # should be accepted\n assert events.must_contain_entry(iteration.events, SendProcessed, {})\n assert iteration.new_state, 'payment task should be there waiting for next block'\n\n # process the the block after lock expiration\n current_state = iteration.new_state\n state_change = Block(\n block_number=expiry_block + 1,\n gas_limit=1,\n block_hash=factories.make_transaction_hash(),\n )\n iteration = initiator_manager.state_transition(\n current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n expiry_block + 1,\n )\n assert iteration.new_state is None, 'from this point on the payment task should go'\n\n\ndef test_cancel_transfer():\n setup = setup_initiator_tests()\n state_change = ActionCancelPayment(\n payment_identifier=UNIT_TRANSFER_IDENTIFIER,\n )\n\n iteration = initiator_manager.state_transition(\n setup.current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n assert iteration.new_state is None\n assert len(iteration.events) == 2\n\n unlocked_failed = next(e for e in iteration.events if isinstance(e, EventUnlockFailed))\n sent_failed = next(e for e in iteration.events if isinstance(e, EventPaymentSentFailed))\n\n assert unlocked_failed\n assert sent_failed\n\n\ndef test_cancelpayment():\n \"\"\" A payment can be cancelled as long as the secret has not been revealed. \"\"\"\n setup = setup_initiator_tests(\n amount=2 * MAXIMUM_PENDING_TRANSFERS * UNIT_TRANSFER_AMOUNT,\n )\n assert isinstance(setup.current_state, InitiatorPaymentState)\n\n iteration = initiator_manager.handle_cancelpayment(\n payment_state=setup.current_state,\n channel_state=setup.channel,\n )\n msg = 'The secret has not been revealed yet, the payment can be cancelled'\n assert iteration.new_state is None, msg\n\n\ndef test_invalid_cancelpayment():\n \"\"\" A payment can *NOT* be cancelled if a secret for any transfer has been\n revealed.\n \"\"\"\n setup = setup_initiator_tests(\n amount=2 * MAXIMUM_PENDING_TRANSFERS * UNIT_TRANSFER_AMOUNT,\n )\n receive_secret_request = ReceiveSecretRequest(\n UNIT_TRANSFER_IDENTIFIER,\n setup.lock.amount,\n setup.lock.expiration,\n setup.lock.secrethash,\n UNIT_TRANSFER_TARGET,\n )\n secret_transition = initiator_manager.state_transition(\n payment_state=setup.current_state,\n state_change=receive_secret_request,\n channelidentifiers_to_channels=setup.channel_map,\n pseudo_random_generator=setup.prng,\n block_number=1,\n )\n\n iteration = initiator_manager.handle_cancelpayment(\n payment_state=secret_transition.new_state,\n channel_state=setup.channel,\n )\n msg = 'The secret *has* been revealed, the payment must not be cancelled'\n assert iteration.new_state is not None, msg\n assert not iteration.events, msg\n\n\ndef test_action_cancel_route_comparison():\n \"\"\"There was a bug in ActionCancelRoute comparison function which we check for\"\"\"\n routes1 = []\n routes2 = [RouteState(ADDR, ADDR)]\n a = ActionCancelRoute(UNIT_TRANSFER_INITIATOR, 5, routes1)\n b = ActionCancelRoute(UNIT_TRANSFER_TARGET, 5, routes1)\n c = ActionCancelRoute(UNIT_TRANSFER_TARGET, 3, routes2)\n d = ActionCancelRoute(UNIT_TRANSFER_TARGET, 3, routes2)\n\n assert a != b\n assert a != c\n assert c == d\n\n\ndef test_init_with_maximum_pending_transfers_exceeded():\n channel1 = factories.make_channel(\n our_balance=2 * MAXIMUM_PENDING_TRANSFERS * UNIT_TRANSFER_AMOUNT,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n channel_map = {channel1.identifier: channel1}\n available_routes = [factories.route_from_channel(channel1)]\n pseudo_random_generator = random.Random()\n\n transitions = list()\n block_number = 1\n for _ in range(MAXIMUM_PENDING_TRANSFERS + 1):\n init_state_change = ActionInitInitiator(make_transfer_description(), available_routes)\n transitions.append(initiator_manager.state_transition(\n None,\n init_state_change,\n channel_map,\n pseudo_random_generator,\n block_number,\n ))\n\n failed_transition = transitions.pop()\n assert all(\n isinstance(transition.new_state, InitiatorPaymentState)\n for transition in transitions\n )\n\n assert failed_transition.new_state is None\n assert len(failed_transition.events) == 1\n assert isinstance(failed_transition.events[0], EventPaymentSentFailed)\n\n\ndef test_handle_offchain_secretreveal():\n setup = setup_initiator_tests()\n\n secret_reveal = ReceiveSecretReveal(\n secret=UNIT_SECRET,\n sender=setup.channel.partner_state.address,\n )\n message_identifier = message_identifier_from_prng(deepcopy(setup.prng))\n iteration = initiator.handle_offchain_secretreveal(\n initiator_state=setup.current_state.initiator,\n state_change=secret_reveal,\n channel_state=setup.channel,\n pseudo_random_generator=setup.prng,\n )\n\n payment_identifier = setup.current_state.initiator.transfer_description.payment_identifier\n assert events.must_contain_entry(iteration.events, SendBalanceProof, {\n 'message_identifier': message_identifier,\n 'payment_identifier': payment_identifier,\n })\n\n\ndef test_handle_offchain_emptyhash_secret():\n setup = setup_initiator_tests(block_number=10)\n\n secret_reveal = ReceiveSecretReveal(\n secret=EMPTY_HASH,\n sender=setup.channel.partner_state.address,\n )\n iteration = initiator.handle_offchain_secretreveal(\n initiator_state=setup.current_state.initiator,\n state_change=secret_reveal,\n channel_state=setup.channel,\n pseudo_random_generator=setup.prng,\n )\n secrethash = factories.UNIT_TRANSFER_DESCRIPTION.secrethash\n assert len(iteration.events) == 0\n # make sure the lock has not moved\n assert secrethash in setup.channel.our_state.secrethashes_to_lockedlocks\n\n\ndef test_initiator_lock_expired():\n amount = UNIT_TRANSFER_AMOUNT * 2\n\n channel1 = factories.make_channel(\n our_balance=amount,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n channel2 = factories.make_channel(\n our_balance=0,\n token_address=UNIT_TOKEN_ADDRESS,\n token_network_identifier=UNIT_TOKEN_NETWORK_ADDRESS,\n )\n pseudo_random_generator = random.Random()\n\n channel_map = {\n channel1.identifier: channel1,\n channel2.identifier: channel2,\n }\n\n available_routes = [\n factories.route_from_channel(channel1),\n factories.route_from_channel(channel2),\n ]\n\n block_number = 10\n transfer_description = factories.make_transfer_description(\n secret=UNIT_SECRET,\n payment_network_identifier=channel1.payment_network_identifier,\n )\n current_state = make_initiator_manager_state(\n available_routes,\n transfer_description,\n channel_map,\n pseudo_random_generator,\n block_number,\n )\n\n transfer = current_state.initiator.transfer\n\n assert transfer.lock.secrethash in channel1.our_state.secrethashes_to_lockedlocks\n\n # Trigger lock expiry\n state_change = Block(\n block_number=transfer.lock.expiration + DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS * 2,\n gas_limit=1,\n block_hash=factories.make_transaction_hash(),\n )\n\n iteration = initiator_manager.state_transition(\n current_state,\n state_change,\n channel_map,\n pseudo_random_generator,\n block_number,\n )\n\n assert events.must_contain_entry(iteration.events, SendLockExpired, {\n 'balance_proof': {\n 'nonce': 2,\n 'transferred_amount': 0,\n 'locked_amount': 0,\n },\n 'secrethash': transfer.lock.secrethash,\n 'recipient': channel1.partner_state.address,\n })\n # Since the lock expired make sure we also get the payment sent failed event\n assert events.must_contain_entry(iteration.events, EventPaymentSentFailed, {\n 'payment_network_identifier': channel1.payment_network_identifier,\n 'token_network_identifier': channel1.token_network_identifier,\n 'identifier': UNIT_TRANSFER_IDENTIFIER,\n 'target': transfer.target,\n 'reason': \"transfer's lock has expired\",\n })\n\n assert transfer.lock.secrethash not in channel1.our_state.secrethashes_to_lockedlocks\n msg = 'the initiator payment task must be deleted at block of the lock expiration'\n assert not iteration.new_state, msg\n\n # Create 2 other transfers\n transfer2_state = make_initiator_manager_state(\n available_routes,\n make_transfer_description('transfer2'),\n channel_map,\n pseudo_random_generator,\n 30,\n )\n transfer2_lock = transfer2_state.initiator.transfer.lock\n\n transfer3_state = make_initiator_manager_state(\n available_routes,\n make_transfer_description('transfer3'),\n channel_map,\n pseudo_random_generator,\n 32,\n )\n\n transfer3_lock = transfer3_state.initiator.transfer.lock\n\n assert len(channel1.our_state.secrethashes_to_lockedlocks) == 2\n\n assert transfer2_lock.secrethash in channel1.our_state.secrethashes_to_lockedlocks\n\n expiration_block_number = transfer2_lock.expiration + DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS * 2\n\n block = Block(\n block_number=expiration_block_number,\n gas_limit=1,\n block_hash=factories.make_transaction_hash(),\n )\n iteration = initiator_manager.state_transition(\n transfer2_state,\n block,\n channel_map,\n pseudo_random_generator,\n expiration_block_number,\n )\n\n # Transfer 2 expired\n assert transfer2_lock.secrethash not in channel1.our_state.secrethashes_to_lockedlocks\n\n # Transfer 3 is still there\n assert transfer3_lock.secrethash in channel1.our_state.secrethashes_to_lockedlocks\n\n\ndef test_initiator_handle_contract_receive_secret_reveal():\n \"\"\" Initiator must unlock off-chain if the secret is revealed on-chain and\n the channel is open.\n \"\"\"\n setup = setup_initiator_tests(amount=UNIT_TRANSFER_AMOUNT * 2, block_number=10)\n\n transfer = setup.current_state.initiator.transfer\n assert transfer.lock.secrethash in setup.channel.our_state.secrethashes_to_lockedlocks\n\n state_change = ContractReceiveSecretReveal(\n transaction_hash=factories.make_transaction_hash(),\n secret_registry_address=factories.make_address(),\n secrethash=transfer.lock.secrethash,\n secret=UNIT_SECRET,\n block_number=transfer.lock.expiration,\n )\n\n message_identifier = message_identifier_from_prng(deepcopy(setup.prng))\n\n iteration = initiator_manager.handle_onchain_secretreveal(\n payment_state=setup.current_state,\n state_change=state_change,\n channelidentifiers_to_channels=setup.channel_map,\n pseudo_random_generator=setup.prng,\n )\n\n payment_identifier = setup.current_state.initiator.transfer_description.payment_identifier\n assert events.must_contain_entry(iteration.events, SendBalanceProof, {\n 'message_identifier': message_identifier,\n 'payment_identifier': payment_identifier,\n })\n\n\ndef test_initiator_handle_contract_receive_emptyhash_secret_reveal():\n \"\"\" Initiator must not accept contract receive secret reveal with emptyhash\n \"\"\"\n setup = setup_initiator_tests(amount=UNIT_TRANSFER_AMOUNT * 2, block_number=10)\n\n transfer = setup.current_state.initiator.transfer\n assert transfer.lock.secrethash in setup.channel.our_state.secrethashes_to_lockedlocks\n\n state_change = ContractReceiveSecretReveal(\n transaction_hash=factories.make_transaction_hash(),\n secret_registry_address=factories.make_address(),\n secrethash=transfer.lock.secrethash,\n secret=EMPTY_HASH,\n block_number=transfer.lock.expiration,\n )\n\n iteration = initiator_manager.handle_onchain_secretreveal(\n payment_state=setup.current_state,\n state_change=state_change,\n channelidentifiers_to_channels=setup.channel_map,\n pseudo_random_generator=setup.prng,\n )\n assert len(iteration.events) == 0\n # make sure the original lock wasn't moved\n assert transfer.lock.secrethash in setup.channel.our_state.secrethashes_to_lockedlocks\n\n\ndef test_initiator_handle_contract_receive_secret_reveal_expired():\n \"\"\" Initiator must *not* unlock off-chain if the secret is revealed\n on-chain *after* the lock expiration.\n \"\"\"\n setup = setup_initiator_tests(amount=UNIT_TRANSFER_AMOUNT * 2, block_number=10)\n\n transfer = setup.current_state.initiator.transfer\n assert transfer.lock.secrethash in setup.channel.our_state.secrethashes_to_lockedlocks\n\n state_change = ContractReceiveSecretReveal(\n transaction_hash=factories.make_transaction_hash(),\n secret_registry_address=factories.make_address(),\n secrethash=transfer.lock.secrethash,\n secret=UNIT_SECRET,\n block_number=transfer.lock.expiration + 1,\n )\n\n iteration = initiator_manager.handle_onchain_secretreveal(\n payment_state=setup.current_state,\n state_change=state_change,\n channelidentifiers_to_channels=setup.channel_map,\n pseudo_random_generator=setup.prng,\n )\n\n assert events.must_contain_entry(iteration.events, SendBalanceProof, {}) is None\n\n\ndef test_lock_expiry_updates_balance_proof():\n setup = setup_initiator_tests(amount=UNIT_TRANSFER_AMOUNT * 2, block_number=10)\n\n transfer = setup.current_state.initiator.transfer\n assert transfer.lock.secrethash in setup.channel.our_state.secrethashes_to_lockedlocks\n\n nonce_before_lock_expiry = setup.channel.our_state.balance_proof.nonce\n\n # Trigger lock expiry\n state_change = Block(\n block_number=transfer.lock.expiration + DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS * 2,\n gas_limit=1,\n block_hash=factories.make_transaction_hash(),\n )\n\n initiator_manager.state_transition(\n setup.current_state,\n state_change,\n setup.channel_map,\n setup.prng,\n setup.block_number,\n )\n\n balance_proof = setup.channel.our_state.balance_proof\n assert balance_proof.nonce == nonce_before_lock_expiry + 1\n assert balance_proof.transferred_amount == 0\n assert balance_proof.locked_amount == 0\n","sub_path":"raiden/tests/unit/transfer/mediated_transfer/test_initiatorstate.py","file_name":"test_initiatorstate.py","file_ext":"py","file_size_in_byte":36670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47050604","text":"#!/usr/bin/env python\n\nimport sys\nimport numpy as np\nimport pysam\nimport argparse\nimport collections\nfrom sklearn.cluster import DBSCAN\n# import hdbscan\n\ndef parse_args(args):\n parser = argparse.ArgumentParser('Identify transposon flanking regions')\n parser.add_argument('input_bam')\n# parser.add_argument('-a', '--min_coverage', type=int, default=4,\n# help=(\"Minimal coverage for a family to be \"\n# \"exported as a peak - the number \"\n# \"checked is the maximal coverage for \"\n# \"that set of mapping reads. (default 4)\"))\n parser.add_argument('-s', '--stringency', type=int, default=5,\n help=(\"Stringency to determine if a hit maps \"\n \"uniquely. This score is the \"\n \"minimal allowed difference between the \"\n \"scores of the first and second \"\n \"hit before a read is assumed to be \"\n \"mapped to it's correct, unique, \"\n \"location. (default=5)\"))\n# parser.add_argument('-c', '--trim_cov', type=float, default=3.,\n# help=(\"Minimal coverage of a read region \"\n# \"that is considered part of the \"\n# \"peak. This number is used to trim \"\n# \"trailing edges from a peak, or, if \"\n# \"necessary to cut a peak into an \"\n# \"number of smaller peaks. Note, if you \"\n# \"set a value below 0, it will be \"\n# \"interpreted as a fraction of the \"\n# \"maximal coverage observed for that \"\n# \"peak. (default: 3)\"))\n# parser.add_argument('-C', '--min_trim_cov', type=int, default=3,\n# help=(\"When using a fraction for -c, this \"\n# \"value sets a lower limit - anything \"\n# \"below this value will be trimmed \"\n# \"for sure. (default 3)\"))\n# parser.add_argument('-q', '--output_nonunique',\n# action='store_true', default=False,\n# help=(\"also output peaks which are no likely \"\n# \"to be uniquely mapped\"))\n parser.add_argument('--eps', type=int, default=100,\n help=(\"When using the DBSCAN method to identify \"\n \"read clusters, eps is the minimum distance \"\n \"allowable between two points for inclusion \"\n \"in the the same neighbourhood\"))\n parser.add_argument('--min_tips', type=int, default=5,\n help=(\"When using the DBSCAN method to identify \"\n \"read clusters, min_tips is the minimum number \"\n \"of read tips found in a single neighbourhood \"\n \"in order to count as a cluster\"))\n return parser.parse_args(args)\n\n\n# def extract_clusters(sam):\n# \"\"\"\n# Extracts all clusters of overlapping reads from a sorted, indexed pysam object.\n# Generates a dictionary per cluster.\n# Accepts a pysam object.\n# Returns a dictionary generator.\n# \"\"\"\n#\n# cluster = {\"reads\": [],\n# \"reference\": \"\",\n# \"start\": -1,\n# \"stop\": -1}\n#\n# for i, read in enumerate(sam.fetch()):\n# read_reference = sam.getrname(read.tid)\n# read_start = read.pos\n# read_stop = read.pos + read.qlen\n#\n# # if read overlaps the current cluster\n# if (read_reference == cluster[\"reference\"]) and (read_start < cluster[\"stop\"]):\n#\n# # add the read to the current cluster\n# cluster[\"reads\"].append(read)\n# cluster[\"stop\"] = read_stop\n#\n# # else read is the start of a new cluster\n# else:\n#\n# # yield the previous cluster but skip the first blank cluster\n# if i > 0:\n# yield cluster\n#\n# # create a new cluster dictionary based on the current read\n# cluster[\"reads\"] = [read]\n# cluster[\"reference\"] = read_reference\n# cluster[\"start\"] = read_start\n# cluster[\"stop\"] = read_stop\n#\n# # ensure the final cluster is not skipped\n# yield cluster\n\n\ndef extract_references(sam):\n \"\"\"\n Takes a sam object and returns a cluster-dictionary per reference.\n Accepts a pysam object.\n Returns a dictionary generator.\n \"\"\"\n for reference, length in zip(sam.references, sam.lengths):\n cluster = {\"reads\": list(sam.fetch(reference)),\n \"reference\": reference,\n \"start\": 0,\n \"stop\": int(length)}\n yield cluster\n\n\ndef sub_cluster(parent_cluster, read_subset, **kwargs):\n \"\"\"\n Returns a modified cluster with a subset of the original reads.\n Additional parameters can be added as **kwargs.\n Accepts a dictionary\n Returns a dictionary\n \"\"\"\n child_cluster = {}\n\n # avoid passing reference to parent cluster or parent clusters reads\n for key in parent_cluster:\n if key == \"reads\":\n pass\n else:\n child_cluster[key] = parent_cluster[key]\n\n # add new attributes passed as kwargs to child cluster\n for key, value in kwargs.items():\n child_cluster[key] = value\n\n # add the explicitly passed reads to child cluster\n child_cluster[\"reads\"] = read_subset\n\n return child_cluster\n\n\n# def split_gaps(cluster_generator):\n# \"\"\"\n# Subdivides read-clusters based on gaps between non-overlapping reads.\n# Accepts a dictionary generator.\n# Returns a dictionary generator.\n# \"\"\"\n# for parent_cluster in cluster_generator:\n#\n# # Dummy cluster for comparison with initial read\n# child_cluster = {\"start\": -1, \"stop\": -1}\n#\n# for i, read in enumerate(parent_cluster[\"reads\"]):\n# read_start = read.pos\n# read_stop = read.pos + read.qlen\n#\n# # if read overlaps the current cluster\n# if read_start < child_cluster[\"stop\"]:\n#\n# # add the read to the current cluster\n# child_cluster[\"reads\"].append(read)\n# child_cluster[\"stop\"] = read_stop\n#\n# # else read is the start of a new cluster\n# else:\n#\n# # yield the previous cluster but skip the first dummy cluster\n# if i > 0:\n#\n# yield child_cluster\n#\n# # create a new cluster dictionary based on the current read\n# child_cluster = sub_cluster(parent_cluster, [read])\n# child_cluster[\"start\"] = min([read.pos for read in child_cluster[\"reads\"]])\n# child_cluster[\"stop\"] = max([(read.pos + read.qlen) for read in child_cluster[\"reads\"]])\n#\n# # ensure the final cluster is not skipped\n# yield child_cluster\n\n\ndef split_families(cluster_generator):\n \"\"\"\n Subdivides read-clusters based on read family.\n Accepts a dictionary generator.\n Returns a dictionary generator.\n \"\"\"\n for parent_cluster in cluster_generator:\n families = collections.defaultdict(list)\n for read in parent_cluster[\"reads\"]:\n try:\n family = read.qname.split('__')[0].rsplit('/', 1)[1]\n except IndexError:\n family = read.qname.split('__')[0]\n families[family].append(read)\n\n for family, reads in families.items():\n child_cluster = sub_cluster(parent_cluster, reads, family=family)\n yield child_cluster\n\n\ndef split_orientation(cluster_generator):\n \"\"\"\n Subdivides read-clusters based on read orientation.\n Accepts a dictionary generator.\n Returns a dictionary generator.\n \"\"\"\n for parent_cluster in cluster_generator:\n orientations = {\"+\": [],\n \"-\": []}\n for read in parent_cluster[\"reads\"]:\n if read.is_reverse:\n orientations[\"-\"].append(read)\n else:\n orientations[\"+\"].append(read)\n\n for orientation, reads in orientations.items():\n if len(reads) > 0:\n child_cluster = sub_cluster(parent_cluster, reads, orientation=orientation)\n yield child_cluster\n\n\ndef filter_unique(cluster_generator, args):\n \"\"\"\n Filters read-clusters by the amount of uniquely mapped reads.\n threshold=args.min_diff\n Accepts a dictionary generator.\n Returns a dictionary generator.\n \"\"\"\n for parent_cluster in cluster_generator:\n unique_reads = []\n for read in parent_cluster[\"reads\"]:\n tag_as = -999\n tag_xs = -999\n for tag in read.tags:\n if tag[0] == 'AS':\n tag_as = tag[1]\n if tag[0] == 'XS':\n tag_xs = tag[1]\n\n score = tag_as - tag_xs\n if score >= args.stringency:\n unique_reads.append(read)\n else:\n pass\n\n if len(unique_reads) > 0:\n child_cluster = sub_cluster(parent_cluster, unique_reads, read_type='UNIQUE')\n yield child_cluster\n\n\n# def filter_depth(cluster_generator, threshold):\n# \"\"\"\n# Filters read-clusters based on maximum read depth.\n# Accepts a dictionary generator.\n# Returns a dictionary generator.\n# \"\"\"\n# pass\n\n\ndef read_depth(cluster):\n \"\"\"\n Calculates the read depth of a cluster.\n Accepts a dictionary.\n Returns an array.\n \"\"\"\n depth = np.zeros((cluster[\"stop\"] - cluster[\"start\"]))\n for read in cluster[\"reads\"]:\n depth[(read.pos - cluster[\"start\"]):(read.pos + read.qlen - cluster[\"start\"])] += 1\n return depth\n\n\ndef read_tips(cluster):#\n \"\"\"\n Returns the read end positions of a cluster based on orientation.\n Returns right tip of forwards reads and left tip of reverse reads\n Accepts a dictionary.\n Returns an array.\n \"\"\"\n tips = np.zeros(len(cluster[\"reads\"]))\n count = 0\n for read in cluster[\"reads\"]:\n if read.is_reverse:\n tips[count] = read.pos\n else:\n tips[count] = read.pos + read.qlen\n count += 1\n return tips.astype(np.int)\n\n\n# def group_clusters(cluster_generator, *args):\n# \"\"\"\n# Groups cluster-dictionaries by unique combinations of values for an arbitrary number of keys.\n# Groups are dictionaries that contain a list of clusters and the key value pairs used to categorise them.\n# Accepts a dictionary generator.\n# Returns a dictionary generator.\n# \"\"\"\n# groups = {}\n# for cluster in cluster_generator:\n# group = '_'.join([cluster[key] for key in args])\n# if group not in groups:\n# groups[group] = {\"clusters\": []}\n# for key in args:\n# groups[group][key] = cluster[key]\n# groups[group][\"clusters\"].append(cluster)\n# for key, values in groups.items():\n# yield values\n\n\n# def identify_features_by_std(cluster_generator, *args):\n# \"\"\"\n# Identifies features by identifying loci with a read depth of two standard deviations above the mean.\n# Clusters are grouped together by a combination attributes as specified by *args.\n# This allows for calculating the mean and standard deviation across multiple references.\n# Accepts a dictionary generator.\n# Returns a dictionary generator.\n# \"\"\"\n# group_generator = group_clusters(cluster_generator, *args)\n# for group in group_generator:\n# group[\"depth\"] = np.empty(0, dtype = int)\n# for cluster in group[\"clusters\"]:\n# cluster[\"depth\"] = read_depth(cluster)\n# group[\"depth\"] = np.concatenate((group[\"depth\"], cluster[\"depth\"]))\n# group[\"mean\"] = group[\"depth\"].mean()\n# group[\"std\"] = group[\"depth\"].std()\n# group[\"threshold\"] = group[\"mean\"] + (2 * group[\"std\"])\n# for cluster in group[\"clusters\"]:\n# cluster[\"threshold\"] = group[\"threshold\"]\n# cluster[\"feature\"] = cluster[\"depth\"] > cluster[\"threshold\"]\n# yield cluster\n\n\n# def identify_features_by_cov(cluster_generator, args):\n# \"\"\"\n# Identifies features that are over a minimum threshold depth in args\n# :param cluster_generator: a dictionary generator\n# :param args: command line arguments\n# :return: a dictionary generator\n# \"\"\"\n# threshold = args.trim_cov\n# for cluster in cluster_generator:\n# cluster[\"depth\"] = read_depth(cluster)\n# cluster[\"feature\"] = cluster[\"depth\"] > threshold\n# yield cluster\n\n\ndef identify_features_by_dbscan(cluster_generator, args):\n \"\"\"\n Identifies features based on a DBSCAN clustering algorithm on tip positions\n :param args: command line arguments\n :param cluster_generator: a dictionary generator\n :return: a dictionary generator\n \"\"\"\n for cluster in cluster_generator:\n tips = read_tips(cluster).astype(np.int)\n input_tips = np.array(zip(tips, np.zeros(len(tips))), dtype=np.int)\n dbscan = DBSCAN(eps=args.eps, min_samples=args.min_tips).fit(input_tips)\n cluster[\"feature\"] = np.zeros((cluster[\"stop\"] - cluster[\"start\"]), dtype=bool)\n labels = dbscan.labels_.astype(np.int)\n groups = np.unique(labels)\n groups = groups[groups >= 0]\n for group in groups:\n group_tips = tips[labels == group]\n cluster[\"feature\"][min(group_tips) - 1: max(group_tips)] = True\n cluster[\"depth\"] = read_depth(cluster)\n yield cluster\n\n\n# def identify_features_by_hdbscan(cluster_generator, min_tips=5):\n# \"\"\"\n# Identifies features based on a DBSCAN clustering algorithm on tip positions\n# :param eps: maximum distance between read tips to be considered in the same neighbourhood\n# :param min_tips: minimum number of tips in a neighbourhood to count as a feature\n# :param cluster_generator: a dictionary generator\n# :return: a dictionary generator\n# \"\"\"\n# for cluster in cluster_generator:\n# if (len(cluster[\"reads\"])) < min_tips:\n# continue\n# tips = read_tips(cluster)\n# input_tips = np.array(zip(tips, np.zeros(len(tips))), dtype=np.int)\n# hdb = hdbscan.HDBSCAN(min_cluster_size=min_tips)\n# cluster[\"feature\"] = np.zeros((cluster[\"stop\"] - cluster[\"start\"]), dtype=bool)\n# labels = hdb.fit_predict(input_tips).astype(np.int)\n# groups = np.unique(labels)\n# groups = groups[groups >= 0]\n# for group in groups:\n# group_tips = tips[labels == group]\n# cluster[\"feature\"][min(group_tips) - 1: max(group_tips)] = True\n# cluster[\"depth\"] = read_depth(cluster)\n# yield cluster\n\n\ndef extract_features(cluster_generator):\n \"\"\"\n Extracts features for a gff file from clusters based of the feature attribute-array.\n Features are returned as dictionaries with start and stop attributes and inherit other attributes\n from their parent cluster.\n Accepts a dictionary generator.\n Returns a dictionary generator.\n \"\"\"\n for cluster in cluster_generator:\n\n feature = {\"start\": 0, \"stop\": 0, \"mean_depth\": 0}\n for key in cluster:\n if key not in [\"reads\", \"start\", \"stop\", \"feature\", \"depth\"]:\n feature[key] = cluster[key]\n else:\n pass\n\n # determine position of features\n previously_in_feature = False\n for position, currently_in_feature in enumerate(cluster[\"feature\"]):\n\n if not previously_in_feature and currently_in_feature:\n # start of a feature\n previously_in_feature = True\n feature[\"start\"] = position + 1\n\n elif previously_in_feature and not currently_in_feature:\n # end of a feature\n previously_in_feature = False\n feature[\"stop\"] = position\n feature[\"mean_depth\"] = cluster[\"depth\"][feature[\"start\"] - 1: feature[\"stop\"]].mean()\n feature[\"depth\"] = cluster[\"depth\"][feature[\"start\"] - 1: feature[\"stop\"]]\n yield feature\n\n\ndef format_features(feature_generator):\n \"\"\"\n Formats feature dictionaries as strings for a gff file.\n Accepts a dictionary generator.\n Returns a string generator.\n \"\"\"\n for feature in feature_generator:\n formated = \"\\t\".join([feature[\"reference\"],\n \"REFS\",\n \"REFS.\" + feature[\"read_type\"] + \".\" + feature[\"family\"],\n str(feature[\"start\"]),\n str(feature[\"stop\"]),\n str(feature[\"mean_depth\"]),\n feature[\"orientation\"],\n \".\",\n \"ID=reps\" + feature[\"reference\"] + str(feature[\"start\"]) +\n feature[\"family\"] + \";Name=\" + feature[\"family\"]])\n yield formated\n\n\ndef output_features(formatted_features):\n for feature in formatted_features:\n print(feature)\n\n\ndef trim_clusters():\n \"\"\"\n Trims read-clusters based on a read depth.\n Accepts a dictionary generator.\n Returns a dictionary generator.\n \"\"\"\n pass\n\n\ndef construct_gff():\n \"\"\"\n Accepts a dictionary generator.\n Prints a gff file to standard out.\n \"\"\"\n pass\n\n\ndef main():\n args = parse_args(sys.argv[1:])\n sam = pysam.Samfile(args.input_bam, 'rb')\n cluster_generator = extract_references(sam)\n cluster_generator = split_families(cluster_generator)\n cluster_generator = split_orientation(cluster_generator)\n cluster_generator = filter_unique(cluster_generator, args)\n cluster_generator = identify_features_by_dbscan(cluster_generator, args)\n feature_generator = extract_features(cluster_generator)\n formatted_features = format_features(feature_generator)\n output_features(formatted_features)\n\n\nif __name__ == '__main__':\n main()","sub_path":"lf_regionify2.py","file_name":"lf_regionify2.py","file_ext":"py","file_size_in_byte":18312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"5367547","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Date : 2018-05-11 13:28:56\n# @Author : Wangjojo (wangjojo1995@gmail.com)\nfrom .models import *\n\nimport xadmin\nfrom xadmin import views\n\nclass BaseSetting(object):\n '''\n '''\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object):\n site_title = 'jojo的管理系统'\n site_footer = 'jojo在线'\n\n menu_style = 'accordion'\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['code','email','send_type','send_time']\n search_fields = ['code','email','send_type']\n list_filter = ['code','email','send_type','send_time']\n\n\nclass BannerAdmin(object):\n list_display = ['index','title','image','url','add_time']\n search_fields = ['index','title','image','url']\n list_filter = ['index','title','image','url','add_time']\n\n\nxadmin.site.register(views.BaseAdminView,BaseSetting)\nxadmin.site.register(views.CommAdminView,GlobalSettings)\nxadmin.site.register(EmailVerifyRecord,EmailVerifyRecordAdmin)\nxadmin.site.register(Banner,BannerAdmin)","sub_path":"blogsite/apps/users/adminx.py","file_name":"adminx.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"353631966","text":"import os\nimport sys\nimport subprocess\nimport importlib\nimport scadnano as sc\n\n\ndef main():\n for filename in os.listdir(\".\"):\n if filename.endswith(\".py\") and not sys.argv[0].endswith(filename):\n print(f\"running {filename}\")\n run(filename)\n\n\ndef run(filename):\n if not filename.endswith('.py'):\n print(f\" filename {filename} does not end with '.py'; skipping\")\n return\n modulename = filename[:-3]\n print(f' importing module {modulename}')\n module = importlib.import_module(modulename)\n if hasattr(module, \"main\"):\n print(f\" found main function in module {modulename}; running it and writing its output\")\n design: sc.Design = module.create_design()\n design.write_scadnano_file(directory='output_designs',\n filename=modulename + f'.{sc.default_scadnano_file_extension}')\n else:\n print(f\" found no main function in module {modulename}; running as subprocess instead\")\n try:\n retcode = subprocess.call(f\"python {filename}\", shell=True)\n if retcode < 0:\n print(\"Child was terminated by signal\", -retcode, file=sys.stderr)\n except OSError as e:\n print(\"Execution failed:\", e, file=sys.stderr)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"web/examples/run_all_examples.py","file_name":"run_all_examples.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"559261390","text":"# fastai libraries\nfrom fastai.vision import *\nfrom fastai.callbacks.hooks import *\nfrom fastai.utils.mem import *\nfrom fastai.callbacks import EarlyStoppingCallback\n\n# functions that alter data into format that is usable for deep learning\nimport pandas as pd\nimport numpy as np\nimport random\nimport os\nimport torch\n\ndef dataset_setup(train_df, valid_df, seed, sample_perc = 0.05):\n '''function that prepares dataset for training'''\n # create lists of u-one and u-zero features (according to performance in paper)\n u_one_features = ['Atelectasis', 'Edema', 'Pleural Effusion']\n u_zero_features = ['Cardiomegaly', 'Consolidation']\n # create valid column indicating if observation is part of training or validation set\n train_df['valid'] = False\n valid_df['valid'] = True\n # create patient and study columns\n train_df['patient'] = train_df['Path'].str.split('/', 3, True)[2]\n train_df['study'] = train_df['Path'].str.split('/', 4, True)[3]\n # do the same for the validation set\n valid_df['patient'] = valid_df['Path'].str.split('/', 3, True)[2]\n valid_df['study'] = valid_df['Path'].str.split('/', 4, True)[3]\n # combine train_df and valid_df\n full_df = pd.concat([train_df, valid_df])\n \n def feature_string(row):\n '''function that determines what pathologies are present for each observation'''\n feature_list = []\n for feature in u_one_features:\n if row[feature] in [-1,1]:\n feature_list.append(feature)\n \n for feature in u_zero_features:\n if row[feature] == 1:\n feature_list.append(feature)\n \n return ';'.join(feature_list)\n \n # apply feature_string function to full_df to extract pathologies for each observation\n full_df['feature_string'] = full_df.apply(feature_string, axis=1).fillna('')\n \n # the following functions seed the data and then gather a sample of CheXpert data set (allows for faster iteration)\n def seed_everything(seed):\n '''function that seeds data according to user input'''\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n \n def sample_chexpert(sample_perc):\n '''function that gathers a sample data set according to seed'''\n train_only_df = full_df[~full_df['valid']]\n valid_only_df = full_df[full_df['valid']]\n unique_patients = train_only_df['patient'].unique()\n mask = np.random.rand(len(unique_patients)) <= sample_perc\n sample_patients = unique_patients[mask]\n \n # gather sample_df\n sample_df = train_only_df[train_df['patient'].isin(sample_patients)]\n full_sample_df = pd.concat([sample_df, valid_only_df])\n \n return full_sample_df\n \ndef get_src(df = full_df):\n return (ImageList.from_df(df, data_path, 'Path').split_from_df('valid')\n .label_from_df('feature_string',label_delim=';'))\n \ndef get_data(size, src, bs=16):\n return (src.transform(get_transforms(do_flip=False), size=size, padding_mode='zeros')\n .databunch(bs=bs).normalize(imagenet_stats))","sub_path":"capstone_2/capstone/multiclass.py","file_name":"multiclass.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"175405679","text":"print(\"\\n \\n \\t Seleccione una operacion: \\n1: Suma \\n2: Resta\\n3: Division \\n4: multiplicacion\\n5: Datos \\n6: multiplicacion de la clase \\n7: salir \\n0:Comapar dos numeros\")\r\n\r\nx=input(\"\\n \\n \\t Opcion: \")\r\nif x == '1' :\r\n print(\"\\n\\t Suma\")\r\n num1=float(input(\"Dame un numero: \"))\r\n num2=float(input(\"Dame otro numero: \"))\r\n resultado=num1+num2\r\n print(\"El resultado es:\",resultado)\r\n input(\"........\"),\r\nelif x == '2' :\r\n print(\"\\n \\t Resta\")\r\n num1=float(input(\"Dame un numero: \"))\r\n num2=float(input(\"Dame otro numero: \"))\r\n resultado=num1-num2\r\n print(\"El resultado es:\",resultado)\r\n input(\"........\"),\r\nelif x == '3' :\r\n print(\"\\n \\t Division\")\r\n num1=float(input(\"Dame un numero: \"))\r\n num2=float(input(\"Dame otro numero: \"))\r\n resultado=num1/num2\r\n print(\"El resultado es:\",resultado)\r\n input(\"........\"),\r\nelif x == '4' :\r\n print(\"\\n \\t Multiplicacion\")\r\n num1=float(input(\"Dame un numero: \"))\r\n num2=float(input(\"Dame otro numero: \"))\r\n resultado=num1+num2\r\n print(\"El resultado es:\",resultado)\r\n input(\"........\"),\r\nelif x == '5' :\r\n print(\"\\n \\t Ingresa tus DATOS \")\r\n nom=input(\"Nombre: \")\r\n edad=float(input(\"Edad: \"))\r\n peso=float(input(\"Peso: \"))\r\n print(\"tu nombre es\",nom,\"tienes \",edad,\"tu peso es \",peso)\r\n input(\"........\"),\r\nelif x == '6' :\r\n print(\"\\n \\t Tablas de multiplicar\")\r\n numero=int(input(\"De que tabla sera?:\"))\r\n vecez=int(input(\"Cuantas tablas?:\"))\r\n for x in range (0,vecez):\r\n print(numero,\"*\",x+1,\"=\",numero*(x+1))\r\n\r\n input(\"....\")\r\nelif x == '7' :\r\n print(\"\\n \\t Saliendo\")\r\n input(\"........\"),\r\nelif x == '0' :\r\n print(\"Son los numeros iguales?\")\r\n num1=float(input(\"Dame un numero: \"))\r\n num2=float(input(\"Dame otro numero: \"))\r\n if num1 == num2:\r\n print(\"Los numeros son iguales.\")\r\n elif num1 < num2:\r\n print(num1,\" Es menor\")\r\n elif num1 > num2:\r\n print(num1,\" Es mayor\")\r\n else:\r\n print(\"kkkkkkkkkkkkk\")\r\n input(\"........\"),\r\nelse:\r\n print(\"Opcion invalida\")\r\n input(\"...........\")\r\n","sub_path":"clase 3/menu dos.py","file_name":"menu dos.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"149065995","text":"import cv2\nimport numpy as np\n\n# BGR\nimg = cv2.imread(\"imori.jpg\")\nb = img[:, :, 0].copy()\ng = img[:, :, 1].copy()\nr = img[:, :, 2].copy()\n\n# Gray Scale\nout = 0.2126 * r + 0.7152 * g + 0.0722 * b\nout = out.astype(np.uint8)\n\n# cv2.imwrite(\"imori_out.jpg\", out)\ncv2.imshow(\"imori\", out)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","sub_path":"src/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"188271369","text":"import sys\nsys.path.append(__file__.replace('\\\\NN\\\\example\\\\ex2_xor2.py',''))\n\nimport NN as nn\nimport tensor\nimport time\n\nprint('start')\n# 다른 프로세스가 중복 실행을 방지\nif __name__ == '__main__':\n # xor 데이터\n x = tensor.Tensor([0., 0., 0., 1., 1., 0., 1., 1.,0., 0., 0., 1., 1., 0., 1., 1.], [8,2])\n y = tensor.Tensor([0.,1.,1.,0.,1.,0.,0.,1.,0.,1.,1.,0.,1.,0.,0.,1.], [8,2])\n data = nn.Dataset(x, y)\n\n\n # 입력층 뉴련이 2개인 네트워크 생성\n network = nn.Network(2)\n\n # 뉴런이 4개인 히든층\n network.append_affine(4).append_batchnormalization().append_shift().append_sigmoid()\n # 뉴런이 2개인 출력층\n network.append_affine(2).append_softmax()\n\n # 옵티마이저\n optimizer = nn.optimizer.SGD(0.01)\n\n # 학습을 위한 객체 생성\n learner = nn.Learner(data, network, optimizer)\n\n # 4개의 배치 사이즈로 내부 신경망을 초기화\n learner.init(8)\n\n # 처음 정확도 출력하기\n print(learner.findAccuracy())\n\n # 학습\n learner.learn(1000, True)\n\n # 결과\n print(learner.findAccuracy())\n\n\n\n ","sub_path":"example/ex2_xor2.py","file_name":"ex2_xor2.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"365722165","text":"import os\nimport time\nfrom viframe import *\nfrom ApplianceUI import *\nfrom ApplianceUtilities import *\nfrom ApplianceTestCaseUI import *\n\n\nclass VwTopologyDetailsUI(ApplianceTestCaseUI): \n \"\"\"\n Contains tests for the first run VirtualWisdom Topology Details UI.\n \"\"\"\n\n\n @beforeclass(alwaysRun=True)\n @parameters(['LAB_selenium_address', 'LAB_selenium_browser'])\n def beforeClass(self, selenium, browser):\n \"\"\"\n Create AM service API tool and other required tools for testing.\n \"\"\"\n # Create common test tools\n self.CreateApplianceTestCaseToolsUI(address=selenium, browser=browser)\n \n\n @afterclass(alwaysRun=True)\n def afterClass(self):\n \"\"\"\n Clean up selenium sessions.\n \"\"\"\n self.assertTrue(self.selenium_.quit(), \"Closed selenium session\")\n \n \n @test(groups=['functional'],\n priority=0)\n @parameters(['LAB_target_directory']) \n def VwToplogyDetails_DebugTest(self, targetDir):\n \"\"\"\n \"\"\"\n address = self.resolveParameters('[NIC0_[NIC0_DEFAULT_network]_address]')\n self.OpenBrowser('http://%s' % (address), screenshotPath=targetDir+'/screenshots/', maximize=True)\n\n steps = [\n (self.HandleAdministratorLogin, None, None, {}),\n (self.ClickUiElement, [UI_ELEMENT_TOPOLOGY_TAB], None, {}),\n (self.ClickUiElement, [UI_ELEMENT_TOPOLOGY_TOPOLOGYDETAILS_TAB], None, {}),\n (self.ClickUiElement, [UI_ELEMENT_TOPOLOGYDETAILS_APPS_BUTTON], None, {}),\n (self.InputUiElementText, [UI_ELEMENT_TOPOLOGYDETAILS_APPS_SEARCH_INPUT, \"sblaze2\"], {'sendReturn':True}, {'postWait':10}),\n (self.ClickUiElement, [UI_ELEMENT_TOPOLOGYDETAILS_APPS_SEARCH_MENUITEM], None, {}), \n (self.wait, [10, 'Render wait'], None, {}), \n (self.ClickUiElement, [UI_ELEMENT_TOPOLOGYDETAILS_ZOOMIN_BUTTON], None, {'postWait':2}),\n (self.ClickUiElement, [UI_ELEMENT_TOPOLOGYDETAILS_ZOOMOUT_BUTTON], None, {'postWait':2}),\n (self.ClickUiElement, [UI_ELEMENT_TOPOLOGYDETAILS_ZOOMOUT_BUTTON], None, {'postWait':2}),\n (self.ClickUiElement, [UI_ELEMENT_TOPOLOGYDETAILS_FITCONTENT_BUTTON], None, {'postWait':2}),\n (self.wait, [10, 'Generic wait'], None, {}), \n ]\n\n self.ExecuteUiTestSteps(steps)\n","sub_path":"src/test/ApplianceManager/UI/VirtualWisdom/Topology/TopologyDetails/VwTopologyDetailsUI.py","file_name":"VwTopologyDetailsUI.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"18706634","text":"\"\"\"\nCustomize logging for Project teaching_helper\n\"\"\"\n\nimport os\nimport functools\nimport inspect\nimport logging\nimport logging.config\nimport typing\n\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom django.http import JsonResponse\nfrom django.shortcuts import HttpResponse, render\n\nfrom teaching_helper import gdata\n\n__all__ = [r'get_logger', r'APIViewCatchException']\n\ncurrent_dir = os.path.abspath(os.path.dirname(__file__))\nlog_conf_path = os.path.join(current_dir, 'logging.ini')\n\nlogging.config.fileConfig(log_conf_path)\n\n\n# functions\n\n\ndef get_logger(name):\n return logging.getLogger(name)\n\n\ndef _get_local_self_ins():\n \"\"\"Get `self` instance in class object method\n \"\"\"\n frame = inspect.currentframe().f_back.f_back\n _, _, _, init_method_locals = inspect.getargvalues(frame)\n\n return init_method_locals.get('self', None)\n\n\n# classes\n\n\nclass BaseDecorator(object):\n\n def __init__(self, obj, logger, decor_methods: typing.List = None):\n \"\"\"\n :param obj:\n :param logger:\n :param decor_methods: decorated classes set\n * default -> gdata.REST_HTTP_METHODS\n \"\"\"\n self.obj = obj\n self.logger = logger\n self.decor_methods = decor_methods\n\n self._set_default()\n\n def decorate(self):\n for name, method in self._iter():\n self._call(name, method)\n\n def _iter(self):\n for _f_name in dir(self.obj):\n if _f_name.lower() in self.decor_methods:\n yield _f_name, getattr(self.obj, _f_name)\n\n def _set_default(self):\n \"\"\"init member variable which is None\n\n you must assign a default value to member variable of `self` which is None\n \"\"\"\n raise NotImplementedError('_set_default must be implemented by subclass')\n\n def _call(self, name, method):\n \"\"\"method substitution\n \"\"\"\n raise NotImplementedError('_set_default must be implemented by subclass')\n\n\nclass APIViewCatchException(BaseDecorator):\n \"\"\"This class automatically catches exceptions under the specified set of methods\n\n process: by method substitution\n\n example:\n you want to initialize a class named `BookInfoView`,\n so that, you can use this class as follows:\n\n ```\n >>> def __init__(self, **kwargs):\n >>> APIViewCatchException().decorate()\n ```\n \"\"\"\n\n def _set_default(self):\n if not self.obj:\n self.obj = _get_local_self_ins()\n if not self.logger:\n self.logger = get_logger(__name__)\n if not self.decor_methods:\n self.decor_methods = [_f.lower() for _f in gdata.REST_HTTP_METHODS]\n\n def _call(self, func_name, func):\n \"\"\"execute method under protection\n \"\"\"\n\n @functools.wraps(func)\n def new_method(*args, **kwargs):\n try:\n _response = func(*args, **kwargs)\n if not isinstance(_response, (Response, render, HttpResponse, JsonResponse)):\n raise Exception('内部异常,响��类型错误.')\n return _response\n except Exception as e:\n self.logger.error(e, exc_info=True)\n return Response(data=e, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n setattr(self.obj, func_name, new_method)\n\n\n# 当方法内发生异常时,返回 value\ndef convert_exception_to_value(value):\n def _real_decorator(fn):\n @functools.wraps(fn)\n def wrapper(*args, **kv):\n try:\n return fn(*args, **kv)\n except Exception as e:\n logging.getLogger(fn.__module__).error(\n r'{fn_name} raise Exception need convert to {value} :{e}'.format(\n fn_name=fn.__qualname__, e=e, value=value), exc_info=True)\n return value\n\n return wrapper\n\n return _real_decorator\n","sub_path":"teaching_helper/glog.py","file_name":"glog.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"490148874","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2017-2018 AVSystem \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 urllib.request\nimport argparse\nimport collections\nimport sys\nimport os\nfrom xml.etree import ElementTree\n\n\nclass Lwm2mObjectEntry:\n \"\"\"\n LwM2M Object Registry entry.\n\n Available attributes are the same as tag names in the DDF XML structure.\n \"\"\"\n\n def __init__(self, tree):\n self._tree = tree\n\n def __getattr__(self, name):\n node = self._tree.find(name)\n if node is not None:\n return node.text.strip()\n return self._tree.get(name)\n\n\ndef _read_url(url: str) -> bytes:\n # we need to change the User-Agent - default one causes the server\n # to respond with 403 Forbidden\n req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n with urllib.request.urlopen(req) as f:\n return f.read()\n\n\nclass Lwm2mObjectRegistry:\n def __init__(self, ddf_url='http://www.openmobilealliance.org/wp/OMNA/LwM2M/DDF.xml'):\n root = ElementTree.fromstring(_read_url(ddf_url))\n entries = (Lwm2mObjectEntry(obj) for obj in root.findall('Item'))\n\n self.objects = collections.OrderedDict(sorted((int(entry.ObjectID), entry) for entry in entries))\n\n\ndef _print_object_list():\n for oid, obj in Lwm2mObjectRegistry().objects.items():\n print('%d\\t%s' % (oid, obj.Name))\n\n\ndef _print_object_definition(urn_or_oid):\n urn = urn_or_oid.strip()\n if urn.startswith('urn:oma:lwm2m:'):\n oid = int(urn.split(':')[-1])\n else:\n oid = int(urn)\n\n try:\n object_ddf_url = Lwm2mObjectRegistry().objects[oid].DDF\n print(_read_url(object_ddf_url).decode('utf-8-sig'))\n except KeyError:\n raise ValueError('Object with ID = %d not found' % oid)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Accesses LwM2M Object registry.\")\n parser.add_argument(\"--get-xml\", type=str, metavar='urn_or_oid', help=\"Get Object definition XML by URN or ID\")\n parser.add_argument(\"--list\", action='store_true', help=\"List all registered LwM2M Objects\")\n\n args = parser.parse_args()\n\n if args.list and args.get_xml is not None:\n print('conflicting options: --list, --get-xml')\n sys.exit(1)\n\n if args.list:\n _print_object_list()\n elif args.get_xml is not None:\n _print_object_definition(args.get_xml)\n else:\n parser.print_usage()\n sys.exit(1)\n","sub_path":"tools/lwm2m_object_registry.py","file_name":"lwm2m_object_registry.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"477703216","text":"import math\nimport re\nfrom random import shuffle\nfrom catapult.core.constants import BOT\nfrom catapult.modules.balancer import get_circled_linked_list, get_balancing, fill_balancing_nodes\nfrom catapult.modules.library import render_path, normalize_bot_servers, get_total_weight, render_string\nfrom catapult.library import get_template_path\n\n\nclass Module:\n def __init__(self, config, storage, register):\n self.storage = storage\n self.config = config\n\n # TODO move stage (install and check) to constants\n register('check', BOT, self.render_check_bot())\n register('install', BOT, self.render_install_bot())\n\n def render_check_bot(self):\n generated = render_path(get_template_path('supervisor', 'check'), {\n 'get': self.storage.get\n })\n\n return generated\n\n def render_install_bot(self):\n generated = render_path(get_template_path('supervisor', 'install'), {\n 'release_path': self.storage.get('path.remote.release'),\n 'file_name': 'catapult-{}'.format(self.storage.get('release.service')),\n 'get': self.storage.get\n })\n\n return generated\n\n def configure(self, config):\n demons = normalize_demons(config)\n servers = normalize_bot_servers(self.storage.get_servers(BOT))\n\n if not servers or not config:\n return\n\n # balancing\n\n balancing_demons = get_balancing_demons(demons)\n balancing_weight = get_total_weight(balancing_demons)\n\n servers_weight = get_total_weight(servers)\n\n point = math.ceil(balancing_weight / float(servers_weight))\n\n server_node = get_circled_linked_list(servers, point)\n fill_balancing_nodes(balancing_demons, server_node)\n balancing = get_balancing(server_node)\n\n # mirroring\n\n mirroring = get_mirroring_demons(demons)\n\n # supervisor\n\n supervisor = {}\n\n for server in servers:\n supervisor[server['host']] = []\n\n for demon in mirroring:\n supervisor[server['host']].append(demon)\n\n for demon in balancing[server['host']]:\n supervisor[server['host']].append(demon)\n\n # render\n\n configs = {}\n\n for host in supervisor:\n configs[host] = render(\n supervisor[host],\n self.storage\n )\n\n return configs\n\n\ndef render(demons, context):\n items = []\n\n for demon in demons:\n command = render_string(demon['command'], {\n 'release_path': context.get('path.remote.code'),\n 'get': context.get\n })\n\n numprocs = 1\n if demon['type'] == 'mirroring':\n numprocs = demon['instances']\n\n program = re.sub(' ', '_', demon['name'])\n program = re.sub(r'[^\\w]', '', program)\n\n item = render_path(get_template_path('supervisor', 'item'), {\n 'program': program,\n 'process_name': '%(program_name)s_%(process_num)02d',\n 'command': command,\n 'user': context.get('config.deploy.user'),\n 'numprocs': str(numprocs),\n 'get': context.get\n })\n\n items.append(item)\n\n generated = render_path(get_template_path('supervisor', 'supervisor'), {\n 'items': '\\n\\n'.join(map(str, items)),\n 'get': context.get\n })\n\n return generated\n\n\ndef normalize_demons(demons):\n normalized = []\n\n for demon in demons:\n # normalize type\n if 'type' not in demon:\n demon['type'] = 'balancing'\n\n if demon['type'] not in ['balancing', 'mirroring']:\n demon['type'] = 'balancing'\n\n # normalize weight\n if 'weight' not in demon:\n demon['weight'] = 1\n\n if demon['weight'] > 3:\n demon['weight'] = 3\n\n if demon['weight'] < 1:\n demon['weight'] = 1\n\n # normalize instances\n if 'instances' not in demon:\n demon['instances'] = 1\n\n if demon['instances'] > 50:\n demon['instances'] = 50\n\n if demon['instances'] < 1:\n demon['instances'] = 1\n\n # normalize name\n if 'name' not in demon or not demon['name']:\n name = render_string(demon['command'], {})\n\n demon['name'] = name\n\n demon['name'] = str(demon['name']).strip(' \\t\\n\\r')\n\n if not demon['name']:\n name = render_string(demon['command'], {})\n\n demon['name'] = name\n\n demon['name'] = re.sub('[^A-Za-z0-9]+', '_', demon['name'])\n\n normalized.append(demon)\n\n return normalized\n\n\ndef get_balancing_demons(demons):\n balancing = []\n for demon in demons:\n if demon['type'] != 'balancing':\n continue\n\n for _ in range(0, demon['instances']):\n balancing.append(demon)\n\n shuffle(balancing)\n\n return balancing\n\n\ndef get_mirroring_demons(demons):\n mirroring = []\n for demon in demons:\n if demon['type'] == 'mirroring':\n mirroring.append(demon)\n\n return mirroring\n\n\n","sub_path":"catapult/modules/supervisor/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":5060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"150452279","text":"# Copyright Contributors to the Packit project.\n# SPDX-License-Identifier: MIT\n\nimport inspect\nimport re\nfrom logging import getLogger\nfrom pathlib import Path\nfrom typing import Union, List, Optional, Dict\n\nfrom packit.patches import PatchMetadata\nfrom rebasehelper.helpers.macro_helper import MacroHelper\nfrom rebasehelper.specfile import SpecFile, RebaseHelperError, saves, PatchObject\nfrom rebasehelper.tags import Tag, Tags\n\ntry:\n from rebasehelper.plugins.plugin_manager import plugin_manager\nexcept ImportError:\n from rebasehelper.versioneer import versioneers_runner\n\nfrom packit.exceptions import PackitException\n\nlogger = getLogger(__name__)\n\n\nclass Specfile(SpecFile):\n def __init__(self, path: Union[str, Path], sources_dir: Union[str, Path] = \"\"):\n s = inspect.signature(SpecFile)\n if \"changelog_entry\" in s.parameters:\n super().__init__(\n path=str(path), sources_location=str(sources_dir), changelog_entry=\"\"\n )\n else:\n super().__init__(path=str(path), sources_location=str(sources_dir))\n self._patch_id_digits: Optional[int] = None\n self._uses_autosetup: Optional[bool] = None\n\n def update_spec(self):\n if hasattr(self, \"update\"):\n # new rebase-helper\n self.update()\n else:\n # old rebase-helper\n self._update_data()\n\n def update_changelog_in_spec(self, changelog_entry):\n if hasattr(self, \"update_changelog\"):\n # new rebase-helper\n self.update_changelog(changelog_entry)\n else:\n # old rebase-helper\n self.changelog_entry = changelog_entry\n new_log = self.get_new_log()\n new_log.extend(self.spec_content.sections[\"%changelog\"])\n self.spec_content.sections[\"%changelog\"] = new_log\n self.save()\n\n def set_spec_version(\n self, version: str = None, release: str = None, changelog_entry: str = None\n ):\n \"\"\"\n Set version in spec, release and add a changelog_entry (if they are presented).\n\n :param version: new version\n :param release: new release\n :param changelog_entry: accompanying changelog entry\n \"\"\"\n try:\n if version:\n # also this code adds 3 rpmbuild dirs into the upstream repo,\n # we should ask rebase-helper not to do that\n # using set_tag instead of set_version to turn off preserving macros\n self.set_tag(\"Version\", version, preserve_macros=False)\n\n if release:\n # using set_tag instead of set_release to turn off preserving macros\n self.set_tag(\n \"Release\", \"{}%{{?dist}}\".format(release), preserve_macros=False\n )\n\n if not changelog_entry:\n return\n\n self.update_changelog_in_spec(changelog_entry)\n\n except RebaseHelperError as ex:\n logger.error(f\"Rebase-helper failed to change the spec file: {ex}\")\n raise PackitException(\"Rebase-helper didn't do the job.\")\n\n def write_spec_content(self):\n if hasattr(self, \"_write_spec_content\"):\n # new rebase-helper\n self._write_spec_content()\n else:\n # old rebase-helper\n self._write_spec_file_to_disc()\n\n @staticmethod\n def get_upstream_version(versioneer, package_name, category):\n \"\"\"\n Call the method of rebase-helper (due to the version of rebase-helper)\n to get the latest upstream version of a package.\n :param versioneer:\n :param package_name: str\n :param category:\n :return: str version\n \"\"\"\n try:\n get_version = plugin_manager.versioneers.run\n except NameError:\n get_version = versioneers_runner.run\n return get_version(versioneer, package_name, category)\n\n def get_release_number(self) -> str:\n \"\"\"\n Removed in rebasehelper=0.20.0\n \"\"\"\n release = self.header.release\n dist = MacroHelper.expand(\"%{dist}\")\n if dist:\n release = release.replace(dist, \"\")\n return re.sub(r\"([0-9.]*[0-9]+).*\", r\"\\1\", release)\n\n @saves\n def set_patches(\n self, patch_list: List[PatchMetadata], patch_id_digits: int = 4\n ) -> None:\n \"\"\"\n Set given patches in the spec file\n\n :param patch_list: [PatchMetadata]\n :param patch_id_digits: Number of digits of the generated patch ID.\n This is used to control whether to have 'Patch' or 'Patch1' or 'Patch0001'.\n \"\"\"\n if not patch_list:\n return\n\n if all(p.present_in_specfile for p in patch_list):\n logger.debug(\n \"All patches are present in the spec file, nothing to do here 🚀\"\n )\n return\n\n # we could have generated patches before (via git-format-patch)\n # so let's reload the spec\n self.reload()\n\n applied_patches: Dict[str, PatchObject] = {\n p.get_patch_name(): p for p in self.get_applied_patches()\n }\n\n for patch_metadata in patch_list:\n if patch_metadata.present_in_specfile:\n logger.debug(\n f\"Patch {patch_metadata.name} is already present in the spec file.\"\n )\n continue\n\n if patch_metadata.name in applied_patches:\n logger.debug(\n f\"Patch {patch_metadata.name} is already defined in the spec file.\"\n )\n continue\n\n self.add_patch(patch_metadata, patch_id_digits)\n\n def add_patch(\n self, patch_metadata: PatchMetadata, patch_id_digits: Optional[int] = 4\n ):\n \"\"\"\n Add provided patch to the spec file:\n * Set Patch index to be +1 than the highest index of an existing specfile patch\n * The Patch placement logic works like this:\n * If there already are patches, then the patch is added after them\n * If there are no existing patches, the patch is added after Source definitions\n\n Args:\n patch_metadata: Metadata of the patch to be added.\n patch_id_digits: Number of digits of the generated patch ID. This is used to\n control whether to have 'Patch' or 'Patch1' or 'Patch0001'.\n \"\"\"\n try:\n patch_number_offset = max(x.index for x in self.get_applied_patches())\n except ValueError:\n logger.debug(\"There are no patches in the spec.\")\n # 0 is a valid patch index\n patch_number_offset = -1\n\n if patch_metadata.patch_id is not None:\n if patch_metadata.patch_id <= patch_number_offset:\n raise PackitException(\n f\"The 'patch_id' requested ({patch_metadata.patch_id}) for patch \"\n f\"{patch_metadata.name} is less than or equal to the last used patch ID \"\n f\"({patch_number_offset}). Re-ordering the patches using 'patch_id' is \"\n \"not allowed - if you want to change the order of those patches, \"\n \"please reorder the commits in your source-git repository.\"\n )\n patch_id = patch_metadata.patch_id\n else:\n # 0 is a valid patch index, but let's start with 1 which is more common, e.g.\n # https://src.fedoraproject.org/rpms/glibc/blob/f6682c9bac5872385b3caae0cd51fe3dbfcbb88f/f/glibc.spec#_158\n # https://src.fedoraproject.org/rpms/python3.10/blob/ac9a5093cb9f534ef2f65cbd1f50684c88b91eec/f/python3.10.spec#_267\n patch_id = max(patch_number_offset + 1, 1)\n\n new_content = \"\\n\"\n new_content += \"\\n\".join(\n line if line.startswith(\"#\") else f\"# {line}\".strip()\n for line in patch_metadata.specfile_comment.splitlines()\n )\n patch_id_str = f\"{patch_id:0{patch_id_digits}d}\" if patch_id_digits > 0 else \"\"\n new_content += f\"\\nPatch{patch_id_str}: {patch_metadata.name}\"\n\n if self.get_applied_patches():\n last_source_tag_line = [\n t.line for t in self.tags.filter(name=\"Patch*\", valid=None)\n ][-1]\n else:\n last_source_tag_line = [\n t.line for t in self.tags.filter(name=\"Source*\", valid=None)\n ][-1]\n\n # Find first empty line after last_source_tag_line\n for index, line in enumerate(\n self.spec_content.section(\"%package\")[last_source_tag_line:],\n start=last_source_tag_line,\n ):\n if not line:\n where = index\n break\n else:\n where = len(self.spec_content.section(\"%package\"))\n\n logger.debug(f\"Adding patch {patch_metadata.name} to the spec file.\")\n self.spec_content.section(\"%package\")[where:where] = new_content.splitlines()\n self.save()\n\n def get_source(self, source_name: str) -> Optional[Tag]:\n \"\"\"\n get specific Source from spec\n\n :param source_name: precise name of the Source, e.g. Source1, or Source\n :return: corresponding Source Tag\n \"\"\"\n # sanitize the name, this will also add index if there isn't one\n source_name, *_ = Tags._sanitize_tag(source_name, 0, 0)\n return next(self.tags.filter(name=source_name, valid=None), None)\n\n def read_patch_comments(self) -> dict:\n \"\"\"Read the spec again, detect comment lines right above a patch-line\n and save it as an attribute to the patch for later retrieval.\n\n Match patch-lines with the patch-data from rebase-helper on the name of\n the patches.\n\n Returns:\n A dict where each patch name (the basename of the value of the\n patch-line) has 0 or more comment lines associated with it.\n \"\"\"\n comment: List[str] = []\n patch_comments = {}\n for line in self.spec_content.section(\"%package\"):\n # An empty line clears the comment lines collected so far.\n if not line.strip():\n comment = []\n # Remember a comment line.\n if line.startswith(\"#\"):\n comment.append(line[1:].strip())\n # Associate comments with patches and clear the comments\n # collected.\n if line.lower().startswith(\"patch\"):\n patch_name = Path(line.split(\":\", 1)[1].strip()).name\n patch_comments[patch_name] = comment\n comment = []\n return patch_comments\n\n @property\n def patch_id_digits(self) -> int:\n \"\"\"Detect and return the number of digits used in patch IDs (indices).\n\n Look for the first patch-line, and use that as a reference.\n\n 0 - no patch ID at all, just a bare \"Patch\"\n 1 - no leading zeros for patch IDs\n 2 or more - the minimum number of digits to be used for patch IDs.\n\n Returns:\n Number of digits used on the first patch-line, or 0 if there is\n no patch-line found.\n \"\"\"\n if self._patch_id_digits is not None:\n return self._patch_id_digits\n\n self._patch_id_digits = 1\n for line in self.spec_content.section(\"%package\"):\n if line.lower().startswith(\"patch\"):\n match = re.match(r\"^patch(\\d*)\\s*:.+\", line, flags=re.IGNORECASE)\n if not match[1]:\n self._patch_id_digits = 0\n elif match[1].startswith(\"0\"):\n self._patch_id_digits = len(match[1])\n break\n\n return self._patch_id_digits\n\n @property\n def uses_autosetup(self) -> bool:\n \"\"\"Tell if the specfile uses %autosetup\n\n Returns:\n True if the file uses %autosetup, otherwise False.\n \"\"\"\n\n if self._uses_autosetup is not None:\n return self._uses_autosetup\n\n self._uses_autosetup = False\n for line in self.spec_content.section(\"%prep\"):\n if line.startswith(\"%autosetup\"):\n self._uses_autosetup = True\n break\n\n return self._uses_autosetup\n\n def remove_patches(self):\n \"\"\"Remove all patch-lines from the spec file\"\"\"\n content = []\n stretch = []\n for line in self.spec_content.section(\"%package\"):\n stretch.append(line)\n # Empty lines save the current stretch into content.\n if not line.strip():\n content += stretch\n stretch = []\n # Patch-lines throw away the current stretch.\n if line.lower().startswith(\"patch\"):\n stretch = []\n # If there is an empty line at the end of content\n # throw it away, to avoid duplicate lines.\n if not content[-1].strip():\n content.pop()\n self.spec_content.replace_section(\"%package\", content)\n self.save()\n","sub_path":"packit/specfile.py","file_name":"specfile.py","file_ext":"py","file_size_in_byte":13008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"224999620","text":"import os\r\nimport numpy as np\r\nfrom random import randint\r\nfrom PIL import Image\r\nos.chdir('dataset-v2')\r\n\r\ninput_shape = (56, 56)\r\n\r\n\r\ndef get_fixed_img(src):\r\n target = [0, 0]\r\n if src.size[0] < src.size[1]:\r\n target[1] = input_shape[0]\r\n target[0] = int(src.size[0] / src.size[1] * input_shape[1])\r\n else:\r\n target[0] = input_shape[1]\r\n target[1] = int(src.size[1] / src.size[0] * input_shape[0])\r\n\r\n img = src.resize(target)\r\n res = Image.new(\"RGB\", input_shape, (255, 255, 255))\r\n res.paste(img, ((input_shape[0]-target[0])//2, (input_shape[1]-target[1])//2))\r\n return res\r\n\r\n\r\ndef sign(x):\r\n if x > 0:\r\n return x\r\n return 0\r\n\r\n\r\ncreate_new = False\r\n\r\n\r\nli = os.listdir()\r\n\r\nif create_new:\r\n for i in li:\r\n if '.jpg' not in i or 'n' in i:\r\n continue\r\n get_fixed_img(Image.open(i)).save(i)\r\n\r\n for i in li:\r\n if 'n' not in i or 'f' in i:\r\n continue\r\n # 每张图选择15个区域\r\n im = Image.open(i)\r\n pos = [0, 0, 0, 0]\r\n size = im.size\r\n for j in range(15):\r\n pos[0] = randint(0, sign(size[0] - input_shape[0] * 3))\r\n pos[1] = randint(0, sign(size[1] - input_shape[1] * 3))\r\n pos[2] = min((pos[0] + input_shape[0] * 3, size[0]))\r\n pos[3] = min((pos[1] + input_shape[1] * 3, size[1]))\r\n res = im.crop(pos).resize(input_shape)\r\n res.save(i.split('.jpg')[0] + str(j) + 'f' + '.jpg')\r\n\r\ndata = []\r\nlabel = []\r\nli = os.listdir()\r\nfor i in li:\r\n if 'n' in i and 'f' not in i:\r\n continue\r\n im = Image.open(i).convert('L')\r\n data.append(np.array(im))\r\n if 'n' in i:\r\n label.append(0)\r\n else:\r\n label.append(1)\r\n\r\nnp.savez('position2-2.npz', data=data, label=label)\r\n\r\n","sub_path":"make_data_v2.py","file_name":"make_data_v2.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"636550130","text":"#!/usr/bin/env python3\n\nimport argparse, os, re, subprocess, sys\n\ndef failWithMessage(message):\n print(message)\n sys.exit(1)\n\nif __name__ == \"__main__\":\n # Build a parser and parse the command line\n parser = argparse.ArgumentParser(description = \"Extract the\t embedded video from a Samsung Motion Photo.\")\n parser.add_argument(\"-s\", \"--split\", action = \"store_true\",\n help = \"Split the files, that is, remove the embedded video from the jpg file as well. WARNING: use at your own risk - it might be a good idea to make a backup first.\")\n parser.add_argument(\"jpg_file\", type = str, help = \"The photo file that should contain the embedded video\")\n args = parser.parse_args()\n \n # Check if exiftool is there\n try:\n status = subprocess.run([\"exiftool\", \"-ver\"], stdout = subprocess.PIPE)\n except FileNotFoundError:\n failWithMessage(\"Please install Exiftool\")\n if status.returncode != 0:\n failWithMessage(\"Exiftool can't be run\")\n\n if not os.path.exists(args.jpg_file):\n failWithMessage(\"Photo file %s does not exist\" % args.jpg_file)\n\n # Check the EmbeddedVideoType flag, should be \"MotionPhoto_Data\" for Samsung\n # Motion Photos\n result = subprocess.run([\"exiftool\", \"-S\", \"-EmbeddedVideoType\", args.jpg_file], stdout = subprocess.PIPE)\n if result.returncode != 0:\n failWithMessage(\"Exiftool failed on %s\" % args.jpg_file)\n stdout = result.stdout.decode(\"utf-8\").split(\":\")\n if len(stdout) != 2 or stdout[1].strip() != \"MotionPhoto_Data\":\n failWithMessage(\"'%s' is probably not a Samsung Motion Photo\" % args.jpg_file)\n \n # If we're good, extract the embedded video and copy the metadata\n base, _ = os.path.splitext(args.jpg_file)\n result = subprocess.run([\"exiftool\", \"-b\", \"-EmbeddedVideoFile\", args.jpg_file], stdout = subprocess.PIPE)\n if result.returncode != 0:\n failWithMessage(\"Couldn't extract the embedded video\")\n else:\n with open(base + \".mp4\", \"wb\") as mp4:\n mp4.write(result.stdout)\n print(\"Embedded video saved as '%s.mp4'\" % base)\n result_metadata = subprocess.run([\"exiftool\", \"-overwrite_original\", \"-tagsfromfile\", args.jpg_file, base + \".mp4\"], stdout = subprocess.PIPE)\n if result_metadata.returncode != 0:\n print(\"Warning: couldn't copy metadata to mp4 file\")\n\n if args.split:\n # The embedded video is basically pasted to the end of the jpg file, so\n # removing it basically means cutting the tail off the jpg file. Let's\n # ask Exiftool where we should cut.\n # NOTE: we could use this same mechanism to extract the video, but it's\n # a bit safer to just use Exiftool for this.\n result = subprocess.run([\"exiftool\", \"-v1\", args.jpg_file], stdout = subprocess.PIPE)\n if result.returncode != 0:\n failWithMessage(\"Couldn't remove the embedded video\")\n stdout = result.stdout.decode(\"UTF-8\")\n\n # Do a sanity check to see if there's only an embedded video in the JPG\n # trailer\n offset = None\n in_samsung_section = False\n for line in stdout.split(\"\\n\"):\n if not in_samsung_section and line.startswith(\"Samsung trailer\"):\n in_samsung_section = True\n\n # While we're here, extract the offset of the Samsung trailer \n offset_match = re.search(\"Samsung trailer \\(\\d+ bytes at offset (0x[\\da-f]+)\", line)\n if offset_match:\n offset = offset_match.group(1)\n else:\n failWithMessage(\"Couldn't remove the embedded video\")\n\n elif in_samsung_section:\n if line.startswith(\" \"):\n if not re.match(\" (Samsung_Trailer|TimeStamp|SamsungTrailer|EmbeddedVideo)\", line):\n failWithMessage(\"Unknown content found in Samsung portion of the file. Embedded video couldn't be removed\")\n else:\n in_samsung_section = False\n\n if offset == None:\n failWithMessage(\"Couldn't remove the embedded video\")\n\n # Save a trunctated version of the jpg file up to the offset\n with open(args.jpg_file, \"rb\") as jpg_file:\n jpg_data = jpg_file.read(int(offset, 16))\n with open(args.jpg_file, \"wb\") as jpg_file:\n jpg_file.write(jpg_data)\n","sub_path":"extractmotionphoto.py","file_name":"extractmotionphoto.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"45976689","text":"import sys\nimport socket\nimport threading\n\nports = [31000, 31001, 31002]\n\ndef do_thread(i):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_address = ('127.0.0.1', i)\n print(f\"starting up on {server_address}\")\n\n sock.bind(server_address)\n sock.listen(1)\n\n print(\"waiting for a connection\")\n connection, client_address = sock.accept()\n \n print(f\"Handle connection from {client_address}\")\n while True:\n data = connection.recv(32)\n print(f\"[ Port {i}] received {data}\")\n if data:\n print(f\"[ Port {i}] sending back data\")\n connection.sendall(data)\n break\n \n connection.close()\n\n# Listen for incoming connections\nmulti_threads = []\nfor i in ports: \n thr = threading.Thread(target=do_thread, args=(i,))\n multi_threads.append(thr)\n\nfor thr in multi_threads:\n thr.start()\n\nprint('Exit')","sub_path":"tugas1/tugas1_di_3_port/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377407146","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2012 James Thornton (http://jamesthornton.com)\n# BSD License (see LICENSE for details)\n#\n\"\"\"\nAn interface for interacting with indices on Rexster.\n\n\"\"\"\n\nfrom bulbs.utils import initialize_element, initialize_elements, get_one_result\n\nclass IndexProxy(object):\n \"\"\"Abstract base class the index proxies.\"\"\"\n\n def __init__(self,index_class,client): \n #: The index class for this proxy, e.g. ExactIndex.\n self.index_class = index_class\n\n #: The Client object for the database.\n self.client = client\n \n\nclass VertexIndexProxy(IndexProxy):\n \"\"\"\n An interface for interacting with indices on Rexster.\n\n :param client: The Client object for the database.\n :param index_class: The index class for this proxy, e.g. RexsterIndex.\n\n \"\"\"\n \n def create(self,index_name,*args,**kwds):\n \"\"\"Creates an an index and returns it.\"\"\"\n resp = self.client.create_vertex_index(index_name,*args,**kwds)\n index = self.index_class(self.client,resp.results)\n self.client.registry.add_index(index_name,index)\n return index\n\n def get(self,index_name):\n \"\"\"Returns the Index object with the specified name or None if not found.\"\"\"\n resp = self.client.get_vertex_index(index_name)\n if resp.results:\n index = self.index_class(self.client,resp.results)\n self.client.registry.add_index(index_name,index)\n return index\n\n def get_or_create(self,index_name,*args,**kwds):\n # get it, create if doesn't exist, then register it\n try:\n index = self.get(index_name)\n except LookupError:\n index = self.create(index_name,*args,**kwds)\n return index\n\n def delete(self,index_name):\n \"\"\"Deletes/drops an index and returns the Rexster Response object.\"\"\"\n try:\n return self.client.delete_vertex_index(index_name)\n except LookupError:\n return None\n\nclass EdgeIndexProxy(IndexProxy):\n \"\"\"\n An interface for interacting with indices on Rexster.\n\n :param client: The Client object for the database.\n :param index_class: The index class for this proxy, e.g. RexsterIndex.\n\n \"\"\"\n\n def create(self,index_name,*args,**kwds):\n \"\"\" \n Adds an index to the database and returns it. \n\n index_keys must be a string in this format: '[k1,k2]'\n Don't pass actual list b/c keys get double quoted.\n\n :param index_name: The name of the index to create.\n\n :param index_class: The class of the elements stored in the index. \n Either vertex or edge.\n \n \"\"\"\n resp = self.client.create_edge_index(index_name,*args,**kwds)\n index = self.index_class(self.client,resp.results)\n self.client.registry.add_index(index_name,index)\n return index\n\n def get(self,index_name):\n \"\"\"Returns the Index object with the specified name or None if not found.\"\"\"\n resp = self.client.get_edge_index(index_name)\n if resp.results:\n index = self.index_class(self.client,resp.results)\n self.client.registry.add_index(index_name,index)\n return index\n\n def get_or_create(self,index_name,*args,**kwds):\n # get it, create if doesn't exist, then register it\n try: \n index = self.get(index_name)\n except LookupError:\n index = self.create(index_name,*args,**kwds)\n return index\n\n def delete(self,index_name):\n \"\"\"Deletes/drops an index and returns the Rexster Response object.\"\"\"\n try:\n return self.client.delete_edge_index(index_name)\n except LookupError:\n return None\n\n\nclass Index(object):\n\n def __init__(self,client,results):\n self.client = client\n self.results = results\n\n @property\n def index_name(self):\n \"\"\"Returns the index name.\"\"\"\n return self.results.data['name']\n\n @property\n def index_class(self):\n \"\"\"Returns the index class, which will either be vertex or edge.\"\"\"\n return self.results.data['class']\n\n @property\n def index_type(self):\n \"\"\"Returns the index type, which will either be automatic or manual.\"\"\"\n return self.results.data['type']\n\n # TODO: change to lookup?\n def lookup(self,key=None,value=None,**pair):\n \"\"\"\n Return a generator containing all the elements with key property equal \n to value in the index.\n\n :param key: The index key. This is optional because you can instead \n supply a key/value pair such as name=\"James\". \n\n :param value: The index key's value. This is optional because you can \n instead supply a key/value pair such as name=\"James\". \n\n :param raw: Optional keyword param. If set to True, it won't try to \n initialize the results. Defaults to False. \n\n :param **pair: Optional keyword param. Instead of supplying key=name \n and value = 'James', you can supply a key/value pair in\n the form of name='James'.\n \"\"\"\n key, value = self._parse_args(key,value,pair)\n resp = self.client.lookup_vertex(self.index_name,key,value)\n return initialize_elements(self.client,resp)\n\n def _parse_args(self,key,value,pair):\n if pair:\n key, value = pair.popitem()\n return key, value\n \n def count(self,key=None,value=None,**pair):\n \"\"\"\n Return a count of all elements with 'key' equal to 'value' in the index.\n\n :param key: The index key. This is optional because you can instead \n supply a key/value pair such as name=\"James\". \n\n :param value: The index key's value. This is optional because you can \n instead supply a key/value pair such as name=\"James\". \n\n :param **pair: Optional keyword param. Instead of supplying key=name \n and value = 'James', you can supply a key/value pair in\n the form of name='James'.\n \"\"\"\n key, value = self._parse_args(key,value,pair)\n resp = self.client.index_count(self.index_name,key,value)\n return resp.content['totalSize']\n\n def keys(self):\n \"\"\"Return the index's keys.\"\"\"\n resp = self.client.index_keys(self.index_name)\n return list(resp.results)\n\n\nclass AutomaticIndex(Index):\n \n def rebuild(self):\n # need class_map b/c the Blueprints need capitalized class names, \n # but Rexster returns lower-case class names for index_class\n method_map = dict(vertex=self.client.rebuild_vertex_index,\n edge=self.client.rebuild_edge_index)\n rebuild_method = method_map.get(self.index_class)\n resp = rebuild_method(self.index_name)\n return list(resp.results)\n\n\nclass ManualIndex(Index):\n \"\"\"\n Creates, retrieves, and deletes indices provided by the graph database.\n\n Use this class to get, put, and update items in an index.\n \n\n :param client: The Client object for the database.\n\n :param results: The results list returned by Rexster.\n\n :param classes: Zero or more subclasses of Element to use when \n initializing the the elements returned by the query. \n For example, if Person is a subclass of Node (which \n is defined in model.py and is a subclass of Vertex), \n and the query returns person elements, pass in the \n Person class and the method will use the element_type\n defined in the class to initialize the returned items\n to a Person object.\n\n Example that creates an index for Web page URL stubs, \n adds an page element to it, and then retrieves it from the index::\n\n >>> graph = Graph()\n >>> graph.indices.create(\"page\",\"vertex\",\"automatic\",\"[stub]\")\n >>> index = graph.indices.get(\"page\")\n >>> index.put(\"stub\",stub,page._id)\n >>> page = index.get(\"stub\",stub)\n\n \"\"\"\n\n \n def put(self,_id,key=None,value=None,**pair):\n \"\"\"\n Put an element into the index at key/value and return Rexster's \n response.\n\n :param _id: The element ID.\n\n :param key: The index key. This is optional because you can instead \n supply a key/value pair such as name=\"James\". \n\n :param value: The index key's value. This is optional because you can \n instead supply a key/value pair such as name=\"James\". \n\n :param **pair: Optional keyword param. Instead of supplying key=name \n and value = 'James', you can supply a key/value pair in\n the form of name='James'.\n\n \"\"\"\n # NOTE: if you ever change the _id arg to element, change remove() too\n key, value = self._parse_args(key,value,pair)\n method_map = dict(vertex=self.client.put_vertex,\n edge=self.client.put_edge)\n put_method = method_map.get(self.index_class)\n resp = put_method(self.index_name,key,value,_id)\n return resp\n\n def put_unique(self,_id,key=None,value=None,**pair):\n \"\"\"\n Put an element into the index at key/value and overwrite it if an \n element already exists at that key and value; thus, there will be a max\n of 1 element returned for that key/value pair. Return Rexster's \n response.\n\n :param _id: The element ID.\n\n :param key: The index key. This is optional because you can instead \n supply a key/value pair such as name=\"James\". \n\n :param value: The index key's value. This is optional because you can \n instead supply a key/value pair such as name=\"James\". \n\n :param **pair: Optional keyword param. Instead of supplying key=name \n and value = 'James', you can supply a key/value pair in \n the form of name='James'.\n\n \"\"\"\n key, value = self._parse_args(key,value,pair)\n method_map = dict(vertex=self.client.remove_vertex,\n edge=self.client.remove_edge)\n remove_method = method_map.get(self.index_type)\n for result in self.get(key,value):\n remove_method(self.index_name,result._id,key,value)\n resp = self.put(_id,key,value)\n return resp\n\n def update(self,_id,key=None,value=None,**pair):\n \"\"\"\n Update the element ID for the key and value and return Rexsters' \n response.\n\n :param _id: The element ID.\n\n :param key: The index key. This is optional because you can instead \n supply a key/value pair such as name=\"James\". \n\n :param value: The index key's value. This is optional because you can \n instead supply a key/value pair such as name=\"James\". \n\n :param **pair: Optional keyword param. Instead of supplying key=name \n and value = 'James', you can supply a key/value pair in\n the form of name='James'.\n \"\"\"\n return self.put_unique(_id,key,value,**pair)\n\n \n def lookup_unique(self,key=None,value=None,**pair):\n \"\"\"\n Returns a max of 1 elements matching the key/value pair in the index.\n\n :param key: The index key. This is optional because you can instead \n supply a key/value pair such as name=\"James\". \n\n :param value: The index key's value. This is optional because you can \n instead supply a key/value pair such as name=\"James\". \n\n :param **pair: Optional keyword param. Instead of supplying key=name \n and value = 'James', you can supply a key/value pair in\n the form of name='James'.\n \"\"\"\n key, value = self._parse_args(key,value,pair)\n resp = self.client.lookup_vertex(self.index_name,key,value)\n result = get_one_result(resp)\n return initialize_element(self.client,result)\n\n def remove(self,_id,key=None,value=None,**pair):\n \"\"\"\n Remove the element from the index located by key/value.\n\n :param _id: The element ID.\n\n :param key: The index key. This is optional because you can instead \n supply a key/value pair such as name=\"James\". \n\n :param value: The index key's value. This is optional because you can \n instead supply a key/value pair such as name=\"James\". \n\n :param **pair: Optional keyword param. Instead of supplying key=name \n and value = 'James', you can supply a key/value pair in\n the form of name='James'.\n \"\"\"\n key, value = self._parse_args(key,value,pair)\n method_map = dict(vertex=self.client.remove_vertex,\n edge=self.client.remove_edge)\n remove_method = method_map.get(self.index_class)\n return remove_method(self.index_name,_id,key,value)\n\n\n\n \n","sub_path":"bulbs/rexster/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":13161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"131444972","text":"from simple_salesforce import (\n Salesforce,\n SalesforceAPI,\n SFType,\n SalesforceError,\n SalesforceMoreThanOneRecord,\n SalesforceExpiredSession,\n SalesforceRefusedRequest,\n SalesforceResourceNotFound,\n SalesforceGeneralError,\n SalesforceMalformedRequest\n)\n\nimport sys\nfrom _datetime import timedelta\nfrom datetime import date\nimport csv\ndef goDelete(sf):\n \n for annee in range(2017,2018):\n for mois in range(1,13):\n qry = 'SELECT Date_de_commande__c ,id,Year_Month__c,Facture__c,Bon_de_livraison__c FROM Commande__c where Year_Month__c =' +'%s'%((annee*100)+mois)\n print(qry)\n records = sf.query_all(qry)['records']\n tobedel = []\n for r in records :\n if r['Facture__c'] is not None and r['Facture__c'][0].isalpha() : ## si le premie char de facture__c est une lettre => vient de EURODEP\n continue ## donc on efface pas. \n tobedel.append({'Id':r['Id']})\n print((annee*100)+mois,'lignes:',len(tobedel))\n try:\n if len(tobedel)>0:\n sf.bulk.Commande__c.delete(tobedel)\n except Exception as e:\n print(len(tobedel))\n\n \ndef doIt(sf):\n ## insertion des lignes\n fieldsToInsert = ['Compte__c','Quantite__c','Date_de_commande__c','Facture__c','Ligne__c','Prix_Net__c','Produit__c','Bon_de_livraison__c','Prix_Brut__c']\n arrInsertions = []\n nbreSent = 0\n with open('./lignes.2008.all.csv','r') as allRecords:\n reader = csv.DictReader(allRecords,delimiter=';')\n for r in reader:\n if int(r['Date_de_commande__c'][:4]) >=2006:\n lai ={}\n for k in r.keys():\n if k in fieldsToInsert:\n lai[k] = r[k]\n arrInsertions.append(lai)\n if len(arrInsertions) >= 250:\n try :\n print('Sending one batch ! ',nbreSent)\n nbreSent += 1\n sf.bulk.commande__c.insert(arrInsertions)\n arrInsertions = []\n except Exception as e:\n print('Erreur ', e)\n sys.exit()\n try :\n print('Sending remaining records ',nbreSent)\n sf.bulk.commande__c.insert(arrInsertions)\n arrInsertions = []\n except Exception as e:\n print('Erreur ', e)\n sys.exit()\n \ndef utilsDelete(sf):\n qry = 'SELECT CreatedDate,Date_de_commande__c,Facture__c,Id FROM Commande__c WHERE CreatedDate < 2017-04-30T05:00:00Z'\n rec =sf.query_all(qry)['records']\n tobedel=[] \n for r in rec:\n tobedel.append({'Id':r['Id']})\n if len(tobedel)>0:\n sf.bulk.Commande__c.delete(tobedel)\n \nif __name__ == '__main__':\n sf = Salesforce(username='projets@homme-de-fer.com', password='ubiclouder$2017', security_token='mQ8aTUVjtfoghbJSsZFhQqzJk')\n goDelete(sf)\n doIt(sf)\n ## utilsDelete(sf)\n \n ## ","sub_path":"prepareMigration.py","file_name":"prepareMigration.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"497822346","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Dec 15 14:56:06 2016\r\n\r\n@author: ladretp\r\n\"\"\"\r\nimport numpy as np\r\nimport skimage as sk\r\nfrom skimage import color, data,feature,filters\r\nfrom scipy.ndimage import convolve \r\n \r\n\"\"\" Mesure de Flou\r\n Méthode Fredérique Crêté\r\n[1]: The blur effect: perception and estimation with a new no-reference\r\n perceptual blur metric . Frederique Crete, Thierry Dolmiere, Patricia Ladret,\r\n Marina Nicolas.Electronic Imaging 2007. 64920I-64920I-11. \r\n International Society for Optics and Photonics \"\"\"\r\n \r\ndef DiffCol(I):\r\n taille=np.shape(I)\r\n S=np.zeros(taille,dtype='float')\r\n S=np.abs(I[:,2:taille[1]]-I[:,1:taille[1]-1])\r\n S[:,0]=S[:,1]\r\n return S\r\ndef Difflig(I):\r\n taille=np.shape(I)\r\n S=np.zeros(taille,dtype='float')\r\n S=np.abs(I[2:taille[0],:]-I[1:taille[0]-1,:])\r\n S[0,:]=S[1,:]\r\n return S\r\n \r\ndef BluM(I):\r\n \r\n h=np.ones((11,1),dtype=np.float)/11\r\n #print(h)\r\n #h[2,:]=np.array([1.0/5,1.0/5,1.0/5,1.0/5,1.0/5])\r\n taille=np.shape(I)\r\n \r\n if np.size(taille)==3:\r\n I=color.rgb2gray(I)\r\n \r\n y=np.copy(I)\r\n y=sk.img_as_float(I)\r\n \r\n #Flou Vertical\r\n Iver=convolve(y,h)\r\n\r\n ImNette=Difflig(y)\r\n \r\n \r\n ImFlou=Difflig(Iver)\r\n #T=np.abs(ImNette-ImFlou)\r\n #T=ImNette-ImFlou\r\n T=np.fmax(np.zeros_like(ImNette),ImNette-ImFlou)\r\n M1=np.sum(ImNette[2:taille[0]-1,2:taille[1]-1])\r\n print('M1=',M1)\r\n M2=np.sum(T[2:taille[0]-1,2:taille[1]-1])\r\n print('M2=',M2)\r\n F1=np.abs((M1-M2))/M1\r\n \r\n #Flou Horizontal\r\n Ihor=convolve(y,np.transpose(h))\r\n \r\n ImNette=np.copy(I)\r\n ImNette=sk.img_as_float(ImNette)\r\n ImNette=DiffCol(y)\r\n \r\n\r\n ImFlou=DiffCol(Ihor)\r\n #T=np.abs(ImNette-ImFlou)\r\n #T=ImNette-ImFlou\r\n T=np.fmax(np.zeros_like(ImNette),ImNette-ImFlou)\r\n\r\n M1=np.sum(ImNette[2:taille[0]-1,2:taille[1]-1])\r\n #print('M1=',M1)\r\n \r\n M2=np.sum(T[2:taille[0]-1,2:taille[1]-1])\r\n #print('M2=',M2)\r\n F2=np.abs((M1-M2))/M1\r\n F= np.array([F1,F2])\r\n print('Flou=',F)\r\n return np.max(F)\r\n \r\n#________________________________________________________________________\r\n# Mesure de bloc méthode de Perra\r\n\"\"\" [2]Estimating blockness distortion for performance evaluation \r\nof picture coding algorithms. D.D. Giusto ; M. Perra. \r\n1997 IEEE Pacific Rim Conference on Communications, Computers and Signal Processing, PACRIM.\r\n \"\"\" \r\ndef BlocM(I):\r\n taille=np.shape(I)\r\n taillex=taille[0]\r\n tailley=taille[1]\r\n \r\n if np.size(taille)==3:\r\n I=color.rgb2gray(I)\r\n y=np.copy(I)\r\n y=sk.img_as_float(I)\r\n h=np.zeros((3,3),dtype=np.float)\r\n h[1,:]=np.array([-1.0,0.0,1.0,])\r\n Dx=convolve(y,h)\r\n Dy=convolve(y,np.transpose(h))\r\n D=np.sqrt(Dx*Dx+Dy*Dy)\r\n s1=0.0;\r\n s2=0.0;nbbloc=0.0;MES_Bloc=0.0;\r\n for k in np.arange(8,taillex-24,8):\r\n for l in np.arange(8,tailley-24,8):\r\n BH1=Dy[k,l:l+8]\r\n BH2=Dy[k+8,l:l+8]\r\n BV1=Dx[k:k+8,l]\r\n BV2=Dx[k:k+8,l+8]\r\n BC=D[k+1:k+7,l+1:l+7]\r\n omega1H=np.array([BV1, BV2]);\r\n omega1V=np.array([BH1, BH2]);\r\n valabs1=np.amax(np.abs(omega1H));\r\n valabs2=np.amax(np.abs(omega1V));\r\n s11=0.0;s12=0.0;\r\n if (valabs1 > 0.0):\r\n s11=np.sum((np.abs(omega1H)/np.amax((np.abs(omega1H)))));\r\n \r\n \r\n if (valabs2 > 0.0):\r\n s12=np.sum((np.abs(omega1V)/np.amax((np.abs(omega1V)))));\r\n \r\n s1=(s11+s12)/32.0;\r\n \r\n if np.amax(np.abs(BC))>0.0:\r\n s2=np.sum(BC)/np.amax(BC)/36.0;\r\n if (s1*s1+s2*s2)>0.0:\r\n MES_Bloc= MES_Bloc+np.abs((s1*s1-s2*s2)/(s1*s1+s2*s2));\r\n nbbloc=nbbloc+1.0;\r\n \r\n else:\r\n if ((valabs1>0.0) | (valabs2>0.0)):\r\n MES_Bloc=MES_Bloc+1.0;\r\n \r\n nbbloc=nbbloc+1;\r\n\r\n MES_Bloc=MES_Bloc/nbbloc;\r\n\r\n \r\n \r\n return MES_Bloc;\r\n \r\n ","sub_path":"BluM.py","file_name":"BluM.py","file_ext":"py","file_size_in_byte":4112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"616019841","text":"\"\"\"A minimal vtk wrapper to automate (vtk -> numpy) conversions.\"\"\"\n\nimport os\nfrom importlib import import_module\nfrom pathlib import Path\n\nimport numpy as np\nimport vtk\nfrom vtk.util.numpy_support import vtk_to_numpy\n\n\nclass VacDataSorter:\n \"\"\"A simple data holder class for non-amr runs.\"\"\"\n\n _readers = {\n # note : StructuredGrid can not be used because dimensions\n # are not stored by AMRVAC (as they usually don't make sense)\n \"vtu\": vtk.vtkXMLUnstructuredGridReader\n }\n\n def __init__(self, file_name: str, shape: tuple = None, **kwargs):\n if not isinstance(file_name, (str, os.PathLike)):\n raise TypeError\n if not Path(file_name).exists():\n raise FileNotFoundError(file_name)\n\n if not kwargs == {}:\n print(\"VacDataSorter warning: the following keyword arguments were not used:\")\n print(list(kwargs.keys()))\n self.file_name = str(file_name)\n\n # init vtk reader\n file_type = file_name.split(\".\")[-1]\n self.reader = __class__._readers[file_type]()\n self.reader.SetFileName(file_name)\n self.reader.Update()\n\n # set fields dictionnary\n cd = self.reader.GetOutput().GetCellData()\n sort_key = self._get_sort_key()\n self.fields = {}\n for i in range(cd.GetNumberOfArrays()):\n arrname = cd.GetArrayName(i)\n self.fields.update({arrname: vtk_to_numpy(cd.GetArray(arrname))[sort_key]})\n\n # optional reshaping (shape can not be read internally)\n self.shape = shape\n if self.shape:\n for k in self.fields:\n self.fields[k].shape = shape\n else:\n k0 = [k for k in self.fields.keys()][0]\n self.shape = (len(self.fields[k0]),)\n\n def __getitem__(self, key) -> np.ndarray:\n \"\"\"Mimic the behavior of the embedded dictionnary for scrapping\"\"\"\n return self.fields[key]\n\n def __iter__(self) -> (str, np.ndarray):\n \"\"\"Allow iteration over fields.items() at base level\"\"\"\n for k, v in self.fields.items():\n yield k, v\n\n def get_ticks(self, axis: int = 0) -> np.ndarray:\n \"\"\"Reconstruct an array with cell coordinates along given axis.\"\"\"\n if isinstance(axis, str):\n axis = {\"r\": 0, \"phi\": 1}[axis]\n\n axis_bounds = self.reader.GetOutput().GetBounds()[2 * axis : 2 * (axis + 1)]\n npoints = self.shape[axis]\n if axis == 1: # phi\n ticks = np.linspace(*axis_bounds, npoints)\n elif axis == 0: # r\n # emulate AMRVAC\n base = np.linspace(*axis_bounds, npoints + 1)\n ticks = np.empty(npoints)\n for i in range(npoints):\n ticks[i] = 0.5 * (base[i] + base[i + 1])\n return ticks\n\n def get_meshgrid(self, dim: int = 2) -> list:\n \"\"\"Reconstruct an evenly spaced (2d) grid to locate cells.\n\n return is meant to be unpacked and used as input for\n matplotlib.pyplot.pcolormesh()\n \"\"\"\n if dim != 2:\n raise NotImplementedError\n vectors = [self.get_ticks(ax) for ax in range(dim)]\n vectors.reverse()\n return np.meshgrid(*vectors)\n\n def _get_sort_key(self) -> np.array:\n \"\"\"Allow reordering of data points against location in the physical space.\"\"\"\n data = self.reader.GetOutput()\n raw_cell_coords = np.empty((data.GetNumberOfCells(), 3))\n for i in range(data.GetNumberOfCells()):\n cell_corners = vtk_to_numpy(data.GetCell(i).GetPoints().GetData())\n raw_cell_coords[i] = np.array(\n [cell_corners[:, n].mean() for n in range(cell_corners.shape[1])]\n )\n\n cell_coords = np.array(\n [tuple(line) for line in raw_cell_coords],\n dtype=[(\"r\", \"f4\"), (\"phi\", \"f4\"), (\"z\", \"f4\")],\n )\n return cell_coords.argsort(order=[\"r\", \"phi\"])\n\n # deprecated!\n def get_axis(self, axis: int = 0) -> np.array:\n \"\"\"Reconstruct an evenly spaced array for cell coordinates along given axis.\"\"\"\n from warnings import warn\n\n message = \"This method is deprecated, use instead\"\n warn(message, DeprecationWarning, stacklevel=2)\n axis_bounds = self.reader.GetOutput().GetBounds()[2 * axis : 2 * (axis + 1)]\n return np.linspace(*axis_bounds, self.shape[axis])\n\n\ndef optional_dependency(package_name):\n \"\"\"meta decorator\"\"\"\n\n def _dependency(f):\n try:\n import_module(package_name)\n return f\n except ImportError:\n\n def fvoid(*args, **kwargs):\n print(\n f\"This function is undefined because an optional dependency ({package_name}) is missing\"\n )\n return None\n\n return fvoid\n\n return _dependency\n\n\nclass AugmentedVacDataSorter(VacDataSorter):\n \"\"\"VDS subclass that allows to transparently call some defined derived quantities.\n \n the vorticity recipe is based on my vector_calculus.Polar class\"\"\"\n\n def __init__(self, sim_params=None, **args):\n super(__class__, self).__init__(**args)\n self.sim_params = sim_params\n\n def _pressure(vds) -> np.ndarray:\n return (\n vds.sim_params[\"hd_list\"][\"hd_adiab\"]\n * vds[\"rho\"] ** vds.sim_params[\"hd_list\"].get(\"hd_gamma\", 5/3)\n )\n\n def _soundspeed(vds) -> np.ndarray:\n return np.sqrt(vds.sim_params[\"hd_list\"].get(\"hd_gamma\", 5/3) * vds[\"pressure\"] / vds[\"rho\"])\n\n def _v1(vds) -> np.ndarray:\n return vds[\"m1\"] / vds[\"rho\"]\n\n def _v2(vds) -> np.ndarray:\n return vds[\"m2\"] / vds[\"rho\"]\n\n def _keplerian_velocity(self) -> np.ndarray:\n _, rg = self.get_meshgrid()\n M_s = self.sim_params[\"disk_list\"][\"central_mass\"]\n G = 4 * np.pi ** 2 * self.sim_params[\"disk_list\"][\"ref_radius\"] ** 3 / M_s\n return np.sqrt(G * M_s) * rg ** -0.5\n\n @optional_dependency(\"vector_calculus\")\n def _vorticity(vds) -> np.ndarray:\n \"\"\"Derive the discrete vorticity in a dataset and add it to its fields\"\"\"\n from vector_calculus import Polar\n\n vorticity_z = Polar.curl(\n v_r=vds[\"v1\"],\n v_phi=vds[\"v2\"],\n r_coords=vds.get_ticks(axis=0),\n phi_coords=vds.get_ticks(axis=1),\n )\n return vorticity_z\n\n @optional_dependency(\"vector_calculus\")\n def _vortensity(vds) -> np.ndarray:\n return vds[\"vorticity\"] / vds[\"rho\"]\n\n def _rhod_total(vds) -> np.ndarray:\n nbins = 0\n while f\"rhod{nbins+1}\" in vds.fields.keys():\n nbins += 1\n return np.sum([vds[f\"rhod{j}\"] for j in range(1, nbins + 1)], axis=0)\n\n def _epsilon(vds) -> np.ndarray:\n \"\"\"Dust to gas ratio\"\"\"\n return vds[\"rhod_tot\"] / vds[\"rho\"]\n\n known_recipes = {\n \"v1\": _v1,\n \"v2\": _v2,\n \"pressure\": _pressure,\n \"soundspeed\": _soundspeed,\n \"vorticity\": _vorticity,\n \"vortensity\": _vortensity,\n \"rhod_tot\": _rhod_total,\n \"eps\": _epsilon,\n \"keplerian_velocity\": _keplerian_velocity,\n }\n\n @property\n def loaded_fields(self) -> list:\n return [k for k in self.fields.keys()]\n\n def __getitem__(self, key: str) -> np.ndarray:\n if key in self.loaded_fields:\n return self.fields[key]\n elif key in [k for k in __class__.known_recipes.keys()]:\n self.fields[key] = __class__.known_recipes[key](self)\n return self.fields[key]\n else:\n raise KeyError(f\"\"\"Unknown quantity/recipe \"{key}\" \"\"\")\n","sub_path":"vtk_vacreader/datasorter.py","file_name":"datasorter.py","file_ext":"py","file_size_in_byte":7652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"216715603","text":"# baidu map try\nfrom urllib import request\nimport json\n\npoint=[39.9,116.4]\nradius=1000.0\n\nbmap_web_key = 'RKdmGLIj21REUjYIez9FICyLQ1YcfCP6'\nbmap_poi_place_url = 'http://api.map.baidu.com/place/v2/'\n\ndef getpoi_page(point,radius):\n bmap_req_url = bmap_poi_place_url+'search?query=ATM&location='+str(point[0])+','+str(point[1])+'&radius='+str(radius)+'&output=json&ak='+bmap_web_key\n data = ''\n with request.urlopen(bmap_req_url) as f:\n data = f.read()\n data = data.decode('utf-8')\n\n result=json.loads(data)\n pois=result['results']\n return pois\n\npois=getpoi_page(point,radius)\n\nfor i in range(len(pois)):\n print(str(pois[i]['location'])+'\\t'+pois[i]['name'])","sub_path":"Python/LFR_POI/baidu_map_try.py","file_name":"baidu_map_try.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"465062146","text":"'''\nCreated on Wed Feb 19 23:06:00 2020\nAuthor: Saymon G. Bandeira\nContact: saymongb@gmail.com\nSummary: This script was created to merge three Microsoft Excel\n files sent by ThyssenKrupp colleagues with the \n historical demands of some spare parts.\nNote: \nFix: \nStatus: Finished. \nNext: N/A.\n'''\n\nimport numpy as np\nimport pandas as pd\n\nfileCorredica = u'Demanda corrediça.xlsx'\ncorredicaSheets = ['2017','2018','2019']\nfileElevadores = u'demandas_elevadores.xlsx'\nfilePlastica = u'Demanda peças plastica.xlsx'\npath = '../dataset/'\n\ncols = ['STATIONS','DATE','PARTS','DEMANDS']\ndata = pd.DataFrame(columns = cols)\ndataTemp = pd.DataFrame(columns = cols)\n\n# Elevator datasheet\ntemp = pd.read_excel(path+fileElevadores)\ndataTemp[cols] = temp[['Cidade','Data Emissão NF','Peça','Demanda']]\ndata = data.append(dataTemp,ignore_index=True)\n\n# Peça plástica datasheet\ntemp = pd.read_excel(path+filePlastica)\ndataTemp = pd.DataFrame(columns = cols)\ndataTemp[cols] = temp[['Unidade','Data','Descrição Material','Quantidade']]\ndata = data.append(dataTemp,ignore_index=True)\n\n# Corrediça datasheet\ntemp = pd.read_excel(path+fileCorredica,None)\nfor sheet in corredicaSheets:\n tempAux = temp[sheet]\n tempAux['Unidade'] = tempAux['Unidade'].str.replace(\" +\",\"\") #remove extra space at end of the string\n dataTemp = pd.DataFrame(columns = cols)\n dataTemp[cols] = tempAux[['Unidade','Data','Descrição Material','Quantidade']]\n data = data.append(dataTemp,ignore_index=True)\n\n# Treat inconsistencies\ndata['STATIONS'] = data['STATIONS'].str.replace(\"Aracajú\",\"ARACAJU\")\ndata['STATIONS'] = data['STATIONS'].str.replace(\"BALNEÁRIO CAMBURIÚ\",\"BALNEARIO CAMBORIU\")\ndata['STATIONS'] = data['STATIONS'].str.replace(\"BARUERI / OSASCO\",\"BARUERI\")\ndata['STATIONS'] = data['STATIONS'].str.replace(\"POA - CENTRO SUL\",\"POA - Central SUL\")\ndata['STATIONS'] = data['STATIONS'].str.replace(\"NITERÓI\",\"NITEROI\")\ndata['STATIONS'] = data['STATIONS'].str.replace(\"SÃO LUIS\",\"São Luiz do Maranhão\")\ndata['STATIONS'] = data['STATIONS'].str.replace(\"MACEIÓ\",\"MACEIO\")\ndata['STATIONS'] = data['STATIONS'].str.replace(\"Sâo José dos Campos \",\"SÃO JOSÉ DOS CAMPOS\")\ndata['STATIONS'] = data['STATIONS'].str.upper()\ndata['PARTS'] = data['PARTS'].str.upper()\n\n#write data to disk\nwriter = pd.ExcelWriter(path+'DATA'+'.xls')\ndata.to_excel(excel_writer=writer,sheet_name='demands',index=False) \nwriter.save()\n\n# Summary of the data generated on the process\nparts = data.groupby(['PARTS'],as_index=False).count()[['PARTS','DEMANDS']]\nparts.columns = ['PARTS','ORDERS']\nordersByRemoteStations = data.groupby(by=['STATIONS','PARTS'],\n as_index=False).count()[['STATIONS','PARTS','DEMANDS']]\nordersByRemoteStations.columns = ['STATIONS','PARTS','ORDERS']\nordersFrame = ordersByRemoteStations.groupby(['STATIONS'],as_index=False).sum()\npartsFrame = ordersByRemoteStations.groupby(['STATIONS'],as_index=False).count()\nordersFrame = ordersFrame.join(partsFrame[['PARTS']])\n\nwriter_ts = pd.ExcelWriter(path+'DATA-SUMMARY'+'.xls')\n\nordersByRemoteStations.to_excel(excel_writer=writer_ts,sheet_name='ORDERS',index=False)\nparts.to_excel(excel_writer=writer_ts,sheet_name='PARTS',index=False) \nordersFrame.to_excel(excel_writer=writer_ts,sheet_name='STATIONS',index=False)\n\nwriter_ts.save()","sub_path":"ppat-oas/tests/merge_files.py","file_name":"merge_files.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"99896387","text":"import Pantry\nimport json\nimport sys\nimport main\n\ndef pantry_menu():\n print(\"Welcome to the pantry\")\n\n try:\n with open(\"pantry.json\", \"r\") as myPantry:\n pantry = Pantry.Pantry(json.load(myPantry))\n print(\"-- Found an existing file!\\n\")\n except:\n pantry = Pantry.Pantry()\n print(\"-- No existing file found. Here's a fresh pantry!\\n\")\n \n while True:\n print(\"[0] Print current pantry\")\n print(\"[1] Add item to pantry\")\n print(\"[2] Save pantry\")\n print(\"[3] Update pantry item\")\n print(\"[4] Search pantry for item\")\n print(\"[q] Exit\")\n\n pantrynav = input(\"\\nChoose an option from above: \")\n print(\"===========================================\")\n\n if pantrynav == '0':\n pantry.toString()\n elif pantrynav == '1':\n iname = input(\"Name: \")\n ipdate = input(\"Purchase date: \")\n iedate = input(\"Expiration date: \")\n iquantity = input(\"Quantity: \")\n print(pantry.add_item(iname, ipdate, iedate, iquantity))\n elif pantrynav == '2':\n print(pantry.save())\n elif pantrynav == '3':\n new_attr = []\n print(\"Enter the name of item to update and information to update\")\n new_attr.append(input(\"Name: \"))\n new_attr.append(input(\"Attribute: \"))\n new_attr.append(input(\"Value: \"))\n print(pantry.update(new_attr))\n elif pantrynav == '4':\n print(pantry.search(input(\"Name: \")))\n elif pantrynav == 'q':\n pantry.save()\n main.main_menu()\n else:\n print(\"Invalid choice\")\n\n print(\"===========================================\")\n\nif __name__ == \"__main__\":\n pantry_menu()\n","sub_path":"pantrymenu.py","file_name":"pantrymenu.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"609660279","text":"import random\n\nfrom hadoopimport.ct_enabler import CTEnabler, CTConfigProperty\nfrom hadoopimport.ingestion_group import IngestionGroup\nfrom hadoopimport.tests.base_test_case import BaseTestCase\n\n\nclass CTEnablerTest(BaseTestCase):\n\n def mock_config_get(self, section, option):\n \"\"\"\n\n :type section: str\n :type option: str\n :rtype: object\n \"\"\"\n if option == CTConfigProperty.RETENTION_HOURS_CONFIG:\n return self.retention_hours\n else:\n return None\n\n def mock_db_mgr_execute_query(self, query, query_params=None, db_conn_conf=None, db_name=None):\n \"\"\"\n\n :type query: str\n :type query_params: dict\n :type db_conn_conf: DbConnConf\n :type db_name: str\n :rtype: list of dict\n \"\"\"\n if query == CTEnabler.IS_DB_CT_ENABLED_QUERY:\n if db_conn_conf.db_name in self.enabled_db_tables:\n return [{\"DATABASE_ID\": random.randint(0, 1000)}]\n else:\n return []\n elif query == CTEnabler.IS_TABLE_CT_ENABLED_QUERY.format(db_conn_conf.table_name):\n if db_conn_conf.db_name in self.enabled_db_tables and \\\n db_conn_conf.table_name in self.enabled_db_tables[db_conn_conf.db_name]:\n return [{\"TABLE_ID\": random.randint(0, 1000)}]\n else:\n return []\n elif query == CTEnabler.ENABLE_DB_CT_QUERY.format(self.retention_hours):\n if db_conn_conf.db_name not in self.enabled_db_tables:\n self.enabled_db_tables[db_conn_conf.db_name] = []\n else:\n raise Exception(\"DB already has CT enabled\")\n return []\n elif query == CTEnabler.ENABLE_TABLE_CT_QUERY.format(db_conn_conf.table_name):\n if db_conn_conf.db_name in self.enabled_db_tables:\n if db_conn_conf.table_name not in self.enabled_db_tables[db_conn_conf.db_name]:\n self.enabled_db_tables[db_conn_conf.table_name].append(db_conn_conf.table_name)\n else:\n raise Exception(\"Table already has CT enabled\")\n else:\n raise Exception(\"DB doesnt have CT enabled\")\n return []\n else:\n raise NotImplementedError\n\n def setUp(self):\n self.ingestion_group = IngestionGroup.KA\n\n # Mock config\n self.mock_config_class = self.get_mock_class(\"hadoopimport.ct_enabler.Config\")\n self.mock_config = self.mock_config_class.return_value\n self.mock_config.get.side_effect = self.mock_config_get\n\n # Mock DB Manager\n self.mock_msql_db_mgr = self.get_mock(\"hadoopimport.ct_enabler.MsSqlDbManager\")\n self.mock_msql_db_mgr.execute_query.side_effect = self.mock_db_mgr_execute_query\n\n # Mock DB Table List Generator\n self.mock_ingestible_db_table_list_generator = self.get_mock(\n \"hadoopimport.ct_enabler.IngestibleDbTableListGenerator\")\n\n # Dict of db name to list of tables that have enabled Change Tracking\n self.enabled_db_tables = {}\n\n # CT Retention hours\n self.retention_hours = 10\n\n def test_enable_ct_for_all_dbs(self):\n # Given\n ingestible_db_tables = [(\"db1\", \"table1\"),\n (\"db1\", \"table2\"),\n (\"db2\", \"table2\"),\n (\"db2\", \"table3\")]\n self.enabled_db_tables = {\"db2\": [\"table2\"]}\n\n # Patch\n self.mock_ingestible_db_table_list_generator.get_all_db_tables.return_value = [\n self.build_ingestible_db_table_conf(db_name=ingestible[0], table_name=ingestible[1])\n for ingestible in ingestible_db_tables]\n\n # When\n self.ct_enabler = CTEnabler()\n self.ct_enabler.enable_ct_for_all_dbs(self.ingestion_group)\n\n # Then\n self.mock_ingestible_db_table_list_generator.get_all_db_tables.assert_called_once()\n db_queries = map(lambda call: call[0][0].lower(), self.mock_msql_db_mgr.execute_query.call_args_list)\n alter_ct_queries = filter(lambda query: \"alter\" in query and \"change_tracking\" in query, db_queries)\n enable_db_ct_queries = filter(lambda query: \"database\" in query, alter_ct_queries)\n enable_db_table_queries = filter(lambda query: \"table\" in query, alter_ct_queries)\n\n self.assertEquals(len(enable_db_ct_queries), 1)\n self.assertEquals(len(enable_db_table_queries), 3)","sub_path":"Projects/hadoop_import/hadoopimport/tests/test_ct_enabler.py","file_name":"test_ct_enabler.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"319601694","text":"from cakehouse.serializers import ProductoSerializer\nfrom productos.models import Producto,Tipo_producto\nfrom django.contrib.auth.models import User, Group\nfrom rest_framework import viewsets\nfrom rest_framework import permissions\nfrom cakehouse.serializers import UserSerializer, GroupSerializer, ProductoSerializer, Tipo_productoSerializer\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows users to be viewed or edited.\n \"\"\"\n queryset = User.objects.all().order_by('-date_joined')\n serializer_class = UserSerializer\n permission_classes = [permissions.IsAuthenticated]\n\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n queryset = Group.objects.all()\n serializer_class = GroupSerializer\n permission_classes = [permissions.IsAuthenticated]\n\nclass ProductoViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n queryset = Producto.objects.all()\n serializer_class = ProductoSerializer\n permission_classes = [permissions.IsAuthenticated] \n\nclass Tipo_productoViewSet(viewsets.ModelViewSet):\n \"\"\"\n API endpoint that allows groups to be viewed or edited.\n \"\"\"\n queryset = Tipo_producto.objects.all()\n serializer_class = Tipo_productoSerializer\n permission_classes = [permissions.IsAuthenticated] ","sub_path":"cakehouse/cakehouse/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"353034283","text":"def show_hough_line(img, accumulator, rhos, thetas):\n '''# ! Delete this before submission'''\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots(1, 2, figsize=(10, 10))\n\n ax[0].imshow(img, cmap=plt.cm.gray)\n ax[0].set_title('Input image')\n ax[0].axis('image')\n\n ax[1].imshow(\n accumulator, cmap='jet',\n extent=[np.rad2deg(thetas[-1]), np.rad2deg(thetas[0]), rhos[-1], rhos[0]])\n ax[1].set_aspect('equal', adjustable='box')\n ax[1].set_title('Hough transform')\n ax[1].set_xlabel('Angles (degrees)')\n ax[1].set_ylabel('Distance (pixels)')\n ax[1].axis('image')\n\n # plt.axis('off')\n plt.savefig('./../imgs/chess_out2.png', bbox_inches='tight')\n plt.show()\n\ndef plot_hough_acc(H, plot_title='Hough Accumulator Plot'):\n ''' A function that plot a Hough Space using Matplotlib. '''\n '''# ! Delete this before submission'''\n fig = plt.figure(figsize=(10, 10))\n fig.canvas.set_window_title(plot_title)\n\n plt.imshow(H, cmap='jet')\n\n plt.xlabel('Theta Direction'), plt.ylabel('Rho Direction')\n plt.tight_layout()\n plt.show()\n","sub_path":"Old/ShowHoughTransform.py","file_name":"ShowHoughTransform.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"358040571","text":"# afficher la liste des variables d’environnement et leurs valeurs associee,\n# par ordre alphab ́etique des noms de variables\n\nimport os\n\nss = os.environ\nfor k in sorted(ss): \n\tprint(\"%s : %s\" %(k, ss[k]))\n\t\n\t\n\t","sub_path":"env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"605314987","text":"class Node():\r\n def __init__(self,dado):\r\n self.dados = dado\r\n self.pai = None\r\n self.fLeft = None\r\n self.fRight = None\r\n self.cor = 1\r\n def getDado(self):\r\n return self.dados\r\n\r\nclass Avl():\r\n def __init__(self):\r\n self.objectNull = Node(0)\r\n self.objectNull.cor = 0\r\n self.objectNull.fLeft = None\r\n self.objectNull.fRight = None\r\n self.raiz = self.objectNull\r\n\r\n def rotateLeft(self,x):\r\n y = x.fRight\r\n x.fRight = y.fLeft\r\n if y.fLeft != self.objectNull:\r\n y.fLeft.pai = x\r\n\r\n y.pai = x.pai\r\n if x.pai == None:\r\n self.raiz = y\r\n elif x == x.pai.fLeft:\r\n x.pai.fLeft = y\r\n else:\r\n x.pai.fRight = y\r\n y.fLeft = x\r\n x.pai = y\r\n\r\n def rotateRight(self,x):\r\n y = x.fLeft\r\n x.fLeft = y.fRight\r\n if y.fRight != self.objectNull:\r\n y.fRight.pai = x\r\n\r\n y.pai = x.pai\r\n if x.pai == None:\r\n self.raiz = y\r\n elif x == x.pai.fRight:\r\n x.pai.fRight = y\r\n else:\r\n x.pai.fLeft = y\r\n y.fRight = x\r\n x.pai = y\r\n def __hDelete(self,node,key):\r\n u = self.__tBusca(node,key)\r\n if u == self.objectNull:\r\n print(\"%s nao presente na arvore\"%key)\r\n return\r\n\r\n y = u\r\n yPrimal = y.cor\r\n if u.fLeft == self.objectNull:\r\n x = u.fRight\r\n self.__hTrocar(u,u.fRight)\r\n elif u.fRight == self.objectNull:\r\n x = u.fLeft\r\n self.__hTrocar(u,u.fLeft)\r\n else:\r\n y = self.inMin(u.fRight)\r\n yPrimal = y.cor\r\n x = y.fRight\r\n if y.pai == u:\r\n x.pai = y\r\n else:\r\n self.__hTrocar(y,y.fRight)\r\n y.fRight = u.fRight\r\n y.fRight.pai = y\r\n\r\n self.__hTrocar(u,y)\r\n y.fLeft = u.fLeft\r\n y.fLeft.pai = y\r\n y.cor = u.cor\r\n if yPrimal == 0:\r\n self.__deleteFix(x)\r\n\r\n def __deleteFix(self, x):\r\n while x != self.raiz and x.cor == 0:\r\n if x == x.pai.fLeft:\r\n s = x.pai.fRight\r\n if s.cor == 1:\r\n s.cor = 0\r\n x.pai.cor = 1\r\n self.rotateLeft(x.pai)\r\n s = x.pai.fRight\r\n\r\n if s.fLeft.cor == 0 and s.fRight.cor == 0:\r\n s.cor = 1\r\n x = x.pai\r\n else:\r\n if s.fRight.cor == 0:\r\n s.fLeft.cor = 0\r\n s.cor = 1\r\n self.rotateRight(s)\r\n s = x.pai.fRight\r\n\r\n s.cor = x.pai.cor\r\n x.pai.cor = 0\r\n s.fRight.cor = 0\r\n self.rotateLeft(x.pai)\r\n x = self.raiz\r\n else:\r\n s = x.pai.fLeft\r\n if s.cor == 1:\r\n s.cor = 0\r\n x.pai.cor = 1\r\n self.rotateRight(x.pai)\r\n s = x.pai.fLeft\r\n\r\n if s.fRight.cor == 0 and s.fRight.cor == 0:\r\n s.cor = 1\r\n x = x.pai\r\n else:\r\n if s.fLeft.cor == 0:\r\n s.fRight.cor = 0\r\n s.cor = 1\r\n self.rotateLeft(s)\r\n s = x.pai.fLeft\r\n\r\n s.cor = x.pai.cor\r\n x.pai.cor = 0\r\n s.fLeft.cor = 0\r\n self.rotateRight(x.pai)\r\n s = self.raiz\r\n x.cor = 0\r\n\r\n def __hTrocar(self,u,v):\r\n if u.pai == None:\r\n self.raiz = v\r\n elif u == u.pai.fLeft:\r\n u.pai.fLeft = v\r\n else:\r\n u.pai.fRight = v\r\n v.pai = u.pai\r\n def inMax(self, node):\r\n while True:\r\n if node.fLeft == self.objectNull:\r\n return node\r\n node = node.fLeft\r\n def insertFix(self, node):\r\n while node.pai.cor == 1:\r\n if node.pai == node.pai.pai.fRight:\r\n u = node.pai.pai.fLeft\r\n if u.cor == 1:\r\n u.cor = 0\r\n node.pai.cor = 0\r\n node.pai.pai.cor = 1\r\n node = node.pai.pai\r\n else:\r\n if node == node.pai.fLeft:\r\n node = node.pai\r\n self.rotateRight(node)\r\n node.pai.cor = 0\r\n node.pai.pai.cor = 1\r\n self.rotateLeft(node.pai.pai)\r\n else:\r\n u = node.pai.pai.fRight\r\n if u.cor == 1:\r\n u.cor = 0\r\n node.pai.cor = 0\r\n node.pai.pai.cor = 1\r\n node = node.pai.pai\r\n else:\r\n if node == node.pai.fRight:\r\n node = node.pai\r\n node.pai.cor = 0\r\n node.pai.pai.cor = 1\r\n self.rotateRight(node.pai.pai)\r\n if node == self.raiz:\r\n break\r\n self.raiz.cor = 0\r\n def inMin(self, node):\r\n while True:\r\n if node.fRight == self.objectNull:\r\n return node\r\n node = node.fRight\r\n def predecessor(self,x):\r\n if x.fLeft != self.objectNull:\r\n return self.inMax(x.fLeft)\r\n y = x.pai\r\n while y != self.objectNull and x == y.fLeft:\r\n x = y\r\n y = y.pai\r\n return y\r\n def sucessor(self, x):\r\n if x.fRight != self.objectNull:\r\n return self.inMin(x.fRight)\r\n y = x.pai\r\n while y != self.objectNull and x == y.fRight:\r\n x = y\r\n y = y.pai\r\n def tInserir(self,key):\r\n node = Node(key)\r\n node.pai = None\r\n node.dados = key\r\n node.fLeft = self.objectNull\r\n node.fRight= self.objectNull\r\n node.cor = 1\r\n\r\n y = None\r\n x = self.raiz\r\n\r\n while True:\r\n if x != self.objectNull:\r\n y = x\r\n if node.getDado() < x.getDado():\r\n x = x.fLeft\r\n else:\r\n x = x.fRight\r\n else:\r\n break\r\n\r\n node.pai = y\r\n if y == None:\r\n self.raiz = node\r\n elif node.getDado() < y.getDado():\r\n y.fLeft = node\r\n else:\r\n y.fRight = node\r\n\r\n if node.pai == None:\r\n node.cor = 0\r\n return\r\n if node.pai.pai == None:\r\n return\r\n self.insertFix(node)\r\n print(\"dado inserido\")\r\n def tGetRaiz(self):\r\n return self.raiz\r\n def tDelete(self,dado):\r\n self.__hDelete(self.raiz, dado)\r\n def __tBusca(self,node, x):\r\n if node == self.objectNull or node.getDado() == x:\r\n return node\r\n else:\r\n if node.getDado() > x:\r\n return self.__tBusca(node.fLeft,x)\r\n else:\r\n return self.__tBusca(node.fRight,x)\r\n def tSearch(self,x):\r\n return self.__tBusca(self.raiz,x)\r\n\r\n def tPrint(self):\r\n return self.__hPrint(self.raiz,1)\r\n def __hPrint(self,node,filho,s=\"\"):\r\n if node != self.objectNull:\r\n if node.pai == None:\r\n lado = \"Raiz\"\r\n elif filho:\r\n lado = \"--Right\"\r\n else:\r\n lado = \"--Left\"\r\n print(s,lado,node.getDado())\r\n s += \" \"\r\n self.__hPrint(node.fLeft,0,s)\r\n self.__hPrint(node.fRight,1,s)\r\n\r\nclass Menu():\r\n def __init__(self,tela=0):\r\n self.arvore = Avl()\r\n self.tela = tela\r\n self.tela0 = \"\"\"\r\n \\tArvore AVL\r\n\\t1- inserir\r\n\\t2- deletar\r\n\\t3- visualizar\r\n\\t4- sair\r\n\"\"\"\r\n self.tela1 = \"\"\"\\t|- inserir -|\r\n \\t# inserir e ,se preciso, balancear a arvore #\r\n \\t# é possivel inserir varios valores ao mesmo tempo\r\n \\t colocando um espaço entre cada valor # \r\n input = \"\"\"\r\n self.tela2 = \"\"\"\\t|- deletar -|\r\n \\t # deleta e balanceia a arvore #\r\n input = \"\"\"\r\n\r\n def menu_mudar(self,menu_t,b=True):\r\n if b :\r\n if menu_t == 0:\r\n print(self.tela0)\r\n self.menu_mudar(int(input()))\r\n elif menu_t == 1:\r\n print(self.tela1,end= \"\")\r\n for x in [int(p) for p in input().split(\" \")]:\r\n print(x)\r\n self.arvore.tInserir(x)\r\n self.menu_mudar(0)\r\n elif menu_t == 2:\r\n print(self.tela2,end= \"\")\r\n self.arvore.tDelete(int(input()))\r\n self.menu_mudar(0)\r\n elif menu_t == 3:\r\n self.arvore.tPrint()\r\n a = input(\"Pressione ENTER para continuar...\")\r\n self.menu_mudar(0)\r\n else:\r\n b = False\r\n\r\np = Menu()\r\np.menu_mudar(0)","sub_path":"Arvore AVL.py","file_name":"Arvore AVL.py","file_ext":"py","file_size_in_byte":9214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"321147220","text":"from contextlib import closing\nfrom datetime import timedelta\nimport os\nimport pathlib\n\nimport pandas as pd\nimport prefect\nimport sqlalchemy as sa\nfrom prefect import Flow, task\nfrom prefect.schedules import CronSchedule\nfrom prefect.tasks.secrets import EnvVarSecret\nfrom prefect.tasks.shell import ShellTask\n\nDATA_PATH = pathlib.Path(os.environ[\"DATAPATH\"]) / \"final\"\nCSV_FN = DATA_PATH / \"can_scrape_api_covid_us.csv\"\nDATA_PATH.mkdir(parents=True, exist_ok=True)\nFN_STR = \"can_scrape_api_covid_us{}\"\n\n\n@task(max_retries=3, retry_delay=timedelta(minutes=1))\ndef export_to_csv(connstr: str):\n db = sa.create_engine(connstr)\n with open(CSV_FN, \"w\") as f:\n with closing(db.raw_connection()) as conn:\n with closing(conn.cursor()) as cur:\n cur.copy_expert(\n \"COPY (SELECT * From covid_us) TO STDOUT CSV HEADER;\", f\n )\n\n return True\n\n\n@task(max_retries=3, retry_delay=timedelta(minutes=1), nout=2)\ndef create_parquet(_success):\n ts = prefect.context.scheduled_start_time\n dt_str = pd.to_datetime(ts).strftime(\"%Y-%m-%dT%H\")\n vintage_fn = FN_STR.format(dt_str) + \".parquet\"\n fn = FN_STR.format(\"\") + \".parquet\"\n\n df = pd.read_csv(CSV_FN, parse_dates=[\"dt\"])\n df.to_parquet(DATA_PATH / vintage_fn, index=False)\n df.to_parquet(DATA_PATH / fn, index=False)\n return vintage_fn, fn\n\n\n@task\ndef get_gcs_cmd(fn):\n return f\"gsutil acl ch -u AllUsers:R gs://can-scrape-outputs/final/{fn}\"\n\n\nshell = ShellTask()\nwith Flow(\"UpdateParquetFiles\", CronSchedule(\"10 */2 * * *\")) as f:\n connstr = EnvVarSecret(\"COVID_DB_CONN_URI\")\n success = export_to_csv(connstr)\n vintage_fn, fn = create_parquet(success)\n shell(get_gcs_cmd(vintage_fn))\n shell(get_gcs_cmd(fn))\n\nf.register(project_name=\"can-scrape\")\n","sub_path":"services/prefect/flows/update_api_view.py","file_name":"update_api_view.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"435221038","text":"def format_matrix(matrix):\n\n\t# set max length of rows and columns\n\trows = len(matrix)\n\tcolumns = len(matrix[0])\n\n\t# for each entry\n\tfor row in range(rows):\n\n\t\tfor column in range(columns):\n\n\t\t\t# round to three decimel places\n\t\t\tmatrix[row][column] = round(matrix[row][column], 3)\n\t\t\t\n\treturn matrix\n","sub_path":"MDP/format_matrix.py","file_name":"format_matrix.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"523121279","text":"from odoo import http, api\nfrom odoo.http import request\nimport logging\nimport pprint\nimport werkzeug\n\n_logger = logging.getLogger(__name__)\n\nclass OgoneController(http.Controller):\n _accept_url = '/payment/mpay/feedback'\n\n @http.route([\n '/payment/mpay/feedback',\n ], type='http', auth='none', csrf=False)\n def mpay_form_feedback(self, **post):\n _logger.info('Beginning form_feedback with post data %s', pprint.pformat(post)) # debug\n print(post)\n request.env['payment.transaction'].sudo().form_feedback(post, 'transfer')\n return werkzeug.utils.redirect(post.pop('return_url', '/'))\n\n#####Just for Demostration #################################################\n @http.route('/auth_usr', type='http', auth='public', website=True, ) #\n def render_demo_page(self): #\n return http.request.render(\"Mpay.example__page\", {}) #\n####Just for Demostration ##################################################\n\n def extract_data(self,template,message):\n tokenized_message=message.split()\n tokenized_template=template.split()\n data={}\n try:\n if( len(tokenized_message) != len(tokenized_template) ):\n for i in range(0,len(tokenized_message)):\n if(tokenized_message[i] != tokenized_template[i]) and tokenized_template[i][0:1] == \"$\" and len(tokenized_template)!= (i+1):\n data.update( {tokenized_template[i][1:] : tokenized_message[i]} )\n\n elif (tokenized_message[i] != tokenized_template[i]) and tokenized_template[i][0:1] != \"$\" and len(tokenized_template)!= (i+1):\n while True:\n if (tokenized_message[i] != tokenized_template[i]) and tokenized_template[i][0:1] != \"$\":\n data[tokenized_template[i-1][1:]]=data[tokenized_template[i-1][1:]]+\" \"+tokenized_message[i]\n del tokenized_message[i]\n else:\n break;\n elif (tokenized_message[i] != tokenized_template[i]) and tokenized_template[i][0:1] == \"$\" and len(tokenized_template)== (i+1):\n help_message=\"\"\n iterator=iter(tokenized_message[i:])\n for p in iterator:\n test=next(iterator,True)\n if test==True:\n help_message=help_message+p+\"\"\n else:\n help_message=help_message+p+\" \"\n data.update({tokenized_template[i][1:]:help_message})\n break;\n return data\n\n else:\n for i in range(0,len(tokenized_message)):\n if(tokenized_message[i] != tokenized_template[i]) and tokenized_template[i][0:1] == \"$\" :\n data.update( {tokenized_template[i][1:] : tokenized_message[i]} )\n\n return data\n except Exception as e:\n print(\"Error 001: Invalid formating of template\\nCheck if your message corresponds with the template\\n\")\n\n\n @http.route('/get_transaction_sms', type='http', auth='public', website=True, methods=['POST'], csrf=False)\n def post_method(self, **sms):\n #Here we have to extract important information from SMS sent and store to \"received.transaction\" model\n if sms['secret'] !='ilomoyezy':\n return \"Error 404.\"\n\n received_sms=sms['message']\n get_record=request.env['payment.service'].sudo().search([(\"service_provider\",\"=\",\"Vodacom\")]);\n if get_record.exists():\n template=get_record.template_sms;\n else:\n template=\"$transaction_id Imethibitishwa umepokea $received_amount kutoka kwa $name Tarehe $date saa $time kwa kumbukumbu namba $reference\"\n\n try :\n transaction_sms=self.extract_data(template,received_sms)\n data=request.env['received.transaction'].sudo().create({'reference': transaction_sms['reference'],'sender_name': transaction_sms['name'], 'sender_phone': transaction_sms['name'], 'transaction_id': transaction_sms['transaction_id'], 'transaction_status': 'pending', 'transaction_currency': transaction_sms['received_amount'][0:3], 'received_amount': float(transaction_sms['received_amount'][3:].replace(\",\", \"\")), 'service_provider': sms['from'] } )\n trs=request.env['payment.transaction'].sudo().search( [('reference','=',transaction_sms['reference'] )] )\n print(len(transaction_sms['reference']));\n print(received_sms)\n if trs.exists(): ##########If the order exists\n if trs.state!='done' and data.transaction_status!='done' and trs.amount <= data.received_amount: ##If paid amount is equal or greater than expected amount\n trs.write({'state':'done'})\n data.write({'transaction_status': 'done'})\n print('\\033[1m'+'\\033[92m'+\"\\nMpay payment for order # \"+transaction_sms['reference']+ \" confirmed\\n\"+'\\033[0m')\n elif trs.state!='done' and data.transaction_status!='done' and trs.amount > data.received_amount: ##If paid amount is less than expected amount\n data.write({'transaction_status': 'incomplete'})\n print('\\033[1m'+'\\033[91m'+\"\\nIncomplete payment.\\n\"+'\\033[0m')\n else :\n data.write({'transaction_status': 'cancelled'})\n print('\\033[1m'+'\\033[1m'+'\\033[1m'+'\\033[91m'+\"\\nOrder \"+transaction_sms['reference']+ \" has already been processed.\\n\"+'\\033[0m')#Order with the same order number exist\n else: ###########If the order doesn't exist\n print('\\033[1m'+'\\033[91m'+\"\\nOrder \"+transaction_sms['reference']+\" does not exist.\\n\" +'\\033[0m')\n\n except Exception as e:\n print(e)\n print('\\033[1m'+'\\033[91m'+\"\\nOooop!, it seems like your SMS does not involve payment transaction!.\\n\"+'\\033[0m')\n","sub_path":"controllers/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":5908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"125839956","text":"\"\"\"Rope element views.\"\"\"\nimport json\n\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.utils import translation\n\nfrom rest_framework import generics\n\nfrom . import models\nfrom . import serializers\n\n\nclass ElementListView(generics.ListAPIView):\n \"\"\"API endpoint to list rope elements.\"\"\"\n queryset = models.Element.objects.all()\n serializer_class = serializers.ElementSerializer\n\n def get(self, request, *args, **kwargs):\n translation.activate(request.path.split('/')[1])\n return self.list(request, *args, **kwargs)\n\n\ndef ropeelements(request, **kwargs):\n \"\"\"Rope elements template view.\"\"\"\n contact = models.Config.objects.get(variable='contact')\n ssb_config = models.Config.objects.get(variable='ssb')\n powerfan_config = models.Config.objects.get(variable='powerfan')\n\n difficulties = [\n serializers.DifficultySerializer(difficulty).data\n for difficulty in models.Difficulty.objects.order_by('order')]\n\n translation.activate(request.path.split('/')[1])\n\n return render_to_response(\n 'ropeelements.html', {\n 'difficulties': json.dumps(difficulties),\n 'contact_url': contact.url,\n 'ssb_url': ssb_config.url,\n 'ssb_title': ssb_config.text,\n 'powerfan_url': powerfan_config.url,\n 'powerfan_title': powerfan_config.text,\n }, RequestContext(request))\n","sub_path":"ropeelements/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"312073657","text":"import operator\n\n\nOPERATORS = {\n '+': operator.add,\n '-': operator.sub,\n '*': operator.mul,\n '/': operator.truediv,\n '^': operator.pow,\n '%': operator.mod,\n '**': operator.pow,\n '//': operator.floordiv,\n}\n\ndef calc(expr):\n buffer = []\n for val in expr.split():\n if val in OPERATORS:\n func = OPERATORS[val]\n op2, op1 = buffer.pop(), buffer.pop()\n buffer.append(func(op1, op2))\n else:\n buffer.append(float(val))\n if buffer:\n return buffer.pop()\n return 0\n\ndef main():\n while True:\n try:\n expr = input('rpn>>> ')\n except EOFError:\n break\n if not expr:\n continue\n result = calc(expr)\n print(result)\n\n\nif __name__ == '__main__':\n main()","sub_path":"rpn/the_easy_way.py","file_name":"the_easy_way.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"81244320","text":"import logging\nimport re\nimport sys\n\nfrom mako.template import Template\nimport itertools\n\ndef read_games(csv):\n for line in csv:\n try:\n timestamp, player, win, game = line[:-1].split(\",\")\n except ValueError as e:\n logger.warning(\"invalid line: \" + line[:-1])\n yield { \"timestamp\": timestamp,\n \"player\": player,\n \"win\": win,\n \"game\": game }\n\ndef points(game):\n # Get Null out of the way\n if game == \"N\":\n return 23\n elif game == \"Nh\":\n return 35\n elif game == \"No\":\n return 46\n elif game == \"Nho\":\n return 59\n spiel = int(game[1]) + 1\n colour = (9, 10, 11, 12, 24)[int(game[2])]\n mod = len(game[3:])\n return (spiel + mod) * colour\n\ndef compute_scores(games):\n scores = {}\n for game in games:\n score = points(game[\"game\"]) * (-2, 1)[int(game[\"win\"])]\n scores[game[\"player\"]] = scores.get(game[\"player\"], 0) + score\n return scores\n\ndef genhtml(templatefile, scores):\n template = Template(filename=templatefile, input_encoding='utf-8')\n return template.render(players=scores.keys(), scores=scores)\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"usage: {}